diff --git a/.DS_Store b/.DS_Store index af95e2f5..1aff60ee 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/.gitignore b/.gitignore index ee064b32..c0f450c0 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,7 @@ bin/* .idea /hidden .hidden -*/.DS_Store \ No newline at end of file +*/.DS_Store +cmd/streaming/sample.yaml +/test/streaming/config/* +gitleaks-report.json \ No newline at end of file diff --git a/Makefile b/Makefile index 8bb5b5d4..578bad7f 100644 --- a/Makefile +++ b/Makefile @@ -112,3 +112,21 @@ build/docker: docker buildx build --platform linux/amd64 -t sqlpipe/sqlpipe:latest -f sqlpipe.dockerfile . --load @echo 'Pushing docker image...' docker push sqlpipe/sqlpipe:latest + +## test: run tests in the /test directory +.PHONY: test +test: + @echo 'Running tests in the /test directory...' + STRIPE_API_KEY=$(STRIPE_API_KEY) go test -v -count=1 ./test/... + +## one-table: run the two_table_test.go test in the /test directory +.PHONY: one-table +one-table: + @echo 'Running one_table_test.go in the /test directory...' + STRIPE_API_KEY=$(STRIPE_API_KEY) go test -v -count=1 ./test/streaming/one_table_test.go + +## two-table: run the two_table_test.go test in the /test directory +.PHONY: two-tables +two-table: + @echo 'Running two_tables_test.go in the /test directory...' + STRIPE_API_KEY=$(STRIPE_API_KEY) go test -v -count=1 ./test/streaming/two_tables_test.go diff --git a/sqlpipe.dockerfile b/batch.dockerfile similarity index 100% rename from sqlpipe.dockerfile rename to batch.dockerfile diff --git a/cmd/sqlpipe/errors.go b/cmd/batch/errors.go similarity index 100% rename from cmd/sqlpipe/errors.go rename to cmd/batch/errors.go diff --git a/cmd/sqlpipe/helpers.go b/cmd/batch/helpers.go similarity index 100% rename from cmd/sqlpipe/helpers.go rename to cmd/batch/helpers.go diff --git a/cmd/sqlpipe/main.go b/cmd/batch/main.go similarity index 100% rename from cmd/sqlpipe/main.go rename to cmd/batch/main.go diff --git a/cmd/sqlpipe/routes.go b/cmd/batch/routes.go similarity index 100% rename from cmd/sqlpipe/routes.go rename to cmd/batch/routes.go diff --git a/cmd/sqlpipe/system_mssql.go b/cmd/batch/system_mssql.go similarity index 100% rename from cmd/sqlpipe/system_mssql.go rename to cmd/batch/system_mssql.go diff --git a/cmd/sqlpipe/system_mysql.go b/cmd/batch/system_mysql.go similarity index 100% rename from cmd/sqlpipe/system_mysql.go rename to cmd/batch/system_mysql.go diff --git a/cmd/sqlpipe/system_oracle.go b/cmd/batch/system_oracle.go similarity index 100% rename from cmd/sqlpipe/system_oracle.go rename to cmd/batch/system_oracle.go diff --git a/cmd/sqlpipe/system_postgresql.go b/cmd/batch/system_postgresql.go similarity index 99% rename from cmd/sqlpipe/system_postgresql.go rename to cmd/batch/system_postgresql.go index 5139dc12..cedd5b5c 100644 --- a/cmd/sqlpipe/system_postgresql.go +++ b/cmd/batch/system_postgresql.go @@ -385,7 +385,6 @@ func (system Postgresql) getPipeFileFormatters() ( timeVal, err := time.Parse("15:04:05.999999", timeString) if err != nil { - fmt.Println(timeString) return "", errors.New("error parsing time value in postgresqlPipeFileFormatters") } diff --git a/cmd/sqlpipe/system_snowflake.go b/cmd/batch/system_snowflake.go similarity index 100% rename from cmd/sqlpipe/system_snowflake.go rename to cmd/batch/system_snowflake.go diff --git a/cmd/sqlpipe/systems.go b/cmd/batch/systems.go similarity index 100% rename from cmd/sqlpipe/systems.go rename to cmd/batch/systems.go diff --git a/cmd/sqlpipe/transfers.go b/cmd/batch/transfers.go similarity index 100% rename from cmd/sqlpipe/transfers.go rename to cmd/batch/transfers.go diff --git a/cmd/streaming/.DS_Store b/cmd/streaming/.DS_Store new file mode 100644 index 00000000..4bd27771 Binary files /dev/null and b/cmd/streaming/.DS_Store differ diff --git a/cmd/streaming/errors.go b/cmd/streaming/errors.go new file mode 100644 index 00000000..82e7706c --- /dev/null +++ b/cmd/streaming/errors.go @@ -0,0 +1,41 @@ +package main + +import ( + "fmt" + "net/http" +) + +func (app *application) notFoundResponse(w http.ResponseWriter, r *http.Request) { + message := "the requested resource could not be found" + app.errorResponse(w, r, http.StatusNotFound, message) +} + +func (app *application) methodNotAllowedResponse(w http.ResponseWriter, r *http.Request) { + message := fmt.Sprintf("the %s method is not supported for this resource", r.Method) + app.errorResponse(w, r, http.StatusMethodNotAllowed, message) +} + +func (app *application) errorResponse(w http.ResponseWriter, r *http.Request, status int, message any) { + env := envelope{"error": message} + + err := app.writeJSON(w, status, env, nil) + if err != nil { + app.logError(r, err) + w.WriteHeader(500) + } +} +func (app *application) logError(r *http.Request, err error) { + var ( + method = r.Method + uri = r.URL.RequestURI() + ) + + app.logger.Error(err.Error(), "method", method, "uri", uri) +} + +func (app *application) serverErrorResponse(w http.ResponseWriter, r *http.Request, err error) { + app.logError(r, err) + + message := "the server encountered a problem and could not process your request" + app.errorResponse(w, r, http.StatusInternalServerError, message) +} diff --git a/cmd/streaming/helpers.go b/cmd/streaming/helpers.go new file mode 100644 index 00000000..dfaf9b87 --- /dev/null +++ b/cmd/streaming/helpers.go @@ -0,0 +1,100 @@ +package main + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "net/http" + "reflect" + "strings" + "time" +) + +type envelope map[string]any + +func (app *application) writeJSON(w http.ResponseWriter, status int, data envelope, headers http.Header) error { + js, err := json.MarshalIndent(data, "", "\t") + if err != nil { + return err + } + + js = append(js, '\n') + + for key, value := range headers { + w.Header()[key] = value + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + w.Write(js) + + return nil +} + +func (app *application) healthcheckHandler(w http.ResponseWriter, r *http.Request) { + env := envelope{ + "status": "available", + "system_info": map[string]string{ + "version": version, + }, + } + + err := app.writeJSON(w, http.StatusOK, env, nil) + if err != nil { + app.serverErrorResponse(w, r, err) + } +} + +func openConnectionPool(name, connectionString, driverName string) (connectionPool *sql.DB, err error) { + + connectionPool, err = sql.Open(driverName, connectionString) + if err != nil { + return nil, fmt.Errorf("error opening connection to %v :: %v", name, err) + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + err = connectionPool.PingContext(ctx) + if err != nil { + return nil, fmt.Errorf("error pinging %v :: %v", name, err) + } + + return connectionPool, nil +} + +func (app *application) receiveHandler(w http.ResponseWriter, r *http.Request) { + + path := r.URL.Path + if len(path) > 0 && path[0] == '/' { + path = path[1:] + } + + app.systemMap[path].handleWebhook(w, r) +} + +// getNestedValue traverses a map[string]any using dot notation for nested fields +func getNestedValue(obj map[string]any, dottedKey string) any { + keys := strings.Split(dottedKey, ".") + var val any = obj + for _, k := range keys { + m, ok := val.(map[string]any) + if !ok { + return nil + } + val, ok = m[k] + if !ok { + return nil + } + } + return val +} + +// isZeroValue checks if the given value is the zero value for its type. +func isZeroValue(x interface{}) bool { + if x == nil { + return true + } + return reflect.ValueOf(x).IsZero() +} diff --git a/cmd/streaming/main.go b/cmd/streaming/main.go new file mode 100644 index 00000000..7ede7c27 --- /dev/null +++ b/cmd/streaming/main.go @@ -0,0 +1,453 @@ +package main + +import ( + "encoding/json" + "expvar" + "flag" + "fmt" + "io" + "io/fs" + "log/slog" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "time" + + "github.com/santhosh-tekuri/jsonschema/v6" + "github.com/sqlpipe/sqlpipe/internal/vcs" + + "gopkg.in/yaml.v3" + + _ "github.com/jackc/pgx/v5/stdlib" +) + +var ( + version = vcs.Version() +) + +type config struct { + port int + systemsDir string + modelsDir string + keepDuplicatesFor time.Duration +} + +type application struct { + config config + logger *slog.Logger + wg sync.WaitGroup + systemMap map[string]SystemInterface + // receiveRouter map[string]map[string]map[string]map[string]Location // system_name.object_name.model_name.key_name_from_obj.key_name_from_schema + // pushFieldMap map[string]map[string]map[string]map[string]Location // system_name.object_name.model_name.key_name_from_schema.key_name_for_obj] + schemaMap map[string]*jsonschema.Schema + storageEngine *storageEngine + schemaRootMap map[string]*SchemaRoot +} + +func main() { + + var cfg config + flag.IntVar(&cfg.port, "port", 4000, "API port") + flag.StringVar(&cfg.systemsDir, "systems-dir", "./systems", "Directory for systems configuration") + flag.StringVar(&cfg.modelsDir, "models-dir", "./models", "Directory for models configuration") + flag.DurationVar(&cfg.keepDuplicatesFor, "keep-duplicates-for", 1*time.Hour, "Duration to keep duplicate entries") + displayVersion := flag.Bool("version", false, "Display version and exit") + + flag.Parse() + + if *displayVersion { + fmt.Printf("Version:\t%s\n", version) + os.Exit(0) + } + + logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) + + expvar.NewString("version").Set(version) + expvar.Publish("goroutines", expvar.Func(func() any { + return runtime.NumGoroutine() + })) + expvar.Publish("timestamp", expvar.Func(func() any { + return time.Now().Unix() + })) + + schemaMap, schemaRootMap, err := createModelMap(cfg) + if err != nil { + logger.Error("failed to load model schemas", "error", err) + os.Exit(1) + } + + systemInfoMap, err := createSystemInfoMap(cfg) + if err != nil { + logger.Error("failed to load system configurations", "error", err) + os.Exit(1) + } + + storageEngine, err := newStorageEngine() + if err != nil { + logger.Error("failed to create storage engine", "error", err) + os.Exit(1) + } + + app := &application{ + config: cfg, + logger: logger, + systemMap: make(map[string]SystemInterface), + schemaMap: schemaMap, + // receiveRouter: receiveRouter, + // pushFieldMap: pushFieldMap, + storageEngine: storageEngine, + schemaRootMap: schemaRootMap, + } + + serveQuitCh := make(chan struct{}) + + duplicateChecker := make(map[string][]ExpiringObject) + + for schemaName := range app.schemaMap { + duplicateChecker[schemaName] = []ExpiringObject{} + } + + // The server must be running to check that webhooks are valid (needed for system initialization) + go func() { + err = app.serve() + if err != nil { + logger.Error(err.Error()) + os.Exit(1) + } + close(serveQuitCh) + }() + + app.setSystemMap(systemInfoMap, duplicateChecker) + if err != nil { + logger.Error("failed to create system map", "error", err) + os.Exit(1) + } + + <-serveQuitCh + app.logger.Info("shutting down server") +} + +func createSystemInfoMap(cfg config) (map[string]SystemInfo, error) { + systemInfoMap := make(map[string]SystemInfo) + + err := filepath.Walk(cfg.systemsDir, func(path string, info os.FileInfo, err error) error { + if err != nil { + return fmt.Errorf("error walking path %s: %w", path, err) + } + + if !info.IsDir() && (filepath.Ext(path) == ".yaml" || filepath.Ext(path) == ".yml") { + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() + + var infos map[string]SystemInfo + decoder := yaml.NewDecoder(f) + err = decoder.Decode(&infos) + if err != nil { + if err == io.EOF { + // Empty YAML file, skip it + return nil + } + return err + } + for name, info := range infos { + info.Name = name + systemInfoMap[info.Name] = info + } + } + return nil + }) + if err != nil { + return nil, fmt.Errorf("failed to walk systems dir: %w", err) + } + + return systemInfoMap, nil +} + +func (app *application) setSystemMap(systemInfoMap map[string]SystemInfo, duplicateChecker map[string][]ExpiringObject) { + var systemMapMu sync.Mutex + errCh := make(chan error, len(systemInfoMap)) + doneCh := make(chan struct{}, len(systemInfoMap)) + + for systemName, systemInfo := range systemInfoMap { + go func(systemName string, systemInfo SystemInfo) { + // Create a new copy of duplicateChecker for each system + dupCheckerCopy := make(map[string][]ExpiringObject, len(duplicateChecker)) + for k, v := range duplicateChecker { + // Create a new slice for each key to avoid sharing underlying arrays + copiedSlice := make([]ExpiringObject, len(v)) + copy(copiedSlice, v) + dupCheckerCopy[k] = copiedSlice + } + + system, err := app.NewSystem(systemInfo, app.config.port, dupCheckerCopy) + if err != nil { + errCh <- err + } else { + systemMapMu.Lock() + app.systemMap[systemInfo.Name] = system + systemMapMu.Unlock() + } + doneCh <- struct{}{} + }(systemName, systemInfo) + } + + // Wait for all goroutines to finish + for i := 0; i < len(systemInfoMap); i++ { + <-doneCh + } + + // Collect and handle errors from errCh + var systemInitErrs []error + for e := range errCh { + systemInitErrs = append(systemInitErrs, e) + } + if len(systemInitErrs) > 0 { + app.logger.Error("failed to initialize one or more systems", "errors", systemInitErrs) + os.Exit(1) + } +} + +type Location struct { + PullObject string `json:"pull_object,omitempty"` + PushObject string `json:"push_object,omitempty"` + Field string `json:"field,omitempty"` + SearchKey bool `json:"search_key,omitempty"` + Pull bool `json:"pull,omitempty"` + Push bool `json:"push,omitempty"` +} + +type PropertySystemConfig struct { + RequireForCreate bool `json:"require_for_create"` + Receive []Location `json:"receive"` + Push []Location `json:"push"` + Sync []Location `json:"sync"` +} + +type Property struct { + Type any `json:"type"` + Systems map[string]PropertySystemConfig `json:"systems"` +} + +type SchemaRoot struct { + Title string `json:"title"` + Properties map[string]Property `json:"properties"` +} + +// type Field struct { +// Name string +// SearchKey bool +// } + +// type FieldRemaps struct { +// Title string +// Fields map[string]Field +// } + +// type FieldMapper struct { +// Systems map[string]map[string][]Model +// } + +func createModelMap(cfg config) ( + schemaMap map[string]*jsonschema.Schema, + schemaRoot map[string]*SchemaRoot, + err error, +) { + + jsonFiles := []string{} + + err = filepath.WalkDir(cfg.modelsDir, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + // Skip directories and non-JSON files + if d.IsDir() || !strings.HasSuffix(d.Name(), ".json") { + return nil + } + jsonFiles = append(jsonFiles, path) + return nil + }) + if err != nil { + return nil, nil, err + } + + schemaMap = make(map[string]*jsonschema.Schema) + // fieldMapper = map[string]map[string][]FieldRemaps{} + // receiveRouter = make(map[string]map[string]map[string]map[string]Location) + // pushFieldMap = make(map[string]map[string]map[string]map[string]Location) + // searchFieldMap = make(map[string]map[string]map[string]bool) + schemaRootMap := map[string]*SchemaRoot{} + compiler := jsonschema.NewCompiler() + + for _, path := range jsonFiles { + + schemaRoot := &SchemaRoot{} + + url := "file://" + filepath.ToSlash(path) + schema, err := compiler.Compile(url) + if err != nil { + return nil, nil, fmt.Errorf("compile %s: %w", path, err) + } + + if schema.Title == "" { + return nil, nil, fmt.Errorf("schema %s has no title", path) + } + + schemaMap[schema.Title] = schema + + f, err := os.Open(path) + if err != nil { + return nil, nil, fmt.Errorf("failed to open model file %s: %w", path, err) + } + defer f.Close() + + decoder := json.NewDecoder(f) + if err := decoder.Decode(&schemaRoot); err != nil { + return nil, nil, fmt.Errorf("failed to decode model file %s: %w", path, err) + } + + schemaRootMap[schema.Title] = schemaRoot + + // for propertyNameInSchema, schemaProperty := range schemaRoot.Properties { + + // for systemName, system := range schemaProperty.Systems { + + // if _, ok := receiveFieldMap[systemName]; !ok { + // receiveFieldMap[systemName] = make(map[string]map[string]map[string]Location) + // } + + // for _, location := range system.Receive { + + // if _, ok := receiveFieldMap[systemName][location.PullObject]; !ok { + // receiveFieldMap[systemName][location.PullObject] = make(map[string]map[string]Location) + // } + + // if _, ok := receiveFieldMap[systemName][location.PullObject][schema.Title]; !ok { + // receiveFieldMap[systemName][location.PullObject][schema.Title] = make(map[string]Location) + // } + + // receiveFieldMap[systemName][location.PullObject][schema.Title][location.Field] = Location{ + // Field: propertyNameInSchema, + // SearchKey: location.SearchKey, + // Pull: true, + // Push: false, + // } + // } + + // for _, location := range system.Sync { + + // if _, ok := receiveFieldMap[systemName][location.PullObject]; !ok { + // receiveFieldMap[systemName][location.PullObject] = make(map[string]map[string]Location) + // } + + // if _, ok := receiveFieldMap[systemName][location.PullObject][schema.Title]; !ok { + // receiveFieldMap[systemName][location.PullObject][schema.Title] = make(map[string]Location) + // } + + // receiveFieldMap[systemName][location.PullObject][schema.Title][location.Field] = Location{ + // Field: propertyNameInSchema, + // SearchKey: location.SearchKey, + // Pull: true, + // Push: true, + // } + // } + + // for _, location := range system.Push { + + // if _, ok := receiveFieldMap[systemName][location.PullObject]; !ok { + // receiveFieldMap[systemName][location.PullObject] = make(map[string]map[string]Location) + // } + + // if _, ok := receiveFieldMap[systemName][location.PullObject][schema.Title]; !ok { + // receiveFieldMap[systemName][location.PullObject][schema.Title] = make(map[string]Location) + // } + + // receiveFieldMap[systemName][location.PullObject][schema.Title][location.Field] = Location{ + // Field: propertyNameInSchema, + // SearchKey: location.SearchKey, + // Pull: false, + // Push: true, + // } + // } + + // if _, ok := pushFieldMap[systemName]; !ok { + // pushFieldMap[systemName] = make(map[string]map[string]map[string]Location) + // } + + // for _, location := range system.Receive { + // if _, ok := pushFieldMap[systemName][schema.Title]; !ok { + // pushFieldMap[systemName][schema.Title] = make(map[string]map[string]Location) + // } + + // if _, ok := pushFieldMap[systemName][schema.Title][location.PushObject]; !ok { + // pushFieldMap[systemName][schema.Title][location.PushObject] = make(map[string]Location) + // } + + // pushFieldMap[systemName][schema.Title][location.PushObject][propertyNameInSchema] = Location{ + // Field: location.Field, + // SearchKey: location.SearchKey, + // Pull: false, + // Push: false, + // PushObject: location.PushObject, + // } + // } + + // for _, location := range system.Push { + // if _, ok := pushFieldMap[systemName][schema.Title]; !ok { + // pushFieldMap[systemName][schema.Title] = make(map[string]map[string]Location) + // } + + // if _, ok := pushFieldMap[systemName][schema.Title][location.PushObject]; !ok { + // pushFieldMap[systemName][schema.Title][location.PushObject] = make(map[string]Location) + // } + + // pushFieldMap[systemName][schema.Title][location.PushObject][propertyNameInSchema] = Location{ + // Field: location.Field, + // SearchKey: location.SearchKey, + // Pull: false, + // Push: true, + // PushObject: location.PushObject, + // } + // } + + // for _, location := range system.Sync { + // if _, ok := pushFieldMap[systemName][schema.Title]; !ok { + // pushFieldMap[systemName][schema.Title] = make(map[string]map[string]Location) + // } + + // if _, ok := pushFieldMap[systemName][schema.Title][location.PushObject]; !ok { + // pushFieldMap[systemName][schema.Title][location.PushObject] = make(map[string]Location) + // } + + // pushFieldMap[systemName][schema.Title][location.PushObject][propertyNameInSchema] = Location{ + // Field: location.Field, + // SearchKey: location.SearchKey, + // Pull: false, + // Push: true, + // PushObject: location.PushObject, + // } + // } + // } + // } + } + + // b, err := json.MarshalIndent(receiveFieldMap, "", " ") + // if err != nil { + // fmt.Fprintf(os.Stderr, "failed to marshal receiveFieldMap: %v\n", err) + // } else { + // fmt.Printf("receiveFieldMap:\n%s\n", string(b)) + // } + + // b, err = json.MarshalIndent(pushFieldMap, "", " ") + // if err != nil { + // fmt.Fprintf(os.Stderr, "failed to marshal pushFieldMap: %v\n", err) + // } else { + // fmt.Printf("pushFieldMap:\n%s\n", string(b)) + // } + + return schemaMap, schemaRootMap, nil +} diff --git a/cmd/streaming/postgresql.go b/cmd/streaming/postgresql.go new file mode 100644 index 00000000..d12a20a1 --- /dev/null +++ b/cmd/streaming/postgresql.go @@ -0,0 +1,526 @@ +package main + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "log" + "net/http" + "os" + "strings" + "time" + + "github.com/jackc/pglogrepl" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgproto3" + "golang.org/x/time/rate" +) + +type ExpiringObject struct { + Object Object `json:"object"` + Expiry time.Time `json:"expiry"` +} + +func newExpiringObject(object Object, timeFromNow time.Duration) ExpiringObject { + return ExpiringObject{ + Object: object, + Expiry: time.Now().Add(timeFromNow), + } +} + +type Postgresql struct { + db *sql.DB + replConn *pgconn.PgConn + app *application + systemInfo SystemInfo + limiter *rate.Limiter + duplicateChecker map[string][]ExpiringObject +} + +func (app *application) newPostgresql(systemInfo SystemInfo, duplicateChecker map[string][]ExpiringObject) (postgresql Postgresql, err error) { + db, err := openConnectionPool(systemInfo.Name, systemInfo.ConnectionString, DriverPostgreSQL) + if err != nil { + return postgresql, fmt.Errorf("error opening postgresql db :: %v", err) + } + + // Create replication connection + replConn, err := pgconn.Connect(context.Background(), systemInfo.ReplicationDsn) + if err != nil { + return postgresql, fmt.Errorf("error opening postgresql replication connection :: %v", err) + } + + postgresql.db = db + postgresql.replConn = replConn + postgresql.app = app + postgresql.systemInfo = systemInfo + postgresql.limiter = rate.NewLimiter(rate.Limit(systemInfo.RateLimit), systemInfo.RateBucketSize) + postgresql.duplicateChecker = duplicateChecker + + app.storageEngine.setSafeIndexMap(systemInfo.Name, 0) + + go postgresql.watchQueue() + go postgresql.watchCDC() + + return postgresql, nil +} + +func (p Postgresql) watchQueue() { + var index int64 + for { + // Get the last safe object index for this system + var exists bool + index, exists = p.app.storageEngine.getSafeIndexMap(p.systemInfo.Name) + if !exists { + panic(fmt.Sprintf("safe index not found for system %s", p.systemInfo.Name)) + } + + // Wait for rate limiter + err := p.limiter.Wait(context.Background()) + if err != nil { + // Optionally log or handle error, then break or continue + continue + } + + // Query safeObjects after lastIndex + objects := p.app.storageEngine.getSafeObjectsFromIndex(index) + if len(objects) > 0 { + // Process new objects as needed + index += int64(len(objects)) + } + + for _, object := range objects { + searchFields := []string{} + + prettyObj, err := json.MarshalIndent(object, "", " ") + if err != nil { + p.app.logger.Error("error pretty printing object", "error", err) + } else { + fmt.Printf("Postgresql got object from queue:\n%s\n", string(prettyObj)) + } + + for locationInSystem, fields := range p.systemInfo.PushRouter[object.Type] { + newObj := map[string]any{} + for keyInSchema, location := range fields { + if _, ok := object.Payload[keyInSchema]; ok { + newObj[location.Field] = object.Payload[keyInSchema] + + if fields[keyInSchema].SearchKey { + searchFields = append(searchFields, location.Field) + } + } + } + + var objectIsDuplicate bool + foundDuplicate := false + for i, expiringObj := range p.duplicateChecker[object.Type] { + + objectIsDuplicate = true + + for k, v := range newObj { + if _, ok := expiringObj.Object.Payload[k]; !ok { + objectIsDuplicate = false + break + } + if v != expiringObj.Object.Payload[k] { + objectIsDuplicate = false + break + } + } + + if objectIsDuplicate { + fmt.Println("Postgresql found duplicate object in duplicate checker while watching queue:", expiringObj.Object) + // If we found a duplicate, we can remove it from the duplicate checker + p.duplicateChecker[object.Type] = append(p.duplicateChecker[object.Type][:i], p.duplicateChecker[object.Type][i+1:]...) + foundDuplicate = true + break + } + } + + if !foundDuplicate { + fmt.Println("No duplicate found for object, upserting to PostgreSQL", object) + fmt.Printf("PostgreSQL is upserting object: %v\n", newObj) + + switch object.Operation { + case "upsert": + err = p.upsertJSON(object.Payload, searchFields, locationInSystem, object.Type) + if err != nil { + p.app.logger.Error("error upserting JSON to PostgreSQL", "error", err, "objectType", object.Type, "locationInSystem", locationInSystem, "data", newObj) + } + case "delete": + err = p.deleteFromPostgresql(object.Payload, searchFields, locationInSystem) + if err != nil { + p.app.logger.Error("error deleting from PostgreSQL", "error", err, "objectType", object.Type, "locationInSystem", locationInSystem, "data", newObj) + } + } + } + + } + } + + // Update the safe index map for this system + p.app.storageEngine.setSafeIndexMap(p.systemInfo.Name, index) + } +} + +func (p Postgresql) handleWebhook(w http.ResponseWriter, r *http.Request) { + p.app.logger.Error("PostgreSQL does not support webhooks", "system", p.systemInfo.Name) +} + +func (p Postgresql) upsertJSON(data map[string]any, searchFields []string, locationInSystem string, objectType string) error { + var foundMatch bool + var conflictField string + var conflictValue any + + for _, field := range searchFields { + if v, ok := data[field]; ok { + // Check if a row exists with this search field + query := fmt.Sprintf("SELECT 1 FROM %s WHERE %s = $1 LIMIT 1", locationInSystem, field) + row := p.db.QueryRow(query, v) + var dummy int + err := row.Scan(&dummy) + if err == nil { + foundMatch = true + conflictField = field + conflictValue = v + break + } + if err != sql.ErrNoRows && err != nil { + p.app.logger.Error("error checking for existing row", "error", err, "query", query, "value", v) + return fmt.Errorf("error checking for existing row: %v", err) + } + } + } + + if foundMatch { + // Prepare UPDATE: set all columns except the conflict field + setCols := make([]string, 0, len(data)) + values := make([]any, 0, len(data)) + idx := 1 + for k, v := range data { + if k != conflictField { + setCols = append(setCols, fmt.Sprintf("%s = $%d", k, idx)) + values = append(values, v) + idx++ + } + } + // Add WHERE for the conflict field + whereClause := fmt.Sprintf("%s = $%d", conflictField, idx) + values = append(values, conflictValue) + + updateQuery := fmt.Sprintf( + "UPDATE %s SET %s WHERE %s", + locationInSystem, + strings.Join(setCols, ", "), + whereClause, + ) + + _, err := p.db.Exec(updateQuery, values...) + if err != nil { + p.app.logger.Error("error executing update query", "error", err, "query", updateQuery, "values", values) + return fmt.Errorf("error executing update query: %v", err) + } + } else { + // Build INSERT + columns := make([]string, 0, len(data)) + placeholders := make([]string, 0, len(data)) + insertValues := make([]any, 0, len(data)) + + idx := 1 + for k, v := range data { + columns = append(columns, k) + placeholders = append(placeholders, fmt.Sprintf("$%d", idx)) + insertValues = append(insertValues, v) + idx++ + } + insertQuery := fmt.Sprintf( + "INSERT INTO %s (%s) VALUES (%s)", + locationInSystem, + strings.Join(columns, ", "), + strings.Join(placeholders, ", "), + ) + _, err := p.db.Exec(insertQuery, insertValues...) + if err != nil { + p.app.logger.Error("error executing insert query", "error", err, "query", insertQuery, "values", insertValues) + return fmt.Errorf("error executing insert query: %v", err) + } + } + + object := Object{ + Type: objectType, + Payload: data, + } + + expiringObj := newExpiringObject(object, p.app.config.keepDuplicatesFor) + p.duplicateChecker[objectType] = append(p.duplicateChecker[objectType], expiringObj) + + return nil +} + +// Start CDC for all tables in publication +func (p *Postgresql) watchCDC() { + slotName := "sqlpipe_slot" + outputPlugin := "wal2json" + + replConn, err := pgconn.Connect(context.Background(), p.systemInfo.ReplicationDsn) + if err != nil { + p.app.logger.Error("failed to connect", "error", err) + os.Exit(1) + } + defer replConn.Close(context.Background()) + + sysident, err := pglogrepl.IdentifySystem(context.Background(), replConn) + if err != nil { + p.app.logger.Error("IdentifySystem failed", "error", err) + os.Exit(1) + } + + _, err = pglogrepl.CreateReplicationSlot(context.Background(), replConn, slotName, outputPlugin, pglogrepl.CreateReplicationSlotOptions{Temporary: false, Mode: pglogrepl.LogicalReplication}) + if err != nil { + // If the error is "already exists", it's OK, otherwise fail + if !strings.Contains(err.Error(), "already exists") { + p.app.logger.Error("CreateReplicationSlot failed", "error", err) + os.Exit(1) + } + } + + pluginArguments := []string{"\"pretty-print\" 'true'"} + err = pglogrepl.StartReplication(context.Background(), replConn, slotName, sysident.XLogPos, + pglogrepl.StartReplicationOptions{ + PluginArgs: pluginArguments, + }) + if err != nil { + p.app.logger.Error("StartReplication failed", "error", err) + os.Exit(1) + } + + clientXLogPos := sysident.XLogPos + standbyMessageTimeout := time.Second * 10 + nextStandbyMessageDeadline := time.Now().Add(standbyMessageTimeout) + + for { + if time.Now().After(nextStandbyMessageDeadline) { + err = pglogrepl.SendStandbyStatusUpdate(context.Background(), replConn, pglogrepl.StandbyStatusUpdate{WALWritePosition: clientXLogPos}) + if err != nil { + log.Fatalln("SendStandbyStatusUpdate failed:", err) + } + nextStandbyMessageDeadline = time.Now().Add(standbyMessageTimeout) + } + + ctx, cancel := context.WithDeadline(context.Background(), nextStandbyMessageDeadline) + rawMsg, err := replConn.ReceiveMessage(ctx) + cancel() + if err != nil { + if pgconn.Timeout(err) { + continue + } + log.Fatalln("ReceiveMessage failed:", err) + } + + if errMsg, ok := rawMsg.(*pgproto3.ErrorResponse); ok { + log.Fatalf("received Postgres WAL error: %+v", errMsg) + } + + msg, ok := rawMsg.(*pgproto3.CopyData) + if !ok { + log.Printf("Received unexpected message: %T\n", rawMsg) + continue + } + + switch msg.Data[0] { + case pglogrepl.PrimaryKeepaliveMessageByteID: + pkm, err := pglogrepl.ParsePrimaryKeepaliveMessage(msg.Data[1:]) + if err != nil { + log.Fatalln("ParsePrimaryKeepaliveMessage failed:", err) + } + if pkm.ServerWALEnd > clientXLogPos { + clientXLogPos = pkm.ServerWALEnd + } + if pkm.ReplyRequested { + nextStandbyMessageDeadline = time.Time{} + } + + case pglogrepl.XLogDataByteID: + xld, err := pglogrepl.ParseXLogData(msg.Data[1:]) + if err != nil { + log.Fatalln("ParseXLogData failed:", err) + } + + // if outputPlugin == "wal2json" { + // log.Printf("wal2json data: %s\n", string(xld.WALData)) + // } + + err = p.handleCdcEvent(string(xld.WALData)) + if err != nil { + p.app.logger.Error("error handling CDC event", "error", err, "data", string(xld.WALData)) + return + } + + if xld.WALStart > clientXLogPos { + clientXLogPos = xld.WALStart + } + default: + } + } +} + +type OldKeys struct { + KeyNames []string `json:"keynames"` + KeyValues []any `json:"keyvalues,omitempty"` // Optional, if not provided, the old keys are not included +} + +type CdcChange struct { + Kind string `json:"kind"` + Schema string `json:"schema"` + Table string `json:"table"` + ColumnNames []string `json:"columnnames"` + ColumnTypes []string `json:"columntypes"` + ColumnValues []any `json:"columnvalues"` + OldKeys OldKeys `json:"oldkeys,omitempty"` // Optional, if not provided, the old keys are not included +} + +type CdcEvent struct { + Change []CdcChange `json:"change"` +} + +func (p Postgresql) handleCdcEvent(jsonString string) error { + + // fmt.Println("receive field map: ", p.receiveFieldMap) + + var event CdcEvent + err := json.Unmarshal([]byte(jsonString), &event) + if err != nil { + return fmt.Errorf("error unmarshalling CDC event: %v", err) + } + + // objs := []map[string]any{} + + for _, change := range event.Change { + pullLocation := change.Schema + "." + change.Table + operationType := change.Kind + + obj := map[string]any{} + newObjs := make(map[string]map[string]any) + + switch operationType { + case "insert", "update": + operationType = "upsert" + for i, colName := range change.ColumnNames { + if change.ColumnValues[i] != nil { + obj[colName] = change.ColumnValues[i] + } + } + case "delete": + operationType = "delete" + for i, colName := range change.OldKeys.KeyNames { + if change.OldKeys.KeyValues != nil { + obj[colName] = change.OldKeys.KeyValues[i] + } + } + default: + return fmt.Errorf("unknown operation type: %s", operationType) + } + + fmt.Println("Received cdc data from PostgreSQL:", jsonString) + + for objectType, pullObject := range p.systemInfo.ReceiveRouter[pullLocation] { + newObj := map[string]any{} + + for keyInObj, fields := range pullObject { + newObj[fields.Field] = obj[keyInObj] + } + + newObjs[objectType] = newObj + } + + for schemaName, obj := range newObjs { + + for k, v := range obj { + if v == nil { + delete(obj, k) + } + } + + fmt.Println("Postgresql validating / dupe scanning obj:", obj) + + schema, inMap := p.app.schemaMap[schemaName] + if !inMap { + return fmt.Errorf("no schema found for pull location: %s", pullLocation) + } + + err = schema.Validate(obj) + if err != nil { + return fmt.Errorf("object failed postgresql schema validation for '%s': %v", pullLocation, err) + } + + var objectIsDuplicate bool + foundDuplicate := false + for i, expiringObj := range p.duplicateChecker[schemaName] { + + objectIsDuplicate = true + + for k, v := range obj { + if v != expiringObj.Object.Payload[k] { + objectIsDuplicate = false + break + } + } + + if objectIsDuplicate { + fmt.Println("Postgresql found duplicate object in duplicate checker while handling cdc event:", expiringObj.Object) + // If we found a duplicate, we can remove it from the duplicate checker + p.duplicateChecker[schemaName] = append(p.duplicateChecker[schemaName][:i], p.duplicateChecker[schemaName][i+1:]...) + foundDuplicate = true + break + } + } + + if !foundDuplicate { + + object := Object{ + Operation: operationType, + Type: schemaName, + Payload: obj, + } + + // also add to storage engine + fmt.Println("PostgreSQL no duplicate found. Storing object in queue", obj) + p.app.storageEngine.addSafeObject(object) + + fmt.Println("PostgreSQL no duplicate found for object, adding to duplicate checker", obj) + expiringObj := newExpiringObject(object, p.app.config.keepDuplicatesFor) + p.duplicateChecker[schemaName] = append(p.duplicateChecker[schemaName], expiringObj) + } + } + } + + return nil +} + +// deleteFromPostgresql deletes a row from PostgreSQL based on the searchFields and payload. +func (p Postgresql) deleteFromPostgresql(payload map[string]any, searchFields []string, locationInSystem string) error { + if len(searchFields) == 0 { + return fmt.Errorf("no search fields provided for delete operation") + } + + whereClauses := make([]string, 0, len(searchFields)) + values := make([]any, 0, len(searchFields)) + idx := 1 + for _, field := range searchFields { + val, ok := payload[field] + if !ok { + return fmt.Errorf("search field '%s' not found in payload", field) + } + whereClauses = append(whereClauses, fmt.Sprintf("%s = $%d", field, idx)) + values = append(values, val) + idx++ + } + + deleteQuery := fmt.Sprintf("DELETE FROM %s WHERE %s", locationInSystem, strings.Join(whereClauses, " AND ")) + _, err := p.db.Exec(deleteQuery, values...) + if err != nil { + p.app.logger.Error("error executing delete query", "error", err, "query", deleteQuery, "values", values) + return fmt.Errorf("error executing delete query: %v", err) + } + return nil +} diff --git a/cmd/streaming/routes.go b/cmd/streaming/routes.go new file mode 100644 index 00000000..9664943a --- /dev/null +++ b/cmd/streaming/routes.go @@ -0,0 +1,22 @@ +package main + +import ( + "expvar" + "net/http" + + "github.com/julienschmidt/httprouter" +) + +func (app *application) routes() http.Handler { + router := httprouter.New() + + router.NotFound = http.HandlerFunc(app.receiveHandler) + router.MethodNotAllowed = http.HandlerFunc(app.methodNotAllowedResponse) + + router.HandlerFunc(http.MethodGet, "/v1/healthcheck", app.healthcheckHandler) + router.Handler(http.MethodGet, "/debug/vars", expvar.Handler()) + + return router + + // return app.metrics(app.recoverPanic(app.enableCORS(app.rateLimit(app.authenticate(router))))) +} diff --git a/cmd/streaming/server.go b/cmd/streaming/server.go new file mode 100644 index 00000000..b742ffb4 --- /dev/null +++ b/cmd/streaming/server.go @@ -0,0 +1,62 @@ +package main + +import ( + "context" + "errors" + "fmt" + "net/http" + "os" + "os/signal" + "syscall" + "time" +) + +func (app *application) serve() error { + + srv := &http.Server{ + Addr: fmt.Sprintf(":%d", app.config.port), + Handler: app.routes(), + IdleTimeout: time.Minute, + ReadTimeout: 5 * time.Second, + WriteTimeout: 10 * time.Second, + } + + shutdownError := make(chan error) + + go func() { + quit := make(chan os.Signal, 1) + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + s := <-quit + + app.logger.Info("caught signal", "signal", s.String()) + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + err := srv.Shutdown(ctx) + if err != nil { + shutdownError <- err + } + + app.logger.Info("completing background tasks", "addr", srv.Addr) + + app.wg.Wait() + shutdownError <- nil + }() + + app.logger.Info("starting server", "addr", srv.Addr) + + err := srv.ListenAndServe() + if !errors.Is(err, http.ErrServerClosed) { + return err + } + + err = <-shutdownError + if err != nil { + return err + } + + app.logger.Info("stopped server", "addr", srv.Addr) + + return nil +} diff --git a/cmd/streaming/snowflake.go b/cmd/streaming/snowflake.go new file mode 100644 index 00000000..fade084d --- /dev/null +++ b/cmd/streaming/snowflake.go @@ -0,0 +1,33 @@ +package main + +import ( + "database/sql" + "errors" + "fmt" + "net/http" + + _ "github.com/snowflakedb/gosnowflake" +) + +type Snowflake struct { + Connection *sql.DB +} + +func newSnowflake(systemInfo SystemInfo) (snowflake Snowflake, err error) { + db, err := openConnectionPool(systemInfo.Name, systemInfo.ConnectionString, DriverSnowflake) + if err != nil { + return snowflake, fmt.Errorf("error opening snowflake db :: %v", err) + } + + snowflake.Connection = db + + return snowflake, nil +} + +func (s Snowflake) handleWebhook(w http.ResponseWriter, r *http.Request) { + // Snowflake will not send us webhooks, so this is a no-op +} + +func (s Snowflake) mapProperties(obj map[string]interface{}) (map[string]interface{}, error) { + return nil, errors.New("not implemented for snowflake yet") +} diff --git a/cmd/streaming/storageEngine.go b/cmd/streaming/storageEngine.go new file mode 100644 index 00000000..0d5c1b4c --- /dev/null +++ b/cmd/streaming/storageEngine.go @@ -0,0 +1,75 @@ +package main + +import ( + "fmt" + "sync" +) + +type Object struct { + Type string `json:"type"` + Operation string `json:"operation"` + Payload map[string]any `json:"payload"` +} + +type storageEngine struct { + safeIndexMap map[string]int64 + indexMapMu sync.RWMutex + safeObjects []Object + objectsMu sync.RWMutex +} + +func newStorageEngine() (*storageEngine, error) { + storageEngine := &storageEngine{ + safeIndexMap: make(map[string]int64), + safeObjects: make([]Object, 0), + } + return storageEngine, nil +} + +func (s *storageEngine) setSafeIndexMap(key string, index int64) { + s.indexMapMu.Lock() + defer s.indexMapMu.Unlock() + s.safeIndexMap[key] = index +} + +func (s *storageEngine) getSafeIndexMap(key string) (int64, bool) { + s.indexMapMu.RLock() + defer s.indexMapMu.RUnlock() + index, exists := s.safeIndexMap[key] + return index, exists +} + +func (s *storageEngine) addSafeObject(object Object) { + s.objectsMu.Lock() + defer s.objectsMu.Unlock() + s.safeObjects = append(s.safeObjects, object) +} + +func (s *storageEngine) getSafeObjectsFromIndex(index int64) []Object { + s.objectsMu.RLock() + defer s.objectsMu.RUnlock() + + if index < 0 || index >= int64(len(s.safeObjects)) { + return nil + } + + // Return a slice of safeObjects starting from the given index + return s.safeObjects[index:] +} + +func (s *storageEngine) printAllContents() { + s.indexMapMu.RLock() + defer s.indexMapMu.RUnlock() + s.objectsMu.RLock() + defer s.objectsMu.RUnlock() + + println("safeIndexMap contents:") + for k, v := range s.safeIndexMap { + println(" Key:", k, "Value:", v) + } + + println("safeObjects contents:") + for i, obj := range s.safeObjects { + println(" Index:", i, "Value:", fmt.Sprintf("%v", obj)) + } +} diff --git a/cmd/streaming/stripe.go b/cmd/streaming/stripe.go new file mode 100644 index 00000000..787fbd29 --- /dev/null +++ b/cmd/streaming/stripe.go @@ -0,0 +1,451 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "os/exec" + "time" + + "github.com/stripe/stripe-go/v82" + "golang.org/x/time/rate" +) + +// deleteFromStripe simulates deleting an object from Stripe based on the searchKey and searchValue. +func (s Stripe) deleteFromStripe(endpoint string, object Object, searchKey, searchValue string) error { + if searchKey == "" || searchValue == "" { + return fmt.Errorf("deleteFromStripe: searchKey and searchValue must be provided") + } + + baseURL := "https://api.stripe.com/v1" + deleteUrl := fmt.Sprintf("%s/%s/%s", baseURL, endpoint, searchValue) + req, err := http.NewRequest("DELETE", deleteUrl, nil) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+s.apiKey) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + fmt.Printf("Making DELETE request to Stripe: %s\n", deleteUrl) + resp, err := http.DefaultClient.Do(req) + if err != nil { + return fmt.Errorf("failed to delete object at stripe route %s, error making request: %w", deleteUrl, err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("failed to read response body from stripe route %s, error reading response body: %w", deleteUrl, err) + } + + if resp.StatusCode >= 400 { + return fmt.Errorf("failed to delete object at stripe route %s, status code: %d, response: %s", deleteUrl, resp.StatusCode, string(body)) + } + + fmt.Println("Stripe deleted object:", string(body)) + return nil +} + +type Stripe struct { + client *stripe.Client + apiKey string + app *application + // receiveFieldMap map[string]map[string]map[string]Location + // pushFieldMap map[string]map[string]map[string]Location + limiter *rate.Limiter + systemInfo SystemInfo + duplicateChecker map[string][]ExpiringObject +} + +func (app *application) newStripe(systemInfo SystemInfo, duplicateChecker map[string][]ExpiringObject) (system SystemInterface, err error) { + + if systemInfo.UseCliListener { + + if _, err := exec.LookPath("stripe"); err != nil { + return nil, fmt.Errorf("Stripe CLI not found in PATH. Please install it to use Stripe listening mode: %w", err) + } + + // Forward Stripe events to our local endpoint + forwardURL := fmt.Sprintf("http://localhost:%d/%v", app.config.port, systemInfo.Name) + cmd := exec.Command("stripe", "listen", "--forward-to", forwardURL) + cmd.Stderr = os.Stderr + + cmd.Env = append(os.Environ(), fmt.Sprintf("STRIPE_API_KEY=%s", systemInfo.ApiKey)) + + go func() { + app.logger.Info("Starting Stripe CLI listener", "command", cmd.String()) + err := cmd.Run() + if err != nil { + return + } + }() + } + + stripeClient := stripe.NewClient(systemInfo.ApiKey) + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + listParams := &stripe.CouponListParams{} + listParams.Limit = stripe.Int64(1) + + for _, err := range stripeClient.V1Coupons.List(ctx, listParams) { + // We are only testing the connection, so we don't want to do anything with + // the data. Do not read it, store it, print it, or log it. Nothing! + if err != nil { + return nil, err + } + + break + } + + app.logger.Info("Stripe test api call was successful", "system", systemInfo.Name) + + stripeSystem := &Stripe{ + client: stripeClient, + app: app, + limiter: rate.NewLimiter(rate.Limit(systemInfo.RateLimit), systemInfo.RateBucketSize), + systemInfo: systemInfo, + duplicateChecker: duplicateChecker, + apiKey: systemInfo.ApiKey, + } + + app.storageEngine.setSafeIndexMap(systemInfo.Name, 0) + + go stripeSystem.watchQueue() + + return stripeSystem, nil +} + +func (s Stripe) watchQueue() { + var index int64 + for { + // Get the last safe object index for this system + var exists bool + index, exists = s.app.storageEngine.getSafeIndexMap(s.systemInfo.Name) + if !exists { + panic(fmt.Sprintf("safe index not found for system %s", s.systemInfo.Name)) + } + + // Wait for rate limiter + err := s.limiter.Wait(context.Background()) + if err != nil { + // Optionally log or handle error, then break or continue + continue + } + + // Query safeObjects after lastIndex + objects := s.app.storageEngine.getSafeObjectsFromIndex(index) + if len(objects) > 0 { + // Process new objects as needed + index += int64(len(objects)) + } + + for _, object := range objects { + + fmt.Printf("Stripe got object from queue: %v\n", object) + var searchKey string + var searchValue string + + for locationInSystem, pushLocation := range s.systemInfo.PushRouter[object.Type] { + newObj := Object{ + Payload: make(map[string]any), + Operation: object.Operation, + Type: object.Type, + } + for keyInSchema, field := range pushLocation { + if _, ok := object.Payload[keyInSchema]; ok { + newObj.Payload[field.Field] = object.Payload[keyInSchema] + + if field.SearchKey { + searchKey = field.Field + searchValue = fmt.Sprint(newObj.Payload[field.Field]) + } + } + + if field.Hardcode != nil && !isZeroValue(field.Hardcode) { + newObj.Payload[field.Field] = field.Hardcode + } + } + + var objectIsDuplicate bool + foundDuplicate := false + for i, expiringObj := range s.duplicateChecker[object.Type] { + fmt.Println("Stripe checking duplicate checker for object:", expiringObj.Object) + objectIsDuplicate = true + for k, v := range expiringObj.Object.Payload { + if v != object.Payload[k] { + objectIsDuplicate = false + break + } + } + if objectIsDuplicate { + fmt.Println("Stripe found duplicate object in duplicate checker while watching queue:", expiringObj.Object) + // If we found a duplicate, we can remove it from the duplicate checker + s.duplicateChecker[object.Type] = append(s.duplicateChecker[object.Type][:i], s.duplicateChecker[object.Type][i+1:]...) + foundDuplicate = true + break + } + } + + if !foundDuplicate { + switch object.Operation { + case "upsert": + fmt.Printf("Stripe is upserting object. Search key: %v, Search value: %v (route: %s): %v\n", searchKey, searchValue, locationInSystem, newObj) + // Upsert the object to Stripe + _, err := s.upsertObject(locationInSystem, newObj, object.Type, searchKey, searchValue) + if err != nil { + s.app.logger.Error("Failed to upsert object to Stripe", "error", err, "object", newObj) + continue + } + case "delete": + fmt.Printf("Stripe is deleting object. Search key: %v, Search value: %v (route: %s): %v\n", searchKey, searchValue, locationInSystem, newObj) + err := s.deleteFromStripe(locationInSystem, newObj, searchKey, searchValue) + if err != nil { + s.app.logger.Error("Failed to delete object from Stripe", "error", err, "object", newObj) + continue + } + } + } + } + } + + // Update the safe index map for this system + s.app.storageEngine.setSafeIndexMap(s.systemInfo.Name, index) + } +} + +func (s Stripe) upsertObject(endpoint string, object Object, objectType string, searchKey, searchValue string) ([]byte, error) { + // Replace with your actual secret key or use an environment variable + form := url.Values{} + + for key, value := range object.Payload { + + if key == searchKey { + continue + } + + switch v := value.(type) { + case string: + form.Set(key, v) + case int, int64, float64: + form.Set(key, fmt.Sprintf("%v", v)) + case bool: + if v { + form.Set(key, "true") + } else { + form.Set(key, "false") + } + default: + return nil, fmt.Errorf("unsupported value type for key %s: %T", key, value) + } + } + + if len(form) == 0 { + return nil, nil + } + + baseURL := "https://api.stripe.com/v1" + encoded := form.Encode() + + // If searchValue is empty, just create (insert) the object + if searchValue == "" { + createUrl := fmt.Sprintf("%s/%s", baseURL, endpoint) + req, err := http.NewRequest("POST", createUrl, bytes.NewBufferString(encoded)) + if err != nil { + return nil, err + } + + req.Header.Set("Authorization", "Bearer "+s.apiKey) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + fmt.Printf("Making request to Stripe to create object: %s\n", createUrl) + fmt.Println("Stripe create form data:", form.Encode()) + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, fmt.Errorf("failed to create object at stripe route %s, error making request: %w", createUrl, err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to create object at stripe route %s, error reading response body: %w", createUrl, err) + } + + if resp.StatusCode >= 400 { + return nil, fmt.Errorf("failed to create object at stripe route %s, status code: %d, response: %s", createUrl, resp.StatusCode, string(body)) + } + + fmt.Println("Stripe created object:", string(body)) + expiringObj := newExpiringObject(object, s.app.config.keepDuplicatesFor) + s.duplicateChecker[objectType] = append(s.duplicateChecker[objectType], expiringObj) + return body, nil + } + + // Otherwise, update it + updateUrl := fmt.Sprintf("%s/%s/%s", baseURL, endpoint, searchValue) + req, err := http.NewRequest("POST", updateUrl, bytes.NewBufferString(encoded)) + if err != nil { + return nil, err + } + + req.Header.Set("Authorization", "Bearer "+s.apiKey) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + fmt.Printf("Making request to Stripe: %s\n", updateUrl) + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body from stripe route %s, error reading response body: %w", updateUrl, err) + } + + expiringObj := newExpiringObject(object, s.app.config.keepDuplicatesFor) + s.duplicateChecker[objectType] = append(s.duplicateChecker[objectType], expiringObj) + + return body, nil +} + +func (s *Stripe) handleWebhook(w http.ResponseWriter, r *http.Request) { + // Immediately acknowledge receipt to Stripe + w.WriteHeader(http.StatusOK) + var err error + + // fmt.Println("Received Stripe webhook") + + var event stripe.Event + if err := json.NewDecoder(r.Body).Decode(&event); err != nil { + s.app.logger.Error("Failed to decode Stripe event", "error", err) + return + } + + prettyData, err := json.MarshalIndent(event, "", " ") + if err != nil { + s.app.logger.Error("Failed to pretty print Stripe event", "error", err) + } else { + fmt.Printf("Received Stripe event:\n%s\n", string(prettyData)) + } + + objectName := string(event.Type) + var operationType string + // If the event type contains a period, we only want the part before it + if idx := indexOfPeriod(objectName); idx > 0 { + operationType = objectName[idx+1:] + objectName = objectName[:idx] + } + + switch operationType { + case "created", "updated": + operationType = "upsert" + case "deleted": + operationType = "delete" + default: + s.app.logger.Error("Unknown Stripe event type", "event_type", event.Type) + return + } + + var obj map[string]any + err = json.Unmarshal(event.Data.Raw, &obj) + if err != nil { + s.app.logger.Error("Failed to unmarshal Stripe event data", "error", err) + return + } + + newObjs := make(map[string]map[string]any) + + for schemaName, fields := range s.systemInfo.ReceiveRouter[objectName] { + newModel := map[string]any{} + + for keyInObj, field := range fields { + if field.Hardcode != nil && !isZeroValue(field.Hardcode) { + newModel[field.Field] = field.Hardcode + } else { + newModel[field.Field] = getNestedValue(obj, keyInObj) + } + } + + newObjs[schemaName] = newModel + } + + for schemaName, obj := range newObjs { + + schema, inMap := s.app.schemaMap[schemaName] + if !inMap { + fmt.Printf("No schema found for object: %s\n", objectName) + return + } + + for k, v := range obj { + if v == nil { + delete(obj, k) + } + } + + fmt.Println("About to validate new object against schema:", schemaName, obj) + + err = schema.Validate(obj) + if err != nil { + fmt.Printf("Object failed stripe schema validation for '%s': %v\n", objectName, err) + return + } + + var objectIsDuplicate bool + foundDuplicate := false + for i, expiringObj := range s.duplicateChecker[schemaName] { + + fmt.Println("Stripe checking duplicate checker for object:", expiringObj.Object) + + objectIsDuplicate = true + + for k, v := range obj { + if v != expiringObj.Object.Payload[k] { + objectIsDuplicate = false + break + } + } + + if objectIsDuplicate { + fmt.Println("Stripe found duplicate object in duplicate checker while handling cdc event:", expiringObj.Object) + // If we found a duplicate, we can remove it from the duplicate checker + s.duplicateChecker[schemaName] = append(s.duplicateChecker[schemaName][:i], s.duplicateChecker[schemaName][i+1:]...) + foundDuplicate = true + break + } + } + + if !foundDuplicate { + + object := Object{ + Type: schemaName, + Operation: operationType, + Payload: obj, + } + + fmt.Println("Stripe no duplicate found for object, adding to queue", obj) + s.app.storageEngine.addSafeObject(object) + + fmt.Println("Stripe no duplicate found for object, adding to duplicate checker", obj) + expiringObj := newExpiringObject(object, s.app.config.keepDuplicatesFor) + s.duplicateChecker[schemaName] = append(s.duplicateChecker[schemaName], expiringObj) + } + } +} + +// indexOfPeriod returns the index of the first period in s, or -1 if not found +func indexOfPeriod(s string) int { + for i, c := range s { + if c == '.' { + return i + } + } + return -1 +} diff --git a/cmd/streaming/systems.go b/cmd/streaming/systems.go new file mode 100644 index 00000000..9b497500 --- /dev/null +++ b/cmd/streaming/systems.go @@ -0,0 +1,86 @@ +package main + +import ( + "fmt" + "net/http" + "time" +) + +var ( + Statuses = []string{StatusQueued, StatusRunning, StatusCancelled, StatusError, StatusComplete, ""} + + StatusQueued = "queued" + StatusRunning = "running" + StatusCancelled = "cancelled" + StatusError = "error" + StatusComplete = "complete" + + TypePostgreSQL = "postgresql" + TypeMySQL = "mysql" + TypeMSSQL = "mssql" + TypeOracle = "oracle" + TypeSnowflake = "snowflake" + TypeStripe = "stripe" + + DriverPostgreSQL = "pgx" + DriverMySQL = "mysql" + DriverMSSQL = "sqlserver" + DriverOracle = "oracle" + DriverSnowflake = "snowflake" +) + +type Field struct { + Field string `yaml:"field" json:"field"` + SearchKey bool `yaml:"search_key,omitempty" json:"search_key,omitempty"` + Hardcode any `yaml:"hardcode,omitempty" json:"hardcode,omitempty"` +} + +type PullObject map[string]Field +type PullLocation map[string]PullObject +type ReceiveRouter map[string]PullLocation + +type PushRouter map[string]PushObject +type PushObject map[string]PushLocation +type PushLocation map[string]Field + +type SystemInfo struct { + Name string `yaml:"name" json:"name"` + Type string `yaml:"type" json:"type"` + ConnectionString string `yaml:"dsn" json:"dsn"` + MaxOpenConnections int `yaml:"max_open_connections" json:"max_open_connections"` + MaxIdleConnections int `yaml:"max_idle_connections" json:"max_idle_connections"` + MaxIdleTime time.Duration `yaml:"max_connection_idle_time" json:"max_connection_idle_time"` + Hostname string `yaml:"hostname,omitempty" json:"hostname,omitempty"` + Port int `yaml:"port,omitempty" json:"port,omitempty"` + Database string `yaml:"database,omitempty" json:"database,omitempty"` + Username string `yaml:"username,omitempty" json:"username,omitempty"` + Password string `yaml:"-" json:"-"` + Dsn string `yaml:"-" json:"-"` + ReplicationDsn string `yaml:"replication_dsn,omitempty" json:"replication_dsn,omitempty"` + ApiKey string `yaml:"api_key" json:"-"` + EndpointSecret string `yaml:"-" json:"-"` + RateLimit int `yaml:"rate_limit,omitempty" json:"rate_limit,omitempty"` + RateBucketSize int `yaml:"rate_bucket_size,omitempty" json:"rate_bucket_size,omitempty"` + UseCliListener bool `yaml:"use_cli_listener,omitempty" json:"use_cli_listener,omitempty"` + ReceiveRouter ReceiveRouter `yaml:"receive_router,omitempty" json:"receive_router,omitempty"` + PushRouter PushRouter `yaml:"push_router,omitempty" json:"push_router,omitempty"` +} + +type SystemInterface interface { + handleWebhook(w http.ResponseWriter, r *http.Request) + // getFieldMap() map[string]string + // createModels(obj map[string]interface{}) (map[string]interface{}, error) +} + +func (app *application) NewSystem(systemInfo SystemInfo, port int, duplicateChecker map[string][]ExpiringObject) (system SystemInterface, err error) { + switch systemInfo.Type { + case TypePostgreSQL: + return app.newPostgresql(systemInfo, duplicateChecker) + case TypeSnowflake: + return newSnowflake(systemInfo) + case TypeStripe: + return app.newStripe(systemInfo, duplicateChecker) + default: + return system, fmt.Errorf("unsupported system type %v", systemInfo.Type) + } +} diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100644 index 00000000..7981546f --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,8 @@ +#!/bin/sh + +exec /bin/streaming \ + -port $PORT \ + -systems-dir "$SYSTEMS_DIR" \ + -models-dir "$MODELS_DIR" +# -segment-size $SEGMENT_SIZE \ +# -queue-dir "$QUEUE_DIR" diff --git a/go.mod b/go.mod index 0a521e56..3195cf39 100644 --- a/go.mod +++ b/go.mod @@ -1,25 +1,36 @@ -module github.com/sqlpipe/sqlpipe-pro +module github.com/sqlpipe/sqlpipe -go 1.20 +go 1.24 require ( - github.com/go-sql-driver/mysql v1.7.1 + github.com/go-sql-driver/mysql v1.8.1 github.com/google/uuid v1.4.0 - github.com/jackc/pgx/v5 v5.5.0 + github.com/jackc/pglogrepl v0.0.0-20250509230407-a9884f6bd75a + github.com/jackc/pgx/v5 v5.5.4 github.com/julienschmidt/httprouter v1.3.0 github.com/microsoft/go-mssqldb v1.6.0 + github.com/ory/dockertest/v3 v3.12.0 + github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 github.com/sijms/go-ora/v2 v2.7.19 github.com/snowflakedb/gosnowflake v1.6.25 - golang.org/x/sync v0.5.0 + github.com/stripe/stripe-go/v82 v82.3.0 + golang.org/x/sync v0.8.0 + golang.org/x/time v0.12.0 + gopkg.in/yaml.v3 v3.0.1 ) require ( + dario.cat/mergo v1.0.0 // indirect + filippo.io/edwards25519 v1.1.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.2 // indirect github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.2.0 // indirect + github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c // indirect + github.com/Microsoft/go-winio v0.6.2 // indirect + github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 // indirect github.com/andybalholm/brotli v1.0.6 // indirect github.com/apache/arrow/go/v12 v12.0.1 // indirect github.com/apache/thrift v0.19.0 // indirect @@ -36,17 +47,27 @@ require ( github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.16.2 // indirect github.com/aws/aws-sdk-go-v2/service/s3 v1.42.1 // indirect github.com/aws/smithy-go v1.16.0 // indirect + github.com/cenkalti/backoff/v4 v4.3.0 // indirect + github.com/containerd/continuity v0.4.5 // indirect github.com/danieljoos/wincred v1.2.0 // indirect + github.com/docker/cli v27.4.1+incompatible // indirect + github.com/docker/docker v27.1.1+incompatible // indirect + github.com/docker/go-connections v0.5.0 // indirect + github.com/docker/go-units v0.5.0 // indirect github.com/dvsekhvalnov/jose2go v1.5.0 // indirect github.com/form3tech-oss/jwt-go v3.2.5+incompatible // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect + github.com/go-viper/mapstructure/v2 v2.1.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect + github.com/gogo/protobuf v1.3.2 // indirect github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect github.com/golang-sql/sqlexp v0.1.0 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/google/flatbuffers v23.5.26+incompatible // indirect + github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect + github.com/jackc/pgio v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/puddle/v2 v2.2.1 // indirect @@ -56,18 +77,30 @@ require ( github.com/klauspost/cpuid/v2 v2.2.6 // indirect github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8 // indirect github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3 // indirect + github.com/moby/docker-image-spec v1.3.1 // indirect + github.com/moby/sys/user v0.3.0 // indirect + github.com/moby/term v0.5.0 // indirect github.com/mtibben/percent v0.2.1 // indirect + github.com/opencontainers/go-digest v1.0.0 // indirect + github.com/opencontainers/image-spec v1.1.0 // indirect + github.com/opencontainers/runc v1.2.3 // indirect github.com/pierrec/lz4/v4 v4.1.18 // indirect github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect + github.com/pkg/errors v0.9.1 // indirect github.com/sirupsen/logrus v1.9.3 // indirect + github.com/stretchr/objx v0.5.2 // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect + github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect + github.com/xeipuuv/gojsonschema v1.2.0 // indirect github.com/zeebo/xxh3 v1.0.2 // indirect - golang.org/x/crypto v0.15.0 // indirect + golang.org/x/crypto v0.22.0 // indirect golang.org/x/exp v0.0.0-20231108232855-2478ac86f678 // indirect golang.org/x/mod v0.14.0 // indirect - golang.org/x/net v0.18.0 // indirect - golang.org/x/sys v0.14.0 // indirect - golang.org/x/term v0.14.0 // indirect + golang.org/x/net v0.24.0 // indirect + golang.org/x/sys v0.28.0 // indirect + golang.org/x/term v0.19.0 // indirect golang.org/x/text v0.14.0 // indirect golang.org/x/tools v0.15.0 // indirect golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index d2786ae8..83c02caa 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,7 @@ +dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk= +dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs= github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN7oaIRCjzsZ2dE+yG5k+rsdt3qcwykqK6HVGcKwsw4= github.com/99designs/keyring v1.2.2 h1:pZd3neh/EmUzWONb35LxQfvuY7kiSXAq3HQd97+XBn0= @@ -5,16 +9,27 @@ github.com/99designs/keyring v1.2.2/go.mod h1:wes/FrByc8j7lFOAGLGSNEg8f/PaI3cgTB github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0 h1:fb8kj/Dh4CSwgsOzHeZY4Xh68cFVbzXx+ONXGMY//4w= github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0/go.mod h1:uReU2sSxZExRPBAg3qKzmAucSi51+SP1OhohieR821Q= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.3.0 h1:vcYCAze6p19qBW7MhZybIsqD8sMV8js0NyQM8JDnVtg= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.3.0/go.mod h1:OQeznEEkTZ9OrhHJoDD8ZDq51FHgXjqtP9z6bEwBq9U= github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.0 h1:d81/ng9rET2YqdVkVwkb6EXeRrLJIwyGnJcAlAWKwhs= github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.0/go.mod h1:s4kgfzA0covAXNicZHDMN58jExvcng2mC/DepXiF1EI= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.2.0 h1:Ma67P/GGprNwsslzEH6+Kb8nybI8jpDTm4Wmzu2ReK8= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.2.0/go.mod h1:c+Lifp3EDEamAkPVzMooRNOK6CZjNSdEnf1A7jsI9u4= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.0.0 h1:yfJe15aSwEQ6Oo6J+gdfdulPNoZ3TEhmbhLIoxZcA+U= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.0.0/go.mod h1:Q28U+75mpCaSCDowNEmhIo/rmgdkqmkmzI7N6TGR4UY= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v0.8.0 h1:T028gtTPiYt/RMUfs8nVsAL7FDQrfLlrm/NnRG/zcC4= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v0.8.0/go.mod h1:cw4zVQgBby0Z5f2v0itn6se2dDP17nTjbZFXW5uPyHA= github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.2.0 h1:gggzg0SUMs6SQbEw+3LoSsYf9YMjkupeAnHMX8O9mmY= github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.2.0/go.mod h1:+6KLcKIVgxoBDMqMO/Nvy7bZ9a0nbU3I1DtFQK3YvB4= +github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= +github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/AzureAD/microsoft-authentication-library-for-go v1.1.0 h1:HCc0+LpPfpCKs6LGGLAhwBARt9632unrVcI6i8s/8os= +github.com/AzureAD/microsoft-authentication-library-for-go v1.1.0/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c h1:RGWPOewvKIROun94nF7v2cua9qP+thov/7M50KEoeSU= github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c/go.mod h1:X0CRv0ky0k6m906ixxpzmDRLvX58TFUKS2eePweuyxk= +github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= +github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= +github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 h1:TngWCqHvy9oXAN6lEVMRuU21PR1EtLVZJmdB18Gu3Rw= +github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5/go.mod h1:lmUJ/7eu/Q8D7ML55dXQrVaamCz2vxCfdQBasLZfHKk= github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI= github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= github.com/apache/arrow/go/v12 v12.0.1 h1:JsR2+hzYYjgSUkBSaahpqCetqZMr76djX80fF/DiJbg= @@ -26,9 +41,11 @@ github.com/aws/aws-sdk-go-v2 v1.22.2/go.mod h1:Kd0OJtkW3Q0M0lUWGszapWjEvrXDzRW+D github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.5.0 h1:hHgLiIrTRtddC0AKcJr5s7i/hLgcpTt+q/FKxf1Zayk= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.5.0/go.mod h1:w4I/v3NOWgD+qvs1NPEwhd++1h3XPHFaVxasfY6HlYQ= github.com/aws/aws-sdk-go-v2/config v1.22.3 h1:JewoyAW8yPRpWus3gy/rIGhorHN4zInB8wgJfavaxwM= +github.com/aws/aws-sdk-go-v2/config v1.22.3/go.mod h1:/kLz7rok3cKoM3dcQuNr86T4rXnC6HYIMWMx8vFUXig= github.com/aws/aws-sdk-go-v2/credentials v1.15.2 h1:rKH7khRMxPdD0u3dHecd0Q7NOVw3EUe7AqdkUOkiOGI= github.com/aws/aws-sdk-go-v2/credentials v1.15.2/go.mod h1:tXM8wmaeAhfC7nZoCxb0FzM/aRaB1m1WQ7x0qlBLq80= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.3 h1:G5KawTAkyHH6WyKQCdHiW4h3PmAXNJpOgwKg3H7sDRE= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.3/go.mod h1:hugKmSFnZB+HgNI1sYGT14BUPZkO6alC/e0AWu+0IAQ= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.13.4 h1:MD4eOs8lbf86CUawDXwkPoRrY0Ds2gDo1QLfDnwrAfk= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.13.4/go.mod h1:C4NNsNsbOD7YwuQRmNToEizYYoJVBM7CjpjvppTPl+k= github.com/aws/aws-sdk-go-v2/internal/configsources v1.2.2 h1:AaQsr5vvGR7rmeSWBtTCcw16tT9r51mWijuCQhzLnq8= @@ -36,6 +53,7 @@ github.com/aws/aws-sdk-go-v2/internal/configsources v1.2.2/go.mod h1:o1IiRn7CWoc github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.5.2 h1:UZx8SXZ0YtzRiALzYAWcjb9Y9hZUR7MBKaBQ5ouOjPs= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.5.2/go.mod h1:ipuRpcSaklmxR6C39G187TpBAO132gUfleTGccUPs8c= github.com/aws/aws-sdk-go-v2/internal/ini v1.5.2 h1:5KL4rS1yq5rJ6Q8lrlsFPHCPWwhkMINNiRXHb4YbFyc= +github.com/aws/aws-sdk-go-v2/internal/ini v1.5.2/go.mod h1:rdAuXeHWhI/zkpYcO5n8WCpaIgY9MUxFyBsuqq3kjyA= github.com/aws/aws-sdk-go-v2/internal/v4a v1.2.2 h1:pyVrNAf7Hwz0u39dLKN5t+n0+K/3rMYKuiOoIum3AsU= github.com/aws/aws-sdk-go-v2/internal/v4a v1.2.2/go.mod h1:mydrfOb9uiOYCxuCPR8YHQNQyGQwUQ7gPMZGBKbH8NY= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.10.0 h1:CJxo7ZBbaIzmXfV3hjcx36n9V87gJsIUPJflwqEHl3Q= @@ -49,29 +67,54 @@ github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.16.2/go.mod h1:p+S7RNb github.com/aws/aws-sdk-go-v2/service/s3 v1.42.1 h1:o6MCcX1rJW8Y3g+hvg2xpjF6JR6DftuYhfl3Nc1WV9Q= github.com/aws/aws-sdk-go-v2/service/s3 v1.42.1/go.mod h1:UDtxEWbREX6y4KREapT+jjtjoH0TiVSS6f5nfaY1UaM= github.com/aws/aws-sdk-go-v2/service/sso v1.17.1 h1:km+ZNjtLtpXYf42RdaDZnNHm9s7SYAuDGTafy6nd89A= +github.com/aws/aws-sdk-go-v2/service/sso v1.17.1/go.mod h1:aHBr3pvBSD5MbzOvQtYutyPLLRPbl/y9x86XyJJnUXQ= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.19.1 h1:iRFNqZH4a67IqPvK8xxtyQYnyrlsvwmpHOe9r55ggBA= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.19.1/go.mod h1:pTy5WM+6sNv2tB24JNKFtn6EvciQ5k40ZJ0pq/Iaxj0= github.com/aws/aws-sdk-go-v2/service/sts v1.25.1 h1:txgVXIXWPXyqdiVn92BV6a/rgtpX31HYdsOYj0sVQQQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.25.1/go.mod h1:VAiJiNaoP1L89STFlEMgmHX1bKixY+FaP+TpRFrmyZ4= github.com/aws/smithy-go v1.16.0 h1:gJZEH/Fqh+RsvlJ1Zt4tVAtV6bKkp3cC+R6FCZMNzik= github.com/aws/smithy-go v1.16.0/go.mod h1:NukqUGpCZIILqqiV0NIjeFh24kd/FAa4beRb6nbIUPE= +github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= +github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/containerd/continuity v0.4.5 h1:ZRoN1sXq9u7V6QoHMcVWGhOwDFqZ4B9i5H6un1Wh0x4= +github.com/containerd/continuity v0.4.5/go.mod h1:/lNJvtJKUQStBzpVQ1+rasXO1LAWtUQssk28EZvJ3nE= +github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= +github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/danieljoos/wincred v1.2.0 h1:ozqKHaLK0W/ii4KVbbvluM91W2H3Sh0BncbUNPS7jLE= github.com/danieljoos/wincred v1.2.0/go.mod h1:FzQLLMKBFdvu+osBrnFODiv32YGwCfx0SkRa/eYHgec= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= +github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/docker/cli v27.4.1+incompatible h1:VzPiUlRJ/xh+otB75gva3r05isHMo5wXDfPRi5/b4hI= +github.com/docker/cli v27.4.1+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/docker v27.1.1+incompatible h1:hO/M4MtV36kzKldqnA37IWhebRA+LnqqcqDja6kVaKY= +github.com/docker/docker v27.1.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c= +github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/dvsekhvalnov/jose2go v1.5.0 h1:3j8ya4Z4kMCwT5nXIKFSV84YS+HdqSSO0VsTQxaLAeM= github.com/dvsekhvalnov/jose2go v1.5.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU= github.com/form3tech-oss/jwt-go v3.2.5+incompatible h1:/l4kBbb4/vGSsdtB5nUe8L7B9mImVMaBPw9L/0TBHU8= github.com/form3tech-oss/jwt-go v3.2.5+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= -github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= -github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= +github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +github.com/go-viper/mapstructure/v2 v2.1.0 h1:gHnMa2Y/pIxElCH2GlZZ1lZSsn6XMtufpGyP1XxdC/w= +github.com/go-viper/mapstructure/v2 v2.1.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 h1:ZpnhV/YsD2/4cESfV5+Hoeu/iUR3ruzNvZ+yQfO03a0= github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE= +github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA= github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A= @@ -80,17 +123,24 @@ github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/flatbuffers v23.5.26+incompatible h1:M9dgRyhJemaM4Sw8+66GHBu8ioaQmyPLg1b8VwK5WJg= github.com/google/flatbuffers v23.5.26+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= -github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4= github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= +github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE= +github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8= +github.com/jackc/pglogrepl v0.0.0-20250509230407-a9884f6bd75a h1:f2a1BtfxAaGSs+kI2MfZjNf9KiHzynJKqOPLTkF8L4Y= +github.com/jackc/pglogrepl v0.0.0-20250509230407-a9884f6bd75a/go.mod h1:YC4Mb92BuoJKDNno/uRIBKU9FOt+y2uMFLQqo2fMgN4= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.5.0 h1:NxstgwndsTRy7eq9/kqYc/BZh5w2hHJV86wjvO+1xPw= -github.com/jackc/pgx/v5 v5.5.0/go.mod h1:Ig06C2Vu0t5qXC60W8sqIthScaEnFvojjj9dSljmHRA= +github.com/jackc/pgx/v5 v5.5.4 h1:Xp2aQS8uXButQdnCMWNmvx6UysWQQC+u1EoizjguY+8= +github.com/jackc/pgx/v5 v5.5.4/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A= github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk= github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= @@ -99,6 +149,8 @@ github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGw github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U= github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/asmfmt v1.3.2 h1:4Ri7ox3EwapiOjCki+hw14RyKk201CN4rzyCJRFLpK4= github.com/klauspost/asmfmt v1.3.2/go.mod h1:AG8TuvYojzulgDAMCnYn50l/5QV3Bs/tp6j0HLHbNSE= github.com/klauspost/compress v1.17.2 h1:RlWWUY/Dr4fL8qk9YG7DTZ7PDgME2V4csBXA8L/ixi4= @@ -106,26 +158,50 @@ github.com/klauspost/compress v1.17.2/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQs github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc= github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/microsoft/go-mssqldb v1.6.0 h1:mM3gYdVwEPFrlg/Dvr2DNVEgYFG7L42l+dGc67NNNpc= github.com/microsoft/go-mssqldb v1.6.0/go.mod h1:00mDtPbeQCRGC1HwOOR5K/gr30P1NcEG0vx6Kbv2aJU= github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8 h1:AMFGa4R4MiIpspGNG7Z948v4n35fFGB3RR3G/ry4FWs= github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8/go.mod h1:mC1jAcsrzbxHt8iiaC+zU4b1ylILSosueou12R++wfY= github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3 h1:+n/aFZefKZp7spd8DFdX7uMikMLXX4oubIzJF4kv/wI= github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3/go.mod h1:RagcQ7I8IeTMnF8JTXieKnO4Z6JCsikNEzj0DwauVzE= +github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= +github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= +github.com/moby/sys/user v0.3.0 h1:9ni5DlcW5an3SvRSx4MouotOygvzaXbaSrc/wGDFWPo= +github.com/moby/sys/user v0.3.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs= +github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= +github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs= github.com/mtibben/percent v0.2.1/go.mod h1:KG9uO+SZkUp+VkRHsCdYQV3XSZrrSpR3O9ibNBTZrns= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug= +github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM= +github.com/opencontainers/runc v1.2.3 h1:fxE7amCzfZflJO2lHXf4y/y8M1BoAqp+FVmG19oYB80= +github.com/opencontainers/runc v1.2.3/go.mod h1:nSxcWUydXrsBZVYNSkTjoQ/N6rcyTtn+1SD5D4+kRIM= +github.com/ory/dockertest/v3 v3.12.0 h1:3oV9d0sDzlSQfHtIaB5k6ghUCVMVLpAY8hwrqoCyRCw= +github.com/ory/dockertest/v3 v3.12.0/go.mod h1:aKNDTva3cp8dwOWwb9cWuX84aH5akkxXRvO7KCwWVjE= github.com/pierrec/lz4/v4 v4.1.18 h1:xaKrnTkyoqfh1YItXl56+6KJNVYWlEEPuAQW9xsplYQ= github.com/pierrec/lz4/v4 v4.1.18/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= github.com/sijms/go-ora/v2 v2.7.19 h1:+p0V51zrnpchRIIfx9kcEFGNUXkC0q9uZiyh05tyybI= github.com/sijms/go-ora/v2 v2.7.19/go.mod h1:EHxlY6x7y9HAsdfumurRfTd+v8NrEOTR3Xl4FWlH6xk= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= @@ -133,41 +209,89 @@ github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVs github.com/snowflakedb/gosnowflake v1.6.25 h1:o5zUmxTOo0Eo9AdkEj8blCeiMuILrQJ+rjUMAeZhcRE= github.com/snowflakedb/gosnowflake v1.6.25/go.mod h1:KfO4F7bk+aXPUIvBqYxvPhxLlu2/w4TtSC8Rw/yr5Mg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stripe/stripe-go/v82 v82.3.0 h1:6+E33xPmZ1Kzo2P/k90+Q5w2jwdKUU1XoEcrv3Fvtvk= +github.com/stripe/stripe-go/v82 v82.3.0/go.mod h1:majCQX6AfObAvJiHraPi/5udwHi4ojRvJnnxckvHrX8= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= +github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ= +github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= -golang.org/x/crypto v0.15.0 h1:frVn1TEaCEaZcn3Tmd7Y2b5KKPaZ+I32Q2OA3kYp5TA= -golang.org/x/crypto v0.15.0/go.mod h1:4ChreQoLWfG3xLDer1WdlH5NdlQ3+mwnQq1YTKY+72g= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= +golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= golang.org/x/exp v0.0.0-20231108232855-2478ac86f678 h1:mchzmB1XO2pMaKFRqk/+MV3mgGG96aqaPXaMifQU47w= golang.org/x/exp v0.0.0-20231108232855-2478ac86f678/go.mod h1:zk2irFbV9DP96SEBUUAy67IdHUaZuSnrz1n472HUCLE= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0= golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/net v0.18.0 h1:mIYleuAkSbHh0tCv7RvjL3F6ZVbLjq4+R7zbOn3Kokg= -golang.org/x/net v0.18.0/go.mod h1:/czyP5RqHAH4odGYxBJ1qz0+CE5WZ+2j1YgoEo8F2jQ= -golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE= -golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= +golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q= -golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.14.0 h1:LGK9IlZ8T9jvdy6cTdfKUCltatMFOehAQo9SRC46UQ8= -golang.org/x/term v0.14.0/go.mod h1:TySc+nGkYR6qt8km8wUhuFRTVSMIX3XPR58y2lC8vww= +golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= +golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.19.0 h1:+ThwsDv+tYfnJFhF4L8jITxu1tdTWRTZpdsWgEgjL6Q= +golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= +golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.15.0 h1:zdAyfUGbYmuVokhzVmghFl2ZJh5QhcfebBgmVPFYA+8= golang.org/x/tools v0.15.0/go.mod h1:hpksKq4dtpQWS1uQ61JkdqWM3LscIS6Slf+VVkm+wQk= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 h1:+cNy6SZtPcJQH3LJVLOSmiC7MMxXNOb3PU/VUEz+EhU= golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= gonum.org/v1/gonum v0.11.0 h1:f1IJhK4Km5tBJmaiJXtk/PkL4cdVX6J+tGiM187uT5E= +gonum.org/v1/gonum v0.11.0/go.mod h1:fSG4YDCxxUZQJ7rKsQrj0gMOg00Il0Z96/qMA4bVQhA= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU= +gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU= diff --git a/internal/vcs/vcs.go b/internal/vcs/vcs.go new file mode 100644 index 00000000..87910aba --- /dev/null +++ b/internal/vcs/vcs.go @@ -0,0 +1,14 @@ +package vcs + +import ( + "runtime/debug" +) + +func Version() string { + bi, ok := debug.ReadBuildInfo() + if ok { + return bi.Main.Version + } + + return "" +} diff --git a/postgresql.dockerfile b/postgresql.dockerfile new file mode 100644 index 00000000..2a29623e --- /dev/null +++ b/postgresql.dockerfile @@ -0,0 +1,6 @@ +FROM postgres:15 + +# Install wal2json (uses apt for Debian-based images) +RUN apt-get update \ + && apt-get install -y postgresql-15-wal2json \ + && rm -rf /var/lib/apt/lists/* diff --git a/streaming b/streaming new file mode 100755 index 00000000..fa6ae104 Binary files /dev/null and b/streaming differ diff --git a/streaming.dockerfile b/streaming.dockerfile new file mode 100644 index 00000000..ada98834 --- /dev/null +++ b/streaming.dockerfile @@ -0,0 +1,23 @@ +FROM debian:12 + +# Install required tools for HTTPS repositories and GPG +RUN apt-get update && apt-get install -y \ + ca-certificates \ + curl \ + gnupg + +RUN curl -s https://packages.stripe.dev/api/security/keypair/stripe-cli-gpg/public | gpg --dearmor | tee /usr/share/keyrings/stripe.gpg +RUN echo "deb [signed-by=/usr/share/keyrings/stripe.gpg] https://packages.stripe.dev/stripe-cli-debian-local stable main" | tee -a /etc/apt/sources.list.d/stripe.list + +RUN apt-get update +RUN apt-get install stripe -y + +RUN rm -rf /var/lib/apt/lists/* + +COPY /bin/streaming /bin/streaming +COPY entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh + +EXPOSE 4000 + +ENTRYPOINT ["/entrypoint.sh"] diff --git a/streaming.test b/streaming.test new file mode 100755 index 00000000..890b94de Binary files /dev/null and b/streaming.test differ diff --git a/setup-sql/mssql.sql b/test/setup-sql/mssql.sql similarity index 100% rename from setup-sql/mssql.sql rename to test/setup-sql/mssql.sql diff --git a/setup-sql/mysql.sql b/test/setup-sql/mysql.sql similarity index 100% rename from setup-sql/mysql.sql rename to test/setup-sql/mysql.sql diff --git a/setup-sql/oracle.sql b/test/setup-sql/oracle.sql similarity index 100% rename from setup-sql/oracle.sql rename to test/setup-sql/oracle.sql diff --git a/setup-sql/postgresql-complex.sql b/test/setup-sql/postgresql-complex.sql similarity index 100% rename from setup-sql/postgresql-complex.sql rename to test/setup-sql/postgresql-complex.sql diff --git a/setup-sql/postgresql-simple.sql b/test/setup-sql/postgresql-simple.sql similarity index 100% rename from setup-sql/postgresql-simple.sql rename to test/setup-sql/postgresql-simple.sql diff --git a/test/streaming/one_table_test.go b/test/streaming/one_table_test.go new file mode 100644 index 00000000..6f8dd2b3 --- /dev/null +++ b/test/streaming/one_table_test.go @@ -0,0 +1,267 @@ +package test + +import ( + "database/sql" + "fmt" + "log" + "net/http" + "os" + "os/exec" + "os/signal" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + _ "github.com/jackc/pgx/v5/stdlib" + "github.com/ory/dockertest/v3" + "github.com/ory/dockertest/v3/docker" +) + +func createPostgresqlProductsTable(t *testing.T, db *sql.DB) { + _, err := db.Exec(` + CREATE TABLE products ( + id bigserial PRIMARY KEY, + stripe_id TEXT UNIQUE, + name TEXT NOT NULL, + active BOOLEAN DEFAULT TRUE, + price int, + created TIMESTAMPTZ, + updated TIMESTAMPTZ, + description TEXT, + livemode BOOLEAN DEFAULT FALSE, + statement_descriptor TEXT, + unit_label TEXT, + category TEXT, + internal_notes TEXT + ); + `) + if err != nil { + t.Fatalf("Failed to create table: %v", err) + } +} + +func TestOneTableStreaming(t *testing.T) { + + pool, err := dockertest.NewPool("") + if err != nil { + t.Fatalf("Could not connect to docker: %s", err) + } + + pool.MaxWait = 20 * time.Second + + postgresqlPassword := "Mypass123" + postgresqlUsername := "postgres" + postgresqlDatabase := "postgres" + + // Resource handles for cleanup + var ( + network *dockertest.Network + postgresqlContainer *dockertest.Resource + sqlpipeContainer *dockertest.Resource + ) + + // Setup signal handler for cleanup with improved error handling + cleanup := func() { + // Helper to check for specific Docker errors + isAlreadyRemoving := func(err error) bool { + return err != nil && (strings.Contains(err.Error(), "removal of container") && strings.Contains(err.Error(), "is already in progress")) + } + isNetworkActive := func(err error) bool { + return err != nil && (strings.Contains(err.Error(), "network") && strings.Contains(err.Error(), "has active endpoints")) + } + + if sqlpipeContainer != nil { + if err := pool.Purge(sqlpipeContainer); err != nil && !isAlreadyRemoving(err) { + log.Printf("Could not purge sqlpipe resource: %s", err) + } + } + if postgresqlContainer != nil { + if err := pool.Purge(postgresqlContainer); err != nil && !isAlreadyRemoving(err) { + log.Printf("Could not purge resource: %s", err) + } + } + if network != nil { + // Retry network removal if it has active endpoints + for i := 0; i < 5; i++ { + if err := pool.RemoveNetwork(network); err != nil { + if isNetworkActive(err) { + time.Sleep(1 * time.Second) + continue + } + log.Printf("Could not remove docker network: %s", err) + break + } + break // success + } + } + } + + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, os.Interrupt) + go func() { + <-sigs + log.Println("Interrupt received, cleaning up Docker resources...") + cleanup() + os.Exit(1) + }() + + defer cleanup() + + // Create a network for both containers + network, err = pool.CreateNetwork("sqlpipe-test-network") + if err != nil { + t.Fatalf("Could not create docker network: %s", err) + } + + postgresqlContainer, err = pool.BuildAndRunWithOptions("../../postgresql.dockerfile", &dockertest.RunOptions{ + Name: "test-postgres", + Env: []string{ + fmt.Sprintf("POSTGRES_USER=%v", postgresqlUsername), + fmt.Sprintf("POSTGRES_PASSWORD=%v", postgresqlPassword), + fmt.Sprintf("POSTGRES_DB=%v", postgresqlDatabase), + }, + NetworkID: network.Network.ID, + ExposedPorts: []string{"5432/tcp"}, + PortBindings: map[docker.Port][]docker.PortBinding{ + "5432/tcp": {{HostIP: "0.0.0.0", HostPort: "5432"}}, + }, + Cmd: []string{ + "postgres", + "-c", "wal_level=logical", + "-c", "max_replication_slots=5", + "-c", "max_wal_senders=5", + "-c", "max_connections=100", + }, + }) + if err != nil { + t.Fatalf("Could not start resource: %s", err) + } + + var db *sql.DB + if err := pool.Retry(func() error { + var err error + port := postgresqlContainer.GetPort("5432/tcp") + dsn := fmt.Sprintf("postgres://%v:%v@localhost:%s/%v?sslmode=disable", postgresqlUsername, postgresqlPassword, port, postgresqlDatabase) + db, err = sql.Open("pgx", dsn) + if err != nil { + return err + } + return db.Ping() + }); err != nil { + t.Fatalf("Could not connect to database: %s", err) + } + + createPostgresqlProductsTable(t, db) + + _, err = db.Exec(`CREATE PUBLICATION my_pub FOR ALL TABLES;`) + if err != nil { + t.Fatalf("Failed to create publication: %v", err) + } + + buildCmd := exec.Command("go", []string{"build", "-o", "../../bin/streaming", "../../cmd/streaming"}...) + buildCmd.Env = append(os.Environ(), + "GOOS=linux", + fmt.Sprintf("GOARCH=%v", runtime.GOARCH), + "CGO_ENABLED=0", + ) + + // buildCmd.Stdout = os.Stdout + buildCmd.Stderr = os.Stderr + if err := buildCmd.Run(); err != nil { + t.Fatalf("Failed to build streaming app: %v", err) + } + + systemsHostDir, err := filepath.Abs("./config/one-table/systems") + if err != nil { + t.Fatalf("Failed to get absolute path for systems config: %v", err) + } + if _, err := os.Stat(systemsHostDir); os.IsNotExist(err) { + t.Fatalf("Systems config directory does not exist: %s", systemsHostDir) + } + + modelsHostDir, err := filepath.Abs("./config/one-table/models") + if err != nil { + t.Fatalf("Failed to get absolute path for models config: %v", err) + } + if _, err := os.Stat(modelsHostDir); os.IsNotExist(err) { + t.Fatalf("Models config directory does not exist: %s", modelsHostDir) + } + + sqlpipeContainer, err = pool.BuildAndRunWithOptions("../../streaming.dockerfile", &dockertest.RunOptions{ + Name: "sqlpipe-streaming", + Env: []string{ + "PORT=4000", + "SYSTEMS_DIR=/config/one-table/systems", + "MODELS_DIR=/config/one-table/models", + }, + Mounts: []string{ + fmt.Sprintf("%s:/config/one-table/systems", systemsHostDir), + fmt.Sprintf("%s:/config/one-table/models", modelsHostDir), + }, + NetworkID: network.Network.ID, + }) + if err != nil { + t.Fatalf("Could not start resource: %s", err) + } + + go func() { + pool.Client.Logs(docker.LogsOptions{ + Container: sqlpipeContainer.Container.ID, + OutputStream: os.Stdout, + ErrorStream: os.Stderr, + Follow: true, + Stdout: true, + Stderr: true, + }) + }() + + err = pool.Retry(func() error { + + inspect, err := pool.Client.InspectContainer(sqlpipeContainer.Container.ID) + if err != nil { + return fmt.Errorf("failed to inspect container: %w", err) + } + if !inspect.State.Running { + return fmt.Errorf("container exited with code: %d", inspect.State.ExitCode) + } + + hostPort := sqlpipeContainer.GetPort("4000/tcp") + healthcheckURL := fmt.Sprintf("http://localhost:%s/v1/healthcheck", hostPort) + + resp, err := http.Get(healthcheckURL) + if err != nil { + return fmt.Errorf("healthcheck error: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("healthcheck returned status %d", resp.StatusCode) + } + return nil // success! + }) + if err != nil { + t.Fatalf("SQLpipe healthcheck failed: %v", err) + } + + fmt.Println("SQLpipe is running and healthy!") + + // stripeCmd := exec.Command("stripe", "trigger", "price.created") + // stripeCmd := exec.Command("stripe", "trigger", "tax_rate.created") + + time.Sleep(1 * time.Second) + + stripeCmd := exec.Command("stripe", "trigger", "product.created") + stripeCmd.Stdout = os.Stdout + stripeCmd.Stderr = os.Stderr + fmt.Println("stripe api key: ", os.Getenv("STRIPE_API_KEY")) + stripeCmd.Env = append(os.Environ(), fmt.Sprintf("STRIPE_API_KEY=%s", os.Getenv("STRIPE_API_KEY"))) + err = stripeCmd.Run() + if err != nil { + t.Fatalf("Failed to run stripe trigger: %v", err) + } + + fmt.Println("Test is running. Press Ctrl+C to exit.") + select {} + +} diff --git a/test/streaming/two_tables_test.go b/test/streaming/two_tables_test.go new file mode 100644 index 00000000..ef2ac720 --- /dev/null +++ b/test/streaming/two_tables_test.go @@ -0,0 +1,274 @@ +package test + +import ( + "database/sql" + "fmt" + "log" + "net/http" + "os" + "os/exec" + "os/signal" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + _ "github.com/jackc/pgx/v5/stdlib" + "github.com/ory/dockertest/v3" + "github.com/ory/dockertest/v3/docker" +) + +func createPostgresqlProductsAndPricesTables(t *testing.T, db *sql.DB) { + _, err := db.Exec(` + CREATE TABLE products ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + default_price_id TEXT UNIQUE, + active BOOLEAN DEFAULT TRUE, + created TIMESTAMPTZ, + updated TIMESTAMPTZ, + description TEXT, + livemode BOOLEAN DEFAULT FALSE, + statement_descriptor TEXT, + unit_label TEXT, + category TEXT, + internal_notes TEXT + ); + `) + if err != nil { + t.Fatalf("Failed to create table: %v", err) + } + + _, err = db.Exec(` + CREATE TABLE prices ( + id text PRIMARY KEY, + product_id TEXT NOT NULL, + unit_amount INT NOT NULL, + currency TEXT NOT NULL + ); + `) + if err != nil { + t.Fatalf("Failed to create prices table: %v", err) + } +} + +func TestTwoTablesStreaming(t *testing.T) { + + pool, err := dockertest.NewPool("") + if err != nil { + t.Fatalf("Could not connect to docker: %s", err) + } + + pool.MaxWait = 20 * time.Second + + postgresqlPassword := "Mypass123" + postgresqlUsername := "postgres" + postgresqlDatabase := "postgres" + + // Resource handles for cleanup + var ( + network *dockertest.Network + postgresqlContainer *dockertest.Resource + sqlpipeContainer *dockertest.Resource + ) + + // Setup signal handler for cleanup with improved error handling + cleanup := func() { + // Helper to check for specific Docker errors + isAlreadyRemoving := func(err error) bool { + return err != nil && (strings.Contains(err.Error(), "removal of container") && strings.Contains(err.Error(), "is already in progress")) + } + isNetworkActive := func(err error) bool { + return err != nil && (strings.Contains(err.Error(), "network") && strings.Contains(err.Error(), "has active endpoints")) + } + + if sqlpipeContainer != nil { + if err := pool.Purge(sqlpipeContainer); err != nil && !isAlreadyRemoving(err) { + log.Printf("Could not purge sqlpipe resource: %s", err) + } + } + if postgresqlContainer != nil { + if err := pool.Purge(postgresqlContainer); err != nil && !isAlreadyRemoving(err) { + log.Printf("Could not purge resource: %s", err) + } + } + if network != nil { + // Retry network removal if it has active endpoints + for i := 0; i < 5; i++ { + if err := pool.RemoveNetwork(network); err != nil { + if isNetworkActive(err) { + time.Sleep(1 * time.Second) + continue + } + log.Printf("Could not remove docker network: %s", err) + break + } + break // success + } + } + } + + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, os.Interrupt) + go func() { + <-sigs + log.Println("Interrupt received, cleaning up Docker resources...") + cleanup() + os.Exit(1) + }() + + defer cleanup() + + // Create a network for both containers + network, err = pool.CreateNetwork("sqlpipe-test-network") + if err != nil { + t.Fatalf("Could not create docker network: %s", err) + } + + postgresqlContainer, err = pool.BuildAndRunWithOptions("../../postgresql.dockerfile", &dockertest.RunOptions{ + Name: "test-postgres", + Env: []string{ + fmt.Sprintf("POSTGRES_USER=%v", postgresqlUsername), + fmt.Sprintf("POSTGRES_PASSWORD=%v", postgresqlPassword), + fmt.Sprintf("POSTGRES_DB=%v", postgresqlDatabase), + }, + NetworkID: network.Network.ID, + ExposedPorts: []string{"5432/tcp"}, + PortBindings: map[docker.Port][]docker.PortBinding{ + "5432/tcp": {{HostIP: "0.0.0.0", HostPort: "5432"}}, + }, + Cmd: []string{ + "postgres", + "-c", "wal_level=logical", + "-c", "max_replication_slots=5", + "-c", "max_wal_senders=5", + "-c", "max_connections=100", + }, + }) + if err != nil { + t.Fatalf("Could not start resource: %s", err) + } + + var db *sql.DB + if err := pool.Retry(func() error { + var err error + port := postgresqlContainer.GetPort("5432/tcp") + dsn := fmt.Sprintf("postgres://%v:%v@localhost:%s/%v?sslmode=disable", postgresqlUsername, postgresqlPassword, port, postgresqlDatabase) + db, err = sql.Open("pgx", dsn) + if err != nil { + return err + } + return db.Ping() + }); err != nil { + t.Fatalf("Could not connect to database: %s", err) + } + + createPostgresqlProductsAndPricesTables(t, db) + + _, err = db.Exec(`CREATE PUBLICATION my_pub FOR ALL TABLES;`) + if err != nil { + t.Fatalf("Failed to create publication: %v", err) + } + + buildCmd := exec.Command("go", []string{"build", "-o", "../../bin/streaming", "../../cmd/streaming"}...) + buildCmd.Env = append(os.Environ(), + "GOOS=linux", + fmt.Sprintf("GOARCH=%v", runtime.GOARCH), + "CGO_ENABLED=0", + ) + + // buildCmd.Stdout = os.Stdout + buildCmd.Stderr = os.Stderr + if err := buildCmd.Run(); err != nil { + t.Fatalf("Failed to build streaming app: %v", err) + } + + systemsHostDir, err := filepath.Abs("./config/two-tables/systems") + if err != nil { + t.Fatalf("Failed to get absolute path for systems config: %v", err) + } + if _, err := os.Stat(systemsHostDir); os.IsNotExist(err) { + t.Fatalf("Systems config directory does not exist: %s", systemsHostDir) + } + + modelsHostDir, err := filepath.Abs("./config/two-tables/models") + if err != nil { + t.Fatalf("Failed to get absolute path for models config: %v", err) + } + if _, err := os.Stat(modelsHostDir); os.IsNotExist(err) { + t.Fatalf("Models config directory does not exist: %s", modelsHostDir) + } + + sqlpipeContainer, err = pool.BuildAndRunWithOptions("../../streaming.dockerfile", &dockertest.RunOptions{ + Name: "sqlpipe-streaming", + Env: []string{ + "PORT=4000", + "SYSTEMS_DIR=/config/two-tables/systems", + "MODELS_DIR=/config/two-tables/models", + }, + Mounts: []string{ + fmt.Sprintf("%s:/config/two-tables/systems", systemsHostDir), + fmt.Sprintf("%s:/config/two-tables/models", modelsHostDir), + }, + NetworkID: network.Network.ID, + }) + if err != nil { + t.Fatalf("Could not start resource: %s", err) + } + + go func() { + pool.Client.Logs(docker.LogsOptions{ + Container: sqlpipeContainer.Container.ID, + OutputStream: os.Stdout, + ErrorStream: os.Stderr, + Follow: true, + Stdout: true, + Stderr: true, + }) + }() + + err = pool.Retry(func() error { + + inspect, err := pool.Client.InspectContainer(sqlpipeContainer.Container.ID) + if err != nil { + return fmt.Errorf("failed to inspect container: %w", err) + } + if !inspect.State.Running { + return fmt.Errorf("container exited with code: %d", inspect.State.ExitCode) + } + + hostPort := sqlpipeContainer.GetPort("4000/tcp") + healthcheckURL := fmt.Sprintf("http://localhost:%s/v1/healthcheck", hostPort) + + resp, err := http.Get(healthcheckURL) + if err != nil { + return fmt.Errorf("healthcheck error: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("healthcheck returned status %d", resp.StatusCode) + } + return nil // success! + }) + if err != nil { + t.Fatalf("SQLpipe healthcheck failed: %v", err) + } + + fmt.Println("SQLpipe is running and healthy!") + + time.Sleep(1 * time.Second) + + stripeCmd := exec.Command("stripe", "trigger", "product.created") + stripeCmd.Stdout = os.Stdout + stripeCmd.Stderr = os.Stderr + fmt.Println("stripe api key: ", os.Getenv("STRIPE_API_KEY")) + stripeCmd.Env = append(os.Environ(), fmt.Sprintf("STRIPE_API_KEY=%s", os.Getenv("STRIPE_API_KEY"))) + err = stripeCmd.Run() + if err != nil { + t.Fatalf("Failed to run stripe trigger: %v", err) + } + + fmt.Println("Test is running. Press Ctrl+C to exit.") + select {} +} diff --git a/vendor/dario.cat/mergo/.deepsource.toml b/vendor/dario.cat/mergo/.deepsource.toml new file mode 100644 index 00000000..a8bc979e --- /dev/null +++ b/vendor/dario.cat/mergo/.deepsource.toml @@ -0,0 +1,12 @@ +version = 1 + +test_patterns = [ + "*_test.go" +] + +[[analyzers]] +name = "go" +enabled = true + + [analyzers.meta] + import_path = "dario.cat/mergo" \ No newline at end of file diff --git a/vendor/dario.cat/mergo/.gitignore b/vendor/dario.cat/mergo/.gitignore new file mode 100644 index 00000000..529c3412 --- /dev/null +++ b/vendor/dario.cat/mergo/.gitignore @@ -0,0 +1,33 @@ +#### joe made this: http://goel.io/joe + +#### go #### +# Binaries for programs and plugins +*.exe +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 +.glide/ + +#### vim #### +# Swap +[._]*.s[a-v][a-z] +[._]*.sw[a-p] +[._]s[a-v][a-z] +[._]sw[a-p] + +# Session +Session.vim + +# Temporary +.netrwhist +*~ +# Auto-generated tag files +tags diff --git a/vendor/dario.cat/mergo/.travis.yml b/vendor/dario.cat/mergo/.travis.yml new file mode 100644 index 00000000..d324c43b --- /dev/null +++ b/vendor/dario.cat/mergo/.travis.yml @@ -0,0 +1,12 @@ +language: go +arch: + - amd64 + - ppc64le +install: + - go get -t + - go get golang.org/x/tools/cmd/cover + - go get github.com/mattn/goveralls +script: + - go test -race -v ./... +after_script: + - $HOME/gopath/bin/goveralls -service=travis-ci -repotoken $COVERALLS_TOKEN diff --git a/vendor/dario.cat/mergo/CODE_OF_CONDUCT.md b/vendor/dario.cat/mergo/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..469b4490 --- /dev/null +++ b/vendor/dario.cat/mergo/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at i@dario.im. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/dario.cat/mergo/CONTRIBUTING.md b/vendor/dario.cat/mergo/CONTRIBUTING.md new file mode 100644 index 00000000..0a1ff9f9 --- /dev/null +++ b/vendor/dario.cat/mergo/CONTRIBUTING.md @@ -0,0 +1,112 @@ + +# Contributing to mergo + +First off, thanks for taking the time to contribute! ❤️ + +All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉 + +> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about: +> - Star the project +> - Tweet about it +> - Refer this project in your project's readme +> - Mention the project at local meetups and tell your friends/colleagues + + +## Table of Contents + +- [Code of Conduct](#code-of-conduct) +- [I Have a Question](#i-have-a-question) +- [I Want To Contribute](#i-want-to-contribute) +- [Reporting Bugs](#reporting-bugs) +- [Suggesting Enhancements](#suggesting-enhancements) + +## Code of Conduct + +This project and everyone participating in it is governed by the +[mergo Code of Conduct](https://github.com/imdario/mergoblob/master/CODE_OF_CONDUCT.md). +By participating, you are expected to uphold this code. Please report unacceptable behavior +to <>. + + +## I Have a Question + +> If you want to ask a question, we assume that you have read the available [Documentation](https://pkg.go.dev/github.com/imdario/mergo). + +Before you ask a question, it is best to search for existing [Issues](https://github.com/imdario/mergo/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first. + +If you then still feel the need to ask a question and need clarification, we recommend the following: + +- Open an [Issue](https://github.com/imdario/mergo/issues/new). +- Provide as much context as you can about what you're running into. +- Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. + +We will then take care of the issue as soon as possible. + +## I Want To Contribute + +> ### Legal Notice +> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license. + +### Reporting Bugs + + +#### Before Submitting a Bug Report + +A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible. + +- Make sure that you are using the latest version. +- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](). If you are looking for support, you might want to check [this section](#i-have-a-question)). +- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/imdario/mergoissues?q=label%3Abug). +- Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue. +- Collect information about the bug: +- Stack trace (Traceback) +- OS, Platform and Version (Windows, Linux, macOS, x86, ARM) +- Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant. +- Possibly your input and the output +- Can you reliably reproduce the issue? And can you also reproduce it with older versions? + + +#### How Do I Submit a Good Bug Report? + +> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to . + + +We use GitHub issues to track bugs and errors. If you run into an issue with the project: + +- Open an [Issue](https://github.com/imdario/mergo/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.) +- Explain the behavior you would expect and the actual behavior. +- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case. +- Provide the information you collected in the previous section. + +Once it's filed: + +- The project team will label the issue accordingly. +- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced. +- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be implemented by someone. + +### Suggesting Enhancements + +This section guides you through submitting an enhancement suggestion for mergo, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions. + + +#### Before Submitting an Enhancement + +- Make sure that you are using the latest version. +- Read the [documentation]() carefully and find out if the functionality is already covered, maybe by an individual configuration. +- Perform a [search](https://github.com/imdario/mergo/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. +- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library. + + +#### How Do I Submit a Good Enhancement Suggestion? + +Enhancement suggestions are tracked as [GitHub issues](https://github.com/imdario/mergo/issues). + +- Use a **clear and descriptive title** for the issue to identify the suggestion. +- Provide a **step-by-step description of the suggested enhancement** in as many details as possible. +- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you. +- You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. +- **Explain why this enhancement would be useful** to most mergo users. You may also want to point out the other projects that solved it better and which could serve as inspiration. + + +## Attribution +This guide is based on the **contributing-gen**. [Make your own](https://github.com/bttger/contributing-gen)! diff --git a/vendor/dario.cat/mergo/LICENSE b/vendor/dario.cat/mergo/LICENSE new file mode 100644 index 00000000..68668029 --- /dev/null +++ b/vendor/dario.cat/mergo/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2013 Dario Castañé. All rights reserved. +Copyright (c) 2012 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/dario.cat/mergo/README.md b/vendor/dario.cat/mergo/README.md new file mode 100644 index 00000000..7d0cf9f3 --- /dev/null +++ b/vendor/dario.cat/mergo/README.md @@ -0,0 +1,248 @@ +# Mergo + +[![GitHub release][5]][6] +[![GoCard][7]][8] +[![Test status][1]][2] +[![OpenSSF Scorecard][21]][22] +[![OpenSSF Best Practices][19]][20] +[![Coverage status][9]][10] +[![Sourcegraph][11]][12] +[![FOSSA status][13]][14] + +[![GoDoc][3]][4] +[![Become my sponsor][15]][16] +[![Tidelift][17]][18] + +[1]: https://github.com/imdario/mergo/workflows/tests/badge.svg?branch=master +[2]: https://github.com/imdario/mergo/actions/workflows/tests.yml +[3]: https://godoc.org/github.com/imdario/mergo?status.svg +[4]: https://godoc.org/github.com/imdario/mergo +[5]: https://img.shields.io/github/release/imdario/mergo.svg +[6]: https://github.com/imdario/mergo/releases +[7]: https://goreportcard.com/badge/imdario/mergo +[8]: https://goreportcard.com/report/github.com/imdario/mergo +[9]: https://coveralls.io/repos/github/imdario/mergo/badge.svg?branch=master +[10]: https://coveralls.io/github/imdario/mergo?branch=master +[11]: https://sourcegraph.com/github.com/imdario/mergo/-/badge.svg +[12]: https://sourcegraph.com/github.com/imdario/mergo?badge +[13]: https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimdario%2Fmergo.svg?type=shield +[14]: https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_shield +[15]: https://img.shields.io/github/sponsors/imdario +[16]: https://github.com/sponsors/imdario +[17]: https://tidelift.com/badges/package/go/github.com%2Fimdario%2Fmergo +[18]: https://tidelift.com/subscription/pkg/go-github.com-imdario-mergo +[19]: https://bestpractices.coreinfrastructure.org/projects/7177/badge +[20]: https://bestpractices.coreinfrastructure.org/projects/7177 +[21]: https://api.securityscorecards.dev/projects/github.com/imdario/mergo/badge +[22]: https://api.securityscorecards.dev/projects/github.com/imdario/mergo + +A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. + +Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection). + +Also a lovely [comune](http://en.wikipedia.org/wiki/Mergo) (municipality) in the Province of Ancona in the Italian region of Marche. + +## Status + +It is ready for production use. [It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, Microsoft, etc](https://github.com/imdario/mergo#mergo-in-the-wild). + +### Important notes + +#### 1.0.0 + +In [1.0.0](//github.com/imdario/mergo/releases/tag/1.0.0) Mergo moves to a vanity URL `dario.cat/mergo`. + +#### 0.3.9 + +Please keep in mind that a problematic PR broke [0.3.9](//github.com/imdario/mergo/releases/tag/0.3.9). I reverted it in [0.3.10](//github.com/imdario/mergo/releases/tag/0.3.10), and I consider it stable but not bug-free. Also, this version adds support for go modules. + +Keep in mind that in [0.3.2](//github.com/imdario/mergo/releases/tag/0.3.2), Mergo changed `Merge()`and `Map()` signatures to support [transformers](#transformers). I added an optional/variadic argument so that it won't break the existing code. + +If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with ```go get -u dario.cat/mergo```. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0). + +### Donations + +If Mergo is useful to you, consider buying me a coffee, a beer, or making a monthly donation to allow me to keep building great free software. :heart_eyes: + +Buy Me a Coffee at ko-fi.com +Donate using Liberapay +Become my sponsor + +### Mergo in the wild + +- [moby/moby](https://github.com/moby/moby) +- [kubernetes/kubernetes](https://github.com/kubernetes/kubernetes) +- [vmware/dispatch](https://github.com/vmware/dispatch) +- [Shopify/themekit](https://github.com/Shopify/themekit) +- [imdario/zas](https://github.com/imdario/zas) +- [matcornic/hermes](https://github.com/matcornic/hermes) +- [OpenBazaar/openbazaar-go](https://github.com/OpenBazaar/openbazaar-go) +- [kataras/iris](https://github.com/kataras/iris) +- [michaelsauter/crane](https://github.com/michaelsauter/crane) +- [go-task/task](https://github.com/go-task/task) +- [sensu/uchiwa](https://github.com/sensu/uchiwa) +- [ory/hydra](https://github.com/ory/hydra) +- [sisatech/vcli](https://github.com/sisatech/vcli) +- [dairycart/dairycart](https://github.com/dairycart/dairycart) +- [projectcalico/felix](https://github.com/projectcalico/felix) +- [resin-os/balena](https://github.com/resin-os/balena) +- [go-kivik/kivik](https://github.com/go-kivik/kivik) +- [Telefonica/govice](https://github.com/Telefonica/govice) +- [supergiant/supergiant](supergiant/supergiant) +- [SergeyTsalkov/brooce](https://github.com/SergeyTsalkov/brooce) +- [soniah/dnsmadeeasy](https://github.com/soniah/dnsmadeeasy) +- [ohsu-comp-bio/funnel](https://github.com/ohsu-comp-bio/funnel) +- [EagerIO/Stout](https://github.com/EagerIO/Stout) +- [lynndylanhurley/defsynth-api](https://github.com/lynndylanhurley/defsynth-api) +- [russross/canvasassignments](https://github.com/russross/canvasassignments) +- [rdegges/cryptly-api](https://github.com/rdegges/cryptly-api) +- [casualjim/exeggutor](https://github.com/casualjim/exeggutor) +- [divshot/gitling](https://github.com/divshot/gitling) +- [RWJMurphy/gorl](https://github.com/RWJMurphy/gorl) +- [andrerocker/deploy42](https://github.com/andrerocker/deploy42) +- [elwinar/rambler](https://github.com/elwinar/rambler) +- [tmaiaroto/gopartman](https://github.com/tmaiaroto/gopartman) +- [jfbus/impressionist](https://github.com/jfbus/impressionist) +- [Jmeyering/zealot](https://github.com/Jmeyering/zealot) +- [godep-migrator/rigger-host](https://github.com/godep-migrator/rigger-host) +- [Dronevery/MultiwaySwitch-Go](https://github.com/Dronevery/MultiwaySwitch-Go) +- [thoas/picfit](https://github.com/thoas/picfit) +- [mantasmatelis/whooplist-server](https://github.com/mantasmatelis/whooplist-server) +- [jnuthong/item_search](https://github.com/jnuthong/item_search) +- [bukalapak/snowboard](https://github.com/bukalapak/snowboard) +- [containerssh/containerssh](https://github.com/containerssh/containerssh) +- [goreleaser/goreleaser](https://github.com/goreleaser/goreleaser) +- [tjpnz/structbot](https://github.com/tjpnz/structbot) + +## Install + + go get dario.cat/mergo + + // use in your .go code + import ( + "dario.cat/mergo" + ) + +## Usage + +You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as [they are zero values](https://golang.org/ref/spec#The_zero_value) too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection). + +```go +if err := mergo.Merge(&dst, src); err != nil { + // ... +} +``` + +Also, you can merge overwriting values using the transformer `WithOverride`. + +```go +if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil { + // ... +} +``` + +Additionally, you can map a `map[string]interface{}` to a struct (and otherwise, from struct to map), following the same restrictions as in `Merge()`. Keys are capitalized to find each corresponding exported field. + +```go +if err := mergo.Map(&dst, srcMap); err != nil { + // ... +} +``` + +Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as `map[string]interface{}`. They will be just assigned as values. + +Here is a nice example: + +```go +package main + +import ( + "fmt" + "dario.cat/mergo" +) + +type Foo struct { + A string + B int64 +} + +func main() { + src := Foo{ + A: "one", + B: 2, + } + dest := Foo{ + A: "two", + } + mergo.Merge(&dest, src) + fmt.Println(dest) + // Will print + // {two 2} +} +``` + +Note: if test are failing due missing package, please execute: + + go get gopkg.in/yaml.v3 + +### Transformers + +Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, `time.Time` is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero `time.Time`? + +```go +package main + +import ( + "fmt" + "dario.cat/mergo" + "reflect" + "time" +) + +type timeTransformer struct { +} + +func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error { + if typ == reflect.TypeOf(time.Time{}) { + return func(dst, src reflect.Value) error { + if dst.CanSet() { + isZero := dst.MethodByName("IsZero") + result := isZero.Call([]reflect.Value{}) + if result[0].Bool() { + dst.Set(src) + } + } + return nil + } + } + return nil +} + +type Snapshot struct { + Time time.Time + // ... +} + +func main() { + src := Snapshot{time.Now()} + dest := Snapshot{} + mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{})) + fmt.Println(dest) + // Will print + // { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 } +} +``` + +## Contact me + +If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): [@im_dario](https://twitter.com/im_dario) + +## About + +Written by [Dario Castañé](http://dario.im). + +## License + +[BSD 3-Clause](http://opensource.org/licenses/BSD-3-Clause) license, as [Go language](http://golang.org/LICENSE). + +[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimdario%2Fmergo.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_large) diff --git a/vendor/dario.cat/mergo/SECURITY.md b/vendor/dario.cat/mergo/SECURITY.md new file mode 100644 index 00000000..a5de61f7 --- /dev/null +++ b/vendor/dario.cat/mergo/SECURITY.md @@ -0,0 +1,14 @@ +# Security Policy + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.3.x | :white_check_mark: | +| < 0.3 | :x: | + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff --git a/vendor/dario.cat/mergo/doc.go b/vendor/dario.cat/mergo/doc.go new file mode 100644 index 00000000..7d96ec05 --- /dev/null +++ b/vendor/dario.cat/mergo/doc.go @@ -0,0 +1,148 @@ +// Copyright 2013 Dario Castañé. All rights reserved. +// Copyright 2009 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. + +/* +A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. + +Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection). + +# Status + +It is ready for production use. It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, etc. + +# Important notes + +1.0.0 + +In 1.0.0 Mergo moves to a vanity URL `dario.cat/mergo`. + +0.3.9 + +Please keep in mind that a problematic PR broke 0.3.9. We reverted it in 0.3.10. We consider 0.3.10 as stable but not bug-free. . Also, this version adds suppot for go modules. + +Keep in mind that in 0.3.2, Mergo changed Merge() and Map() signatures to support transformers. We added an optional/variadic argument so that it won't break the existing code. + +If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with go get -u dario.cat/mergo. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0). + +# Install + +Do your usual installation procedure: + + go get dario.cat/mergo + + // use in your .go code + import ( + "dario.cat/mergo" + ) + +# Usage + +You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as they are zero values too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection). + + if err := mergo.Merge(&dst, src); err != nil { + // ... + } + +Also, you can merge overwriting values using the transformer WithOverride. + + if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil { + // ... + } + +Additionally, you can map a map[string]interface{} to a struct (and otherwise, from struct to map), following the same restrictions as in Merge(). Keys are capitalized to find each corresponding exported field. + + if err := mergo.Map(&dst, srcMap); err != nil { + // ... + } + +Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as map[string]interface{}. They will be just assigned as values. + +Here is a nice example: + + package main + + import ( + "fmt" + "dario.cat/mergo" + ) + + type Foo struct { + A string + B int64 + } + + func main() { + src := Foo{ + A: "one", + B: 2, + } + dest := Foo{ + A: "two", + } + mergo.Merge(&dest, src) + fmt.Println(dest) + // Will print + // {two 2} + } + +# Transformers + +Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, time.Time is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero time.Time? + + package main + + import ( + "fmt" + "dario.cat/mergo" + "reflect" + "time" + ) + + type timeTransformer struct { + } + + func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error { + if typ == reflect.TypeOf(time.Time{}) { + return func(dst, src reflect.Value) error { + if dst.CanSet() { + isZero := dst.MethodByName("IsZero") + result := isZero.Call([]reflect.Value{}) + if result[0].Bool() { + dst.Set(src) + } + } + return nil + } + } + return nil + } + + type Snapshot struct { + Time time.Time + // ... + } + + func main() { + src := Snapshot{time.Now()} + dest := Snapshot{} + mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{})) + fmt.Println(dest) + // Will print + // { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 } + } + +# Contact me + +If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): https://twitter.com/im_dario + +# About + +Written by Dario Castañé: https://da.rio.hn + +# License + +BSD 3-Clause license, as Go language. +*/ +package mergo diff --git a/vendor/dario.cat/mergo/map.go b/vendor/dario.cat/mergo/map.go new file mode 100644 index 00000000..b50d5c2a --- /dev/null +++ b/vendor/dario.cat/mergo/map.go @@ -0,0 +1,178 @@ +// Copyright 2014 Dario Castañé. All rights reserved. +// Copyright 2009 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. + +// Based on src/pkg/reflect/deepequal.go from official +// golang's stdlib. + +package mergo + +import ( + "fmt" + "reflect" + "unicode" + "unicode/utf8" +) + +func changeInitialCase(s string, mapper func(rune) rune) string { + if s == "" { + return s + } + r, n := utf8.DecodeRuneInString(s) + return string(mapper(r)) + s[n:] +} + +func isExported(field reflect.StructField) bool { + r, _ := utf8.DecodeRuneInString(field.Name) + return r >= 'A' && r <= 'Z' +} + +// Traverses recursively both values, assigning src's fields values to dst. +// The map argument tracks comparisons that have already been seen, which allows +// short circuiting on recursive types. +func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) { + overwrite := config.Overwrite + if dst.CanAddr() { + addr := dst.UnsafeAddr() + h := 17 * addr + seen := visited[h] + typ := dst.Type() + for p := seen; p != nil; p = p.next { + if p.ptr == addr && p.typ == typ { + return nil + } + } + // Remember, remember... + visited[h] = &visit{typ, seen, addr} + } + zeroValue := reflect.Value{} + switch dst.Kind() { + case reflect.Map: + dstMap := dst.Interface().(map[string]interface{}) + for i, n := 0, src.NumField(); i < n; i++ { + srcType := src.Type() + field := srcType.Field(i) + if !isExported(field) { + continue + } + fieldName := field.Name + fieldName = changeInitialCase(fieldName, unicode.ToLower) + if v, ok := dstMap[fieldName]; !ok || (isEmptyValue(reflect.ValueOf(v), !config.ShouldNotDereference) || overwrite) { + dstMap[fieldName] = src.Field(i).Interface() + } + } + case reflect.Ptr: + if dst.IsNil() { + v := reflect.New(dst.Type().Elem()) + dst.Set(v) + } + dst = dst.Elem() + fallthrough + case reflect.Struct: + srcMap := src.Interface().(map[string]interface{}) + for key := range srcMap { + config.overwriteWithEmptyValue = true + srcValue := srcMap[key] + fieldName := changeInitialCase(key, unicode.ToUpper) + dstElement := dst.FieldByName(fieldName) + if dstElement == zeroValue { + // We discard it because the field doesn't exist. + continue + } + srcElement := reflect.ValueOf(srcValue) + dstKind := dstElement.Kind() + srcKind := srcElement.Kind() + if srcKind == reflect.Ptr && dstKind != reflect.Ptr { + srcElement = srcElement.Elem() + srcKind = reflect.TypeOf(srcElement.Interface()).Kind() + } else if dstKind == reflect.Ptr { + // Can this work? I guess it can't. + if srcKind != reflect.Ptr && srcElement.CanAddr() { + srcPtr := srcElement.Addr() + srcElement = reflect.ValueOf(srcPtr) + srcKind = reflect.Ptr + } + } + + if !srcElement.IsValid() { + continue + } + if srcKind == dstKind { + if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { + return + } + } else if dstKind == reflect.Interface && dstElement.Kind() == reflect.Interface { + if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { + return + } + } else if srcKind == reflect.Map { + if err = deepMap(dstElement, srcElement, visited, depth+1, config); err != nil { + return + } + } else { + return fmt.Errorf("type mismatch on %s field: found %v, expected %v", fieldName, srcKind, dstKind) + } + } + } + return +} + +// Map sets fields' values in dst from src. +// src can be a map with string keys or a struct. dst must be the opposite: +// if src is a map, dst must be a valid pointer to struct. If src is a struct, +// dst must be map[string]interface{}. +// It won't merge unexported (private) fields and will do recursively +// any exported field. +// If dst is a map, keys will be src fields' names in lower camel case. +// Missing key in src that doesn't match a field in dst will be skipped. This +// doesn't apply if dst is a map. +// This is separated method from Merge because it is cleaner and it keeps sane +// semantics: merging equal types, mapping different (restricted) types. +func Map(dst, src interface{}, opts ...func(*Config)) error { + return _map(dst, src, opts...) +} + +// MapWithOverwrite will do the same as Map except that non-empty dst attributes will be overridden by +// non-empty src attribute values. +// Deprecated: Use Map(…) with WithOverride +func MapWithOverwrite(dst, src interface{}, opts ...func(*Config)) error { + return _map(dst, src, append(opts, WithOverride)...) +} + +func _map(dst, src interface{}, opts ...func(*Config)) error { + if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr { + return ErrNonPointerArgument + } + var ( + vDst, vSrc reflect.Value + err error + ) + config := &Config{} + + for _, opt := range opts { + opt(config) + } + + if vDst, vSrc, err = resolveValues(dst, src); err != nil { + return err + } + // To be friction-less, we redirect equal-type arguments + // to deepMerge. Only because arguments can be anything. + if vSrc.Kind() == vDst.Kind() { + return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) + } + switch vSrc.Kind() { + case reflect.Struct: + if vDst.Kind() != reflect.Map { + return ErrExpectedMapAsDestination + } + case reflect.Map: + if vDst.Kind() != reflect.Struct { + return ErrExpectedStructAsDestination + } + default: + return ErrNotSupported + } + return deepMap(vDst, vSrc, make(map[uintptr]*visit), 0, config) +} diff --git a/vendor/dario.cat/mergo/merge.go b/vendor/dario.cat/mergo/merge.go new file mode 100644 index 00000000..0ef9b213 --- /dev/null +++ b/vendor/dario.cat/mergo/merge.go @@ -0,0 +1,409 @@ +// Copyright 2013 Dario Castañé. All rights reserved. +// Copyright 2009 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. + +// Based on src/pkg/reflect/deepequal.go from official +// golang's stdlib. + +package mergo + +import ( + "fmt" + "reflect" +) + +func hasMergeableFields(dst reflect.Value) (exported bool) { + for i, n := 0, dst.NumField(); i < n; i++ { + field := dst.Type().Field(i) + if field.Anonymous && dst.Field(i).Kind() == reflect.Struct { + exported = exported || hasMergeableFields(dst.Field(i)) + } else if isExportedComponent(&field) { + exported = exported || len(field.PkgPath) == 0 + } + } + return +} + +func isExportedComponent(field *reflect.StructField) bool { + pkgPath := field.PkgPath + if len(pkgPath) > 0 { + return false + } + c := field.Name[0] + if 'a' <= c && c <= 'z' || c == '_' { + return false + } + return true +} + +type Config struct { + Transformers Transformers + Overwrite bool + ShouldNotDereference bool + AppendSlice bool + TypeCheck bool + overwriteWithEmptyValue bool + overwriteSliceWithEmptyValue bool + sliceDeepCopy bool + debug bool +} + +type Transformers interface { + Transformer(reflect.Type) func(dst, src reflect.Value) error +} + +// Traverses recursively both values, assigning src's fields values to dst. +// The map argument tracks comparisons that have already been seen, which allows +// short circuiting on recursive types. +func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) { + overwrite := config.Overwrite + typeCheck := config.TypeCheck + overwriteWithEmptySrc := config.overwriteWithEmptyValue + overwriteSliceWithEmptySrc := config.overwriteSliceWithEmptyValue + sliceDeepCopy := config.sliceDeepCopy + + if !src.IsValid() { + return + } + if dst.CanAddr() { + addr := dst.UnsafeAddr() + h := 17 * addr + seen := visited[h] + typ := dst.Type() + for p := seen; p != nil; p = p.next { + if p.ptr == addr && p.typ == typ { + return nil + } + } + // Remember, remember... + visited[h] = &visit{typ, seen, addr} + } + + if config.Transformers != nil && !isReflectNil(dst) && dst.IsValid() { + if fn := config.Transformers.Transformer(dst.Type()); fn != nil { + err = fn(dst, src) + return + } + } + + switch dst.Kind() { + case reflect.Struct: + if hasMergeableFields(dst) { + for i, n := 0, dst.NumField(); i < n; i++ { + if err = deepMerge(dst.Field(i), src.Field(i), visited, depth+1, config); err != nil { + return + } + } + } else { + if dst.CanSet() && (isReflectNil(dst) || overwrite) && (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc) { + dst.Set(src) + } + } + case reflect.Map: + if dst.IsNil() && !src.IsNil() { + if dst.CanSet() { + dst.Set(reflect.MakeMap(dst.Type())) + } else { + dst = src + return + } + } + + if src.Kind() != reflect.Map { + if overwrite && dst.CanSet() { + dst.Set(src) + } + return + } + + for _, key := range src.MapKeys() { + srcElement := src.MapIndex(key) + if !srcElement.IsValid() { + continue + } + dstElement := dst.MapIndex(key) + switch srcElement.Kind() { + case reflect.Chan, reflect.Func, reflect.Map, reflect.Interface, reflect.Slice: + if srcElement.IsNil() { + if overwrite { + dst.SetMapIndex(key, srcElement) + } + continue + } + fallthrough + default: + if !srcElement.CanInterface() { + continue + } + switch reflect.TypeOf(srcElement.Interface()).Kind() { + case reflect.Struct: + fallthrough + case reflect.Ptr: + fallthrough + case reflect.Map: + srcMapElm := srcElement + dstMapElm := dstElement + if srcMapElm.CanInterface() { + srcMapElm = reflect.ValueOf(srcMapElm.Interface()) + if dstMapElm.IsValid() { + dstMapElm = reflect.ValueOf(dstMapElm.Interface()) + } + } + if err = deepMerge(dstMapElm, srcMapElm, visited, depth+1, config); err != nil { + return + } + case reflect.Slice: + srcSlice := reflect.ValueOf(srcElement.Interface()) + + var dstSlice reflect.Value + if !dstElement.IsValid() || dstElement.IsNil() { + dstSlice = reflect.MakeSlice(srcSlice.Type(), 0, srcSlice.Len()) + } else { + dstSlice = reflect.ValueOf(dstElement.Interface()) + } + + if (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) && !config.AppendSlice && !sliceDeepCopy { + if typeCheck && srcSlice.Type() != dstSlice.Type() { + return fmt.Errorf("cannot override two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type()) + } + dstSlice = srcSlice + } else if config.AppendSlice { + if srcSlice.Type() != dstSlice.Type() { + return fmt.Errorf("cannot append two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type()) + } + dstSlice = reflect.AppendSlice(dstSlice, srcSlice) + } else if sliceDeepCopy { + i := 0 + for ; i < srcSlice.Len() && i < dstSlice.Len(); i++ { + srcElement := srcSlice.Index(i) + dstElement := dstSlice.Index(i) + + if srcElement.CanInterface() { + srcElement = reflect.ValueOf(srcElement.Interface()) + } + if dstElement.CanInterface() { + dstElement = reflect.ValueOf(dstElement.Interface()) + } + + if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { + return + } + } + + } + dst.SetMapIndex(key, dstSlice) + } + } + + if dstElement.IsValid() && !isEmptyValue(dstElement, !config.ShouldNotDereference) { + if reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Slice { + continue + } + if reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Map && reflect.TypeOf(dstElement.Interface()).Kind() == reflect.Map { + continue + } + } + + if srcElement.IsValid() && ((srcElement.Kind() != reflect.Ptr && overwrite) || !dstElement.IsValid() || isEmptyValue(dstElement, !config.ShouldNotDereference)) { + if dst.IsNil() { + dst.Set(reflect.MakeMap(dst.Type())) + } + dst.SetMapIndex(key, srcElement) + } + } + + // Ensure that all keys in dst are deleted if they are not in src. + if overwriteWithEmptySrc { + for _, key := range dst.MapKeys() { + srcElement := src.MapIndex(key) + if !srcElement.IsValid() { + dst.SetMapIndex(key, reflect.Value{}) + } + } + } + case reflect.Slice: + if !dst.CanSet() { + break + } + if (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) && !config.AppendSlice && !sliceDeepCopy { + dst.Set(src) + } else if config.AppendSlice { + if src.Type() != dst.Type() { + return fmt.Errorf("cannot append two slice with different type (%s, %s)", src.Type(), dst.Type()) + } + dst.Set(reflect.AppendSlice(dst, src)) + } else if sliceDeepCopy { + for i := 0; i < src.Len() && i < dst.Len(); i++ { + srcElement := src.Index(i) + dstElement := dst.Index(i) + if srcElement.CanInterface() { + srcElement = reflect.ValueOf(srcElement.Interface()) + } + if dstElement.CanInterface() { + dstElement = reflect.ValueOf(dstElement.Interface()) + } + + if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { + return + } + } + } + case reflect.Ptr: + fallthrough + case reflect.Interface: + if isReflectNil(src) { + if overwriteWithEmptySrc && dst.CanSet() && src.Type().AssignableTo(dst.Type()) { + dst.Set(src) + } + break + } + + if src.Kind() != reflect.Interface { + if dst.IsNil() || (src.Kind() != reflect.Ptr && overwrite) { + if dst.CanSet() && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) { + dst.Set(src) + } + } else if src.Kind() == reflect.Ptr { + if !config.ShouldNotDereference { + if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { + return + } + } else { + if overwriteWithEmptySrc || (overwrite && !src.IsNil()) || dst.IsNil() { + dst.Set(src) + } + } + } else if dst.Elem().Type() == src.Type() { + if err = deepMerge(dst.Elem(), src, visited, depth+1, config); err != nil { + return + } + } else { + return ErrDifferentArgumentsTypes + } + break + } + + if dst.IsNil() || overwrite { + if dst.CanSet() && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) { + dst.Set(src) + } + break + } + + if dst.Elem().Kind() == src.Elem().Kind() { + if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { + return + } + break + } + default: + mustSet := (isEmptyValue(dst, !config.ShouldNotDereference) || overwrite) && (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc) + if mustSet { + if dst.CanSet() { + dst.Set(src) + } else { + dst = src + } + } + } + + return +} + +// Merge will fill any empty for value type attributes on the dst struct using corresponding +// src attributes if they themselves are not empty. dst and src must be valid same-type structs +// and dst must be a pointer to struct. +// It won't merge unexported (private) fields and will do recursively any exported field. +func Merge(dst, src interface{}, opts ...func(*Config)) error { + return merge(dst, src, opts...) +} + +// MergeWithOverwrite will do the same as Merge except that non-empty dst attributes will be overridden by +// non-empty src attribute values. +// Deprecated: use Merge(…) with WithOverride +func MergeWithOverwrite(dst, src interface{}, opts ...func(*Config)) error { + return merge(dst, src, append(opts, WithOverride)...) +} + +// WithTransformers adds transformers to merge, allowing to customize the merging of some types. +func WithTransformers(transformers Transformers) func(*Config) { + return func(config *Config) { + config.Transformers = transformers + } +} + +// WithOverride will make merge override non-empty dst attributes with non-empty src attributes values. +func WithOverride(config *Config) { + config.Overwrite = true +} + +// WithOverwriteWithEmptyValue will make merge override non empty dst attributes with empty src attributes values. +func WithOverwriteWithEmptyValue(config *Config) { + config.Overwrite = true + config.overwriteWithEmptyValue = true +} + +// WithOverrideEmptySlice will make merge override empty dst slice with empty src slice. +func WithOverrideEmptySlice(config *Config) { + config.overwriteSliceWithEmptyValue = true +} + +// WithoutDereference prevents dereferencing pointers when evaluating whether they are empty +// (i.e. a non-nil pointer is never considered empty). +func WithoutDereference(config *Config) { + config.ShouldNotDereference = true +} + +// WithAppendSlice will make merge append slices instead of overwriting it. +func WithAppendSlice(config *Config) { + config.AppendSlice = true +} + +// WithTypeCheck will make merge check types while overwriting it (must be used with WithOverride). +func WithTypeCheck(config *Config) { + config.TypeCheck = true +} + +// WithSliceDeepCopy will merge slice element one by one with Overwrite flag. +func WithSliceDeepCopy(config *Config) { + config.sliceDeepCopy = true + config.Overwrite = true +} + +func merge(dst, src interface{}, opts ...func(*Config)) error { + if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr { + return ErrNonPointerArgument + } + var ( + vDst, vSrc reflect.Value + err error + ) + + config := &Config{} + + for _, opt := range opts { + opt(config) + } + + if vDst, vSrc, err = resolveValues(dst, src); err != nil { + return err + } + if vDst.Type() != vSrc.Type() { + return ErrDifferentArgumentsTypes + } + return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) +} + +// IsReflectNil is the reflect value provided nil +func isReflectNil(v reflect.Value) bool { + k := v.Kind() + switch k { + case reflect.Interface, reflect.Slice, reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr: + // Both interface and slice are nil if first word is 0. + // Both are always bigger than a word; assume flagIndir. + return v.IsNil() + default: + return false + } +} diff --git a/vendor/dario.cat/mergo/mergo.go b/vendor/dario.cat/mergo/mergo.go new file mode 100644 index 00000000..0a721e2d --- /dev/null +++ b/vendor/dario.cat/mergo/mergo.go @@ -0,0 +1,81 @@ +// Copyright 2013 Dario Castañé. All rights reserved. +// Copyright 2009 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. + +// Based on src/pkg/reflect/deepequal.go from official +// golang's stdlib. + +package mergo + +import ( + "errors" + "reflect" +) + +// Errors reported by Mergo when it finds invalid arguments. +var ( + ErrNilArguments = errors.New("src and dst must not be nil") + ErrDifferentArgumentsTypes = errors.New("src and dst must be of same type") + ErrNotSupported = errors.New("only structs, maps, and slices are supported") + ErrExpectedMapAsDestination = errors.New("dst was expected to be a map") + ErrExpectedStructAsDestination = errors.New("dst was expected to be a struct") + ErrNonPointerArgument = errors.New("dst must be a pointer") +) + +// During deepMerge, must keep track of checks that are +// in progress. The comparison algorithm assumes that all +// checks in progress are true when it reencounters them. +// Visited are stored in a map indexed by 17 * a1 + a2; +type visit struct { + typ reflect.Type + next *visit + ptr uintptr +} + +// From src/pkg/encoding/json/encode.go. +func isEmptyValue(v reflect.Value, shouldDereference bool) bool { + switch v.Kind() { + case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Interface, reflect.Ptr: + if v.IsNil() { + return true + } + if shouldDereference { + return isEmptyValue(v.Elem(), shouldDereference) + } + return false + case reflect.Func: + return v.IsNil() + case reflect.Invalid: + return true + } + return false +} + +func resolveValues(dst, src interface{}) (vDst, vSrc reflect.Value, err error) { + if dst == nil || src == nil { + err = ErrNilArguments + return + } + vDst = reflect.ValueOf(dst).Elem() + if vDst.Kind() != reflect.Struct && vDst.Kind() != reflect.Map && vDst.Kind() != reflect.Slice { + err = ErrNotSupported + return + } + vSrc = reflect.ValueOf(src) + // We check if vSrc is a pointer to dereference it. + if vSrc.Kind() == reflect.Ptr { + vSrc = vSrc.Elem() + } + return +} diff --git a/vendor/filippo.io/edwards25519/LICENSE b/vendor/filippo.io/edwards25519/LICENSE new file mode 100644 index 00000000..6a66aea5 --- /dev/null +++ b/vendor/filippo.io/edwards25519/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2009 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/filippo.io/edwards25519/README.md b/vendor/filippo.io/edwards25519/README.md new file mode 100644 index 00000000..24e2457d --- /dev/null +++ b/vendor/filippo.io/edwards25519/README.md @@ -0,0 +1,14 @@ +# filippo.io/edwards25519 + +``` +import "filippo.io/edwards25519" +``` + +This library implements the edwards25519 elliptic curve, exposing the necessary APIs to build a wide array of higher-level primitives. +Read the docs at [pkg.go.dev/filippo.io/edwards25519](https://pkg.go.dev/filippo.io/edwards25519). + +The code is originally derived from Adam Langley's internal implementation in the Go standard library, and includes George Tankersley's [performance improvements](https://golang.org/cl/71950). It was then further developed by Henry de Valence for use in ristretto255, and was finally [merged back into the Go standard library](https://golang.org/cl/276272) as of Go 1.17. It now tracks the upstream codebase and extends it with additional functionality. + +Most users don't need this package, and should instead use `crypto/ed25519` for signatures, `golang.org/x/crypto/curve25519` for Diffie-Hellman, or `github.com/gtank/ristretto255` for prime order group logic. However, for anyone currently using a fork of `crypto/internal/edwards25519`/`crypto/ed25519/internal/edwards25519` or `github.com/agl/edwards25519`, this package should be a safer, faster, and more powerful alternative. + +Since this package is meant to curb proliferation of edwards25519 implementations in the Go ecosystem, it welcomes requests for new APIs or reviewable performance improvements. diff --git a/vendor/filippo.io/edwards25519/doc.go b/vendor/filippo.io/edwards25519/doc.go new file mode 100644 index 00000000..ab6aaebc --- /dev/null +++ b/vendor/filippo.io/edwards25519/doc.go @@ -0,0 +1,20 @@ +// Copyright (c) 2021 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 edwards25519 implements group logic for the twisted Edwards curve +// +// -x^2 + y^2 = 1 + -(121665/121666)*x^2*y^2 +// +// This is better known as the Edwards curve equivalent to Curve25519, and is +// the curve used by the Ed25519 signature scheme. +// +// Most users don't need this package, and should instead use crypto/ed25519 for +// signatures, golang.org/x/crypto/curve25519 for Diffie-Hellman, or +// github.com/gtank/ristretto255 for prime order group logic. +// +// However, developers who do need to interact with low-level edwards25519 +// operations can use this package, which is an extended version of +// crypto/internal/edwards25519 from the standard library repackaged as +// an importable module. +package edwards25519 diff --git a/vendor/filippo.io/edwards25519/edwards25519.go b/vendor/filippo.io/edwards25519/edwards25519.go new file mode 100644 index 00000000..a744da2c --- /dev/null +++ b/vendor/filippo.io/edwards25519/edwards25519.go @@ -0,0 +1,427 @@ +// Copyright (c) 2017 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 edwards25519 + +import ( + "errors" + + "filippo.io/edwards25519/field" +) + +// Point types. + +type projP1xP1 struct { + X, Y, Z, T field.Element +} + +type projP2 struct { + X, Y, Z field.Element +} + +// Point represents a point on the edwards25519 curve. +// +// This type works similarly to math/big.Int, and all arguments and receivers +// are allowed to alias. +// +// The zero value is NOT valid, and it may be used only as a receiver. +type Point struct { + // Make the type not comparable (i.e. used with == or as a map key), as + // equivalent points can be represented by different Go values. + _ incomparable + + // The point is internally represented in extended coordinates (X, Y, Z, T) + // where x = X/Z, y = Y/Z, and xy = T/Z per https://eprint.iacr.org/2008/522. + x, y, z, t field.Element +} + +type incomparable [0]func() + +func checkInitialized(points ...*Point) { + for _, p := range points { + if p.x == (field.Element{}) && p.y == (field.Element{}) { + panic("edwards25519: use of uninitialized Point") + } + } +} + +type projCached struct { + YplusX, YminusX, Z, T2d field.Element +} + +type affineCached struct { + YplusX, YminusX, T2d field.Element +} + +// Constructors. + +func (v *projP2) Zero() *projP2 { + v.X.Zero() + v.Y.One() + v.Z.One() + return v +} + +// identity is the point at infinity. +var identity, _ = new(Point).SetBytes([]byte{ + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) + +// NewIdentityPoint returns a new Point set to the identity. +func NewIdentityPoint() *Point { + return new(Point).Set(identity) +} + +// generator is the canonical curve basepoint. See TestGenerator for the +// correspondence of this encoding with the values in RFC 8032. +var generator, _ = new(Point).SetBytes([]byte{ + 0x58, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, + 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, + 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, + 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66}) + +// NewGeneratorPoint returns a new Point set to the canonical generator. +func NewGeneratorPoint() *Point { + return new(Point).Set(generator) +} + +func (v *projCached) Zero() *projCached { + v.YplusX.One() + v.YminusX.One() + v.Z.One() + v.T2d.Zero() + return v +} + +func (v *affineCached) Zero() *affineCached { + v.YplusX.One() + v.YminusX.One() + v.T2d.Zero() + return v +} + +// Assignments. + +// Set sets v = u, and returns v. +func (v *Point) Set(u *Point) *Point { + *v = *u + return v +} + +// Encoding. + +// Bytes returns the canonical 32-byte encoding of v, according to RFC 8032, +// Section 5.1.2. +func (v *Point) Bytes() []byte { + // This function is outlined to make the allocations inline in the caller + // rather than happen on the heap. + var buf [32]byte + return v.bytes(&buf) +} + +func (v *Point) bytes(buf *[32]byte) []byte { + checkInitialized(v) + + var zInv, x, y field.Element + zInv.Invert(&v.z) // zInv = 1 / Z + x.Multiply(&v.x, &zInv) // x = X / Z + y.Multiply(&v.y, &zInv) // y = Y / Z + + out := copyFieldElement(buf, &y) + out[31] |= byte(x.IsNegative() << 7) + return out +} + +var feOne = new(field.Element).One() + +// SetBytes sets v = x, where x is a 32-byte encoding of v. If x does not +// represent a valid point on the curve, SetBytes returns nil and an error and +// the receiver is unchanged. Otherwise, SetBytes returns v. +// +// Note that SetBytes accepts all non-canonical encodings of valid points. +// That is, it follows decoding rules that match most implementations in +// the ecosystem rather than RFC 8032. +func (v *Point) SetBytes(x []byte) (*Point, error) { + // Specifically, the non-canonical encodings that are accepted are + // 1) the ones where the field element is not reduced (see the + // (*field.Element).SetBytes docs) and + // 2) the ones where the x-coordinate is zero and the sign bit is set. + // + // Read more at https://hdevalence.ca/blog/2020-10-04-its-25519am, + // specifically the "Canonical A, R" section. + + y, err := new(field.Element).SetBytes(x) + if err != nil { + return nil, errors.New("edwards25519: invalid point encoding length") + } + + // -x² + y² = 1 + dx²y² + // x² + dx²y² = x²(dy² + 1) = y² - 1 + // x² = (y² - 1) / (dy² + 1) + + // u = y² - 1 + y2 := new(field.Element).Square(y) + u := new(field.Element).Subtract(y2, feOne) + + // v = dy² + 1 + vv := new(field.Element).Multiply(y2, d) + vv = vv.Add(vv, feOne) + + // x = +√(u/v) + xx, wasSquare := new(field.Element).SqrtRatio(u, vv) + if wasSquare == 0 { + return nil, errors.New("edwards25519: invalid point encoding") + } + + // Select the negative square root if the sign bit is set. + xxNeg := new(field.Element).Negate(xx) + xx = xx.Select(xxNeg, xx, int(x[31]>>7)) + + v.x.Set(xx) + v.y.Set(y) + v.z.One() + v.t.Multiply(xx, y) // xy = T / Z + + return v, nil +} + +func copyFieldElement(buf *[32]byte, v *field.Element) []byte { + copy(buf[:], v.Bytes()) + return buf[:] +} + +// Conversions. + +func (v *projP2) FromP1xP1(p *projP1xP1) *projP2 { + v.X.Multiply(&p.X, &p.T) + v.Y.Multiply(&p.Y, &p.Z) + v.Z.Multiply(&p.Z, &p.T) + return v +} + +func (v *projP2) FromP3(p *Point) *projP2 { + v.X.Set(&p.x) + v.Y.Set(&p.y) + v.Z.Set(&p.z) + return v +} + +func (v *Point) fromP1xP1(p *projP1xP1) *Point { + v.x.Multiply(&p.X, &p.T) + v.y.Multiply(&p.Y, &p.Z) + v.z.Multiply(&p.Z, &p.T) + v.t.Multiply(&p.X, &p.Y) + return v +} + +func (v *Point) fromP2(p *projP2) *Point { + v.x.Multiply(&p.X, &p.Z) + v.y.Multiply(&p.Y, &p.Z) + v.z.Square(&p.Z) + v.t.Multiply(&p.X, &p.Y) + return v +} + +// d is a constant in the curve equation. +var d, _ = new(field.Element).SetBytes([]byte{ + 0xa3, 0x78, 0x59, 0x13, 0xca, 0x4d, 0xeb, 0x75, + 0xab, 0xd8, 0x41, 0x41, 0x4d, 0x0a, 0x70, 0x00, + 0x98, 0xe8, 0x79, 0x77, 0x79, 0x40, 0xc7, 0x8c, + 0x73, 0xfe, 0x6f, 0x2b, 0xee, 0x6c, 0x03, 0x52}) +var d2 = new(field.Element).Add(d, d) + +func (v *projCached) FromP3(p *Point) *projCached { + v.YplusX.Add(&p.y, &p.x) + v.YminusX.Subtract(&p.y, &p.x) + v.Z.Set(&p.z) + v.T2d.Multiply(&p.t, d2) + return v +} + +func (v *affineCached) FromP3(p *Point) *affineCached { + v.YplusX.Add(&p.y, &p.x) + v.YminusX.Subtract(&p.y, &p.x) + v.T2d.Multiply(&p.t, d2) + + var invZ field.Element + invZ.Invert(&p.z) + v.YplusX.Multiply(&v.YplusX, &invZ) + v.YminusX.Multiply(&v.YminusX, &invZ) + v.T2d.Multiply(&v.T2d, &invZ) + return v +} + +// (Re)addition and subtraction. + +// Add sets v = p + q, and returns v. +func (v *Point) Add(p, q *Point) *Point { + checkInitialized(p, q) + qCached := new(projCached).FromP3(q) + result := new(projP1xP1).Add(p, qCached) + return v.fromP1xP1(result) +} + +// Subtract sets v = p - q, and returns v. +func (v *Point) Subtract(p, q *Point) *Point { + checkInitialized(p, q) + qCached := new(projCached).FromP3(q) + result := new(projP1xP1).Sub(p, qCached) + return v.fromP1xP1(result) +} + +func (v *projP1xP1) Add(p *Point, q *projCached) *projP1xP1 { + var YplusX, YminusX, PP, MM, TT2d, ZZ2 field.Element + + YplusX.Add(&p.y, &p.x) + YminusX.Subtract(&p.y, &p.x) + + PP.Multiply(&YplusX, &q.YplusX) + MM.Multiply(&YminusX, &q.YminusX) + TT2d.Multiply(&p.t, &q.T2d) + ZZ2.Multiply(&p.z, &q.Z) + + ZZ2.Add(&ZZ2, &ZZ2) + + v.X.Subtract(&PP, &MM) + v.Y.Add(&PP, &MM) + v.Z.Add(&ZZ2, &TT2d) + v.T.Subtract(&ZZ2, &TT2d) + return v +} + +func (v *projP1xP1) Sub(p *Point, q *projCached) *projP1xP1 { + var YplusX, YminusX, PP, MM, TT2d, ZZ2 field.Element + + YplusX.Add(&p.y, &p.x) + YminusX.Subtract(&p.y, &p.x) + + PP.Multiply(&YplusX, &q.YminusX) // flipped sign + MM.Multiply(&YminusX, &q.YplusX) // flipped sign + TT2d.Multiply(&p.t, &q.T2d) + ZZ2.Multiply(&p.z, &q.Z) + + ZZ2.Add(&ZZ2, &ZZ2) + + v.X.Subtract(&PP, &MM) + v.Y.Add(&PP, &MM) + v.Z.Subtract(&ZZ2, &TT2d) // flipped sign + v.T.Add(&ZZ2, &TT2d) // flipped sign + return v +} + +func (v *projP1xP1) AddAffine(p *Point, q *affineCached) *projP1xP1 { + var YplusX, YminusX, PP, MM, TT2d, Z2 field.Element + + YplusX.Add(&p.y, &p.x) + YminusX.Subtract(&p.y, &p.x) + + PP.Multiply(&YplusX, &q.YplusX) + MM.Multiply(&YminusX, &q.YminusX) + TT2d.Multiply(&p.t, &q.T2d) + + Z2.Add(&p.z, &p.z) + + v.X.Subtract(&PP, &MM) + v.Y.Add(&PP, &MM) + v.Z.Add(&Z2, &TT2d) + v.T.Subtract(&Z2, &TT2d) + return v +} + +func (v *projP1xP1) SubAffine(p *Point, q *affineCached) *projP1xP1 { + var YplusX, YminusX, PP, MM, TT2d, Z2 field.Element + + YplusX.Add(&p.y, &p.x) + YminusX.Subtract(&p.y, &p.x) + + PP.Multiply(&YplusX, &q.YminusX) // flipped sign + MM.Multiply(&YminusX, &q.YplusX) // flipped sign + TT2d.Multiply(&p.t, &q.T2d) + + Z2.Add(&p.z, &p.z) + + v.X.Subtract(&PP, &MM) + v.Y.Add(&PP, &MM) + v.Z.Subtract(&Z2, &TT2d) // flipped sign + v.T.Add(&Z2, &TT2d) // flipped sign + return v +} + +// Doubling. + +func (v *projP1xP1) Double(p *projP2) *projP1xP1 { + var XX, YY, ZZ2, XplusYsq field.Element + + XX.Square(&p.X) + YY.Square(&p.Y) + ZZ2.Square(&p.Z) + ZZ2.Add(&ZZ2, &ZZ2) + XplusYsq.Add(&p.X, &p.Y) + XplusYsq.Square(&XplusYsq) + + v.Y.Add(&YY, &XX) + v.Z.Subtract(&YY, &XX) + + v.X.Subtract(&XplusYsq, &v.Y) + v.T.Subtract(&ZZ2, &v.Z) + return v +} + +// Negation. + +// Negate sets v = -p, and returns v. +func (v *Point) Negate(p *Point) *Point { + checkInitialized(p) + v.x.Negate(&p.x) + v.y.Set(&p.y) + v.z.Set(&p.z) + v.t.Negate(&p.t) + return v +} + +// Equal returns 1 if v is equivalent to u, and 0 otherwise. +func (v *Point) Equal(u *Point) int { + checkInitialized(v, u) + + var t1, t2, t3, t4 field.Element + t1.Multiply(&v.x, &u.z) + t2.Multiply(&u.x, &v.z) + t3.Multiply(&v.y, &u.z) + t4.Multiply(&u.y, &v.z) + + return t1.Equal(&t2) & t3.Equal(&t4) +} + +// Constant-time operations + +// Select sets v to a if cond == 1 and to b if cond == 0. +func (v *projCached) Select(a, b *projCached, cond int) *projCached { + v.YplusX.Select(&a.YplusX, &b.YplusX, cond) + v.YminusX.Select(&a.YminusX, &b.YminusX, cond) + v.Z.Select(&a.Z, &b.Z, cond) + v.T2d.Select(&a.T2d, &b.T2d, cond) + return v +} + +// Select sets v to a if cond == 1 and to b if cond == 0. +func (v *affineCached) Select(a, b *affineCached, cond int) *affineCached { + v.YplusX.Select(&a.YplusX, &b.YplusX, cond) + v.YminusX.Select(&a.YminusX, &b.YminusX, cond) + v.T2d.Select(&a.T2d, &b.T2d, cond) + return v +} + +// CondNeg negates v if cond == 1 and leaves it unchanged if cond == 0. +func (v *projCached) CondNeg(cond int) *projCached { + v.YplusX.Swap(&v.YminusX, cond) + v.T2d.Select(new(field.Element).Negate(&v.T2d), &v.T2d, cond) + return v +} + +// CondNeg negates v if cond == 1 and leaves it unchanged if cond == 0. +func (v *affineCached) CondNeg(cond int) *affineCached { + v.YplusX.Swap(&v.YminusX, cond) + v.T2d.Select(new(field.Element).Negate(&v.T2d), &v.T2d, cond) + return v +} diff --git a/vendor/filippo.io/edwards25519/extra.go b/vendor/filippo.io/edwards25519/extra.go new file mode 100644 index 00000000..d152d68f --- /dev/null +++ b/vendor/filippo.io/edwards25519/extra.go @@ -0,0 +1,349 @@ +// Copyright (c) 2021 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 edwards25519 + +// This file contains additional functionality that is not included in the +// upstream crypto/internal/edwards25519 package. + +import ( + "errors" + + "filippo.io/edwards25519/field" +) + +// ExtendedCoordinates returns v in extended coordinates (X:Y:Z:T) where +// x = X/Z, y = Y/Z, and xy = T/Z as in https://eprint.iacr.org/2008/522. +func (v *Point) ExtendedCoordinates() (X, Y, Z, T *field.Element) { + // This function is outlined to make the allocations inline in the caller + // rather than happen on the heap. Don't change the style without making + // sure it doesn't increase the inliner cost. + var e [4]field.Element + X, Y, Z, T = v.extendedCoordinates(&e) + return +} + +func (v *Point) extendedCoordinates(e *[4]field.Element) (X, Y, Z, T *field.Element) { + checkInitialized(v) + X = e[0].Set(&v.x) + Y = e[1].Set(&v.y) + Z = e[2].Set(&v.z) + T = e[3].Set(&v.t) + return +} + +// SetExtendedCoordinates sets v = (X:Y:Z:T) in extended coordinates where +// x = X/Z, y = Y/Z, and xy = T/Z as in https://eprint.iacr.org/2008/522. +// +// If the coordinates are invalid or don't represent a valid point on the curve, +// SetExtendedCoordinates returns nil and an error and the receiver is +// unchanged. Otherwise, SetExtendedCoordinates returns v. +func (v *Point) SetExtendedCoordinates(X, Y, Z, T *field.Element) (*Point, error) { + if !isOnCurve(X, Y, Z, T) { + return nil, errors.New("edwards25519: invalid point coordinates") + } + v.x.Set(X) + v.y.Set(Y) + v.z.Set(Z) + v.t.Set(T) + return v, nil +} + +func isOnCurve(X, Y, Z, T *field.Element) bool { + var lhs, rhs field.Element + XX := new(field.Element).Square(X) + YY := new(field.Element).Square(Y) + ZZ := new(field.Element).Square(Z) + TT := new(field.Element).Square(T) + // -x² + y² = 1 + dx²y² + // -(X/Z)² + (Y/Z)² = 1 + d(T/Z)² + // -X² + Y² = Z² + dT² + lhs.Subtract(YY, XX) + rhs.Multiply(d, TT).Add(&rhs, ZZ) + if lhs.Equal(&rhs) != 1 { + return false + } + // xy = T/Z + // XY/Z² = T/Z + // XY = TZ + lhs.Multiply(X, Y) + rhs.Multiply(T, Z) + return lhs.Equal(&rhs) == 1 +} + +// BytesMontgomery converts v to a point on the birationally-equivalent +// Curve25519 Montgomery curve, and returns its canonical 32 bytes encoding +// according to RFC 7748. +// +// Note that BytesMontgomery only encodes the u-coordinate, so v and -v encode +// to the same value. If v is the identity point, BytesMontgomery returns 32 +// zero bytes, analogously to the X25519 function. +// +// The lack of an inverse operation (such as SetMontgomeryBytes) is deliberate: +// while every valid edwards25519 point has a unique u-coordinate Montgomery +// encoding, X25519 accepts inputs on the quadratic twist, which don't correspond +// to any edwards25519 point, and every other X25519 input corresponds to two +// edwards25519 points. +func (v *Point) BytesMontgomery() []byte { + // This function is outlined to make the allocations inline in the caller + // rather than happen on the heap. + var buf [32]byte + return v.bytesMontgomery(&buf) +} + +func (v *Point) bytesMontgomery(buf *[32]byte) []byte { + checkInitialized(v) + + // RFC 7748, Section 4.1 provides the bilinear map to calculate the + // Montgomery u-coordinate + // + // u = (1 + y) / (1 - y) + // + // where y = Y / Z. + + var y, recip, u field.Element + + y.Multiply(&v.y, y.Invert(&v.z)) // y = Y / Z + recip.Invert(recip.Subtract(feOne, &y)) // r = 1/(1 - y) + u.Multiply(u.Add(feOne, &y), &recip) // u = (1 + y)*r + + return copyFieldElement(buf, &u) +} + +// MultByCofactor sets v = 8 * p, and returns v. +func (v *Point) MultByCofactor(p *Point) *Point { + checkInitialized(p) + result := projP1xP1{} + pp := (&projP2{}).FromP3(p) + result.Double(pp) + pp.FromP1xP1(&result) + result.Double(pp) + pp.FromP1xP1(&result) + result.Double(pp) + return v.fromP1xP1(&result) +} + +// Given k > 0, set s = s**(2*i). +func (s *Scalar) pow2k(k int) { + for i := 0; i < k; i++ { + s.Multiply(s, s) + } +} + +// Invert sets s to the inverse of a nonzero scalar v, and returns s. +// +// If t is zero, Invert returns zero. +func (s *Scalar) Invert(t *Scalar) *Scalar { + // Uses a hardcoded sliding window of width 4. + var table [8]Scalar + var tt Scalar + tt.Multiply(t, t) + table[0] = *t + for i := 0; i < 7; i++ { + table[i+1].Multiply(&table[i], &tt) + } + // Now table = [t**1, t**3, t**5, t**7, t**9, t**11, t**13, t**15] + // so t**k = t[k/2] for odd k + + // To compute the sliding window digits, use the following Sage script: + + // sage: import itertools + // sage: def sliding_window(w,k): + // ....: digits = [] + // ....: while k > 0: + // ....: if k % 2 == 1: + // ....: kmod = k % (2**w) + // ....: digits.append(kmod) + // ....: k = k - kmod + // ....: else: + // ....: digits.append(0) + // ....: k = k // 2 + // ....: return digits + + // Now we can compute s roughly as follows: + + // sage: s = 1 + // sage: for coeff in reversed(sliding_window(4,l-2)): + // ....: s = s*s + // ....: if coeff > 0 : + // ....: s = s*t**coeff + + // This works on one bit at a time, with many runs of zeros. + // The digits can be collapsed into [(count, coeff)] as follows: + + // sage: [(len(list(group)),d) for d,group in itertools.groupby(sliding_window(4,l-2))] + + // Entries of the form (k, 0) turn into pow2k(k) + // Entries of the form (1, coeff) turn into a squaring and then a table lookup. + // We can fold the squaring into the previous pow2k(k) as pow2k(k+1). + + *s = table[1/2] + s.pow2k(127 + 1) + s.Multiply(s, &table[1/2]) + s.pow2k(4 + 1) + s.Multiply(s, &table[9/2]) + s.pow2k(3 + 1) + s.Multiply(s, &table[11/2]) + s.pow2k(3 + 1) + s.Multiply(s, &table[13/2]) + s.pow2k(3 + 1) + s.Multiply(s, &table[15/2]) + s.pow2k(4 + 1) + s.Multiply(s, &table[7/2]) + s.pow2k(4 + 1) + s.Multiply(s, &table[15/2]) + s.pow2k(3 + 1) + s.Multiply(s, &table[5/2]) + s.pow2k(3 + 1) + s.Multiply(s, &table[1/2]) + s.pow2k(4 + 1) + s.Multiply(s, &table[15/2]) + s.pow2k(4 + 1) + s.Multiply(s, &table[15/2]) + s.pow2k(4 + 1) + s.Multiply(s, &table[7/2]) + s.pow2k(3 + 1) + s.Multiply(s, &table[3/2]) + s.pow2k(4 + 1) + s.Multiply(s, &table[11/2]) + s.pow2k(5 + 1) + s.Multiply(s, &table[11/2]) + s.pow2k(9 + 1) + s.Multiply(s, &table[9/2]) + s.pow2k(3 + 1) + s.Multiply(s, &table[3/2]) + s.pow2k(4 + 1) + s.Multiply(s, &table[3/2]) + s.pow2k(4 + 1) + s.Multiply(s, &table[3/2]) + s.pow2k(4 + 1) + s.Multiply(s, &table[9/2]) + s.pow2k(3 + 1) + s.Multiply(s, &table[7/2]) + s.pow2k(3 + 1) + s.Multiply(s, &table[3/2]) + s.pow2k(3 + 1) + s.Multiply(s, &table[13/2]) + s.pow2k(3 + 1) + s.Multiply(s, &table[7/2]) + s.pow2k(4 + 1) + s.Multiply(s, &table[9/2]) + s.pow2k(3 + 1) + s.Multiply(s, &table[15/2]) + s.pow2k(4 + 1) + s.Multiply(s, &table[11/2]) + + return s +} + +// MultiScalarMult sets v = sum(scalars[i] * points[i]), and returns v. +// +// Execution time depends only on the lengths of the two slices, which must match. +func (v *Point) MultiScalarMult(scalars []*Scalar, points []*Point) *Point { + if len(scalars) != len(points) { + panic("edwards25519: called MultiScalarMult with different size inputs") + } + checkInitialized(points...) + + // Proceed as in the single-base case, but share doublings + // between each point in the multiscalar equation. + + // Build lookup tables for each point + tables := make([]projLookupTable, len(points)) + for i := range tables { + tables[i].FromP3(points[i]) + } + // Compute signed radix-16 digits for each scalar + digits := make([][64]int8, len(scalars)) + for i := range digits { + digits[i] = scalars[i].signedRadix16() + } + + // Unwrap first loop iteration to save computing 16*identity + multiple := &projCached{} + tmp1 := &projP1xP1{} + tmp2 := &projP2{} + // Lookup-and-add the appropriate multiple of each input point + for j := range tables { + tables[j].SelectInto(multiple, digits[j][63]) + tmp1.Add(v, multiple) // tmp1 = v + x_(j,63)*Q in P1xP1 coords + v.fromP1xP1(tmp1) // update v + } + tmp2.FromP3(v) // set up tmp2 = v in P2 coords for next iteration + for i := 62; i >= 0; i-- { + tmp1.Double(tmp2) // tmp1 = 2*(prev) in P1xP1 coords + tmp2.FromP1xP1(tmp1) // tmp2 = 2*(prev) in P2 coords + tmp1.Double(tmp2) // tmp1 = 4*(prev) in P1xP1 coords + tmp2.FromP1xP1(tmp1) // tmp2 = 4*(prev) in P2 coords + tmp1.Double(tmp2) // tmp1 = 8*(prev) in P1xP1 coords + tmp2.FromP1xP1(tmp1) // tmp2 = 8*(prev) in P2 coords + tmp1.Double(tmp2) // tmp1 = 16*(prev) in P1xP1 coords + v.fromP1xP1(tmp1) // v = 16*(prev) in P3 coords + // Lookup-and-add the appropriate multiple of each input point + for j := range tables { + tables[j].SelectInto(multiple, digits[j][i]) + tmp1.Add(v, multiple) // tmp1 = v + x_(j,i)*Q in P1xP1 coords + v.fromP1xP1(tmp1) // update v + } + tmp2.FromP3(v) // set up tmp2 = v in P2 coords for next iteration + } + return v +} + +// VarTimeMultiScalarMult sets v = sum(scalars[i] * points[i]), and returns v. +// +// Execution time depends on the inputs. +func (v *Point) VarTimeMultiScalarMult(scalars []*Scalar, points []*Point) *Point { + if len(scalars) != len(points) { + panic("edwards25519: called VarTimeMultiScalarMult with different size inputs") + } + checkInitialized(points...) + + // Generalize double-base NAF computation to arbitrary sizes. + // Here all the points are dynamic, so we only use the smaller + // tables. + + // Build lookup tables for each point + tables := make([]nafLookupTable5, len(points)) + for i := range tables { + tables[i].FromP3(points[i]) + } + // Compute a NAF for each scalar + nafs := make([][256]int8, len(scalars)) + for i := range nafs { + nafs[i] = scalars[i].nonAdjacentForm(5) + } + + multiple := &projCached{} + tmp1 := &projP1xP1{} + tmp2 := &projP2{} + tmp2.Zero() + + // Move from high to low bits, doubling the accumulator + // at each iteration and checking whether there is a nonzero + // coefficient to look up a multiple of. + // + // Skip trying to find the first nonzero coefficent, because + // searching might be more work than a few extra doublings. + for i := 255; i >= 0; i-- { + tmp1.Double(tmp2) + + for j := range nafs { + if nafs[j][i] > 0 { + v.fromP1xP1(tmp1) + tables[j].SelectInto(multiple, nafs[j][i]) + tmp1.Add(v, multiple) + } else if nafs[j][i] < 0 { + v.fromP1xP1(tmp1) + tables[j].SelectInto(multiple, -nafs[j][i]) + tmp1.Sub(v, multiple) + } + } + + tmp2.FromP1xP1(tmp1) + } + + v.fromP2(tmp2) + return v +} diff --git a/vendor/filippo.io/edwards25519/field/fe.go b/vendor/filippo.io/edwards25519/field/fe.go new file mode 100644 index 00000000..5518ef2b --- /dev/null +++ b/vendor/filippo.io/edwards25519/field/fe.go @@ -0,0 +1,420 @@ +// Copyright (c) 2017 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 field implements fast arithmetic modulo 2^255-19. +package field + +import ( + "crypto/subtle" + "encoding/binary" + "errors" + "math/bits" +) + +// Element represents an element of the field GF(2^255-19). Note that this +// is not a cryptographically secure group, and should only be used to interact +// with edwards25519.Point coordinates. +// +// This type works similarly to math/big.Int, and all arguments and receivers +// are allowed to alias. +// +// The zero value is a valid zero element. +type Element struct { + // An element t represents the integer + // t.l0 + t.l1*2^51 + t.l2*2^102 + t.l3*2^153 + t.l4*2^204 + // + // Between operations, all limbs are expected to be lower than 2^52. + l0 uint64 + l1 uint64 + l2 uint64 + l3 uint64 + l4 uint64 +} + +const maskLow51Bits uint64 = (1 << 51) - 1 + +var feZero = &Element{0, 0, 0, 0, 0} + +// Zero sets v = 0, and returns v. +func (v *Element) Zero() *Element { + *v = *feZero + return v +} + +var feOne = &Element{1, 0, 0, 0, 0} + +// One sets v = 1, and returns v. +func (v *Element) One() *Element { + *v = *feOne + return v +} + +// reduce reduces v modulo 2^255 - 19 and returns it. +func (v *Element) reduce() *Element { + v.carryPropagate() + + // After the light reduction we now have a field element representation + // v < 2^255 + 2^13 * 19, but need v < 2^255 - 19. + + // If v >= 2^255 - 19, then v + 19 >= 2^255, which would overflow 2^255 - 1, + // generating a carry. That is, c will be 0 if v < 2^255 - 19, and 1 otherwise. + c := (v.l0 + 19) >> 51 + c = (v.l1 + c) >> 51 + c = (v.l2 + c) >> 51 + c = (v.l3 + c) >> 51 + c = (v.l4 + c) >> 51 + + // If v < 2^255 - 19 and c = 0, this will be a no-op. Otherwise, it's + // effectively applying the reduction identity to the carry. + v.l0 += 19 * c + + v.l1 += v.l0 >> 51 + v.l0 = v.l0 & maskLow51Bits + v.l2 += v.l1 >> 51 + v.l1 = v.l1 & maskLow51Bits + v.l3 += v.l2 >> 51 + v.l2 = v.l2 & maskLow51Bits + v.l4 += v.l3 >> 51 + v.l3 = v.l3 & maskLow51Bits + // no additional carry + v.l4 = v.l4 & maskLow51Bits + + return v +} + +// Add sets v = a + b, and returns v. +func (v *Element) Add(a, b *Element) *Element { + v.l0 = a.l0 + b.l0 + v.l1 = a.l1 + b.l1 + v.l2 = a.l2 + b.l2 + v.l3 = a.l3 + b.l3 + v.l4 = a.l4 + b.l4 + // Using the generic implementation here is actually faster than the + // assembly. Probably because the body of this function is so simple that + // the compiler can figure out better optimizations by inlining the carry + // propagation. + return v.carryPropagateGeneric() +} + +// Subtract sets v = a - b, and returns v. +func (v *Element) Subtract(a, b *Element) *Element { + // We first add 2 * p, to guarantee the subtraction won't underflow, and + // then subtract b (which can be up to 2^255 + 2^13 * 19). + v.l0 = (a.l0 + 0xFFFFFFFFFFFDA) - b.l0 + v.l1 = (a.l1 + 0xFFFFFFFFFFFFE) - b.l1 + v.l2 = (a.l2 + 0xFFFFFFFFFFFFE) - b.l2 + v.l3 = (a.l3 + 0xFFFFFFFFFFFFE) - b.l3 + v.l4 = (a.l4 + 0xFFFFFFFFFFFFE) - b.l4 + return v.carryPropagate() +} + +// Negate sets v = -a, and returns v. +func (v *Element) Negate(a *Element) *Element { + return v.Subtract(feZero, a) +} + +// Invert sets v = 1/z mod p, and returns v. +// +// If z == 0, Invert returns v = 0. +func (v *Element) Invert(z *Element) *Element { + // Inversion is implemented as exponentiation with exponent p − 2. It uses the + // same sequence of 255 squarings and 11 multiplications as [Curve25519]. + var z2, z9, z11, z2_5_0, z2_10_0, z2_20_0, z2_50_0, z2_100_0, t Element + + z2.Square(z) // 2 + t.Square(&z2) // 4 + t.Square(&t) // 8 + z9.Multiply(&t, z) // 9 + z11.Multiply(&z9, &z2) // 11 + t.Square(&z11) // 22 + z2_5_0.Multiply(&t, &z9) // 31 = 2^5 - 2^0 + + t.Square(&z2_5_0) // 2^6 - 2^1 + for i := 0; i < 4; i++ { + t.Square(&t) // 2^10 - 2^5 + } + z2_10_0.Multiply(&t, &z2_5_0) // 2^10 - 2^0 + + t.Square(&z2_10_0) // 2^11 - 2^1 + for i := 0; i < 9; i++ { + t.Square(&t) // 2^20 - 2^10 + } + z2_20_0.Multiply(&t, &z2_10_0) // 2^20 - 2^0 + + t.Square(&z2_20_0) // 2^21 - 2^1 + for i := 0; i < 19; i++ { + t.Square(&t) // 2^40 - 2^20 + } + t.Multiply(&t, &z2_20_0) // 2^40 - 2^0 + + t.Square(&t) // 2^41 - 2^1 + for i := 0; i < 9; i++ { + t.Square(&t) // 2^50 - 2^10 + } + z2_50_0.Multiply(&t, &z2_10_0) // 2^50 - 2^0 + + t.Square(&z2_50_0) // 2^51 - 2^1 + for i := 0; i < 49; i++ { + t.Square(&t) // 2^100 - 2^50 + } + z2_100_0.Multiply(&t, &z2_50_0) // 2^100 - 2^0 + + t.Square(&z2_100_0) // 2^101 - 2^1 + for i := 0; i < 99; i++ { + t.Square(&t) // 2^200 - 2^100 + } + t.Multiply(&t, &z2_100_0) // 2^200 - 2^0 + + t.Square(&t) // 2^201 - 2^1 + for i := 0; i < 49; i++ { + t.Square(&t) // 2^250 - 2^50 + } + t.Multiply(&t, &z2_50_0) // 2^250 - 2^0 + + t.Square(&t) // 2^251 - 2^1 + t.Square(&t) // 2^252 - 2^2 + t.Square(&t) // 2^253 - 2^3 + t.Square(&t) // 2^254 - 2^4 + t.Square(&t) // 2^255 - 2^5 + + return v.Multiply(&t, &z11) // 2^255 - 21 +} + +// Set sets v = a, and returns v. +func (v *Element) Set(a *Element) *Element { + *v = *a + return v +} + +// SetBytes sets v to x, where x is a 32-byte little-endian encoding. If x is +// not of the right length, SetBytes returns nil and an error, and the +// receiver is unchanged. +// +// Consistent with RFC 7748, the most significant bit (the high bit of the +// last byte) is ignored, and non-canonical values (2^255-19 through 2^255-1) +// are accepted. Note that this is laxer than specified by RFC 8032, but +// consistent with most Ed25519 implementations. +func (v *Element) SetBytes(x []byte) (*Element, error) { + if len(x) != 32 { + return nil, errors.New("edwards25519: invalid field element input size") + } + + // Bits 0:51 (bytes 0:8, bits 0:64, shift 0, mask 51). + v.l0 = binary.LittleEndian.Uint64(x[0:8]) + v.l0 &= maskLow51Bits + // Bits 51:102 (bytes 6:14, bits 48:112, shift 3, mask 51). + v.l1 = binary.LittleEndian.Uint64(x[6:14]) >> 3 + v.l1 &= maskLow51Bits + // Bits 102:153 (bytes 12:20, bits 96:160, shift 6, mask 51). + v.l2 = binary.LittleEndian.Uint64(x[12:20]) >> 6 + v.l2 &= maskLow51Bits + // Bits 153:204 (bytes 19:27, bits 152:216, shift 1, mask 51). + v.l3 = binary.LittleEndian.Uint64(x[19:27]) >> 1 + v.l3 &= maskLow51Bits + // Bits 204:255 (bytes 24:32, bits 192:256, shift 12, mask 51). + // Note: not bytes 25:33, shift 4, to avoid overread. + v.l4 = binary.LittleEndian.Uint64(x[24:32]) >> 12 + v.l4 &= maskLow51Bits + + return v, nil +} + +// Bytes returns the canonical 32-byte little-endian encoding of v. +func (v *Element) Bytes() []byte { + // This function is outlined to make the allocations inline in the caller + // rather than happen on the heap. + var out [32]byte + return v.bytes(&out) +} + +func (v *Element) bytes(out *[32]byte) []byte { + t := *v + t.reduce() + + var buf [8]byte + for i, l := range [5]uint64{t.l0, t.l1, t.l2, t.l3, t.l4} { + bitsOffset := i * 51 + binary.LittleEndian.PutUint64(buf[:], l<= len(out) { + break + } + out[off] |= bb + } + } + + return out[:] +} + +// Equal returns 1 if v and u are equal, and 0 otherwise. +func (v *Element) Equal(u *Element) int { + sa, sv := u.Bytes(), v.Bytes() + return subtle.ConstantTimeCompare(sa, sv) +} + +// mask64Bits returns 0xffffffff if cond is 1, and 0 otherwise. +func mask64Bits(cond int) uint64 { return ^(uint64(cond) - 1) } + +// Select sets v to a if cond == 1, and to b if cond == 0. +func (v *Element) Select(a, b *Element, cond int) *Element { + m := mask64Bits(cond) + v.l0 = (m & a.l0) | (^m & b.l0) + v.l1 = (m & a.l1) | (^m & b.l1) + v.l2 = (m & a.l2) | (^m & b.l2) + v.l3 = (m & a.l3) | (^m & b.l3) + v.l4 = (m & a.l4) | (^m & b.l4) + return v +} + +// Swap swaps v and u if cond == 1 or leaves them unchanged if cond == 0, and returns v. +func (v *Element) Swap(u *Element, cond int) { + m := mask64Bits(cond) + t := m & (v.l0 ^ u.l0) + v.l0 ^= t + u.l0 ^= t + t = m & (v.l1 ^ u.l1) + v.l1 ^= t + u.l1 ^= t + t = m & (v.l2 ^ u.l2) + v.l2 ^= t + u.l2 ^= t + t = m & (v.l3 ^ u.l3) + v.l3 ^= t + u.l3 ^= t + t = m & (v.l4 ^ u.l4) + v.l4 ^= t + u.l4 ^= t +} + +// IsNegative returns 1 if v is negative, and 0 otherwise. +func (v *Element) IsNegative() int { + return int(v.Bytes()[0] & 1) +} + +// Absolute sets v to |u|, and returns v. +func (v *Element) Absolute(u *Element) *Element { + return v.Select(new(Element).Negate(u), u, u.IsNegative()) +} + +// Multiply sets v = x * y, and returns v. +func (v *Element) Multiply(x, y *Element) *Element { + feMul(v, x, y) + return v +} + +// Square sets v = x * x, and returns v. +func (v *Element) Square(x *Element) *Element { + feSquare(v, x) + return v +} + +// Mult32 sets v = x * y, and returns v. +func (v *Element) Mult32(x *Element, y uint32) *Element { + x0lo, x0hi := mul51(x.l0, y) + x1lo, x1hi := mul51(x.l1, y) + x2lo, x2hi := mul51(x.l2, y) + x3lo, x3hi := mul51(x.l3, y) + x4lo, x4hi := mul51(x.l4, y) + v.l0 = x0lo + 19*x4hi // carried over per the reduction identity + v.l1 = x1lo + x0hi + v.l2 = x2lo + x1hi + v.l3 = x3lo + x2hi + v.l4 = x4lo + x3hi + // The hi portions are going to be only 32 bits, plus any previous excess, + // so we can skip the carry propagation. + return v +} + +// mul51 returns lo + hi * 2⁵¹ = a * b. +func mul51(a uint64, b uint32) (lo uint64, hi uint64) { + mh, ml := bits.Mul64(a, uint64(b)) + lo = ml & maskLow51Bits + hi = (mh << 13) | (ml >> 51) + return +} + +// Pow22523 set v = x^((p-5)/8), and returns v. (p-5)/8 is 2^252-3. +func (v *Element) Pow22523(x *Element) *Element { + var t0, t1, t2 Element + + t0.Square(x) // x^2 + t1.Square(&t0) // x^4 + t1.Square(&t1) // x^8 + t1.Multiply(x, &t1) // x^9 + t0.Multiply(&t0, &t1) // x^11 + t0.Square(&t0) // x^22 + t0.Multiply(&t1, &t0) // x^31 + t1.Square(&t0) // x^62 + for i := 1; i < 5; i++ { // x^992 + t1.Square(&t1) + } + t0.Multiply(&t1, &t0) // x^1023 -> 1023 = 2^10 - 1 + t1.Square(&t0) // 2^11 - 2 + for i := 1; i < 10; i++ { // 2^20 - 2^10 + t1.Square(&t1) + } + t1.Multiply(&t1, &t0) // 2^20 - 1 + t2.Square(&t1) // 2^21 - 2 + for i := 1; i < 20; i++ { // 2^40 - 2^20 + t2.Square(&t2) + } + t1.Multiply(&t2, &t1) // 2^40 - 1 + t1.Square(&t1) // 2^41 - 2 + for i := 1; i < 10; i++ { // 2^50 - 2^10 + t1.Square(&t1) + } + t0.Multiply(&t1, &t0) // 2^50 - 1 + t1.Square(&t0) // 2^51 - 2 + for i := 1; i < 50; i++ { // 2^100 - 2^50 + t1.Square(&t1) + } + t1.Multiply(&t1, &t0) // 2^100 - 1 + t2.Square(&t1) // 2^101 - 2 + for i := 1; i < 100; i++ { // 2^200 - 2^100 + t2.Square(&t2) + } + t1.Multiply(&t2, &t1) // 2^200 - 1 + t1.Square(&t1) // 2^201 - 2 + for i := 1; i < 50; i++ { // 2^250 - 2^50 + t1.Square(&t1) + } + t0.Multiply(&t1, &t0) // 2^250 - 1 + t0.Square(&t0) // 2^251 - 2 + t0.Square(&t0) // 2^252 - 4 + return v.Multiply(&t0, x) // 2^252 - 3 -> x^(2^252-3) +} + +// sqrtM1 is 2^((p-1)/4), which squared is equal to -1 by Euler's Criterion. +var sqrtM1 = &Element{1718705420411056, 234908883556509, + 2233514472574048, 2117202627021982, 765476049583133} + +// SqrtRatio sets r to the non-negative square root of the ratio of u and v. +// +// If u/v is square, SqrtRatio returns r and 1. If u/v is not square, SqrtRatio +// sets r according to Section 4.3 of draft-irtf-cfrg-ristretto255-decaf448-00, +// and returns r and 0. +func (r *Element) SqrtRatio(u, v *Element) (R *Element, wasSquare int) { + t0 := new(Element) + + // r = (u * v3) * (u * v7)^((p-5)/8) + v2 := new(Element).Square(v) + uv3 := new(Element).Multiply(u, t0.Multiply(v2, v)) + uv7 := new(Element).Multiply(uv3, t0.Square(v2)) + rr := new(Element).Multiply(uv3, t0.Pow22523(uv7)) + + check := new(Element).Multiply(v, t0.Square(rr)) // check = v * r^2 + + uNeg := new(Element).Negate(u) + correctSignSqrt := check.Equal(u) + flippedSignSqrt := check.Equal(uNeg) + flippedSignSqrtI := check.Equal(t0.Multiply(uNeg, sqrtM1)) + + rPrime := new(Element).Multiply(rr, sqrtM1) // r_prime = SQRT_M1 * r + // r = CT_SELECT(r_prime IF flipped_sign_sqrt | flipped_sign_sqrt_i ELSE r) + rr.Select(rPrime, rr, flippedSignSqrt|flippedSignSqrtI) + + r.Absolute(rr) // Choose the nonnegative square root. + return r, correctSignSqrt | flippedSignSqrt +} diff --git a/vendor/filippo.io/edwards25519/field/fe_amd64.go b/vendor/filippo.io/edwards25519/field/fe_amd64.go new file mode 100644 index 00000000..edcf163c --- /dev/null +++ b/vendor/filippo.io/edwards25519/field/fe_amd64.go @@ -0,0 +1,16 @@ +// Code generated by command: go run fe_amd64_asm.go -out ../fe_amd64.s -stubs ../fe_amd64.go -pkg field. DO NOT EDIT. + +//go:build amd64 && gc && !purego +// +build amd64,gc,!purego + +package field + +// feMul sets out = a * b. It works like feMulGeneric. +// +//go:noescape +func feMul(out *Element, a *Element, b *Element) + +// feSquare sets out = a * a. It works like feSquareGeneric. +// +//go:noescape +func feSquare(out *Element, a *Element) diff --git a/vendor/filippo.io/edwards25519/field/fe_amd64.s b/vendor/filippo.io/edwards25519/field/fe_amd64.s new file mode 100644 index 00000000..293f013c --- /dev/null +++ b/vendor/filippo.io/edwards25519/field/fe_amd64.s @@ -0,0 +1,379 @@ +// Code generated by command: go run fe_amd64_asm.go -out ../fe_amd64.s -stubs ../fe_amd64.go -pkg field. DO NOT EDIT. + +//go:build amd64 && gc && !purego +// +build amd64,gc,!purego + +#include "textflag.h" + +// func feMul(out *Element, a *Element, b *Element) +TEXT ·feMul(SB), NOSPLIT, $0-24 + MOVQ a+8(FP), CX + MOVQ b+16(FP), BX + + // r0 = a0×b0 + MOVQ (CX), AX + MULQ (BX) + MOVQ AX, DI + MOVQ DX, SI + + // r0 += 19×a1×b4 + MOVQ 8(CX), AX + IMUL3Q $0x13, AX, AX + MULQ 32(BX) + ADDQ AX, DI + ADCQ DX, SI + + // r0 += 19×a2×b3 + MOVQ 16(CX), AX + IMUL3Q $0x13, AX, AX + MULQ 24(BX) + ADDQ AX, DI + ADCQ DX, SI + + // r0 += 19×a3×b2 + MOVQ 24(CX), AX + IMUL3Q $0x13, AX, AX + MULQ 16(BX) + ADDQ AX, DI + ADCQ DX, SI + + // r0 += 19×a4×b1 + MOVQ 32(CX), AX + IMUL3Q $0x13, AX, AX + MULQ 8(BX) + ADDQ AX, DI + ADCQ DX, SI + + // r1 = a0×b1 + MOVQ (CX), AX + MULQ 8(BX) + MOVQ AX, R9 + MOVQ DX, R8 + + // r1 += a1×b0 + MOVQ 8(CX), AX + MULQ (BX) + ADDQ AX, R9 + ADCQ DX, R8 + + // r1 += 19×a2×b4 + MOVQ 16(CX), AX + IMUL3Q $0x13, AX, AX + MULQ 32(BX) + ADDQ AX, R9 + ADCQ DX, R8 + + // r1 += 19×a3×b3 + MOVQ 24(CX), AX + IMUL3Q $0x13, AX, AX + MULQ 24(BX) + ADDQ AX, R9 + ADCQ DX, R8 + + // r1 += 19×a4×b2 + MOVQ 32(CX), AX + IMUL3Q $0x13, AX, AX + MULQ 16(BX) + ADDQ AX, R9 + ADCQ DX, R8 + + // r2 = a0×b2 + MOVQ (CX), AX + MULQ 16(BX) + MOVQ AX, R11 + MOVQ DX, R10 + + // r2 += a1×b1 + MOVQ 8(CX), AX + MULQ 8(BX) + ADDQ AX, R11 + ADCQ DX, R10 + + // r2 += a2×b0 + MOVQ 16(CX), AX + MULQ (BX) + ADDQ AX, R11 + ADCQ DX, R10 + + // r2 += 19×a3×b4 + MOVQ 24(CX), AX + IMUL3Q $0x13, AX, AX + MULQ 32(BX) + ADDQ AX, R11 + ADCQ DX, R10 + + // r2 += 19×a4×b3 + MOVQ 32(CX), AX + IMUL3Q $0x13, AX, AX + MULQ 24(BX) + ADDQ AX, R11 + ADCQ DX, R10 + + // r3 = a0×b3 + MOVQ (CX), AX + MULQ 24(BX) + MOVQ AX, R13 + MOVQ DX, R12 + + // r3 += a1×b2 + MOVQ 8(CX), AX + MULQ 16(BX) + ADDQ AX, R13 + ADCQ DX, R12 + + // r3 += a2×b1 + MOVQ 16(CX), AX + MULQ 8(BX) + ADDQ AX, R13 + ADCQ DX, R12 + + // r3 += a3×b0 + MOVQ 24(CX), AX + MULQ (BX) + ADDQ AX, R13 + ADCQ DX, R12 + + // r3 += 19×a4×b4 + MOVQ 32(CX), AX + IMUL3Q $0x13, AX, AX + MULQ 32(BX) + ADDQ AX, R13 + ADCQ DX, R12 + + // r4 = a0×b4 + MOVQ (CX), AX + MULQ 32(BX) + MOVQ AX, R15 + MOVQ DX, R14 + + // r4 += a1×b3 + MOVQ 8(CX), AX + MULQ 24(BX) + ADDQ AX, R15 + ADCQ DX, R14 + + // r4 += a2×b2 + MOVQ 16(CX), AX + MULQ 16(BX) + ADDQ AX, R15 + ADCQ DX, R14 + + // r4 += a3×b1 + MOVQ 24(CX), AX + MULQ 8(BX) + ADDQ AX, R15 + ADCQ DX, R14 + + // r4 += a4×b0 + MOVQ 32(CX), AX + MULQ (BX) + ADDQ AX, R15 + ADCQ DX, R14 + + // First reduction chain + MOVQ $0x0007ffffffffffff, AX + SHLQ $0x0d, DI, SI + SHLQ $0x0d, R9, R8 + SHLQ $0x0d, R11, R10 + SHLQ $0x0d, R13, R12 + SHLQ $0x0d, R15, R14 + ANDQ AX, DI + IMUL3Q $0x13, R14, R14 + ADDQ R14, DI + ANDQ AX, R9 + ADDQ SI, R9 + ANDQ AX, R11 + ADDQ R8, R11 + ANDQ AX, R13 + ADDQ R10, R13 + ANDQ AX, R15 + ADDQ R12, R15 + + // Second reduction chain (carryPropagate) + MOVQ DI, SI + SHRQ $0x33, SI + MOVQ R9, R8 + SHRQ $0x33, R8 + MOVQ R11, R10 + SHRQ $0x33, R10 + MOVQ R13, R12 + SHRQ $0x33, R12 + MOVQ R15, R14 + SHRQ $0x33, R14 + ANDQ AX, DI + IMUL3Q $0x13, R14, R14 + ADDQ R14, DI + ANDQ AX, R9 + ADDQ SI, R9 + ANDQ AX, R11 + ADDQ R8, R11 + ANDQ AX, R13 + ADDQ R10, R13 + ANDQ AX, R15 + ADDQ R12, R15 + + // Store output + MOVQ out+0(FP), AX + MOVQ DI, (AX) + MOVQ R9, 8(AX) + MOVQ R11, 16(AX) + MOVQ R13, 24(AX) + MOVQ R15, 32(AX) + RET + +// func feSquare(out *Element, a *Element) +TEXT ·feSquare(SB), NOSPLIT, $0-16 + MOVQ a+8(FP), CX + + // r0 = l0×l0 + MOVQ (CX), AX + MULQ (CX) + MOVQ AX, SI + MOVQ DX, BX + + // r0 += 38×l1×l4 + MOVQ 8(CX), AX + IMUL3Q $0x26, AX, AX + MULQ 32(CX) + ADDQ AX, SI + ADCQ DX, BX + + // r0 += 38×l2×l3 + MOVQ 16(CX), AX + IMUL3Q $0x26, AX, AX + MULQ 24(CX) + ADDQ AX, SI + ADCQ DX, BX + + // r1 = 2×l0×l1 + MOVQ (CX), AX + SHLQ $0x01, AX + MULQ 8(CX) + MOVQ AX, R8 + MOVQ DX, DI + + // r1 += 38×l2×l4 + MOVQ 16(CX), AX + IMUL3Q $0x26, AX, AX + MULQ 32(CX) + ADDQ AX, R8 + ADCQ DX, DI + + // r1 += 19×l3×l3 + MOVQ 24(CX), AX + IMUL3Q $0x13, AX, AX + MULQ 24(CX) + ADDQ AX, R8 + ADCQ DX, DI + + // r2 = 2×l0×l2 + MOVQ (CX), AX + SHLQ $0x01, AX + MULQ 16(CX) + MOVQ AX, R10 + MOVQ DX, R9 + + // r2 += l1×l1 + MOVQ 8(CX), AX + MULQ 8(CX) + ADDQ AX, R10 + ADCQ DX, R9 + + // r2 += 38×l3×l4 + MOVQ 24(CX), AX + IMUL3Q $0x26, AX, AX + MULQ 32(CX) + ADDQ AX, R10 + ADCQ DX, R9 + + // r3 = 2×l0×l3 + MOVQ (CX), AX + SHLQ $0x01, AX + MULQ 24(CX) + MOVQ AX, R12 + MOVQ DX, R11 + + // r3 += 2×l1×l2 + MOVQ 8(CX), AX + IMUL3Q $0x02, AX, AX + MULQ 16(CX) + ADDQ AX, R12 + ADCQ DX, R11 + + // r3 += 19×l4×l4 + MOVQ 32(CX), AX + IMUL3Q $0x13, AX, AX + MULQ 32(CX) + ADDQ AX, R12 + ADCQ DX, R11 + + // r4 = 2×l0×l4 + MOVQ (CX), AX + SHLQ $0x01, AX + MULQ 32(CX) + MOVQ AX, R14 + MOVQ DX, R13 + + // r4 += 2×l1×l3 + MOVQ 8(CX), AX + IMUL3Q $0x02, AX, AX + MULQ 24(CX) + ADDQ AX, R14 + ADCQ DX, R13 + + // r4 += l2×l2 + MOVQ 16(CX), AX + MULQ 16(CX) + ADDQ AX, R14 + ADCQ DX, R13 + + // First reduction chain + MOVQ $0x0007ffffffffffff, AX + SHLQ $0x0d, SI, BX + SHLQ $0x0d, R8, DI + SHLQ $0x0d, R10, R9 + SHLQ $0x0d, R12, R11 + SHLQ $0x0d, R14, R13 + ANDQ AX, SI + IMUL3Q $0x13, R13, R13 + ADDQ R13, SI + ANDQ AX, R8 + ADDQ BX, R8 + ANDQ AX, R10 + ADDQ DI, R10 + ANDQ AX, R12 + ADDQ R9, R12 + ANDQ AX, R14 + ADDQ R11, R14 + + // Second reduction chain (carryPropagate) + MOVQ SI, BX + SHRQ $0x33, BX + MOVQ R8, DI + SHRQ $0x33, DI + MOVQ R10, R9 + SHRQ $0x33, R9 + MOVQ R12, R11 + SHRQ $0x33, R11 + MOVQ R14, R13 + SHRQ $0x33, R13 + ANDQ AX, SI + IMUL3Q $0x13, R13, R13 + ADDQ R13, SI + ANDQ AX, R8 + ADDQ BX, R8 + ANDQ AX, R10 + ADDQ DI, R10 + ANDQ AX, R12 + ADDQ R9, R12 + ANDQ AX, R14 + ADDQ R11, R14 + + // Store output + MOVQ out+0(FP), AX + MOVQ SI, (AX) + MOVQ R8, 8(AX) + MOVQ R10, 16(AX) + MOVQ R12, 24(AX) + MOVQ R14, 32(AX) + RET diff --git a/vendor/filippo.io/edwards25519/field/fe_amd64_noasm.go b/vendor/filippo.io/edwards25519/field/fe_amd64_noasm.go new file mode 100644 index 00000000..ddb6c9b8 --- /dev/null +++ b/vendor/filippo.io/edwards25519/field/fe_amd64_noasm.go @@ -0,0 +1,12 @@ +// Copyright (c) 2019 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. + +//go:build !amd64 || !gc || purego +// +build !amd64 !gc purego + +package field + +func feMul(v, x, y *Element) { feMulGeneric(v, x, y) } + +func feSquare(v, x *Element) { feSquareGeneric(v, x) } diff --git a/vendor/filippo.io/edwards25519/field/fe_arm64.go b/vendor/filippo.io/edwards25519/field/fe_arm64.go new file mode 100644 index 00000000..af459ef5 --- /dev/null +++ b/vendor/filippo.io/edwards25519/field/fe_arm64.go @@ -0,0 +1,16 @@ +// Copyright (c) 2020 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. + +//go:build arm64 && gc && !purego +// +build arm64,gc,!purego + +package field + +//go:noescape +func carryPropagate(v *Element) + +func (v *Element) carryPropagate() *Element { + carryPropagate(v) + return v +} diff --git a/vendor/filippo.io/edwards25519/field/fe_arm64.s b/vendor/filippo.io/edwards25519/field/fe_arm64.s new file mode 100644 index 00000000..3126a434 --- /dev/null +++ b/vendor/filippo.io/edwards25519/field/fe_arm64.s @@ -0,0 +1,42 @@ +// Copyright (c) 2020 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. + +//go:build arm64 && gc && !purego + +#include "textflag.h" + +// carryPropagate works exactly like carryPropagateGeneric and uses the +// same AND, ADD, and LSR+MADD instructions emitted by the compiler, but +// avoids loading R0-R4 twice and uses LDP and STP. +// +// See https://golang.org/issues/43145 for the main compiler issue. +// +// func carryPropagate(v *Element) +TEXT ·carryPropagate(SB),NOFRAME|NOSPLIT,$0-8 + MOVD v+0(FP), R20 + + LDP 0(R20), (R0, R1) + LDP 16(R20), (R2, R3) + MOVD 32(R20), R4 + + AND $0x7ffffffffffff, R0, R10 + AND $0x7ffffffffffff, R1, R11 + AND $0x7ffffffffffff, R2, R12 + AND $0x7ffffffffffff, R3, R13 + AND $0x7ffffffffffff, R4, R14 + + ADD R0>>51, R11, R11 + ADD R1>>51, R12, R12 + ADD R2>>51, R13, R13 + ADD R3>>51, R14, R14 + // R4>>51 * 19 + R10 -> R10 + LSR $51, R4, R21 + MOVD $19, R22 + MADD R22, R10, R21, R10 + + STP (R10, R11), 0(R20) + STP (R12, R13), 16(R20) + MOVD R14, 32(R20) + + RET diff --git a/vendor/filippo.io/edwards25519/field/fe_arm64_noasm.go b/vendor/filippo.io/edwards25519/field/fe_arm64_noasm.go new file mode 100644 index 00000000..234a5b2e --- /dev/null +++ b/vendor/filippo.io/edwards25519/field/fe_arm64_noasm.go @@ -0,0 +1,12 @@ +// Copyright (c) 2021 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. + +//go:build !arm64 || !gc || purego +// +build !arm64 !gc purego + +package field + +func (v *Element) carryPropagate() *Element { + return v.carryPropagateGeneric() +} diff --git a/vendor/filippo.io/edwards25519/field/fe_extra.go b/vendor/filippo.io/edwards25519/field/fe_extra.go new file mode 100644 index 00000000..1ef503b9 --- /dev/null +++ b/vendor/filippo.io/edwards25519/field/fe_extra.go @@ -0,0 +1,50 @@ +// Copyright (c) 2021 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 field + +import "errors" + +// This file contains additional functionality that is not included in the +// upstream crypto/ed25519/edwards25519/field package. + +// SetWideBytes sets v to x, where x is a 64-byte little-endian encoding, which +// is reduced modulo the field order. If x is not of the right length, +// SetWideBytes returns nil and an error, and the receiver is unchanged. +// +// SetWideBytes is not necessary to select a uniformly distributed value, and is +// only provided for compatibility: SetBytes can be used instead as the chance +// of bias is less than 2⁻²⁵⁰. +func (v *Element) SetWideBytes(x []byte) (*Element, error) { + if len(x) != 64 { + return nil, errors.New("edwards25519: invalid SetWideBytes input size") + } + + // Split the 64 bytes into two elements, and extract the most significant + // bit of each, which is ignored by SetBytes. + lo, _ := new(Element).SetBytes(x[:32]) + loMSB := uint64(x[31] >> 7) + hi, _ := new(Element).SetBytes(x[32:]) + hiMSB := uint64(x[63] >> 7) + + // The output we want is + // + // v = lo + loMSB * 2²⁵⁵ + hi * 2²⁵⁶ + hiMSB * 2⁵¹¹ + // + // which applying the reduction identity comes out to + // + // v = lo + loMSB * 19 + hi * 2 * 19 + hiMSB * 2 * 19² + // + // l0 will be the sum of a 52 bits value (lo.l0), plus a 5 bits value + // (loMSB * 19), a 6 bits value (hi.l0 * 2 * 19), and a 10 bits value + // (hiMSB * 2 * 19²), so it fits in a uint64. + + v.l0 = lo.l0 + loMSB*19 + hi.l0*2*19 + hiMSB*2*19*19 + v.l1 = lo.l1 + hi.l1*2*19 + v.l2 = lo.l2 + hi.l2*2*19 + v.l3 = lo.l3 + hi.l3*2*19 + v.l4 = lo.l4 + hi.l4*2*19 + + return v.carryPropagate(), nil +} diff --git a/vendor/filippo.io/edwards25519/field/fe_generic.go b/vendor/filippo.io/edwards25519/field/fe_generic.go new file mode 100644 index 00000000..86f5fd95 --- /dev/null +++ b/vendor/filippo.io/edwards25519/field/fe_generic.go @@ -0,0 +1,266 @@ +// Copyright (c) 2017 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 field + +import "math/bits" + +// uint128 holds a 128-bit number as two 64-bit limbs, for use with the +// bits.Mul64 and bits.Add64 intrinsics. +type uint128 struct { + lo, hi uint64 +} + +// mul64 returns a * b. +func mul64(a, b uint64) uint128 { + hi, lo := bits.Mul64(a, b) + return uint128{lo, hi} +} + +// addMul64 returns v + a * b. +func addMul64(v uint128, a, b uint64) uint128 { + hi, lo := bits.Mul64(a, b) + lo, c := bits.Add64(lo, v.lo, 0) + hi, _ = bits.Add64(hi, v.hi, c) + return uint128{lo, hi} +} + +// shiftRightBy51 returns a >> 51. a is assumed to be at most 115 bits. +func shiftRightBy51(a uint128) uint64 { + return (a.hi << (64 - 51)) | (a.lo >> 51) +} + +func feMulGeneric(v, a, b *Element) { + a0 := a.l0 + a1 := a.l1 + a2 := a.l2 + a3 := a.l3 + a4 := a.l4 + + b0 := b.l0 + b1 := b.l1 + b2 := b.l2 + b3 := b.l3 + b4 := b.l4 + + // Limb multiplication works like pen-and-paper columnar multiplication, but + // with 51-bit limbs instead of digits. + // + // a4 a3 a2 a1 a0 x + // b4 b3 b2 b1 b0 = + // ------------------------ + // a4b0 a3b0 a2b0 a1b0 a0b0 + + // a4b1 a3b1 a2b1 a1b1 a0b1 + + // a4b2 a3b2 a2b2 a1b2 a0b2 + + // a4b3 a3b3 a2b3 a1b3 a0b3 + + // a4b4 a3b4 a2b4 a1b4 a0b4 = + // ---------------------------------------------- + // r8 r7 r6 r5 r4 r3 r2 r1 r0 + // + // We can then use the reduction identity (a * 2²⁵⁵ + b = a * 19 + b) to + // reduce the limbs that would overflow 255 bits. r5 * 2²⁵⁵ becomes 19 * r5, + // r6 * 2³⁰⁶ becomes 19 * r6 * 2⁵¹, etc. + // + // Reduction can be carried out simultaneously to multiplication. For + // example, we do not compute r5: whenever the result of a multiplication + // belongs to r5, like a1b4, we multiply it by 19 and add the result to r0. + // + // a4b0 a3b0 a2b0 a1b0 a0b0 + + // a3b1 a2b1 a1b1 a0b1 19×a4b1 + + // a2b2 a1b2 a0b2 19×a4b2 19×a3b2 + + // a1b3 a0b3 19×a4b3 19×a3b3 19×a2b3 + + // a0b4 19×a4b4 19×a3b4 19×a2b4 19×a1b4 = + // -------------------------------------- + // r4 r3 r2 r1 r0 + // + // Finally we add up the columns into wide, overlapping limbs. + + a1_19 := a1 * 19 + a2_19 := a2 * 19 + a3_19 := a3 * 19 + a4_19 := a4 * 19 + + // r0 = a0×b0 + 19×(a1×b4 + a2×b3 + a3×b2 + a4×b1) + r0 := mul64(a0, b0) + r0 = addMul64(r0, a1_19, b4) + r0 = addMul64(r0, a2_19, b3) + r0 = addMul64(r0, a3_19, b2) + r0 = addMul64(r0, a4_19, b1) + + // r1 = a0×b1 + a1×b0 + 19×(a2×b4 + a3×b3 + a4×b2) + r1 := mul64(a0, b1) + r1 = addMul64(r1, a1, b0) + r1 = addMul64(r1, a2_19, b4) + r1 = addMul64(r1, a3_19, b3) + r1 = addMul64(r1, a4_19, b2) + + // r2 = a0×b2 + a1×b1 + a2×b0 + 19×(a3×b4 + a4×b3) + r2 := mul64(a0, b2) + r2 = addMul64(r2, a1, b1) + r2 = addMul64(r2, a2, b0) + r2 = addMul64(r2, a3_19, b4) + r2 = addMul64(r2, a4_19, b3) + + // r3 = a0×b3 + a1×b2 + a2×b1 + a3×b0 + 19×a4×b4 + r3 := mul64(a0, b3) + r3 = addMul64(r3, a1, b2) + r3 = addMul64(r3, a2, b1) + r3 = addMul64(r3, a3, b0) + r3 = addMul64(r3, a4_19, b4) + + // r4 = a0×b4 + a1×b3 + a2×b2 + a3×b1 + a4×b0 + r4 := mul64(a0, b4) + r4 = addMul64(r4, a1, b3) + r4 = addMul64(r4, a2, b2) + r4 = addMul64(r4, a3, b1) + r4 = addMul64(r4, a4, b0) + + // After the multiplication, we need to reduce (carry) the five coefficients + // to obtain a result with limbs that are at most slightly larger than 2⁵¹, + // to respect the Element invariant. + // + // Overall, the reduction works the same as carryPropagate, except with + // wider inputs: we take the carry for each coefficient by shifting it right + // by 51, and add it to the limb above it. The top carry is multiplied by 19 + // according to the reduction identity and added to the lowest limb. + // + // The largest coefficient (r0) will be at most 111 bits, which guarantees + // that all carries are at most 111 - 51 = 60 bits, which fits in a uint64. + // + // r0 = a0×b0 + 19×(a1×b4 + a2×b3 + a3×b2 + a4×b1) + // r0 < 2⁵²×2⁵² + 19×(2⁵²×2⁵² + 2⁵²×2⁵² + 2⁵²×2⁵² + 2⁵²×2⁵²) + // r0 < (1 + 19 × 4) × 2⁵² × 2⁵² + // r0 < 2⁷ × 2⁵² × 2⁵² + // r0 < 2¹¹¹ + // + // Moreover, the top coefficient (r4) is at most 107 bits, so c4 is at most + // 56 bits, and c4 * 19 is at most 61 bits, which again fits in a uint64 and + // allows us to easily apply the reduction identity. + // + // r4 = a0×b4 + a1×b3 + a2×b2 + a3×b1 + a4×b0 + // r4 < 5 × 2⁵² × 2⁵² + // r4 < 2¹⁰⁷ + // + + c0 := shiftRightBy51(r0) + c1 := shiftRightBy51(r1) + c2 := shiftRightBy51(r2) + c3 := shiftRightBy51(r3) + c4 := shiftRightBy51(r4) + + rr0 := r0.lo&maskLow51Bits + c4*19 + rr1 := r1.lo&maskLow51Bits + c0 + rr2 := r2.lo&maskLow51Bits + c1 + rr3 := r3.lo&maskLow51Bits + c2 + rr4 := r4.lo&maskLow51Bits + c3 + + // Now all coefficients fit into 64-bit registers but are still too large to + // be passed around as an Element. We therefore do one last carry chain, + // where the carries will be small enough to fit in the wiggle room above 2⁵¹. + *v = Element{rr0, rr1, rr2, rr3, rr4} + v.carryPropagate() +} + +func feSquareGeneric(v, a *Element) { + l0 := a.l0 + l1 := a.l1 + l2 := a.l2 + l3 := a.l3 + l4 := a.l4 + + // Squaring works precisely like multiplication above, but thanks to its + // symmetry we get to group a few terms together. + // + // l4 l3 l2 l1 l0 x + // l4 l3 l2 l1 l0 = + // ------------------------ + // l4l0 l3l0 l2l0 l1l0 l0l0 + + // l4l1 l3l1 l2l1 l1l1 l0l1 + + // l4l2 l3l2 l2l2 l1l2 l0l2 + + // l4l3 l3l3 l2l3 l1l3 l0l3 + + // l4l4 l3l4 l2l4 l1l4 l0l4 = + // ---------------------------------------------- + // r8 r7 r6 r5 r4 r3 r2 r1 r0 + // + // l4l0 l3l0 l2l0 l1l0 l0l0 + + // l3l1 l2l1 l1l1 l0l1 19×l4l1 + + // l2l2 l1l2 l0l2 19×l4l2 19×l3l2 + + // l1l3 l0l3 19×l4l3 19×l3l3 19×l2l3 + + // l0l4 19×l4l4 19×l3l4 19×l2l4 19×l1l4 = + // -------------------------------------- + // r4 r3 r2 r1 r0 + // + // With precomputed 2×, 19×, and 2×19× terms, we can compute each limb with + // only three Mul64 and four Add64, instead of five and eight. + + l0_2 := l0 * 2 + l1_2 := l1 * 2 + + l1_38 := l1 * 38 + l2_38 := l2 * 38 + l3_38 := l3 * 38 + + l3_19 := l3 * 19 + l4_19 := l4 * 19 + + // r0 = l0×l0 + 19×(l1×l4 + l2×l3 + l3×l2 + l4×l1) = l0×l0 + 19×2×(l1×l4 + l2×l3) + r0 := mul64(l0, l0) + r0 = addMul64(r0, l1_38, l4) + r0 = addMul64(r0, l2_38, l3) + + // r1 = l0×l1 + l1×l0 + 19×(l2×l4 + l3×l3 + l4×l2) = 2×l0×l1 + 19×2×l2×l4 + 19×l3×l3 + r1 := mul64(l0_2, l1) + r1 = addMul64(r1, l2_38, l4) + r1 = addMul64(r1, l3_19, l3) + + // r2 = l0×l2 + l1×l1 + l2×l0 + 19×(l3×l4 + l4×l3) = 2×l0×l2 + l1×l1 + 19×2×l3×l4 + r2 := mul64(l0_2, l2) + r2 = addMul64(r2, l1, l1) + r2 = addMul64(r2, l3_38, l4) + + // r3 = l0×l3 + l1×l2 + l2×l1 + l3×l0 + 19×l4×l4 = 2×l0×l3 + 2×l1×l2 + 19×l4×l4 + r3 := mul64(l0_2, l3) + r3 = addMul64(r3, l1_2, l2) + r3 = addMul64(r3, l4_19, l4) + + // r4 = l0×l4 + l1×l3 + l2×l2 + l3×l1 + l4×l0 = 2×l0×l4 + 2×l1×l3 + l2×l2 + r4 := mul64(l0_2, l4) + r4 = addMul64(r4, l1_2, l3) + r4 = addMul64(r4, l2, l2) + + c0 := shiftRightBy51(r0) + c1 := shiftRightBy51(r1) + c2 := shiftRightBy51(r2) + c3 := shiftRightBy51(r3) + c4 := shiftRightBy51(r4) + + rr0 := r0.lo&maskLow51Bits + c4*19 + rr1 := r1.lo&maskLow51Bits + c0 + rr2 := r2.lo&maskLow51Bits + c1 + rr3 := r3.lo&maskLow51Bits + c2 + rr4 := r4.lo&maskLow51Bits + c3 + + *v = Element{rr0, rr1, rr2, rr3, rr4} + v.carryPropagate() +} + +// carryPropagateGeneric brings the limbs below 52 bits by applying the reduction +// identity (a * 2²⁵⁵ + b = a * 19 + b) to the l4 carry. +func (v *Element) carryPropagateGeneric() *Element { + c0 := v.l0 >> 51 + c1 := v.l1 >> 51 + c2 := v.l2 >> 51 + c3 := v.l3 >> 51 + c4 := v.l4 >> 51 + + // c4 is at most 64 - 51 = 13 bits, so c4*19 is at most 18 bits, and + // the final l0 will be at most 52 bits. Similarly for the rest. + v.l0 = v.l0&maskLow51Bits + c4*19 + v.l1 = v.l1&maskLow51Bits + c0 + v.l2 = v.l2&maskLow51Bits + c1 + v.l3 = v.l3&maskLow51Bits + c2 + v.l4 = v.l4&maskLow51Bits + c3 + + return v +} diff --git a/vendor/filippo.io/edwards25519/scalar.go b/vendor/filippo.io/edwards25519/scalar.go new file mode 100644 index 00000000..3fd16538 --- /dev/null +++ b/vendor/filippo.io/edwards25519/scalar.go @@ -0,0 +1,343 @@ +// Copyright (c) 2016 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 edwards25519 + +import ( + "encoding/binary" + "errors" +) + +// A Scalar is an integer modulo +// +// l = 2^252 + 27742317777372353535851937790883648493 +// +// which is the prime order of the edwards25519 group. +// +// This type works similarly to math/big.Int, and all arguments and +// receivers are allowed to alias. +// +// The zero value is a valid zero element. +type Scalar struct { + // s is the scalar in the Montgomery domain, in the format of the + // fiat-crypto implementation. + s fiatScalarMontgomeryDomainFieldElement +} + +// The field implementation in scalar_fiat.go is generated by the fiat-crypto +// project (https://github.com/mit-plv/fiat-crypto) at version v0.0.9 (23d2dbc) +// from a formally verified model. +// +// fiat-crypto code comes under the following license. +// +// Copyright (c) 2015-2020 The fiat-crypto Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// THIS SOFTWARE IS PROVIDED BY the fiat-crypto authors "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Berkeley Software Design, +// Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// + +// NewScalar returns a new zero Scalar. +func NewScalar() *Scalar { + return &Scalar{} +} + +// MultiplyAdd sets s = x * y + z mod l, and returns s. It is equivalent to +// using Multiply and then Add. +func (s *Scalar) MultiplyAdd(x, y, z *Scalar) *Scalar { + // Make a copy of z in case it aliases s. + zCopy := new(Scalar).Set(z) + return s.Multiply(x, y).Add(s, zCopy) +} + +// Add sets s = x + y mod l, and returns s. +func (s *Scalar) Add(x, y *Scalar) *Scalar { + // s = 1 * x + y mod l + fiatScalarAdd(&s.s, &x.s, &y.s) + return s +} + +// Subtract sets s = x - y mod l, and returns s. +func (s *Scalar) Subtract(x, y *Scalar) *Scalar { + // s = -1 * y + x mod l + fiatScalarSub(&s.s, &x.s, &y.s) + return s +} + +// Negate sets s = -x mod l, and returns s. +func (s *Scalar) Negate(x *Scalar) *Scalar { + // s = -1 * x + 0 mod l + fiatScalarOpp(&s.s, &x.s) + return s +} + +// Multiply sets s = x * y mod l, and returns s. +func (s *Scalar) Multiply(x, y *Scalar) *Scalar { + // s = x * y + 0 mod l + fiatScalarMul(&s.s, &x.s, &y.s) + return s +} + +// Set sets s = x, and returns s. +func (s *Scalar) Set(x *Scalar) *Scalar { + *s = *x + return s +} + +// SetUniformBytes sets s = x mod l, where x is a 64-byte little-endian integer. +// If x is not of the right length, SetUniformBytes returns nil and an error, +// and the receiver is unchanged. +// +// SetUniformBytes can be used to set s to a uniformly distributed value given +// 64 uniformly distributed random bytes. +func (s *Scalar) SetUniformBytes(x []byte) (*Scalar, error) { + if len(x) != 64 { + return nil, errors.New("edwards25519: invalid SetUniformBytes input length") + } + + // We have a value x of 512 bits, but our fiatScalarFromBytes function + // expects an input lower than l, which is a little over 252 bits. + // + // Instead of writing a reduction function that operates on wider inputs, we + // can interpret x as the sum of three shorter values a, b, and c. + // + // x = a + b * 2^168 + c * 2^336 mod l + // + // We then precompute 2^168 and 2^336 modulo l, and perform the reduction + // with two multiplications and two additions. + + s.setShortBytes(x[:21]) + t := new(Scalar).setShortBytes(x[21:42]) + s.Add(s, t.Multiply(t, scalarTwo168)) + t.setShortBytes(x[42:]) + s.Add(s, t.Multiply(t, scalarTwo336)) + + return s, nil +} + +// scalarTwo168 and scalarTwo336 are 2^168 and 2^336 modulo l, encoded as a +// fiatScalarMontgomeryDomainFieldElement, which is a little-endian 4-limb value +// in the 2^256 Montgomery domain. +var scalarTwo168 = &Scalar{s: [4]uint64{0x5b8ab432eac74798, 0x38afddd6de59d5d7, + 0xa2c131b399411b7c, 0x6329a7ed9ce5a30}} +var scalarTwo336 = &Scalar{s: [4]uint64{0xbd3d108e2b35ecc5, 0x5c3a3718bdf9c90b, + 0x63aa97a331b4f2ee, 0x3d217f5be65cb5c}} + +// setShortBytes sets s = x mod l, where x is a little-endian integer shorter +// than 32 bytes. +func (s *Scalar) setShortBytes(x []byte) *Scalar { + if len(x) >= 32 { + panic("edwards25519: internal error: setShortBytes called with a long string") + } + var buf [32]byte + copy(buf[:], x) + fiatScalarFromBytes((*[4]uint64)(&s.s), &buf) + fiatScalarToMontgomery(&s.s, (*fiatScalarNonMontgomeryDomainFieldElement)(&s.s)) + return s +} + +// SetCanonicalBytes sets s = x, where x is a 32-byte little-endian encoding of +// s, and returns s. If x is not a canonical encoding of s, SetCanonicalBytes +// returns nil and an error, and the receiver is unchanged. +func (s *Scalar) SetCanonicalBytes(x []byte) (*Scalar, error) { + if len(x) != 32 { + return nil, errors.New("invalid scalar length") + } + if !isReduced(x) { + return nil, errors.New("invalid scalar encoding") + } + + fiatScalarFromBytes((*[4]uint64)(&s.s), (*[32]byte)(x)) + fiatScalarToMontgomery(&s.s, (*fiatScalarNonMontgomeryDomainFieldElement)(&s.s)) + + return s, nil +} + +// scalarMinusOneBytes is l - 1 in little endian. +var scalarMinusOneBytes = [32]byte{236, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16} + +// isReduced returns whether the given scalar in 32-byte little endian encoded +// form is reduced modulo l. +func isReduced(s []byte) bool { + if len(s) != 32 { + return false + } + + for i := len(s) - 1; i >= 0; i-- { + switch { + case s[i] > scalarMinusOneBytes[i]: + return false + case s[i] < scalarMinusOneBytes[i]: + return true + } + } + return true +} + +// SetBytesWithClamping applies the buffer pruning described in RFC 8032, +// Section 5.1.5 (also known as clamping) and sets s to the result. The input +// must be 32 bytes, and it is not modified. If x is not of the right length, +// SetBytesWithClamping returns nil and an error, and the receiver is unchanged. +// +// Note that since Scalar values are always reduced modulo the prime order of +// the curve, the resulting value will not preserve any of the cofactor-clearing +// properties that clamping is meant to provide. It will however work as +// expected as long as it is applied to points on the prime order subgroup, like +// in Ed25519. In fact, it is lost to history why RFC 8032 adopted the +// irrelevant RFC 7748 clamping, but it is now required for compatibility. +func (s *Scalar) SetBytesWithClamping(x []byte) (*Scalar, error) { + // The description above omits the purpose of the high bits of the clamping + // for brevity, but those are also lost to reductions, and are also + // irrelevant to edwards25519 as they protect against a specific + // implementation bug that was once observed in a generic Montgomery ladder. + if len(x) != 32 { + return nil, errors.New("edwards25519: invalid SetBytesWithClamping input length") + } + + // We need to use the wide reduction from SetUniformBytes, since clamping + // sets the 2^254 bit, making the value higher than the order. + var wideBytes [64]byte + copy(wideBytes[:], x[:]) + wideBytes[0] &= 248 + wideBytes[31] &= 63 + wideBytes[31] |= 64 + return s.SetUniformBytes(wideBytes[:]) +} + +// Bytes returns the canonical 32-byte little-endian encoding of s. +func (s *Scalar) Bytes() []byte { + // This function is outlined to make the allocations inline in the caller + // rather than happen on the heap. + var encoded [32]byte + return s.bytes(&encoded) +} + +func (s *Scalar) bytes(out *[32]byte) []byte { + var ss fiatScalarNonMontgomeryDomainFieldElement + fiatScalarFromMontgomery(&ss, &s.s) + fiatScalarToBytes(out, (*[4]uint64)(&ss)) + return out[:] +} + +// Equal returns 1 if s and t are equal, and 0 otherwise. +func (s *Scalar) Equal(t *Scalar) int { + var diff fiatScalarMontgomeryDomainFieldElement + fiatScalarSub(&diff, &s.s, &t.s) + var nonzero uint64 + fiatScalarNonzero(&nonzero, (*[4]uint64)(&diff)) + nonzero |= nonzero >> 32 + nonzero |= nonzero >> 16 + nonzero |= nonzero >> 8 + nonzero |= nonzero >> 4 + nonzero |= nonzero >> 2 + nonzero |= nonzero >> 1 + return int(^nonzero) & 1 +} + +// nonAdjacentForm computes a width-w non-adjacent form for this scalar. +// +// w must be between 2 and 8, or nonAdjacentForm will panic. +func (s *Scalar) nonAdjacentForm(w uint) [256]int8 { + // This implementation is adapted from the one + // in curve25519-dalek and is documented there: + // https://github.com/dalek-cryptography/curve25519-dalek/blob/f630041af28e9a405255f98a8a93adca18e4315b/src/scalar.rs#L800-L871 + b := s.Bytes() + if b[31] > 127 { + panic("scalar has high bit set illegally") + } + if w < 2 { + panic("w must be at least 2 by the definition of NAF") + } else if w > 8 { + panic("NAF digits must fit in int8") + } + + var naf [256]int8 + var digits [5]uint64 + + for i := 0; i < 4; i++ { + digits[i] = binary.LittleEndian.Uint64(b[i*8:]) + } + + width := uint64(1 << w) + windowMask := uint64(width - 1) + + pos := uint(0) + carry := uint64(0) + for pos < 256 { + indexU64 := pos / 64 + indexBit := pos % 64 + var bitBuf uint64 + if indexBit < 64-w { + // This window's bits are contained in a single u64 + bitBuf = digits[indexU64] >> indexBit + } else { + // Combine the current 64 bits with bits from the next 64 + bitBuf = (digits[indexU64] >> indexBit) | (digits[1+indexU64] << (64 - indexBit)) + } + + // Add carry into the current window + window := carry + (bitBuf & windowMask) + + if window&1 == 0 { + // If the window value is even, preserve the carry and continue. + // Why is the carry preserved? + // If carry == 0 and window & 1 == 0, + // then the next carry should be 0 + // If carry == 1 and window & 1 == 0, + // then bit_buf & 1 == 1 so the next carry should be 1 + pos += 1 + continue + } + + if window < width/2 { + carry = 0 + naf[pos] = int8(window) + } else { + carry = 1 + naf[pos] = int8(window) - int8(width) + } + + pos += w + } + return naf +} + +func (s *Scalar) signedRadix16() [64]int8 { + b := s.Bytes() + if b[31] > 127 { + panic("scalar has high bit set illegally") + } + + var digits [64]int8 + + // Compute unsigned radix-16 digits: + for i := 0; i < 32; i++ { + digits[2*i] = int8(b[i] & 15) + digits[2*i+1] = int8((b[i] >> 4) & 15) + } + + // Recenter coefficients: + for i := 0; i < 63; i++ { + carry := (digits[i] + 8) >> 4 + digits[i] -= carry << 4 + digits[i+1] += carry + } + + return digits +} diff --git a/vendor/filippo.io/edwards25519/scalar_fiat.go b/vendor/filippo.io/edwards25519/scalar_fiat.go new file mode 100644 index 00000000..2e5782b6 --- /dev/null +++ b/vendor/filippo.io/edwards25519/scalar_fiat.go @@ -0,0 +1,1147 @@ +// Code generated by Fiat Cryptography. DO NOT EDIT. +// +// Autogenerated: word_by_word_montgomery --lang Go --cmovznz-by-mul --relax-primitive-carry-to-bitwidth 32,64 --public-function-case camelCase --public-type-case camelCase --private-function-case camelCase --private-type-case camelCase --doc-text-before-function-name '' --doc-newline-before-package-declaration --doc-prepend-header 'Code generated by Fiat Cryptography. DO NOT EDIT.' --package-name edwards25519 Scalar 64 '2^252 + 27742317777372353535851937790883648493' mul add sub opp nonzero from_montgomery to_montgomery to_bytes from_bytes +// +// curve description: Scalar +// +// machine_wordsize = 64 (from "64") +// +// requested operations: mul, add, sub, opp, nonzero, from_montgomery, to_montgomery, to_bytes, from_bytes +// +// m = 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed (from "2^252 + 27742317777372353535851937790883648493") +// +// +// +// NOTE: In addition to the bounds specified above each function, all +// +// functions synthesized for this Montgomery arithmetic require the +// +// input to be strictly less than the prime modulus (m), and also +// +// require the input to be in the unique saturated representation. +// +// All functions also ensure that these two properties are true of +// +// return values. +// +// +// +// Computed values: +// +// eval z = z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) +// +// bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) +// +// twos_complement_eval z = let x1 := z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) in +// +// if x1 & (2^256-1) < 2^255 then x1 & (2^256-1) else (x1 & (2^256-1)) - 2^256 + +package edwards25519 + +import "math/bits" + +type fiatScalarUint1 uint64 // We use uint64 instead of a more narrow type for performance reasons; see https://github.com/mit-plv/fiat-crypto/pull/1006#issuecomment-892625927 +type fiatScalarInt1 int64 // We use uint64 instead of a more narrow type for performance reasons; see https://github.com/mit-plv/fiat-crypto/pull/1006#issuecomment-892625927 + +// The type fiatScalarMontgomeryDomainFieldElement is a field element in the Montgomery domain. +// +// Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] +type fiatScalarMontgomeryDomainFieldElement [4]uint64 + +// The type fiatScalarNonMontgomeryDomainFieldElement is a field element NOT in the Montgomery domain. +// +// Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] +type fiatScalarNonMontgomeryDomainFieldElement [4]uint64 + +// fiatScalarCmovznzU64 is a single-word conditional move. +// +// Postconditions: +// +// out1 = (if arg1 = 0 then arg2 else arg3) +// +// Input Bounds: +// +// arg1: [0x0 ~> 0x1] +// arg2: [0x0 ~> 0xffffffffffffffff] +// arg3: [0x0 ~> 0xffffffffffffffff] +// +// Output Bounds: +// +// out1: [0x0 ~> 0xffffffffffffffff] +func fiatScalarCmovznzU64(out1 *uint64, arg1 fiatScalarUint1, arg2 uint64, arg3 uint64) { + x1 := (uint64(arg1) * 0xffffffffffffffff) + x2 := ((x1 & arg3) | ((^x1) & arg2)) + *out1 = x2 +} + +// fiatScalarMul multiplies two field elements in the Montgomery domain. +// +// Preconditions: +// +// 0 ≤ eval arg1 < m +// 0 ≤ eval arg2 < m +// +// Postconditions: +// +// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m +// 0 ≤ eval out1 < m +func fiatScalarMul(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement, arg2 *fiatScalarMontgomeryDomainFieldElement) { + x1 := arg1[1] + x2 := arg1[2] + x3 := arg1[3] + x4 := arg1[0] + var x5 uint64 + var x6 uint64 + x6, x5 = bits.Mul64(x4, arg2[3]) + var x7 uint64 + var x8 uint64 + x8, x7 = bits.Mul64(x4, arg2[2]) + var x9 uint64 + var x10 uint64 + x10, x9 = bits.Mul64(x4, arg2[1]) + var x11 uint64 + var x12 uint64 + x12, x11 = bits.Mul64(x4, arg2[0]) + var x13 uint64 + var x14 uint64 + x13, x14 = bits.Add64(x12, x9, uint64(0x0)) + var x15 uint64 + var x16 uint64 + x15, x16 = bits.Add64(x10, x7, uint64(fiatScalarUint1(x14))) + var x17 uint64 + var x18 uint64 + x17, x18 = bits.Add64(x8, x5, uint64(fiatScalarUint1(x16))) + x19 := (uint64(fiatScalarUint1(x18)) + x6) + var x20 uint64 + _, x20 = bits.Mul64(x11, 0xd2b51da312547e1b) + var x22 uint64 + var x23 uint64 + x23, x22 = bits.Mul64(x20, 0x1000000000000000) + var x24 uint64 + var x25 uint64 + x25, x24 = bits.Mul64(x20, 0x14def9dea2f79cd6) + var x26 uint64 + var x27 uint64 + x27, x26 = bits.Mul64(x20, 0x5812631a5cf5d3ed) + var x28 uint64 + var x29 uint64 + x28, x29 = bits.Add64(x27, x24, uint64(0x0)) + x30 := (uint64(fiatScalarUint1(x29)) + x25) + var x32 uint64 + _, x32 = bits.Add64(x11, x26, uint64(0x0)) + var x33 uint64 + var x34 uint64 + x33, x34 = bits.Add64(x13, x28, uint64(fiatScalarUint1(x32))) + var x35 uint64 + var x36 uint64 + x35, x36 = bits.Add64(x15, x30, uint64(fiatScalarUint1(x34))) + var x37 uint64 + var x38 uint64 + x37, x38 = bits.Add64(x17, x22, uint64(fiatScalarUint1(x36))) + var x39 uint64 + var x40 uint64 + x39, x40 = bits.Add64(x19, x23, uint64(fiatScalarUint1(x38))) + var x41 uint64 + var x42 uint64 + x42, x41 = bits.Mul64(x1, arg2[3]) + var x43 uint64 + var x44 uint64 + x44, x43 = bits.Mul64(x1, arg2[2]) + var x45 uint64 + var x46 uint64 + x46, x45 = bits.Mul64(x1, arg2[1]) + var x47 uint64 + var x48 uint64 + x48, x47 = bits.Mul64(x1, arg2[0]) + var x49 uint64 + var x50 uint64 + x49, x50 = bits.Add64(x48, x45, uint64(0x0)) + var x51 uint64 + var x52 uint64 + x51, x52 = bits.Add64(x46, x43, uint64(fiatScalarUint1(x50))) + var x53 uint64 + var x54 uint64 + x53, x54 = bits.Add64(x44, x41, uint64(fiatScalarUint1(x52))) + x55 := (uint64(fiatScalarUint1(x54)) + x42) + var x56 uint64 + var x57 uint64 + x56, x57 = bits.Add64(x33, x47, uint64(0x0)) + var x58 uint64 + var x59 uint64 + x58, x59 = bits.Add64(x35, x49, uint64(fiatScalarUint1(x57))) + var x60 uint64 + var x61 uint64 + x60, x61 = bits.Add64(x37, x51, uint64(fiatScalarUint1(x59))) + var x62 uint64 + var x63 uint64 + x62, x63 = bits.Add64(x39, x53, uint64(fiatScalarUint1(x61))) + var x64 uint64 + var x65 uint64 + x64, x65 = bits.Add64(uint64(fiatScalarUint1(x40)), x55, uint64(fiatScalarUint1(x63))) + var x66 uint64 + _, x66 = bits.Mul64(x56, 0xd2b51da312547e1b) + var x68 uint64 + var x69 uint64 + x69, x68 = bits.Mul64(x66, 0x1000000000000000) + var x70 uint64 + var x71 uint64 + x71, x70 = bits.Mul64(x66, 0x14def9dea2f79cd6) + var x72 uint64 + var x73 uint64 + x73, x72 = bits.Mul64(x66, 0x5812631a5cf5d3ed) + var x74 uint64 + var x75 uint64 + x74, x75 = bits.Add64(x73, x70, uint64(0x0)) + x76 := (uint64(fiatScalarUint1(x75)) + x71) + var x78 uint64 + _, x78 = bits.Add64(x56, x72, uint64(0x0)) + var x79 uint64 + var x80 uint64 + x79, x80 = bits.Add64(x58, x74, uint64(fiatScalarUint1(x78))) + var x81 uint64 + var x82 uint64 + x81, x82 = bits.Add64(x60, x76, uint64(fiatScalarUint1(x80))) + var x83 uint64 + var x84 uint64 + x83, x84 = bits.Add64(x62, x68, uint64(fiatScalarUint1(x82))) + var x85 uint64 + var x86 uint64 + x85, x86 = bits.Add64(x64, x69, uint64(fiatScalarUint1(x84))) + x87 := (uint64(fiatScalarUint1(x86)) + uint64(fiatScalarUint1(x65))) + var x88 uint64 + var x89 uint64 + x89, x88 = bits.Mul64(x2, arg2[3]) + var x90 uint64 + var x91 uint64 + x91, x90 = bits.Mul64(x2, arg2[2]) + var x92 uint64 + var x93 uint64 + x93, x92 = bits.Mul64(x2, arg2[1]) + var x94 uint64 + var x95 uint64 + x95, x94 = bits.Mul64(x2, arg2[0]) + var x96 uint64 + var x97 uint64 + x96, x97 = bits.Add64(x95, x92, uint64(0x0)) + var x98 uint64 + var x99 uint64 + x98, x99 = bits.Add64(x93, x90, uint64(fiatScalarUint1(x97))) + var x100 uint64 + var x101 uint64 + x100, x101 = bits.Add64(x91, x88, uint64(fiatScalarUint1(x99))) + x102 := (uint64(fiatScalarUint1(x101)) + x89) + var x103 uint64 + var x104 uint64 + x103, x104 = bits.Add64(x79, x94, uint64(0x0)) + var x105 uint64 + var x106 uint64 + x105, x106 = bits.Add64(x81, x96, uint64(fiatScalarUint1(x104))) + var x107 uint64 + var x108 uint64 + x107, x108 = bits.Add64(x83, x98, uint64(fiatScalarUint1(x106))) + var x109 uint64 + var x110 uint64 + x109, x110 = bits.Add64(x85, x100, uint64(fiatScalarUint1(x108))) + var x111 uint64 + var x112 uint64 + x111, x112 = bits.Add64(x87, x102, uint64(fiatScalarUint1(x110))) + var x113 uint64 + _, x113 = bits.Mul64(x103, 0xd2b51da312547e1b) + var x115 uint64 + var x116 uint64 + x116, x115 = bits.Mul64(x113, 0x1000000000000000) + var x117 uint64 + var x118 uint64 + x118, x117 = bits.Mul64(x113, 0x14def9dea2f79cd6) + var x119 uint64 + var x120 uint64 + x120, x119 = bits.Mul64(x113, 0x5812631a5cf5d3ed) + var x121 uint64 + var x122 uint64 + x121, x122 = bits.Add64(x120, x117, uint64(0x0)) + x123 := (uint64(fiatScalarUint1(x122)) + x118) + var x125 uint64 + _, x125 = bits.Add64(x103, x119, uint64(0x0)) + var x126 uint64 + var x127 uint64 + x126, x127 = bits.Add64(x105, x121, uint64(fiatScalarUint1(x125))) + var x128 uint64 + var x129 uint64 + x128, x129 = bits.Add64(x107, x123, uint64(fiatScalarUint1(x127))) + var x130 uint64 + var x131 uint64 + x130, x131 = bits.Add64(x109, x115, uint64(fiatScalarUint1(x129))) + var x132 uint64 + var x133 uint64 + x132, x133 = bits.Add64(x111, x116, uint64(fiatScalarUint1(x131))) + x134 := (uint64(fiatScalarUint1(x133)) + uint64(fiatScalarUint1(x112))) + var x135 uint64 + var x136 uint64 + x136, x135 = bits.Mul64(x3, arg2[3]) + var x137 uint64 + var x138 uint64 + x138, x137 = bits.Mul64(x3, arg2[2]) + var x139 uint64 + var x140 uint64 + x140, x139 = bits.Mul64(x3, arg2[1]) + var x141 uint64 + var x142 uint64 + x142, x141 = bits.Mul64(x3, arg2[0]) + var x143 uint64 + var x144 uint64 + x143, x144 = bits.Add64(x142, x139, uint64(0x0)) + var x145 uint64 + var x146 uint64 + x145, x146 = bits.Add64(x140, x137, uint64(fiatScalarUint1(x144))) + var x147 uint64 + var x148 uint64 + x147, x148 = bits.Add64(x138, x135, uint64(fiatScalarUint1(x146))) + x149 := (uint64(fiatScalarUint1(x148)) + x136) + var x150 uint64 + var x151 uint64 + x150, x151 = bits.Add64(x126, x141, uint64(0x0)) + var x152 uint64 + var x153 uint64 + x152, x153 = bits.Add64(x128, x143, uint64(fiatScalarUint1(x151))) + var x154 uint64 + var x155 uint64 + x154, x155 = bits.Add64(x130, x145, uint64(fiatScalarUint1(x153))) + var x156 uint64 + var x157 uint64 + x156, x157 = bits.Add64(x132, x147, uint64(fiatScalarUint1(x155))) + var x158 uint64 + var x159 uint64 + x158, x159 = bits.Add64(x134, x149, uint64(fiatScalarUint1(x157))) + var x160 uint64 + _, x160 = bits.Mul64(x150, 0xd2b51da312547e1b) + var x162 uint64 + var x163 uint64 + x163, x162 = bits.Mul64(x160, 0x1000000000000000) + var x164 uint64 + var x165 uint64 + x165, x164 = bits.Mul64(x160, 0x14def9dea2f79cd6) + var x166 uint64 + var x167 uint64 + x167, x166 = bits.Mul64(x160, 0x5812631a5cf5d3ed) + var x168 uint64 + var x169 uint64 + x168, x169 = bits.Add64(x167, x164, uint64(0x0)) + x170 := (uint64(fiatScalarUint1(x169)) + x165) + var x172 uint64 + _, x172 = bits.Add64(x150, x166, uint64(0x0)) + var x173 uint64 + var x174 uint64 + x173, x174 = bits.Add64(x152, x168, uint64(fiatScalarUint1(x172))) + var x175 uint64 + var x176 uint64 + x175, x176 = bits.Add64(x154, x170, uint64(fiatScalarUint1(x174))) + var x177 uint64 + var x178 uint64 + x177, x178 = bits.Add64(x156, x162, uint64(fiatScalarUint1(x176))) + var x179 uint64 + var x180 uint64 + x179, x180 = bits.Add64(x158, x163, uint64(fiatScalarUint1(x178))) + x181 := (uint64(fiatScalarUint1(x180)) + uint64(fiatScalarUint1(x159))) + var x182 uint64 + var x183 uint64 + x182, x183 = bits.Sub64(x173, 0x5812631a5cf5d3ed, uint64(0x0)) + var x184 uint64 + var x185 uint64 + x184, x185 = bits.Sub64(x175, 0x14def9dea2f79cd6, uint64(fiatScalarUint1(x183))) + var x186 uint64 + var x187 uint64 + x186, x187 = bits.Sub64(x177, uint64(0x0), uint64(fiatScalarUint1(x185))) + var x188 uint64 + var x189 uint64 + x188, x189 = bits.Sub64(x179, 0x1000000000000000, uint64(fiatScalarUint1(x187))) + var x191 uint64 + _, x191 = bits.Sub64(x181, uint64(0x0), uint64(fiatScalarUint1(x189))) + var x192 uint64 + fiatScalarCmovznzU64(&x192, fiatScalarUint1(x191), x182, x173) + var x193 uint64 + fiatScalarCmovznzU64(&x193, fiatScalarUint1(x191), x184, x175) + var x194 uint64 + fiatScalarCmovznzU64(&x194, fiatScalarUint1(x191), x186, x177) + var x195 uint64 + fiatScalarCmovznzU64(&x195, fiatScalarUint1(x191), x188, x179) + out1[0] = x192 + out1[1] = x193 + out1[2] = x194 + out1[3] = x195 +} + +// fiatScalarAdd adds two field elements in the Montgomery domain. +// +// Preconditions: +// +// 0 ≤ eval arg1 < m +// 0 ≤ eval arg2 < m +// +// Postconditions: +// +// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m +// 0 ≤ eval out1 < m +func fiatScalarAdd(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement, arg2 *fiatScalarMontgomeryDomainFieldElement) { + var x1 uint64 + var x2 uint64 + x1, x2 = bits.Add64(arg1[0], arg2[0], uint64(0x0)) + var x3 uint64 + var x4 uint64 + x3, x4 = bits.Add64(arg1[1], arg2[1], uint64(fiatScalarUint1(x2))) + var x5 uint64 + var x6 uint64 + x5, x6 = bits.Add64(arg1[2], arg2[2], uint64(fiatScalarUint1(x4))) + var x7 uint64 + var x8 uint64 + x7, x8 = bits.Add64(arg1[3], arg2[3], uint64(fiatScalarUint1(x6))) + var x9 uint64 + var x10 uint64 + x9, x10 = bits.Sub64(x1, 0x5812631a5cf5d3ed, uint64(0x0)) + var x11 uint64 + var x12 uint64 + x11, x12 = bits.Sub64(x3, 0x14def9dea2f79cd6, uint64(fiatScalarUint1(x10))) + var x13 uint64 + var x14 uint64 + x13, x14 = bits.Sub64(x5, uint64(0x0), uint64(fiatScalarUint1(x12))) + var x15 uint64 + var x16 uint64 + x15, x16 = bits.Sub64(x7, 0x1000000000000000, uint64(fiatScalarUint1(x14))) + var x18 uint64 + _, x18 = bits.Sub64(uint64(fiatScalarUint1(x8)), uint64(0x0), uint64(fiatScalarUint1(x16))) + var x19 uint64 + fiatScalarCmovznzU64(&x19, fiatScalarUint1(x18), x9, x1) + var x20 uint64 + fiatScalarCmovznzU64(&x20, fiatScalarUint1(x18), x11, x3) + var x21 uint64 + fiatScalarCmovznzU64(&x21, fiatScalarUint1(x18), x13, x5) + var x22 uint64 + fiatScalarCmovznzU64(&x22, fiatScalarUint1(x18), x15, x7) + out1[0] = x19 + out1[1] = x20 + out1[2] = x21 + out1[3] = x22 +} + +// fiatScalarSub subtracts two field elements in the Montgomery domain. +// +// Preconditions: +// +// 0 ≤ eval arg1 < m +// 0 ≤ eval arg2 < m +// +// Postconditions: +// +// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m +// 0 ≤ eval out1 < m +func fiatScalarSub(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement, arg2 *fiatScalarMontgomeryDomainFieldElement) { + var x1 uint64 + var x2 uint64 + x1, x2 = bits.Sub64(arg1[0], arg2[0], uint64(0x0)) + var x3 uint64 + var x4 uint64 + x3, x4 = bits.Sub64(arg1[1], arg2[1], uint64(fiatScalarUint1(x2))) + var x5 uint64 + var x6 uint64 + x5, x6 = bits.Sub64(arg1[2], arg2[2], uint64(fiatScalarUint1(x4))) + var x7 uint64 + var x8 uint64 + x7, x8 = bits.Sub64(arg1[3], arg2[3], uint64(fiatScalarUint1(x6))) + var x9 uint64 + fiatScalarCmovznzU64(&x9, fiatScalarUint1(x8), uint64(0x0), 0xffffffffffffffff) + var x10 uint64 + var x11 uint64 + x10, x11 = bits.Add64(x1, (x9 & 0x5812631a5cf5d3ed), uint64(0x0)) + var x12 uint64 + var x13 uint64 + x12, x13 = bits.Add64(x3, (x9 & 0x14def9dea2f79cd6), uint64(fiatScalarUint1(x11))) + var x14 uint64 + var x15 uint64 + x14, x15 = bits.Add64(x5, uint64(0x0), uint64(fiatScalarUint1(x13))) + var x16 uint64 + x16, _ = bits.Add64(x7, (x9 & 0x1000000000000000), uint64(fiatScalarUint1(x15))) + out1[0] = x10 + out1[1] = x12 + out1[2] = x14 + out1[3] = x16 +} + +// fiatScalarOpp negates a field element in the Montgomery domain. +// +// Preconditions: +// +// 0 ≤ eval arg1 < m +// +// Postconditions: +// +// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m +// 0 ≤ eval out1 < m +func fiatScalarOpp(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement) { + var x1 uint64 + var x2 uint64 + x1, x2 = bits.Sub64(uint64(0x0), arg1[0], uint64(0x0)) + var x3 uint64 + var x4 uint64 + x3, x4 = bits.Sub64(uint64(0x0), arg1[1], uint64(fiatScalarUint1(x2))) + var x5 uint64 + var x6 uint64 + x5, x6 = bits.Sub64(uint64(0x0), arg1[2], uint64(fiatScalarUint1(x4))) + var x7 uint64 + var x8 uint64 + x7, x8 = bits.Sub64(uint64(0x0), arg1[3], uint64(fiatScalarUint1(x6))) + var x9 uint64 + fiatScalarCmovznzU64(&x9, fiatScalarUint1(x8), uint64(0x0), 0xffffffffffffffff) + var x10 uint64 + var x11 uint64 + x10, x11 = bits.Add64(x1, (x9 & 0x5812631a5cf5d3ed), uint64(0x0)) + var x12 uint64 + var x13 uint64 + x12, x13 = bits.Add64(x3, (x9 & 0x14def9dea2f79cd6), uint64(fiatScalarUint1(x11))) + var x14 uint64 + var x15 uint64 + x14, x15 = bits.Add64(x5, uint64(0x0), uint64(fiatScalarUint1(x13))) + var x16 uint64 + x16, _ = bits.Add64(x7, (x9 & 0x1000000000000000), uint64(fiatScalarUint1(x15))) + out1[0] = x10 + out1[1] = x12 + out1[2] = x14 + out1[3] = x16 +} + +// fiatScalarNonzero outputs a single non-zero word if the input is non-zero and zero otherwise. +// +// Preconditions: +// +// 0 ≤ eval arg1 < m +// +// Postconditions: +// +// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 +// +// Input Bounds: +// +// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] +// +// Output Bounds: +// +// out1: [0x0 ~> 0xffffffffffffffff] +func fiatScalarNonzero(out1 *uint64, arg1 *[4]uint64) { + x1 := (arg1[0] | (arg1[1] | (arg1[2] | arg1[3]))) + *out1 = x1 +} + +// fiatScalarFromMontgomery translates a field element out of the Montgomery domain. +// +// Preconditions: +// +// 0 ≤ eval arg1 < m +// +// Postconditions: +// +// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m +// 0 ≤ eval out1 < m +func fiatScalarFromMontgomery(out1 *fiatScalarNonMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement) { + x1 := arg1[0] + var x2 uint64 + _, x2 = bits.Mul64(x1, 0xd2b51da312547e1b) + var x4 uint64 + var x5 uint64 + x5, x4 = bits.Mul64(x2, 0x1000000000000000) + var x6 uint64 + var x7 uint64 + x7, x6 = bits.Mul64(x2, 0x14def9dea2f79cd6) + var x8 uint64 + var x9 uint64 + x9, x8 = bits.Mul64(x2, 0x5812631a5cf5d3ed) + var x10 uint64 + var x11 uint64 + x10, x11 = bits.Add64(x9, x6, uint64(0x0)) + var x13 uint64 + _, x13 = bits.Add64(x1, x8, uint64(0x0)) + var x14 uint64 + var x15 uint64 + x14, x15 = bits.Add64(uint64(0x0), x10, uint64(fiatScalarUint1(x13))) + var x16 uint64 + var x17 uint64 + x16, x17 = bits.Add64(x14, arg1[1], uint64(0x0)) + var x18 uint64 + _, x18 = bits.Mul64(x16, 0xd2b51da312547e1b) + var x20 uint64 + var x21 uint64 + x21, x20 = bits.Mul64(x18, 0x1000000000000000) + var x22 uint64 + var x23 uint64 + x23, x22 = bits.Mul64(x18, 0x14def9dea2f79cd6) + var x24 uint64 + var x25 uint64 + x25, x24 = bits.Mul64(x18, 0x5812631a5cf5d3ed) + var x26 uint64 + var x27 uint64 + x26, x27 = bits.Add64(x25, x22, uint64(0x0)) + var x29 uint64 + _, x29 = bits.Add64(x16, x24, uint64(0x0)) + var x30 uint64 + var x31 uint64 + x30, x31 = bits.Add64((uint64(fiatScalarUint1(x17)) + (uint64(fiatScalarUint1(x15)) + (uint64(fiatScalarUint1(x11)) + x7))), x26, uint64(fiatScalarUint1(x29))) + var x32 uint64 + var x33 uint64 + x32, x33 = bits.Add64(x4, (uint64(fiatScalarUint1(x27)) + x23), uint64(fiatScalarUint1(x31))) + var x34 uint64 + var x35 uint64 + x34, x35 = bits.Add64(x5, x20, uint64(fiatScalarUint1(x33))) + var x36 uint64 + var x37 uint64 + x36, x37 = bits.Add64(x30, arg1[2], uint64(0x0)) + var x38 uint64 + var x39 uint64 + x38, x39 = bits.Add64(x32, uint64(0x0), uint64(fiatScalarUint1(x37))) + var x40 uint64 + var x41 uint64 + x40, x41 = bits.Add64(x34, uint64(0x0), uint64(fiatScalarUint1(x39))) + var x42 uint64 + _, x42 = bits.Mul64(x36, 0xd2b51da312547e1b) + var x44 uint64 + var x45 uint64 + x45, x44 = bits.Mul64(x42, 0x1000000000000000) + var x46 uint64 + var x47 uint64 + x47, x46 = bits.Mul64(x42, 0x14def9dea2f79cd6) + var x48 uint64 + var x49 uint64 + x49, x48 = bits.Mul64(x42, 0x5812631a5cf5d3ed) + var x50 uint64 + var x51 uint64 + x50, x51 = bits.Add64(x49, x46, uint64(0x0)) + var x53 uint64 + _, x53 = bits.Add64(x36, x48, uint64(0x0)) + var x54 uint64 + var x55 uint64 + x54, x55 = bits.Add64(x38, x50, uint64(fiatScalarUint1(x53))) + var x56 uint64 + var x57 uint64 + x56, x57 = bits.Add64(x40, (uint64(fiatScalarUint1(x51)) + x47), uint64(fiatScalarUint1(x55))) + var x58 uint64 + var x59 uint64 + x58, x59 = bits.Add64((uint64(fiatScalarUint1(x41)) + (uint64(fiatScalarUint1(x35)) + x21)), x44, uint64(fiatScalarUint1(x57))) + var x60 uint64 + var x61 uint64 + x60, x61 = bits.Add64(x54, arg1[3], uint64(0x0)) + var x62 uint64 + var x63 uint64 + x62, x63 = bits.Add64(x56, uint64(0x0), uint64(fiatScalarUint1(x61))) + var x64 uint64 + var x65 uint64 + x64, x65 = bits.Add64(x58, uint64(0x0), uint64(fiatScalarUint1(x63))) + var x66 uint64 + _, x66 = bits.Mul64(x60, 0xd2b51da312547e1b) + var x68 uint64 + var x69 uint64 + x69, x68 = bits.Mul64(x66, 0x1000000000000000) + var x70 uint64 + var x71 uint64 + x71, x70 = bits.Mul64(x66, 0x14def9dea2f79cd6) + var x72 uint64 + var x73 uint64 + x73, x72 = bits.Mul64(x66, 0x5812631a5cf5d3ed) + var x74 uint64 + var x75 uint64 + x74, x75 = bits.Add64(x73, x70, uint64(0x0)) + var x77 uint64 + _, x77 = bits.Add64(x60, x72, uint64(0x0)) + var x78 uint64 + var x79 uint64 + x78, x79 = bits.Add64(x62, x74, uint64(fiatScalarUint1(x77))) + var x80 uint64 + var x81 uint64 + x80, x81 = bits.Add64(x64, (uint64(fiatScalarUint1(x75)) + x71), uint64(fiatScalarUint1(x79))) + var x82 uint64 + var x83 uint64 + x82, x83 = bits.Add64((uint64(fiatScalarUint1(x65)) + (uint64(fiatScalarUint1(x59)) + x45)), x68, uint64(fiatScalarUint1(x81))) + x84 := (uint64(fiatScalarUint1(x83)) + x69) + var x85 uint64 + var x86 uint64 + x85, x86 = bits.Sub64(x78, 0x5812631a5cf5d3ed, uint64(0x0)) + var x87 uint64 + var x88 uint64 + x87, x88 = bits.Sub64(x80, 0x14def9dea2f79cd6, uint64(fiatScalarUint1(x86))) + var x89 uint64 + var x90 uint64 + x89, x90 = bits.Sub64(x82, uint64(0x0), uint64(fiatScalarUint1(x88))) + var x91 uint64 + var x92 uint64 + x91, x92 = bits.Sub64(x84, 0x1000000000000000, uint64(fiatScalarUint1(x90))) + var x94 uint64 + _, x94 = bits.Sub64(uint64(0x0), uint64(0x0), uint64(fiatScalarUint1(x92))) + var x95 uint64 + fiatScalarCmovznzU64(&x95, fiatScalarUint1(x94), x85, x78) + var x96 uint64 + fiatScalarCmovznzU64(&x96, fiatScalarUint1(x94), x87, x80) + var x97 uint64 + fiatScalarCmovznzU64(&x97, fiatScalarUint1(x94), x89, x82) + var x98 uint64 + fiatScalarCmovznzU64(&x98, fiatScalarUint1(x94), x91, x84) + out1[0] = x95 + out1[1] = x96 + out1[2] = x97 + out1[3] = x98 +} + +// fiatScalarToMontgomery translates a field element into the Montgomery domain. +// +// Preconditions: +// +// 0 ≤ eval arg1 < m +// +// Postconditions: +// +// eval (from_montgomery out1) mod m = eval arg1 mod m +// 0 ≤ eval out1 < m +func fiatScalarToMontgomery(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarNonMontgomeryDomainFieldElement) { + x1 := arg1[1] + x2 := arg1[2] + x3 := arg1[3] + x4 := arg1[0] + var x5 uint64 + var x6 uint64 + x6, x5 = bits.Mul64(x4, 0x399411b7c309a3d) + var x7 uint64 + var x8 uint64 + x8, x7 = bits.Mul64(x4, 0xceec73d217f5be65) + var x9 uint64 + var x10 uint64 + x10, x9 = bits.Mul64(x4, 0xd00e1ba768859347) + var x11 uint64 + var x12 uint64 + x12, x11 = bits.Mul64(x4, 0xa40611e3449c0f01) + var x13 uint64 + var x14 uint64 + x13, x14 = bits.Add64(x12, x9, uint64(0x0)) + var x15 uint64 + var x16 uint64 + x15, x16 = bits.Add64(x10, x7, uint64(fiatScalarUint1(x14))) + var x17 uint64 + var x18 uint64 + x17, x18 = bits.Add64(x8, x5, uint64(fiatScalarUint1(x16))) + var x19 uint64 + _, x19 = bits.Mul64(x11, 0xd2b51da312547e1b) + var x21 uint64 + var x22 uint64 + x22, x21 = bits.Mul64(x19, 0x1000000000000000) + var x23 uint64 + var x24 uint64 + x24, x23 = bits.Mul64(x19, 0x14def9dea2f79cd6) + var x25 uint64 + var x26 uint64 + x26, x25 = bits.Mul64(x19, 0x5812631a5cf5d3ed) + var x27 uint64 + var x28 uint64 + x27, x28 = bits.Add64(x26, x23, uint64(0x0)) + var x30 uint64 + _, x30 = bits.Add64(x11, x25, uint64(0x0)) + var x31 uint64 + var x32 uint64 + x31, x32 = bits.Add64(x13, x27, uint64(fiatScalarUint1(x30))) + var x33 uint64 + var x34 uint64 + x33, x34 = bits.Add64(x15, (uint64(fiatScalarUint1(x28)) + x24), uint64(fiatScalarUint1(x32))) + var x35 uint64 + var x36 uint64 + x35, x36 = bits.Add64(x17, x21, uint64(fiatScalarUint1(x34))) + var x37 uint64 + var x38 uint64 + x38, x37 = bits.Mul64(x1, 0x399411b7c309a3d) + var x39 uint64 + var x40 uint64 + x40, x39 = bits.Mul64(x1, 0xceec73d217f5be65) + var x41 uint64 + var x42 uint64 + x42, x41 = bits.Mul64(x1, 0xd00e1ba768859347) + var x43 uint64 + var x44 uint64 + x44, x43 = bits.Mul64(x1, 0xa40611e3449c0f01) + var x45 uint64 + var x46 uint64 + x45, x46 = bits.Add64(x44, x41, uint64(0x0)) + var x47 uint64 + var x48 uint64 + x47, x48 = bits.Add64(x42, x39, uint64(fiatScalarUint1(x46))) + var x49 uint64 + var x50 uint64 + x49, x50 = bits.Add64(x40, x37, uint64(fiatScalarUint1(x48))) + var x51 uint64 + var x52 uint64 + x51, x52 = bits.Add64(x31, x43, uint64(0x0)) + var x53 uint64 + var x54 uint64 + x53, x54 = bits.Add64(x33, x45, uint64(fiatScalarUint1(x52))) + var x55 uint64 + var x56 uint64 + x55, x56 = bits.Add64(x35, x47, uint64(fiatScalarUint1(x54))) + var x57 uint64 + var x58 uint64 + x57, x58 = bits.Add64(((uint64(fiatScalarUint1(x36)) + (uint64(fiatScalarUint1(x18)) + x6)) + x22), x49, uint64(fiatScalarUint1(x56))) + var x59 uint64 + _, x59 = bits.Mul64(x51, 0xd2b51da312547e1b) + var x61 uint64 + var x62 uint64 + x62, x61 = bits.Mul64(x59, 0x1000000000000000) + var x63 uint64 + var x64 uint64 + x64, x63 = bits.Mul64(x59, 0x14def9dea2f79cd6) + var x65 uint64 + var x66 uint64 + x66, x65 = bits.Mul64(x59, 0x5812631a5cf5d3ed) + var x67 uint64 + var x68 uint64 + x67, x68 = bits.Add64(x66, x63, uint64(0x0)) + var x70 uint64 + _, x70 = bits.Add64(x51, x65, uint64(0x0)) + var x71 uint64 + var x72 uint64 + x71, x72 = bits.Add64(x53, x67, uint64(fiatScalarUint1(x70))) + var x73 uint64 + var x74 uint64 + x73, x74 = bits.Add64(x55, (uint64(fiatScalarUint1(x68)) + x64), uint64(fiatScalarUint1(x72))) + var x75 uint64 + var x76 uint64 + x75, x76 = bits.Add64(x57, x61, uint64(fiatScalarUint1(x74))) + var x77 uint64 + var x78 uint64 + x78, x77 = bits.Mul64(x2, 0x399411b7c309a3d) + var x79 uint64 + var x80 uint64 + x80, x79 = bits.Mul64(x2, 0xceec73d217f5be65) + var x81 uint64 + var x82 uint64 + x82, x81 = bits.Mul64(x2, 0xd00e1ba768859347) + var x83 uint64 + var x84 uint64 + x84, x83 = bits.Mul64(x2, 0xa40611e3449c0f01) + var x85 uint64 + var x86 uint64 + x85, x86 = bits.Add64(x84, x81, uint64(0x0)) + var x87 uint64 + var x88 uint64 + x87, x88 = bits.Add64(x82, x79, uint64(fiatScalarUint1(x86))) + var x89 uint64 + var x90 uint64 + x89, x90 = bits.Add64(x80, x77, uint64(fiatScalarUint1(x88))) + var x91 uint64 + var x92 uint64 + x91, x92 = bits.Add64(x71, x83, uint64(0x0)) + var x93 uint64 + var x94 uint64 + x93, x94 = bits.Add64(x73, x85, uint64(fiatScalarUint1(x92))) + var x95 uint64 + var x96 uint64 + x95, x96 = bits.Add64(x75, x87, uint64(fiatScalarUint1(x94))) + var x97 uint64 + var x98 uint64 + x97, x98 = bits.Add64(((uint64(fiatScalarUint1(x76)) + (uint64(fiatScalarUint1(x58)) + (uint64(fiatScalarUint1(x50)) + x38))) + x62), x89, uint64(fiatScalarUint1(x96))) + var x99 uint64 + _, x99 = bits.Mul64(x91, 0xd2b51da312547e1b) + var x101 uint64 + var x102 uint64 + x102, x101 = bits.Mul64(x99, 0x1000000000000000) + var x103 uint64 + var x104 uint64 + x104, x103 = bits.Mul64(x99, 0x14def9dea2f79cd6) + var x105 uint64 + var x106 uint64 + x106, x105 = bits.Mul64(x99, 0x5812631a5cf5d3ed) + var x107 uint64 + var x108 uint64 + x107, x108 = bits.Add64(x106, x103, uint64(0x0)) + var x110 uint64 + _, x110 = bits.Add64(x91, x105, uint64(0x0)) + var x111 uint64 + var x112 uint64 + x111, x112 = bits.Add64(x93, x107, uint64(fiatScalarUint1(x110))) + var x113 uint64 + var x114 uint64 + x113, x114 = bits.Add64(x95, (uint64(fiatScalarUint1(x108)) + x104), uint64(fiatScalarUint1(x112))) + var x115 uint64 + var x116 uint64 + x115, x116 = bits.Add64(x97, x101, uint64(fiatScalarUint1(x114))) + var x117 uint64 + var x118 uint64 + x118, x117 = bits.Mul64(x3, 0x399411b7c309a3d) + var x119 uint64 + var x120 uint64 + x120, x119 = bits.Mul64(x3, 0xceec73d217f5be65) + var x121 uint64 + var x122 uint64 + x122, x121 = bits.Mul64(x3, 0xd00e1ba768859347) + var x123 uint64 + var x124 uint64 + x124, x123 = bits.Mul64(x3, 0xa40611e3449c0f01) + var x125 uint64 + var x126 uint64 + x125, x126 = bits.Add64(x124, x121, uint64(0x0)) + var x127 uint64 + var x128 uint64 + x127, x128 = bits.Add64(x122, x119, uint64(fiatScalarUint1(x126))) + var x129 uint64 + var x130 uint64 + x129, x130 = bits.Add64(x120, x117, uint64(fiatScalarUint1(x128))) + var x131 uint64 + var x132 uint64 + x131, x132 = bits.Add64(x111, x123, uint64(0x0)) + var x133 uint64 + var x134 uint64 + x133, x134 = bits.Add64(x113, x125, uint64(fiatScalarUint1(x132))) + var x135 uint64 + var x136 uint64 + x135, x136 = bits.Add64(x115, x127, uint64(fiatScalarUint1(x134))) + var x137 uint64 + var x138 uint64 + x137, x138 = bits.Add64(((uint64(fiatScalarUint1(x116)) + (uint64(fiatScalarUint1(x98)) + (uint64(fiatScalarUint1(x90)) + x78))) + x102), x129, uint64(fiatScalarUint1(x136))) + var x139 uint64 + _, x139 = bits.Mul64(x131, 0xd2b51da312547e1b) + var x141 uint64 + var x142 uint64 + x142, x141 = bits.Mul64(x139, 0x1000000000000000) + var x143 uint64 + var x144 uint64 + x144, x143 = bits.Mul64(x139, 0x14def9dea2f79cd6) + var x145 uint64 + var x146 uint64 + x146, x145 = bits.Mul64(x139, 0x5812631a5cf5d3ed) + var x147 uint64 + var x148 uint64 + x147, x148 = bits.Add64(x146, x143, uint64(0x0)) + var x150 uint64 + _, x150 = bits.Add64(x131, x145, uint64(0x0)) + var x151 uint64 + var x152 uint64 + x151, x152 = bits.Add64(x133, x147, uint64(fiatScalarUint1(x150))) + var x153 uint64 + var x154 uint64 + x153, x154 = bits.Add64(x135, (uint64(fiatScalarUint1(x148)) + x144), uint64(fiatScalarUint1(x152))) + var x155 uint64 + var x156 uint64 + x155, x156 = bits.Add64(x137, x141, uint64(fiatScalarUint1(x154))) + x157 := ((uint64(fiatScalarUint1(x156)) + (uint64(fiatScalarUint1(x138)) + (uint64(fiatScalarUint1(x130)) + x118))) + x142) + var x158 uint64 + var x159 uint64 + x158, x159 = bits.Sub64(x151, 0x5812631a5cf5d3ed, uint64(0x0)) + var x160 uint64 + var x161 uint64 + x160, x161 = bits.Sub64(x153, 0x14def9dea2f79cd6, uint64(fiatScalarUint1(x159))) + var x162 uint64 + var x163 uint64 + x162, x163 = bits.Sub64(x155, uint64(0x0), uint64(fiatScalarUint1(x161))) + var x164 uint64 + var x165 uint64 + x164, x165 = bits.Sub64(x157, 0x1000000000000000, uint64(fiatScalarUint1(x163))) + var x167 uint64 + _, x167 = bits.Sub64(uint64(0x0), uint64(0x0), uint64(fiatScalarUint1(x165))) + var x168 uint64 + fiatScalarCmovznzU64(&x168, fiatScalarUint1(x167), x158, x151) + var x169 uint64 + fiatScalarCmovznzU64(&x169, fiatScalarUint1(x167), x160, x153) + var x170 uint64 + fiatScalarCmovznzU64(&x170, fiatScalarUint1(x167), x162, x155) + var x171 uint64 + fiatScalarCmovznzU64(&x171, fiatScalarUint1(x167), x164, x157) + out1[0] = x168 + out1[1] = x169 + out1[2] = x170 + out1[3] = x171 +} + +// fiatScalarToBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. +// +// Preconditions: +// +// 0 ≤ eval arg1 < m +// +// Postconditions: +// +// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] +// +// Input Bounds: +// +// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x1fffffffffffffff]] +// +// Output Bounds: +// +// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x1f]] +func fiatScalarToBytes(out1 *[32]uint8, arg1 *[4]uint64) { + x1 := arg1[3] + x2 := arg1[2] + x3 := arg1[1] + x4 := arg1[0] + x5 := (uint8(x4) & 0xff) + x6 := (x4 >> 8) + x7 := (uint8(x6) & 0xff) + x8 := (x6 >> 8) + x9 := (uint8(x8) & 0xff) + x10 := (x8 >> 8) + x11 := (uint8(x10) & 0xff) + x12 := (x10 >> 8) + x13 := (uint8(x12) & 0xff) + x14 := (x12 >> 8) + x15 := (uint8(x14) & 0xff) + x16 := (x14 >> 8) + x17 := (uint8(x16) & 0xff) + x18 := uint8((x16 >> 8)) + x19 := (uint8(x3) & 0xff) + x20 := (x3 >> 8) + x21 := (uint8(x20) & 0xff) + x22 := (x20 >> 8) + x23 := (uint8(x22) & 0xff) + x24 := (x22 >> 8) + x25 := (uint8(x24) & 0xff) + x26 := (x24 >> 8) + x27 := (uint8(x26) & 0xff) + x28 := (x26 >> 8) + x29 := (uint8(x28) & 0xff) + x30 := (x28 >> 8) + x31 := (uint8(x30) & 0xff) + x32 := uint8((x30 >> 8)) + x33 := (uint8(x2) & 0xff) + x34 := (x2 >> 8) + x35 := (uint8(x34) & 0xff) + x36 := (x34 >> 8) + x37 := (uint8(x36) & 0xff) + x38 := (x36 >> 8) + x39 := (uint8(x38) & 0xff) + x40 := (x38 >> 8) + x41 := (uint8(x40) & 0xff) + x42 := (x40 >> 8) + x43 := (uint8(x42) & 0xff) + x44 := (x42 >> 8) + x45 := (uint8(x44) & 0xff) + x46 := uint8((x44 >> 8)) + x47 := (uint8(x1) & 0xff) + x48 := (x1 >> 8) + x49 := (uint8(x48) & 0xff) + x50 := (x48 >> 8) + x51 := (uint8(x50) & 0xff) + x52 := (x50 >> 8) + x53 := (uint8(x52) & 0xff) + x54 := (x52 >> 8) + x55 := (uint8(x54) & 0xff) + x56 := (x54 >> 8) + x57 := (uint8(x56) & 0xff) + x58 := (x56 >> 8) + x59 := (uint8(x58) & 0xff) + x60 := uint8((x58 >> 8)) + out1[0] = x5 + out1[1] = x7 + out1[2] = x9 + out1[3] = x11 + out1[4] = x13 + out1[5] = x15 + out1[6] = x17 + out1[7] = x18 + out1[8] = x19 + out1[9] = x21 + out1[10] = x23 + out1[11] = x25 + out1[12] = x27 + out1[13] = x29 + out1[14] = x31 + out1[15] = x32 + out1[16] = x33 + out1[17] = x35 + out1[18] = x37 + out1[19] = x39 + out1[20] = x41 + out1[21] = x43 + out1[22] = x45 + out1[23] = x46 + out1[24] = x47 + out1[25] = x49 + out1[26] = x51 + out1[27] = x53 + out1[28] = x55 + out1[29] = x57 + out1[30] = x59 + out1[31] = x60 +} + +// fiatScalarFromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. +// +// Preconditions: +// +// 0 ≤ bytes_eval arg1 < m +// +// Postconditions: +// +// eval out1 mod m = bytes_eval arg1 mod m +// 0 ≤ eval out1 < m +// +// Input Bounds: +// +// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x1f]] +// +// Output Bounds: +// +// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x1fffffffffffffff]] +func fiatScalarFromBytes(out1 *[4]uint64, arg1 *[32]uint8) { + x1 := (uint64(arg1[31]) << 56) + x2 := (uint64(arg1[30]) << 48) + x3 := (uint64(arg1[29]) << 40) + x4 := (uint64(arg1[28]) << 32) + x5 := (uint64(arg1[27]) << 24) + x6 := (uint64(arg1[26]) << 16) + x7 := (uint64(arg1[25]) << 8) + x8 := arg1[24] + x9 := (uint64(arg1[23]) << 56) + x10 := (uint64(arg1[22]) << 48) + x11 := (uint64(arg1[21]) << 40) + x12 := (uint64(arg1[20]) << 32) + x13 := (uint64(arg1[19]) << 24) + x14 := (uint64(arg1[18]) << 16) + x15 := (uint64(arg1[17]) << 8) + x16 := arg1[16] + x17 := (uint64(arg1[15]) << 56) + x18 := (uint64(arg1[14]) << 48) + x19 := (uint64(arg1[13]) << 40) + x20 := (uint64(arg1[12]) << 32) + x21 := (uint64(arg1[11]) << 24) + x22 := (uint64(arg1[10]) << 16) + x23 := (uint64(arg1[9]) << 8) + x24 := arg1[8] + x25 := (uint64(arg1[7]) << 56) + x26 := (uint64(arg1[6]) << 48) + x27 := (uint64(arg1[5]) << 40) + x28 := (uint64(arg1[4]) << 32) + x29 := (uint64(arg1[3]) << 24) + x30 := (uint64(arg1[2]) << 16) + x31 := (uint64(arg1[1]) << 8) + x32 := arg1[0] + x33 := (x31 + uint64(x32)) + x34 := (x30 + x33) + x35 := (x29 + x34) + x36 := (x28 + x35) + x37 := (x27 + x36) + x38 := (x26 + x37) + x39 := (x25 + x38) + x40 := (x23 + uint64(x24)) + x41 := (x22 + x40) + x42 := (x21 + x41) + x43 := (x20 + x42) + x44 := (x19 + x43) + x45 := (x18 + x44) + x46 := (x17 + x45) + x47 := (x15 + uint64(x16)) + x48 := (x14 + x47) + x49 := (x13 + x48) + x50 := (x12 + x49) + x51 := (x11 + x50) + x52 := (x10 + x51) + x53 := (x9 + x52) + x54 := (x7 + uint64(x8)) + x55 := (x6 + x54) + x56 := (x5 + x55) + x57 := (x4 + x56) + x58 := (x3 + x57) + x59 := (x2 + x58) + x60 := (x1 + x59) + out1[0] = x39 + out1[1] = x46 + out1[2] = x53 + out1[3] = x60 +} diff --git a/vendor/filippo.io/edwards25519/scalarmult.go b/vendor/filippo.io/edwards25519/scalarmult.go new file mode 100644 index 00000000..f7ca3cef --- /dev/null +++ b/vendor/filippo.io/edwards25519/scalarmult.go @@ -0,0 +1,214 @@ +// Copyright (c) 2019 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 edwards25519 + +import "sync" + +// basepointTable is a set of 32 affineLookupTables, where table i is generated +// from 256i * basepoint. It is precomputed the first time it's used. +func basepointTable() *[32]affineLookupTable { + basepointTablePrecomp.initOnce.Do(func() { + p := NewGeneratorPoint() + for i := 0; i < 32; i++ { + basepointTablePrecomp.table[i].FromP3(p) + for j := 0; j < 8; j++ { + p.Add(p, p) + } + } + }) + return &basepointTablePrecomp.table +} + +var basepointTablePrecomp struct { + table [32]affineLookupTable + initOnce sync.Once +} + +// ScalarBaseMult sets v = x * B, where B is the canonical generator, and +// returns v. +// +// The scalar multiplication is done in constant time. +func (v *Point) ScalarBaseMult(x *Scalar) *Point { + basepointTable := basepointTable() + + // Write x = sum(x_i * 16^i) so x*B = sum( B*x_i*16^i ) + // as described in the Ed25519 paper + // + // Group even and odd coefficients + // x*B = x_0*16^0*B + x_2*16^2*B + ... + x_62*16^62*B + // + x_1*16^1*B + x_3*16^3*B + ... + x_63*16^63*B + // x*B = x_0*16^0*B + x_2*16^2*B + ... + x_62*16^62*B + // + 16*( x_1*16^0*B + x_3*16^2*B + ... + x_63*16^62*B) + // + // We use a lookup table for each i to get x_i*16^(2*i)*B + // and do four doublings to multiply by 16. + digits := x.signedRadix16() + + multiple := &affineCached{} + tmp1 := &projP1xP1{} + tmp2 := &projP2{} + + // Accumulate the odd components first + v.Set(NewIdentityPoint()) + for i := 1; i < 64; i += 2 { + basepointTable[i/2].SelectInto(multiple, digits[i]) + tmp1.AddAffine(v, multiple) + v.fromP1xP1(tmp1) + } + + // Multiply by 16 + tmp2.FromP3(v) // tmp2 = v in P2 coords + tmp1.Double(tmp2) // tmp1 = 2*v in P1xP1 coords + tmp2.FromP1xP1(tmp1) // tmp2 = 2*v in P2 coords + tmp1.Double(tmp2) // tmp1 = 4*v in P1xP1 coords + tmp2.FromP1xP1(tmp1) // tmp2 = 4*v in P2 coords + tmp1.Double(tmp2) // tmp1 = 8*v in P1xP1 coords + tmp2.FromP1xP1(tmp1) // tmp2 = 8*v in P2 coords + tmp1.Double(tmp2) // tmp1 = 16*v in P1xP1 coords + v.fromP1xP1(tmp1) // now v = 16*(odd components) + + // Accumulate the even components + for i := 0; i < 64; i += 2 { + basepointTable[i/2].SelectInto(multiple, digits[i]) + tmp1.AddAffine(v, multiple) + v.fromP1xP1(tmp1) + } + + return v +} + +// ScalarMult sets v = x * q, and returns v. +// +// The scalar multiplication is done in constant time. +func (v *Point) ScalarMult(x *Scalar, q *Point) *Point { + checkInitialized(q) + + var table projLookupTable + table.FromP3(q) + + // Write x = sum(x_i * 16^i) + // so x*Q = sum( Q*x_i*16^i ) + // = Q*x_0 + 16*(Q*x_1 + 16*( ... + Q*x_63) ... ) + // <------compute inside out--------- + // + // We use the lookup table to get the x_i*Q values + // and do four doublings to compute 16*Q + digits := x.signedRadix16() + + // Unwrap first loop iteration to save computing 16*identity + multiple := &projCached{} + tmp1 := &projP1xP1{} + tmp2 := &projP2{} + table.SelectInto(multiple, digits[63]) + + v.Set(NewIdentityPoint()) + tmp1.Add(v, multiple) // tmp1 = x_63*Q in P1xP1 coords + for i := 62; i >= 0; i-- { + tmp2.FromP1xP1(tmp1) // tmp2 = (prev) in P2 coords + tmp1.Double(tmp2) // tmp1 = 2*(prev) in P1xP1 coords + tmp2.FromP1xP1(tmp1) // tmp2 = 2*(prev) in P2 coords + tmp1.Double(tmp2) // tmp1 = 4*(prev) in P1xP1 coords + tmp2.FromP1xP1(tmp1) // tmp2 = 4*(prev) in P2 coords + tmp1.Double(tmp2) // tmp1 = 8*(prev) in P1xP1 coords + tmp2.FromP1xP1(tmp1) // tmp2 = 8*(prev) in P2 coords + tmp1.Double(tmp2) // tmp1 = 16*(prev) in P1xP1 coords + v.fromP1xP1(tmp1) // v = 16*(prev) in P3 coords + table.SelectInto(multiple, digits[i]) + tmp1.Add(v, multiple) // tmp1 = x_i*Q + 16*(prev) in P1xP1 coords + } + v.fromP1xP1(tmp1) + return v +} + +// basepointNafTable is the nafLookupTable8 for the basepoint. +// It is precomputed the first time it's used. +func basepointNafTable() *nafLookupTable8 { + basepointNafTablePrecomp.initOnce.Do(func() { + basepointNafTablePrecomp.table.FromP3(NewGeneratorPoint()) + }) + return &basepointNafTablePrecomp.table +} + +var basepointNafTablePrecomp struct { + table nafLookupTable8 + initOnce sync.Once +} + +// VarTimeDoubleScalarBaseMult sets v = a * A + b * B, where B is the canonical +// generator, and returns v. +// +// Execution time depends on the inputs. +func (v *Point) VarTimeDoubleScalarBaseMult(a *Scalar, A *Point, b *Scalar) *Point { + checkInitialized(A) + + // Similarly to the single variable-base approach, we compute + // digits and use them with a lookup table. However, because + // we are allowed to do variable-time operations, we don't + // need constant-time lookups or constant-time digit + // computations. + // + // So we use a non-adjacent form of some width w instead of + // radix 16. This is like a binary representation (one digit + // for each binary place) but we allow the digits to grow in + // magnitude up to 2^{w-1} so that the nonzero digits are as + // sparse as possible. Intuitively, this "condenses" the + // "mass" of the scalar onto sparse coefficients (meaning + // fewer additions). + + basepointNafTable := basepointNafTable() + var aTable nafLookupTable5 + aTable.FromP3(A) + // Because the basepoint is fixed, we can use a wider NAF + // corresponding to a bigger table. + aNaf := a.nonAdjacentForm(5) + bNaf := b.nonAdjacentForm(8) + + // Find the first nonzero coefficient. + i := 255 + for j := i; j >= 0; j-- { + if aNaf[j] != 0 || bNaf[j] != 0 { + break + } + } + + multA := &projCached{} + multB := &affineCached{} + tmp1 := &projP1xP1{} + tmp2 := &projP2{} + tmp2.Zero() + + // Move from high to low bits, doubling the accumulator + // at each iteration and checking whether there is a nonzero + // coefficient to look up a multiple of. + for ; i >= 0; i-- { + tmp1.Double(tmp2) + + // Only update v if we have a nonzero coeff to add in. + if aNaf[i] > 0 { + v.fromP1xP1(tmp1) + aTable.SelectInto(multA, aNaf[i]) + tmp1.Add(v, multA) + } else if aNaf[i] < 0 { + v.fromP1xP1(tmp1) + aTable.SelectInto(multA, -aNaf[i]) + tmp1.Sub(v, multA) + } + + if bNaf[i] > 0 { + v.fromP1xP1(tmp1) + basepointNafTable.SelectInto(multB, bNaf[i]) + tmp1.AddAffine(v, multB) + } else if bNaf[i] < 0 { + v.fromP1xP1(tmp1) + basepointNafTable.SelectInto(multB, -bNaf[i]) + tmp1.SubAffine(v, multB) + } + + tmp2.FromP1xP1(tmp1) + } + + v.fromP2(tmp2) + return v +} diff --git a/vendor/filippo.io/edwards25519/tables.go b/vendor/filippo.io/edwards25519/tables.go new file mode 100644 index 00000000..83234bbc --- /dev/null +++ b/vendor/filippo.io/edwards25519/tables.go @@ -0,0 +1,129 @@ +// Copyright (c) 2019 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 edwards25519 + +import ( + "crypto/subtle" +) + +// A dynamic lookup table for variable-base, constant-time scalar muls. +type projLookupTable struct { + points [8]projCached +} + +// A precomputed lookup table for fixed-base, constant-time scalar muls. +type affineLookupTable struct { + points [8]affineCached +} + +// A dynamic lookup table for variable-base, variable-time scalar muls. +type nafLookupTable5 struct { + points [8]projCached +} + +// A precomputed lookup table for fixed-base, variable-time scalar muls. +type nafLookupTable8 struct { + points [64]affineCached +} + +// Constructors. + +// Builds a lookup table at runtime. Fast. +func (v *projLookupTable) FromP3(q *Point) { + // Goal: v.points[i] = (i+1)*Q, i.e., Q, 2Q, ..., 8Q + // This allows lookup of -8Q, ..., -Q, 0, Q, ..., 8Q + v.points[0].FromP3(q) + tmpP3 := Point{} + tmpP1xP1 := projP1xP1{} + for i := 0; i < 7; i++ { + // Compute (i+1)*Q as Q + i*Q and convert to a projCached + // This is needlessly complicated because the API has explicit + // receivers instead of creating stack objects and relying on RVO + v.points[i+1].FromP3(tmpP3.fromP1xP1(tmpP1xP1.Add(q, &v.points[i]))) + } +} + +// This is not optimised for speed; fixed-base tables should be precomputed. +func (v *affineLookupTable) FromP3(q *Point) { + // Goal: v.points[i] = (i+1)*Q, i.e., Q, 2Q, ..., 8Q + // This allows lookup of -8Q, ..., -Q, 0, Q, ..., 8Q + v.points[0].FromP3(q) + tmpP3 := Point{} + tmpP1xP1 := projP1xP1{} + for i := 0; i < 7; i++ { + // Compute (i+1)*Q as Q + i*Q and convert to affineCached + v.points[i+1].FromP3(tmpP3.fromP1xP1(tmpP1xP1.AddAffine(q, &v.points[i]))) + } +} + +// Builds a lookup table at runtime. Fast. +func (v *nafLookupTable5) FromP3(q *Point) { + // Goal: v.points[i] = (2*i+1)*Q, i.e., Q, 3Q, 5Q, ..., 15Q + // This allows lookup of -15Q, ..., -3Q, -Q, 0, Q, 3Q, ..., 15Q + v.points[0].FromP3(q) + q2 := Point{} + q2.Add(q, q) + tmpP3 := Point{} + tmpP1xP1 := projP1xP1{} + for i := 0; i < 7; i++ { + v.points[i+1].FromP3(tmpP3.fromP1xP1(tmpP1xP1.Add(&q2, &v.points[i]))) + } +} + +// This is not optimised for speed; fixed-base tables should be precomputed. +func (v *nafLookupTable8) FromP3(q *Point) { + v.points[0].FromP3(q) + q2 := Point{} + q2.Add(q, q) + tmpP3 := Point{} + tmpP1xP1 := projP1xP1{} + for i := 0; i < 63; i++ { + v.points[i+1].FromP3(tmpP3.fromP1xP1(tmpP1xP1.AddAffine(&q2, &v.points[i]))) + } +} + +// Selectors. + +// Set dest to x*Q, where -8 <= x <= 8, in constant time. +func (v *projLookupTable) SelectInto(dest *projCached, x int8) { + // Compute xabs = |x| + xmask := x >> 7 + xabs := uint8((x + xmask) ^ xmask) + + dest.Zero() + for j := 1; j <= 8; j++ { + // Set dest = j*Q if |x| = j + cond := subtle.ConstantTimeByteEq(xabs, uint8(j)) + dest.Select(&v.points[j-1], dest, cond) + } + // Now dest = |x|*Q, conditionally negate to get x*Q + dest.CondNeg(int(xmask & 1)) +} + +// Set dest to x*Q, where -8 <= x <= 8, in constant time. +func (v *affineLookupTable) SelectInto(dest *affineCached, x int8) { + // Compute xabs = |x| + xmask := x >> 7 + xabs := uint8((x + xmask) ^ xmask) + + dest.Zero() + for j := 1; j <= 8; j++ { + // Set dest = j*Q if |x| = j + cond := subtle.ConstantTimeByteEq(xabs, uint8(j)) + dest.Select(&v.points[j-1], dest, cond) + } + // Now dest = |x|*Q, conditionally negate to get x*Q + dest.CondNeg(int(xmask & 1)) +} + +// Given odd x with 0 < x < 2^4, return x*Q (in variable time). +func (v *nafLookupTable5) SelectInto(dest *projCached, x int8) { + *dest = v.points[x/2] +} + +// Given odd x with 0 < x < 2^7, return x*Q (in variable time). +func (v *nafLookupTable8) SelectInto(dest *affineCached, x int8) { + *dest = v.points[x/2] +} diff --git a/vendor/github.com/Azure/go-ansiterm/LICENSE b/vendor/github.com/Azure/go-ansiterm/LICENSE new file mode 100644 index 00000000..e3d9a64d --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Microsoft Corporation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/Azure/go-ansiterm/README.md b/vendor/github.com/Azure/go-ansiterm/README.md new file mode 100644 index 00000000..261c041e --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/README.md @@ -0,0 +1,12 @@ +# go-ansiterm + +This is a cross platform Ansi Terminal Emulation library. It reads a stream of Ansi characters and produces the appropriate function calls. The results of the function calls are platform dependent. + +For example the parser might receive "ESC, [, A" as a stream of three characters. This is the code for Cursor Up (http://www.vt100.net/docs/vt510-rm/CUU). The parser then calls the cursor up function (CUU()) on an event handler. The event handler determines what platform specific work must be done to cause the cursor to move up one position. + +The parser (parser.go) is a partial implementation of this state machine (http://vt100.net/emu/vt500_parser.png). There are also two event handler implementations, one for tests (test_event_handler.go) to validate that the expected events are being produced and called, the other is a Windows implementation (winterm/win_event_handler.go). + +See parser_test.go for examples exercising the state machine and generating appropriate function calls. + +----- +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/vendor/github.com/Azure/go-ansiterm/SECURITY.md b/vendor/github.com/Azure/go-ansiterm/SECURITY.md new file mode 100644 index 00000000..e138ec5d --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/SECURITY.md @@ -0,0 +1,41 @@ + + +## Security + +Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). + +If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. + +## Reporting Security Issues + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). + +If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). + +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). + +Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: + + * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. + +## Preferred Languages + +We prefer all communications to be in English. + +## Policy + +Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). + + diff --git a/vendor/github.com/Azure/go-ansiterm/constants.go b/vendor/github.com/Azure/go-ansiterm/constants.go new file mode 100644 index 00000000..96504a33 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/constants.go @@ -0,0 +1,188 @@ +package ansiterm + +const LogEnv = "DEBUG_TERMINAL" + +// ANSI constants +// References: +// -- http://www.ecma-international.org/publications/standards/Ecma-048.htm +// -- http://man7.org/linux/man-pages/man4/console_codes.4.html +// -- http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html +// -- http://en.wikipedia.org/wiki/ANSI_escape_code +// -- http://vt100.net/emu/dec_ansi_parser +// -- http://vt100.net/emu/vt500_parser.svg +// -- http://invisible-island.net/xterm/ctlseqs/ctlseqs.html +// -- http://www.inwap.com/pdp10/ansicode.txt +const ( + // ECMA-48 Set Graphics Rendition + // Note: + // -- Constants leading with an underscore (e.g., _ANSI_xxx) are unsupported or reserved + // -- Fonts could possibly be supported via SetCurrentConsoleFontEx + // -- Windows does not expose the per-window cursor (i.e., caret) blink times + ANSI_SGR_RESET = 0 + ANSI_SGR_BOLD = 1 + ANSI_SGR_DIM = 2 + _ANSI_SGR_ITALIC = 3 + ANSI_SGR_UNDERLINE = 4 + _ANSI_SGR_BLINKSLOW = 5 + _ANSI_SGR_BLINKFAST = 6 + ANSI_SGR_REVERSE = 7 + _ANSI_SGR_INVISIBLE = 8 + _ANSI_SGR_LINETHROUGH = 9 + _ANSI_SGR_FONT_00 = 10 + _ANSI_SGR_FONT_01 = 11 + _ANSI_SGR_FONT_02 = 12 + _ANSI_SGR_FONT_03 = 13 + _ANSI_SGR_FONT_04 = 14 + _ANSI_SGR_FONT_05 = 15 + _ANSI_SGR_FONT_06 = 16 + _ANSI_SGR_FONT_07 = 17 + _ANSI_SGR_FONT_08 = 18 + _ANSI_SGR_FONT_09 = 19 + _ANSI_SGR_FONT_10 = 20 + _ANSI_SGR_DOUBLEUNDERLINE = 21 + ANSI_SGR_BOLD_DIM_OFF = 22 + _ANSI_SGR_ITALIC_OFF = 23 + ANSI_SGR_UNDERLINE_OFF = 24 + _ANSI_SGR_BLINK_OFF = 25 + _ANSI_SGR_RESERVED_00 = 26 + ANSI_SGR_REVERSE_OFF = 27 + _ANSI_SGR_INVISIBLE_OFF = 28 + _ANSI_SGR_LINETHROUGH_OFF = 29 + ANSI_SGR_FOREGROUND_BLACK = 30 + ANSI_SGR_FOREGROUND_RED = 31 + ANSI_SGR_FOREGROUND_GREEN = 32 + ANSI_SGR_FOREGROUND_YELLOW = 33 + ANSI_SGR_FOREGROUND_BLUE = 34 + ANSI_SGR_FOREGROUND_MAGENTA = 35 + ANSI_SGR_FOREGROUND_CYAN = 36 + ANSI_SGR_FOREGROUND_WHITE = 37 + _ANSI_SGR_RESERVED_01 = 38 + ANSI_SGR_FOREGROUND_DEFAULT = 39 + ANSI_SGR_BACKGROUND_BLACK = 40 + ANSI_SGR_BACKGROUND_RED = 41 + ANSI_SGR_BACKGROUND_GREEN = 42 + ANSI_SGR_BACKGROUND_YELLOW = 43 + ANSI_SGR_BACKGROUND_BLUE = 44 + ANSI_SGR_BACKGROUND_MAGENTA = 45 + ANSI_SGR_BACKGROUND_CYAN = 46 + ANSI_SGR_BACKGROUND_WHITE = 47 + _ANSI_SGR_RESERVED_02 = 48 + ANSI_SGR_BACKGROUND_DEFAULT = 49 + // 50 - 65: Unsupported + + ANSI_MAX_CMD_LENGTH = 4096 + + MAX_INPUT_EVENTS = 128 + DEFAULT_WIDTH = 80 + DEFAULT_HEIGHT = 24 + + ANSI_BEL = 0x07 + ANSI_BACKSPACE = 0x08 + ANSI_TAB = 0x09 + ANSI_LINE_FEED = 0x0A + ANSI_VERTICAL_TAB = 0x0B + ANSI_FORM_FEED = 0x0C + ANSI_CARRIAGE_RETURN = 0x0D + ANSI_ESCAPE_PRIMARY = 0x1B + ANSI_ESCAPE_SECONDARY = 0x5B + ANSI_OSC_STRING_ENTRY = 0x5D + ANSI_COMMAND_FIRST = 0x40 + ANSI_COMMAND_LAST = 0x7E + DCS_ENTRY = 0x90 + CSI_ENTRY = 0x9B + OSC_STRING = 0x9D + ANSI_PARAMETER_SEP = ";" + ANSI_CMD_G0 = '(' + ANSI_CMD_G1 = ')' + ANSI_CMD_G2 = '*' + ANSI_CMD_G3 = '+' + ANSI_CMD_DECPNM = '>' + ANSI_CMD_DECPAM = '=' + ANSI_CMD_OSC = ']' + ANSI_CMD_STR_TERM = '\\' + + KEY_CONTROL_PARAM_2 = ";2" + KEY_CONTROL_PARAM_3 = ";3" + KEY_CONTROL_PARAM_4 = ";4" + KEY_CONTROL_PARAM_5 = ";5" + KEY_CONTROL_PARAM_6 = ";6" + KEY_CONTROL_PARAM_7 = ";7" + KEY_CONTROL_PARAM_8 = ";8" + KEY_ESC_CSI = "\x1B[" + KEY_ESC_N = "\x1BN" + KEY_ESC_O = "\x1BO" + + FILL_CHARACTER = ' ' +) + +func getByteRange(start byte, end byte) []byte { + bytes := make([]byte, 0, 32) + for i := start; i <= end; i++ { + bytes = append(bytes, byte(i)) + } + + return bytes +} + +var toGroundBytes = getToGroundBytes() +var executors = getExecuteBytes() + +// SPACE 20+A0 hex Always and everywhere a blank space +// Intermediate 20-2F hex !"#$%&'()*+,-./ +var intermeds = getByteRange(0x20, 0x2F) + +// Parameters 30-3F hex 0123456789:;<=>? +// CSI Parameters 30-39, 3B hex 0123456789; +var csiParams = getByteRange(0x30, 0x3F) + +var csiCollectables = append(getByteRange(0x30, 0x39), getByteRange(0x3B, 0x3F)...) + +// Uppercase 40-5F hex @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_ +var upperCase = getByteRange(0x40, 0x5F) + +// Lowercase 60-7E hex `abcdefghijlkmnopqrstuvwxyz{|}~ +var lowerCase = getByteRange(0x60, 0x7E) + +// Alphabetics 40-7E hex (all of upper and lower case) +var alphabetics = append(upperCase, lowerCase...) + +var printables = getByteRange(0x20, 0x7F) + +var escapeIntermediateToGroundBytes = getByteRange(0x30, 0x7E) +var escapeToGroundBytes = getEscapeToGroundBytes() + +// See http://www.vt100.net/emu/vt500_parser.png for description of the complex +// byte ranges below + +func getEscapeToGroundBytes() []byte { + escapeToGroundBytes := getByteRange(0x30, 0x4F) + escapeToGroundBytes = append(escapeToGroundBytes, getByteRange(0x51, 0x57)...) + escapeToGroundBytes = append(escapeToGroundBytes, 0x59) + escapeToGroundBytes = append(escapeToGroundBytes, 0x5A) + escapeToGroundBytes = append(escapeToGroundBytes, 0x5C) + escapeToGroundBytes = append(escapeToGroundBytes, getByteRange(0x60, 0x7E)...) + return escapeToGroundBytes +} + +func getExecuteBytes() []byte { + executeBytes := getByteRange(0x00, 0x17) + executeBytes = append(executeBytes, 0x19) + executeBytes = append(executeBytes, getByteRange(0x1C, 0x1F)...) + return executeBytes +} + +func getToGroundBytes() []byte { + groundBytes := []byte{0x18} + groundBytes = append(groundBytes, 0x1A) + groundBytes = append(groundBytes, getByteRange(0x80, 0x8F)...) + groundBytes = append(groundBytes, getByteRange(0x91, 0x97)...) + groundBytes = append(groundBytes, 0x99) + groundBytes = append(groundBytes, 0x9A) + groundBytes = append(groundBytes, 0x9C) + return groundBytes +} + +// Delete 7F hex Always and everywhere ignored +// C1 Control 80-9F hex 32 additional control characters +// G1 Displayable A1-FE hex 94 additional displayable characters +// Special A0+FF hex Same as SPACE and DELETE diff --git a/vendor/github.com/Azure/go-ansiterm/context.go b/vendor/github.com/Azure/go-ansiterm/context.go new file mode 100644 index 00000000..8d66e777 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/context.go @@ -0,0 +1,7 @@ +package ansiterm + +type ansiContext struct { + currentChar byte + paramBuffer []byte + interBuffer []byte +} diff --git a/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go b/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go new file mode 100644 index 00000000..bcbe00d0 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go @@ -0,0 +1,49 @@ +package ansiterm + +type csiEntryState struct { + baseState +} + +func (csiState csiEntryState) Handle(b byte) (s state, e error) { + csiState.parser.logf("CsiEntry::Handle %#x", b) + + nextState, err := csiState.baseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case sliceContains(alphabetics, b): + return csiState.parser.ground, nil + case sliceContains(csiCollectables, b): + return csiState.parser.csiParam, nil + case sliceContains(executors, b): + return csiState, csiState.parser.execute() + } + + return csiState, nil +} + +func (csiState csiEntryState) Transition(s state) error { + csiState.parser.logf("CsiEntry::Transition %s --> %s", csiState.Name(), s.Name()) + csiState.baseState.Transition(s) + + switch s { + case csiState.parser.ground: + return csiState.parser.csiDispatch() + case csiState.parser.csiParam: + switch { + case sliceContains(csiParams, csiState.parser.context.currentChar): + csiState.parser.collectParam() + case sliceContains(intermeds, csiState.parser.context.currentChar): + csiState.parser.collectInter() + } + } + + return nil +} + +func (csiState csiEntryState) Enter() error { + csiState.parser.clear() + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/csi_param_state.go b/vendor/github.com/Azure/go-ansiterm/csi_param_state.go new file mode 100644 index 00000000..7ed5e01c --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/csi_param_state.go @@ -0,0 +1,38 @@ +package ansiterm + +type csiParamState struct { + baseState +} + +func (csiState csiParamState) Handle(b byte) (s state, e error) { + csiState.parser.logf("CsiParam::Handle %#x", b) + + nextState, err := csiState.baseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case sliceContains(alphabetics, b): + return csiState.parser.ground, nil + case sliceContains(csiCollectables, b): + csiState.parser.collectParam() + return csiState, nil + case sliceContains(executors, b): + return csiState, csiState.parser.execute() + } + + return csiState, nil +} + +func (csiState csiParamState) Transition(s state) error { + csiState.parser.logf("CsiParam::Transition %s --> %s", csiState.Name(), s.Name()) + csiState.baseState.Transition(s) + + switch s { + case csiState.parser.ground: + return csiState.parser.csiDispatch() + } + + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go b/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go new file mode 100644 index 00000000..1c719db9 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go @@ -0,0 +1,36 @@ +package ansiterm + +type escapeIntermediateState struct { + baseState +} + +func (escState escapeIntermediateState) Handle(b byte) (s state, e error) { + escState.parser.logf("escapeIntermediateState::Handle %#x", b) + nextState, err := escState.baseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case sliceContains(intermeds, b): + return escState, escState.parser.collectInter() + case sliceContains(executors, b): + return escState, escState.parser.execute() + case sliceContains(escapeIntermediateToGroundBytes, b): + return escState.parser.ground, nil + } + + return escState, nil +} + +func (escState escapeIntermediateState) Transition(s state) error { + escState.parser.logf("escapeIntermediateState::Transition %s --> %s", escState.Name(), s.Name()) + escState.baseState.Transition(s) + + switch s { + case escState.parser.ground: + return escState.parser.escDispatch() + } + + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/escape_state.go b/vendor/github.com/Azure/go-ansiterm/escape_state.go new file mode 100644 index 00000000..6390abd2 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/escape_state.go @@ -0,0 +1,47 @@ +package ansiterm + +type escapeState struct { + baseState +} + +func (escState escapeState) Handle(b byte) (s state, e error) { + escState.parser.logf("escapeState::Handle %#x", b) + nextState, err := escState.baseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case b == ANSI_ESCAPE_SECONDARY: + return escState.parser.csiEntry, nil + case b == ANSI_OSC_STRING_ENTRY: + return escState.parser.oscString, nil + case sliceContains(executors, b): + return escState, escState.parser.execute() + case sliceContains(escapeToGroundBytes, b): + return escState.parser.ground, nil + case sliceContains(intermeds, b): + return escState.parser.escapeIntermediate, nil + } + + return escState, nil +} + +func (escState escapeState) Transition(s state) error { + escState.parser.logf("Escape::Transition %s --> %s", escState.Name(), s.Name()) + escState.baseState.Transition(s) + + switch s { + case escState.parser.ground: + return escState.parser.escDispatch() + case escState.parser.escapeIntermediate: + return escState.parser.collectInter() + } + + return nil +} + +func (escState escapeState) Enter() error { + escState.parser.clear() + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/event_handler.go b/vendor/github.com/Azure/go-ansiterm/event_handler.go new file mode 100644 index 00000000..98087b38 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/event_handler.go @@ -0,0 +1,90 @@ +package ansiterm + +type AnsiEventHandler interface { + // Print + Print(b byte) error + + // Execute C0 commands + Execute(b byte) error + + // CUrsor Up + CUU(int) error + + // CUrsor Down + CUD(int) error + + // CUrsor Forward + CUF(int) error + + // CUrsor Backward + CUB(int) error + + // Cursor to Next Line + CNL(int) error + + // Cursor to Previous Line + CPL(int) error + + // Cursor Horizontal position Absolute + CHA(int) error + + // Vertical line Position Absolute + VPA(int) error + + // CUrsor Position + CUP(int, int) error + + // Horizontal and Vertical Position (depends on PUM) + HVP(int, int) error + + // Text Cursor Enable Mode + DECTCEM(bool) error + + // Origin Mode + DECOM(bool) error + + // 132 Column Mode + DECCOLM(bool) error + + // Erase in Display + ED(int) error + + // Erase in Line + EL(int) error + + // Insert Line + IL(int) error + + // Delete Line + DL(int) error + + // Insert Character + ICH(int) error + + // Delete Character + DCH(int) error + + // Set Graphics Rendition + SGR([]int) error + + // Pan Down + SU(int) error + + // Pan Up + SD(int) error + + // Device Attributes + DA([]string) error + + // Set Top and Bottom Margins + DECSTBM(int, int) error + + // Index + IND() error + + // Reverse Index + RI() error + + // Flush updates from previous commands + Flush() error +} diff --git a/vendor/github.com/Azure/go-ansiterm/ground_state.go b/vendor/github.com/Azure/go-ansiterm/ground_state.go new file mode 100644 index 00000000..52451e94 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/ground_state.go @@ -0,0 +1,24 @@ +package ansiterm + +type groundState struct { + baseState +} + +func (gs groundState) Handle(b byte) (s state, e error) { + gs.parser.context.currentChar = b + + nextState, err := gs.baseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case sliceContains(printables, b): + return gs, gs.parser.print() + + case sliceContains(executors, b): + return gs, gs.parser.execute() + } + + return gs, nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/osc_string_state.go b/vendor/github.com/Azure/go-ansiterm/osc_string_state.go new file mode 100644 index 00000000..593b10ab --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/osc_string_state.go @@ -0,0 +1,31 @@ +package ansiterm + +type oscStringState struct { + baseState +} + +func (oscState oscStringState) Handle(b byte) (s state, e error) { + oscState.parser.logf("OscString::Handle %#x", b) + nextState, err := oscState.baseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case isOscStringTerminator(b): + return oscState.parser.ground, nil + } + + return oscState, nil +} + +// See below for OSC string terminators for linux +// http://man7.org/linux/man-pages/man4/console_codes.4.html +func isOscStringTerminator(b byte) bool { + + if b == ANSI_BEL || b == 0x5C { + return true + } + + return false +} diff --git a/vendor/github.com/Azure/go-ansiterm/parser.go b/vendor/github.com/Azure/go-ansiterm/parser.go new file mode 100644 index 00000000..03cec7ad --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/parser.go @@ -0,0 +1,151 @@ +package ansiterm + +import ( + "errors" + "log" + "os" +) + +type AnsiParser struct { + currState state + eventHandler AnsiEventHandler + context *ansiContext + csiEntry state + csiParam state + dcsEntry state + escape state + escapeIntermediate state + error state + ground state + oscString state + stateMap []state + + logf func(string, ...interface{}) +} + +type Option func(*AnsiParser) + +func WithLogf(f func(string, ...interface{})) Option { + return func(ap *AnsiParser) { + ap.logf = f + } +} + +func CreateParser(initialState string, evtHandler AnsiEventHandler, opts ...Option) *AnsiParser { + ap := &AnsiParser{ + eventHandler: evtHandler, + context: &ansiContext{}, + } + for _, o := range opts { + o(ap) + } + + if isDebugEnv := os.Getenv(LogEnv); isDebugEnv == "1" { + logFile, _ := os.Create("ansiParser.log") + logger := log.New(logFile, "", log.LstdFlags) + if ap.logf != nil { + l := ap.logf + ap.logf = func(s string, v ...interface{}) { + l(s, v...) + logger.Printf(s, v...) + } + } else { + ap.logf = logger.Printf + } + } + + if ap.logf == nil { + ap.logf = func(string, ...interface{}) {} + } + + ap.csiEntry = csiEntryState{baseState{name: "CsiEntry", parser: ap}} + ap.csiParam = csiParamState{baseState{name: "CsiParam", parser: ap}} + ap.dcsEntry = dcsEntryState{baseState{name: "DcsEntry", parser: ap}} + ap.escape = escapeState{baseState{name: "Escape", parser: ap}} + ap.escapeIntermediate = escapeIntermediateState{baseState{name: "EscapeIntermediate", parser: ap}} + ap.error = errorState{baseState{name: "Error", parser: ap}} + ap.ground = groundState{baseState{name: "Ground", parser: ap}} + ap.oscString = oscStringState{baseState{name: "OscString", parser: ap}} + + ap.stateMap = []state{ + ap.csiEntry, + ap.csiParam, + ap.dcsEntry, + ap.escape, + ap.escapeIntermediate, + ap.error, + ap.ground, + ap.oscString, + } + + ap.currState = getState(initialState, ap.stateMap) + + ap.logf("CreateParser: parser %p", ap) + return ap +} + +func getState(name string, states []state) state { + for _, el := range states { + if el.Name() == name { + return el + } + } + + return nil +} + +func (ap *AnsiParser) Parse(bytes []byte) (int, error) { + for i, b := range bytes { + if err := ap.handle(b); err != nil { + return i, err + } + } + + return len(bytes), ap.eventHandler.Flush() +} + +func (ap *AnsiParser) handle(b byte) error { + ap.context.currentChar = b + newState, err := ap.currState.Handle(b) + if err != nil { + return err + } + + if newState == nil { + ap.logf("WARNING: newState is nil") + return errors.New("New state of 'nil' is invalid.") + } + + if newState != ap.currState { + if err := ap.changeState(newState); err != nil { + return err + } + } + + return nil +} + +func (ap *AnsiParser) changeState(newState state) error { + ap.logf("ChangeState %s --> %s", ap.currState.Name(), newState.Name()) + + // Exit old state + if err := ap.currState.Exit(); err != nil { + ap.logf("Exit state '%s' failed with : '%v'", ap.currState.Name(), err) + return err + } + + // Perform transition action + if err := ap.currState.Transition(newState); err != nil { + ap.logf("Transition from '%s' to '%s' failed with: '%v'", ap.currState.Name(), newState.Name, err) + return err + } + + // Enter new state + if err := newState.Enter(); err != nil { + ap.logf("Enter state '%s' failed with: '%v'", newState.Name(), err) + return err + } + + ap.currState = newState + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go b/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go new file mode 100644 index 00000000..de0a1f9c --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go @@ -0,0 +1,99 @@ +package ansiterm + +import ( + "strconv" +) + +func parseParams(bytes []byte) ([]string, error) { + paramBuff := make([]byte, 0, 0) + params := []string{} + + for _, v := range bytes { + if v == ';' { + if len(paramBuff) > 0 { + // Completed parameter, append it to the list + s := string(paramBuff) + params = append(params, s) + paramBuff = make([]byte, 0, 0) + } + } else { + paramBuff = append(paramBuff, v) + } + } + + // Last parameter may not be terminated with ';' + if len(paramBuff) > 0 { + s := string(paramBuff) + params = append(params, s) + } + + return params, nil +} + +func parseCmd(context ansiContext) (string, error) { + return string(context.currentChar), nil +} + +func getInt(params []string, dflt int) int { + i := getInts(params, 1, dflt)[0] + return i +} + +func getInts(params []string, minCount int, dflt int) []int { + ints := []int{} + + for _, v := range params { + i, _ := strconv.Atoi(v) + // Zero is mapped to the default value in VT100. + if i == 0 { + i = dflt + } + ints = append(ints, i) + } + + if len(ints) < minCount { + remaining := minCount - len(ints) + for i := 0; i < remaining; i++ { + ints = append(ints, dflt) + } + } + + return ints +} + +func (ap *AnsiParser) modeDispatch(param string, set bool) error { + switch param { + case "?3": + return ap.eventHandler.DECCOLM(set) + case "?6": + return ap.eventHandler.DECOM(set) + case "?25": + return ap.eventHandler.DECTCEM(set) + } + return nil +} + +func (ap *AnsiParser) hDispatch(params []string) error { + if len(params) == 1 { + return ap.modeDispatch(params[0], true) + } + + return nil +} + +func (ap *AnsiParser) lDispatch(params []string) error { + if len(params) == 1 { + return ap.modeDispatch(params[0], false) + } + + return nil +} + +func getEraseParam(params []string) int { + param := getInt(params, 0) + if param < 0 || 3 < param { + param = 0 + } + + return param +} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_actions.go b/vendor/github.com/Azure/go-ansiterm/parser_actions.go new file mode 100644 index 00000000..0bb5e51e --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/parser_actions.go @@ -0,0 +1,119 @@ +package ansiterm + +func (ap *AnsiParser) collectParam() error { + currChar := ap.context.currentChar + ap.logf("collectParam %#x", currChar) + ap.context.paramBuffer = append(ap.context.paramBuffer, currChar) + return nil +} + +func (ap *AnsiParser) collectInter() error { + currChar := ap.context.currentChar + ap.logf("collectInter %#x", currChar) + ap.context.paramBuffer = append(ap.context.interBuffer, currChar) + return nil +} + +func (ap *AnsiParser) escDispatch() error { + cmd, _ := parseCmd(*ap.context) + intermeds := ap.context.interBuffer + ap.logf("escDispatch currentChar: %#x", ap.context.currentChar) + ap.logf("escDispatch: %v(%v)", cmd, intermeds) + + switch cmd { + case "D": // IND + return ap.eventHandler.IND() + case "E": // NEL, equivalent to CRLF + err := ap.eventHandler.Execute(ANSI_CARRIAGE_RETURN) + if err == nil { + err = ap.eventHandler.Execute(ANSI_LINE_FEED) + } + return err + case "M": // RI + return ap.eventHandler.RI() + } + + return nil +} + +func (ap *AnsiParser) csiDispatch() error { + cmd, _ := parseCmd(*ap.context) + params, _ := parseParams(ap.context.paramBuffer) + ap.logf("Parsed params: %v with length: %d", params, len(params)) + + ap.logf("csiDispatch: %v(%v)", cmd, params) + + switch cmd { + case "@": + return ap.eventHandler.ICH(getInt(params, 1)) + case "A": + return ap.eventHandler.CUU(getInt(params, 1)) + case "B": + return ap.eventHandler.CUD(getInt(params, 1)) + case "C": + return ap.eventHandler.CUF(getInt(params, 1)) + case "D": + return ap.eventHandler.CUB(getInt(params, 1)) + case "E": + return ap.eventHandler.CNL(getInt(params, 1)) + case "F": + return ap.eventHandler.CPL(getInt(params, 1)) + case "G": + return ap.eventHandler.CHA(getInt(params, 1)) + case "H": + ints := getInts(params, 2, 1) + x, y := ints[0], ints[1] + return ap.eventHandler.CUP(x, y) + case "J": + param := getEraseParam(params) + return ap.eventHandler.ED(param) + case "K": + param := getEraseParam(params) + return ap.eventHandler.EL(param) + case "L": + return ap.eventHandler.IL(getInt(params, 1)) + case "M": + return ap.eventHandler.DL(getInt(params, 1)) + case "P": + return ap.eventHandler.DCH(getInt(params, 1)) + case "S": + return ap.eventHandler.SU(getInt(params, 1)) + case "T": + return ap.eventHandler.SD(getInt(params, 1)) + case "c": + return ap.eventHandler.DA(params) + case "d": + return ap.eventHandler.VPA(getInt(params, 1)) + case "f": + ints := getInts(params, 2, 1) + x, y := ints[0], ints[1] + return ap.eventHandler.HVP(x, y) + case "h": + return ap.hDispatch(params) + case "l": + return ap.lDispatch(params) + case "m": + return ap.eventHandler.SGR(getInts(params, 1, 0)) + case "r": + ints := getInts(params, 2, 1) + top, bottom := ints[0], ints[1] + return ap.eventHandler.DECSTBM(top, bottom) + default: + ap.logf("ERROR: Unsupported CSI command: '%s', with full context: %v", cmd, ap.context) + return nil + } + +} + +func (ap *AnsiParser) print() error { + return ap.eventHandler.Print(ap.context.currentChar) +} + +func (ap *AnsiParser) clear() error { + ap.context = &ansiContext{} + return nil +} + +func (ap *AnsiParser) execute() error { + return ap.eventHandler.Execute(ap.context.currentChar) +} diff --git a/vendor/github.com/Azure/go-ansiterm/states.go b/vendor/github.com/Azure/go-ansiterm/states.go new file mode 100644 index 00000000..f2ea1fcd --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/states.go @@ -0,0 +1,71 @@ +package ansiterm + +type stateID int + +type state interface { + Enter() error + Exit() error + Handle(byte) (state, error) + Name() string + Transition(state) error +} + +type baseState struct { + name string + parser *AnsiParser +} + +func (base baseState) Enter() error { + return nil +} + +func (base baseState) Exit() error { + return nil +} + +func (base baseState) Handle(b byte) (s state, e error) { + + switch { + case b == CSI_ENTRY: + return base.parser.csiEntry, nil + case b == DCS_ENTRY: + return base.parser.dcsEntry, nil + case b == ANSI_ESCAPE_PRIMARY: + return base.parser.escape, nil + case b == OSC_STRING: + return base.parser.oscString, nil + case sliceContains(toGroundBytes, b): + return base.parser.ground, nil + } + + return nil, nil +} + +func (base baseState) Name() string { + return base.name +} + +func (base baseState) Transition(s state) error { + if s == base.parser.ground { + execBytes := []byte{0x18} + execBytes = append(execBytes, 0x1A) + execBytes = append(execBytes, getByteRange(0x80, 0x8F)...) + execBytes = append(execBytes, getByteRange(0x91, 0x97)...) + execBytes = append(execBytes, 0x99) + execBytes = append(execBytes, 0x9A) + + if sliceContains(execBytes, base.parser.context.currentChar) { + return base.parser.execute() + } + } + + return nil +} + +type dcsEntryState struct { + baseState +} + +type errorState struct { + baseState +} diff --git a/vendor/github.com/Azure/go-ansiterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/utilities.go new file mode 100644 index 00000000..39211449 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/utilities.go @@ -0,0 +1,21 @@ +package ansiterm + +import ( + "strconv" +) + +func sliceContains(bytes []byte, b byte) bool { + for _, v := range bytes { + if v == b { + return true + } + } + + return false +} + +func convertBytesToInteger(bytes []byte) int { + s := string(bytes) + i, _ := strconv.Atoi(s) + return i +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go new file mode 100644 index 00000000..5599082a --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go @@ -0,0 +1,196 @@ +// +build windows + +package winterm + +import ( + "fmt" + "os" + "strconv" + "strings" + "syscall" + + "github.com/Azure/go-ansiterm" + windows "golang.org/x/sys/windows" +) + +// Windows keyboard constants +// See https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx. +const ( + VK_PRIOR = 0x21 // PAGE UP key + VK_NEXT = 0x22 // PAGE DOWN key + VK_END = 0x23 // END key + VK_HOME = 0x24 // HOME key + VK_LEFT = 0x25 // LEFT ARROW key + VK_UP = 0x26 // UP ARROW key + VK_RIGHT = 0x27 // RIGHT ARROW key + VK_DOWN = 0x28 // DOWN ARROW key + VK_SELECT = 0x29 // SELECT key + VK_PRINT = 0x2A // PRINT key + VK_EXECUTE = 0x2B // EXECUTE key + VK_SNAPSHOT = 0x2C // PRINT SCREEN key + VK_INSERT = 0x2D // INS key + VK_DELETE = 0x2E // DEL key + VK_HELP = 0x2F // HELP key + VK_F1 = 0x70 // F1 key + VK_F2 = 0x71 // F2 key + VK_F3 = 0x72 // F3 key + VK_F4 = 0x73 // F4 key + VK_F5 = 0x74 // F5 key + VK_F6 = 0x75 // F6 key + VK_F7 = 0x76 // F7 key + VK_F8 = 0x77 // F8 key + VK_F9 = 0x78 // F9 key + VK_F10 = 0x79 // F10 key + VK_F11 = 0x7A // F11 key + VK_F12 = 0x7B // F12 key + + RIGHT_ALT_PRESSED = 0x0001 + LEFT_ALT_PRESSED = 0x0002 + RIGHT_CTRL_PRESSED = 0x0004 + LEFT_CTRL_PRESSED = 0x0008 + SHIFT_PRESSED = 0x0010 + NUMLOCK_ON = 0x0020 + SCROLLLOCK_ON = 0x0040 + CAPSLOCK_ON = 0x0080 + ENHANCED_KEY = 0x0100 +) + +type ansiCommand struct { + CommandBytes []byte + Command string + Parameters []string + IsSpecial bool +} + +func newAnsiCommand(command []byte) *ansiCommand { + + if isCharacterSelectionCmdChar(command[1]) { + // Is Character Set Selection commands + return &ansiCommand{ + CommandBytes: command, + Command: string(command), + IsSpecial: true, + } + } + + // last char is command character + lastCharIndex := len(command) - 1 + + ac := &ansiCommand{ + CommandBytes: command, + Command: string(command[lastCharIndex]), + IsSpecial: false, + } + + // more than a single escape + if lastCharIndex != 0 { + start := 1 + // skip if double char escape sequence + if command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_ESCAPE_SECONDARY { + start++ + } + // convert this to GetNextParam method + ac.Parameters = strings.Split(string(command[start:lastCharIndex]), ansiterm.ANSI_PARAMETER_SEP) + } + + return ac +} + +func (ac *ansiCommand) paramAsSHORT(index int, defaultValue int16) int16 { + if index < 0 || index >= len(ac.Parameters) { + return defaultValue + } + + param, err := strconv.ParseInt(ac.Parameters[index], 10, 16) + if err != nil { + return defaultValue + } + + return int16(param) +} + +func (ac *ansiCommand) String() string { + return fmt.Sprintf("0x%v \"%v\" (\"%v\")", + bytesToHex(ac.CommandBytes), + ac.Command, + strings.Join(ac.Parameters, "\",\"")) +} + +// isAnsiCommandChar returns true if the passed byte falls within the range of ANSI commands. +// See http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html. +func isAnsiCommandChar(b byte) bool { + switch { + case ansiterm.ANSI_COMMAND_FIRST <= b && b <= ansiterm.ANSI_COMMAND_LAST && b != ansiterm.ANSI_ESCAPE_SECONDARY: + return true + case b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_OSC || b == ansiterm.ANSI_CMD_DECPAM || b == ansiterm.ANSI_CMD_DECPNM: + // non-CSI escape sequence terminator + return true + case b == ansiterm.ANSI_CMD_STR_TERM || b == ansiterm.ANSI_BEL: + // String escape sequence terminator + return true + } + return false +} + +func isXtermOscSequence(command []byte, current byte) bool { + return (len(command) >= 2 && command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_CMD_OSC && current != ansiterm.ANSI_BEL) +} + +func isCharacterSelectionCmdChar(b byte) bool { + return (b == ansiterm.ANSI_CMD_G0 || b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_G2 || b == ansiterm.ANSI_CMD_G3) +} + +// bytesToHex converts a slice of bytes to a human-readable string. +func bytesToHex(b []byte) string { + hex := make([]string, len(b)) + for i, ch := range b { + hex[i] = fmt.Sprintf("%X", ch) + } + return strings.Join(hex, "") +} + +// ensureInRange adjusts the passed value, if necessary, to ensure it is within +// the passed min / max range. +func ensureInRange(n int16, min int16, max int16) int16 { + if n < min { + return min + } else if n > max { + return max + } else { + return n + } +} + +func GetStdFile(nFile int) (*os.File, uintptr) { + var file *os.File + + // syscall uses negative numbers + // windows package uses very big uint32 + // Keep these switches split so we don't have to convert ints too much. + switch uint32(nFile) { + case windows.STD_INPUT_HANDLE: + file = os.Stdin + case windows.STD_OUTPUT_HANDLE: + file = os.Stdout + case windows.STD_ERROR_HANDLE: + file = os.Stderr + default: + switch nFile { + case syscall.STD_INPUT_HANDLE: + file = os.Stdin + case syscall.STD_OUTPUT_HANDLE: + file = os.Stdout + case syscall.STD_ERROR_HANDLE: + file = os.Stderr + default: + panic(fmt.Errorf("Invalid standard handle identifier: %v", nFile)) + } + } + + fd, err := syscall.GetStdHandle(nFile) + if err != nil { + panic(fmt.Errorf("Invalid standard handle identifier: %v -- %v", nFile, err)) + } + + return file, uintptr(fd) +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/api.go b/vendor/github.com/Azure/go-ansiterm/winterm/api.go new file mode 100644 index 00000000..6055e33b --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/api.go @@ -0,0 +1,327 @@ +// +build windows + +package winterm + +import ( + "fmt" + "syscall" + "unsafe" +) + +//=========================================================================================================== +// IMPORTANT NOTE: +// +// The methods below make extensive use of the "unsafe" package to obtain the required pointers. +// Beginning in Go 1.3, the garbage collector may release local variables (e.g., incoming arguments, stack +// variables) the pointers reference *before* the API completes. +// +// As a result, in those cases, the code must hint that the variables remain in active by invoking the +// dummy method "use" (see below). Newer versions of Go are planned to change the mechanism to no longer +// require unsafe pointers. +// +// If you add or modify methods, ENSURE protection of local variables through the "use" builtin to inform +// the garbage collector the variables remain in use if: +// +// -- The value is not a pointer (e.g., int32, struct) +// -- The value is not referenced by the method after passing the pointer to Windows +// +// See http://golang.org/doc/go1.3. +//=========================================================================================================== + +var ( + kernel32DLL = syscall.NewLazyDLL("kernel32.dll") + + getConsoleCursorInfoProc = kernel32DLL.NewProc("GetConsoleCursorInfo") + setConsoleCursorInfoProc = kernel32DLL.NewProc("SetConsoleCursorInfo") + setConsoleCursorPositionProc = kernel32DLL.NewProc("SetConsoleCursorPosition") + setConsoleModeProc = kernel32DLL.NewProc("SetConsoleMode") + getConsoleScreenBufferInfoProc = kernel32DLL.NewProc("GetConsoleScreenBufferInfo") + setConsoleScreenBufferSizeProc = kernel32DLL.NewProc("SetConsoleScreenBufferSize") + scrollConsoleScreenBufferProc = kernel32DLL.NewProc("ScrollConsoleScreenBufferA") + setConsoleTextAttributeProc = kernel32DLL.NewProc("SetConsoleTextAttribute") + setConsoleWindowInfoProc = kernel32DLL.NewProc("SetConsoleWindowInfo") + writeConsoleOutputProc = kernel32DLL.NewProc("WriteConsoleOutputW") + readConsoleInputProc = kernel32DLL.NewProc("ReadConsoleInputW") + waitForSingleObjectProc = kernel32DLL.NewProc("WaitForSingleObject") +) + +// Windows Console constants +const ( + // Console modes + // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx. + ENABLE_PROCESSED_INPUT = 0x0001 + ENABLE_LINE_INPUT = 0x0002 + ENABLE_ECHO_INPUT = 0x0004 + ENABLE_WINDOW_INPUT = 0x0008 + ENABLE_MOUSE_INPUT = 0x0010 + ENABLE_INSERT_MODE = 0x0020 + ENABLE_QUICK_EDIT_MODE = 0x0040 + ENABLE_EXTENDED_FLAGS = 0x0080 + ENABLE_AUTO_POSITION = 0x0100 + ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200 + + ENABLE_PROCESSED_OUTPUT = 0x0001 + ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002 + ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 + DISABLE_NEWLINE_AUTO_RETURN = 0x0008 + ENABLE_LVB_GRID_WORLDWIDE = 0x0010 + + // Character attributes + // Note: + // -- The attributes are combined to produce various colors (e.g., Blue + Green will create Cyan). + // Clearing all foreground or background colors results in black; setting all creates white. + // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes. + FOREGROUND_BLUE uint16 = 0x0001 + FOREGROUND_GREEN uint16 = 0x0002 + FOREGROUND_RED uint16 = 0x0004 + FOREGROUND_INTENSITY uint16 = 0x0008 + FOREGROUND_MASK uint16 = 0x000F + + BACKGROUND_BLUE uint16 = 0x0010 + BACKGROUND_GREEN uint16 = 0x0020 + BACKGROUND_RED uint16 = 0x0040 + BACKGROUND_INTENSITY uint16 = 0x0080 + BACKGROUND_MASK uint16 = 0x00F0 + + COMMON_LVB_MASK uint16 = 0xFF00 + COMMON_LVB_REVERSE_VIDEO uint16 = 0x4000 + COMMON_LVB_UNDERSCORE uint16 = 0x8000 + + // Input event types + // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx. + KEY_EVENT = 0x0001 + MOUSE_EVENT = 0x0002 + WINDOW_BUFFER_SIZE_EVENT = 0x0004 + MENU_EVENT = 0x0008 + FOCUS_EVENT = 0x0010 + + // WaitForSingleObject return codes + WAIT_ABANDONED = 0x00000080 + WAIT_FAILED = 0xFFFFFFFF + WAIT_SIGNALED = 0x0000000 + WAIT_TIMEOUT = 0x00000102 + + // WaitForSingleObject wait duration + WAIT_INFINITE = 0xFFFFFFFF + WAIT_ONE_SECOND = 1000 + WAIT_HALF_SECOND = 500 + WAIT_QUARTER_SECOND = 250 +) + +// Windows API Console types +// -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682101(v=vs.85).aspx for Console specific types (e.g., COORD) +// -- See https://msdn.microsoft.com/en-us/library/aa296569(v=vs.60).aspx for comments on alignment +type ( + CHAR_INFO struct { + UnicodeChar uint16 + Attributes uint16 + } + + CONSOLE_CURSOR_INFO struct { + Size uint32 + Visible int32 + } + + CONSOLE_SCREEN_BUFFER_INFO struct { + Size COORD + CursorPosition COORD + Attributes uint16 + Window SMALL_RECT + MaximumWindowSize COORD + } + + COORD struct { + X int16 + Y int16 + } + + SMALL_RECT struct { + Left int16 + Top int16 + Right int16 + Bottom int16 + } + + // INPUT_RECORD is a C/C++ union of which KEY_EVENT_RECORD is one case, it is also the largest + // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx. + INPUT_RECORD struct { + EventType uint16 + KeyEvent KEY_EVENT_RECORD + } + + KEY_EVENT_RECORD struct { + KeyDown int32 + RepeatCount uint16 + VirtualKeyCode uint16 + VirtualScanCode uint16 + UnicodeChar uint16 + ControlKeyState uint32 + } + + WINDOW_BUFFER_SIZE struct { + Size COORD + } +) + +// boolToBOOL converts a Go bool into a Windows int32. +func boolToBOOL(f bool) int32 { + if f { + return int32(1) + } else { + return int32(0) + } +} + +// GetConsoleCursorInfo retrieves information about the size and visiblity of the console cursor. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683163(v=vs.85).aspx. +func GetConsoleCursorInfo(handle uintptr, cursorInfo *CONSOLE_CURSOR_INFO) error { + r1, r2, err := getConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0) + return checkError(r1, r2, err) +} + +// SetConsoleCursorInfo sets the size and visiblity of the console cursor. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686019(v=vs.85).aspx. +func SetConsoleCursorInfo(handle uintptr, cursorInfo *CONSOLE_CURSOR_INFO) error { + r1, r2, err := setConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0) + return checkError(r1, r2, err) +} + +// SetConsoleCursorPosition location of the console cursor. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx. +func SetConsoleCursorPosition(handle uintptr, coord COORD) error { + r1, r2, err := setConsoleCursorPositionProc.Call(handle, coordToPointer(coord)) + use(coord) + return checkError(r1, r2, err) +} + +// GetConsoleMode gets the console mode for given file descriptor +// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx. +func GetConsoleMode(handle uintptr) (mode uint32, err error) { + err = syscall.GetConsoleMode(syscall.Handle(handle), &mode) + return mode, err +} + +// SetConsoleMode sets the console mode for given file descriptor +// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx. +func SetConsoleMode(handle uintptr, mode uint32) error { + r1, r2, err := setConsoleModeProc.Call(handle, uintptr(mode), 0) + use(mode) + return checkError(r1, r2, err) +} + +// GetConsoleScreenBufferInfo retrieves information about the specified console screen buffer. +// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683171(v=vs.85).aspx. +func GetConsoleScreenBufferInfo(handle uintptr) (*CONSOLE_SCREEN_BUFFER_INFO, error) { + info := CONSOLE_SCREEN_BUFFER_INFO{} + err := checkError(getConsoleScreenBufferInfoProc.Call(handle, uintptr(unsafe.Pointer(&info)), 0)) + if err != nil { + return nil, err + } + return &info, nil +} + +func ScrollConsoleScreenBuffer(handle uintptr, scrollRect SMALL_RECT, clipRect SMALL_RECT, destOrigin COORD, char CHAR_INFO) error { + r1, r2, err := scrollConsoleScreenBufferProc.Call(handle, uintptr(unsafe.Pointer(&scrollRect)), uintptr(unsafe.Pointer(&clipRect)), coordToPointer(destOrigin), uintptr(unsafe.Pointer(&char))) + use(scrollRect) + use(clipRect) + use(destOrigin) + use(char) + return checkError(r1, r2, err) +} + +// SetConsoleScreenBufferSize sets the size of the console screen buffer. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686044(v=vs.85).aspx. +func SetConsoleScreenBufferSize(handle uintptr, coord COORD) error { + r1, r2, err := setConsoleScreenBufferSizeProc.Call(handle, coordToPointer(coord)) + use(coord) + return checkError(r1, r2, err) +} + +// SetConsoleTextAttribute sets the attributes of characters written to the +// console screen buffer by the WriteFile or WriteConsole function. +// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx. +func SetConsoleTextAttribute(handle uintptr, attribute uint16) error { + r1, r2, err := setConsoleTextAttributeProc.Call(handle, uintptr(attribute), 0) + use(attribute) + return checkError(r1, r2, err) +} + +// SetConsoleWindowInfo sets the size and position of the console screen buffer's window. +// Note that the size and location must be within and no larger than the backing console screen buffer. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686125(v=vs.85).aspx. +func SetConsoleWindowInfo(handle uintptr, isAbsolute bool, rect SMALL_RECT) error { + r1, r2, err := setConsoleWindowInfoProc.Call(handle, uintptr(boolToBOOL(isAbsolute)), uintptr(unsafe.Pointer(&rect))) + use(isAbsolute) + use(rect) + return checkError(r1, r2, err) +} + +// WriteConsoleOutput writes the CHAR_INFOs from the provided buffer to the active console buffer. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687404(v=vs.85).aspx. +func WriteConsoleOutput(handle uintptr, buffer []CHAR_INFO, bufferSize COORD, bufferCoord COORD, writeRegion *SMALL_RECT) error { + r1, r2, err := writeConsoleOutputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), coordToPointer(bufferSize), coordToPointer(bufferCoord), uintptr(unsafe.Pointer(writeRegion))) + use(buffer) + use(bufferSize) + use(bufferCoord) + return checkError(r1, r2, err) +} + +// ReadConsoleInput reads (and removes) data from the console input buffer. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms684961(v=vs.85).aspx. +func ReadConsoleInput(handle uintptr, buffer []INPUT_RECORD, count *uint32) error { + r1, r2, err := readConsoleInputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), uintptr(len(buffer)), uintptr(unsafe.Pointer(count))) + use(buffer) + return checkError(r1, r2, err) +} + +// WaitForSingleObject waits for the passed handle to be signaled. +// It returns true if the handle was signaled; false otherwise. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx. +func WaitForSingleObject(handle uintptr, msWait uint32) (bool, error) { + r1, _, err := waitForSingleObjectProc.Call(handle, uintptr(uint32(msWait))) + switch r1 { + case WAIT_ABANDONED, WAIT_TIMEOUT: + return false, nil + case WAIT_SIGNALED: + return true, nil + } + use(msWait) + return false, err +} + +// String helpers +func (info CONSOLE_SCREEN_BUFFER_INFO) String() string { + return fmt.Sprintf("Size(%v) Cursor(%v) Window(%v) Max(%v)", info.Size, info.CursorPosition, info.Window, info.MaximumWindowSize) +} + +func (coord COORD) String() string { + return fmt.Sprintf("%v,%v", coord.X, coord.Y) +} + +func (rect SMALL_RECT) String() string { + return fmt.Sprintf("(%v,%v),(%v,%v)", rect.Left, rect.Top, rect.Right, rect.Bottom) +} + +// checkError evaluates the results of a Windows API call and returns the error if it failed. +func checkError(r1, r2 uintptr, err error) error { + // Windows APIs return non-zero to indicate success + if r1 != 0 { + return nil + } + + // Return the error if provided, otherwise default to EINVAL + if err != nil { + return err + } + return syscall.EINVAL +} + +// coordToPointer converts a COORD into a uintptr (by fooling the type system). +func coordToPointer(c COORD) uintptr { + // Note: This code assumes the two SHORTs are correctly laid out; the "cast" to uint32 is just to get a pointer to pass. + return uintptr(*((*uint32)(unsafe.Pointer(&c)))) +} + +// use is a no-op, but the compiler cannot see that it is. +// Calling use(p) ensures that p is kept live until that point. +func use(p interface{}) {} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go new file mode 100644 index 00000000..cbec8f72 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go @@ -0,0 +1,100 @@ +// +build windows + +package winterm + +import "github.com/Azure/go-ansiterm" + +const ( + FOREGROUND_COLOR_MASK = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE + BACKGROUND_COLOR_MASK = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE +) + +// collectAnsiIntoWindowsAttributes modifies the passed Windows text mode flags to reflect the +// request represented by the passed ANSI mode. +func collectAnsiIntoWindowsAttributes(windowsMode uint16, inverted bool, baseMode uint16, ansiMode int16) (uint16, bool) { + switch ansiMode { + + // Mode styles + case ansiterm.ANSI_SGR_BOLD: + windowsMode = windowsMode | FOREGROUND_INTENSITY + + case ansiterm.ANSI_SGR_DIM, ansiterm.ANSI_SGR_BOLD_DIM_OFF: + windowsMode &^= FOREGROUND_INTENSITY + + case ansiterm.ANSI_SGR_UNDERLINE: + windowsMode = windowsMode | COMMON_LVB_UNDERSCORE + + case ansiterm.ANSI_SGR_REVERSE: + inverted = true + + case ansiterm.ANSI_SGR_REVERSE_OFF: + inverted = false + + case ansiterm.ANSI_SGR_UNDERLINE_OFF: + windowsMode &^= COMMON_LVB_UNDERSCORE + + // Foreground colors + case ansiterm.ANSI_SGR_FOREGROUND_DEFAULT: + windowsMode = (windowsMode &^ FOREGROUND_MASK) | (baseMode & FOREGROUND_MASK) + + case ansiterm.ANSI_SGR_FOREGROUND_BLACK: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) + + case ansiterm.ANSI_SGR_FOREGROUND_RED: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED + + case ansiterm.ANSI_SGR_FOREGROUND_GREEN: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN + + case ansiterm.ANSI_SGR_FOREGROUND_YELLOW: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN + + case ansiterm.ANSI_SGR_FOREGROUND_BLUE: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_BLUE + + case ansiterm.ANSI_SGR_FOREGROUND_MAGENTA: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_BLUE + + case ansiterm.ANSI_SGR_FOREGROUND_CYAN: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN | FOREGROUND_BLUE + + case ansiterm.ANSI_SGR_FOREGROUND_WHITE: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE + + // Background colors + case ansiterm.ANSI_SGR_BACKGROUND_DEFAULT: + // Black with no intensity + windowsMode = (windowsMode &^ BACKGROUND_MASK) | (baseMode & BACKGROUND_MASK) + + case ansiterm.ANSI_SGR_BACKGROUND_BLACK: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) + + case ansiterm.ANSI_SGR_BACKGROUND_RED: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED + + case ansiterm.ANSI_SGR_BACKGROUND_GREEN: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN + + case ansiterm.ANSI_SGR_BACKGROUND_YELLOW: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN + + case ansiterm.ANSI_SGR_BACKGROUND_BLUE: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_BLUE + + case ansiterm.ANSI_SGR_BACKGROUND_MAGENTA: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_BLUE + + case ansiterm.ANSI_SGR_BACKGROUND_CYAN: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN | BACKGROUND_BLUE + + case ansiterm.ANSI_SGR_BACKGROUND_WHITE: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE + } + + return windowsMode, inverted +} + +// invertAttributes inverts the foreground and background colors of a Windows attributes value +func invertAttributes(windowsMode uint16) uint16 { + return (COMMON_LVB_MASK & windowsMode) | ((FOREGROUND_MASK & windowsMode) << 4) | ((BACKGROUND_MASK & windowsMode) >> 4) +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go new file mode 100644 index 00000000..3ee06ea7 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go @@ -0,0 +1,101 @@ +// +build windows + +package winterm + +const ( + horizontal = iota + vertical +) + +func (h *windowsAnsiEventHandler) getCursorWindow(info *CONSOLE_SCREEN_BUFFER_INFO) SMALL_RECT { + if h.originMode { + sr := h.effectiveSr(info.Window) + return SMALL_RECT{ + Top: sr.top, + Bottom: sr.bottom, + Left: 0, + Right: info.Size.X - 1, + } + } else { + return SMALL_RECT{ + Top: info.Window.Top, + Bottom: info.Window.Bottom, + Left: 0, + Right: info.Size.X - 1, + } + } +} + +// setCursorPosition sets the cursor to the specified position, bounded to the screen size +func (h *windowsAnsiEventHandler) setCursorPosition(position COORD, window SMALL_RECT) error { + position.X = ensureInRange(position.X, window.Left, window.Right) + position.Y = ensureInRange(position.Y, window.Top, window.Bottom) + err := SetConsoleCursorPosition(h.fd, position) + if err != nil { + return err + } + h.logf("Cursor position set: (%d, %d)", position.X, position.Y) + return err +} + +func (h *windowsAnsiEventHandler) moveCursorVertical(param int) error { + return h.moveCursor(vertical, param) +} + +func (h *windowsAnsiEventHandler) moveCursorHorizontal(param int) error { + return h.moveCursor(horizontal, param) +} + +func (h *windowsAnsiEventHandler) moveCursor(moveMode int, param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + position := info.CursorPosition + switch moveMode { + case horizontal: + position.X += int16(param) + case vertical: + position.Y += int16(param) + } + + if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { + return err + } + + return nil +} + +func (h *windowsAnsiEventHandler) moveCursorLine(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + position := info.CursorPosition + position.X = 0 + position.Y += int16(param) + + if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { + return err + } + + return nil +} + +func (h *windowsAnsiEventHandler) moveCursorColumn(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + position := info.CursorPosition + position.X = int16(param) - 1 + + if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go new file mode 100644 index 00000000..244b5fa2 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go @@ -0,0 +1,84 @@ +// +build windows + +package winterm + +import "github.com/Azure/go-ansiterm" + +func (h *windowsAnsiEventHandler) clearRange(attributes uint16, fromCoord COORD, toCoord COORD) error { + // Ignore an invalid (negative area) request + if toCoord.Y < fromCoord.Y { + return nil + } + + var err error + + var coordStart = COORD{} + var coordEnd = COORD{} + + xCurrent, yCurrent := fromCoord.X, fromCoord.Y + xEnd, yEnd := toCoord.X, toCoord.Y + + // Clear any partial initial line + if xCurrent > 0 { + coordStart.X, coordStart.Y = xCurrent, yCurrent + coordEnd.X, coordEnd.Y = xEnd, yCurrent + + err = h.clearRect(attributes, coordStart, coordEnd) + if err != nil { + return err + } + + xCurrent = 0 + yCurrent += 1 + } + + // Clear intervening rectangular section + if yCurrent < yEnd { + coordStart.X, coordStart.Y = xCurrent, yCurrent + coordEnd.X, coordEnd.Y = xEnd, yEnd-1 + + err = h.clearRect(attributes, coordStart, coordEnd) + if err != nil { + return err + } + + xCurrent = 0 + yCurrent = yEnd + } + + // Clear remaining partial ending line + coordStart.X, coordStart.Y = xCurrent, yCurrent + coordEnd.X, coordEnd.Y = xEnd, yEnd + + err = h.clearRect(attributes, coordStart, coordEnd) + if err != nil { + return err + } + + return nil +} + +func (h *windowsAnsiEventHandler) clearRect(attributes uint16, fromCoord COORD, toCoord COORD) error { + region := SMALL_RECT{Top: fromCoord.Y, Left: fromCoord.X, Bottom: toCoord.Y, Right: toCoord.X} + width := toCoord.X - fromCoord.X + 1 + height := toCoord.Y - fromCoord.Y + 1 + size := uint32(width) * uint32(height) + + if size <= 0 { + return nil + } + + buffer := make([]CHAR_INFO, size) + + char := CHAR_INFO{ansiterm.FILL_CHARACTER, attributes} + for i := 0; i < int(size); i++ { + buffer[i] = char + } + + err := WriteConsoleOutput(h.fd, buffer, COORD{X: width, Y: height}, COORD{X: 0, Y: 0}, ®ion) + if err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go new file mode 100644 index 00000000..2d27fa1d --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go @@ -0,0 +1,118 @@ +// +build windows + +package winterm + +// effectiveSr gets the current effective scroll region in buffer coordinates +func (h *windowsAnsiEventHandler) effectiveSr(window SMALL_RECT) scrollRegion { + top := addInRange(window.Top, h.sr.top, window.Top, window.Bottom) + bottom := addInRange(window.Top, h.sr.bottom, window.Top, window.Bottom) + if top >= bottom { + top = window.Top + bottom = window.Bottom + } + return scrollRegion{top: top, bottom: bottom} +} + +func (h *windowsAnsiEventHandler) scrollUp(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + sr := h.effectiveSr(info.Window) + return h.scroll(param, sr, info) +} + +func (h *windowsAnsiEventHandler) scrollDown(param int) error { + return h.scrollUp(-param) +} + +func (h *windowsAnsiEventHandler) deleteLines(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + start := info.CursorPosition.Y + sr := h.effectiveSr(info.Window) + // Lines cannot be inserted or deleted outside the scrolling region. + if start >= sr.top && start <= sr.bottom { + sr.top = start + return h.scroll(param, sr, info) + } else { + return nil + } +} + +func (h *windowsAnsiEventHandler) insertLines(param int) error { + return h.deleteLines(-param) +} + +// scroll scrolls the provided scroll region by param lines. The scroll region is in buffer coordinates. +func (h *windowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSOLE_SCREEN_BUFFER_INFO) error { + h.logf("scroll: scrollTop: %d, scrollBottom: %d", sr.top, sr.bottom) + h.logf("scroll: windowTop: %d, windowBottom: %d", info.Window.Top, info.Window.Bottom) + + // Copy from and clip to the scroll region (full buffer width) + scrollRect := SMALL_RECT{ + Top: sr.top, + Bottom: sr.bottom, + Left: 0, + Right: info.Size.X - 1, + } + + // Origin to which area should be copied + destOrigin := COORD{ + X: 0, + Y: sr.top - int16(param), + } + + char := CHAR_INFO{ + UnicodeChar: ' ', + Attributes: h.attributes, + } + + if err := ScrollConsoleScreenBuffer(h.fd, scrollRect, scrollRect, destOrigin, char); err != nil { + return err + } + return nil +} + +func (h *windowsAnsiEventHandler) deleteCharacters(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + return h.scrollLine(param, info.CursorPosition, info) +} + +func (h *windowsAnsiEventHandler) insertCharacters(param int) error { + return h.deleteCharacters(-param) +} + +// scrollLine scrolls a line horizontally starting at the provided position by a number of columns. +func (h *windowsAnsiEventHandler) scrollLine(columns int, position COORD, info *CONSOLE_SCREEN_BUFFER_INFO) error { + // Copy from and clip to the scroll region (full buffer width) + scrollRect := SMALL_RECT{ + Top: position.Y, + Bottom: position.Y, + Left: position.X, + Right: info.Size.X - 1, + } + + // Origin to which area should be copied + destOrigin := COORD{ + X: position.X - int16(columns), + Y: position.Y, + } + + char := CHAR_INFO{ + UnicodeChar: ' ', + Attributes: h.attributes, + } + + if err := ScrollConsoleScreenBuffer(h.fd, scrollRect, scrollRect, destOrigin, char); err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go new file mode 100644 index 00000000..afa7635d --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go @@ -0,0 +1,9 @@ +// +build windows + +package winterm + +// AddInRange increments a value by the passed quantity while ensuring the values +// always remain within the supplied min / max range. +func addInRange(n int16, increment int16, min int16, max int16) int16 { + return ensureInRange(n+increment, min, max) +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go new file mode 100644 index 00000000..2d40fb75 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go @@ -0,0 +1,743 @@ +// +build windows + +package winterm + +import ( + "bytes" + "log" + "os" + "strconv" + + "github.com/Azure/go-ansiterm" +) + +type windowsAnsiEventHandler struct { + fd uintptr + file *os.File + infoReset *CONSOLE_SCREEN_BUFFER_INFO + sr scrollRegion + buffer bytes.Buffer + attributes uint16 + inverted bool + wrapNext bool + drewMarginByte bool + originMode bool + marginByte byte + curInfo *CONSOLE_SCREEN_BUFFER_INFO + curPos COORD + logf func(string, ...interface{}) +} + +type Option func(*windowsAnsiEventHandler) + +func WithLogf(f func(string, ...interface{})) Option { + return func(w *windowsAnsiEventHandler) { + w.logf = f + } +} + +func CreateWinEventHandler(fd uintptr, file *os.File, opts ...Option) ansiterm.AnsiEventHandler { + infoReset, err := GetConsoleScreenBufferInfo(fd) + if err != nil { + return nil + } + + h := &windowsAnsiEventHandler{ + fd: fd, + file: file, + infoReset: infoReset, + attributes: infoReset.Attributes, + } + for _, o := range opts { + o(h) + } + + if isDebugEnv := os.Getenv(ansiterm.LogEnv); isDebugEnv == "1" { + logFile, _ := os.Create("winEventHandler.log") + logger := log.New(logFile, "", log.LstdFlags) + if h.logf != nil { + l := h.logf + h.logf = func(s string, v ...interface{}) { + l(s, v...) + logger.Printf(s, v...) + } + } else { + h.logf = logger.Printf + } + } + + if h.logf == nil { + h.logf = func(string, ...interface{}) {} + } + + return h +} + +type scrollRegion struct { + top int16 + bottom int16 +} + +// simulateLF simulates a LF or CR+LF by scrolling if necessary to handle the +// current cursor position and scroll region settings, in which case it returns +// true. If no special handling is necessary, then it does nothing and returns +// false. +// +// In the false case, the caller should ensure that a carriage return +// and line feed are inserted or that the text is otherwise wrapped. +func (h *windowsAnsiEventHandler) simulateLF(includeCR bool) (bool, error) { + if h.wrapNext { + if err := h.Flush(); err != nil { + return false, err + } + h.clearWrap() + } + pos, info, err := h.getCurrentInfo() + if err != nil { + return false, err + } + sr := h.effectiveSr(info.Window) + if pos.Y == sr.bottom { + // Scrolling is necessary. Let Windows automatically scroll if the scrolling region + // is the full window. + if sr.top == info.Window.Top && sr.bottom == info.Window.Bottom { + if includeCR { + pos.X = 0 + h.updatePos(pos) + } + return false, nil + } + + // A custom scroll region is active. Scroll the window manually to simulate + // the LF. + if err := h.Flush(); err != nil { + return false, err + } + h.logf("Simulating LF inside scroll region") + if err := h.scrollUp(1); err != nil { + return false, err + } + if includeCR { + pos.X = 0 + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return false, err + } + } + return true, nil + + } else if pos.Y < info.Window.Bottom { + // Let Windows handle the LF. + pos.Y++ + if includeCR { + pos.X = 0 + } + h.updatePos(pos) + return false, nil + } else { + // The cursor is at the bottom of the screen but outside the scroll + // region. Skip the LF. + h.logf("Simulating LF outside scroll region") + if includeCR { + if err := h.Flush(); err != nil { + return false, err + } + pos.X = 0 + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return false, err + } + } + return true, nil + } +} + +// executeLF executes a LF without a CR. +func (h *windowsAnsiEventHandler) executeLF() error { + handled, err := h.simulateLF(false) + if err != nil { + return err + } + if !handled { + // Windows LF will reset the cursor column position. Write the LF + // and restore the cursor position. + pos, _, err := h.getCurrentInfo() + if err != nil { + return err + } + h.buffer.WriteByte(ansiterm.ANSI_LINE_FEED) + if pos.X != 0 { + if err := h.Flush(); err != nil { + return err + } + h.logf("Resetting cursor position for LF without CR") + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return err + } + } + } + return nil +} + +func (h *windowsAnsiEventHandler) Print(b byte) error { + if h.wrapNext { + h.buffer.WriteByte(h.marginByte) + h.clearWrap() + if _, err := h.simulateLF(true); err != nil { + return err + } + } + pos, info, err := h.getCurrentInfo() + if err != nil { + return err + } + if pos.X == info.Size.X-1 { + h.wrapNext = true + h.marginByte = b + } else { + pos.X++ + h.updatePos(pos) + h.buffer.WriteByte(b) + } + return nil +} + +func (h *windowsAnsiEventHandler) Execute(b byte) error { + switch b { + case ansiterm.ANSI_TAB: + h.logf("Execute(TAB)") + // Move to the next tab stop, but preserve auto-wrap if already set. + if !h.wrapNext { + pos, info, err := h.getCurrentInfo() + if err != nil { + return err + } + pos.X = (pos.X + 8) - pos.X%8 + if pos.X >= info.Size.X { + pos.X = info.Size.X - 1 + } + if err := h.Flush(); err != nil { + return err + } + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return err + } + } + return nil + + case ansiterm.ANSI_BEL: + h.buffer.WriteByte(ansiterm.ANSI_BEL) + return nil + + case ansiterm.ANSI_BACKSPACE: + if h.wrapNext { + if err := h.Flush(); err != nil { + return err + } + h.clearWrap() + } + pos, _, err := h.getCurrentInfo() + if err != nil { + return err + } + if pos.X > 0 { + pos.X-- + h.updatePos(pos) + h.buffer.WriteByte(ansiterm.ANSI_BACKSPACE) + } + return nil + + case ansiterm.ANSI_VERTICAL_TAB, ansiterm.ANSI_FORM_FEED: + // Treat as true LF. + return h.executeLF() + + case ansiterm.ANSI_LINE_FEED: + // Simulate a CR and LF for now since there is no way in go-ansiterm + // to tell if the LF should include CR (and more things break when it's + // missing than when it's incorrectly added). + handled, err := h.simulateLF(true) + if handled || err != nil { + return err + } + return h.buffer.WriteByte(ansiterm.ANSI_LINE_FEED) + + case ansiterm.ANSI_CARRIAGE_RETURN: + if h.wrapNext { + if err := h.Flush(); err != nil { + return err + } + h.clearWrap() + } + pos, _, err := h.getCurrentInfo() + if err != nil { + return err + } + if pos.X != 0 { + pos.X = 0 + h.updatePos(pos) + h.buffer.WriteByte(ansiterm.ANSI_CARRIAGE_RETURN) + } + return nil + + default: + return nil + } +} + +func (h *windowsAnsiEventHandler) CUU(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("CUU: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorVertical(-param) +} + +func (h *windowsAnsiEventHandler) CUD(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("CUD: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorVertical(param) +} + +func (h *windowsAnsiEventHandler) CUF(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("CUF: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorHorizontal(param) +} + +func (h *windowsAnsiEventHandler) CUB(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("CUB: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorHorizontal(-param) +} + +func (h *windowsAnsiEventHandler) CNL(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("CNL: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorLine(param) +} + +func (h *windowsAnsiEventHandler) CPL(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("CPL: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorLine(-param) +} + +func (h *windowsAnsiEventHandler) CHA(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("CHA: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorColumn(param) +} + +func (h *windowsAnsiEventHandler) VPA(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("VPA: [[%d]]", param) + h.clearWrap() + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + window := h.getCursorWindow(info) + position := info.CursorPosition + position.Y = window.Top + int16(param) - 1 + return h.setCursorPosition(position, window) +} + +func (h *windowsAnsiEventHandler) CUP(row int, col int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("CUP: [[%d %d]]", row, col) + h.clearWrap() + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + window := h.getCursorWindow(info) + position := COORD{window.Left + int16(col) - 1, window.Top + int16(row) - 1} + return h.setCursorPosition(position, window) +} + +func (h *windowsAnsiEventHandler) HVP(row int, col int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("HVP: [[%d %d]]", row, col) + h.clearWrap() + return h.CUP(row, col) +} + +func (h *windowsAnsiEventHandler) DECTCEM(visible bool) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("DECTCEM: [%v]", []string{strconv.FormatBool(visible)}) + h.clearWrap() + return nil +} + +func (h *windowsAnsiEventHandler) DECOM(enable bool) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("DECOM: [%v]", []string{strconv.FormatBool(enable)}) + h.clearWrap() + h.originMode = enable + return h.CUP(1, 1) +} + +func (h *windowsAnsiEventHandler) DECCOLM(use132 bool) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("DECCOLM: [%v]", []string{strconv.FormatBool(use132)}) + h.clearWrap() + if err := h.ED(2); err != nil { + return err + } + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + targetWidth := int16(80) + if use132 { + targetWidth = 132 + } + if info.Size.X < targetWidth { + if err := SetConsoleScreenBufferSize(h.fd, COORD{targetWidth, info.Size.Y}); err != nil { + h.logf("set buffer failed: %v", err) + return err + } + } + window := info.Window + window.Left = 0 + window.Right = targetWidth - 1 + if err := SetConsoleWindowInfo(h.fd, true, window); err != nil { + h.logf("set window failed: %v", err) + return err + } + if info.Size.X > targetWidth { + if err := SetConsoleScreenBufferSize(h.fd, COORD{targetWidth, info.Size.Y}); err != nil { + h.logf("set buffer failed: %v", err) + return err + } + } + return SetConsoleCursorPosition(h.fd, COORD{0, 0}) +} + +func (h *windowsAnsiEventHandler) ED(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("ED: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + + // [J -- Erases from the cursor to the end of the screen, including the cursor position. + // [1J -- Erases from the beginning of the screen to the cursor, including the cursor position. + // [2J -- Erases the complete display. The cursor does not move. + // Notes: + // -- Clearing the entire buffer, versus just the Window, works best for Windows Consoles + + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + var start COORD + var end COORD + + switch param { + case 0: + start = info.CursorPosition + end = COORD{info.Size.X - 1, info.Size.Y - 1} + + case 1: + start = COORD{0, 0} + end = info.CursorPosition + + case 2: + start = COORD{0, 0} + end = COORD{info.Size.X - 1, info.Size.Y - 1} + } + + err = h.clearRange(h.attributes, start, end) + if err != nil { + return err + } + + // If the whole buffer was cleared, move the window to the top while preserving + // the window-relative cursor position. + if param == 2 { + pos := info.CursorPosition + window := info.Window + pos.Y -= window.Top + window.Bottom -= window.Top + window.Top = 0 + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return err + } + if err := SetConsoleWindowInfo(h.fd, true, window); err != nil { + return err + } + } + + return nil +} + +func (h *windowsAnsiEventHandler) EL(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("EL: [%v]", strconv.Itoa(param)) + h.clearWrap() + + // [K -- Erases from the cursor to the end of the line, including the cursor position. + // [1K -- Erases from the beginning of the line to the cursor, including the cursor position. + // [2K -- Erases the complete line. + + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + var start COORD + var end COORD + + switch param { + case 0: + start = info.CursorPosition + end = COORD{info.Size.X, info.CursorPosition.Y} + + case 1: + start = COORD{0, info.CursorPosition.Y} + end = info.CursorPosition + + case 2: + start = COORD{0, info.CursorPosition.Y} + end = COORD{info.Size.X, info.CursorPosition.Y} + } + + err = h.clearRange(h.attributes, start, end) + if err != nil { + return err + } + + return nil +} + +func (h *windowsAnsiEventHandler) IL(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("IL: [%v]", strconv.Itoa(param)) + h.clearWrap() + return h.insertLines(param) +} + +func (h *windowsAnsiEventHandler) DL(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("DL: [%v]", strconv.Itoa(param)) + h.clearWrap() + return h.deleteLines(param) +} + +func (h *windowsAnsiEventHandler) ICH(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("ICH: [%v]", strconv.Itoa(param)) + h.clearWrap() + return h.insertCharacters(param) +} + +func (h *windowsAnsiEventHandler) DCH(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("DCH: [%v]", strconv.Itoa(param)) + h.clearWrap() + return h.deleteCharacters(param) +} + +func (h *windowsAnsiEventHandler) SGR(params []int) error { + if err := h.Flush(); err != nil { + return err + } + strings := []string{} + for _, v := range params { + strings = append(strings, strconv.Itoa(v)) + } + + h.logf("SGR: [%v]", strings) + + if len(params) <= 0 { + h.attributes = h.infoReset.Attributes + h.inverted = false + } else { + for _, attr := range params { + + if attr == ansiterm.ANSI_SGR_RESET { + h.attributes = h.infoReset.Attributes + h.inverted = false + continue + } + + h.attributes, h.inverted = collectAnsiIntoWindowsAttributes(h.attributes, h.inverted, h.infoReset.Attributes, int16(attr)) + } + } + + attributes := h.attributes + if h.inverted { + attributes = invertAttributes(attributes) + } + err := SetConsoleTextAttribute(h.fd, attributes) + if err != nil { + return err + } + + return nil +} + +func (h *windowsAnsiEventHandler) SU(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("SU: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.scrollUp(param) +} + +func (h *windowsAnsiEventHandler) SD(param int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("SD: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.scrollDown(param) +} + +func (h *windowsAnsiEventHandler) DA(params []string) error { + h.logf("DA: [%v]", params) + // DA cannot be implemented because it must send data on the VT100 input stream, + // which is not available to go-ansiterm. + return nil +} + +func (h *windowsAnsiEventHandler) DECSTBM(top int, bottom int) error { + if err := h.Flush(); err != nil { + return err + } + h.logf("DECSTBM: [%d, %d]", top, bottom) + + // Windows is 0 indexed, Linux is 1 indexed + h.sr.top = int16(top - 1) + h.sr.bottom = int16(bottom - 1) + + // This command also moves the cursor to the origin. + h.clearWrap() + return h.CUP(1, 1) +} + +func (h *windowsAnsiEventHandler) RI() error { + if err := h.Flush(); err != nil { + return err + } + h.logf("RI: []") + h.clearWrap() + + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + sr := h.effectiveSr(info.Window) + if info.CursorPosition.Y == sr.top { + return h.scrollDown(1) + } + + return h.moveCursorVertical(-1) +} + +func (h *windowsAnsiEventHandler) IND() error { + h.logf("IND: []") + return h.executeLF() +} + +func (h *windowsAnsiEventHandler) Flush() error { + h.curInfo = nil + if h.buffer.Len() > 0 { + h.logf("Flush: [%s]", h.buffer.Bytes()) + if _, err := h.buffer.WriteTo(h.file); err != nil { + return err + } + } + + if h.wrapNext && !h.drewMarginByte { + h.logf("Flush: drawing margin byte '%c'", h.marginByte) + + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + charInfo := []CHAR_INFO{{UnicodeChar: uint16(h.marginByte), Attributes: info.Attributes}} + size := COORD{1, 1} + position := COORD{0, 0} + region := SMALL_RECT{Left: info.CursorPosition.X, Top: info.CursorPosition.Y, Right: info.CursorPosition.X, Bottom: info.CursorPosition.Y} + if err := WriteConsoleOutput(h.fd, charInfo, size, position, ®ion); err != nil { + return err + } + h.drewMarginByte = true + } + return nil +} + +// cacheConsoleInfo ensures that the current console screen information has been queried +// since the last call to Flush(). It must be called before accessing h.curInfo or h.curPos. +func (h *windowsAnsiEventHandler) getCurrentInfo() (COORD, *CONSOLE_SCREEN_BUFFER_INFO, error) { + if h.curInfo == nil { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return COORD{}, nil, err + } + h.curInfo = info + h.curPos = info.CursorPosition + } + return h.curPos, h.curInfo, nil +} + +func (h *windowsAnsiEventHandler) updatePos(pos COORD) { + if h.curInfo == nil { + panic("failed to call getCurrentInfo before calling updatePos") + } + h.curPos = pos +} + +// clearWrap clears the state where the cursor is in the margin +// waiting for the next character before wrapping the line. This must +// be done before most operations that act on the cursor. +func (h *windowsAnsiEventHandler) clearWrap() { + h.wrapNext = false + h.drewMarginByte = false +} diff --git a/vendor/github.com/Nvveen/Gotty/LICENSE b/vendor/github.com/Nvveen/Gotty/LICENSE new file mode 100644 index 00000000..0b71c973 --- /dev/null +++ b/vendor/github.com/Nvveen/Gotty/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2012, Neal van Veen (nealvanveen@gmail.com) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The views and conclusions contained in the software and documentation are those +of the authors and should not be interpreted as representing official policies, +either expressed or implied, of the FreeBSD Project. diff --git a/vendor/github.com/Nvveen/Gotty/README b/vendor/github.com/Nvveen/Gotty/README new file mode 100644 index 00000000..a6b0d9a8 --- /dev/null +++ b/vendor/github.com/Nvveen/Gotty/README @@ -0,0 +1,5 @@ +Gotty is a library written in Go that determines and reads termcap database +files to produce an interface for interacting with the capabilities of a +terminal. +See the godoc documentation or the source code for more information about +function usage. diff --git a/vendor/github.com/Nvveen/Gotty/TODO b/vendor/github.com/Nvveen/Gotty/TODO new file mode 100644 index 00000000..47046053 --- /dev/null +++ b/vendor/github.com/Nvveen/Gotty/TODO @@ -0,0 +1,3 @@ +gotty.go:// TODO add more concurrency to name lookup, look for more opportunities. +all:// TODO add more documentation, with function usage in a doc.go file. +all:// TODO add more testing/benchmarking with go test. diff --git a/vendor/github.com/Nvveen/Gotty/attributes.go b/vendor/github.com/Nvveen/Gotty/attributes.go new file mode 100644 index 00000000..a4c005fa --- /dev/null +++ b/vendor/github.com/Nvveen/Gotty/attributes.go @@ -0,0 +1,514 @@ +// Copyright 2012 Neal van Veen. All rights reserved. +// Usage of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package gotty + +// Boolean capabilities +var BoolAttr = [...]string{ + "auto_left_margin", "bw", + "auto_right_margin", "am", + "no_esc_ctlc", "xsb", + "ceol_standout_glitch", "xhp", + "eat_newline_glitch", "xenl", + "erase_overstrike", "eo", + "generic_type", "gn", + "hard_copy", "hc", + "has_meta_key", "km", + "has_status_line", "hs", + "insert_null_glitch", "in", + "memory_above", "da", + "memory_below", "db", + "move_insert_mode", "mir", + "move_standout_mode", "msgr", + "over_strike", "os", + "status_line_esc_ok", "eslok", + "dest_tabs_magic_smso", "xt", + "tilde_glitch", "hz", + "transparent_underline", "ul", + "xon_xoff", "nxon", + "needs_xon_xoff", "nxon", + "prtr_silent", "mc5i", + "hard_cursor", "chts", + "non_rev_rmcup", "nrrmc", + "no_pad_char", "npc", + "non_dest_scroll_region", "ndscr", + "can_change", "ccc", + "back_color_erase", "bce", + "hue_lightness_saturation", "hls", + "col_addr_glitch", "xhpa", + "cr_cancels_micro_mode", "crxm", + "has_print_wheel", "daisy", + "row_addr_glitch", "xvpa", + "semi_auto_right_margin", "sam", + "cpi_changes_res", "cpix", + "lpi_changes_res", "lpix", + "backspaces_with_bs", "", + "crt_no_scrolling", "", + "no_correctly_working_cr", "", + "gnu_has_meta_key", "", + "linefeed_is_newline", "", + "has_hardware_tabs", "", + "return_does_clr_eol", "", +} + +// Numerical capabilities +var NumAttr = [...]string{ + "columns", "cols", + "init_tabs", "it", + "lines", "lines", + "lines_of_memory", "lm", + "magic_cookie_glitch", "xmc", + "padding_baud_rate", "pb", + "virtual_terminal", "vt", + "width_status_line", "wsl", + "num_labels", "nlab", + "label_height", "lh", + "label_width", "lw", + "max_attributes", "ma", + "maximum_windows", "wnum", + "max_colors", "colors", + "max_pairs", "pairs", + "no_color_video", "ncv", + "buffer_capacity", "bufsz", + "dot_vert_spacing", "spinv", + "dot_horz_spacing", "spinh", + "max_micro_address", "maddr", + "max_micro_jump", "mjump", + "micro_col_size", "mcs", + "micro_line_size", "mls", + "number_of_pins", "npins", + "output_res_char", "orc", + "output_res_line", "orl", + "output_res_horz_inch", "orhi", + "output_res_vert_inch", "orvi", + "print_rate", "cps", + "wide_char_size", "widcs", + "buttons", "btns", + "bit_image_entwining", "bitwin", + "bit_image_type", "bitype", + "magic_cookie_glitch_ul", "", + "carriage_return_delay", "", + "new_line_delay", "", + "backspace_delay", "", + "horizontal_tab_delay", "", + "number_of_function_keys", "", +} + +// String capabilities +var StrAttr = [...]string{ + "back_tab", "cbt", + "bell", "bel", + "carriage_return", "cr", + "change_scroll_region", "csr", + "clear_all_tabs", "tbc", + "clear_screen", "clear", + "clr_eol", "el", + "clr_eos", "ed", + "column_address", "hpa", + "command_character", "cmdch", + "cursor_address", "cup", + "cursor_down", "cud1", + "cursor_home", "home", + "cursor_invisible", "civis", + "cursor_left", "cub1", + "cursor_mem_address", "mrcup", + "cursor_normal", "cnorm", + "cursor_right", "cuf1", + "cursor_to_ll", "ll", + "cursor_up", "cuu1", + "cursor_visible", "cvvis", + "delete_character", "dch1", + "delete_line", "dl1", + "dis_status_line", "dsl", + "down_half_line", "hd", + "enter_alt_charset_mode", "smacs", + "enter_blink_mode", "blink", + "enter_bold_mode", "bold", + "enter_ca_mode", "smcup", + "enter_delete_mode", "smdc", + "enter_dim_mode", "dim", + "enter_insert_mode", "smir", + "enter_secure_mode", "invis", + "enter_protected_mode", "prot", + "enter_reverse_mode", "rev", + "enter_standout_mode", "smso", + "enter_underline_mode", "smul", + "erase_chars", "ech", + "exit_alt_charset_mode", "rmacs", + "exit_attribute_mode", "sgr0", + "exit_ca_mode", "rmcup", + "exit_delete_mode", "rmdc", + "exit_insert_mode", "rmir", + "exit_standout_mode", "rmso", + "exit_underline_mode", "rmul", + "flash_screen", "flash", + "form_feed", "ff", + "from_status_line", "fsl", + "init_1string", "is1", + "init_2string", "is2", + "init_3string", "is3", + "init_file", "if", + "insert_character", "ich1", + "insert_line", "il1", + "insert_padding", "ip", + "key_backspace", "kbs", + "key_catab", "ktbc", + "key_clear", "kclr", + "key_ctab", "kctab", + "key_dc", "kdch1", + "key_dl", "kdl1", + "key_down", "kcud1", + "key_eic", "krmir", + "key_eol", "kel", + "key_eos", "ked", + "key_f0", "kf0", + "key_f1", "kf1", + "key_f10", "kf10", + "key_f2", "kf2", + "key_f3", "kf3", + "key_f4", "kf4", + "key_f5", "kf5", + "key_f6", "kf6", + "key_f7", "kf7", + "key_f8", "kf8", + "key_f9", "kf9", + "key_home", "khome", + "key_ic", "kich1", + "key_il", "kil1", + "key_left", "kcub1", + "key_ll", "kll", + "key_npage", "knp", + "key_ppage", "kpp", + "key_right", "kcuf1", + "key_sf", "kind", + "key_sr", "kri", + "key_stab", "khts", + "key_up", "kcuu1", + "keypad_local", "rmkx", + "keypad_xmit", "smkx", + "lab_f0", "lf0", + "lab_f1", "lf1", + "lab_f10", "lf10", + "lab_f2", "lf2", + "lab_f3", "lf3", + "lab_f4", "lf4", + "lab_f5", "lf5", + "lab_f6", "lf6", + "lab_f7", "lf7", + "lab_f8", "lf8", + "lab_f9", "lf9", + "meta_off", "rmm", + "meta_on", "smm", + "newline", "_glitch", + "pad_char", "npc", + "parm_dch", "dch", + "parm_delete_line", "dl", + "parm_down_cursor", "cud", + "parm_ich", "ich", + "parm_index", "indn", + "parm_insert_line", "il", + "parm_left_cursor", "cub", + "parm_right_cursor", "cuf", + "parm_rindex", "rin", + "parm_up_cursor", "cuu", + "pkey_key", "pfkey", + "pkey_local", "pfloc", + "pkey_xmit", "pfx", + "print_screen", "mc0", + "prtr_off", "mc4", + "prtr_on", "mc5", + "repeat_char", "rep", + "reset_1string", "rs1", + "reset_2string", "rs2", + "reset_3string", "rs3", + "reset_file", "rf", + "restore_cursor", "rc", + "row_address", "mvpa", + "save_cursor", "row_address", + "scroll_forward", "ind", + "scroll_reverse", "ri", + "set_attributes", "sgr", + "set_tab", "hts", + "set_window", "wind", + "tab", "s_magic_smso", + "to_status_line", "tsl", + "underline_char", "uc", + "up_half_line", "hu", + "init_prog", "iprog", + "key_a1", "ka1", + "key_a3", "ka3", + "key_b2", "kb2", + "key_c1", "kc1", + "key_c3", "kc3", + "prtr_non", "mc5p", + "char_padding", "rmp", + "acs_chars", "acsc", + "plab_norm", "pln", + "key_btab", "kcbt", + "enter_xon_mode", "smxon", + "exit_xon_mode", "rmxon", + "enter_am_mode", "smam", + "exit_am_mode", "rmam", + "xon_character", "xonc", + "xoff_character", "xoffc", + "ena_acs", "enacs", + "label_on", "smln", + "label_off", "rmln", + "key_beg", "kbeg", + "key_cancel", "kcan", + "key_close", "kclo", + "key_command", "kcmd", + "key_copy", "kcpy", + "key_create", "kcrt", + "key_end", "kend", + "key_enter", "kent", + "key_exit", "kext", + "key_find", "kfnd", + "key_help", "khlp", + "key_mark", "kmrk", + "key_message", "kmsg", + "key_move", "kmov", + "key_next", "knxt", + "key_open", "kopn", + "key_options", "kopt", + "key_previous", "kprv", + "key_print", "kprt", + "key_redo", "krdo", + "key_reference", "kref", + "key_refresh", "krfr", + "key_replace", "krpl", + "key_restart", "krst", + "key_resume", "kres", + "key_save", "ksav", + "key_suspend", "kspd", + "key_undo", "kund", + "key_sbeg", "kBEG", + "key_scancel", "kCAN", + "key_scommand", "kCMD", + "key_scopy", "kCPY", + "key_screate", "kCRT", + "key_sdc", "kDC", + "key_sdl", "kDL", + "key_select", "kslt", + "key_send", "kEND", + "key_seol", "kEOL", + "key_sexit", "kEXT", + "key_sfind", "kFND", + "key_shelp", "kHLP", + "key_shome", "kHOM", + "key_sic", "kIC", + "key_sleft", "kLFT", + "key_smessage", "kMSG", + "key_smove", "kMOV", + "key_snext", "kNXT", + "key_soptions", "kOPT", + "key_sprevious", "kPRV", + "key_sprint", "kPRT", + "key_sredo", "kRDO", + "key_sreplace", "kRPL", + "key_sright", "kRIT", + "key_srsume", "kRES", + "key_ssave", "kSAV", + "key_ssuspend", "kSPD", + "key_sundo", "kUND", + "req_for_input", "rfi", + "key_f11", "kf11", + "key_f12", "kf12", + "key_f13", "kf13", + "key_f14", "kf14", + "key_f15", "kf15", + "key_f16", "kf16", + "key_f17", "kf17", + "key_f18", "kf18", + "key_f19", "kf19", + "key_f20", "kf20", + "key_f21", "kf21", + "key_f22", "kf22", + "key_f23", "kf23", + "key_f24", "kf24", + "key_f25", "kf25", + "key_f26", "kf26", + "key_f27", "kf27", + "key_f28", "kf28", + "key_f29", "kf29", + "key_f30", "kf30", + "key_f31", "kf31", + "key_f32", "kf32", + "key_f33", "kf33", + "key_f34", "kf34", + "key_f35", "kf35", + "key_f36", "kf36", + "key_f37", "kf37", + "key_f38", "kf38", + "key_f39", "kf39", + "key_f40", "kf40", + "key_f41", "kf41", + "key_f42", "kf42", + "key_f43", "kf43", + "key_f44", "kf44", + "key_f45", "kf45", + "key_f46", "kf46", + "key_f47", "kf47", + "key_f48", "kf48", + "key_f49", "kf49", + "key_f50", "kf50", + "key_f51", "kf51", + "key_f52", "kf52", + "key_f53", "kf53", + "key_f54", "kf54", + "key_f55", "kf55", + "key_f56", "kf56", + "key_f57", "kf57", + "key_f58", "kf58", + "key_f59", "kf59", + "key_f60", "kf60", + "key_f61", "kf61", + "key_f62", "kf62", + "key_f63", "kf63", + "clr_bol", "el1", + "clear_margins", "mgc", + "set_left_margin", "smgl", + "set_right_margin", "smgr", + "label_format", "fln", + "set_clock", "sclk", + "display_clock", "dclk", + "remove_clock", "rmclk", + "create_window", "cwin", + "goto_window", "wingo", + "hangup", "hup", + "dial_phone", "dial", + "quick_dial", "qdial", + "tone", "tone", + "pulse", "pulse", + "flash_hook", "hook", + "fixed_pause", "pause", + "wait_tone", "wait", + "user0", "u0", + "user1", "u1", + "user2", "u2", + "user3", "u3", + "user4", "u4", + "user5", "u5", + "user6", "u6", + "user7", "u7", + "user8", "u8", + "user9", "u9", + "orig_pair", "op", + "orig_colors", "oc", + "initialize_color", "initc", + "initialize_pair", "initp", + "set_color_pair", "scp", + "set_foreground", "setf", + "set_background", "setb", + "change_char_pitch", "cpi", + "change_line_pitch", "lpi", + "change_res_horz", "chr", + "change_res_vert", "cvr", + "define_char", "defc", + "enter_doublewide_mode", "swidm", + "enter_draft_quality", "sdrfq", + "enter_italics_mode", "sitm", + "enter_leftward_mode", "slm", + "enter_micro_mode", "smicm", + "enter_near_letter_quality", "snlq", + "enter_normal_quality", "snrmq", + "enter_shadow_mode", "sshm", + "enter_subscript_mode", "ssubm", + "enter_superscript_mode", "ssupm", + "enter_upward_mode", "sum", + "exit_doublewide_mode", "rwidm", + "exit_italics_mode", "ritm", + "exit_leftward_mode", "rlm", + "exit_micro_mode", "rmicm", + "exit_shadow_mode", "rshm", + "exit_subscript_mode", "rsubm", + "exit_superscript_mode", "rsupm", + "exit_upward_mode", "rum", + "micro_column_address", "mhpa", + "micro_down", "mcud1", + "micro_left", "mcub1", + "micro_right", "mcuf1", + "micro_row_address", "mvpa", + "micro_up", "mcuu1", + "order_of_pins", "porder", + "parm_down_micro", "mcud", + "parm_left_micro", "mcub", + "parm_right_micro", "mcuf", + "parm_up_micro", "mcuu", + "select_char_set", "scs", + "set_bottom_margin", "smgb", + "set_bottom_margin_parm", "smgbp", + "set_left_margin_parm", "smglp", + "set_right_margin_parm", "smgrp", + "set_top_margin", "smgt", + "set_top_margin_parm", "smgtp", + "start_bit_image", "sbim", + "start_char_set_def", "scsd", + "stop_bit_image", "rbim", + "stop_char_set_def", "rcsd", + "subscript_characters", "subcs", + "superscript_characters", "supcs", + "these_cause_cr", "docr", + "zero_motion", "zerom", + "char_set_names", "csnm", + "key_mouse", "kmous", + "mouse_info", "minfo", + "req_mouse_pos", "reqmp", + "get_mouse", "getm", + "set_a_foreground", "setaf", + "set_a_background", "setab", + "pkey_plab", "pfxl", + "device_type", "devt", + "code_set_init", "csin", + "set0_des_seq", "s0ds", + "set1_des_seq", "s1ds", + "set2_des_seq", "s2ds", + "set3_des_seq", "s3ds", + "set_lr_margin", "smglr", + "set_tb_margin", "smgtb", + "bit_image_repeat", "birep", + "bit_image_newline", "binel", + "bit_image_carriage_return", "bicr", + "color_names", "colornm", + "define_bit_image_region", "defbi", + "end_bit_image_region", "endbi", + "set_color_band", "setcolor", + "set_page_length", "slines", + "display_pc_char", "dispc", + "enter_pc_charset_mode", "smpch", + "exit_pc_charset_mode", "rmpch", + "enter_scancode_mode", "smsc", + "exit_scancode_mode", "rmsc", + "pc_term_options", "pctrm", + "scancode_escape", "scesc", + "alt_scancode_esc", "scesa", + "enter_horizontal_hl_mode", "ehhlm", + "enter_left_hl_mode", "elhlm", + "enter_low_hl_mode", "elohlm", + "enter_right_hl_mode", "erhlm", + "enter_top_hl_mode", "ethlm", + "enter_vertical_hl_mode", "evhlm", + "set_a_attributes", "sgr1", + "set_pglen_inch", "slength", + "termcap_init2", "", + "termcap_reset", "", + "linefeed_if_not_lf", "", + "backspace_if_not_bs", "", + "other_non_function_keys", "", + "arrow_key_map", "", + "acs_ulcorner", "", + "acs_llcorner", "", + "acs_urcorner", "", + "acs_lrcorner", "", + "acs_ltee", "", + "acs_rtee", "", + "acs_btee", "", + "acs_ttee", "", + "acs_hline", "", + "acs_vline", "", + "acs_plus", "", + "memory_lock", "", + "memory_unlock", "", + "box_chars_1", "", +} diff --git a/vendor/github.com/Nvveen/Gotty/gotty.go b/vendor/github.com/Nvveen/Gotty/gotty.go new file mode 100644 index 00000000..093cbf37 --- /dev/null +++ b/vendor/github.com/Nvveen/Gotty/gotty.go @@ -0,0 +1,238 @@ +// Copyright 2012 Neal van Veen. All rights reserved. +// Usage of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Gotty is a Go-package for reading and parsing the terminfo database +package gotty + +// TODO add more concurrency to name lookup, look for more opportunities. + +import ( + "encoding/binary" + "errors" + "fmt" + "os" + "reflect" + "strings" + "sync" +) + +// Open a terminfo file by the name given and construct a TermInfo object. +// If something went wrong reading the terminfo database file, an error is +// returned. +func OpenTermInfo(termName string) (*TermInfo, error) { + var term *TermInfo + var err error + // Find the environment variables + termloc := os.Getenv("TERMINFO") + if len(termloc) == 0 { + // Search like ncurses + locations := []string{os.Getenv("HOME") + "/.terminfo/", "/etc/terminfo/", + "/lib/terminfo/", "/usr/share/terminfo/"} + var path string + for _, str := range locations { + // Construct path + path = str + string(termName[0]) + "/" + termName + // Check if path can be opened + file, _ := os.Open(path) + if file != nil { + // Path can open, fall out and use current path + file.Close() + break + } + } + if len(path) > 0 { + term, err = readTermInfo(path) + } else { + err = errors.New(fmt.Sprintf("No terminfo file(-location) found")) + } + } + return term, err +} + +// Open a terminfo file from the environment variable containing the current +// terminal name and construct a TermInfo object. If something went wrong +// reading the terminfo database file, an error is returned. +func OpenTermInfoEnv() (*TermInfo, error) { + termenv := os.Getenv("TERM") + return OpenTermInfo(termenv) +} + +// Return an attribute by the name attr provided. If none can be found, +// an error is returned. +func (term *TermInfo) GetAttribute(attr string) (stacker, error) { + // Channel to store the main value in. + var value stacker + // Add a blocking WaitGroup + var block sync.WaitGroup + // Keep track of variable being written. + written := false + // Function to put into goroutine. + f := func(ats interface{}) { + var ok bool + var v stacker + // Switch on type of map to use and assign value to it. + switch reflect.TypeOf(ats).Elem().Kind() { + case reflect.Bool: + v, ok = ats.(map[string]bool)[attr] + case reflect.Int16: + v, ok = ats.(map[string]int16)[attr] + case reflect.String: + v, ok = ats.(map[string]string)[attr] + } + // If ok, a value is found, so we can write. + if ok { + value = v + written = true + } + // Goroutine is done + block.Done() + } + block.Add(3) + // Go for all 3 attribute lists. + go f(term.boolAttributes) + go f(term.numAttributes) + go f(term.strAttributes) + // Wait until every goroutine is done. + block.Wait() + // If a value has been written, return it. + if written { + return value, nil + } + // Otherwise, error. + return nil, fmt.Errorf("Erorr finding attribute") +} + +// Return an attribute by the name attr provided. If none can be found, +// an error is returned. A name is first converted to its termcap value. +func (term *TermInfo) GetAttributeName(name string) (stacker, error) { + tc := GetTermcapName(name) + return term.GetAttribute(tc) +} + +// A utility function that finds and returns the termcap equivalent of a +// variable name. +func GetTermcapName(name string) string { + // Termcap name + var tc string + // Blocking group + var wait sync.WaitGroup + // Function to put into a goroutine + f := func(attrs []string) { + // Find the string corresponding to the name + for i, s := range attrs { + if s == name { + tc = attrs[i+1] + } + } + // Goroutine is finished + wait.Done() + } + wait.Add(3) + // Go for all 3 attribute lists + go f(BoolAttr[:]) + go f(NumAttr[:]) + go f(StrAttr[:]) + // Wait until every goroutine is done + wait.Wait() + // Return the termcap name + return tc +} + +// This function takes a path to a terminfo file and reads it in binary +// form to construct the actual TermInfo file. +func readTermInfo(path string) (*TermInfo, error) { + // Open the terminfo file + file, err := os.Open(path) + defer file.Close() + if err != nil { + return nil, err + } + + // magic, nameSize, boolSize, nrSNum, nrOffsetsStr, strSize + // Header is composed of the magic 0432 octal number, size of the name + // section, size of the boolean section, the amount of number values, + // the number of offsets of strings, and the size of the string section. + var header [6]int16 + // Byte array is used to read in byte values + var byteArray []byte + // Short array is used to read in short values + var shArray []int16 + // TermInfo object to store values + var term TermInfo + + // Read in the header + err = binary.Read(file, binary.LittleEndian, &header) + if err != nil { + return nil, err + } + // If magic number isn't there or isn't correct, we have the wrong filetype + if header[0] != 0432 { + return nil, errors.New(fmt.Sprintf("Wrong filetype")) + } + + // Read in the names + byteArray = make([]byte, header[1]) + err = binary.Read(file, binary.LittleEndian, &byteArray) + if err != nil { + return nil, err + } + term.Names = strings.Split(string(byteArray), "|") + + // Read in the booleans + byteArray = make([]byte, header[2]) + err = binary.Read(file, binary.LittleEndian, &byteArray) + if err != nil { + return nil, err + } + term.boolAttributes = make(map[string]bool) + for i, b := range byteArray { + if b == 1 { + term.boolAttributes[BoolAttr[i*2+1]] = true + } + } + // If the number of bytes read is not even, a byte for alignment is added + if len(byteArray)%2 != 0 { + err = binary.Read(file, binary.LittleEndian, make([]byte, 1)) + if err != nil { + return nil, err + } + } + + // Read in shorts + shArray = make([]int16, header[3]) + err = binary.Read(file, binary.LittleEndian, &shArray) + if err != nil { + return nil, err + } + term.numAttributes = make(map[string]int16) + for i, n := range shArray { + if n != 0377 && n > -1 { + term.numAttributes[NumAttr[i*2+1]] = n + } + } + + // Read the offsets into the short array + shArray = make([]int16, header[4]) + err = binary.Read(file, binary.LittleEndian, &shArray) + if err != nil { + return nil, err + } + // Read the actual strings in the byte array + byteArray = make([]byte, header[5]) + err = binary.Read(file, binary.LittleEndian, &byteArray) + if err != nil { + return nil, err + } + term.strAttributes = make(map[string]string) + // We get an offset, and then iterate until the string is null-terminated + for i, offset := range shArray { + if offset > -1 { + r := offset + for ; byteArray[r] != 0; r++ { + } + term.strAttributes[StrAttr[i*2+1]] = string(byteArray[offset:r]) + } + } + return &term, nil +} diff --git a/vendor/github.com/Nvveen/Gotty/parser.go b/vendor/github.com/Nvveen/Gotty/parser.go new file mode 100644 index 00000000..a9d5d23c --- /dev/null +++ b/vendor/github.com/Nvveen/Gotty/parser.go @@ -0,0 +1,362 @@ +// Copyright 2012 Neal van Veen. All rights reserved. +// Usage of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package gotty + +import ( + "bytes" + "errors" + "fmt" + "regexp" + "strconv" + "strings" +) + +var exp = [...]string{ + "%%", + "%c", + "%s", + "%p(\\d)", + "%P([A-z])", + "%g([A-z])", + "%'(.)'", + "%{([0-9]+)}", + "%l", + "%\\+|%-|%\\*|%/|%m", + "%&|%\\||%\\^", + "%=|%>|%<", + "%A|%O", + "%!|%~", + "%i", + "%(:[\\ #\\-\\+]{0,4})?(\\d+\\.\\d+|\\d+)?[doxXs]", + "%\\?(.*?);", +} + +var regex *regexp.Regexp +var staticVar map[byte]stacker + +// Parses the attribute that is received with name attr and parameters params. +func (term *TermInfo) Parse(attr string, params ...interface{}) (string, error) { + // Get the attribute name first. + iface, err := term.GetAttribute(attr) + str, ok := iface.(string) + if err != nil { + return "", err + } + if !ok { + return str, errors.New("Only string capabilities can be parsed.") + } + // Construct the hidden parser struct so we can use a recursive stack based + // parser. + ps := &parser{} + // Dynamic variables only exist in this context. + ps.dynamicVar = make(map[byte]stacker, 26) + ps.parameters = make([]stacker, len(params)) + // Convert the parameters to insert them into the parser struct. + for i, x := range params { + ps.parameters[i] = x + } + // Recursively walk and return. + result, err := ps.walk(str) + return result, err +} + +// Parses the attribute that is received with name attr and parameters params. +// Only works on full name of a capability that is given, which it uses to +// search for the termcap name. +func (term *TermInfo) ParseName(attr string, params ...interface{}) (string, error) { + tc := GetTermcapName(attr) + return term.Parse(tc, params) +} + +// Identify each token in a stack based manner and do the actual parsing. +func (ps *parser) walk(attr string) (string, error) { + // We use a buffer to get the modified string. + var buf bytes.Buffer + // Next, find and identify all tokens by their indices and strings. + tokens := regex.FindAllStringSubmatch(attr, -1) + if len(tokens) == 0 { + return attr, nil + } + indices := regex.FindAllStringIndex(attr, -1) + q := 0 // q counts the matches of one token + // Iterate through the string per character. + for i := 0; i < len(attr); i++ { + // If the current position is an identified token, execute the following + // steps. + if q < len(indices) && i >= indices[q][0] && i < indices[q][1] { + // Switch on token. + switch { + case tokens[q][0][:2] == "%%": + // Literal percentage character. + buf.WriteByte('%') + case tokens[q][0][:2] == "%c": + // Pop a character. + c, err := ps.st.pop() + if err != nil { + return buf.String(), err + } + buf.WriteByte(c.(byte)) + case tokens[q][0][:2] == "%s": + // Pop a string. + str, err := ps.st.pop() + if err != nil { + return buf.String(), err + } + if _, ok := str.(string); !ok { + return buf.String(), errors.New("Stack head is not a string") + } + buf.WriteString(str.(string)) + case tokens[q][0][:2] == "%p": + // Push a parameter on the stack. + index, err := strconv.ParseInt(tokens[q][1], 10, 8) + index-- + if err != nil { + return buf.String(), err + } + if int(index) >= len(ps.parameters) { + return buf.String(), errors.New("Parameters index out of bound") + } + ps.st.push(ps.parameters[index]) + case tokens[q][0][:2] == "%P": + // Pop a variable from the stack as a dynamic or static variable. + val, err := ps.st.pop() + if err != nil { + return buf.String(), err + } + index := tokens[q][2] + if len(index) > 1 { + errorStr := fmt.Sprintf("%s is not a valid dynamic variables index", + index) + return buf.String(), errors.New(errorStr) + } + // Specify either dynamic or static. + if index[0] >= 'a' && index[0] <= 'z' { + ps.dynamicVar[index[0]] = val + } else if index[0] >= 'A' && index[0] <= 'Z' { + staticVar[index[0]] = val + } + case tokens[q][0][:2] == "%g": + // Push a variable from the stack as a dynamic or static variable. + index := tokens[q][3] + if len(index) > 1 { + errorStr := fmt.Sprintf("%s is not a valid static variables index", + index) + return buf.String(), errors.New(errorStr) + } + var val stacker + if index[0] >= 'a' && index[0] <= 'z' { + val = ps.dynamicVar[index[0]] + } else if index[0] >= 'A' && index[0] <= 'Z' { + val = staticVar[index[0]] + } + ps.st.push(val) + case tokens[q][0][:2] == "%'": + // Push a character constant. + con := tokens[q][4] + if len(con) > 1 { + errorStr := fmt.Sprintf("%s is not a valid character constant", con) + return buf.String(), errors.New(errorStr) + } + ps.st.push(con[0]) + case tokens[q][0][:2] == "%{": + // Push an integer constant. + con, err := strconv.ParseInt(tokens[q][5], 10, 32) + if err != nil { + return buf.String(), err + } + ps.st.push(con) + case tokens[q][0][:2] == "%l": + // Push the length of the string that is popped from the stack. + popStr, err := ps.st.pop() + if err != nil { + return buf.String(), err + } + if _, ok := popStr.(string); !ok { + errStr := fmt.Sprintf("Stack head is not a string") + return buf.String(), errors.New(errStr) + } + ps.st.push(len(popStr.(string))) + case tokens[q][0][:2] == "%?": + // If-then-else construct. First, the whole string is identified and + // then inside this substring, we can specify which parts to switch on. + ifReg, _ := regexp.Compile("%\\?(.*)%t(.*)%e(.*);|%\\?(.*)%t(.*);") + ifTokens := ifReg.FindStringSubmatch(tokens[q][0]) + var ( + ifStr string + err error + ) + // Parse the if-part to determine if-else. + if len(ifTokens[1]) > 0 { + ifStr, err = ps.walk(ifTokens[1]) + } else { // else + ifStr, err = ps.walk(ifTokens[4]) + } + // Return any errors + if err != nil { + return buf.String(), err + } else if len(ifStr) > 0 { + // Self-defined limitation, not sure if this is correct, but didn't + // seem like it. + return buf.String(), errors.New("If-clause cannot print statements") + } + var thenStr string + // Pop the first value that is set by parsing the if-clause. + choose, err := ps.st.pop() + if err != nil { + return buf.String(), err + } + // Switch to if or else. + if choose.(int) == 0 && len(ifTokens[1]) > 0 { + thenStr, err = ps.walk(ifTokens[3]) + } else if choose.(int) != 0 { + if len(ifTokens[1]) > 0 { + thenStr, err = ps.walk(ifTokens[2]) + } else { + thenStr, err = ps.walk(ifTokens[5]) + } + } + if err != nil { + return buf.String(), err + } + buf.WriteString(thenStr) + case tokens[q][0][len(tokens[q][0])-1] == 'd': // Fallthrough for printing + fallthrough + case tokens[q][0][len(tokens[q][0])-1] == 'o': // digits. + fallthrough + case tokens[q][0][len(tokens[q][0])-1] == 'x': + fallthrough + case tokens[q][0][len(tokens[q][0])-1] == 'X': + fallthrough + case tokens[q][0][len(tokens[q][0])-1] == 's': + token := tokens[q][0] + // Remove the : that comes before a flag. + if token[1] == ':' { + token = token[:1] + token[2:] + } + digit, err := ps.st.pop() + if err != nil { + return buf.String(), err + } + // The rest is determined like the normal formatted prints. + digitStr := fmt.Sprintf(token, digit.(int)) + buf.WriteString(digitStr) + case tokens[q][0][:2] == "%i": + // Increment the parameters by one. + if len(ps.parameters) < 2 { + return buf.String(), errors.New("Not enough parameters to increment.") + } + val1, val2 := ps.parameters[0].(int), ps.parameters[1].(int) + val1++ + val2++ + ps.parameters[0], ps.parameters[1] = val1, val2 + default: + // The rest of the tokens is a special case, where two values are + // popped and then operated on by the token that comes after them. + op1, err := ps.st.pop() + if err != nil { + return buf.String(), err + } + op2, err := ps.st.pop() + if err != nil { + return buf.String(), err + } + var result stacker + switch tokens[q][0][:2] { + case "%+": + // Addition + result = op2.(int) + op1.(int) + case "%-": + // Subtraction + result = op2.(int) - op1.(int) + case "%*": + // Multiplication + result = op2.(int) * op1.(int) + case "%/": + // Division + result = op2.(int) / op1.(int) + case "%m": + // Modulo + result = op2.(int) % op1.(int) + case "%&": + // Bitwise AND + result = op2.(int) & op1.(int) + case "%|": + // Bitwise OR + result = op2.(int) | op1.(int) + case "%^": + // Bitwise XOR + result = op2.(int) ^ op1.(int) + case "%=": + // Equals + result = op2 == op1 + case "%>": + // Greater-than + result = op2.(int) > op1.(int) + case "%<": + // Lesser-than + result = op2.(int) < op1.(int) + case "%A": + // Logical AND + result = op2.(bool) && op1.(bool) + case "%O": + // Logical OR + result = op2.(bool) || op1.(bool) + case "%!": + // Logical complement + result = !op1.(bool) + case "%~": + // Bitwise complement + result = ^(op1.(int)) + } + ps.st.push(result) + } + + i = indices[q][1] - 1 + q++ + } else { + // We are not "inside" a token, so just skip until the end or the next + // token, and add all characters to the buffer. + j := i + if q != len(indices) { + for !(j >= indices[q][0] && j < indices[q][1]) { + j++ + } + } else { + j = len(attr) + } + buf.WriteString(string(attr[i:j])) + i = j + } + } + // Return the buffer as a string. + return buf.String(), nil +} + +// Push a stacker-value onto the stack. +func (st *stack) push(s stacker) { + *st = append(*st, s) +} + +// Pop a stacker-value from the stack. +func (st *stack) pop() (stacker, error) { + if len(*st) == 0 { + return nil, errors.New("Stack is empty.") + } + newStack := make(stack, len(*st)-1) + val := (*st)[len(*st)-1] + copy(newStack, (*st)[:len(*st)-1]) + *st = newStack + return val, nil +} + +// Initialize regexes and the static vars (that don't get changed between +// calls. +func init() { + // Initialize the main regex. + expStr := strings.Join(exp[:], "|") + regex, _ = regexp.Compile(expStr) + // Initialize the static variables. + staticVar = make(map[byte]stacker, 26) +} diff --git a/vendor/github.com/Nvveen/Gotty/types.go b/vendor/github.com/Nvveen/Gotty/types.go new file mode 100644 index 00000000..9bcc65e9 --- /dev/null +++ b/vendor/github.com/Nvveen/Gotty/types.go @@ -0,0 +1,23 @@ +// Copyright 2012 Neal van Veen. All rights reserved. +// Usage of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package gotty + +type TermInfo struct { + boolAttributes map[string]bool + numAttributes map[string]int16 + strAttributes map[string]string + // The various names of the TermInfo file. + Names []string +} + +type stacker interface { +} +type stack []stacker + +type parser struct { + st stack + parameters []stacker + dynamicVar map[byte]stacker +} diff --git a/vendor/github.com/cenkalti/backoff/v4/.gitignore b/vendor/github.com/cenkalti/backoff/v4/.gitignore new file mode 100644 index 00000000..50d95c54 --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v4/.gitignore @@ -0,0 +1,25 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe + +# IDEs +.idea/ diff --git a/vendor/github.com/cenkalti/backoff/v4/LICENSE b/vendor/github.com/cenkalti/backoff/v4/LICENSE new file mode 100644 index 00000000..89b81799 --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v4/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Cenk Altı + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/cenkalti/backoff/v4/README.md b/vendor/github.com/cenkalti/backoff/v4/README.md new file mode 100644 index 00000000..9433004a --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v4/README.md @@ -0,0 +1,30 @@ +# Exponential Backoff [![GoDoc][godoc image]][godoc] [![Coverage Status][coveralls image]][coveralls] + +This is a Go port of the exponential backoff algorithm from [Google's HTTP Client Library for Java][google-http-java-client]. + +[Exponential backoff][exponential backoff wiki] +is an algorithm that uses feedback to multiplicatively decrease the rate of some process, +in order to gradually find an acceptable rate. +The retries exponentially increase and stop increasing when a certain threshold is met. + +## Usage + +Import path is `github.com/cenkalti/backoff/v4`. Please note the version part at the end. + +Use https://pkg.go.dev/github.com/cenkalti/backoff/v4 to view the documentation. + +## Contributing + +* I would like to keep this library as small as possible. +* Please don't send a PR without opening an issue and discussing it first. +* If proposed change is not a common use case, I will probably not accept it. + +[godoc]: https://pkg.go.dev/github.com/cenkalti/backoff/v4 +[godoc image]: https://godoc.org/github.com/cenkalti/backoff?status.png +[coveralls]: https://coveralls.io/github/cenkalti/backoff?branch=master +[coveralls image]: https://coveralls.io/repos/github/cenkalti/backoff/badge.svg?branch=master + +[google-http-java-client]: https://github.com/google/google-http-java-client/blob/da1aa993e90285ec18579f1553339b00e19b3ab5/google-http-client/src/main/java/com/google/api/client/util/ExponentialBackOff.java +[exponential backoff wiki]: http://en.wikipedia.org/wiki/Exponential_backoff + +[advanced example]: https://pkg.go.dev/github.com/cenkalti/backoff/v4?tab=doc#pkg-examples diff --git a/vendor/github.com/cenkalti/backoff/v4/backoff.go b/vendor/github.com/cenkalti/backoff/v4/backoff.go new file mode 100644 index 00000000..3676ee40 --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v4/backoff.go @@ -0,0 +1,66 @@ +// Package backoff implements backoff algorithms for retrying operations. +// +// Use Retry function for retrying operations that may fail. +// If Retry does not meet your needs, +// copy/paste the function into your project and modify as you wish. +// +// There is also Ticker type similar to time.Ticker. +// You can use it if you need to work with channels. +// +// See Examples section below for usage examples. +package backoff + +import "time" + +// BackOff is a backoff policy for retrying an operation. +type BackOff interface { + // NextBackOff returns the duration to wait before retrying the operation, + // or backoff. Stop to indicate that no more retries should be made. + // + // Example usage: + // + // duration := backoff.NextBackOff(); + // if (duration == backoff.Stop) { + // // Do not retry operation. + // } else { + // // Sleep for duration and retry operation. + // } + // + NextBackOff() time.Duration + + // Reset to initial state. + Reset() +} + +// Stop indicates that no more retries should be made for use in NextBackOff(). +const Stop time.Duration = -1 + +// ZeroBackOff is a fixed backoff policy whose backoff time is always zero, +// meaning that the operation is retried immediately without waiting, indefinitely. +type ZeroBackOff struct{} + +func (b *ZeroBackOff) Reset() {} + +func (b *ZeroBackOff) NextBackOff() time.Duration { return 0 } + +// StopBackOff is a fixed backoff policy that always returns backoff.Stop for +// NextBackOff(), meaning that the operation should never be retried. +type StopBackOff struct{} + +func (b *StopBackOff) Reset() {} + +func (b *StopBackOff) NextBackOff() time.Duration { return Stop } + +// ConstantBackOff is a backoff policy that always returns the same backoff delay. +// This is in contrast to an exponential backoff policy, +// which returns a delay that grows longer as you call NextBackOff() over and over again. +type ConstantBackOff struct { + Interval time.Duration +} + +func (b *ConstantBackOff) Reset() {} +func (b *ConstantBackOff) NextBackOff() time.Duration { return b.Interval } + +func NewConstantBackOff(d time.Duration) *ConstantBackOff { + return &ConstantBackOff{Interval: d} +} diff --git a/vendor/github.com/cenkalti/backoff/v4/context.go b/vendor/github.com/cenkalti/backoff/v4/context.go new file mode 100644 index 00000000..48482330 --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v4/context.go @@ -0,0 +1,62 @@ +package backoff + +import ( + "context" + "time" +) + +// BackOffContext is a backoff policy that stops retrying after the context +// is canceled. +type BackOffContext interface { // nolint: golint + BackOff + Context() context.Context +} + +type backOffContext struct { + BackOff + ctx context.Context +} + +// WithContext returns a BackOffContext with context ctx +// +// ctx must not be nil +func WithContext(b BackOff, ctx context.Context) BackOffContext { // nolint: golint + if ctx == nil { + panic("nil context") + } + + if b, ok := b.(*backOffContext); ok { + return &backOffContext{ + BackOff: b.BackOff, + ctx: ctx, + } + } + + return &backOffContext{ + BackOff: b, + ctx: ctx, + } +} + +func getContext(b BackOff) context.Context { + if cb, ok := b.(BackOffContext); ok { + return cb.Context() + } + if tb, ok := b.(*backOffTries); ok { + return getContext(tb.delegate) + } + return context.Background() +} + +func (b *backOffContext) Context() context.Context { + return b.ctx +} + +func (b *backOffContext) NextBackOff() time.Duration { + select { + case <-b.ctx.Done(): + return Stop + default: + return b.BackOff.NextBackOff() + } +} diff --git a/vendor/github.com/cenkalti/backoff/v4/exponential.go b/vendor/github.com/cenkalti/backoff/v4/exponential.go new file mode 100644 index 00000000..aac99f19 --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v4/exponential.go @@ -0,0 +1,216 @@ +package backoff + +import ( + "math/rand" + "time" +) + +/* +ExponentialBackOff is a backoff implementation that increases the backoff +period for each retry attempt using a randomization function that grows exponentially. + +NextBackOff() is calculated using the following formula: + + randomized interval = + RetryInterval * (random value in range [1 - RandomizationFactor, 1 + RandomizationFactor]) + +In other words NextBackOff() will range between the randomization factor +percentage below and above the retry interval. + +For example, given the following parameters: + + RetryInterval = 2 + RandomizationFactor = 0.5 + Multiplier = 2 + +the actual backoff period used in the next retry attempt will range between 1 and 3 seconds, +multiplied by the exponential, that is, between 2 and 6 seconds. + +Note: MaxInterval caps the RetryInterval and not the randomized interval. + +If the time elapsed since an ExponentialBackOff instance is created goes past the +MaxElapsedTime, then the method NextBackOff() starts returning backoff.Stop. + +The elapsed time can be reset by calling Reset(). + +Example: Given the following default arguments, for 10 tries the sequence will be, +and assuming we go over the MaxElapsedTime on the 10th try: + + Request # RetryInterval (seconds) Randomized Interval (seconds) + + 1 0.5 [0.25, 0.75] + 2 0.75 [0.375, 1.125] + 3 1.125 [0.562, 1.687] + 4 1.687 [0.8435, 2.53] + 5 2.53 [1.265, 3.795] + 6 3.795 [1.897, 5.692] + 7 5.692 [2.846, 8.538] + 8 8.538 [4.269, 12.807] + 9 12.807 [6.403, 19.210] + 10 19.210 backoff.Stop + +Note: Implementation is not thread-safe. +*/ +type ExponentialBackOff struct { + InitialInterval time.Duration + RandomizationFactor float64 + Multiplier float64 + MaxInterval time.Duration + // After MaxElapsedTime the ExponentialBackOff returns Stop. + // It never stops if MaxElapsedTime == 0. + MaxElapsedTime time.Duration + Stop time.Duration + Clock Clock + + currentInterval time.Duration + startTime time.Time +} + +// Clock is an interface that returns current time for BackOff. +type Clock interface { + Now() time.Time +} + +// ExponentialBackOffOpts is a function type used to configure ExponentialBackOff options. +type ExponentialBackOffOpts func(*ExponentialBackOff) + +// Default values for ExponentialBackOff. +const ( + DefaultInitialInterval = 500 * time.Millisecond + DefaultRandomizationFactor = 0.5 + DefaultMultiplier = 1.5 + DefaultMaxInterval = 60 * time.Second + DefaultMaxElapsedTime = 15 * time.Minute +) + +// NewExponentialBackOff creates an instance of ExponentialBackOff using default values. +func NewExponentialBackOff(opts ...ExponentialBackOffOpts) *ExponentialBackOff { + b := &ExponentialBackOff{ + InitialInterval: DefaultInitialInterval, + RandomizationFactor: DefaultRandomizationFactor, + Multiplier: DefaultMultiplier, + MaxInterval: DefaultMaxInterval, + MaxElapsedTime: DefaultMaxElapsedTime, + Stop: Stop, + Clock: SystemClock, + } + for _, fn := range opts { + fn(b) + } + b.Reset() + return b +} + +// WithInitialInterval sets the initial interval between retries. +func WithInitialInterval(duration time.Duration) ExponentialBackOffOpts { + return func(ebo *ExponentialBackOff) { + ebo.InitialInterval = duration + } +} + +// WithRandomizationFactor sets the randomization factor to add jitter to intervals. +func WithRandomizationFactor(randomizationFactor float64) ExponentialBackOffOpts { + return func(ebo *ExponentialBackOff) { + ebo.RandomizationFactor = randomizationFactor + } +} + +// WithMultiplier sets the multiplier for increasing the interval after each retry. +func WithMultiplier(multiplier float64) ExponentialBackOffOpts { + return func(ebo *ExponentialBackOff) { + ebo.Multiplier = multiplier + } +} + +// WithMaxInterval sets the maximum interval between retries. +func WithMaxInterval(duration time.Duration) ExponentialBackOffOpts { + return func(ebo *ExponentialBackOff) { + ebo.MaxInterval = duration + } +} + +// WithMaxElapsedTime sets the maximum total time for retries. +func WithMaxElapsedTime(duration time.Duration) ExponentialBackOffOpts { + return func(ebo *ExponentialBackOff) { + ebo.MaxElapsedTime = duration + } +} + +// WithRetryStopDuration sets the duration after which retries should stop. +func WithRetryStopDuration(duration time.Duration) ExponentialBackOffOpts { + return func(ebo *ExponentialBackOff) { + ebo.Stop = duration + } +} + +// WithClockProvider sets the clock used to measure time. +func WithClockProvider(clock Clock) ExponentialBackOffOpts { + return func(ebo *ExponentialBackOff) { + ebo.Clock = clock + } +} + +type systemClock struct{} + +func (t systemClock) Now() time.Time { + return time.Now() +} + +// SystemClock implements Clock interface that uses time.Now(). +var SystemClock = systemClock{} + +// Reset the interval back to the initial retry interval and restarts the timer. +// Reset must be called before using b. +func (b *ExponentialBackOff) Reset() { + b.currentInterval = b.InitialInterval + b.startTime = b.Clock.Now() +} + +// NextBackOff calculates the next backoff interval using the formula: +// Randomized interval = RetryInterval * (1 ± RandomizationFactor) +func (b *ExponentialBackOff) NextBackOff() time.Duration { + // Make sure we have not gone over the maximum elapsed time. + elapsed := b.GetElapsedTime() + next := getRandomValueFromInterval(b.RandomizationFactor, rand.Float64(), b.currentInterval) + b.incrementCurrentInterval() + if b.MaxElapsedTime != 0 && elapsed+next > b.MaxElapsedTime { + return b.Stop + } + return next +} + +// GetElapsedTime returns the elapsed time since an ExponentialBackOff instance +// is created and is reset when Reset() is called. +// +// The elapsed time is computed using time.Now().UnixNano(). It is +// safe to call even while the backoff policy is used by a running +// ticker. +func (b *ExponentialBackOff) GetElapsedTime() time.Duration { + return b.Clock.Now().Sub(b.startTime) +} + +// Increments the current interval by multiplying it with the multiplier. +func (b *ExponentialBackOff) incrementCurrentInterval() { + // Check for overflow, if overflow is detected set the current interval to the max interval. + if float64(b.currentInterval) >= float64(b.MaxInterval)/b.Multiplier { + b.currentInterval = b.MaxInterval + } else { + b.currentInterval = time.Duration(float64(b.currentInterval) * b.Multiplier) + } +} + +// Returns a random value from the following interval: +// [currentInterval - randomizationFactor * currentInterval, currentInterval + randomizationFactor * currentInterval]. +func getRandomValueFromInterval(randomizationFactor, random float64, currentInterval time.Duration) time.Duration { + if randomizationFactor == 0 { + return currentInterval // make sure no randomness is used when randomizationFactor is 0. + } + var delta = randomizationFactor * float64(currentInterval) + var minInterval = float64(currentInterval) - delta + var maxInterval = float64(currentInterval) + delta + + // Get a random value from the range [minInterval, maxInterval]. + // The formula used below has a +1 because if the minInterval is 1 and the maxInterval is 3 then + // we want a 33% chance for selecting either 1, 2 or 3. + return time.Duration(minInterval + (random * (maxInterval - minInterval + 1))) +} diff --git a/vendor/github.com/cenkalti/backoff/v4/retry.go b/vendor/github.com/cenkalti/backoff/v4/retry.go new file mode 100644 index 00000000..b9c0c51c --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v4/retry.go @@ -0,0 +1,146 @@ +package backoff + +import ( + "errors" + "time" +) + +// An OperationWithData is executing by RetryWithData() or RetryNotifyWithData(). +// The operation will be retried using a backoff policy if it returns an error. +type OperationWithData[T any] func() (T, error) + +// An Operation is executing by Retry() or RetryNotify(). +// The operation will be retried using a backoff policy if it returns an error. +type Operation func() error + +func (o Operation) withEmptyData() OperationWithData[struct{}] { + return func() (struct{}, error) { + return struct{}{}, o() + } +} + +// Notify is a notify-on-error function. It receives an operation error and +// backoff delay if the operation failed (with an error). +// +// NOTE that if the backoff policy stated to stop retrying, +// the notify function isn't called. +type Notify func(error, time.Duration) + +// Retry the operation o until it does not return error or BackOff stops. +// o is guaranteed to be run at least once. +// +// If o returns a *PermanentError, the operation is not retried, and the +// wrapped error is returned. +// +// Retry sleeps the goroutine for the duration returned by BackOff after a +// failed operation returns. +func Retry(o Operation, b BackOff) error { + return RetryNotify(o, b, nil) +} + +// RetryWithData is like Retry but returns data in the response too. +func RetryWithData[T any](o OperationWithData[T], b BackOff) (T, error) { + return RetryNotifyWithData(o, b, nil) +} + +// RetryNotify calls notify function with the error and wait duration +// for each failed attempt before sleep. +func RetryNotify(operation Operation, b BackOff, notify Notify) error { + return RetryNotifyWithTimer(operation, b, notify, nil) +} + +// RetryNotifyWithData is like RetryNotify but returns data in the response too. +func RetryNotifyWithData[T any](operation OperationWithData[T], b BackOff, notify Notify) (T, error) { + return doRetryNotify(operation, b, notify, nil) +} + +// RetryNotifyWithTimer calls notify function with the error and wait duration using the given Timer +// for each failed attempt before sleep. +// A default timer that uses system timer is used when nil is passed. +func RetryNotifyWithTimer(operation Operation, b BackOff, notify Notify, t Timer) error { + _, err := doRetryNotify(operation.withEmptyData(), b, notify, t) + return err +} + +// RetryNotifyWithTimerAndData is like RetryNotifyWithTimer but returns data in the response too. +func RetryNotifyWithTimerAndData[T any](operation OperationWithData[T], b BackOff, notify Notify, t Timer) (T, error) { + return doRetryNotify(operation, b, notify, t) +} + +func doRetryNotify[T any](operation OperationWithData[T], b BackOff, notify Notify, t Timer) (T, error) { + var ( + err error + next time.Duration + res T + ) + if t == nil { + t = &defaultTimer{} + } + + defer func() { + t.Stop() + }() + + ctx := getContext(b) + + b.Reset() + for { + res, err = operation() + if err == nil { + return res, nil + } + + var permanent *PermanentError + if errors.As(err, &permanent) { + return res, permanent.Err + } + + if next = b.NextBackOff(); next == Stop { + if cerr := ctx.Err(); cerr != nil { + return res, cerr + } + + return res, err + } + + if notify != nil { + notify(err, next) + } + + t.Start(next) + + select { + case <-ctx.Done(): + return res, ctx.Err() + case <-t.C(): + } + } +} + +// PermanentError signals that the operation should not be retried. +type PermanentError struct { + Err error +} + +func (e *PermanentError) Error() string { + return e.Err.Error() +} + +func (e *PermanentError) Unwrap() error { + return e.Err +} + +func (e *PermanentError) Is(target error) bool { + _, ok := target.(*PermanentError) + return ok +} + +// Permanent wraps the given err in a *PermanentError. +func Permanent(err error) error { + if err == nil { + return nil + } + return &PermanentError{ + Err: err, + } +} diff --git a/vendor/github.com/cenkalti/backoff/v4/ticker.go b/vendor/github.com/cenkalti/backoff/v4/ticker.go new file mode 100644 index 00000000..df9d68bc --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v4/ticker.go @@ -0,0 +1,97 @@ +package backoff + +import ( + "context" + "sync" + "time" +) + +// Ticker holds a channel that delivers `ticks' of a clock at times reported by a BackOff. +// +// Ticks will continue to arrive when the previous operation is still running, +// so operations that take a while to fail could run in quick succession. +type Ticker struct { + C <-chan time.Time + c chan time.Time + b BackOff + ctx context.Context + timer Timer + stop chan struct{} + stopOnce sync.Once +} + +// NewTicker returns a new Ticker containing a channel that will send +// the time at times specified by the BackOff argument. Ticker is +// guaranteed to tick at least once. The channel is closed when Stop +// method is called or BackOff stops. It is not safe to manipulate the +// provided backoff policy (notably calling NextBackOff or Reset) +// while the ticker is running. +func NewTicker(b BackOff) *Ticker { + return NewTickerWithTimer(b, &defaultTimer{}) +} + +// NewTickerWithTimer returns a new Ticker with a custom timer. +// A default timer that uses system timer is used when nil is passed. +func NewTickerWithTimer(b BackOff, timer Timer) *Ticker { + if timer == nil { + timer = &defaultTimer{} + } + c := make(chan time.Time) + t := &Ticker{ + C: c, + c: c, + b: b, + ctx: getContext(b), + timer: timer, + stop: make(chan struct{}), + } + t.b.Reset() + go t.run() + return t +} + +// Stop turns off a ticker. After Stop, no more ticks will be sent. +func (t *Ticker) Stop() { + t.stopOnce.Do(func() { close(t.stop) }) +} + +func (t *Ticker) run() { + c := t.c + defer close(c) + + // Ticker is guaranteed to tick at least once. + afterC := t.send(time.Now()) + + for { + if afterC == nil { + return + } + + select { + case tick := <-afterC: + afterC = t.send(tick) + case <-t.stop: + t.c = nil // Prevent future ticks from being sent to the channel. + return + case <-t.ctx.Done(): + return + } + } +} + +func (t *Ticker) send(tick time.Time) <-chan time.Time { + select { + case t.c <- tick: + case <-t.stop: + return nil + } + + next := t.b.NextBackOff() + if next == Stop { + t.Stop() + return nil + } + + t.timer.Start(next) + return t.timer.C() +} diff --git a/vendor/github.com/cenkalti/backoff/v4/timer.go b/vendor/github.com/cenkalti/backoff/v4/timer.go new file mode 100644 index 00000000..8120d021 --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v4/timer.go @@ -0,0 +1,35 @@ +package backoff + +import "time" + +type Timer interface { + Start(duration time.Duration) + Stop() + C() <-chan time.Time +} + +// defaultTimer implements Timer interface using time.Timer +type defaultTimer struct { + timer *time.Timer +} + +// C returns the timers channel which receives the current time when the timer fires. +func (t *defaultTimer) C() <-chan time.Time { + return t.timer.C +} + +// Start starts the timer to fire after the given duration +func (t *defaultTimer) Start(duration time.Duration) { + if t.timer == nil { + t.timer = time.NewTimer(duration) + } else { + t.timer.Reset(duration) + } +} + +// Stop is called when the timer is not used anymore and resources may be freed. +func (t *defaultTimer) Stop() { + if t.timer != nil { + t.timer.Stop() + } +} diff --git a/vendor/github.com/cenkalti/backoff/v4/tries.go b/vendor/github.com/cenkalti/backoff/v4/tries.go new file mode 100644 index 00000000..28d58ca3 --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v4/tries.go @@ -0,0 +1,38 @@ +package backoff + +import "time" + +/* +WithMaxRetries creates a wrapper around another BackOff, which will +return Stop if NextBackOff() has been called too many times since +the last time Reset() was called + +Note: Implementation is not thread-safe. +*/ +func WithMaxRetries(b BackOff, max uint64) BackOff { + return &backOffTries{delegate: b, maxTries: max} +} + +type backOffTries struct { + delegate BackOff + maxTries uint64 + numTries uint64 +} + +func (b *backOffTries) NextBackOff() time.Duration { + if b.maxTries == 0 { + return Stop + } + if b.maxTries > 0 { + if b.maxTries <= b.numTries { + return Stop + } + b.numTries++ + } + return b.delegate.NextBackOff() +} + +func (b *backOffTries) Reset() { + b.numTries = 0 + b.delegate.Reset() +} diff --git a/vendor/github.com/containerd/continuity/AUTHORS b/vendor/github.com/containerd/continuity/AUTHORS new file mode 100644 index 00000000..0b4a03cd --- /dev/null +++ b/vendor/github.com/containerd/continuity/AUTHORS @@ -0,0 +1,40 @@ +Aaron Lehmann +Akash Gupta +Akihiro Suda +Andrew Pennebaker +Brandon Philips +Brian Goff +Christopher Jones +Daniel, Dao Quang Minh +Darren Stahl +Derek McGowan +Edward Pilatowicz +Fu Wei +Gabriel Adrian Samfira +Hajime Tazaki +Ian Campbell +Ivan Markin +Jacob Blain Christen +Justin Cormack +Justin Cummins +Kasper Fabæch Brandt +Kazuyoshi Kato +Kir Kolyshkin +Michael Crosby +Michael Wan +Mike Brown +Niels de Vos +Phil Estes +Sam Whited +Samuel Karp +Sebastiaan van Stijn +Shengjing Zhu +Stephen J Day +Tibor Vass +Tobias Klauser +Tom Faulhaber +Tonis Tiigi +Trevor Porter +Wei Fu +Wilbert van de Ridder +Xiaodong Ye diff --git a/vendor/github.com/containerd/continuity/LICENSE b/vendor/github.com/containerd/continuity/LICENSE new file mode 100644 index 00000000..584149b6 --- /dev/null +++ b/vendor/github.com/containerd/continuity/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright The containerd Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/containerd/continuity/pathdriver/path_driver.go b/vendor/github.com/containerd/continuity/pathdriver/path_driver.go new file mode 100644 index 00000000..b0d5a6b5 --- /dev/null +++ b/vendor/github.com/containerd/continuity/pathdriver/path_driver.go @@ -0,0 +1,101 @@ +/* + Copyright The containerd Authors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package pathdriver + +import ( + "path/filepath" +) + +// PathDriver provides all of the path manipulation functions in a common +// interface. The context should call these and never use the `filepath` +// package or any other package to manipulate paths. +type PathDriver interface { + Join(paths ...string) string + IsAbs(path string) bool + Rel(base, target string) (string, error) + Base(path string) string + Dir(path string) string + Clean(path string) string + Split(path string) (dir, file string) + Separator() byte + Abs(path string) (string, error) + Walk(string, filepath.WalkFunc) error + FromSlash(path string) string + ToSlash(path string) string + Match(pattern, name string) (matched bool, err error) +} + +// pathDriver is a simple default implementation calls the filepath package. +type pathDriver struct{} + +// LocalPathDriver is the exported pathDriver struct for convenience. +var LocalPathDriver PathDriver = &pathDriver{} + +func (*pathDriver) Join(paths ...string) string { + return filepath.Join(paths...) +} + +func (*pathDriver) IsAbs(path string) bool { + return filepath.IsAbs(path) +} + +func (*pathDriver) Rel(base, target string) (string, error) { + return filepath.Rel(base, target) +} + +func (*pathDriver) Base(path string) string { + return filepath.Base(path) +} + +func (*pathDriver) Dir(path string) string { + return filepath.Dir(path) +} + +func (*pathDriver) Clean(path string) string { + return filepath.Clean(path) +} + +func (*pathDriver) Split(path string) (dir, file string) { + return filepath.Split(path) +} + +func (*pathDriver) Separator() byte { + return filepath.Separator +} + +func (*pathDriver) Abs(path string) (string, error) { + return filepath.Abs(path) +} + +// Note that filepath.Walk calls os.Stat, so if the context wants to +// to call Driver.Stat() for Walk, they need to create a new struct that +// overrides this method. +func (*pathDriver) Walk(root string, walkFn filepath.WalkFunc) error { + return filepath.Walk(root, walkFn) +} + +func (*pathDriver) FromSlash(path string) string { + return filepath.FromSlash(path) +} + +func (*pathDriver) ToSlash(path string) string { + return filepath.ToSlash(path) +} + +func (*pathDriver) Match(pattern, name string) (bool, error) { + return filepath.Match(pattern, name) +} diff --git a/vendor/github.com/docker/cli/AUTHORS b/vendor/github.com/docker/cli/AUTHORS new file mode 100644 index 00000000..ad1abd49 --- /dev/null +++ b/vendor/github.com/docker/cli/AUTHORS @@ -0,0 +1,910 @@ +# File @generated by scripts/docs/generate-authors.sh. DO NOT EDIT. +# This file lists all contributors to the repository. +# See scripts/docs/generate-authors.sh to make modifications. + +A. Lester Buck III +Aanand Prasad +Aaron L. Xu +Aaron Lehmann +Aaron.L.Xu +Abdur Rehman +Abhinandan Prativadi +Abin Shahab +Abreto FU +Ace Tang +Addam Hardy +Adolfo Ochagavía +Adrian Plata +Adrien Duermael +Adrien Folie +Adyanth Hosavalike +Ahmet Alp Balkan +Aidan Feldman +Aidan Hobson Sayers +AJ Bowen +Akhil Mohan +Akihiro Suda +Akim Demaille +Alan Thompson +Alano Terblanche +Albert Callarisa +Alberto Roura +Albin Kerouanton +Aleksa Sarai +Aleksander Piotrowski +Alessandro Boch +Alex Couture-Beil +Alex Mavrogiannis +Alex Mayer +Alexander Boyd +Alexander Chneerov +Alexander Larsson +Alexander Morozov +Alexander Ryabov +Alexandre González +Alexey Igrychev +Alexis Couvreur +Alfred Landrum +Ali Rostami +Alicia Lauerman +Allen Sun +Alvin Deng +Amen Belayneh +Amey Shrivastava <72866602+AmeyShrivastava@users.noreply.github.com> +Amir Goldstein +Amit Krishnan +Amit Shukla +Amy Lindburg +Anca Iordache +Anda Xu +Andrea Luzzardi +Andreas Köhler +Andres G. Aragoneses +Andres Leon Rangel +Andrew France +Andrew Hsu +Andrew Macpherson +Andrew McDonnell +Andrew Po +Andrew-Zipperer +Andrey Petrov +Andrii Berehuliak +André Martins +Andy Goldstein +Andy Rothfusz +Anil Madhavapeddy +Ankush Agarwal +Anne Henmi +Anton Polonskiy +Antonio Murdaca +Antonis Kalipetis +Anusha Ragunathan +Ao Li +Arash Deshmeh +Arko Dasgupta +Arnaud Porterie +Arnaud Rebillout +Arthur Peka +Ashly Mathew +Ashwini Oruganti +Aslam Ahemad +Azat Khuyiyakhmetov +Bardia Keyoumarsi +Barnaby Gray +Bastiaan Bakker +BastianHofmann +Ben Bodenmiller +Ben Bonnefoy +Ben Creasy +Ben Firshman +Benjamin Boudreau +Benjamin Böhmke +Benjamin Nater +Benoit Sigoure +Bhumika Bayani +Bill Wang +Bin Liu +Bingshen Wang +Bishal Das +Bjorn Neergaard +Boaz Shuster +Boban Acimovic +Bogdan Anton +Boris Pruessmann +Brad Baker +Bradley Cicenas +Brandon Mitchell +Brandon Philips +Brent Salisbury +Bret Fisher +Brian (bex) Exelbierd +Brian Goff +Brian Tracy +Brian Wieder +Bruno Sousa +Bryan Bess +Bryan Boreham +Bryan Murphy +bryfry +Calvin Liu +Cameron Spear +Cao Weiwei +Carlo Mion +Carlos Alexandro Becker +Carlos de Paula +Casey Korver +Ce Gao +Cedric Davies +Cezar Sa Espinola +Chad Faragher +Chao Wang +Charles Chan +Charles Law +Charles Smith +Charlie Drage +Charlotte Mach +ChaYoung You +Chee Hau Lim +Chen Chuanliang +Chen Hanxiao +Chen Mingjie +Chen Qiu +Chris Chinchilla +Chris Couzens +Chris Gavin +Chris Gibson +Chris McKinnel +Chris Snow +Chris Vermilion +Chris Weyl +Christian Persson +Christian Stefanescu +Christophe Robin +Christophe Vidal +Christopher Biscardi +Christopher Crone +Christopher Jones +Christopher Petito <47751006+krissetto@users.noreply.github.com> +Christopher Petito +Christopher Svensson +Christy Norman +Chun Chen +Clinton Kitson +Coenraad Loubser +Colin Hebert +Collin Guarino +Colm Hally +Comical Derskeal <27731088+derskeal@users.noreply.github.com> +Conner Crosby +Corey Farrell +Corey Quon +Cory Bennet +Cory Snider +Craig Osterhout +Craig Wilhite +Cristian Staretu +Daehyeok Mun +Dafydd Crosby +Daisuke Ito +dalanlan +Damien Nadé +Dan Cotora +Danial Gharib +Daniel Artine +Daniel Cassidy +Daniel Dao +Daniel Farrell +Daniel Gasienica +Daniel Goosen +Daniel Helfand +Daniel Hiltgen +Daniel J Walsh +Daniel Nephin +Daniel Norberg +Daniel Watkins +Daniel Zhang +Daniil Nikolenko +Danny Berger +Darren Shepherd +Darren Stahl +Dattatraya Kumbhar +Dave Goodchild +Dave Henderson +Dave Tucker +David Alvarez +David Beitey +David Calavera +David Cramer +David Dooling +David Gageot +David Karlsson +David le Blanc +David Lechner +David Scott +David Sheets +David Williamson +David Xia +David Young +Deng Guangxing +Denis Defreyne +Denis Gladkikh +Denis Ollier +Dennis Docter +dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> +Derek McGowan +Des Preston +Deshi Xiao +Dharmit Shah +Dhawal Yogesh Bhanushali +Dieter Reuter +Dima Stopel +Dimitry Andric +Ding Fei +Diogo Monica +Djordje Lukic +Dmitriy Fishman +Dmitry Gusev +Dmitry Smirnov +Dmitry V. Krivenok +Dominik Braun +Don Kjer +Dong Chen +DongGeon Lee +Doug Davis +Drew Erny +Ed Costello +Ed Morley <501702+edmorley@users.noreply.github.com> +Elango Sivanandam +Eli Uriegas +Eli Uriegas +Elias Faxö +Elliot Luo <956941328@qq.com> +Eric Bode +Eric Curtin +Eric Engestrom +Eric G. Noriega +Eric Rosenberg +Eric Sage +Eric-Olivier Lamey +Erica Windisch +Erik Hollensbe +Erik Humphrey +Erik St. Martin +Essam A. Hassan +Ethan Haynes +Euan Kemp +Eugene Yakubovich +Evan Allrich +Evan Hazlett +Evan Krall +Evan Lezar +Evelyn Xu +Everett Toews +Fabio Falci +Fabrizio Soppelsa +Felix Geyer +Felix Hupfeld +Felix Rabe +fezzik1620 +Filip Jareš +Flavio Crisciani +Florian Klein +Forest Johnson +Foysal Iqbal +François Scala +Fred Lifton +Frederic Hemberger +Frederick F. Kautz IV +Frederik Nordahl Jul Sabroe +Frieder Bluemle +Gabriel Gore +Gabriel Nicolas Avellaneda +Gabriela Georgieva +Gaetan de Villele +Gang Qiao +Gary Schaetz +Genki Takiuchi +George MacRorie +George Margaritis +George Xie +Gianluca Borello +Gildas Cuisinier +Gio d'Amelio +Gleb Stsenov +Goksu Toprak +Gou Rao +Govind Rai +Grace Choi +Graeme Wiebe +Grant Reaber +Greg Pflaum +Gsealy +Guilhem Lettron +Guillaume J. Charmes +Guillaume Le Floch +Guillaume Tardif +gwx296173 +Günther Jungbluth +Hakan Özler +Hao Zhang <21521210@zju.edu.cn> +Harald Albers +Harold Cooper +Harry Zhang +He Simei +Hector S +Helen Xie +Henning Sprang +Henry N +Hernan Garcia +Hongbin Lu +Hu Keping +Huayi Zhang +Hugo Chastel +Hugo Gabriel Eyherabide +huqun +Huu Nguyen +Hyzhou Zhy +Iain Samuel McLean Elder +Ian Campbell +Ian Philpot +Ignacio Capurro +Ilya Dmitrichenko +Ilya Khlopotov +Ilya Sotkov +Ioan Eugen Stan +Isabel Jimenez +Ivan Grcic +Ivan Grund +Ivan Markin +Jacob Atzen +Jacob Tomlinson +Jacopo Rigoli +Jaivish Kothari +Jake Lambert +Jake Sanders +Jake Stokes +Jakub Panek +James Nesbitt +James Turnbull +Jamie Hannaford +Jan Koprowski +Jan Pazdziora +Jan-Jaap Driessen +Jana Radhakrishnan +Jared Hocutt +Jasmine Hegman +Jason Hall +Jason Heiss +Jason Plum +Jay Kamat +Jean Lecordier +Jean Rouge +Jean-Christophe Sirot +Jean-Pierre Huynh +Jeff Lindsay +Jeff Nickoloff +Jeff Silberman +Jennings Zhang +Jeremy Chambers +Jeremy Unruh +Jeremy Yallop +Jeroen Franse +Jesse Adametz +Jessica Frazelle +Jezeniel Zapanta +Jian Zhang +Jie Luo +Jilles Oldenbeuving +Jim Chen +Jim Galasyn +Jim Lin +Jimmy Leger +Jimmy Song +jimmyxian +Jintao Zhang +Joao Fernandes +Joe Abbey +Joe Doliner +Joe Gordon +Joel Handwell +Joey Geiger +Joffrey F +Johan Euphrosine +Johannes 'fish' Ziemke +John Feminella +John Harris +John Howard +John Howard +John Laswell +John Maguire +John Mulhausen +John Starks +John Stephens +John Tims +John V. Martinez +John Willis +Jon Johnson +Jon Zeolla +Jonatas Baldin +Jonathan A. Sternberg +Jonathan Boulle +Jonathan Lee +Jonathan Lomas +Jonathan McCrohan +Jonathan Warriss-Simmons +Jonh Wendell +Jordan Jennings +Jorge Vallecillo +Jose J. Escobar <53836904+jescobar-docker@users.noreply.github.com> +Joseph Kern +Josh Bodah +Josh Chorlton +Josh Hawn +Josh Horwitz +Josh Soref +Julian +Julien Barbier +Julien Kassar +Julien Maitrehenry +Justas Brazauskas +Justin Chadwell +Justin Cormack +Justin Simonelis +Justyn Temme +Jyrki Puttonen +Jérémie Drouet +Jérôme Petazzoni +Jörg Thalheim +Kai Blin +Kai Qiang Wu (Kennan) +Kara Alexandra +Kareem Khazem +Karthik Nayak +Kat Samperi +Kathryn Spiers +Katie McLaughlin +Ke Xu +Kei Ohmura +Keith Hudgins +Kelton Bassingthwaite +Ken Cochrane +Ken ICHIKAWA +Kenfe-Mickaël Laventure +Kevin Alvarez +Kevin Burke +Kevin Feyrer +Kevin Kern +Kevin Kirsche +Kevin Meredith +Kevin Richardson +Kevin Woblick +khaled souf +Kim Eik +Kir Kolyshkin +Kirill A. Korinsky +Kotaro Yoshimatsu +Krasi Georgiev +Kris-Mikael Krister +Kun Zhang +Kunal Kushwaha +Kyle Mitofsky +Lachlan Cooper +Lai Jiangshan +Lars Kellogg-Stedman +Laura Brehm +Laura Frank +Laurent Erignoux +Lee Gaines +Lei Jitang +Lennie +Leo Gallucci +Leonid Skorospelov +Lewis Daly +Li Fu Bang +Li Yi +Li Yi +Liang-Chi Hsieh +Lihua Tang +Lily Guo +Lin Lu +Linus Heckemann +Liping Xue +Liron Levin +liwenqi +lixiaobing10051267 +Lloyd Dewolf +Lorenzo Fontana +Louis Opter +Luca Favatella +Luca Marturana +Lucas Chan +Luis Henrique Mulinari +Luka Hartwig +Lukas Heeren +Lukasz Zajaczkowski +Lydell Manganti +Lénaïc Huard +Ma Shimiao +Mabin +Maciej Kalisz +Madhav Puri +Madhu Venugopal +Madhur Batra +Malte Janduda +Manjunath A Kumatagi +Mansi Nahar +mapk0y +Marc Bihlmaier +Marc Cornellà +Marco Mariani +Marco Spiess +Marco Vedovati +Marcus Martins +Marianna Tessel +Marius Ileana +Marius Meschter +Marius Sturm +Mark Oates +Marsh Macy +Martin Mosegaard Amdisen +Mary Anthony +Mason Fish +Mason Malone +Mateusz Major +Mathias Duedahl <64321057+Lussebullen@users.noreply.github.com> +Mathieu Champlon +Mathieu Rollet +Matt Gucci +Matt Robenolt +Matteo Orefice +Matthew Heon +Matthieu Hauglustaine +Mauro Porras P +Max Shytikov +Max-Julian Pogner +Maxime Petazzoni +Maximillian Fan Xavier +Mei ChunTao +Melroy van den Berg +Metal <2466052+tedhexaflow@users.noreply.github.com> +Micah Zoltu +Michael A. Smith +Michael Bridgen +Michael Crosby +Michael Friis +Michael Irwin +Michael Käufl +Michael Prokop +Michael Scharf +Michael Spetsiotis +Michael Steinert +Michael West +Michal Minář +Michał Czeraszkiewicz +Miguel Angel Alvarez Cabrerizo +Mihai Borobocea +Mihuleacc Sergiu +Mike Brown +Mike Casas +Mike Dalton +Mike Danese +Mike Dillon +Mike Goelzer +Mike MacCana +mikelinjie <294893458@qq.com> +Mikhail Vasin +Milind Chawre +Mindaugas Rukas +Miroslav Gula +Misty Stanley-Jones +Mohammad Banikazemi +Mohammed Aaqib Ansari +Mohini Anne Dsouza +Moorthy RS +Morgan Bauer +Morten Hekkvang +Morten Linderud +Moysés Borges +Mozi <29089388+pzhlkj6612@users.noreply.github.com> +Mrunal Patel +muicoder +Murukesh Mohanan +Muthukumar R +Máximo Cuadros +Mårten Cassel +Nace Oroz +Nahum Shalman +Nalin Dahyabhai +Nao YONASHIRO +Nassim 'Nass' Eddequiouaq +Natalie Parker +Nate Brennand +Nathan Hsieh +Nathan LeClaire +Nathan McCauley +Neil Peterson +Nick Adcock +Nick Santos +Nick Sieger +Nico Stapelbroek +Nicola Kabar +Nicolas Borboën +Nicolas De Loof +Nikhil Chawla +Nikolas Garofil +Nikolay Milovanov +Nir Soffer +Nishant Totla +NIWA Hideyuki +Noah Treuhaft +O.S. Tezer +Oded Arbel +Odin Ugedal +ohmystack +OKA Naoya +Oliver Pomeroy +Olle Jonsson +Olli Janatuinen +Oscar Wieman +Otto Kekäläinen +Ovidio Mallo +Pascal Borreli +Patrick Böänziger +Patrick Daigle <114765035+pdaig@users.noreply.github.com> +Patrick Hemmer +Patrick Lang +Paul +Paul Kehrer +Paul Lietar +Paul Mulders +Paul Seyfert +Paul Weaver +Pavel Pospisil +Paweł Gronowski +Paweł Pokrywka +Paweł Szczekutowicz +Peeyush Gupta +Per Lundberg +Peter Dave Hello +Peter Edge +Peter Hsu +Peter Jaffe +Peter Kehl +Peter Nagy +Peter Salvatore +Peter Waller +Phil Estes +Philip Alexander Etling +Philipp Gillé +Philipp Schmied +Phong Tran +pidster +Pieter E Smit +pixelistik +Pratik Karki +Prayag Verma +Preston Cowley +Pure White +Qiang Huang +Qinglan Peng +QQ喵 +qudongfang +Raghavendra K T +Rahul Kadyan +Rahul Zoldyck +Ravi Shekhar Jethani +Ray Tsang +Reficul +Remy Suen +Renaud Gaubert +Ricardo N Feliciano +Rich Moyse +Richard Chen Zheng <58443436+rchenzheng@users.noreply.github.com> +Richard Mathie +Richard Scothern +Rick Wieman +Ritesh H Shukla +Riyaz Faizullabhoy +Rob Gulewich +Rob Murray +Robert Wallis +Robin Naundorf +Robin Speekenbrink +Roch Feuillade +Rodolfo Ortiz +Rogelio Canedo +Rohan Verma +Roland Kammerer +Roman Dudin +Rory Hunter +Ross Boucher +Rubens Figueiredo +Rui Cao +Rui JingAn +Ryan Belgrave +Ryan Detzel +Ryan Stelly +Ryan Wilson-Perkin +Ryan Zhang +Sainath Grandhi +Sakeven Jiang +Sally O'Malley +Sam Neirinck +Sam Thibault +Samarth Shah +Sambuddha Basu +Sami Tabet +Samuel Cochran +Samuel Karp +Sandro Jäckel +Santhosh Manohar +Sargun Dhillon +Saswat Bhattacharya +Saurabh Kumar +Scott Brenner +Scott Collier +Sean Christopherson +Sean Rodman +Sebastiaan van Stijn +Sergey Tryuber +Serhat Gülçiçek +Sevki Hasirci +Shaun Kaasten +Sheng Yang +Shijiang Wei +Shishir Mahajan +Shoubhik Bose +Shukui Yang +Sian Lerk Lau +Sidhartha Mani +sidharthamani +Silvin Lubecki +Simei He +Simon Ferquel +Simon Heimberg +Sindhu S +Slava Semushin +Solomon Hykes +Song Gao +Spencer Brown +Spring Lee +squeegels +Srini Brahmaroutu +Stefan S. +Stefan Scherer +Stefan Weil +Stephane Jeandeaux +Stephen Day +Stephen Rust +Steve Durrheimer +Steve Richards +Steven Burgess +Stoica-Marcu Floris-Andrei +Subhajit Ghosh +Sun Jianbo +Sune Keller +Sungwon Han +Sunny Gogoi +Sven Dowideit +Sylvain Baubeau +Sébastien HOUZÉ +T K Sourabh +TAGOMORI Satoshi +taiji-tech +Takeshi Koenuma +Takuya Noguchi +Taylor Jones +Teiva Harsanyi +Tejaswini Duggaraju +Tengfei Wang +Teppei Fukuda +Thatcher Peskens +Thibault Coupin +Thomas Gazagnaire +Thomas Krzero +Thomas Leonard +Thomas Léveil +Thomas Riccardi +Thomas Swift +Tianon Gravi +Tianyi Wang +Tibor Vass +Tim Dettrick +Tim Hockin +Tim Sampson +Tim Smith +Tim Waugh +Tim Welsh +Tim Wraight +timfeirg +Timothy Hobbs +Tobias Bradtke +Tobias Gesellchen +Todd Whiteman +Tom Denham +Tom Fotherby +Tom Klingenberg +Tom Milligan +Tom X. Tobin +Tomas Bäckman +Tomas Tomecek +Tomasz Kopczynski +Tomáš Hrčka +Tony Abboud +Tõnis Tiigi +Trapier Marshall +Travis Cline +Tristan Carel +Tycho Andersen +Tycho Andersen +uhayate +Ulrich Bareth +Ulysses Souza +Umesh Yadav +Vaclav Struhar +Valentin Lorentz +Vardan Pogosian +Venkateswara Reddy Bukkasamudram +Veres Lajos +Victor Vieux +Victoria Bialas +Viktor Stanchev +Ville Skyttä +Vimal Raghubir +Vincent Batts +Vincent Bernat +Vincent Demeester +Vincent Woo +Vishnu Kannan +Vivek Goyal +Wang Jie +Wang Lei +Wang Long +Wang Ping +Wang Xing +Wang Yuexiao +Wang Yumu <37442693@qq.com> +Wataru Ishida +Wayne Song +Wen Cheng Ma +Wenzhi Liang +Wes Morgan +Wewang Xiaorenfine +William Henry +Xianglin Gao +Xiaodong Liu +Xiaodong Zhang +Xiaoxi He +Xinbo Weng +Xuecong Liao +Yan Feng +Yanqiang Miao +Yassine Tijani +Yi EungJun +Ying Li +Yong Tang +Yosef Fertel +Yu Peng +Yuan Sun +Yucheng Wu +Yue Zhang +Yunxiang Huang +Zachary Romero +Zander Mackie +zebrilee +Zeel B Patel +Zhang Kun +Zhang Wei +Zhang Wentao +ZhangHang +zhenghenghuo +Zhiwei Liang +Zhou Hao +Zhoulin Xie +Zhu Guihua +Zhuo Zhi +Álex González +Álvaro Lázaro +Átila Camurça Alves +Александр Менщиков <__Singleton__@hackerdom.ru> +徐俊杰 diff --git a/vendor/github.com/docker/cli/LICENSE b/vendor/github.com/docker/cli/LICENSE new file mode 100644 index 00000000..9c8e20ab --- /dev/null +++ b/vendor/github.com/docker/cli/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2013-2017 Docker, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/docker/cli/NOTICE b/vendor/github.com/docker/cli/NOTICE new file mode 100644 index 00000000..1c40faae --- /dev/null +++ b/vendor/github.com/docker/cli/NOTICE @@ -0,0 +1,19 @@ +Docker +Copyright 2012-2017 Docker, Inc. + +This product includes software developed at Docker, Inc. (https://www.docker.com). + +This product contains software (https://github.com/creack/pty) developed +by Keith Rarick, licensed under the MIT License. + +The following is courtesy of our legal counsel: + + +Use and transfer of Docker may be subject to certain restrictions by the +United States and other governments. +It is your responsibility to ensure that your use and/or transfer does not +violate applicable laws. + +For more information, see https://www.bis.doc.gov + +See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/docker/cli/cli/compose/interpolation/interpolation.go b/vendor/github.com/docker/cli/cli/compose/interpolation/interpolation.go new file mode 100644 index 00000000..ee11656f --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/interpolation/interpolation.go @@ -0,0 +1,164 @@ +// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: +//go:build go1.22 + +package interpolation + +import ( + "os" + "strings" + + "github.com/docker/cli/cli/compose/template" + "github.com/pkg/errors" +) + +// Options supported by Interpolate +type Options struct { + // LookupValue from a key + LookupValue LookupValue + // TypeCastMapping maps key paths to functions to cast to a type + TypeCastMapping map[Path]Cast + // Substitution function to use + Substitute func(string, template.Mapping) (string, error) +} + +// LookupValue is a function which maps from variable names to values. +// Returns the value as a string and a bool indicating whether +// the value is present, to distinguish between an empty string +// and the absence of a value. +type LookupValue func(key string) (string, bool) + +// Cast a value to a new type, or return an error if the value can't be cast +type Cast func(value string) (any, error) + +// Interpolate replaces variables in a string with the values from a mapping +func Interpolate(config map[string]any, opts Options) (map[string]any, error) { + if opts.LookupValue == nil { + opts.LookupValue = os.LookupEnv + } + if opts.TypeCastMapping == nil { + opts.TypeCastMapping = make(map[Path]Cast) + } + if opts.Substitute == nil { + opts.Substitute = template.Substitute + } + + out := map[string]any{} + + for key, value := range config { + interpolatedValue, err := recursiveInterpolate(value, NewPath(key), opts) + if err != nil { + return out, err + } + out[key] = interpolatedValue + } + + return out, nil +} + +func recursiveInterpolate(value any, path Path, opts Options) (any, error) { + switch value := value.(type) { + case string: + newValue, err := opts.Substitute(value, template.Mapping(opts.LookupValue)) + if err != nil || newValue == value { + return value, newPathError(path, err) + } + caster, ok := opts.getCasterForPath(path) + if !ok { + return newValue, nil + } + casted, err := caster(newValue) + return casted, newPathError(path, errors.Wrap(err, "failed to cast to expected type")) + + case map[string]any: + out := map[string]any{} + for key, elem := range value { + interpolatedElem, err := recursiveInterpolate(elem, path.Next(key), opts) + if err != nil { + return nil, err + } + out[key] = interpolatedElem + } + return out, nil + + case []any: + out := make([]any, len(value)) + for i, elem := range value { + interpolatedElem, err := recursiveInterpolate(elem, path.Next(PathMatchList), opts) + if err != nil { + return nil, err + } + out[i] = interpolatedElem + } + return out, nil + + default: + return value, nil + } +} + +func newPathError(path Path, err error) error { + switch err := err.(type) { + case nil: + return nil + case *template.InvalidTemplateError: + return errors.Errorf( + "invalid interpolation format for %s: %#v; you may need to escape any $ with another $", + path, err.Template) + default: + return errors.Wrapf(err, "error while interpolating %s", path) + } +} + +const pathSeparator = "." + +// PathMatchAll is a token used as part of a Path to match any key at that level +// in the nested structure +const PathMatchAll = "*" + +// PathMatchList is a token used as part of a Path to match items in a list +const PathMatchList = "[]" + +// Path is a dotted path of keys to a value in a nested mapping structure. A * +// section in a path will match any key in the mapping structure. +type Path string + +// NewPath returns a new Path +func NewPath(items ...string) Path { + return Path(strings.Join(items, pathSeparator)) +} + +// Next returns a new path by append part to the current path +func (p Path) Next(part string) Path { + return Path(string(p) + pathSeparator + part) +} + +func (p Path) parts() []string { + return strings.Split(string(p), pathSeparator) +} + +func (p Path) matches(pattern Path) bool { + patternParts := pattern.parts() + parts := p.parts() + + if len(patternParts) != len(parts) { + return false + } + for index, part := range parts { + switch patternParts[index] { + case PathMatchAll, part: + continue + default: + return false + } + } + return true +} + +func (o Options) getCasterForPath(path Path) (Cast, bool) { + for pattern, caster := range o.TypeCastMapping { + if path.matches(pattern) { + return caster, true + } + } + return nil, false +} diff --git a/vendor/github.com/docker/cli/cli/compose/loader/example1.env b/vendor/github.com/docker/cli/cli/compose/loader/example1.env new file mode 100644 index 00000000..f19ec0df --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/loader/example1.env @@ -0,0 +1,8 @@ +# passed through +FOO=foo_from_env_file + +# overridden in example2.env +BAR=bar_from_env_file + +# overridden in full-example.yml +BAZ=baz_from_env_file diff --git a/vendor/github.com/docker/cli/cli/compose/loader/example2.env b/vendor/github.com/docker/cli/cli/compose/loader/example2.env new file mode 100644 index 00000000..f47d1e61 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/loader/example2.env @@ -0,0 +1,4 @@ +BAR=bar_from_env_file_2 + +# overridden in configDetails.Environment +QUX=quz_from_env_file_2 diff --git a/vendor/github.com/docker/cli/cli/compose/loader/full-example.yml b/vendor/github.com/docker/cli/cli/compose/loader/full-example.yml new file mode 100644 index 00000000..36ebf833 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/loader/full-example.yml @@ -0,0 +1,452 @@ +version: "3.13" + +services: + foo: + + build: + context: ./dir + dockerfile: Dockerfile + args: + foo: bar + target: foo + network: foo + cache_from: + - foo + - bar + extra_hosts: + - "ipv4.example.com:127.0.0.1" + - "ipv6.example.com:::1" + labels: [FOO=BAR] + + + cap_add: + - ALL + + cap_drop: + - NET_ADMIN + - SYS_ADMIN + + cgroup_parent: m-executor-abcd + + # String or list + command: bundle exec thin -p 3000 + # command: ["bundle", "exec", "thin", "-p", "3000"] + + configs: + - config1 + - source: config2 + target: /my_config + uid: '103' + gid: '103' + mode: 0440 + + container_name: my-web-container + + depends_on: + - db + - redis + + deploy: + mode: replicated + replicas: 6 + labels: [FOO=BAR] + rollback_config: + parallelism: 3 + delay: 10s + failure_action: continue + monitor: 60s + max_failure_ratio: 0.3 + order: start-first + update_config: + parallelism: 3 + delay: 10s + failure_action: continue + monitor: 60s + max_failure_ratio: 0.3 + order: start-first + resources: + limits: + cpus: '0.001' + memory: 50M + pids: 100 + reservations: + cpus: '0.0001' + memory: 20M + generic_resources: + - discrete_resource_spec: + kind: 'gpu' + value: 2 + - discrete_resource_spec: + kind: 'ssd' + value: 1 + restart_policy: + condition: on-failure + delay: 5s + max_attempts: 3 + window: 120s + placement: + constraints: [node=foo] + max_replicas_per_node: 5 + preferences: + - spread: node.labels.az + endpoint_mode: dnsrr + + devices: + - "/dev/ttyUSB0:/dev/ttyUSB0" + + # String or list + # dns: 8.8.8.8 + dns: + - 8.8.8.8 + - 9.9.9.9 + + # String or list + # dns_search: example.com + dns_search: + - dc1.example.com + - dc2.example.com + + domainname: foo.com + + # String or list + # entrypoint: /code/entrypoint.sh -p 3000 + entrypoint: ["/code/entrypoint.sh", "-p", "3000"] + + # String or list + # env_file: .env + env_file: + - ./example1.env + - ./example2.env + + # Mapping or list + # Mapping values can be strings, numbers or null + # Booleans are not allowed - must be quoted + environment: + BAZ: baz_from_service_def + QUX: + # environment: + # - RACK_ENV=development + # - SHOW=true + # - SESSION_SECRET + + # Items can be strings or numbers + expose: + - "3000" + - 8000 + + external_links: + - redis_1 + - project_db_1:mysql + - project_db_1:postgresql + + # Mapping or list + # Mapping values must be strings + # extra_hosts: + # somehost: "162.242.195.82" + # otherhost: "50.31.209.229" + # host.docker.internal: "host-gateway" + extra_hosts: + - "somehost:162.242.195.82" + - "otherhost:50.31.209.229" + - "host.docker.internal:host-gateway" + + hostname: foo + + healthcheck: + test: echo "hello world" + interval: 10s + timeout: 1s + retries: 5 + start_period: 15s + start_interval: 1s + + # Any valid image reference - repo, tag, id, sha + image: redis + # image: ubuntu:14.04 + # image: tutum/influxdb + # image: example-registry.com:4000/postgresql + # image: a4bc65fd + # image: busybox@sha256:38a203e1986cf79639cfb9b2e1d6e773de84002feea2d4eb006b52004ee8502d + + ipc: host + + # Mapping or list + # Mapping values can be strings, numbers or null + labels: + com.example.description: "Accounting webapp" + com.example.number: 42 + com.example.empty-label: + # labels: + # - "com.example.description=Accounting webapp" + # - "com.example.number=42" + # - "com.example.empty-label" + + links: + - db + - db:database + - redis + + logging: + driver: syslog + options: + syslog-address: "tcp://192.168.0.42:123" + + mac_address: 02:42:ac:11:65:43 + + # network_mode: "bridge" + # network_mode: "host" + # network_mode: "none" + # Use the network mode of an arbitrary container from another service + # network_mode: "service:db" + # Use the network mode of another container, specified by name or id + # network_mode: "container:some-container" + network_mode: "container:0cfeab0f748b9a743dc3da582046357c6ef497631c1a016d28d2bf9b4f899f7b" + + networks: + some-network: + aliases: + - alias1 + - alias3 + driver_opts: + "driveropt1": "optval1" + "driveropt2": "optval2" + other-network: + ipv4_address: 172.16.238.10 + ipv6_address: 2001:3984:3989::10 + other-other-network: + + pid: "host" + + ports: + - 3000 + - "3001-3005" + - "8000:8000" + - "9090-9091:8080-8081" + - "49100:22" + - "127.0.0.1:8001:8001" + - "127.0.0.1:5000-5010:5000-5010" + + privileged: true + + read_only: true + + restart: always + + secrets: + - secret1 + - source: secret2 + target: my_secret + uid: '103' + gid: '103' + mode: 0440 + + security_opt: + - label=level:s0:c100,c200 + - label=type:svirt_apache_t + + stdin_open: true + + stop_grace_period: 20s + + stop_signal: SIGUSR1 + + sysctls: + net.core.somaxconn: 1024 + net.ipv4.tcp_syncookies: 0 + + # String or list + # tmpfs: /run + tmpfs: + - /run + - /tmp + + tty: true + + ulimits: + # Single number or mapping with soft + hard limits + nproc: 65535 + nofile: + soft: 20000 + hard: 40000 + + user: someone + + volumes: + # Just specify a path and let the Engine create a volume + - /var/lib/mysql + # Specify an absolute path mapping + - /opt/data:/var/lib/mysql + # Path on the host, relative to the Compose file + - .:/code + - ./static:/var/www/html + # User-relative path + - ~/configs:/etc/configs/:ro + # Named volume + - datavolume:/var/lib/mysql + - type: bind + source: ./opt + target: /opt + consistency: cached + - type: tmpfs + target: /opt + tmpfs: + size: 10000 + - type: cluster + source: group:mygroup + target: /srv + + working_dir: /code + x-bar: baz + x-foo: bar + +networks: + # Entries can be null, which specifies simply that a network + # called "{project name}_some-network" should be created and + # use the default driver + some-network: + + other-network: + driver: overlay + + driver_opts: + # Values can be strings or numbers + foo: "bar" + baz: 1 + + ipam: + driver: overlay + # driver_opts: + # # Values can be strings or numbers + # com.docker.network.enable_ipv6: "true" + # com.docker.network.numeric_value: 1 + config: + - subnet: 172.16.238.0/24 + # gateway: 172.16.238.1 + - subnet: 2001:3984:3989::/64 + # gateway: 2001:3984:3989::1 + + labels: + foo: bar + + external-network: + # Specifies that a pre-existing network called "external-network" + # can be referred to within this file as "external-network" + external: true + + other-external-network: + # Specifies that a pre-existing network called "my-cool-network" + # can be referred to within this file as "other-external-network" + external: + name: my-cool-network + x-bar: baz + x-foo: bar + +volumes: + # Entries can be null, which specifies simply that a volume + # called "{project name}_some-volume" should be created and + # use the default driver + some-volume: + + other-volume: + driver: flocker + + driver_opts: + # Values can be strings or numbers + foo: "bar" + baz: 1 + labels: + foo: bar + + another-volume: + name: "user_specified_name" + driver: vsphere + + driver_opts: + # Values can be strings or numbers + foo: "bar" + baz: 1 + + external-volume: + # Specifies that a pre-existing volume called "external-volume" + # can be referred to within this file as "external-volume" + external: true + + other-external-volume: + # Specifies that a pre-existing volume called "my-cool-volume" + # can be referred to within this file as "other-external-volume" + # This example uses the deprecated "volume.external.name" (replaced by "volume.name") + external: + name: my-cool-volume + + external-volume3: + # Specifies that a pre-existing volume called "this-is-volume3" + # can be referred to within this file as "external-volume3" + name: this-is-volume3 + external: true + x-bar: baz + x-foo: bar + + cluster-volume: + driver: my-csi-driver + x-cluster-spec: + group: mygroup + access_mode: + scope: single + sharing: none + block_volume: {} + accessibility_requirements: + requisite: + - segments: + - region=R1 + - zone=Z1 + - segments: + region: R1 + zone: Z2 + preferred: + - segments: + region: R1 + zone: Z1 + capacity_range: + required_bytes: 1G + limit_bytes: 8G + secrets: + - key: mycsisecret + secret: secret1 + - key: mycsisecret2 + secret: secret4 + availability: active + +configs: + config1: + file: ./config_data + labels: + foo: bar + config2: + external: + name: my_config + config3: + external: true + config4: + name: foo + x-bar: baz + x-foo: bar + +secrets: + secret1: + file: ./secret_data + labels: + foo: bar + secret2: + external: + name: my_secret + secret3: + external: true + secret4: + name: bar + x-bar: baz + x-foo: bar +x-bar: baz +x-foo: bar +x-nested: + bar: baz + foo: bar diff --git a/vendor/github.com/docker/cli/cli/compose/loader/interpolate.go b/vendor/github.com/docker/cli/cli/compose/loader/interpolate.go new file mode 100644 index 00000000..82c36d7d --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/loader/interpolate.go @@ -0,0 +1,76 @@ +// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: +//go:build go1.22 + +package loader + +import ( + "strconv" + "strings" + + interp "github.com/docker/cli/cli/compose/interpolation" + "github.com/pkg/errors" +) + +var interpolateTypeCastMapping = map[interp.Path]interp.Cast{ + servicePath("configs", interp.PathMatchList, "mode"): toInt, + servicePath("secrets", interp.PathMatchList, "mode"): toInt, + servicePath("healthcheck", "retries"): toInt, + servicePath("healthcheck", "disable"): toBoolean, + servicePath("deploy", "replicas"): toInt, + servicePath("deploy", "update_config", "parallelism"): toInt, + servicePath("deploy", "update_config", "max_failure_ratio"): toFloat, + servicePath("deploy", "rollback_config", "parallelism"): toInt, + servicePath("deploy", "rollback_config", "max_failure_ratio"): toFloat, + servicePath("deploy", "restart_policy", "max_attempts"): toInt, + servicePath("deploy", "placement", "max_replicas_per_node"): toInt, + servicePath("ports", interp.PathMatchList, "target"): toInt, + servicePath("ports", interp.PathMatchList, "published"): toInt, + servicePath("ulimits", interp.PathMatchAll): toInt, + servicePath("ulimits", interp.PathMatchAll, "hard"): toInt, + servicePath("ulimits", interp.PathMatchAll, "soft"): toInt, + servicePath("privileged"): toBoolean, + servicePath("oom_score_adj"): toInt, + servicePath("read_only"): toBoolean, + servicePath("stdin_open"): toBoolean, + servicePath("tty"): toBoolean, + servicePath("volumes", interp.PathMatchList, "read_only"): toBoolean, + servicePath("volumes", interp.PathMatchList, "volume", "nocopy"): toBoolean, + iPath("networks", interp.PathMatchAll, "external"): toBoolean, + iPath("networks", interp.PathMatchAll, "internal"): toBoolean, + iPath("networks", interp.PathMatchAll, "attachable"): toBoolean, + iPath("volumes", interp.PathMatchAll, "external"): toBoolean, + iPath("secrets", interp.PathMatchAll, "external"): toBoolean, + iPath("configs", interp.PathMatchAll, "external"): toBoolean, +} + +func iPath(parts ...string) interp.Path { + return interp.NewPath(parts...) +} + +func servicePath(parts ...string) interp.Path { + return iPath(append([]string{"services", interp.PathMatchAll}, parts...)...) +} + +func toInt(value string) (any, error) { + return strconv.Atoi(value) +} + +func toFloat(value string) (any, error) { + return strconv.ParseFloat(value, 64) +} + +// should match http://yaml.org/type/bool.html +func toBoolean(value string) (any, error) { + switch strings.ToLower(value) { + case "y", "yes", "true", "on": + return true, nil + case "n", "no", "false", "off": + return false, nil + default: + return nil, errors.Errorf("invalid boolean: %s", value) + } +} + +func interpolateConfig(configDict map[string]any, opts interp.Options) (map[string]any, error) { + return interp.Interpolate(configDict, opts) +} diff --git a/vendor/github.com/docker/cli/cli/compose/loader/loader.go b/vendor/github.com/docker/cli/cli/compose/loader/loader.go new file mode 100644 index 00000000..7bc420b2 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/loader/loader.go @@ -0,0 +1,988 @@ +// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: +//go:build go1.22 + +package loader + +import ( + "fmt" + "path" + "path/filepath" + "reflect" + "sort" + "strconv" + "strings" + "time" + + interp "github.com/docker/cli/cli/compose/interpolation" + "github.com/docker/cli/cli/compose/schema" + "github.com/docker/cli/cli/compose/template" + "github.com/docker/cli/cli/compose/types" + "github.com/docker/cli/opts" + "github.com/docker/docker/api/types/versions" + "github.com/docker/go-connections/nat" + units "github.com/docker/go-units" + "github.com/go-viper/mapstructure/v2" + "github.com/google/shlex" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + yaml "gopkg.in/yaml.v2" +) + +// Options supported by Load +type Options struct { + // Skip schema validation + SkipValidation bool + // Skip interpolation + SkipInterpolation bool + // Interpolation options + Interpolate *interp.Options + // Discard 'env_file' entries after resolving to 'environment' section + discardEnvFiles bool +} + +// WithDiscardEnvFiles sets the Options to discard the `env_file` section after resolving to +// the `environment` section +func WithDiscardEnvFiles(options *Options) { + options.discardEnvFiles = true +} + +// ParseYAML reads the bytes from a file, parses the bytes into a mapping +// structure, and returns it. +func ParseYAML(source []byte) (map[string]any, error) { + var cfg any + if err := yaml.Unmarshal(source, &cfg); err != nil { + return nil, err + } + cfgMap, ok := cfg.(map[any]any) + if !ok { + return nil, errors.Errorf("top-level object must be a mapping") + } + converted, err := convertToStringKeysRecursive(cfgMap, "") + if err != nil { + return nil, err + } + return converted.(map[string]any), nil +} + +// Load reads a ConfigDetails and returns a fully loaded configuration +func Load(configDetails types.ConfigDetails, opt ...func(*Options)) (*types.Config, error) { + if len(configDetails.ConfigFiles) < 1 { + return nil, errors.Errorf("No files specified") + } + + options := &Options{ + Interpolate: &interp.Options{ + Substitute: template.Substitute, + LookupValue: configDetails.LookupEnv, + TypeCastMapping: interpolateTypeCastMapping, + }, + } + + for _, op := range opt { + op(options) + } + + configs := []*types.Config{} + var err error + + for _, file := range configDetails.ConfigFiles { + configDict := file.Config + version := schema.Version(configDict) + if configDetails.Version == "" { + configDetails.Version = version + } + if configDetails.Version != version { + return nil, errors.Errorf("version mismatched between two composefiles : %v and %v", configDetails.Version, version) + } + + if err := validateForbidden(configDict); err != nil { + return nil, err + } + + if !options.SkipInterpolation { + configDict, err = interpolateConfig(configDict, *options.Interpolate) + if err != nil { + return nil, err + } + } + + if !options.SkipValidation { + if err := schema.Validate(configDict, configDetails.Version); err != nil { + return nil, err + } + } + + cfg, err := loadSections(configDict, configDetails) + if err != nil { + return nil, err + } + cfg.Filename = file.Filename + if options.discardEnvFiles { + for i := range cfg.Services { + cfg.Services[i].EnvFile = nil + } + } + + configs = append(configs, cfg) + } + + return merge(configs) +} + +func validateForbidden(configDict map[string]any) error { + servicesDict, ok := configDict["services"].(map[string]any) + if !ok { + return nil + } + forbidden := getProperties(servicesDict, types.ForbiddenProperties) + if len(forbidden) > 0 { + return &ForbiddenPropertiesError{Properties: forbidden} + } + return nil +} + +func loadSections(config map[string]any, configDetails types.ConfigDetails) (*types.Config, error) { + var err error + cfg := types.Config{ + Version: schema.Version(config), + } + + loaders := []struct { + key string + fnc func(config map[string]any) error + }{ + { + key: "services", + fnc: func(config map[string]any) error { + cfg.Services, err = LoadServices(config, configDetails.WorkingDir, configDetails.LookupEnv) + return err + }, + }, + { + key: "networks", + fnc: func(config map[string]any) error { + cfg.Networks, err = LoadNetworks(config, configDetails.Version) + return err + }, + }, + { + key: "volumes", + fnc: func(config map[string]any) error { + cfg.Volumes, err = LoadVolumes(config, configDetails.Version) + return err + }, + }, + { + key: "secrets", + fnc: func(config map[string]any) error { + cfg.Secrets, err = LoadSecrets(config, configDetails) + return err + }, + }, + { + key: "configs", + fnc: func(config map[string]any) error { + cfg.Configs, err = LoadConfigObjs(config, configDetails) + return err + }, + }, + } + for _, loader := range loaders { + if err := loader.fnc(getSection(config, loader.key)); err != nil { + return nil, err + } + } + cfg.Extras = getExtras(config) + return &cfg, nil +} + +func getSection(config map[string]any, key string) map[string]any { + section, ok := config[key] + if !ok { + return make(map[string]any) + } + return section.(map[string]any) +} + +// GetUnsupportedProperties returns the list of any unsupported properties that are +// used in the Compose files. +func GetUnsupportedProperties(configDicts ...map[string]any) []string { + unsupported := map[string]bool{} + + for _, configDict := range configDicts { + for _, service := range getServices(configDict) { + serviceDict := service.(map[string]any) + for _, property := range types.UnsupportedProperties { + if _, isSet := serviceDict[property]; isSet { + unsupported[property] = true + } + } + } + } + + return sortedKeys(unsupported) +} + +func sortedKeys(set map[string]bool) []string { + keys := make([]string, 0, len(set)) + for key := range set { + keys = append(keys, key) + } + sort.Strings(keys) + return keys +} + +// GetDeprecatedProperties returns the list of any deprecated properties that +// are used in the compose files. +func GetDeprecatedProperties(configDicts ...map[string]any) map[string]string { + deprecated := map[string]string{} + + for _, configDict := range configDicts { + deprecatedProperties := getProperties(getServices(configDict), types.DeprecatedProperties) + for key, value := range deprecatedProperties { + deprecated[key] = value + } + } + + return deprecated +} + +func getProperties(services map[string]any, propertyMap map[string]string) map[string]string { + output := map[string]string{} + + for _, service := range services { + if serviceDict, ok := service.(map[string]any); ok { + for property, description := range propertyMap { + if _, isSet := serviceDict[property]; isSet { + output[property] = description + } + } + } + } + + return output +} + +// ForbiddenPropertiesError is returned when there are properties in the Compose +// file that are forbidden. +type ForbiddenPropertiesError struct { + Properties map[string]string +} + +func (e *ForbiddenPropertiesError) Error() string { + return "Configuration contains forbidden properties" +} + +func getServices(configDict map[string]any) map[string]any { + if services, ok := configDict["services"]; ok { + if servicesDict, ok := services.(map[string]any); ok { + return servicesDict + } + } + + return map[string]any{} +} + +// Transform converts the source into the target struct with compose types transformer +// and the specified transformers if any. +func Transform(source any, target any, additionalTransformers ...Transformer) error { + data := mapstructure.Metadata{} + config := &mapstructure.DecoderConfig{ + DecodeHook: mapstructure.ComposeDecodeHookFunc( + createTransformHook(additionalTransformers...), + mapstructure.StringToTimeDurationHookFunc()), + Result: target, + Metadata: &data, + } + decoder, err := mapstructure.NewDecoder(config) + if err != nil { + return err + } + return decoder.Decode(source) +} + +// TransformerFunc defines a function to perform the actual transformation +type TransformerFunc func(any) (any, error) + +// Transformer defines a map to type transformer +type Transformer struct { + TypeOf reflect.Type + Func TransformerFunc +} + +func createTransformHook(additionalTransformers ...Transformer) mapstructure.DecodeHookFuncType { + transforms := map[reflect.Type]func(any) (any, error){ + reflect.TypeOf(types.External{}): transformExternal, + reflect.TypeOf(types.HealthCheckTest{}): transformHealthCheckTest, + reflect.TypeOf(types.ShellCommand{}): transformShellCommand, + reflect.TypeOf(types.StringList{}): transformStringList, + reflect.TypeOf(map[string]string{}): transformMapStringString, + reflect.TypeOf(types.UlimitsConfig{}): transformUlimits, + reflect.TypeOf(types.UnitBytes(0)): transformSize, + reflect.TypeOf([]types.ServicePortConfig{}): transformServicePort, + reflect.TypeOf(types.ServiceSecretConfig{}): transformStringSourceMap, + reflect.TypeOf(types.ServiceConfigObjConfig{}): transformStringSourceMap, + reflect.TypeOf(types.StringOrNumberList{}): transformStringOrNumberList, + reflect.TypeOf(map[string]*types.ServiceNetworkConfig{}): transformServiceNetworkMap, + reflect.TypeOf(types.Mapping{}): transformMappingOrListFunc("=", false), + reflect.TypeOf(types.MappingWithEquals{}): transformMappingOrListFunc("=", true), + reflect.TypeOf(types.Labels{}): transformMappingOrListFunc("=", false), + reflect.TypeOf(types.MappingWithColon{}): transformMappingOrListFunc(":", false), + reflect.TypeOf(types.HostsList{}): transformHostsList, + reflect.TypeOf(types.ServiceVolumeConfig{}): transformServiceVolumeConfig, + reflect.TypeOf(types.BuildConfig{}): transformBuildConfig, + reflect.TypeOf(types.Duration(0)): transformStringToDuration, + } + + for _, transformer := range additionalTransformers { + transforms[transformer.TypeOf] = transformer.Func + } + + return func(_ reflect.Type, target reflect.Type, data any) (any, error) { + transform, ok := transforms[target] + if !ok { + return data, nil + } + return transform(data) + } +} + +// keys needs to be converted to strings for jsonschema +func convertToStringKeysRecursive(value any, keyPrefix string) (any, error) { + if mapping, ok := value.(map[any]any); ok { + dict := make(map[string]any) + for key, entry := range mapping { + str, ok := key.(string) + if !ok { + return nil, formatInvalidKeyError(keyPrefix, key) + } + var newKeyPrefix string + if keyPrefix == "" { + newKeyPrefix = str + } else { + newKeyPrefix = fmt.Sprintf("%s.%s", keyPrefix, str) + } + convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix) + if err != nil { + return nil, err + } + dict[str] = convertedEntry + } + return dict, nil + } + if list, ok := value.([]any); ok { + var convertedList []any + for index, entry := range list { + newKeyPrefix := fmt.Sprintf("%s[%d]", keyPrefix, index) + convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix) + if err != nil { + return nil, err + } + convertedList = append(convertedList, convertedEntry) + } + return convertedList, nil + } + return value, nil +} + +func formatInvalidKeyError(keyPrefix string, key any) error { + var location string + if keyPrefix == "" { + location = "at top level" + } else { + location = "in " + keyPrefix + } + return errors.Errorf("non-string key %s: %#v", location, key) +} + +// LoadServices produces a ServiceConfig map from a compose file Dict +// the servicesDict is not validated if directly used. Use Load() to enable validation +func LoadServices(servicesDict map[string]any, workingDir string, lookupEnv template.Mapping) ([]types.ServiceConfig, error) { + services := make([]types.ServiceConfig, 0, len(servicesDict)) + + for name, serviceDef := range servicesDict { + serviceConfig, err := LoadService(name, serviceDef.(map[string]any), workingDir, lookupEnv) + if err != nil { + return nil, err + } + services = append(services, *serviceConfig) + } + + return services, nil +} + +// LoadService produces a single ServiceConfig from a compose file Dict +// the serviceDict is not validated if directly used. Use Load() to enable validation +func LoadService(name string, serviceDict map[string]any, workingDir string, lookupEnv template.Mapping) (*types.ServiceConfig, error) { + serviceConfig := &types.ServiceConfig{} + if err := Transform(serviceDict, serviceConfig); err != nil { + return nil, err + } + serviceConfig.Name = name + + if err := resolveEnvironment(serviceConfig, workingDir, lookupEnv); err != nil { + return nil, err + } + + if err := resolveVolumePaths(serviceConfig.Volumes, workingDir, lookupEnv); err != nil { + return nil, err + } + + serviceConfig.Extras = getExtras(serviceDict) + + return serviceConfig, nil +} + +func loadExtras(name string, source map[string]any) map[string]any { + if dict, ok := source[name].(map[string]any); ok { + return getExtras(dict) + } + return nil +} + +func getExtras(dict map[string]any) map[string]any { + extras := map[string]any{} + for key, value := range dict { + if strings.HasPrefix(key, "x-") { + extras[key] = value + } + } + if len(extras) == 0 { + return nil + } + return extras +} + +func updateEnvironment(environment map[string]*string, vars map[string]*string, lookupEnv template.Mapping) { + for k, v := range vars { + interpolatedV, ok := lookupEnv(k) + if (v == nil || *v == "") && ok { + // lookupEnv is prioritized over vars + environment[k] = &interpolatedV + } else { + environment[k] = v + } + } +} + +func resolveEnvironment(serviceConfig *types.ServiceConfig, workingDir string, lookupEnv template.Mapping) error { + environment := make(map[string]*string) + + if len(serviceConfig.EnvFile) > 0 { + var envVars []string + + for _, file := range serviceConfig.EnvFile { + filePath := absPath(workingDir, file) + fileVars, err := opts.ParseEnvFile(filePath) + if err != nil { + return err + } + envVars = append(envVars, fileVars...) + } + updateEnvironment(environment, + opts.ConvertKVStringsToMapWithNil(envVars), lookupEnv) + } + + updateEnvironment(environment, serviceConfig.Environment, lookupEnv) + serviceConfig.Environment = environment + return nil +} + +func resolveVolumePaths(volumes []types.ServiceVolumeConfig, workingDir string, lookupEnv template.Mapping) error { + for i, volume := range volumes { + if volume.Type != "bind" { + continue + } + + if volume.Source == "" { + return errors.New(`invalid mount config for type "bind": field Source must not be empty`) + } + + filePath := expandUser(volume.Source, lookupEnv) + // Check if source is an absolute path (either Unix or Windows), to + // handle a Windows client with a Unix daemon or vice-versa. + // + // Note that this is not required for Docker for Windows when specifying + // a local Windows path, because Docker for Windows translates the Windows + // path into a valid path within the VM. + if !path.IsAbs(filePath) && !isAbs(filePath) { + filePath = absPath(workingDir, filePath) + } + volume.Source = filePath + volumes[i] = volume + } + return nil +} + +// TODO: make this more robust +func expandUser(srcPath string, lookupEnv template.Mapping) string { + if strings.HasPrefix(srcPath, "~") { + home, ok := lookupEnv("HOME") + if !ok { + logrus.Warn("cannot expand '~', because the environment lacks HOME") + return srcPath + } + return strings.Replace(srcPath, "~", home, 1) + } + return srcPath +} + +func transformUlimits(data any) (any, error) { + switch value := data.(type) { + case int: + return types.UlimitsConfig{Single: value}, nil + case map[string]any: + ulimit := types.UlimitsConfig{} + ulimit.Soft = value["soft"].(int) + ulimit.Hard = value["hard"].(int) + return ulimit, nil + default: + return data, errors.Errorf("invalid type %T for ulimits", value) + } +} + +// LoadNetworks produces a NetworkConfig map from a compose file Dict +// the source Dict is not validated if directly used. Use Load() to enable validation +func LoadNetworks(source map[string]any, version string) (map[string]types.NetworkConfig, error) { + networks := make(map[string]types.NetworkConfig) + err := Transform(source, &networks) + if err != nil { + return networks, err + } + for name, network := range networks { + if !network.External.External { + continue + } + switch { + case network.External.Name != "": + if network.Name != "" { + return nil, errors.Errorf("network %s: network.external.name and network.name conflict; only use network.name", name) + } + if versions.GreaterThanOrEqualTo(version, "3.5") { + logrus.Warnf("network %s: network.external.name is deprecated in favor of network.name", name) + } + network.Name = network.External.Name + network.External.Name = "" + case network.Name == "": + network.Name = name + } + network.Extras = loadExtras(name, source) + networks[name] = network + } + return networks, nil +} + +func externalVolumeError(volume, key string) error { + return errors.Errorf( + "conflicting parameters \"external\" and %q specified for volume %q", + key, volume) +} + +// LoadVolumes produces a VolumeConfig map from a compose file Dict +// the source Dict is not validated if directly used. Use Load() to enable validation +func LoadVolumes(source map[string]any, version string) (map[string]types.VolumeConfig, error) { + volumes := make(map[string]types.VolumeConfig) + if err := Transform(source, &volumes); err != nil { + return volumes, err + } + + for name, volume := range volumes { + if !volume.External.External { + continue + } + switch { + case volume.Driver != "": + return nil, externalVolumeError(name, "driver") + case len(volume.DriverOpts) > 0: + return nil, externalVolumeError(name, "driver_opts") + case len(volume.Labels) > 0: + return nil, externalVolumeError(name, "labels") + case volume.External.Name != "": + if volume.Name != "" { + return nil, errors.Errorf("volume %s: volume.external.name and volume.name conflict; only use volume.name", name) + } + if versions.GreaterThanOrEqualTo(version, "3.4") { + logrus.Warnf("volume %s: volume.external.name is deprecated in favor of volume.name", name) + } + volume.Name = volume.External.Name + volume.External.Name = "" + case volume.Name == "": + volume.Name = name + } + volume.Extras = loadExtras(name, source) + volumes[name] = volume + } + return volumes, nil +} + +// LoadSecrets produces a SecretConfig map from a compose file Dict +// the source Dict is not validated if directly used. Use Load() to enable validation +func LoadSecrets(source map[string]any, details types.ConfigDetails) (map[string]types.SecretConfig, error) { + secrets := make(map[string]types.SecretConfig) + if err := Transform(source, &secrets); err != nil { + return secrets, err + } + for name, secret := range secrets { + obj, err := loadFileObjectConfig(name, "secret", types.FileObjectConfig(secret), details) + if err != nil { + return nil, err + } + secretConfig := types.SecretConfig(obj) + secretConfig.Extras = loadExtras(name, source) + secrets[name] = secretConfig + } + return secrets, nil +} + +// LoadConfigObjs produces a ConfigObjConfig map from a compose file Dict +// the source Dict is not validated if directly used. Use Load() to enable validation +func LoadConfigObjs(source map[string]any, details types.ConfigDetails) (map[string]types.ConfigObjConfig, error) { + configs := make(map[string]types.ConfigObjConfig) + if err := Transform(source, &configs); err != nil { + return configs, err + } + for name, config := range configs { + obj, err := loadFileObjectConfig(name, "config", types.FileObjectConfig(config), details) + if err != nil { + return nil, err + } + configConfig := types.ConfigObjConfig(obj) + configConfig.Extras = loadExtras(name, source) + configs[name] = configConfig + } + return configs, nil +} + +func loadFileObjectConfig(name string, objType string, obj types.FileObjectConfig, details types.ConfigDetails) (types.FileObjectConfig, error) { + // if "external: true" + switch { + case obj.External.External: + // handle deprecated external.name + if obj.External.Name != "" { + if obj.Name != "" { + return obj, errors.Errorf("%[1]s %[2]s: %[1]s.external.name and %[1]s.name conflict; only use %[1]s.name", objType, name) + } + if versions.GreaterThanOrEqualTo(details.Version, "3.5") { + logrus.Warnf("%[1]s %[2]s: %[1]s.external.name is deprecated in favor of %[1]s.name", objType, name) + } + obj.Name = obj.External.Name + obj.External.Name = "" + } else if obj.Name == "" { + obj.Name = name + } + // if not "external: true" + case obj.Driver != "": + if obj.File != "" { + return obj, errors.Errorf("%[1]s %[2]s: %[1]s.driver and %[1]s.file conflict; only use %[1]s.driver", objType, name) + } + default: + obj.File = absPath(details.WorkingDir, obj.File) + } + + return obj, nil +} + +func absPath(workingDir string, filePath string) string { + if filepath.IsAbs(filePath) { + return filePath + } + return filepath.Join(workingDir, filePath) +} + +var transformMapStringString TransformerFunc = func(data any) (any, error) { + switch value := data.(type) { + case map[string]any: + return toMapStringString(value, false), nil + case map[string]string: + return value, nil + default: + return data, errors.Errorf("invalid type %T for map[string]string", value) + } +} + +var transformExternal TransformerFunc = func(data any) (any, error) { + switch value := data.(type) { + case bool: + return map[string]any{"external": value}, nil + case map[string]any: + return map[string]any{"external": true, "name": value["name"]}, nil + default: + return data, errors.Errorf("invalid type %T for external", value) + } +} + +var transformServicePort TransformerFunc = func(data any) (any, error) { + switch entries := data.(type) { + case []any: + // We process the list instead of individual items here. + // The reason is that one entry might be mapped to multiple ServicePortConfig. + // Therefore we take an input of a list and return an output of a list. + ports := []any{} + for _, entry := range entries { + switch value := entry.(type) { + case int: + v, err := toServicePortConfigs(strconv.Itoa(value)) + if err != nil { + return data, err + } + ports = append(ports, v...) + case string: + v, err := toServicePortConfigs(value) + if err != nil { + return data, err + } + ports = append(ports, v...) + case map[string]any: + ports = append(ports, value) + default: + return data, errors.Errorf("invalid type %T for port", value) + } + } + return ports, nil + default: + return data, errors.Errorf("invalid type %T for port", entries) + } +} + +var transformStringSourceMap TransformerFunc = func(data any) (any, error) { + switch value := data.(type) { + case string: + return map[string]any{"source": value}, nil + case map[string]any: + return data, nil + default: + return data, errors.Errorf("invalid type %T for secret", value) + } +} + +var transformBuildConfig TransformerFunc = func(data any) (any, error) { + switch value := data.(type) { + case string: + return map[string]any{"context": value}, nil + case map[string]any: + return data, nil + default: + return data, errors.Errorf("invalid type %T for service build", value) + } +} + +var transformServiceVolumeConfig TransformerFunc = func(data any) (any, error) { + switch value := data.(type) { + case string: + return ParseVolume(value) + case map[string]any: + return data, nil + default: + return data, errors.Errorf("invalid type %T for service volume", value) + } +} + +var transformServiceNetworkMap TransformerFunc = func(value any) (any, error) { + if list, ok := value.([]any); ok { + mapValue := map[any]any{} + for _, name := range list { + mapValue[name] = nil + } + return mapValue, nil + } + return value, nil +} + +var transformStringOrNumberList TransformerFunc = func(value any) (any, error) { + list := value.([]any) + result := make([]string, len(list)) + for i, item := range list { + result[i] = fmt.Sprint(item) + } + return result, nil +} + +var transformStringList TransformerFunc = func(data any) (any, error) { + switch value := data.(type) { + case string: + return []string{value}, nil + case []any: + return value, nil + default: + return data, errors.Errorf("invalid type %T for string list", value) + } +} + +var transformHostsList TransformerFunc = func(data any) (any, error) { + hl := transformListOrMapping(data, ":", false, []string{"=", ":"}) + + // Remove brackets from IP addresses if present (for example "[::1]" -> "::1"). + result := make([]string, 0, len(hl)) + for _, hip := range hl { + host, ip, _ := strings.Cut(hip, ":") + if len(ip) > 2 && ip[0] == '[' && ip[len(ip)-1] == ']' { + ip = ip[1 : len(ip)-1] + } + result = append(result, fmt.Sprintf("%s:%s", host, ip)) + } + return result, nil +} + +// transformListOrMapping transforms pairs of strings that may be represented as +// a map, or a list of '=' or ':' separated strings, into a list of ':' separated +// strings. +func transformListOrMapping(listOrMapping any, sep string, allowNil bool, allowSeps []string) []string { + switch value := listOrMapping.(type) { + case map[string]any: + return toStringList(value, sep, allowNil) + case []any: + result := make([]string, 0, len(value)) + for _, entry := range value { + for i, allowSep := range allowSeps { + entry := fmt.Sprint(entry) + k, v, ok := strings.Cut(entry, allowSep) + if ok { + // Entry uses this allowed separator. Add it to the result, using + // sep as a separator. + result = append(result, fmt.Sprintf("%s%s%s", k, sep, v)) + break + } else if i == len(allowSeps)-1 { + // No more separators to try, keep the entry if allowNil. + if allowNil { + result = append(result, k) + } + } + } + } + return result + } + panic(errors.Errorf("expected a map or a list, got %T: %#v", listOrMapping, listOrMapping)) +} + +func transformMappingOrListFunc(sep string, allowNil bool) TransformerFunc { + return func(data any) (any, error) { + return transformMappingOrList(data, sep, allowNil), nil + } +} + +func transformMappingOrList(mappingOrList any, sep string, allowNil bool) any { + switch values := mappingOrList.(type) { + case map[string]any: + return toMapStringString(values, allowNil) + case []any: + result := make(map[string]any) + for _, v := range values { + key, val, hasValue := strings.Cut(v.(string), sep) + switch { + case !hasValue && allowNil: + result[key] = nil + case !hasValue && !allowNil: + result[key] = "" + default: + result[key] = val + } + } + return result + } + panic(errors.Errorf("expected a map or a list, got %T: %#v", mappingOrList, mappingOrList)) +} + +var transformShellCommand TransformerFunc = func(value any) (any, error) { + if str, ok := value.(string); ok { + return shlex.Split(str) + } + return value, nil +} + +var transformHealthCheckTest TransformerFunc = func(data any) (any, error) { + switch value := data.(type) { + case string: + return append([]string{"CMD-SHELL"}, value), nil + case []any: + return value, nil + default: + return value, errors.Errorf("invalid type %T for healthcheck.test", value) + } +} + +var transformSize TransformerFunc = func(value any) (any, error) { + switch value := value.(type) { + case int: + return int64(value), nil + case string: + return units.RAMInBytes(value) + } + panic(errors.Errorf("invalid type for size %T", value)) +} + +var transformStringToDuration TransformerFunc = func(value any) (any, error) { + switch value := value.(type) { + case string: + d, err := time.ParseDuration(value) + if err != nil { + return value, err + } + return types.Duration(d), nil + default: + return value, errors.Errorf("invalid type %T for duration", value) + } +} + +func toServicePortConfigs(value string) ([]any, error) { + var portConfigs []any + + ports, portBindings, err := nat.ParsePortSpecs([]string{value}) + if err != nil { + return nil, err + } + // We need to sort the key of the ports to make sure it is consistent + keys := []string{} + for port := range ports { + keys = append(keys, string(port)) + } + sort.Strings(keys) + + for _, key := range keys { + // Reuse ConvertPortToPortConfig so that it is consistent + portConfig, err := opts.ConvertPortToPortConfig(nat.Port(key), portBindings) + if err != nil { + return nil, err + } + for _, p := range portConfig { + portConfigs = append(portConfigs, types.ServicePortConfig{ + Protocol: string(p.Protocol), + Target: p.TargetPort, + Published: p.PublishedPort, + Mode: string(p.PublishMode), + }) + } + } + + return portConfigs, nil +} + +func toMapStringString(value map[string]any, allowNil bool) map[string]any { + output := make(map[string]any) + for key, value := range value { + output[key] = toString(value, allowNil) + } + return output +} + +func toString(value any, allowNil bool) any { + switch { + case value != nil: + return fmt.Sprint(value) + case allowNil: + return nil + default: + return "" + } +} + +func toStringList(value map[string]any, separator string, allowNil bool) []string { + output := []string{} + for key, value := range value { + if value == nil && !allowNil { + continue + } + output = append(output, fmt.Sprintf("%s%s%s", key, separator, value)) + } + sort.Strings(output) + return output +} diff --git a/vendor/github.com/docker/cli/cli/compose/loader/merge.go b/vendor/github.com/docker/cli/cli/compose/loader/merge.go new file mode 100644 index 00000000..34455d59 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/loader/merge.go @@ -0,0 +1,304 @@ +// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: +//go:build go1.22 + +package loader + +import ( + "reflect" + "sort" + + "dario.cat/mergo" + "github.com/docker/cli/cli/compose/types" + "github.com/pkg/errors" +) + +type specials struct { + m map[reflect.Type]func(dst, src reflect.Value) error +} + +func (s *specials) Transformer(t reflect.Type) func(dst, src reflect.Value) error { + if fn, ok := s.m[t]; ok { + return fn + } + return nil +} + +func merge(configs []*types.Config) (*types.Config, error) { + base := configs[0] + for _, override := range configs[1:] { + var err error + base.Services, err = mergeServices(base.Services, override.Services) + if err != nil { + return base, errors.Wrapf(err, "cannot merge services from %s", override.Filename) + } + base.Volumes, err = mergeVolumes(base.Volumes, override.Volumes) + if err != nil { + return base, errors.Wrapf(err, "cannot merge volumes from %s", override.Filename) + } + base.Networks, err = mergeNetworks(base.Networks, override.Networks) + if err != nil { + return base, errors.Wrapf(err, "cannot merge networks from %s", override.Filename) + } + base.Secrets, err = mergeSecrets(base.Secrets, override.Secrets) + if err != nil { + return base, errors.Wrapf(err, "cannot merge secrets from %s", override.Filename) + } + base.Configs, err = mergeConfigs(base.Configs, override.Configs) + if err != nil { + return base, errors.Wrapf(err, "cannot merge configs from %s", override.Filename) + } + } + return base, nil +} + +func mergeServices(base, override []types.ServiceConfig) ([]types.ServiceConfig, error) { + baseServices := mapByName(base) + overrideServices := mapByName(override) + specials := &specials{ + m: map[reflect.Type]func(dst, src reflect.Value) error{ + reflect.TypeOf(&types.LoggingConfig{}): safelyMerge(mergeLoggingConfig), + reflect.TypeOf([]types.ServicePortConfig{}): mergeSlice(toServicePortConfigsMap, toServicePortConfigsSlice), + reflect.TypeOf([]types.ServiceSecretConfig{}): mergeSlice(toServiceSecretConfigsMap, toServiceSecretConfigsSlice), + reflect.TypeOf([]types.ServiceConfigObjConfig{}): mergeSlice(toServiceConfigObjConfigsMap, toSServiceConfigObjConfigsSlice), + reflect.TypeOf(&types.UlimitsConfig{}): mergeUlimitsConfig, + reflect.TypeOf([]types.ServiceVolumeConfig{}): mergeSlice(toServiceVolumeConfigsMap, toServiceVolumeConfigsSlice), + reflect.TypeOf(types.ShellCommand{}): mergeShellCommand, + reflect.TypeOf(&types.ServiceNetworkConfig{}): mergeServiceNetworkConfig, + reflect.PointerTo(reflect.TypeOf(uint64(1))): mergeUint64, + }, + } + for name, overrideService := range overrideServices { + overrideService := overrideService + if baseService, ok := baseServices[name]; ok { + if err := mergo.Merge(&baseService, &overrideService, mergo.WithAppendSlice, mergo.WithOverride, mergo.WithTransformers(specials)); err != nil { + return base, errors.Wrapf(err, "cannot merge service %s", name) + } + baseServices[name] = baseService + continue + } + baseServices[name] = overrideService + } + services := []types.ServiceConfig{} + for _, baseService := range baseServices { + services = append(services, baseService) + } + sort.Slice(services, func(i, j int) bool { return services[i].Name < services[j].Name }) + return services, nil +} + +func toServiceSecretConfigsMap(s any) (map[any]any, error) { + secrets, ok := s.([]types.ServiceSecretConfig) + if !ok { + return nil, errors.Errorf("not a serviceSecretConfig: %v", s) + } + m := map[any]any{} + for _, secret := range secrets { + m[secret.Source] = secret + } + return m, nil +} + +func toServiceConfigObjConfigsMap(s any) (map[any]any, error) { + secrets, ok := s.([]types.ServiceConfigObjConfig) + if !ok { + return nil, errors.Errorf("not a serviceSecretConfig: %v", s) + } + m := map[any]any{} + for _, secret := range secrets { + m[secret.Source] = secret + } + return m, nil +} + +func toServicePortConfigsMap(s any) (map[any]any, error) { + ports, ok := s.([]types.ServicePortConfig) + if !ok { + return nil, errors.Errorf("not a servicePortConfig slice: %v", s) + } + m := map[any]any{} + for _, p := range ports { + m[p.Published] = p + } + return m, nil +} + +func toServiceVolumeConfigsMap(s any) (map[any]any, error) { + volumes, ok := s.([]types.ServiceVolumeConfig) + if !ok { + return nil, errors.Errorf("not a serviceVolumeConfig slice: %v", s) + } + m := map[any]any{} + for _, v := range volumes { + m[v.Target] = v + } + return m, nil +} + +func toServiceSecretConfigsSlice(dst reflect.Value, m map[any]any) error { + s := []types.ServiceSecretConfig{} + for _, v := range m { + s = append(s, v.(types.ServiceSecretConfig)) + } + sort.Slice(s, func(i, j int) bool { return s[i].Source < s[j].Source }) + dst.Set(reflect.ValueOf(s)) + return nil +} + +func toSServiceConfigObjConfigsSlice(dst reflect.Value, m map[any]any) error { + s := []types.ServiceConfigObjConfig{} + for _, v := range m { + s = append(s, v.(types.ServiceConfigObjConfig)) + } + sort.Slice(s, func(i, j int) bool { return s[i].Source < s[j].Source }) + dst.Set(reflect.ValueOf(s)) + return nil +} + +func toServicePortConfigsSlice(dst reflect.Value, m map[any]any) error { + s := []types.ServicePortConfig{} + for _, v := range m { + s = append(s, v.(types.ServicePortConfig)) + } + sort.Slice(s, func(i, j int) bool { return s[i].Published < s[j].Published }) + dst.Set(reflect.ValueOf(s)) + return nil +} + +func toServiceVolumeConfigsSlice(dst reflect.Value, m map[any]any) error { + s := []types.ServiceVolumeConfig{} + for _, v := range m { + s = append(s, v.(types.ServiceVolumeConfig)) + } + sort.Slice(s, func(i, j int) bool { return s[i].Target < s[j].Target }) + dst.Set(reflect.ValueOf(s)) + return nil +} + +type ( + tomapFn func(s any) (map[any]any, error) + writeValueFromMapFn func(reflect.Value, map[any]any) error +) + +func safelyMerge(mergeFn func(dst, src reflect.Value) error) func(dst, src reflect.Value) error { + return func(dst, src reflect.Value) error { + if src.IsNil() { + return nil + } + if dst.IsNil() { + dst.Set(src) + return nil + } + return mergeFn(dst, src) + } +} + +func mergeSlice(tomap tomapFn, writeValue writeValueFromMapFn) func(dst, src reflect.Value) error { + return func(dst, src reflect.Value) error { + dstMap, err := sliceToMap(tomap, dst) + if err != nil { + return err + } + srcMap, err := sliceToMap(tomap, src) + if err != nil { + return err + } + if err := mergo.Map(&dstMap, srcMap, mergo.WithOverride); err != nil { + return err + } + return writeValue(dst, dstMap) + } +} + +func sliceToMap(tomap tomapFn, v reflect.Value) (map[any]any, error) { + // check if valid + if !v.IsValid() { + return nil, errors.Errorf("invalid value : %+v", v) + } + return tomap(v.Interface()) +} + +func mergeLoggingConfig(dst, src reflect.Value) error { + // Same driver, merging options + if getLoggingDriver(dst.Elem()) == getLoggingDriver(src.Elem()) || + getLoggingDriver(dst.Elem()) == "" || getLoggingDriver(src.Elem()) == "" { + if getLoggingDriver(dst.Elem()) == "" { + dst.Elem().FieldByName("Driver").SetString(getLoggingDriver(src.Elem())) + } + dstOptions := dst.Elem().FieldByName("Options").Interface().(map[string]string) + srcOptions := src.Elem().FieldByName("Options").Interface().(map[string]string) + return mergo.Merge(&dstOptions, srcOptions, mergo.WithOverride) + } + // Different driver, override with src + dst.Set(src) + return nil +} + +//nolint:unparam +func mergeUlimitsConfig(dst, src reflect.Value) error { + if src.Interface() != reflect.Zero(reflect.TypeOf(src.Interface())).Interface() { + dst.Elem().Set(src.Elem()) + } + return nil +} + +//nolint:unparam +func mergeShellCommand(dst, src reflect.Value) error { + if src.Len() != 0 { + dst.Set(src) + } + return nil +} + +//nolint:unparam +func mergeServiceNetworkConfig(dst, src reflect.Value) error { + if src.Interface() != reflect.Zero(reflect.TypeOf(src.Interface())).Interface() { + dst.Elem().FieldByName("Aliases").Set(src.Elem().FieldByName("Aliases")) + if ipv4 := src.Elem().FieldByName("Ipv4Address").Interface().(string); ipv4 != "" { + dst.Elem().FieldByName("Ipv4Address").SetString(ipv4) + } + if ipv6 := src.Elem().FieldByName("Ipv6Address").Interface().(string); ipv6 != "" { + dst.Elem().FieldByName("Ipv6Address").SetString(ipv6) + } + } + return nil +} + +//nolint:unparam +func mergeUint64(dst, src reflect.Value) error { + if !src.IsNil() { + dst.Elem().Set(src.Elem()) + } + return nil +} + +func getLoggingDriver(v reflect.Value) string { + return v.FieldByName("Driver").String() +} + +func mapByName(services []types.ServiceConfig) map[string]types.ServiceConfig { + m := map[string]types.ServiceConfig{} + for _, service := range services { + m[service.Name] = service + } + return m +} + +func mergeVolumes(base, override map[string]types.VolumeConfig) (map[string]types.VolumeConfig, error) { + err := mergo.Map(&base, &override, mergo.WithOverride) + return base, err +} + +func mergeNetworks(base, override map[string]types.NetworkConfig) (map[string]types.NetworkConfig, error) { + err := mergo.Map(&base, &override, mergo.WithOverride) + return base, err +} + +func mergeSecrets(base, override map[string]types.SecretConfig) (map[string]types.SecretConfig, error) { + err := mergo.Map(&base, &override, mergo.WithOverride) + return base, err +} + +func mergeConfigs(base, override map[string]types.ConfigObjConfig) (map[string]types.ConfigObjConfig, error) { + err := mergo.Map(&base, &override, mergo.WithOverride) + return base, err +} diff --git a/vendor/github.com/docker/cli/cli/compose/loader/volume.go b/vendor/github.com/docker/cli/cli/compose/loader/volume.go new file mode 100644 index 00000000..f043f4aa --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/loader/volume.go @@ -0,0 +1,125 @@ +package loader + +import ( + "strings" + "unicode" + "unicode/utf8" + + "github.com/docker/cli/cli/compose/types" + "github.com/docker/docker/api/types/mount" + "github.com/pkg/errors" +) + +const endOfSpec = rune(0) + +// ParseVolume parses a volume spec without any knowledge of the target platform +func ParseVolume(spec string) (types.ServiceVolumeConfig, error) { + volume := types.ServiceVolumeConfig{} + + switch len(spec) { + case 0: + return volume, errors.New("invalid empty volume spec") + case 1, 2: + volume.Target = spec + volume.Type = string(mount.TypeVolume) + return volume, nil + } + + buffer := []rune{} + for _, char := range spec + string(endOfSpec) { + switch { + case isWindowsDrive(buffer, char): + buffer = append(buffer, char) + case char == ':' || char == endOfSpec: + if err := populateFieldFromBuffer(char, buffer, &volume); err != nil { + populateType(&volume) + return volume, errors.Wrapf(err, "invalid spec: %s", spec) + } + buffer = []rune{} + default: + buffer = append(buffer, char) + } + } + + populateType(&volume) + return volume, nil +} + +func isWindowsDrive(buffer []rune, char rune) bool { + return char == ':' && len(buffer) == 1 && unicode.IsLetter(buffer[0]) +} + +func populateFieldFromBuffer(char rune, buffer []rune, volume *types.ServiceVolumeConfig) error { + strBuffer := string(buffer) + switch { + case len(buffer) == 0: + return errors.New("empty section between colons") + // Anonymous volume + case volume.Source == "" && char == endOfSpec: + volume.Target = strBuffer + return nil + case volume.Source == "": + volume.Source = strBuffer + return nil + case volume.Target == "": + volume.Target = strBuffer + return nil + case char == ':': + return errors.New("too many colons") + } + for _, option := range strings.Split(strBuffer, ",") { + switch option { + case "ro": + volume.ReadOnly = true + case "rw": + volume.ReadOnly = false + case "nocopy": + volume.Volume = &types.ServiceVolumeVolume{NoCopy: true} + default: + if isBindOption(option) { + volume.Bind = &types.ServiceVolumeBind{Propagation: option} + } + // ignore unknown options + } + } + return nil +} + +func isBindOption(option string) bool { + for _, propagation := range mount.Propagations { + if mount.Propagation(option) == propagation { + return true + } + } + return false +} + +func populateType(volume *types.ServiceVolumeConfig) { + switch { + // Anonymous volume + case volume.Source == "": + volume.Type = string(mount.TypeVolume) + case isFilePath(volume.Source): + volume.Type = string(mount.TypeBind) + default: + volume.Type = string(mount.TypeVolume) + } +} + +func isFilePath(source string) bool { + switch source[0] { + case '.', '/', '~': + return true + } + if len([]rune(source)) == 1 { + return false + } + + // windows named pipes + if strings.HasPrefix(source, `\\`) { + return true + } + + first, nextIndex := utf8.DecodeRuneInString(source) + return isWindowsDrive([]rune{first}, rune(source[nextIndex])) +} diff --git a/vendor/github.com/docker/cli/cli/compose/loader/windows_path.go b/vendor/github.com/docker/cli/cli/compose/loader/windows_path.go new file mode 100644 index 00000000..3070bf88 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/loader/windows_path.go @@ -0,0 +1,67 @@ +package loader + +// Copyright 2010 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. +// https://github.com/golang/go/blob/master/LICENSE + +// This file contains utilities to check for Windows absolute paths on Linux. +// The code in this file was largely copied from the Golang filepath package +// https://github.com/golang/go/blob/1d0e94b1e13d5e8a323a63cd1cc1ef95290c9c36/src/path/filepath/path_windows.go#L12-L65 + +func isSlash(c uint8) bool { + return c == '\\' || c == '/' +} + +// isAbs reports whether the path is a Windows absolute path. +func isAbs(path string) (b bool) { + l := volumeNameLen(path) + if l == 0 { + return false + } + path = path[l:] + if path == "" { + return false + } + return isSlash(path[0]) +} + +// volumeNameLen returns length of the leading volume name on Windows. +// It returns 0 elsewhere. +// +//nolint:gocyclo +func volumeNameLen(path string) int { + if len(path) < 2 { + return 0 + } + // with drive letter + c := path[0] + if path[1] == ':' && ('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') { + return 2 + } + // is it UNC? https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx + if l := len(path); l >= 5 && isSlash(path[0]) && isSlash(path[1]) && + !isSlash(path[2]) && path[2] != '.' { + // first, leading `\\` and next shouldn't be `\`. its server name. + for n := 3; n < l-1; n++ { + // second, next '\' shouldn't be repeated. + if isSlash(path[n]) { + n++ + // third, following something characters. its share name. + if !isSlash(path[n]) { + if path[n] == '.' { + break + } + for ; n < l; n++ { + if isSlash(path[n]) { + break + } + } + return n + } + break + } + } + } + return 0 +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.0.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.0.json new file mode 100644 index 00000000..f39344cf --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.0.json @@ -0,0 +1,384 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "id": "config_schema_v3.0.json", + "type": "object", + "required": ["version"], + + "properties": { + "version": { + "type": "string" + }, + + "services": { + "id": "#/properties/services", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/service" + } + }, + "additionalProperties": false + }, + + "networks": { + "id": "#/properties/networks", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/network" + } + } + }, + + "volumes": { + "id": "#/properties/volumes", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/volume" + } + }, + "additionalProperties": false + } + }, + + "additionalProperties": false, + + "definitions": { + + "service": { + "id": "#/definitions/service", + "type": "object", + + "properties": { + "deploy": {"$ref": "#/definitions/deployment"}, + "build": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "context": {"type": "string"}, + "dockerfile": {"type": "string"}, + "args": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + } + ] + }, + "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cgroup_parent": {"type": "string"}, + "command": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "container_name": {"type": "string"}, + "depends_on": {"$ref": "#/definitions/list_of_strings"}, + "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "dns": {"$ref": "#/definitions/string_or_list"}, + "dns_search": {"$ref": "#/definitions/string_or_list"}, + "domainname": {"type": "string"}, + "entrypoint": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "env_file": {"$ref": "#/definitions/string_or_list"}, + "environment": {"$ref": "#/definitions/list_or_dict"}, + + "expose": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "expose" + }, + "uniqueItems": true + }, + + "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, + "healthcheck": {"$ref": "#/definitions/healthcheck"}, + "hostname": {"type": "string"}, + "image": {"type": "string"}, + "ipc": {"type": "string"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + + "logging": { + "type": "object", + + "properties": { + "driver": {"type": "string"}, + "options": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number", "null"]} + } + } + }, + "additionalProperties": false + }, + + "mac_address": {"type": "string"}, + "network_mode": {"type": "string"}, + + "networks": { + "oneOf": [ + {"$ref": "#/definitions/list_of_strings"}, + { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "oneOf": [ + { + "type": "object", + "properties": { + "aliases": {"$ref": "#/definitions/list_of_strings"}, + "ipv4_address": {"type": "string"}, + "ipv6_address": {"type": "string"} + }, + "additionalProperties": false + }, + {"type": "null"} + ] + } + }, + "additionalProperties": false + } + ] + }, + "pid": {"type": ["string", "null"]}, + + "ports": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "ports" + }, + "uniqueItems": true + }, + + "privileged": {"type": "boolean"}, + "read_only": {"type": "boolean"}, + "restart": {"type": "string"}, + "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "shm_size": {"type": ["number", "string"]}, + "sysctls": {"$ref": "#/definitions/list_or_dict"}, + "stdin_open": {"type": "boolean"}, + "stop_grace_period": {"type": "string", "format": "duration"}, + "stop_signal": {"type": "string"}, + "tmpfs": {"$ref": "#/definitions/string_or_list"}, + "tty": {"type": "boolean"}, + "ulimits": { + "type": "object", + "patternProperties": { + "^[a-z]+$": { + "oneOf": [ + {"type": "integer"}, + { + "type":"object", + "properties": { + "hard": {"type": "integer"}, + "soft": {"type": "integer"} + }, + "required": ["soft", "hard"], + "additionalProperties": false + } + ] + } + } + }, + "user": {"type": "string"}, + "userns_mode": {"type": "string"}, + "volumes": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "working_dir": {"type": "string"} + }, + "additionalProperties": false + }, + + "healthcheck": { + "id": "#/definitions/healthcheck", + "type": "object", + "additionalProperties": false, + "properties": { + "disable": {"type": "boolean"}, + "interval": {"type": "string"}, + "retries": {"type": "number"}, + "test": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "timeout": {"type": "string"} + } + }, + "deployment": { + "id": "#/definitions/deployment", + "type": ["object", "null"], + "properties": { + "mode": {"type": "string"}, + "replicas": {"type": "integer"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "update_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"} + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "properties": { + "limits": {"$ref": "#/definitions/resource"}, + "reservations": {"$ref": "#/definitions/resource"} + }, + "additionalProperties": false + }, + "restart_policy": { + "type": "object", + "properties": { + "condition": {"type": "string"}, + "delay": {"type": "string", "format": "duration"}, + "max_attempts": {"type": "integer"}, + "window": {"type": "string", "format": "duration"} + }, + "additionalProperties": false + }, + "placement": { + "type": "object", + "properties": { + "constraints": {"type": "array", "items": {"type": "string"}} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + + "resource": { + "id": "#/definitions/resource", + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"} + }, + "additionalProperties": false + }, + + "network": { + "id": "#/definitions/network", + "type": ["object", "null"], + "properties": { + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "ipam": { + "type": "object", + "properties": { + "driver": {"type": "string"}, + "config": { + "type": "array", + "items": { + "type": "object", + "properties": { + "subnet": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "internal": {"type": "boolean"}, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "volume": { + "id": "#/definitions/volume", + "type": ["object", "null"], + "properties": { + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "string_or_list": { + "oneOf": [ + {"type": "string"}, + {"$ref": "#/definitions/list_of_strings"} + ] + }, + + "list_of_strings": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + + "list_or_dict": { + "oneOf": [ + { + "type": "object", + "patternProperties": { + ".+": { + "type": ["string", "number", "null"] + } + }, + "additionalProperties": false + }, + {"type": "array", "items": {"type": "string"}, "uniqueItems": true} + ] + }, + + "constraints": { + "service": { + "id": "#/definitions/constraints/service", + "anyOf": [ + {"required": ["build"]}, + {"required": ["image"]} + ], + "properties": { + "build": { + "required": ["context"] + } + } + } + } + } +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.1.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.1.json new file mode 100644 index 00000000..719c0fa7 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.1.json @@ -0,0 +1,429 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "id": "config_schema_v3.1.json", + "type": "object", + "required": ["version"], + + "properties": { + "version": { + "type": "string" + }, + + "services": { + "id": "#/properties/services", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/service" + } + }, + "additionalProperties": false + }, + + "networks": { + "id": "#/properties/networks", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/network" + } + } + }, + + "volumes": { + "id": "#/properties/volumes", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/volume" + } + }, + "additionalProperties": false + }, + + "secrets": { + "id": "#/properties/secrets", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/secret" + } + }, + "additionalProperties": false + } + }, + + "additionalProperties": false, + + "definitions": { + + "service": { + "id": "#/definitions/service", + "type": "object", + + "properties": { + "deploy": {"$ref": "#/definitions/deployment"}, + "build": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "context": {"type": "string"}, + "dockerfile": {"type": "string"}, + "args": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + } + ] + }, + "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cgroup_parent": {"type": "string"}, + "command": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "container_name": {"type": "string"}, + "depends_on": {"$ref": "#/definitions/list_of_strings"}, + "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "dns": {"$ref": "#/definitions/string_or_list"}, + "dns_search": {"$ref": "#/definitions/string_or_list"}, + "domainname": {"type": "string"}, + "entrypoint": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "env_file": {"$ref": "#/definitions/string_or_list"}, + "environment": {"$ref": "#/definitions/list_or_dict"}, + + "expose": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "expose" + }, + "uniqueItems": true + }, + + "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, + "healthcheck": {"$ref": "#/definitions/healthcheck"}, + "hostname": {"type": "string"}, + "image": {"type": "string"}, + "ipc": {"type": "string"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + + "logging": { + "type": "object", + + "properties": { + "driver": {"type": "string"}, + "options": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number", "null"]} + } + } + }, + "additionalProperties": false + }, + + "mac_address": {"type": "string"}, + "network_mode": {"type": "string"}, + + "networks": { + "oneOf": [ + {"$ref": "#/definitions/list_of_strings"}, + { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "oneOf": [ + { + "type": "object", + "properties": { + "aliases": {"$ref": "#/definitions/list_of_strings"}, + "ipv4_address": {"type": "string"}, + "ipv6_address": {"type": "string"} + }, + "additionalProperties": false + }, + {"type": "null"} + ] + } + }, + "additionalProperties": false + } + ] + }, + "pid": {"type": ["string", "null"]}, + + "ports": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "ports" + }, + "uniqueItems": true + }, + + "privileged": {"type": "boolean"}, + "read_only": {"type": "boolean"}, + "restart": {"type": "string"}, + "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "shm_size": {"type": ["number", "string"]}, + "secrets": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "sysctls": {"$ref": "#/definitions/list_or_dict"}, + "stdin_open": {"type": "boolean"}, + "stop_grace_period": {"type": "string", "format": "duration"}, + "stop_signal": {"type": "string"}, + "tmpfs": {"$ref": "#/definitions/string_or_list"}, + "tty": {"type": "boolean"}, + "ulimits": { + "type": "object", + "patternProperties": { + "^[a-z]+$": { + "oneOf": [ + {"type": "integer"}, + { + "type":"object", + "properties": { + "hard": {"type": "integer"}, + "soft": {"type": "integer"} + }, + "required": ["soft", "hard"], + "additionalProperties": false + } + ] + } + } + }, + "user": {"type": "string"}, + "userns_mode": {"type": "string"}, + "volumes": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "working_dir": {"type": "string"} + }, + "additionalProperties": false + }, + + "healthcheck": { + "id": "#/definitions/healthcheck", + "type": "object", + "additionalProperties": false, + "properties": { + "disable": {"type": "boolean"}, + "interval": {"type": "string"}, + "retries": {"type": "number"}, + "test": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "timeout": {"type": "string"} + } + }, + "deployment": { + "id": "#/definitions/deployment", + "type": ["object", "null"], + "properties": { + "mode": {"type": "string"}, + "replicas": {"type": "integer"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "update_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"} + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "properties": { + "limits": {"$ref": "#/definitions/resource"}, + "reservations": {"$ref": "#/definitions/resource"} + }, + "additionalProperties": false + }, + "restart_policy": { + "type": "object", + "properties": { + "condition": {"type": "string"}, + "delay": {"type": "string", "format": "duration"}, + "max_attempts": {"type": "integer"}, + "window": {"type": "string", "format": "duration"} + }, + "additionalProperties": false + }, + "placement": { + "type": "object", + "properties": { + "constraints": {"type": "array", "items": {"type": "string"}} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + + "resource": { + "id": "#/definitions/resource", + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"} + }, + "additionalProperties": false + }, + + "network": { + "id": "#/definitions/network", + "type": ["object", "null"], + "properties": { + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "ipam": { + "type": "object", + "properties": { + "driver": {"type": "string"}, + "config": { + "type": "array", + "items": { + "type": "object", + "properties": { + "subnet": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "internal": {"type": "boolean"}, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "volume": { + "id": "#/definitions/volume", + "type": ["object", "null"], + "properties": { + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "secret": { + "id": "#/definitions/secret", + "type": "object", + "properties": { + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "string_or_list": { + "oneOf": [ + {"type": "string"}, + {"$ref": "#/definitions/list_of_strings"} + ] + }, + + "list_of_strings": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + + "list_or_dict": { + "oneOf": [ + { + "type": "object", + "patternProperties": { + ".+": { + "type": ["string", "number", "null"] + } + }, + "additionalProperties": false + }, + {"type": "array", "items": {"type": "string"}, "uniqueItems": true} + ] + }, + + "constraints": { + "service": { + "id": "#/definitions/constraints/service", + "anyOf": [ + {"required": ["build"]}, + {"required": ["image"]} + ], + "properties": { + "build": { + "required": ["context"] + } + } + } + } + } +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.10.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.10.json new file mode 100644 index 00000000..7c032cf5 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.10.json @@ -0,0 +1,672 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "id": "config_schema_v3.10.json", + "type": "object", + + "properties": { + "version": { + "type": "string", + "default": "3.10" + }, + + "services": { + "id": "#/properties/services", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/service" + } + }, + "additionalProperties": false + }, + + "networks": { + "id": "#/properties/networks", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/network" + } + } + }, + + "volumes": { + "id": "#/properties/volumes", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/volume" + } + }, + "additionalProperties": false + }, + + "secrets": { + "id": "#/properties/secrets", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/secret" + } + }, + "additionalProperties": false + }, + + "configs": { + "id": "#/properties/configs", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/config" + } + }, + "additionalProperties": false + } + }, + + "patternProperties": {"^x-": {}}, + "additionalProperties": false, + + "definitions": { + + "service": { + "id": "#/definitions/service", + "type": "object", + + "properties": { + "deploy": {"$ref": "#/definitions/deployment"}, + "build": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "context": {"type": "string"}, + "dockerfile": {"type": "string"}, + "args": {"$ref": "#/definitions/list_or_dict"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "cache_from": {"$ref": "#/definitions/list_of_strings"}, + "network": {"type": "string"}, + "target": {"type": "string"}, + "shm_size": {"type": ["integer", "string"]}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + } + ] + }, + "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cgroupns_mode": {"type": "string"}, + "cgroup_parent": {"type": "string"}, + "command": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "configs": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "container_name": {"type": "string"}, + "credential_spec": { + "type": "object", + "properties": { + "config": {"type": "string"}, + "file": {"type": "string"}, + "registry": {"type": "string"} + }, + "additionalProperties": false + }, + "depends_on": {"$ref": "#/definitions/list_of_strings"}, + "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "dns": {"$ref": "#/definitions/string_or_list"}, + "dns_search": {"$ref": "#/definitions/string_or_list"}, + "domainname": {"type": "string"}, + "entrypoint": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "env_file": {"$ref": "#/definitions/string_or_list"}, + "environment": {"$ref": "#/definitions/list_or_dict"}, + + "expose": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "expose" + }, + "uniqueItems": true + }, + + "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, + "healthcheck": {"$ref": "#/definitions/healthcheck"}, + "hostname": {"type": "string"}, + "image": {"type": "string"}, + "init": {"type": "boolean"}, + "ipc": {"type": "string"}, + "isolation": {"type": "string"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + + "logging": { + "type": "object", + + "properties": { + "driver": {"type": "string"}, + "options": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number", "null"]} + } + } + }, + "additionalProperties": false + }, + + "mac_address": {"type": "string"}, + "network_mode": {"type": "string"}, + + "networks": { + "oneOf": [ + {"$ref": "#/definitions/list_of_strings"}, + { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "oneOf": [ + { + "type": "object", + "properties": { + "aliases": {"$ref": "#/definitions/list_of_strings"}, + "ipv4_address": {"type": "string"}, + "ipv6_address": {"type": "string"} + }, + "additionalProperties": false + }, + {"type": "null"} + ] + } + }, + "additionalProperties": false + } + ] + }, + "pid": {"type": ["string", "null"]}, + + "ports": { + "type": "array", + "items": { + "oneOf": [ + {"type": "number", "format": "ports"}, + {"type": "string", "format": "ports"}, + { + "type": "object", + "properties": { + "mode": {"type": "string"}, + "target": {"type": "integer"}, + "published": {"type": "integer"}, + "protocol": {"type": "string"} + }, + "additionalProperties": false + } + ] + }, + "uniqueItems": true + }, + + "privileged": {"type": "boolean"}, + "read_only": {"type": "boolean"}, + "restart": {"type": "string"}, + "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "shm_size": {"type": ["number", "string"]}, + "secrets": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "sysctls": {"$ref": "#/definitions/list_or_dict"}, + "stdin_open": {"type": "boolean"}, + "stop_grace_period": {"type": "string", "format": "duration"}, + "stop_signal": {"type": "string"}, + "tmpfs": {"$ref": "#/definitions/string_or_list"}, + "tty": {"type": "boolean"}, + "ulimits": { + "type": "object", + "patternProperties": { + "^[a-z]+$": { + "oneOf": [ + {"type": "integer"}, + { + "type":"object", + "properties": { + "hard": {"type": "integer"}, + "soft": {"type": "integer"} + }, + "required": ["soft", "hard"], + "additionalProperties": false + } + ] + } + } + }, + "user": {"type": "string"}, + "userns_mode": {"type": "string"}, + "volumes": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "required": ["type"], + "properties": { + "type": {"type": "string"}, + "source": {"type": "string"}, + "target": {"type": "string"}, + "read_only": {"type": "boolean"}, + "consistency": {"type": "string"}, + "bind": { + "type": "object", + "properties": { + "propagation": {"type": "string"} + } + }, + "volume": { + "type": "object", + "properties": { + "nocopy": {"type": "boolean"} + } + }, + "tmpfs": { + "type": "object", + "properties": { + "size": { + "type": "integer", + "minimum": 0 + } + } + } + }, + "additionalProperties": false + } + ], + "uniqueItems": true + } + }, + "working_dir": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "healthcheck": { + "id": "#/definitions/healthcheck", + "type": "object", + "additionalProperties": false, + "properties": { + "disable": {"type": "boolean"}, + "interval": {"type": "string", "format": "duration"}, + "retries": {"type": "number"}, + "test": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "timeout": {"type": "string", "format": "duration"}, + "start_period": {"type": "string", "format": "duration"} + } + }, + "deployment": { + "id": "#/definitions/deployment", + "type": ["object", "null"], + "properties": { + "mode": {"type": "string"}, + "endpoint_mode": {"type": "string"}, + "replicas": {"type": "integer"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "rollback_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "update_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "properties": { + "limits": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"}, + "pids": {"type": "integer"} + }, + "additionalProperties": false + }, + "reservations": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"}, + "generic_resources": {"$ref": "#/definitions/generic_resources"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "restart_policy": { + "type": "object", + "properties": { + "condition": {"type": "string"}, + "delay": {"type": "string", "format": "duration"}, + "max_attempts": {"type": "integer"}, + "window": {"type": "string", "format": "duration"} + }, + "additionalProperties": false + }, + "placement": { + "type": "object", + "properties": { + "constraints": {"type": "array", "items": {"type": "string"}}, + "preferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "spread": {"type": "string"} + }, + "additionalProperties": false + } + }, + "max_replicas_per_node": {"type": "integer"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + + "generic_resources": { + "id": "#/definitions/generic_resources", + "type": "array", + "items": { + "type": "object", + "properties": { + "discrete_resource_spec": { + "type": "object", + "properties": { + "kind": {"type": "string"}, + "value": {"type": "number"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + + "network": { + "id": "#/definitions/network", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "ipam": { + "type": "object", + "properties": { + "driver": {"type": "string"}, + "config": { + "type": "array", + "items": { + "type": "object", + "properties": { + "subnet": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "internal": {"type": "boolean"}, + "attachable": {"type": "boolean"}, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "volume": { + "id": "#/definitions/volume", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "x-cluster-spec": { + "type": "object", + "properties": { + "group": {"type": "string"}, + "access_mode": { + "type": "object", + "properties": { + "scope": {"type": "string"}, + "sharing": {"type": "string"}, + "block_volume": {"type": "object"}, + "mount_volume": { + "type": "object", + "properties": { + "fs_type": {"type": "string"}, + "mount_flags": {"type": "array", "items": {"type": "string"}} + } + } + } + }, + "accessibility_requirements": { + "type": "object", + "properties": { + "requisite": { + "type": "array", + "items": { + "type": "object", + "properties": { + "segments": {"$ref": "#/definitions/list_or_dict"} + } + } + }, + "preferred": { + "type": "array", + "items": { + "type": "object", + "properties": { + "segments": {"$ref": "#/definitions/list_or_dict"} + } + } + } + } + }, + "capacity_range": { + "type": "object", + "properties": { + "required_bytes": {"type": "string"}, + "limit_bytes": {"type": "string"} + } + }, + "availability": {"type": "string"} + } + } + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "secret": { + "id": "#/definitions/secret", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "template_driver": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "config": { + "id": "#/definitions/config", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "template_driver": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "string_or_list": { + "oneOf": [ + {"type": "string"}, + {"$ref": "#/definitions/list_of_strings"} + ] + }, + + "list_of_strings": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + + "list_or_dict": { + "oneOf": [ + { + "type": "object", + "patternProperties": { + ".+": { + "type": ["string", "number", "null"] + } + }, + "additionalProperties": false + }, + {"type": "array", "items": {"type": "string"}, "uniqueItems": true} + ] + }, + + "constraints": { + "service": { + "id": "#/definitions/constraints/service", + "anyOf": [ + {"required": ["build"]}, + {"required": ["image"]} + ], + "properties": { + "build": { + "required": ["context"] + } + } + } + } + } +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.11.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.11.json new file mode 100644 index 00000000..fb2c9fd8 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.11.json @@ -0,0 +1,672 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "id": "config_schema_v3.11.json", + "type": "object", + + "properties": { + "version": { + "type": "string", + "default": "3.11" + }, + + "services": { + "id": "#/properties/services", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/service" + } + }, + "additionalProperties": false + }, + + "networks": { + "id": "#/properties/networks", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/network" + } + } + }, + + "volumes": { + "id": "#/properties/volumes", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/volume" + } + }, + "additionalProperties": false + }, + + "secrets": { + "id": "#/properties/secrets", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/secret" + } + }, + "additionalProperties": false + }, + + "configs": { + "id": "#/properties/configs", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/config" + } + }, + "additionalProperties": false + } + }, + + "patternProperties": {"^x-": {}}, + "additionalProperties": false, + + "definitions": { + + "service": { + "id": "#/definitions/service", + "type": "object", + + "properties": { + "deploy": {"$ref": "#/definitions/deployment"}, + "build": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "context": {"type": "string"}, + "dockerfile": {"type": "string"}, + "args": {"$ref": "#/definitions/list_or_dict"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "cache_from": {"$ref": "#/definitions/list_of_strings"}, + "network": {"type": "string"}, + "target": {"type": "string"}, + "shm_size": {"type": ["integer", "string"]}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": true + } + ] + }, + "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cgroupns_mode": {"type": "string"}, + "cgroup_parent": {"type": "string"}, + "command": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "configs": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "container_name": {"type": "string"}, + "credential_spec": { + "type": "object", + "properties": { + "config": {"type": "string"}, + "file": {"type": "string"}, + "registry": {"type": "string"} + }, + "additionalProperties": false + }, + "depends_on": {"$ref": "#/definitions/list_of_strings"}, + "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "dns": {"$ref": "#/definitions/string_or_list"}, + "dns_search": {"$ref": "#/definitions/string_or_list"}, + "domainname": {"type": "string"}, + "entrypoint": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "env_file": {"$ref": "#/definitions/string_or_list"}, + "environment": {"$ref": "#/definitions/list_or_dict"}, + + "expose": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "expose" + }, + "uniqueItems": true + }, + + "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, + "healthcheck": {"$ref": "#/definitions/healthcheck"}, + "hostname": {"type": "string"}, + "image": {"type": "string"}, + "init": {"type": "boolean"}, + "ipc": {"type": "string"}, + "isolation": {"type": "string"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + + "logging": { + "type": "object", + + "properties": { + "driver": {"type": "string"}, + "options": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number", "null"]} + } + } + }, + "additionalProperties": false + }, + + "mac_address": {"type": "string"}, + "network_mode": {"type": "string"}, + + "networks": { + "oneOf": [ + {"$ref": "#/definitions/list_of_strings"}, + { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "oneOf": [ + { + "type": "object", + "properties": { + "aliases": {"$ref": "#/definitions/list_of_strings"}, + "ipv4_address": {"type": "string"}, + "ipv6_address": {"type": "string"} + }, + "additionalProperties": false + }, + {"type": "null"} + ] + } + }, + "additionalProperties": false + } + ] + }, + "pid": {"type": ["string", "null"]}, + + "ports": { + "type": "array", + "items": { + "oneOf": [ + {"type": "number", "format": "ports"}, + {"type": "string", "format": "ports"}, + { + "type": "object", + "properties": { + "mode": {"type": "string"}, + "target": {"type": "integer"}, + "published": {"type": "integer"}, + "protocol": {"type": "string"} + }, + "additionalProperties": false + } + ] + }, + "uniqueItems": true + }, + + "privileged": {"type": "boolean"}, + "read_only": {"type": "boolean"}, + "restart": {"type": "string"}, + "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "shm_size": {"type": ["number", "string"]}, + "secrets": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "sysctls": {"$ref": "#/definitions/list_or_dict"}, + "stdin_open": {"type": "boolean"}, + "stop_grace_period": {"type": "string", "format": "duration"}, + "stop_signal": {"type": "string"}, + "tmpfs": {"$ref": "#/definitions/string_or_list"}, + "tty": {"type": "boolean"}, + "ulimits": { + "type": "object", + "patternProperties": { + "^[a-z]+$": { + "oneOf": [ + {"type": "integer"}, + { + "type":"object", + "properties": { + "hard": {"type": "integer"}, + "soft": {"type": "integer"} + }, + "required": ["soft", "hard"], + "additionalProperties": false + } + ] + } + } + }, + "user": {"type": "string"}, + "userns_mode": {"type": "string"}, + "volumes": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "required": ["type"], + "properties": { + "type": {"type": "string"}, + "source": {"type": "string"}, + "target": {"type": "string"}, + "read_only": {"type": "boolean"}, + "consistency": {"type": "string"}, + "bind": { + "type": "object", + "properties": { + "propagation": {"type": "string"} + } + }, + "volume": { + "type": "object", + "properties": { + "nocopy": {"type": "boolean"} + } + }, + "tmpfs": { + "type": "object", + "properties": { + "size": { + "type": "integer", + "minimum": 0 + } + } + } + }, + "additionalProperties": false + } + ], + "uniqueItems": true + } + }, + "working_dir": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "healthcheck": { + "id": "#/definitions/healthcheck", + "type": "object", + "additionalProperties": false, + "properties": { + "disable": {"type": "boolean"}, + "interval": {"type": "string", "format": "duration"}, + "retries": {"type": "number"}, + "test": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "timeout": {"type": "string", "format": "duration"}, + "start_period": {"type": "string", "format": "duration"} + } + }, + "deployment": { + "id": "#/definitions/deployment", + "type": ["object", "null"], + "properties": { + "mode": {"type": "string"}, + "endpoint_mode": {"type": "string"}, + "replicas": {"type": "integer"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "rollback_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "update_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "properties": { + "limits": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"}, + "pids": {"type": "integer"} + }, + "additionalProperties": false + }, + "reservations": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"}, + "generic_resources": {"$ref": "#/definitions/generic_resources"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "restart_policy": { + "type": "object", + "properties": { + "condition": {"type": "string"}, + "delay": {"type": "string", "format": "duration"}, + "max_attempts": {"type": "integer"}, + "window": {"type": "string", "format": "duration"} + }, + "additionalProperties": false + }, + "placement": { + "type": "object", + "properties": { + "constraints": {"type": "array", "items": {"type": "string"}}, + "preferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "spread": {"type": "string"} + }, + "additionalProperties": false + } + }, + "max_replicas_per_node": {"type": "integer"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + + "generic_resources": { + "id": "#/definitions/generic_resources", + "type": "array", + "items": { + "type": "object", + "properties": { + "discrete_resource_spec": { + "type": "object", + "properties": { + "kind": {"type": "string"}, + "value": {"type": "number"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + + "network": { + "id": "#/definitions/network", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "ipam": { + "type": "object", + "properties": { + "driver": {"type": "string"}, + "config": { + "type": "array", + "items": { + "type": "object", + "properties": { + "subnet": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "internal": {"type": "boolean"}, + "attachable": {"type": "boolean"}, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "volume": { + "id": "#/definitions/volume", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "x-cluster-spec": { + "type": "object", + "properties": { + "group": {"type": "string"}, + "access_mode": { + "type": "object", + "properties": { + "scope": {"type": "string"}, + "sharing": {"type": "string"}, + "block_volume": {"type": "object"}, + "mount_volume": { + "type": "object", + "properties": { + "fs_type": {"type": "string"}, + "mount_flags": {"type": "array", "items": {"type": "string"}} + } + } + } + }, + "accessibility_requirements": { + "type": "object", + "properties": { + "requisite": { + "type": "array", + "items": { + "type": "object", + "properties": { + "segments": {"$ref": "#/definitions/list_or_dict"} + } + } + }, + "preferred": { + "type": "array", + "items": { + "type": "object", + "properties": { + "segments": {"$ref": "#/definitions/list_or_dict"} + } + } + } + } + }, + "capacity_range": { + "type": "object", + "properties": { + "required_bytes": {"type": "string"}, + "limit_bytes": {"type": "string"} + } + }, + "availability": {"type": "string"} + } + } + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "secret": { + "id": "#/definitions/secret", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "template_driver": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "config": { + "id": "#/definitions/config", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "template_driver": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "string_or_list": { + "oneOf": [ + {"type": "string"}, + {"$ref": "#/definitions/list_of_strings"} + ] + }, + + "list_of_strings": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + + "list_or_dict": { + "oneOf": [ + { + "type": "object", + "patternProperties": { + ".+": { + "type": ["string", "number", "null"] + } + }, + "additionalProperties": false + }, + {"type": "array", "items": {"type": "string"}, "uniqueItems": true} + ] + }, + + "constraints": { + "service": { + "id": "#/definitions/constraints/service", + "anyOf": [ + {"required": ["build"]}, + {"required": ["image"]} + ], + "properties": { + "build": { + "required": ["context"] + } + } + } + } + } +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.12.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.12.json new file mode 100644 index 00000000..2a548a38 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.12.json @@ -0,0 +1,673 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "id": "config_schema_v3.12.json", + "type": "object", + + "properties": { + "version": { + "type": "string", + "default": "3.12" + }, + + "services": { + "id": "#/properties/services", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/service" + } + }, + "additionalProperties": false + }, + + "networks": { + "id": "#/properties/networks", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/network" + } + } + }, + + "volumes": { + "id": "#/properties/volumes", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/volume" + } + }, + "additionalProperties": false + }, + + "secrets": { + "id": "#/properties/secrets", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/secret" + } + }, + "additionalProperties": false + }, + + "configs": { + "id": "#/properties/configs", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/config" + } + }, + "additionalProperties": false + } + }, + + "patternProperties": {"^x-": {}}, + "additionalProperties": false, + + "definitions": { + + "service": { + "id": "#/definitions/service", + "type": "object", + + "properties": { + "deploy": {"$ref": "#/definitions/deployment"}, + "build": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "context": {"type": "string"}, + "dockerfile": {"type": "string"}, + "args": {"$ref": "#/definitions/list_or_dict"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "cache_from": {"$ref": "#/definitions/list_of_strings"}, + "network": {"type": "string"}, + "target": {"type": "string"}, + "shm_size": {"type": ["integer", "string"]}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": true + } + ] + }, + "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cgroupns_mode": {"type": "string"}, + "cgroup_parent": {"type": "string"}, + "command": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "configs": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "container_name": {"type": "string"}, + "credential_spec": { + "type": "object", + "properties": { + "config": {"type": "string"}, + "file": {"type": "string"}, + "registry": {"type": "string"} + }, + "additionalProperties": false + }, + "depends_on": {"$ref": "#/definitions/list_of_strings"}, + "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "dns": {"$ref": "#/definitions/string_or_list"}, + "dns_search": {"$ref": "#/definitions/string_or_list"}, + "domainname": {"type": "string"}, + "entrypoint": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "env_file": {"$ref": "#/definitions/string_or_list"}, + "environment": {"$ref": "#/definitions/list_or_dict"}, + + "expose": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "expose" + }, + "uniqueItems": true + }, + + "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, + "healthcheck": {"$ref": "#/definitions/healthcheck"}, + "hostname": {"type": "string"}, + "image": {"type": "string"}, + "init": {"type": "boolean"}, + "ipc": {"type": "string"}, + "isolation": {"type": "string"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + + "logging": { + "type": "object", + + "properties": { + "driver": {"type": "string"}, + "options": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number", "null"]} + } + } + }, + "additionalProperties": false + }, + + "mac_address": {"type": "string"}, + "network_mode": {"type": "string"}, + + "networks": { + "oneOf": [ + {"$ref": "#/definitions/list_of_strings"}, + { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "oneOf": [ + { + "type": "object", + "properties": { + "aliases": {"$ref": "#/definitions/list_of_strings"}, + "ipv4_address": {"type": "string"}, + "ipv6_address": {"type": "string"} + }, + "additionalProperties": false + }, + {"type": "null"} + ] + } + }, + "additionalProperties": false + } + ] + }, + "pid": {"type": ["string", "null"]}, + + "ports": { + "type": "array", + "items": { + "oneOf": [ + {"type": "number", "format": "ports"}, + {"type": "string", "format": "ports"}, + { + "type": "object", + "properties": { + "mode": {"type": "string"}, + "target": {"type": "integer"}, + "published": {"type": "integer"}, + "protocol": {"type": "string"} + }, + "additionalProperties": false + } + ] + }, + "uniqueItems": true + }, + + "privileged": {"type": "boolean"}, + "read_only": {"type": "boolean"}, + "restart": {"type": "string"}, + "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "shm_size": {"type": ["number", "string"]}, + "secrets": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "sysctls": {"$ref": "#/definitions/list_or_dict"}, + "stdin_open": {"type": "boolean"}, + "stop_grace_period": {"type": "string", "format": "duration"}, + "stop_signal": {"type": "string"}, + "tmpfs": {"$ref": "#/definitions/string_or_list"}, + "tty": {"type": "boolean"}, + "ulimits": { + "type": "object", + "patternProperties": { + "^[a-z]+$": { + "oneOf": [ + {"type": "integer"}, + { + "type":"object", + "properties": { + "hard": {"type": "integer"}, + "soft": {"type": "integer"} + }, + "required": ["soft", "hard"], + "additionalProperties": false + } + ] + } + } + }, + "user": {"type": "string"}, + "userns_mode": {"type": "string"}, + "volumes": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "required": ["type"], + "properties": { + "type": {"type": "string"}, + "source": {"type": "string"}, + "target": {"type": "string"}, + "read_only": {"type": "boolean"}, + "consistency": {"type": "string"}, + "bind": { + "type": "object", + "properties": { + "propagation": {"type": "string"} + } + }, + "volume": { + "type": "object", + "properties": { + "nocopy": {"type": "boolean"} + } + }, + "tmpfs": { + "type": "object", + "properties": { + "size": { + "type": "integer", + "minimum": 0 + } + } + } + }, + "additionalProperties": false + } + ], + "uniqueItems": true + } + }, + "working_dir": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "healthcheck": { + "id": "#/definitions/healthcheck", + "type": "object", + "additionalProperties": false, + "properties": { + "disable": {"type": "boolean"}, + "interval": {"type": "string", "format": "duration"}, + "retries": {"type": "number"}, + "test": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "timeout": {"type": "string", "format": "duration"}, + "start_period": {"type": "string", "format": "duration"}, + "start_interval": {"type": "string", "format": "duration"} + } + }, + "deployment": { + "id": "#/definitions/deployment", + "type": ["object", "null"], + "properties": { + "mode": {"type": "string"}, + "endpoint_mode": {"type": "string"}, + "replicas": {"type": "integer"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "rollback_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "update_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "properties": { + "limits": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"}, + "pids": {"type": "integer"} + }, + "additionalProperties": false + }, + "reservations": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"}, + "generic_resources": {"$ref": "#/definitions/generic_resources"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "restart_policy": { + "type": "object", + "properties": { + "condition": {"type": "string"}, + "delay": {"type": "string", "format": "duration"}, + "max_attempts": {"type": "integer"}, + "window": {"type": "string", "format": "duration"} + }, + "additionalProperties": false + }, + "placement": { + "type": "object", + "properties": { + "constraints": {"type": "array", "items": {"type": "string"}}, + "preferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "spread": {"type": "string"} + }, + "additionalProperties": false + } + }, + "max_replicas_per_node": {"type": "integer"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + + "generic_resources": { + "id": "#/definitions/generic_resources", + "type": "array", + "items": { + "type": "object", + "properties": { + "discrete_resource_spec": { + "type": "object", + "properties": { + "kind": {"type": "string"}, + "value": {"type": "number"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + + "network": { + "id": "#/definitions/network", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "ipam": { + "type": "object", + "properties": { + "driver": {"type": "string"}, + "config": { + "type": "array", + "items": { + "type": "object", + "properties": { + "subnet": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "internal": {"type": "boolean"}, + "attachable": {"type": "boolean"}, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "volume": { + "id": "#/definitions/volume", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "x-cluster-spec": { + "type": "object", + "properties": { + "group": {"type": "string"}, + "access_mode": { + "type": "object", + "properties": { + "scope": {"type": "string"}, + "sharing": {"type": "string"}, + "block_volume": {"type": "object"}, + "mount_volume": { + "type": "object", + "properties": { + "fs_type": {"type": "string"}, + "mount_flags": {"type": "array", "items": {"type": "string"}} + } + } + } + }, + "accessibility_requirements": { + "type": "object", + "properties": { + "requisite": { + "type": "array", + "items": { + "type": "object", + "properties": { + "segments": {"$ref": "#/definitions/list_or_dict"} + } + } + }, + "preferred": { + "type": "array", + "items": { + "type": "object", + "properties": { + "segments": {"$ref": "#/definitions/list_or_dict"} + } + } + } + } + }, + "capacity_range": { + "type": "object", + "properties": { + "required_bytes": {"type": "string"}, + "limit_bytes": {"type": "string"} + } + }, + "availability": {"type": "string"} + } + } + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "secret": { + "id": "#/definitions/secret", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "template_driver": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "config": { + "id": "#/definitions/config", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "template_driver": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "string_or_list": { + "oneOf": [ + {"type": "string"}, + {"$ref": "#/definitions/list_of_strings"} + ] + }, + + "list_of_strings": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + + "list_or_dict": { + "oneOf": [ + { + "type": "object", + "patternProperties": { + ".+": { + "type": ["string", "number", "null"] + } + }, + "additionalProperties": false + }, + {"type": "array", "items": {"type": "string"}, "uniqueItems": true} + ] + }, + + "constraints": { + "service": { + "id": "#/definitions/constraints/service", + "anyOf": [ + {"required": ["build"]}, + {"required": ["image"]} + ], + "properties": { + "build": { + "required": ["context"] + } + } + } + } + } +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.13.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.13.json new file mode 100644 index 00000000..8daa8892 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.13.json @@ -0,0 +1,680 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "id": "config_schema_v3.13.json", + "type": "object", + + "properties": { + "version": { + "type": "string", + "default": "3.13" + }, + + "services": { + "id": "#/properties/services", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/service" + } + }, + "additionalProperties": false + }, + + "networks": { + "id": "#/properties/networks", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/network" + } + } + }, + + "volumes": { + "id": "#/properties/volumes", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/volume" + } + }, + "additionalProperties": false + }, + + "secrets": { + "id": "#/properties/secrets", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/secret" + } + }, + "additionalProperties": false + }, + + "configs": { + "id": "#/properties/configs", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/config" + } + }, + "additionalProperties": false + } + }, + + "patternProperties": {"^x-": {}}, + "additionalProperties": false, + + "definitions": { + + "service": { + "id": "#/definitions/service", + "type": "object", + + "properties": { + "deploy": {"$ref": "#/definitions/deployment"}, + "build": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "context": {"type": "string"}, + "dockerfile": {"type": "string"}, + "args": {"$ref": "#/definitions/list_or_dict"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "cache_from": {"$ref": "#/definitions/list_of_strings"}, + "network": {"type": "string"}, + "target": {"type": "string"}, + "shm_size": {"type": ["integer", "string"]}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": true + } + ] + }, + "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cgroupns_mode": {"type": "string"}, + "cgroup_parent": {"type": "string"}, + "command": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "configs": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "container_name": {"type": "string"}, + "credential_spec": { + "type": "object", + "properties": { + "config": {"type": "string"}, + "file": {"type": "string"}, + "registry": {"type": "string"} + }, + "additionalProperties": false + }, + "depends_on": {"$ref": "#/definitions/list_of_strings"}, + "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "dns": {"$ref": "#/definitions/string_or_list"}, + "dns_search": {"$ref": "#/definitions/string_or_list"}, + "domainname": {"type": "string"}, + "entrypoint": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "env_file": {"$ref": "#/definitions/string_or_list"}, + "environment": {"$ref": "#/definitions/list_or_dict"}, + + "expose": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "expose" + }, + "uniqueItems": true + }, + + "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, + "healthcheck": {"$ref": "#/definitions/healthcheck"}, + "hostname": {"type": "string"}, + "image": {"type": "string"}, + "init": {"type": "boolean"}, + "ipc": {"type": "string"}, + "isolation": {"type": "string"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + + "logging": { + "type": "object", + + "properties": { + "driver": {"type": "string"}, + "options": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number", "null"]} + } + } + }, + "additionalProperties": false + }, + + "mac_address": {"type": "string"}, + "network_mode": {"type": "string"}, + + "networks": { + "oneOf": [ + {"$ref": "#/definitions/list_of_strings"}, + { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "oneOf": [ + { + "type": "object", + "properties": { + "aliases": {"$ref": "#/definitions/list_of_strings"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": { "type": ["string", "number"] } + } + }, + "ipv4_address": {"type": "string"}, + "ipv6_address": {"type": "string"} + }, + "additionalProperties": false + }, + {"type": "null"} + ] + } + }, + "additionalProperties": false + } + ] + }, + "pid": {"type": ["string", "null"]}, + + "ports": { + "type": "array", + "items": { + "oneOf": [ + {"type": "number", "format": "ports"}, + {"type": "string", "format": "ports"}, + { + "type": "object", + "properties": { + "mode": {"type": "string"}, + "target": {"type": "integer"}, + "published": {"type": "integer"}, + "protocol": {"type": "string"} + }, + "additionalProperties": false + } + ] + }, + "uniqueItems": true + }, + + "privileged": {"type": "boolean"}, + "read_only": {"type": "boolean"}, + "restart": {"type": "string"}, + "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "shm_size": {"type": ["number", "string"]}, + "secrets": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "sysctls": {"$ref": "#/definitions/list_or_dict"}, + "stdin_open": {"type": "boolean"}, + "stop_grace_period": {"type": "string", "format": "duration"}, + "stop_signal": {"type": "string"}, + "tmpfs": {"$ref": "#/definitions/string_or_list"}, + "tty": {"type": "boolean"}, + "ulimits": { + "type": "object", + "patternProperties": { + "^[a-z]+$": { + "oneOf": [ + {"type": "integer"}, + { + "type":"object", + "properties": { + "hard": {"type": "integer"}, + "soft": {"type": "integer"} + }, + "required": ["soft", "hard"], + "additionalProperties": false + } + ] + } + } + }, + "oom_score_adj": {"type": "integer"}, + "user": {"type": "string"}, + "userns_mode": {"type": "string"}, + "volumes": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "required": ["type"], + "properties": { + "type": {"type": "string"}, + "source": {"type": "string"}, + "target": {"type": "string"}, + "read_only": {"type": "boolean"}, + "consistency": {"type": "string"}, + "bind": { + "type": "object", + "properties": { + "propagation": {"type": "string"} + } + }, + "volume": { + "type": "object", + "properties": { + "nocopy": {"type": "boolean"} + } + }, + "tmpfs": { + "type": "object", + "properties": { + "size": { + "type": "integer", + "minimum": 0 + } + } + } + }, + "additionalProperties": false + } + ], + "uniqueItems": true + } + }, + "working_dir": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "healthcheck": { + "id": "#/definitions/healthcheck", + "type": "object", + "additionalProperties": false, + "properties": { + "disable": {"type": "boolean"}, + "interval": {"type": "string", "format": "duration"}, + "retries": {"type": "number"}, + "test": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "timeout": {"type": "string", "format": "duration"}, + "start_period": {"type": "string", "format": "duration"}, + "start_interval": {"type": "string", "format": "duration"} + } + }, + "deployment": { + "id": "#/definitions/deployment", + "type": ["object", "null"], + "properties": { + "mode": {"type": "string"}, + "endpoint_mode": {"type": "string"}, + "replicas": {"type": "integer"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "rollback_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "update_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "properties": { + "limits": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"}, + "pids": {"type": "integer"} + }, + "additionalProperties": false + }, + "reservations": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"}, + "generic_resources": {"$ref": "#/definitions/generic_resources"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "restart_policy": { + "type": "object", + "properties": { + "condition": {"type": "string"}, + "delay": {"type": "string", "format": "duration"}, + "max_attempts": {"type": "integer"}, + "window": {"type": "string", "format": "duration"} + }, + "additionalProperties": false + }, + "placement": { + "type": "object", + "properties": { + "constraints": {"type": "array", "items": {"type": "string"}}, + "preferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "spread": {"type": "string"} + }, + "additionalProperties": false + } + }, + "max_replicas_per_node": {"type": "integer"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + + "generic_resources": { + "id": "#/definitions/generic_resources", + "type": "array", + "items": { + "type": "object", + "properties": { + "discrete_resource_spec": { + "type": "object", + "properties": { + "kind": {"type": "string"}, + "value": {"type": "number"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + + "network": { + "id": "#/definitions/network", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "ipam": { + "type": "object", + "properties": { + "driver": {"type": "string"}, + "config": { + "type": "array", + "items": { + "type": "object", + "properties": { + "subnet": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "internal": {"type": "boolean"}, + "attachable": {"type": "boolean"}, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "volume": { + "id": "#/definitions/volume", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "x-cluster-spec": { + "type": "object", + "properties": { + "group": {"type": "string"}, + "access_mode": { + "type": "object", + "properties": { + "scope": {"type": "string"}, + "sharing": {"type": "string"}, + "block_volume": {"type": "object"}, + "mount_volume": { + "type": "object", + "properties": { + "fs_type": {"type": "string"}, + "mount_flags": {"type": "array", "items": {"type": "string"}} + } + } + } + }, + "accessibility_requirements": { + "type": "object", + "properties": { + "requisite": { + "type": "array", + "items": { + "type": "object", + "properties": { + "segments": {"$ref": "#/definitions/list_or_dict"} + } + } + }, + "preferred": { + "type": "array", + "items": { + "type": "object", + "properties": { + "segments": {"$ref": "#/definitions/list_or_dict"} + } + } + } + } + }, + "capacity_range": { + "type": "object", + "properties": { + "required_bytes": {"type": "string"}, + "limit_bytes": {"type": "string"} + } + }, + "availability": {"type": "string"} + } + } + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "secret": { + "id": "#/definitions/secret", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "template_driver": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "config": { + "id": "#/definitions/config", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "template_driver": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "string_or_list": { + "oneOf": [ + {"type": "string"}, + {"$ref": "#/definitions/list_of_strings"} + ] + }, + + "list_of_strings": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + + "list_or_dict": { + "oneOf": [ + { + "type": "object", + "patternProperties": { + ".+": { + "type": ["string", "number", "null"] + } + }, + "additionalProperties": false + }, + {"type": "array", "items": {"type": "string"}, "uniqueItems": true} + ] + }, + + "constraints": { + "service": { + "id": "#/definitions/constraints/service", + "anyOf": [ + {"required": ["build"]}, + {"required": ["image"]} + ], + "properties": { + "build": { + "required": ["context"] + } + } + } + } + } +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.2.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.2.json new file mode 100644 index 00000000..6e0e0e74 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.2.json @@ -0,0 +1,476 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "id": "config_schema_v3.2.json", + "type": "object", + "required": ["version"], + + "properties": { + "version": { + "type": "string" + }, + + "services": { + "id": "#/properties/services", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/service" + } + }, + "additionalProperties": false + }, + + "networks": { + "id": "#/properties/networks", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/network" + } + } + }, + + "volumes": { + "id": "#/properties/volumes", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/volume" + } + }, + "additionalProperties": false + }, + + "secrets": { + "id": "#/properties/secrets", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/secret" + } + }, + "additionalProperties": false + } + }, + + "additionalProperties": false, + + "definitions": { + + "service": { + "id": "#/definitions/service", + "type": "object", + + "properties": { + "deploy": {"$ref": "#/definitions/deployment"}, + "build": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "context": {"type": "string"}, + "dockerfile": {"type": "string"}, + "args": {"$ref": "#/definitions/list_or_dict"}, + "cache_from": {"$ref": "#/definitions/list_of_strings"} + }, + "additionalProperties": false + } + ] + }, + "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cgroup_parent": {"type": "string"}, + "command": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "container_name": {"type": "string"}, + "depends_on": {"$ref": "#/definitions/list_of_strings"}, + "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "dns": {"$ref": "#/definitions/string_or_list"}, + "dns_search": {"$ref": "#/definitions/string_or_list"}, + "domainname": {"type": "string"}, + "entrypoint": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "env_file": {"$ref": "#/definitions/string_or_list"}, + "environment": {"$ref": "#/definitions/list_or_dict"}, + + "expose": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "expose" + }, + "uniqueItems": true + }, + + "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, + "healthcheck": {"$ref": "#/definitions/healthcheck"}, + "hostname": {"type": "string"}, + "image": {"type": "string"}, + "ipc": {"type": "string"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + + "logging": { + "type": "object", + + "properties": { + "driver": {"type": "string"}, + "options": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number", "null"]} + } + } + }, + "additionalProperties": false + }, + + "mac_address": {"type": "string"}, + "network_mode": {"type": "string"}, + + "networks": { + "oneOf": [ + {"$ref": "#/definitions/list_of_strings"}, + { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "oneOf": [ + { + "type": "object", + "properties": { + "aliases": {"$ref": "#/definitions/list_of_strings"}, + "ipv4_address": {"type": "string"}, + "ipv6_address": {"type": "string"} + }, + "additionalProperties": false + }, + {"type": "null"} + ] + } + }, + "additionalProperties": false + } + ] + }, + "pid": {"type": ["string", "null"]}, + + "ports": { + "type": "array", + "items": { + "oneOf": [ + {"type": "number", "format": "ports"}, + {"type": "string", "format": "ports"}, + { + "type": "object", + "properties": { + "mode": {"type": "string"}, + "target": {"type": "integer"}, + "published": {"type": "integer"}, + "protocol": {"type": "string"} + }, + "additionalProperties": false + } + ] + }, + "uniqueItems": true + }, + + "privileged": {"type": "boolean"}, + "read_only": {"type": "boolean"}, + "restart": {"type": "string"}, + "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "shm_size": {"type": ["number", "string"]}, + "secrets": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "sysctls": {"$ref": "#/definitions/list_or_dict"}, + "stdin_open": {"type": "boolean"}, + "stop_grace_period": {"type": "string", "format": "duration"}, + "stop_signal": {"type": "string"}, + "tmpfs": {"$ref": "#/definitions/string_or_list"}, + "tty": {"type": "boolean"}, + "ulimits": { + "type": "object", + "patternProperties": { + "^[a-z]+$": { + "oneOf": [ + {"type": "integer"}, + { + "type":"object", + "properties": { + "hard": {"type": "integer"}, + "soft": {"type": "integer"} + }, + "required": ["soft", "hard"], + "additionalProperties": false + } + ] + } + } + }, + "user": {"type": "string"}, + "userns_mode": {"type": "string"}, + "volumes": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "required": ["type"], + "properties": { + "type": {"type": "string"}, + "source": {"type": "string"}, + "target": {"type": "string"}, + "read_only": {"type": "boolean"}, + "consistency": {"type": "string"}, + "bind": { + "type": "object", + "properties": { + "propagation": {"type": "string"} + } + }, + "volume": { + "type": "object", + "properties": { + "nocopy": {"type": "boolean"} + } + } + }, + "additionalProperties": false + } + ], + "uniqueItems": true + } + }, + "working_dir": {"type": "string"} + }, + "additionalProperties": false + }, + + "healthcheck": { + "id": "#/definitions/healthcheck", + "type": "object", + "additionalProperties": false, + "properties": { + "disable": {"type": "boolean"}, + "interval": {"type": "string"}, + "retries": {"type": "number"}, + "test": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "timeout": {"type": "string"} + } + }, + "deployment": { + "id": "#/definitions/deployment", + "type": ["object", "null"], + "properties": { + "mode": {"type": "string"}, + "endpoint_mode": {"type": "string"}, + "replicas": {"type": "integer"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "update_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"} + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "properties": { + "limits": {"$ref": "#/definitions/resource"}, + "reservations": {"$ref": "#/definitions/resource"} + }, + "additionalProperties": false + }, + "restart_policy": { + "type": "object", + "properties": { + "condition": {"type": "string"}, + "delay": {"type": "string", "format": "duration"}, + "max_attempts": {"type": "integer"}, + "window": {"type": "string", "format": "duration"} + }, + "additionalProperties": false + }, + "placement": { + "type": "object", + "properties": { + "constraints": {"type": "array", "items": {"type": "string"}} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + + "resource": { + "id": "#/definitions/resource", + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"} + }, + "additionalProperties": false + }, + + "network": { + "id": "#/definitions/network", + "type": ["object", "null"], + "properties": { + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "ipam": { + "type": "object", + "properties": { + "driver": {"type": "string"}, + "config": { + "type": "array", + "items": { + "type": "object", + "properties": { + "subnet": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "internal": {"type": "boolean"}, + "attachable": {"type": "boolean"}, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "volume": { + "id": "#/definitions/volume", + "type": ["object", "null"], + "properties": { + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "secret": { + "id": "#/definitions/secret", + "type": "object", + "properties": { + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "string_or_list": { + "oneOf": [ + {"type": "string"}, + {"$ref": "#/definitions/list_of_strings"} + ] + }, + + "list_of_strings": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + + "list_or_dict": { + "oneOf": [ + { + "type": "object", + "patternProperties": { + ".+": { + "type": ["string", "number", "null"] + } + }, + "additionalProperties": false + }, + {"type": "array", "items": {"type": "string"}, "uniqueItems": true} + ] + }, + + "constraints": { + "service": { + "id": "#/definitions/constraints/service", + "anyOf": [ + {"required": ["build"]}, + {"required": ["image"]} + ], + "properties": { + "build": { + "required": ["context"] + } + } + } + } + } +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.3.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.3.json new file mode 100644 index 00000000..13a58044 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.3.json @@ -0,0 +1,540 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "id": "config_schema_v3.3.json", + "type": "object", + "required": ["version"], + + "properties": { + "version": { + "type": "string" + }, + + "services": { + "id": "#/properties/services", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/service" + } + }, + "additionalProperties": false + }, + + "networks": { + "id": "#/properties/networks", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/network" + } + } + }, + + "volumes": { + "id": "#/properties/volumes", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/volume" + } + }, + "additionalProperties": false + }, + + "secrets": { + "id": "#/properties/secrets", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/secret" + } + }, + "additionalProperties": false + }, + + "configs": { + "id": "#/properties/configs", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/config" + } + }, + "additionalProperties": false + } + }, + + "additionalProperties": false, + + "definitions": { + + "service": { + "id": "#/definitions/service", + "type": "object", + + "properties": { + "deploy": {"$ref": "#/definitions/deployment"}, + "build": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "context": {"type": "string"}, + "dockerfile": {"type": "string"}, + "args": {"$ref": "#/definitions/list_or_dict"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "cache_from": {"$ref": "#/definitions/list_of_strings"} + }, + "additionalProperties": false + } + ] + }, + "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cgroup_parent": {"type": "string"}, + "command": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "configs": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "container_name": {"type": "string"}, + "credential_spec": { + "type": "object", + "properties": { + "file": {"type": "string"}, + "registry": {"type": "string"} + }, + "additionalProperties": false + }, + "depends_on": {"$ref": "#/definitions/list_of_strings"}, + "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "dns": {"$ref": "#/definitions/string_or_list"}, + "dns_search": {"$ref": "#/definitions/string_or_list"}, + "domainname": {"type": "string"}, + "entrypoint": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "env_file": {"$ref": "#/definitions/string_or_list"}, + "environment": {"$ref": "#/definitions/list_or_dict"}, + + "expose": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "expose" + }, + "uniqueItems": true + }, + + "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, + "healthcheck": {"$ref": "#/definitions/healthcheck"}, + "hostname": {"type": "string"}, + "image": {"type": "string"}, + "ipc": {"type": "string"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + + "logging": { + "type": "object", + + "properties": { + "driver": {"type": "string"}, + "options": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number", "null"]} + } + } + }, + "additionalProperties": false + }, + + "mac_address": {"type": "string"}, + "network_mode": {"type": "string"}, + + "networks": { + "oneOf": [ + {"$ref": "#/definitions/list_of_strings"}, + { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "oneOf": [ + { + "type": "object", + "properties": { + "aliases": {"$ref": "#/definitions/list_of_strings"}, + "ipv4_address": {"type": "string"}, + "ipv6_address": {"type": "string"} + }, + "additionalProperties": false + }, + {"type": "null"} + ] + } + }, + "additionalProperties": false + } + ] + }, + "pid": {"type": ["string", "null"]}, + + "ports": { + "type": "array", + "items": { + "oneOf": [ + {"type": "number", "format": "ports"}, + {"type": "string", "format": "ports"}, + { + "type": "object", + "properties": { + "mode": {"type": "string"}, + "target": {"type": "integer"}, + "published": {"type": "integer"}, + "protocol": {"type": "string"} + }, + "additionalProperties": false + } + ] + }, + "uniqueItems": true + }, + + "privileged": {"type": "boolean"}, + "read_only": {"type": "boolean"}, + "restart": {"type": "string"}, + "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "shm_size": {"type": ["number", "string"]}, + "secrets": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "sysctls": {"$ref": "#/definitions/list_or_dict"}, + "stdin_open": {"type": "boolean"}, + "stop_grace_period": {"type": "string", "format": "duration"}, + "stop_signal": {"type": "string"}, + "tmpfs": {"$ref": "#/definitions/string_or_list"}, + "tty": {"type": "boolean"}, + "ulimits": { + "type": "object", + "patternProperties": { + "^[a-z]+$": { + "oneOf": [ + {"type": "integer"}, + { + "type":"object", + "properties": { + "hard": {"type": "integer"}, + "soft": {"type": "integer"} + }, + "required": ["soft", "hard"], + "additionalProperties": false + } + ] + } + } + }, + "user": {"type": "string"}, + "userns_mode": {"type": "string"}, + "volumes": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "required": ["type"], + "properties": { + "type": {"type": "string"}, + "source": {"type": "string"}, + "target": {"type": "string"}, + "read_only": {"type": "boolean"}, + "consistency": {"type": "string"}, + "bind": { + "type": "object", + "properties": { + "propagation": {"type": "string"} + } + }, + "volume": { + "type": "object", + "properties": { + "nocopy": {"type": "boolean"} + } + } + }, + "additionalProperties": false + } + ], + "uniqueItems": true + } + }, + "working_dir": {"type": "string"} + }, + "additionalProperties": false + }, + + "healthcheck": { + "id": "#/definitions/healthcheck", + "type": "object", + "additionalProperties": false, + "properties": { + "disable": {"type": "boolean"}, + "interval": {"type": "string"}, + "retries": {"type": "number"}, + "test": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "timeout": {"type": "string"} + } + }, + "deployment": { + "id": "#/definitions/deployment", + "type": ["object", "null"], + "properties": { + "mode": {"type": "string"}, + "endpoint_mode": {"type": "string"}, + "replicas": {"type": "integer"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "update_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"} + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "properties": { + "limits": {"$ref": "#/definitions/resource"}, + "reservations": {"$ref": "#/definitions/resource"} + }, + "additionalProperties": false + }, + "restart_policy": { + "type": "object", + "properties": { + "condition": {"type": "string"}, + "delay": {"type": "string", "format": "duration"}, + "max_attempts": {"type": "integer"}, + "window": {"type": "string", "format": "duration"} + }, + "additionalProperties": false + }, + "placement": { + "type": "object", + "properties": { + "constraints": {"type": "array", "items": {"type": "string"}}, + "preferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "spread": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + + "resource": { + "id": "#/definitions/resource", + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"} + }, + "additionalProperties": false + }, + + "network": { + "id": "#/definitions/network", + "type": ["object", "null"], + "properties": { + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "ipam": { + "type": "object", + "properties": { + "driver": {"type": "string"}, + "config": { + "type": "array", + "items": { + "type": "object", + "properties": { + "subnet": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "internal": {"type": "boolean"}, + "attachable": {"type": "boolean"}, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "volume": { + "id": "#/definitions/volume", + "type": ["object", "null"], + "properties": { + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "secret": { + "id": "#/definitions/secret", + "type": "object", + "properties": { + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "config": { + "id": "#/definitions/config", + "type": "object", + "properties": { + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "string_or_list": { + "oneOf": [ + {"type": "string"}, + {"$ref": "#/definitions/list_of_strings"} + ] + }, + + "list_of_strings": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + + "list_or_dict": { + "oneOf": [ + { + "type": "object", + "patternProperties": { + ".+": { + "type": ["string", "number", "null"] + } + }, + "additionalProperties": false + }, + {"type": "array", "items": {"type": "string"}, "uniqueItems": true} + ] + }, + + "constraints": { + "service": { + "id": "#/definitions/constraints/service", + "anyOf": [ + {"required": ["build"]}, + {"required": ["image"]} + ], + "properties": { + "build": { + "required": ["context"] + } + } + } + } + } +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.4.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.4.json new file mode 100644 index 00000000..8660c98d --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.4.json @@ -0,0 +1,548 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "id": "config_schema_v3.4.json", + "type": "object", + "required": ["version"], + + "properties": { + "version": { + "type": "string" + }, + + "services": { + "id": "#/properties/services", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/service" + } + }, + "additionalProperties": false + }, + + "networks": { + "id": "#/properties/networks", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/network" + } + } + }, + + "volumes": { + "id": "#/properties/volumes", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/volume" + } + }, + "additionalProperties": false + }, + + "secrets": { + "id": "#/properties/secrets", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/secret" + } + }, + "additionalProperties": false + }, + + "configs": { + "id": "#/properties/configs", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/config" + } + }, + "additionalProperties": false + } + }, + + "patternProperties": {"^x-": {}}, + "additionalProperties": false, + + "definitions": { + + "service": { + "id": "#/definitions/service", + "type": "object", + + "properties": { + "deploy": {"$ref": "#/definitions/deployment"}, + "build": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "context": {"type": "string"}, + "dockerfile": {"type": "string"}, + "args": {"$ref": "#/definitions/list_or_dict"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "cache_from": {"$ref": "#/definitions/list_of_strings"}, + "network": {"type": "string"}, + "target": {"type": "string"} + }, + "additionalProperties": false + } + ] + }, + "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cgroup_parent": {"type": "string"}, + "command": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "configs": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "container_name": {"type": "string"}, + "credential_spec": { + "type": "object", + "properties": { + "file": {"type": "string"}, + "registry": {"type": "string"} + }, + "additionalProperties": false + }, + "depends_on": {"$ref": "#/definitions/list_of_strings"}, + "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "dns": {"$ref": "#/definitions/string_or_list"}, + "dns_search": {"$ref": "#/definitions/string_or_list"}, + "domainname": {"type": "string"}, + "entrypoint": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "env_file": {"$ref": "#/definitions/string_or_list"}, + "environment": {"$ref": "#/definitions/list_or_dict"}, + + "expose": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "expose" + }, + "uniqueItems": true + }, + + "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, + "healthcheck": {"$ref": "#/definitions/healthcheck"}, + "hostname": {"type": "string"}, + "image": {"type": "string"}, + "ipc": {"type": "string"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + + "logging": { + "type": "object", + + "properties": { + "driver": {"type": "string"}, + "options": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number", "null"]} + } + } + }, + "additionalProperties": false + }, + + "mac_address": {"type": "string"}, + "network_mode": {"type": "string"}, + + "networks": { + "oneOf": [ + {"$ref": "#/definitions/list_of_strings"}, + { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "oneOf": [ + { + "type": "object", + "properties": { + "aliases": {"$ref": "#/definitions/list_of_strings"}, + "ipv4_address": {"type": "string"}, + "ipv6_address": {"type": "string"} + }, + "additionalProperties": false + }, + {"type": "null"} + ] + } + }, + "additionalProperties": false + } + ] + }, + "pid": {"type": ["string", "null"]}, + + "ports": { + "type": "array", + "items": { + "oneOf": [ + {"type": "number", "format": "ports"}, + {"type": "string", "format": "ports"}, + { + "type": "object", + "properties": { + "mode": {"type": "string"}, + "target": {"type": "integer"}, + "published": {"type": "integer"}, + "protocol": {"type": "string"} + }, + "additionalProperties": false + } + ] + }, + "uniqueItems": true + }, + + "privileged": {"type": "boolean"}, + "read_only": {"type": "boolean"}, + "restart": {"type": "string"}, + "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "shm_size": {"type": ["number", "string"]}, + "secrets": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "sysctls": {"$ref": "#/definitions/list_or_dict"}, + "stdin_open": {"type": "boolean"}, + "stop_grace_period": {"type": "string", "format": "duration"}, + "stop_signal": {"type": "string"}, + "tmpfs": {"$ref": "#/definitions/string_or_list"}, + "tty": {"type": "boolean"}, + "ulimits": { + "type": "object", + "patternProperties": { + "^[a-z]+$": { + "oneOf": [ + {"type": "integer"}, + { + "type":"object", + "properties": { + "hard": {"type": "integer"}, + "soft": {"type": "integer"} + }, + "required": ["soft", "hard"], + "additionalProperties": false + } + ] + } + } + }, + "user": {"type": "string"}, + "userns_mode": {"type": "string"}, + "volumes": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "required": ["type"], + "properties": { + "type": {"type": "string"}, + "source": {"type": "string"}, + "target": {"type": "string"}, + "read_only": {"type": "boolean"}, + "consistency": {"type": "string"}, + "bind": { + "type": "object", + "properties": { + "propagation": {"type": "string"} + } + }, + "volume": { + "type": "object", + "properties": { + "nocopy": {"type": "boolean"} + } + } + }, + "additionalProperties": false + } + ], + "uniqueItems": true + } + }, + "working_dir": {"type": "string"} + }, + "additionalProperties": false + }, + + "healthcheck": { + "id": "#/definitions/healthcheck", + "type": "object", + "additionalProperties": false, + "properties": { + "disable": {"type": "boolean"}, + "interval": {"type": "string", "format": "duration"}, + "retries": {"type": "number"}, + "test": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "timeout": {"type": "string", "format": "duration"}, + "start_period": {"type": "string", "format": "duration"} + } + }, + "deployment": { + "id": "#/definitions/deployment", + "type": ["object", "null"], + "properties": { + "mode": {"type": "string"}, + "endpoint_mode": {"type": "string"}, + "replicas": {"type": "integer"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "update_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "properties": { + "limits": {"$ref": "#/definitions/resource"}, + "reservations": {"$ref": "#/definitions/resource"} + }, + "additionalProperties": false + }, + "restart_policy": { + "type": "object", + "properties": { + "condition": {"type": "string"}, + "delay": {"type": "string", "format": "duration"}, + "max_attempts": {"type": "integer"}, + "window": {"type": "string", "format": "duration"} + }, + "additionalProperties": false + }, + "placement": { + "type": "object", + "properties": { + "constraints": {"type": "array", "items": {"type": "string"}}, + "preferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "spread": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + + "resource": { + "id": "#/definitions/resource", + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"} + }, + "additionalProperties": false + }, + + "network": { + "id": "#/definitions/network", + "type": ["object", "null"], + "properties": { + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "ipam": { + "type": "object", + "properties": { + "driver": {"type": "string"}, + "config": { + "type": "array", + "items": { + "type": "object", + "properties": { + "subnet": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "internal": {"type": "boolean"}, + "attachable": {"type": "boolean"}, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "volume": { + "id": "#/definitions/volume", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "secret": { + "id": "#/definitions/secret", + "type": "object", + "properties": { + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "config": { + "id": "#/definitions/config", + "type": "object", + "properties": { + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "string_or_list": { + "oneOf": [ + {"type": "string"}, + {"$ref": "#/definitions/list_of_strings"} + ] + }, + + "list_of_strings": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + + "list_or_dict": { + "oneOf": [ + { + "type": "object", + "patternProperties": { + ".+": { + "type": ["string", "number", "null"] + } + }, + "additionalProperties": false + }, + {"type": "array", "items": {"type": "string"}, "uniqueItems": true} + ] + }, + + "constraints": { + "service": { + "id": "#/definitions/constraints/service", + "anyOf": [ + {"required": ["build"]}, + {"required": ["image"]} + ], + "properties": { + "build": { + "required": ["context"] + } + } + } + } + } +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.5.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.5.json new file mode 100644 index 00000000..bf9c56c0 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.5.json @@ -0,0 +1,577 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "id": "config_schema_v3.5.json", + "type": "object", + "required": ["version"], + + "properties": { + "version": { + "type": "string" + }, + + "services": { + "id": "#/properties/services", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/service" + } + }, + "additionalProperties": false + }, + + "networks": { + "id": "#/properties/networks", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/network" + } + } + }, + + "volumes": { + "id": "#/properties/volumes", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/volume" + } + }, + "additionalProperties": false + }, + + "secrets": { + "id": "#/properties/secrets", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/secret" + } + }, + "additionalProperties": false + }, + + "configs": { + "id": "#/properties/configs", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/config" + } + }, + "additionalProperties": false + } + }, + + "patternProperties": {"^x-": {}}, + "additionalProperties": false, + + "definitions": { + + "service": { + "id": "#/definitions/service", + "type": "object", + + "properties": { + "deploy": {"$ref": "#/definitions/deployment"}, + "build": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "context": {"type": "string"}, + "dockerfile": {"type": "string"}, + "args": {"$ref": "#/definitions/list_or_dict"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "cache_from": {"$ref": "#/definitions/list_of_strings"}, + "network": {"type": "string"}, + "target": {"type": "string"}, + "shm_size": {"type": ["integer", "string"]} + }, + "additionalProperties": false + } + ] + }, + "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cgroup_parent": {"type": "string"}, + "command": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "configs": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "container_name": {"type": "string"}, + "credential_spec": { + "type": "object", + "properties": { + "file": {"type": "string"}, + "registry": {"type": "string"} + }, + "additionalProperties": false + }, + "depends_on": {"$ref": "#/definitions/list_of_strings"}, + "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "dns": {"$ref": "#/definitions/string_or_list"}, + "dns_search": {"$ref": "#/definitions/string_or_list"}, + "domainname": {"type": "string"}, + "entrypoint": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "env_file": {"$ref": "#/definitions/string_or_list"}, + "environment": {"$ref": "#/definitions/list_or_dict"}, + + "expose": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "expose" + }, + "uniqueItems": true + }, + + "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, + "healthcheck": {"$ref": "#/definitions/healthcheck"}, + "hostname": {"type": "string"}, + "image": {"type": "string"}, + "ipc": {"type": "string"}, + "isolation": {"type": "string"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + + "logging": { + "type": "object", + + "properties": { + "driver": {"type": "string"}, + "options": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number", "null"]} + } + } + }, + "additionalProperties": false + }, + + "mac_address": {"type": "string"}, + "network_mode": {"type": "string"}, + + "networks": { + "oneOf": [ + {"$ref": "#/definitions/list_of_strings"}, + { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "oneOf": [ + { + "type": "object", + "properties": { + "aliases": {"$ref": "#/definitions/list_of_strings"}, + "ipv4_address": {"type": "string"}, + "ipv6_address": {"type": "string"} + }, + "additionalProperties": false + }, + {"type": "null"} + ] + } + }, + "additionalProperties": false + } + ] + }, + "pid": {"type": ["string", "null"]}, + + "ports": { + "type": "array", + "items": { + "oneOf": [ + {"type": "number", "format": "ports"}, + {"type": "string", "format": "ports"}, + { + "type": "object", + "properties": { + "mode": {"type": "string"}, + "target": {"type": "integer"}, + "published": {"type": "integer"}, + "protocol": {"type": "string"} + }, + "additionalProperties": false + } + ] + }, + "uniqueItems": true + }, + + "privileged": {"type": "boolean"}, + "read_only": {"type": "boolean"}, + "restart": {"type": "string"}, + "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "shm_size": {"type": ["number", "string"]}, + "secrets": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "sysctls": {"$ref": "#/definitions/list_or_dict"}, + "stdin_open": {"type": "boolean"}, + "stop_grace_period": {"type": "string", "format": "duration"}, + "stop_signal": {"type": "string"}, + "tmpfs": {"$ref": "#/definitions/string_or_list"}, + "tty": {"type": "boolean"}, + "ulimits": { + "type": "object", + "patternProperties": { + "^[a-z]+$": { + "oneOf": [ + {"type": "integer"}, + { + "type":"object", + "properties": { + "hard": {"type": "integer"}, + "soft": {"type": "integer"} + }, + "required": ["soft", "hard"], + "additionalProperties": false + } + ] + } + } + }, + "user": {"type": "string"}, + "userns_mode": {"type": "string"}, + "volumes": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "required": ["type"], + "properties": { + "type": {"type": "string"}, + "source": {"type": "string"}, + "target": {"type": "string"}, + "read_only": {"type": "boolean"}, + "consistency": {"type": "string"}, + "bind": { + "type": "object", + "properties": { + "propagation": {"type": "string"} + } + }, + "volume": { + "type": "object", + "properties": { + "nocopy": {"type": "boolean"} + } + } + }, + "additionalProperties": false + } + ], + "uniqueItems": true + } + }, + "working_dir": {"type": "string"} + }, + "additionalProperties": false + }, + + "healthcheck": { + "id": "#/definitions/healthcheck", + "type": "object", + "additionalProperties": false, + "properties": { + "disable": {"type": "boolean"}, + "interval": {"type": "string", "format": "duration"}, + "retries": {"type": "number"}, + "test": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "timeout": {"type": "string", "format": "duration"}, + "start_period": {"type": "string", "format": "duration"} + } + }, + "deployment": { + "id": "#/definitions/deployment", + "type": ["object", "null"], + "properties": { + "mode": {"type": "string"}, + "endpoint_mode": {"type": "string"}, + "replicas": {"type": "integer"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "update_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "properties": { + "limits": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"} + }, + "additionalProperties": false + }, + "reservations": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"}, + "generic_resources": {"$ref": "#/definitions/generic_resources"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "restart_policy": { + "type": "object", + "properties": { + "condition": {"type": "string"}, + "delay": {"type": "string", "format": "duration"}, + "max_attempts": {"type": "integer"}, + "window": {"type": "string", "format": "duration"} + }, + "additionalProperties": false + }, + "placement": { + "type": "object", + "properties": { + "constraints": {"type": "array", "items": {"type": "string"}}, + "preferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "spread": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + + "generic_resources": { + "id": "#/definitions/generic_resources", + "type": "array", + "items": { + "type": "object", + "properties": { + "discrete_resource_spec": { + "type": "object", + "properties": { + "kind": {"type": "string"}, + "value": {"type": "number"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + + "network": { + "id": "#/definitions/network", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "ipam": { + "type": "object", + "properties": { + "driver": {"type": "string"}, + "config": { + "type": "array", + "items": { + "type": "object", + "properties": { + "subnet": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "internal": {"type": "boolean"}, + "attachable": {"type": "boolean"}, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "volume": { + "id": "#/definitions/volume", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "secret": { + "id": "#/definitions/secret", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "config": { + "id": "#/definitions/config", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "string_or_list": { + "oneOf": [ + {"type": "string"}, + {"$ref": "#/definitions/list_of_strings"} + ] + }, + + "list_of_strings": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + + "list_or_dict": { + "oneOf": [ + { + "type": "object", + "patternProperties": { + ".+": { + "type": ["string", "number", "null"] + } + }, + "additionalProperties": false + }, + {"type": "array", "items": {"type": "string"}, "uniqueItems": true} + ] + }, + + "constraints": { + "service": { + "id": "#/definitions/constraints/service", + "anyOf": [ + {"required": ["build"]}, + {"required": ["image"]} + ], + "properties": { + "build": { + "required": ["context"] + } + } + } + } + } +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.6.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.6.json new file mode 100644 index 00000000..cd6a638c --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.6.json @@ -0,0 +1,586 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "id": "config_schema_v3.6.json", + "type": "object", + "required": ["version"], + + "properties": { + "version": { + "type": "string" + }, + + "services": { + "id": "#/properties/services", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/service" + } + }, + "additionalProperties": false + }, + + "networks": { + "id": "#/properties/networks", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/network" + } + } + }, + + "volumes": { + "id": "#/properties/volumes", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/volume" + } + }, + "additionalProperties": false + }, + + "secrets": { + "id": "#/properties/secrets", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/secret" + } + }, + "additionalProperties": false + }, + + "configs": { + "id": "#/properties/configs", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/config" + } + }, + "additionalProperties": false + } + }, + + "patternProperties": {"^x-": {}}, + "additionalProperties": false, + + "definitions": { + + "service": { + "id": "#/definitions/service", + "type": "object", + + "properties": { + "deploy": {"$ref": "#/definitions/deployment"}, + "build": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "context": {"type": "string"}, + "dockerfile": {"type": "string"}, + "args": {"$ref": "#/definitions/list_or_dict"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "cache_from": {"$ref": "#/definitions/list_of_strings"}, + "network": {"type": "string"}, + "target": {"type": "string"}, + "shm_size": {"type": ["integer", "string"]} + }, + "additionalProperties": false + } + ] + }, + "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cgroup_parent": {"type": "string"}, + "command": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "configs": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "container_name": {"type": "string"}, + "credential_spec": { + "type": "object", + "properties": { + "file": {"type": "string"}, + "registry": {"type": "string"} + }, + "additionalProperties": false + }, + "depends_on": {"$ref": "#/definitions/list_of_strings"}, + "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "dns": {"$ref": "#/definitions/string_or_list"}, + "dns_search": {"$ref": "#/definitions/string_or_list"}, + "domainname": {"type": "string"}, + "entrypoint": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "env_file": {"$ref": "#/definitions/string_or_list"}, + "environment": {"$ref": "#/definitions/list_or_dict"}, + + "expose": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "expose" + }, + "uniqueItems": true + }, + + "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, + "healthcheck": {"$ref": "#/definitions/healthcheck"}, + "hostname": {"type": "string"}, + "image": {"type": "string"}, + "ipc": {"type": "string"}, + "isolation": {"type": "string"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + + "logging": { + "type": "object", + + "properties": { + "driver": {"type": "string"}, + "options": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number", "null"]} + } + } + }, + "additionalProperties": false + }, + + "mac_address": {"type": "string"}, + "network_mode": {"type": "string"}, + + "networks": { + "oneOf": [ + {"$ref": "#/definitions/list_of_strings"}, + { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "oneOf": [ + { + "type": "object", + "properties": { + "aliases": {"$ref": "#/definitions/list_of_strings"}, + "ipv4_address": {"type": "string"}, + "ipv6_address": {"type": "string"} + }, + "additionalProperties": false + }, + {"type": "null"} + ] + } + }, + "additionalProperties": false + } + ] + }, + "pid": {"type": ["string", "null"]}, + + "ports": { + "type": "array", + "items": { + "oneOf": [ + {"type": "number", "format": "ports"}, + {"type": "string", "format": "ports"}, + { + "type": "object", + "properties": { + "mode": {"type": "string"}, + "target": {"type": "integer"}, + "published": {"type": "integer"}, + "protocol": {"type": "string"} + }, + "additionalProperties": false + } + ] + }, + "uniqueItems": true + }, + + "privileged": {"type": "boolean"}, + "read_only": {"type": "boolean"}, + "restart": {"type": "string"}, + "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "shm_size": {"type": ["number", "string"]}, + "secrets": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "sysctls": {"$ref": "#/definitions/list_or_dict"}, + "stdin_open": {"type": "boolean"}, + "stop_grace_period": {"type": "string", "format": "duration"}, + "stop_signal": {"type": "string"}, + "tmpfs": {"$ref": "#/definitions/string_or_list"}, + "tty": {"type": "boolean"}, + "ulimits": { + "type": "object", + "patternProperties": { + "^[a-z]+$": { + "oneOf": [ + {"type": "integer"}, + { + "type":"object", + "properties": { + "hard": {"type": "integer"}, + "soft": {"type": "integer"} + }, + "required": ["soft", "hard"], + "additionalProperties": false + } + ] + } + } + }, + "user": {"type": "string"}, + "userns_mode": {"type": "string"}, + "volumes": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "required": ["type"], + "properties": { + "type": {"type": "string"}, + "source": {"type": "string"}, + "target": {"type": "string"}, + "read_only": {"type": "boolean"}, + "consistency": {"type": "string"}, + "bind": { + "type": "object", + "properties": { + "propagation": {"type": "string"} + } + }, + "volume": { + "type": "object", + "properties": { + "nocopy": {"type": "boolean"} + } + }, + "tmpfs": { + "type": "object", + "properties": { + "size": { + "type": "integer", + "minimum": 0 + } + } + } + }, + "additionalProperties": false + } + ], + "uniqueItems": true + } + }, + "working_dir": {"type": "string"} + }, + "additionalProperties": false + }, + + "healthcheck": { + "id": "#/definitions/healthcheck", + "type": "object", + "additionalProperties": false, + "properties": { + "disable": {"type": "boolean"}, + "interval": {"type": "string", "format": "duration"}, + "retries": {"type": "number"}, + "test": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "timeout": {"type": "string", "format": "duration"}, + "start_period": {"type": "string", "format": "duration"} + } + }, + "deployment": { + "id": "#/definitions/deployment", + "type": ["object", "null"], + "properties": { + "mode": {"type": "string"}, + "endpoint_mode": {"type": "string"}, + "replicas": {"type": "integer"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "update_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "properties": { + "limits": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"} + }, + "additionalProperties": false + }, + "reservations": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"}, + "generic_resources": {"$ref": "#/definitions/generic_resources"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "restart_policy": { + "type": "object", + "properties": { + "condition": {"type": "string"}, + "delay": {"type": "string", "format": "duration"}, + "max_attempts": {"type": "integer"}, + "window": {"type": "string", "format": "duration"} + }, + "additionalProperties": false + }, + "placement": { + "type": "object", + "properties": { + "constraints": {"type": "array", "items": {"type": "string"}}, + "preferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "spread": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + + "generic_resources": { + "id": "#/definitions/generic_resources", + "type": "array", + "items": { + "type": "object", + "properties": { + "discrete_resource_spec": { + "type": "object", + "properties": { + "kind": {"type": "string"}, + "value": {"type": "number"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + + "network": { + "id": "#/definitions/network", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "ipam": { + "type": "object", + "properties": { + "driver": {"type": "string"}, + "config": { + "type": "array", + "items": { + "type": "object", + "properties": { + "subnet": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "internal": {"type": "boolean"}, + "attachable": {"type": "boolean"}, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "volume": { + "id": "#/definitions/volume", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "secret": { + "id": "#/definitions/secret", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "config": { + "id": "#/definitions/config", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + }, + + "string_or_list": { + "oneOf": [ + {"type": "string"}, + {"$ref": "#/definitions/list_of_strings"} + ] + }, + + "list_of_strings": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + + "list_or_dict": { + "oneOf": [ + { + "type": "object", + "patternProperties": { + ".+": { + "type": ["string", "number", "null"] + } + }, + "additionalProperties": false + }, + {"type": "array", "items": {"type": "string"}, "uniqueItems": true} + ] + }, + + "constraints": { + "service": { + "id": "#/definitions/constraints/service", + "anyOf": [ + {"required": ["build"]}, + {"required": ["image"]} + ], + "properties": { + "build": { + "required": ["context"] + } + } + } + } + } +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.7.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.7.json new file mode 100644 index 00000000..69d5c52f --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.7.json @@ -0,0 +1,606 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "id": "config_schema_v3.7.json", + "type": "object", + "required": ["version"], + + "properties": { + "version": { + "type": "string" + }, + + "services": { + "id": "#/properties/services", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/service" + } + }, + "additionalProperties": false + }, + + "networks": { + "id": "#/properties/networks", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/network" + } + } + }, + + "volumes": { + "id": "#/properties/volumes", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/volume" + } + }, + "additionalProperties": false + }, + + "secrets": { + "id": "#/properties/secrets", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/secret" + } + }, + "additionalProperties": false + }, + + "configs": { + "id": "#/properties/configs", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/config" + } + }, + "additionalProperties": false + } + }, + + "patternProperties": {"^x-": {}}, + "additionalProperties": false, + + "definitions": { + + "service": { + "id": "#/definitions/service", + "type": "object", + + "properties": { + "deploy": {"$ref": "#/definitions/deployment"}, + "build": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "context": {"type": "string"}, + "dockerfile": {"type": "string"}, + "args": {"$ref": "#/definitions/list_or_dict"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "cache_from": {"$ref": "#/definitions/list_of_strings"}, + "network": {"type": "string"}, + "target": {"type": "string"}, + "shm_size": {"type": ["integer", "string"]} + }, + "additionalProperties": false + } + ] + }, + "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cgroup_parent": {"type": "string"}, + "command": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "configs": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "container_name": {"type": "string"}, + "credential_spec": { + "type": "object", + "properties": { + "file": {"type": "string"}, + "registry": {"type": "string"} + }, + "additionalProperties": false + }, + "depends_on": {"$ref": "#/definitions/list_of_strings"}, + "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "dns": {"$ref": "#/definitions/string_or_list"}, + "dns_search": {"$ref": "#/definitions/string_or_list"}, + "domainname": {"type": "string"}, + "entrypoint": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "env_file": {"$ref": "#/definitions/string_or_list"}, + "environment": {"$ref": "#/definitions/list_or_dict"}, + + "expose": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "expose" + }, + "uniqueItems": true + }, + + "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, + "healthcheck": {"$ref": "#/definitions/healthcheck"}, + "hostname": {"type": "string"}, + "image": {"type": "string"}, + "init": {"type": "boolean"}, + "ipc": {"type": "string"}, + "isolation": {"type": "string"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + + "logging": { + "type": "object", + + "properties": { + "driver": {"type": "string"}, + "options": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number", "null"]} + } + } + }, + "additionalProperties": false + }, + + "mac_address": {"type": "string"}, + "network_mode": {"type": "string"}, + + "networks": { + "oneOf": [ + {"$ref": "#/definitions/list_of_strings"}, + { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "oneOf": [ + { + "type": "object", + "properties": { + "aliases": {"$ref": "#/definitions/list_of_strings"}, + "ipv4_address": {"type": "string"}, + "ipv6_address": {"type": "string"} + }, + "additionalProperties": false + }, + {"type": "null"} + ] + } + }, + "additionalProperties": false + } + ] + }, + "pid": {"type": ["string", "null"]}, + + "ports": { + "type": "array", + "items": { + "oneOf": [ + {"type": "number", "format": "ports"}, + {"type": "string", "format": "ports"}, + { + "type": "object", + "properties": { + "mode": {"type": "string"}, + "target": {"type": "integer"}, + "published": {"type": "integer"}, + "protocol": {"type": "string"} + }, + "additionalProperties": false + } + ] + }, + "uniqueItems": true + }, + + "privileged": {"type": "boolean"}, + "read_only": {"type": "boolean"}, + "restart": {"type": "string"}, + "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "shm_size": {"type": ["number", "string"]}, + "secrets": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "sysctls": {"$ref": "#/definitions/list_or_dict"}, + "stdin_open": {"type": "boolean"}, + "stop_grace_period": {"type": "string", "format": "duration"}, + "stop_signal": {"type": "string"}, + "tmpfs": {"$ref": "#/definitions/string_or_list"}, + "tty": {"type": "boolean"}, + "ulimits": { + "type": "object", + "patternProperties": { + "^[a-z]+$": { + "oneOf": [ + {"type": "integer"}, + { + "type":"object", + "properties": { + "hard": {"type": "integer"}, + "soft": {"type": "integer"} + }, + "required": ["soft", "hard"], + "additionalProperties": false + } + ] + } + } + }, + "user": {"type": "string"}, + "userns_mode": {"type": "string"}, + "volumes": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "required": ["type"], + "properties": { + "type": {"type": "string"}, + "source": {"type": "string"}, + "target": {"type": "string"}, + "read_only": {"type": "boolean"}, + "consistency": {"type": "string"}, + "bind": { + "type": "object", + "properties": { + "propagation": {"type": "string"} + } + }, + "volume": { + "type": "object", + "properties": { + "nocopy": {"type": "boolean"} + } + }, + "tmpfs": { + "type": "object", + "properties": { + "size": { + "type": "integer", + "minimum": 0 + } + } + } + }, + "additionalProperties": false + } + ], + "uniqueItems": true + } + }, + "working_dir": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "healthcheck": { + "id": "#/definitions/healthcheck", + "type": "object", + "additionalProperties": false, + "properties": { + "disable": {"type": "boolean"}, + "interval": {"type": "string", "format": "duration"}, + "retries": {"type": "number"}, + "test": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "timeout": {"type": "string", "format": "duration"}, + "start_period": {"type": "string", "format": "duration"} + } + }, + "deployment": { + "id": "#/definitions/deployment", + "type": ["object", "null"], + "properties": { + "mode": {"type": "string"}, + "endpoint_mode": {"type": "string"}, + "replicas": {"type": "integer"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "rollback_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "update_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "properties": { + "limits": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"} + }, + "additionalProperties": false + }, + "reservations": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"}, + "generic_resources": {"$ref": "#/definitions/generic_resources"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "restart_policy": { + "type": "object", + "properties": { + "condition": {"type": "string"}, + "delay": {"type": "string", "format": "duration"}, + "max_attempts": {"type": "integer"}, + "window": {"type": "string", "format": "duration"} + }, + "additionalProperties": false + }, + "placement": { + "type": "object", + "properties": { + "constraints": {"type": "array", "items": {"type": "string"}}, + "preferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "spread": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + + "generic_resources": { + "id": "#/definitions/generic_resources", + "type": "array", + "items": { + "type": "object", + "properties": { + "discrete_resource_spec": { + "type": "object", + "properties": { + "kind": {"type": "string"}, + "value": {"type": "number"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + + "network": { + "id": "#/definitions/network", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "ipam": { + "type": "object", + "properties": { + "driver": {"type": "string"}, + "config": { + "type": "array", + "items": { + "type": "object", + "properties": { + "subnet": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "internal": {"type": "boolean"}, + "attachable": {"type": "boolean"}, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "volume": { + "id": "#/definitions/volume", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "secret": { + "id": "#/definitions/secret", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "config": { + "id": "#/definitions/config", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "string_or_list": { + "oneOf": [ + {"type": "string"}, + {"$ref": "#/definitions/list_of_strings"} + ] + }, + + "list_of_strings": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + + "list_or_dict": { + "oneOf": [ + { + "type": "object", + "patternProperties": { + ".+": { + "type": ["string", "number", "null"] + } + }, + "additionalProperties": false + }, + {"type": "array", "items": {"type": "string"}, "uniqueItems": true} + ] + }, + + "constraints": { + "service": { + "id": "#/definitions/constraints/service", + "anyOf": [ + {"required": ["build"]}, + {"required": ["image"]} + ], + "properties": { + "build": { + "required": ["context"] + } + } + } + } + } +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.8.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.8.json new file mode 100644 index 00000000..059c0bcf --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.8.json @@ -0,0 +1,617 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "id": "config_schema_v3.8.json", + "type": "object", + "required": ["version"], + + "properties": { + "version": { + "type": "string" + }, + + "services": { + "id": "#/properties/services", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/service" + } + }, + "additionalProperties": false + }, + + "networks": { + "id": "#/properties/networks", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/network" + } + } + }, + + "volumes": { + "id": "#/properties/volumes", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/volume" + } + }, + "additionalProperties": false + }, + + "secrets": { + "id": "#/properties/secrets", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/secret" + } + }, + "additionalProperties": false + }, + + "configs": { + "id": "#/properties/configs", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/config" + } + }, + "additionalProperties": false + } + }, + + "patternProperties": {"^x-": {}}, + "additionalProperties": false, + + "definitions": { + + "service": { + "id": "#/definitions/service", + "type": "object", + + "properties": { + "deploy": {"$ref": "#/definitions/deployment"}, + "build": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "context": {"type": "string"}, + "dockerfile": {"type": "string"}, + "args": {"$ref": "#/definitions/list_or_dict"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "cache_from": {"$ref": "#/definitions/list_of_strings"}, + "network": {"type": "string"}, + "target": {"type": "string"}, + "shm_size": {"type": ["integer", "string"]} + }, + "additionalProperties": false + } + ] + }, + "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cgroup_parent": {"type": "string"}, + "command": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "configs": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "container_name": {"type": "string"}, + "credential_spec": { + "type": "object", + "properties": { + "config": {"type": "string"}, + "file": {"type": "string"}, + "registry": {"type": "string"} + }, + "additionalProperties": false + }, + "depends_on": {"$ref": "#/definitions/list_of_strings"}, + "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "dns": {"$ref": "#/definitions/string_or_list"}, + "dns_search": {"$ref": "#/definitions/string_or_list"}, + "domainname": {"type": "string"}, + "entrypoint": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "env_file": {"$ref": "#/definitions/string_or_list"}, + "environment": {"$ref": "#/definitions/list_or_dict"}, + + "expose": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "expose" + }, + "uniqueItems": true + }, + + "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, + "healthcheck": {"$ref": "#/definitions/healthcheck"}, + "hostname": {"type": "string"}, + "image": {"type": "string"}, + "init": {"type": "boolean"}, + "ipc": {"type": "string"}, + "isolation": {"type": "string"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + + "logging": { + "type": "object", + + "properties": { + "driver": {"type": "string"}, + "options": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number", "null"]} + } + } + }, + "additionalProperties": false + }, + + "mac_address": {"type": "string"}, + "network_mode": {"type": "string"}, + + "networks": { + "oneOf": [ + {"$ref": "#/definitions/list_of_strings"}, + { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "oneOf": [ + { + "type": "object", + "properties": { + "aliases": {"$ref": "#/definitions/list_of_strings"}, + "ipv4_address": {"type": "string"}, + "ipv6_address": {"type": "string"} + }, + "additionalProperties": false + }, + {"type": "null"} + ] + } + }, + "additionalProperties": false + } + ] + }, + "pid": {"type": ["string", "null"]}, + + "ports": { + "type": "array", + "items": { + "oneOf": [ + {"type": "number", "format": "ports"}, + {"type": "string", "format": "ports"}, + { + "type": "object", + "properties": { + "mode": {"type": "string"}, + "target": {"type": "integer"}, + "published": {"type": "integer"}, + "protocol": {"type": "string"} + }, + "additionalProperties": false + } + ] + }, + "uniqueItems": true + }, + + "privileged": {"type": "boolean"}, + "read_only": {"type": "boolean"}, + "restart": {"type": "string"}, + "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "shm_size": {"type": ["number", "string"]}, + "secrets": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "sysctls": {"$ref": "#/definitions/list_or_dict"}, + "stdin_open": {"type": "boolean"}, + "stop_grace_period": {"type": "string", "format": "duration"}, + "stop_signal": {"type": "string"}, + "tmpfs": {"$ref": "#/definitions/string_or_list"}, + "tty": {"type": "boolean"}, + "ulimits": { + "type": "object", + "patternProperties": { + "^[a-z]+$": { + "oneOf": [ + {"type": "integer"}, + { + "type":"object", + "properties": { + "hard": {"type": "integer"}, + "soft": {"type": "integer"} + }, + "required": ["soft", "hard"], + "additionalProperties": false + } + ] + } + } + }, + "user": {"type": "string"}, + "userns_mode": {"type": "string"}, + "volumes": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "required": ["type"], + "properties": { + "type": {"type": "string"}, + "source": {"type": "string"}, + "target": {"type": "string"}, + "read_only": {"type": "boolean"}, + "consistency": {"type": "string"}, + "bind": { + "type": "object", + "properties": { + "propagation": {"type": "string"} + } + }, + "volume": { + "type": "object", + "properties": { + "nocopy": {"type": "boolean"} + } + }, + "tmpfs": { + "type": "object", + "properties": { + "size": { + "type": "integer", + "minimum": 0 + } + } + } + }, + "additionalProperties": false + } + ], + "uniqueItems": true + } + }, + "working_dir": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "healthcheck": { + "id": "#/definitions/healthcheck", + "type": "object", + "additionalProperties": false, + "properties": { + "disable": {"type": "boolean"}, + "interval": {"type": "string", "format": "duration"}, + "retries": {"type": "number"}, + "test": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "timeout": {"type": "string", "format": "duration"}, + "start_period": {"type": "string", "format": "duration"} + } + }, + "deployment": { + "id": "#/definitions/deployment", + "type": ["object", "null"], + "properties": { + "mode": {"type": "string"}, + "endpoint_mode": {"type": "string"}, + "replicas": {"type": "integer"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "rollback_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "update_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "properties": { + "limits": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"} + }, + "additionalProperties": false + }, + "reservations": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"}, + "generic_resources": {"$ref": "#/definitions/generic_resources"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "restart_policy": { + "type": "object", + "properties": { + "condition": {"type": "string"}, + "delay": {"type": "string", "format": "duration"}, + "max_attempts": {"type": "integer"}, + "window": {"type": "string", "format": "duration"} + }, + "additionalProperties": false + }, + "placement": { + "type": "object", + "properties": { + "constraints": {"type": "array", "items": {"type": "string"}}, + "preferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "spread": {"type": "string"} + }, + "additionalProperties": false + } + }, + "max_replicas_per_node": {"type": "integer"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + + "generic_resources": { + "id": "#/definitions/generic_resources", + "type": "array", + "items": { + "type": "object", + "properties": { + "discrete_resource_spec": { + "type": "object", + "properties": { + "kind": {"type": "string"}, + "value": {"type": "number"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + + "network": { + "id": "#/definitions/network", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "ipam": { + "type": "object", + "properties": { + "driver": {"type": "string"}, + "config": { + "type": "array", + "items": { + "type": "object", + "properties": { + "subnet": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "internal": {"type": "boolean"}, + "attachable": {"type": "boolean"}, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "volume": { + "id": "#/definitions/volume", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "secret": { + "id": "#/definitions/secret", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "template_driver": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "config": { + "id": "#/definitions/config", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "template_driver": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "string_or_list": { + "oneOf": [ + {"type": "string"}, + {"$ref": "#/definitions/list_of_strings"} + ] + }, + + "list_of_strings": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + + "list_or_dict": { + "oneOf": [ + { + "type": "object", + "patternProperties": { + ".+": { + "type": ["string", "number", "null"] + } + }, + "additionalProperties": false + }, + {"type": "array", "items": {"type": "string"}, "uniqueItems": true} + ] + }, + + "constraints": { + "service": { + "id": "#/definitions/constraints/service", + "anyOf": [ + {"required": ["build"]}, + {"required": ["image"]} + ], + "properties": { + "build": { + "required": ["context"] + } + } + } + } + } +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.9.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.9.json new file mode 100644 index 00000000..c6f63fda --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.9.json @@ -0,0 +1,620 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "id": "config_schema_v3.9.json", + "type": "object", + "required": ["version"], + + "properties": { + "version": { + "type": "string" + }, + + "services": { + "id": "#/properties/services", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/service" + } + }, + "additionalProperties": false + }, + + "networks": { + "id": "#/properties/networks", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/network" + } + } + }, + + "volumes": { + "id": "#/properties/volumes", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/volume" + } + }, + "additionalProperties": false + }, + + "secrets": { + "id": "#/properties/secrets", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/secret" + } + }, + "additionalProperties": false + }, + + "configs": { + "id": "#/properties/configs", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "$ref": "#/definitions/config" + } + }, + "additionalProperties": false + } + }, + + "patternProperties": {"^x-": {}}, + "additionalProperties": false, + + "definitions": { + + "service": { + "id": "#/definitions/service", + "type": "object", + + "properties": { + "deploy": {"$ref": "#/definitions/deployment"}, + "build": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "context": {"type": "string"}, + "dockerfile": {"type": "string"}, + "args": {"$ref": "#/definitions/list_or_dict"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "cache_from": {"$ref": "#/definitions/list_of_strings"}, + "network": {"type": "string"}, + "target": {"type": "string"}, + "shm_size": {"type": ["integer", "string"]}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"} + }, + "additionalProperties": false + } + ] + }, + "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "cgroupns_mode": {"type": "string"}, + "cgroup_parent": {"type": "string"}, + "command": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "configs": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "container_name": {"type": "string"}, + "credential_spec": { + "type": "object", + "properties": { + "config": {"type": "string"}, + "file": {"type": "string"}, + "registry": {"type": "string"} + }, + "additionalProperties": false + }, + "depends_on": {"$ref": "#/definitions/list_of_strings"}, + "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "dns": {"$ref": "#/definitions/string_or_list"}, + "dns_search": {"$ref": "#/definitions/string_or_list"}, + "domainname": {"type": "string"}, + "entrypoint": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "env_file": {"$ref": "#/definitions/string_or_list"}, + "environment": {"$ref": "#/definitions/list_or_dict"}, + + "expose": { + "type": "array", + "items": { + "type": ["string", "number"], + "format": "expose" + }, + "uniqueItems": true + }, + + "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, + "healthcheck": {"$ref": "#/definitions/healthcheck"}, + "hostname": {"type": "string"}, + "image": {"type": "string"}, + "init": {"type": "boolean"}, + "ipc": {"type": "string"}, + "isolation": {"type": "string"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + + "logging": { + "type": "object", + + "properties": { + "driver": {"type": "string"}, + "options": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number", "null"]} + } + } + }, + "additionalProperties": false + }, + + "mac_address": {"type": "string"}, + "network_mode": {"type": "string"}, + + "networks": { + "oneOf": [ + {"$ref": "#/definitions/list_of_strings"}, + { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9._-]+$": { + "oneOf": [ + { + "type": "object", + "properties": { + "aliases": {"$ref": "#/definitions/list_of_strings"}, + "ipv4_address": {"type": "string"}, + "ipv6_address": {"type": "string"} + }, + "additionalProperties": false + }, + {"type": "null"} + ] + } + }, + "additionalProperties": false + } + ] + }, + "pid": {"type": ["string", "null"]}, + + "ports": { + "type": "array", + "items": { + "oneOf": [ + {"type": "number", "format": "ports"}, + {"type": "string", "format": "ports"}, + { + "type": "object", + "properties": { + "mode": {"type": "string"}, + "target": {"type": "integer"}, + "published": {"type": "integer"}, + "protocol": {"type": "string"} + }, + "additionalProperties": false + } + ] + }, + "uniqueItems": true + }, + + "privileged": {"type": "boolean"}, + "read_only": {"type": "boolean"}, + "restart": {"type": "string"}, + "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + "shm_size": {"type": ["number", "string"]}, + "secrets": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "properties": { + "source": {"type": "string"}, + "target": {"type": "string"}, + "uid": {"type": "string"}, + "gid": {"type": "string"}, + "mode": {"type": "number"} + } + } + ] + } + }, + "sysctls": {"$ref": "#/definitions/list_or_dict"}, + "stdin_open": {"type": "boolean"}, + "stop_grace_period": {"type": "string", "format": "duration"}, + "stop_signal": {"type": "string"}, + "tmpfs": {"$ref": "#/definitions/string_or_list"}, + "tty": {"type": "boolean"}, + "ulimits": { + "type": "object", + "patternProperties": { + "^[a-z]+$": { + "oneOf": [ + {"type": "integer"}, + { + "type":"object", + "properties": { + "hard": {"type": "integer"}, + "soft": {"type": "integer"} + }, + "required": ["soft", "hard"], + "additionalProperties": false + } + ] + } + } + }, + "user": {"type": "string"}, + "userns_mode": {"type": "string"}, + "volumes": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "required": ["type"], + "properties": { + "type": {"type": "string"}, + "source": {"type": "string"}, + "target": {"type": "string"}, + "read_only": {"type": "boolean"}, + "consistency": {"type": "string"}, + "bind": { + "type": "object", + "properties": { + "propagation": {"type": "string"} + } + }, + "volume": { + "type": "object", + "properties": { + "nocopy": {"type": "boolean"} + } + }, + "tmpfs": { + "type": "object", + "properties": { + "size": { + "type": "integer", + "minimum": 0 + } + } + } + }, + "additionalProperties": false + } + ], + "uniqueItems": true + } + }, + "working_dir": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "healthcheck": { + "id": "#/definitions/healthcheck", + "type": "object", + "additionalProperties": false, + "properties": { + "disable": {"type": "boolean"}, + "interval": {"type": "string", "format": "duration"}, + "retries": {"type": "number"}, + "test": { + "oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ] + }, + "timeout": {"type": "string", "format": "duration"}, + "start_period": {"type": "string", "format": "duration"} + } + }, + "deployment": { + "id": "#/definitions/deployment", + "type": ["object", "null"], + "properties": { + "mode": {"type": "string"}, + "endpoint_mode": {"type": "string"}, + "replicas": {"type": "integer"}, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "rollback_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "update_config": { + "type": "object", + "properties": { + "parallelism": {"type": "integer"}, + "delay": {"type": "string", "format": "duration"}, + "failure_action": {"type": "string"}, + "monitor": {"type": "string", "format": "duration"}, + "max_failure_ratio": {"type": "number"}, + "order": {"type": "string", "enum": [ + "start-first", "stop-first" + ]} + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "properties": { + "limits": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"}, + "pids": {"type": "integer"} + }, + "additionalProperties": false + }, + "reservations": { + "type": "object", + "properties": { + "cpus": {"type": "string"}, + "memory": {"type": "string"}, + "generic_resources": {"$ref": "#/definitions/generic_resources"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "restart_policy": { + "type": "object", + "properties": { + "condition": {"type": "string"}, + "delay": {"type": "string", "format": "duration"}, + "max_attempts": {"type": "integer"}, + "window": {"type": "string", "format": "duration"} + }, + "additionalProperties": false + }, + "placement": { + "type": "object", + "properties": { + "constraints": {"type": "array", "items": {"type": "string"}}, + "preferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "spread": {"type": "string"} + }, + "additionalProperties": false + } + }, + "max_replicas_per_node": {"type": "integer"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + + "generic_resources": { + "id": "#/definitions/generic_resources", + "type": "array", + "items": { + "type": "object", + "properties": { + "discrete_resource_spec": { + "type": "object", + "properties": { + "kind": {"type": "string"}, + "value": {"type": "number"} + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + + "network": { + "id": "#/definitions/network", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "ipam": { + "type": "object", + "properties": { + "driver": {"type": "string"}, + "config": { + "type": "array", + "items": { + "type": "object", + "properties": { + "subnet": {"type": "string"} + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "internal": {"type": "boolean"}, + "attachable": {"type": "boolean"}, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "volume": { + "id": "#/definitions/volume", + "type": ["object", "null"], + "properties": { + "name": {"type": "string"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + }, + "additionalProperties": false + }, + "labels": {"$ref": "#/definitions/list_or_dict"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "secret": { + "id": "#/definitions/secret", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "driver": {"type": "string"}, + "driver_opts": { + "type": "object", + "patternProperties": { + "^.+$": {"type": ["string", "number"]} + } + }, + "template_driver": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "config": { + "id": "#/definitions/config", + "type": "object", + "properties": { + "name": {"type": "string"}, + "file": {"type": "string"}, + "external": { + "type": ["boolean", "object"], + "properties": { + "name": {"type": "string"} + } + }, + "labels": {"$ref": "#/definitions/list_or_dict"}, + "template_driver": {"type": "string"} + }, + "patternProperties": {"^x-": {}}, + "additionalProperties": false + }, + + "string_or_list": { + "oneOf": [ + {"type": "string"}, + {"$ref": "#/definitions/list_of_strings"} + ] + }, + + "list_of_strings": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + + "list_or_dict": { + "oneOf": [ + { + "type": "object", + "patternProperties": { + ".+": { + "type": ["string", "number", "null"] + } + }, + "additionalProperties": false + }, + {"type": "array", "items": {"type": "string"}, "uniqueItems": true} + ] + }, + + "constraints": { + "service": { + "id": "#/definitions/constraints/service", + "anyOf": [ + {"required": ["build"]}, + {"required": ["image"]} + ], + "properties": { + "build": { + "required": ["context"] + } + } + } + } + } +} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/schema.go b/vendor/github.com/docker/cli/cli/compose/schema/schema.go new file mode 100644 index 00000000..2ef1245b --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/schema/schema.go @@ -0,0 +1,180 @@ +// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: +//go:build go1.22 + +package schema + +import ( + "embed" + "fmt" + "strings" + "time" + + "github.com/pkg/errors" + "github.com/xeipuuv/gojsonschema" +) + +const ( + defaultVersion = "3.13" + versionField = "version" +) + +type portsFormatChecker struct{} + +func (checker portsFormatChecker) IsFormat(_ any) bool { + // TODO: implement this + return true +} + +type durationFormatChecker struct{} + +func (checker durationFormatChecker) IsFormat(input any) bool { + value, ok := input.(string) + if !ok { + return false + } + _, err := time.ParseDuration(value) + return err == nil +} + +func init() { + gojsonschema.FormatCheckers.Add("expose", portsFormatChecker{}) + gojsonschema.FormatCheckers.Add("ports", portsFormatChecker{}) + gojsonschema.FormatCheckers.Add("duration", durationFormatChecker{}) +} + +// Version returns the version of the config, defaulting to the latest "3.x" +// version (3.13). If only the major version "3" is specified, it is used as +// version "3.x" and returns the default version (latest 3.x). +func Version(config map[string]any) string { + version, ok := config[versionField] + if !ok { + return defaultVersion + } + return normalizeVersion(fmt.Sprintf("%v", version)) +} + +func normalizeVersion(version string) string { + switch version { + case "", "3": + return defaultVersion + default: + return version + } +} + +//go:embed data/config_schema_v*.json +var schemas embed.FS + +// Validate uses the jsonschema to validate the configuration +func Validate(config map[string]any, version string) error { + version = normalizeVersion(version) + schemaData, err := schemas.ReadFile("data/config_schema_v" + version + ".json") + if err != nil { + return errors.Errorf("unsupported Compose file version: %s", version) + } + + schemaLoader := gojsonschema.NewStringLoader(string(schemaData)) + dataLoader := gojsonschema.NewGoLoader(config) + + result, err := gojsonschema.Validate(schemaLoader, dataLoader) + if err != nil { + return err + } + + if !result.Valid() { + return toError(result) + } + + return nil +} + +func toError(result *gojsonschema.Result) error { + err := getMostSpecificError(result.Errors()) + return err +} + +const ( + jsonschemaOneOf = "number_one_of" + jsonschemaAnyOf = "number_any_of" +) + +func getDescription(err validationError) string { + switch err.parent.Type() { + case "invalid_type": + if expectedType, ok := err.parent.Details()["expected"].(string); ok { + return "must be a " + humanReadableType(expectedType) + } + case jsonschemaOneOf, jsonschemaAnyOf: + if err.child == nil { + return err.parent.Description() + } + return err.child.Description() + } + return err.parent.Description() +} + +func humanReadableType(definition string) string { + if definition[0:1] == "[" { + allTypes := strings.Split(definition[1:len(definition)-1], ",") + for i, t := range allTypes { + allTypes[i] = humanReadableType(t) + } + return fmt.Sprintf( + "%s or %s", + strings.Join(allTypes[0:len(allTypes)-1], ", "), + allTypes[len(allTypes)-1], + ) + } + if definition == "object" { + return "mapping" + } + if definition == "array" { + return "list" + } + return definition +} + +type validationError struct { + parent gojsonschema.ResultError + child gojsonschema.ResultError +} + +func (err validationError) Error() string { + description := getDescription(err) + return fmt.Sprintf("%s %s", err.parent.Field(), description) +} + +func getMostSpecificError(errs []gojsonschema.ResultError) validationError { + mostSpecificError := 0 + for i, err := range errs { + if specificity(err) > specificity(errs[mostSpecificError]) { + mostSpecificError = i + continue + } + + if specificity(err) == specificity(errs[mostSpecificError]) { + // Invalid type errors win in a tie-breaker for most specific field name + if err.Type() == "invalid_type" && errs[mostSpecificError].Type() != "invalid_type" { + mostSpecificError = i + } + } + } + + if mostSpecificError+1 == len(errs) { + return validationError{parent: errs[mostSpecificError]} + } + + switch errs[mostSpecificError].Type() { + case "number_one_of", "number_any_of": + return validationError{ + parent: errs[mostSpecificError], + child: errs[mostSpecificError+1], + } + default: + return validationError{parent: errs[mostSpecificError]} + } +} + +func specificity(err gojsonschema.ResultError) int { + return len(strings.Split(err.Field(), ".")) +} diff --git a/vendor/github.com/docker/cli/cli/compose/template/template.go b/vendor/github.com/docker/cli/cli/compose/template/template.go new file mode 100644 index 00000000..1507c0ee --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/template/template.go @@ -0,0 +1,248 @@ +// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: +//go:build go1.22 + +package template + +import ( + "fmt" + "regexp" + "strings" +) + +const ( + delimiter = "\\$" + subst = "[_a-z][_a-z0-9]*(?::?[-?][^}]*)?" +) + +var defaultPattern = regexp.MustCompile(fmt.Sprintf( + "%s(?i:(?P%s)|(?P%s)|{(?P%s)}|(?P))", + delimiter, delimiter, subst, subst, +)) + +// DefaultSubstituteFuncs contains the default SubstituteFunc used by the docker cli +var DefaultSubstituteFuncs = []SubstituteFunc{ + softDefault, + hardDefault, + requiredNonEmpty, + required, +} + +// InvalidTemplateError is returned when a variable template is not in a valid +// format +type InvalidTemplateError struct { + Template string +} + +func (e InvalidTemplateError) Error() string { + return fmt.Sprintf("Invalid template: %#v", e.Template) +} + +// Mapping is a user-supplied function which maps from variable names to values. +// Returns the value as a string and a bool indicating whether +// the value is present, to distinguish between an empty string +// and the absence of a value. +type Mapping func(string) (string, bool) + +// SubstituteFunc is a user-supplied function that apply substitution. +// Returns the value as a string, a bool indicating if the function could apply +// the substitution and an error. +type SubstituteFunc func(string, Mapping) (string, bool, error) + +// SubstituteWith substitutes variables in the string with their values. +// It accepts additional substitute function. +func SubstituteWith(template string, mapping Mapping, pattern *regexp.Regexp, subsFuncs ...SubstituteFunc) (string, error) { + var err error + result := pattern.ReplaceAllStringFunc(template, func(substring string) string { + matches := pattern.FindStringSubmatch(substring) + groups := matchGroups(matches, pattern) + if escaped := groups["escaped"]; escaped != "" { + return escaped + } + + substitution := groups["named"] + if substitution == "" { + substitution = groups["braced"] + } + + if substitution == "" { + err = &InvalidTemplateError{Template: template} + return "" + } + + for _, f := range subsFuncs { + var ( + value string + applied bool + ) + value, applied, err = f(substitution, mapping) + if err != nil { + return "" + } + if !applied { + continue + } + return value + } + + value, _ := mapping(substitution) + return value + }) + + return result, err +} + +// Substitute variables in the string with their values +func Substitute(template string, mapping Mapping) (string, error) { + return SubstituteWith(template, mapping, defaultPattern, DefaultSubstituteFuncs...) +} + +// ExtractVariables returns a map of all the variables defined in the specified +// composefile (dict representation) and their default value if any. +func ExtractVariables(configDict map[string]any, pattern *regexp.Regexp) map[string]string { + if pattern == nil { + pattern = defaultPattern + } + return recurseExtract(configDict, pattern) +} + +func recurseExtract(value any, pattern *regexp.Regexp) map[string]string { + m := map[string]string{} + + switch value := value.(type) { + case string: + if values, is := extractVariable(value, pattern); is { + for _, v := range values { + m[v.name] = v.value + } + } + case map[string]any: + for _, elem := range value { + submap := recurseExtract(elem, pattern) + for key, value := range submap { + m[key] = value + } + } + + case []any: + for _, elem := range value { + if values, is := extractVariable(elem, pattern); is { + for _, v := range values { + m[v.name] = v.value + } + } + } + } + + return m +} + +type extractedValue struct { + name string + value string +} + +func extractVariable(value any, pattern *regexp.Regexp) ([]extractedValue, bool) { + sValue, ok := value.(string) + if !ok { + return []extractedValue{}, false + } + matches := pattern.FindAllStringSubmatch(sValue, -1) + if len(matches) == 0 { + return []extractedValue{}, false + } + values := []extractedValue{} + for _, match := range matches { + groups := matchGroups(match, pattern) + if escaped := groups["escaped"]; escaped != "" { + continue + } + val := groups["named"] + if val == "" { + val = groups["braced"] + } + name := val + var defaultValue string + switch { + case strings.Contains(val, ":?"): + name, _ = partition(val, ":?") + case strings.Contains(val, "?"): + name, _ = partition(val, "?") + case strings.Contains(val, ":-"): + name, defaultValue = partition(val, ":-") + case strings.Contains(val, "-"): + name, defaultValue = partition(val, "-") + } + values = append(values, extractedValue{name: name, value: defaultValue}) + } + return values, len(values) > 0 +} + +// Soft default (fall back if unset or empty) +func softDefault(substitution string, mapping Mapping) (string, bool, error) { + sep := ":-" + if !strings.Contains(substitution, sep) { + return "", false, nil + } + name, defaultValue := partition(substitution, sep) + value, ok := mapping(name) + if !ok || value == "" { + return defaultValue, true, nil + } + return value, true, nil +} + +// Hard default (fall back if-and-only-if empty) +func hardDefault(substitution string, mapping Mapping) (string, bool, error) { + sep := "-" + if !strings.Contains(substitution, sep) { + return "", false, nil + } + name, defaultValue := partition(substitution, sep) + value, ok := mapping(name) + if !ok { + return defaultValue, true, nil + } + return value, true, nil +} + +func requiredNonEmpty(substitution string, mapping Mapping) (string, bool, error) { + return withRequired(substitution, mapping, ":?", func(v string) bool { return v != "" }) +} + +func required(substitution string, mapping Mapping) (string, bool, error) { + return withRequired(substitution, mapping, "?", func(_ string) bool { return true }) +} + +func withRequired(substitution string, mapping Mapping, sep string, valid func(string) bool) (string, bool, error) { + if !strings.Contains(substitution, sep) { + return "", false, nil + } + name, errorMessage := partition(substitution, sep) + value, ok := mapping(name) + if !ok || !valid(value) { + return "", true, &InvalidTemplateError{ + Template: fmt.Sprintf("required variable %s is missing a value: %s", name, errorMessage), + } + } + return value, true, nil +} + +func matchGroups(matches []string, pattern *regexp.Regexp) map[string]string { + groups := make(map[string]string) + for i, name := range pattern.SubexpNames()[1:] { + groups[name] = matches[i+1] + } + return groups +} + +// Split the string at the first occurrence of sep, and return the part before the separator, +// and the part after the separator. +// +// If the separator is not found, return the string itself, followed by an empty string. +func partition(s, sep string) (string, string) { + k, v, ok := strings.Cut(s, sep) + if !ok { + return s, "" + } + return k, v +} diff --git a/vendor/github.com/docker/cli/cli/compose/types/types.go b/vendor/github.com/docker/cli/cli/compose/types/types.go new file mode 100644 index 00000000..55b80365 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/compose/types/types.go @@ -0,0 +1,602 @@ +// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: +//go:build go1.22 + +package types + +import ( + "encoding/json" + "fmt" + "strconv" + "time" +) + +// UnsupportedProperties not yet supported by this implementation of the compose file +var UnsupportedProperties = []string{ + "build", + "cgroupns_mode", + "cgroup_parent", + "devices", + "domainname", + "external_links", + "ipc", + "links", + "mac_address", + "network_mode", + "pid", + "privileged", + "restart", + "security_opt", + "shm_size", + "userns_mode", +} + +// DeprecatedProperties that were removed from the v3 format, but their +// use should not impact the behaviour of the application. +var DeprecatedProperties = map[string]string{ + "container_name": "Setting the container name is not supported.", + "expose": "Exposing ports is unnecessary - services on the same network can access each other's containers on any port.", +} + +// ForbiddenProperties that are not supported in this implementation of the +// compose file. +var ForbiddenProperties = map[string]string{ + "extends": "Support for `extends` is not implemented yet.", + "volume_driver": "Instead of setting the volume driver on the service, define a volume using the top-level `volumes` option and specify the driver there.", + "volumes_from": "To share a volume between services, define it using the top-level `volumes` option and reference it from each service that shares it using the service-level `volumes` option.", + "cpu_quota": "Set resource limits using deploy.resources", + "cpu_shares": "Set resource limits using deploy.resources", + "cpuset": "Set resource limits using deploy.resources", + "mem_limit": "Set resource limits using deploy.resources", + "memswap_limit": "Set resource limits using deploy.resources", +} + +// ConfigFile is a filename and the contents of the file as a Dict +type ConfigFile struct { + Filename string + Config map[string]any +} + +// ConfigDetails are the details about a group of ConfigFiles +type ConfigDetails struct { + Version string + WorkingDir string + ConfigFiles []ConfigFile + Environment map[string]string +} + +// Duration is a thin wrapper around time.Duration with improved JSON marshalling +type Duration time.Duration + +func (d Duration) String() string { + return time.Duration(d).String() +} + +// ConvertDurationPtr converts a typedefined Duration pointer to a time.Duration pointer with the same value. +func ConvertDurationPtr(d *Duration) *time.Duration { + if d == nil { + return nil + } + res := time.Duration(*d) + return &res +} + +// MarshalJSON makes Duration implement json.Marshaler +func (d Duration) MarshalJSON() ([]byte, error) { + return json.Marshal(d.String()) +} + +// MarshalYAML makes Duration implement yaml.Marshaler +func (d Duration) MarshalYAML() (any, error) { + return d.String(), nil +} + +// LookupEnv provides a lookup function for environment variables +func (cd ConfigDetails) LookupEnv(key string) (string, bool) { + v, ok := cd.Environment[key] + return v, ok +} + +// Config is a full compose file configuration +type Config struct { + Filename string `yaml:"-" json:"-"` + Version string `json:"version"` + Services Services `json:"services"` + Networks map[string]NetworkConfig `yaml:",omitempty" json:"networks,omitempty"` + Volumes map[string]VolumeConfig `yaml:",omitempty" json:"volumes,omitempty"` + Secrets map[string]SecretConfig `yaml:",omitempty" json:"secrets,omitempty"` + Configs map[string]ConfigObjConfig `yaml:",omitempty" json:"configs,omitempty"` + Extras map[string]any `yaml:",inline" json:"-"` +} + +// MarshalJSON makes Config implement json.Marshaler +func (c Config) MarshalJSON() ([]byte, error) { + m := map[string]any{ + "version": c.Version, + "services": c.Services, + } + + if len(c.Networks) > 0 { + m["networks"] = c.Networks + } + if len(c.Volumes) > 0 { + m["volumes"] = c.Volumes + } + if len(c.Secrets) > 0 { + m["secrets"] = c.Secrets + } + if len(c.Configs) > 0 { + m["configs"] = c.Configs + } + for k, v := range c.Extras { + m[k] = v + } + return json.Marshal(m) +} + +// Services is a list of ServiceConfig +type Services []ServiceConfig + +// MarshalYAML makes Services implement yaml.Marshaller +func (s Services) MarshalYAML() (any, error) { + services := map[string]ServiceConfig{} + for _, service := range s { + services[service.Name] = service + } + return services, nil +} + +// MarshalJSON makes Services implement json.Marshaler +func (s Services) MarshalJSON() ([]byte, error) { + data, err := s.MarshalYAML() + if err != nil { + return nil, err + } + return json.MarshalIndent(data, "", " ") +} + +// ServiceConfig is the configuration of one service +type ServiceConfig struct { + Name string `yaml:"-" json:"-"` + + Build BuildConfig `yaml:",omitempty" json:"build,omitempty"` + CapAdd []string `mapstructure:"cap_add" yaml:"cap_add,omitempty" json:"cap_add,omitempty"` + CapDrop []string `mapstructure:"cap_drop" yaml:"cap_drop,omitempty" json:"cap_drop,omitempty"` + CgroupNSMode string `mapstructure:"cgroupns_mode" yaml:"cgroupns_mode,omitempty" json:"cgroupns_mode,omitempty"` + CgroupParent string `mapstructure:"cgroup_parent" yaml:"cgroup_parent,omitempty" json:"cgroup_parent,omitempty"` + Command ShellCommand `yaml:",omitempty" json:"command,omitempty"` + Configs []ServiceConfigObjConfig `yaml:",omitempty" json:"configs,omitempty"` + ContainerName string `mapstructure:"container_name" yaml:"container_name,omitempty" json:"container_name,omitempty"` + CredentialSpec CredentialSpecConfig `mapstructure:"credential_spec" yaml:"credential_spec,omitempty" json:"credential_spec,omitempty"` + DependsOn []string `mapstructure:"depends_on" yaml:"depends_on,omitempty" json:"depends_on,omitempty"` + Deploy DeployConfig `yaml:",omitempty" json:"deploy,omitempty"` + Devices []string `yaml:",omitempty" json:"devices,omitempty"` + DNS StringList `yaml:",omitempty" json:"dns,omitempty"` + DNSSearch StringList `mapstructure:"dns_search" yaml:"dns_search,omitempty" json:"dns_search,omitempty"` + DomainName string `mapstructure:"domainname" yaml:"domainname,omitempty" json:"domainname,omitempty"` + Entrypoint ShellCommand `yaml:",omitempty" json:"entrypoint,omitempty"` + Environment MappingWithEquals `yaml:",omitempty" json:"environment,omitempty"` + EnvFile StringList `mapstructure:"env_file" yaml:"env_file,omitempty" json:"env_file,omitempty"` + Expose StringOrNumberList `yaml:",omitempty" json:"expose,omitempty"` + ExternalLinks []string `mapstructure:"external_links" yaml:"external_links,omitempty" json:"external_links,omitempty"` + ExtraHosts HostsList `mapstructure:"extra_hosts" yaml:"extra_hosts,omitempty" json:"extra_hosts,omitempty"` + Hostname string `yaml:",omitempty" json:"hostname,omitempty"` + HealthCheck *HealthCheckConfig `yaml:",omitempty" json:"healthcheck,omitempty"` + Image string `yaml:",omitempty" json:"image,omitempty"` + Init *bool `yaml:",omitempty" json:"init,omitempty"` + Ipc string `yaml:",omitempty" json:"ipc,omitempty"` + Isolation string `mapstructure:"isolation" yaml:"isolation,omitempty" json:"isolation,omitempty"` + Labels Labels `yaml:",omitempty" json:"labels,omitempty"` + Links []string `yaml:",omitempty" json:"links,omitempty"` + Logging *LoggingConfig `yaml:",omitempty" json:"logging,omitempty"` + MacAddress string `mapstructure:"mac_address" yaml:"mac_address,omitempty" json:"mac_address,omitempty"` + NetworkMode string `mapstructure:"network_mode" yaml:"network_mode,omitempty" json:"network_mode,omitempty"` + Networks map[string]*ServiceNetworkConfig `yaml:",omitempty" json:"networks,omitempty"` + Pid string `yaml:",omitempty" json:"pid,omitempty"` + Ports []ServicePortConfig `yaml:",omitempty" json:"ports,omitempty"` + Privileged bool `yaml:",omitempty" json:"privileged,omitempty"` + ReadOnly bool `mapstructure:"read_only" yaml:"read_only,omitempty" json:"read_only,omitempty"` + Restart string `yaml:",omitempty" json:"restart,omitempty"` + Secrets []ServiceSecretConfig `yaml:",omitempty" json:"secrets,omitempty"` + SecurityOpt []string `mapstructure:"security_opt" yaml:"security_opt,omitempty" json:"security_opt,omitempty"` + ShmSize string `mapstructure:"shm_size" yaml:"shm_size,omitempty" json:"shm_size,omitempty"` + StdinOpen bool `mapstructure:"stdin_open" yaml:"stdin_open,omitempty" json:"stdin_open,omitempty"` + StopGracePeriod *Duration `mapstructure:"stop_grace_period" yaml:"stop_grace_period,omitempty" json:"stop_grace_period,omitempty"` + StopSignal string `mapstructure:"stop_signal" yaml:"stop_signal,omitempty" json:"stop_signal,omitempty"` + Sysctls Mapping `yaml:",omitempty" json:"sysctls,omitempty"` + Tmpfs StringList `yaml:",omitempty" json:"tmpfs,omitempty"` + Tty bool `mapstructure:"tty" yaml:"tty,omitempty" json:"tty,omitempty"` + Ulimits map[string]*UlimitsConfig `yaml:",omitempty" json:"ulimits,omitempty"` + User string `yaml:",omitempty" json:"user,omitempty"` + OomScoreAdj int64 `yaml:",omitempty" json:"oom_score_adj,omitempty"` + UserNSMode string `mapstructure:"userns_mode" yaml:"userns_mode,omitempty" json:"userns_mode,omitempty"` + Volumes []ServiceVolumeConfig `yaml:",omitempty" json:"volumes,omitempty"` + WorkingDir string `mapstructure:"working_dir" yaml:"working_dir,omitempty" json:"working_dir,omitempty"` + + Extras map[string]any `yaml:",inline" json:"-"` +} + +// BuildConfig is a type for build +// using the same format at libcompose: https://github.com/docker/libcompose/blob/master/yaml/build.go#L12 +type BuildConfig struct { + Context string `yaml:",omitempty" json:"context,omitempty"` + Dockerfile string `yaml:",omitempty" json:"dockerfile,omitempty"` + Args MappingWithEquals `yaml:",omitempty" json:"args,omitempty"` + Labels Labels `yaml:",omitempty" json:"labels,omitempty"` + CacheFrom StringList `mapstructure:"cache_from" yaml:"cache_from,omitempty" json:"cache_from,omitempty"` + ExtraHosts HostsList `mapstructure:"extra_hosts" yaml:"extra_hosts,omitempty" json:"extra_hosts,omitempty"` + Network string `yaml:",omitempty" json:"network,omitempty"` + Target string `yaml:",omitempty" json:"target,omitempty"` +} + +// ShellCommand is a string or list of string args +type ShellCommand []string + +// StringList is a type for fields that can be a string or list of strings +type StringList []string + +// StringOrNumberList is a type for fields that can be a list of strings or +// numbers +type StringOrNumberList []string + +// MappingWithEquals is a mapping type that can be converted from a list of +// key[=value] strings. +// For the key with an empty value (`key=`), the mapped value is set to a pointer to `""`. +// For the key without value (`key`), the mapped value is set to nil. +type MappingWithEquals map[string]*string + +// Mapping is a mapping type that can be converted from a list of +// key[=value] strings. +// For the key with an empty value (`key=`), or key without value (`key`), the +// mapped value is set to an empty string `""`. +type Mapping map[string]string + +// Labels is a mapping type for labels +type Labels map[string]string + +// MappingWithColon is a mapping type that can be converted from a list of +// 'key: value' strings +type MappingWithColon map[string]string + +// HostsList is a list of colon-separated host-ip mappings +type HostsList []string + +// LoggingConfig the logging configuration for a service +type LoggingConfig struct { + Driver string `yaml:",omitempty" json:"driver,omitempty"` + Options map[string]string `yaml:",omitempty" json:"options,omitempty"` +} + +// DeployConfig the deployment configuration for a service +type DeployConfig struct { + Mode string `yaml:",omitempty" json:"mode,omitempty"` + Replicas *uint64 `yaml:",omitempty" json:"replicas,omitempty"` + Labels Labels `yaml:",omitempty" json:"labels,omitempty"` + UpdateConfig *UpdateConfig `mapstructure:"update_config" yaml:"update_config,omitempty" json:"update_config,omitempty"` + RollbackConfig *UpdateConfig `mapstructure:"rollback_config" yaml:"rollback_config,omitempty" json:"rollback_config,omitempty"` + Resources Resources `yaml:",omitempty" json:"resources,omitempty"` + RestartPolicy *RestartPolicy `mapstructure:"restart_policy" yaml:"restart_policy,omitempty" json:"restart_policy,omitempty"` + Placement Placement `yaml:",omitempty" json:"placement,omitempty"` + EndpointMode string `mapstructure:"endpoint_mode" yaml:"endpoint_mode,omitempty" json:"endpoint_mode,omitempty"` +} + +// HealthCheckConfig the healthcheck configuration for a service +type HealthCheckConfig struct { + Test HealthCheckTest `yaml:",omitempty" json:"test,omitempty"` + Timeout *Duration `yaml:",omitempty" json:"timeout,omitempty"` + Interval *Duration `yaml:",omitempty" json:"interval,omitempty"` + Retries *uint64 `yaml:",omitempty" json:"retries,omitempty"` + StartPeriod *Duration `mapstructure:"start_period" yaml:"start_period,omitempty" json:"start_period,omitempty"` + StartInterval *Duration `mapstructure:"start_interval" yaml:"start_interval,omitempty" json:"start_interval,omitempty"` + Disable bool `yaml:",omitempty" json:"disable,omitempty"` +} + +// HealthCheckTest is the command run to test the health of a service +type HealthCheckTest []string + +// UpdateConfig the service update configuration +type UpdateConfig struct { + Parallelism *uint64 `yaml:",omitempty" json:"parallelism,omitempty"` + Delay Duration `yaml:",omitempty" json:"delay,omitempty"` + FailureAction string `mapstructure:"failure_action" yaml:"failure_action,omitempty" json:"failure_action,omitempty"` + Monitor Duration `yaml:",omitempty" json:"monitor,omitempty"` + MaxFailureRatio float32 `mapstructure:"max_failure_ratio" yaml:"max_failure_ratio,omitempty" json:"max_failure_ratio,omitempty"` + Order string `yaml:",omitempty" json:"order,omitempty"` +} + +// Resources the resource limits and reservations +type Resources struct { + Limits *ResourceLimit `yaml:",omitempty" json:"limits,omitempty"` + Reservations *Resource `yaml:",omitempty" json:"reservations,omitempty"` +} + +// ResourceLimit is a resource to be limited +type ResourceLimit struct { + // TODO: types to convert from units and ratios + NanoCPUs string `mapstructure:"cpus" yaml:"cpus,omitempty" json:"cpus,omitempty"` + MemoryBytes UnitBytes `mapstructure:"memory" yaml:"memory,omitempty" json:"memory,omitempty"` + Pids int64 `mapstructure:"pids" yaml:"pids,omitempty" json:"pids,omitempty"` +} + +// Resource is a resource to be reserved +type Resource struct { + // TODO: types to convert from units and ratios + NanoCPUs string `mapstructure:"cpus" yaml:"cpus,omitempty" json:"cpus,omitempty"` + MemoryBytes UnitBytes `mapstructure:"memory" yaml:"memory,omitempty" json:"memory,omitempty"` + GenericResources []GenericResource `mapstructure:"generic_resources" yaml:"generic_resources,omitempty" json:"generic_resources,omitempty"` +} + +// GenericResource represents a "user defined" resource which can +// only be an integer (e.g: SSD=3) for a service +type GenericResource struct { + DiscreteResourceSpec *DiscreteGenericResource `mapstructure:"discrete_resource_spec" yaml:"discrete_resource_spec,omitempty" json:"discrete_resource_spec,omitempty"` +} + +// DiscreteGenericResource represents a "user defined" resource which is defined +// as an integer +// "Kind" is used to describe the Kind of a resource (e.g: "GPU", "FPGA", "SSD", ...) +// Value is used to count the resource (SSD=5, HDD=3, ...) +type DiscreteGenericResource struct { + Kind string `json:"kind"` + Value int64 `json:"value"` +} + +// UnitBytes is the bytes type +type UnitBytes int64 + +// MarshalYAML makes UnitBytes implement yaml.Marshaller +func (u UnitBytes) MarshalYAML() (any, error) { + return fmt.Sprintf("%d", u), nil +} + +// MarshalJSON makes UnitBytes implement json.Marshaler +func (u UnitBytes) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%d"`, u)), nil +} + +// RestartPolicy the service restart policy +type RestartPolicy struct { + Condition string `yaml:",omitempty" json:"condition,omitempty"` + Delay *Duration `yaml:",omitempty" json:"delay,omitempty"` + MaxAttempts *uint64 `mapstructure:"max_attempts" yaml:"max_attempts,omitempty" json:"max_attempts,omitempty"` + Window *Duration `yaml:",omitempty" json:"window,omitempty"` +} + +// Placement constraints for the service +type Placement struct { + Constraints []string `yaml:",omitempty" json:"constraints,omitempty"` + Preferences []PlacementPreferences `yaml:",omitempty" json:"preferences,omitempty"` + MaxReplicas uint64 `mapstructure:"max_replicas_per_node" yaml:"max_replicas_per_node,omitempty" json:"max_replicas_per_node,omitempty"` +} + +// PlacementPreferences is the preferences for a service placement +type PlacementPreferences struct { + Spread string `yaml:",omitempty" json:"spread,omitempty"` +} + +// ServiceNetworkConfig is the network configuration for a service +type ServiceNetworkConfig struct { + Aliases []string `yaml:",omitempty" json:"aliases,omitempty"` + DriverOpts map[string]string `mapstructure:"driver_opts" yaml:"driver_opts,omitempty" json:"driver_opts,omitempty"` + Ipv4Address string `mapstructure:"ipv4_address" yaml:"ipv4_address,omitempty" json:"ipv4_address,omitempty"` + Ipv6Address string `mapstructure:"ipv6_address" yaml:"ipv6_address,omitempty" json:"ipv6_address,omitempty"` +} + +// ServicePortConfig is the port configuration for a service +type ServicePortConfig struct { + Mode string `yaml:",omitempty" json:"mode,omitempty"` + Target uint32 `yaml:",omitempty" json:"target,omitempty"` + Published uint32 `yaml:",omitempty" json:"published,omitempty"` + Protocol string `yaml:",omitempty" json:"protocol,omitempty"` +} + +// ServiceVolumeConfig are references to a volume used by a service +type ServiceVolumeConfig struct { + Type string `yaml:",omitempty" json:"type,omitempty"` + Source string `yaml:",omitempty" json:"source,omitempty"` + Target string `yaml:",omitempty" json:"target,omitempty"` + ReadOnly bool `mapstructure:"read_only" yaml:"read_only,omitempty" json:"read_only,omitempty"` + Consistency string `yaml:",omitempty" json:"consistency,omitempty"` + Bind *ServiceVolumeBind `yaml:",omitempty" json:"bind,omitempty"` + Volume *ServiceVolumeVolume `yaml:",omitempty" json:"volume,omitempty"` + Tmpfs *ServiceVolumeTmpfs `yaml:",omitempty" json:"tmpfs,omitempty"` + Cluster *ServiceVolumeCluster `yaml:",omitempty" json:"cluster,omitempty"` +} + +// ServiceVolumeBind are options for a service volume of type bind +type ServiceVolumeBind struct { + Propagation string `yaml:",omitempty" json:"propagation,omitempty"` +} + +// ServiceVolumeVolume are options for a service volume of type volume +type ServiceVolumeVolume struct { + NoCopy bool `mapstructure:"nocopy" yaml:"nocopy,omitempty" json:"nocopy,omitempty"` +} + +// ServiceVolumeTmpfs are options for a service volume of type tmpfs +type ServiceVolumeTmpfs struct { + Size int64 `yaml:",omitempty" json:"size,omitempty"` +} + +// ServiceVolumeCluster are options for a service volume of type cluster. +// Deliberately left blank for future options, but unused now. +type ServiceVolumeCluster struct{} + +// FileReferenceConfig for a reference to a swarm file object +type FileReferenceConfig struct { + Source string `yaml:",omitempty" json:"source,omitempty"` + Target string `yaml:",omitempty" json:"target,omitempty"` + UID string `yaml:",omitempty" json:"uid,omitempty"` + GID string `yaml:",omitempty" json:"gid,omitempty"` + Mode *uint32 `yaml:",omitempty" json:"mode,omitempty"` +} + +// ServiceConfigObjConfig is the config obj configuration for a service +type ServiceConfigObjConfig FileReferenceConfig + +// ServiceSecretConfig is the secret configuration for a service +type ServiceSecretConfig FileReferenceConfig + +// UlimitsConfig the ulimit configuration +type UlimitsConfig struct { + Single int `yaml:",omitempty" json:"single,omitempty"` + Soft int `yaml:",omitempty" json:"soft,omitempty"` + Hard int `yaml:",omitempty" json:"hard,omitempty"` +} + +// MarshalYAML makes UlimitsConfig implement yaml.Marshaller +func (u *UlimitsConfig) MarshalYAML() (any, error) { + if u.Single != 0 { + return u.Single, nil + } + // Return as a value to avoid re-entering this method and use the default implementation + return *u, nil +} + +// MarshalJSON makes UlimitsConfig implement json.Marshaller +func (u *UlimitsConfig) MarshalJSON() ([]byte, error) { + if u.Single != 0 { + return json.Marshal(u.Single) + } + // Pass as a value to avoid re-entering this method and use the default implementation + return json.Marshal(*u) +} + +// NetworkConfig for a network +type NetworkConfig struct { + Name string `yaml:",omitempty" json:"name,omitempty"` + Driver string `yaml:",omitempty" json:"driver,omitempty"` + DriverOpts map[string]string `mapstructure:"driver_opts" yaml:"driver_opts,omitempty" json:"driver_opts,omitempty"` + Ipam IPAMConfig `yaml:",omitempty" json:"ipam,omitempty"` + External External `yaml:",omitempty" json:"external,omitempty"` + Internal bool `yaml:",omitempty" json:"internal,omitempty"` + Attachable bool `yaml:",omitempty" json:"attachable,omitempty"` + Labels Labels `yaml:",omitempty" json:"labels,omitempty"` + Extras map[string]any `yaml:",inline" json:"-"` +} + +// IPAMConfig for a network +type IPAMConfig struct { + Driver string `yaml:",omitempty" json:"driver,omitempty"` + Config []*IPAMPool `yaml:",omitempty" json:"config,omitempty"` +} + +// IPAMPool for a network +type IPAMPool struct { + Subnet string `yaml:",omitempty" json:"subnet,omitempty"` +} + +// VolumeConfig for a volume +type VolumeConfig struct { + Name string `yaml:",omitempty" json:"name,omitempty"` + Driver string `yaml:",omitempty" json:"driver,omitempty"` + DriverOpts map[string]string `mapstructure:"driver_opts" yaml:"driver_opts,omitempty" json:"driver_opts,omitempty"` + External External `yaml:",omitempty" json:"external,omitempty"` + Labels Labels `yaml:",omitempty" json:"labels,omitempty"` + Extras map[string]any `yaml:",inline" json:"-"` + Spec *ClusterVolumeSpec `mapstructure:"x-cluster-spec" yaml:"x-cluster-spec,omitempty" json:"x-cluster-spec,omitempty"` +} + +// ClusterVolumeSpec defines all the configuration and options specific to a +// cluster (CSI) volume. +type ClusterVolumeSpec struct { + Group string `yaml:",omitempty" json:"group,omitempty"` + AccessMode *AccessMode `mapstructure:"access_mode" yaml:"access_mode,omitempty" json:"access_mode,omitempty"` + AccessibilityRequirements *TopologyRequirement `mapstructure:"accessibility_requirements" yaml:"accessibility_requirements,omitempty" json:"accessibility_requirements,omitempty"` + CapacityRange *CapacityRange `mapstructure:"capacity_range" yaml:"capacity_range,omitempty" json:"capacity_range,omitempty"` + + Secrets []VolumeSecret `yaml:",omitempty" json:"secrets,omitempty"` + + Availability string `yaml:",omitempty" json:"availability,omitempty"` +} + +// AccessMode defines the way a cluster volume is accessed by the tasks +type AccessMode struct { + Scope string `yaml:",omitempty" json:"scope,omitempty"` + Sharing string `yaml:",omitempty" json:"sharing,omitempty"` + + MountVolume *MountVolume `mapstructure:"mount_volume" yaml:"mount_volume,omitempty" json:"mount_volume,omitempty"` + BlockVolume *BlockVolume `mapstructure:"block_volume" yaml:"block_volume,omitempty" json:"block_volume,omitempty"` +} + +// MountVolume defines options for using a volume as a Mount +type MountVolume struct { + FsType string `mapstructure:"fs_type" yaml:"fs_type,omitempty" json:"fs_type,omitempty"` + MountFlags []string `mapstructure:"mount_flags" yaml:"mount_flags,omitempty" json:"mount_flags,omitempty"` +} + +// BlockVolume is deliberately empty +type BlockVolume struct{} + +// TopologyRequirement defines the requirements for volume placement in the +// cluster. +type TopologyRequirement struct { + Requisite []Topology `yaml:",omitempty" json:"requisite,omitempty"` + Preferred []Topology `yaml:",omitempty" json:"preferred,omitempty"` +} + +// Topology defines a particular topology group +type Topology struct { + Segments Mapping `yaml:",omitempty" json:"segments,omitempty"` +} + +// CapacityRange defines the minimum and maximum size of a volume. +type CapacityRange struct { + RequiredBytes UnitBytes `mapstructure:"required_bytes" yaml:"required_bytes,omitempty" json:"required_bytes,omitempty"` + LimitBytes UnitBytes `mapstructure:"limit_bytes" yaml:"limit_bytes,omitempty" json:"limit_bytes,omitempty"` +} + +// VolumeSecret defines a secret that needs to be passed to the CSI plugin when +// using the volume. +type VolumeSecret struct { + Key string `yaml:",omitempty" json:"key,omitempty"` + Secret string `yaml:",omitempty" json:"secret,omitempty"` +} + +// External identifies a Volume or Network as a reference to a resource that is +// not managed, and should already exist. +// External.name is deprecated and replaced by Volume.name +type External struct { + Name string `yaml:",omitempty" json:"name,omitempty"` + External bool `yaml:",omitempty" json:"external,omitempty"` +} + +// MarshalYAML makes External implement yaml.Marshaller +func (e External) MarshalYAML() (any, error) { + if e.Name == "" { + return e.External, nil + } + return External{Name: e.Name}, nil +} + +// MarshalJSON makes External implement json.Marshaller +func (e External) MarshalJSON() ([]byte, error) { + if e.Name == "" { + return []byte(strconv.FormatBool(e.External)), nil + } + return []byte(fmt.Sprintf(`{"name": %q}`, e.Name)), nil +} + +// CredentialSpecConfig for credential spec on Windows +type CredentialSpecConfig struct { + Config string `yaml:",omitempty" json:"config,omitempty"` // Config was added in API v1.40 + File string `yaml:",omitempty" json:"file,omitempty"` + Registry string `yaml:",omitempty" json:"registry,omitempty"` +} + +// FileObjectConfig is a config type for a file used by a service +type FileObjectConfig struct { + Name string `yaml:",omitempty" json:"name,omitempty"` + File string `yaml:",omitempty" json:"file,omitempty"` + External External `yaml:",omitempty" json:"external,omitempty"` + Labels Labels `yaml:",omitempty" json:"labels,omitempty"` + Extras map[string]any `yaml:",inline" json:"-"` + Driver string `yaml:",omitempty" json:"driver,omitempty"` + DriverOpts map[string]string `mapstructure:"driver_opts" yaml:"driver_opts,omitempty" json:"driver_opts,omitempty"` + TemplateDriver string `mapstructure:"template_driver" yaml:"template_driver,omitempty" json:"template_driver,omitempty"` +} + +// SecretConfig for a secret +type SecretConfig FileObjectConfig + +// ConfigObjConfig is the config for the swarm "Config" object +type ConfigObjConfig FileObjectConfig diff --git a/vendor/github.com/docker/cli/opts/capabilities.go b/vendor/github.com/docker/cli/opts/capabilities.go new file mode 100644 index 00000000..82d07185 --- /dev/null +++ b/vendor/github.com/docker/cli/opts/capabilities.go @@ -0,0 +1,89 @@ +package opts + +import ( + "sort" + "strings" +) + +const ( + // AllCapabilities is a special value to add or drop all capabilities + AllCapabilities = "ALL" + + // ResetCapabilities is a special value to reset capabilities when updating. + // This value should only be used when updating, not used on "create". + ResetCapabilities = "RESET" +) + +// NormalizeCapability normalizes a capability by upper-casing, trimming white space +// and adding a CAP_ prefix (if not yet present). This function also accepts the +// "ALL" magic-value, as used by CapAdd/CapDrop. +// +// This function only handles rudimentary formatting; no validation is performed, +// as the list of available capabilities can be updated over time, thus should be +// handled by the daemon. +func NormalizeCapability(capability string) string { + capability = strings.ToUpper(strings.TrimSpace(capability)) + if capability == AllCapabilities || capability == ResetCapabilities { + return capability + } + if !strings.HasPrefix(capability, "CAP_") { + capability = "CAP_" + capability + } + return capability +} + +// CapabilitiesMap normalizes the given capabilities and converts them to a map. +func CapabilitiesMap(caps []string) map[string]bool { + normalized := make(map[string]bool) + for _, c := range caps { + normalized[NormalizeCapability(c)] = true + } + return normalized +} + +// EffectiveCapAddCapDrop normalizes and sorts capabilities to "add" and "drop", +// and returns the effective capabilities to include in both. +// +// "CapAdd" takes precedence over "CapDrop", so capabilities included in both +// lists are removed from the list of capabilities to drop. The special "ALL" +// capability is also taken into account. +// +// Note that the special "RESET" value is only used when updating an existing +// service, and will be ignored. +// +// Duplicates are removed, and the resulting lists are sorted. +func EffectiveCapAddCapDrop(add, drop []string) (capAdd, capDrop []string) { + var ( + addCaps = CapabilitiesMap(add) + dropCaps = CapabilitiesMap(drop) + ) + + if addCaps[AllCapabilities] { + // Special case: "ALL capabilities" trumps any other capability added. + addCaps = map[string]bool{AllCapabilities: true} + } + if dropCaps[AllCapabilities] { + // Special case: "ALL capabilities" trumps any other capability added. + dropCaps = map[string]bool{AllCapabilities: true} + } + for c := range dropCaps { + if addCaps[c] { + // Adding a capability takes precedence, so skip dropping + continue + } + if c != ResetCapabilities { + capDrop = append(capDrop, c) + } + } + + for c := range addCaps { + if c != ResetCapabilities { + capAdd = append(capAdd, c) + } + } + + sort.Strings(capAdd) + sort.Strings(capDrop) + + return capAdd, capDrop +} diff --git a/vendor/github.com/docker/cli/opts/config.go b/vendor/github.com/docker/cli/opts/config.go new file mode 100644 index 00000000..1423ae3b --- /dev/null +++ b/vendor/github.com/docker/cli/opts/config.go @@ -0,0 +1,100 @@ +package opts + +import ( + "encoding/csv" + "errors" + "fmt" + "os" + "strconv" + "strings" + + swarmtypes "github.com/docker/docker/api/types/swarm" +) + +// ConfigOpt is a Value type for parsing configs +type ConfigOpt struct { + values []*swarmtypes.ConfigReference +} + +// Set a new config value +func (o *ConfigOpt) Set(value string) error { + csvReader := csv.NewReader(strings.NewReader(value)) + fields, err := csvReader.Read() + if err != nil { + return err + } + + options := &swarmtypes.ConfigReference{ + File: &swarmtypes.ConfigReferenceFileTarget{ + UID: "0", + GID: "0", + Mode: 0o444, + }, + } + + // support a simple syntax of --config foo + if len(fields) == 1 && !strings.Contains(fields[0], "=") { + options.File.Name = fields[0] + options.ConfigName = fields[0] + o.values = append(o.values, options) + return nil + } + + for _, field := range fields { + key, val, ok := strings.Cut(field, "=") + if !ok || key == "" { + return fmt.Errorf("invalid field '%s' must be a key=value pair", field) + } + + // TODO(thaJeztah): these options should not be case-insensitive. + switch strings.ToLower(key) { + case "source", "src": + options.ConfigName = val + case "target": + options.File.Name = val + case "uid": + options.File.UID = val + case "gid": + options.File.GID = val + case "mode": + m, err := strconv.ParseUint(val, 0, 32) + if err != nil { + return fmt.Errorf("invalid mode specified: %v", err) + } + + options.File.Mode = os.FileMode(m) + default: + return fmt.Errorf("invalid field in config request: %s", key) + } + } + + if options.ConfigName == "" { + return errors.New("source is required") + } + if options.File.Name == "" { + options.File.Name = options.ConfigName + } + + o.values = append(o.values, options) + return nil +} + +// Type returns the type of this option +func (o *ConfigOpt) Type() string { + return "config" +} + +// String returns a string repr of this option +func (o *ConfigOpt) String() string { + configs := []string{} + for _, config := range o.values { + repr := fmt.Sprintf("%s -> %s", config.ConfigName, config.File.Name) + configs = append(configs, repr) + } + return strings.Join(configs, ", ") +} + +// Value returns the config requests +func (o *ConfigOpt) Value() []*swarmtypes.ConfigReference { + return o.values +} diff --git a/vendor/github.com/docker/cli/opts/duration.go b/vendor/github.com/docker/cli/opts/duration.go new file mode 100644 index 00000000..5dc6eeaa --- /dev/null +++ b/vendor/github.com/docker/cli/opts/duration.go @@ -0,0 +1,64 @@ +package opts + +import ( + "time" + + "github.com/pkg/errors" +) + +// PositiveDurationOpt is an option type for time.Duration that uses a pointer. +// It behave similarly to DurationOpt but only allows positive duration values. +type PositiveDurationOpt struct { + DurationOpt +} + +// Set a new value on the option. Setting a negative duration value will cause +// an error to be returned. +func (d *PositiveDurationOpt) Set(s string) error { + err := d.DurationOpt.Set(s) + if err != nil { + return err + } + if *d.DurationOpt.value < 0 { + return errors.Errorf("duration cannot be negative") + } + return nil +} + +// DurationOpt is an option type for time.Duration that uses a pointer. This +// allows us to get nil values outside, instead of defaulting to 0 +type DurationOpt struct { + value *time.Duration +} + +// NewDurationOpt creates a DurationOpt with the specified duration +func NewDurationOpt(value *time.Duration) *DurationOpt { + return &DurationOpt{ + value: value, + } +} + +// Set a new value on the option +func (d *DurationOpt) Set(s string) error { + v, err := time.ParseDuration(s) + d.value = &v + return err +} + +// Type returns the type of this option, which will be displayed in `--help` output +func (d *DurationOpt) Type() string { + return "duration" +} + +// String returns a string repr of this option +func (d *DurationOpt) String() string { + if d.value != nil { + return d.value.String() + } + return "" +} + +// Value returns the time.Duration +func (d *DurationOpt) Value() *time.Duration { + return d.value +} diff --git a/vendor/github.com/docker/cli/opts/env.go b/vendor/github.com/docker/cli/opts/env.go new file mode 100644 index 00000000..214d6f44 --- /dev/null +++ b/vendor/github.com/docker/cli/opts/env.go @@ -0,0 +1,31 @@ +package opts + +import ( + "os" + "strings" + + "github.com/pkg/errors" +) + +// ValidateEnv validates an environment variable and returns it. +// If no value is specified, it obtains its value from the current environment +// +// As on ParseEnvFile and related to #16585, environment variable names +// are not validated, and it's up to the application inside the container +// to validate them or not. +// +// The only validation here is to check if name is empty, per #25099 +func ValidateEnv(val string) (string, error) { + k, _, hasValue := strings.Cut(val, "=") + if k == "" { + return "", errors.New("invalid environment variable: " + val) + } + if hasValue { + // val contains a "=" (but value may be an empty string) + return val, nil + } + if envVal, ok := os.LookupEnv(k); ok { + return k + "=" + envVal, nil + } + return val, nil +} diff --git a/vendor/github.com/docker/cli/opts/envfile.go b/vendor/github.com/docker/cli/opts/envfile.go new file mode 100644 index 00000000..3a16e6c1 --- /dev/null +++ b/vendor/github.com/docker/cli/opts/envfile.go @@ -0,0 +1,24 @@ +package opts + +import ( + "os" + + "github.com/docker/cli/pkg/kvfile" +) + +// ParseEnvFile reads a file with environment variables enumerated by lines +// +// “Environment variable names used by the utilities in the Shell and +// Utilities volume of IEEE Std 1003.1-2001 consist solely of uppercase +// letters, digits, and the '_' (underscore) from the characters defined in +// Portable Character Set and do not begin with a digit. *But*, other +// characters may be permitted by an implementation; applications shall +// tolerate the presence of such names.” +// -- http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html +// +// As of #16585, it's up to application inside docker to validate or not +// environment variables, that's why we just strip leading whitespace and +// nothing more. +func ParseEnvFile(filename string) ([]string, error) { + return kvfile.Parse(filename, os.LookupEnv) +} diff --git a/vendor/github.com/docker/cli/opts/gpus.go b/vendor/github.com/docker/cli/opts/gpus.go new file mode 100644 index 00000000..93bf9397 --- /dev/null +++ b/vendor/github.com/docker/cli/opts/gpus.go @@ -0,0 +1,111 @@ +package opts + +import ( + "encoding/csv" + "fmt" + "strconv" + "strings" + + "github.com/docker/docker/api/types/container" + "github.com/pkg/errors" +) + +// GpuOpts is a Value type for parsing mounts +type GpuOpts struct { + values []container.DeviceRequest +} + +func parseCount(s string) (int, error) { + if s == "all" { + return -1, nil + } + i, err := strconv.Atoi(s) + return i, errors.Wrap(err, "count must be an integer") +} + +// Set a new mount value +// +//nolint:gocyclo +func (o *GpuOpts) Set(value string) error { + csvReader := csv.NewReader(strings.NewReader(value)) + fields, err := csvReader.Read() + if err != nil { + return err + } + + req := container.DeviceRequest{} + + seen := map[string]struct{}{} + // Set writable as the default + for _, field := range fields { + key, val, withValue := strings.Cut(field, "=") + if _, ok := seen[key]; ok { + return fmt.Errorf("gpu request key '%s' can be specified only once", key) + } + seen[key] = struct{}{} + + if !withValue { + seen["count"] = struct{}{} + req.Count, err = parseCount(key) + if err != nil { + return err + } + continue + } + + switch key { + case "driver": + req.Driver = val + case "count": + req.Count, err = parseCount(val) + if err != nil { + return err + } + case "device": + req.DeviceIDs = strings.Split(val, ",") + case "capabilities": + req.Capabilities = [][]string{append(strings.Split(val, ","), "gpu")} + case "options": + r := csv.NewReader(strings.NewReader(val)) + optFields, err := r.Read() + if err != nil { + return errors.Wrap(err, "failed to read gpu options") + } + req.Options = ConvertKVStringsToMap(optFields) + default: + return fmt.Errorf("unexpected key '%s' in '%s'", key, field) + } + } + + if _, ok := seen["count"]; !ok && req.DeviceIDs == nil { + req.Count = 1 + } + if req.Options == nil { + req.Options = make(map[string]string) + } + if req.Capabilities == nil { + req.Capabilities = [][]string{{"gpu"}} + } + + o.values = append(o.values, req) + return nil +} + +// Type returns the type of this option +func (o *GpuOpts) Type() string { + return "gpu-request" +} + +// String returns a string repr of this option +func (o *GpuOpts) String() string { + gpus := []string{} + for _, gpu := range o.values { + gpus = append(gpus, fmt.Sprintf("%v", gpu)) + } + return strings.Join(gpus, ", ") +} + +// Value returns the mounts +func (o *GpuOpts) Value() []container.DeviceRequest { + return o.values +} diff --git a/vendor/github.com/docker/cli/opts/hosts.go b/vendor/github.com/docker/cli/opts/hosts.go new file mode 100644 index 00000000..552ab6b4 --- /dev/null +++ b/vendor/github.com/docker/cli/opts/hosts.go @@ -0,0 +1,213 @@ +package opts + +import ( + "fmt" + "net" + "net/url" + "strconv" + "strings" +) + +const ( + // defaultHTTPPort Default HTTP Port used if only the protocol is provided to -H flag e.g. dockerd -H tcp:// + // These are the IANA registered port numbers for use with Docker + // see http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml?search=docker + defaultHTTPPort = "2375" // Default HTTP Port + // defaultTLSHTTPPort Default HTTP Port used when TLS enabled + defaultTLSHTTPPort = "2376" // Default TLS encrypted HTTP Port + // defaultUnixSocket Path for the unix socket. + // Docker daemon by default always listens on the default unix socket + defaultUnixSocket = "/var/run/docker.sock" + // defaultTCPHost constant defines the default host string used by docker on Windows + defaultTCPHost = "tcp://" + defaultHTTPHost + ":" + defaultHTTPPort + // DefaultTLSHost constant defines the default host string used by docker for TLS sockets + defaultTLSHost = "tcp://" + defaultHTTPHost + ":" + defaultTLSHTTPPort + // DefaultNamedPipe defines the default named pipe used by docker on Windows + defaultNamedPipe = `//./pipe/docker_engine` + // hostGatewayName defines a special string which users can append to --add-host + // to add an extra entry in /etc/hosts that maps host.docker.internal to the host IP + // TODO Consider moving the hostGatewayName constant defined in docker at + // github.com/docker/docker/daemon/network/constants.go outside of the "daemon" + // package, so that the CLI can consume it. + hostGatewayName = "host-gateway" +) + +// ValidateHost validates that the specified string is a valid host and returns it. +// +// TODO(thaJeztah): ValidateHost appears to be unused; deprecate it. +func ValidateHost(val string) (string, error) { + host := strings.TrimSpace(val) + // The empty string means default and is not handled by parseDockerDaemonHost + if host != "" { + _, err := parseDockerDaemonHost(host) + if err != nil { + return val, err + } + } + // Note: unlike most flag validators, we don't return the mutated value here + // we need to know what the user entered later (using ParseHost) to adjust for TLS + return val, nil +} + +// ParseHost and set defaults for a Daemon host string +func ParseHost(defaultToTLS bool, val string) (string, error) { + host := strings.TrimSpace(val) + if host == "" { + if defaultToTLS { + host = defaultTLSHost + } else { + host = defaultHost + } + } else { + var err error + host, err = parseDockerDaemonHost(host) + if err != nil { + return val, err + } + } + return host, nil +} + +// parseDockerDaemonHost parses the specified address and returns an address that will be used as the host. +// Depending of the address specified, this may return one of the global Default* strings defined in hosts.go. +func parseDockerDaemonHost(addr string) (string, error) { + proto, host, hasProto := strings.Cut(addr, "://") + if !hasProto && proto != "" { + host = proto + proto = "tcp" + } + + switch proto { + case "tcp": + return ParseTCPAddr(host, defaultTCPHost) + case "unix": + return parseSimpleProtoAddr(proto, host, defaultUnixSocket) + case "npipe": + return parseSimpleProtoAddr(proto, host, defaultNamedPipe) + case "fd": + return addr, nil + case "ssh": + return addr, nil + default: + return "", fmt.Errorf("invalid bind address format: %s", addr) + } +} + +// parseSimpleProtoAddr parses and validates that the specified address is a valid +// socket address for simple protocols like unix and npipe. It returns a formatted +// socket address, either using the address parsed from addr, or the contents of +// defaultAddr if addr is a blank string. +func parseSimpleProtoAddr(proto, addr, defaultAddr string) (string, error) { + addr = strings.TrimPrefix(addr, proto+"://") + if strings.Contains(addr, "://") { + return "", fmt.Errorf("invalid proto, expected %s: %s", proto, addr) + } + if addr == "" { + addr = defaultAddr + } + return fmt.Sprintf("%s://%s", proto, addr), nil +} + +// ParseTCPAddr parses and validates that the specified address is a valid TCP +// address. It returns a formatted TCP address, either using the address parsed +// from tryAddr, or the contents of defaultAddr if tryAddr is a blank string. +// tryAddr is expected to have already been Trim()'d +// defaultAddr must be in the full `tcp://host:port` form +func ParseTCPAddr(tryAddr string, defaultAddr string) (string, error) { + if tryAddr == "" || tryAddr == "tcp://" { + return defaultAddr, nil + } + addr := strings.TrimPrefix(tryAddr, "tcp://") + if strings.Contains(addr, "://") || addr == "" { + return "", fmt.Errorf("invalid proto, expected tcp: %s", tryAddr) + } + + defaultAddr = strings.TrimPrefix(defaultAddr, "tcp://") + defaultHost, defaultPort, err := net.SplitHostPort(defaultAddr) + if err != nil { + return "", err + } + // url.Parse fails for trailing colon on IPv6 brackets on Go 1.5, but + // not 1.4. See https://github.com/golang/go/issues/12200 and + // https://github.com/golang/go/issues/6530. + if strings.HasSuffix(addr, "]:") { + addr += defaultPort + } + + u, err := url.Parse("tcp://" + addr) + if err != nil { + return "", err + } + host, port, err := net.SplitHostPort(u.Host) + if err != nil { + // try port addition once + host, port, err = net.SplitHostPort(net.JoinHostPort(u.Host, defaultPort)) + } + if err != nil { + return "", fmt.Errorf("invalid bind address format: %s", tryAddr) + } + + if host == "" { + host = defaultHost + } + if port == "" { + port = defaultPort + } + p, err := strconv.Atoi(port) + if err != nil && p == 0 { + return "", fmt.Errorf("invalid bind address format: %s", tryAddr) + } + + return fmt.Sprintf("tcp://%s%s", net.JoinHostPort(host, port), u.Path), nil +} + +// ValidateExtraHost validates that the specified string is a valid extrahost and +// returns it. ExtraHost is in the form of name:ip or name=ip, where the ip has +// to be a valid ip (IPv4 or IPv6). The address may be enclosed in square +// brackets. +// +// For example: +// +// my-hostname:127.0.0.1 +// my-hostname:::1 +// my-hostname=::1 +// my-hostname:[::1] +// +// For compatibility with the API server, this function normalises the given +// argument to use the ':' separator and strip square brackets enclosing the +// address. +func ValidateExtraHost(val string) (string, error) { + k, v, ok := strings.Cut(val, "=") + if !ok { + // allow for IPv6 addresses in extra hosts by only splitting on first ":" + k, v, ok = strings.Cut(val, ":") + } + // Check that a hostname was given, and that it doesn't contain a ":". (Colon + // isn't allowed in a hostname, along with many other characters. It's + // special-cased here because the API server doesn't know about '=' separators in + // '--add-host'. So, it'll split at the first colon and generate a strange error + // message.) + if !ok || k == "" || strings.Contains(k, ":") { + return "", fmt.Errorf("bad format for add-host: %q", val) + } + // Skip IPaddr validation for "host-gateway" string + if v != hostGatewayName { + // If the address is enclosed in square brackets, extract it (for IPv6, but + // permit it for IPv4 as well; we don't know the address family here, but it's + // unambiguous). + if len(v) > 2 && v[0] == '[' && v[len(v)-1] == ']' { + v = v[1 : len(v)-1] + } + // ValidateIPAddress returns the address in canonical form (for example, + // 0:0:0:0:0:0:0:1 -> ::1). But, stick with the original form, to avoid + // surprising a user who's expecting to see the address they supplied in the + // output of 'docker inspect' or '/etc/hosts'. + if _, err := ValidateIPAddress(v); err != nil { + return "", fmt.Errorf("invalid IP address in add-host: %q", v) + } + } + // This result is passed directly to the API, the daemon doesn't accept the '=' + // separator or an address enclosed in brackets. So, construct something it can + // understand. + return k + ":" + v, nil +} diff --git a/vendor/github.com/docker/cli/opts/hosts_unix.go b/vendor/github.com/docker/cli/opts/hosts_unix.go new file mode 100644 index 00000000..7cddd453 --- /dev/null +++ b/vendor/github.com/docker/cli/opts/hosts_unix.go @@ -0,0 +1,9 @@ +//go:build !windows + +package opts + +// defaultHost constant defines the default host string used by docker on other hosts than Windows +const defaultHost = "unix://" + defaultUnixSocket + +// defaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. dockerd -H tcp://:8080 +const defaultHTTPHost = "localhost" diff --git a/vendor/github.com/docker/cli/opts/hosts_windows.go b/vendor/github.com/docker/cli/opts/hosts_windows.go new file mode 100644 index 00000000..1e42a2d7 --- /dev/null +++ b/vendor/github.com/docker/cli/opts/hosts_windows.go @@ -0,0 +1,59 @@ +package opts + +// defaultHost constant defines the default host string used by docker on Windows +const defaultHost = "npipe://" + defaultNamedPipe + +// TODO Windows. Identify bug in GOLang 1.5.1+ and/or Windows Server 2016 TP5. +// @jhowardmsft, @swernli. +// +// On Windows, this mitigates a problem with the default options of running +// a docker client against a local docker daemon on TP5. +// +// What was found that if the default host is "localhost", even if the client +// (and daemon as this is local) is not physically on a network, and the DNS +// cache is flushed (ipconfig /flushdns), then the client will pause for +// exactly one second when connecting to the daemon for calls. For example +// using docker run windowsservercore cmd, the CLI will send a create followed +// by an attach. You see the delay between the attach finishing and the attach +// being seen by the daemon. +// +// Here's some daemon debug logs with additional debug spew put in. The +// AfterWriteJSON log is the very last thing the daemon does as part of the +// create call. The POST /attach is the second CLI call. Notice the second +// time gap. +// +// time="2015-11-06T13:38:37.259627400-08:00" level=debug msg="After createRootfs" +// time="2015-11-06T13:38:37.263626300-08:00" level=debug msg="After setHostConfig" +// time="2015-11-06T13:38:37.267631200-08:00" level=debug msg="before createContainerPl...." +// time="2015-11-06T13:38:37.271629500-08:00" level=debug msg=ToDiskLocking.... +// time="2015-11-06T13:38:37.275643200-08:00" level=debug msg="loggin event...." +// time="2015-11-06T13:38:37.277627600-08:00" level=debug msg="logged event...." +// time="2015-11-06T13:38:37.279631800-08:00" level=debug msg="In defer func" +// time="2015-11-06T13:38:37.282628100-08:00" level=debug msg="After daemon.create" +// time="2015-11-06T13:38:37.286651700-08:00" level=debug msg="return 2" +// time="2015-11-06T13:38:37.289629500-08:00" level=debug msg="Returned from daemon.ContainerCreate" +// time="2015-11-06T13:38:37.311629100-08:00" level=debug msg="After WriteJSON" +// ... 1 second gap here.... +// time="2015-11-06T13:38:38.317866200-08:00" level=debug msg="Calling POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach" +// time="2015-11-06T13:38:38.326882500-08:00" level=info msg="POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach?stderr=1&stdin=1&stdout=1&stream=1" +// +// We suspect this is either a bug introduced in GOLang 1.5.1, or that a change +// in GOLang 1.5.1 (from 1.4.3) is exposing a bug in Windows. In theory, +// the Windows networking stack is supposed to resolve "localhost" internally, +// without hitting DNS, or even reading the hosts file (which is why localhost +// is commented out in the hosts file on Windows). +// +// We have validated that working around this using the actual IPv4 localhost +// address does not cause the delay. +// +// This does not occur with the docker client built with 1.4.3 on the same +// Windows build, regardless of whether the daemon is built using 1.5.1 +// or 1.4.3. It does not occur on Linux. We also verified we see the same thing +// on a cross-compiled Windows binary (from Linux). +// +// Final note: This is a mitigation, not a 'real' fix. It is still susceptible +// to the delay if a user were to do 'docker run -H=tcp://localhost:2375...' +// explicitly. + +// defaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. dockerd -H tcp://:8080 +const defaultHTTPHost = "127.0.0.1" diff --git a/vendor/github.com/docker/cli/opts/mount.go b/vendor/github.com/docker/cli/opts/mount.go new file mode 100644 index 00000000..3a4ee31a --- /dev/null +++ b/vendor/github.com/docker/cli/opts/mount.go @@ -0,0 +1,223 @@ +package opts + +import ( + "encoding/csv" + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + + mounttypes "github.com/docker/docker/api/types/mount" + "github.com/docker/go-units" + "github.com/sirupsen/logrus" +) + +// MountOpt is a Value type for parsing mounts +type MountOpt struct { + values []mounttypes.Mount +} + +// Set a new mount value +// +//nolint:gocyclo +func (m *MountOpt) Set(value string) error { + csvReader := csv.NewReader(strings.NewReader(value)) + fields, err := csvReader.Read() + if err != nil { + return err + } + + mount := mounttypes.Mount{} + + volumeOptions := func() *mounttypes.VolumeOptions { + if mount.VolumeOptions == nil { + mount.VolumeOptions = &mounttypes.VolumeOptions{ + Labels: make(map[string]string), + } + } + if mount.VolumeOptions.DriverConfig == nil { + mount.VolumeOptions.DriverConfig = &mounttypes.Driver{} + } + return mount.VolumeOptions + } + + bindOptions := func() *mounttypes.BindOptions { + if mount.BindOptions == nil { + mount.BindOptions = new(mounttypes.BindOptions) + } + return mount.BindOptions + } + + tmpfsOptions := func() *mounttypes.TmpfsOptions { + if mount.TmpfsOptions == nil { + mount.TmpfsOptions = new(mounttypes.TmpfsOptions) + } + return mount.TmpfsOptions + } + + setValueOnMap := func(target map[string]string, value string) { + k, v, _ := strings.Cut(value, "=") + if k != "" { + target[k] = v + } + } + + mount.Type = mounttypes.TypeVolume // default to volume mounts + // Set writable as the default + for _, field := range fields { + key, val, ok := strings.Cut(field, "=") + + // TODO(thaJeztah): these options should not be case-insensitive. + key = strings.ToLower(key) + + if !ok { + switch key { + case "readonly", "ro": + mount.ReadOnly = true + continue + case "volume-nocopy": + volumeOptions().NoCopy = true + continue + case "bind-nonrecursive": + bindOptions().NonRecursive = true + continue + default: + return fmt.Errorf("invalid field '%s' must be a key=value pair", field) + } + } + + switch key { + case "type": + mount.Type = mounttypes.Type(strings.ToLower(val)) + case "source", "src": + mount.Source = val + if strings.HasPrefix(val, "."+string(filepath.Separator)) || val == "." { + if abs, err := filepath.Abs(val); err == nil { + mount.Source = abs + } + } + case "target", "dst", "destination": + mount.Target = val + case "readonly", "ro": + mount.ReadOnly, err = strconv.ParseBool(val) + if err != nil { + return fmt.Errorf("invalid value for %s: %s", key, val) + } + case "consistency": + mount.Consistency = mounttypes.Consistency(strings.ToLower(val)) + case "bind-propagation": + bindOptions().Propagation = mounttypes.Propagation(strings.ToLower(val)) + case "bind-nonrecursive": + bindOptions().NonRecursive, err = strconv.ParseBool(val) + if err != nil { + return fmt.Errorf("invalid value for %s: %s", key, val) + } + logrus.Warn("bind-nonrecursive is deprecated, use bind-recursive=disabled instead") + case "bind-recursive": + switch val { + case "enabled": // read-only mounts are recursively read-only if Engine >= v25 && kernel >= v5.12, otherwise writable + // NOP + case "disabled": // alias of bind-nonrecursive=true + bindOptions().NonRecursive = true + case "writable": // conforms to the default read-only bind-mount of Docker v24; read-only mounts are recursively mounted but not recursively read-only + bindOptions().ReadOnlyNonRecursive = true + case "readonly": // force recursively read-only, or raise an error + bindOptions().ReadOnlyForceRecursive = true + // TODO: implicitly set propagation and error if the user specifies a propagation in a future refactor/UX polish pass + // https://github.com/docker/cli/pull/4316#discussion_r1341974730 + default: + return fmt.Errorf("invalid value for %s: %s (must be \"enabled\", \"disabled\", \"writable\", or \"readonly\")", + key, val) + } + case "volume-subpath": + volumeOptions().Subpath = val + case "volume-nocopy": + volumeOptions().NoCopy, err = strconv.ParseBool(val) + if err != nil { + return fmt.Errorf("invalid value for volume-nocopy: %s", val) + } + case "volume-label": + setValueOnMap(volumeOptions().Labels, val) + case "volume-driver": + volumeOptions().DriverConfig.Name = val + case "volume-opt": + if volumeOptions().DriverConfig.Options == nil { + volumeOptions().DriverConfig.Options = make(map[string]string) + } + setValueOnMap(volumeOptions().DriverConfig.Options, val) + case "tmpfs-size": + sizeBytes, err := units.RAMInBytes(val) + if err != nil { + return fmt.Errorf("invalid value for %s: %s", key, val) + } + tmpfsOptions().SizeBytes = sizeBytes + case "tmpfs-mode": + ui64, err := strconv.ParseUint(val, 8, 32) + if err != nil { + return fmt.Errorf("invalid value for %s: %s", key, val) + } + tmpfsOptions().Mode = os.FileMode(ui64) + default: + return fmt.Errorf("unexpected key '%s' in '%s'", key, field) + } + } + + if mount.Type == "" { + return errors.New("type is required") + } + + if mount.Target == "" { + return errors.New("target is required") + } + + if mount.VolumeOptions != nil && mount.Type != mounttypes.TypeVolume { + return fmt.Errorf("cannot mix 'volume-*' options with mount type '%s'", mount.Type) + } + if mount.BindOptions != nil && mount.Type != mounttypes.TypeBind { + return fmt.Errorf("cannot mix 'bind-*' options with mount type '%s'", mount.Type) + } + if mount.TmpfsOptions != nil && mount.Type != mounttypes.TypeTmpfs { + return fmt.Errorf("cannot mix 'tmpfs-*' options with mount type '%s'", mount.Type) + } + + if mount.BindOptions != nil { + if mount.BindOptions.ReadOnlyNonRecursive { + if !mount.ReadOnly { + return errors.New("option 'bind-recursive=writable' requires 'readonly' to be specified in conjunction") + } + } + if mount.BindOptions.ReadOnlyForceRecursive { + if !mount.ReadOnly { + return errors.New("option 'bind-recursive=readonly' requires 'readonly' to be specified in conjunction") + } + if mount.BindOptions.Propagation != mounttypes.PropagationRPrivate { + return errors.New("option 'bind-recursive=readonly' requires 'bind-propagation=rprivate' to be specified in conjunction") + } + } + } + + m.values = append(m.values, mount) + return nil +} + +// Type returns the type of this option +func (m *MountOpt) Type() string { + return "mount" +} + +// String returns a string repr of this option +func (m *MountOpt) String() string { + mounts := []string{} + for _, mount := range m.values { + repr := fmt.Sprintf("%s %s %s", mount.Type, mount.Source, mount.Target) + mounts = append(mounts, repr) + } + return strings.Join(mounts, ", ") +} + +// Value returns the mounts +func (m *MountOpt) Value() []mounttypes.Mount { + return m.values +} diff --git a/vendor/github.com/docker/cli/opts/network.go b/vendor/github.com/docker/cli/opts/network.go new file mode 100644 index 00000000..413aec7b --- /dev/null +++ b/vendor/github.com/docker/cli/opts/network.go @@ -0,0 +1,135 @@ +package opts + +import ( + "encoding/csv" + "errors" + "fmt" + "regexp" + "strings" +) + +const ( + networkOptName = "name" + networkOptAlias = "alias" + networkOptIPv4Address = "ip" + networkOptIPv6Address = "ip6" + networkOptMacAddress = "mac-address" + networkOptLinkLocalIP = "link-local-ip" + driverOpt = "driver-opt" +) + +// NetworkAttachmentOpts represents the network options for endpoint creation +type NetworkAttachmentOpts struct { + Target string + Aliases []string + DriverOpts map[string]string + Links []string // TODO add support for links in the csv notation of `--network` + IPv4Address string + IPv6Address string + LinkLocalIPs []string + MacAddress string +} + +// NetworkOpt represents a network config in swarm mode. +type NetworkOpt struct { + options []NetworkAttachmentOpts +} + +// Set networkopts value +func (n *NetworkOpt) Set(value string) error { //nolint:gocyclo + longSyntax, err := regexp.MatchString(`\w+=\w+(,\w+=\w+)*`, value) + if err != nil { + return err + } + + var netOpt NetworkAttachmentOpts + if longSyntax { + csvReader := csv.NewReader(strings.NewReader(value)) + fields, err := csvReader.Read() + if err != nil { + return err + } + + netOpt.Aliases = []string{} + for _, field := range fields { + // TODO(thaJeztah): these options should not be case-insensitive. + key, val, ok := strings.Cut(strings.ToLower(field), "=") + if !ok || key == "" { + return fmt.Errorf("invalid field %s", field) + } + + key = strings.TrimSpace(key) + val = strings.TrimSpace(val) + + switch key { + case networkOptName: + netOpt.Target = val + case networkOptAlias: + netOpt.Aliases = append(netOpt.Aliases, val) + case networkOptIPv4Address: + netOpt.IPv4Address = val + case networkOptIPv6Address: + netOpt.IPv6Address = val + case networkOptMacAddress: + netOpt.MacAddress = val + case networkOptLinkLocalIP: + netOpt.LinkLocalIPs = append(netOpt.LinkLocalIPs, val) + case driverOpt: + key, val, err = parseDriverOpt(val) + if err != nil { + return err + } + if netOpt.DriverOpts == nil { + netOpt.DriverOpts = make(map[string]string) + } + netOpt.DriverOpts[key] = val + default: + return errors.New("invalid field key " + key) + } + } + if len(netOpt.Target) == 0 { + return errors.New("network name/id is not specified") + } + } else { + netOpt.Target = value + } + n.options = append(n.options, netOpt) + return nil +} + +// Type returns the type of this option +func (n *NetworkOpt) Type() string { + return "network" +} + +// Value returns the networkopts +func (n *NetworkOpt) Value() []NetworkAttachmentOpts { + return n.options +} + +// String returns the network opts as a string +func (n *NetworkOpt) String() string { + return "" +} + +// NetworkMode return the network mode for the network option +func (n *NetworkOpt) NetworkMode() string { + networkIDOrName := "default" + netOptVal := n.Value() + if len(netOptVal) > 0 { + networkIDOrName = netOptVal[0].Target + } + return networkIDOrName +} + +func parseDriverOpt(driverOpt string) (string, string, error) { + // TODO(thaJeztah): these options should not be case-insensitive. + // TODO(thaJeztah): should value be converted to lowercase as well, or only the key? + key, value, ok := strings.Cut(strings.ToLower(driverOpt), "=") + if !ok || key == "" { + return "", "", errors.New("invalid key value pair format in driver options") + } + key = strings.TrimSpace(key) + value = strings.TrimSpace(value) + return key, value, nil +} diff --git a/vendor/github.com/docker/cli/opts/opts.go b/vendor/github.com/docker/cli/opts/opts.go new file mode 100644 index 00000000..157b30f3 --- /dev/null +++ b/vendor/github.com/docker/cli/opts/opts.go @@ -0,0 +1,519 @@ +package opts + +import ( + "fmt" + "math/big" + "net" + "path" + "regexp" + "strings" + + "github.com/docker/docker/api/types/filters" + units "github.com/docker/go-units" + "github.com/pkg/errors" +) + +var ( + alphaRegexp = regexp.MustCompile(`[a-zA-Z]`) + domainRegexp = regexp.MustCompile(`^(:?(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]))(:?\.(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])))*)\.?\s*$`) +) + +// ListOpts holds a list of values and a validation function. +type ListOpts struct { + values *[]string + validator ValidatorFctType +} + +// NewListOpts creates a new ListOpts with the specified validator. +func NewListOpts(validator ValidatorFctType) ListOpts { + var values []string + return *NewListOptsRef(&values, validator) +} + +// NewListOptsRef creates a new ListOpts with the specified values and validator. +func NewListOptsRef(values *[]string, validator ValidatorFctType) *ListOpts { + return &ListOpts{ + values: values, + validator: validator, + } +} + +func (opts *ListOpts) String() string { + if len(*opts.values) == 0 { + return "" + } + return fmt.Sprintf("%v", *opts.values) +} + +// Set validates if needed the input value and adds it to the +// internal slice. +func (opts *ListOpts) Set(value string) error { + if opts.validator != nil { + v, err := opts.validator(value) + if err != nil { + return err + } + value = v + } + *opts.values = append(*opts.values, value) + return nil +} + +// Delete removes the specified element from the slice. +func (opts *ListOpts) Delete(key string) { + for i, k := range *opts.values { + if k == key { + *opts.values = append((*opts.values)[:i], (*opts.values)[i+1:]...) + return + } + } +} + +// GetMap returns the content of values in a map in order to avoid +// duplicates. +func (opts *ListOpts) GetMap() map[string]struct{} { + ret := make(map[string]struct{}) + for _, k := range *opts.values { + ret[k] = struct{}{} + } + return ret +} + +// GetAll returns the values of slice. +func (opts *ListOpts) GetAll() []string { + return *opts.values +} + +// GetAllOrEmpty returns the values of the slice +// or an empty slice when there are no values. +func (opts *ListOpts) GetAllOrEmpty() []string { + v := *opts.values + if v == nil { + return make([]string, 0) + } + return v +} + +// Get checks the existence of the specified key. +func (opts *ListOpts) Get(key string) bool { + for _, k := range *opts.values { + if k == key { + return true + } + } + return false +} + +// Len returns the amount of element in the slice. +func (opts *ListOpts) Len() int { + return len(*opts.values) +} + +// Type returns a string name for this Option type +func (opts *ListOpts) Type() string { + return "list" +} + +// WithValidator returns the ListOpts with validator set. +func (opts *ListOpts) WithValidator(validator ValidatorFctType) *ListOpts { + opts.validator = validator + return opts +} + +// NamedOption is an interface that list and map options +// with names implement. +type NamedOption interface { + Name() string +} + +// NamedListOpts is a ListOpts with a configuration name. +// This struct is useful to keep reference to the assigned +// field name in the internal configuration struct. +type NamedListOpts struct { + name string + ListOpts +} + +var _ NamedOption = &NamedListOpts{} + +// NewNamedListOptsRef creates a reference to a new NamedListOpts struct. +func NewNamedListOptsRef(name string, values *[]string, validator ValidatorFctType) *NamedListOpts { + return &NamedListOpts{ + name: name, + ListOpts: *NewListOptsRef(values, validator), + } +} + +// Name returns the name of the NamedListOpts in the configuration. +func (o *NamedListOpts) Name() string { + return o.name +} + +// MapOpts holds a map of values and a validation function. +type MapOpts struct { + values map[string]string + validator ValidatorFctType +} + +// Set validates if needed the input value and add it to the +// internal map, by splitting on '='. +func (opts *MapOpts) Set(value string) error { + if opts.validator != nil { + v, err := opts.validator(value) + if err != nil { + return err + } + value = v + } + k, v, _ := strings.Cut(value, "=") + opts.values[k] = v + return nil +} + +// GetAll returns the values of MapOpts as a map. +func (opts *MapOpts) GetAll() map[string]string { + return opts.values +} + +func (opts *MapOpts) String() string { + return fmt.Sprintf("%v", opts.values) +} + +// Type returns a string name for this Option type +func (opts *MapOpts) Type() string { + return "map" +} + +// NewMapOpts creates a new MapOpts with the specified map of values and a validator. +func NewMapOpts(values map[string]string, validator ValidatorFctType) *MapOpts { + if values == nil { + values = make(map[string]string) + } + return &MapOpts{ + values: values, + validator: validator, + } +} + +// NamedMapOpts is a MapOpts struct with a configuration name. +// This struct is useful to keep reference to the assigned +// field name in the internal configuration struct. +type NamedMapOpts struct { + name string + MapOpts +} + +var _ NamedOption = &NamedMapOpts{} + +// NewNamedMapOpts creates a reference to a new NamedMapOpts struct. +func NewNamedMapOpts(name string, values map[string]string, validator ValidatorFctType) *NamedMapOpts { + return &NamedMapOpts{ + name: name, + MapOpts: *NewMapOpts(values, validator), + } +} + +// Name returns the name of the NamedMapOpts in the configuration. +func (o *NamedMapOpts) Name() string { + return o.name +} + +// ValidatorFctType defines a validator function that returns a validated string and/or an error. +type ValidatorFctType func(val string) (string, error) + +// ValidatorFctListType defines a validator function that returns a validated list of string and/or an error +type ValidatorFctListType func(val string) ([]string, error) + +// ValidateIPAddress validates if the given value is a correctly formatted +// IP address, and returns the value in normalized form. Leading and trailing +// whitespace is allowed, but it does not allow IPv6 addresses surrounded by +// square brackets ("[::1]"). +// +// Refer to [net.ParseIP] for accepted formats. +func ValidateIPAddress(val string) (string, error) { + if ip := net.ParseIP(strings.TrimSpace(val)); ip != nil { + return ip.String(), nil + } + return "", fmt.Errorf("IP address is not correctly formatted: %s", val) +} + +// ValidateMACAddress validates a MAC address. +func ValidateMACAddress(val string) (string, error) { + _, err := net.ParseMAC(strings.TrimSpace(val)) + if err != nil { + return "", err + } + return val, nil +} + +// ValidateDNSSearch validates domain for resolvconf search configuration. +// A zero length domain is represented by a dot (.). +func ValidateDNSSearch(val string) (string, error) { + if val = strings.Trim(val, " "); val == "." { + return val, nil + } + return validateDomain(val) +} + +func validateDomain(val string) (string, error) { + if alphaRegexp.FindString(val) == "" { + return "", fmt.Errorf("%s is not a valid domain", val) + } + ns := domainRegexp.FindSubmatch([]byte(val)) + if len(ns) > 0 && len(ns[1]) < 255 { + return string(ns[1]), nil + } + return "", fmt.Errorf("%s is not a valid domain", val) +} + +const whiteSpaces = " \t" + +// ValidateLabel validates that the specified string is a valid label, and returns it. +// +// Labels are in the form of key=value; key must be a non-empty string, and not +// contain whitespaces. A value is optional (defaults to an empty string if omitted). +// +// Leading whitespace is removed during validation but values are kept as-is +// otherwise, so any string value is accepted for both, which includes whitespace +// (for values) and quotes (surrounding, or embedded in key or value). +// +// TODO discuss if quotes (and other special characters) should be valid or invalid for keys +// TODO discuss if leading/trailing whitespace in keys should be preserved (and valid) +func ValidateLabel(value string) (string, error) { + key, _, _ := strings.Cut(value, "=") + key = strings.TrimLeft(key, whiteSpaces) + if key == "" { + return "", fmt.Errorf("invalid label '%s': empty name", value) + } + if strings.ContainsAny(key, whiteSpaces) { + return "", fmt.Errorf("label '%s' contains whitespaces", key) + } + return value, nil +} + +// ValidateSysctl validates a sysctl and returns it. +func ValidateSysctl(val string) (string, error) { + validSysctlMap := map[string]bool{ + "kernel.msgmax": true, + "kernel.msgmnb": true, + "kernel.msgmni": true, + "kernel.sem": true, + "kernel.shmall": true, + "kernel.shmmax": true, + "kernel.shmmni": true, + "kernel.shm_rmid_forced": true, + } + validSysctlPrefixes := []string{ + "net.", + "fs.mqueue.", + } + k, _, ok := strings.Cut(val, "=") + if !ok || k == "" { + return "", fmt.Errorf("sysctl '%s' is not allowed", val) + } + if validSysctlMap[k] { + return val, nil + } + for _, vp := range validSysctlPrefixes { + if strings.HasPrefix(k, vp) { + return val, nil + } + } + return "", fmt.Errorf("sysctl '%s' is not allowed", val) +} + +// FilterOpt is a flag type for validating filters +type FilterOpt struct { + filter filters.Args +} + +// NewFilterOpt returns a new FilterOpt +func NewFilterOpt() FilterOpt { + return FilterOpt{filter: filters.NewArgs()} +} + +func (o *FilterOpt) String() string { + repr, err := filters.ToJSON(o.filter) + if err != nil { + return "invalid filters" + } + return repr +} + +// Set sets the value of the opt by parsing the command line value +func (o *FilterOpt) Set(value string) error { + if value == "" { + return nil + } + if !strings.Contains(value, "=") { + return errors.New("bad format of filter (expected name=value)") + } + name, val, _ := strings.Cut(value, "=") + + // TODO(thaJeztah): these options should not be case-insensitive. + name = strings.ToLower(strings.TrimSpace(name)) + val = strings.TrimSpace(val) + o.filter.Add(name, val) + return nil +} + +// Type returns the option type +func (o *FilterOpt) Type() string { + return "filter" +} + +// Value returns the value of this option +func (o *FilterOpt) Value() filters.Args { + return o.filter +} + +// NanoCPUs is a type for fixed point fractional number. +type NanoCPUs int64 + +// String returns the string format of the number +func (c *NanoCPUs) String() string { + if *c == 0 { + return "" + } + return big.NewRat(c.Value(), 1e9).FloatString(3) +} + +// Set sets the value of the NanoCPU by passing a string +func (c *NanoCPUs) Set(value string) error { + cpus, err := ParseCPUs(value) + *c = NanoCPUs(cpus) + return err +} + +// Type returns the type +func (c *NanoCPUs) Type() string { + return "decimal" +} + +// Value returns the value in int64 +func (c *NanoCPUs) Value() int64 { + return int64(*c) +} + +// ParseCPUs takes a string ratio and returns an integer value of nano cpus +func ParseCPUs(value string) (int64, error) { + cpu, ok := new(big.Rat).SetString(value) + if !ok { + return 0, fmt.Errorf("failed to parse %v as a rational number", value) + } + nano := cpu.Mul(cpu, big.NewRat(1e9, 1)) + if !nano.IsInt() { + return 0, errors.New("value is too precise") + } + return nano.Num().Int64(), nil +} + +// ParseLink parses and validates the specified string as a link format (name:alias) +func ParseLink(val string) (string, string, error) { + if val == "" { + return "", "", errors.New("empty string specified for links") + } + // We expect two parts, but restrict to three to allow detecting invalid formats. + arr := strings.SplitN(val, ":", 3) + + // TODO(thaJeztah): clean up this logic!! + if len(arr) > 2 { + return "", "", errors.New("bad format for links: " + val) + } + // TODO(thaJeztah): this should trim the "/" prefix as well?? + if len(arr) == 1 { + return val, val, nil + } + // This is kept because we can actually get a HostConfig with links + // from an already created container and the format is not `foo:bar` + // but `/foo:/c1/bar` + if strings.HasPrefix(arr[0], "/") { + // TODO(thaJeztah): clean up this logic!! + _, alias := path.Split(arr[1]) + return arr[0][1:], alias, nil + } + return arr[0], arr[1], nil +} + +// ValidateLink validates that the specified string has a valid link format (containerName:alias). +func ValidateLink(val string) (string, error) { + _, _, err := ParseLink(val) + return val, err +} + +// MemBytes is a type for human readable memory bytes (like 128M, 2g, etc) +type MemBytes int64 + +// String returns the string format of the human readable memory bytes +func (m *MemBytes) String() string { + // NOTE: In spf13/pflag/flag.go, "0" is considered as "zero value" while "0 B" is not. + // We return "0" in case value is 0 here so that the default value is hidden. + // (Sometimes "default 0 B" is actually misleading) + if m.Value() != 0 { + return units.BytesSize(float64(m.Value())) + } + return "0" +} + +// Set sets the value of the MemBytes by passing a string +func (m *MemBytes) Set(value string) error { + val, err := units.RAMInBytes(value) + *m = MemBytes(val) + return err +} + +// Type returns the type +func (m *MemBytes) Type() string { + return "bytes" +} + +// Value returns the value in int64 +func (m *MemBytes) Value() int64 { + return int64(*m) +} + +// UnmarshalJSON is the customized unmarshaler for MemBytes +func (m *MemBytes) UnmarshalJSON(s []byte) error { + if len(s) <= 2 || s[0] != '"' || s[len(s)-1] != '"' { + return fmt.Errorf("invalid size: %q", s) + } + val, err := units.RAMInBytes(string(s[1 : len(s)-1])) + *m = MemBytes(val) + return err +} + +// MemSwapBytes is a type for human readable memory bytes (like 128M, 2g, etc). +// It differs from MemBytes in that -1 is valid and the default. +type MemSwapBytes int64 + +// Set sets the value of the MemSwapBytes by passing a string +func (m *MemSwapBytes) Set(value string) error { + if value == "-1" { + *m = MemSwapBytes(-1) + return nil + } + val, err := units.RAMInBytes(value) + *m = MemSwapBytes(val) + return err +} + +// Type returns the type +func (m *MemSwapBytes) Type() string { + return "bytes" +} + +// Value returns the value in int64 +func (m *MemSwapBytes) Value() int64 { + return int64(*m) +} + +func (m *MemSwapBytes) String() string { + b := MemBytes(*m) + return b.String() +} + +// UnmarshalJSON is the customized unmarshaler for MemSwapBytes +func (m *MemSwapBytes) UnmarshalJSON(s []byte) error { + b := MemBytes(*m) + return b.UnmarshalJSON(s) +} diff --git a/vendor/github.com/docker/cli/opts/parse.go b/vendor/github.com/docker/cli/opts/parse.go new file mode 100644 index 00000000..996d4d7e --- /dev/null +++ b/vendor/github.com/docker/cli/opts/parse.go @@ -0,0 +1,97 @@ +package opts + +import ( + "errors" + "os" + "strconv" + "strings" + + "github.com/docker/cli/pkg/kvfile" + "github.com/docker/docker/api/types/container" +) + +// ReadKVStrings reads a file of line terminated key=value pairs, and overrides any keys +// present in the file with additional pairs specified in the override parameter +func ReadKVStrings(files []string, override []string) ([]string, error) { + return readKVStrings(files, override, nil) +} + +// ReadKVEnvStrings reads a file of line terminated key=value pairs, and overrides any keys +// present in the file with additional pairs specified in the override parameter. +// If a key has no value, it will get the value from the environment. +func ReadKVEnvStrings(files []string, override []string) ([]string, error) { + return readKVStrings(files, override, os.LookupEnv) +} + +func readKVStrings(files []string, override []string, emptyFn func(string) (string, bool)) ([]string, error) { + var variables []string + for _, ef := range files { + parsedVars, err := kvfile.Parse(ef, emptyFn) + if err != nil { + return nil, err + } + variables = append(variables, parsedVars...) + } + // parse the '-e' and '--env' after, to allow override + variables = append(variables, override...) + + return variables, nil +} + +// ConvertKVStringsToMap converts ["key=value"] to {"key":"value"} +func ConvertKVStringsToMap(values []string) map[string]string { + result := make(map[string]string, len(values)) + for _, value := range values { + k, v, _ := strings.Cut(value, "=") + result[k] = v + } + + return result +} + +// ConvertKVStringsToMapWithNil converts ["key=value"] to {"key":"value"} +// but set unset keys to nil - meaning the ones with no "=" in them. +// We use this in cases where we need to distinguish between +// +// FOO= and FOO +// +// where the latter case just means FOO was mentioned but not given a value +func ConvertKVStringsToMapWithNil(values []string) map[string]*string { + result := make(map[string]*string, len(values)) + for _, value := range values { + k, v, ok := strings.Cut(value, "=") + if !ok { + result[k] = nil + } else { + result[k] = &v + } + } + + return result +} + +// ParseRestartPolicy returns the parsed policy or an error indicating what is incorrect +func ParseRestartPolicy(policy string) (container.RestartPolicy, error) { + if policy == "" { + // for backward-compatibility, we don't set the default ("no") + // policy here, because older versions of the engine may not + // support it. + return container.RestartPolicy{}, nil + } + + p := container.RestartPolicy{} + k, v, ok := strings.Cut(policy, ":") + if ok && k == "" { + return container.RestartPolicy{}, errors.New("invalid restart policy format: no policy provided before colon") + } + if v != "" { + count, err := strconv.Atoi(v) + if err != nil { + return container.RestartPolicy{}, errors.New("invalid restart policy format: maximum retry count must be an integer") + } + p.MaximumRetryCount = count + } + + p.Name = container.RestartPolicyMode(k) + return p, nil +} diff --git a/vendor/github.com/docker/cli/opts/port.go b/vendor/github.com/docker/cli/opts/port.go new file mode 100644 index 00000000..099aae35 --- /dev/null +++ b/vendor/github.com/docker/cli/opts/port.go @@ -0,0 +1,173 @@ +package opts + +import ( + "encoding/csv" + "errors" + "fmt" + "net" + "regexp" + "strconv" + "strings" + + "github.com/docker/docker/api/types/swarm" + "github.com/docker/go-connections/nat" + "github.com/sirupsen/logrus" +) + +const ( + portOptTargetPort = "target" + portOptPublishedPort = "published" + portOptProtocol = "protocol" + portOptMode = "mode" +) + +// PortOpt represents a port config in swarm mode. +type PortOpt struct { + ports []swarm.PortConfig +} + +// Set a new port value +// +//nolint:gocyclo +func (p *PortOpt) Set(value string) error { + longSyntax, err := regexp.MatchString(`\w+=\w+(,\w+=\w+)*`, value) + if err != nil { + return err + } + if longSyntax { + csvReader := csv.NewReader(strings.NewReader(value)) + fields, err := csvReader.Read() + if err != nil { + return err + } + + pConfig := swarm.PortConfig{} + for _, field := range fields { + // TODO(thaJeztah): these options should not be case-insensitive. + key, val, ok := strings.Cut(strings.ToLower(field), "=") + if !ok || key == "" { + return fmt.Errorf("invalid field %s", field) + } + switch key { + case portOptProtocol: + if val != string(swarm.PortConfigProtocolTCP) && val != string(swarm.PortConfigProtocolUDP) && val != string(swarm.PortConfigProtocolSCTP) { + return fmt.Errorf("invalid protocol value %s", val) + } + + pConfig.Protocol = swarm.PortConfigProtocol(val) + case portOptMode: + if val != string(swarm.PortConfigPublishModeIngress) && val != string(swarm.PortConfigPublishModeHost) { + return fmt.Errorf("invalid publish mode value %s", val) + } + + pConfig.PublishMode = swarm.PortConfigPublishMode(val) + case portOptTargetPort: + tPort, err := strconv.ParseUint(val, 10, 16) + if err != nil { + return err + } + + pConfig.TargetPort = uint32(tPort) + case portOptPublishedPort: + pPort, err := strconv.ParseUint(val, 10, 16) + if err != nil { + return err + } + + pConfig.PublishedPort = uint32(pPort) + default: + return fmt.Errorf("invalid field key %s", key) + } + } + + if pConfig.TargetPort == 0 { + return fmt.Errorf("missing mandatory field %q", portOptTargetPort) + } + + if pConfig.PublishMode == "" { + pConfig.PublishMode = swarm.PortConfigPublishModeIngress + } + + if pConfig.Protocol == "" { + pConfig.Protocol = swarm.PortConfigProtocolTCP + } + + p.ports = append(p.ports, pConfig) + } else { + // short syntax + portConfigs := []swarm.PortConfig{} + ports, portBindingMap, err := nat.ParsePortSpecs([]string{value}) + if err != nil { + return err + } + for _, portBindings := range portBindingMap { + for _, portBinding := range portBindings { + if portBinding.HostIP != "" { + return errors.New("hostip is not supported") + } + } + } + + for port := range ports { + portConfig, err := ConvertPortToPortConfig(port, portBindingMap) + if err != nil { + return err + } + portConfigs = append(portConfigs, portConfig...) + } + p.ports = append(p.ports, portConfigs...) + } + return nil +} + +// Type returns the type of this option +func (p *PortOpt) Type() string { + return "port" +} + +// String returns a string repr of this option +func (p *PortOpt) String() string { + ports := []string{} + for _, port := range p.ports { + repr := fmt.Sprintf("%v:%v/%s/%s", port.PublishedPort, port.TargetPort, port.Protocol, port.PublishMode) + ports = append(ports, repr) + } + return strings.Join(ports, ", ") +} + +// Value returns the ports +func (p *PortOpt) Value() []swarm.PortConfig { + return p.ports +} + +// ConvertPortToPortConfig converts ports to the swarm type +func ConvertPortToPortConfig( + port nat.Port, + portBindings map[nat.Port][]nat.PortBinding, +) ([]swarm.PortConfig, error) { + ports := []swarm.PortConfig{} + + for _, binding := range portBindings[port] { + if p := net.ParseIP(binding.HostIP); p != nil && !p.IsUnspecified() { + // TODO(thaJeztah): use context-logger, so that this output can be suppressed (in tests). + logrus.Warnf("ignoring IP-address (%s:%s) service will listen on '0.0.0.0'", net.JoinHostPort(binding.HostIP, binding.HostPort), port) + } + + startHostPort, endHostPort, err := nat.ParsePortRange(binding.HostPort) + + if err != nil && binding.HostPort != "" { + return nil, fmt.Errorf("invalid hostport binding (%s) for port (%s)", binding.HostPort, port.Port()) + } + + for i := startHostPort; i <= endHostPort; i++ { + ports = append(ports, swarm.PortConfig{ + // TODO Name: ? + Protocol: swarm.PortConfigProtocol(strings.ToLower(port.Proto())), + TargetPort: uint32(port.Int()), + PublishedPort: uint32(i), + PublishMode: swarm.PortConfigPublishModeIngress, + }) + } + } + return ports, nil +} diff --git a/vendor/github.com/docker/cli/opts/quotedstring.go b/vendor/github.com/docker/cli/opts/quotedstring.go new file mode 100644 index 00000000..741f450b --- /dev/null +++ b/vendor/github.com/docker/cli/opts/quotedstring.go @@ -0,0 +1,40 @@ +package opts + +// QuotedString is a string that may have extra quotes around the value. The +// quotes are stripped from the value. +type QuotedString struct { + value *string +} + +// Set sets a new value +func (s *QuotedString) Set(val string) error { + *s.value = trimQuotes(val) + return nil +} + +// Type returns the type of the value +func (s *QuotedString) Type() string { + return "string" +} + +func (s *QuotedString) String() string { + return *s.value +} + +func trimQuotes(value string) string { + if len(value) < 2 { + return value + } + lastIndex := len(value) - 1 + for _, char := range []byte{'\'', '"'} { + if value[0] == char && value[lastIndex] == char { + return value[1:lastIndex] + } + } + return value +} + +// NewQuotedString returns a new quoted string option +func NewQuotedString(value *string) *QuotedString { + return &QuotedString{value: value} +} diff --git a/vendor/github.com/docker/cli/opts/secret.go b/vendor/github.com/docker/cli/opts/secret.go new file mode 100644 index 00000000..09d2b2b3 --- /dev/null +++ b/vendor/github.com/docker/cli/opts/secret.go @@ -0,0 +1,99 @@ +package opts + +import ( + "encoding/csv" + "errors" + "fmt" + "os" + "strconv" + "strings" + + swarmtypes "github.com/docker/docker/api/types/swarm" +) + +// SecretOpt is a Value type for parsing secrets +type SecretOpt struct { + values []*swarmtypes.SecretReference +} + +// Set a new secret value +func (o *SecretOpt) Set(value string) error { + csvReader := csv.NewReader(strings.NewReader(value)) + fields, err := csvReader.Read() + if err != nil { + return err + } + + options := &swarmtypes.SecretReference{ + File: &swarmtypes.SecretReferenceFileTarget{ + UID: "0", + GID: "0", + Mode: 0o444, + }, + } + + // support a simple syntax of --secret foo + if len(fields) == 1 && !strings.Contains(fields[0], "=") { + options.File.Name = fields[0] + options.SecretName = fields[0] + o.values = append(o.values, options) + return nil + } + + for _, field := range fields { + key, val, ok := strings.Cut(field, "=") + if !ok || key == "" { + return fmt.Errorf("invalid field '%s' must be a key=value pair", field) + } + // TODO(thaJeztah): these options should not be case-insensitive. + switch strings.ToLower(key) { + case "source", "src": + options.SecretName = val + case "target": + options.File.Name = val + case "uid": + options.File.UID = val + case "gid": + options.File.GID = val + case "mode": + m, err := strconv.ParseUint(val, 0, 32) + if err != nil { + return fmt.Errorf("invalid mode specified: %v", err) + } + + options.File.Mode = os.FileMode(m) + default: + return errors.New("invalid field in secret request: " + key) + } + } + + if options.SecretName == "" { + return errors.New("source is required") + } + if options.File.Name == "" { + options.File.Name = options.SecretName + } + + o.values = append(o.values, options) + return nil +} + +// Type returns the type of this option +func (o *SecretOpt) Type() string { + return "secret" +} + +// String returns a string repr of this option +func (o *SecretOpt) String() string { + secrets := []string{} + for _, secret := range o.values { + repr := fmt.Sprintf("%s -> %s", secret.SecretName, secret.File.Name) + secrets = append(secrets, repr) + } + return strings.Join(secrets, ", ") +} + +// Value returns the secret requests +func (o *SecretOpt) Value() []*swarmtypes.SecretReference { + return o.values +} diff --git a/vendor/github.com/docker/cli/opts/throttledevice.go b/vendor/github.com/docker/cli/opts/throttledevice.go new file mode 100644 index 00000000..8bf12880 --- /dev/null +++ b/vendor/github.com/docker/cli/opts/throttledevice.go @@ -0,0 +1,105 @@ +package opts + +import ( + "fmt" + "strconv" + "strings" + + "github.com/docker/docker/api/types/blkiodev" + "github.com/docker/go-units" +) + +// ValidatorThrottleFctType defines a validator function that returns a validated struct and/or an error. +type ValidatorThrottleFctType func(val string) (*blkiodev.ThrottleDevice, error) + +// ValidateThrottleBpsDevice validates that the specified string has a valid device-rate format. +func ValidateThrottleBpsDevice(val string) (*blkiodev.ThrottleDevice, error) { + k, v, ok := strings.Cut(val, ":") + if !ok || k == "" { + return nil, fmt.Errorf("bad format: %s", val) + } + // TODO(thaJeztah): should we really validate this on the client? + if !strings.HasPrefix(k, "/dev/") { + return nil, fmt.Errorf("bad format for device path: %s", val) + } + rate, err := units.RAMInBytes(v) + if err != nil { + return nil, fmt.Errorf("invalid rate for device: %s. The correct format is :[]. Number must be a positive integer. Unit is optional and can be kb, mb, or gb", val) + } + if rate < 0 { + return nil, fmt.Errorf("invalid rate for device: %s. The correct format is :[]. Number must be a positive integer. Unit is optional and can be kb, mb, or gb", val) + } + + return &blkiodev.ThrottleDevice{ + Path: k, + Rate: uint64(rate), + }, nil +} + +// ValidateThrottleIOpsDevice validates that the specified string has a valid device-rate format. +func ValidateThrottleIOpsDevice(val string) (*blkiodev.ThrottleDevice, error) { + k, v, ok := strings.Cut(val, ":") + if !ok || k == "" { + return nil, fmt.Errorf("bad format: %s", val) + } + // TODO(thaJeztah): should we really validate this on the client? + if !strings.HasPrefix(k, "/dev/") { + return nil, fmt.Errorf("bad format for device path: %s", val) + } + rate, err := strconv.ParseUint(v, 10, 64) + if err != nil { + return nil, fmt.Errorf("invalid rate for device: %s. The correct format is :. Number must be a positive integer", val) + } + + return &blkiodev.ThrottleDevice{Path: k, Rate: rate}, nil +} + +// ThrottledeviceOpt defines a map of ThrottleDevices +type ThrottledeviceOpt struct { + values []*blkiodev.ThrottleDevice + validator ValidatorThrottleFctType +} + +// NewThrottledeviceOpt creates a new ThrottledeviceOpt +func NewThrottledeviceOpt(validator ValidatorThrottleFctType) ThrottledeviceOpt { + return ThrottledeviceOpt{ + values: []*blkiodev.ThrottleDevice{}, + validator: validator, + } +} + +// Set validates a ThrottleDevice and sets its name as a key in ThrottledeviceOpt +func (opt *ThrottledeviceOpt) Set(val string) error { + var value *blkiodev.ThrottleDevice + if opt.validator != nil { + v, err := opt.validator(val) + if err != nil { + return err + } + value = v + } + opt.values = append(opt.values, value) + return nil +} + +// String returns ThrottledeviceOpt values as a string. +func (opt *ThrottledeviceOpt) String() string { + out := make([]string, 0, len(opt.values)) + for _, v := range opt.values { + out = append(out, v.String()) + } + + return fmt.Sprintf("%v", out) +} + +// GetList returns a slice of pointers to ThrottleDevices. +func (opt *ThrottledeviceOpt) GetList() []*blkiodev.ThrottleDevice { + out := make([]*blkiodev.ThrottleDevice, len(opt.values)) + copy(out, opt.values) + return out +} + +// Type returns the option type +func (opt *ThrottledeviceOpt) Type() string { + return "list" +} diff --git a/vendor/github.com/docker/cli/opts/ulimit.go b/vendor/github.com/docker/cli/opts/ulimit.go new file mode 100644 index 00000000..1409a109 --- /dev/null +++ b/vendor/github.com/docker/cli/opts/ulimit.go @@ -0,0 +1,63 @@ +package opts + +import ( + "fmt" + "sort" + + "github.com/docker/docker/api/types/container" + "github.com/docker/go-units" +) + +// UlimitOpt defines a map of Ulimits +type UlimitOpt struct { + values *map[string]*container.Ulimit +} + +// NewUlimitOpt creates a new UlimitOpt. Ulimits are not validated. +func NewUlimitOpt(ref *map[string]*container.Ulimit) *UlimitOpt { + // TODO(thaJeztah): why do we need a map with pointers here? + if ref == nil { + ref = &map[string]*container.Ulimit{} + } + return &UlimitOpt{ref} +} + +// Set validates a Ulimit and sets its name as a key in UlimitOpt +func (o *UlimitOpt) Set(val string) error { + // FIXME(thaJeztah): these functions also need to be moved over from go-units. + l, err := units.ParseUlimit(val) + if err != nil { + return err + } + + (*o.values)[l.Name] = l + + return nil +} + +// String returns Ulimit values as a string. Values are sorted by name. +func (o *UlimitOpt) String() string { + out := make([]string, 0, len(*o.values)) + for _, v := range *o.values { + out = append(out, v.String()) + } + sort.Strings(out) + return fmt.Sprintf("%v", out) +} + +// GetList returns a slice of pointers to Ulimits. Values are sorted by name. +func (o *UlimitOpt) GetList() []*container.Ulimit { + ulimits := make([]*container.Ulimit, 0, len(*o.values)) + for _, v := range *o.values { + ulimits = append(ulimits, v) + } + sort.SliceStable(ulimits, func(i, j int) bool { + return ulimits[i].Name < ulimits[j].Name + }) + return ulimits +} + +// Type returns the option type +func (o *UlimitOpt) Type() string { + return "ulimit" +} diff --git a/vendor/github.com/docker/cli/opts/weightdevice.go b/vendor/github.com/docker/cli/opts/weightdevice.go new file mode 100644 index 00000000..ee377fc3 --- /dev/null +++ b/vendor/github.com/docker/cli/opts/weightdevice.go @@ -0,0 +1,84 @@ +package opts + +import ( + "fmt" + "strconv" + "strings" + + "github.com/docker/docker/api/types/blkiodev" +) + +// ValidatorWeightFctType defines a validator function that returns a validated struct and/or an error. +type ValidatorWeightFctType func(val string) (*blkiodev.WeightDevice, error) + +// ValidateWeightDevice validates that the specified string has a valid device-weight format. +func ValidateWeightDevice(val string) (*blkiodev.WeightDevice, error) { + k, v, ok := strings.Cut(val, ":") + if !ok || k == "" { + return nil, fmt.Errorf("bad format: %s", val) + } + // TODO(thaJeztah): should we really validate this on the client? + if !strings.HasPrefix(k, "/dev/") { + return nil, fmt.Errorf("bad format for device path: %s", val) + } + weight, err := strconv.ParseUint(v, 10, 16) + if err != nil { + return nil, fmt.Errorf("invalid weight for device: %s", val) + } + if weight > 0 && (weight < 10 || weight > 1000) { + return nil, fmt.Errorf("invalid weight for device: %s", val) + } + + return &blkiodev.WeightDevice{ + Path: k, + Weight: uint16(weight), + }, nil +} + +// WeightdeviceOpt defines a map of WeightDevices +type WeightdeviceOpt struct { + values []*blkiodev.WeightDevice + validator ValidatorWeightFctType +} + +// NewWeightdeviceOpt creates a new WeightdeviceOpt +func NewWeightdeviceOpt(validator ValidatorWeightFctType) WeightdeviceOpt { + return WeightdeviceOpt{ + values: []*blkiodev.WeightDevice{}, + validator: validator, + } +} + +// Set validates a WeightDevice and sets its name as a key in WeightdeviceOpt +func (opt *WeightdeviceOpt) Set(val string) error { + var value *blkiodev.WeightDevice + if opt.validator != nil { + v, err := opt.validator(val) + if err != nil { + return err + } + value = v + } + opt.values = append(opt.values, value) + return nil +} + +// String returns WeightdeviceOpt values as a string. +func (opt *WeightdeviceOpt) String() string { + out := make([]string, 0, len(opt.values)) + for _, v := range opt.values { + out = append(out, v.String()) + } + + return fmt.Sprintf("%v", out) +} + +// GetList returns a slice of pointers to WeightDevices. +func (opt *WeightdeviceOpt) GetList() []*blkiodev.WeightDevice { + return opt.values +} + +// Type returns the option type +func (opt *WeightdeviceOpt) Type() string { + return "list" +} diff --git a/vendor/github.com/docker/cli/pkg/kvfile/kvfile.go b/vendor/github.com/docker/cli/pkg/kvfile/kvfile.go new file mode 100644 index 00000000..f6ac8ef4 --- /dev/null +++ b/vendor/github.com/docker/cli/pkg/kvfile/kvfile.go @@ -0,0 +1,130 @@ +// Package kvfile provides utilities to parse line-delimited key/value files +// such as used for label-files and env-files. +// +// # File format +// +// key/value files use the following syntax: +// +// - File must be valid UTF-8. +// - BOM headers are removed. +// - Leading whitespace is removed for each line. +// - Lines starting with "#" are ignored. +// - Empty lines are ignored. +// - Key/Value pairs are provided as "KEY[=]". +// - Maximum line-length is limited to [bufio.MaxScanTokenSize]. +// +// # Interpolation, substitution, and escaping +// +// Both keys and values are used as-is; no interpolation, substitution or +// escaping is supported, and quotes are considered part of the key or value. +// Whitespace in values (including leading and trailing) is preserved. Given +// that the file format is line-delimited, neither key, nor value, can contain +// newlines. +// +// # Key/Value pairs +// +// Key/Value pairs take the following format: +// +// KEY[=] +// +// KEY is required and may not contain whitespaces or NUL characters. Any +// other character (except for the "=" delimiter) are accepted, but it is +// recommended to use a subset of the POSIX portable character set, as +// outlined in [Environment Variables]. +// +// VALUE is optional, but may be empty. If no value is provided (i.e., no +// equal sign ("=") is present), the KEY is omitted in the result, but some +// functions accept a lookup-function to provide a default value for the +// given key. +// +// [Environment Variables]: https://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html +package kvfile + +import ( + "bufio" + "bytes" + "fmt" + "io" + "os" + "strings" + "unicode" + "unicode/utf8" +) + +// Parse parses a line-delimited key/value pairs separated by equal sign. +// It accepts a lookupFn to lookup default values for keys that do not define +// a value. An error is produced if parsing failed, the content contains invalid +// UTF-8 characters, or a key contains whitespaces. +func Parse(filename string, lookupFn func(key string) (value string, found bool)) ([]string, error) { + fh, err := os.Open(filename) + if err != nil { + return []string{}, err + } + out, err := parseKeyValueFile(fh, lookupFn) + _ = fh.Close() + if err != nil { + return []string{}, fmt.Errorf("invalid env file (%s): %v", filename, err) + } + return out, nil +} + +// ParseFromReader parses a line-delimited key/value pairs separated by equal sign. +// It accepts a lookupFn to lookup default values for keys that do not define +// a value. An error is produced if parsing failed, the content contains invalid +// UTF-8 characters, or a key contains whitespaces. +func ParseFromReader(r io.Reader, lookupFn func(key string) (value string, found bool)) ([]string, error) { + return parseKeyValueFile(r, lookupFn) +} + +const whiteSpaces = " \t" + +func parseKeyValueFile(r io.Reader, lookupFn func(string) (string, bool)) ([]string, error) { + lines := []string{} + scanner := bufio.NewScanner(r) + utf8bom := []byte{0xEF, 0xBB, 0xBF} + for currentLine := 1; scanner.Scan(); currentLine++ { + scannedBytes := scanner.Bytes() + if !utf8.Valid(scannedBytes) { + return []string{}, fmt.Errorf("invalid utf8 bytes at line %d: %v", currentLine, scannedBytes) + } + // We trim UTF8 BOM + if currentLine == 1 { + scannedBytes = bytes.TrimPrefix(scannedBytes, utf8bom) + } + // trim the line from all leading whitespace first. trailing whitespace + // is part of the value, and is kept unmodified. + line := strings.TrimLeftFunc(string(scannedBytes), unicode.IsSpace) + + if len(line) == 0 || line[0] == '#' { + // skip empty lines and comments (lines starting with '#') + continue + } + + key, _, hasValue := strings.Cut(line, "=") + if len(key) == 0 { + return []string{}, fmt.Errorf("no variable name on line '%s'", line) + } + + // leading whitespace was already removed from the line, but + // variables are not allowed to contain whitespace or have + // trailing whitespace. + if strings.ContainsAny(key, whiteSpaces) { + return []string{}, fmt.Errorf("variable '%s' contains whitespaces", key) + } + + if hasValue { + // key/value pair is valid and has a value; add the line as-is. + lines = append(lines, line) + continue + } + + if lookupFn != nil { + // No value given; try to look up the value. The value may be + // empty but if no value is found, the key is omitted. + if value, found := lookupFn(line); found { + lines = append(lines, key+"="+value) + } + } + } + return lines, scanner.Err() +} diff --git a/vendor/github.com/docker/docker/AUTHORS b/vendor/github.com/docker/docker/AUTHORS new file mode 100644 index 00000000..5f93eeb4 --- /dev/null +++ b/vendor/github.com/docker/docker/AUTHORS @@ -0,0 +1,2456 @@ +# File @generated by hack/generate-authors.sh. DO NOT EDIT. +# This file lists all contributors to the repository. +# See hack/generate-authors.sh to make modifications. + +Aanand Prasad +Aaron Davidson +Aaron Feng +Aaron Hnatiw +Aaron Huslage +Aaron L. Xu +Aaron Lehmann +Aaron Welch +Aaron Yoshitake +Abel Muiño +Abhijeet Kasurde +Abhinandan Prativadi +Abhinav Ajgaonkar +Abhishek Chanda +Abhishek Sharma +Abin Shahab +Abirdcfly +Ada Mancini +Adam Avilla +Adam Dobrawy +Adam Eijdenberg +Adam Kunk +Adam Miller +Adam Mills +Adam Pointer +Adam Singer +Adam Thornton +Adam Walz +Adam Williams +AdamKorcz +Addam Hardy +Aditi Rajagopal +Aditya +Adnan Khan +Adolfo Ochagavía +Adria Casas +Adrian Moisey +Adrian Mouat +Adrian Oprea +Adrien Folie +Adrien Gallouët +Ahmed Kamal +Ahmet Alp Balkan +Aidan Feldman +Aidan Hobson Sayers +AJ Bowen +Ajey Charantimath +ajneu +Akash Gupta +Akhil Mohan +Akihiro Matsushima +Akihiro Suda +Akim Demaille +Akira Koyasu +Akshay Karle +Akshay Moghe +Al Tobey +alambike +Alan Hoyle +Alan Scherger +Alan Thompson +Alano Terblanche +Albert Callarisa +Albert Zhang +Albin Kerouanton +Alec Benson +Alejandro González Hevia +Aleksa Sarai +Aleksandr Chebotov +Aleksandrs Fadins +Alena Prokharchyk +Alessandro Boch +Alessio Biancalana +Alex Chan +Alex Chen +Alex Coventry +Alex Crawford +Alex Ellis +Alex Gaynor +Alex Goodman +Alex Nordlund +Alex Olshansky +Alex Samorukov +Alex Stockinger +Alex Warhawk +Alexander Artemenko +Alexander Boyd +Alexander Larsson +Alexander Midlash +Alexander Morozov +Alexander Polakov +Alexander Shopov +Alexandre Beslic +Alexandre Garnier +Alexandre González +Alexandre Jomin +Alexandru Sfirlogea +Alexei Margasov +Alexey Guskov +Alexey Kotlyarov +Alexey Shamrin +Alexis Ries +Alexis Thomas +Alfred Landrum +Ali Dehghani +Alicia Lauerman +Alihan Demir +Allen Madsen +Allen Sun +almoehi +Alvaro Saurin +Alvin Deng +Alvin Richards +amangoel +Amen Belayneh +Ameya Gawde +Amir Goldstein +Amit Bakshi +Amit Krishnan +Amit Shukla +Amr Gawish +Amy Lindburg +Anand Patil +AnandkumarPatel +Anatoly Borodin +Anca Iordache +Anchal Agrawal +Anda Xu +Anders Janmyr +Andre Dublin <81dublin@gmail.com> +Andre Granovsky +Andrea Denisse Gómez +Andrea Luzzardi +Andrea Turli +Andreas Elvers +Andreas Köhler +Andreas Savvides +Andreas Tiefenthaler +Andrei Gherzan +Andrei Ushakov +Andrei Vagin +Andrew Baxter <423qpsxzhh8k3h@s.rendaw.me> +Andrew C. Bodine +Andrew Clay Shafer +Andrew Duckworth +Andrew France +Andrew Gerrand +Andrew Guenther +Andrew He +Andrew Hsu +Andrew Kim +Andrew Kuklewicz +Andrew Macgregor +Andrew Macpherson +Andrew Martin +Andrew McDonnell +Andrew Munsell +Andrew Pennebaker +Andrew Po +Andrew Weiss +Andrew Williams +Andrews Medina +Andrey Kolomentsev +Andrey Petrov +Andrey Stolbovsky +André Martins +Andy Chambers +andy diller +Andy Goldstein +Andy Kipp +Andy Lindeman +Andy Rothfusz +Andy Smith +Andy Wilson +Andy Zhang +Aneesh Kulkarni +Anes Hasicic +Angel Velazquez +Anil Belur +Anil Madhavapeddy +Ankit Jain +Ankush Agarwal +Anonmily +Anran Qiao +Anshul Pundir +Anthon van der Neut +Anthony Baire +Anthony Bishopric +Anthony Dahanne +Anthony Sottile +Anton Löfgren +Anton Nikitin +Anton Polonskiy +Anton Tiurin +Antonio Aguilar +Antonio Murdaca +Antonis Kalipetis +Antony Messerli +Anuj Bahuguna +Anuj Varma +Anusha Ragunathan +Anyu Wang +apocas +Arash Deshmeh +arcosx +ArikaChen +Arko Dasgupta +Arnaud Lefebvre +Arnaud Porterie +Arnaud Rebillout +Artem Khramov +Arthur Barr +Arthur Gautier +Artur Meyster +Arun Gupta +Asad Saeeduddin +Asbjørn Enge +Austin Vazquez +averagehuman +Avi Das +Avi Kivity +Avi Miller +Avi Vaid +Azat Khuyiyakhmetov +Bao Yonglei +Bardia Keyoumarsi +Barnaby Gray +Barry Allard +Bartłomiej Piotrowski +Bastiaan Bakker +Bastien Pascard +bdevloed +Bearice Ren +Ben Bonnefoy +Ben Firshman +Ben Golub +Ben Gould +Ben Hall +Ben Langfeld +Ben Lovy +Ben Sargent +Ben Severson +Ben Toews +Ben Wiklund +Benjamin Atkin +Benjamin Baker +Benjamin Boudreau +Benjamin Böhmke +Benjamin Wang +Benjamin Yolken +Benny Ng +Benoit Chesneau +Bernerd Schaefer +Bernhard M. Wiedemann +Bert Goethals +Bertrand Roussel +Bevisy Zhang +Bharath Thiruveedula +Bhiraj Butala +Bhumika Bayani +Bilal Amarni +Bill Wang +Billy Ridgway +Bily Zhang +Bin Liu +Bingshen Wang +Bjorn Neergaard +Blake Geno +Boaz Shuster +bobby abbott +Bojun Zhu +Boqin Qin +Boris Pruessmann +Boshi Lian +Bouke Haarsma +Boyd Hemphill +boynux +Bradley Cicenas +Bradley Wright +Brandon Liu +Brandon Philips +Brandon Rhodes +Brendan Dixon +Brennan Kinney <5098581+polarathene@users.noreply.github.com> +Brent Salisbury +Brett Higgins +Brett Kochendorfer +Brett Milford +Brett Randall +Brian (bex) Exelbierd +Brian Bland +Brian DeHamer +Brian Dorsey +Brian Flad +Brian Goff +Brian McCallister +Brian Olsen +Brian Schwind +Brian Shumate +Brian Torres-Gil +Brian Trump +Brice Jaglin +Briehan Lombaard +Brielle Broder +Bruno Bigras +Bruno Binet +Bruno Gazzera +Bruno Renié +Bruno Tavares +Bryan Bess +Bryan Boreham +Bryan Matsuo +Bryan Murphy +Burke Libbey +Byung Kang +Caleb Spare +Calen Pennington +Calvin Liu +Cameron Boehmer +Cameron Sparr +Cameron Spear +Campbell Allen +Candid Dauth +Cao Weiwei +Carl Henrik Lunde +Carl Loa Odin +Carl X. Su +Carlo Mion +Carlos Alexandro Becker +Carlos de Paula +Carlos Sanchez +Carol Fager-Higgins +Cary +Casey Bisson +Catalin Pirvu +Ce Gao +Cedric Davies +Cezar Sa Espinola +Chad Swenson +Chance Zibolski +Chander Govindarajan +Chanhun Jeong +Chao Wang +Charles Chan +Charles Hooper +Charles Law +Charles Lindsay +Charles Merriam +Charles Sarrazin +Charles Smith +Charlie Drage +Charlie Lewis +Chase Bolt +ChaYoung You +Chee Hau Lim +Chen Chao +Chen Chuanliang +Chen Hanxiao +Chen Min +Chen Mingjie +Chen Qiu +Cheng-mean Liu +Chengfei Shang +Chengguang Xu +Chentianze +Chenyang Yan +chenyuzhu +Chetan Birajdar +Chewey +Chia-liang Kao +Chiranjeevi Tirunagari +chli +Cholerae Hu +Chris Alfonso +Chris Armstrong +Chris Dias +Chris Dituri +Chris Fordham +Chris Gavin +Chris Gibson +Chris Khoo +Chris Kreussling (Flatbush Gardener) +Chris McKinnel +Chris McKinnel +Chris Price +Chris Seto +Chris Snow +Chris St. Pierre +Chris Stivers +Chris Swan +Chris Telfer +Chris Wahl +Chris Weyl +Chris White +Christian Becker +Christian Berendt +Christian Brauner +Christian Böhme +Christian Muehlhaeuser +Christian Persson +Christian Rotzoll +Christian Simon +Christian Stefanescu +Christoph Ziebuhr +Christophe Mehay +Christophe Troestler +Christophe Vidal +Christopher Biscardi +Christopher Crone +Christopher Currie +Christopher Jones +Christopher Latham +Christopher Petito +Christopher Rigor +Christy Norman +Chun Chen +Ciro S. Costa +Clayton Coleman +Clint Armstrong +Clinton Kitson +clubby789 +Cody Roseborough +Coenraad Loubser +Colin Dunklau +Colin Hebert +Colin Panisset +Colin Rice +Colin Walters +Collin Guarino +Colm Hally +companycy +Conor Evans +Corbin Coleman +Corey Farrell +Cory Forsyth +Cory Snider +cressie176 +Cristian Ariza +Cristian Staretu +cristiano balducci +Cristina Yenyxe Gonzalez Garcia +Cruceru Calin-Cristian +cui fliter +CUI Wei +Cuong Manh Le +Cyprian Gracz +Cyril F +Da McGrady +Daan van Berkel +Daehyeok Mun +Dafydd Crosby +dalanlan +Damian Smyth +Damien Nadé +Damien Nozay +Damjan Georgievski +Dan Anolik +Dan Buch +Dan Cotora +Dan Feldman +Dan Griffin +Dan Hirsch +Dan Keder +Dan Levy +Dan McPherson +Dan Plamadeala +Dan Stine +Dan Williams +Dani Hodovic +Dani Louca +Daniel Antlinger +Daniel Black +Daniel Dao +Daniel Exner +Daniel Farrell +Daniel Garcia +Daniel Gasienica +Daniel Grunwell +Daniel Helfand +Daniel Hiltgen +Daniel J Walsh +Daniel Menet +Daniel Mizyrycki +Daniel Nephin +Daniel Norberg +Daniel Nordberg +Daniel P. Berrangé +Daniel Robinson +Daniel S +Daniel Sweet +Daniel Von Fange +Daniel Watkins +Daniel X Moore +Daniel YC Lin +Daniel Zhang +Daniele Rondina +Danny Berger +Danny Milosavljevic +Danny Yates +Danyal Khaliq +Darren Coxall +Darren Shepherd +Darren Stahl +Dattatraya Kumbhar +Davanum Srinivas +Dave Barboza +Dave Goodchild +Dave Henderson +Dave MacDonald +Dave Tucker +David Anderson +David Bellotti +David Calavera +David Chung +David Corking +David Cramer +David Currie +David Davis +David Dooling +David Gageot +David Gebler +David Glasser +David Karlsson <35727626+dvdksn@users.noreply.github.com> +David Lawrence +David Lechner +David M. Karr +David Mackey +David Manouchehri +David Mat +David Mcanulty +David McKay +David O'Rourke +David P Hilton +David Pelaez +David R. Jenni +David Röthlisberger +David Sheets +David Sissitka +David Trott +David Wang <00107082@163.com> +David Williamson +David Xia +David Young +Davide Ceretti +Dawn Chen +dbdd +dcylabs +Debayan De +Deborah Gertrude Digges +deed02392 +Deep Debroy +Deng Guangxing +Deni Bertovic +Denis Defreyne +Denis Gladkikh +Denis Ollier +Dennis Chen +Dennis Chen +Dennis Docter +Derek +Derek +Derek Ch +Derek McGowan +Deric Crago +Deshi Xiao +Devon Estes +Devvyn Murphy +Dharmit Shah +Dhawal Yogesh Bhanushali +Dhilip Kumars +Diego Romero +Diego Siqueira +Dieter Reuter +Dillon Dixon +Dima Stopel +Dimitri John Ledkov +Dimitris Mandalidis +Dimitris Rozakis +Dimitry Andric +Dinesh Subhraveti +Ding Fei +dingwei +Diogo Monica +DiuDiugirl +Djibril Koné +Djordje Lukic +dkumor +Dmitri Logvinenko +Dmitri Shuralyov +Dmitry Demeshchuk +Dmitry Gusev +Dmitry Kononenko +Dmitry Sharshakov +Dmitry Shyshkin +Dmitry Smirnov +Dmitry V. Krivenok +Dmitry Vorobev +Dmytro Iakovliev +docker-unir[bot] +Dolph Mathews +Dominic Tubach +Dominic Yin +Dominik Dingel +Dominik Finkbeiner +Dominik Honnef +Don Kirkby +Don Kjer +Don Spaulding +Donald Huang +Dong Chen +Donghwa Kim +Donovan Jones +Dorin Geman +Doron Podoleanu +Doug Davis +Doug MacEachern +Doug Tangren +Douglas Curtis +Dr Nic Williams +dragon788 +Dražen Lučanin +Drew Erny +Drew Hubl +Dustin Sallings +Ed Costello +Edmund Wagner +Eiichi Tsukata +Eike Herzbach +Eivin Giske Skaaren +Eivind Uggedal +Elan Ruusamäe +Elango Sivanandam +Elena Morozova +Eli Uriegas +Elias Faxö +Elias Koromilas +Elias Probst +Elijah Zupancic +eluck +Elvir Kuric +Emil Davtyan +Emil Hernvall +Emily Maier +Emily Rose +Emir Ozer +Eng Zer Jun +Enguerran +Enrico Weigelt, metux IT consult +Eohyung Lee +epeterso +er0k +Eric Barch +Eric Curtin +Eric G. Noriega +Eric Hanchrow +Eric Lee +Eric Mountain +Eric Myhre +Eric Paris +Eric Rafaloff +Eric Rosenberg +Eric Sage +Eric Soderstrom +Eric Yang +Eric-Olivier Lamey +Erica Windisch +Erich Cordoba +Erik Bray +Erik Dubbelboer +Erik Hollensbe +Erik Inge Bolsø +Erik Kristensen +Erik Sipsma +Erik Sjölund +Erik St. Martin +Erik Weathers +Erno Hopearuoho +Erwin van der Koogh +Espen Suenson +Ethan Bell +Ethan Mosbaugh +Euan Harris +Euan Kemp +Eugen Krizo +Eugene Yakubovich +Evan Allrich +Evan Carmi +Evan Hazlett +Evan Krall +Evan Lezar +Evan Phoenix +Evan Wies +Evelyn Xu +Everett Toews +Evgeniy Makhrov +Evgeny Shmarnev +Evgeny Vereshchagin +Ewa Czechowska +Eystein Måløy Stenberg +ezbercih +Ezra Silvera +Fabian Kramm +Fabian Lauer +Fabian Raetz +Fabiano Rosas +Fabio Falci +Fabio Kung +Fabio Rapposelli +Fabio Rehm +Fabrizio Regini +Fabrizio Soppelsa +Faiz Khan +falmp +Fangming Fang +Fangyuan Gao <21551127@zju.edu.cn> +fanjiyun +Fareed Dudhia +Fathi Boudra +Federico Gimenez +Felipe Oliveira +Felipe Ruhland +Felix Abecassis +Felix Geisendörfer +Felix Hupfeld +Felix Rabe +Felix Ruess +Felix Schindler +Feng Yan +Fengtu Wang +Ferenc Szabo +Fernando +Fero Volar +Feroz Salam +Ferran Rodenas +Filipe Brandenburger +Filipe Oliveira +Filipe Pina +Flavio Castelli +Flavio Crisciani +Florian +Florian Klein +Florian Maier +Florian Noeding +Florian Schmaus +Florian Weingarten +Florin Asavoaie +Florin Patan +fonglh +Foysal Iqbal +Francesc Campoy +Francesco Degrassi +Francesco Mari +Francis Chuang +Francisco Carriedo +Francisco Souza +Frank Groeneveld +Frank Herrmann +Frank Macreery +Frank Rosquin +Frank Villaro-Dixon +Frank Yang +Fred Lifton +Frederick F. Kautz IV +Frederico F. de Oliveira +Frederik Loeffert +Frederik Nordahl Jul Sabroe +Freek Kalter +Frieder Bluemle +frobnicaty <92033765+frobnicaty@users.noreply.github.com> +Frédéric Dalleau +Fu JinLin +Félix Baylac-Jacqué +Félix Cantournet +Gabe Rosenhouse +Gabor Nagy +Gabriel Adrian Samfira +Gabriel Goller +Gabriel L. Somlo +Gabriel Linder +Gabriel Monroy +Gabriel Nicolas Avellaneda +Gabriel Tomitsuka +Gaetan de Villele +Galen Sampson +Gang Qiao +Gareth Rushgrove +Garrett Barboza +Gary Schaetz +Gaurav +Gaurav Singh +Gaël PORTAY +Genki Takiuchi +GennadySpb +Geoff Levand +Geoffrey Bachelet +Geon Kim +George Kontridze +George Ma +George MacRorie +George Xie +Georgi Hristozov +Georgy Yakovlev +Gereon Frey +German DZ +Gert van Valkenhoef +Gerwim Feiken +Ghislain Bourgeois +Giampaolo Mancini +Gianluca Borello +Gildas Cuisinier +Giovan Isa Musthofa +gissehel +Giuseppe Mazzotta +Giuseppe Scrivano +Gleb Fotengauer-Malinovskiy +Gleb M Borisov +Glyn Normington +GoBella +Goffert van Gool +Goldwyn Rodrigues +Gopikannan Venugopalsamy +Gosuke Miyashita +Gou Rao +Govinda Fichtner +Grant Millar +Grant Reaber +Graydon Hoare +Greg Fausak +Greg Pflaum +Greg Stephens +Greg Thornton +Grzegorz Jaśkiewicz +Guilhem Lettron +Guilherme Salgado +Guillaume Dufour +Guillaume J. Charmes +Gunadhya S. <6939749+gunadhya@users.noreply.github.com> +Guoqiang QI +guoxiuyan +Guri +Gurjeet Singh +Guruprasad +Gustav Sinder +gwx296173 +Günter Zöchbauer +Haichao Yang +haikuoliu +haining.cao +Hakan Özler +Hamish Hutchings +Hannes Ljungberg +Hans Kristian Flaatten +Hans Rødtang +Hao Shu Wei +Hao Zhang <21521210@zju.edu.cn> +Harald Albers +Harald Niesche +Harley Laue +Harold Cooper +Harrison Turton +Harry Zhang +Harshal Patil +Harshal Patil +He Simei +He Xiaoxi +He Xin +heartlock <21521209@zju.edu.cn> +Hector Castro +Helen Xie +Henning Sprang +Hiroshi Hatake +Hiroyuki Sasagawa +Hobofan +Hollie Teal +Hong Xu +Hongbin Lu +Hongxu Jia +Honza Pokorny +Hsing-Hui Hsu +Hsing-Yu (David) Chen +hsinko <21551195@zju.edu.cn> +Hu Keping +Hu Tao +Huajin Tong +huang-jl <1046678590@qq.com> +HuanHuan Ye +Huanzhong Zhang +Huayi Zhang +Hugo Barrera +Hugo Duncan +Hugo Marisco <0x6875676f@gmail.com> +Hui Kang +Hunter Blanks +huqun +Huu Nguyen +Hyeongkyu Lee +Hyzhou Zhy +Iago López Galeiras +Ian Bishop +Ian Bull +Ian Calvert +Ian Campbell +Ian Chen +Ian Lee +Ian Main +Ian Philpot +Ian Truslove +Iavael +Icaro Seara +Ignacio Capurro +Igor Dolzhikov +Igor Karpovich +Iliana Weller +Ilkka Laukkanen +Illia Antypenko +Illo Abdulrahim +Ilya Dmitrichenko +Ilya Gusev +Ilya Khlopotov +imalasong <2879499479@qq.com> +imre Fitos +inglesp +Ingo Gottwald +Innovimax +Isaac Dupree +Isabel Jimenez +Isaiah Grace +Isao Jonas +Iskander Sharipov +Ivan Babrou +Ivan Fraixedes +Ivan Grcic +Ivan Markin +J Bruni +J. Nunn +Jack Danger Canty +Jack Laxson +Jack Walker <90711509+j2walker@users.noreply.github.com> +Jacob Atzen +Jacob Edelman +Jacob Tomlinson +Jacob Vallejo +Jacob Wen +Jaime Cepeda +Jaivish Kothari +Jake Champlin +Jake Moshenko +Jake Sanders +Jakub Drahos +Jakub Guzik +James Allen +James Carey +James Carr +James DeFelice +James Harrison Fisher +James Kyburz +James Kyle +James Lal +James Mills +James Nesbitt +James Nugent +James Sanders +James Turnbull +James Watkins-Harvey +Jamie Hannaford +Jamshid Afshar +Jan Breig +Jan Chren +Jan Garcia +Jan Götte +Jan Keromnes +Jan Koprowski +Jan Pazdziora +Jan Toebes +Jan-Gerd Tenberge +Jan-Jaap Driessen +Jana Radhakrishnan +Jannick Fahlbusch +Januar Wayong +Jared Biel +Jared Hocutt +Jaroslav Jindrak +Jaroslaw Zabiello +Jasmine Hegman +Jason A. Donenfeld +Jason Divock +Jason Giedymin +Jason Green +Jason Hall +Jason Heiss +Jason Livesay +Jason McVetta +Jason Plum +Jason Shepherd +Jason Smith +Jason Sommer +Jason Stangroome +Jasper Siepkes +Javier Bassi +jaxgeller +Jay +Jay Kamat +Jay Lim +Jean Rouge +Jean-Baptiste Barth +Jean-Baptiste Dalido +Jean-Christophe Berthon +Jean-Michel Rouet +Jean-Paul Calderone +Jean-Pierre Huynh +Jean-Tiare Le Bigot +Jeeva S. Chelladhurai +Jeff Anderson +Jeff Hajewski +Jeff Johnston +Jeff Lindsay +Jeff Mickey +Jeff Minard +Jeff Nickoloff +Jeff Silberman +Jeff Welch +Jeff Zvier +Jeffrey Bolle +Jeffrey Morgan +Jeffrey van Gogh +Jenny Gebske +Jeongseok Kang +Jeremy Chambers +Jeremy Grosser +Jeremy Huntwork +Jeremy Price +Jeremy Qian +Jeremy Unruh +Jeremy Yallop +Jeroen Franse +Jeroen Jacobs +Jesse Dearing +Jesse Dubay +Jessica Frazelle +Jeyanthinath Muthuram +Jezeniel Zapanta +Jhon Honce +Ji.Zhilong +Jian Liao +Jian Zeng +Jian Zhang +Jiang Jinyang +Jianyong Wu +Jie Luo +Jie Ma +Jihyun Hwang +Jilles Oldenbeuving +Jim Alateras +Jim Carroll +Jim Ehrismann +Jim Galasyn +Jim Lin +Jim Minter +Jim Perrin +Jimmy Cuadra +Jimmy Puckett +Jimmy Song +Jinsoo Park +Jintao Zhang +Jiri Appl +Jiri Popelka +Jiuyue Ma +Jiří Župka +Joakim Roubert +Joao Fernandes +Joao Trindade +Joe Beda +Joe Doliner +Joe Ferguson +Joe Gordon +Joe Shaw +Joe Van Dyk +Joel Friedly +Joel Handwell +Joel Hansson +Joel Wurtz +Joey Geiger +Joey Geiger +Joey Gibson +Joffrey F +Johan Euphrosine +Johan Rydberg +Johanan Lieberman +Johannes 'fish' Ziemke +John Costa +John Feminella +John Gardiner Myers +John Gossman +John Harris +John Howard +John Laswell +John Maguire +John Mulhausen +John OBrien III +John Starks +John Stephens +John Tims +John V. Martinez +John Warwick +John Willis +Jon Johnson +Jon Surrell +Jon Wedaman +Jonas Dohse +Jonas Geiler +Jonas Heinrich +Jonas Pfenniger +Jonathan A. Schweder +Jonathan A. Sternberg +Jonathan Boulle +Jonathan Camp +Jonathan Choy +Jonathan Dowland +Jonathan Lebon +Jonathan Lomas +Jonathan McCrohan +Jonathan Mueller +Jonathan Pares +Jonathan Rudenberg +Jonathan Stoppani +Jonh Wendell +Joni Sar +Joost Cassee +Jordan Arentsen +Jordan Jennings +Jordan Sissel +Jordi Massaguer Pla +Jorge Marin +Jorit Kleine-Möllhoff +Jose Diaz-Gonzalez +Joseph Anthony Pasquale Holsten +Joseph Hager +Joseph Kern +Joseph Rothrock +Josh +Josh Bodah +Josh Bonczkowski +Josh Chorlton +Josh Eveleth +Josh Hawn +Josh Horwitz +Josh Poimboeuf +Josh Soref +Josh Wilson +Josiah Kiehl +José Tomás Albornoz +Joyce Jang +JP +Julian Taylor +Julien Barbier +Julien Bisconti +Julien Bordellier +Julien Dubois +Julien Kassar +Julien Maitrehenry +Julien Pervillé +Julien Pivotto +Julio Guerra +Julio Montes +Jun Du +Jun-Ru Chang +junxu +Jussi Nummelin +Justas Brazauskas +Justen Martin +Justin Chadwell +Justin Cormack +Justin Force +Justin Keller <85903732+jk-vb@users.noreply.github.com> +Justin Menga +Justin Plock +Justin Simonelis +Justin Terry +Justyn Temme +Jyrki Puttonen +Jérémy Leherpeur +Jérôme Petazzoni +Jörg Thalheim +K. Heller +Kai Blin +Kai Qiang Wu (Kennan) +Kaijie Chen +Kamil Domański +Kamjar Gerami +Kanstantsin Shautsou +Kara Alexandra +Karan Lyons +Kareem Khazem +kargakis +Karl Grzeszczak +Karol Duleba +Karthik Karanth +Karthik Nayak +Kasper Fabæch Brandt +Kate Heddleston +Katie McLaughlin +Kato Kazuyoshi +Katrina Owen +Kawsar Saiyeed +Kay Yan +kayrus +Kazuhiro Sera +Kazuyoshi Kato +Ke Li +Ke Xu +Kei Ohmura +Keith Hudgins +Keli Hu +Ken Bannister +Ken Cochrane +Ken Herner +Ken ICHIKAWA +Ken Reese +Kenfe-Mickaël Laventure +Kenjiro Nakayama +Kent Johnson +Kenta Tada +Kevin "qwazerty" Houdebert +Kevin Alvarez +Kevin Burke +Kevin Clark +Kevin Feyrer +Kevin J. Lynagh +Kevin Jing Qiu +Kevin Kern +Kevin Menard +Kevin Meredith +Kevin P. Kucharczyk +Kevin Parsons +Kevin Richardson +Kevin Shi +Kevin Wallace +Kevin Yap +Keyvan Fatehi +kies +Kim BKC Carlbacker +Kim Eik +Kimbro Staken +Kir Kolyshkin +Kiran Gangadharan +Kirill SIbirev +Kirk Easterson +knappe +Kohei Tsuruta +Koichi Shiraishi +Konrad Kleine +Konrad Ponichtera +Konstantin Gribov +Konstantin L +Konstantin Pelykh +Kostadin Plachkov +kpcyrd +Krasi Georgiev +Krasimir Georgiev +Kris-Mikael Krister +Kristian Haugene +Kristina Zabunova +Krystian Wojcicki +Kunal Kushwaha +Kunal Tyagi +Kyle Conroy +Kyle Linden +Kyle Squizzato +Kyle Wuolle +kyu +Lachlan Coote +Lai Jiangshan +Lajos Papp +Lakshan Perera +Lalatendu Mohanty +Lance Chen +Lance Kinley +Lars Andringa +Lars Butler +Lars Kellogg-Stedman +Lars R. Damerow +Lars-Magnus Skog +Laszlo Meszaros +Laura Brehm +Laura Frank +Laurent Bernaille +Laurent Erignoux +Laurie Voss +Leandro Motta Barros +Leandro Siqueira +Lee Calcote +Lee Chao <932819864@qq.com> +Lee, Meng-Han +Lei Gong +Lei Jitang +Leiiwang +Len Weincier +Lennie +Leo Gallucci +Leonardo Nodari +Leonardo Taccari +Leszek Kowalski +Levi Blackstone +Levi Gross +Levi Harrison +Lewis Daly +Lewis Marshall +Lewis Peckover +Li Yi +Liam Macgillavry +Liana Lo +Liang Mingqiang +Liang-Chi Hsieh +liangwei +Liao Qingwei +Lifubang +Lihua Tang +Lily Guo +limeidan +Lin Lu +LingFaKe +Linus Heckemann +Liran Tal +Liron Levin +Liu Bo +Liu Hua +liwenqi +lixiaobing10051267 +Liz Zhang +LIZAO LI +Lizzie Dixon <_@lizzie.io> +Lloyd Dewolf +Lokesh Mandvekar +longliqiang88 <394564827@qq.com> +Lorenz Leutgeb +Lorenzo Fontana +Lotus Fenn +Louis Delossantos +Louis Opter +Luboslav Pivarc +Luca Favatella +Luca Marturana +Luca Orlandi +Luca-Bogdan Grigorescu +Lucas Chan +Lucas Chi +Lucas Molas +Lucas Silvestre +Luciano Mores +Luis Henrique Mulinari +Luis Martínez de Bartolomé Izquierdo +Luiz Svoboda +Lukas Heeren +Lukas Waslowski +lukaspustina +Lukasz Zajaczkowski +Luke Marsden +Lyn +Lynda O'Leary +Lénaïc Huard +Ma Müller +Ma Shimiao +Mabin +Madhan Raj Mookkandy +Madhav Puri +Madhu Venugopal +Mageee +Mahesh Tiyyagura +malnick +Malte Janduda +Manfred Touron +Manfred Zabarauskas +Manjunath A Kumatagi +Mansi Nahar +Manuel Meurer +Manuel Rüger +Manuel Woelker +mapk0y +Marat Radchenko +Marc Abramowitz +Marc Kuo +Marc Tamsky +Marcel Edmund Franke +Marcelo Horacio Fortino +Marcelo Salazar +Marco Hennings +Marcus Cobden +Marcus Farkas +Marcus Linke +Marcus Martins +Marcus Ramberg +Marek Goldmann +Marian Marinov +Marianna Tessel +Mario Loriedo +Marius Gundersen +Marius Sturm +Marius Voila +Mark Allen +Mark Feit +Mark Jeromin +Mark McGranaghan +Mark McKinstry +Mark Milstein +Mark Oates +Mark Parker +Mark Vainomaa +Mark West +Markan Patel +Marko Mikulicic +Marko Tibold +Markus Fix +Markus Kortlang +Martijn Dwars +Martijn van Oosterhout +Martin Braun +Martin Dojcak +Martin Honermeyer +Martin Jirku +Martin Kelly +Martin Mosegaard Amdisen +Martin Muzatko +Martin Redmond +Maru Newby +Mary Anthony +Masahito Zembutsu +Masato Ohba +Masayuki Morita +Mason Malone +Mateusz Sulima +Mathias Monnerville +Mathieu Champlon +Mathieu Le Marec - Pasquet +Mathieu Parent +Mathieu Paturel +Matt Apperson +Matt Bachmann +Matt Bajor +Matt Bentley +Matt Haggard +Matt Hoyle +Matt McCormick +Matt Moore +Matt Morrison <3maven@gmail.com> +Matt Richardson +Matt Rickard +Matt Robenolt +Matt Schurenko +Matt Williams +Matthew Heon +Matthew Lapworth +Matthew Mayer +Matthew Mosesohn +Matthew Mueller +Matthew Riley +Matthias Klumpp +Matthias Kühnle +Matthias Rampke +Matthieu Fronton +Matthieu Hauglustaine +Mattias Jernberg +Mauricio Garavaglia +mauriyouth +Max Harmathy +Max Shytikov +Max Timchenko +Maxim Fedchyshyn +Maxim Ivanov +Maxim Kulkin +Maxim Treskin +Maxime Petazzoni +Maximiliano Maccanti +Maxwell +Meaglith Ma +meejah +Megan Kostick +Mehul Kar +Mei ChunTao +Mengdi Gao +Menghui Chen +Mert Yazıcıoğlu +mgniu +Micah Zoltu +Michael A. Smith +Michael Beskin +Michael Bridgen +Michael Brown +Michael Chiang +Michael Crosby +Michael Currie +Michael Friis +Michael Gorsuch +Michael Grauer +Michael Holzheu +Michael Hudson-Doyle +Michael Huettermann +Michael Irwin +Michael Kebe +Michael Kuehn +Michael Käufl +Michael Neale +Michael Nussbaum +Michael Prokop +Michael Scharf +Michael Spetsiotis +Michael Stapelberg +Michael Steinert +Michael Thies +Michael Weidmann +Michael West +Michael Zhao +Michal Fojtik +Michal Gebauer +Michal Jemala +Michal Kostrzewa +Michal Minář +Michal Rostecki +Michal Wieczorek +Michaël Pailloncy +Michał Czeraszkiewicz +Michał Gryko +Michał Kosek +Michiel de Jong +Mickaël Fortunato +Mickaël Remars +Miguel Angel Fernández +Miguel Morales +Miguel Perez +Mihai Borobocea +Mihuleacc Sergiu +Mikael Davranche +Mike Brown +Mike Bush +Mike Casas +Mike Chelen +Mike Danese +Mike Dillon +Mike Dougherty +Mike Estes +Mike Gaffney +Mike Goelzer +Mike Leone +Mike Lundy +Mike MacCana +Mike Naberezny +Mike Snitzer +Mike Sul +mikelinjie <294893458@qq.com> +Mikhail Sobolev +Miklos Szegedi +Milas Bowman +Milind Chawre +Miloslav Trmač +mingqing +Mingzhen Feng +Misty Stanley-Jones +Mitch Capper +Mizuki Urushida +mlarcher +Mohammad Banikazemi +Mohammad Nasirifar +Mohammed Aaqib Ansari +Mohd Sadiq +Mohit Soni +Moorthy RS +Morgan Bauer +Morgante Pell +Morgy93 +Morten Siebuhr +Morton Fox +Moysés Borges +mrfly +Mrunal Patel +Muayyad Alsadi +Muhammad Zohaib Aslam +Mustafa Akın +Muthukumar R +Máximo Cuadros +Médi-Rémi Hashim +Nace Oroz +Nahum Shalman +Nakul Pathak +Nalin Dahyabhai +Nan Monnand Deng +Naoki Orii +Natalie Parker +Natanael Copa +Natasha Jarus +Nate Brennand +Nate Eagleson +Nate Jones +Nathan Carlson +Nathan Herald +Nathan Hsieh +Nathan Kleyn +Nathan LeClaire +Nathan McCauley +Nathan Williams +Naveed Jamil +Neal McBurnett +Neil Horman +Neil Peterson +Nelson Chen +Neyazul Haque +Nghia Tran +Niall O'Higgins +Nicholas E. Rabenau +Nick Adcock +Nick DeCoursin +Nick Irvine +Nick Neisen +Nick Parker +Nick Payne +Nick Russo +Nick Santos +Nick Stenning +Nick Stinemates +Nick Wood +NickrenREN +Nicola Kabar +Nicolas Borboën +Nicolas De Loof +Nicolas Dudebout +Nicolas Goy +Nicolas Kaiser +Nicolas Sterchele +Nicolas V Castet +Nicolás Hock Isaza +Niel Drummond +Nigel Poulton +Nik Nyby +Nikhil Chawla +NikolaMandic +Nikolas Garofil +Nikolay Edigaryev +Nikolay Milovanov +ningmingxiao +Nirmal Mehta +Nishant Totla +NIWA Hideyuki +Noah Meyerhans +Noah Treuhaft +NobodyOnSE +noducks +Nolan Darilek +Nolan Miles +Noriki Nakamura +nponeccop +Nurahmadie +Nuutti Kotivuori +nzwsch +O.S. Tezer +objectified +Odin Ugedal +Oguz Bilgic +Oh Jinkyun +Ohad Schneider +ohmystack +Ole Reifschneider +Oliver Neal +Oliver Reason +Olivier Gambier +Olle Jonsson +Olli Janatuinen +Olly Pomeroy +Omri Shiv +Onur Filiz +Oriol Francès +Oscar Bonilla <6f6231@gmail.com> +oscar.chen <2972789494@qq.com> +Oskar Niburski +Otto Kekäläinen +Ouyang Liduo +Ovidio Mallo +Panagiotis Moustafellos +Paolo G. Giarrusso +Pascal +Pascal Bach +Pascal Borreli +Pascal Hartig +Patrick Böänziger +Patrick Devine +Patrick Haas +Patrick Hemmer +Patrick St. laurent +Patrick Stapleton +Patrik Cyvoct +pattichen +Paul "TBBle" Hampson +Paul +paul +Paul Annesley +Paul Bellamy +Paul Bowsher +Paul Furtado +Paul Hammond +Paul Jimenez +Paul Kehrer +Paul Lietar +Paul Liljenberg +Paul Morie +Paul Nasrat +Paul Seiffert +Paul Weaver +Paulo Gomes +Paulo Ribeiro +Pavel Lobashov +Pavel Matěja +Pavel Pletenev +Pavel Pospisil +Pavel Sutyrin +Pavel Tikhomirov +Pavlos Ratis +Pavol Vargovcik +Pawel Konczalski +Paweł Gronowski +payall4u +Peeyush Gupta +Peggy Li +Pei Su +Peng Tao +Penghan Wang +Per Weijnitz +perhapszzy@sina.com +Pete Woods +Peter Bourgon +Peter Braden +Peter Bücker +Peter Choi +Peter Dave Hello +Peter Edge +Peter Ericson +Peter Esbensen +Peter Jaffe +Peter Kang +Peter Malmgren +Peter Salvatore +Peter Volpe +Peter Waller +Petr Švihlík +Petros Angelatos +Phil +Phil Estes +Phil Sphicas +Phil Spitler +Philip Alexander Etling +Philip K. Warren +Philip Monroe +Philipp Fruck +Philipp Gillé +Philipp Wahala +Philipp Weissensteiner +Phillip Alexander +phineas +pidster +Piergiuliano Bossi +Pierre +Pierre Carrier +Pierre Dal-Pra +Pierre Wacrenier +Pierre-Alain RIVIERE +Piotr Bogdan +Piotr Karbowski +Porjo +Poul Kjeldager Sørensen +Pradeep Chhetri +Pradip Dhara +Pradipta Kr. Banerjee +Prasanna Gautam +Pratik Karki +Prayag Verma +Priya Wadhwa +Projjol Banerji +Przemek Hejman +Puneet Pruthi +Pure White +pysqz +Qiang Huang +Qin TianHuan +Qinglan Peng +Quan Tian +qudongfang +Quentin Brossard +Quentin Perez +Quentin Tayssier +r0n22 +Rachit Sharma +Radostin Stoyanov +Rafal Jeczalik +Rafe Colton +Raghavendra K T +Raghuram Devarakonda +Raja Sami +Rajat Pandit +Rajdeep Dua +Ralf Sippl +Ralle +Ralph Bean +Ramkumar Ramachandra +Ramon Brooker +Ramon van Alteren +RaviTeja Pothana +Ray Tsang +ReadmeCritic +realityone +Recursive Madman +Reficul +Regan McCooey +Remi Rampin +Remy Suen +Renato Riccieri Santos Zannon +Renaud Gaubert +Rhys Hiltner +Ri Xu +Ricardo N Feliciano +Rich Horwood +Rich Moyse +Rich Seymour +Richard Burnison +Richard Hansen +Richard Harvey +Richard Mathie +Richard Metzler +Richard Scothern +Richo Healey +Rick Bradley +Rick van de Loo +Rick Wieman +Rik Nijessen +Riku Voipio +Riley Guerin +Ritesh H Shukla +Riyaz Faizullabhoy +Rob Cowsill <42620235+rcowsill@users.noreply.github.com> +Rob Gulewich +Rob Murray +Rob Vesse +Robert Bachmann +Robert Bittle +Robert Obryk +Robert Schneider +Robert Shade +Robert Stern +Robert Terhaar +Robert Wallis +Robert Wang +Roberto G. Hashioka +Roberto Muñoz Fernández +Robin Naundorf +Robin Schneider +Robin Speekenbrink +Robin Thoni +robpc +Rodolfo Carvalho +Rodrigo Campos +Rodrigo Vaz +Roel Van Nyen +Roger Peppe +Rohit Jnagal +Rohit Kadam +Rohit Kapur +Rojin George +Roland Huß +Roland Kammerer +Roland Moriz +Roma Sokolov +Roman Dudin +Roman Mazur +Roman Strashkin +Roman Volosatovs +Roman Zabaluev +Ron Smits +Ron Williams +Rong Gao +Rong Zhang +Rongxiang Song +Rony Weng +root +root +root +root +Rory Hunter +Rory McCune +Ross Boucher +Rovanion Luckey +Roy Reznik +Royce Remer +Rozhnov Alexandr +Rudolph Gottesheim +Rui Cao +Rui JingAn +Rui Lopes +Ruilin Li +Runshen Zhu +Russ Magee +Ryan Abrams +Ryan Anderson +Ryan Aslett +Ryan Barry +Ryan Belgrave +Ryan Campbell +Ryan Detzel +Ryan Fowler +Ryan Liu +Ryan McLaughlin +Ryan O'Donnell +Ryan Seto +Ryan Shea +Ryan Simmen +Ryan Stelly +Ryan Thomas +Ryan Trauntvein +Ryan Wallner +Ryan Zhang +ryancooper7 +RyanDeng +Ryo Nakao +Ryoga Saito +Régis Behmo +Rémy Greinhofer +s. rannou +Sabin Basyal +Sachin Joshi +Sagar Hani +Sainath Grandhi +Sakeven Jiang +Salahuddin Khan +Sally O'Malley +Sam Abed +Sam Alba +Sam Bailey +Sam J Sharpe +Sam Neirinck +Sam Reis +Sam Rijs +Sam Thibault +Sam Whited +Sambuddha Basu +Sami Wagiaalla +Samuel Andaya +Samuel Dion-Girardeau +Samuel Karp +Samuel PHAN +sanchayanghosh +Sandeep Bansal +Sankar சங்கர் +Sanket Saurav +Santhosh Manohar +sapphiredev +Sargun Dhillon +Sascha Andres +Sascha Grunert +SataQiu +Satnam Singh +Satoshi Amemiya +Satoshi Tagomori +Scott Bessler +Scott Collier +Scott Johnston +Scott Moser +Scott Percival +Scott Stamp +Scott Walls +sdreyesg +Sean Christopherson +Sean Cronin +Sean Lee +Sean McIntyre +Sean OMeara +Sean P. Kane +Sean Rodman +Sebastiaan van Steenis +Sebastiaan van Stijn +Sebastian Höffner +Sebastian Radloff +Sebastian Thomschke +Sebastien Goasguen +Senthil Kumar Selvaraj +Senthil Kumaran +SeongJae Park +Seongyeol Lim +Serge Hallyn +Sergey Alekseev +Sergey Evstifeev +Sergii Kabashniuk +Sergio Lopez +Serhat Gülçiçek +Serhii Nakon +SeungUkLee +Sevki Hasirci +Shane Canon +Shane da Silva +Shaun Kaasten +shaunol +Shawn Landden +Shawn Siefkas +shawnhe +Shayan Pooya +Shayne Wang +Shekhar Gulati +Sheng Yang +Shengbo Song +Shengjing Zhu +Shev Yan +Shih-Yuan Lee +Shihao Xia +Shijiang Wei +Shijun Qin +Shishir Mahajan +Shoubhik Bose +Shourya Sarcar +Shu-Wai Chow +shuai-z +Shukui Yang +Sian Lerk Lau +Siarhei Rasiukevich +Sidhartha Mani +sidharthamani +Silas Sewell +Silvan Jegen +Simão Reis +Simon Barendse +Simon Eskildsen +Simon Ferquel +Simon Leinen +Simon Menke +Simon Taranto +Simon Vikstrom +Sindhu S +Sjoerd Langkemper +skanehira +Smark Meng +Solganik Alexander +Solomon Hykes +Song Gao +Soshi Katsuta +Sotiris Salloumis +Soulou +Spencer Brown +Spencer Smith +Spike Curtis +Sridatta Thatipamala +Sridhar Ratnakumar +Srini Brahmaroutu +Srinivasan Srivatsan +Staf Wagemakers +Stanislav Bondarenko +Stanislav Levin +Steeve Morin +Stefan Berger +Stefan Gehrig +Stefan J. Wernli +Stefan Praszalowicz +Stefan S. +Stefan Scherer +Stefan Staudenmeyer +Stefan Weil +Steffen Butzer +Stephan Henningsen +Stephan Spindler +Stephen Benjamin +Stephen Crosby +Stephen Day +Stephen Drake +Stephen Rust +Steve Desmond +Steve Dougherty +Steve Durrheimer +Steve Francia +Steve Koch +Steven Burgess +Steven Erenst +Steven Hartland +Steven Iveson +Steven Merrill +Steven Richards +Steven Taylor +Stéphane Este-Gracias +Stig Larsson +Su Wang +Subhajit Ghosh +Sujith Haridasan +Sun Gengze <690388648@qq.com> +Sun Jianbo +Sune Keller +Sunny Gogoi +Suryakumar Sudar +Sven Dowideit +Swapnil Daingade +Sylvain Baubeau +Sylvain Bellemare +Sébastien +Sébastien HOUZÉ +Sébastien Luttringer +Sébastien Stormacq +Sören Tempel +Tabakhase +Tadej Janež +Takuto Sato +tang0th +Tangi Colin +Tatsuki Sugiura +Tatsushi Inagaki +Taylan Isikdemir +Taylor Jones +Ted M. Young +Tehmasp Chaudhri +Tejaswini Duggaraju +Tejesh Mehta +Terry Chu +terryding77 <550147740@qq.com> +Thatcher Peskens +theadactyl +Thell 'Bo' Fowler +Thermionix +Thiago Alves Silva +Thijs Terlouw +Thomas Bikeev +Thomas Frössman +Thomas Gazagnaire +Thomas Graf +Thomas Grainger +Thomas Hansen +Thomas Ledos +Thomas Leonard +Thomas Léveil +Thomas Orozco +Thomas Riccardi +Thomas Schroeter +Thomas Sjögren +Thomas Swift +Thomas Tanaka +Thomas Texier +Ti Zhou +Tiago Seabra +Tianon Gravi +Tianyi Wang +Tibor Vass +Tiffany Jernigan +Tiffany Low +Till Claassen +Till Wegmüller +Tim +Tim Bart +Tim Bosse +Tim Dettrick +Tim Düsterhus +Tim Hockin +Tim Potter +Tim Ruffles +Tim Smith +Tim Terhorst +Tim Wagner +Tim Wang +Tim Waugh +Tim Wraight +Tim Zju <21651152@zju.edu.cn> +timchenxiaoyu <837829664@qq.com> +timfeirg +Timo Rothenpieler +Timothy Hobbs +tjwebb123 +tobe +Tobias Bieniek +Tobias Bradtke +Tobias Gesellchen +Tobias Klauser +Tobias Munk +Tobias Pfandzelter +Tobias Schmidt +Tobias Schwab +Todd Crane +Todd Lunter +Todd Whiteman +Toli Kuznets +Tom Barlow +Tom Booth +Tom Denham +Tom Fotherby +Tom Howe +Tom Hulihan +Tom Maaswinkel +Tom Parker +Tom Sweeney +Tom Wilkie +Tom X. Tobin +Tom Zhao +Tomas Janousek +Tomas Kral +Tomas Tomecek +Tomasz Kopczynski +Tomasz Lipinski +Tomasz Nurkiewicz +Tomek Mańko +Tommaso Visconti +Tomoya Tabuchi +Tomáš Hrčka +Tomáš Virtus +tonic +Tonny Xu +Tony Abboud +Tony Daws +Tony Miller +toogley +Torstein Husebø +Toshiaki Makita +Tõnis Tiigi +Trace Andreason +tracylihui <793912329@qq.com> +Trapier Marshall +Travis Cline +Travis Thieman +Trent Ogren +Trevor +Trevor Pounds +Trevor Sullivan +Trishna Guha +Tristan Carel +Troy Denton +Tudor Brindus +Ty Alexander +Tycho Andersen +Tyler Brock +Tyler Brown +Tzu-Jung Lee +uhayate +Ulysse Carion +Umesh Yadav +Utz Bacher +vagrant +Vaidas Jablonskis +Valentin Kulesh +vanderliang +Velko Ivanov +Veres Lajos +Victor Algaze +Victor Coisne +Victor Costan +Victor I. Wood +Victor Lyuboslavsky +Victor Marmol +Victor Palma +Victor Toni +Victor Vieux +Victoria Bialas +Vijaya Kumar K +Vikas Choudhary +Vikram bir Singh +Viktor Stanchev +Viktor Vojnovski +VinayRaghavanKS +Vincent Batts +Vincent Bernat +Vincent Boulineau +Vincent Demeester +Vincent Giersch +Vincent Mayers +Vincent Woo +Vinod Kulkarni +Vishal Doshi +Vishnu Kannan +Vitaly Ostrosablin +Vitor Anjos +Vitor Monteiro +Vivek Agarwal +Vivek Dasgupta +Vivek Goyal +Vladimir Bulyga +Vladimir Kirillov +Vladimir Pouzanov +Vladimir Rutsky +Vladimir Varankin +VladimirAus +Vladislav Kolesnikov +Vlastimil Zeman +Vojtech Vitek (V-Teq) +voloder <110066198+voloder@users.noreply.github.com> +Walter Leibbrandt +Walter Stanish +Wang Chao +Wang Guoliang +Wang Jie +Wang Long +Wang Ping +Wang Xing +Wang Yuexiao +Wang Yumu <37442693@qq.com> +wanghuaiqing +Ward Vandewege +WarheadsSE +Wassim Dhif +Wataru Ishida +Wayne Chang +Wayne Song +weebney +Weerasak Chongnguluam +Wei Fu +Wei Wu +Wei-Ting Kuo +weipeng +weiyan +Weiyang Zhu +Wen Cheng Ma +Wendel Fleming +Wenjun Tang +Wenkai Yin +wenlxie +Wenxuan Zhao +Wenyu You <21551128@zju.edu.cn> +Wenzhi Liang +Wes Morgan +Wesley Pettit +Wewang Xiaorenfine +Wiktor Kwapisiewicz +Will Dietz +Will Rouesnel +Will Weaver +willhf +William Delanoue +William Henry +William Hubbs +William Martin +William Riancho +William Thurston +Wilson Júnior +Wing-Kam Wong +WiseTrem +Wolfgang Nagele +Wolfgang Powisch +Wonjun Kim +WuLonghui +xamyzhao +Xia Wu +Xian Chaobo +Xianglin Gao +Xianjie +Xianlu Bird +Xiao YongBiao +Xiao Zhang +XiaoBing Jiang +Xiaodong Liu +Xiaodong Zhang +Xiaohua Ding +Xiaoxi He +Xiaoxu Chen +Xiaoyu Zhang +xichengliudui <1693291525@qq.com> +xiekeyang +Ximo Guanter Gonzálbez +xin.li +Xinbo Weng +Xinfeng Liu +Xinzi Zhou +Xiuming Chen +Xuecong Liao +xuzhaokui +Yadnyawalkya Tale +Yahya +yalpul +YAMADA Tsuyoshi +Yamasaki Masahide +Yamazaki Masashi +Yan Feng +Yan Zhu +Yang Bai +Yang Li +Yang Pengfei +yangchenliang +Yann Autissier +Yanqiang Miao +Yao Zaiyong +Yash Murty +Yassine Tijani +Yasunori Mahata +Yazhong Liu +Yestin Sun +Yi EungJun +Yibai Zhang +Yihang Ho +Ying Li +Yohei Ueda +Yong Tang +Yongxin Li +Yongzhi Pan +Yosef Fertel +You-Sheng Yang (楊有勝) +youcai +Youcef YEKHLEF +Youfu Zhang +Yu Changchun +Yu Chengxia +Yu Peng +Yu-Ju Hong +Yuan Sun +Yuanhong Peng +Yue Zhang +Yufei Xiong +Yuhao Fang +Yuichiro Kaneko +YujiOshima +Yunxiang Huang +Yurii Rashkovskii +Yusuf Tarık Günaydın +Yves Blusseau <90z7oey02@sneakemail.com> +Yves Junqueira +Zac Dover +Zach Borboa +Zach Gershman +Zachary Jaffee +Zain Memon +Zaiste! +Zane DeGraffenried +Zefan Li +Zen Lin(Zhinan Lin) +Zhang Kun +Zhang Wei +Zhang Wentao +zhangguanzhang +ZhangHang +zhangxianwei +Zhenan Ye <21551168@zju.edu.cn> +zhenghenghuo +Zhenhai Gao +Zhenkun Bi +ZhiPeng Lu +zhipengzuo +Zhou Hao +Zhoulin Xie +Zhu Guihua +Zhu Kunjia +Zhuoyun Wei +Ziheng Liu +Zilin Du +zimbatm +Ziming Dong +ZJUshuaizhou <21551191@zju.edu.cn> +zmarouf +Zoltan Tombol +Zou Yu +zqh +Zuhayr Elahi +Zunayed Ali +Álvaro Lázaro +Átila Camurça Alves +吴小白 <296015668@qq.com> +尹吉峰 +屈骏 +徐俊杰 +慕陶 +搏通 +黄艳红00139573 +정재영 diff --git a/vendor/github.com/docker/docker/LICENSE b/vendor/github.com/docker/docker/LICENSE new file mode 100644 index 00000000..6d8d58fb --- /dev/null +++ b/vendor/github.com/docker/docker/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2013-2018 Docker, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/docker/docker/NOTICE b/vendor/github.com/docker/docker/NOTICE new file mode 100644 index 00000000..58b19b6d --- /dev/null +++ b/vendor/github.com/docker/docker/NOTICE @@ -0,0 +1,19 @@ +Docker +Copyright 2012-2017 Docker, Inc. + +This product includes software developed at Docker, Inc. (https://www.docker.com). + +This product contains software (https://github.com/creack/pty) developed +by Keith Rarick, licensed under the MIT License. + +The following is courtesy of our legal counsel: + + +Use and transfer of Docker may be subject to certain restrictions by the +United States and other governments. +It is your responsibility to ensure that your use and/or transfer does not +violate applicable laws. + +For more information, please see https://www.bis.doc.gov + +See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go b/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go new file mode 100644 index 00000000..bf3463b9 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go @@ -0,0 +1,23 @@ +package blkiodev // import "github.com/docker/docker/api/types/blkiodev" + +import "fmt" + +// WeightDevice is a structure that holds device:weight pair +type WeightDevice struct { + Path string + Weight uint16 +} + +func (w *WeightDevice) String() string { + return fmt.Sprintf("%s:%d", w.Path, w.Weight) +} + +// ThrottleDevice is a structure that holds device:rate_per_second pair +type ThrottleDevice struct { + Path string + Rate uint64 +} + +func (t *ThrottleDevice) String() string { + return fmt.Sprintf("%s:%d", t.Path, t.Rate) +} diff --git a/vendor/github.com/docker/docker/api/types/container/change_type.go b/vendor/github.com/docker/docker/api/types/container/change_type.go new file mode 100644 index 00000000..fe8d6d36 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/change_type.go @@ -0,0 +1,15 @@ +package container + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// ChangeType Kind of change +// +// Can be one of: +// +// - `0`: Modified ("C") +// - `1`: Added ("A") +// - `2`: Deleted ("D") +// +// swagger:model ChangeType +type ChangeType uint8 diff --git a/vendor/github.com/docker/docker/api/types/container/change_types.go b/vendor/github.com/docker/docker/api/types/container/change_types.go new file mode 100644 index 00000000..3a3a8386 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/change_types.go @@ -0,0 +1,23 @@ +package container + +const ( + // ChangeModify represents the modify operation. + ChangeModify ChangeType = 0 + // ChangeAdd represents the add operation. + ChangeAdd ChangeType = 1 + // ChangeDelete represents the delete operation. + ChangeDelete ChangeType = 2 +) + +func (ct ChangeType) String() string { + switch ct { + case ChangeModify: + return "C" + case ChangeAdd: + return "A" + case ChangeDelete: + return "D" + default: + return "" + } +} diff --git a/vendor/github.com/docker/docker/api/types/container/config.go b/vendor/github.com/docker/docker/api/types/container/config.go new file mode 100644 index 00000000..d6b03e8b --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/config.go @@ -0,0 +1,73 @@ +package container // import "github.com/docker/docker/api/types/container" + +import ( + "time" + + "github.com/docker/docker/api/types/strslice" + "github.com/docker/go-connections/nat" + dockerspec "github.com/moby/docker-image-spec/specs-go/v1" +) + +// MinimumDuration puts a minimum on user configured duration. +// This is to prevent API error on time unit. For example, API may +// set 3 as healthcheck interval with intention of 3 seconds, but +// Docker interprets it as 3 nanoseconds. +const MinimumDuration = 1 * time.Millisecond + +// StopOptions holds the options to stop or restart a container. +type StopOptions struct { + // Signal (optional) is the signal to send to the container to (gracefully) + // stop it before forcibly terminating the container with SIGKILL after the + // timeout expires. If not value is set, the default (SIGTERM) is used. + Signal string `json:",omitempty"` + + // Timeout (optional) is the timeout (in seconds) to wait for the container + // to stop gracefully before forcibly terminating it with SIGKILL. + // + // - Use nil to use the default timeout (10 seconds). + // - Use '-1' to wait indefinitely. + // - Use '0' to not wait for the container to exit gracefully, and + // immediately proceeds to forcibly terminating the container. + // - Other positive values are used as timeout (in seconds). + Timeout *int `json:",omitempty"` +} + +// HealthConfig holds configuration settings for the HEALTHCHECK feature. +type HealthConfig = dockerspec.HealthcheckConfig + +// Config contains the configuration data about a container. +// It should hold only portable information about the container. +// Here, "portable" means "independent from the host we are running on". +// Non-portable information *should* appear in HostConfig. +// All fields added to this struct must be marked `omitempty` to keep getting +// predictable hashes from the old `v1Compatibility` configuration. +type Config struct { + Hostname string // Hostname + Domainname string // Domainname + User string // User that will run the command(s) inside the container, also support user:group + AttachStdin bool // Attach the standard input, makes possible user interaction + AttachStdout bool // Attach the standard output + AttachStderr bool // Attach the standard error + ExposedPorts nat.PortSet `json:",omitempty"` // List of exposed ports + Tty bool // Attach standard streams to a tty, including stdin if it is not closed. + OpenStdin bool // Open stdin + StdinOnce bool // If true, close stdin after the 1 attached client disconnects. + Env []string // List of environment variable to set in the container + Cmd strslice.StrSlice // Command to run when starting the container + Healthcheck *HealthConfig `json:",omitempty"` // Healthcheck describes how to check the container is healthy + ArgsEscaped bool `json:",omitempty"` // True if command is already escaped (meaning treat as a command line) (Windows specific). + Image string // Name of the image as it was passed by the operator (e.g. could be symbolic) + Volumes map[string]struct{} // List of volumes (mounts) used for the container + WorkingDir string // Current directory (PWD) in the command will be launched + Entrypoint strslice.StrSlice // Entrypoint to run when starting the container + NetworkDisabled bool `json:",omitempty"` // Is network disabled + // Mac Address of the container. + // + // Deprecated: this field is deprecated since API v1.44. Use EndpointSettings.MacAddress instead. + MacAddress string `json:",omitempty"` + OnBuild []string // ONBUILD metadata that were defined on the image Dockerfile + Labels map[string]string // List of labels set to this container + StopSignal string `json:",omitempty"` // Signal to stop a container + StopTimeout *int `json:",omitempty"` // Timeout (in seconds) to stop a container + Shell strslice.StrSlice `json:",omitempty"` // Shell for shell-form of RUN, CMD, ENTRYPOINT +} diff --git a/vendor/github.com/docker/docker/api/types/container/container.go b/vendor/github.com/docker/docker/api/types/container/container.go new file mode 100644 index 00000000..711af12c --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/container.go @@ -0,0 +1,44 @@ +package container + +import ( + "io" + "os" + "time" +) + +// PruneReport contains the response for Engine API: +// POST "/containers/prune" +type PruneReport struct { + ContainersDeleted []string + SpaceReclaimed uint64 +} + +// PathStat is used to encode the header from +// GET "/containers/{name:.*}/archive" +// "Name" is the file or directory name. +type PathStat struct { + Name string `json:"name"` + Size int64 `json:"size"` + Mode os.FileMode `json:"mode"` + Mtime time.Time `json:"mtime"` + LinkTarget string `json:"linkTarget"` +} + +// CopyToContainerOptions holds information +// about files to copy into a container +type CopyToContainerOptions struct { + AllowOverwriteDirWithFile bool + CopyUIDGID bool +} + +// StatsResponseReader wraps an io.ReadCloser to read (a stream of) stats +// for a container, as produced by the GET "/stats" endpoint. +// +// The OSType field is set to the server's platform to allow +// platform-specific handling of the response. +// +// TODO(thaJeztah): remove this wrapper, and make OSType part of [StatsResponse]. +type StatsResponseReader struct { + Body io.ReadCloser `json:"body"` + OSType string `json:"ostype"` +} diff --git a/vendor/github.com/docker/docker/api/types/container/container_top.go b/vendor/github.com/docker/docker/api/types/container/container_top.go new file mode 100644 index 00000000..63381da3 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/container_top.go @@ -0,0 +1,22 @@ +package container // import "github.com/docker/docker/api/types/container" + +// ---------------------------------------------------------------------------- +// Code generated by `swagger generate operation`. DO NOT EDIT. +// +// See hack/generate-swagger-api.sh +// ---------------------------------------------------------------------------- + +// ContainerTopOKBody OK response to ContainerTop operation +// swagger:model ContainerTopOKBody +type ContainerTopOKBody struct { + + // Each process running in the container, where each is process + // is an array of values corresponding to the titles. + // + // Required: true + Processes [][]string `json:"Processes"` + + // The ps column titles + // Required: true + Titles []string `json:"Titles"` +} diff --git a/vendor/github.com/docker/docker/api/types/container/container_update.go b/vendor/github.com/docker/docker/api/types/container/container_update.go new file mode 100644 index 00000000..c10f175e --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/container_update.go @@ -0,0 +1,16 @@ +package container // import "github.com/docker/docker/api/types/container" + +// ---------------------------------------------------------------------------- +// Code generated by `swagger generate operation`. DO NOT EDIT. +// +// See hack/generate-swagger-api.sh +// ---------------------------------------------------------------------------- + +// ContainerUpdateOKBody OK response to ContainerUpdate operation +// swagger:model ContainerUpdateOKBody +type ContainerUpdateOKBody struct { + + // warnings + // Required: true + Warnings []string `json:"Warnings"` +} diff --git a/vendor/github.com/docker/docker/api/types/container/create_request.go b/vendor/github.com/docker/docker/api/types/container/create_request.go new file mode 100644 index 00000000..e98dd6ad --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/create_request.go @@ -0,0 +1,13 @@ +package container + +import "github.com/docker/docker/api/types/network" + +// CreateRequest is the request message sent to the server for container +// create calls. It is a config wrapper that holds the container [Config] +// (portable) and the corresponding [HostConfig] (non-portable) and +// [network.NetworkingConfig]. +type CreateRequest struct { + *Config + HostConfig *HostConfig `json:"HostConfig,omitempty"` + NetworkingConfig *network.NetworkingConfig `json:"NetworkingConfig,omitempty"` +} diff --git a/vendor/github.com/docker/docker/api/types/container/create_response.go b/vendor/github.com/docker/docker/api/types/container/create_response.go new file mode 100644 index 00000000..aa0e7f7d --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/create_response.go @@ -0,0 +1,19 @@ +package container + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// CreateResponse ContainerCreateResponse +// +// OK response to ContainerCreate operation +// swagger:model CreateResponse +type CreateResponse struct { + + // The ID of the created container + // Required: true + ID string `json:"Id"` + + // Warnings encountered when creating the container + // Required: true + Warnings []string `json:"Warnings"` +} diff --git a/vendor/github.com/docker/docker/api/types/container/errors.go b/vendor/github.com/docker/docker/api/types/container/errors.go new file mode 100644 index 00000000..32c97803 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/errors.go @@ -0,0 +1,9 @@ +package container + +type errInvalidParameter struct{ error } + +func (e *errInvalidParameter) InvalidParameter() {} + +func (e *errInvalidParameter) Unwrap() error { + return e.error +} diff --git a/vendor/github.com/docker/docker/api/types/container/exec.go b/vendor/github.com/docker/docker/api/types/container/exec.go new file mode 100644 index 00000000..96093eb5 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/exec.go @@ -0,0 +1,43 @@ +package container + +// ExecOptions is a small subset of the Config struct that holds the configuration +// for the exec feature of docker. +type ExecOptions struct { + User string // User that will run the command + Privileged bool // Is the container in privileged mode + Tty bool // Attach standard streams to a tty. + ConsoleSize *[2]uint `json:",omitempty"` // Initial console size [height, width] + AttachStdin bool // Attach the standard input, makes possible user interaction + AttachStderr bool // Attach the standard error + AttachStdout bool // Attach the standard output + Detach bool // Execute in detach mode + DetachKeys string // Escape keys for detach + Env []string // Environment variables + WorkingDir string // Working directory + Cmd []string // Execution commands and args +} + +// ExecStartOptions is a temp struct used by execStart +// Config fields is part of ExecConfig in runconfig package +type ExecStartOptions struct { + // ExecStart will first check if it's detached + Detach bool + // Check if there's a tty + Tty bool + // Terminal size [height, width], unused if Tty == false + ConsoleSize *[2]uint `json:",omitempty"` +} + +// ExecAttachOptions is a temp struct used by execAttach. +// +// TODO(thaJeztah): make this a separate type; ContainerExecAttach does not use the Detach option, and cannot run detached. +type ExecAttachOptions = ExecStartOptions + +// ExecInspect holds information returned by exec inspect. +type ExecInspect struct { + ExecID string `json:"ID"` + ContainerID string + Running bool + ExitCode int + Pid int +} diff --git a/vendor/github.com/docker/docker/api/types/container/filesystem_change.go b/vendor/github.com/docker/docker/api/types/container/filesystem_change.go new file mode 100644 index 00000000..9e9c2ad1 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/filesystem_change.go @@ -0,0 +1,19 @@ +package container + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// FilesystemChange Change in the container's filesystem. +// +// swagger:model FilesystemChange +type FilesystemChange struct { + + // kind + // Required: true + Kind ChangeType `json:"Kind"` + + // Path to file or directory that has changed. + // + // Required: true + Path string `json:"Path"` +} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig.go b/vendor/github.com/docker/docker/api/types/container/hostconfig.go new file mode 100644 index 00000000..727da883 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/hostconfig.go @@ -0,0 +1,500 @@ +package container // import "github.com/docker/docker/api/types/container" + +import ( + "fmt" + "strings" + + "github.com/docker/docker/api/types/blkiodev" + "github.com/docker/docker/api/types/mount" + "github.com/docker/docker/api/types/network" + "github.com/docker/docker/api/types/strslice" + "github.com/docker/go-connections/nat" + units "github.com/docker/go-units" +) + +// CgroupnsMode represents the cgroup namespace mode of the container +type CgroupnsMode string + +// cgroup namespace modes for containers +const ( + CgroupnsModeEmpty CgroupnsMode = "" + CgroupnsModePrivate CgroupnsMode = "private" + CgroupnsModeHost CgroupnsMode = "host" +) + +// IsPrivate indicates whether the container uses its own private cgroup namespace +func (c CgroupnsMode) IsPrivate() bool { + return c == CgroupnsModePrivate +} + +// IsHost indicates whether the container shares the host's cgroup namespace +func (c CgroupnsMode) IsHost() bool { + return c == CgroupnsModeHost +} + +// IsEmpty indicates whether the container cgroup namespace mode is unset +func (c CgroupnsMode) IsEmpty() bool { + return c == CgroupnsModeEmpty +} + +// Valid indicates whether the cgroup namespace mode is valid +func (c CgroupnsMode) Valid() bool { + return c.IsEmpty() || c.IsPrivate() || c.IsHost() +} + +// Isolation represents the isolation technology of a container. The supported +// values are platform specific +type Isolation string + +// Isolation modes for containers +const ( + IsolationEmpty Isolation = "" // IsolationEmpty is unspecified (same behavior as default) + IsolationDefault Isolation = "default" // IsolationDefault is the default isolation mode on current daemon + IsolationProcess Isolation = "process" // IsolationProcess is process isolation mode + IsolationHyperV Isolation = "hyperv" // IsolationHyperV is HyperV isolation mode +) + +// IsDefault indicates the default isolation technology of a container. On Linux this +// is the native driver. On Windows, this is a Windows Server Container. +func (i Isolation) IsDefault() bool { + // TODO consider making isolation-mode strict (case-sensitive) + v := Isolation(strings.ToLower(string(i))) + return v == IsolationDefault || v == IsolationEmpty +} + +// IsHyperV indicates the use of a Hyper-V partition for isolation +func (i Isolation) IsHyperV() bool { + // TODO consider making isolation-mode strict (case-sensitive) + return Isolation(strings.ToLower(string(i))) == IsolationHyperV +} + +// IsProcess indicates the use of process isolation +func (i Isolation) IsProcess() bool { + // TODO consider making isolation-mode strict (case-sensitive) + return Isolation(strings.ToLower(string(i))) == IsolationProcess +} + +// IpcMode represents the container ipc stack. +type IpcMode string + +// IpcMode constants +const ( + IPCModeNone IpcMode = "none" + IPCModeHost IpcMode = "host" + IPCModeContainer IpcMode = "container" + IPCModePrivate IpcMode = "private" + IPCModeShareable IpcMode = "shareable" +) + +// IsPrivate indicates whether the container uses its own private ipc namespace which can not be shared. +func (n IpcMode) IsPrivate() bool { + return n == IPCModePrivate +} + +// IsHost indicates whether the container shares the host's ipc namespace. +func (n IpcMode) IsHost() bool { + return n == IPCModeHost +} + +// IsShareable indicates whether the container's ipc namespace can be shared with another container. +func (n IpcMode) IsShareable() bool { + return n == IPCModeShareable +} + +// IsContainer indicates whether the container uses another container's ipc namespace. +func (n IpcMode) IsContainer() bool { + _, ok := containerID(string(n)) + return ok +} + +// IsNone indicates whether container IpcMode is set to "none". +func (n IpcMode) IsNone() bool { + return n == IPCModeNone +} + +// IsEmpty indicates whether container IpcMode is empty +func (n IpcMode) IsEmpty() bool { + return n == "" +} + +// Valid indicates whether the ipc mode is valid. +func (n IpcMode) Valid() bool { + // TODO(thaJeztah): align with PidMode, and consider container-mode without a container name/ID to be invalid. + return n.IsEmpty() || n.IsNone() || n.IsPrivate() || n.IsHost() || n.IsShareable() || n.IsContainer() +} + +// Container returns the name of the container ipc stack is going to be used. +func (n IpcMode) Container() (idOrName string) { + idOrName, _ = containerID(string(n)) + return idOrName +} + +// NetworkMode represents the container network stack. +type NetworkMode string + +// IsNone indicates whether container isn't using a network stack. +func (n NetworkMode) IsNone() bool { + return n == network.NetworkNone +} + +// IsDefault indicates whether container uses the default network stack. +func (n NetworkMode) IsDefault() bool { + return n == network.NetworkDefault +} + +// IsPrivate indicates whether container uses its private network stack. +func (n NetworkMode) IsPrivate() bool { + return !(n.IsHost() || n.IsContainer()) +} + +// IsContainer indicates whether container uses a container network stack. +func (n NetworkMode) IsContainer() bool { + _, ok := containerID(string(n)) + return ok +} + +// ConnectedContainer is the id of the container which network this container is connected to. +func (n NetworkMode) ConnectedContainer() (idOrName string) { + idOrName, _ = containerID(string(n)) + return idOrName +} + +// UserDefined indicates user-created network +func (n NetworkMode) UserDefined() string { + if n.IsUserDefined() { + return string(n) + } + return "" +} + +// UsernsMode represents userns mode in the container. +type UsernsMode string + +// IsHost indicates whether the container uses the host's userns. +func (n UsernsMode) IsHost() bool { + return n == "host" +} + +// IsPrivate indicates whether the container uses the a private userns. +func (n UsernsMode) IsPrivate() bool { + return !n.IsHost() +} + +// Valid indicates whether the userns is valid. +func (n UsernsMode) Valid() bool { + return n == "" || n.IsHost() +} + +// CgroupSpec represents the cgroup to use for the container. +type CgroupSpec string + +// IsContainer indicates whether the container is using another container cgroup +func (c CgroupSpec) IsContainer() bool { + _, ok := containerID(string(c)) + return ok +} + +// Valid indicates whether the cgroup spec is valid. +func (c CgroupSpec) Valid() bool { + // TODO(thaJeztah): align with PidMode, and consider container-mode without a container name/ID to be invalid. + return c == "" || c.IsContainer() +} + +// Container returns the ID or name of the container whose cgroup will be used. +func (c CgroupSpec) Container() (idOrName string) { + idOrName, _ = containerID(string(c)) + return idOrName +} + +// UTSMode represents the UTS namespace of the container. +type UTSMode string + +// IsPrivate indicates whether the container uses its private UTS namespace. +func (n UTSMode) IsPrivate() bool { + return !n.IsHost() +} + +// IsHost indicates whether the container uses the host's UTS namespace. +func (n UTSMode) IsHost() bool { + return n == "host" +} + +// Valid indicates whether the UTS namespace is valid. +func (n UTSMode) Valid() bool { + return n == "" || n.IsHost() +} + +// PidMode represents the pid namespace of the container. +type PidMode string + +// IsPrivate indicates whether the container uses its own new pid namespace. +func (n PidMode) IsPrivate() bool { + return !(n.IsHost() || n.IsContainer()) +} + +// IsHost indicates whether the container uses the host's pid namespace. +func (n PidMode) IsHost() bool { + return n == "host" +} + +// IsContainer indicates whether the container uses a container's pid namespace. +func (n PidMode) IsContainer() bool { + _, ok := containerID(string(n)) + return ok +} + +// Valid indicates whether the pid namespace is valid. +func (n PidMode) Valid() bool { + return n == "" || n.IsHost() || validContainer(string(n)) +} + +// Container returns the name of the container whose pid namespace is going to be used. +func (n PidMode) Container() (idOrName string) { + idOrName, _ = containerID(string(n)) + return idOrName +} + +// DeviceRequest represents a request for devices from a device driver. +// Used by GPU device drivers. +type DeviceRequest struct { + Driver string // Name of device driver + Count int // Number of devices to request (-1 = All) + DeviceIDs []string // List of device IDs as recognizable by the device driver + Capabilities [][]string // An OR list of AND lists of device capabilities (e.g. "gpu") + Options map[string]string // Options to pass onto the device driver +} + +// DeviceMapping represents the device mapping between the host and the container. +type DeviceMapping struct { + PathOnHost string + PathInContainer string + CgroupPermissions string +} + +// RestartPolicy represents the restart policies of the container. +type RestartPolicy struct { + Name RestartPolicyMode + MaximumRetryCount int +} + +type RestartPolicyMode string + +const ( + RestartPolicyDisabled RestartPolicyMode = "no" + RestartPolicyAlways RestartPolicyMode = "always" + RestartPolicyOnFailure RestartPolicyMode = "on-failure" + RestartPolicyUnlessStopped RestartPolicyMode = "unless-stopped" +) + +// IsNone indicates whether the container has the "no" restart policy. +// This means the container will not automatically restart when exiting. +func (rp *RestartPolicy) IsNone() bool { + return rp.Name == RestartPolicyDisabled || rp.Name == "" +} + +// IsAlways indicates whether the container has the "always" restart policy. +// This means the container will automatically restart regardless of the exit status. +func (rp *RestartPolicy) IsAlways() bool { + return rp.Name == RestartPolicyAlways +} + +// IsOnFailure indicates whether the container has the "on-failure" restart policy. +// This means the container will automatically restart of exiting with a non-zero exit status. +func (rp *RestartPolicy) IsOnFailure() bool { + return rp.Name == RestartPolicyOnFailure +} + +// IsUnlessStopped indicates whether the container has the +// "unless-stopped" restart policy. This means the container will +// automatically restart unless user has put it to stopped state. +func (rp *RestartPolicy) IsUnlessStopped() bool { + return rp.Name == RestartPolicyUnlessStopped +} + +// IsSame compares two RestartPolicy to see if they are the same +func (rp *RestartPolicy) IsSame(tp *RestartPolicy) bool { + return rp.Name == tp.Name && rp.MaximumRetryCount == tp.MaximumRetryCount +} + +// ValidateRestartPolicy validates the given RestartPolicy. +func ValidateRestartPolicy(policy RestartPolicy) error { + switch policy.Name { + case RestartPolicyAlways, RestartPolicyUnlessStopped, RestartPolicyDisabled: + if policy.MaximumRetryCount != 0 { + msg := "invalid restart policy: maximum retry count can only be used with 'on-failure'" + if policy.MaximumRetryCount < 0 { + msg += " and cannot be negative" + } + return &errInvalidParameter{fmt.Errorf(msg)} + } + return nil + case RestartPolicyOnFailure: + if policy.MaximumRetryCount < 0 { + return &errInvalidParameter{fmt.Errorf("invalid restart policy: maximum retry count cannot be negative")} + } + return nil + case "": + // Versions before v25.0.0 created an empty restart-policy "name" as + // default. Allow an empty name with "any" MaximumRetryCount for + // backward-compatibility. + return nil + default: + return &errInvalidParameter{fmt.Errorf("invalid restart policy: unknown policy '%s'; use one of '%s', '%s', '%s', or '%s'", policy.Name, RestartPolicyDisabled, RestartPolicyAlways, RestartPolicyOnFailure, RestartPolicyUnlessStopped)} + } +} + +// LogMode is a type to define the available modes for logging +// These modes affect how logs are handled when log messages start piling up. +type LogMode string + +// Available logging modes +const ( + LogModeUnset LogMode = "" + LogModeBlocking LogMode = "blocking" + LogModeNonBlock LogMode = "non-blocking" +) + +// LogConfig represents the logging configuration of the container. +type LogConfig struct { + Type string + Config map[string]string +} + +// Ulimit is an alias for [units.Ulimit], which may be moving to a different +// location or become a local type. This alias is to help transitioning. +// +// Users are recommended to use this alias instead of using [units.Ulimit] directly. +type Ulimit = units.Ulimit + +// Resources contains container's resources (cgroups config, ulimits...) +type Resources struct { + // Applicable to all platforms + CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers) + Memory int64 // Memory limit (in bytes) + NanoCPUs int64 `json:"NanoCpus"` // CPU quota in units of 10-9 CPUs. + + // Applicable to UNIX platforms + CgroupParent string // Parent cgroup. + BlkioWeight uint16 // Block IO weight (relative weight vs. other containers) + BlkioWeightDevice []*blkiodev.WeightDevice + BlkioDeviceReadBps []*blkiodev.ThrottleDevice + BlkioDeviceWriteBps []*blkiodev.ThrottleDevice + BlkioDeviceReadIOps []*blkiodev.ThrottleDevice + BlkioDeviceWriteIOps []*blkiodev.ThrottleDevice + CPUPeriod int64 `json:"CpuPeriod"` // CPU CFS (Completely Fair Scheduler) period + CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota + CPURealtimePeriod int64 `json:"CpuRealtimePeriod"` // CPU real-time period + CPURealtimeRuntime int64 `json:"CpuRealtimeRuntime"` // CPU real-time runtime + CpusetCpus string // CpusetCpus 0-2, 0,1 + CpusetMems string // CpusetMems 0-2, 0,1 + Devices []DeviceMapping // List of devices to map inside the container + DeviceCgroupRules []string // List of rule to be added to the device cgroup + DeviceRequests []DeviceRequest // List of device requests for device drivers + + // KernelMemory specifies the kernel memory limit (in bytes) for the container. + // Deprecated: kernel 5.4 deprecated kmem.limit_in_bytes. + KernelMemory int64 `json:",omitempty"` + KernelMemoryTCP int64 `json:",omitempty"` // Hard limit for kernel TCP buffer memory (in bytes) + MemoryReservation int64 // Memory soft limit (in bytes) + MemorySwap int64 // Total memory usage (memory + swap); set `-1` to enable unlimited swap + MemorySwappiness *int64 // Tuning container memory swappiness behaviour + OomKillDisable *bool // Whether to disable OOM Killer or not + PidsLimit *int64 // Setting PIDs limit for a container; Set `0` or `-1` for unlimited, or `null` to not change. + Ulimits []*Ulimit // List of ulimits to be set in the container + + // Applicable to Windows + CPUCount int64 `json:"CpuCount"` // CPU count + CPUPercent int64 `json:"CpuPercent"` // CPU percent + IOMaximumIOps uint64 // Maximum IOps for the container system drive + IOMaximumBandwidth uint64 // Maximum IO in bytes per second for the container system drive +} + +// UpdateConfig holds the mutable attributes of a Container. +// Those attributes can be updated at runtime. +type UpdateConfig struct { + // Contains container's resources (cgroups, ulimits) + Resources + RestartPolicy RestartPolicy +} + +// HostConfig the non-portable Config structure of a container. +// Here, "non-portable" means "dependent of the host we are running on". +// Portable information *should* appear in Config. +type HostConfig struct { + // Applicable to all platforms + Binds []string // List of volume bindings for this container + ContainerIDFile string // File (path) where the containerId is written + LogConfig LogConfig // Configuration of the logs for this container + NetworkMode NetworkMode // Network mode to use for the container + PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host + RestartPolicy RestartPolicy // Restart policy to be used for the container + AutoRemove bool // Automatically remove container when it exits + VolumeDriver string // Name of the volume driver used to mount volumes + VolumesFrom []string // List of volumes to take from other container + ConsoleSize [2]uint // Initial console size (height,width) + Annotations map[string]string `json:",omitempty"` // Arbitrary non-identifying metadata attached to container and provided to the runtime + + // Applicable to UNIX platforms + CapAdd strslice.StrSlice // List of kernel capabilities to add to the container + CapDrop strslice.StrSlice // List of kernel capabilities to remove from the container + CgroupnsMode CgroupnsMode // Cgroup namespace mode to use for the container + DNS []string `json:"Dns"` // List of DNS server to lookup + DNSOptions []string `json:"DnsOptions"` // List of DNSOption to look for + DNSSearch []string `json:"DnsSearch"` // List of DNSSearch to look for + ExtraHosts []string // List of extra hosts + GroupAdd []string // List of additional groups that the container process will run as + IpcMode IpcMode // IPC namespace to use for the container + Cgroup CgroupSpec // Cgroup to use for the container + Links []string // List of links (in the name:alias form) + OomScoreAdj int // Container preference for OOM-killing + PidMode PidMode // PID namespace to use for the container + Privileged bool // Is the container in privileged mode + PublishAllPorts bool // Should docker publish all exposed port for the container + ReadonlyRootfs bool // Is the container root filesystem in read-only + SecurityOpt []string // List of string values to customize labels for MLS systems, such as SELinux. + StorageOpt map[string]string `json:",omitempty"` // Storage driver options per container. + Tmpfs map[string]string `json:",omitempty"` // List of tmpfs (mounts) used for the container + UTSMode UTSMode // UTS namespace to use for the container + UsernsMode UsernsMode // The user namespace to use for the container + ShmSize int64 // Total shm memory usage + Sysctls map[string]string `json:",omitempty"` // List of Namespaced sysctls used for the container + Runtime string `json:",omitempty"` // Runtime to use with this container + + // Applicable to Windows + Isolation Isolation // Isolation technology of the container (e.g. default, hyperv) + + // Contains container's resources (cgroups, ulimits) + Resources + + // Mounts specs used by the container + Mounts []mount.Mount `json:",omitempty"` + + // MaskedPaths is the list of paths to be masked inside the container (this overrides the default set of paths) + MaskedPaths []string + + // ReadonlyPaths is the list of paths to be set as read-only inside the container (this overrides the default set of paths) + ReadonlyPaths []string + + // Run a custom init inside the container, if null, use the daemon's configured settings + Init *bool `json:",omitempty"` +} + +// containerID splits "container:" values. It returns the container +// ID or name, and whether an ID/name was found. It returns an empty string and +// a "false" if the value does not have a "container:" prefix. Further validation +// of the returned, including checking if the value is empty, should be handled +// by the caller. +func containerID(val string) (idOrName string, ok bool) { + k, v, hasSep := strings.Cut(val, ":") + if !hasSep || k != "container" { + return "", false + } + return v, true +} + +// validContainer checks if the given value is a "container:" mode with +// a non-empty name/ID. +func validContainer(val string) bool { + id, ok := containerID(val) + return ok && id != "" +} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go b/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go new file mode 100644 index 00000000..cdee49ea --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go @@ -0,0 +1,45 @@ +//go:build !windows + +package container // import "github.com/docker/docker/api/types/container" + +import "github.com/docker/docker/api/types/network" + +// IsValid indicates if an isolation technology is valid +func (i Isolation) IsValid() bool { + return i.IsDefault() +} + +// IsBridge indicates whether container uses the bridge network stack +func (n NetworkMode) IsBridge() bool { + return n == network.NetworkBridge +} + +// IsHost indicates whether container uses the host network stack. +func (n NetworkMode) IsHost() bool { + return n == network.NetworkHost +} + +// IsUserDefined indicates user-created network +func (n NetworkMode) IsUserDefined() bool { + return !n.IsDefault() && !n.IsBridge() && !n.IsHost() && !n.IsNone() && !n.IsContainer() +} + +// NetworkName returns the name of the network stack. +func (n NetworkMode) NetworkName() string { + switch { + case n.IsDefault(): + return network.NetworkDefault + case n.IsBridge(): + return network.NetworkBridge + case n.IsHost(): + return network.NetworkHost + case n.IsNone(): + return network.NetworkNone + case n.IsContainer(): + return "container" + case n.IsUserDefined(): + return n.UserDefined() + default: + return "" + } +} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go b/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go new file mode 100644 index 00000000..f0854554 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go @@ -0,0 +1,47 @@ +package container // import "github.com/docker/docker/api/types/container" + +import "github.com/docker/docker/api/types/network" + +// IsValid indicates if an isolation technology is valid +func (i Isolation) IsValid() bool { + return i.IsDefault() || i.IsHyperV() || i.IsProcess() +} + +// IsBridge indicates whether container uses the bridge network stack +// in windows it is given the name NAT +func (n NetworkMode) IsBridge() bool { + return n == network.NetworkNat +} + +// IsHost indicates whether container uses the host network stack. +// returns false as this is not supported by windows +func (n NetworkMode) IsHost() bool { + return false +} + +// IsUserDefined indicates user-created network +func (n NetworkMode) IsUserDefined() bool { + return !n.IsDefault() && !n.IsNone() && !n.IsBridge() && !n.IsContainer() +} + +// NetworkName returns the name of the network stack. +func (n NetworkMode) NetworkName() string { + switch { + case n.IsDefault(): + return network.NetworkDefault + case n.IsBridge(): + return network.NetworkNat + case n.IsHost(): + // Windows currently doesn't support host network-mode, so + // this would currently never happen.. + return network.NetworkHost + case n.IsNone(): + return network.NetworkNone + case n.IsContainer(): + return "container" + case n.IsUserDefined(): + return n.UserDefined() + default: + return "" + } +} diff --git a/vendor/github.com/docker/docker/api/types/container/options.go b/vendor/github.com/docker/docker/api/types/container/options.go new file mode 100644 index 00000000..7a230057 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/options.go @@ -0,0 +1,67 @@ +package container + +import "github.com/docker/docker/api/types/filters" + +// ResizeOptions holds parameters to resize a TTY. +// It can be used to resize container TTYs and +// exec process TTYs too. +type ResizeOptions struct { + Height uint + Width uint +} + +// AttachOptions holds parameters to attach to a container. +type AttachOptions struct { + Stream bool + Stdin bool + Stdout bool + Stderr bool + DetachKeys string + Logs bool +} + +// CommitOptions holds parameters to commit changes into a container. +type CommitOptions struct { + Reference string + Comment string + Author string + Changes []string + Pause bool + Config *Config +} + +// RemoveOptions holds parameters to remove containers. +type RemoveOptions struct { + RemoveVolumes bool + RemoveLinks bool + Force bool +} + +// StartOptions holds parameters to start containers. +type StartOptions struct { + CheckpointID string + CheckpointDir string +} + +// ListOptions holds parameters to list containers with. +type ListOptions struct { + Size bool + All bool + Latest bool + Since string + Before string + Limit int + Filters filters.Args +} + +// LogsOptions holds parameters to filter logs with. +type LogsOptions struct { + ShowStdout bool + ShowStderr bool + Since string + Until string + Timestamps bool + Follow bool + Tail string + Details bool +} diff --git a/vendor/github.com/docker/docker/api/types/container/stats.go b/vendor/github.com/docker/docker/api/types/container/stats.go new file mode 100644 index 00000000..3b3fb131 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/stats.go @@ -0,0 +1,181 @@ +package container + +import "time" + +// ThrottlingData stores CPU throttling stats of one running container. +// Not used on Windows. +type ThrottlingData struct { + // Number of periods with throttling active + Periods uint64 `json:"periods"` + // Number of periods when the container hits its throttling limit. + ThrottledPeriods uint64 `json:"throttled_periods"` + // Aggregate time the container was throttled for in nanoseconds. + ThrottledTime uint64 `json:"throttled_time"` +} + +// CPUUsage stores All CPU stats aggregated since container inception. +type CPUUsage struct { + // Total CPU time consumed. + // Units: nanoseconds (Linux) + // Units: 100's of nanoseconds (Windows) + TotalUsage uint64 `json:"total_usage"` + + // Total CPU time consumed per core (Linux). Not used on Windows. + // Units: nanoseconds. + PercpuUsage []uint64 `json:"percpu_usage,omitempty"` + + // Time spent by tasks of the cgroup in kernel mode (Linux). + // Time spent by all container processes in kernel mode (Windows). + // Units: nanoseconds (Linux). + // Units: 100's of nanoseconds (Windows). Not populated for Hyper-V Containers. + UsageInKernelmode uint64 `json:"usage_in_kernelmode"` + + // Time spent by tasks of the cgroup in user mode (Linux). + // Time spent by all container processes in user mode (Windows). + // Units: nanoseconds (Linux). + // Units: 100's of nanoseconds (Windows). Not populated for Hyper-V Containers + UsageInUsermode uint64 `json:"usage_in_usermode"` +} + +// CPUStats aggregates and wraps all CPU related info of container +type CPUStats struct { + // CPU Usage. Linux and Windows. + CPUUsage CPUUsage `json:"cpu_usage"` + + // System Usage. Linux only. + SystemUsage uint64 `json:"system_cpu_usage,omitempty"` + + // Online CPUs. Linux only. + OnlineCPUs uint32 `json:"online_cpus,omitempty"` + + // Throttling Data. Linux only. + ThrottlingData ThrottlingData `json:"throttling_data,omitempty"` +} + +// MemoryStats aggregates all memory stats since container inception on Linux. +// Windows returns stats for commit and private working set only. +type MemoryStats struct { + // Linux Memory Stats + + // current res_counter usage for memory + Usage uint64 `json:"usage,omitempty"` + // maximum usage ever recorded. + MaxUsage uint64 `json:"max_usage,omitempty"` + // TODO(vishh): Export these as stronger types. + // all the stats exported via memory.stat. + Stats map[string]uint64 `json:"stats,omitempty"` + // number of times memory usage hits limits. + Failcnt uint64 `json:"failcnt,omitempty"` + Limit uint64 `json:"limit,omitempty"` + + // Windows Memory Stats + // See https://technet.microsoft.com/en-us/magazine/ff382715.aspx + + // committed bytes + Commit uint64 `json:"commitbytes,omitempty"` + // peak committed bytes + CommitPeak uint64 `json:"commitpeakbytes,omitempty"` + // private working set + PrivateWorkingSet uint64 `json:"privateworkingset,omitempty"` +} + +// BlkioStatEntry is one small entity to store a piece of Blkio stats +// Not used on Windows. +type BlkioStatEntry struct { + Major uint64 `json:"major"` + Minor uint64 `json:"minor"` + Op string `json:"op"` + Value uint64 `json:"value"` +} + +// BlkioStats stores All IO service stats for data read and write. +// This is a Linux specific structure as the differences between expressing +// block I/O on Windows and Linux are sufficiently significant to make +// little sense attempting to morph into a combined structure. +type BlkioStats struct { + // number of bytes transferred to and from the block device + IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"` + IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive"` + IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive"` + IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive"` + IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive"` + IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive"` + IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive"` + SectorsRecursive []BlkioStatEntry `json:"sectors_recursive"` +} + +// StorageStats is the disk I/O stats for read/write on Windows. +type StorageStats struct { + ReadCountNormalized uint64 `json:"read_count_normalized,omitempty"` + ReadSizeBytes uint64 `json:"read_size_bytes,omitempty"` + WriteCountNormalized uint64 `json:"write_count_normalized,omitempty"` + WriteSizeBytes uint64 `json:"write_size_bytes,omitempty"` +} + +// NetworkStats aggregates the network stats of one container +type NetworkStats struct { + // Bytes received. Windows and Linux. + RxBytes uint64 `json:"rx_bytes"` + // Packets received. Windows and Linux. + RxPackets uint64 `json:"rx_packets"` + // Received errors. Not used on Windows. Note that we don't `omitempty` this + // field as it is expected in the >=v1.21 API stats structure. + RxErrors uint64 `json:"rx_errors"` + // Incoming packets dropped. Windows and Linux. + RxDropped uint64 `json:"rx_dropped"` + // Bytes sent. Windows and Linux. + TxBytes uint64 `json:"tx_bytes"` + // Packets sent. Windows and Linux. + TxPackets uint64 `json:"tx_packets"` + // Sent errors. Not used on Windows. Note that we don't `omitempty` this + // field as it is expected in the >=v1.21 API stats structure. + TxErrors uint64 `json:"tx_errors"` + // Outgoing packets dropped. Windows and Linux. + TxDropped uint64 `json:"tx_dropped"` + // Endpoint ID. Not used on Linux. + EndpointID string `json:"endpoint_id,omitempty"` + // Instance ID. Not used on Linux. + InstanceID string `json:"instance_id,omitempty"` +} + +// PidsStats contains the stats of a container's pids +type PidsStats struct { + // Current is the number of pids in the cgroup + Current uint64 `json:"current,omitempty"` + // Limit is the hard limit on the number of pids in the cgroup. + // A "Limit" of 0 means that there is no limit. + Limit uint64 `json:"limit,omitempty"` +} + +// Stats is Ultimate struct aggregating all types of stats of one container +type Stats struct { + // Common stats + Read time.Time `json:"read"` + PreRead time.Time `json:"preread"` + + // Linux specific stats, not populated on Windows. + PidsStats PidsStats `json:"pids_stats,omitempty"` + BlkioStats BlkioStats `json:"blkio_stats,omitempty"` + + // Windows specific stats, not populated on Linux. + NumProcs uint32 `json:"num_procs"` + StorageStats StorageStats `json:"storage_stats,omitempty"` + + // Shared stats + CPUStats CPUStats `json:"cpu_stats,omitempty"` + PreCPUStats CPUStats `json:"precpu_stats,omitempty"` // "Pre"="Previous" + MemoryStats MemoryStats `json:"memory_stats,omitempty"` +} + +// StatsResponse is newly used Networks. +// +// TODO(thaJeztah): unify with [Stats]. This wrapper was to account for pre-api v1.21 changes, see https://github.com/moby/moby/commit/d3379946ec96fb6163cb8c4517d7d5a067045801 +type StatsResponse struct { + Stats + + Name string `json:"name,omitempty"` + ID string `json:"id,omitempty"` + + // Networks request version >=1.21 + Networks map[string]NetworkStats `json:"networks,omitempty"` +} diff --git a/vendor/github.com/docker/docker/api/types/container/wait_exit_error.go b/vendor/github.com/docker/docker/api/types/container/wait_exit_error.go new file mode 100644 index 00000000..ab56d4ee --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/wait_exit_error.go @@ -0,0 +1,12 @@ +package container + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// WaitExitError container waiting error, if any +// swagger:model WaitExitError +type WaitExitError struct { + + // Details of an error + Message string `json:"Message,omitempty"` +} diff --git a/vendor/github.com/docker/docker/api/types/container/wait_response.go b/vendor/github.com/docker/docker/api/types/container/wait_response.go new file mode 100644 index 00000000..84fc6afd --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/wait_response.go @@ -0,0 +1,18 @@ +package container + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// WaitResponse ContainerWaitResponse +// +// OK response to ContainerWait operation +// swagger:model WaitResponse +type WaitResponse struct { + + // error + Error *WaitExitError `json:"Error,omitempty"` + + // Exit code of the container + // Required: true + StatusCode int64 `json:"StatusCode"` +} diff --git a/vendor/github.com/docker/docker/api/types/container/waitcondition.go b/vendor/github.com/docker/docker/api/types/container/waitcondition.go new file mode 100644 index 00000000..cd8311f9 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/waitcondition.go @@ -0,0 +1,22 @@ +package container // import "github.com/docker/docker/api/types/container" + +// WaitCondition is a type used to specify a container state for which +// to wait. +type WaitCondition string + +// Possible WaitCondition Values. +// +// WaitConditionNotRunning (default) is used to wait for any of the non-running +// states: "created", "exited", "dead", "removing", or "removed". +// +// WaitConditionNextExit is used to wait for the next time the state changes +// to a non-running state. If the state is currently "created" or "exited", +// this would cause Wait() to block until either the container runs and exits +// or is removed. +// +// WaitConditionRemoved is used to wait for the container to be removed. +const ( + WaitConditionNotRunning WaitCondition = "not-running" + WaitConditionNextExit WaitCondition = "next-exit" + WaitConditionRemoved WaitCondition = "removed" +) diff --git a/vendor/github.com/docker/docker/api/types/filters/errors.go b/vendor/github.com/docker/docker/api/types/filters/errors.go new file mode 100644 index 00000000..f52f6944 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/filters/errors.go @@ -0,0 +1,37 @@ +package filters + +import "fmt" + +// invalidFilter indicates that the provided filter or its value is invalid +type invalidFilter struct { + Filter string + Value []string +} + +func (e invalidFilter) Error() string { + msg := "invalid filter" + if e.Filter != "" { + msg += " '" + e.Filter + if e.Value != nil { + msg = fmt.Sprintf("%s=%s", msg, e.Value) + } + msg += "'" + } + return msg +} + +// InvalidParameter marks this error as ErrInvalidParameter +func (e invalidFilter) InvalidParameter() {} + +// unreachableCode is an error indicating that the code path was not expected to be reached. +type unreachableCode struct { + Filter string + Value []string +} + +// System marks this error as ErrSystem +func (e unreachableCode) System() {} + +func (e unreachableCode) Error() string { + return fmt.Sprintf("unreachable code reached for filter: %q with values: %s", e.Filter, e.Value) +} diff --git a/vendor/github.com/docker/docker/api/types/filters/parse.go b/vendor/github.com/docker/docker/api/types/filters/parse.go new file mode 100644 index 00000000..0c39ab5f --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/filters/parse.go @@ -0,0 +1,346 @@ +/* +Package filters provides tools for encoding a mapping of keys to a set of +multiple values. +*/ +package filters // import "github.com/docker/docker/api/types/filters" + +import ( + "encoding/json" + "regexp" + "strings" + + "github.com/docker/docker/api/types/versions" +) + +// Args stores a mapping of keys to a set of multiple values. +type Args struct { + fields map[string]map[string]bool +} + +// KeyValuePair are used to initialize a new Args +type KeyValuePair struct { + Key string + Value string +} + +// Arg creates a new KeyValuePair for initializing Args +func Arg(key, value string) KeyValuePair { + return KeyValuePair{Key: key, Value: value} +} + +// NewArgs returns a new Args populated with the initial args +func NewArgs(initialArgs ...KeyValuePair) Args { + args := Args{fields: map[string]map[string]bool{}} + for _, arg := range initialArgs { + args.Add(arg.Key, arg.Value) + } + return args +} + +// Keys returns all the keys in list of Args +func (args Args) Keys() []string { + keys := make([]string, 0, len(args.fields)) + for k := range args.fields { + keys = append(keys, k) + } + return keys +} + +// MarshalJSON returns a JSON byte representation of the Args +func (args Args) MarshalJSON() ([]byte, error) { + if len(args.fields) == 0 { + return []byte("{}"), nil + } + return json.Marshal(args.fields) +} + +// ToJSON returns the Args as a JSON encoded string +func ToJSON(a Args) (string, error) { + if a.Len() == 0 { + return "", nil + } + buf, err := json.Marshal(a) + return string(buf), err +} + +// ToParamWithVersion encodes Args as a JSON string. If version is less than 1.22 +// then the encoded format will use an older legacy format where the values are a +// list of strings, instead of a set. +// +// Deprecated: do not use in any new code; use ToJSON instead +func ToParamWithVersion(version string, a Args) (string, error) { + if a.Len() == 0 { + return "", nil + } + + if version != "" && versions.LessThan(version, "1.22") { + buf, err := json.Marshal(convertArgsToSlice(a.fields)) + return string(buf), err + } + + return ToJSON(a) +} + +// FromJSON decodes a JSON encoded string into Args +func FromJSON(p string) (Args, error) { + args := NewArgs() + + if p == "" { + return args, nil + } + + raw := []byte(p) + err := json.Unmarshal(raw, &args) + if err == nil { + return args, nil + } + + // Fallback to parsing arguments in the legacy slice format + deprecated := map[string][]string{} + if legacyErr := json.Unmarshal(raw, &deprecated); legacyErr != nil { + return args, &invalidFilter{} + } + + args.fields = deprecatedArgs(deprecated) + return args, nil +} + +// UnmarshalJSON populates the Args from JSON encode bytes +func (args Args) UnmarshalJSON(raw []byte) error { + return json.Unmarshal(raw, &args.fields) +} + +// Get returns the list of values associated with the key +func (args Args) Get(key string) []string { + values := args.fields[key] + if values == nil { + return make([]string, 0) + } + slice := make([]string, 0, len(values)) + for key := range values { + slice = append(slice, key) + } + return slice +} + +// Add a new value to the set of values +func (args Args) Add(key, value string) { + if _, ok := args.fields[key]; ok { + args.fields[key][value] = true + } else { + args.fields[key] = map[string]bool{value: true} + } +} + +// Del removes a value from the set +func (args Args) Del(key, value string) { + if _, ok := args.fields[key]; ok { + delete(args.fields[key], value) + if len(args.fields[key]) == 0 { + delete(args.fields, key) + } + } +} + +// Len returns the number of keys in the mapping +func (args Args) Len() int { + return len(args.fields) +} + +// MatchKVList returns true if all the pairs in sources exist as key=value +// pairs in the mapping at key, or if there are no values at key. +func (args Args) MatchKVList(key string, sources map[string]string) bool { + fieldValues := args.fields[key] + + // do not filter if there is no filter set or cannot determine filter + if len(fieldValues) == 0 { + return true + } + + if len(sources) == 0 { + return false + } + + for value := range fieldValues { + testK, testV, hasValue := strings.Cut(value, "=") + + v, ok := sources[testK] + if !ok { + return false + } + if hasValue && testV != v { + return false + } + } + + return true +} + +// Match returns true if any of the values at key match the source string +func (args Args) Match(field, source string) bool { + if args.ExactMatch(field, source) { + return true + } + + fieldValues := args.fields[field] + for name2match := range fieldValues { + match, err := regexp.MatchString(name2match, source) + if err != nil { + continue + } + if match { + return true + } + } + return false +} + +// GetBoolOrDefault returns a boolean value of the key if the key is present +// and is intepretable as a boolean value. Otherwise the default value is returned. +// Error is not nil only if the filter values are not valid boolean or are conflicting. +func (args Args) GetBoolOrDefault(key string, defaultValue bool) (bool, error) { + fieldValues, ok := args.fields[key] + + if !ok { + return defaultValue, nil + } + + if len(fieldValues) == 0 { + return defaultValue, &invalidFilter{key, nil} + } + + isFalse := fieldValues["0"] || fieldValues["false"] + isTrue := fieldValues["1"] || fieldValues["true"] + + conflicting := isFalse && isTrue + invalid := !isFalse && !isTrue + + if conflicting || invalid { + return defaultValue, &invalidFilter{key, args.Get(key)} + } else if isFalse { + return false, nil + } else if isTrue { + return true, nil + } + + // This code shouldn't be reached. + return defaultValue, &unreachableCode{Filter: key, Value: args.Get(key)} +} + +// ExactMatch returns true if the source matches exactly one of the values. +func (args Args) ExactMatch(key, source string) bool { + fieldValues, ok := args.fields[key] + // do not filter if there is no filter set or cannot determine filter + if !ok || len(fieldValues) == 0 { + return true + } + + // try to match full name value to avoid O(N) regular expression matching + return fieldValues[source] +} + +// UniqueExactMatch returns true if there is only one value and the source +// matches exactly the value. +func (args Args) UniqueExactMatch(key, source string) bool { + fieldValues := args.fields[key] + // do not filter if there is no filter set or cannot determine filter + if len(fieldValues) == 0 { + return true + } + if len(args.fields[key]) != 1 { + return false + } + + // try to match full name value to avoid O(N) regular expression matching + return fieldValues[source] +} + +// FuzzyMatch returns true if the source matches exactly one value, or the +// source has one of the values as a prefix. +func (args Args) FuzzyMatch(key, source string) bool { + if args.ExactMatch(key, source) { + return true + } + + fieldValues := args.fields[key] + for prefix := range fieldValues { + if strings.HasPrefix(source, prefix) { + return true + } + } + return false +} + +// Contains returns true if the key exists in the mapping +func (args Args) Contains(field string) bool { + _, ok := args.fields[field] + return ok +} + +// Validate compared the set of accepted keys against the keys in the mapping. +// An error is returned if any mapping keys are not in the accepted set. +func (args Args) Validate(accepted map[string]bool) error { + for name := range args.fields { + if !accepted[name] { + return &invalidFilter{name, nil} + } + } + return nil +} + +// WalkValues iterates over the list of values for a key in the mapping and calls +// op() for each value. If op returns an error the iteration stops and the +// error is returned. +func (args Args) WalkValues(field string, op func(value string) error) error { + if _, ok := args.fields[field]; !ok { + return nil + } + for v := range args.fields[field] { + if err := op(v); err != nil { + return err + } + } + return nil +} + +// Clone returns a copy of args. +func (args Args) Clone() (newArgs Args) { + newArgs.fields = make(map[string]map[string]bool, len(args.fields)) + for k, m := range args.fields { + var mm map[string]bool + if m != nil { + mm = make(map[string]bool, len(m)) + for kk, v := range m { + mm[kk] = v + } + } + newArgs.fields[k] = mm + } + return newArgs +} + +func deprecatedArgs(d map[string][]string) map[string]map[string]bool { + m := map[string]map[string]bool{} + for k, v := range d { + values := map[string]bool{} + for _, vv := range v { + values[vv] = true + } + m[k] = values + } + return m +} + +func convertArgsToSlice(f map[string]map[string]bool) map[string][]string { + m := map[string][]string{} + for k, v := range f { + values := []string{} + for kk := range v { + if v[kk] { + values = append(values, kk) + } + } + m[k] = values + } + return m +} diff --git a/vendor/github.com/docker/docker/api/types/mount/mount.go b/vendor/github.com/docker/docker/api/types/mount/mount.go new file mode 100644 index 00000000..c68dcf65 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/mount/mount.go @@ -0,0 +1,150 @@ +package mount // import "github.com/docker/docker/api/types/mount" + +import ( + "os" +) + +// Type represents the type of a mount. +type Type string + +// Type constants +const ( + // TypeBind is the type for mounting host dir + TypeBind Type = "bind" + // TypeVolume is the type for remote storage volumes + TypeVolume Type = "volume" + // TypeTmpfs is the type for mounting tmpfs + TypeTmpfs Type = "tmpfs" + // TypeNamedPipe is the type for mounting Windows named pipes + TypeNamedPipe Type = "npipe" + // TypeCluster is the type for Swarm Cluster Volumes. + TypeCluster Type = "cluster" +) + +// Mount represents a mount (volume). +type Mount struct { + Type Type `json:",omitempty"` + // Source specifies the name of the mount. Depending on mount type, this + // may be a volume name or a host path, or even ignored. + // Source is not supported for tmpfs (must be an empty value) + Source string `json:",omitempty"` + Target string `json:",omitempty"` + ReadOnly bool `json:",omitempty"` // attempts recursive read-only if possible + Consistency Consistency `json:",omitempty"` + + BindOptions *BindOptions `json:",omitempty"` + VolumeOptions *VolumeOptions `json:",omitempty"` + TmpfsOptions *TmpfsOptions `json:",omitempty"` + ClusterOptions *ClusterOptions `json:",omitempty"` +} + +// Propagation represents the propagation of a mount. +type Propagation string + +const ( + // PropagationRPrivate RPRIVATE + PropagationRPrivate Propagation = "rprivate" + // PropagationPrivate PRIVATE + PropagationPrivate Propagation = "private" + // PropagationRShared RSHARED + PropagationRShared Propagation = "rshared" + // PropagationShared SHARED + PropagationShared Propagation = "shared" + // PropagationRSlave RSLAVE + PropagationRSlave Propagation = "rslave" + // PropagationSlave SLAVE + PropagationSlave Propagation = "slave" +) + +// Propagations is the list of all valid mount propagations +var Propagations = []Propagation{ + PropagationRPrivate, + PropagationPrivate, + PropagationRShared, + PropagationShared, + PropagationRSlave, + PropagationSlave, +} + +// Consistency represents the consistency requirements of a mount. +type Consistency string + +const ( + // ConsistencyFull guarantees bind mount-like consistency + ConsistencyFull Consistency = "consistent" + // ConsistencyCached mounts can cache read data and FS structure + ConsistencyCached Consistency = "cached" + // ConsistencyDelegated mounts can cache read and written data and structure + ConsistencyDelegated Consistency = "delegated" + // ConsistencyDefault provides "consistent" behavior unless overridden + ConsistencyDefault Consistency = "default" +) + +// BindOptions defines options specific to mounts of type "bind". +type BindOptions struct { + Propagation Propagation `json:",omitempty"` + NonRecursive bool `json:",omitempty"` + CreateMountpoint bool `json:",omitempty"` + // ReadOnlyNonRecursive makes the mount non-recursively read-only, but still leaves the mount recursive + // (unless NonRecursive is set to true in conjunction). + ReadOnlyNonRecursive bool `json:",omitempty"` + // ReadOnlyForceRecursive raises an error if the mount cannot be made recursively read-only. + ReadOnlyForceRecursive bool `json:",omitempty"` +} + +// VolumeOptions represents the options for a mount of type volume. +type VolumeOptions struct { + NoCopy bool `json:",omitempty"` + Labels map[string]string `json:",omitempty"` + Subpath string `json:",omitempty"` + DriverConfig *Driver `json:",omitempty"` +} + +// Driver represents a volume driver. +type Driver struct { + Name string `json:",omitempty"` + Options map[string]string `json:",omitempty"` +} + +// TmpfsOptions defines options specific to mounts of type "tmpfs". +type TmpfsOptions struct { + // Size sets the size of the tmpfs, in bytes. + // + // This will be converted to an operating system specific value + // depending on the host. For example, on linux, it will be converted to + // use a 'k', 'm' or 'g' syntax. BSD, though not widely supported with + // docker, uses a straight byte value. + // + // Percentages are not supported. + SizeBytes int64 `json:",omitempty"` + // Mode of the tmpfs upon creation + Mode os.FileMode `json:",omitempty"` + // Options to be passed to the tmpfs mount. An array of arrays. Flag + // options should be provided as 1-length arrays. Other types should be + // provided as 2-length arrays, where the first item is the key and the + // second the value. + Options [][]string `json:",omitempty"` + // TODO(stevvooe): There are several more tmpfs flags, specified in the + // daemon, that are accepted. Only the most basic are added for now. + // + // From https://github.com/moby/sys/blob/mount/v0.1.1/mount/flags.go#L47-L56 + // + // var validFlags = map[string]bool{ + // "": true, + // "size": true, X + // "mode": true, X + // "uid": true, + // "gid": true, + // "nr_inodes": true, + // "nr_blocks": true, + // "mpol": true, + // } + // + // Some of these may be straightforward to add, but others, such as + // uid/gid have implications in a clustered system. +} + +// ClusterOptions specifies options for a Cluster volume. +type ClusterOptions struct { + // intentionally empty +} diff --git a/vendor/github.com/docker/docker/api/types/network/create_response.go b/vendor/github.com/docker/docker/api/types/network/create_response.go new file mode 100644 index 00000000..c32b35bf --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/network/create_response.go @@ -0,0 +1,19 @@ +package network + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// CreateResponse NetworkCreateResponse +// +// OK response to NetworkCreate operation +// swagger:model CreateResponse +type CreateResponse struct { + + // The ID of the created network. + // Required: true + ID string `json:"Id"` + + // Warnings encountered when creating the container + // Required: true + Warning string `json:"Warning"` +} diff --git a/vendor/github.com/docker/docker/api/types/network/endpoint.go b/vendor/github.com/docker/docker/api/types/network/endpoint.go new file mode 100644 index 00000000..0fbb40b3 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/network/endpoint.go @@ -0,0 +1,147 @@ +package network + +import ( + "errors" + "fmt" + "net" + + "github.com/docker/docker/internal/multierror" +) + +// EndpointSettings stores the network endpoint details +type EndpointSettings struct { + // Configurations + IPAMConfig *EndpointIPAMConfig + Links []string + Aliases []string // Aliases holds the list of extra, user-specified DNS names for this endpoint. + // MacAddress may be used to specify a MAC address when the container is created. + // Once the container is running, it becomes operational data (it may contain a + // generated address). + MacAddress string + DriverOpts map[string]string + // Operational data + NetworkID string + EndpointID string + Gateway string + IPAddress string + IPPrefixLen int + IPv6Gateway string + GlobalIPv6Address string + GlobalIPv6PrefixLen int + // DNSNames holds all the (non fully qualified) DNS names associated to this endpoint. First entry is used to + // generate PTR records. + DNSNames []string +} + +// Copy makes a deep copy of `EndpointSettings` +func (es *EndpointSettings) Copy() *EndpointSettings { + epCopy := *es + if es.IPAMConfig != nil { + epCopy.IPAMConfig = es.IPAMConfig.Copy() + } + + if es.Links != nil { + links := make([]string, 0, len(es.Links)) + epCopy.Links = append(links, es.Links...) + } + + if es.Aliases != nil { + aliases := make([]string, 0, len(es.Aliases)) + epCopy.Aliases = append(aliases, es.Aliases...) + } + + if len(es.DNSNames) > 0 { + epCopy.DNSNames = make([]string, len(es.DNSNames)) + copy(epCopy.DNSNames, es.DNSNames) + } + + return &epCopy +} + +// EndpointIPAMConfig represents IPAM configurations for the endpoint +type EndpointIPAMConfig struct { + IPv4Address string `json:",omitempty"` + IPv6Address string `json:",omitempty"` + LinkLocalIPs []string `json:",omitempty"` +} + +// Copy makes a copy of the endpoint ipam config +func (cfg *EndpointIPAMConfig) Copy() *EndpointIPAMConfig { + cfgCopy := *cfg + cfgCopy.LinkLocalIPs = make([]string, 0, len(cfg.LinkLocalIPs)) + cfgCopy.LinkLocalIPs = append(cfgCopy.LinkLocalIPs, cfg.LinkLocalIPs...) + return &cfgCopy +} + +// NetworkSubnet describes a user-defined subnet for a specific network. It's only used to validate if an +// EndpointIPAMConfig is valid for a specific network. +type NetworkSubnet interface { + // Contains checks whether the NetworkSubnet contains [addr]. + Contains(addr net.IP) bool + // IsStatic checks whether the subnet was statically allocated (ie. user-defined). + IsStatic() bool +} + +// IsInRange checks whether static IP addresses are valid in a specific network. +func (cfg *EndpointIPAMConfig) IsInRange(v4Subnets []NetworkSubnet, v6Subnets []NetworkSubnet) error { + var errs []error + + if err := validateEndpointIPAddress(cfg.IPv4Address, v4Subnets); err != nil { + errs = append(errs, err) + } + if err := validateEndpointIPAddress(cfg.IPv6Address, v6Subnets); err != nil { + errs = append(errs, err) + } + + return multierror.Join(errs...) +} + +func validateEndpointIPAddress(epAddr string, ipamSubnets []NetworkSubnet) error { + if epAddr == "" { + return nil + } + + var staticSubnet bool + parsedAddr := net.ParseIP(epAddr) + for _, subnet := range ipamSubnets { + if subnet.IsStatic() { + staticSubnet = true + if subnet.Contains(parsedAddr) { + return nil + } + } + } + + if staticSubnet { + return fmt.Errorf("no configured subnet or ip-range contain the IP address %s", epAddr) + } + + return errors.New("user specified IP address is supported only when connecting to networks with user configured subnets") +} + +// Validate checks whether cfg is valid. +func (cfg *EndpointIPAMConfig) Validate() error { + if cfg == nil { + return nil + } + + var errs []error + + if cfg.IPv4Address != "" { + if addr := net.ParseIP(cfg.IPv4Address); addr == nil || addr.To4() == nil || addr.IsUnspecified() { + errs = append(errs, fmt.Errorf("invalid IPv4 address: %s", cfg.IPv4Address)) + } + } + if cfg.IPv6Address != "" { + if addr := net.ParseIP(cfg.IPv6Address); addr == nil || addr.To4() != nil || addr.IsUnspecified() { + errs = append(errs, fmt.Errorf("invalid IPv6 address: %s", cfg.IPv6Address)) + } + } + for _, addr := range cfg.LinkLocalIPs { + if parsed := net.ParseIP(addr); parsed == nil || parsed.IsUnspecified() { + errs = append(errs, fmt.Errorf("invalid link-local IP address: %s", addr)) + } + } + + return multierror.Join(errs...) +} diff --git a/vendor/github.com/docker/docker/api/types/network/ipam.go b/vendor/github.com/docker/docker/api/types/network/ipam.go new file mode 100644 index 00000000..f319e140 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/network/ipam.go @@ -0,0 +1,134 @@ +package network + +import ( + "errors" + "fmt" + "net/netip" + + "github.com/docker/docker/internal/multierror" +) + +// IPAM represents IP Address Management +type IPAM struct { + Driver string + Options map[string]string // Per network IPAM driver options + Config []IPAMConfig +} + +// IPAMConfig represents IPAM configurations +type IPAMConfig struct { + Subnet string `json:",omitempty"` + IPRange string `json:",omitempty"` + Gateway string `json:",omitempty"` + AuxAddress map[string]string `json:"AuxiliaryAddresses,omitempty"` +} + +type ipFamily string + +const ( + ip4 ipFamily = "IPv4" + ip6 ipFamily = "IPv6" +) + +// ValidateIPAM checks whether the network's IPAM passed as argument is valid. It returns a joinError of the list of +// errors found. +func ValidateIPAM(ipam *IPAM, enableIPv6 bool) error { + if ipam == nil { + return nil + } + + var errs []error + for _, cfg := range ipam.Config { + subnet, err := netip.ParsePrefix(cfg.Subnet) + if err != nil { + errs = append(errs, fmt.Errorf("invalid subnet %s: invalid CIDR block notation", cfg.Subnet)) + continue + } + subnetFamily := ip4 + if subnet.Addr().Is6() { + subnetFamily = ip6 + } + + if !enableIPv6 && subnetFamily == ip6 { + continue + } + + if subnet != subnet.Masked() { + errs = append(errs, fmt.Errorf("invalid subnet %s: it should be %s", subnet, subnet.Masked())) + } + + if ipRangeErrs := validateIPRange(cfg.IPRange, subnet, subnetFamily); len(ipRangeErrs) > 0 { + errs = append(errs, ipRangeErrs...) + } + + if err := validateAddress(cfg.Gateway, subnet, subnetFamily); err != nil { + errs = append(errs, fmt.Errorf("invalid gateway %s: %w", cfg.Gateway, err)) + } + + for auxName, aux := range cfg.AuxAddress { + if err := validateAddress(aux, subnet, subnetFamily); err != nil { + errs = append(errs, fmt.Errorf("invalid auxiliary address %s: %w", auxName, err)) + } + } + } + + if err := multierror.Join(errs...); err != nil { + return fmt.Errorf("invalid network config:\n%w", err) + } + + return nil +} + +func validateIPRange(ipRange string, subnet netip.Prefix, subnetFamily ipFamily) []error { + if ipRange == "" { + return nil + } + prefix, err := netip.ParsePrefix(ipRange) + if err != nil { + return []error{fmt.Errorf("invalid ip-range %s: invalid CIDR block notation", ipRange)} + } + family := ip4 + if prefix.Addr().Is6() { + family = ip6 + } + + if family != subnetFamily { + return []error{fmt.Errorf("invalid ip-range %s: parent subnet is an %s block", ipRange, subnetFamily)} + } + + var errs []error + if prefix.Bits() < subnet.Bits() { + errs = append(errs, fmt.Errorf("invalid ip-range %s: CIDR block is bigger than its parent subnet %s", ipRange, subnet)) + } + if prefix != prefix.Masked() { + errs = append(errs, fmt.Errorf("invalid ip-range %s: it should be %s", prefix, prefix.Masked())) + } + if !subnet.Overlaps(prefix) { + errs = append(errs, fmt.Errorf("invalid ip-range %s: parent subnet %s doesn't contain ip-range", ipRange, subnet)) + } + + return errs +} + +func validateAddress(address string, subnet netip.Prefix, subnetFamily ipFamily) error { + if address == "" { + return nil + } + addr, err := netip.ParseAddr(address) + if err != nil { + return errors.New("invalid address") + } + family := ip4 + if addr.Is6() { + family = ip6 + } + + if family != subnetFamily { + return fmt.Errorf("parent subnet is an %s block", subnetFamily) + } + if !subnet.Contains(addr) { + return fmt.Errorf("parent subnet %s doesn't contain this address", subnet) + } + + return nil +} diff --git a/vendor/github.com/docker/docker/api/types/network/network.go b/vendor/github.com/docker/docker/api/types/network/network.go new file mode 100644 index 00000000..c8db97a7 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/network/network.go @@ -0,0 +1,166 @@ +package network // import "github.com/docker/docker/api/types/network" + +import ( + "time" + + "github.com/docker/docker/api/types/filters" +) + +const ( + // NetworkDefault is a platform-independent alias to choose the platform-specific default network stack. + NetworkDefault = "default" + // NetworkHost is the name of the predefined network used when the NetworkMode host is selected (only available on Linux) + NetworkHost = "host" + // NetworkNone is the name of the predefined network used when the NetworkMode none is selected (available on both Linux and Windows) + NetworkNone = "none" + // NetworkBridge is the name of the default network on Linux + NetworkBridge = "bridge" + // NetworkNat is the name of the default network on Windows + NetworkNat = "nat" +) + +// CreateRequest is the request message sent to the server for network create call. +type CreateRequest struct { + CreateOptions + Name string // Name is the requested name of the network. + + // Deprecated: CheckDuplicate is deprecated since API v1.44, but it defaults to true when sent by the client + // package to older daemons. + CheckDuplicate *bool `json:",omitempty"` +} + +// CreateOptions holds options to create a network. +type CreateOptions struct { + Driver string // Driver is the driver-name used to create the network (e.g. `bridge`, `overlay`) + Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level). + EnableIPv6 *bool `json:",omitempty"` // EnableIPv6 represents whether to enable IPv6. + IPAM *IPAM // IPAM is the network's IP Address Management. + Internal bool // Internal represents if the network is used internal only. + Attachable bool // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode. + Ingress bool // Ingress indicates the network is providing the routing-mesh for the swarm cluster. + ConfigOnly bool // ConfigOnly creates a config-only network. Config-only networks are place-holder networks for network configurations to be used by other networks. ConfigOnly networks cannot be used directly to run containers or services. + ConfigFrom *ConfigReference // ConfigFrom specifies the source which will provide the configuration for this network. The specified network must be a config-only network; see [CreateOptions.ConfigOnly]. + Options map[string]string // Options specifies the network-specific options to use for when creating the network. + Labels map[string]string // Labels holds metadata specific to the network being created. +} + +// ListOptions holds parameters to filter the list of networks with. +type ListOptions struct { + Filters filters.Args +} + +// InspectOptions holds parameters to inspect network. +type InspectOptions struct { + Scope string + Verbose bool +} + +// ConnectOptions represents the data to be used to connect a container to the +// network. +type ConnectOptions struct { + Container string + EndpointConfig *EndpointSettings `json:",omitempty"` +} + +// DisconnectOptions represents the data to be used to disconnect a container +// from the network. +type DisconnectOptions struct { + Container string + Force bool +} + +// Inspect is the body of the "get network" http response message. +type Inspect struct { + Name string // Name is the name of the network + ID string `json:"Id"` // ID uniquely identifies a network on a single machine + Created time.Time // Created is the time the network created + Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level) + Driver string // Driver is the Driver name used to create the network (e.g. `bridge`, `overlay`) + EnableIPv6 bool // EnableIPv6 represents whether to enable IPv6 + IPAM IPAM // IPAM is the network's IP Address Management + Internal bool // Internal represents if the network is used internal only + Attachable bool // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode. + Ingress bool // Ingress indicates the network is providing the routing-mesh for the swarm cluster. + ConfigFrom ConfigReference // ConfigFrom specifies the source which will provide the configuration for this network. + ConfigOnly bool // ConfigOnly networks are place-holder networks for network configurations to be used by other networks. ConfigOnly networks cannot be used directly to run containers or services. + Containers map[string]EndpointResource // Containers contains endpoints belonging to the network + Options map[string]string // Options holds the network specific options to use for when creating the network + Labels map[string]string // Labels holds metadata specific to the network being created + Peers []PeerInfo `json:",omitempty"` // List of peer nodes for an overlay network + Services map[string]ServiceInfo `json:",omitempty"` +} + +// Summary is used as response when listing networks. It currently is an alias +// for [Inspect], but may diverge in the future, as not all information may +// be included when listing networks. +type Summary = Inspect + +// Address represents an IP address +type Address struct { + Addr string + PrefixLen int +} + +// PeerInfo represents one peer of an overlay network +type PeerInfo struct { + Name string + IP string +} + +// Task carries the information about one backend task +type Task struct { + Name string + EndpointID string + EndpointIP string + Info map[string]string +} + +// ServiceInfo represents service parameters with the list of service's tasks +type ServiceInfo struct { + VIP string + Ports []string + LocalLBIndex int + Tasks []Task +} + +// EndpointResource contains network resources allocated and used for a +// container in a network. +type EndpointResource struct { + Name string + EndpointID string + MacAddress string + IPv4Address string + IPv6Address string +} + +// NetworkingConfig represents the container's networking configuration for each of its interfaces +// Carries the networking configs specified in the `docker run` and `docker network connect` commands +type NetworkingConfig struct { + EndpointsConfig map[string]*EndpointSettings // Endpoint configs for each connecting network +} + +// ConfigReference specifies the source which provides a network's configuration +type ConfigReference struct { + Network string +} + +var acceptedFilters = map[string]bool{ + "dangling": true, + "driver": true, + "id": true, + "label": true, + "name": true, + "scope": true, + "type": true, +} + +// ValidateFilters validates the list of filter args with the available filters. +func ValidateFilters(filter filters.Args) error { + return filter.Validate(acceptedFilters) +} + +// PruneReport contains the response for Engine API: +// POST "/networks/prune" +type PruneReport struct { + NetworksDeleted []string +} diff --git a/vendor/github.com/docker/docker/api/types/strslice/strslice.go b/vendor/github.com/docker/docker/api/types/strslice/strslice.go new file mode 100644 index 00000000..82921ceb --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/strslice/strslice.go @@ -0,0 +1,30 @@ +package strslice // import "github.com/docker/docker/api/types/strslice" + +import "encoding/json" + +// StrSlice represents a string or an array of strings. +// We need to override the json decoder to accept both options. +type StrSlice []string + +// UnmarshalJSON decodes the byte slice whether it's a string or an array of +// strings. This method is needed to implement json.Unmarshaler. +func (e *StrSlice) UnmarshalJSON(b []byte) error { + if len(b) == 0 { + // With no input, we preserve the existing value by returning nil and + // leaving the target alone. This allows defining default values for + // the type. + return nil + } + + p := make([]string, 0, 1) + if err := json.Unmarshal(b, &p); err != nil { + var s string + if err := json.Unmarshal(b, &s); err != nil { + return err + } + p = append(p, s) + } + + *e = p + return nil +} diff --git a/vendor/github.com/docker/docker/api/types/swarm/common.go b/vendor/github.com/docker/docker/api/types/swarm/common.go new file mode 100644 index 00000000..5ded7dba --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/common.go @@ -0,0 +1,48 @@ +package swarm // import "github.com/docker/docker/api/types/swarm" + +import ( + "strconv" + "time" +) + +// Version represents the internal object version. +type Version struct { + Index uint64 `json:",omitempty"` +} + +// String implements fmt.Stringer interface. +func (v Version) String() string { + return strconv.FormatUint(v.Index, 10) +} + +// Meta is a base object inherited by most of the other once. +type Meta struct { + Version Version `json:",omitempty"` + CreatedAt time.Time `json:",omitempty"` + UpdatedAt time.Time `json:",omitempty"` +} + +// Annotations represents how to describe an object. +type Annotations struct { + Name string `json:",omitempty"` + Labels map[string]string `json:"Labels"` +} + +// Driver represents a driver (network, logging, secrets backend). +type Driver struct { + Name string `json:",omitempty"` + Options map[string]string `json:",omitempty"` +} + +// TLSInfo represents the TLS information about what CA certificate is trusted, +// and who the issuer for a TLS certificate is +type TLSInfo struct { + // TrustRoot is the trusted CA root certificate in PEM format + TrustRoot string `json:",omitempty"` + + // CertIssuer is the raw subject bytes of the issuer + CertIssuerSubject []byte `json:",omitempty"` + + // CertIssuerPublicKey is the raw public key bytes of the issuer + CertIssuerPublicKey []byte `json:",omitempty"` +} diff --git a/vendor/github.com/docker/docker/api/types/swarm/config.go b/vendor/github.com/docker/docker/api/types/swarm/config.go new file mode 100644 index 00000000..16202ccc --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/config.go @@ -0,0 +1,40 @@ +package swarm // import "github.com/docker/docker/api/types/swarm" + +import "os" + +// Config represents a config. +type Config struct { + ID string + Meta + Spec ConfigSpec +} + +// ConfigSpec represents a config specification from a config in swarm +type ConfigSpec struct { + Annotations + Data []byte `json:",omitempty"` + + // Templating controls whether and how to evaluate the config payload as + // a template. If it is not set, no templating is used. + Templating *Driver `json:",omitempty"` +} + +// ConfigReferenceFileTarget is a file target in a config reference +type ConfigReferenceFileTarget struct { + Name string + UID string + GID string + Mode os.FileMode +} + +// ConfigReferenceRuntimeTarget is a target for a config specifying that it +// isn't mounted into the container but instead has some other purpose. +type ConfigReferenceRuntimeTarget struct{} + +// ConfigReference is a reference to a config in swarm +type ConfigReference struct { + File *ConfigReferenceFileTarget `json:",omitempty"` + Runtime *ConfigReferenceRuntimeTarget `json:",omitempty"` + ConfigID string + ConfigName string +} diff --git a/vendor/github.com/docker/docker/api/types/swarm/container.go b/vendor/github.com/docker/docker/api/types/swarm/container.go new file mode 100644 index 00000000..30e3de70 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/container.go @@ -0,0 +1,119 @@ +package swarm // import "github.com/docker/docker/api/types/swarm" + +import ( + "time" + + "github.com/docker/docker/api/types/container" + "github.com/docker/docker/api/types/mount" +) + +// DNSConfig specifies DNS related configurations in resolver configuration file (resolv.conf) +// Detailed documentation is available in: +// http://man7.org/linux/man-pages/man5/resolv.conf.5.html +// `nameserver`, `search`, `options` have been supported. +// TODO: `domain` is not supported yet. +type DNSConfig struct { + // Nameservers specifies the IP addresses of the name servers + Nameservers []string `json:",omitempty"` + // Search specifies the search list for host-name lookup + Search []string `json:",omitempty"` + // Options allows certain internal resolver variables to be modified + Options []string `json:",omitempty"` +} + +// SELinuxContext contains the SELinux labels of the container. +type SELinuxContext struct { + Disable bool + + User string + Role string + Type string + Level string +} + +// SeccompMode is the type used for the enumeration of possible seccomp modes +// in SeccompOpts +type SeccompMode string + +const ( + SeccompModeDefault SeccompMode = "default" + SeccompModeUnconfined SeccompMode = "unconfined" + SeccompModeCustom SeccompMode = "custom" +) + +// SeccompOpts defines the options for configuring seccomp on a swarm-managed +// container. +type SeccompOpts struct { + // Mode is the SeccompMode used for the container. + Mode SeccompMode `json:",omitempty"` + // Profile is the custom seccomp profile as a json object to be used with + // the container. Mode should be set to SeccompModeCustom when using a + // custom profile in this manner. + Profile []byte `json:",omitempty"` +} + +// AppArmorMode is type used for the enumeration of possible AppArmor modes in +// AppArmorOpts +type AppArmorMode string + +const ( + AppArmorModeDefault AppArmorMode = "default" + AppArmorModeDisabled AppArmorMode = "disabled" +) + +// AppArmorOpts defines the options for configuring AppArmor on a swarm-managed +// container. Currently, custom AppArmor profiles are not supported. +type AppArmorOpts struct { + Mode AppArmorMode `json:",omitempty"` +} + +// CredentialSpec for managed service account (Windows only) +type CredentialSpec struct { + Config string + File string + Registry string +} + +// Privileges defines the security options for the container. +type Privileges struct { + CredentialSpec *CredentialSpec + SELinuxContext *SELinuxContext + Seccomp *SeccompOpts `json:",omitempty"` + AppArmor *AppArmorOpts `json:",omitempty"` + NoNewPrivileges bool +} + +// ContainerSpec represents the spec of a container. +type ContainerSpec struct { + Image string `json:",omitempty"` + Labels map[string]string `json:",omitempty"` + Command []string `json:",omitempty"` + Args []string `json:",omitempty"` + Hostname string `json:",omitempty"` + Env []string `json:",omitempty"` + Dir string `json:",omitempty"` + User string `json:",omitempty"` + Groups []string `json:",omitempty"` + Privileges *Privileges `json:",omitempty"` + Init *bool `json:",omitempty"` + StopSignal string `json:",omitempty"` + TTY bool `json:",omitempty"` + OpenStdin bool `json:",omitempty"` + ReadOnly bool `json:",omitempty"` + Mounts []mount.Mount `json:",omitempty"` + StopGracePeriod *time.Duration `json:",omitempty"` + Healthcheck *container.HealthConfig `json:",omitempty"` + // The format of extra hosts on swarmkit is specified in: + // http://man7.org/linux/man-pages/man5/hosts.5.html + // IP_address canonical_hostname [aliases...] + Hosts []string `json:",omitempty"` + DNSConfig *DNSConfig `json:",omitempty"` + Secrets []*SecretReference `json:",omitempty"` + Configs []*ConfigReference `json:",omitempty"` + Isolation container.Isolation `json:",omitempty"` + Sysctls map[string]string `json:",omitempty"` + CapabilityAdd []string `json:",omitempty"` + CapabilityDrop []string `json:",omitempty"` + Ulimits []*container.Ulimit `json:",omitempty"` + OomScoreAdj int64 `json:",omitempty"` +} diff --git a/vendor/github.com/docker/docker/api/types/swarm/network.go b/vendor/github.com/docker/docker/api/types/swarm/network.go new file mode 100644 index 00000000..98ef3284 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/network.go @@ -0,0 +1,121 @@ +package swarm // import "github.com/docker/docker/api/types/swarm" + +import ( + "github.com/docker/docker/api/types/network" +) + +// Endpoint represents an endpoint. +type Endpoint struct { + Spec EndpointSpec `json:",omitempty"` + Ports []PortConfig `json:",omitempty"` + VirtualIPs []EndpointVirtualIP `json:",omitempty"` +} + +// EndpointSpec represents the spec of an endpoint. +type EndpointSpec struct { + Mode ResolutionMode `json:",omitempty"` + Ports []PortConfig `json:",omitempty"` +} + +// ResolutionMode represents a resolution mode. +type ResolutionMode string + +const ( + // ResolutionModeVIP VIP + ResolutionModeVIP ResolutionMode = "vip" + // ResolutionModeDNSRR DNSRR + ResolutionModeDNSRR ResolutionMode = "dnsrr" +) + +// PortConfig represents the config of a port. +type PortConfig struct { + Name string `json:",omitempty"` + Protocol PortConfigProtocol `json:",omitempty"` + // TargetPort is the port inside the container + TargetPort uint32 `json:",omitempty"` + // PublishedPort is the port on the swarm hosts + PublishedPort uint32 `json:",omitempty"` + // PublishMode is the mode in which port is published + PublishMode PortConfigPublishMode `json:",omitempty"` +} + +// PortConfigPublishMode represents the mode in which the port is to +// be published. +type PortConfigPublishMode string + +const ( + // PortConfigPublishModeIngress is used for ports published + // for ingress load balancing using routing mesh. + PortConfigPublishModeIngress PortConfigPublishMode = "ingress" + // PortConfigPublishModeHost is used for ports published + // for direct host level access on the host where the task is running. + PortConfigPublishModeHost PortConfigPublishMode = "host" +) + +// PortConfigProtocol represents the protocol of a port. +type PortConfigProtocol string + +const ( + // TODO(stevvooe): These should be used generally, not just for PortConfig. + + // PortConfigProtocolTCP TCP + PortConfigProtocolTCP PortConfigProtocol = "tcp" + // PortConfigProtocolUDP UDP + PortConfigProtocolUDP PortConfigProtocol = "udp" + // PortConfigProtocolSCTP SCTP + PortConfigProtocolSCTP PortConfigProtocol = "sctp" +) + +// EndpointVirtualIP represents the virtual ip of a port. +type EndpointVirtualIP struct { + NetworkID string `json:",omitempty"` + Addr string `json:",omitempty"` +} + +// Network represents a network. +type Network struct { + ID string + Meta + Spec NetworkSpec `json:",omitempty"` + DriverState Driver `json:",omitempty"` + IPAMOptions *IPAMOptions `json:",omitempty"` +} + +// NetworkSpec represents the spec of a network. +type NetworkSpec struct { + Annotations + DriverConfiguration *Driver `json:",omitempty"` + IPv6Enabled bool `json:",omitempty"` + Internal bool `json:",omitempty"` + Attachable bool `json:",omitempty"` + Ingress bool `json:",omitempty"` + IPAMOptions *IPAMOptions `json:",omitempty"` + ConfigFrom *network.ConfigReference `json:",omitempty"` + Scope string `json:",omitempty"` +} + +// NetworkAttachmentConfig represents the configuration of a network attachment. +type NetworkAttachmentConfig struct { + Target string `json:",omitempty"` + Aliases []string `json:",omitempty"` + DriverOpts map[string]string `json:",omitempty"` +} + +// NetworkAttachment represents a network attachment. +type NetworkAttachment struct { + Network Network `json:",omitempty"` + Addresses []string `json:",omitempty"` +} + +// IPAMOptions represents ipam options. +type IPAMOptions struct { + Driver Driver `json:",omitempty"` + Configs []IPAMConfig `json:",omitempty"` +} + +// IPAMConfig represents ipam configuration. +type IPAMConfig struct { + Subnet string `json:",omitempty"` + Range string `json:",omitempty"` + Gateway string `json:",omitempty"` +} diff --git a/vendor/github.com/docker/docker/api/types/swarm/node.go b/vendor/github.com/docker/docker/api/types/swarm/node.go new file mode 100644 index 00000000..bb98d5ee --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/node.go @@ -0,0 +1,139 @@ +package swarm // import "github.com/docker/docker/api/types/swarm" + +// Node represents a node. +type Node struct { + ID string + Meta + // Spec defines the desired state of the node as specified by the user. + // The system will honor this and will *never* modify it. + Spec NodeSpec `json:",omitempty"` + // Description encapsulates the properties of the Node as reported by the + // agent. + Description NodeDescription `json:",omitempty"` + // Status provides the current status of the node, as seen by the manager. + Status NodeStatus `json:",omitempty"` + // ManagerStatus provides the current status of the node's manager + // component, if the node is a manager. + ManagerStatus *ManagerStatus `json:",omitempty"` +} + +// NodeSpec represents the spec of a node. +type NodeSpec struct { + Annotations + Role NodeRole `json:",omitempty"` + Availability NodeAvailability `json:",omitempty"` +} + +// NodeRole represents the role of a node. +type NodeRole string + +const ( + // NodeRoleWorker WORKER + NodeRoleWorker NodeRole = "worker" + // NodeRoleManager MANAGER + NodeRoleManager NodeRole = "manager" +) + +// NodeAvailability represents the availability of a node. +type NodeAvailability string + +const ( + // NodeAvailabilityActive ACTIVE + NodeAvailabilityActive NodeAvailability = "active" + // NodeAvailabilityPause PAUSE + NodeAvailabilityPause NodeAvailability = "pause" + // NodeAvailabilityDrain DRAIN + NodeAvailabilityDrain NodeAvailability = "drain" +) + +// NodeDescription represents the description of a node. +type NodeDescription struct { + Hostname string `json:",omitempty"` + Platform Platform `json:",omitempty"` + Resources Resources `json:",omitempty"` + Engine EngineDescription `json:",omitempty"` + TLSInfo TLSInfo `json:",omitempty"` + CSIInfo []NodeCSIInfo `json:",omitempty"` +} + +// Platform represents the platform (Arch/OS). +type Platform struct { + Architecture string `json:",omitempty"` + OS string `json:",omitempty"` +} + +// EngineDescription represents the description of an engine. +type EngineDescription struct { + EngineVersion string `json:",omitempty"` + Labels map[string]string `json:",omitempty"` + Plugins []PluginDescription `json:",omitempty"` +} + +// NodeCSIInfo represents information about a CSI plugin available on the node +type NodeCSIInfo struct { + // PluginName is the name of the CSI plugin. + PluginName string `json:",omitempty"` + // NodeID is the ID of the node as reported by the CSI plugin. This is + // different from the swarm node ID. + NodeID string `json:",omitempty"` + // MaxVolumesPerNode is the maximum number of volumes that may be published + // to this node + MaxVolumesPerNode int64 `json:",omitempty"` + // AccessibleTopology indicates the location of this node in the CSI + // plugin's topology + AccessibleTopology *Topology `json:",omitempty"` +} + +// PluginDescription represents the description of an engine plugin. +type PluginDescription struct { + Type string `json:",omitempty"` + Name string `json:",omitempty"` +} + +// NodeStatus represents the status of a node. +type NodeStatus struct { + State NodeState `json:",omitempty"` + Message string `json:",omitempty"` + Addr string `json:",omitempty"` +} + +// Reachability represents the reachability of a node. +type Reachability string + +const ( + // ReachabilityUnknown UNKNOWN + ReachabilityUnknown Reachability = "unknown" + // ReachabilityUnreachable UNREACHABLE + ReachabilityUnreachable Reachability = "unreachable" + // ReachabilityReachable REACHABLE + ReachabilityReachable Reachability = "reachable" +) + +// ManagerStatus represents the status of a manager. +type ManagerStatus struct { + Leader bool `json:",omitempty"` + Reachability Reachability `json:",omitempty"` + Addr string `json:",omitempty"` +} + +// NodeState represents the state of a node. +type NodeState string + +const ( + // NodeStateUnknown UNKNOWN + NodeStateUnknown NodeState = "unknown" + // NodeStateDown DOWN + NodeStateDown NodeState = "down" + // NodeStateReady READY + NodeStateReady NodeState = "ready" + // NodeStateDisconnected DISCONNECTED + NodeStateDisconnected NodeState = "disconnected" +) + +// Topology defines the CSI topology of this node. This type is a duplicate of +// github.com/docker/docker/api/types.Topology. Because the type definition +// is so simple and to avoid complicated structure or circular imports, we just +// duplicate it here. See that type for full documentation +type Topology struct { + Segments map[string]string `json:",omitempty"` +} diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime.go b/vendor/github.com/docker/docker/api/types/swarm/runtime.go new file mode 100644 index 00000000..0c77403c --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/runtime.go @@ -0,0 +1,27 @@ +package swarm // import "github.com/docker/docker/api/types/swarm" + +// RuntimeType is the type of runtime used for the TaskSpec +type RuntimeType string + +// RuntimeURL is the proto type url +type RuntimeURL string + +const ( + // RuntimeContainer is the container based runtime + RuntimeContainer RuntimeType = "container" + // RuntimePlugin is the plugin based runtime + RuntimePlugin RuntimeType = "plugin" + // RuntimeNetworkAttachment is the network attachment runtime + RuntimeNetworkAttachment RuntimeType = "attachment" + + // RuntimeURLContainer is the proto url for the container type + RuntimeURLContainer RuntimeURL = "types.docker.com/RuntimeContainer" + // RuntimeURLPlugin is the proto url for the plugin type + RuntimeURLPlugin RuntimeURL = "types.docker.com/RuntimePlugin" +) + +// NetworkAttachmentSpec represents the runtime spec type for network +// attachment tasks +type NetworkAttachmentSpec struct { + ContainerID string +} diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime/gen.go b/vendor/github.com/docker/docker/api/types/swarm/runtime/gen.go new file mode 100644 index 00000000..292bd7af --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/runtime/gen.go @@ -0,0 +1,3 @@ +//go:generate protoc --gogofaster_out=import_path=github.com/docker/docker/api/types/swarm/runtime:. plugin.proto + +package runtime // import "github.com/docker/docker/api/types/swarm/runtime" diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.pb.go b/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.pb.go new file mode 100644 index 00000000..32aaf0d5 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.pb.go @@ -0,0 +1,808 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: plugin.proto + +package runtime + +import ( + fmt "fmt" + proto "github.com/gogo/protobuf/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// PluginSpec defines the base payload which clients can specify for creating +// a service with the plugin runtime. +type PluginSpec struct { + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + Remote string `protobuf:"bytes,2,opt,name=remote,proto3" json:"remote,omitempty"` + Privileges []*PluginPrivilege `protobuf:"bytes,3,rep,name=privileges,proto3" json:"privileges,omitempty"` + Disabled bool `protobuf:"varint,4,opt,name=disabled,proto3" json:"disabled,omitempty"` + Env []string `protobuf:"bytes,5,rep,name=env,proto3" json:"env,omitempty"` +} + +func (m *PluginSpec) Reset() { *m = PluginSpec{} } +func (m *PluginSpec) String() string { return proto.CompactTextString(m) } +func (*PluginSpec) ProtoMessage() {} +func (*PluginSpec) Descriptor() ([]byte, []int) { + return fileDescriptor_22a625af4bc1cc87, []int{0} +} +func (m *PluginSpec) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PluginSpec) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PluginSpec.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PluginSpec) XXX_Merge(src proto.Message) { + xxx_messageInfo_PluginSpec.Merge(m, src) +} +func (m *PluginSpec) XXX_Size() int { + return m.Size() +} +func (m *PluginSpec) XXX_DiscardUnknown() { + xxx_messageInfo_PluginSpec.DiscardUnknown(m) +} + +var xxx_messageInfo_PluginSpec proto.InternalMessageInfo + +func (m *PluginSpec) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *PluginSpec) GetRemote() string { + if m != nil { + return m.Remote + } + return "" +} + +func (m *PluginSpec) GetPrivileges() []*PluginPrivilege { + if m != nil { + return m.Privileges + } + return nil +} + +func (m *PluginSpec) GetDisabled() bool { + if m != nil { + return m.Disabled + } + return false +} + +func (m *PluginSpec) GetEnv() []string { + if m != nil { + return m.Env + } + return nil +} + +// PluginPrivilege describes a permission the user has to accept +// upon installing a plugin. +type PluginPrivilege struct { + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` + Value []string `protobuf:"bytes,3,rep,name=value,proto3" json:"value,omitempty"` +} + +func (m *PluginPrivilege) Reset() { *m = PluginPrivilege{} } +func (m *PluginPrivilege) String() string { return proto.CompactTextString(m) } +func (*PluginPrivilege) ProtoMessage() {} +func (*PluginPrivilege) Descriptor() ([]byte, []int) { + return fileDescriptor_22a625af4bc1cc87, []int{1} +} +func (m *PluginPrivilege) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PluginPrivilege) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PluginPrivilege.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PluginPrivilege) XXX_Merge(src proto.Message) { + xxx_messageInfo_PluginPrivilege.Merge(m, src) +} +func (m *PluginPrivilege) XXX_Size() int { + return m.Size() +} +func (m *PluginPrivilege) XXX_DiscardUnknown() { + xxx_messageInfo_PluginPrivilege.DiscardUnknown(m) +} + +var xxx_messageInfo_PluginPrivilege proto.InternalMessageInfo + +func (m *PluginPrivilege) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *PluginPrivilege) GetDescription() string { + if m != nil { + return m.Description + } + return "" +} + +func (m *PluginPrivilege) GetValue() []string { + if m != nil { + return m.Value + } + return nil +} + +func init() { + proto.RegisterType((*PluginSpec)(nil), "PluginSpec") + proto.RegisterType((*PluginPrivilege)(nil), "PluginPrivilege") +} + +func init() { proto.RegisterFile("plugin.proto", fileDescriptor_22a625af4bc1cc87) } + +var fileDescriptor_22a625af4bc1cc87 = []byte{ + // 225 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x29, 0xc8, 0x29, 0x4d, + 0xcf, 0xcc, 0xd3, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x57, 0x9a, 0xc1, 0xc8, 0xc5, 0x15, 0x00, 0x16, + 0x08, 0x2e, 0x48, 0x4d, 0x16, 0x12, 0xe2, 0x62, 0xc9, 0x4b, 0xcc, 0x4d, 0x95, 0x60, 0x54, 0x60, + 0xd4, 0xe0, 0x0c, 0x02, 0xb3, 0x85, 0xc4, 0xb8, 0xd8, 0x8a, 0x52, 0x73, 0xf3, 0x4b, 0x52, 0x25, + 0x98, 0xc0, 0xa2, 0x50, 0x9e, 0x90, 0x01, 0x17, 0x57, 0x41, 0x51, 0x66, 0x59, 0x66, 0x4e, 0x6a, + 0x7a, 0x6a, 0xb1, 0x04, 0xb3, 0x02, 0xb3, 0x06, 0xb7, 0x91, 0x80, 0x1e, 0xc4, 0xb0, 0x00, 0x98, + 0x44, 0x10, 0x92, 0x1a, 0x21, 0x29, 0x2e, 0x8e, 0x94, 0xcc, 0xe2, 0xc4, 0xa4, 0x9c, 0xd4, 0x14, + 0x09, 0x16, 0x05, 0x46, 0x0d, 0x8e, 0x20, 0x38, 0x5f, 0x48, 0x80, 0x8b, 0x39, 0x35, 0xaf, 0x4c, + 0x82, 0x55, 0x81, 0x59, 0x83, 0x33, 0x08, 0xc4, 0x54, 0x8a, 0xe5, 0xe2, 0x47, 0x33, 0x0c, 0xab, + 0xf3, 0x14, 0xb8, 0xb8, 0x53, 0x52, 0x8b, 0x93, 0x8b, 0x32, 0x0b, 0x4a, 0x32, 0xf3, 0xf3, 0xa0, + 0x6e, 0x44, 0x16, 0x12, 0x12, 0xe1, 0x62, 0x2d, 0x4b, 0xcc, 0x29, 0x4d, 0x05, 0xbb, 0x91, 0x33, + 0x08, 0xc2, 0x71, 0x92, 0x38, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, + 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x24, 0x36, + 0x70, 0xd0, 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x37, 0xea, 0xe2, 0xca, 0x2a, 0x01, 0x00, + 0x00, +} + +func (m *PluginSpec) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PluginSpec) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PluginSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Env) > 0 { + for iNdEx := len(m.Env) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Env[iNdEx]) + copy(dAtA[i:], m.Env[iNdEx]) + i = encodeVarintPlugin(dAtA, i, uint64(len(m.Env[iNdEx]))) + i-- + dAtA[i] = 0x2a + } + } + if m.Disabled { + i-- + if m.Disabled { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x20 + } + if len(m.Privileges) > 0 { + for iNdEx := len(m.Privileges) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Privileges[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintPlugin(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if len(m.Remote) > 0 { + i -= len(m.Remote) + copy(dAtA[i:], m.Remote) + i = encodeVarintPlugin(dAtA, i, uint64(len(m.Remote))) + i-- + dAtA[i] = 0x12 + } + if len(m.Name) > 0 { + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintPlugin(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *PluginPrivilege) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PluginPrivilege) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PluginPrivilege) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Value) > 0 { + for iNdEx := len(m.Value) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Value[iNdEx]) + copy(dAtA[i:], m.Value[iNdEx]) + i = encodeVarintPlugin(dAtA, i, uint64(len(m.Value[iNdEx]))) + i-- + dAtA[i] = 0x1a + } + } + if len(m.Description) > 0 { + i -= len(m.Description) + copy(dAtA[i:], m.Description) + i = encodeVarintPlugin(dAtA, i, uint64(len(m.Description))) + i-- + dAtA[i] = 0x12 + } + if len(m.Name) > 0 { + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintPlugin(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintPlugin(dAtA []byte, offset int, v uint64) int { + offset -= sovPlugin(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *PluginSpec) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovPlugin(uint64(l)) + } + l = len(m.Remote) + if l > 0 { + n += 1 + l + sovPlugin(uint64(l)) + } + if len(m.Privileges) > 0 { + for _, e := range m.Privileges { + l = e.Size() + n += 1 + l + sovPlugin(uint64(l)) + } + } + if m.Disabled { + n += 2 + } + if len(m.Env) > 0 { + for _, s := range m.Env { + l = len(s) + n += 1 + l + sovPlugin(uint64(l)) + } + } + return n +} + +func (m *PluginPrivilege) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovPlugin(uint64(l)) + } + l = len(m.Description) + if l > 0 { + n += 1 + l + sovPlugin(uint64(l)) + } + if len(m.Value) > 0 { + for _, s := range m.Value { + l = len(s) + n += 1 + l + sovPlugin(uint64(l)) + } + } + return n +} + +func sovPlugin(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozPlugin(x uint64) (n int) { + return sovPlugin(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *PluginSpec) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPlugin + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PluginSpec: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PluginSpec: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPlugin + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthPlugin + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPlugin + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Remote", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPlugin + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthPlugin + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPlugin + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Remote = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Privileges", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPlugin + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPlugin + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthPlugin + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Privileges = append(m.Privileges, &PluginPrivilege{}) + if err := m.Privileges[len(m.Privileges)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Disabled", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPlugin + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Disabled = bool(v != 0) + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Env", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPlugin + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthPlugin + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPlugin + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Env = append(m.Env, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPlugin(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthPlugin + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PluginPrivilege) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPlugin + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PluginPrivilege: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PluginPrivilege: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPlugin + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthPlugin + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPlugin + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPlugin + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthPlugin + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPlugin + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPlugin + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthPlugin + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPlugin + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Value = append(m.Value, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPlugin(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthPlugin + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipPlugin(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPlugin + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPlugin + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPlugin + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthPlugin + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupPlugin + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthPlugin + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthPlugin = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowPlugin = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupPlugin = fmt.Errorf("proto: unexpected end of group") +) diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.proto b/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.proto new file mode 100644 index 00000000..e311b36b --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.proto @@ -0,0 +1,19 @@ +syntax = "proto3"; + +// PluginSpec defines the base payload which clients can specify for creating +// a service with the plugin runtime. +message PluginSpec { + string name = 1; + string remote = 2; + repeated PluginPrivilege privileges = 3; + bool disabled = 4; + repeated string env = 5; +} + +// PluginPrivilege describes a permission the user has to accept +// upon installing a plugin. +message PluginPrivilege { + string name = 1; + string description = 2; + repeated string value = 3; +} diff --git a/vendor/github.com/docker/docker/api/types/swarm/secret.go b/vendor/github.com/docker/docker/api/types/swarm/secret.go new file mode 100644 index 00000000..d5213ec9 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/secret.go @@ -0,0 +1,36 @@ +package swarm // import "github.com/docker/docker/api/types/swarm" + +import "os" + +// Secret represents a secret. +type Secret struct { + ID string + Meta + Spec SecretSpec +} + +// SecretSpec represents a secret specification from a secret in swarm +type SecretSpec struct { + Annotations + Data []byte `json:",omitempty"` + Driver *Driver `json:",omitempty"` // name of the secrets driver used to fetch the secret's value from an external secret store + + // Templating controls whether and how to evaluate the secret payload as + // a template. If it is not set, no templating is used. + Templating *Driver `json:",omitempty"` +} + +// SecretReferenceFileTarget is a file target in a secret reference +type SecretReferenceFileTarget struct { + Name string + UID string + GID string + Mode os.FileMode +} + +// SecretReference is a reference to a secret in swarm +type SecretReference struct { + File *SecretReferenceFileTarget + SecretID string + SecretName string +} diff --git a/vendor/github.com/docker/docker/api/types/swarm/service.go b/vendor/github.com/docker/docker/api/types/swarm/service.go new file mode 100644 index 00000000..5b6d5ec1 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/service.go @@ -0,0 +1,202 @@ +package swarm // import "github.com/docker/docker/api/types/swarm" + +import "time" + +// Service represents a service. +type Service struct { + ID string + Meta + Spec ServiceSpec `json:",omitempty"` + PreviousSpec *ServiceSpec `json:",omitempty"` + Endpoint Endpoint `json:",omitempty"` + UpdateStatus *UpdateStatus `json:",omitempty"` + + // ServiceStatus is an optional, extra field indicating the number of + // desired and running tasks. It is provided primarily as a shortcut to + // calculating these values client-side, which otherwise would require + // listing all tasks for a service, an operation that could be + // computation and network expensive. + ServiceStatus *ServiceStatus `json:",omitempty"` + + // JobStatus is the status of a Service which is in one of ReplicatedJob or + // GlobalJob modes. It is absent on Replicated and Global services. + JobStatus *JobStatus `json:",omitempty"` +} + +// ServiceSpec represents the spec of a service. +type ServiceSpec struct { + Annotations + + // TaskTemplate defines how the service should construct new tasks when + // orchestrating this service. + TaskTemplate TaskSpec `json:",omitempty"` + Mode ServiceMode `json:",omitempty"` + UpdateConfig *UpdateConfig `json:",omitempty"` + RollbackConfig *UpdateConfig `json:",omitempty"` + + // Networks specifies which networks the service should attach to. + // + // Deprecated: This field is deprecated since v1.44. The Networks field in TaskSpec should be used instead. + Networks []NetworkAttachmentConfig `json:",omitempty"` + EndpointSpec *EndpointSpec `json:",omitempty"` +} + +// ServiceMode represents the mode of a service. +type ServiceMode struct { + Replicated *ReplicatedService `json:",omitempty"` + Global *GlobalService `json:",omitempty"` + ReplicatedJob *ReplicatedJob `json:",omitempty"` + GlobalJob *GlobalJob `json:",omitempty"` +} + +// UpdateState is the state of a service update. +type UpdateState string + +const ( + // UpdateStateUpdating is the updating state. + UpdateStateUpdating UpdateState = "updating" + // UpdateStatePaused is the paused state. + UpdateStatePaused UpdateState = "paused" + // UpdateStateCompleted is the completed state. + UpdateStateCompleted UpdateState = "completed" + // UpdateStateRollbackStarted is the state with a rollback in progress. + UpdateStateRollbackStarted UpdateState = "rollback_started" + // UpdateStateRollbackPaused is the state with a rollback in progress. + UpdateStateRollbackPaused UpdateState = "rollback_paused" + // UpdateStateRollbackCompleted is the state with a rollback in progress. + UpdateStateRollbackCompleted UpdateState = "rollback_completed" +) + +// UpdateStatus reports the status of a service update. +type UpdateStatus struct { + State UpdateState `json:",omitempty"` + StartedAt *time.Time `json:",omitempty"` + CompletedAt *time.Time `json:",omitempty"` + Message string `json:",omitempty"` +} + +// ReplicatedService is a kind of ServiceMode. +type ReplicatedService struct { + Replicas *uint64 `json:",omitempty"` +} + +// GlobalService is a kind of ServiceMode. +type GlobalService struct{} + +// ReplicatedJob is the a type of Service which executes a defined Tasks +// in parallel until the specified number of Tasks have succeeded. +type ReplicatedJob struct { + // MaxConcurrent indicates the maximum number of Tasks that should be + // executing simultaneously for this job at any given time. There may be + // fewer Tasks that MaxConcurrent executing simultaneously; for example, if + // there are fewer than MaxConcurrent tasks needed to reach + // TotalCompletions. + // + // If this field is empty, it will default to a max concurrency of 1. + MaxConcurrent *uint64 `json:",omitempty"` + + // TotalCompletions is the total number of Tasks desired to run to + // completion. + // + // If this field is empty, the value of MaxConcurrent will be used. + TotalCompletions *uint64 `json:",omitempty"` +} + +// GlobalJob is the type of a Service which executes a Task on every Node +// matching the Service's placement constraints. These tasks run to completion +// and then exit. +// +// This type is deliberately empty. +type GlobalJob struct{} + +const ( + // UpdateFailureActionPause PAUSE + UpdateFailureActionPause = "pause" + // UpdateFailureActionContinue CONTINUE + UpdateFailureActionContinue = "continue" + // UpdateFailureActionRollback ROLLBACK + UpdateFailureActionRollback = "rollback" + + // UpdateOrderStopFirst STOP_FIRST + UpdateOrderStopFirst = "stop-first" + // UpdateOrderStartFirst START_FIRST + UpdateOrderStartFirst = "start-first" +) + +// UpdateConfig represents the update configuration. +type UpdateConfig struct { + // Maximum number of tasks to be updated in one iteration. + // 0 means unlimited parallelism. + Parallelism uint64 + + // Amount of time between updates. + Delay time.Duration `json:",omitempty"` + + // FailureAction is the action to take when an update failures. + FailureAction string `json:",omitempty"` + + // Monitor indicates how long to monitor a task for failure after it is + // created. If the task fails by ending up in one of the states + // REJECTED, COMPLETED, or FAILED, within Monitor from its creation, + // this counts as a failure. If it fails after Monitor, it does not + // count as a failure. If Monitor is unspecified, a default value will + // be used. + Monitor time.Duration `json:",omitempty"` + + // MaxFailureRatio is the fraction of tasks that may fail during + // an update before the failure action is invoked. Any task created by + // the current update which ends up in one of the states REJECTED, + // COMPLETED or FAILED within Monitor from its creation counts as a + // failure. The number of failures is divided by the number of tasks + // being updated, and if this fraction is greater than + // MaxFailureRatio, the failure action is invoked. + // + // If the failure action is CONTINUE, there is no effect. + // If the failure action is PAUSE, no more tasks will be updated until + // another update is started. + MaxFailureRatio float32 + + // Order indicates the order of operations when rolling out an updated + // task. Either the old task is shut down before the new task is + // started, or the new task is started before the old task is shut down. + Order string +} + +// ServiceStatus represents the number of running tasks in a service and the +// number of tasks desired to be running. +type ServiceStatus struct { + // RunningTasks is the number of tasks for the service actually in the + // Running state + RunningTasks uint64 + + // DesiredTasks is the number of tasks desired to be running by the + // service. For replicated services, this is the replica count. For global + // services, this is computed by taking the number of tasks with desired + // state of not-Shutdown. + DesiredTasks uint64 + + // CompletedTasks is the number of tasks in the state Completed, if this + // service is in ReplicatedJob or GlobalJob mode. This field must be + // cross-referenced with the service type, because the default value of 0 + // may mean that a service is not in a job mode, or it may mean that the + // job has yet to complete any tasks. + CompletedTasks uint64 +} + +// JobStatus is the status of a job-type service. +type JobStatus struct { + // JobIteration is a value increased each time a Job is executed, + // successfully or otherwise. "Executed", in this case, means the job as a + // whole has been started, not that an individual Task has been launched. A + // job is "Executed" when its ServiceSpec is updated. JobIteration can be + // used to disambiguate Tasks belonging to different executions of a job. + // + // Though JobIteration will increase with each subsequent execution, it may + // not necessarily increase by 1, and so JobIteration should not be used to + // keep track of the number of times a job has been executed. + JobIteration Version + + // LastExecution is the time that the job was last executed, as observed by + // Swarm manager. + LastExecution time.Time `json:",omitempty"` +} diff --git a/vendor/github.com/docker/docker/api/types/swarm/service_create_response.go b/vendor/github.com/docker/docker/api/types/swarm/service_create_response.go new file mode 100644 index 00000000..9a268ff1 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/service_create_response.go @@ -0,0 +1,20 @@ +package swarm + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// ServiceCreateResponse contains the information returned to a client on the +// creation of a new service. +// +// swagger:model ServiceCreateResponse +type ServiceCreateResponse struct { + + // The ID of the created service. + ID string `json:"ID,omitempty"` + + // Optional warning message. + // + // FIXME(thaJeztah): this should have "omitempty" in the generated type. + // + Warnings []string `json:"Warnings"` +} diff --git a/vendor/github.com/docker/docker/api/types/swarm/service_update_response.go b/vendor/github.com/docker/docker/api/types/swarm/service_update_response.go new file mode 100644 index 00000000..0417467d --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/service_update_response.go @@ -0,0 +1,12 @@ +package swarm + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// ServiceUpdateResponse service update response +// swagger:model ServiceUpdateResponse +type ServiceUpdateResponse struct { + + // Optional warning messages + Warnings []string `json:"Warnings"` +} diff --git a/vendor/github.com/docker/docker/api/types/swarm/swarm.go b/vendor/github.com/docker/docker/api/types/swarm/swarm.go new file mode 100644 index 00000000..3eae4b9b --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/swarm.go @@ -0,0 +1,237 @@ +package swarm // import "github.com/docker/docker/api/types/swarm" + +import ( + "time" +) + +// ClusterInfo represents info about the cluster for outputting in "info" +// it contains the same information as "Swarm", but without the JoinTokens +type ClusterInfo struct { + ID string + Meta + Spec Spec + TLSInfo TLSInfo + RootRotationInProgress bool + DefaultAddrPool []string + SubnetSize uint32 + DataPathPort uint32 +} + +// Swarm represents a swarm. +type Swarm struct { + ClusterInfo + JoinTokens JoinTokens +} + +// JoinTokens contains the tokens workers and managers need to join the swarm. +type JoinTokens struct { + // Worker is the join token workers may use to join the swarm. + Worker string + // Manager is the join token managers may use to join the swarm. + Manager string +} + +// Spec represents the spec of a swarm. +type Spec struct { + Annotations + + Orchestration OrchestrationConfig `json:",omitempty"` + Raft RaftConfig `json:",omitempty"` + Dispatcher DispatcherConfig `json:",omitempty"` + CAConfig CAConfig `json:",omitempty"` + TaskDefaults TaskDefaults `json:",omitempty"` + EncryptionConfig EncryptionConfig `json:",omitempty"` +} + +// OrchestrationConfig represents orchestration configuration. +type OrchestrationConfig struct { + // TaskHistoryRetentionLimit is the number of historic tasks to keep per instance or + // node. If negative, never remove completed or failed tasks. + TaskHistoryRetentionLimit *int64 `json:",omitempty"` +} + +// TaskDefaults parameterizes cluster-level task creation with default values. +type TaskDefaults struct { + // LogDriver selects the log driver to use for tasks created in the + // orchestrator if unspecified by a service. + // + // Updating this value will only have an affect on new tasks. Old tasks + // will continue use their previously configured log driver until + // recreated. + LogDriver *Driver `json:",omitempty"` +} + +// EncryptionConfig controls at-rest encryption of data and keys. +type EncryptionConfig struct { + // AutoLockManagers specifies whether or not managers TLS keys and raft data + // should be encrypted at rest in such a way that they must be unlocked + // before the manager node starts up again. + AutoLockManagers bool +} + +// RaftConfig represents raft configuration. +type RaftConfig struct { + // SnapshotInterval is the number of log entries between snapshots. + SnapshotInterval uint64 `json:",omitempty"` + + // KeepOldSnapshots is the number of snapshots to keep beyond the + // current snapshot. + KeepOldSnapshots *uint64 `json:",omitempty"` + + // LogEntriesForSlowFollowers is the number of log entries to keep + // around to sync up slow followers after a snapshot is created. + LogEntriesForSlowFollowers uint64 `json:",omitempty"` + + // ElectionTick is the number of ticks that a follower will wait for a message + // from the leader before becoming a candidate and starting an election. + // ElectionTick must be greater than HeartbeatTick. + // + // A tick currently defaults to one second, so these translate directly to + // seconds currently, but this is NOT guaranteed. + ElectionTick int + + // HeartbeatTick is the number of ticks between heartbeats. Every + // HeartbeatTick ticks, the leader will send a heartbeat to the + // followers. + // + // A tick currently defaults to one second, so these translate directly to + // seconds currently, but this is NOT guaranteed. + HeartbeatTick int +} + +// DispatcherConfig represents dispatcher configuration. +type DispatcherConfig struct { + // HeartbeatPeriod defines how often agent should send heartbeats to + // dispatcher. + HeartbeatPeriod time.Duration `json:",omitempty"` +} + +// CAConfig represents CA configuration. +type CAConfig struct { + // NodeCertExpiry is the duration certificates should be issued for + NodeCertExpiry time.Duration `json:",omitempty"` + + // ExternalCAs is a list of CAs to which a manager node will make + // certificate signing requests for node certificates. + ExternalCAs []*ExternalCA `json:",omitempty"` + + // SigningCACert and SigningCAKey specify the desired signing root CA and + // root CA key for the swarm. When inspecting the cluster, the key will + // be redacted. + SigningCACert string `json:",omitempty"` + SigningCAKey string `json:",omitempty"` + + // If this value changes, and there is no specified signing cert and key, + // then the swarm is forced to generate a new root certificate ane key. + ForceRotate uint64 `json:",omitempty"` +} + +// ExternalCAProtocol represents type of external CA. +type ExternalCAProtocol string + +// ExternalCAProtocolCFSSL CFSSL +const ExternalCAProtocolCFSSL ExternalCAProtocol = "cfssl" + +// ExternalCA defines external CA to be used by the cluster. +type ExternalCA struct { + // Protocol is the protocol used by this external CA. + Protocol ExternalCAProtocol + + // URL is the URL where the external CA can be reached. + URL string + + // Options is a set of additional key/value pairs whose interpretation + // depends on the specified CA type. + Options map[string]string `json:",omitempty"` + + // CACert specifies which root CA is used by this external CA. This certificate must + // be in PEM format. + CACert string +} + +// InitRequest is the request used to init a swarm. +type InitRequest struct { + ListenAddr string + AdvertiseAddr string + DataPathAddr string + DataPathPort uint32 + ForceNewCluster bool + Spec Spec + AutoLockManagers bool + Availability NodeAvailability + DefaultAddrPool []string + SubnetSize uint32 +} + +// JoinRequest is the request used to join a swarm. +type JoinRequest struct { + ListenAddr string + AdvertiseAddr string + DataPathAddr string + RemoteAddrs []string + JoinToken string // accept by secret + Availability NodeAvailability +} + +// UnlockRequest is the request used to unlock a swarm. +type UnlockRequest struct { + // UnlockKey is the unlock key in ASCII-armored format. + UnlockKey string +} + +// LocalNodeState represents the state of the local node. +type LocalNodeState string + +const ( + // LocalNodeStateInactive INACTIVE + LocalNodeStateInactive LocalNodeState = "inactive" + // LocalNodeStatePending PENDING + LocalNodeStatePending LocalNodeState = "pending" + // LocalNodeStateActive ACTIVE + LocalNodeStateActive LocalNodeState = "active" + // LocalNodeStateError ERROR + LocalNodeStateError LocalNodeState = "error" + // LocalNodeStateLocked LOCKED + LocalNodeStateLocked LocalNodeState = "locked" +) + +// Info represents generic information about swarm. +type Info struct { + NodeID string + NodeAddr string + + LocalNodeState LocalNodeState + ControlAvailable bool + Error string + + RemoteManagers []Peer + Nodes int `json:",omitempty"` + Managers int `json:",omitempty"` + + Cluster *ClusterInfo `json:",omitempty"` + + Warnings []string `json:",omitempty"` +} + +// Status provides information about the current swarm status and role, +// obtained from the "Swarm" header in the API response. +type Status struct { + // NodeState represents the state of the node. + NodeState LocalNodeState + + // ControlAvailable indicates if the node is a swarm manager. + ControlAvailable bool +} + +// Peer represents a peer. +type Peer struct { + NodeID string + Addr string +} + +// UpdateFlags contains flags for SwarmUpdate. +type UpdateFlags struct { + RotateWorkerToken bool + RotateManagerToken bool + RotateManagerUnlockKey bool +} diff --git a/vendor/github.com/docker/docker/api/types/swarm/task.go b/vendor/github.com/docker/docker/api/types/swarm/task.go new file mode 100644 index 00000000..ad3eeca0 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/task.go @@ -0,0 +1,225 @@ +package swarm // import "github.com/docker/docker/api/types/swarm" + +import ( + "time" + + "github.com/docker/docker/api/types/swarm/runtime" +) + +// TaskState represents the state of a task. +type TaskState string + +const ( + // TaskStateNew NEW + TaskStateNew TaskState = "new" + // TaskStateAllocated ALLOCATED + TaskStateAllocated TaskState = "allocated" + // TaskStatePending PENDING + TaskStatePending TaskState = "pending" + // TaskStateAssigned ASSIGNED + TaskStateAssigned TaskState = "assigned" + // TaskStateAccepted ACCEPTED + TaskStateAccepted TaskState = "accepted" + // TaskStatePreparing PREPARING + TaskStatePreparing TaskState = "preparing" + // TaskStateReady READY + TaskStateReady TaskState = "ready" + // TaskStateStarting STARTING + TaskStateStarting TaskState = "starting" + // TaskStateRunning RUNNING + TaskStateRunning TaskState = "running" + // TaskStateComplete COMPLETE + TaskStateComplete TaskState = "complete" + // TaskStateShutdown SHUTDOWN + TaskStateShutdown TaskState = "shutdown" + // TaskStateFailed FAILED + TaskStateFailed TaskState = "failed" + // TaskStateRejected REJECTED + TaskStateRejected TaskState = "rejected" + // TaskStateRemove REMOVE + TaskStateRemove TaskState = "remove" + // TaskStateOrphaned ORPHANED + TaskStateOrphaned TaskState = "orphaned" +) + +// Task represents a task. +type Task struct { + ID string + Meta + Annotations + + Spec TaskSpec `json:",omitempty"` + ServiceID string `json:",omitempty"` + Slot int `json:",omitempty"` + NodeID string `json:",omitempty"` + Status TaskStatus `json:",omitempty"` + DesiredState TaskState `json:",omitempty"` + NetworksAttachments []NetworkAttachment `json:",omitempty"` + GenericResources []GenericResource `json:",omitempty"` + + // JobIteration is the JobIteration of the Service that this Task was + // spawned from, if the Service is a ReplicatedJob or GlobalJob. This is + // used to determine which Tasks belong to which run of the job. This field + // is absent if the Service mode is Replicated or Global. + JobIteration *Version `json:",omitempty"` + + // Volumes is the list of VolumeAttachments for this task. It specifies + // which particular volumes are to be used by this particular task, and + // fulfilling what mounts in the spec. + Volumes []VolumeAttachment +} + +// TaskSpec represents the spec of a task. +type TaskSpec struct { + // ContainerSpec, NetworkAttachmentSpec, and PluginSpec are mutually exclusive. + // PluginSpec is only used when the `Runtime` field is set to `plugin` + // NetworkAttachmentSpec is used if the `Runtime` field is set to + // `attachment`. + ContainerSpec *ContainerSpec `json:",omitempty"` + PluginSpec *runtime.PluginSpec `json:",omitempty"` + NetworkAttachmentSpec *NetworkAttachmentSpec `json:",omitempty"` + + Resources *ResourceRequirements `json:",omitempty"` + RestartPolicy *RestartPolicy `json:",omitempty"` + Placement *Placement `json:",omitempty"` + Networks []NetworkAttachmentConfig `json:",omitempty"` + + // LogDriver specifies the LogDriver to use for tasks created from this + // spec. If not present, the one on cluster default on swarm.Spec will be + // used, finally falling back to the engine default if not specified. + LogDriver *Driver `json:",omitempty"` + + // ForceUpdate is a counter that triggers an update even if no relevant + // parameters have been changed. + ForceUpdate uint64 + + Runtime RuntimeType `json:",omitempty"` +} + +// Resources represents resources (CPU/Memory) which can be advertised by a +// node and requested to be reserved for a task. +type Resources struct { + NanoCPUs int64 `json:",omitempty"` + MemoryBytes int64 `json:",omitempty"` + GenericResources []GenericResource `json:",omitempty"` +} + +// Limit describes limits on resources which can be requested by a task. +type Limit struct { + NanoCPUs int64 `json:",omitempty"` + MemoryBytes int64 `json:",omitempty"` + Pids int64 `json:",omitempty"` +} + +// GenericResource represents a "user defined" resource which can +// be either an integer (e.g: SSD=3) or a string (e.g: SSD=sda1) +type GenericResource struct { + NamedResourceSpec *NamedGenericResource `json:",omitempty"` + DiscreteResourceSpec *DiscreteGenericResource `json:",omitempty"` +} + +// NamedGenericResource represents a "user defined" resource which is defined +// as a string. +// "Kind" is used to describe the Kind of a resource (e.g: "GPU", "FPGA", "SSD", ...) +// Value is used to identify the resource (GPU="UUID-1", FPGA="/dev/sdb5", ...) +type NamedGenericResource struct { + Kind string `json:",omitempty"` + Value string `json:",omitempty"` +} + +// DiscreteGenericResource represents a "user defined" resource which is defined +// as an integer +// "Kind" is used to describe the Kind of a resource (e.g: "GPU", "FPGA", "SSD", ...) +// Value is used to count the resource (SSD=5, HDD=3, ...) +type DiscreteGenericResource struct { + Kind string `json:",omitempty"` + Value int64 `json:",omitempty"` +} + +// ResourceRequirements represents resources requirements. +type ResourceRequirements struct { + Limits *Limit `json:",omitempty"` + Reservations *Resources `json:",omitempty"` +} + +// Placement represents orchestration parameters. +type Placement struct { + Constraints []string `json:",omitempty"` + Preferences []PlacementPreference `json:",omitempty"` + MaxReplicas uint64 `json:",omitempty"` + + // Platforms stores all the platforms that the image can run on. + // This field is used in the platform filter for scheduling. If empty, + // then the platform filter is off, meaning there are no scheduling restrictions. + Platforms []Platform `json:",omitempty"` +} + +// PlacementPreference provides a way to make the scheduler aware of factors +// such as topology. +type PlacementPreference struct { + Spread *SpreadOver +} + +// SpreadOver is a scheduling preference that instructs the scheduler to spread +// tasks evenly over groups of nodes identified by labels. +type SpreadOver struct { + // label descriptor, such as engine.labels.az + SpreadDescriptor string +} + +// RestartPolicy represents the restart policy. +type RestartPolicy struct { + Condition RestartPolicyCondition `json:",omitempty"` + Delay *time.Duration `json:",omitempty"` + MaxAttempts *uint64 `json:",omitempty"` + Window *time.Duration `json:",omitempty"` +} + +// RestartPolicyCondition represents when to restart. +type RestartPolicyCondition string + +const ( + // RestartPolicyConditionNone NONE + RestartPolicyConditionNone RestartPolicyCondition = "none" + // RestartPolicyConditionOnFailure ON_FAILURE + RestartPolicyConditionOnFailure RestartPolicyCondition = "on-failure" + // RestartPolicyConditionAny ANY + RestartPolicyConditionAny RestartPolicyCondition = "any" +) + +// TaskStatus represents the status of a task. +type TaskStatus struct { + Timestamp time.Time `json:",omitempty"` + State TaskState `json:",omitempty"` + Message string `json:",omitempty"` + Err string `json:",omitempty"` + ContainerStatus *ContainerStatus `json:",omitempty"` + PortStatus PortStatus `json:",omitempty"` +} + +// ContainerStatus represents the status of a container. +type ContainerStatus struct { + ContainerID string + PID int + ExitCode int +} + +// PortStatus represents the port status of a task's host ports whose +// service has published host ports +type PortStatus struct { + Ports []PortConfig `json:",omitempty"` +} + +// VolumeAttachment contains the associating a Volume to a Task. +type VolumeAttachment struct { + // ID is the Swarmkit ID of the Volume. This is not the CSI VolumeId. + ID string `json:",omitempty"` + + // Source, together with Target, indicates the Mount, as specified in the + // ContainerSpec, that this volume fulfills. + Source string `json:",omitempty"` + + // Target, together with Source, indicates the Mount, as specified + // in the ContainerSpec, that this volume fulfills. + Target string `json:",omitempty"` +} diff --git a/vendor/github.com/docker/docker/api/types/versions/compare.go b/vendor/github.com/docker/docker/api/types/versions/compare.go new file mode 100644 index 00000000..621725a3 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/versions/compare.go @@ -0,0 +1,65 @@ +package versions // import "github.com/docker/docker/api/types/versions" + +import ( + "strconv" + "strings" +) + +// compare compares two version strings +// returns -1 if v1 < v2, 1 if v1 > v2, 0 otherwise. +func compare(v1, v2 string) int { + if v1 == v2 { + return 0 + } + var ( + currTab = strings.Split(v1, ".") + otherTab = strings.Split(v2, ".") + ) + + maxVer := len(currTab) + if len(otherTab) > maxVer { + maxVer = len(otherTab) + } + for i := 0; i < maxVer; i++ { + var currInt, otherInt int + + if len(currTab) > i { + currInt, _ = strconv.Atoi(currTab[i]) + } + if len(otherTab) > i { + otherInt, _ = strconv.Atoi(otherTab[i]) + } + if currInt > otherInt { + return 1 + } + if otherInt > currInt { + return -1 + } + } + return 0 +} + +// LessThan checks if a version is less than another +func LessThan(v, other string) bool { + return compare(v, other) == -1 +} + +// LessThanOrEqualTo checks if a version is less than or equal to another +func LessThanOrEqualTo(v, other string) bool { + return compare(v, other) <= 0 +} + +// GreaterThan checks if a version is greater than another +func GreaterThan(v, other string) bool { + return compare(v, other) == 1 +} + +// GreaterThanOrEqualTo checks if a version is greater than or equal to another +func GreaterThanOrEqualTo(v, other string) bool { + return compare(v, other) >= 0 +} + +// Equal checks if a version is equal to another +func Equal(v, other string) bool { + return compare(v, other) == 0 +} diff --git a/vendor/github.com/docker/docker/internal/multierror/multierror.go b/vendor/github.com/docker/docker/internal/multierror/multierror.go new file mode 100644 index 00000000..cf4d6a59 --- /dev/null +++ b/vendor/github.com/docker/docker/internal/multierror/multierror.go @@ -0,0 +1,46 @@ +package multierror + +import ( + "strings" +) + +// Join is a drop-in replacement for errors.Join with better formatting. +func Join(errs ...error) error { + n := 0 + for _, err := range errs { + if err != nil { + n++ + } + } + if n == 0 { + return nil + } + e := &joinError{ + errs: make([]error, 0, n), + } + for _, err := range errs { + if err != nil { + e.errs = append(e.errs, err) + } + } + return e +} + +type joinError struct { + errs []error +} + +func (e *joinError) Error() string { + if len(e.errs) == 1 { + return strings.TrimSpace(e.errs[0].Error()) + } + stringErrs := make([]string, 0, len(e.errs)) + for _, subErr := range e.errs { + stringErrs = append(stringErrs, strings.Replace(subErr.Error(), "\n", "\n\t", -1)) + } + return "* " + strings.Join(stringErrs, "\n* ") +} + +func (e *joinError) Unwrap() []error { + return e.errs +} diff --git a/vendor/github.com/docker/go-connections/LICENSE b/vendor/github.com/docker/go-connections/LICENSE new file mode 100644 index 00000000..b55b37bc --- /dev/null +++ b/vendor/github.com/docker/go-connections/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2015 Docker, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/docker/go-connections/nat/nat.go b/vendor/github.com/docker/go-connections/nat/nat.go new file mode 100644 index 00000000..4049d780 --- /dev/null +++ b/vendor/github.com/docker/go-connections/nat/nat.go @@ -0,0 +1,240 @@ +// Package nat is a convenience package for manipulation of strings describing network ports. +package nat + +import ( + "fmt" + "net" + "strconv" + "strings" +) + +// PortBinding represents a binding between a Host IP address and a Host Port +type PortBinding struct { + // HostIP is the host IP Address + HostIP string `json:"HostIp"` + // HostPort is the host port number + HostPort string +} + +// PortMap is a collection of PortBinding indexed by Port +type PortMap map[Port][]PortBinding + +// PortSet is a collection of structs indexed by Port +type PortSet map[Port]struct{} + +// Port is a string containing port number and protocol in the format "80/tcp" +type Port string + +// NewPort creates a new instance of a Port given a protocol and port number or port range +func NewPort(proto, port string) (Port, error) { + // Check for parsing issues on "port" now so we can avoid having + // to check it later on. + + portStartInt, portEndInt, err := ParsePortRangeToInt(port) + if err != nil { + return "", err + } + + if portStartInt == portEndInt { + return Port(fmt.Sprintf("%d/%s", portStartInt, proto)), nil + } + return Port(fmt.Sprintf("%d-%d/%s", portStartInt, portEndInt, proto)), nil +} + +// ParsePort parses the port number string and returns an int +func ParsePort(rawPort string) (int, error) { + if len(rawPort) == 0 { + return 0, nil + } + port, err := strconv.ParseUint(rawPort, 10, 16) + if err != nil { + return 0, err + } + return int(port), nil +} + +// ParsePortRangeToInt parses the port range string and returns start/end ints +func ParsePortRangeToInt(rawPort string) (int, int, error) { + if len(rawPort) == 0 { + return 0, 0, nil + } + start, end, err := ParsePortRange(rawPort) + if err != nil { + return 0, 0, err + } + return int(start), int(end), nil +} + +// Proto returns the protocol of a Port +func (p Port) Proto() string { + proto, _ := SplitProtoPort(string(p)) + return proto +} + +// Port returns the port number of a Port +func (p Port) Port() string { + _, port := SplitProtoPort(string(p)) + return port +} + +// Int returns the port number of a Port as an int +func (p Port) Int() int { + portStr := p.Port() + // We don't need to check for an error because we're going to + // assume that any error would have been found, and reported, in NewPort() + port, _ := ParsePort(portStr) + return port +} + +// Range returns the start/end port numbers of a Port range as ints +func (p Port) Range() (int, int, error) { + return ParsePortRangeToInt(p.Port()) +} + +// SplitProtoPort splits a port in the format of proto/port +func SplitProtoPort(rawPort string) (string, string) { + parts := strings.Split(rawPort, "/") + l := len(parts) + if len(rawPort) == 0 || l == 0 || len(parts[0]) == 0 { + return "", "" + } + if l == 1 { + return "tcp", rawPort + } + if len(parts[1]) == 0 { + return "tcp", parts[0] + } + return parts[1], parts[0] +} + +func validateProto(proto string) bool { + for _, availableProto := range []string{"tcp", "udp", "sctp"} { + if availableProto == proto { + return true + } + } + return false +} + +// ParsePortSpecs receives port specs in the format of ip:public:private/proto and parses +// these in to the internal types +func ParsePortSpecs(ports []string) (map[Port]struct{}, map[Port][]PortBinding, error) { + var ( + exposedPorts = make(map[Port]struct{}, len(ports)) + bindings = make(map[Port][]PortBinding) + ) + for _, rawPort := range ports { + portMappings, err := ParsePortSpec(rawPort) + if err != nil { + return nil, nil, err + } + + for _, portMapping := range portMappings { + port := portMapping.Port + if _, exists := exposedPorts[port]; !exists { + exposedPorts[port] = struct{}{} + } + bslice, exists := bindings[port] + if !exists { + bslice = []PortBinding{} + } + bindings[port] = append(bslice, portMapping.Binding) + } + } + return exposedPorts, bindings, nil +} + +// PortMapping is a data object mapping a Port to a PortBinding +type PortMapping struct { + Port Port + Binding PortBinding +} + +func splitParts(rawport string) (string, string, string) { + parts := strings.Split(rawport, ":") + n := len(parts) + containerPort := parts[n-1] + + switch n { + case 1: + return "", "", containerPort + case 2: + return "", parts[0], containerPort + case 3: + return parts[0], parts[1], containerPort + default: + return strings.Join(parts[:n-2], ":"), parts[n-2], containerPort + } +} + +// ParsePortSpec parses a port specification string into a slice of PortMappings +func ParsePortSpec(rawPort string) ([]PortMapping, error) { + var proto string + ip, hostPort, containerPort := splitParts(rawPort) + proto, containerPort = SplitProtoPort(containerPort) + + if ip != "" && ip[0] == '[' { + // Strip [] from IPV6 addresses + rawIP, _, err := net.SplitHostPort(ip + ":") + if err != nil { + return nil, fmt.Errorf("invalid IP address %v: %w", ip, err) + } + ip = rawIP + } + if ip != "" && net.ParseIP(ip) == nil { + return nil, fmt.Errorf("invalid IP address: %s", ip) + } + if containerPort == "" { + return nil, fmt.Errorf("no port specified: %s", rawPort) + } + + startPort, endPort, err := ParsePortRange(containerPort) + if err != nil { + return nil, fmt.Errorf("invalid containerPort: %s", containerPort) + } + + var startHostPort, endHostPort uint64 = 0, 0 + if len(hostPort) > 0 { + startHostPort, endHostPort, err = ParsePortRange(hostPort) + if err != nil { + return nil, fmt.Errorf("invalid hostPort: %s", hostPort) + } + } + + if hostPort != "" && (endPort-startPort) != (endHostPort-startHostPort) { + // Allow host port range iff containerPort is not a range. + // In this case, use the host port range as the dynamic + // host port range to allocate into. + if endPort != startPort { + return nil, fmt.Errorf("invalid ranges specified for container and host Ports: %s and %s", containerPort, hostPort) + } + } + + if !validateProto(strings.ToLower(proto)) { + return nil, fmt.Errorf("invalid proto: %s", proto) + } + + ports := []PortMapping{} + for i := uint64(0); i <= (endPort - startPort); i++ { + containerPort = strconv.FormatUint(startPort+i, 10) + if len(hostPort) > 0 { + hostPort = strconv.FormatUint(startHostPort+i, 10) + } + // Set hostPort to a range only if there is a single container port + // and a dynamic host port. + if startPort == endPort && startHostPort != endHostPort { + hostPort = fmt.Sprintf("%s-%s", hostPort, strconv.FormatUint(endHostPort, 10)) + } + port, err := NewPort(strings.ToLower(proto), containerPort) + if err != nil { + return nil, err + } + + binding := PortBinding{ + HostIP: ip, + HostPort: hostPort, + } + ports = append(ports, PortMapping{Port: port, Binding: binding}) + } + return ports, nil +} diff --git a/vendor/github.com/docker/go-connections/nat/parse.go b/vendor/github.com/docker/go-connections/nat/parse.go new file mode 100644 index 00000000..e4b53e8a --- /dev/null +++ b/vendor/github.com/docker/go-connections/nat/parse.go @@ -0,0 +1,33 @@ +package nat + +import ( + "fmt" + "strconv" + "strings" +) + +// ParsePortRange parses and validates the specified string as a port-range (8000-9000) +func ParsePortRange(ports string) (uint64, uint64, error) { + if ports == "" { + return 0, 0, fmt.Errorf("empty string specified for ports") + } + if !strings.Contains(ports, "-") { + start, err := strconv.ParseUint(ports, 10, 16) + end := start + return start, end, err + } + + parts := strings.Split(ports, "-") + start, err := strconv.ParseUint(parts[0], 10, 16) + if err != nil { + return 0, 0, err + } + end, err := strconv.ParseUint(parts[1], 10, 16) + if err != nil { + return 0, 0, err + } + if end < start { + return 0, 0, fmt.Errorf("invalid range specified for port: %s", ports) + } + return start, end, nil +} diff --git a/vendor/github.com/docker/go-connections/nat/sort.go b/vendor/github.com/docker/go-connections/nat/sort.go new file mode 100644 index 00000000..b6eed145 --- /dev/null +++ b/vendor/github.com/docker/go-connections/nat/sort.go @@ -0,0 +1,96 @@ +package nat + +import ( + "sort" + "strings" +) + +type portSorter struct { + ports []Port + by func(i, j Port) bool +} + +func (s *portSorter) Len() int { + return len(s.ports) +} + +func (s *portSorter) Swap(i, j int) { + s.ports[i], s.ports[j] = s.ports[j], s.ports[i] +} + +func (s *portSorter) Less(i, j int) bool { + ip := s.ports[i] + jp := s.ports[j] + + return s.by(ip, jp) +} + +// Sort sorts a list of ports using the provided predicate +// This function should compare `i` and `j`, returning true if `i` is +// considered to be less than `j` +func Sort(ports []Port, predicate func(i, j Port) bool) { + s := &portSorter{ports, predicate} + sort.Sort(s) +} + +type portMapEntry struct { + port Port + binding PortBinding +} + +type portMapSorter []portMapEntry + +func (s portMapSorter) Len() int { return len(s) } +func (s portMapSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] } + +// Less sorts the port so that the order is: +// 1. port with larger specified bindings +// 2. larger port +// 3. port with tcp protocol +func (s portMapSorter) Less(i, j int) bool { + pi, pj := s[i].port, s[j].port + hpi, hpj := toInt(s[i].binding.HostPort), toInt(s[j].binding.HostPort) + return hpi > hpj || pi.Int() > pj.Int() || (pi.Int() == pj.Int() && strings.ToLower(pi.Proto()) == "tcp") +} + +// SortPortMap sorts the list of ports and their respected mapping. The ports +// will explicit HostPort will be placed first. +func SortPortMap(ports []Port, bindings PortMap) { + s := portMapSorter{} + for _, p := range ports { + if binding, ok := bindings[p]; ok && len(binding) > 0 { + for _, b := range binding { + s = append(s, portMapEntry{port: p, binding: b}) + } + bindings[p] = []PortBinding{} + } else { + s = append(s, portMapEntry{port: p}) + } + } + + sort.Sort(s) + var ( + i int + pm = make(map[Port]struct{}) + ) + // reorder ports + for _, entry := range s { + if _, ok := pm[entry.port]; !ok { + ports[i] = entry.port + pm[entry.port] = struct{}{} + i++ + } + // reorder bindings for this port + if _, ok := bindings[entry.port]; ok { + bindings[entry.port] = append(bindings[entry.port], entry.binding) + } + } +} + +func toInt(s string) uint64 { + i, _, err := ParsePortRange(s) + if err != nil { + i = 0 + } + return i +} diff --git a/vendor/github.com/docker/go-units/CONTRIBUTING.md b/vendor/github.com/docker/go-units/CONTRIBUTING.md new file mode 100644 index 00000000..9ea86d78 --- /dev/null +++ b/vendor/github.com/docker/go-units/CONTRIBUTING.md @@ -0,0 +1,67 @@ +# Contributing to go-units + +Want to hack on go-units? Awesome! Here are instructions to get you started. + +go-units is a part of the [Docker](https://www.docker.com) project, and follows +the same rules and principles. If you're already familiar with the way +Docker does things, you'll feel right at home. + +Otherwise, go read Docker's +[contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md), +[issue triaging](https://github.com/docker/docker/blob/master/project/ISSUE-TRIAGE.md), +[review process](https://github.com/docker/docker/blob/master/project/REVIEWING.md) and +[branches and tags](https://github.com/docker/docker/blob/master/project/BRANCHES-AND-TAGS.md). + +### Sign your work + +The sign-off is a simple line at the end of the explanation for the patch. Your +signature certifies that you wrote the patch or otherwise have the right to pass +it on as an open-source patch. The rules are pretty simple: if you can certify +the below (from [developercertificate.org](http://developercertificate.org/)): + +``` +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. +660 York Street, Suite 102, +San Francisco, CA 94110 USA + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +Then you just add a line to every git commit message: + + Signed-off-by: Joe Smith + +Use your real name (sorry, no pseudonyms or anonymous contributions.) + +If you set your `user.name` and `user.email` git configs, you can sign your +commit automatically with `git commit -s`. diff --git a/vendor/github.com/docker/go-units/LICENSE b/vendor/github.com/docker/go-units/LICENSE new file mode 100644 index 00000000..b55b37bc --- /dev/null +++ b/vendor/github.com/docker/go-units/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2015 Docker, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/docker/go-units/MAINTAINERS b/vendor/github.com/docker/go-units/MAINTAINERS new file mode 100644 index 00000000..4aac7c74 --- /dev/null +++ b/vendor/github.com/docker/go-units/MAINTAINERS @@ -0,0 +1,46 @@ +# go-units maintainers file +# +# This file describes who runs the docker/go-units project and how. +# This is a living document - if you see something out of date or missing, speak up! +# +# It is structured to be consumable by both humans and programs. +# To extract its contents programmatically, use any TOML-compliant parser. +# +# This file is compiled into the MAINTAINERS file in docker/opensource. +# +[Org] + [Org."Core maintainers"] + people = [ + "akihirosuda", + "dnephin", + "thajeztah", + "vdemeester", + ] + +[people] + +# A reference list of all people associated with the project. +# All other sections should refer to people by their canonical key +# in the people section. + + # ADD YOURSELF HERE IN ALPHABETICAL ORDER + + [people.akihirosuda] + Name = "Akihiro Suda" + Email = "akihiro.suda.cz@hco.ntt.co.jp" + GitHub = "AkihiroSuda" + + [people.dnephin] + Name = "Daniel Nephin" + Email = "dnephin@gmail.com" + GitHub = "dnephin" + + [people.thajeztah] + Name = "Sebastiaan van Stijn" + Email = "github@gone.nl" + GitHub = "thaJeztah" + + [people.vdemeester] + Name = "Vincent Demeester" + Email = "vincent@sbr.pm" + GitHub = "vdemeester" \ No newline at end of file diff --git a/vendor/github.com/docker/go-units/README.md b/vendor/github.com/docker/go-units/README.md new file mode 100644 index 00000000..4f70a4e1 --- /dev/null +++ b/vendor/github.com/docker/go-units/README.md @@ -0,0 +1,16 @@ +[![GoDoc](https://godoc.org/github.com/docker/go-units?status.svg)](https://godoc.org/github.com/docker/go-units) + +# Introduction + +go-units is a library to transform human friendly measurements into machine friendly values. + +## Usage + +See the [docs in godoc](https://godoc.org/github.com/docker/go-units) for examples and documentation. + +## Copyright and license + +Copyright © 2015 Docker, Inc. + +go-units is licensed under the Apache License, Version 2.0. +See [LICENSE](LICENSE) for the full text of the license. diff --git a/vendor/github.com/docker/go-units/circle.yml b/vendor/github.com/docker/go-units/circle.yml new file mode 100644 index 00000000..af9d6055 --- /dev/null +++ b/vendor/github.com/docker/go-units/circle.yml @@ -0,0 +1,11 @@ +dependencies: + post: + # install golint + - go get golang.org/x/lint/golint + +test: + pre: + # run analysis before tests + - go vet ./... + - test -z "$(golint ./... | tee /dev/stderr)" + - test -z "$(gofmt -s -l . | tee /dev/stderr)" diff --git a/vendor/github.com/docker/go-units/duration.go b/vendor/github.com/docker/go-units/duration.go new file mode 100644 index 00000000..48dd8744 --- /dev/null +++ b/vendor/github.com/docker/go-units/duration.go @@ -0,0 +1,35 @@ +// Package units provides helper function to parse and print size and time units +// in human-readable format. +package units + +import ( + "fmt" + "time" +) + +// HumanDuration returns a human-readable approximation of a duration +// (eg. "About a minute", "4 hours ago", etc.). +func HumanDuration(d time.Duration) string { + if seconds := int(d.Seconds()); seconds < 1 { + return "Less than a second" + } else if seconds == 1 { + return "1 second" + } else if seconds < 60 { + return fmt.Sprintf("%d seconds", seconds) + } else if minutes := int(d.Minutes()); minutes == 1 { + return "About a minute" + } else if minutes < 60 { + return fmt.Sprintf("%d minutes", minutes) + } else if hours := int(d.Hours() + 0.5); hours == 1 { + return "About an hour" + } else if hours < 48 { + return fmt.Sprintf("%d hours", hours) + } else if hours < 24*7*2 { + return fmt.Sprintf("%d days", hours/24) + } else if hours < 24*30*2 { + return fmt.Sprintf("%d weeks", hours/24/7) + } else if hours < 24*365*2 { + return fmt.Sprintf("%d months", hours/24/30) + } + return fmt.Sprintf("%d years", int(d.Hours())/24/365) +} diff --git a/vendor/github.com/docker/go-units/size.go b/vendor/github.com/docker/go-units/size.go new file mode 100644 index 00000000..c245a895 --- /dev/null +++ b/vendor/github.com/docker/go-units/size.go @@ -0,0 +1,154 @@ +package units + +import ( + "fmt" + "strconv" + "strings" +) + +// See: http://en.wikipedia.org/wiki/Binary_prefix +const ( + // Decimal + + KB = 1000 + MB = 1000 * KB + GB = 1000 * MB + TB = 1000 * GB + PB = 1000 * TB + + // Binary + + KiB = 1024 + MiB = 1024 * KiB + GiB = 1024 * MiB + TiB = 1024 * GiB + PiB = 1024 * TiB +) + +type unitMap map[byte]int64 + +var ( + decimalMap = unitMap{'k': KB, 'm': MB, 'g': GB, 't': TB, 'p': PB} + binaryMap = unitMap{'k': KiB, 'm': MiB, 'g': GiB, 't': TiB, 'p': PiB} +) + +var ( + decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} + binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"} +) + +func getSizeAndUnit(size float64, base float64, _map []string) (float64, string) { + i := 0 + unitsLimit := len(_map) - 1 + for size >= base && i < unitsLimit { + size = size / base + i++ + } + return size, _map[i] +} + +// CustomSize returns a human-readable approximation of a size +// using custom format. +func CustomSize(format string, size float64, base float64, _map []string) string { + size, unit := getSizeAndUnit(size, base, _map) + return fmt.Sprintf(format, size, unit) +} + +// HumanSizeWithPrecision allows the size to be in any precision, +// instead of 4 digit precision used in units.HumanSize. +func HumanSizeWithPrecision(size float64, precision int) string { + size, unit := getSizeAndUnit(size, 1000.0, decimapAbbrs) + return fmt.Sprintf("%.*g%s", precision, size, unit) +} + +// HumanSize returns a human-readable approximation of a size +// capped at 4 valid numbers (eg. "2.746 MB", "796 KB"). +func HumanSize(size float64) string { + return HumanSizeWithPrecision(size, 4) +} + +// BytesSize returns a human-readable size in bytes, kibibytes, +// mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB"). +func BytesSize(size float64) string { + return CustomSize("%.4g%s", size, 1024.0, binaryAbbrs) +} + +// FromHumanSize returns an integer from a human-readable specification of a +// size using SI standard (eg. "44kB", "17MB"). +func FromHumanSize(size string) (int64, error) { + return parseSize(size, decimalMap) +} + +// RAMInBytes parses a human-readable string representing an amount of RAM +// in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and +// returns the number of bytes, or -1 if the string is unparseable. +// Units are case-insensitive, and the 'b' suffix is optional. +func RAMInBytes(size string) (int64, error) { + return parseSize(size, binaryMap) +} + +// Parses the human-readable size string into the amount it represents. +func parseSize(sizeStr string, uMap unitMap) (int64, error) { + // TODO: rewrite to use strings.Cut if there's a space + // once Go < 1.18 is deprecated. + sep := strings.LastIndexAny(sizeStr, "01234567890. ") + if sep == -1 { + // There should be at least a digit. + return -1, fmt.Errorf("invalid size: '%s'", sizeStr) + } + var num, sfx string + if sizeStr[sep] != ' ' { + num = sizeStr[:sep+1] + sfx = sizeStr[sep+1:] + } else { + // Omit the space separator. + num = sizeStr[:sep] + sfx = sizeStr[sep+1:] + } + + size, err := strconv.ParseFloat(num, 64) + if err != nil { + return -1, err + } + // Backward compatibility: reject negative sizes. + if size < 0 { + return -1, fmt.Errorf("invalid size: '%s'", sizeStr) + } + + if len(sfx) == 0 { + return int64(size), nil + } + + // Process the suffix. + + if len(sfx) > 3 { // Too long. + goto badSuffix + } + sfx = strings.ToLower(sfx) + // Trivial case: b suffix. + if sfx[0] == 'b' { + if len(sfx) > 1 { // no extra characters allowed after b. + goto badSuffix + } + return int64(size), nil + } + // A suffix from the map. + if mul, ok := uMap[sfx[0]]; ok { + size *= float64(mul) + } else { + goto badSuffix + } + + // The suffix may have extra "b" or "ib" (e.g. KiB or MB). + switch { + case len(sfx) == 2 && sfx[1] != 'b': + goto badSuffix + case len(sfx) == 3 && sfx[1:] != "ib": + goto badSuffix + } + + return int64(size), nil + +badSuffix: + return -1, fmt.Errorf("invalid suffix: '%s'", sfx) +} diff --git a/vendor/github.com/docker/go-units/ulimit.go b/vendor/github.com/docker/go-units/ulimit.go new file mode 100644 index 00000000..fca0400c --- /dev/null +++ b/vendor/github.com/docker/go-units/ulimit.go @@ -0,0 +1,123 @@ +package units + +import ( + "fmt" + "strconv" + "strings" +) + +// Ulimit is a human friendly version of Rlimit. +type Ulimit struct { + Name string + Hard int64 + Soft int64 +} + +// Rlimit specifies the resource limits, such as max open files. +type Rlimit struct { + Type int `json:"type,omitempty"` + Hard uint64 `json:"hard,omitempty"` + Soft uint64 `json:"soft,omitempty"` +} + +const ( + // magic numbers for making the syscall + // some of these are defined in the syscall package, but not all. + // Also since Windows client doesn't get access to the syscall package, need to + // define these here + rlimitAs = 9 + rlimitCore = 4 + rlimitCPU = 0 + rlimitData = 2 + rlimitFsize = 1 + rlimitLocks = 10 + rlimitMemlock = 8 + rlimitMsgqueue = 12 + rlimitNice = 13 + rlimitNofile = 7 + rlimitNproc = 6 + rlimitRss = 5 + rlimitRtprio = 14 + rlimitRttime = 15 + rlimitSigpending = 11 + rlimitStack = 3 +) + +var ulimitNameMapping = map[string]int{ + //"as": rlimitAs, // Disabled since this doesn't seem usable with the way Docker inits a container. + "core": rlimitCore, + "cpu": rlimitCPU, + "data": rlimitData, + "fsize": rlimitFsize, + "locks": rlimitLocks, + "memlock": rlimitMemlock, + "msgqueue": rlimitMsgqueue, + "nice": rlimitNice, + "nofile": rlimitNofile, + "nproc": rlimitNproc, + "rss": rlimitRss, + "rtprio": rlimitRtprio, + "rttime": rlimitRttime, + "sigpending": rlimitSigpending, + "stack": rlimitStack, +} + +// ParseUlimit parses and returns a Ulimit from the specified string. +func ParseUlimit(val string) (*Ulimit, error) { + parts := strings.SplitN(val, "=", 2) + if len(parts) != 2 { + return nil, fmt.Errorf("invalid ulimit argument: %s", val) + } + + if _, exists := ulimitNameMapping[parts[0]]; !exists { + return nil, fmt.Errorf("invalid ulimit type: %s", parts[0]) + } + + var ( + soft int64 + hard = &soft // default to soft in case no hard was set + temp int64 + err error + ) + switch limitVals := strings.Split(parts[1], ":"); len(limitVals) { + case 2: + temp, err = strconv.ParseInt(limitVals[1], 10, 64) + if err != nil { + return nil, err + } + hard = &temp + fallthrough + case 1: + soft, err = strconv.ParseInt(limitVals[0], 10, 64) + if err != nil { + return nil, err + } + default: + return nil, fmt.Errorf("too many limit value arguments - %s, can only have up to two, `soft[:hard]`", parts[1]) + } + + if *hard != -1 { + if soft == -1 { + return nil, fmt.Errorf("ulimit soft limit must be less than or equal to hard limit: soft: -1 (unlimited), hard: %d", *hard) + } + if soft > *hard { + return nil, fmt.Errorf("ulimit soft limit must be less than or equal to hard limit: %d > %d", soft, *hard) + } + } + + return &Ulimit{Name: parts[0], Soft: soft, Hard: *hard}, nil +} + +// GetRlimit returns the RLimit corresponding to Ulimit. +func (u *Ulimit) GetRlimit() (*Rlimit, error) { + t, exists := ulimitNameMapping[u.Name] + if !exists { + return nil, fmt.Errorf("invalid ulimit name %s", u.Name) + } + + return &Rlimit{Type: t, Soft: uint64(u.Soft), Hard: uint64(u.Hard)}, nil +} + +func (u *Ulimit) String() string { + return fmt.Sprintf("%s=%d:%d", u.Name, u.Soft, u.Hard) +} diff --git a/vendor/github.com/go-sql-driver/mysql/AUTHORS b/vendor/github.com/go-sql-driver/mysql/AUTHORS index fb1478c3..4021b96c 100644 --- a/vendor/github.com/go-sql-driver/mysql/AUTHORS +++ b/vendor/github.com/go-sql-driver/mysql/AUTHORS @@ -13,6 +13,7 @@ Aaron Hopkins Achille Roussel +Aidan Alex Snast Alexey Palazhchenko Andrew Reid @@ -20,12 +21,14 @@ Animesh Ray Arne Hormann Ariel Mashraki Asta Xie +Brian Hendriks Bulat Gaifullin Caine Jette Carlos Nieto Chris Kirkland Chris Moos Craig Wilson +Daemonxiao <735462752 at qq.com> Daniel Montoya Daniel Nichter Daniël van Eeden @@ -33,9 +36,11 @@ Dave Protasowski DisposaBoy Egor Smolyakov Erwan Martin +Evan Elias Evan Shaw Frederick Mayle Gustavo Kristic +Gusted Hajime Nakagami Hanno Braun Henri Yandell @@ -47,8 +52,11 @@ INADA Naoki Jacek Szwec James Harr Janek Vedock +Jason Ng +Jean-Yves Pellé Jeff Hodges Jeffrey Charles +Jennifer Purevsuren Jerome Meyer Jiajia Zhong Jian Zhen @@ -74,9 +82,11 @@ Maciej Zimnoch Michael Woolnough Nathanial Murphy Nicola Peduzzi +Oliver Bone Olivier Mengué oscarzhao Paul Bonser +Paulius Lozys Peter Schultz Phil Porada Rebecca Chin @@ -95,6 +105,7 @@ Stan Putrya Stanley Gunawan Steven Hartland Tan Jinhua <312841925 at qq.com> +Tetsuro Aoki Thomas Wodarek Tim Ruffles Tom Jenkinson @@ -104,6 +115,7 @@ Xiangyu Hu Xiaobing Jiang Xiuming Chen Xuehong Chan +Zhang Xiang Zhenye Xie Zhixin Wen Ziheng Lyu @@ -113,14 +125,18 @@ Ziheng Lyu Barracuda Networks, Inc. Counting Ltd. DigitalOcean Inc. +Dolthub Inc. dyves labs AG Facebook Inc. GitHub Inc. Google Inc. InfoSum Ltd. Keybase Inc. +Microsoft Corp. Multiplay Ltd. Percona LLC +PingCAP Inc. Pivotal Inc. +Shattered Silicon Ltd. Stripe Inc. Zendesk Inc. diff --git a/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md b/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md index 5166e4ad..0c9bd9b1 100644 --- a/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md +++ b/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md @@ -1,3 +1,45 @@ +## Version 1.8.1 (2024-03-26) + +Bugfixes: + +- fix race condition when context is canceled in [#1562](https://github.com/go-sql-driver/mysql/pull/1562) and [#1570](https://github.com/go-sql-driver/mysql/pull/1570) + +## Version 1.8.0 (2024-03-09) + +Major Changes: + +- Use `SET NAMES charset COLLATE collation`. by @methane in [#1437](https://github.com/go-sql-driver/mysql/pull/1437) + - Older go-mysql-driver used `collation_id` in the handshake packet. But it caused collation mismatch in some situation. + - If you don't specify charset nor collation, go-mysql-driver sends `SET NAMES utf8mb4` for new connection. This uses server's default collation for utf8mb4. + - If you specify charset, go-mysql-driver sends `SET NAMES `. This uses the server's default collation for ``. + - If you specify collation and/or charset, go-mysql-driver sends `SET NAMES charset COLLATE collation`. +- PathEscape dbname in DSN. by @methane in [#1432](https://github.com/go-sql-driver/mysql/pull/1432) + - This is backward incompatible in rare case. Check your DSN. +- Drop Go 1.13-17 support by @methane in [#1420](https://github.com/go-sql-driver/mysql/pull/1420) + - Use Go 1.18+ +- Parse numbers on text protocol too by @methane in [#1452](https://github.com/go-sql-driver/mysql/pull/1452) + - When text protocol is used, go-mysql-driver passed bare `[]byte` to database/sql for avoid unnecessary allocation and conversion. + - If user specified `*any` to `Scan()`, database/sql passed the `[]byte` into the target variable. + - This confused users because most user doesn't know when text/binary protocol used. + - go-mysql-driver 1.8 converts integer/float values into int64/double even in text protocol. This doesn't increase allocation compared to `[]byte` and conversion cost is negatable. +- New options start using the Functional Option Pattern to avoid increasing technical debt in the Config object. Future version may introduce Functional Option for existing options, but not for now. + - Make TimeTruncate functional option by @methane in [1552](https://github.com/go-sql-driver/mysql/pull/1552) + - Add BeforeConnect callback to configuration object by @ItalyPaleAle in [#1469](https://github.com/go-sql-driver/mysql/pull/1469) + + +Other changes: + +- Adding DeregisterDialContext to prevent memory leaks with dialers we don't need anymore by @jypelle in https://github.com/go-sql-driver/mysql/pull/1422 +- Make logger configurable per connection by @frozenbonito in https://github.com/go-sql-driver/mysql/pull/1408 +- Fix ColumnType.DatabaseTypeName for mediumint unsigned by @evanelias in https://github.com/go-sql-driver/mysql/pull/1428 +- Add connection attributes by @Daemonxiao in https://github.com/go-sql-driver/mysql/pull/1389 +- Stop `ColumnTypeScanType()` from returning `sql.RawBytes` by @methane in https://github.com/go-sql-driver/mysql/pull/1424 +- Exec() now provides access to status of multiple statements. by @mherr-google in https://github.com/go-sql-driver/mysql/pull/1309 +- Allow to change (or disable) the default driver name for registration by @dolmen in https://github.com/go-sql-driver/mysql/pull/1499 +- Add default connection attribute '_server_host' by @oblitorum in https://github.com/go-sql-driver/mysql/pull/1506 +- QueryUnescape DSN ConnectionAttribute value by @zhangyangyu in https://github.com/go-sql-driver/mysql/pull/1470 +- Add client_ed25519 authentication by @Gusted in https://github.com/go-sql-driver/mysql/pull/1518 + ## Version 1.7.1 (2023-04-25) Changes: @@ -162,7 +204,7 @@ New Features: - Enable microsecond resolution on TIME, DATETIME and TIMESTAMP (#249) - Support for returning table alias on Columns() (#289, #359, #382) - - Placeholder interpolation, can be actived with the DSN parameter `interpolateParams=true` (#309, #318, #490) + - Placeholder interpolation, can be activated with the DSN parameter `interpolateParams=true` (#309, #318, #490) - Support for uint64 parameters with high bit set (#332, #345) - Cleartext authentication plugin support (#327) - Exported ParseDSN function and the Config struct (#403, #419, #429) @@ -206,7 +248,7 @@ Changes: - Also exported the MySQLWarning type - mysqlConn.Close returns the first error encountered instead of ignoring all errors - writePacket() automatically writes the packet size to the header - - readPacket() uses an iterative approach instead of the recursive approach to merge splitted packets + - readPacket() uses an iterative approach instead of the recursive approach to merge split packets New Features: @@ -254,7 +296,7 @@ Bugfixes: - Fixed MySQL 4.1 support: MySQL 4.1 sends packets with lengths which differ from the specification - Convert to DB timezone when inserting `time.Time` - - Splitted packets (more than 16MB) are now merged correctly + - Split packets (more than 16MB) are now merged correctly - Fixed false positive `io.EOF` errors when the data was fully read - Avoid panics on reuse of closed connections - Fixed empty string producing false nil values diff --git a/vendor/github.com/go-sql-driver/mysql/README.md b/vendor/github.com/go-sql-driver/mysql/README.md index 3b5d229a..4968cb06 100644 --- a/vendor/github.com/go-sql-driver/mysql/README.md +++ b/vendor/github.com/go-sql-driver/mysql/README.md @@ -40,15 +40,23 @@ A MySQL-Driver for Go's [database/sql](https://golang.org/pkg/database/sql/) pac * Optional placeholder interpolation ## Requirements - * Go 1.13 or higher. We aim to support the 3 latest versions of Go. - * MySQL (4.1+), MariaDB, Percona Server, Google CloudSQL or Sphinx (2.2.3+) + +* Go 1.19 or higher. We aim to support the 3 latest versions of Go. +* MySQL (5.7+) and MariaDB (10.3+) are supported. +* [TiDB](https://github.com/pingcap/tidb) is supported by PingCAP. + * Do not ask questions about TiDB in our issue tracker or forum. + * [Document](https://docs.pingcap.com/tidb/v6.1/dev-guide-sample-application-golang) + * [Forum](https://ask.pingcap.com/) +* go-mysql would work with Percona Server, Google CloudSQL or Sphinx (2.2.3+). + * Maintainers won't support them. Do not expect issues are investigated and resolved by maintainers. + * Investigate issues yourself and please send a pull request to fix it. --------------------------------------- ## Installation Simple install the package to your [$GOPATH](https://github.com/golang/go/wiki/GOPATH "GOPATH") with the [go tool](https://golang.org/cmd/go/ "go command") from shell: ```bash -$ go get -u github.com/go-sql-driver/mysql +go get -u github.com/go-sql-driver/mysql ``` Make sure [Git is installed](https://git-scm.com/downloads) on your machine and in your system's `PATH`. @@ -114,6 +122,12 @@ This has the same effect as an empty DSN string: ``` +`dbname` is escaped by [PathEscape()](https://pkg.go.dev/net/url#PathEscape) since v1.8.0. If your database name is `dbname/withslash`, it becomes: + +``` +/dbname%2Fwithslash +``` + Alternatively, [Config.FormatDSN](https://godoc.org/github.com/go-sql-driver/mysql#Config.FormatDSN) can be used to create a DSN string by filling a struct. #### Password @@ -121,7 +135,7 @@ Passwords can consist of any character. Escaping is **not** necessary. #### Protocol See [net.Dial](https://golang.org/pkg/net/#Dial) for more information which networks are available. -In general you should use an Unix domain socket if available and TCP otherwise for best performance. +In general you should use a Unix domain socket if available and TCP otherwise for best performance. #### Address For TCP and UDP networks, addresses have the form `host[:port]`. @@ -145,7 +159,7 @@ Default: false ``` `allowAllFiles=true` disables the file allowlist for `LOAD DATA LOCAL INFILE` and allows *all* files. -[*Might be insecure!*](http://dev.mysql.com/doc/refman/5.7/en/load-data-local.html) +[*Might be insecure!*](https://dev.mysql.com/doc/refman/8.0/en/load-data.html#load-data-local) ##### `allowCleartextPasswords` @@ -194,10 +208,9 @@ Valid Values: Default: none ``` -Sets the charset used for client-server interaction (`"SET NAMES "`). If multiple charsets are set (separated by a comma), the following charset is used if setting the charset failes. This enables for example support for `utf8mb4` ([introduced in MySQL 5.5.3](http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html)) with fallback to `utf8` for older servers (`charset=utf8mb4,utf8`). +Sets the charset used for client-server interaction (`"SET NAMES "`). If multiple charsets are set (separated by a comma), the following charset is used if setting the charset fails. This enables for example support for `utf8mb4` ([introduced in MySQL 5.5.3](http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html)) with fallback to `utf8` for older servers (`charset=utf8mb4,utf8`). -Usage of the `charset` parameter is discouraged because it issues additional queries to the server. -Unless you need the fallback behavior, please use `collation` instead. +See also [Unicode Support](#unicode-support). ##### `checkConnLiveness` @@ -226,6 +239,7 @@ The default collation (`utf8mb4_general_ci`) is supported from MySQL 5.5. You s Collations for charset "ucs2", "utf16", "utf16le", and "utf32" can not be used ([ref](https://dev.mysql.com/doc/refman/5.7/en/charset-connection.html#charset-connection-impermissible-client-charset)). +See also [Unicode Support](#unicode-support). ##### `clientFoundRows` @@ -279,6 +293,15 @@ Note that this sets the location for time.Time values but does not change MySQL' Please keep in mind, that param values must be [url.QueryEscape](https://golang.org/pkg/net/url/#QueryEscape)'ed. Alternatively you can manually replace the `/` with `%2F`. For example `US/Pacific` would be `loc=US%2FPacific`. +##### `timeTruncate` + +``` +Type: duration +Default: 0 +``` + +[Truncate time values](https://pkg.go.dev/time#Duration.Truncate) to the specified duration. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*. + ##### `maxAllowedPacket` ``` Type: decimal number @@ -295,9 +318,25 @@ Valid Values: true, false Default: false ``` -Allow multiple statements in one query. While this allows batch queries, it also greatly increases the risk of SQL injections. Only the result of the first query is returned, all other results are silently discarded. +Allow multiple statements in one query. This can be used to bach multiple queries. Use [Rows.NextResultSet()](https://pkg.go.dev/database/sql#Rows.NextResultSet) to get result of the second and subsequent queries. + +When `multiStatements` is used, `?` parameters must only be used in the first statement. [interpolateParams](#interpolateparams) can be used to avoid this limitation unless prepared statement is used explicitly. + +It's possible to access the last inserted ID and number of affected rows for multiple statements by using `sql.Conn.Raw()` and the `mysql.Result`. For example: -When `multiStatements` is used, `?` parameters must only be used in the first statement. +```go +conn, _ := db.Conn(ctx) +conn.Raw(func(conn any) error { + ex := conn.(driver.Execer) + res, err := ex.Exec(` + UPDATE point SET x = 1 WHERE y = 2; + UPDATE point SET x = 2 WHERE y = 3; + `, nil) + // Both slices have 2 elements. + log.Print(res.(mysql.Result).AllRowsAffected()) + log.Print(res.(mysql.Result).AllLastInsertIds()) +}) +``` ##### `parseTime` @@ -393,6 +432,15 @@ Default: 0 I/O write timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*. +##### `connectionAttributes` + +``` +Type: comma-delimited string of user-defined "key:value" pairs +Valid Values: (:,:,...) +Default: none +``` + +[Connection attributes](https://dev.mysql.com/doc/refman/8.0/en/performance-schema-connection-attribute-tables.html) are key-value pairs that application programs can pass to the server at connect time. ##### System Variables @@ -465,7 +513,7 @@ user:password@/ The connection pool is managed by Go's database/sql package. For details on how to configure the size of the pool and how long connections stay in the pool see `*DB.SetMaxOpenConns`, `*DB.SetMaxIdleConns`, and `*DB.SetConnMaxLifetime` in the [database/sql documentation](https://golang.org/pkg/database/sql/). The read, write, and dial timeouts for each individual connection are configured with the DSN parameters [`readTimeout`](#readtimeout), [`writeTimeout`](#writetimeout), and [`timeout`](#timeout), respectively. ## `ColumnType` Support -This driver supports the [`ColumnType` interface](https://golang.org/pkg/database/sql/#ColumnType) introduced in Go 1.8, with the exception of [`ColumnType.Length()`](https://golang.org/pkg/database/sql/#ColumnType.Length), which is currently not supported. All Unsigned database type names will be returned `UNSIGNED ` with `INT`, `TINYINT`, `SMALLINT`, `BIGINT`. +This driver supports the [`ColumnType` interface](https://golang.org/pkg/database/sql/#ColumnType) introduced in Go 1.8, with the exception of [`ColumnType.Length()`](https://golang.org/pkg/database/sql/#ColumnType.Length), which is currently not supported. All Unsigned database type names will be returned `UNSIGNED ` with `INT`, `TINYINT`, `SMALLINT`, `MEDIUMINT`, `BIGINT`. ## `context.Context` Support Go 1.8 added `database/sql` support for `context.Context`. This driver supports query timeouts and cancellation via contexts. @@ -478,7 +526,7 @@ For this feature you need direct access to the package. Therefore you must chang import "github.com/go-sql-driver/mysql" ``` -Files must be explicitly allowed by registering them with `mysql.RegisterLocalFile(filepath)` (recommended) or the allowlist check must be deactivated by using the DSN parameter `allowAllFiles=true` ([*Might be insecure!*](http://dev.mysql.com/doc/refman/5.7/en/load-data-local.html)). +Files must be explicitly allowed by registering them with `mysql.RegisterLocalFile(filepath)` (recommended) or the allowlist check must be deactivated by using the DSN parameter `allowAllFiles=true` ([*Might be insecure!*](https://dev.mysql.com/doc/refman/8.0/en/load-data.html#load-data-local)). To use a `io.Reader` a handler function must be registered with `mysql.RegisterReaderHandler(name, handler)` which returns a `io.Reader` or `io.ReadCloser`. The Reader is available with the filepath `Reader::` then. Choose different names for different handlers and `DeregisterReaderHandler` when you don't need it anymore. @@ -496,9 +544,11 @@ However, many want to scan MySQL `DATE` and `DATETIME` values into `time.Time` v ### Unicode support Since version 1.5 Go-MySQL-Driver automatically uses the collation ` utf8mb4_general_ci` by default. -Other collations / charsets can be set using the [`collation`](#collation) DSN parameter. +Other charsets / collations can be set using the [`charset`](#charset) or [`collation`](#collation) DSN parameter. -Version 1.0 of the driver recommended adding `&charset=utf8` (alias for `SET NAMES utf8`) to the DSN to enable proper UTF-8 support. This is not necessary anymore. The [`collation`](#collation) parameter should be preferred to set another collation / charset than the default. +- When only the `charset` is specified, the `SET NAMES ` query is sent and the server's default collation is used. +- When both the `charset` and `collation` are specified, the `SET NAMES COLLATE ` query is sent. +- When only the `collation` is specified, the collation is specified in the protocol handshake and the `SET NAMES` query is not sent. This can save one roundtrip, but note that the server may ignore the specified collation silently and use the server's default charset/collation instead. See http://dev.mysql.com/doc/refman/8.0/en/charset-unicode.html for more details on MySQL's Unicode support. diff --git a/vendor/github.com/go-sql-driver/mysql/auth.go b/vendor/github.com/go-sql-driver/mysql/auth.go index 1ff203e5..74e1bd03 100644 --- a/vendor/github.com/go-sql-driver/mysql/auth.go +++ b/vendor/github.com/go-sql-driver/mysql/auth.go @@ -13,10 +13,13 @@ import ( "crypto/rsa" "crypto/sha1" "crypto/sha256" + "crypto/sha512" "crypto/x509" "encoding/pem" "fmt" "sync" + + "filippo.io/edwards25519" ) // server pub keys registry @@ -33,7 +36,7 @@ var ( // Note: The provided rsa.PublicKey instance is exclusively owned by the driver // after registering it and may not be modified. // -// data, err := ioutil.ReadFile("mykey.pem") +// data, err := os.ReadFile("mykey.pem") // if err != nil { // log.Fatal(err) // } @@ -225,6 +228,44 @@ func encryptPassword(password string, seed []byte, pub *rsa.PublicKey) ([]byte, return rsa.EncryptOAEP(sha1, rand.Reader, pub, plain, nil) } +// authEd25519 does ed25519 authentication used by MariaDB. +func authEd25519(scramble []byte, password string) ([]byte, error) { + // Derived from https://github.com/MariaDB/server/blob/d8e6bb00888b1f82c031938f4c8ac5d97f6874c3/plugin/auth_ed25519/ref10/sign.c + // Code style is from https://cs.opensource.google/go/go/+/refs/tags/go1.21.5:src/crypto/ed25519/ed25519.go;l=207 + h := sha512.Sum512([]byte(password)) + + s, err := edwards25519.NewScalar().SetBytesWithClamping(h[:32]) + if err != nil { + return nil, err + } + A := (&edwards25519.Point{}).ScalarBaseMult(s) + + mh := sha512.New() + mh.Write(h[32:]) + mh.Write(scramble) + messageDigest := mh.Sum(nil) + r, err := edwards25519.NewScalar().SetUniformBytes(messageDigest) + if err != nil { + return nil, err + } + + R := (&edwards25519.Point{}).ScalarBaseMult(r) + + kh := sha512.New() + kh.Write(R.Bytes()) + kh.Write(A.Bytes()) + kh.Write(scramble) + hramDigest := kh.Sum(nil) + k, err := edwards25519.NewScalar().SetUniformBytes(hramDigest) + if err != nil { + return nil, err + } + + S := k.MultiplyAdd(k, s, r) + + return append(R.Bytes(), S.Bytes()...), nil +} + func (mc *mysqlConn) sendEncryptedPassword(seed []byte, pub *rsa.PublicKey) error { enc, err := encryptPassword(mc.cfg.Passwd, seed, pub) if err != nil { @@ -290,8 +331,14 @@ func (mc *mysqlConn) auth(authData []byte, plugin string) ([]byte, error) { enc, err := encryptPassword(mc.cfg.Passwd, authData, pubKey) return enc, err + case "client_ed25519": + if len(authData) != 32 { + return nil, ErrMalformPkt + } + return authEd25519(authData, mc.cfg.Passwd) + default: - errLog.Print("unknown auth plugin:", plugin) + mc.log("unknown auth plugin:", plugin) return nil, ErrUnknownPlugin } } @@ -338,7 +385,7 @@ func (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string) error { switch plugin { - // https://insidemysql.com/preparing-your-community-connector-for-mysql-8-part-2-sha256/ + // https://dev.mysql.com/blog-archive/preparing-your-community-connector-for-mysql-8-part-2-sha256/ case "caching_sha2_password": switch len(authData) { case 0: @@ -346,7 +393,7 @@ func (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string) error { case 1: switch authData[0] { case cachingSha2PasswordFastAuthSuccess: - if err = mc.readResultOK(); err == nil { + if err = mc.resultUnchanged().readResultOK(); err == nil { return nil // auth successful } @@ -376,13 +423,13 @@ func (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string) error { } if data[0] != iAuthMoreData { - return fmt.Errorf("unexpect resp from server for caching_sha2_password perform full authentication") + return fmt.Errorf("unexpected resp from server for caching_sha2_password, perform full authentication") } // parse public key block, rest := pem.Decode(data[1:]) if block == nil { - return fmt.Errorf("No Pem data found, data: %s", rest) + return fmt.Errorf("no pem data found, data: %s", rest) } pkix, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { @@ -397,7 +444,7 @@ func (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string) error { return err } } - return mc.readResultOK() + return mc.resultUnchanged().readResultOK() default: return ErrMalformPkt @@ -426,7 +473,7 @@ func (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string) error { if err != nil { return err } - return mc.readResultOK() + return mc.resultUnchanged().readResultOK() } default: diff --git a/vendor/github.com/go-sql-driver/mysql/collations.go b/vendor/github.com/go-sql-driver/mysql/collations.go index 295bfbe5..1cdf97b6 100644 --- a/vendor/github.com/go-sql-driver/mysql/collations.go +++ b/vendor/github.com/go-sql-driver/mysql/collations.go @@ -9,7 +9,7 @@ package mysql const defaultCollation = "utf8mb4_general_ci" -const binaryCollation = "binary" +const binaryCollationID = 63 // A list of available collations mapped to the internal ID. // To update this map use the following MySQL query: diff --git a/vendor/github.com/go-sql-driver/mysql/connection.go b/vendor/github.com/go-sql-driver/mysql/connection.go index 947a883e..eff978d9 100644 --- a/vendor/github.com/go-sql-driver/mysql/connection.go +++ b/vendor/github.com/go-sql-driver/mysql/connection.go @@ -23,10 +23,10 @@ import ( type mysqlConn struct { buf buffer netConn net.Conn - rawConn net.Conn // underlying connection when netConn is TLS connection. - affectedRows uint64 - insertId uint64 + rawConn net.Conn // underlying connection when netConn is TLS connection. + result mysqlResult // managed by clearResult() and handleOkPacket(). cfg *Config + connector *connector maxAllowedPacket int maxWriteSize int writeTimeout time.Duration @@ -34,7 +34,6 @@ type mysqlConn struct { status statusFlag sequence uint8 parseTime bool - reset bool // set when the Go SQL package calls ResetSession // for context support (Go 1.8+) watching bool @@ -45,17 +44,27 @@ type mysqlConn struct { closed atomicBool // set when conn is closed, before closech is closed } +// Helper function to call per-connection logger. +func (mc *mysqlConn) log(v ...any) { + mc.cfg.Logger.Print(v...) +} + // Handles parameters set in DSN after the connection is established func (mc *mysqlConn) handleParams() (err error) { var cmdSet strings.Builder + for param, val := range mc.cfg.Params { switch param { // Charset: character_set_connection, character_set_client, character_set_results case "charset": charsets := strings.Split(val, ",") - for i := range charsets { + for _, cs := range charsets { // ignore errors here - a charset may not exist - err = mc.exec("SET NAMES " + charsets[i]) + if mc.cfg.Collation != "" { + err = mc.exec("SET NAMES " + cs + " COLLATE " + mc.cfg.Collation) + } else { + err = mc.exec("SET NAMES " + cs) + } if err == nil { break } @@ -68,7 +77,7 @@ func (mc *mysqlConn) handleParams() (err error) { default: if cmdSet.Len() == 0 { // Heuristic: 29 chars for each other key=value to reduce reallocations - cmdSet.Grow(4 + len(param) + 1 + len(val) + 30*(len(mc.cfg.Params)-1)) + cmdSet.Grow(4 + len(param) + 3 + len(val) + 30*(len(mc.cfg.Params)-1)) cmdSet.WriteString("SET ") } else { cmdSet.WriteString(", ") @@ -105,7 +114,7 @@ func (mc *mysqlConn) Begin() (driver.Tx, error) { func (mc *mysqlConn) begin(readOnly bool) (driver.Tx, error) { if mc.closed.Load() { - errLog.Print(ErrInvalidConn) + mc.log(ErrInvalidConn) return nil, driver.ErrBadConn } var q string @@ -128,7 +137,7 @@ func (mc *mysqlConn) Close() (err error) { } mc.cleanup() - + mc.clearResult() return } @@ -143,12 +152,16 @@ func (mc *mysqlConn) cleanup() { // Makes cleanup idempotent close(mc.closech) - if mc.netConn == nil { + conn := mc.rawConn + if conn == nil { return } - if err := mc.netConn.Close(); err != nil { - errLog.Print(err) + if err := conn.Close(); err != nil { + mc.log(err) } + // This function can be called from multiple goroutines. + // So we can not mc.clearResult() here. + // Caller should do it if they are in safe goroutine. } func (mc *mysqlConn) error() error { @@ -163,14 +176,14 @@ func (mc *mysqlConn) error() error { func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) { if mc.closed.Load() { - errLog.Print(ErrInvalidConn) + mc.log(ErrInvalidConn) return nil, driver.ErrBadConn } // Send command err := mc.writeCommandPacketStr(comStmtPrepare, query) if err != nil { // STMT_PREPARE is safe to retry. So we can return ErrBadConn here. - errLog.Print(err) + mc.log(err) return nil, driver.ErrBadConn } @@ -204,7 +217,7 @@ func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (strin buf, err := mc.buf.takeCompleteBuffer() if err != nil { // can not take the buffer. Something must be wrong with the connection - errLog.Print(err) + mc.log(err) return "", ErrInvalidConn } buf = buf[:0] @@ -246,7 +259,7 @@ func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (strin buf = append(buf, "'0000-00-00'"...) } else { buf = append(buf, '\'') - buf, err = appendDateTime(buf, v.In(mc.cfg.Loc)) + buf, err = appendDateTime(buf, v.In(mc.cfg.Loc), mc.cfg.timeTruncate) if err != nil { return "", err } @@ -296,7 +309,7 @@ func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (strin func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) { if mc.closed.Load() { - errLog.Print(ErrInvalidConn) + mc.log(ErrInvalidConn) return nil, driver.ErrBadConn } if len(args) != 0 { @@ -310,28 +323,25 @@ func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, err } query = prepared } - mc.affectedRows = 0 - mc.insertId = 0 err := mc.exec(query) if err == nil { - return &mysqlResult{ - affectedRows: int64(mc.affectedRows), - insertId: int64(mc.insertId), - }, err + copied := mc.result + return &copied, err } return nil, mc.markBadConn(err) } // Internal function to execute commands func (mc *mysqlConn) exec(query string) error { + handleOk := mc.clearResult() // Send command if err := mc.writeCommandPacketStr(comQuery, query); err != nil { return mc.markBadConn(err) } // Read Result - resLen, err := mc.readResultSetHeaderPacket() + resLen, err := handleOk.readResultSetHeaderPacket() if err != nil { return err } @@ -348,7 +358,7 @@ func (mc *mysqlConn) exec(query string) error { } } - return mc.discardResults() + return handleOk.discardResults() } func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) { @@ -356,8 +366,10 @@ func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, erro } func (mc *mysqlConn) query(query string, args []driver.Value) (*textRows, error) { + handleOk := mc.clearResult() + if mc.closed.Load() { - errLog.Print(ErrInvalidConn) + mc.log(ErrInvalidConn) return nil, driver.ErrBadConn } if len(args) != 0 { @@ -376,7 +388,7 @@ func (mc *mysqlConn) query(query string, args []driver.Value) (*textRows, error) if err == nil { // Read Result var resLen int - resLen, err = mc.readResultSetHeaderPacket() + resLen, err = handleOk.readResultSetHeaderPacket() if err == nil { rows := new(textRows) rows.mc = mc @@ -404,12 +416,13 @@ func (mc *mysqlConn) query(query string, args []driver.Value) (*textRows, error) // The returned byte slice is only valid until the next read func (mc *mysqlConn) getSystemVar(name string) ([]byte, error) { // Send command + handleOk := mc.clearResult() if err := mc.writeCommandPacketStr(comQuery, "SELECT @@"+name); err != nil { return nil, err } // Read Result - resLen, err := mc.readResultSetHeaderPacket() + resLen, err := handleOk.readResultSetHeaderPacket() if err == nil { rows := new(textRows) rows.mc = mc @@ -451,7 +464,7 @@ func (mc *mysqlConn) finish() { // Ping implements driver.Pinger interface func (mc *mysqlConn) Ping(ctx context.Context) (err error) { if mc.closed.Load() { - errLog.Print(ErrInvalidConn) + mc.log(ErrInvalidConn) return driver.ErrBadConn } @@ -460,11 +473,12 @@ func (mc *mysqlConn) Ping(ctx context.Context) (err error) { } defer mc.finish() + handleOk := mc.clearResult() if err = mc.writeCommandPacket(comPing); err != nil { return mc.markBadConn(err) } - return mc.readResultOK() + return handleOk.readResultOK() } // BeginTx implements driver.ConnBeginTx interface @@ -639,7 +653,31 @@ func (mc *mysqlConn) ResetSession(ctx context.Context) error { if mc.closed.Load() { return driver.ErrBadConn } - mc.reset = true + + // Perform a stale connection check. We only perform this check for + // the first query on a connection that has been checked out of the + // connection pool: a fresh connection from the pool is more likely + // to be stale, and it has not performed any previous writes that + // could cause data corruption, so it's safe to return ErrBadConn + // if the check fails. + if mc.cfg.CheckConnLiveness { + conn := mc.netConn + if mc.rawConn != nil { + conn = mc.rawConn + } + var err error + if mc.cfg.ReadTimeout != 0 { + err = conn.SetReadDeadline(time.Now().Add(mc.cfg.ReadTimeout)) + } + if err == nil { + err = connCheck(conn) + } + if err != nil { + mc.log("closing bad idle connection: ", err) + return driver.ErrBadConn + } + } + return nil } diff --git a/vendor/github.com/go-sql-driver/mysql/connector.go b/vendor/github.com/go-sql-driver/mysql/connector.go index d567b4e4..b6707759 100644 --- a/vendor/github.com/go-sql-driver/mysql/connector.go +++ b/vendor/github.com/go-sql-driver/mysql/connector.go @@ -12,10 +12,53 @@ import ( "context" "database/sql/driver" "net" + "os" + "strconv" + "strings" ) type connector struct { - cfg *Config // immutable private copy. + cfg *Config // immutable private copy. + encodedAttributes string // Encoded connection attributes. +} + +func encodeConnectionAttributes(cfg *Config) string { + connAttrsBuf := make([]byte, 0) + + // default connection attributes + connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrClientName) + connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrClientNameValue) + connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrOS) + connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrOSValue) + connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrPlatform) + connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrPlatformValue) + connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrPid) + connAttrsBuf = appendLengthEncodedString(connAttrsBuf, strconv.Itoa(os.Getpid())) + serverHost, _, _ := net.SplitHostPort(cfg.Addr) + if serverHost != "" { + connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrServerHost) + connAttrsBuf = appendLengthEncodedString(connAttrsBuf, serverHost) + } + + // user-defined connection attributes + for _, connAttr := range strings.Split(cfg.ConnectionAttributes, ",") { + k, v, found := strings.Cut(connAttr, ":") + if !found { + continue + } + connAttrsBuf = appendLengthEncodedString(connAttrsBuf, k) + connAttrsBuf = appendLengthEncodedString(connAttrsBuf, v) + } + + return string(connAttrsBuf) +} + +func newConnector(cfg *Config) *connector { + encodedAttributes := encodeConnectionAttributes(cfg) + return &connector{ + cfg: cfg, + encodedAttributes: encodedAttributes, + } } // Connect implements driver.Connector interface. @@ -23,12 +66,23 @@ type connector struct { func (c *connector) Connect(ctx context.Context) (driver.Conn, error) { var err error + // Invoke beforeConnect if present, with a copy of the configuration + cfg := c.cfg + if c.cfg.beforeConnect != nil { + cfg = c.cfg.Clone() + err = c.cfg.beforeConnect(ctx, cfg) + if err != nil { + return nil, err + } + } + // New mysqlConn mc := &mysqlConn{ maxAllowedPacket: maxPacketSize, maxWriteSize: maxPacketSize - 1, closech: make(chan struct{}), - cfg: c.cfg, + cfg: cfg, + connector: c, } mc.parseTime = mc.cfg.ParseTime @@ -48,18 +102,15 @@ func (c *connector) Connect(ctx context.Context) (driver.Conn, error) { nd := net.Dialer{Timeout: mc.cfg.Timeout} mc.netConn, err = nd.DialContext(ctx, mc.cfg.Net, mc.cfg.Addr) } - if err != nil { return nil, err } + mc.rawConn = mc.netConn // Enable TCP Keepalives on TCP connections if tc, ok := mc.netConn.(*net.TCPConn); ok { if err := tc.SetKeepAlive(true); err != nil { - // Don't send COM_QUIT before handshake. - mc.netConn.Close() - mc.netConn = nil - return nil, err + c.cfg.Logger.Print(err) } } @@ -92,7 +143,7 @@ func (c *connector) Connect(ctx context.Context) (driver.Conn, error) { authResp, err := mc.auth(authData, plugin) if err != nil { // try the default auth plugin, if using the requested plugin failed - errLog.Print("could not use requested auth plugin '"+plugin+"': ", err.Error()) + c.cfg.Logger.Print("could not use requested auth plugin '"+plugin+"': ", err.Error()) plugin = defaultAuthPlugin authResp, err = mc.auth(authData, plugin) if err != nil { diff --git a/vendor/github.com/go-sql-driver/mysql/const.go b/vendor/github.com/go-sql-driver/mysql/const.go index 64e2bced..22526e03 100644 --- a/vendor/github.com/go-sql-driver/mysql/const.go +++ b/vendor/github.com/go-sql-driver/mysql/const.go @@ -8,12 +8,25 @@ package mysql +import "runtime" + const ( defaultAuthPlugin = "mysql_native_password" defaultMaxAllowedPacket = 64 << 20 // 64 MiB. See https://github.com/go-sql-driver/mysql/issues/1355 minProtocolVersion = 10 maxPacketSize = 1<<24 - 1 timeFormat = "2006-01-02 15:04:05.999999" + + // Connection attributes + // See https://dev.mysql.com/doc/refman/8.0/en/performance-schema-connection-attribute-tables.html#performance-schema-connection-attributes-available + connAttrClientName = "_client_name" + connAttrClientNameValue = "Go-MySQL-Driver" + connAttrOS = "_os" + connAttrOSValue = runtime.GOOS + connAttrPlatform = "_platform" + connAttrPlatformValue = runtime.GOARCH + connAttrPid = "_pid" + connAttrServerHost = "_server_host" ) // MySQL constants documentation: diff --git a/vendor/github.com/go-sql-driver/mysql/driver.go b/vendor/github.com/go-sql-driver/mysql/driver.go index ad7aec21..105316b8 100644 --- a/vendor/github.com/go-sql-driver/mysql/driver.go +++ b/vendor/github.com/go-sql-driver/mysql/driver.go @@ -55,6 +55,15 @@ func RegisterDialContext(net string, dial DialContextFunc) { dials[net] = dial } +// DeregisterDialContext removes the custom dial function registered with the given net. +func DeregisterDialContext(net string) { + dialsLock.Lock() + defer dialsLock.Unlock() + if dials != nil { + delete(dials, net) + } +} + // RegisterDial registers a custom dial function. It can then be used by the // network address mynet(addr), where mynet is the registered new network. // addr is passed as a parameter to the dial function. @@ -74,14 +83,18 @@ func (d MySQLDriver) Open(dsn string) (driver.Conn, error) { if err != nil { return nil, err } - c := &connector{ - cfg: cfg, - } + c := newConnector(cfg) return c.Connect(context.Background()) } +// This variable can be replaced with -ldflags like below: +// go build "-ldflags=-X github.com/go-sql-driver/mysql.driverName=custom" +var driverName = "mysql" + func init() { - sql.Register("mysql", &MySQLDriver{}) + if driverName != "" { + sql.Register(driverName, &MySQLDriver{}) + } } // NewConnector returns new driver.Connector. @@ -92,7 +105,7 @@ func NewConnector(cfg *Config) (driver.Connector, error) { if err := cfg.normalize(); err != nil { return nil, err } - return &connector{cfg: cfg}, nil + return newConnector(cfg), nil } // OpenConnector implements driver.DriverContext. @@ -101,7 +114,5 @@ func (d MySQLDriver) OpenConnector(dsn string) (driver.Connector, error) { if err != nil { return nil, err } - return &connector{ - cfg: cfg, - }, nil + return newConnector(cfg), nil } diff --git a/vendor/github.com/go-sql-driver/mysql/dsn.go b/vendor/github.com/go-sql-driver/mysql/dsn.go index 4b71aaab..65f5a024 100644 --- a/vendor/github.com/go-sql-driver/mysql/dsn.go +++ b/vendor/github.com/go-sql-driver/mysql/dsn.go @@ -10,6 +10,7 @@ package mysql import ( "bytes" + "context" "crypto/rsa" "crypto/tls" "errors" @@ -34,22 +35,27 @@ var ( // If a new Config is created instead of being parsed from a DSN string, // the NewConfig function should be used, which sets default values. type Config struct { - User string // Username - Passwd string // Password (requires User) - Net string // Network type - Addr string // Network address (requires Net) - DBName string // Database name - Params map[string]string // Connection parameters - Collation string // Connection collation - Loc *time.Location // Location for time.Time values - MaxAllowedPacket int // Max packet size allowed - ServerPubKey string // Server public key name - pubKey *rsa.PublicKey // Server public key - TLSConfig string // TLS configuration name - TLS *tls.Config // TLS configuration, its priority is higher than TLSConfig - Timeout time.Duration // Dial timeout - ReadTimeout time.Duration // I/O read timeout - WriteTimeout time.Duration // I/O write timeout + // non boolean fields + + User string // Username + Passwd string // Password (requires User) + Net string // Network (e.g. "tcp", "tcp6", "unix". default: "tcp") + Addr string // Address (default: "127.0.0.1:3306" for "tcp" and "/tmp/mysql.sock" for "unix") + DBName string // Database name + Params map[string]string // Connection parameters + ConnectionAttributes string // Connection Attributes, comma-delimited string of user-defined "key:value" pairs + Collation string // Connection collation + Loc *time.Location // Location for time.Time values + MaxAllowedPacket int // Max packet size allowed + ServerPubKey string // Server public key name + TLSConfig string // TLS configuration name + TLS *tls.Config // TLS configuration, its priority is higher than TLSConfig + Timeout time.Duration // Dial timeout + ReadTimeout time.Duration // I/O read timeout + WriteTimeout time.Duration // I/O write timeout + Logger Logger // Logger + + // boolean fields AllowAllFiles bool // Allow all files to be used with LOAD DATA LOCAL INFILE AllowCleartextPasswords bool // Allows the cleartext client side plugin @@ -63,17 +69,57 @@ type Config struct { MultiStatements bool // Allow multiple statements in one query ParseTime bool // Parse time values to time.Time RejectReadOnly bool // Reject read-only connections + + // unexported fields. new options should be come here + + beforeConnect func(context.Context, *Config) error // Invoked before a connection is established + pubKey *rsa.PublicKey // Server public key + timeTruncate time.Duration // Truncate time.Time values to the specified duration } +// Functional Options Pattern +// https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis +type Option func(*Config) error + // NewConfig creates a new Config and sets default values. func NewConfig() *Config { - return &Config{ - Collation: defaultCollation, + cfg := &Config{ Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, + Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true, } + + return cfg +} + +// Apply applies the given options to the Config object. +func (c *Config) Apply(opts ...Option) error { + for _, opt := range opts { + err := opt(c) + if err != nil { + return err + } + } + return nil +} + +// TimeTruncate sets the time duration to truncate time.Time values in +// query parameters. +func TimeTruncate(d time.Duration) Option { + return func(cfg *Config) error { + cfg.timeTruncate = d + return nil + } +} + +// BeforeConnect sets the function to be invoked before a connection is established. +func BeforeConnect(fn func(context.Context, *Config) error) Option { + return func(cfg *Config) error { + cfg.beforeConnect = fn + return nil + } } func (cfg *Config) Clone() *Config { @@ -97,7 +143,7 @@ func (cfg *Config) Clone() *Config { } func (cfg *Config) normalize() error { - if cfg.InterpolateParams && unsafeCollations[cfg.Collation] { + if cfg.InterpolateParams && cfg.Collation != "" && unsafeCollations[cfg.Collation] { return errInvalidDSNUnsafeCollation } @@ -153,6 +199,10 @@ func (cfg *Config) normalize() error { } } + if cfg.Logger == nil { + cfg.Logger = defaultLogger + } + return nil } @@ -171,6 +221,8 @@ func writeDSNParam(buf *bytes.Buffer, hasParam *bool, name, value string) { // FormatDSN formats the given Config into a DSN string which can be passed to // the driver. +// +// Note: use [NewConnector] and [database/sql.OpenDB] to open a connection from a [*Config]. func (cfg *Config) FormatDSN() string { var buf bytes.Buffer @@ -196,7 +248,7 @@ func (cfg *Config) FormatDSN() string { // /dbname buf.WriteByte('/') - buf.WriteString(cfg.DBName) + buf.WriteString(url.PathEscape(cfg.DBName)) // [?param1=value1&...¶mN=valueN] hasParam := false @@ -230,7 +282,7 @@ func (cfg *Config) FormatDSN() string { writeDSNParam(&buf, &hasParam, "clientFoundRows", "true") } - if col := cfg.Collation; col != defaultCollation && len(col) > 0 { + if col := cfg.Collation; col != "" { writeDSNParam(&buf, &hasParam, "collation", col) } @@ -254,6 +306,10 @@ func (cfg *Config) FormatDSN() string { writeDSNParam(&buf, &hasParam, "parseTime", "true") } + if cfg.timeTruncate > 0 { + writeDSNParam(&buf, &hasParam, "timeTruncate", cfg.timeTruncate.String()) + } + if cfg.ReadTimeout > 0 { writeDSNParam(&buf, &hasParam, "readTimeout", cfg.ReadTimeout.String()) } @@ -358,7 +414,11 @@ func ParseDSN(dsn string) (cfg *Config, err error) { break } } - cfg.DBName = dsn[i+1 : j] + + dbname := dsn[i+1 : j] + if cfg.DBName, err = url.PathUnescape(dbname); err != nil { + return nil, fmt.Errorf("invalid dbname %q: %w", dbname, err) + } break } @@ -378,13 +438,13 @@ func ParseDSN(dsn string) (cfg *Config, err error) { // Values must be url.QueryEscape'ed func parseDSNParams(cfg *Config, params string) (err error) { for _, v := range strings.Split(params, "&") { - param := strings.SplitN(v, "=", 2) - if len(param) != 2 { + key, value, found := strings.Cut(v, "=") + if !found { continue } // cfg params - switch value := param[1]; param[0] { + switch key { // Disable INFILE allowlist / enable all files case "allowAllFiles": var isBool bool @@ -490,6 +550,13 @@ func parseDSNParams(cfg *Config, params string) (err error) { return errors.New("invalid bool value: " + value) } + // time.Time truncation + case "timeTruncate": + cfg.timeTruncate, err = time.ParseDuration(value) + if err != nil { + return fmt.Errorf("invalid timeTruncate value: %v, error: %w", value, err) + } + // I/O read Timeout case "readTimeout": cfg.ReadTimeout, err = time.ParseDuration(value) @@ -554,13 +621,22 @@ func parseDSNParams(cfg *Config, params string) (err error) { if err != nil { return } + + // Connection attributes + case "connectionAttributes": + connectionAttributes, err := url.QueryUnescape(value) + if err != nil { + return fmt.Errorf("invalid connectionAttributes value: %v", err) + } + cfg.ConnectionAttributes = connectionAttributes + default: // lazy init if cfg.Params == nil { cfg.Params = make(map[string]string) } - if cfg.Params[param[0]], err = url.QueryUnescape(value); err != nil { + if cfg.Params[key], err = url.QueryUnescape(value); err != nil { return } } diff --git a/vendor/github.com/go-sql-driver/mysql/errors.go b/vendor/github.com/go-sql-driver/mysql/errors.go index ff9a8f08..a7ef8890 100644 --- a/vendor/github.com/go-sql-driver/mysql/errors.go +++ b/vendor/github.com/go-sql-driver/mysql/errors.go @@ -21,7 +21,7 @@ var ( ErrMalformPkt = errors.New("malformed packet") ErrNoTLS = errors.New("TLS requested but server does not support TLS") ErrCleartextPassword = errors.New("this user requires clear text authentication. If you still want to use it, please add 'allowCleartextPasswords=1' to your DSN") - ErrNativePassword = errors.New("this user requires mysql native password authentication.") + ErrNativePassword = errors.New("this user requires mysql native password authentication") ErrOldPassword = errors.New("this user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords") ErrUnknownPlugin = errors.New("this authentication plugin is not supported") ErrOldProtocol = errors.New("MySQL server does not support required protocol 41+") @@ -37,20 +37,26 @@ var ( errBadConnNoWrite = errors.New("bad connection") ) -var errLog = Logger(log.New(os.Stderr, "[mysql] ", log.Ldate|log.Ltime|log.Lshortfile)) +var defaultLogger = Logger(log.New(os.Stderr, "[mysql] ", log.Ldate|log.Ltime|log.Lshortfile)) // Logger is used to log critical error messages. type Logger interface { - Print(v ...interface{}) + Print(v ...any) } -// SetLogger is used to set the logger for critical errors. +// NopLogger is a nop implementation of the Logger interface. +type NopLogger struct{} + +// Print implements Logger interface. +func (nl *NopLogger) Print(_ ...any) {} + +// SetLogger is used to set the default logger for critical errors. // The initial logger is os.Stderr. func SetLogger(logger Logger) error { if logger == nil { return errors.New("logger is nil") } - errLog = logger + defaultLogger = logger return nil } diff --git a/vendor/github.com/go-sql-driver/mysql/fields.go b/vendor/github.com/go-sql-driver/mysql/fields.go index e0654a83..28608424 100644 --- a/vendor/github.com/go-sql-driver/mysql/fields.go +++ b/vendor/github.com/go-sql-driver/mysql/fields.go @@ -18,7 +18,7 @@ func (mf *mysqlField) typeDatabaseName() string { case fieldTypeBit: return "BIT" case fieldTypeBLOB: - if mf.charSet != collations[binaryCollation] { + if mf.charSet != binaryCollationID { return "TEXT" } return "BLOB" @@ -37,6 +37,9 @@ func (mf *mysqlField) typeDatabaseName() string { case fieldTypeGeometry: return "GEOMETRY" case fieldTypeInt24: + if mf.flags&flagUnsigned != 0 { + return "UNSIGNED MEDIUMINT" + } return "MEDIUMINT" case fieldTypeJSON: return "JSON" @@ -46,7 +49,7 @@ func (mf *mysqlField) typeDatabaseName() string { } return "INT" case fieldTypeLongBLOB: - if mf.charSet != collations[binaryCollation] { + if mf.charSet != binaryCollationID { return "LONGTEXT" } return "LONGBLOB" @@ -56,7 +59,7 @@ func (mf *mysqlField) typeDatabaseName() string { } return "BIGINT" case fieldTypeMediumBLOB: - if mf.charSet != collations[binaryCollation] { + if mf.charSet != binaryCollationID { return "MEDIUMTEXT" } return "MEDIUMBLOB" @@ -74,7 +77,12 @@ func (mf *mysqlField) typeDatabaseName() string { } return "SMALLINT" case fieldTypeString: - if mf.charSet == collations[binaryCollation] { + if mf.flags&flagEnum != 0 { + return "ENUM" + } else if mf.flags&flagSet != 0 { + return "SET" + } + if mf.charSet == binaryCollationID { return "BINARY" } return "CHAR" @@ -88,17 +96,17 @@ func (mf *mysqlField) typeDatabaseName() string { } return "TINYINT" case fieldTypeTinyBLOB: - if mf.charSet != collations[binaryCollation] { + if mf.charSet != binaryCollationID { return "TINYTEXT" } return "TINYBLOB" case fieldTypeVarChar: - if mf.charSet == collations[binaryCollation] { + if mf.charSet == binaryCollationID { return "VARBINARY" } return "VARCHAR" case fieldTypeVarString: - if mf.charSet == collations[binaryCollation] { + if mf.charSet == binaryCollationID { return "VARBINARY" } return "VARCHAR" @@ -110,21 +118,23 @@ func (mf *mysqlField) typeDatabaseName() string { } var ( - scanTypeFloat32 = reflect.TypeOf(float32(0)) - scanTypeFloat64 = reflect.TypeOf(float64(0)) - scanTypeInt8 = reflect.TypeOf(int8(0)) - scanTypeInt16 = reflect.TypeOf(int16(0)) - scanTypeInt32 = reflect.TypeOf(int32(0)) - scanTypeInt64 = reflect.TypeOf(int64(0)) - scanTypeNullFloat = reflect.TypeOf(sql.NullFloat64{}) - scanTypeNullInt = reflect.TypeOf(sql.NullInt64{}) - scanTypeNullTime = reflect.TypeOf(sql.NullTime{}) - scanTypeUint8 = reflect.TypeOf(uint8(0)) - scanTypeUint16 = reflect.TypeOf(uint16(0)) - scanTypeUint32 = reflect.TypeOf(uint32(0)) - scanTypeUint64 = reflect.TypeOf(uint64(0)) - scanTypeRawBytes = reflect.TypeOf(sql.RawBytes{}) - scanTypeUnknown = reflect.TypeOf(new(interface{})) + scanTypeFloat32 = reflect.TypeOf(float32(0)) + scanTypeFloat64 = reflect.TypeOf(float64(0)) + scanTypeInt8 = reflect.TypeOf(int8(0)) + scanTypeInt16 = reflect.TypeOf(int16(0)) + scanTypeInt32 = reflect.TypeOf(int32(0)) + scanTypeInt64 = reflect.TypeOf(int64(0)) + scanTypeNullFloat = reflect.TypeOf(sql.NullFloat64{}) + scanTypeNullInt = reflect.TypeOf(sql.NullInt64{}) + scanTypeNullTime = reflect.TypeOf(sql.NullTime{}) + scanTypeUint8 = reflect.TypeOf(uint8(0)) + scanTypeUint16 = reflect.TypeOf(uint16(0)) + scanTypeUint32 = reflect.TypeOf(uint32(0)) + scanTypeUint64 = reflect.TypeOf(uint64(0)) + scanTypeString = reflect.TypeOf("") + scanTypeNullString = reflect.TypeOf(sql.NullString{}) + scanTypeBytes = reflect.TypeOf([]byte{}) + scanTypeUnknown = reflect.TypeOf(new(any)) ) type mysqlField struct { @@ -187,12 +197,18 @@ func (mf *mysqlField) scanType() reflect.Type { } return scanTypeNullFloat + case fieldTypeBit, fieldTypeTinyBLOB, fieldTypeMediumBLOB, fieldTypeLongBLOB, + fieldTypeBLOB, fieldTypeVarString, fieldTypeString, fieldTypeGeometry: + if mf.charSet == binaryCollationID { + return scanTypeBytes + } + fallthrough case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar, - fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB, - fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB, - fieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeJSON, - fieldTypeTime: - return scanTypeRawBytes + fieldTypeEnum, fieldTypeSet, fieldTypeJSON, fieldTypeTime: + if mf.flags&flagNotNULL != 0 { + return scanTypeString + } + return scanTypeNullString case fieldTypeDate, fieldTypeNewDate, fieldTypeTimestamp, fieldTypeDateTime: diff --git a/vendor/github.com/go-sql-driver/mysql/fuzz.go b/vendor/github.com/go-sql-driver/mysql/fuzz.go deleted file mode 100644 index 3a4ec25a..00000000 --- a/vendor/github.com/go-sql-driver/mysql/fuzz.go +++ /dev/null @@ -1,25 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package. -// -// Copyright 2020 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -//go:build gofuzz -// +build gofuzz - -package mysql - -import ( - "database/sql" -) - -func Fuzz(data []byte) int { - db, err := sql.Open("mysql", string(data)) - if err != nil { - return 0 - } - db.Close() - return 1 -} diff --git a/vendor/github.com/go-sql-driver/mysql/infile.go b/vendor/github.com/go-sql-driver/mysql/infile.go index 3279dcff..0c8af9f1 100644 --- a/vendor/github.com/go-sql-driver/mysql/infile.go +++ b/vendor/github.com/go-sql-driver/mysql/infile.go @@ -93,7 +93,7 @@ func deferredClose(err *error, closer io.Closer) { const defaultPacketSize = 16 * 1024 // 16KB is small enough for disk readahead and large enough for TCP -func (mc *mysqlConn) handleInFileRequest(name string) (err error) { +func (mc *okHandler) handleInFileRequest(name string) (err error) { var rdr io.Reader var data []byte packetSize := defaultPacketSize @@ -116,10 +116,10 @@ func (mc *mysqlConn) handleInFileRequest(name string) (err error) { defer deferredClose(&err, cl) } } else { - err = fmt.Errorf("Reader '%s' is ", name) + err = fmt.Errorf("reader '%s' is ", name) } } else { - err = fmt.Errorf("Reader '%s' is not registered", name) + err = fmt.Errorf("reader '%s' is not registered", name) } } else { // File name = strings.Trim(name, `"`) @@ -154,7 +154,7 @@ func (mc *mysqlConn) handleInFileRequest(name string) (err error) { for err == nil { n, err = rdr.Read(data[4:]) if n > 0 { - if ioErr := mc.writePacket(data[:4+n]); ioErr != nil { + if ioErr := mc.conn().writePacket(data[:4+n]); ioErr != nil { return ioErr } } @@ -168,7 +168,7 @@ func (mc *mysqlConn) handleInFileRequest(name string) (err error) { if data == nil { data = make([]byte, 4) } - if ioErr := mc.writePacket(data[:4]); ioErr != nil { + if ioErr := mc.conn().writePacket(data[:4]); ioErr != nil { return ioErr } @@ -177,6 +177,6 @@ func (mc *mysqlConn) handleInFileRequest(name string) (err error) { return mc.readResultOK() } - mc.readPacket() + mc.conn().readPacket() return err } diff --git a/vendor/github.com/go-sql-driver/mysql/nulltime.go b/vendor/github.com/go-sql-driver/mysql/nulltime.go index 36c8a42c..316a48aa 100644 --- a/vendor/github.com/go-sql-driver/mysql/nulltime.go +++ b/vendor/github.com/go-sql-driver/mysql/nulltime.go @@ -38,7 +38,7 @@ type NullTime sql.NullTime // Scan implements the Scanner interface. // The value type must be time.Time or string / []byte (formatted time-string), // otherwise Scan fails. -func (nt *NullTime) Scan(value interface{}) (err error) { +func (nt *NullTime) Scan(value any) (err error) { if value == nil { nt.Time, nt.Valid = time.Time{}, false return @@ -59,7 +59,7 @@ func (nt *NullTime) Scan(value interface{}) (err error) { } nt.Valid = false - return fmt.Errorf("Can't convert %T to time.Time", value) + return fmt.Errorf("can't convert %T to time.Time", value) } // Value implements the driver Valuer interface. diff --git a/vendor/github.com/go-sql-driver/mysql/packets.go b/vendor/github.com/go-sql-driver/mysql/packets.go index ee05c95a..90a34728 100644 --- a/vendor/github.com/go-sql-driver/mysql/packets.go +++ b/vendor/github.com/go-sql-driver/mysql/packets.go @@ -14,10 +14,10 @@ import ( "database/sql/driver" "encoding/binary" "encoding/json" - "errors" "fmt" "io" "math" + "strconv" "time" ) @@ -34,7 +34,7 @@ func (mc *mysqlConn) readPacket() ([]byte, error) { if cerr := mc.canceled.Value(); cerr != nil { return nil, cerr } - errLog.Print(err) + mc.log(err) mc.Close() return nil, ErrInvalidConn } @@ -44,6 +44,7 @@ func (mc *mysqlConn) readPacket() ([]byte, error) { // check packet sync [8 bit] if data[3] != mc.sequence { + mc.Close() if data[3] > mc.sequence { return nil, ErrPktSyncMul } @@ -56,7 +57,7 @@ func (mc *mysqlConn) readPacket() ([]byte, error) { if pktLen == 0 { // there was no previous packet if prevData == nil { - errLog.Print(ErrMalformPkt) + mc.log(ErrMalformPkt) mc.Close() return nil, ErrInvalidConn } @@ -70,7 +71,7 @@ func (mc *mysqlConn) readPacket() ([]byte, error) { if cerr := mc.canceled.Value(); cerr != nil { return nil, cerr } - errLog.Print(err) + mc.log(err) mc.Close() return nil, ErrInvalidConn } @@ -97,34 +98,6 @@ func (mc *mysqlConn) writePacket(data []byte) error { return ErrPktTooLarge } - // Perform a stale connection check. We only perform this check for - // the first query on a connection that has been checked out of the - // connection pool: a fresh connection from the pool is more likely - // to be stale, and it has not performed any previous writes that - // could cause data corruption, so it's safe to return ErrBadConn - // if the check fails. - if mc.reset { - mc.reset = false - conn := mc.netConn - if mc.rawConn != nil { - conn = mc.rawConn - } - var err error - if mc.cfg.CheckConnLiveness { - if mc.cfg.ReadTimeout != 0 { - err = conn.SetReadDeadline(time.Now().Add(mc.cfg.ReadTimeout)) - } - if err == nil { - err = connCheck(conn) - } - } - if err != nil { - errLog.Print("closing bad idle connection: ", err) - mc.Close() - return driver.ErrBadConn - } - } - for { var size int if pktLen >= maxPacketSize { @@ -161,7 +134,7 @@ func (mc *mysqlConn) writePacket(data []byte) error { // Handle error if err == nil { // n != len(data) mc.cleanup() - errLog.Print(ErrMalformPkt) + mc.log(ErrMalformPkt) } else { if cerr := mc.canceled.Value(); cerr != nil { return cerr @@ -171,7 +144,7 @@ func (mc *mysqlConn) writePacket(data []byte) error { return errBadConnNoWrite } mc.cleanup() - errLog.Print(err) + mc.log(err) } return ErrInvalidConn } @@ -239,7 +212,7 @@ func (mc *mysqlConn) readHandshakePacket() (data []byte, plugin string, err erro // reserved (all [00]) [10 bytes] pos += 1 + 2 + 2 + 1 + 10 - // second part of the password cipher [mininum 13 bytes], + // second part of the password cipher [minimum 13 bytes], // where len=MAX(13, length of auth-plugin-data - 8) // // The web documentation is ambiguous about the length. However, @@ -285,6 +258,7 @@ func (mc *mysqlConn) writeHandshakeResponsePacket(authResp []byte, plugin string clientLocalFiles | clientPluginAuth | clientMultiResults | + clientConnectAttrs | mc.flags&clientLongFlag if mc.cfg.ClientFoundRows { @@ -318,11 +292,17 @@ func (mc *mysqlConn) writeHandshakeResponsePacket(authResp []byte, plugin string pktLen += n + 1 } + // encode length of the connection attributes + var connAttrsLEIBuf [9]byte + connAttrsLen := len(mc.connector.encodedAttributes) + connAttrsLEI := appendLengthEncodedInteger(connAttrsLEIBuf[:0], uint64(connAttrsLen)) + pktLen += len(connAttrsLEI) + len(mc.connector.encodedAttributes) + // Calculate packet length and get buffer with that size - data, err := mc.buf.takeSmallBuffer(pktLen + 4) + data, err := mc.buf.takeBuffer(pktLen + 4) if err != nil { // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) + mc.log(err) return errBadConnNoWrite } @@ -338,14 +318,18 @@ func (mc *mysqlConn) writeHandshakeResponsePacket(authResp []byte, plugin string data[10] = 0x00 data[11] = 0x00 - // Charset [1 byte] + // Collation ID [1 byte] + cname := mc.cfg.Collation + if cname == "" { + cname = defaultCollation + } var found bool - data[12], found = collations[mc.cfg.Collation] + data[12], found = collations[cname] if !found { // Note possibility for false negatives: // could be triggered although the collation is valid if the // collations map does not contain entries the server supports. - return errors.New("unknown collation") + return fmt.Errorf("unknown collation: %q", cname) } // Filler [23 bytes] (all 0x00) @@ -367,7 +351,6 @@ func (mc *mysqlConn) writeHandshakeResponsePacket(authResp []byte, plugin string if err := tlsConn.Handshake(); err != nil { return err } - mc.rawConn = mc.netConn mc.netConn = tlsConn mc.buf.nc = tlsConn } @@ -394,6 +377,10 @@ func (mc *mysqlConn) writeHandshakeResponsePacket(authResp []byte, plugin string data[pos] = 0x00 pos++ + // Connection Attributes + pos += copy(data[pos:], connAttrsLEI) + pos += copy(data[pos:], []byte(mc.connector.encodedAttributes)) + // Send Auth packet return mc.writePacket(data[:pos]) } @@ -404,7 +391,7 @@ func (mc *mysqlConn) writeAuthSwitchPacket(authData []byte) error { data, err := mc.buf.takeSmallBuffer(pktLen) if err != nil { // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) + mc.log(err) return errBadConnNoWrite } @@ -424,7 +411,7 @@ func (mc *mysqlConn) writeCommandPacket(command byte) error { data, err := mc.buf.takeSmallBuffer(4 + 1) if err != nil { // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) + mc.log(err) return errBadConnNoWrite } @@ -443,7 +430,7 @@ func (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) error { data, err := mc.buf.takeBuffer(pktLen + 4) if err != nil { // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) + mc.log(err) return errBadConnNoWrite } @@ -464,7 +451,7 @@ func (mc *mysqlConn) writeCommandPacketUint32(command byte, arg uint32) error { data, err := mc.buf.takeSmallBuffer(4 + 1 + 4) if err != nil { // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) + mc.log(err) return errBadConnNoWrite } @@ -495,7 +482,9 @@ func (mc *mysqlConn) readAuthResult() ([]byte, string, error) { switch data[0] { case iOK: - return nil, "", mc.handleOkPacket(data) + // resultUnchanged, since auth happens before any queries or + // commands have been executed. + return nil, "", mc.resultUnchanged().handleOkPacket(data) case iAuthMoreData: return data[1:], "", err @@ -518,9 +507,9 @@ func (mc *mysqlConn) readAuthResult() ([]byte, string, error) { } } -// Returns error if Packet is not an 'Result OK'-Packet -func (mc *mysqlConn) readResultOK() error { - data, err := mc.readPacket() +// Returns error if Packet is not a 'Result OK'-Packet +func (mc *okHandler) readResultOK() error { + data, err := mc.conn().readPacket() if err != nil { return err } @@ -528,13 +517,17 @@ func (mc *mysqlConn) readResultOK() error { if data[0] == iOK { return mc.handleOkPacket(data) } - return mc.handleErrorPacket(data) + return mc.conn().handleErrorPacket(data) } // Result Set Header Packet // http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::Resultset -func (mc *mysqlConn) readResultSetHeaderPacket() (int, error) { - data, err := mc.readPacket() +func (mc *okHandler) readResultSetHeaderPacket() (int, error) { + // handleOkPacket replaces both values; other cases leave the values unchanged. + mc.result.affectedRows = append(mc.result.affectedRows, 0) + mc.result.insertIds = append(mc.result.insertIds, 0) + + data, err := mc.conn().readPacket() if err == nil { switch data[0] { @@ -542,19 +535,16 @@ func (mc *mysqlConn) readResultSetHeaderPacket() (int, error) { return 0, mc.handleOkPacket(data) case iERR: - return 0, mc.handleErrorPacket(data) + return 0, mc.conn().handleErrorPacket(data) case iLocalInFile: return 0, mc.handleInFileRequest(string(data[1:])) } // column count - num, _, n := readLengthEncodedInteger(data) - if n-len(data) == 0 { - return int(num), nil - } - - return 0, ErrMalformPkt + num, _, _ := readLengthEncodedInteger(data) + // ignore remaining data in the packet. see #1478. + return int(num), nil } return 0, err } @@ -607,18 +597,61 @@ func readStatus(b []byte) statusFlag { return statusFlag(b[0]) | statusFlag(b[1])<<8 } +// Returns an instance of okHandler for codepaths where mysqlConn.result doesn't +// need to be cleared first (e.g. during authentication, or while additional +// resultsets are being fetched.) +func (mc *mysqlConn) resultUnchanged() *okHandler { + return (*okHandler)(mc) +} + +// okHandler represents the state of the connection when mysqlConn.result has +// been prepared for processing of OK packets. +// +// To correctly populate mysqlConn.result (updated by handleOkPacket()), all +// callpaths must either: +// +// 1. first clear it using clearResult(), or +// 2. confirm that they don't need to (by calling resultUnchanged()). +// +// Both return an instance of type *okHandler. +type okHandler mysqlConn + +// Exposes the underlying type's methods. +func (mc *okHandler) conn() *mysqlConn { + return (*mysqlConn)(mc) +} + +// clearResult clears the connection's stored affectedRows and insertIds +// fields. +// +// It returns a handler that can process OK responses. +func (mc *mysqlConn) clearResult() *okHandler { + mc.result = mysqlResult{} + return (*okHandler)(mc) +} + // Ok Packet // http://dev.mysql.com/doc/internals/en/generic-response-packets.html#packet-OK_Packet -func (mc *mysqlConn) handleOkPacket(data []byte) error { +func (mc *okHandler) handleOkPacket(data []byte) error { var n, m int + var affectedRows, insertId uint64 // 0x00 [1 byte] // Affected rows [Length Coded Binary] - mc.affectedRows, _, n = readLengthEncodedInteger(data[1:]) + affectedRows, _, n = readLengthEncodedInteger(data[1:]) // Insert id [Length Coded Binary] - mc.insertId, _, m = readLengthEncodedInteger(data[1+n:]) + insertId, _, m = readLengthEncodedInteger(data[1+n:]) + + // Update for the current statement result (only used by + // readResultSetHeaderPacket). + if len(mc.result.affectedRows) > 0 { + mc.result.affectedRows[len(mc.result.affectedRows)-1] = int64(affectedRows) + } + if len(mc.result.insertIds) > 0 { + mc.result.insertIds[len(mc.result.insertIds)-1] = int64(insertId) + } // server_status [2 bytes] mc.status = readStatus(data[1+n+m : 1+n+m+2]) @@ -769,7 +802,8 @@ func (rows *textRows) readRow(dest []driver.Value) error { for i := range dest { // Read bytes and convert to string - dest[i], isNull, n, err = readLengthEncodedString(data[pos:]) + var buf []byte + buf, isNull, n, err = readLengthEncodedString(data[pos:]) pos += n if err != nil { @@ -781,19 +815,40 @@ func (rows *textRows) readRow(dest []driver.Value) error { continue } - if !mc.parseTime { - continue - } - - // Parse time field switch rows.rs.columns[i].fieldType { case fieldTypeTimestamp, fieldTypeDateTime, fieldTypeDate, fieldTypeNewDate: - if dest[i], err = parseDateTime(dest[i].([]byte), mc.cfg.Loc); err != nil { - return err + if mc.parseTime { + dest[i], err = parseDateTime(buf, mc.cfg.Loc) + } else { + dest[i] = buf } + + case fieldTypeTiny, fieldTypeShort, fieldTypeInt24, fieldTypeYear, fieldTypeLong: + dest[i], err = strconv.ParseInt(string(buf), 10, 64) + + case fieldTypeLongLong: + if rows.rs.columns[i].flags&flagUnsigned != 0 { + dest[i], err = strconv.ParseUint(string(buf), 10, 64) + } else { + dest[i], err = strconv.ParseInt(string(buf), 10, 64) + } + + case fieldTypeFloat: + var d float64 + d, err = strconv.ParseFloat(string(buf), 32) + dest[i] = float32(d) + + case fieldTypeDouble: + dest[i], err = strconv.ParseFloat(string(buf), 64) + + default: + dest[i] = buf + } + if err != nil { + return err } } @@ -938,7 +993,7 @@ func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error { } if err != nil { // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) + mc.log(err) return errBadConnNoWrite } @@ -1116,7 +1171,7 @@ func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error { if v.IsZero() { b = append(b, "0000-00-00"...) } else { - b, err = appendDateTime(b, v.In(mc.cfg.Loc)) + b, err = appendDateTime(b, v.In(mc.cfg.Loc), mc.cfg.timeTruncate) if err != nil { return err } @@ -1137,7 +1192,7 @@ func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error { if valuesCap != cap(paramValues) { data = append(data[:pos], paramValues...) if err = mc.buf.store(data); err != nil { - errLog.Print(err) + mc.log(err) return errBadConnNoWrite } } @@ -1149,7 +1204,9 @@ func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error { return mc.writePacket(data) } -func (mc *mysqlConn) discardResults() error { +// For each remaining resultset in the stream, discards its rows and updates +// mc.affectedRows and mc.insertIds. +func (mc *okHandler) discardResults() error { for mc.status&statusMoreResultsExists != 0 { resLen, err := mc.readResultSetHeaderPacket() if err != nil { @@ -1157,11 +1214,11 @@ func (mc *mysqlConn) discardResults() error { } if resLen > 0 { // columns - if err := mc.readUntilEOF(); err != nil { + if err := mc.conn().readUntilEOF(); err != nil { return err } // rows - if err := mc.readUntilEOF(); err != nil { + if err := mc.conn().readUntilEOF(); err != nil { return err } } diff --git a/vendor/github.com/go-sql-driver/mysql/result.go b/vendor/github.com/go-sql-driver/mysql/result.go index c6438d03..d5163146 100644 --- a/vendor/github.com/go-sql-driver/mysql/result.go +++ b/vendor/github.com/go-sql-driver/mysql/result.go @@ -8,15 +8,43 @@ package mysql +import "database/sql/driver" + +// Result exposes data not available through *connection.Result. +// +// This is accessible by executing statements using sql.Conn.Raw() and +// downcasting the returned result: +// +// res, err := rawConn.Exec(...) +// res.(mysql.Result).AllRowsAffected() +type Result interface { + driver.Result + // AllRowsAffected returns a slice containing the affected rows for each + // executed statement. + AllRowsAffected() []int64 + // AllLastInsertIds returns a slice containing the last inserted ID for each + // executed statement. + AllLastInsertIds() []int64 +} + type mysqlResult struct { - affectedRows int64 - insertId int64 + // One entry in both slices is created for every executed statement result. + affectedRows []int64 + insertIds []int64 } func (res *mysqlResult) LastInsertId() (int64, error) { - return res.insertId, nil + return res.insertIds[len(res.insertIds)-1], nil } func (res *mysqlResult) RowsAffected() (int64, error) { - return res.affectedRows, nil + return res.affectedRows[len(res.affectedRows)-1], nil +} + +func (res *mysqlResult) AllLastInsertIds() []int64 { + return append([]int64{}, res.insertIds...) // defensive copy +} + +func (res *mysqlResult) AllRowsAffected() []int64 { + return append([]int64{}, res.affectedRows...) // defensive copy } diff --git a/vendor/github.com/go-sql-driver/mysql/rows.go b/vendor/github.com/go-sql-driver/mysql/rows.go index 888bdb5f..81fa6062 100644 --- a/vendor/github.com/go-sql-driver/mysql/rows.go +++ b/vendor/github.com/go-sql-driver/mysql/rows.go @@ -123,7 +123,8 @@ func (rows *mysqlRows) Close() (err error) { err = mc.readUntilEOF() } if err == nil { - if err = mc.discardResults(); err != nil { + handleOk := mc.clearResult() + if err = handleOk.discardResults(); err != nil { return err } } @@ -160,7 +161,15 @@ func (rows *mysqlRows) nextResultSet() (int, error) { return 0, io.EOF } rows.rs = resultSet{} - return rows.mc.readResultSetHeaderPacket() + // rows.mc.affectedRows and rows.mc.insertIds accumulate on each call to + // nextResultSet. + resLen, err := rows.mc.resultUnchanged().readResultSetHeaderPacket() + if err != nil { + // Clean up about multi-results flag + rows.rs.done = true + rows.mc.status = rows.mc.status & (^statusMoreResultsExists) + } + return resLen, err } func (rows *mysqlRows) nextNotEmptyResultSet() (int, error) { diff --git a/vendor/github.com/go-sql-driver/mysql/statement.go b/vendor/github.com/go-sql-driver/mysql/statement.go index 10ece8bd..0436f224 100644 --- a/vendor/github.com/go-sql-driver/mysql/statement.go +++ b/vendor/github.com/go-sql-driver/mysql/statement.go @@ -51,7 +51,7 @@ func (stmt *mysqlStmt) CheckNamedValue(nv *driver.NamedValue) (err error) { func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) { if stmt.mc.closed.Load() { - errLog.Print(ErrInvalidConn) + stmt.mc.log(ErrInvalidConn) return nil, driver.ErrBadConn } // Send command @@ -61,12 +61,10 @@ func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) { } mc := stmt.mc - - mc.affectedRows = 0 - mc.insertId = 0 + handleOk := stmt.mc.clearResult() // Read Result - resLen, err := mc.readResultSetHeaderPacket() + resLen, err := handleOk.readResultSetHeaderPacket() if err != nil { return nil, err } @@ -83,14 +81,12 @@ func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) { } } - if err := mc.discardResults(); err != nil { + if err := handleOk.discardResults(); err != nil { return nil, err } - return &mysqlResult{ - affectedRows: int64(mc.affectedRows), - insertId: int64(mc.insertId), - }, nil + copied := mc.result + return &copied, nil } func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) { @@ -99,7 +95,7 @@ func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) { func (stmt *mysqlStmt) query(args []driver.Value) (*binaryRows, error) { if stmt.mc.closed.Load() { - errLog.Print(ErrInvalidConn) + stmt.mc.log(ErrInvalidConn) return nil, driver.ErrBadConn } // Send command @@ -111,7 +107,8 @@ func (stmt *mysqlStmt) query(args []driver.Value) (*binaryRows, error) { mc := stmt.mc // Read Result - resLen, err := mc.readResultSetHeaderPacket() + handleOk := stmt.mc.clearResult() + resLen, err := handleOk.readResultSetHeaderPacket() if err != nil { return nil, err } @@ -144,7 +141,7 @@ type converter struct{} // implementation does not. This function should be kept in sync with // database/sql/driver defaultConverter.ConvertValue() except for that // deliberate difference. -func (c converter) ConvertValue(v interface{}) (driver.Value, error) { +func (c converter) ConvertValue(v any) (driver.Value, error) { if driver.IsValue(v) { return v, nil } diff --git a/vendor/github.com/go-sql-driver/mysql/utils.go b/vendor/github.com/go-sql-driver/mysql/utils.go index 15dbd8d1..cda24fe7 100644 --- a/vendor/github.com/go-sql-driver/mysql/utils.go +++ b/vendor/github.com/go-sql-driver/mysql/utils.go @@ -36,7 +36,7 @@ var ( // registering it. // // rootCertPool := x509.NewCertPool() -// pem, err := ioutil.ReadFile("/path/ca-cert.pem") +// pem, err := os.ReadFile("/path/ca-cert.pem") // if err != nil { // log.Fatal(err) // } @@ -265,7 +265,11 @@ func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Va return nil, fmt.Errorf("invalid DATETIME packet length %d", num) } -func appendDateTime(buf []byte, t time.Time) ([]byte, error) { +func appendDateTime(buf []byte, t time.Time, timeTruncate time.Duration) ([]byte, error) { + if timeTruncate > 0 { + t = t.Truncate(timeTruncate) + } + year, month, day := t.Date() hour, min, sec := t.Clock() nsec := t.Nanosecond() @@ -616,6 +620,11 @@ func appendLengthEncodedInteger(b []byte, n uint64) []byte { byte(n>>32), byte(n>>40), byte(n>>48), byte(n>>56)) } +func appendLengthEncodedString(b []byte, s string) []byte { + b = appendLengthEncodedInteger(b, uint64(len(s))) + return append(b, s...) +} + // reserveBuffer checks cap(buf) and expand buffer to len(buf) + appendSize. // If cap(buf) is not enough, reallocate new buffer. func reserveBuffer(buf []byte, appendSize int) []byte { diff --git a/vendor/github.com/go-viper/mapstructure/v2/.editorconfig b/vendor/github.com/go-viper/mapstructure/v2/.editorconfig new file mode 100644 index 00000000..1f664d13 --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/.editorconfig @@ -0,0 +1,18 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true + +[*.go] +indent_style = tab + +[{Makefile,*.mk}] +indent_style = tab + +[*.nix] +indent_size = 2 diff --git a/vendor/github.com/go-viper/mapstructure/v2/.gitignore b/vendor/github.com/go-viper/mapstructure/v2/.gitignore new file mode 100644 index 00000000..470e7ca2 --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/.gitignore @@ -0,0 +1,6 @@ +/.devenv/ +/.direnv/ +/.pre-commit-config.yaml +/bin/ +/build/ +/var/ diff --git a/vendor/github.com/go-viper/mapstructure/v2/.golangci.yaml b/vendor/github.com/go-viper/mapstructure/v2/.golangci.yaml new file mode 100644 index 00000000..763143aa --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/.golangci.yaml @@ -0,0 +1,23 @@ +run: + timeout: 5m + +linters-settings: + gci: + sections: + - standard + - default + - prefix(github.com/go-viper/mapstructure) + golint: + min-confidence: 0 + goimports: + local-prefixes: github.com/go-viper/maptstructure + +linters: + disable-all: true + enable: + - gci + - gofmt + - gofumpt + - goimports + - staticcheck + # - stylecheck diff --git a/vendor/github.com/go-viper/mapstructure/v2/CHANGELOG.md b/vendor/github.com/go-viper/mapstructure/v2/CHANGELOG.md new file mode 100644 index 00000000..afd44e5f --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/CHANGELOG.md @@ -0,0 +1,104 @@ +> [!WARNING] +> As of v2 of this library, change log can be found in GitHub releases. + +## 1.5.1 + +* Wrap errors so they're compatible with `errors.Is` and `errors.As` [GH-282] +* Fix map of slices not decoding properly in certain cases. [GH-266] + +## 1.5.0 + +* New option `IgnoreUntaggedFields` to ignore decoding to any fields + without `mapstructure` (or the configured tag name) set [GH-277] +* New option `ErrorUnset` which makes it an error if any fields + in a target struct are not set by the decoding process. [GH-225] +* New function `OrComposeDecodeHookFunc` to help compose decode hooks. [GH-240] +* Decoding to slice from array no longer crashes [GH-265] +* Decode nested struct pointers to map [GH-271] +* Fix issue where `,squash` was ignored if `Squash` option was set. [GH-280] +* Fix issue where fields with `,omitempty` would sometimes decode + into a map with an empty string key [GH-281] + +## 1.4.3 + +* Fix cases where `json.Number` didn't decode properly [GH-261] + +## 1.4.2 + +* Custom name matchers to support any sort of casing, formatting, etc. for + field names. [GH-250] +* Fix possible panic in ComposeDecodeHookFunc [GH-251] + +## 1.4.1 + +* Fix regression where `*time.Time` value would be set to empty and not be sent + to decode hooks properly [GH-232] + +## 1.4.0 + +* A new decode hook type `DecodeHookFuncValue` has been added that has + access to the full values. [GH-183] +* Squash is now supported with embedded fields that are struct pointers [GH-205] +* Empty strings will convert to 0 for all numeric types when weakly decoding [GH-206] + +## 1.3.3 + +* Decoding maps from maps creates a settable value for decode hooks [GH-203] + +## 1.3.2 + +* Decode into interface type with a struct value is supported [GH-187] + +## 1.3.1 + +* Squash should only squash embedded structs. [GH-194] + +## 1.3.0 + +* Added `",omitempty"` support. This will ignore zero values in the source + structure when encoding. [GH-145] + +## 1.2.3 + +* Fix duplicate entries in Keys list with pointer values. [GH-185] + +## 1.2.2 + +* Do not add unsettable (unexported) values to the unused metadata key + or "remain" value. [GH-150] + +## 1.2.1 + +* Go modules checksum mismatch fix + +## 1.2.0 + +* Added support to capture unused values in a field using the `",remain"` value + in the mapstructure tag. There is an example to showcase usage. +* Added `DecoderConfig` option to always squash embedded structs +* `json.Number` can decode into `uint` types +* Empty slices are preserved and not replaced with nil slices +* Fix panic that can occur in when decoding a map into a nil slice of structs +* Improved package documentation for godoc + +## 1.1.2 + +* Fix error when decode hook decodes interface implementation into interface + type. [GH-140] + +## 1.1.1 + +* Fix panic that can happen in `decodePtr` + +## 1.1.0 + +* Added `StringToIPHookFunc` to convert `string` to `net.IP` and `net.IPNet` [GH-133] +* Support struct to struct decoding [GH-137] +* If source map value is nil, then destination map value is nil (instead of empty) +* If source slice value is nil, then destination slice value is nil (instead of empty) +* If source pointer is nil, then destination pointer is set to nil (instead of + allocated zero value of type) + +## 1.0.0 + +* Initial tagged stable release. diff --git a/vendor/github.com/go-viper/mapstructure/v2/LICENSE b/vendor/github.com/go-viper/mapstructure/v2/LICENSE new file mode 100644 index 00000000..f9c841a5 --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013 Mitchell Hashimoto + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/go-viper/mapstructure/v2/README.md b/vendor/github.com/go-viper/mapstructure/v2/README.md new file mode 100644 index 00000000..dd5ec69d --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/README.md @@ -0,0 +1,80 @@ +# mapstructure + +[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/go-viper/mapstructure/ci.yaml?branch=main&style=flat-square)](https://github.com/go-viper/mapstructure/actions?query=workflow%3ACI) +[![go.dev reference](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/mod/github.com/go-viper/mapstructure/v2) +![Go Version](https://img.shields.io/badge/go%20version-%3E=1.18-61CFDD.svg?style=flat-square) + +mapstructure is a Go library for decoding generic map values to structures +and vice versa, while providing helpful error handling. + +This library is most useful when decoding values from some data stream (JSON, +Gob, etc.) where you don't _quite_ know the structure of the underlying data +until you read a part of it. You can therefore read a `map[string]interface{}` +and use this library to decode it into the proper underlying native Go +structure. + +## Installation + +```shell +go get github.com/go-viper/mapstructure/v2 +``` + +## Migrating from `github.com/mitchellh/mapstructure` + +[@mitchehllh](https://github.com/mitchellh) announced his intent to archive some of his unmaintained projects (see [here](https://gist.github.com/mitchellh/90029601268e59a29e64e55bab1c5bdc) and [here](https://github.com/mitchellh/mapstructure/issues/349)). This is a repository achieved the "blessed fork" status. + +You can migrate to this package by changing your import paths in your Go files to `github.com/go-viper/mapstructure/v2`. +The API is the same, so you don't need to change anything else. + +Here is a script that can help you with the migration: + +```shell +sed -i 's/github.com\/mitchellh\/mapstructure/github.com\/go-viper\/mapstructure\/v2/g' $(find . -type f -name '*.go') +``` + +If you need more time to migrate your code, that is absolutely fine. + +Some of the latest fixes are backported to the v1 release branch of this package, so you can use the Go modules `replace` feature until you are ready to migrate: + +```shell +replace github.com/mitchellh/mapstructure => github.com/go-viper/mapstructure v1.6.0 +``` + +## Usage & Example + +For usage and examples see the [documentation](https://pkg.go.dev/mod/github.com/go-viper/mapstructure/v2). + +The `Decode` function has examples associated with it there. + +## But Why?! + +Go offers fantastic standard libraries for decoding formats such as JSON. +The standard method is to have a struct pre-created, and populate that struct +from the bytes of the encoded format. This is great, but the problem is if +you have configuration or an encoding that changes slightly depending on +specific fields. For example, consider this JSON: + +```json +{ + "type": "person", + "name": "Mitchell" +} +``` + +Perhaps we can't populate a specific structure without first reading +the "type" field from the JSON. We could always do two passes over the +decoding of the JSON (reading the "type" first, and the rest later). +However, it is much simpler to just decode this into a `map[string]interface{}` +structure, read the "type" key, then use something like this library +to decode it into the proper structure. + +## Credits + +Mapstructure was originally created by [@mitchellh](https://github.com/mitchellh). +This is a maintained fork of the original library. + +Read more about the reasons for the fork [here](https://github.com/mitchellh/mapstructure/issues/349). + +## License + +The project is licensed under the [MIT License](LICENSE). diff --git a/vendor/github.com/go-viper/mapstructure/v2/decode_hooks.go b/vendor/github.com/go-viper/mapstructure/v2/decode_hooks.go new file mode 100644 index 00000000..2523c6ad --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/decode_hooks.go @@ -0,0 +1,609 @@ +package mapstructure + +import ( + "encoding" + "errors" + "fmt" + "net" + "net/netip" + "reflect" + "strconv" + "strings" + "time" +) + +// typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns +// it into the proper DecodeHookFunc type, such as DecodeHookFuncType. +func typedDecodeHook(h DecodeHookFunc) DecodeHookFunc { + // Create variables here so we can reference them with the reflect pkg + var f1 DecodeHookFuncType + var f2 DecodeHookFuncKind + var f3 DecodeHookFuncValue + + // Fill in the variables into this interface and the rest is done + // automatically using the reflect package. + potential := []interface{}{f1, f2, f3} + + v := reflect.ValueOf(h) + vt := v.Type() + for _, raw := range potential { + pt := reflect.ValueOf(raw).Type() + if vt.ConvertibleTo(pt) { + return v.Convert(pt).Interface() + } + } + + return nil +} + +// cachedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns +// it into a closure to be used directly +// if the type fails to convert we return a closure always erroring to keep the previous behaviour +func cachedDecodeHook(raw DecodeHookFunc) func(from reflect.Value, to reflect.Value) (interface{}, error) { + switch f := typedDecodeHook(raw).(type) { + case DecodeHookFuncType: + return func(from reflect.Value, to reflect.Value) (interface{}, error) { + return f(from.Type(), to.Type(), from.Interface()) + } + case DecodeHookFuncKind: + return func(from reflect.Value, to reflect.Value) (interface{}, error) { + return f(from.Kind(), to.Kind(), from.Interface()) + } + case DecodeHookFuncValue: + return func(from reflect.Value, to reflect.Value) (interface{}, error) { + return f(from, to) + } + default: + return func(from reflect.Value, to reflect.Value) (interface{}, error) { + return nil, errors.New("invalid decode hook signature") + } + } +} + +// DecodeHookExec executes the given decode hook. This should be used +// since it'll naturally degrade to the older backwards compatible DecodeHookFunc +// that took reflect.Kind instead of reflect.Type. +func DecodeHookExec( + raw DecodeHookFunc, + from reflect.Value, to reflect.Value, +) (interface{}, error) { + switch f := typedDecodeHook(raw).(type) { + case DecodeHookFuncType: + return f(from.Type(), to.Type(), from.Interface()) + case DecodeHookFuncKind: + return f(from.Kind(), to.Kind(), from.Interface()) + case DecodeHookFuncValue: + return f(from, to) + default: + return nil, errors.New("invalid decode hook signature") + } +} + +// ComposeDecodeHookFunc creates a single DecodeHookFunc that +// automatically composes multiple DecodeHookFuncs. +// +// The composed funcs are called in order, with the result of the +// previous transformation. +func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { + cached := make([]func(from reflect.Value, to reflect.Value) (interface{}, error), 0, len(fs)) + for _, f := range fs { + cached = append(cached, cachedDecodeHook(f)) + } + return func(f reflect.Value, t reflect.Value) (interface{}, error) { + var err error + data := f.Interface() + + newFrom := f + for _, c := range cached { + data, err = c(newFrom, t) + if err != nil { + return nil, err + } + newFrom = reflect.ValueOf(data) + } + + return data, nil + } +} + +// OrComposeDecodeHookFunc executes all input hook functions until one of them returns no error. In that case its value is returned. +// If all hooks return an error, OrComposeDecodeHookFunc returns an error concatenating all error messages. +func OrComposeDecodeHookFunc(ff ...DecodeHookFunc) DecodeHookFunc { + cached := make([]func(from reflect.Value, to reflect.Value) (interface{}, error), 0, len(ff)) + for _, f := range ff { + cached = append(cached, cachedDecodeHook(f)) + } + return func(a, b reflect.Value) (interface{}, error) { + var allErrs string + var out interface{} + var err error + + for _, c := range cached { + out, err = c(a, b) + if err != nil { + allErrs += err.Error() + "\n" + continue + } + + return out, nil + } + + return nil, errors.New(allErrs) + } +} + +// StringToSliceHookFunc returns a DecodeHookFunc that converts +// string to []string by splitting on the given sep. +func StringToSliceHookFunc(sep string) DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.SliceOf(f) { + return data, nil + } + + raw := data.(string) + if raw == "" { + return []string{}, nil + } + + return strings.Split(raw, sep), nil + } +} + +// StringToTimeDurationHookFunc returns a DecodeHookFunc that converts +// strings to time.Duration. +func StringToTimeDurationHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(time.Duration(5)) { + return data, nil + } + + // Convert it by parsing + return time.ParseDuration(data.(string)) + } +} + +// StringToIPHookFunc returns a DecodeHookFunc that converts +// strings to net.IP +func StringToIPHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(net.IP{}) { + return data, nil + } + + // Convert it by parsing + ip := net.ParseIP(data.(string)) + if ip == nil { + return net.IP{}, fmt.Errorf("failed parsing ip %v", data) + } + + return ip, nil + } +} + +// StringToIPNetHookFunc returns a DecodeHookFunc that converts +// strings to net.IPNet +func StringToIPNetHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(net.IPNet{}) { + return data, nil + } + + // Convert it by parsing + _, net, err := net.ParseCIDR(data.(string)) + return net, err + } +} + +// StringToTimeHookFunc returns a DecodeHookFunc that converts +// strings to time.Time. +func StringToTimeHookFunc(layout string) DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(time.Time{}) { + return data, nil + } + + // Convert it by parsing + return time.Parse(layout, data.(string)) + } +} + +// WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to +// the decoder. +// +// Note that this is significantly different from the WeaklyTypedInput option +// of the DecoderConfig. +func WeaklyTypedHook( + f reflect.Kind, + t reflect.Kind, + data interface{}, +) (interface{}, error) { + dataVal := reflect.ValueOf(data) + switch t { + case reflect.String: + switch f { + case reflect.Bool: + if dataVal.Bool() { + return "1", nil + } + return "0", nil + case reflect.Float32: + return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil + case reflect.Int: + return strconv.FormatInt(dataVal.Int(), 10), nil + case reflect.Slice: + dataType := dataVal.Type() + elemKind := dataType.Elem().Kind() + if elemKind == reflect.Uint8 { + return string(dataVal.Interface().([]uint8)), nil + } + case reflect.Uint: + return strconv.FormatUint(dataVal.Uint(), 10), nil + } + } + + return data, nil +} + +func RecursiveStructToMapHookFunc() DecodeHookFunc { + return func(f reflect.Value, t reflect.Value) (interface{}, error) { + if f.Kind() != reflect.Struct { + return f.Interface(), nil + } + + var i interface{} = struct{}{} + if t.Type() != reflect.TypeOf(&i).Elem() { + return f.Interface(), nil + } + + m := make(map[string]interface{}) + t.Set(reflect.ValueOf(m)) + + return f.Interface(), nil + } +} + +// TextUnmarshallerHookFunc returns a DecodeHookFunc that applies +// strings to the UnmarshalText function, when the target type +// implements the encoding.TextUnmarshaler interface +func TextUnmarshallerHookFunc() DecodeHookFuncType { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + result := reflect.New(t).Interface() + unmarshaller, ok := result.(encoding.TextUnmarshaler) + if !ok { + return data, nil + } + str, ok := data.(string) + if !ok { + str = reflect.Indirect(reflect.ValueOf(&data)).Elem().String() + } + if err := unmarshaller.UnmarshalText([]byte(str)); err != nil { + return nil, err + } + return result, nil + } +} + +// StringToNetIPAddrHookFunc returns a DecodeHookFunc that converts +// strings to netip.Addr. +func StringToNetIPAddrHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(netip.Addr{}) { + return data, nil + } + + // Convert it by parsing + return netip.ParseAddr(data.(string)) + } +} + +// StringToNetIPAddrPortHookFunc returns a DecodeHookFunc that converts +// strings to netip.AddrPort. +func StringToNetIPAddrPortHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(netip.AddrPort{}) { + return data, nil + } + + // Convert it by parsing + return netip.ParseAddrPort(data.(string)) + } +} + +// StringToBasicTypeHookFunc returns a DecodeHookFunc that converts +// strings to basic types. +// int8, uint8, int16, uint16, int32, uint32, int64, uint64, int, uint, float32, float64, bool, byte, rune, complex64, complex128 +func StringToBasicTypeHookFunc() DecodeHookFunc { + return ComposeDecodeHookFunc( + StringToInt8HookFunc(), + StringToUint8HookFunc(), + StringToInt16HookFunc(), + StringToUint16HookFunc(), + StringToInt32HookFunc(), + StringToUint32HookFunc(), + StringToInt64HookFunc(), + StringToUint64HookFunc(), + StringToIntHookFunc(), + StringToUintHookFunc(), + StringToFloat32HookFunc(), + StringToFloat64HookFunc(), + StringToBoolHookFunc(), + // byte and rune are aliases for uint8 and int32 respectively + // StringToByteHookFunc(), + // StringToRuneHookFunc(), + StringToComplex64HookFunc(), + StringToComplex128HookFunc(), + ) +} + +// StringToInt8HookFunc returns a DecodeHookFunc that converts +// strings to int8. +func StringToInt8HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Int8 { + return data, nil + } + + // Convert it by parsing + i64, err := strconv.ParseInt(data.(string), 0, 8) + return int8(i64), err + } +} + +// StringToUint8HookFunc returns a DecodeHookFunc that converts +// strings to uint8. +func StringToUint8HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Uint8 { + return data, nil + } + + // Convert it by parsing + u64, err := strconv.ParseUint(data.(string), 0, 8) + return uint8(u64), err + } +} + +// StringToInt16HookFunc returns a DecodeHookFunc that converts +// strings to int16. +func StringToInt16HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Int16 { + return data, nil + } + + // Convert it by parsing + i64, err := strconv.ParseInt(data.(string), 0, 16) + return int16(i64), err + } +} + +// StringToUint16HookFunc returns a DecodeHookFunc that converts +// strings to uint16. +func StringToUint16HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Uint16 { + return data, nil + } + + // Convert it by parsing + u64, err := strconv.ParseUint(data.(string), 0, 16) + return uint16(u64), err + } +} + +// StringToInt32HookFunc returns a DecodeHookFunc that converts +// strings to int32. +func StringToInt32HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Int32 { + return data, nil + } + + // Convert it by parsing + i64, err := strconv.ParseInt(data.(string), 0, 32) + return int32(i64), err + } +} + +// StringToUint32HookFunc returns a DecodeHookFunc that converts +// strings to uint32. +func StringToUint32HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Uint32 { + return data, nil + } + + // Convert it by parsing + u64, err := strconv.ParseUint(data.(string), 0, 32) + return uint32(u64), err + } +} + +// StringToInt64HookFunc returns a DecodeHookFunc that converts +// strings to int64. +func StringToInt64HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Int64 { + return data, nil + } + + // Convert it by parsing + return strconv.ParseInt(data.(string), 0, 64) + } +} + +// StringToUint64HookFunc returns a DecodeHookFunc that converts +// strings to uint64. +func StringToUint64HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Uint64 { + return data, nil + } + + // Convert it by parsing + return strconv.ParseUint(data.(string), 0, 64) + } +} + +// StringToIntHookFunc returns a DecodeHookFunc that converts +// strings to int. +func StringToIntHookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Int { + return data, nil + } + + // Convert it by parsing + i64, err := strconv.ParseInt(data.(string), 0, 0) + return int(i64), err + } +} + +// StringToUintHookFunc returns a DecodeHookFunc that converts +// strings to uint. +func StringToUintHookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Uint { + return data, nil + } + + // Convert it by parsing + u64, err := strconv.ParseUint(data.(string), 0, 0) + return uint(u64), err + } +} + +// StringToFloat32HookFunc returns a DecodeHookFunc that converts +// strings to float32. +func StringToFloat32HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Float32 { + return data, nil + } + + // Convert it by parsing + f64, err := strconv.ParseFloat(data.(string), 32) + return float32(f64), err + } +} + +// StringToFloat64HookFunc returns a DecodeHookFunc that converts +// strings to float64. +func StringToFloat64HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Float64 { + return data, nil + } + + // Convert it by parsing + return strconv.ParseFloat(data.(string), 64) + } +} + +// StringToBoolHookFunc returns a DecodeHookFunc that converts +// strings to bool. +func StringToBoolHookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Bool { + return data, nil + } + + // Convert it by parsing + return strconv.ParseBool(data.(string)) + } +} + +// StringToByteHookFunc returns a DecodeHookFunc that converts +// strings to byte. +func StringToByteHookFunc() DecodeHookFunc { + return StringToUint8HookFunc() +} + +// StringToRuneHookFunc returns a DecodeHookFunc that converts +// strings to rune. +func StringToRuneHookFunc() DecodeHookFunc { + return StringToInt32HookFunc() +} + +// StringToComplex64HookFunc returns a DecodeHookFunc that converts +// strings to complex64. +func StringToComplex64HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Complex64 { + return data, nil + } + + // Convert it by parsing + c128, err := strconv.ParseComplex(data.(string), 64) + return complex64(c128), err + } +} + +// StringToComplex128HookFunc returns a DecodeHookFunc that converts +// strings to complex128. +func StringToComplex128HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Complex128 { + return data, nil + } + + // Convert it by parsing + return strconv.ParseComplex(data.(string), 128) + } +} diff --git a/vendor/github.com/go-viper/mapstructure/v2/flake.lock b/vendor/github.com/go-viper/mapstructure/v2/flake.lock new file mode 100644 index 00000000..4bea8154 --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/flake.lock @@ -0,0 +1,472 @@ +{ + "nodes": { + "cachix": { + "inputs": { + "devenv": "devenv_2", + "flake-compat": [ + "devenv", + "flake-compat" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ], + "pre-commit-hooks": [ + "devenv", + "pre-commit-hooks" + ] + }, + "locked": { + "lastModified": 1712055811, + "narHash": "sha256-7FcfMm5A/f02yyzuavJe06zLa9hcMHsagE28ADcmQvk=", + "owner": "cachix", + "repo": "cachix", + "rev": "02e38da89851ec7fec3356a5c04bc8349cae0e30", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "cachix", + "type": "github" + } + }, + "devenv": { + "inputs": { + "cachix": "cachix", + "flake-compat": "flake-compat_2", + "nix": "nix_2", + "nixpkgs": "nixpkgs_2", + "pre-commit-hooks": "pre-commit-hooks" + }, + "locked": { + "lastModified": 1717245169, + "narHash": "sha256-+mW3rTBjGU8p1THJN0lX/Dd/8FbnF+3dB+mJuSaxewE=", + "owner": "cachix", + "repo": "devenv", + "rev": "c3f9f053c077c6f88a3de5276d9178c62baa3fc3", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "devenv", + "type": "github" + } + }, + "devenv_2": { + "inputs": { + "flake-compat": [ + "devenv", + "cachix", + "flake-compat" + ], + "nix": "nix", + "nixpkgs": "nixpkgs", + "poetry2nix": "poetry2nix", + "pre-commit-hooks": [ + "devenv", + "cachix", + "pre-commit-hooks" + ] + }, + "locked": { + "lastModified": 1708704632, + "narHash": "sha256-w+dOIW60FKMaHI1q5714CSibk99JfYxm0CzTinYWr+Q=", + "owner": "cachix", + "repo": "devenv", + "rev": "2ee4450b0f4b95a1b90f2eb5ffea98b90e48c196", + "type": "github" + }, + "original": { + "owner": "cachix", + "ref": "python-rewrite", + "repo": "devenv", + "type": "github" + } + }, + "flake-compat": { + "flake": false, + "locked": { + "lastModified": 1673956053, + "narHash": "sha256-4gtG9iQuiKITOjNQQeQIpoIB6b16fm+504Ch3sNKLd8=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "35bb57c0c8d8b62bbfd284272c928ceb64ddbde9", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-compat_2": { + "flake": false, + "locked": { + "lastModified": 1696426674, + "narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "0f9255e01c2351cc7d116c072cb317785dd33b33", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-parts": { + "inputs": { + "nixpkgs-lib": "nixpkgs-lib" + }, + "locked": { + "lastModified": 1717285511, + "narHash": "sha256-iKzJcpdXih14qYVcZ9QC9XuZYnPc6T8YImb6dX166kw=", + "owner": "hercules-ci", + "repo": "flake-parts", + "rev": "2a55567fcf15b1b1c7ed712a2c6fadaec7412ea8", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "flake-parts", + "type": "github" + } + }, + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1689068808, + "narHash": "sha256-6ixXo3wt24N/melDWjq70UuHQLxGV8jZvooRanIHXw0=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "919d646de7be200f3bf08cb76ae1f09402b6f9b4", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_2": { + "inputs": { + "systems": "systems_2" + }, + "locked": { + "lastModified": 1710146030, + "narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "gitignore": { + "inputs": { + "nixpkgs": [ + "devenv", + "pre-commit-hooks", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1709087332, + "narHash": "sha256-HG2cCnktfHsKV0s4XW83gU3F57gaTljL9KNSuG6bnQs=", + "owner": "hercules-ci", + "repo": "gitignore.nix", + "rev": "637db329424fd7e46cf4185293b9cc8c88c95394", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "gitignore.nix", + "type": "github" + } + }, + "nix": { + "inputs": { + "flake-compat": "flake-compat", + "nixpkgs": [ + "devenv", + "cachix", + "devenv", + "nixpkgs" + ], + "nixpkgs-regression": "nixpkgs-regression" + }, + "locked": { + "lastModified": 1712911606, + "narHash": "sha256-BGvBhepCufsjcUkXnEEXhEVjwdJAwPglCC2+bInc794=", + "owner": "domenkozar", + "repo": "nix", + "rev": "b24a9318ea3f3600c1e24b4a00691ee912d4de12", + "type": "github" + }, + "original": { + "owner": "domenkozar", + "ref": "devenv-2.21", + "repo": "nix", + "type": "github" + } + }, + "nix-github-actions": { + "inputs": { + "nixpkgs": [ + "devenv", + "cachix", + "devenv", + "poetry2nix", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1688870561, + "narHash": "sha256-4UYkifnPEw1nAzqqPOTL2MvWtm3sNGw1UTYTalkTcGY=", + "owner": "nix-community", + "repo": "nix-github-actions", + "rev": "165b1650b753316aa7f1787f3005a8d2da0f5301", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nix-github-actions", + "type": "github" + } + }, + "nix_2": { + "inputs": { + "flake-compat": [ + "devenv", + "flake-compat" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ], + "nixpkgs-regression": "nixpkgs-regression_2" + }, + "locked": { + "lastModified": 1712911606, + "narHash": "sha256-BGvBhepCufsjcUkXnEEXhEVjwdJAwPglCC2+bInc794=", + "owner": "domenkozar", + "repo": "nix", + "rev": "b24a9318ea3f3600c1e24b4a00691ee912d4de12", + "type": "github" + }, + "original": { + "owner": "domenkozar", + "ref": "devenv-2.21", + "repo": "nix", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1692808169, + "narHash": "sha256-x9Opq06rIiwdwGeK2Ykj69dNc2IvUH1fY55Wm7atwrE=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "9201b5ff357e781bf014d0330d18555695df7ba8", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs-lib": { + "locked": { + "lastModified": 1717284937, + "narHash": "sha256-lIbdfCsf8LMFloheeE6N31+BMIeixqyQWbSr2vk79EQ=", + "type": "tarball", + "url": "https://github.com/NixOS/nixpkgs/archive/eb9ceca17df2ea50a250b6b27f7bf6ab0186f198.tar.gz" + }, + "original": { + "type": "tarball", + "url": "https://github.com/NixOS/nixpkgs/archive/eb9ceca17df2ea50a250b6b27f7bf6ab0186f198.tar.gz" + } + }, + "nixpkgs-regression": { + "locked": { + "lastModified": 1643052045, + "narHash": "sha256-uGJ0VXIhWKGXxkeNnq4TvV3CIOkUJ3PAoLZ3HMzNVMw=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2", + "type": "github" + }, + "original": { + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2", + "type": "github" + } + }, + "nixpkgs-regression_2": { + "locked": { + "lastModified": 1643052045, + "narHash": "sha256-uGJ0VXIhWKGXxkeNnq4TvV3CIOkUJ3PAoLZ3HMzNVMw=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2", + "type": "github" + }, + "original": { + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2", + "type": "github" + } + }, + "nixpkgs-stable": { + "locked": { + "lastModified": 1710695816, + "narHash": "sha256-3Eh7fhEID17pv9ZxrPwCLfqXnYP006RKzSs0JptsN84=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "614b4613980a522ba49f0d194531beddbb7220d3", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-23.11", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs_2": { + "locked": { + "lastModified": 1713361204, + "narHash": "sha256-TA6EDunWTkc5FvDCqU3W2T3SFn0gRZqh6D/hJnM02MM=", + "owner": "cachix", + "repo": "devenv-nixpkgs", + "rev": "285676e87ad9f0ca23d8714a6ab61e7e027020c6", + "type": "github" + }, + "original": { + "owner": "cachix", + "ref": "rolling", + "repo": "devenv-nixpkgs", + "type": "github" + } + }, + "nixpkgs_3": { + "locked": { + "lastModified": 1717112898, + "narHash": "sha256-7R2ZvOnvd9h8fDd65p0JnB7wXfUvreox3xFdYWd1BnY=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "6132b0f6e344ce2fe34fc051b72fb46e34f668e0", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "poetry2nix": { + "inputs": { + "flake-utils": "flake-utils", + "nix-github-actions": "nix-github-actions", + "nixpkgs": [ + "devenv", + "cachix", + "devenv", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1692876271, + "narHash": "sha256-IXfZEkI0Mal5y1jr6IRWMqK8GW2/f28xJenZIPQqkY0=", + "owner": "nix-community", + "repo": "poetry2nix", + "rev": "d5006be9c2c2417dafb2e2e5034d83fabd207ee3", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "poetry2nix", + "type": "github" + } + }, + "pre-commit-hooks": { + "inputs": { + "flake-compat": [ + "devenv", + "flake-compat" + ], + "flake-utils": "flake-utils_2", + "gitignore": "gitignore", + "nixpkgs": [ + "devenv", + "nixpkgs" + ], + "nixpkgs-stable": "nixpkgs-stable" + }, + "locked": { + "lastModified": 1713775815, + "narHash": "sha256-Wu9cdYTnGQQwtT20QQMg7jzkANKQjwBD9iccfGKkfls=", + "owner": "cachix", + "repo": "pre-commit-hooks.nix", + "rev": "2ac4dcbf55ed43f3be0bae15e181f08a57af24a4", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "pre-commit-hooks.nix", + "type": "github" + } + }, + "root": { + "inputs": { + "devenv": "devenv", + "flake-parts": "flake-parts", + "nixpkgs": "nixpkgs_3" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + }, + "systems_2": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/vendor/github.com/go-viper/mapstructure/v2/flake.nix b/vendor/github.com/go-viper/mapstructure/v2/flake.nix new file mode 100644 index 00000000..4ed0f533 --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/flake.nix @@ -0,0 +1,39 @@ +{ + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; + flake-parts.url = "github:hercules-ci/flake-parts"; + devenv.url = "github:cachix/devenv"; + }; + + outputs = inputs@{ flake-parts, ... }: + flake-parts.lib.mkFlake { inherit inputs; } { + imports = [ + inputs.devenv.flakeModule + ]; + + systems = [ "x86_64-linux" "x86_64-darwin" "aarch64-darwin" ]; + + perSystem = { config, self', inputs', pkgs, system, ... }: rec { + devenv.shells = { + default = { + languages = { + go.enable = true; + }; + + pre-commit.hooks = { + nixpkgs-fmt.enable = true; + }; + + packages = with pkgs; [ + golangci-lint + ]; + + # https://github.com/cachix/devenv/issues/528#issuecomment-1556108767 + containers = pkgs.lib.mkForce { }; + }; + + ci = devenv.shells.default; + }; + }; + }; +} diff --git a/vendor/github.com/go-viper/mapstructure/v2/internal/errors/errors.go b/vendor/github.com/go-viper/mapstructure/v2/internal/errors/errors.go new file mode 100644 index 00000000..d1c15e47 --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/internal/errors/errors.go @@ -0,0 +1,11 @@ +package errors + +import "errors" + +func New(text string) error { + return errors.New(text) +} + +func As(err error, target interface{}) bool { + return errors.As(err, target) +} diff --git a/vendor/github.com/go-viper/mapstructure/v2/internal/errors/join.go b/vendor/github.com/go-viper/mapstructure/v2/internal/errors/join.go new file mode 100644 index 00000000..d74e3a0b --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/internal/errors/join.go @@ -0,0 +1,9 @@ +//go:build go1.20 + +package errors + +import "errors" + +func Join(errs ...error) error { + return errors.Join(errs...) +} diff --git a/vendor/github.com/go-viper/mapstructure/v2/internal/errors/join_go1_19.go b/vendor/github.com/go-viper/mapstructure/v2/internal/errors/join_go1_19.go new file mode 100644 index 00000000..700b4022 --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/internal/errors/join_go1_19.go @@ -0,0 +1,61 @@ +//go:build !go1.20 + +// Copyright 2022 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 errors + +// Join returns an error that wraps the given errors. +// Any nil error values are discarded. +// Join returns nil if every value in errs is nil. +// The error formats as the concatenation of the strings obtained +// by calling the Error method of each element of errs, with a newline +// between each string. +// +// A non-nil error returned by Join implements the Unwrap() []error method. +func Join(errs ...error) error { + n := 0 + for _, err := range errs { + if err != nil { + n++ + } + } + if n == 0 { + return nil + } + e := &joinError{ + errs: make([]error, 0, n), + } + for _, err := range errs { + if err != nil { + e.errs = append(e.errs, err) + } + } + return e +} + +type joinError struct { + errs []error +} + +func (e *joinError) Error() string { + // Since Join returns nil if every value in errs is nil, + // e.errs cannot be empty. + if len(e.errs) == 1 { + return e.errs[0].Error() + } + + b := []byte(e.errs[0].Error()) + for _, err := range e.errs[1:] { + b = append(b, '\n') + b = append(b, err.Error()...) + } + // At this point, b has at least one byte '\n'. + // return unsafe.String(&b[0], len(b)) + return string(b) +} + +func (e *joinError) Unwrap() []error { + return e.errs +} diff --git a/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go b/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go new file mode 100644 index 00000000..1cd6204b --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go @@ -0,0 +1,1593 @@ +// Package mapstructure exposes functionality to convert one arbitrary +// Go type into another, typically to convert a map[string]interface{} +// into a native Go structure. +// +// The Go structure can be arbitrarily complex, containing slices, +// other structs, etc. and the decoder will properly decode nested +// maps and so on into the proper structures in the native Go struct. +// See the examples to see what the decoder is capable of. +// +// The simplest function to start with is Decode. +// +// # Field Tags +// +// When decoding to a struct, mapstructure will use the field name by +// default to perform the mapping. For example, if a struct has a field +// "Username" then mapstructure will look for a key in the source value +// of "username" (case insensitive). +// +// type User struct { +// Username string +// } +// +// You can change the behavior of mapstructure by using struct tags. +// The default struct tag that mapstructure looks for is "mapstructure" +// but you can customize it using DecoderConfig. +// +// # Renaming Fields +// +// To rename the key that mapstructure looks for, use the "mapstructure" +// tag and set a value directly. For example, to change the "username" example +// above to "user": +// +// type User struct { +// Username string `mapstructure:"user"` +// } +// +// # Embedded Structs and Squashing +// +// Embedded structs are treated as if they're another field with that name. +// By default, the two structs below are equivalent when decoding with +// mapstructure: +// +// type Person struct { +// Name string +// } +// +// type Friend struct { +// Person +// } +// +// type Friend struct { +// Person Person +// } +// +// This would require an input that looks like below: +// +// map[string]interface{}{ +// "person": map[string]interface{}{"name": "alice"}, +// } +// +// If your "person" value is NOT nested, then you can append ",squash" to +// your tag value and mapstructure will treat it as if the embedded struct +// were part of the struct directly. Example: +// +// type Friend struct { +// Person `mapstructure:",squash"` +// } +// +// Now the following input would be accepted: +// +// map[string]interface{}{ +// "name": "alice", +// } +// +// When decoding from a struct to a map, the squash tag squashes the struct +// fields into a single map. Using the example structs from above: +// +// Friend{Person: Person{Name: "alice"}} +// +// Will be decoded into a map: +// +// map[string]interface{}{ +// "name": "alice", +// } +// +// DecoderConfig has a field that changes the behavior of mapstructure +// to always squash embedded structs. +// +// # Remainder Values +// +// If there are any unmapped keys in the source value, mapstructure by +// default will silently ignore them. You can error by setting ErrorUnused +// in DecoderConfig. If you're using Metadata you can also maintain a slice +// of the unused keys. +// +// You can also use the ",remain" suffix on your tag to collect all unused +// values in a map. The field with this tag MUST be a map type and should +// probably be a "map[string]interface{}" or "map[interface{}]interface{}". +// See example below: +// +// type Friend struct { +// Name string +// Other map[string]interface{} `mapstructure:",remain"` +// } +// +// Given the input below, Other would be populated with the other +// values that weren't used (everything but "name"): +// +// map[string]interface{}{ +// "name": "bob", +// "address": "123 Maple St.", +// } +// +// # Omit Empty Values +// +// When decoding from a struct to any other value, you may use the +// ",omitempty" suffix on your tag to omit that value if it equates to +// the zero value. The zero value of all types is specified in the Go +// specification. +// +// For example, the zero type of a numeric type is zero ("0"). If the struct +// field value is zero and a numeric type, the field is empty, and it won't +// be encoded into the destination type. +// +// type Source struct { +// Age int `mapstructure:",omitempty"` +// } +// +// # Unexported fields +// +// Since unexported (private) struct fields cannot be set outside the package +// where they are defined, the decoder will simply skip them. +// +// For this output type definition: +// +// type Exported struct { +// private string // this unexported field will be skipped +// Public string +// } +// +// Using this map as input: +// +// map[string]interface{}{ +// "private": "I will be ignored", +// "Public": "I made it through!", +// } +// +// The following struct will be decoded: +// +// type Exported struct { +// private: "" // field is left with an empty string (zero value) +// Public: "I made it through!" +// } +// +// # Other Configuration +// +// mapstructure is highly configurable. See the DecoderConfig struct +// for other features and options that are supported. +package mapstructure + +import ( + "encoding/json" + "fmt" + "reflect" + "sort" + "strconv" + "strings" + + "github.com/go-viper/mapstructure/v2/internal/errors" +) + +// DecodeHookFunc is the callback function that can be used for +// data transformations. See "DecodeHook" in the DecoderConfig +// struct. +// +// The type must be one of DecodeHookFuncType, DecodeHookFuncKind, or +// DecodeHookFuncValue. +// Values are a superset of Types (Values can return types), and Types are a +// superset of Kinds (Types can return Kinds) and are generally a richer thing +// to use, but Kinds are simpler if you only need those. +// +// The reason DecodeHookFunc is multi-typed is for backwards compatibility: +// we started with Kinds and then realized Types were the better solution, +// but have a promise to not break backwards compat so we now support +// both. +type DecodeHookFunc interface{} + +// DecodeHookFuncType is a DecodeHookFunc which has complete information about +// the source and target types. +type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error) + +// DecodeHookFuncKind is a DecodeHookFunc which knows only the Kinds of the +// source and target types. +type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) + +// DecodeHookFuncValue is a DecodeHookFunc which has complete access to both the source and target +// values. +type DecodeHookFuncValue func(from reflect.Value, to reflect.Value) (interface{}, error) + +// DecoderConfig is the configuration that is used to create a new decoder +// and allows customization of various aspects of decoding. +type DecoderConfig struct { + // DecodeHook, if set, will be called before any decoding and any + // type conversion (if WeaklyTypedInput is on). This lets you modify + // the values before they're set down onto the resulting struct. The + // DecodeHook is called for every map and value in the input. This means + // that if a struct has embedded fields with squash tags the decode hook + // is called only once with all of the input data, not once for each + // embedded struct. + // + // If an error is returned, the entire decode will fail with that error. + DecodeHook DecodeHookFunc + + // If ErrorUnused is true, then it is an error for there to exist + // keys in the original map that were unused in the decoding process + // (extra keys). + ErrorUnused bool + + // If ErrorUnset is true, then it is an error for there to exist + // fields in the result that were not set in the decoding process + // (extra fields). This only applies to decoding to a struct. This + // will affect all nested structs as well. + ErrorUnset bool + + // ZeroFields, if set to true, will zero fields before writing them. + // For example, a map will be emptied before decoded values are put in + // it. If this is false, a map will be merged. + ZeroFields bool + + // If WeaklyTypedInput is true, the decoder will make the following + // "weak" conversions: + // + // - bools to string (true = "1", false = "0") + // - numbers to string (base 10) + // - bools to int/uint (true = 1, false = 0) + // - strings to int/uint (base implied by prefix) + // - int to bool (true if value != 0) + // - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F, + // FALSE, false, False. Anything else is an error) + // - empty array = empty map and vice versa + // - negative numbers to overflowed uint values (base 10) + // - slice of maps to a merged map + // - single values are converted to slices if required. Each + // element is weakly decoded. For example: "4" can become []int{4} + // if the target type is an int slice. + // + WeaklyTypedInput bool + + // Squash will squash embedded structs. A squash tag may also be + // added to an individual struct field using a tag. For example: + // + // type Parent struct { + // Child `mapstructure:",squash"` + // } + Squash bool + + // Metadata is the struct that will contain extra metadata about + // the decoding. If this is nil, then no metadata will be tracked. + Metadata *Metadata + + // Result is a pointer to the struct that will contain the decoded + // value. + Result interface{} + + // The tag name that mapstructure reads for field names. This + // defaults to "mapstructure" + TagName string + + // The option of the value in the tag that indicates a field should + // be squashed. This defaults to "squash". + SquashTagOption string + + // IgnoreUntaggedFields ignores all struct fields without explicit + // TagName, comparable to `mapstructure:"-"` as default behaviour. + IgnoreUntaggedFields bool + + // MatchName is the function used to match the map key to the struct + // field name or tag. Defaults to `strings.EqualFold`. This can be used + // to implement case-sensitive tag values, support snake casing, etc. + MatchName func(mapKey, fieldName string) bool +} + +// A Decoder takes a raw interface value and turns it into structured +// data, keeping track of rich error information along the way in case +// anything goes wrong. Unlike the basic top-level Decode method, you can +// more finely control how the Decoder behaves using the DecoderConfig +// structure. The top-level Decode method is just a convenience that sets +// up the most basic Decoder. +type Decoder struct { + config *DecoderConfig + cachedDecodeHook func(from reflect.Value, to reflect.Value) (interface{}, error) +} + +// Metadata contains information about decoding a structure that +// is tedious or difficult to get otherwise. +type Metadata struct { + // Keys are the keys of the structure which were successfully decoded + Keys []string + + // Unused is a slice of keys that were found in the raw value but + // weren't decoded since there was no matching field in the result interface + Unused []string + + // Unset is a slice of field names that were found in the result interface + // but weren't set in the decoding process since there was no matching value + // in the input + Unset []string +} + +// Decode takes an input structure and uses reflection to translate it to +// the output structure. output must be a pointer to a map or struct. +func Decode(input interface{}, output interface{}) error { + config := &DecoderConfig{ + Metadata: nil, + Result: output, + } + + decoder, err := NewDecoder(config) + if err != nil { + return err + } + + return decoder.Decode(input) +} + +// WeakDecode is the same as Decode but is shorthand to enable +// WeaklyTypedInput. See DecoderConfig for more info. +func WeakDecode(input, output interface{}) error { + config := &DecoderConfig{ + Metadata: nil, + Result: output, + WeaklyTypedInput: true, + } + + decoder, err := NewDecoder(config) + if err != nil { + return err + } + + return decoder.Decode(input) +} + +// DecodeMetadata is the same as Decode, but is shorthand to +// enable metadata collection. See DecoderConfig for more info. +func DecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { + config := &DecoderConfig{ + Metadata: metadata, + Result: output, + } + + decoder, err := NewDecoder(config) + if err != nil { + return err + } + + return decoder.Decode(input) +} + +// WeakDecodeMetadata is the same as Decode, but is shorthand to +// enable both WeaklyTypedInput and metadata collection. See +// DecoderConfig for more info. +func WeakDecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { + config := &DecoderConfig{ + Metadata: metadata, + Result: output, + WeaklyTypedInput: true, + } + + decoder, err := NewDecoder(config) + if err != nil { + return err + } + + return decoder.Decode(input) +} + +// NewDecoder returns a new decoder for the given configuration. Once +// a decoder has been returned, the same configuration must not be used +// again. +func NewDecoder(config *DecoderConfig) (*Decoder, error) { + val := reflect.ValueOf(config.Result) + if val.Kind() != reflect.Ptr { + return nil, errors.New("result must be a pointer") + } + + val = val.Elem() + if !val.CanAddr() { + return nil, errors.New("result must be addressable (a pointer)") + } + + if config.Metadata != nil { + if config.Metadata.Keys == nil { + config.Metadata.Keys = make([]string, 0) + } + + if config.Metadata.Unused == nil { + config.Metadata.Unused = make([]string, 0) + } + + if config.Metadata.Unset == nil { + config.Metadata.Unset = make([]string, 0) + } + } + + if config.TagName == "" { + config.TagName = "mapstructure" + } + + if config.SquashTagOption == "" { + config.SquashTagOption = "squash" + } + + if config.MatchName == nil { + config.MatchName = strings.EqualFold + } + + result := &Decoder{ + config: config, + } + if config.DecodeHook != nil { + result.cachedDecodeHook = cachedDecodeHook(config.DecodeHook) + } + + return result, nil +} + +// Decode decodes the given raw interface to the target pointer specified +// by the configuration. +func (d *Decoder) Decode(input interface{}) error { + err := d.decode("", input, reflect.ValueOf(d.config.Result).Elem()) + + // Retain some of the original behavior when multiple errors ocurr + var joinedErr interface{ Unwrap() []error } + if errors.As(err, &joinedErr) { + return fmt.Errorf("decoding failed due to the following error(s):\n\n%w", err) + } + + return err +} + +// Decodes an unknown data type into a specific reflection value. +func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) error { + var inputVal reflect.Value + if input != nil { + inputVal = reflect.ValueOf(input) + + // We need to check here if input is a typed nil. Typed nils won't + // match the "input == nil" below so we check that here. + if inputVal.Kind() == reflect.Ptr && inputVal.IsNil() { + input = nil + } + } + + if input == nil { + // If the data is nil, then we don't set anything, unless ZeroFields is set + // to true. + if d.config.ZeroFields { + outVal.Set(reflect.Zero(outVal.Type())) + + if d.config.Metadata != nil && name != "" { + d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + } + } + return nil + } + + if !inputVal.IsValid() { + // If the input value is invalid, then we just set the value + // to be the zero value. + outVal.Set(reflect.Zero(outVal.Type())) + if d.config.Metadata != nil && name != "" { + d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + } + return nil + } + + if d.cachedDecodeHook != nil { + // We have a DecodeHook, so let's pre-process the input. + var err error + input, err = d.cachedDecodeHook(inputVal, outVal) + if err != nil { + return fmt.Errorf("error decoding '%s': %w", name, err) + } + } + + var err error + outputKind := getKind(outVal) + addMetaKey := true + switch outputKind { + case reflect.Bool: + err = d.decodeBool(name, input, outVal) + case reflect.Interface: + err = d.decodeBasic(name, input, outVal) + case reflect.String: + err = d.decodeString(name, input, outVal) + case reflect.Int: + err = d.decodeInt(name, input, outVal) + case reflect.Uint: + err = d.decodeUint(name, input, outVal) + case reflect.Float32: + err = d.decodeFloat(name, input, outVal) + case reflect.Complex64: + err = d.decodeComplex(name, input, outVal) + case reflect.Struct: + err = d.decodeStruct(name, input, outVal) + case reflect.Map: + err = d.decodeMap(name, input, outVal) + case reflect.Ptr: + addMetaKey, err = d.decodePtr(name, input, outVal) + case reflect.Slice: + err = d.decodeSlice(name, input, outVal) + case reflect.Array: + err = d.decodeArray(name, input, outVal) + case reflect.Func: + err = d.decodeFunc(name, input, outVal) + default: + // If we reached this point then we weren't able to decode it + return fmt.Errorf("%s: unsupported type: %s", name, outputKind) + } + + // If we reached here, then we successfully decoded SOMETHING, so + // mark the key as used if we're tracking metainput. + if addMetaKey && d.config.Metadata != nil && name != "" { + d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + } + + return err +} + +// This decodes a basic type (bool, int, string, etc.) and sets the +// value to "data" of that type. +func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error { + if val.IsValid() && val.Elem().IsValid() { + elem := val.Elem() + + // If we can't address this element, then its not writable. Instead, + // we make a copy of the value (which is a pointer and therefore + // writable), decode into that, and replace the whole value. + copied := false + if !elem.CanAddr() { + copied = true + + // Make *T + copy := reflect.New(elem.Type()) + + // *T = elem + copy.Elem().Set(elem) + + // Set elem so we decode into it + elem = copy + } + + // Decode. If we have an error then return. We also return right + // away if we're not a copy because that means we decoded directly. + if err := d.decode(name, data, elem); err != nil || !copied { + return err + } + + // If we're a copy, we need to set te final result + val.Set(elem.Elem()) + return nil + } + + dataVal := reflect.ValueOf(data) + + // If the input data is a pointer, and the assigned type is the dereference + // of that exact pointer, then indirect it so that we can assign it. + // Example: *string to string + if dataVal.Kind() == reflect.Ptr && dataVal.Type().Elem() == val.Type() { + dataVal = reflect.Indirect(dataVal) + } + + if !dataVal.IsValid() { + dataVal = reflect.Zero(val.Type()) + } + + dataValType := dataVal.Type() + if !dataValType.AssignableTo(val.Type()) { + return fmt.Errorf( + "'%s' expected type '%s', got '%s'", + name, val.Type(), dataValType) + } + + val.Set(dataVal) + return nil +} + +func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + + converted := true + switch { + case dataKind == reflect.String: + val.SetString(dataVal.String()) + case dataKind == reflect.Bool && d.config.WeaklyTypedInput: + if dataVal.Bool() { + val.SetString("1") + } else { + val.SetString("0") + } + case dataKind == reflect.Int && d.config.WeaklyTypedInput: + val.SetString(strconv.FormatInt(dataVal.Int(), 10)) + case dataKind == reflect.Uint && d.config.WeaklyTypedInput: + val.SetString(strconv.FormatUint(dataVal.Uint(), 10)) + case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: + val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64)) + case dataKind == reflect.Slice && d.config.WeaklyTypedInput, + dataKind == reflect.Array && d.config.WeaklyTypedInput: + dataType := dataVal.Type() + elemKind := dataType.Elem().Kind() + switch elemKind { + case reflect.Uint8: + var uints []uint8 + if dataKind == reflect.Array { + uints = make([]uint8, dataVal.Len(), dataVal.Len()) + for i := range uints { + uints[i] = dataVal.Index(i).Interface().(uint8) + } + } else { + uints = dataVal.Interface().([]uint8) + } + val.SetString(string(uints)) + default: + converted = false + } + default: + converted = false + } + + if !converted { + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + + return nil +} + +func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + dataType := dataVal.Type() + + switch { + case dataKind == reflect.Int: + val.SetInt(dataVal.Int()) + case dataKind == reflect.Uint: + val.SetInt(int64(dataVal.Uint())) + case dataKind == reflect.Float32: + val.SetInt(int64(dataVal.Float())) + case dataKind == reflect.Bool && d.config.WeaklyTypedInput: + if dataVal.Bool() { + val.SetInt(1) + } else { + val.SetInt(0) + } + case dataKind == reflect.String && d.config.WeaklyTypedInput: + str := dataVal.String() + if str == "" { + str = "0" + } + + i, err := strconv.ParseInt(str, 0, val.Type().Bits()) + if err == nil { + val.SetInt(i) + } else { + return fmt.Errorf("cannot parse '%s' as int: %s", name, err) + } + case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": + jn := data.(json.Number) + i, err := jn.Int64() + if err != nil { + return fmt.Errorf( + "error decoding json.Number into %s: %s", name, err) + } + val.SetInt(i) + default: + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + + return nil +} + +func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + dataType := dataVal.Type() + + switch { + case dataKind == reflect.Int: + i := dataVal.Int() + if i < 0 && !d.config.WeaklyTypedInput { + return fmt.Errorf("cannot parse '%s', %d overflows uint", + name, i) + } + val.SetUint(uint64(i)) + case dataKind == reflect.Uint: + val.SetUint(dataVal.Uint()) + case dataKind == reflect.Float32: + f := dataVal.Float() + if f < 0 && !d.config.WeaklyTypedInput { + return fmt.Errorf("cannot parse '%s', %f overflows uint", + name, f) + } + val.SetUint(uint64(f)) + case dataKind == reflect.Bool && d.config.WeaklyTypedInput: + if dataVal.Bool() { + val.SetUint(1) + } else { + val.SetUint(0) + } + case dataKind == reflect.String && d.config.WeaklyTypedInput: + str := dataVal.String() + if str == "" { + str = "0" + } + + i, err := strconv.ParseUint(str, 0, val.Type().Bits()) + if err == nil { + val.SetUint(i) + } else { + return fmt.Errorf("cannot parse '%s' as uint: %s", name, err) + } + case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": + jn := data.(json.Number) + i, err := strconv.ParseUint(string(jn), 0, 64) + if err != nil { + return fmt.Errorf( + "error decoding json.Number into %s: %s", name, err) + } + val.SetUint(i) + default: + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + + return nil +} + +func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + + switch { + case dataKind == reflect.Bool: + val.SetBool(dataVal.Bool()) + case dataKind == reflect.Int && d.config.WeaklyTypedInput: + val.SetBool(dataVal.Int() != 0) + case dataKind == reflect.Uint && d.config.WeaklyTypedInput: + val.SetBool(dataVal.Uint() != 0) + case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: + val.SetBool(dataVal.Float() != 0) + case dataKind == reflect.String && d.config.WeaklyTypedInput: + b, err := strconv.ParseBool(dataVal.String()) + if err == nil { + val.SetBool(b) + } else if dataVal.String() == "" { + val.SetBool(false) + } else { + return fmt.Errorf("cannot parse '%s' as bool: %s", name, err) + } + default: + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + + return nil +} + +func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + dataType := dataVal.Type() + + switch { + case dataKind == reflect.Int: + val.SetFloat(float64(dataVal.Int())) + case dataKind == reflect.Uint: + val.SetFloat(float64(dataVal.Uint())) + case dataKind == reflect.Float32: + val.SetFloat(dataVal.Float()) + case dataKind == reflect.Bool && d.config.WeaklyTypedInput: + if dataVal.Bool() { + val.SetFloat(1) + } else { + val.SetFloat(0) + } + case dataKind == reflect.String && d.config.WeaklyTypedInput: + str := dataVal.String() + if str == "" { + str = "0" + } + + f, err := strconv.ParseFloat(str, val.Type().Bits()) + if err == nil { + val.SetFloat(f) + } else { + return fmt.Errorf("cannot parse '%s' as float: %s", name, err) + } + case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": + jn := data.(json.Number) + i, err := jn.Float64() + if err != nil { + return fmt.Errorf( + "error decoding json.Number into %s: %s", name, err) + } + val.SetFloat(i) + default: + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + + return nil +} + +func (d *Decoder) decodeComplex(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + + switch { + case dataKind == reflect.Complex64: + val.SetComplex(dataVal.Complex()) + default: + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + + return nil +} + +func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error { + valType := val.Type() + valKeyType := valType.Key() + valElemType := valType.Elem() + + // By default we overwrite keys in the current map + valMap := val + + // If the map is nil or we're purposely zeroing fields, make a new map + if valMap.IsNil() || d.config.ZeroFields { + // Make a new map to hold our result + mapType := reflect.MapOf(valKeyType, valElemType) + valMap = reflect.MakeMap(mapType) + } + + dataVal := reflect.ValueOf(data) + + // Resolve any levels of indirection + for dataVal.Kind() == reflect.Pointer { + dataVal = reflect.Indirect(dataVal) + } + + // Check input type and based on the input type jump to the proper func + switch dataVal.Kind() { + case reflect.Map: + return d.decodeMapFromMap(name, dataVal, val, valMap) + + case reflect.Struct: + return d.decodeMapFromStruct(name, dataVal, val, valMap) + + case reflect.Array, reflect.Slice: + if d.config.WeaklyTypedInput { + return d.decodeMapFromSlice(name, dataVal, val, valMap) + } + + fallthrough + + default: + return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) + } +} + +func (d *Decoder) decodeMapFromSlice(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + // Special case for BC reasons (covered by tests) + if dataVal.Len() == 0 { + val.Set(valMap) + return nil + } + + for i := 0; i < dataVal.Len(); i++ { + err := d.decode( + name+"["+strconv.Itoa(i)+"]", + dataVal.Index(i).Interface(), val) + if err != nil { + return err + } + } + + return nil +} + +func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + valType := val.Type() + valKeyType := valType.Key() + valElemType := valType.Elem() + + // Accumulate errors + var errs []error + + // If the input data is empty, then we just match what the input data is. + if dataVal.Len() == 0 { + if dataVal.IsNil() { + if !val.IsNil() { + val.Set(dataVal) + } + } else { + // Set to empty allocated value + val.Set(valMap) + } + + return nil + } + + for _, k := range dataVal.MapKeys() { + fieldName := name + "[" + k.String() + "]" + + // First decode the key into the proper type + currentKey := reflect.Indirect(reflect.New(valKeyType)) + if err := d.decode(fieldName, k.Interface(), currentKey); err != nil { + errs = append(errs, err) + continue + } + + // Next decode the data into the proper type + v := dataVal.MapIndex(k).Interface() + currentVal := reflect.Indirect(reflect.New(valElemType)) + if err := d.decode(fieldName, v, currentVal); err != nil { + errs = append(errs, err) + continue + } + + valMap.SetMapIndex(currentKey, currentVal) + } + + // Set the built up map to the value + val.Set(valMap) + + return errors.Join(errs...) +} + +func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + typ := dataVal.Type() + for i := 0; i < typ.NumField(); i++ { + // Get the StructField first since this is a cheap operation. If the + // field is unexported, then ignore it. + f := typ.Field(i) + if f.PkgPath != "" { + continue + } + + // Next get the actual value of this field and verify it is assignable + // to the map value. + v := dataVal.Field(i) + if !v.Type().AssignableTo(valMap.Type().Elem()) { + return fmt.Errorf("cannot assign type '%s' to map value field of type '%s'", v.Type(), valMap.Type().Elem()) + } + + tagValue := f.Tag.Get(d.config.TagName) + keyName := f.Name + + if tagValue == "" && d.config.IgnoreUntaggedFields { + continue + } + + // If Squash is set in the config, we squash the field down. + squash := d.config.Squash && v.Kind() == reflect.Struct && f.Anonymous + + v = dereferencePtrToStructIfNeeded(v, d.config.TagName) + + // Determine the name of the key in the map + if index := strings.Index(tagValue, ","); index != -1 { + if tagValue[:index] == "-" { + continue + } + // If "omitempty" is specified in the tag, it ignores empty values. + if strings.Index(tagValue[index+1:], "omitempty") != -1 && isEmptyValue(v) { + continue + } + + // If "squash" is specified in the tag, we squash the field down. + squash = squash || strings.Contains(tagValue[index+1:], d.config.SquashTagOption) + if squash { + // When squashing, the embedded type can be a pointer to a struct. + if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct { + v = v.Elem() + } + + // The final type must be a struct + if v.Kind() != reflect.Struct { + return fmt.Errorf("cannot squash non-struct type '%s'", v.Type()) + } + } else { + if strings.Index(tagValue[index+1:], "remain") != -1 { + if v.Kind() != reflect.Map { + return fmt.Errorf("error remain-tag field with invalid type: '%s'", v.Type()) + } + + ptr := v.MapRange() + for ptr.Next() { + valMap.SetMapIndex(ptr.Key(), ptr.Value()) + } + continue + } + } + if keyNameTagValue := tagValue[:index]; keyNameTagValue != "" { + keyName = keyNameTagValue + } + } else if len(tagValue) > 0 { + if tagValue == "-" { + continue + } + keyName = tagValue + } + + switch v.Kind() { + // this is an embedded struct, so handle it differently + case reflect.Struct: + x := reflect.New(v.Type()) + x.Elem().Set(v) + + vType := valMap.Type() + vKeyType := vType.Key() + vElemType := vType.Elem() + mType := reflect.MapOf(vKeyType, vElemType) + vMap := reflect.MakeMap(mType) + + // Creating a pointer to a map so that other methods can completely + // overwrite the map if need be (looking at you decodeMapFromMap). The + // indirection allows the underlying map to be settable (CanSet() == true) + // where as reflect.MakeMap returns an unsettable map. + addrVal := reflect.New(vMap.Type()) + reflect.Indirect(addrVal).Set(vMap) + + err := d.decode(keyName, x.Interface(), reflect.Indirect(addrVal)) + if err != nil { + return err + } + + // the underlying map may have been completely overwritten so pull + // it indirectly out of the enclosing value. + vMap = reflect.Indirect(addrVal) + + if squash { + for _, k := range vMap.MapKeys() { + valMap.SetMapIndex(k, vMap.MapIndex(k)) + } + } else { + valMap.SetMapIndex(reflect.ValueOf(keyName), vMap) + } + + default: + valMap.SetMapIndex(reflect.ValueOf(keyName), v) + } + } + + if val.CanAddr() { + val.Set(valMap) + } + + return nil +} + +func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) (bool, error) { + // If the input data is nil, then we want to just set the output + // pointer to be nil as well. + isNil := data == nil + if !isNil { + switch v := reflect.Indirect(reflect.ValueOf(data)); v.Kind() { + case reflect.Chan, + reflect.Func, + reflect.Interface, + reflect.Map, + reflect.Ptr, + reflect.Slice: + isNil = v.IsNil() + } + } + if isNil { + if !val.IsNil() && val.CanSet() { + nilValue := reflect.New(val.Type()).Elem() + val.Set(nilValue) + } + + return true, nil + } + + // Create an element of the concrete (non pointer) type and decode + // into that. Then set the value of the pointer to this type. + valType := val.Type() + valElemType := valType.Elem() + if val.CanSet() { + realVal := val + if realVal.IsNil() || d.config.ZeroFields { + realVal = reflect.New(valElemType) + } + + if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil { + return false, err + } + + val.Set(realVal) + } else { + if err := d.decode(name, data, reflect.Indirect(val)); err != nil { + return false, err + } + } + return false, nil +} + +func (d *Decoder) decodeFunc(name string, data interface{}, val reflect.Value) error { + // Create an element of the concrete (non pointer) type and decode + // into that. Then set the value of the pointer to this type. + dataVal := reflect.Indirect(reflect.ValueOf(data)) + if val.Type() != dataVal.Type() { + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + val.Set(dataVal) + return nil +} + +func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataValKind := dataVal.Kind() + valType := val.Type() + valElemType := valType.Elem() + sliceType := reflect.SliceOf(valElemType) + + // If we have a non array/slice type then we first attempt to convert. + if dataValKind != reflect.Array && dataValKind != reflect.Slice { + if d.config.WeaklyTypedInput { + switch { + // Slice and array we use the normal logic + case dataValKind == reflect.Slice, dataValKind == reflect.Array: + break + + // Empty maps turn into empty slices + case dataValKind == reflect.Map: + if dataVal.Len() == 0 { + val.Set(reflect.MakeSlice(sliceType, 0, 0)) + return nil + } + // Create slice of maps of other sizes + return d.decodeSlice(name, []interface{}{data}, val) + + case dataValKind == reflect.String && valElemType.Kind() == reflect.Uint8: + return d.decodeSlice(name, []byte(dataVal.String()), val) + + // All other types we try to convert to the slice type + // and "lift" it into it. i.e. a string becomes a string slice. + default: + // Just re-try this function with data as a slice. + return d.decodeSlice(name, []interface{}{data}, val) + } + } + + return fmt.Errorf( + "'%s': source data must be an array or slice, got %s", name, dataValKind) + } + + // If the input value is nil, then don't allocate since empty != nil + if dataValKind != reflect.Array && dataVal.IsNil() { + return nil + } + + valSlice := val + if valSlice.IsNil() || d.config.ZeroFields { + // Make a new slice to hold our result, same size as the original data. + valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) + } else if valSlice.Len() > dataVal.Len() { + valSlice = valSlice.Slice(0, dataVal.Len()) + } + + // Accumulate any errors + var errs []error + + for i := 0; i < dataVal.Len(); i++ { + currentData := dataVal.Index(i).Interface() + for valSlice.Len() <= i { + valSlice = reflect.Append(valSlice, reflect.Zero(valElemType)) + } + currentField := valSlice.Index(i) + + fieldName := name + "[" + strconv.Itoa(i) + "]" + if err := d.decode(fieldName, currentData, currentField); err != nil { + errs = append(errs, err) + } + } + + // Finally, set the value to the slice we built up + val.Set(valSlice) + + return errors.Join(errs...) +} + +func (d *Decoder) decodeArray(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataValKind := dataVal.Kind() + valType := val.Type() + valElemType := valType.Elem() + arrayType := reflect.ArrayOf(valType.Len(), valElemType) + + valArray := val + + if isComparable(valArray) && valArray.Interface() == reflect.Zero(valArray.Type()).Interface() || d.config.ZeroFields { + // Check input type + if dataValKind != reflect.Array && dataValKind != reflect.Slice { + if d.config.WeaklyTypedInput { + switch { + // Empty maps turn into empty arrays + case dataValKind == reflect.Map: + if dataVal.Len() == 0 { + val.Set(reflect.Zero(arrayType)) + return nil + } + + // All other types we try to convert to the array type + // and "lift" it into it. i.e. a string becomes a string array. + default: + // Just re-try this function with data as a slice. + return d.decodeArray(name, []interface{}{data}, val) + } + } + + return fmt.Errorf( + "'%s': source data must be an array or slice, got %s", name, dataValKind) + + } + if dataVal.Len() > arrayType.Len() { + return fmt.Errorf( + "'%s': expected source data to have length less or equal to %d, got %d", name, arrayType.Len(), dataVal.Len()) + } + + // Make a new array to hold our result, same size as the original data. + valArray = reflect.New(arrayType).Elem() + } + + // Accumulate any errors + var errs []error + + for i := 0; i < dataVal.Len(); i++ { + currentData := dataVal.Index(i).Interface() + currentField := valArray.Index(i) + + fieldName := name + "[" + strconv.Itoa(i) + "]" + if err := d.decode(fieldName, currentData, currentField); err != nil { + errs = append(errs, err) + } + } + + // Finally, set the value to the array we built up + val.Set(valArray) + + return errors.Join(errs...) +} + +func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + + // If the type of the value to write to and the data match directly, + // then we just set it directly instead of recursing into the structure. + if dataVal.Type() == val.Type() { + val.Set(dataVal) + return nil + } + + dataValKind := dataVal.Kind() + switch dataValKind { + case reflect.Map: + return d.decodeStructFromMap(name, dataVal, val) + + case reflect.Struct: + // Not the most efficient way to do this but we can optimize later if + // we want to. To convert from struct to struct we go to map first + // as an intermediary. + + // Make a new map to hold our result + mapType := reflect.TypeOf((map[string]interface{})(nil)) + mval := reflect.MakeMap(mapType) + + // Creating a pointer to a map so that other methods can completely + // overwrite the map if need be (looking at you decodeMapFromMap). The + // indirection allows the underlying map to be settable (CanSet() == true) + // where as reflect.MakeMap returns an unsettable map. + addrVal := reflect.New(mval.Type()) + + reflect.Indirect(addrVal).Set(mval) + if err := d.decodeMapFromStruct(name, dataVal, reflect.Indirect(addrVal), mval); err != nil { + return err + } + + result := d.decodeStructFromMap(name, reflect.Indirect(addrVal), val) + return result + + default: + return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) + } +} + +func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) error { + dataValType := dataVal.Type() + if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface { + return fmt.Errorf( + "'%s' needs a map with string keys, has '%s' keys", + name, dataValType.Key().Kind()) + } + + dataValKeys := make(map[reflect.Value]struct{}) + dataValKeysUnused := make(map[interface{}]struct{}) + for _, dataValKey := range dataVal.MapKeys() { + dataValKeys[dataValKey] = struct{}{} + dataValKeysUnused[dataValKey.Interface()] = struct{}{} + } + + targetValKeysUnused := make(map[interface{}]struct{}) + + var errs []error + + // This slice will keep track of all the structs we'll be decoding. + // There can be more than one struct if there are embedded structs + // that are squashed. + structs := make([]reflect.Value, 1, 5) + structs[0] = val + + // Compile the list of all the fields that we're going to be decoding + // from all the structs. + type field struct { + field reflect.StructField + val reflect.Value + } + + // remainField is set to a valid field set with the "remain" tag if + // we are keeping track of remaining values. + var remainField *field + + fields := []field{} + for len(structs) > 0 { + structVal := structs[0] + structs = structs[1:] + + structType := structVal.Type() + + for i := 0; i < structType.NumField(); i++ { + fieldType := structType.Field(i) + fieldVal := structVal.Field(i) + if fieldVal.Kind() == reflect.Ptr && fieldVal.Elem().Kind() == reflect.Struct { + // Handle embedded struct pointers as embedded structs. + fieldVal = fieldVal.Elem() + } + + // If "squash" is specified in the tag, we squash the field down. + squash := d.config.Squash && fieldVal.Kind() == reflect.Struct && fieldType.Anonymous + remain := false + + // We always parse the tags cause we're looking for other tags too + tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",") + for _, tag := range tagParts[1:] { + if tag == d.config.SquashTagOption { + squash = true + break + } + + if tag == "remain" { + remain = true + break + } + } + + if squash { + switch fieldVal.Kind() { + case reflect.Struct: + structs = append(structs, fieldVal) + case reflect.Interface: + if !fieldVal.IsNil() { + structs = append(structs, fieldVal.Elem().Elem()) + } + default: + errs = append(errs, fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldVal.Kind())) + } + continue + } + + // Build our field + if remain { + remainField = &field{fieldType, fieldVal} + } else { + // Normal struct field, store it away + fields = append(fields, field{fieldType, fieldVal}) + } + } + } + + // for fieldType, field := range fields { + for _, f := range fields { + field, fieldValue := f.field, f.val + fieldName := field.Name + + tagValue := field.Tag.Get(d.config.TagName) + if tagValue == "" && d.config.IgnoreUntaggedFields { + continue + } + tagValue = strings.SplitN(tagValue, ",", 2)[0] + if tagValue != "" { + fieldName = tagValue + } + + rawMapKey := reflect.ValueOf(fieldName) + rawMapVal := dataVal.MapIndex(rawMapKey) + if !rawMapVal.IsValid() { + // Do a slower search by iterating over each key and + // doing case-insensitive search. + for dataValKey := range dataValKeys { + mK, ok := dataValKey.Interface().(string) + if !ok { + // Not a string key + continue + } + + if d.config.MatchName(mK, fieldName) { + rawMapKey = dataValKey + rawMapVal = dataVal.MapIndex(dataValKey) + break + } + } + + if !rawMapVal.IsValid() { + // There was no matching key in the map for the value in + // the struct. Remember it for potential errors and metadata. + targetValKeysUnused[fieldName] = struct{}{} + continue + } + } + + if !fieldValue.IsValid() { + // This should never happen + panic("field is not valid") + } + + // If we can't set the field, then it is unexported or something, + // and we just continue onwards. + if !fieldValue.CanSet() { + continue + } + + // Delete the key we're using from the unused map so we stop tracking + delete(dataValKeysUnused, rawMapKey.Interface()) + + // If the name is empty string, then we're at the root, and we + // don't dot-join the fields. + if name != "" { + fieldName = name + "." + fieldName + } + + if err := d.decode(fieldName, rawMapVal.Interface(), fieldValue); err != nil { + errs = append(errs, err) + } + } + + // If we have a "remain"-tagged field and we have unused keys then + // we put the unused keys directly into the remain field. + if remainField != nil && len(dataValKeysUnused) > 0 { + // Build a map of only the unused values + remain := map[interface{}]interface{}{} + for key := range dataValKeysUnused { + remain[key] = dataVal.MapIndex(reflect.ValueOf(key)).Interface() + } + + // Decode it as-if we were just decoding this map onto our map. + if err := d.decodeMap(name, remain, remainField.val); err != nil { + errs = append(errs, err) + } + + // Set the map to nil so we have none so that the next check will + // not error (ErrorUnused) + dataValKeysUnused = nil + } + + if d.config.ErrorUnused && len(dataValKeysUnused) > 0 { + keys := make([]string, 0, len(dataValKeysUnused)) + for rawKey := range dataValKeysUnused { + keys = append(keys, rawKey.(string)) + } + sort.Strings(keys) + + err := fmt.Errorf("'%s' has invalid keys: %s", name, strings.Join(keys, ", ")) + errs = append(errs, err) + } + + if d.config.ErrorUnset && len(targetValKeysUnused) > 0 { + keys := make([]string, 0, len(targetValKeysUnused)) + for rawKey := range targetValKeysUnused { + keys = append(keys, rawKey.(string)) + } + sort.Strings(keys) + + err := fmt.Errorf("'%s' has unset fields: %s", name, strings.Join(keys, ", ")) + errs = append(errs, err) + } + + if err := errors.Join(errs...); err != nil { + return err + } + + // Add the unused keys to the list of unused keys if we're tracking metadata + if d.config.Metadata != nil { + for rawKey := range dataValKeysUnused { + key := rawKey.(string) + if name != "" { + key = name + "." + key + } + + d.config.Metadata.Unused = append(d.config.Metadata.Unused, key) + } + for rawKey := range targetValKeysUnused { + key := rawKey.(string) + if name != "" { + key = name + "." + key + } + + d.config.Metadata.Unset = append(d.config.Metadata.Unset, key) + } + } + + return nil +} + +func isEmptyValue(v reflect.Value) bool { + switch getKind(v) { + case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + } + return false +} + +func getKind(val reflect.Value) reflect.Kind { + kind := val.Kind() + + switch { + case kind >= reflect.Int && kind <= reflect.Int64: + return reflect.Int + case kind >= reflect.Uint && kind <= reflect.Uint64: + return reflect.Uint + case kind >= reflect.Float32 && kind <= reflect.Float64: + return reflect.Float32 + case kind >= reflect.Complex64 && kind <= reflect.Complex128: + return reflect.Complex64 + default: + return kind + } +} + +func isStructTypeConvertibleToMap(typ reflect.Type, checkMapstructureTags bool, tagName string) bool { + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + if f.PkgPath == "" && !checkMapstructureTags { // check for unexported fields + return true + } + if checkMapstructureTags && f.Tag.Get(tagName) != "" { // check for mapstructure tags inside + return true + } + } + return false +} + +func dereferencePtrToStructIfNeeded(v reflect.Value, tagName string) reflect.Value { + if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct { + return v + } + deref := v.Elem() + derefT := deref.Type() + if isStructTypeConvertibleToMap(derefT, true, tagName) { + return deref + } + return v +} diff --git a/vendor/github.com/go-viper/mapstructure/v2/reflect_go1_19.go b/vendor/github.com/go-viper/mapstructure/v2/reflect_go1_19.go new file mode 100644 index 00000000..d0913fff --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/reflect_go1_19.go @@ -0,0 +1,44 @@ +//go:build !go1.20 + +package mapstructure + +import "reflect" + +func isComparable(v reflect.Value) bool { + k := v.Kind() + switch k { + case reflect.Invalid: + return false + + case reflect.Array: + switch v.Type().Elem().Kind() { + case reflect.Interface, reflect.Array, reflect.Struct: + for i := 0; i < v.Type().Len(); i++ { + // if !v.Index(i).Comparable() { + if !isComparable(v.Index(i)) { + return false + } + } + return true + } + return v.Type().Comparable() + + case reflect.Interface: + // return v.Elem().Comparable() + return isComparable(v.Elem()) + + case reflect.Struct: + for i := 0; i < v.NumField(); i++ { + return false + + // if !v.Field(i).Comparable() { + if !isComparable(v.Field(i)) { + return false + } + } + return true + + default: + return v.Type().Comparable() + } +} diff --git a/vendor/github.com/go-viper/mapstructure/v2/reflect_go1_20.go b/vendor/github.com/go-viper/mapstructure/v2/reflect_go1_20.go new file mode 100644 index 00000000..f8255a1b --- /dev/null +++ b/vendor/github.com/go-viper/mapstructure/v2/reflect_go1_20.go @@ -0,0 +1,10 @@ +//go:build go1.20 + +package mapstructure + +import "reflect" + +// TODO: remove once we drop support for Go <1.20 +func isComparable(v reflect.Value) bool { + return v.Comparable() +} diff --git a/vendor/github.com/gogo/protobuf/AUTHORS b/vendor/github.com/gogo/protobuf/AUTHORS new file mode 100644 index 00000000..3d97fc7a --- /dev/null +++ b/vendor/github.com/gogo/protobuf/AUTHORS @@ -0,0 +1,15 @@ +# This is the official list of GoGo authors for copyright purposes. +# This file is distinct from the CONTRIBUTORS file, which +# lists people. For example, employees are listed in CONTRIBUTORS, +# but not in AUTHORS, because the employer holds the copyright. + +# Names should be added to this file as one of +# Organization's name +# Individual's name +# Individual's name + +# Please keep the list sorted. + +Sendgrid, Inc +Vastech SA (PTY) LTD +Walter Schulze diff --git a/vendor/github.com/gogo/protobuf/CONTRIBUTORS b/vendor/github.com/gogo/protobuf/CONTRIBUTORS new file mode 100644 index 00000000..1b4f6c20 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/CONTRIBUTORS @@ -0,0 +1,23 @@ +Anton Povarov +Brian Goff +Clayton Coleman +Denis Smirnov +DongYun Kang +Dwayne Schultz +Georg Apitz +Gustav Paul +Johan Brandhorst +John Shahid +John Tuley +Laurent +Patrick Lee +Peter Edge +Roger Johansson +Sam Nguyen +Sergio Arbeo +Stephen J Day +Tamir Duberstein +Todd Eisenberger +Tormod Erevik Lea +Vyacheslav Kim +Walter Schulze diff --git a/vendor/github.com/gogo/protobuf/LICENSE b/vendor/github.com/gogo/protobuf/LICENSE new file mode 100644 index 00000000..f57de90d --- /dev/null +++ b/vendor/github.com/gogo/protobuf/LICENSE @@ -0,0 +1,35 @@ +Copyright (c) 2013, The GoGo Authors. All rights reserved. + +Protocol Buffers for Go with Gadgets + +Go support for Protocol Buffers - Google's data interchange format + +Copyright 2010 The Go Authors. All rights reserved. +https://github.com/golang/protobuf + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/vendor/github.com/gogo/protobuf/proto/Makefile b/vendor/github.com/gogo/protobuf/proto/Makefile new file mode 100644 index 00000000..00d65f32 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/Makefile @@ -0,0 +1,43 @@ +# Go support for Protocol Buffers - Google's data interchange format +# +# Copyright 2010 The Go Authors. All rights reserved. +# https://github.com/golang/protobuf +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +install: + go install + +test: install generate-test-pbs + go test + + +generate-test-pbs: + make install + make -C test_proto + make -C proto3_proto + make diff --git a/vendor/github.com/gogo/protobuf/proto/clone.go b/vendor/github.com/gogo/protobuf/proto/clone.go new file mode 100644 index 00000000..a26b046d --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/clone.go @@ -0,0 +1,258 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2011 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Protocol buffer deep copy and merge. +// TODO: RawMessage. + +package proto + +import ( + "fmt" + "log" + "reflect" + "strings" +) + +// Clone returns a deep copy of a protocol buffer. +func Clone(src Message) Message { + in := reflect.ValueOf(src) + if in.IsNil() { + return src + } + out := reflect.New(in.Type().Elem()) + dst := out.Interface().(Message) + Merge(dst, src) + return dst +} + +// Merger is the interface representing objects that can merge messages of the same type. +type Merger interface { + // Merge merges src into this message. + // Required and optional fields that are set in src will be set to that value in dst. + // Elements of repeated fields will be appended. + // + // Merge may panic if called with a different argument type than the receiver. + Merge(src Message) +} + +// generatedMerger is the custom merge method that generated protos will have. +// We must add this method since a generate Merge method will conflict with +// many existing protos that have a Merge data field already defined. +type generatedMerger interface { + XXX_Merge(src Message) +} + +// Merge merges src into dst. +// Required and optional fields that are set in src will be set to that value in dst. +// Elements of repeated fields will be appended. +// Merge panics if src and dst are not the same type, or if dst is nil. +func Merge(dst, src Message) { + if m, ok := dst.(Merger); ok { + m.Merge(src) + return + } + + in := reflect.ValueOf(src) + out := reflect.ValueOf(dst) + if out.IsNil() { + panic("proto: nil destination") + } + if in.Type() != out.Type() { + panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src)) + } + if in.IsNil() { + return // Merge from nil src is a noop + } + if m, ok := dst.(generatedMerger); ok { + m.XXX_Merge(src) + return + } + mergeStruct(out.Elem(), in.Elem()) +} + +func mergeStruct(out, in reflect.Value) { + sprop := GetProperties(in.Type()) + for i := 0; i < in.NumField(); i++ { + f := in.Type().Field(i) + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) + } + + if emIn, ok := in.Addr().Interface().(extensionsBytes); ok { + emOut := out.Addr().Interface().(extensionsBytes) + bIn := emIn.GetExtensions() + bOut := emOut.GetExtensions() + *bOut = append(*bOut, *bIn...) + } else if emIn, err := extendable(in.Addr().Interface()); err == nil { + emOut, _ := extendable(out.Addr().Interface()) + mIn, muIn := emIn.extensionsRead() + if mIn != nil { + mOut := emOut.extensionsWrite() + muIn.Lock() + mergeExtension(mOut, mIn) + muIn.Unlock() + } + } + + uf := in.FieldByName("XXX_unrecognized") + if !uf.IsValid() { + return + } + uin := uf.Bytes() + if len(uin) > 0 { + out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) + } +} + +// mergeAny performs a merge between two values of the same type. +// viaPtr indicates whether the values were indirected through a pointer (implying proto2). +// prop is set if this is a struct field (it may be nil). +func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { + if in.Type() == protoMessageType { + if !in.IsNil() { + if out.IsNil() { + out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) + } else { + Merge(out.Interface().(Message), in.Interface().(Message)) + } + } + return + } + switch in.Kind() { + case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, + reflect.String, reflect.Uint32, reflect.Uint64: + if !viaPtr && isProto3Zero(in) { + return + } + out.Set(in) + case reflect.Interface: + // Probably a oneof field; copy non-nil values. + if in.IsNil() { + return + } + // Allocate destination if it is not set, or set to a different type. + // Otherwise we will merge as normal. + if out.IsNil() || out.Elem().Type() != in.Elem().Type() { + out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T) + } + mergeAny(out.Elem(), in.Elem(), false, nil) + case reflect.Map: + if in.Len() == 0 { + return + } + if out.IsNil() { + out.Set(reflect.MakeMap(in.Type())) + } + // For maps with value types of *T or []byte we need to deep copy each value. + elemKind := in.Type().Elem().Kind() + for _, key := range in.MapKeys() { + var val reflect.Value + switch elemKind { + case reflect.Ptr: + val = reflect.New(in.Type().Elem().Elem()) + mergeAny(val, in.MapIndex(key), false, nil) + case reflect.Slice: + val = in.MapIndex(key) + val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) + default: + val = in.MapIndex(key) + } + out.SetMapIndex(key, val) + } + case reflect.Ptr: + if in.IsNil() { + return + } + if out.IsNil() { + out.Set(reflect.New(in.Elem().Type())) + } + mergeAny(out.Elem(), in.Elem(), true, nil) + case reflect.Slice: + if in.IsNil() { + return + } + if in.Type().Elem().Kind() == reflect.Uint8 { + // []byte is a scalar bytes field, not a repeated field. + + // Edge case: if this is in a proto3 message, a zero length + // bytes field is considered the zero value, and should not + // be merged. + if prop != nil && prop.proto3 && in.Len() == 0 { + return + } + + // Make a deep copy. + // Append to []byte{} instead of []byte(nil) so that we never end up + // with a nil result. + out.SetBytes(append([]byte{}, in.Bytes()...)) + return + } + n := in.Len() + if out.IsNil() { + out.Set(reflect.MakeSlice(in.Type(), 0, n)) + } + switch in.Type().Elem().Kind() { + case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, + reflect.String, reflect.Uint32, reflect.Uint64: + out.Set(reflect.AppendSlice(out, in)) + default: + for i := 0; i < n; i++ { + x := reflect.Indirect(reflect.New(in.Type().Elem())) + mergeAny(x, in.Index(i), false, nil) + out.Set(reflect.Append(out, x)) + } + } + case reflect.Struct: + mergeStruct(out, in) + default: + // unknown type, so not a protocol buffer + log.Printf("proto: don't know how to copy %v", in) + } +} + +func mergeExtension(out, in map[int32]Extension) { + for extNum, eIn := range in { + eOut := Extension{desc: eIn.desc} + if eIn.value != nil { + v := reflect.New(reflect.TypeOf(eIn.value)).Elem() + mergeAny(v, reflect.ValueOf(eIn.value), false, nil) + eOut.value = v.Interface() + } + if eIn.enc != nil { + eOut.enc = make([]byte, len(eIn.enc)) + copy(eOut.enc, eIn.enc) + } + + out[extNum] = eOut + } +} diff --git a/vendor/github.com/gogo/protobuf/proto/custom_gogo.go b/vendor/github.com/gogo/protobuf/proto/custom_gogo.go new file mode 100644 index 00000000..24552483 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/custom_gogo.go @@ -0,0 +1,39 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2018, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import "reflect" + +type custom interface { + Marshal() ([]byte, error) + Unmarshal(data []byte) error + Size() int +} + +var customType = reflect.TypeOf((*custom)(nil)).Elem() diff --git a/vendor/github.com/gogo/protobuf/proto/decode.go b/vendor/github.com/gogo/protobuf/proto/decode.go new file mode 100644 index 00000000..63b0f08b --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/decode.go @@ -0,0 +1,427 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Routines for decoding protocol buffer data to construct in-memory representations. + */ + +import ( + "errors" + "fmt" + "io" +) + +// errOverflow is returned when an integer is too large to be represented. +var errOverflow = errors.New("proto: integer overflow") + +// ErrInternalBadWireType is returned by generated code when an incorrect +// wire type is encountered. It does not get returned to user code. +var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") + +// DecodeVarint reads a varint-encoded integer from the slice. +// It returns the integer and the number of bytes consumed, or +// zero if there is not enough. +// This is the format for the +// int32, int64, uint32, uint64, bool, and enum +// protocol buffer types. +func DecodeVarint(buf []byte) (x uint64, n int) { + for shift := uint(0); shift < 64; shift += 7 { + if n >= len(buf) { + return 0, 0 + } + b := uint64(buf[n]) + n++ + x |= (b & 0x7F) << shift + if (b & 0x80) == 0 { + return x, n + } + } + + // The number is too large to represent in a 64-bit value. + return 0, 0 +} + +func (p *Buffer) decodeVarintSlow() (x uint64, err error) { + i := p.index + l := len(p.buf) + + for shift := uint(0); shift < 64; shift += 7 { + if i >= l { + err = io.ErrUnexpectedEOF + return + } + b := p.buf[i] + i++ + x |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + p.index = i + return + } + } + + // The number is too large to represent in a 64-bit value. + err = errOverflow + return +} + +// DecodeVarint reads a varint-encoded integer from the Buffer. +// This is the format for the +// int32, int64, uint32, uint64, bool, and enum +// protocol buffer types. +func (p *Buffer) DecodeVarint() (x uint64, err error) { + i := p.index + buf := p.buf + + if i >= len(buf) { + return 0, io.ErrUnexpectedEOF + } else if buf[i] < 0x80 { + p.index++ + return uint64(buf[i]), nil + } else if len(buf)-i < 10 { + return p.decodeVarintSlow() + } + + var b uint64 + // we already checked the first byte + x = uint64(buf[i]) - 0x80 + i++ + + b = uint64(buf[i]) + i++ + x += b << 7 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 7 + + b = uint64(buf[i]) + i++ + x += b << 14 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 14 + + b = uint64(buf[i]) + i++ + x += b << 21 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 21 + + b = uint64(buf[i]) + i++ + x += b << 28 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 28 + + b = uint64(buf[i]) + i++ + x += b << 35 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 35 + + b = uint64(buf[i]) + i++ + x += b << 42 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 42 + + b = uint64(buf[i]) + i++ + x += b << 49 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 49 + + b = uint64(buf[i]) + i++ + x += b << 56 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 56 + + b = uint64(buf[i]) + i++ + x += b << 63 + if b&0x80 == 0 { + goto done + } + + return 0, errOverflow + +done: + p.index = i + return x, nil +} + +// DecodeFixed64 reads a 64-bit integer from the Buffer. +// This is the format for the +// fixed64, sfixed64, and double protocol buffer types. +func (p *Buffer) DecodeFixed64() (x uint64, err error) { + // x, err already 0 + i := p.index + 8 + if i < 0 || i > len(p.buf) { + err = io.ErrUnexpectedEOF + return + } + p.index = i + + x = uint64(p.buf[i-8]) + x |= uint64(p.buf[i-7]) << 8 + x |= uint64(p.buf[i-6]) << 16 + x |= uint64(p.buf[i-5]) << 24 + x |= uint64(p.buf[i-4]) << 32 + x |= uint64(p.buf[i-3]) << 40 + x |= uint64(p.buf[i-2]) << 48 + x |= uint64(p.buf[i-1]) << 56 + return +} + +// DecodeFixed32 reads a 32-bit integer from the Buffer. +// This is the format for the +// fixed32, sfixed32, and float protocol buffer types. +func (p *Buffer) DecodeFixed32() (x uint64, err error) { + // x, err already 0 + i := p.index + 4 + if i < 0 || i > len(p.buf) { + err = io.ErrUnexpectedEOF + return + } + p.index = i + + x = uint64(p.buf[i-4]) + x |= uint64(p.buf[i-3]) << 8 + x |= uint64(p.buf[i-2]) << 16 + x |= uint64(p.buf[i-1]) << 24 + return +} + +// DecodeZigzag64 reads a zigzag-encoded 64-bit integer +// from the Buffer. +// This is the format used for the sint64 protocol buffer type. +func (p *Buffer) DecodeZigzag64() (x uint64, err error) { + x, err = p.DecodeVarint() + if err != nil { + return + } + x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) + return +} + +// DecodeZigzag32 reads a zigzag-encoded 32-bit integer +// from the Buffer. +// This is the format used for the sint32 protocol buffer type. +func (p *Buffer) DecodeZigzag32() (x uint64, err error) { + x, err = p.DecodeVarint() + if err != nil { + return + } + x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) + return +} + +// DecodeRawBytes reads a count-delimited byte buffer from the Buffer. +// This is the format used for the bytes protocol buffer +// type and for embedded messages. +func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { + n, err := p.DecodeVarint() + if err != nil { + return nil, err + } + + nb := int(n) + if nb < 0 { + return nil, fmt.Errorf("proto: bad byte length %d", nb) + } + end := p.index + nb + if end < p.index || end > len(p.buf) { + return nil, io.ErrUnexpectedEOF + } + + if !alloc { + // todo: check if can get more uses of alloc=false + buf = p.buf[p.index:end] + p.index += nb + return + } + + buf = make([]byte, nb) + copy(buf, p.buf[p.index:]) + p.index += nb + return +} + +// DecodeStringBytes reads an encoded string from the Buffer. +// This is the format used for the proto2 string type. +func (p *Buffer) DecodeStringBytes() (s string, err error) { + buf, err := p.DecodeRawBytes(false) + if err != nil { + return + } + return string(buf), nil +} + +// Unmarshaler is the interface representing objects that can +// unmarshal themselves. The argument points to data that may be +// overwritten, so implementations should not keep references to the +// buffer. +// Unmarshal implementations should not clear the receiver. +// Any unmarshaled data should be merged into the receiver. +// Callers of Unmarshal that do not want to retain existing data +// should Reset the receiver before calling Unmarshal. +type Unmarshaler interface { + Unmarshal([]byte) error +} + +// newUnmarshaler is the interface representing objects that can +// unmarshal themselves. The semantics are identical to Unmarshaler. +// +// This exists to support protoc-gen-go generated messages. +// The proto package will stop type-asserting to this interface in the future. +// +// DO NOT DEPEND ON THIS. +type newUnmarshaler interface { + XXX_Unmarshal([]byte) error +} + +// Unmarshal parses the protocol buffer representation in buf and places the +// decoded result in pb. If the struct underlying pb does not match +// the data in buf, the results can be unpredictable. +// +// Unmarshal resets pb before starting to unmarshal, so any +// existing data in pb is always removed. Use UnmarshalMerge +// to preserve and append to existing data. +func Unmarshal(buf []byte, pb Message) error { + pb.Reset() + if u, ok := pb.(newUnmarshaler); ok { + return u.XXX_Unmarshal(buf) + } + if u, ok := pb.(Unmarshaler); ok { + return u.Unmarshal(buf) + } + return NewBuffer(buf).Unmarshal(pb) +} + +// UnmarshalMerge parses the protocol buffer representation in buf and +// writes the decoded result to pb. If the struct underlying pb does not match +// the data in buf, the results can be unpredictable. +// +// UnmarshalMerge merges into existing data in pb. +// Most code should use Unmarshal instead. +func UnmarshalMerge(buf []byte, pb Message) error { + if u, ok := pb.(newUnmarshaler); ok { + return u.XXX_Unmarshal(buf) + } + if u, ok := pb.(Unmarshaler); ok { + // NOTE: The history of proto have unfortunately been inconsistent + // whether Unmarshaler should or should not implicitly clear itself. + // Some implementations do, most do not. + // Thus, calling this here may or may not do what people want. + // + // See https://github.com/golang/protobuf/issues/424 + return u.Unmarshal(buf) + } + return NewBuffer(buf).Unmarshal(pb) +} + +// DecodeMessage reads a count-delimited message from the Buffer. +func (p *Buffer) DecodeMessage(pb Message) error { + enc, err := p.DecodeRawBytes(false) + if err != nil { + return err + } + return NewBuffer(enc).Unmarshal(pb) +} + +// DecodeGroup reads a tag-delimited group from the Buffer. +// StartGroup tag is already consumed. This function consumes +// EndGroup tag. +func (p *Buffer) DecodeGroup(pb Message) error { + b := p.buf[p.index:] + x, y := findEndGroup(b) + if x < 0 { + return io.ErrUnexpectedEOF + } + err := Unmarshal(b[:x], pb) + p.index += y + return err +} + +// Unmarshal parses the protocol buffer representation in the +// Buffer and places the decoded result in pb. If the struct +// underlying pb does not match the data in the buffer, the results can be +// unpredictable. +// +// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. +func (p *Buffer) Unmarshal(pb Message) error { + // If the object can unmarshal itself, let it. + if u, ok := pb.(newUnmarshaler); ok { + err := u.XXX_Unmarshal(p.buf[p.index:]) + p.index = len(p.buf) + return err + } + if u, ok := pb.(Unmarshaler); ok { + // NOTE: The history of proto have unfortunately been inconsistent + // whether Unmarshaler should or should not implicitly clear itself. + // Some implementations do, most do not. + // Thus, calling this here may or may not do what people want. + // + // See https://github.com/golang/protobuf/issues/424 + err := u.Unmarshal(p.buf[p.index:]) + p.index = len(p.buf) + return err + } + + // Slow workaround for messages that aren't Unmarshalers. + // This includes some hand-coded .pb.go files and + // bootstrap protos. + // TODO: fix all of those and then add Unmarshal to + // the Message interface. Then: + // The cast above and code below can be deleted. + // The old unmarshaler can be deleted. + // Clients can call Unmarshal directly (can already do that, actually). + var info InternalMessageInfo + err := info.Unmarshal(pb, p.buf[p.index:]) + p.index = len(p.buf) + return err +} diff --git a/vendor/github.com/gogo/protobuf/proto/deprecated.go b/vendor/github.com/gogo/protobuf/proto/deprecated.go new file mode 100644 index 00000000..35b882c0 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/deprecated.go @@ -0,0 +1,63 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2018 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import "errors" + +// Deprecated: do not use. +type Stats struct{ Emalloc, Dmalloc, Encode, Decode, Chit, Cmiss, Size uint64 } + +// Deprecated: do not use. +func GetStats() Stats { return Stats{} } + +// Deprecated: do not use. +func MarshalMessageSet(interface{}) ([]byte, error) { + return nil, errors.New("proto: not implemented") +} + +// Deprecated: do not use. +func UnmarshalMessageSet([]byte, interface{}) error { + return errors.New("proto: not implemented") +} + +// Deprecated: do not use. +func MarshalMessageSetJSON(interface{}) ([]byte, error) { + return nil, errors.New("proto: not implemented") +} + +// Deprecated: do not use. +func UnmarshalMessageSetJSON([]byte, interface{}) error { + return errors.New("proto: not implemented") +} + +// Deprecated: do not use. +func RegisterMessageSetType(Message, int32, string) {} diff --git a/vendor/github.com/gogo/protobuf/proto/discard.go b/vendor/github.com/gogo/protobuf/proto/discard.go new file mode 100644 index 00000000..fe1bd7d9 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/discard.go @@ -0,0 +1,350 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2017 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "fmt" + "reflect" + "strings" + "sync" + "sync/atomic" +) + +type generatedDiscarder interface { + XXX_DiscardUnknown() +} + +// DiscardUnknown recursively discards all unknown fields from this message +// and all embedded messages. +// +// When unmarshaling a message with unrecognized fields, the tags and values +// of such fields are preserved in the Message. This allows a later call to +// marshal to be able to produce a message that continues to have those +// unrecognized fields. To avoid this, DiscardUnknown is used to +// explicitly clear the unknown fields after unmarshaling. +// +// For proto2 messages, the unknown fields of message extensions are only +// discarded from messages that have been accessed via GetExtension. +func DiscardUnknown(m Message) { + if m, ok := m.(generatedDiscarder); ok { + m.XXX_DiscardUnknown() + return + } + // TODO: Dynamically populate a InternalMessageInfo for legacy messages, + // but the master branch has no implementation for InternalMessageInfo, + // so it would be more work to replicate that approach. + discardLegacy(m) +} + +// DiscardUnknown recursively discards all unknown fields. +func (a *InternalMessageInfo) DiscardUnknown(m Message) { + di := atomicLoadDiscardInfo(&a.discard) + if di == nil { + di = getDiscardInfo(reflect.TypeOf(m).Elem()) + atomicStoreDiscardInfo(&a.discard, di) + } + di.discard(toPointer(&m)) +} + +type discardInfo struct { + typ reflect.Type + + initialized int32 // 0: only typ is valid, 1: everything is valid + lock sync.Mutex + + fields []discardFieldInfo + unrecognized field +} + +type discardFieldInfo struct { + field field // Offset of field, guaranteed to be valid + discard func(src pointer) +} + +var ( + discardInfoMap = map[reflect.Type]*discardInfo{} + discardInfoLock sync.Mutex +) + +func getDiscardInfo(t reflect.Type) *discardInfo { + discardInfoLock.Lock() + defer discardInfoLock.Unlock() + di := discardInfoMap[t] + if di == nil { + di = &discardInfo{typ: t} + discardInfoMap[t] = di + } + return di +} + +func (di *discardInfo) discard(src pointer) { + if src.isNil() { + return // Nothing to do. + } + + if atomic.LoadInt32(&di.initialized) == 0 { + di.computeDiscardInfo() + } + + for _, fi := range di.fields { + sfp := src.offset(fi.field) + fi.discard(sfp) + } + + // For proto2 messages, only discard unknown fields in message extensions + // that have been accessed via GetExtension. + if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil { + // Ignore lock since DiscardUnknown is not concurrency safe. + emm, _ := em.extensionsRead() + for _, mx := range emm { + if m, ok := mx.value.(Message); ok { + DiscardUnknown(m) + } + } + } + + if di.unrecognized.IsValid() { + *src.offset(di.unrecognized).toBytes() = nil + } +} + +func (di *discardInfo) computeDiscardInfo() { + di.lock.Lock() + defer di.lock.Unlock() + if di.initialized != 0 { + return + } + t := di.typ + n := t.NumField() + + for i := 0; i < n; i++ { + f := t.Field(i) + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + + dfi := discardFieldInfo{field: toField(&f)} + tf := f.Type + + // Unwrap tf to get its most basic type. + var isPointer, isSlice bool + if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { + isSlice = true + tf = tf.Elem() + } + if tf.Kind() == reflect.Ptr { + isPointer = true + tf = tf.Elem() + } + if isPointer && isSlice && tf.Kind() != reflect.Struct { + panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name)) + } + + switch tf.Kind() { + case reflect.Struct: + switch { + case !isPointer: + panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name)) + case isSlice: // E.g., []*pb.T + discardInfo := getDiscardInfo(tf) + dfi.discard = func(src pointer) { + sps := src.getPointerSlice() + for _, sp := range sps { + if !sp.isNil() { + discardInfo.discard(sp) + } + } + } + default: // E.g., *pb.T + discardInfo := getDiscardInfo(tf) + dfi.discard = func(src pointer) { + sp := src.getPointer() + if !sp.isNil() { + discardInfo.discard(sp) + } + } + } + case reflect.Map: + switch { + case isPointer || isSlice: + panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name)) + default: // E.g., map[K]V + if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T) + dfi.discard = func(src pointer) { + sm := src.asPointerTo(tf).Elem() + if sm.Len() == 0 { + return + } + for _, key := range sm.MapKeys() { + val := sm.MapIndex(key) + DiscardUnknown(val.Interface().(Message)) + } + } + } else { + dfi.discard = func(pointer) {} // Noop + } + } + case reflect.Interface: + // Must be oneof field. + switch { + case isPointer || isSlice: + panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name)) + default: // E.g., interface{} + // TODO: Make this faster? + dfi.discard = func(src pointer) { + su := src.asPointerTo(tf).Elem() + if !su.IsNil() { + sv := su.Elem().Elem().Field(0) + if sv.Kind() == reflect.Ptr && sv.IsNil() { + return + } + switch sv.Type().Kind() { + case reflect.Ptr: // Proto struct (e.g., *T) + DiscardUnknown(sv.Interface().(Message)) + } + } + } + } + default: + continue + } + di.fields = append(di.fields, dfi) + } + + di.unrecognized = invalidField + if f, ok := t.FieldByName("XXX_unrecognized"); ok { + if f.Type != reflect.TypeOf([]byte{}) { + panic("expected XXX_unrecognized to be of type []byte") + } + di.unrecognized = toField(&f) + } + + atomic.StoreInt32(&di.initialized, 1) +} + +func discardLegacy(m Message) { + v := reflect.ValueOf(m) + if v.Kind() != reflect.Ptr || v.IsNil() { + return + } + v = v.Elem() + if v.Kind() != reflect.Struct { + return + } + t := v.Type() + + for i := 0; i < v.NumField(); i++ { + f := t.Field(i) + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + vf := v.Field(i) + tf := f.Type + + // Unwrap tf to get its most basic type. + var isPointer, isSlice bool + if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { + isSlice = true + tf = tf.Elem() + } + if tf.Kind() == reflect.Ptr { + isPointer = true + tf = tf.Elem() + } + if isPointer && isSlice && tf.Kind() != reflect.Struct { + panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name)) + } + + switch tf.Kind() { + case reflect.Struct: + switch { + case !isPointer: + panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name)) + case isSlice: // E.g., []*pb.T + for j := 0; j < vf.Len(); j++ { + discardLegacy(vf.Index(j).Interface().(Message)) + } + default: // E.g., *pb.T + discardLegacy(vf.Interface().(Message)) + } + case reflect.Map: + switch { + case isPointer || isSlice: + panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name)) + default: // E.g., map[K]V + tv := vf.Type().Elem() + if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T) + for _, key := range vf.MapKeys() { + val := vf.MapIndex(key) + discardLegacy(val.Interface().(Message)) + } + } + } + case reflect.Interface: + // Must be oneof field. + switch { + case isPointer || isSlice: + panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name)) + default: // E.g., test_proto.isCommunique_Union interface + if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" { + vf = vf.Elem() // E.g., *test_proto.Communique_Msg + if !vf.IsNil() { + vf = vf.Elem() // E.g., test_proto.Communique_Msg + vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value + if vf.Kind() == reflect.Ptr { + discardLegacy(vf.Interface().(Message)) + } + } + } + } + } + } + + if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() { + if vf.Type() != reflect.TypeOf([]byte{}) { + panic("expected XXX_unrecognized to be of type []byte") + } + vf.Set(reflect.ValueOf([]byte(nil))) + } + + // For proto2 messages, only discard unknown fields in message extensions + // that have been accessed via GetExtension. + if em, err := extendable(m); err == nil { + // Ignore lock since discardLegacy is not concurrency safe. + emm, _ := em.extensionsRead() + for _, mx := range emm { + if m, ok := mx.value.(Message); ok { + discardLegacy(m) + } + } + } +} diff --git a/vendor/github.com/gogo/protobuf/proto/duration.go b/vendor/github.com/gogo/protobuf/proto/duration.go new file mode 100644 index 00000000..93464c91 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/duration.go @@ -0,0 +1,100 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2016 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +// This file implements conversions between google.protobuf.Duration +// and time.Duration. + +import ( + "errors" + "fmt" + "time" +) + +const ( + // Range of a Duration in seconds, as specified in + // google/protobuf/duration.proto. This is about 10,000 years in seconds. + maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60) + minSeconds = -maxSeconds +) + +// validateDuration determines whether the Duration is valid according to the +// definition in google/protobuf/duration.proto. A valid Duration +// may still be too large to fit into a time.Duration (the range of Duration +// is about 10,000 years, and the range of time.Duration is about 290). +func validateDuration(d *duration) error { + if d == nil { + return errors.New("duration: nil Duration") + } + if d.Seconds < minSeconds || d.Seconds > maxSeconds { + return fmt.Errorf("duration: %#v: seconds out of range", d) + } + if d.Nanos <= -1e9 || d.Nanos >= 1e9 { + return fmt.Errorf("duration: %#v: nanos out of range", d) + } + // Seconds and Nanos must have the same sign, unless d.Nanos is zero. + if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) { + return fmt.Errorf("duration: %#v: seconds and nanos have different signs", d) + } + return nil +} + +// DurationFromProto converts a Duration to a time.Duration. DurationFromProto +// returns an error if the Duration is invalid or is too large to be +// represented in a time.Duration. +func durationFromProto(p *duration) (time.Duration, error) { + if err := validateDuration(p); err != nil { + return 0, err + } + d := time.Duration(p.Seconds) * time.Second + if int64(d/time.Second) != p.Seconds { + return 0, fmt.Errorf("duration: %#v is out of range for time.Duration", p) + } + if p.Nanos != 0 { + d += time.Duration(p.Nanos) + if (d < 0) != (p.Nanos < 0) { + return 0, fmt.Errorf("duration: %#v is out of range for time.Duration", p) + } + } + return d, nil +} + +// DurationProto converts a time.Duration to a Duration. +func durationProto(d time.Duration) *duration { + nanos := d.Nanoseconds() + secs := nanos / 1e9 + nanos -= secs * 1e9 + return &duration{ + Seconds: secs, + Nanos: int32(nanos), + } +} diff --git a/vendor/github.com/gogo/protobuf/proto/duration_gogo.go b/vendor/github.com/gogo/protobuf/proto/duration_gogo.go new file mode 100644 index 00000000..e748e173 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/duration_gogo.go @@ -0,0 +1,49 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2016, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "reflect" + "time" +) + +var durationType = reflect.TypeOf((*time.Duration)(nil)).Elem() + +type duration struct { + Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` + Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` +} + +func (m *duration) Reset() { *m = duration{} } +func (*duration) ProtoMessage() {} +func (*duration) String() string { return "duration" } + +func init() { + RegisterType((*duration)(nil), "gogo.protobuf.proto.duration") +} diff --git a/vendor/github.com/gogo/protobuf/proto/encode.go b/vendor/github.com/gogo/protobuf/proto/encode.go new file mode 100644 index 00000000..9581ccd3 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/encode.go @@ -0,0 +1,205 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Routines for encoding data into the wire format for protocol buffers. + */ + +import ( + "errors" + "reflect" +) + +var ( + // errRepeatedHasNil is the error returned if Marshal is called with + // a struct with a repeated field containing a nil element. + errRepeatedHasNil = errors.New("proto: repeated field has nil element") + + // errOneofHasNil is the error returned if Marshal is called with + // a struct with a oneof field containing a nil element. + errOneofHasNil = errors.New("proto: oneof field has nil value") + + // ErrNil is the error returned if Marshal is called with nil. + ErrNil = errors.New("proto: Marshal called with nil") + + // ErrTooLarge is the error returned if Marshal is called with a + // message that encodes to >2GB. + ErrTooLarge = errors.New("proto: message encodes to over 2 GB") +) + +// The fundamental encoders that put bytes on the wire. +// Those that take integer types all accept uint64 and are +// therefore of type valueEncoder. + +const maxVarintBytes = 10 // maximum length of a varint + +// EncodeVarint returns the varint encoding of x. +// This is the format for the +// int32, int64, uint32, uint64, bool, and enum +// protocol buffer types. +// Not used by the package itself, but helpful to clients +// wishing to use the same encoding. +func EncodeVarint(x uint64) []byte { + var buf [maxVarintBytes]byte + var n int + for n = 0; x > 127; n++ { + buf[n] = 0x80 | uint8(x&0x7F) + x >>= 7 + } + buf[n] = uint8(x) + n++ + return buf[0:n] +} + +// EncodeVarint writes a varint-encoded integer to the Buffer. +// This is the format for the +// int32, int64, uint32, uint64, bool, and enum +// protocol buffer types. +func (p *Buffer) EncodeVarint(x uint64) error { + for x >= 1<<7 { + p.buf = append(p.buf, uint8(x&0x7f|0x80)) + x >>= 7 + } + p.buf = append(p.buf, uint8(x)) + return nil +} + +// SizeVarint returns the varint encoding size of an integer. +func SizeVarint(x uint64) int { + switch { + case x < 1<<7: + return 1 + case x < 1<<14: + return 2 + case x < 1<<21: + return 3 + case x < 1<<28: + return 4 + case x < 1<<35: + return 5 + case x < 1<<42: + return 6 + case x < 1<<49: + return 7 + case x < 1<<56: + return 8 + case x < 1<<63: + return 9 + } + return 10 +} + +// EncodeFixed64 writes a 64-bit integer to the Buffer. +// This is the format for the +// fixed64, sfixed64, and double protocol buffer types. +func (p *Buffer) EncodeFixed64(x uint64) error { + p.buf = append(p.buf, + uint8(x), + uint8(x>>8), + uint8(x>>16), + uint8(x>>24), + uint8(x>>32), + uint8(x>>40), + uint8(x>>48), + uint8(x>>56)) + return nil +} + +// EncodeFixed32 writes a 32-bit integer to the Buffer. +// This is the format for the +// fixed32, sfixed32, and float protocol buffer types. +func (p *Buffer) EncodeFixed32(x uint64) error { + p.buf = append(p.buf, + uint8(x), + uint8(x>>8), + uint8(x>>16), + uint8(x>>24)) + return nil +} + +// EncodeZigzag64 writes a zigzag-encoded 64-bit integer +// to the Buffer. +// This is the format used for the sint64 protocol buffer type. +func (p *Buffer) EncodeZigzag64(x uint64) error { + // use signed number to get arithmetic right shift. + return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} + +// EncodeZigzag32 writes a zigzag-encoded 32-bit integer +// to the Buffer. +// This is the format used for the sint32 protocol buffer type. +func (p *Buffer) EncodeZigzag32(x uint64) error { + // use signed number to get arithmetic right shift. + return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) +} + +// EncodeRawBytes writes a count-delimited byte buffer to the Buffer. +// This is the format used for the bytes protocol buffer +// type and for embedded messages. +func (p *Buffer) EncodeRawBytes(b []byte) error { + p.EncodeVarint(uint64(len(b))) + p.buf = append(p.buf, b...) + return nil +} + +// EncodeStringBytes writes an encoded string to the Buffer. +// This is the format used for the proto2 string type. +func (p *Buffer) EncodeStringBytes(s string) error { + p.EncodeVarint(uint64(len(s))) + p.buf = append(p.buf, s...) + return nil +} + +// Marshaler is the interface representing objects that can marshal themselves. +type Marshaler interface { + Marshal() ([]byte, error) +} + +// EncodeMessage writes the protocol buffer to the Buffer, +// prefixed by a varint-encoded length. +func (p *Buffer) EncodeMessage(pb Message) error { + siz := Size(pb) + sizVar := SizeVarint(uint64(siz)) + p.grow(siz + sizVar) + p.EncodeVarint(uint64(siz)) + return p.Marshal(pb) +} + +// All protocol buffer fields are nillable, but be careful. +func isNil(v reflect.Value) bool { + switch v.Kind() { + case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + return v.IsNil() + } + return false +} diff --git a/vendor/github.com/gogo/protobuf/proto/encode_gogo.go b/vendor/github.com/gogo/protobuf/proto/encode_gogo.go new file mode 100644 index 00000000..0f5fb173 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/encode_gogo.go @@ -0,0 +1,33 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +func NewRequiredNotSetError(field string) *RequiredNotSetError { + return &RequiredNotSetError{field} +} diff --git a/vendor/github.com/gogo/protobuf/proto/equal.go b/vendor/github.com/gogo/protobuf/proto/equal.go new file mode 100644 index 00000000..d4db5a1c --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/equal.go @@ -0,0 +1,300 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2011 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Protocol buffer comparison. + +package proto + +import ( + "bytes" + "log" + "reflect" + "strings" +) + +/* +Equal returns true iff protocol buffers a and b are equal. +The arguments must both be pointers to protocol buffer structs. + +Equality is defined in this way: + - Two messages are equal iff they are the same type, + corresponding fields are equal, unknown field sets + are equal, and extensions sets are equal. + - Two set scalar fields are equal iff their values are equal. + If the fields are of a floating-point type, remember that + NaN != x for all x, including NaN. If the message is defined + in a proto3 .proto file, fields are not "set"; specifically, + zero length proto3 "bytes" fields are equal (nil == {}). + - Two repeated fields are equal iff their lengths are the same, + and their corresponding elements are equal. Note a "bytes" field, + although represented by []byte, is not a repeated field and the + rule for the scalar fields described above applies. + - Two unset fields are equal. + - Two unknown field sets are equal if their current + encoded state is equal. + - Two extension sets are equal iff they have corresponding + elements that are pairwise equal. + - Two map fields are equal iff their lengths are the same, + and they contain the same set of elements. Zero-length map + fields are equal. + - Every other combination of things are not equal. + +The return value is undefined if a and b are not protocol buffers. +*/ +func Equal(a, b Message) bool { + if a == nil || b == nil { + return a == b + } + v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b) + if v1.Type() != v2.Type() { + return false + } + if v1.Kind() == reflect.Ptr { + if v1.IsNil() { + return v2.IsNil() + } + if v2.IsNil() { + return false + } + v1, v2 = v1.Elem(), v2.Elem() + } + if v1.Kind() != reflect.Struct { + return false + } + return equalStruct(v1, v2) +} + +// v1 and v2 are known to have the same type. +func equalStruct(v1, v2 reflect.Value) bool { + sprop := GetProperties(v1.Type()) + for i := 0; i < v1.NumField(); i++ { + f := v1.Type().Field(i) + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + f1, f2 := v1.Field(i), v2.Field(i) + if f.Type.Kind() == reflect.Ptr { + if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 { + // both unset + continue + } else if n1 != n2 { + // set/unset mismatch + return false + } + f1, f2 = f1.Elem(), f2.Elem() + } + if !equalAny(f1, f2, sprop.Prop[i]) { + return false + } + } + + if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() { + em2 := v2.FieldByName("XXX_InternalExtensions") + if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) { + return false + } + } + + if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { + em2 := v2.FieldByName("XXX_extensions") + if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { + return false + } + } + + uf := v1.FieldByName("XXX_unrecognized") + if !uf.IsValid() { + return true + } + + u1 := uf.Bytes() + u2 := v2.FieldByName("XXX_unrecognized").Bytes() + return bytes.Equal(u1, u2) +} + +// v1 and v2 are known to have the same type. +// prop may be nil. +func equalAny(v1, v2 reflect.Value, prop *Properties) bool { + if v1.Type() == protoMessageType { + m1, _ := v1.Interface().(Message) + m2, _ := v2.Interface().(Message) + return Equal(m1, m2) + } + switch v1.Kind() { + case reflect.Bool: + return v1.Bool() == v2.Bool() + case reflect.Float32, reflect.Float64: + return v1.Float() == v2.Float() + case reflect.Int32, reflect.Int64: + return v1.Int() == v2.Int() + case reflect.Interface: + // Probably a oneof field; compare the inner values. + n1, n2 := v1.IsNil(), v2.IsNil() + if n1 || n2 { + return n1 == n2 + } + e1, e2 := v1.Elem(), v2.Elem() + if e1.Type() != e2.Type() { + return false + } + return equalAny(e1, e2, nil) + case reflect.Map: + if v1.Len() != v2.Len() { + return false + } + for _, key := range v1.MapKeys() { + val2 := v2.MapIndex(key) + if !val2.IsValid() { + // This key was not found in the second map. + return false + } + if !equalAny(v1.MapIndex(key), val2, nil) { + return false + } + } + return true + case reflect.Ptr: + // Maps may have nil values in them, so check for nil. + if v1.IsNil() && v2.IsNil() { + return true + } + if v1.IsNil() != v2.IsNil() { + return false + } + return equalAny(v1.Elem(), v2.Elem(), prop) + case reflect.Slice: + if v1.Type().Elem().Kind() == reflect.Uint8 { + // short circuit: []byte + + // Edge case: if this is in a proto3 message, a zero length + // bytes field is considered the zero value. + if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 { + return true + } + if v1.IsNil() != v2.IsNil() { + return false + } + return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte)) + } + + if v1.Len() != v2.Len() { + return false + } + for i := 0; i < v1.Len(); i++ { + if !equalAny(v1.Index(i), v2.Index(i), prop) { + return false + } + } + return true + case reflect.String: + return v1.Interface().(string) == v2.Interface().(string) + case reflect.Struct: + return equalStruct(v1, v2) + case reflect.Uint32, reflect.Uint64: + return v1.Uint() == v2.Uint() + } + + // unknown type, so not a protocol buffer + log.Printf("proto: don't know how to compare %v", v1) + return false +} + +// base is the struct type that the extensions are based on. +// x1 and x2 are InternalExtensions. +func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool { + em1, _ := x1.extensionsRead() + em2, _ := x2.extensionsRead() + return equalExtMap(base, em1, em2) +} + +func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool { + if len(em1) != len(em2) { + return false + } + + for extNum, e1 := range em1 { + e2, ok := em2[extNum] + if !ok { + return false + } + + m1, m2 := e1.value, e2.value + + if m1 == nil && m2 == nil { + // Both have only encoded form. + if bytes.Equal(e1.enc, e2.enc) { + continue + } + // The bytes are different, but the extensions might still be + // equal. We need to decode them to compare. + } + + if m1 != nil && m2 != nil { + // Both are unencoded. + if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { + return false + } + continue + } + + // At least one is encoded. To do a semantically correct comparison + // we need to unmarshal them first. + var desc *ExtensionDesc + if m := extensionMaps[base]; m != nil { + desc = m[extNum] + } + if desc == nil { + // If both have only encoded form and the bytes are the same, + // it is handled above. We get here when the bytes are different. + // We don't know how to decode it, so just compare them as byte + // slices. + log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) + return false + } + var err error + if m1 == nil { + m1, err = decodeExtension(e1.enc, desc) + } + if m2 == nil && err == nil { + m2, err = decodeExtension(e2.enc, desc) + } + if err != nil { + // The encoded form is invalid. + log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) + return false + } + if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { + return false + } + } + + return true +} diff --git a/vendor/github.com/gogo/protobuf/proto/extensions.go b/vendor/github.com/gogo/protobuf/proto/extensions.go new file mode 100644 index 00000000..341c6f57 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/extensions.go @@ -0,0 +1,605 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Types and routines for supporting protocol buffer extensions. + */ + +import ( + "errors" + "fmt" + "io" + "reflect" + "strconv" + "sync" +) + +// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message. +var ErrMissingExtension = errors.New("proto: missing extension") + +// ExtensionRange represents a range of message extensions for a protocol buffer. +// Used in code generated by the protocol compiler. +type ExtensionRange struct { + Start, End int32 // both inclusive +} + +// extendableProto is an interface implemented by any protocol buffer generated by the current +// proto compiler that may be extended. +type extendableProto interface { + Message + ExtensionRangeArray() []ExtensionRange + extensionsWrite() map[int32]Extension + extensionsRead() (map[int32]Extension, sync.Locker) +} + +// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous +// version of the proto compiler that may be extended. +type extendableProtoV1 interface { + Message + ExtensionRangeArray() []ExtensionRange + ExtensionMap() map[int32]Extension +} + +// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto. +type extensionAdapter struct { + extendableProtoV1 +} + +func (e extensionAdapter) extensionsWrite() map[int32]Extension { + return e.ExtensionMap() +} + +func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) { + return e.ExtensionMap(), notLocker{} +} + +// notLocker is a sync.Locker whose Lock and Unlock methods are nops. +type notLocker struct{} + +func (n notLocker) Lock() {} +func (n notLocker) Unlock() {} + +// extendable returns the extendableProto interface for the given generated proto message. +// If the proto message has the old extension format, it returns a wrapper that implements +// the extendableProto interface. +func extendable(p interface{}) (extendableProto, error) { + switch p := p.(type) { + case extendableProto: + if isNilPtr(p) { + return nil, fmt.Errorf("proto: nil %T is not extendable", p) + } + return p, nil + case extendableProtoV1: + if isNilPtr(p) { + return nil, fmt.Errorf("proto: nil %T is not extendable", p) + } + return extensionAdapter{p}, nil + case extensionsBytes: + return slowExtensionAdapter{p}, nil + } + // Don't allocate a specific error containing %T: + // this is the hot path for Clone and MarshalText. + return nil, errNotExtendable +} + +var errNotExtendable = errors.New("proto: not an extendable proto.Message") + +func isNilPtr(x interface{}) bool { + v := reflect.ValueOf(x) + return v.Kind() == reflect.Ptr && v.IsNil() +} + +// XXX_InternalExtensions is an internal representation of proto extensions. +// +// Each generated message struct type embeds an anonymous XXX_InternalExtensions field, +// thus gaining the unexported 'extensions' method, which can be called only from the proto package. +// +// The methods of XXX_InternalExtensions are not concurrency safe in general, +// but calls to logically read-only methods such as has and get may be executed concurrently. +type XXX_InternalExtensions struct { + // The struct must be indirect so that if a user inadvertently copies a + // generated message and its embedded XXX_InternalExtensions, they + // avoid the mayhem of a copied mutex. + // + // The mutex serializes all logically read-only operations to p.extensionMap. + // It is up to the client to ensure that write operations to p.extensionMap are + // mutually exclusive with other accesses. + p *struct { + mu sync.Mutex + extensionMap map[int32]Extension + } +} + +// extensionsWrite returns the extension map, creating it on first use. +func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension { + if e.p == nil { + e.p = new(struct { + mu sync.Mutex + extensionMap map[int32]Extension + }) + e.p.extensionMap = make(map[int32]Extension) + } + return e.p.extensionMap +} + +// extensionsRead returns the extensions map for read-only use. It may be nil. +// The caller must hold the returned mutex's lock when accessing Elements within the map. +func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) { + if e.p == nil { + return nil, nil + } + return e.p.extensionMap, &e.p.mu +} + +// ExtensionDesc represents an extension specification. +// Used in generated code from the protocol compiler. +type ExtensionDesc struct { + ExtendedType Message // nil pointer to the type that is being extended + ExtensionType interface{} // nil pointer to the extension type + Field int32 // field number + Name string // fully-qualified name of extension, for text formatting + Tag string // protobuf tag style + Filename string // name of the file in which the extension is defined +} + +func (ed *ExtensionDesc) repeated() bool { + t := reflect.TypeOf(ed.ExtensionType) + return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 +} + +// Extension represents an extension in a message. +type Extension struct { + // When an extension is stored in a message using SetExtension + // only desc and value are set. When the message is marshaled + // enc will be set to the encoded form of the message. + // + // When a message is unmarshaled and contains extensions, each + // extension will have only enc set. When such an extension is + // accessed using GetExtension (or GetExtensions) desc and value + // will be set. + desc *ExtensionDesc + value interface{} + enc []byte +} + +// SetRawExtension is for testing only. +func SetRawExtension(base Message, id int32, b []byte) { + if ebase, ok := base.(extensionsBytes); ok { + clearExtension(base, id) + ext := ebase.GetExtensions() + *ext = append(*ext, b...) + return + } + epb, err := extendable(base) + if err != nil { + return + } + extmap := epb.extensionsWrite() + extmap[id] = Extension{enc: b} +} + +// isExtensionField returns true iff the given field number is in an extension range. +func isExtensionField(pb extendableProto, field int32) bool { + for _, er := range pb.ExtensionRangeArray() { + if er.Start <= field && field <= er.End { + return true + } + } + return false +} + +// checkExtensionTypes checks that the given extension is valid for pb. +func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error { + var pbi interface{} = pb + // Check the extended type. + if ea, ok := pbi.(extensionAdapter); ok { + pbi = ea.extendableProtoV1 + } + if ea, ok := pbi.(slowExtensionAdapter); ok { + pbi = ea.extensionsBytes + } + if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b { + return fmt.Errorf("proto: bad extended type; %v does not extend %v", b, a) + } + // Check the range. + if !isExtensionField(pb, extension.Field) { + return errors.New("proto: bad extension number; not in declared ranges") + } + return nil +} + +// extPropKey is sufficient to uniquely identify an extension. +type extPropKey struct { + base reflect.Type + field int32 +} + +var extProp = struct { + sync.RWMutex + m map[extPropKey]*Properties +}{ + m: make(map[extPropKey]*Properties), +} + +func extensionProperties(ed *ExtensionDesc) *Properties { + key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field} + + extProp.RLock() + if prop, ok := extProp.m[key]; ok { + extProp.RUnlock() + return prop + } + extProp.RUnlock() + + extProp.Lock() + defer extProp.Unlock() + // Check again. + if prop, ok := extProp.m[key]; ok { + return prop + } + + prop := new(Properties) + prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil) + extProp.m[key] = prop + return prop +} + +// HasExtension returns whether the given extension is present in pb. +func HasExtension(pb Message, extension *ExtensionDesc) bool { + if epb, doki := pb.(extensionsBytes); doki { + ext := epb.GetExtensions() + buf := *ext + o := 0 + for o < len(buf) { + tag, n := DecodeVarint(buf[o:]) + fieldNum := int32(tag >> 3) + if int32(fieldNum) == extension.Field { + return true + } + wireType := int(tag & 0x7) + o += n + l, err := size(buf[o:], wireType) + if err != nil { + return false + } + o += l + } + return false + } + // TODO: Check types, field numbers, etc.? + epb, err := extendable(pb) + if err != nil { + return false + } + extmap, mu := epb.extensionsRead() + if extmap == nil { + return false + } + mu.Lock() + _, ok := extmap[extension.Field] + mu.Unlock() + return ok +} + +// ClearExtension removes the given extension from pb. +func ClearExtension(pb Message, extension *ExtensionDesc) { + clearExtension(pb, extension.Field) +} + +func clearExtension(pb Message, fieldNum int32) { + if epb, ok := pb.(extensionsBytes); ok { + offset := 0 + for offset != -1 { + offset = deleteExtension(epb, fieldNum, offset) + } + return + } + epb, err := extendable(pb) + if err != nil { + return + } + // TODO: Check types, field numbers, etc.? + extmap := epb.extensionsWrite() + delete(extmap, fieldNum) +} + +// GetExtension retrieves a proto2 extended field from pb. +// +// If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil), +// then GetExtension parses the encoded field and returns a Go value of the specified type. +// If the field is not present, then the default value is returned (if one is specified), +// otherwise ErrMissingExtension is reported. +// +// If the descriptor is not type complete (i.e., ExtensionDesc.ExtensionType is nil), +// then GetExtension returns the raw encoded bytes of the field extension. +func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) { + if epb, doki := pb.(extensionsBytes); doki { + ext := epb.GetExtensions() + return decodeExtensionFromBytes(extension, *ext) + } + + epb, err := extendable(pb) + if err != nil { + return nil, err + } + + if extension.ExtendedType != nil { + // can only check type if this is a complete descriptor + if cerr := checkExtensionTypes(epb, extension); cerr != nil { + return nil, cerr + } + } + + emap, mu := epb.extensionsRead() + if emap == nil { + return defaultExtensionValue(extension) + } + mu.Lock() + defer mu.Unlock() + e, ok := emap[extension.Field] + if !ok { + // defaultExtensionValue returns the default value or + // ErrMissingExtension if there is no default. + return defaultExtensionValue(extension) + } + + if e.value != nil { + // Already decoded. Check the descriptor, though. + if e.desc != extension { + // This shouldn't happen. If it does, it means that + // GetExtension was called twice with two different + // descriptors with the same field number. + return nil, errors.New("proto: descriptor conflict") + } + return e.value, nil + } + + if extension.ExtensionType == nil { + // incomplete descriptor + return e.enc, nil + } + + v, err := decodeExtension(e.enc, extension) + if err != nil { + return nil, err + } + + // Remember the decoded version and drop the encoded version. + // That way it is safe to mutate what we return. + e.value = v + e.desc = extension + e.enc = nil + emap[extension.Field] = e + return e.value, nil +} + +// defaultExtensionValue returns the default value for extension. +// If no default for an extension is defined ErrMissingExtension is returned. +func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) { + if extension.ExtensionType == nil { + // incomplete descriptor, so no default + return nil, ErrMissingExtension + } + + t := reflect.TypeOf(extension.ExtensionType) + props := extensionProperties(extension) + + sf, _, err := fieldDefault(t, props) + if err != nil { + return nil, err + } + + if sf == nil || sf.value == nil { + // There is no default value. + return nil, ErrMissingExtension + } + + if t.Kind() != reflect.Ptr { + // We do not need to return a Ptr, we can directly return sf.value. + return sf.value, nil + } + + // We need to return an interface{} that is a pointer to sf.value. + value := reflect.New(t).Elem() + value.Set(reflect.New(value.Type().Elem())) + if sf.kind == reflect.Int32 { + // We may have an int32 or an enum, but the underlying data is int32. + // Since we can't set an int32 into a non int32 reflect.value directly + // set it as a int32. + value.Elem().SetInt(int64(sf.value.(int32))) + } else { + value.Elem().Set(reflect.ValueOf(sf.value)) + } + return value.Interface(), nil +} + +// decodeExtension decodes an extension encoded in b. +func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { + t := reflect.TypeOf(extension.ExtensionType) + unmarshal := typeUnmarshaler(t, extension.Tag) + + // t is a pointer to a struct, pointer to basic type or a slice. + // Allocate space to store the pointer/slice. + value := reflect.New(t).Elem() + + var err error + for { + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + wire := int(x) & 7 + + b, err = unmarshal(b, valToPointer(value.Addr()), wire) + if err != nil { + return nil, err + } + + if len(b) == 0 { + break + } + } + return value.Interface(), nil +} + +// GetExtensions returns a slice of the extensions present in pb that are also listed in es. +// The returned slice has the same length as es; missing extensions will appear as nil elements. +func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) { + epb, err := extendable(pb) + if err != nil { + return nil, err + } + extensions = make([]interface{}, len(es)) + for i, e := range es { + extensions[i], err = GetExtension(epb, e) + if err == ErrMissingExtension { + err = nil + } + if err != nil { + return + } + } + return +} + +// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order. +// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing +// just the Field field, which defines the extension's field number. +func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { + epb, err := extendable(pb) + if err != nil { + return nil, err + } + registeredExtensions := RegisteredExtensions(pb) + + emap, mu := epb.extensionsRead() + if emap == nil { + return nil, nil + } + mu.Lock() + defer mu.Unlock() + extensions := make([]*ExtensionDesc, 0, len(emap)) + for extid, e := range emap { + desc := e.desc + if desc == nil { + desc = registeredExtensions[extid] + if desc == nil { + desc = &ExtensionDesc{Field: extid} + } + } + + extensions = append(extensions, desc) + } + return extensions, nil +} + +// SetExtension sets the specified extension of pb to the specified value. +func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error { + if epb, ok := pb.(extensionsBytes); ok { + ClearExtension(pb, extension) + newb, err := encodeExtension(extension, value) + if err != nil { + return err + } + bb := epb.GetExtensions() + *bb = append(*bb, newb...) + return nil + } + epb, err := extendable(pb) + if err != nil { + return err + } + if err := checkExtensionTypes(epb, extension); err != nil { + return err + } + typ := reflect.TypeOf(extension.ExtensionType) + if typ != reflect.TypeOf(value) { + return fmt.Errorf("proto: bad extension value type. got: %T, want: %T", value, extension.ExtensionType) + } + // nil extension values need to be caught early, because the + // encoder can't distinguish an ErrNil due to a nil extension + // from an ErrNil due to a missing field. Extensions are + // always optional, so the encoder would just swallow the error + // and drop all the extensions from the encoded message. + if reflect.ValueOf(value).IsNil() { + return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) + } + + extmap := epb.extensionsWrite() + extmap[extension.Field] = Extension{desc: extension, value: value} + return nil +} + +// ClearAllExtensions clears all extensions from pb. +func ClearAllExtensions(pb Message) { + if epb, doki := pb.(extensionsBytes); doki { + ext := epb.GetExtensions() + *ext = []byte{} + return + } + epb, err := extendable(pb) + if err != nil { + return + } + m := epb.extensionsWrite() + for k := range m { + delete(m, k) + } +} + +// A global registry of extensions. +// The generated code will register the generated descriptors by calling RegisterExtension. + +var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc) + +// RegisterExtension is called from the generated code. +func RegisterExtension(desc *ExtensionDesc) { + st := reflect.TypeOf(desc.ExtendedType).Elem() + m := extensionMaps[st] + if m == nil { + m = make(map[int32]*ExtensionDesc) + extensionMaps[st] = m + } + if _, ok := m[desc.Field]; ok { + panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field))) + } + m[desc.Field] = desc +} + +// RegisteredExtensions returns a map of the registered extensions of a +// protocol buffer struct, indexed by the extension number. +// The argument pb should be a nil pointer to the struct type. +func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc { + return extensionMaps[reflect.TypeOf(pb).Elem()] +} diff --git a/vendor/github.com/gogo/protobuf/proto/extensions_gogo.go b/vendor/github.com/gogo/protobuf/proto/extensions_gogo.go new file mode 100644 index 00000000..6f1ae120 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/extensions_gogo.go @@ -0,0 +1,389 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "bytes" + "errors" + "fmt" + "io" + "reflect" + "sort" + "strings" + "sync" +) + +type extensionsBytes interface { + Message + ExtensionRangeArray() []ExtensionRange + GetExtensions() *[]byte +} + +type slowExtensionAdapter struct { + extensionsBytes +} + +func (s slowExtensionAdapter) extensionsWrite() map[int32]Extension { + panic("Please report a bug to github.com/gogo/protobuf if you see this message: Writing extensions is not supported for extensions stored in a byte slice field.") +} + +func (s slowExtensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) { + b := s.GetExtensions() + m, err := BytesToExtensionsMap(*b) + if err != nil { + panic(err) + } + return m, notLocker{} +} + +func GetBoolExtension(pb Message, extension *ExtensionDesc, ifnotset bool) bool { + if reflect.ValueOf(pb).IsNil() { + return ifnotset + } + value, err := GetExtension(pb, extension) + if err != nil { + return ifnotset + } + if value == nil { + return ifnotset + } + if value.(*bool) == nil { + return ifnotset + } + return *(value.(*bool)) +} + +func (this *Extension) Equal(that *Extension) bool { + if err := this.Encode(); err != nil { + return false + } + if err := that.Encode(); err != nil { + return false + } + return bytes.Equal(this.enc, that.enc) +} + +func (this *Extension) Compare(that *Extension) int { + if err := this.Encode(); err != nil { + return 1 + } + if err := that.Encode(); err != nil { + return -1 + } + return bytes.Compare(this.enc, that.enc) +} + +func SizeOfInternalExtension(m extendableProto) (n int) { + info := getMarshalInfo(reflect.TypeOf(m)) + return info.sizeV1Extensions(m.extensionsWrite()) +} + +type sortableMapElem struct { + field int32 + ext Extension +} + +func newSortableExtensionsFromMap(m map[int32]Extension) sortableExtensions { + s := make(sortableExtensions, 0, len(m)) + for k, v := range m { + s = append(s, &sortableMapElem{field: k, ext: v}) + } + return s +} + +type sortableExtensions []*sortableMapElem + +func (this sortableExtensions) Len() int { return len(this) } + +func (this sortableExtensions) Swap(i, j int) { this[i], this[j] = this[j], this[i] } + +func (this sortableExtensions) Less(i, j int) bool { return this[i].field < this[j].field } + +func (this sortableExtensions) String() string { + sort.Sort(this) + ss := make([]string, len(this)) + for i := range this { + ss[i] = fmt.Sprintf("%d: %v", this[i].field, this[i].ext) + } + return "map[" + strings.Join(ss, ",") + "]" +} + +func StringFromInternalExtension(m extendableProto) string { + return StringFromExtensionsMap(m.extensionsWrite()) +} + +func StringFromExtensionsMap(m map[int32]Extension) string { + return newSortableExtensionsFromMap(m).String() +} + +func StringFromExtensionsBytes(ext []byte) string { + m, err := BytesToExtensionsMap(ext) + if err != nil { + panic(err) + } + return StringFromExtensionsMap(m) +} + +func EncodeInternalExtension(m extendableProto, data []byte) (n int, err error) { + return EncodeExtensionMap(m.extensionsWrite(), data) +} + +func EncodeInternalExtensionBackwards(m extendableProto, data []byte) (n int, err error) { + return EncodeExtensionMapBackwards(m.extensionsWrite(), data) +} + +func EncodeExtensionMap(m map[int32]Extension, data []byte) (n int, err error) { + o := 0 + for _, e := range m { + if err := e.Encode(); err != nil { + return 0, err + } + n := copy(data[o:], e.enc) + if n != len(e.enc) { + return 0, io.ErrShortBuffer + } + o += n + } + return o, nil +} + +func EncodeExtensionMapBackwards(m map[int32]Extension, data []byte) (n int, err error) { + o := 0 + end := len(data) + for _, e := range m { + if err := e.Encode(); err != nil { + return 0, err + } + n := copy(data[end-len(e.enc):], e.enc) + if n != len(e.enc) { + return 0, io.ErrShortBuffer + } + end -= n + o += n + } + return o, nil +} + +func GetRawExtension(m map[int32]Extension, id int32) ([]byte, error) { + e := m[id] + if err := e.Encode(); err != nil { + return nil, err + } + return e.enc, nil +} + +func size(buf []byte, wire int) (int, error) { + switch wire { + case WireVarint: + _, n := DecodeVarint(buf) + return n, nil + case WireFixed64: + return 8, nil + case WireBytes: + v, n := DecodeVarint(buf) + return int(v) + n, nil + case WireFixed32: + return 4, nil + case WireStartGroup: + offset := 0 + for { + u, n := DecodeVarint(buf[offset:]) + fwire := int(u & 0x7) + offset += n + if fwire == WireEndGroup { + return offset, nil + } + s, err := size(buf[offset:], wire) + if err != nil { + return 0, err + } + offset += s + } + } + return 0, fmt.Errorf("proto: can't get size for unknown wire type %d", wire) +} + +func BytesToExtensionsMap(buf []byte) (map[int32]Extension, error) { + m := make(map[int32]Extension) + i := 0 + for i < len(buf) { + tag, n := DecodeVarint(buf[i:]) + if n <= 0 { + return nil, fmt.Errorf("unable to decode varint") + } + fieldNum := int32(tag >> 3) + wireType := int(tag & 0x7) + l, err := size(buf[i+n:], wireType) + if err != nil { + return nil, err + } + end := i + int(l) + n + m[int32(fieldNum)] = Extension{enc: buf[i:end]} + i = end + } + return m, nil +} + +func NewExtension(e []byte) Extension { + ee := Extension{enc: make([]byte, len(e))} + copy(ee.enc, e) + return ee +} + +func AppendExtension(e Message, tag int32, buf []byte) { + if ee, eok := e.(extensionsBytes); eok { + ext := ee.GetExtensions() + *ext = append(*ext, buf...) + return + } + if ee, eok := e.(extendableProto); eok { + m := ee.extensionsWrite() + ext := m[int32(tag)] // may be missing + ext.enc = append(ext.enc, buf...) + m[int32(tag)] = ext + } +} + +func encodeExtension(extension *ExtensionDesc, value interface{}) ([]byte, error) { + u := getMarshalInfo(reflect.TypeOf(extension.ExtendedType)) + ei := u.getExtElemInfo(extension) + v := value + p := toAddrPointer(&v, ei.isptr) + siz := ei.sizer(p, SizeVarint(ei.wiretag)) + buf := make([]byte, 0, siz) + return ei.marshaler(buf, p, ei.wiretag, false) +} + +func decodeExtensionFromBytes(extension *ExtensionDesc, buf []byte) (interface{}, error) { + o := 0 + for o < len(buf) { + tag, n := DecodeVarint((buf)[o:]) + fieldNum := int32(tag >> 3) + wireType := int(tag & 0x7) + if o+n > len(buf) { + return nil, fmt.Errorf("unable to decode extension") + } + l, err := size((buf)[o+n:], wireType) + if err != nil { + return nil, err + } + if int32(fieldNum) == extension.Field { + if o+n+l > len(buf) { + return nil, fmt.Errorf("unable to decode extension") + } + v, err := decodeExtension((buf)[o:o+n+l], extension) + if err != nil { + return nil, err + } + return v, nil + } + o += n + l + } + return defaultExtensionValue(extension) +} + +func (this *Extension) Encode() error { + if this.enc == nil { + var err error + this.enc, err = encodeExtension(this.desc, this.value) + if err != nil { + return err + } + } + return nil +} + +func (this Extension) GoString() string { + if err := this.Encode(); err != nil { + return fmt.Sprintf("error encoding extension: %v", err) + } + return fmt.Sprintf("proto.NewExtension(%#v)", this.enc) +} + +func SetUnsafeExtension(pb Message, fieldNum int32, value interface{}) error { + typ := reflect.TypeOf(pb).Elem() + ext, ok := extensionMaps[typ] + if !ok { + return fmt.Errorf("proto: bad extended type; %s is not extendable", typ.String()) + } + desc, ok := ext[fieldNum] + if !ok { + return errors.New("proto: bad extension number; not in declared ranges") + } + return SetExtension(pb, desc, value) +} + +func GetUnsafeExtension(pb Message, fieldNum int32) (interface{}, error) { + typ := reflect.TypeOf(pb).Elem() + ext, ok := extensionMaps[typ] + if !ok { + return nil, fmt.Errorf("proto: bad extended type; %s is not extendable", typ.String()) + } + desc, ok := ext[fieldNum] + if !ok { + return nil, fmt.Errorf("unregistered field number %d", fieldNum) + } + return GetExtension(pb, desc) +} + +func NewUnsafeXXX_InternalExtensions(m map[int32]Extension) XXX_InternalExtensions { + x := &XXX_InternalExtensions{ + p: new(struct { + mu sync.Mutex + extensionMap map[int32]Extension + }), + } + x.p.extensionMap = m + return *x +} + +func GetUnsafeExtensionsMap(extendable Message) map[int32]Extension { + pb := extendable.(extendableProto) + return pb.extensionsWrite() +} + +func deleteExtension(pb extensionsBytes, theFieldNum int32, offset int) int { + ext := pb.GetExtensions() + for offset < len(*ext) { + tag, n1 := DecodeVarint((*ext)[offset:]) + fieldNum := int32(tag >> 3) + wireType := int(tag & 0x7) + n2, err := size((*ext)[offset+n1:], wireType) + if err != nil { + panic(err) + } + newOffset := offset + n1 + n2 + if fieldNum == theFieldNum { + *ext = append((*ext)[:offset], (*ext)[newOffset:]...) + return offset + } + offset = newOffset + } + return -1 +} diff --git a/vendor/github.com/gogo/protobuf/proto/lib.go b/vendor/github.com/gogo/protobuf/proto/lib.go new file mode 100644 index 00000000..80db1c15 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/lib.go @@ -0,0 +1,973 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +/* +Package proto converts data structures to and from the wire format of +protocol buffers. It works in concert with the Go source code generated +for .proto files by the protocol compiler. + +A summary of the properties of the protocol buffer interface +for a protocol buffer variable v: + + - Names are turned from camel_case to CamelCase for export. + - There are no methods on v to set fields; just treat + them as structure fields. + - There are getters that return a field's value if set, + and return the field's default value if unset. + The getters work even if the receiver is a nil message. + - The zero value for a struct is its correct initialization state. + All desired fields must be set before marshaling. + - A Reset() method will restore a protobuf struct to its zero state. + - Non-repeated fields are pointers to the values; nil means unset. + That is, optional or required field int32 f becomes F *int32. + - Repeated fields are slices. + - Helper functions are available to aid the setting of fields. + msg.Foo = proto.String("hello") // set field + - Constants are defined to hold the default values of all fields that + have them. They have the form Default_StructName_FieldName. + Because the getter methods handle defaulted values, + direct use of these constants should be rare. + - Enums are given type names and maps from names to values. + Enum values are prefixed by the enclosing message's name, or by the + enum's type name if it is a top-level enum. Enum types have a String + method, and a Enum method to assist in message construction. + - Nested messages, groups and enums have type names prefixed with the name of + the surrounding message type. + - Extensions are given descriptor names that start with E_, + followed by an underscore-delimited list of the nested messages + that contain it (if any) followed by the CamelCased name of the + extension field itself. HasExtension, ClearExtension, GetExtension + and SetExtension are functions for manipulating extensions. + - Oneof field sets are given a single field in their message, + with distinguished wrapper types for each possible field value. + - Marshal and Unmarshal are functions to encode and decode the wire format. + +When the .proto file specifies `syntax="proto3"`, there are some differences: + + - Non-repeated fields of non-message type are values instead of pointers. + - Enum types do not get an Enum method. + +The simplest way to describe this is to see an example. +Given file test.proto, containing + + package example; + + enum FOO { X = 17; } + + message Test { + required string label = 1; + optional int32 type = 2 [default=77]; + repeated int64 reps = 3; + optional group OptionalGroup = 4 { + required string RequiredField = 5; + } + oneof union { + int32 number = 6; + string name = 7; + } + } + +The resulting file, test.pb.go, is: + + package example + + import proto "github.com/gogo/protobuf/proto" + import math "math" + + type FOO int32 + const ( + FOO_X FOO = 17 + ) + var FOO_name = map[int32]string{ + 17: "X", + } + var FOO_value = map[string]int32{ + "X": 17, + } + + func (x FOO) Enum() *FOO { + p := new(FOO) + *p = x + return p + } + func (x FOO) String() string { + return proto.EnumName(FOO_name, int32(x)) + } + func (x *FOO) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(FOO_value, data) + if err != nil { + return err + } + *x = FOO(value) + return nil + } + + type Test struct { + Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` + Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` + Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` + Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` + // Types that are valid to be assigned to Union: + // *Test_Number + // *Test_Name + Union isTest_Union `protobuf_oneof:"union"` + XXX_unrecognized []byte `json:"-"` + } + func (m *Test) Reset() { *m = Test{} } + func (m *Test) String() string { return proto.CompactTextString(m) } + func (*Test) ProtoMessage() {} + + type isTest_Union interface { + isTest_Union() + } + + type Test_Number struct { + Number int32 `protobuf:"varint,6,opt,name=number"` + } + type Test_Name struct { + Name string `protobuf:"bytes,7,opt,name=name"` + } + + func (*Test_Number) isTest_Union() {} + func (*Test_Name) isTest_Union() {} + + func (m *Test) GetUnion() isTest_Union { + if m != nil { + return m.Union + } + return nil + } + const Default_Test_Type int32 = 77 + + func (m *Test) GetLabel() string { + if m != nil && m.Label != nil { + return *m.Label + } + return "" + } + + func (m *Test) GetType() int32 { + if m != nil && m.Type != nil { + return *m.Type + } + return Default_Test_Type + } + + func (m *Test) GetOptionalgroup() *Test_OptionalGroup { + if m != nil { + return m.Optionalgroup + } + return nil + } + + type Test_OptionalGroup struct { + RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` + } + func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } + func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } + + func (m *Test_OptionalGroup) GetRequiredField() string { + if m != nil && m.RequiredField != nil { + return *m.RequiredField + } + return "" + } + + func (m *Test) GetNumber() int32 { + if x, ok := m.GetUnion().(*Test_Number); ok { + return x.Number + } + return 0 + } + + func (m *Test) GetName() string { + if x, ok := m.GetUnion().(*Test_Name); ok { + return x.Name + } + return "" + } + + func init() { + proto.RegisterEnum("example.FOO", FOO_name, FOO_value) + } + +To create and play with a Test object: + + package main + + import ( + "log" + + "github.com/gogo/protobuf/proto" + pb "./example.pb" + ) + + func main() { + test := &pb.Test{ + Label: proto.String("hello"), + Type: proto.Int32(17), + Reps: []int64{1, 2, 3}, + Optionalgroup: &pb.Test_OptionalGroup{ + RequiredField: proto.String("good bye"), + }, + Union: &pb.Test_Name{"fred"}, + } + data, err := proto.Marshal(test) + if err != nil { + log.Fatal("marshaling error: ", err) + } + newTest := &pb.Test{} + err = proto.Unmarshal(data, newTest) + if err != nil { + log.Fatal("unmarshaling error: ", err) + } + // Now test and newTest contain the same data. + if test.GetLabel() != newTest.GetLabel() { + log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) + } + // Use a type switch to determine which oneof was set. + switch u := test.Union.(type) { + case *pb.Test_Number: // u.Number contains the number. + case *pb.Test_Name: // u.Name contains the string. + } + // etc. + } +*/ +package proto + +import ( + "encoding/json" + "fmt" + "log" + "reflect" + "sort" + "strconv" + "sync" +) + +// RequiredNotSetError is an error type returned by either Marshal or Unmarshal. +// Marshal reports this when a required field is not initialized. +// Unmarshal reports this when a required field is missing from the wire data. +type RequiredNotSetError struct{ field string } + +func (e *RequiredNotSetError) Error() string { + if e.field == "" { + return fmt.Sprintf("proto: required field not set") + } + return fmt.Sprintf("proto: required field %q not set", e.field) +} +func (e *RequiredNotSetError) RequiredNotSet() bool { + return true +} + +type invalidUTF8Error struct{ field string } + +func (e *invalidUTF8Error) Error() string { + if e.field == "" { + return "proto: invalid UTF-8 detected" + } + return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field) +} +func (e *invalidUTF8Error) InvalidUTF8() bool { + return true +} + +// errInvalidUTF8 is a sentinel error to identify fields with invalid UTF-8. +// This error should not be exposed to the external API as such errors should +// be recreated with the field information. +var errInvalidUTF8 = &invalidUTF8Error{} + +// isNonFatal reports whether the error is either a RequiredNotSet error +// or a InvalidUTF8 error. +func isNonFatal(err error) bool { + if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() { + return true + } + if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() { + return true + } + return false +} + +type nonFatal struct{ E error } + +// Merge merges err into nf and reports whether it was successful. +// Otherwise it returns false for any fatal non-nil errors. +func (nf *nonFatal) Merge(err error) (ok bool) { + if err == nil { + return true // not an error + } + if !isNonFatal(err) { + return false // fatal error + } + if nf.E == nil { + nf.E = err // store first instance of non-fatal error + } + return true +} + +// Message is implemented by generated protocol buffer messages. +type Message interface { + Reset() + String() string + ProtoMessage() +} + +// A Buffer is a buffer manager for marshaling and unmarshaling +// protocol buffers. It may be reused between invocations to +// reduce memory usage. It is not necessary to use a Buffer; +// the global functions Marshal and Unmarshal create a +// temporary Buffer and are fine for most applications. +type Buffer struct { + buf []byte // encode/decode byte stream + index int // read point + + deterministic bool +} + +// NewBuffer allocates a new Buffer and initializes its internal data to +// the contents of the argument slice. +func NewBuffer(e []byte) *Buffer { + return &Buffer{buf: e} +} + +// Reset resets the Buffer, ready for marshaling a new protocol buffer. +func (p *Buffer) Reset() { + p.buf = p.buf[0:0] // for reading/writing + p.index = 0 // for reading +} + +// SetBuf replaces the internal buffer with the slice, +// ready for unmarshaling the contents of the slice. +func (p *Buffer) SetBuf(s []byte) { + p.buf = s + p.index = 0 +} + +// Bytes returns the contents of the Buffer. +func (p *Buffer) Bytes() []byte { return p.buf } + +// SetDeterministic sets whether to use deterministic serialization. +// +// Deterministic serialization guarantees that for a given binary, equal +// messages will always be serialized to the same bytes. This implies: +// +// - Repeated serialization of a message will return the same bytes. +// - Different processes of the same binary (which may be executing on +// different machines) will serialize equal messages to the same bytes. +// +// Note that the deterministic serialization is NOT canonical across +// languages. It is not guaranteed to remain stable over time. It is unstable +// across different builds with schema changes due to unknown fields. +// Users who need canonical serialization (e.g., persistent storage in a +// canonical form, fingerprinting, etc.) should define their own +// canonicalization specification and implement their own serializer rather +// than relying on this API. +// +// If deterministic serialization is requested, map entries will be sorted +// by keys in lexographical order. This is an implementation detail and +// subject to change. +func (p *Buffer) SetDeterministic(deterministic bool) { + p.deterministic = deterministic +} + +/* + * Helper routines for simplifying the creation of optional fields of basic type. + */ + +// Bool is a helper routine that allocates a new bool value +// to store v and returns a pointer to it. +func Bool(v bool) *bool { + return &v +} + +// Int32 is a helper routine that allocates a new int32 value +// to store v and returns a pointer to it. +func Int32(v int32) *int32 { + return &v +} + +// Int is a helper routine that allocates a new int32 value +// to store v and returns a pointer to it, but unlike Int32 +// its argument value is an int. +func Int(v int) *int32 { + p := new(int32) + *p = int32(v) + return p +} + +// Int64 is a helper routine that allocates a new int64 value +// to store v and returns a pointer to it. +func Int64(v int64) *int64 { + return &v +} + +// Float32 is a helper routine that allocates a new float32 value +// to store v and returns a pointer to it. +func Float32(v float32) *float32 { + return &v +} + +// Float64 is a helper routine that allocates a new float64 value +// to store v and returns a pointer to it. +func Float64(v float64) *float64 { + return &v +} + +// Uint32 is a helper routine that allocates a new uint32 value +// to store v and returns a pointer to it. +func Uint32(v uint32) *uint32 { + return &v +} + +// Uint64 is a helper routine that allocates a new uint64 value +// to store v and returns a pointer to it. +func Uint64(v uint64) *uint64 { + return &v +} + +// String is a helper routine that allocates a new string value +// to store v and returns a pointer to it. +func String(v string) *string { + return &v +} + +// EnumName is a helper function to simplify printing protocol buffer enums +// by name. Given an enum map and a value, it returns a useful string. +func EnumName(m map[int32]string, v int32) string { + s, ok := m[v] + if ok { + return s + } + return strconv.Itoa(int(v)) +} + +// UnmarshalJSONEnum is a helper function to simplify recovering enum int values +// from their JSON-encoded representation. Given a map from the enum's symbolic +// names to its int values, and a byte buffer containing the JSON-encoded +// value, it returns an int32 that can be cast to the enum type by the caller. +// +// The function can deal with both JSON representations, numeric and symbolic. +func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { + if data[0] == '"' { + // New style: enums are strings. + var repr string + if err := json.Unmarshal(data, &repr); err != nil { + return -1, err + } + val, ok := m[repr] + if !ok { + return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) + } + return val, nil + } + // Old style: enums are ints. + var val int32 + if err := json.Unmarshal(data, &val); err != nil { + return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) + } + return val, nil +} + +// DebugPrint dumps the encoded data in b in a debugging format with a header +// including the string s. Used in testing but made available for general debugging. +func (p *Buffer) DebugPrint(s string, b []byte) { + var u uint64 + + obuf := p.buf + sindex := p.index + p.buf = b + p.index = 0 + depth := 0 + + fmt.Printf("\n--- %s ---\n", s) + +out: + for { + for i := 0; i < depth; i++ { + fmt.Print(" ") + } + + index := p.index + if index == len(p.buf) { + break + } + + op, err := p.DecodeVarint() + if err != nil { + fmt.Printf("%3d: fetching op err %v\n", index, err) + break out + } + tag := op >> 3 + wire := op & 7 + + switch wire { + default: + fmt.Printf("%3d: t=%3d unknown wire=%d\n", + index, tag, wire) + break out + + case WireBytes: + var r []byte + + r, err = p.DecodeRawBytes(false) + if err != nil { + break out + } + fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) + if len(r) <= 6 { + for i := 0; i < len(r); i++ { + fmt.Printf(" %.2x", r[i]) + } + } else { + for i := 0; i < 3; i++ { + fmt.Printf(" %.2x", r[i]) + } + fmt.Printf(" ..") + for i := len(r) - 3; i < len(r); i++ { + fmt.Printf(" %.2x", r[i]) + } + } + fmt.Printf("\n") + + case WireFixed32: + u, err = p.DecodeFixed32() + if err != nil { + fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) + break out + } + fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) + + case WireFixed64: + u, err = p.DecodeFixed64() + if err != nil { + fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) + break out + } + fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) + + case WireVarint: + u, err = p.DecodeVarint() + if err != nil { + fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) + break out + } + fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) + + case WireStartGroup: + fmt.Printf("%3d: t=%3d start\n", index, tag) + depth++ + + case WireEndGroup: + depth-- + fmt.Printf("%3d: t=%3d end\n", index, tag) + } + } + + if depth != 0 { + fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) + } + fmt.Printf("\n") + + p.buf = obuf + p.index = sindex +} + +// SetDefaults sets unset protocol buffer fields to their default values. +// It only modifies fields that are both unset and have defined defaults. +// It recursively sets default values in any non-nil sub-messages. +func SetDefaults(pb Message) { + setDefaults(reflect.ValueOf(pb), true, false) +} + +// v is a struct. +func setDefaults(v reflect.Value, recur, zeros bool) { + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + + defaultMu.RLock() + dm, ok := defaults[v.Type()] + defaultMu.RUnlock() + if !ok { + dm = buildDefaultMessage(v.Type()) + defaultMu.Lock() + defaults[v.Type()] = dm + defaultMu.Unlock() + } + + for _, sf := range dm.scalars { + f := v.Field(sf.index) + if !f.IsNil() { + // field already set + continue + } + dv := sf.value + if dv == nil && !zeros { + // no explicit default, and don't want to set zeros + continue + } + fptr := f.Addr().Interface() // **T + // TODO: Consider batching the allocations we do here. + switch sf.kind { + case reflect.Bool: + b := new(bool) + if dv != nil { + *b = dv.(bool) + } + *(fptr.(**bool)) = b + case reflect.Float32: + f := new(float32) + if dv != nil { + *f = dv.(float32) + } + *(fptr.(**float32)) = f + case reflect.Float64: + f := new(float64) + if dv != nil { + *f = dv.(float64) + } + *(fptr.(**float64)) = f + case reflect.Int32: + // might be an enum + if ft := f.Type(); ft != int32PtrType { + // enum + f.Set(reflect.New(ft.Elem())) + if dv != nil { + f.Elem().SetInt(int64(dv.(int32))) + } + } else { + // int32 field + i := new(int32) + if dv != nil { + *i = dv.(int32) + } + *(fptr.(**int32)) = i + } + case reflect.Int64: + i := new(int64) + if dv != nil { + *i = dv.(int64) + } + *(fptr.(**int64)) = i + case reflect.String: + s := new(string) + if dv != nil { + *s = dv.(string) + } + *(fptr.(**string)) = s + case reflect.Uint8: + // exceptional case: []byte + var b []byte + if dv != nil { + db := dv.([]byte) + b = make([]byte, len(db)) + copy(b, db) + } else { + b = []byte{} + } + *(fptr.(*[]byte)) = b + case reflect.Uint32: + u := new(uint32) + if dv != nil { + *u = dv.(uint32) + } + *(fptr.(**uint32)) = u + case reflect.Uint64: + u := new(uint64) + if dv != nil { + *u = dv.(uint64) + } + *(fptr.(**uint64)) = u + default: + log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) + } + } + + for _, ni := range dm.nested { + f := v.Field(ni) + // f is *T or T or []*T or []T + switch f.Kind() { + case reflect.Struct: + setDefaults(f, recur, zeros) + + case reflect.Ptr: + if f.IsNil() { + continue + } + setDefaults(f, recur, zeros) + + case reflect.Slice: + for i := 0; i < f.Len(); i++ { + e := f.Index(i) + if e.Kind() == reflect.Ptr && e.IsNil() { + continue + } + setDefaults(e, recur, zeros) + } + + case reflect.Map: + for _, k := range f.MapKeys() { + e := f.MapIndex(k) + if e.IsNil() { + continue + } + setDefaults(e, recur, zeros) + } + } + } +} + +var ( + // defaults maps a protocol buffer struct type to a slice of the fields, + // with its scalar fields set to their proto-declared non-zero default values. + defaultMu sync.RWMutex + defaults = make(map[reflect.Type]defaultMessage) + + int32PtrType = reflect.TypeOf((*int32)(nil)) +) + +// defaultMessage represents information about the default values of a message. +type defaultMessage struct { + scalars []scalarField + nested []int // struct field index of nested messages +} + +type scalarField struct { + index int // struct field index + kind reflect.Kind // element type (the T in *T or []T) + value interface{} // the proto-declared default value, or nil +} + +// t is a struct type. +func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { + sprop := GetProperties(t) + for _, prop := range sprop.Prop { + fi, ok := sprop.decoderTags.get(prop.Tag) + if !ok { + // XXX_unrecognized + continue + } + ft := t.Field(fi).Type + + sf, nested, err := fieldDefault(ft, prop) + switch { + case err != nil: + log.Print(err) + case nested: + dm.nested = append(dm.nested, fi) + case sf != nil: + sf.index = fi + dm.scalars = append(dm.scalars, *sf) + } + } + + return dm +} + +// fieldDefault returns the scalarField for field type ft. +// sf will be nil if the field can not have a default. +// nestedMessage will be true if this is a nested message. +// Note that sf.index is not set on return. +func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { + var canHaveDefault bool + switch ft.Kind() { + case reflect.Struct: + nestedMessage = true // non-nullable + + case reflect.Ptr: + if ft.Elem().Kind() == reflect.Struct { + nestedMessage = true + } else { + canHaveDefault = true // proto2 scalar field + } + + case reflect.Slice: + switch ft.Elem().Kind() { + case reflect.Ptr, reflect.Struct: + nestedMessage = true // repeated message + case reflect.Uint8: + canHaveDefault = true // bytes field + } + + case reflect.Map: + if ft.Elem().Kind() == reflect.Ptr { + nestedMessage = true // map with message values + } + } + + if !canHaveDefault { + if nestedMessage { + return nil, true, nil + } + return nil, false, nil + } + + // We now know that ft is a pointer or slice. + sf = &scalarField{kind: ft.Elem().Kind()} + + // scalar fields without defaults + if !prop.HasDefault { + return sf, false, nil + } + + // a scalar field: either *T or []byte + switch ft.Elem().Kind() { + case reflect.Bool: + x, err := strconv.ParseBool(prop.Default) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) + } + sf.value = x + case reflect.Float32: + x, err := strconv.ParseFloat(prop.Default, 32) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) + } + sf.value = float32(x) + case reflect.Float64: + x, err := strconv.ParseFloat(prop.Default, 64) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) + } + sf.value = x + case reflect.Int32: + x, err := strconv.ParseInt(prop.Default, 10, 32) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) + } + sf.value = int32(x) + case reflect.Int64: + x, err := strconv.ParseInt(prop.Default, 10, 64) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) + } + sf.value = x + case reflect.String: + sf.value = prop.Default + case reflect.Uint8: + // []byte (not *uint8) + sf.value = []byte(prop.Default) + case reflect.Uint32: + x, err := strconv.ParseUint(prop.Default, 10, 32) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) + } + sf.value = uint32(x) + case reflect.Uint64: + x, err := strconv.ParseUint(prop.Default, 10, 64) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) + } + sf.value = x + default: + return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) + } + + return sf, false, nil +} + +// mapKeys returns a sort.Interface to be used for sorting the map keys. +// Map fields may have key types of non-float scalars, strings and enums. +func mapKeys(vs []reflect.Value) sort.Interface { + s := mapKeySorter{vs: vs} + + // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps. + if len(vs) == 0 { + return s + } + switch vs[0].Kind() { + case reflect.Int32, reflect.Int64: + s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } + case reflect.Uint32, reflect.Uint64: + s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } + case reflect.Bool: + s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true + case reflect.String: + s.less = func(a, b reflect.Value) bool { return a.String() < b.String() } + default: + panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind())) + } + + return s +} + +type mapKeySorter struct { + vs []reflect.Value + less func(a, b reflect.Value) bool +} + +func (s mapKeySorter) Len() int { return len(s.vs) } +func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } +func (s mapKeySorter) Less(i, j int) bool { + return s.less(s.vs[i], s.vs[j]) +} + +// isProto3Zero reports whether v is a zero proto3 value. +func isProto3Zero(v reflect.Value) bool { + switch v.Kind() { + case reflect.Bool: + return !v.Bool() + case reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint32, reflect.Uint64: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.String: + return v.String() == "" + } + return false +} + +const ( + // ProtoPackageIsVersion3 is referenced from generated protocol buffer files + // to assert that that code is compatible with this version of the proto package. + GoGoProtoPackageIsVersion3 = true + + // ProtoPackageIsVersion2 is referenced from generated protocol buffer files + // to assert that that code is compatible with this version of the proto package. + GoGoProtoPackageIsVersion2 = true + + // ProtoPackageIsVersion1 is referenced from generated protocol buffer files + // to assert that that code is compatible with this version of the proto package. + GoGoProtoPackageIsVersion1 = true +) + +// InternalMessageInfo is a type used internally by generated .pb.go files. +// This type is not intended to be used by non-generated code. +// This type is not subject to any compatibility guarantee. +type InternalMessageInfo struct { + marshal *marshalInfo + unmarshal *unmarshalInfo + merge *mergeInfo + discard *discardInfo +} diff --git a/vendor/github.com/gogo/protobuf/proto/lib_gogo.go b/vendor/github.com/gogo/protobuf/proto/lib_gogo.go new file mode 100644 index 00000000..b3aa3919 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/lib_gogo.go @@ -0,0 +1,50 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "encoding/json" + "strconv" +) + +type Sizer interface { + Size() int +} + +type ProtoSizer interface { + ProtoSize() int +} + +func MarshalJSONEnum(m map[int32]string, value int32) ([]byte, error) { + s, ok := m[value] + if !ok { + s = strconv.Itoa(int(value)) + } + return json.Marshal(s) +} diff --git a/vendor/github.com/gogo/protobuf/proto/message_set.go b/vendor/github.com/gogo/protobuf/proto/message_set.go new file mode 100644 index 00000000..f48a7567 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/message_set.go @@ -0,0 +1,181 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Support for message sets. + */ + +import ( + "errors" +) + +// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. +// A message type ID is required for storing a protocol buffer in a message set. +var errNoMessageTypeID = errors.New("proto does not have a message type ID") + +// The first two types (_MessageSet_Item and messageSet) +// model what the protocol compiler produces for the following protocol message: +// message MessageSet { +// repeated group Item = 1 { +// required int32 type_id = 2; +// required string message = 3; +// }; +// } +// That is the MessageSet wire format. We can't use a proto to generate these +// because that would introduce a circular dependency between it and this package. + +type _MessageSet_Item struct { + TypeId *int32 `protobuf:"varint,2,req,name=type_id"` + Message []byte `protobuf:"bytes,3,req,name=message"` +} + +type messageSet struct { + Item []*_MessageSet_Item `protobuf:"group,1,rep"` + XXX_unrecognized []byte + // TODO: caching? +} + +// Make sure messageSet is a Message. +var _ Message = (*messageSet)(nil) + +// messageTypeIder is an interface satisfied by a protocol buffer type +// that may be stored in a MessageSet. +type messageTypeIder interface { + MessageTypeId() int32 +} + +func (ms *messageSet) find(pb Message) *_MessageSet_Item { + mti, ok := pb.(messageTypeIder) + if !ok { + return nil + } + id := mti.MessageTypeId() + for _, item := range ms.Item { + if *item.TypeId == id { + return item + } + } + return nil +} + +func (ms *messageSet) Has(pb Message) bool { + return ms.find(pb) != nil +} + +func (ms *messageSet) Unmarshal(pb Message) error { + if item := ms.find(pb); item != nil { + return Unmarshal(item.Message, pb) + } + if _, ok := pb.(messageTypeIder); !ok { + return errNoMessageTypeID + } + return nil // TODO: return error instead? +} + +func (ms *messageSet) Marshal(pb Message) error { + msg, err := Marshal(pb) + if err != nil { + return err + } + if item := ms.find(pb); item != nil { + // reuse existing item + item.Message = msg + return nil + } + + mti, ok := pb.(messageTypeIder) + if !ok { + return errNoMessageTypeID + } + + mtid := mti.MessageTypeId() + ms.Item = append(ms.Item, &_MessageSet_Item{ + TypeId: &mtid, + Message: msg, + }) + return nil +} + +func (ms *messageSet) Reset() { *ms = messageSet{} } +func (ms *messageSet) String() string { return CompactTextString(ms) } +func (*messageSet) ProtoMessage() {} + +// Support for the message_set_wire_format message option. + +func skipVarint(buf []byte) []byte { + i := 0 + for ; buf[i]&0x80 != 0; i++ { + } + return buf[i+1:] +} + +// unmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. +// It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option. +func unmarshalMessageSet(buf []byte, exts interface{}) error { + var m map[int32]Extension + switch exts := exts.(type) { + case *XXX_InternalExtensions: + m = exts.extensionsWrite() + case map[int32]Extension: + m = exts + default: + return errors.New("proto: not an extension map") + } + + ms := new(messageSet) + if err := Unmarshal(buf, ms); err != nil { + return err + } + for _, item := range ms.Item { + id := *item.TypeId + msg := item.Message + + // Restore wire type and field number varint, plus length varint. + // Be careful to preserve duplicate items. + b := EncodeVarint(uint64(id)<<3 | WireBytes) + if ext, ok := m[id]; ok { + // Existing data; rip off the tag and length varint + // so we join the new data correctly. + // We can assume that ext.enc is set because we are unmarshaling. + o := ext.enc[len(b):] // skip wire type and field number + _, n := DecodeVarint(o) // calculate length of length varint + o = o[n:] // skip length varint + msg = append(o, msg...) // join old data and new data + } + b = append(b, EncodeVarint(uint64(len(msg)))...) + b = append(b, msg...) + + m[id] = Extension{enc: b} + } + return nil +} diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go b/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go new file mode 100644 index 00000000..b6cad908 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go @@ -0,0 +1,357 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2012 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// +build purego appengine js + +// This file contains an implementation of proto field accesses using package reflect. +// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can +// be used on App Engine. + +package proto + +import ( + "reflect" + "sync" +) + +const unsafeAllowed = false + +// A field identifies a field in a struct, accessible from a pointer. +// In this implementation, a field is identified by the sequence of field indices +// passed to reflect's FieldByIndex. +type field []int + +// toField returns a field equivalent to the given reflect field. +func toField(f *reflect.StructField) field { + return f.Index +} + +// invalidField is an invalid field identifier. +var invalidField = field(nil) + +// zeroField is a noop when calling pointer.offset. +var zeroField = field([]int{}) + +// IsValid reports whether the field identifier is valid. +func (f field) IsValid() bool { return f != nil } + +// The pointer type is for the table-driven decoder. +// The implementation here uses a reflect.Value of pointer type to +// create a generic pointer. In pointer_unsafe.go we use unsafe +// instead of reflect to implement the same (but faster) interface. +type pointer struct { + v reflect.Value +} + +// toPointer converts an interface of pointer type to a pointer +// that points to the same target. +func toPointer(i *Message) pointer { + return pointer{v: reflect.ValueOf(*i)} +} + +// toAddrPointer converts an interface to a pointer that points to +// the interface data. +func toAddrPointer(i *interface{}, isptr bool) pointer { + v := reflect.ValueOf(*i) + u := reflect.New(v.Type()) + u.Elem().Set(v) + return pointer{v: u} +} + +// valToPointer converts v to a pointer. v must be of pointer type. +func valToPointer(v reflect.Value) pointer { + return pointer{v: v} +} + +// offset converts from a pointer to a structure to a pointer to +// one of its fields. +func (p pointer) offset(f field) pointer { + return pointer{v: p.v.Elem().FieldByIndex(f).Addr()} +} + +func (p pointer) isNil() bool { + return p.v.IsNil() +} + +// grow updates the slice s in place to make it one element longer. +// s must be addressable. +// Returns the (addressable) new element. +func grow(s reflect.Value) reflect.Value { + n, m := s.Len(), s.Cap() + if n < m { + s.SetLen(n + 1) + } else { + s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem()))) + } + return s.Index(n) +} + +func (p pointer) toInt64() *int64 { + return p.v.Interface().(*int64) +} +func (p pointer) toInt64Ptr() **int64 { + return p.v.Interface().(**int64) +} +func (p pointer) toInt64Slice() *[]int64 { + return p.v.Interface().(*[]int64) +} + +var int32ptr = reflect.TypeOf((*int32)(nil)) + +func (p pointer) toInt32() *int32 { + return p.v.Convert(int32ptr).Interface().(*int32) +} + +// The toInt32Ptr/Slice methods don't work because of enums. +// Instead, we must use set/get methods for the int32ptr/slice case. +/* + func (p pointer) toInt32Ptr() **int32 { + return p.v.Interface().(**int32) +} + func (p pointer) toInt32Slice() *[]int32 { + return p.v.Interface().(*[]int32) +} +*/ +func (p pointer) getInt32Ptr() *int32 { + if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { + // raw int32 type + return p.v.Elem().Interface().(*int32) + } + // an enum + return p.v.Elem().Convert(int32PtrType).Interface().(*int32) +} +func (p pointer) setInt32Ptr(v int32) { + // Allocate value in a *int32. Possibly convert that to a *enum. + // Then assign it to a **int32 or **enum. + // Note: we can convert *int32 to *enum, but we can't convert + // **int32 to **enum! + p.v.Elem().Set(reflect.ValueOf(&v).Convert(p.v.Type().Elem())) +} + +// getInt32Slice copies []int32 from p as a new slice. +// This behavior differs from the implementation in pointer_unsafe.go. +func (p pointer) getInt32Slice() []int32 { + if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { + // raw int32 type + return p.v.Elem().Interface().([]int32) + } + // an enum + // Allocate a []int32, then assign []enum's values into it. + // Note: we can't convert []enum to []int32. + slice := p.v.Elem() + s := make([]int32, slice.Len()) + for i := 0; i < slice.Len(); i++ { + s[i] = int32(slice.Index(i).Int()) + } + return s +} + +// setInt32Slice copies []int32 into p as a new slice. +// This behavior differs from the implementation in pointer_unsafe.go. +func (p pointer) setInt32Slice(v []int32) { + if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { + // raw int32 type + p.v.Elem().Set(reflect.ValueOf(v)) + return + } + // an enum + // Allocate a []enum, then assign []int32's values into it. + // Note: we can't convert []enum to []int32. + slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v)) + for i, x := range v { + slice.Index(i).SetInt(int64(x)) + } + p.v.Elem().Set(slice) +} +func (p pointer) appendInt32Slice(v int32) { + grow(p.v.Elem()).SetInt(int64(v)) +} + +func (p pointer) toUint64() *uint64 { + return p.v.Interface().(*uint64) +} +func (p pointer) toUint64Ptr() **uint64 { + return p.v.Interface().(**uint64) +} +func (p pointer) toUint64Slice() *[]uint64 { + return p.v.Interface().(*[]uint64) +} +func (p pointer) toUint32() *uint32 { + return p.v.Interface().(*uint32) +} +func (p pointer) toUint32Ptr() **uint32 { + return p.v.Interface().(**uint32) +} +func (p pointer) toUint32Slice() *[]uint32 { + return p.v.Interface().(*[]uint32) +} +func (p pointer) toBool() *bool { + return p.v.Interface().(*bool) +} +func (p pointer) toBoolPtr() **bool { + return p.v.Interface().(**bool) +} +func (p pointer) toBoolSlice() *[]bool { + return p.v.Interface().(*[]bool) +} +func (p pointer) toFloat64() *float64 { + return p.v.Interface().(*float64) +} +func (p pointer) toFloat64Ptr() **float64 { + return p.v.Interface().(**float64) +} +func (p pointer) toFloat64Slice() *[]float64 { + return p.v.Interface().(*[]float64) +} +func (p pointer) toFloat32() *float32 { + return p.v.Interface().(*float32) +} +func (p pointer) toFloat32Ptr() **float32 { + return p.v.Interface().(**float32) +} +func (p pointer) toFloat32Slice() *[]float32 { + return p.v.Interface().(*[]float32) +} +func (p pointer) toString() *string { + return p.v.Interface().(*string) +} +func (p pointer) toStringPtr() **string { + return p.v.Interface().(**string) +} +func (p pointer) toStringSlice() *[]string { + return p.v.Interface().(*[]string) +} +func (p pointer) toBytes() *[]byte { + return p.v.Interface().(*[]byte) +} +func (p pointer) toBytesSlice() *[][]byte { + return p.v.Interface().(*[][]byte) +} +func (p pointer) toExtensions() *XXX_InternalExtensions { + return p.v.Interface().(*XXX_InternalExtensions) +} +func (p pointer) toOldExtensions() *map[int32]Extension { + return p.v.Interface().(*map[int32]Extension) +} +func (p pointer) getPointer() pointer { + return pointer{v: p.v.Elem()} +} +func (p pointer) setPointer(q pointer) { + p.v.Elem().Set(q.v) +} +func (p pointer) appendPointer(q pointer) { + grow(p.v.Elem()).Set(q.v) +} + +// getPointerSlice copies []*T from p as a new []pointer. +// This behavior differs from the implementation in pointer_unsafe.go. +func (p pointer) getPointerSlice() []pointer { + if p.v.IsNil() { + return nil + } + n := p.v.Elem().Len() + s := make([]pointer, n) + for i := 0; i < n; i++ { + s[i] = pointer{v: p.v.Elem().Index(i)} + } + return s +} + +// setPointerSlice copies []pointer into p as a new []*T. +// This behavior differs from the implementation in pointer_unsafe.go. +func (p pointer) setPointerSlice(v []pointer) { + if v == nil { + p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem()) + return + } + s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v)) + for _, p := range v { + s = reflect.Append(s, p.v) + } + p.v.Elem().Set(s) +} + +// getInterfacePointer returns a pointer that points to the +// interface data of the interface pointed by p. +func (p pointer) getInterfacePointer() pointer { + if p.v.Elem().IsNil() { + return pointer{v: p.v.Elem()} + } + return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct +} + +func (p pointer) asPointerTo(t reflect.Type) reflect.Value { + // TODO: check that p.v.Type().Elem() == t? + return p.v +} + +func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { + atomicLock.Lock() + defer atomicLock.Unlock() + return *p +} +func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { + atomicLock.Lock() + defer atomicLock.Unlock() + *p = v +} +func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { + atomicLock.Lock() + defer atomicLock.Unlock() + return *p +} +func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { + atomicLock.Lock() + defer atomicLock.Unlock() + *p = v +} +func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { + atomicLock.Lock() + defer atomicLock.Unlock() + return *p +} +func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { + atomicLock.Lock() + defer atomicLock.Unlock() + *p = v +} +func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { + atomicLock.Lock() + defer atomicLock.Unlock() + return *p +} +func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { + atomicLock.Lock() + defer atomicLock.Unlock() + *p = v +} + +var atomicLock sync.Mutex diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_reflect_gogo.go b/vendor/github.com/gogo/protobuf/proto/pointer_reflect_gogo.go new file mode 100644 index 00000000..7ffd3c29 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/pointer_reflect_gogo.go @@ -0,0 +1,59 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2018, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// +build purego appengine js + +// This file contains an implementation of proto field accesses using package reflect. +// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can +// be used on App Engine. + +package proto + +import ( + "reflect" +) + +// TODO: untested, so probably incorrect. + +func (p pointer) getRef() pointer { + return pointer{v: p.v.Addr()} +} + +func (p pointer) appendRef(v pointer, typ reflect.Type) { + slice := p.getSlice(typ) + elem := v.asPointerTo(typ).Elem() + newSlice := reflect.Append(slice, elem) + slice.Set(newSlice) +} + +func (p pointer) getSlice(typ reflect.Type) reflect.Value { + sliceTyp := reflect.SliceOf(typ) + slice := p.asPointerTo(sliceTyp) + slice = slice.Elem() + return slice +} diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go b/vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go new file mode 100644 index 00000000..d55a335d --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go @@ -0,0 +1,308 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2012 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// +build !purego,!appengine,!js + +// This file contains the implementation of the proto field accesses using package unsafe. + +package proto + +import ( + "reflect" + "sync/atomic" + "unsafe" +) + +const unsafeAllowed = true + +// A field identifies a field in a struct, accessible from a pointer. +// In this implementation, a field is identified by its byte offset from the start of the struct. +type field uintptr + +// toField returns a field equivalent to the given reflect field. +func toField(f *reflect.StructField) field { + return field(f.Offset) +} + +// invalidField is an invalid field identifier. +const invalidField = ^field(0) + +// zeroField is a noop when calling pointer.offset. +const zeroField = field(0) + +// IsValid reports whether the field identifier is valid. +func (f field) IsValid() bool { + return f != invalidField +} + +// The pointer type below is for the new table-driven encoder/decoder. +// The implementation here uses unsafe.Pointer to create a generic pointer. +// In pointer_reflect.go we use reflect instead of unsafe to implement +// the same (but slower) interface. +type pointer struct { + p unsafe.Pointer +} + +// size of pointer +var ptrSize = unsafe.Sizeof(uintptr(0)) + +// toPointer converts an interface of pointer type to a pointer +// that points to the same target. +func toPointer(i *Message) pointer { + // Super-tricky - read pointer out of data word of interface value. + // Saves ~25ns over the equivalent: + // return valToPointer(reflect.ValueOf(*i)) + return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} +} + +// toAddrPointer converts an interface to a pointer that points to +// the interface data. +func toAddrPointer(i *interface{}, isptr bool) pointer { + // Super-tricky - read or get the address of data word of interface value. + if isptr { + // The interface is of pointer type, thus it is a direct interface. + // The data word is the pointer data itself. We take its address. + return pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)} + } + // The interface is not of pointer type. The data word is the pointer + // to the data. + return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} +} + +// valToPointer converts v to a pointer. v must be of pointer type. +func valToPointer(v reflect.Value) pointer { + return pointer{p: unsafe.Pointer(v.Pointer())} +} + +// offset converts from a pointer to a structure to a pointer to +// one of its fields. +func (p pointer) offset(f field) pointer { + // For safety, we should panic if !f.IsValid, however calling panic causes + // this to no longer be inlineable, which is a serious performance cost. + /* + if !f.IsValid() { + panic("invalid field") + } + */ + return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))} +} + +func (p pointer) isNil() bool { + return p.p == nil +} + +func (p pointer) toInt64() *int64 { + return (*int64)(p.p) +} +func (p pointer) toInt64Ptr() **int64 { + return (**int64)(p.p) +} +func (p pointer) toInt64Slice() *[]int64 { + return (*[]int64)(p.p) +} +func (p pointer) toInt32() *int32 { + return (*int32)(p.p) +} + +// See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist. +/* + func (p pointer) toInt32Ptr() **int32 { + return (**int32)(p.p) + } + func (p pointer) toInt32Slice() *[]int32 { + return (*[]int32)(p.p) + } +*/ +func (p pointer) getInt32Ptr() *int32 { + return *(**int32)(p.p) +} +func (p pointer) setInt32Ptr(v int32) { + *(**int32)(p.p) = &v +} + +// getInt32Slice loads a []int32 from p. +// The value returned is aliased with the original slice. +// This behavior differs from the implementation in pointer_reflect.go. +func (p pointer) getInt32Slice() []int32 { + return *(*[]int32)(p.p) +} + +// setInt32Slice stores a []int32 to p. +// The value set is aliased with the input slice. +// This behavior differs from the implementation in pointer_reflect.go. +func (p pointer) setInt32Slice(v []int32) { + *(*[]int32)(p.p) = v +} + +// TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead? +func (p pointer) appendInt32Slice(v int32) { + s := (*[]int32)(p.p) + *s = append(*s, v) +} + +func (p pointer) toUint64() *uint64 { + return (*uint64)(p.p) +} +func (p pointer) toUint64Ptr() **uint64 { + return (**uint64)(p.p) +} +func (p pointer) toUint64Slice() *[]uint64 { + return (*[]uint64)(p.p) +} +func (p pointer) toUint32() *uint32 { + return (*uint32)(p.p) +} +func (p pointer) toUint32Ptr() **uint32 { + return (**uint32)(p.p) +} +func (p pointer) toUint32Slice() *[]uint32 { + return (*[]uint32)(p.p) +} +func (p pointer) toBool() *bool { + return (*bool)(p.p) +} +func (p pointer) toBoolPtr() **bool { + return (**bool)(p.p) +} +func (p pointer) toBoolSlice() *[]bool { + return (*[]bool)(p.p) +} +func (p pointer) toFloat64() *float64 { + return (*float64)(p.p) +} +func (p pointer) toFloat64Ptr() **float64 { + return (**float64)(p.p) +} +func (p pointer) toFloat64Slice() *[]float64 { + return (*[]float64)(p.p) +} +func (p pointer) toFloat32() *float32 { + return (*float32)(p.p) +} +func (p pointer) toFloat32Ptr() **float32 { + return (**float32)(p.p) +} +func (p pointer) toFloat32Slice() *[]float32 { + return (*[]float32)(p.p) +} +func (p pointer) toString() *string { + return (*string)(p.p) +} +func (p pointer) toStringPtr() **string { + return (**string)(p.p) +} +func (p pointer) toStringSlice() *[]string { + return (*[]string)(p.p) +} +func (p pointer) toBytes() *[]byte { + return (*[]byte)(p.p) +} +func (p pointer) toBytesSlice() *[][]byte { + return (*[][]byte)(p.p) +} +func (p pointer) toExtensions() *XXX_InternalExtensions { + return (*XXX_InternalExtensions)(p.p) +} +func (p pointer) toOldExtensions() *map[int32]Extension { + return (*map[int32]Extension)(p.p) +} + +// getPointerSlice loads []*T from p as a []pointer. +// The value returned is aliased with the original slice. +// This behavior differs from the implementation in pointer_reflect.go. +func (p pointer) getPointerSlice() []pointer { + // Super-tricky - p should point to a []*T where T is a + // message type. We load it as []pointer. + return *(*[]pointer)(p.p) +} + +// setPointerSlice stores []pointer into p as a []*T. +// The value set is aliased with the input slice. +// This behavior differs from the implementation in pointer_reflect.go. +func (p pointer) setPointerSlice(v []pointer) { + // Super-tricky - p should point to a []*T where T is a + // message type. We store it as []pointer. + *(*[]pointer)(p.p) = v +} + +// getPointer loads the pointer at p and returns it. +func (p pointer) getPointer() pointer { + return pointer{p: *(*unsafe.Pointer)(p.p)} +} + +// setPointer stores the pointer q at p. +func (p pointer) setPointer(q pointer) { + *(*unsafe.Pointer)(p.p) = q.p +} + +// append q to the slice pointed to by p. +func (p pointer) appendPointer(q pointer) { + s := (*[]unsafe.Pointer)(p.p) + *s = append(*s, q.p) +} + +// getInterfacePointer returns a pointer that points to the +// interface data of the interface pointed by p. +func (p pointer) getInterfacePointer() pointer { + // Super-tricky - read pointer out of data word of interface value. + return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]} +} + +// asPointerTo returns a reflect.Value that is a pointer to an +// object of type t stored at p. +func (p pointer) asPointerTo(t reflect.Type) reflect.Value { + return reflect.NewAt(t, p.p) +} + +func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { + return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) +} +func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) +} +func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { + return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) +} +func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) +} +func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { + return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) +} +func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) +} +func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { + return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) +} +func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) +} diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_unsafe_gogo.go b/vendor/github.com/gogo/protobuf/proto/pointer_unsafe_gogo.go new file mode 100644 index 00000000..aca8eed0 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/pointer_unsafe_gogo.go @@ -0,0 +1,56 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2018, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// +build !purego,!appengine,!js + +// This file contains the implementation of the proto field accesses using package unsafe. + +package proto + +import ( + "reflect" + "unsafe" +) + +func (p pointer) getRef() pointer { + return pointer{p: (unsafe.Pointer)(&p.p)} +} + +func (p pointer) appendRef(v pointer, typ reflect.Type) { + slice := p.getSlice(typ) + elem := v.asPointerTo(typ).Elem() + newSlice := reflect.Append(slice, elem) + slice.Set(newSlice) +} + +func (p pointer) getSlice(typ reflect.Type) reflect.Value { + sliceTyp := reflect.SliceOf(typ) + slice := p.asPointerTo(sliceTyp) + slice = slice.Elem() + return slice +} diff --git a/vendor/github.com/gogo/protobuf/proto/properties.go b/vendor/github.com/gogo/protobuf/proto/properties.go new file mode 100644 index 00000000..28da1475 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/properties.go @@ -0,0 +1,610 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Routines for encoding data into the wire format for protocol buffers. + */ + +import ( + "fmt" + "log" + "reflect" + "sort" + "strconv" + "strings" + "sync" +) + +const debug bool = false + +// Constants that identify the encoding of a value on the wire. +const ( + WireVarint = 0 + WireFixed64 = 1 + WireBytes = 2 + WireStartGroup = 3 + WireEndGroup = 4 + WireFixed32 = 5 +) + +// tagMap is an optimization over map[int]int for typical protocol buffer +// use-cases. Encoded protocol buffers are often in tag order with small tag +// numbers. +type tagMap struct { + fastTags []int + slowTags map[int]int +} + +// tagMapFastLimit is the upper bound on the tag number that will be stored in +// the tagMap slice rather than its map. +const tagMapFastLimit = 1024 + +func (p *tagMap) get(t int) (int, bool) { + if t > 0 && t < tagMapFastLimit { + if t >= len(p.fastTags) { + return 0, false + } + fi := p.fastTags[t] + return fi, fi >= 0 + } + fi, ok := p.slowTags[t] + return fi, ok +} + +func (p *tagMap) put(t int, fi int) { + if t > 0 && t < tagMapFastLimit { + for len(p.fastTags) < t+1 { + p.fastTags = append(p.fastTags, -1) + } + p.fastTags[t] = fi + return + } + if p.slowTags == nil { + p.slowTags = make(map[int]int) + } + p.slowTags[t] = fi +} + +// StructProperties represents properties for all the fields of a struct. +// decoderTags and decoderOrigNames should only be used by the decoder. +type StructProperties struct { + Prop []*Properties // properties for each field + reqCount int // required count + decoderTags tagMap // map from proto tag to struct field number + decoderOrigNames map[string]int // map from original name to struct field number + order []int // list of struct field numbers in tag order + + // OneofTypes contains information about the oneof fields in this message. + // It is keyed by the original name of a field. + OneofTypes map[string]*OneofProperties +} + +// OneofProperties represents information about a specific field in a oneof. +type OneofProperties struct { + Type reflect.Type // pointer to generated struct type for this oneof field + Field int // struct field number of the containing oneof in the message + Prop *Properties +} + +// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. +// See encode.go, (*Buffer).enc_struct. + +func (sp *StructProperties) Len() int { return len(sp.order) } +func (sp *StructProperties) Less(i, j int) bool { + return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag +} +func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } + +// Properties represents the protocol-specific behavior of a single struct field. +type Properties struct { + Name string // name of the field, for error messages + OrigName string // original name before protocol compiler (always set) + JSONName string // name to use for JSON; determined by protoc + Wire string + WireType int + Tag int + Required bool + Optional bool + Repeated bool + Packed bool // relevant for repeated primitives only + Enum string // set for enum types only + proto3 bool // whether this is known to be a proto3 field + oneof bool // whether this is a oneof field + + Default string // default value + HasDefault bool // whether an explicit default was provided + CustomType string + CastType string + StdTime bool + StdDuration bool + WktPointer bool + + stype reflect.Type // set for struct types only + ctype reflect.Type // set for custom types only + sprop *StructProperties // set for struct types only + + mtype reflect.Type // set for map types only + MapKeyProp *Properties // set for map types only + MapValProp *Properties // set for map types only +} + +// String formats the properties in the protobuf struct field tag style. +func (p *Properties) String() string { + s := p.Wire + s += "," + s += strconv.Itoa(p.Tag) + if p.Required { + s += ",req" + } + if p.Optional { + s += ",opt" + } + if p.Repeated { + s += ",rep" + } + if p.Packed { + s += ",packed" + } + s += ",name=" + p.OrigName + if p.JSONName != p.OrigName { + s += ",json=" + p.JSONName + } + if p.proto3 { + s += ",proto3" + } + if p.oneof { + s += ",oneof" + } + if len(p.Enum) > 0 { + s += ",enum=" + p.Enum + } + if p.HasDefault { + s += ",def=" + p.Default + } + return s +} + +// Parse populates p by parsing a string in the protobuf struct field tag style. +func (p *Properties) Parse(s string) { + // "bytes,49,opt,name=foo,def=hello!" + fields := strings.Split(s, ",") // breaks def=, but handled below. + if len(fields) < 2 { + log.Printf("proto: tag has too few fields: %q", s) + return + } + + p.Wire = fields[0] + switch p.Wire { + case "varint": + p.WireType = WireVarint + case "fixed32": + p.WireType = WireFixed32 + case "fixed64": + p.WireType = WireFixed64 + case "zigzag32": + p.WireType = WireVarint + case "zigzag64": + p.WireType = WireVarint + case "bytes", "group": + p.WireType = WireBytes + // no numeric converter for non-numeric types + default: + log.Printf("proto: tag has unknown wire type: %q", s) + return + } + + var err error + p.Tag, err = strconv.Atoi(fields[1]) + if err != nil { + return + } + +outer: + for i := 2; i < len(fields); i++ { + f := fields[i] + switch { + case f == "req": + p.Required = true + case f == "opt": + p.Optional = true + case f == "rep": + p.Repeated = true + case f == "packed": + p.Packed = true + case strings.HasPrefix(f, "name="): + p.OrigName = f[5:] + case strings.HasPrefix(f, "json="): + p.JSONName = f[5:] + case strings.HasPrefix(f, "enum="): + p.Enum = f[5:] + case f == "proto3": + p.proto3 = true + case f == "oneof": + p.oneof = true + case strings.HasPrefix(f, "def="): + p.HasDefault = true + p.Default = f[4:] // rest of string + if i+1 < len(fields) { + // Commas aren't escaped, and def is always last. + p.Default += "," + strings.Join(fields[i+1:], ",") + break outer + } + case strings.HasPrefix(f, "embedded="): + p.OrigName = strings.Split(f, "=")[1] + case strings.HasPrefix(f, "customtype="): + p.CustomType = strings.Split(f, "=")[1] + case strings.HasPrefix(f, "casttype="): + p.CastType = strings.Split(f, "=")[1] + case f == "stdtime": + p.StdTime = true + case f == "stdduration": + p.StdDuration = true + case f == "wktptr": + p.WktPointer = true + } + } +} + +var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() + +// setFieldProps initializes the field properties for submessages and maps. +func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { + isMap := typ.Kind() == reflect.Map + if len(p.CustomType) > 0 && !isMap { + p.ctype = typ + p.setTag(lockGetProp) + return + } + if p.StdTime && !isMap { + p.setTag(lockGetProp) + return + } + if p.StdDuration && !isMap { + p.setTag(lockGetProp) + return + } + if p.WktPointer && !isMap { + p.setTag(lockGetProp) + return + } + switch t1 := typ; t1.Kind() { + case reflect.Struct: + p.stype = typ + case reflect.Ptr: + if t1.Elem().Kind() == reflect.Struct { + p.stype = t1.Elem() + } + case reflect.Slice: + switch t2 := t1.Elem(); t2.Kind() { + case reflect.Ptr: + switch t3 := t2.Elem(); t3.Kind() { + case reflect.Struct: + p.stype = t3 + } + case reflect.Struct: + p.stype = t2 + } + + case reflect.Map: + + p.mtype = t1 + p.MapKeyProp = &Properties{} + p.MapKeyProp.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) + p.MapValProp = &Properties{} + vtype := p.mtype.Elem() + if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice { + // The value type is not a message (*T) or bytes ([]byte), + // so we need encoders for the pointer to this type. + vtype = reflect.PtrTo(vtype) + } + + p.MapValProp.CustomType = p.CustomType + p.MapValProp.StdDuration = p.StdDuration + p.MapValProp.StdTime = p.StdTime + p.MapValProp.WktPointer = p.WktPointer + p.MapValProp.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) + } + p.setTag(lockGetProp) +} + +func (p *Properties) setTag(lockGetProp bool) { + if p.stype != nil { + if lockGetProp { + p.sprop = GetProperties(p.stype) + } else { + p.sprop = getPropertiesLocked(p.stype) + } + } +} + +var ( + marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() +) + +// Init populates the properties from a protocol buffer struct tag. +func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { + p.init(typ, name, tag, f, true) +} + +func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) { + // "bytes,49,opt,def=hello!" + p.Name = name + p.OrigName = name + if tag == "" { + return + } + p.Parse(tag) + p.setFieldProps(typ, f, lockGetProp) +} + +var ( + propertiesMu sync.RWMutex + propertiesMap = make(map[reflect.Type]*StructProperties) +) + +// GetProperties returns the list of properties for the type represented by t. +// t must represent a generated struct type of a protocol message. +func GetProperties(t reflect.Type) *StructProperties { + if t.Kind() != reflect.Struct { + panic("proto: type must have kind struct") + } + + // Most calls to GetProperties in a long-running program will be + // retrieving details for types we have seen before. + propertiesMu.RLock() + sprop, ok := propertiesMap[t] + propertiesMu.RUnlock() + if ok { + return sprop + } + + propertiesMu.Lock() + sprop = getPropertiesLocked(t) + propertiesMu.Unlock() + return sprop +} + +type ( + oneofFuncsIface interface { + XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) + } + oneofWrappersIface interface { + XXX_OneofWrappers() []interface{} + } +) + +// getPropertiesLocked requires that propertiesMu is held. +func getPropertiesLocked(t reflect.Type) *StructProperties { + if prop, ok := propertiesMap[t]; ok { + return prop + } + + prop := new(StructProperties) + // in case of recursive protos, fill this in now. + propertiesMap[t] = prop + + // build properties + prop.Prop = make([]*Properties, t.NumField()) + prop.order = make([]int, t.NumField()) + + isOneofMessage := false + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + p := new(Properties) + name := f.Name + p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) + + oneof := f.Tag.Get("protobuf_oneof") // special case + if oneof != "" { + isOneofMessage = true + // Oneof fields don't use the traditional protobuf tag. + p.OrigName = oneof + } + prop.Prop[i] = p + prop.order[i] = i + if debug { + print(i, " ", f.Name, " ", t.String(), " ") + if p.Tag > 0 { + print(p.String()) + } + print("\n") + } + } + + // Re-order prop.order. + sort.Sort(prop) + + if isOneofMessage { + var oots []interface{} + switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) { + case oneofFuncsIface: + _, _, _, oots = m.XXX_OneofFuncs() + case oneofWrappersIface: + oots = m.XXX_OneofWrappers() + } + if len(oots) > 0 { + // Interpret oneof metadata. + prop.OneofTypes = make(map[string]*OneofProperties) + for _, oot := range oots { + oop := &OneofProperties{ + Type: reflect.ValueOf(oot).Type(), // *T + Prop: new(Properties), + } + sft := oop.Type.Elem().Field(0) + oop.Prop.Name = sft.Name + oop.Prop.Parse(sft.Tag.Get("protobuf")) + // There will be exactly one interface field that + // this new value is assignable to. + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Type.Kind() != reflect.Interface { + continue + } + if !oop.Type.AssignableTo(f.Type) { + continue + } + oop.Field = i + break + } + prop.OneofTypes[oop.Prop.OrigName] = oop + } + } + } + + // build required counts + // build tags + reqCount := 0 + prop.decoderOrigNames = make(map[string]int) + for i, p := range prop.Prop { + if strings.HasPrefix(p.Name, "XXX_") { + // Internal fields should not appear in tags/origNames maps. + // They are handled specially when encoding and decoding. + continue + } + if p.Required { + reqCount++ + } + prop.decoderTags.put(p.Tag, i) + prop.decoderOrigNames[p.OrigName] = i + } + prop.reqCount = reqCount + + return prop +} + +// A global registry of enum types. +// The generated code will register the generated maps by calling RegisterEnum. + +var enumValueMaps = make(map[string]map[string]int32) +var enumStringMaps = make(map[string]map[int32]string) + +// RegisterEnum is called from the generated code to install the enum descriptor +// maps into the global table to aid parsing text format protocol buffers. +func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) { + if _, ok := enumValueMaps[typeName]; ok { + panic("proto: duplicate enum registered: " + typeName) + } + enumValueMaps[typeName] = valueMap + if _, ok := enumStringMaps[typeName]; ok { + panic("proto: duplicate enum registered: " + typeName) + } + enumStringMaps[typeName] = unusedNameMap +} + +// EnumValueMap returns the mapping from names to integers of the +// enum type enumType, or a nil if not found. +func EnumValueMap(enumType string) map[string]int32 { + return enumValueMaps[enumType] +} + +// A registry of all linked message types. +// The string is a fully-qualified proto name ("pkg.Message"). +var ( + protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers + protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types + revProtoTypes = make(map[reflect.Type]string) +) + +// RegisterType is called from generated code and maps from the fully qualified +// proto name to the type (pointer to struct) of the protocol buffer. +func RegisterType(x Message, name string) { + if _, ok := protoTypedNils[name]; ok { + // TODO: Some day, make this a panic. + log.Printf("proto: duplicate proto type registered: %s", name) + return + } + t := reflect.TypeOf(x) + if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 { + // Generated code always calls RegisterType with nil x. + // This check is just for extra safety. + protoTypedNils[name] = x + } else { + protoTypedNils[name] = reflect.Zero(t).Interface().(Message) + } + revProtoTypes[t] = name +} + +// RegisterMapType is called from generated code and maps from the fully qualified +// proto name to the native map type of the proto map definition. +func RegisterMapType(x interface{}, name string) { + if reflect.TypeOf(x).Kind() != reflect.Map { + panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name)) + } + if _, ok := protoMapTypes[name]; ok { + log.Printf("proto: duplicate proto type registered: %s", name) + return + } + t := reflect.TypeOf(x) + protoMapTypes[name] = t + revProtoTypes[t] = name +} + +// MessageName returns the fully-qualified proto name for the given message type. +func MessageName(x Message) string { + type xname interface { + XXX_MessageName() string + } + if m, ok := x.(xname); ok { + return m.XXX_MessageName() + } + return revProtoTypes[reflect.TypeOf(x)] +} + +// MessageType returns the message type (pointer to struct) for a named message. +// The type is not guaranteed to implement proto.Message if the name refers to a +// map entry. +func MessageType(name string) reflect.Type { + if t, ok := protoTypedNils[name]; ok { + return reflect.TypeOf(t) + } + return protoMapTypes[name] +} + +// A registry of all linked proto files. +var ( + protoFiles = make(map[string][]byte) // file name => fileDescriptor +) + +// RegisterFile is called from generated code and maps from the +// full file name of a .proto file to its compressed FileDescriptorProto. +func RegisterFile(filename string, fileDescriptor []byte) { + protoFiles[filename] = fileDescriptor +} + +// FileDescriptor returns the compressed FileDescriptorProto for a .proto file. +func FileDescriptor(filename string) []byte { return protoFiles[filename] } diff --git a/vendor/github.com/gogo/protobuf/proto/properties_gogo.go b/vendor/github.com/gogo/protobuf/proto/properties_gogo.go new file mode 100644 index 00000000..40ea3dd9 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/properties_gogo.go @@ -0,0 +1,36 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2018, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "reflect" +) + +var sizerType = reflect.TypeOf((*Sizer)(nil)).Elem() +var protosizerType = reflect.TypeOf((*ProtoSizer)(nil)).Elem() diff --git a/vendor/github.com/gogo/protobuf/proto/skip_gogo.go b/vendor/github.com/gogo/protobuf/proto/skip_gogo.go new file mode 100644 index 00000000..5a5fd93f --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/skip_gogo.go @@ -0,0 +1,119 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "fmt" + "io" +) + +func Skip(data []byte) (n int, err error) { + l := len(data) + index := 0 + for index < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if index >= l { + return 0, io.ErrUnexpectedEOF + } + b := data[index] + index++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for { + if index >= l { + return 0, io.ErrUnexpectedEOF + } + index++ + if data[index-1] < 0x80 { + break + } + } + return index, nil + case 1: + index += 8 + return index, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if index >= l { + return 0, io.ErrUnexpectedEOF + } + b := data[index] + index++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + index += length + return index, nil + case 3: + for { + var innerWire uint64 + var start int = index + for shift := uint(0); ; shift += 7 { + if index >= l { + return 0, io.ErrUnexpectedEOF + } + b := data[index] + index++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := Skip(data[start:]) + if err != nil { + return 0, err + } + index = start + next + } + return index, nil + case 4: + return index, nil + case 5: + index += 4 + return index, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} diff --git a/vendor/github.com/gogo/protobuf/proto/table_marshal.go b/vendor/github.com/gogo/protobuf/proto/table_marshal.go new file mode 100644 index 00000000..f8babdef --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/table_marshal.go @@ -0,0 +1,3009 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2016 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "errors" + "fmt" + "math" + "reflect" + "sort" + "strconv" + "strings" + "sync" + "sync/atomic" + "unicode/utf8" +) + +// a sizer takes a pointer to a field and the size of its tag, computes the size of +// the encoded data. +type sizer func(pointer, int) int + +// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format), +// marshals the field to the end of the slice, returns the slice and error (if any). +type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) + +// marshalInfo is the information used for marshaling a message. +type marshalInfo struct { + typ reflect.Type + fields []*marshalFieldInfo + unrecognized field // offset of XXX_unrecognized + extensions field // offset of XXX_InternalExtensions + v1extensions field // offset of XXX_extensions + sizecache field // offset of XXX_sizecache + initialized int32 // 0 -- only typ is set, 1 -- fully initialized + messageset bool // uses message set wire format + hasmarshaler bool // has custom marshaler + sync.RWMutex // protect extElems map, also for initialization + extElems map[int32]*marshalElemInfo // info of extension elements + + hassizer bool // has custom sizer + hasprotosizer bool // has custom protosizer + + bytesExtensions field // offset of XXX_extensions where the field type is []byte +} + +// marshalFieldInfo is the information used for marshaling a field of a message. +type marshalFieldInfo struct { + field field + wiretag uint64 // tag in wire format + tagsize int // size of tag in wire format + sizer sizer + marshaler marshaler + isPointer bool + required bool // field is required + name string // name of the field, for error reporting + oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements +} + +// marshalElemInfo is the information used for marshaling an extension or oneof element. +type marshalElemInfo struct { + wiretag uint64 // tag in wire format + tagsize int // size of tag in wire format + sizer sizer + marshaler marshaler + isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only) +} + +var ( + marshalInfoMap = map[reflect.Type]*marshalInfo{} + marshalInfoLock sync.Mutex + + uint8SliceType = reflect.TypeOf(([]uint8)(nil)).Kind() +) + +// getMarshalInfo returns the information to marshal a given type of message. +// The info it returns may not necessarily initialized. +// t is the type of the message (NOT the pointer to it). +func getMarshalInfo(t reflect.Type) *marshalInfo { + marshalInfoLock.Lock() + u, ok := marshalInfoMap[t] + if !ok { + u = &marshalInfo{typ: t} + marshalInfoMap[t] = u + } + marshalInfoLock.Unlock() + return u +} + +// Size is the entry point from generated code, +// and should be ONLY called by generated code. +// It computes the size of encoded data of msg. +// a is a pointer to a place to store cached marshal info. +func (a *InternalMessageInfo) Size(msg Message) int { + u := getMessageMarshalInfo(msg, a) + ptr := toPointer(&msg) + if ptr.isNil() { + // We get here if msg is a typed nil ((*SomeMessage)(nil)), + // so it satisfies the interface, and msg == nil wouldn't + // catch it. We don't want crash in this case. + return 0 + } + return u.size(ptr) +} + +// Marshal is the entry point from generated code, +// and should be ONLY called by generated code. +// It marshals msg to the end of b. +// a is a pointer to a place to store cached marshal info. +func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) { + u := getMessageMarshalInfo(msg, a) + ptr := toPointer(&msg) + if ptr.isNil() { + // We get here if msg is a typed nil ((*SomeMessage)(nil)), + // so it satisfies the interface, and msg == nil wouldn't + // catch it. We don't want crash in this case. + return b, ErrNil + } + return u.marshal(b, ptr, deterministic) +} + +func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo { + // u := a.marshal, but atomically. + // We use an atomic here to ensure memory consistency. + u := atomicLoadMarshalInfo(&a.marshal) + if u == nil { + // Get marshal information from type of message. + t := reflect.ValueOf(msg).Type() + if t.Kind() != reflect.Ptr { + panic(fmt.Sprintf("cannot handle non-pointer message type %v", t)) + } + u = getMarshalInfo(t.Elem()) + // Store it in the cache for later users. + // a.marshal = u, but atomically. + atomicStoreMarshalInfo(&a.marshal, u) + } + return u +} + +// size is the main function to compute the size of the encoded data of a message. +// ptr is the pointer to the message. +func (u *marshalInfo) size(ptr pointer) int { + if atomic.LoadInt32(&u.initialized) == 0 { + u.computeMarshalInfo() + } + + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + if u.hasmarshaler { + // Uses the message's Size method if available + if u.hassizer { + s := ptr.asPointerTo(u.typ).Interface().(Sizer) + return s.Size() + } + // Uses the message's ProtoSize method if available + if u.hasprotosizer { + s := ptr.asPointerTo(u.typ).Interface().(ProtoSizer) + return s.ProtoSize() + } + + m := ptr.asPointerTo(u.typ).Interface().(Marshaler) + b, _ := m.Marshal() + return len(b) + } + + n := 0 + for _, f := range u.fields { + if f.isPointer && ptr.offset(f.field).getPointer().isNil() { + // nil pointer always marshals to nothing + continue + } + n += f.sizer(ptr.offset(f.field), f.tagsize) + } + if u.extensions.IsValid() { + e := ptr.offset(u.extensions).toExtensions() + if u.messageset { + n += u.sizeMessageSet(e) + } else { + n += u.sizeExtensions(e) + } + } + if u.v1extensions.IsValid() { + m := *ptr.offset(u.v1extensions).toOldExtensions() + n += u.sizeV1Extensions(m) + } + if u.bytesExtensions.IsValid() { + s := *ptr.offset(u.bytesExtensions).toBytes() + n += len(s) + } + if u.unrecognized.IsValid() { + s := *ptr.offset(u.unrecognized).toBytes() + n += len(s) + } + + // cache the result for use in marshal + if u.sizecache.IsValid() { + atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n)) + } + return n +} + +// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated), +// fall back to compute the size. +func (u *marshalInfo) cachedsize(ptr pointer) int { + if u.sizecache.IsValid() { + return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32())) + } + return u.size(ptr) +} + +// marshal is the main function to marshal a message. It takes a byte slice and appends +// the encoded data to the end of the slice, returns the slice and error (if any). +// ptr is the pointer to the message. +// If deterministic is true, map is marshaled in deterministic order. +func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) { + if atomic.LoadInt32(&u.initialized) == 0 { + u.computeMarshalInfo() + } + + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + if u.hasmarshaler { + m := ptr.asPointerTo(u.typ).Interface().(Marshaler) + b1, err := m.Marshal() + b = append(b, b1...) + return b, err + } + + var err, errLater error + // The old marshaler encodes extensions at beginning. + if u.extensions.IsValid() { + e := ptr.offset(u.extensions).toExtensions() + if u.messageset { + b, err = u.appendMessageSet(b, e, deterministic) + } else { + b, err = u.appendExtensions(b, e, deterministic) + } + if err != nil { + return b, err + } + } + if u.v1extensions.IsValid() { + m := *ptr.offset(u.v1extensions).toOldExtensions() + b, err = u.appendV1Extensions(b, m, deterministic) + if err != nil { + return b, err + } + } + if u.bytesExtensions.IsValid() { + s := *ptr.offset(u.bytesExtensions).toBytes() + b = append(b, s...) + } + for _, f := range u.fields { + if f.required { + if f.isPointer && ptr.offset(f.field).getPointer().isNil() { + // Required field is not set. + // We record the error but keep going, to give a complete marshaling. + if errLater == nil { + errLater = &RequiredNotSetError{f.name} + } + continue + } + } + if f.isPointer && ptr.offset(f.field).getPointer().isNil() { + // nil pointer always marshals to nothing + continue + } + b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic) + if err != nil { + if err1, ok := err.(*RequiredNotSetError); ok { + // Required field in submessage is not set. + // We record the error but keep going, to give a complete marshaling. + if errLater == nil { + errLater = &RequiredNotSetError{f.name + "." + err1.field} + } + continue + } + if err == errRepeatedHasNil { + err = errors.New("proto: repeated field " + f.name + " has nil element") + } + if err == errInvalidUTF8 { + if errLater == nil { + fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name + errLater = &invalidUTF8Error{fullName} + } + continue + } + return b, err + } + } + if u.unrecognized.IsValid() { + s := *ptr.offset(u.unrecognized).toBytes() + b = append(b, s...) + } + return b, errLater +} + +// computeMarshalInfo initializes the marshal info. +func (u *marshalInfo) computeMarshalInfo() { + u.Lock() + defer u.Unlock() + if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock + return + } + + t := u.typ + u.unrecognized = invalidField + u.extensions = invalidField + u.v1extensions = invalidField + u.bytesExtensions = invalidField + u.sizecache = invalidField + isOneofMessage := false + + if reflect.PtrTo(t).Implements(sizerType) { + u.hassizer = true + } + if reflect.PtrTo(t).Implements(protosizerType) { + u.hasprotosizer = true + } + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + if reflect.PtrTo(t).Implements(marshalerType) { + u.hasmarshaler = true + atomic.StoreInt32(&u.initialized, 1) + return + } + + n := t.NumField() + + // deal with XXX fields first + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Tag.Get("protobuf_oneof") != "" { + isOneofMessage = true + } + if !strings.HasPrefix(f.Name, "XXX_") { + continue + } + switch f.Name { + case "XXX_sizecache": + u.sizecache = toField(&f) + case "XXX_unrecognized": + u.unrecognized = toField(&f) + case "XXX_InternalExtensions": + u.extensions = toField(&f) + u.messageset = f.Tag.Get("protobuf_messageset") == "1" + case "XXX_extensions": + if f.Type.Kind() == reflect.Map { + u.v1extensions = toField(&f) + } else { + u.bytesExtensions = toField(&f) + } + case "XXX_NoUnkeyedLiteral": + // nothing to do + default: + panic("unknown XXX field: " + f.Name) + } + n-- + } + + // get oneof implementers + var oneofImplementers []interface{} + // gogo: isOneofMessage is needed for embedded oneof messages, without a marshaler and unmarshaler + if isOneofMessage { + switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) { + case oneofFuncsIface: + _, _, _, oneofImplementers = m.XXX_OneofFuncs() + case oneofWrappersIface: + oneofImplementers = m.XXX_OneofWrappers() + } + } + + // normal fields + fields := make([]marshalFieldInfo, n) // batch allocation + u.fields = make([]*marshalFieldInfo, 0, n) + for i, j := 0, 0; i < t.NumField(); i++ { + f := t.Field(i) + + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + field := &fields[j] + j++ + field.name = f.Name + u.fields = append(u.fields, field) + if f.Tag.Get("protobuf_oneof") != "" { + field.computeOneofFieldInfo(&f, oneofImplementers) + continue + } + if f.Tag.Get("protobuf") == "" { + // field has no tag (not in generated message), ignore it + u.fields = u.fields[:len(u.fields)-1] + j-- + continue + } + field.computeMarshalFieldInfo(&f) + } + + // fields are marshaled in tag order on the wire. + sort.Sort(byTag(u.fields)) + + atomic.StoreInt32(&u.initialized, 1) +} + +// helper for sorting fields by tag +type byTag []*marshalFieldInfo + +func (a byTag) Len() int { return len(a) } +func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag } + +// getExtElemInfo returns the information to marshal an extension element. +// The info it returns is initialized. +func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo { + // get from cache first + u.RLock() + e, ok := u.extElems[desc.Field] + u.RUnlock() + if ok { + return e + } + + t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct + tags := strings.Split(desc.Tag, ",") + tag, err := strconv.Atoi(tags[1]) + if err != nil { + panic("tag is not an integer") + } + wt := wiretype(tags[0]) + sizr, marshalr := typeMarshaler(t, tags, false, false) + e = &marshalElemInfo{ + wiretag: uint64(tag)<<3 | wt, + tagsize: SizeVarint(uint64(tag) << 3), + sizer: sizr, + marshaler: marshalr, + isptr: t.Kind() == reflect.Ptr, + } + + // update cache + u.Lock() + if u.extElems == nil { + u.extElems = make(map[int32]*marshalElemInfo) + } + u.extElems[desc.Field] = e + u.Unlock() + return e +} + +// computeMarshalFieldInfo fills up the information to marshal a field. +func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) { + // parse protobuf tag of the field. + // tag has format of "bytes,49,opt,name=foo,def=hello!" + tags := strings.Split(f.Tag.Get("protobuf"), ",") + if tags[0] == "" { + return + } + tag, err := strconv.Atoi(tags[1]) + if err != nil { + panic("tag is not an integer") + } + wt := wiretype(tags[0]) + if tags[2] == "req" { + fi.required = true + } + fi.setTag(f, tag, wt) + fi.setMarshaler(f, tags) +} + +func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) { + fi.field = toField(f) + fi.wiretag = math.MaxInt32 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire. + fi.isPointer = true + fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f) + fi.oneofElems = make(map[reflect.Type]*marshalElemInfo) + + ityp := f.Type // interface type + for _, o := range oneofImplementers { + t := reflect.TypeOf(o) + if !t.Implements(ityp) { + continue + } + sf := t.Elem().Field(0) // oneof implementer is a struct with a single field + tags := strings.Split(sf.Tag.Get("protobuf"), ",") + tag, err := strconv.Atoi(tags[1]) + if err != nil { + panic("tag is not an integer") + } + wt := wiretype(tags[0]) + sizr, marshalr := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value + fi.oneofElems[t.Elem()] = &marshalElemInfo{ + wiretag: uint64(tag)<<3 | wt, + tagsize: SizeVarint(uint64(tag) << 3), + sizer: sizr, + marshaler: marshalr, + } + } +} + +// wiretype returns the wire encoding of the type. +func wiretype(encoding string) uint64 { + switch encoding { + case "fixed32": + return WireFixed32 + case "fixed64": + return WireFixed64 + case "varint", "zigzag32", "zigzag64": + return WireVarint + case "bytes": + return WireBytes + case "group": + return WireStartGroup + } + panic("unknown wire type " + encoding) +} + +// setTag fills up the tag (in wire format) and its size in the info of a field. +func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) { + fi.field = toField(f) + fi.wiretag = uint64(tag)<<3 | wt + fi.tagsize = SizeVarint(uint64(tag) << 3) +} + +// setMarshaler fills up the sizer and marshaler in the info of a field. +func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) { + switch f.Type.Kind() { + case reflect.Map: + // map field + fi.isPointer = true + fi.sizer, fi.marshaler = makeMapMarshaler(f) + return + case reflect.Ptr, reflect.Slice: + fi.isPointer = true + } + fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false) +} + +// typeMarshaler returns the sizer and marshaler of a given field. +// t is the type of the field. +// tags is the generated "protobuf" tag of the field. +// If nozero is true, zero value is not marshaled to the wire. +// If oneof is true, it is a oneof field. +func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) { + encoding := tags[0] + + pointer := false + slice := false + if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { + slice = true + t = t.Elem() + } + if t.Kind() == reflect.Ptr { + pointer = true + t = t.Elem() + } + + packed := false + proto3 := false + ctype := false + isTime := false + isDuration := false + isWktPointer := false + validateUTF8 := true + for i := 2; i < len(tags); i++ { + if tags[i] == "packed" { + packed = true + } + if tags[i] == "proto3" { + proto3 = true + } + if strings.HasPrefix(tags[i], "customtype=") { + ctype = true + } + if tags[i] == "stdtime" { + isTime = true + } + if tags[i] == "stdduration" { + isDuration = true + } + if tags[i] == "wktptr" { + isWktPointer = true + } + } + validateUTF8 = validateUTF8 && proto3 + if !proto3 && !pointer && !slice { + nozero = false + } + + if ctype { + if reflect.PtrTo(t).Implements(customType) { + if slice { + return makeMessageRefSliceMarshaler(getMarshalInfo(t)) + } + if pointer { + return makeCustomPtrMarshaler(getMarshalInfo(t)) + } + return makeCustomMarshaler(getMarshalInfo(t)) + } else { + panic(fmt.Sprintf("custom type: type: %v, does not implement the proto.custom interface", t)) + } + } + + if isTime { + if pointer { + if slice { + return makeTimePtrSliceMarshaler(getMarshalInfo(t)) + } + return makeTimePtrMarshaler(getMarshalInfo(t)) + } + if slice { + return makeTimeSliceMarshaler(getMarshalInfo(t)) + } + return makeTimeMarshaler(getMarshalInfo(t)) + } + + if isDuration { + if pointer { + if slice { + return makeDurationPtrSliceMarshaler(getMarshalInfo(t)) + } + return makeDurationPtrMarshaler(getMarshalInfo(t)) + } + if slice { + return makeDurationSliceMarshaler(getMarshalInfo(t)) + } + return makeDurationMarshaler(getMarshalInfo(t)) + } + + if isWktPointer { + switch t.Kind() { + case reflect.Float64: + if pointer { + if slice { + return makeStdDoubleValuePtrSliceMarshaler(getMarshalInfo(t)) + } + return makeStdDoubleValuePtrMarshaler(getMarshalInfo(t)) + } + if slice { + return makeStdDoubleValueSliceMarshaler(getMarshalInfo(t)) + } + return makeStdDoubleValueMarshaler(getMarshalInfo(t)) + case reflect.Float32: + if pointer { + if slice { + return makeStdFloatValuePtrSliceMarshaler(getMarshalInfo(t)) + } + return makeStdFloatValuePtrMarshaler(getMarshalInfo(t)) + } + if slice { + return makeStdFloatValueSliceMarshaler(getMarshalInfo(t)) + } + return makeStdFloatValueMarshaler(getMarshalInfo(t)) + case reflect.Int64: + if pointer { + if slice { + return makeStdInt64ValuePtrSliceMarshaler(getMarshalInfo(t)) + } + return makeStdInt64ValuePtrMarshaler(getMarshalInfo(t)) + } + if slice { + return makeStdInt64ValueSliceMarshaler(getMarshalInfo(t)) + } + return makeStdInt64ValueMarshaler(getMarshalInfo(t)) + case reflect.Uint64: + if pointer { + if slice { + return makeStdUInt64ValuePtrSliceMarshaler(getMarshalInfo(t)) + } + return makeStdUInt64ValuePtrMarshaler(getMarshalInfo(t)) + } + if slice { + return makeStdUInt64ValueSliceMarshaler(getMarshalInfo(t)) + } + return makeStdUInt64ValueMarshaler(getMarshalInfo(t)) + case reflect.Int32: + if pointer { + if slice { + return makeStdInt32ValuePtrSliceMarshaler(getMarshalInfo(t)) + } + return makeStdInt32ValuePtrMarshaler(getMarshalInfo(t)) + } + if slice { + return makeStdInt32ValueSliceMarshaler(getMarshalInfo(t)) + } + return makeStdInt32ValueMarshaler(getMarshalInfo(t)) + case reflect.Uint32: + if pointer { + if slice { + return makeStdUInt32ValuePtrSliceMarshaler(getMarshalInfo(t)) + } + return makeStdUInt32ValuePtrMarshaler(getMarshalInfo(t)) + } + if slice { + return makeStdUInt32ValueSliceMarshaler(getMarshalInfo(t)) + } + return makeStdUInt32ValueMarshaler(getMarshalInfo(t)) + case reflect.Bool: + if pointer { + if slice { + return makeStdBoolValuePtrSliceMarshaler(getMarshalInfo(t)) + } + return makeStdBoolValuePtrMarshaler(getMarshalInfo(t)) + } + if slice { + return makeStdBoolValueSliceMarshaler(getMarshalInfo(t)) + } + return makeStdBoolValueMarshaler(getMarshalInfo(t)) + case reflect.String: + if pointer { + if slice { + return makeStdStringValuePtrSliceMarshaler(getMarshalInfo(t)) + } + return makeStdStringValuePtrMarshaler(getMarshalInfo(t)) + } + if slice { + return makeStdStringValueSliceMarshaler(getMarshalInfo(t)) + } + return makeStdStringValueMarshaler(getMarshalInfo(t)) + case uint8SliceType: + if pointer { + if slice { + return makeStdBytesValuePtrSliceMarshaler(getMarshalInfo(t)) + } + return makeStdBytesValuePtrMarshaler(getMarshalInfo(t)) + } + if slice { + return makeStdBytesValueSliceMarshaler(getMarshalInfo(t)) + } + return makeStdBytesValueMarshaler(getMarshalInfo(t)) + default: + panic(fmt.Sprintf("unknown wktpointer type %#v", t)) + } + } + + switch t.Kind() { + case reflect.Bool: + if pointer { + return sizeBoolPtr, appendBoolPtr + } + if slice { + if packed { + return sizeBoolPackedSlice, appendBoolPackedSlice + } + return sizeBoolSlice, appendBoolSlice + } + if nozero { + return sizeBoolValueNoZero, appendBoolValueNoZero + } + return sizeBoolValue, appendBoolValue + case reflect.Uint32: + switch encoding { + case "fixed32": + if pointer { + return sizeFixed32Ptr, appendFixed32Ptr + } + if slice { + if packed { + return sizeFixed32PackedSlice, appendFixed32PackedSlice + } + return sizeFixed32Slice, appendFixed32Slice + } + if nozero { + return sizeFixed32ValueNoZero, appendFixed32ValueNoZero + } + return sizeFixed32Value, appendFixed32Value + case "varint": + if pointer { + return sizeVarint32Ptr, appendVarint32Ptr + } + if slice { + if packed { + return sizeVarint32PackedSlice, appendVarint32PackedSlice + } + return sizeVarint32Slice, appendVarint32Slice + } + if nozero { + return sizeVarint32ValueNoZero, appendVarint32ValueNoZero + } + return sizeVarint32Value, appendVarint32Value + } + case reflect.Int32: + switch encoding { + case "fixed32": + if pointer { + return sizeFixedS32Ptr, appendFixedS32Ptr + } + if slice { + if packed { + return sizeFixedS32PackedSlice, appendFixedS32PackedSlice + } + return sizeFixedS32Slice, appendFixedS32Slice + } + if nozero { + return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero + } + return sizeFixedS32Value, appendFixedS32Value + case "varint": + if pointer { + return sizeVarintS32Ptr, appendVarintS32Ptr + } + if slice { + if packed { + return sizeVarintS32PackedSlice, appendVarintS32PackedSlice + } + return sizeVarintS32Slice, appendVarintS32Slice + } + if nozero { + return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero + } + return sizeVarintS32Value, appendVarintS32Value + case "zigzag32": + if pointer { + return sizeZigzag32Ptr, appendZigzag32Ptr + } + if slice { + if packed { + return sizeZigzag32PackedSlice, appendZigzag32PackedSlice + } + return sizeZigzag32Slice, appendZigzag32Slice + } + if nozero { + return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero + } + return sizeZigzag32Value, appendZigzag32Value + } + case reflect.Uint64: + switch encoding { + case "fixed64": + if pointer { + return sizeFixed64Ptr, appendFixed64Ptr + } + if slice { + if packed { + return sizeFixed64PackedSlice, appendFixed64PackedSlice + } + return sizeFixed64Slice, appendFixed64Slice + } + if nozero { + return sizeFixed64ValueNoZero, appendFixed64ValueNoZero + } + return sizeFixed64Value, appendFixed64Value + case "varint": + if pointer { + return sizeVarint64Ptr, appendVarint64Ptr + } + if slice { + if packed { + return sizeVarint64PackedSlice, appendVarint64PackedSlice + } + return sizeVarint64Slice, appendVarint64Slice + } + if nozero { + return sizeVarint64ValueNoZero, appendVarint64ValueNoZero + } + return sizeVarint64Value, appendVarint64Value + } + case reflect.Int64: + switch encoding { + case "fixed64": + if pointer { + return sizeFixedS64Ptr, appendFixedS64Ptr + } + if slice { + if packed { + return sizeFixedS64PackedSlice, appendFixedS64PackedSlice + } + return sizeFixedS64Slice, appendFixedS64Slice + } + if nozero { + return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero + } + return sizeFixedS64Value, appendFixedS64Value + case "varint": + if pointer { + return sizeVarintS64Ptr, appendVarintS64Ptr + } + if slice { + if packed { + return sizeVarintS64PackedSlice, appendVarintS64PackedSlice + } + return sizeVarintS64Slice, appendVarintS64Slice + } + if nozero { + return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero + } + return sizeVarintS64Value, appendVarintS64Value + case "zigzag64": + if pointer { + return sizeZigzag64Ptr, appendZigzag64Ptr + } + if slice { + if packed { + return sizeZigzag64PackedSlice, appendZigzag64PackedSlice + } + return sizeZigzag64Slice, appendZigzag64Slice + } + if nozero { + return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero + } + return sizeZigzag64Value, appendZigzag64Value + } + case reflect.Float32: + if pointer { + return sizeFloat32Ptr, appendFloat32Ptr + } + if slice { + if packed { + return sizeFloat32PackedSlice, appendFloat32PackedSlice + } + return sizeFloat32Slice, appendFloat32Slice + } + if nozero { + return sizeFloat32ValueNoZero, appendFloat32ValueNoZero + } + return sizeFloat32Value, appendFloat32Value + case reflect.Float64: + if pointer { + return sizeFloat64Ptr, appendFloat64Ptr + } + if slice { + if packed { + return sizeFloat64PackedSlice, appendFloat64PackedSlice + } + return sizeFloat64Slice, appendFloat64Slice + } + if nozero { + return sizeFloat64ValueNoZero, appendFloat64ValueNoZero + } + return sizeFloat64Value, appendFloat64Value + case reflect.String: + if validateUTF8 { + if pointer { + return sizeStringPtr, appendUTF8StringPtr + } + if slice { + return sizeStringSlice, appendUTF8StringSlice + } + if nozero { + return sizeStringValueNoZero, appendUTF8StringValueNoZero + } + return sizeStringValue, appendUTF8StringValue + } + if pointer { + return sizeStringPtr, appendStringPtr + } + if slice { + return sizeStringSlice, appendStringSlice + } + if nozero { + return sizeStringValueNoZero, appendStringValueNoZero + } + return sizeStringValue, appendStringValue + case reflect.Slice: + if slice { + return sizeBytesSlice, appendBytesSlice + } + if oneof { + // Oneof bytes field may also have "proto3" tag. + // We want to marshal it as a oneof field. Do this + // check before the proto3 check. + return sizeBytesOneof, appendBytesOneof + } + if proto3 { + return sizeBytes3, appendBytes3 + } + return sizeBytes, appendBytes + case reflect.Struct: + switch encoding { + case "group": + if slice { + return makeGroupSliceMarshaler(getMarshalInfo(t)) + } + return makeGroupMarshaler(getMarshalInfo(t)) + case "bytes": + if pointer { + if slice { + return makeMessageSliceMarshaler(getMarshalInfo(t)) + } + return makeMessageMarshaler(getMarshalInfo(t)) + } else { + if slice { + return makeMessageRefSliceMarshaler(getMarshalInfo(t)) + } + return makeMessageRefMarshaler(getMarshalInfo(t)) + } + } + } + panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding)) +} + +// Below are functions to size/marshal a specific type of a field. +// They are stored in the field's info, and called by function pointers. +// They have type sizer or marshaler. + +func sizeFixed32Value(_ pointer, tagsize int) int { + return 4 + tagsize +} +func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toUint32() + if v == 0 { + return 0 + } + return 4 + tagsize +} +func sizeFixed32Ptr(ptr pointer, tagsize int) int { + p := *ptr.toUint32Ptr() + if p == nil { + return 0 + } + return 4 + tagsize +} +func sizeFixed32Slice(ptr pointer, tagsize int) int { + s := *ptr.toUint32Slice() + return (4 + tagsize) * len(s) +} +func sizeFixed32PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toUint32Slice() + if len(s) == 0 { + return 0 + } + return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize +} +func sizeFixedS32Value(_ pointer, tagsize int) int { + return 4 + tagsize +} +func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + if v == 0 { + return 0 + } + return 4 + tagsize +} +func sizeFixedS32Ptr(ptr pointer, tagsize int) int { + p := ptr.getInt32Ptr() + if p == nil { + return 0 + } + return 4 + tagsize +} +func sizeFixedS32Slice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + return (4 + tagsize) * len(s) +} +func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + if len(s) == 0 { + return 0 + } + return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize +} +func sizeFloat32Value(_ pointer, tagsize int) int { + return 4 + tagsize +} +func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int { + v := math.Float32bits(*ptr.toFloat32()) + if v == 0 { + return 0 + } + return 4 + tagsize +} +func sizeFloat32Ptr(ptr pointer, tagsize int) int { + p := *ptr.toFloat32Ptr() + if p == nil { + return 0 + } + return 4 + tagsize +} +func sizeFloat32Slice(ptr pointer, tagsize int) int { + s := *ptr.toFloat32Slice() + return (4 + tagsize) * len(s) +} +func sizeFloat32PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toFloat32Slice() + if len(s) == 0 { + return 0 + } + return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize +} +func sizeFixed64Value(_ pointer, tagsize int) int { + return 8 + tagsize +} +func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toUint64() + if v == 0 { + return 0 + } + return 8 + tagsize +} +func sizeFixed64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toUint64Ptr() + if p == nil { + return 0 + } + return 8 + tagsize +} +func sizeFixed64Slice(ptr pointer, tagsize int) int { + s := *ptr.toUint64Slice() + return (8 + tagsize) * len(s) +} +func sizeFixed64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toUint64Slice() + if len(s) == 0 { + return 0 + } + return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize +} +func sizeFixedS64Value(_ pointer, tagsize int) int { + return 8 + tagsize +} +func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + if v == 0 { + return 0 + } + return 8 + tagsize +} +func sizeFixedS64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toInt64Ptr() + if p == nil { + return 0 + } + return 8 + tagsize +} +func sizeFixedS64Slice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + return (8 + tagsize) * len(s) +} +func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return 0 + } + return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize +} +func sizeFloat64Value(_ pointer, tagsize int) int { + return 8 + tagsize +} +func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int { + v := math.Float64bits(*ptr.toFloat64()) + if v == 0 { + return 0 + } + return 8 + tagsize +} +func sizeFloat64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toFloat64Ptr() + if p == nil { + return 0 + } + return 8 + tagsize +} +func sizeFloat64Slice(ptr pointer, tagsize int) int { + s := *ptr.toFloat64Slice() + return (8 + tagsize) * len(s) +} +func sizeFloat64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toFloat64Slice() + if len(s) == 0 { + return 0 + } + return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize +} +func sizeVarint32Value(ptr pointer, tagsize int) int { + v := *ptr.toUint32() + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toUint32() + if v == 0 { + return 0 + } + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarint32Ptr(ptr pointer, tagsize int) int { + p := *ptr.toUint32Ptr() + if p == nil { + return 0 + } + return SizeVarint(uint64(*p)) + tagsize +} +func sizeVarint32Slice(ptr pointer, tagsize int) int { + s := *ptr.toUint32Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + tagsize + } + return n +} +func sizeVarint32PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toUint32Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeVarintS32Value(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + if v == 0 { + return 0 + } + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarintS32Ptr(ptr pointer, tagsize int) int { + p := ptr.getInt32Ptr() + if p == nil { + return 0 + } + return SizeVarint(uint64(*p)) + tagsize +} +func sizeVarintS32Slice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + tagsize + } + return n +} +func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeVarint64Value(ptr pointer, tagsize int) int { + v := *ptr.toUint64() + return SizeVarint(v) + tagsize +} +func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toUint64() + if v == 0 { + return 0 + } + return SizeVarint(v) + tagsize +} +func sizeVarint64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toUint64Ptr() + if p == nil { + return 0 + } + return SizeVarint(*p) + tagsize +} +func sizeVarint64Slice(ptr pointer, tagsize int) int { + s := *ptr.toUint64Slice() + n := 0 + for _, v := range s { + n += SizeVarint(v) + tagsize + } + return n +} +func sizeVarint64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toUint64Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(v) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeVarintS64Value(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + if v == 0 { + return 0 + } + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarintS64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toInt64Ptr() + if p == nil { + return 0 + } + return SizeVarint(uint64(*p)) + tagsize +} +func sizeVarintS64Slice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + tagsize + } + return n +} +func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeZigzag32Value(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize +} +func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + if v == 0 { + return 0 + } + return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize +} +func sizeZigzag32Ptr(ptr pointer, tagsize int) int { + p := ptr.getInt32Ptr() + if p == nil { + return 0 + } + v := *p + return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize +} +func sizeZigzag32Slice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize + } + return n +} +func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeZigzag64Value(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize +} +func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + if v == 0 { + return 0 + } + return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize +} +func sizeZigzag64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toInt64Ptr() + if p == nil { + return 0 + } + v := *p + return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize +} +func sizeZigzag64Slice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize + } + return n +} +func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeBoolValue(_ pointer, tagsize int) int { + return 1 + tagsize +} +func sizeBoolValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toBool() + if !v { + return 0 + } + return 1 + tagsize +} +func sizeBoolPtr(ptr pointer, tagsize int) int { + p := *ptr.toBoolPtr() + if p == nil { + return 0 + } + return 1 + tagsize +} +func sizeBoolSlice(ptr pointer, tagsize int) int { + s := *ptr.toBoolSlice() + return (1 + tagsize) * len(s) +} +func sizeBoolPackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toBoolSlice() + if len(s) == 0 { + return 0 + } + return len(s) + SizeVarint(uint64(len(s))) + tagsize +} +func sizeStringValue(ptr pointer, tagsize int) int { + v := *ptr.toString() + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeStringValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toString() + if v == "" { + return 0 + } + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeStringPtr(ptr pointer, tagsize int) int { + p := *ptr.toStringPtr() + if p == nil { + return 0 + } + v := *p + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeStringSlice(ptr pointer, tagsize int) int { + s := *ptr.toStringSlice() + n := 0 + for _, v := range s { + n += len(v) + SizeVarint(uint64(len(v))) + tagsize + } + return n +} +func sizeBytes(ptr pointer, tagsize int) int { + v := *ptr.toBytes() + if v == nil { + return 0 + } + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeBytes3(ptr pointer, tagsize int) int { + v := *ptr.toBytes() + if len(v) == 0 { + return 0 + } + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeBytesOneof(ptr pointer, tagsize int) int { + v := *ptr.toBytes() + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeBytesSlice(ptr pointer, tagsize int) int { + s := *ptr.toBytesSlice() + n := 0 + for _, v := range s { + n += len(v) + SizeVarint(uint64(len(v))) + tagsize + } + return n +} + +// appendFixed32 appends an encoded fixed32 to b. +func appendFixed32(b []byte, v uint32) []byte { + b = append(b, + byte(v), + byte(v>>8), + byte(v>>16), + byte(v>>24)) + return b +} + +// appendFixed64 appends an encoded fixed64 to b. +func appendFixed64(b []byte, v uint64) []byte { + b = append(b, + byte(v), + byte(v>>8), + byte(v>>16), + byte(v>>24), + byte(v>>32), + byte(v>>40), + byte(v>>48), + byte(v>>56)) + return b +} + +// appendVarint appends an encoded varint to b. +func appendVarint(b []byte, v uint64) []byte { + // TODO: make 1-byte (maybe 2-byte) case inline-able, once we + // have non-leaf inliner. + switch { + case v < 1<<7: + b = append(b, byte(v)) + case v < 1<<14: + b = append(b, + byte(v&0x7f|0x80), + byte(v>>7)) + case v < 1<<21: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte(v>>14)) + case v < 1<<28: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte(v>>21)) + case v < 1<<35: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte(v>>28)) + case v < 1<<42: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte(v>>35)) + case v < 1<<49: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte(v>>42)) + case v < 1<<56: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte((v>>42)&0x7f|0x80), + byte(v>>49)) + case v < 1<<63: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte((v>>42)&0x7f|0x80), + byte((v>>49)&0x7f|0x80), + byte(v>>56)) + default: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte((v>>42)&0x7f|0x80), + byte((v>>49)&0x7f|0x80), + byte((v>>56)&0x7f|0x80), + 1) + } + return b +} + +func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint32() + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + return b, nil +} +func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + return b, nil +} +func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toUint32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, *p) + return b, nil +} +func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + } + return b, nil +} +func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(4*len(s))) + for _, v := range s { + b = appendFixed32(b, v) + } + return b, nil +} +func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + b = appendVarint(b, wiretag) + b = appendFixed32(b, uint32(v)) + return b, nil +} +func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, uint32(v)) + return b, nil +} +func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := ptr.getInt32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, uint32(*p)) + return b, nil +} +func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed32(b, uint32(v)) + } + return b, nil +} +func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(4*len(s))) + for _, v := range s { + b = appendFixed32(b, uint32(v)) + } + return b, nil +} +func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := math.Float32bits(*ptr.toFloat32()) + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + return b, nil +} +func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := math.Float32bits(*ptr.toFloat32()) + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + return b, nil +} +func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toFloat32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, math.Float32bits(*p)) + return b, nil +} +func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toFloat32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed32(b, math.Float32bits(v)) + } + return b, nil +} +func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toFloat32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(4*len(s))) + for _, v := range s { + b = appendFixed32(b, math.Float32bits(v)) + } + return b, nil +} +func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint64() + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + return b, nil +} +func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + return b, nil +} +func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toUint64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, *p) + return b, nil +} +func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + } + return b, nil +} +func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(8*len(s))) + for _, v := range s { + b = appendFixed64(b, v) + } + return b, nil +} +func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + b = appendVarint(b, wiretag) + b = appendFixed64(b, uint64(v)) + return b, nil +} +func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, uint64(v)) + return b, nil +} +func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toInt64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, uint64(*p)) + return b, nil +} +func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed64(b, uint64(v)) + } + return b, nil +} +func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(8*len(s))) + for _, v := range s { + b = appendFixed64(b, uint64(v)) + } + return b, nil +} +func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := math.Float64bits(*ptr.toFloat64()) + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + return b, nil +} +func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := math.Float64bits(*ptr.toFloat64()) + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + return b, nil +} +func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toFloat64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, math.Float64bits(*p)) + return b, nil +} +func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toFloat64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed64(b, math.Float64bits(v)) + } + return b, nil +} +func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toFloat64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(8*len(s))) + for _, v := range s { + b = appendFixed64(b, math.Float64bits(v)) + } + return b, nil +} +func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint32() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toUint32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(*p)) + return b, nil +} +func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := ptr.getInt32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(*p)) + return b, nil +} +func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint64() + b = appendVarint(b, wiretag) + b = appendVarint(b, v) + return b, nil +} +func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, v) + return b, nil +} +func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toUint64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, *p) + return b, nil +} +func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, v) + } + return b, nil +} +func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(v) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, v) + } + return b, nil +} +func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toInt64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(*p)) + return b, nil +} +func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + return b, nil +} +func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + return b, nil +} +func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := ptr.getInt32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + v := *p + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + return b, nil +} +func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + } + return b, nil +} +func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + } + return b, nil +} +func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + return b, nil +} +func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + return b, nil +} +func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toInt64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + v := *p + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + return b, nil +} +func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + } + return b, nil +} +func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + } + return b, nil +} +func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBool() + b = appendVarint(b, wiretag) + if v { + b = append(b, 1) + } else { + b = append(b, 0) + } + return b, nil +} +func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBool() + if !v { + return b, nil + } + b = appendVarint(b, wiretag) + b = append(b, 1) + return b, nil +} + +func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toBoolPtr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + if *p { + b = append(b, 1) + } else { + b = append(b, 0) + } + return b, nil +} +func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toBoolSlice() + for _, v := range s { + b = appendVarint(b, wiretag) + if v { + b = append(b, 1) + } else { + b = append(b, 0) + } + } + return b, nil +} +func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toBoolSlice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(len(s))) + for _, v := range s { + if v { + b = append(b, 1) + } else { + b = append(b, 0) + } + } + return b, nil +} +func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toString() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toString() + if v == "" { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toStringPtr() + if p == nil { + return b, nil + } + v := *p + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toStringSlice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + } + return b, nil +} +func appendUTF8StringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + var invalidUTF8 bool + v := *ptr.toString() + if !utf8.ValidString(v) { + invalidUTF8 = true + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + if invalidUTF8 { + return b, errInvalidUTF8 + } + return b, nil +} +func appendUTF8StringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + var invalidUTF8 bool + v := *ptr.toString() + if v == "" { + return b, nil + } + if !utf8.ValidString(v) { + invalidUTF8 = true + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + if invalidUTF8 { + return b, errInvalidUTF8 + } + return b, nil +} +func appendUTF8StringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + var invalidUTF8 bool + p := *ptr.toStringPtr() + if p == nil { + return b, nil + } + v := *p + if !utf8.ValidString(v) { + invalidUTF8 = true + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + if invalidUTF8 { + return b, errInvalidUTF8 + } + return b, nil +} +func appendUTF8StringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + var invalidUTF8 bool + s := *ptr.toStringSlice() + for _, v := range s { + if !utf8.ValidString(v) { + invalidUTF8 = true + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + } + if invalidUTF8 { + return b, errInvalidUTF8 + } + return b, nil +} +func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBytes() + if v == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBytes() + if len(v) == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBytes() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toBytesSlice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + } + return b, nil +} + +// makeGroupMarshaler returns the sizer and marshaler for a group. +// u is the marshal info of the underlying message. +func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + p := ptr.getPointer() + if p.isNil() { + return 0 + } + return u.size(p) + 2*tagsize + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + p := ptr.getPointer() + if p.isNil() { + return b, nil + } + var err error + b = appendVarint(b, wiretag) // start group + b, err = u.marshal(b, p, deterministic) + b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group + return b, err + } +} + +// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice. +// u is the marshal info of the underlying message. +func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getPointerSlice() + n := 0 + for _, v := range s { + if v.isNil() { + continue + } + n += u.size(v) + 2*tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getPointerSlice() + var err error + var nerr nonFatal + for _, v := range s { + if v.isNil() { + return b, errRepeatedHasNil + } + b = appendVarint(b, wiretag) // start group + b, err = u.marshal(b, v, deterministic) + b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group + if !nerr.Merge(err) { + if err == ErrNil { + err = errRepeatedHasNil + } + return b, err + } + } + return b, nerr.E + } +} + +// makeMessageMarshaler returns the sizer and marshaler for a message field. +// u is the marshal info of the message. +func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + p := ptr.getPointer() + if p.isNil() { + return 0 + } + siz := u.size(p) + return siz + SizeVarint(uint64(siz)) + tagsize + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + p := ptr.getPointer() + if p.isNil() { + return b, nil + } + b = appendVarint(b, wiretag) + siz := u.cachedsize(p) + b = appendVarint(b, uint64(siz)) + return u.marshal(b, p, deterministic) + } +} + +// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice. +// u is the marshal info of the message. +func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getPointerSlice() + n := 0 + for _, v := range s { + if v.isNil() { + continue + } + siz := u.size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getPointerSlice() + var err error + var nerr nonFatal + for _, v := range s { + if v.isNil() { + return b, errRepeatedHasNil + } + b = appendVarint(b, wiretag) + siz := u.cachedsize(v) + b = appendVarint(b, uint64(siz)) + b, err = u.marshal(b, v, deterministic) + + if !nerr.Merge(err) { + if err == ErrNil { + err = errRepeatedHasNil + } + return b, err + } + } + return b, nerr.E + } +} + +// makeMapMarshaler returns the sizer and marshaler for a map field. +// f is the pointer to the reflect data structure of the field. +func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) { + // figure out key and value type + t := f.Type + keyType := t.Key() + valType := t.Elem() + tags := strings.Split(f.Tag.Get("protobuf"), ",") + keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",") + valTags := strings.Split(f.Tag.Get("protobuf_val"), ",") + stdOptions := false + for _, t := range tags { + if strings.HasPrefix(t, "customtype=") { + valTags = append(valTags, t) + } + if t == "stdtime" { + valTags = append(valTags, t) + stdOptions = true + } + if t == "stdduration" { + valTags = append(valTags, t) + stdOptions = true + } + if t == "wktptr" { + valTags = append(valTags, t) + } + } + keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map + valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map + keyWireTag := 1<<3 | wiretype(keyTags[0]) + valWireTag := 2<<3 | wiretype(valTags[0]) + + // We create an interface to get the addresses of the map key and value. + // If value is pointer-typed, the interface is a direct interface, the + // idata itself is the value. Otherwise, the idata is the pointer to the + // value. + // Key cannot be pointer-typed. + valIsPtr := valType.Kind() == reflect.Ptr + + // If value is a message with nested maps, calling + // valSizer in marshal may be quadratic. We should use + // cached version in marshal (but not in size). + // If value is not message type, we don't have size cache, + // but it cannot be nested either. Just use valSizer. + valCachedSizer := valSizer + if valIsPtr && !stdOptions && valType.Elem().Kind() == reflect.Struct { + u := getMarshalInfo(valType.Elem()) + valCachedSizer = func(ptr pointer, tagsize int) int { + // Same as message sizer, but use cache. + p := ptr.getPointer() + if p.isNil() { + return 0 + } + siz := u.cachedsize(p) + return siz + SizeVarint(uint64(siz)) + tagsize + } + } + return func(ptr pointer, tagsize int) int { + m := ptr.asPointerTo(t).Elem() // the map + n := 0 + for _, k := range m.MapKeys() { + ki := k.Interface() + vi := m.MapIndex(k).Interface() + kaddr := toAddrPointer(&ki, false) // pointer to key + vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value + siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) { + m := ptr.asPointerTo(t).Elem() // the map + var err error + keys := m.MapKeys() + if len(keys) > 1 && deterministic { + sort.Sort(mapKeys(keys)) + } + + var nerr nonFatal + for _, k := range keys { + ki := k.Interface() + vi := m.MapIndex(k).Interface() + kaddr := toAddrPointer(&ki, false) // pointer to key + vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value + b = appendVarint(b, tag) + siz := keySizer(kaddr, 1) + valCachedSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) + b = appendVarint(b, uint64(siz)) + b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic) + if !nerr.Merge(err) { + return b, err + } + b, err = valMarshaler(b, vaddr, valWireTag, deterministic) + if err != ErrNil && !nerr.Merge(err) { // allow nil value in map + return b, err + } + } + return b, nerr.E + } +} + +// makeOneOfMarshaler returns the sizer and marshaler for a oneof field. +// fi is the marshal info of the field. +// f is the pointer to the reflect data structure of the field. +func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) { + // Oneof field is an interface. We need to get the actual data type on the fly. + t := f.Type + return func(ptr pointer, _ int) int { + p := ptr.getInterfacePointer() + if p.isNil() { + return 0 + } + v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct + telem := v.Type() + e := fi.oneofElems[telem] + return e.sizer(p, e.tagsize) + }, + func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) { + p := ptr.getInterfacePointer() + if p.isNil() { + return b, nil + } + v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct + telem := v.Type() + if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() { + return b, errOneofHasNil + } + e := fi.oneofElems[telem] + return e.marshaler(b, p, e.wiretag, deterministic) + } +} + +// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field. +func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int { + m, mu := ext.extensionsRead() + if m == nil { + return 0 + } + mu.Lock() + + n := 0 + for _, e := range m { + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + n += len(e.enc) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + n += ei.sizer(p, ei.tagsize) + } + mu.Unlock() + return n +} + +// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b. +func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { + m, mu := ext.extensionsRead() + if m == nil { + return b, nil + } + mu.Lock() + defer mu.Unlock() + + var err error + var nerr nonFatal + + // Fast-path for common cases: zero or one extensions. + // Don't bother sorting the keys. + if len(m) <= 1 { + for _, e := range m { + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + b = append(b, e.enc...) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, ei.wiretag, deterministic) + if !nerr.Merge(err) { + return b, err + } + } + return b, nerr.E + } + + // Sort the keys to provide a deterministic encoding. + // Not sure this is required, but the old code does it. + keys := make([]int, 0, len(m)) + for k := range m { + keys = append(keys, int(k)) + } + sort.Ints(keys) + + for _, k := range keys { + e := m[int32(k)] + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + b = append(b, e.enc...) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, ei.wiretag, deterministic) + if !nerr.Merge(err) { + return b, err + } + } + return b, nerr.E +} + +// message set format is: +// message MessageSet { +// repeated group Item = 1 { +// required int32 type_id = 2; +// required string message = 3; +// }; +// } + +// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field +// in message set format (above). +func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int { + m, mu := ext.extensionsRead() + if m == nil { + return 0 + } + mu.Lock() + + n := 0 + for id, e := range m { + n += 2 // start group, end group. tag = 1 (size=1) + n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1) + + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint + siz := len(msgWithLen) + n += siz + 1 // message, tag = 3 (size=1) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + n += ei.sizer(p, 1) // message, tag = 3 (size=1) + } + mu.Unlock() + return n +} + +// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above) +// to the end of byte slice b. +func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { + m, mu := ext.extensionsRead() + if m == nil { + return b, nil + } + mu.Lock() + defer mu.Unlock() + + var err error + var nerr nonFatal + + // Fast-path for common cases: zero or one extensions. + // Don't bother sorting the keys. + if len(m) <= 1 { + for id, e := range m { + b = append(b, 1<<3|WireStartGroup) + b = append(b, 2<<3|WireVarint) + b = appendVarint(b, uint64(id)) + + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint + b = append(b, 3<<3|WireBytes) + b = append(b, msgWithLen...) + b = append(b, 1<<3|WireEndGroup) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) + if !nerr.Merge(err) { + return b, err + } + b = append(b, 1<<3|WireEndGroup) + } + return b, nerr.E + } + + // Sort the keys to provide a deterministic encoding. + keys := make([]int, 0, len(m)) + for k := range m { + keys = append(keys, int(k)) + } + sort.Ints(keys) + + for _, id := range keys { + e := m[int32(id)] + b = append(b, 1<<3|WireStartGroup) + b = append(b, 2<<3|WireVarint) + b = appendVarint(b, uint64(id)) + + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint + b = append(b, 3<<3|WireBytes) + b = append(b, msgWithLen...) + b = append(b, 1<<3|WireEndGroup) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) + b = append(b, 1<<3|WireEndGroup) + if !nerr.Merge(err) { + return b, err + } + } + return b, nerr.E +} + +// sizeV1Extensions computes the size of encoded data for a V1-API extension field. +func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int { + if m == nil { + return 0 + } + + n := 0 + for _, e := range m { + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + n += len(e.enc) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + n += ei.sizer(p, ei.tagsize) + } + return n +} + +// appendV1Extensions marshals a V1-API extension field to the end of byte slice b. +func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) { + if m == nil { + return b, nil + } + + // Sort the keys to provide a deterministic encoding. + keys := make([]int, 0, len(m)) + for k := range m { + keys = append(keys, int(k)) + } + sort.Ints(keys) + + var err error + var nerr nonFatal + for _, k := range keys { + e := m[int32(k)] + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + b = append(b, e.enc...) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, ei.wiretag, deterministic) + if !nerr.Merge(err) { + return b, err + } + } + return b, nerr.E +} + +// newMarshaler is the interface representing objects that can marshal themselves. +// +// This exists to support protoc-gen-go generated messages. +// The proto package will stop type-asserting to this interface in the future. +// +// DO NOT DEPEND ON THIS. +type newMarshaler interface { + XXX_Size() int + XXX_Marshal(b []byte, deterministic bool) ([]byte, error) +} + +// Size returns the encoded size of a protocol buffer message. +// This is the main entry point. +func Size(pb Message) int { + if m, ok := pb.(newMarshaler); ok { + return m.XXX_Size() + } + if m, ok := pb.(Marshaler); ok { + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + b, _ := m.Marshal() + return len(b) + } + // in case somehow we didn't generate the wrapper + if pb == nil { + return 0 + } + var info InternalMessageInfo + return info.Size(pb) +} + +// Marshal takes a protocol buffer message +// and encodes it into the wire format, returning the data. +// This is the main entry point. +func Marshal(pb Message) ([]byte, error) { + if m, ok := pb.(newMarshaler); ok { + siz := m.XXX_Size() + b := make([]byte, 0, siz) + return m.XXX_Marshal(b, false) + } + if m, ok := pb.(Marshaler); ok { + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + return m.Marshal() + } + // in case somehow we didn't generate the wrapper + if pb == nil { + return nil, ErrNil + } + var info InternalMessageInfo + siz := info.Size(pb) + b := make([]byte, 0, siz) + return info.Marshal(b, pb, false) +} + +// Marshal takes a protocol buffer message +// and encodes it into the wire format, writing the result to the +// Buffer. +// This is an alternative entry point. It is not necessary to use +// a Buffer for most applications. +func (p *Buffer) Marshal(pb Message) error { + var err error + if p.deterministic { + if _, ok := pb.(Marshaler); ok { + return fmt.Errorf("proto: deterministic not supported by the Marshal method of %T", pb) + } + } + if m, ok := pb.(newMarshaler); ok { + siz := m.XXX_Size() + p.grow(siz) // make sure buf has enough capacity + pp := p.buf[len(p.buf) : len(p.buf) : len(p.buf)+siz] + pp, err = m.XXX_Marshal(pp, p.deterministic) + p.buf = append(p.buf, pp...) + return err + } + if m, ok := pb.(Marshaler); ok { + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + var b []byte + b, err = m.Marshal() + p.buf = append(p.buf, b...) + return err + } + // in case somehow we didn't generate the wrapper + if pb == nil { + return ErrNil + } + var info InternalMessageInfo + siz := info.Size(pb) + p.grow(siz) // make sure buf has enough capacity + p.buf, err = info.Marshal(p.buf, pb, p.deterministic) + return err +} + +// grow grows the buffer's capacity, if necessary, to guarantee space for +// another n bytes. After grow(n), at least n bytes can be written to the +// buffer without another allocation. +func (p *Buffer) grow(n int) { + need := len(p.buf) + n + if need <= cap(p.buf) { + return + } + newCap := len(p.buf) * 2 + if newCap < need { + newCap = need + } + p.buf = append(make([]byte, 0, newCap), p.buf...) +} diff --git a/vendor/github.com/gogo/protobuf/proto/table_marshal_gogo.go b/vendor/github.com/gogo/protobuf/proto/table_marshal_gogo.go new file mode 100644 index 00000000..997f57c1 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/table_marshal_gogo.go @@ -0,0 +1,388 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2018, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "reflect" + "time" +) + +// makeMessageRefMarshaler differs a bit from makeMessageMarshaler +// It marshal a message T instead of a *T +func makeMessageRefMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + siz := u.size(ptr) + return siz + SizeVarint(uint64(siz)) + tagsize + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + b = appendVarint(b, wiretag) + siz := u.cachedsize(ptr) + b = appendVarint(b, uint64(siz)) + return u.marshal(b, ptr, deterministic) + } +} + +// makeMessageRefSliceMarshaler differs quite a lot from makeMessageSliceMarshaler +// It marshals a slice of messages []T instead of []*T +func makeMessageRefSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + e := elem.Interface() + v := toAddrPointer(&e, false) + siz := u.size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + var err, errreq error + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + e := elem.Interface() + v := toAddrPointer(&e, false) + b = appendVarint(b, wiretag) + siz := u.size(v) + b = appendVarint(b, uint64(siz)) + b, err = u.marshal(b, v, deterministic) + + if err != nil { + if _, ok := err.(*RequiredNotSetError); ok { + // Required field in submessage is not set. + // We record the error but keep going, to give a complete marshaling. + if errreq == nil { + errreq = err + } + continue + } + if err == ErrNil { + err = errRepeatedHasNil + } + return b, err + } + } + + return b, errreq + } +} + +func makeCustomPtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + m := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(custom) + siz := m.Size() + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + m := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(custom) + siz := m.Size() + buf, err := m.Marshal() + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + return b, nil + } +} + +func makeCustomMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + m := ptr.asPointerTo(u.typ).Interface().(custom) + siz := m.Size() + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + m := ptr.asPointerTo(u.typ).Interface().(custom) + siz := m.Size() + buf, err := m.Marshal() + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + return b, nil + } +} + +func makeTimeMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + t := ptr.asPointerTo(u.typ).Interface().(*time.Time) + ts, err := timestampProto(*t) + if err != nil { + return 0 + } + siz := Size(ts) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + t := ptr.asPointerTo(u.typ).Interface().(*time.Time) + ts, err := timestampProto(*t) + if err != nil { + return nil, err + } + buf, err := Marshal(ts) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeTimePtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*time.Time) + ts, err := timestampProto(*t) + if err != nil { + return 0 + } + siz := Size(ts) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*time.Time) + ts, err := timestampProto(*t) + if err != nil { + return nil, err + } + buf, err := Marshal(ts) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeTimeSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(time.Time) + ts, err := timestampProto(t) + if err != nil { + return 0 + } + siz := Size(ts) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(time.Time) + ts, err := timestampProto(t) + if err != nil { + return nil, err + } + siz := Size(ts) + buf, err := Marshal(ts) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeTimePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*time.Time) + ts, err := timestampProto(*t) + if err != nil { + return 0 + } + siz := Size(ts) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*time.Time) + ts, err := timestampProto(*t) + if err != nil { + return nil, err + } + siz := Size(ts) + buf, err := Marshal(ts) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeDurationMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + d := ptr.asPointerTo(u.typ).Interface().(*time.Duration) + dur := durationProto(*d) + siz := Size(dur) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + d := ptr.asPointerTo(u.typ).Interface().(*time.Duration) + dur := durationProto(*d) + buf, err := Marshal(dur) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeDurationPtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + d := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*time.Duration) + dur := durationProto(*d) + siz := Size(dur) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + d := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*time.Duration) + dur := durationProto(*d) + buf, err := Marshal(dur) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeDurationSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + d := elem.Interface().(time.Duration) + dur := durationProto(d) + siz := Size(dur) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + d := elem.Interface().(time.Duration) + dur := durationProto(d) + siz := Size(dur) + buf, err := Marshal(dur) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeDurationPtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + d := elem.Interface().(*time.Duration) + dur := durationProto(*d) + siz := Size(dur) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + d := elem.Interface().(*time.Duration) + dur := durationProto(*d) + siz := Size(dur) + buf, err := Marshal(dur) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} diff --git a/vendor/github.com/gogo/protobuf/proto/table_merge.go b/vendor/github.com/gogo/protobuf/proto/table_merge.go new file mode 100644 index 00000000..60dcf70d --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/table_merge.go @@ -0,0 +1,676 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2016 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "fmt" + "reflect" + "strings" + "sync" + "sync/atomic" +) + +// Merge merges the src message into dst. +// This assumes that dst and src of the same type and are non-nil. +func (a *InternalMessageInfo) Merge(dst, src Message) { + mi := atomicLoadMergeInfo(&a.merge) + if mi == nil { + mi = getMergeInfo(reflect.TypeOf(dst).Elem()) + atomicStoreMergeInfo(&a.merge, mi) + } + mi.merge(toPointer(&dst), toPointer(&src)) +} + +type mergeInfo struct { + typ reflect.Type + + initialized int32 // 0: only typ is valid, 1: everything is valid + lock sync.Mutex + + fields []mergeFieldInfo + unrecognized field // Offset of XXX_unrecognized +} + +type mergeFieldInfo struct { + field field // Offset of field, guaranteed to be valid + + // isPointer reports whether the value in the field is a pointer. + // This is true for the following situations: + // * Pointer to struct + // * Pointer to basic type (proto2 only) + // * Slice (first value in slice header is a pointer) + // * String (first value in string header is a pointer) + isPointer bool + + // basicWidth reports the width of the field assuming that it is directly + // embedded in the struct (as is the case for basic types in proto3). + // The possible values are: + // 0: invalid + // 1: bool + // 4: int32, uint32, float32 + // 8: int64, uint64, float64 + basicWidth int + + // Where dst and src are pointers to the types being merged. + merge func(dst, src pointer) +} + +var ( + mergeInfoMap = map[reflect.Type]*mergeInfo{} + mergeInfoLock sync.Mutex +) + +func getMergeInfo(t reflect.Type) *mergeInfo { + mergeInfoLock.Lock() + defer mergeInfoLock.Unlock() + mi := mergeInfoMap[t] + if mi == nil { + mi = &mergeInfo{typ: t} + mergeInfoMap[t] = mi + } + return mi +} + +// merge merges src into dst assuming they are both of type *mi.typ. +func (mi *mergeInfo) merge(dst, src pointer) { + if dst.isNil() { + panic("proto: nil destination") + } + if src.isNil() { + return // Nothing to do. + } + + if atomic.LoadInt32(&mi.initialized) == 0 { + mi.computeMergeInfo() + } + + for _, fi := range mi.fields { + sfp := src.offset(fi.field) + + // As an optimization, we can avoid the merge function call cost + // if we know for sure that the source will have no effect + // by checking if it is the zero value. + if unsafeAllowed { + if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string + continue + } + if fi.basicWidth > 0 { + switch { + case fi.basicWidth == 1 && !*sfp.toBool(): + continue + case fi.basicWidth == 4 && *sfp.toUint32() == 0: + continue + case fi.basicWidth == 8 && *sfp.toUint64() == 0: + continue + } + } + } + + dfp := dst.offset(fi.field) + fi.merge(dfp, sfp) + } + + // TODO: Make this faster? + out := dst.asPointerTo(mi.typ).Elem() + in := src.asPointerTo(mi.typ).Elem() + if emIn, err := extendable(in.Addr().Interface()); err == nil { + emOut, _ := extendable(out.Addr().Interface()) + mIn, muIn := emIn.extensionsRead() + if mIn != nil { + mOut := emOut.extensionsWrite() + muIn.Lock() + mergeExtension(mOut, mIn) + muIn.Unlock() + } + } + + if mi.unrecognized.IsValid() { + if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 { + *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...) + } + } +} + +func (mi *mergeInfo) computeMergeInfo() { + mi.lock.Lock() + defer mi.lock.Unlock() + if mi.initialized != 0 { + return + } + t := mi.typ + n := t.NumField() + + props := GetProperties(t) + for i := 0; i < n; i++ { + f := t.Field(i) + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + + mfi := mergeFieldInfo{field: toField(&f)} + tf := f.Type + + // As an optimization, we can avoid the merge function call cost + // if we know for sure that the source will have no effect + // by checking if it is the zero value. + if unsafeAllowed { + switch tf.Kind() { + case reflect.Ptr, reflect.Slice, reflect.String: + // As a special case, we assume slices and strings are pointers + // since we know that the first field in the SliceSlice or + // StringHeader is a data pointer. + mfi.isPointer = true + case reflect.Bool: + mfi.basicWidth = 1 + case reflect.Int32, reflect.Uint32, reflect.Float32: + mfi.basicWidth = 4 + case reflect.Int64, reflect.Uint64, reflect.Float64: + mfi.basicWidth = 8 + } + } + + // Unwrap tf to get at its most basic type. + var isPointer, isSlice bool + if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { + isSlice = true + tf = tf.Elem() + } + if tf.Kind() == reflect.Ptr { + isPointer = true + tf = tf.Elem() + } + if isPointer && isSlice && tf.Kind() != reflect.Struct { + panic("both pointer and slice for basic type in " + tf.Name()) + } + + switch tf.Kind() { + case reflect.Int32: + switch { + case isSlice: // E.g., []int32 + mfi.merge = func(dst, src pointer) { + // NOTE: toInt32Slice is not defined (see pointer_reflect.go). + /* + sfsp := src.toInt32Slice() + if *sfsp != nil { + dfsp := dst.toInt32Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []int64{} + } + } + */ + sfs := src.getInt32Slice() + if sfs != nil { + dfs := dst.getInt32Slice() + dfs = append(dfs, sfs...) + if dfs == nil { + dfs = []int32{} + } + dst.setInt32Slice(dfs) + } + } + case isPointer: // E.g., *int32 + mfi.merge = func(dst, src pointer) { + // NOTE: toInt32Ptr is not defined (see pointer_reflect.go). + /* + sfpp := src.toInt32Ptr() + if *sfpp != nil { + dfpp := dst.toInt32Ptr() + if *dfpp == nil { + *dfpp = Int32(**sfpp) + } else { + **dfpp = **sfpp + } + } + */ + sfp := src.getInt32Ptr() + if sfp != nil { + dfp := dst.getInt32Ptr() + if dfp == nil { + dst.setInt32Ptr(*sfp) + } else { + *dfp = *sfp + } + } + } + default: // E.g., int32 + mfi.merge = func(dst, src pointer) { + if v := *src.toInt32(); v != 0 { + *dst.toInt32() = v + } + } + } + case reflect.Int64: + switch { + case isSlice: // E.g., []int64 + mfi.merge = func(dst, src pointer) { + sfsp := src.toInt64Slice() + if *sfsp != nil { + dfsp := dst.toInt64Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []int64{} + } + } + } + case isPointer: // E.g., *int64 + mfi.merge = func(dst, src pointer) { + sfpp := src.toInt64Ptr() + if *sfpp != nil { + dfpp := dst.toInt64Ptr() + if *dfpp == nil { + *dfpp = Int64(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., int64 + mfi.merge = func(dst, src pointer) { + if v := *src.toInt64(); v != 0 { + *dst.toInt64() = v + } + } + } + case reflect.Uint32: + switch { + case isSlice: // E.g., []uint32 + mfi.merge = func(dst, src pointer) { + sfsp := src.toUint32Slice() + if *sfsp != nil { + dfsp := dst.toUint32Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []uint32{} + } + } + } + case isPointer: // E.g., *uint32 + mfi.merge = func(dst, src pointer) { + sfpp := src.toUint32Ptr() + if *sfpp != nil { + dfpp := dst.toUint32Ptr() + if *dfpp == nil { + *dfpp = Uint32(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., uint32 + mfi.merge = func(dst, src pointer) { + if v := *src.toUint32(); v != 0 { + *dst.toUint32() = v + } + } + } + case reflect.Uint64: + switch { + case isSlice: // E.g., []uint64 + mfi.merge = func(dst, src pointer) { + sfsp := src.toUint64Slice() + if *sfsp != nil { + dfsp := dst.toUint64Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []uint64{} + } + } + } + case isPointer: // E.g., *uint64 + mfi.merge = func(dst, src pointer) { + sfpp := src.toUint64Ptr() + if *sfpp != nil { + dfpp := dst.toUint64Ptr() + if *dfpp == nil { + *dfpp = Uint64(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., uint64 + mfi.merge = func(dst, src pointer) { + if v := *src.toUint64(); v != 0 { + *dst.toUint64() = v + } + } + } + case reflect.Float32: + switch { + case isSlice: // E.g., []float32 + mfi.merge = func(dst, src pointer) { + sfsp := src.toFloat32Slice() + if *sfsp != nil { + dfsp := dst.toFloat32Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []float32{} + } + } + } + case isPointer: // E.g., *float32 + mfi.merge = func(dst, src pointer) { + sfpp := src.toFloat32Ptr() + if *sfpp != nil { + dfpp := dst.toFloat32Ptr() + if *dfpp == nil { + *dfpp = Float32(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., float32 + mfi.merge = func(dst, src pointer) { + if v := *src.toFloat32(); v != 0 { + *dst.toFloat32() = v + } + } + } + case reflect.Float64: + switch { + case isSlice: // E.g., []float64 + mfi.merge = func(dst, src pointer) { + sfsp := src.toFloat64Slice() + if *sfsp != nil { + dfsp := dst.toFloat64Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []float64{} + } + } + } + case isPointer: // E.g., *float64 + mfi.merge = func(dst, src pointer) { + sfpp := src.toFloat64Ptr() + if *sfpp != nil { + dfpp := dst.toFloat64Ptr() + if *dfpp == nil { + *dfpp = Float64(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., float64 + mfi.merge = func(dst, src pointer) { + if v := *src.toFloat64(); v != 0 { + *dst.toFloat64() = v + } + } + } + case reflect.Bool: + switch { + case isSlice: // E.g., []bool + mfi.merge = func(dst, src pointer) { + sfsp := src.toBoolSlice() + if *sfsp != nil { + dfsp := dst.toBoolSlice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []bool{} + } + } + } + case isPointer: // E.g., *bool + mfi.merge = func(dst, src pointer) { + sfpp := src.toBoolPtr() + if *sfpp != nil { + dfpp := dst.toBoolPtr() + if *dfpp == nil { + *dfpp = Bool(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., bool + mfi.merge = func(dst, src pointer) { + if v := *src.toBool(); v { + *dst.toBool() = v + } + } + } + case reflect.String: + switch { + case isSlice: // E.g., []string + mfi.merge = func(dst, src pointer) { + sfsp := src.toStringSlice() + if *sfsp != nil { + dfsp := dst.toStringSlice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []string{} + } + } + } + case isPointer: // E.g., *string + mfi.merge = func(dst, src pointer) { + sfpp := src.toStringPtr() + if *sfpp != nil { + dfpp := dst.toStringPtr() + if *dfpp == nil { + *dfpp = String(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., string + mfi.merge = func(dst, src pointer) { + if v := *src.toString(); v != "" { + *dst.toString() = v + } + } + } + case reflect.Slice: + isProto3 := props.Prop[i].proto3 + switch { + case isPointer: + panic("bad pointer in byte slice case in " + tf.Name()) + case tf.Elem().Kind() != reflect.Uint8: + panic("bad element kind in byte slice case in " + tf.Name()) + case isSlice: // E.g., [][]byte + mfi.merge = func(dst, src pointer) { + sbsp := src.toBytesSlice() + if *sbsp != nil { + dbsp := dst.toBytesSlice() + for _, sb := range *sbsp { + if sb == nil { + *dbsp = append(*dbsp, nil) + } else { + *dbsp = append(*dbsp, append([]byte{}, sb...)) + } + } + if *dbsp == nil { + *dbsp = [][]byte{} + } + } + } + default: // E.g., []byte + mfi.merge = func(dst, src pointer) { + sbp := src.toBytes() + if *sbp != nil { + dbp := dst.toBytes() + if !isProto3 || len(*sbp) > 0 { + *dbp = append([]byte{}, *sbp...) + } + } + } + } + case reflect.Struct: + switch { + case isSlice && !isPointer: // E.g. []pb.T + mergeInfo := getMergeInfo(tf) + zero := reflect.Zero(tf) + mfi.merge = func(dst, src pointer) { + // TODO: Make this faster? + dstsp := dst.asPointerTo(f.Type) + dsts := dstsp.Elem() + srcs := src.asPointerTo(f.Type).Elem() + for i := 0; i < srcs.Len(); i++ { + dsts = reflect.Append(dsts, zero) + srcElement := srcs.Index(i).Addr() + dstElement := dsts.Index(dsts.Len() - 1).Addr() + mergeInfo.merge(valToPointer(dstElement), valToPointer(srcElement)) + } + if dsts.IsNil() { + dsts = reflect.MakeSlice(f.Type, 0, 0) + } + dstsp.Elem().Set(dsts) + } + case !isPointer: + mergeInfo := getMergeInfo(tf) + mfi.merge = func(dst, src pointer) { + mergeInfo.merge(dst, src) + } + case isSlice: // E.g., []*pb.T + mergeInfo := getMergeInfo(tf) + mfi.merge = func(dst, src pointer) { + sps := src.getPointerSlice() + if sps != nil { + dps := dst.getPointerSlice() + for _, sp := range sps { + var dp pointer + if !sp.isNil() { + dp = valToPointer(reflect.New(tf)) + mergeInfo.merge(dp, sp) + } + dps = append(dps, dp) + } + if dps == nil { + dps = []pointer{} + } + dst.setPointerSlice(dps) + } + } + default: // E.g., *pb.T + mergeInfo := getMergeInfo(tf) + mfi.merge = func(dst, src pointer) { + sp := src.getPointer() + if !sp.isNil() { + dp := dst.getPointer() + if dp.isNil() { + dp = valToPointer(reflect.New(tf)) + dst.setPointer(dp) + } + mergeInfo.merge(dp, sp) + } + } + } + case reflect.Map: + switch { + case isPointer || isSlice: + panic("bad pointer or slice in map case in " + tf.Name()) + default: // E.g., map[K]V + mfi.merge = func(dst, src pointer) { + sm := src.asPointerTo(tf).Elem() + if sm.Len() == 0 { + return + } + dm := dst.asPointerTo(tf).Elem() + if dm.IsNil() { + dm.Set(reflect.MakeMap(tf)) + } + + switch tf.Elem().Kind() { + case reflect.Ptr: // Proto struct (e.g., *T) + for _, key := range sm.MapKeys() { + val := sm.MapIndex(key) + val = reflect.ValueOf(Clone(val.Interface().(Message))) + dm.SetMapIndex(key, val) + } + case reflect.Slice: // E.g. Bytes type (e.g., []byte) + for _, key := range sm.MapKeys() { + val := sm.MapIndex(key) + val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) + dm.SetMapIndex(key, val) + } + default: // Basic type (e.g., string) + for _, key := range sm.MapKeys() { + val := sm.MapIndex(key) + dm.SetMapIndex(key, val) + } + } + } + } + case reflect.Interface: + // Must be oneof field. + switch { + case isPointer || isSlice: + panic("bad pointer or slice in interface case in " + tf.Name()) + default: // E.g., interface{} + // TODO: Make this faster? + mfi.merge = func(dst, src pointer) { + su := src.asPointerTo(tf).Elem() + if !su.IsNil() { + du := dst.asPointerTo(tf).Elem() + typ := su.Elem().Type() + if du.IsNil() || du.Elem().Type() != typ { + du.Set(reflect.New(typ.Elem())) // Initialize interface if empty + } + sv := su.Elem().Elem().Field(0) + if sv.Kind() == reflect.Ptr && sv.IsNil() { + return + } + dv := du.Elem().Elem().Field(0) + if dv.Kind() == reflect.Ptr && dv.IsNil() { + dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty + } + switch sv.Type().Kind() { + case reflect.Ptr: // Proto struct (e.g., *T) + Merge(dv.Interface().(Message), sv.Interface().(Message)) + case reflect.Slice: // E.g. Bytes type (e.g., []byte) + dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...))) + default: // Basic type (e.g., string) + dv.Set(sv) + } + } + } + } + default: + panic(fmt.Sprintf("merger not found for type:%s", tf)) + } + mi.fields = append(mi.fields, mfi) + } + + mi.unrecognized = invalidField + if f, ok := t.FieldByName("XXX_unrecognized"); ok { + if f.Type != reflect.TypeOf([]byte{}) { + panic("expected XXX_unrecognized to be of type []byte") + } + mi.unrecognized = toField(&f) + } + + atomic.StoreInt32(&mi.initialized, 1) +} diff --git a/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go b/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go new file mode 100644 index 00000000..93722938 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go @@ -0,0 +1,2249 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2016 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "errors" + "fmt" + "io" + "math" + "reflect" + "strconv" + "strings" + "sync" + "sync/atomic" + "unicode/utf8" +) + +// Unmarshal is the entry point from the generated .pb.go files. +// This function is not intended to be used by non-generated code. +// This function is not subject to any compatibility guarantee. +// msg contains a pointer to a protocol buffer struct. +// b is the data to be unmarshaled into the protocol buffer. +// a is a pointer to a place to store cached unmarshal information. +func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error { + // Load the unmarshal information for this message type. + // The atomic load ensures memory consistency. + u := atomicLoadUnmarshalInfo(&a.unmarshal) + if u == nil { + // Slow path: find unmarshal info for msg, update a with it. + u = getUnmarshalInfo(reflect.TypeOf(msg).Elem()) + atomicStoreUnmarshalInfo(&a.unmarshal, u) + } + // Then do the unmarshaling. + err := u.unmarshal(toPointer(&msg), b) + return err +} + +type unmarshalInfo struct { + typ reflect.Type // type of the protobuf struct + + // 0 = only typ field is initialized + // 1 = completely initialized + initialized int32 + lock sync.Mutex // prevents double initialization + dense []unmarshalFieldInfo // fields indexed by tag # + sparse map[uint64]unmarshalFieldInfo // fields indexed by tag # + reqFields []string // names of required fields + reqMask uint64 // 1< 0 { + // Read tag and wire type. + // Special case 1 and 2 byte varints. + var x uint64 + if b[0] < 128 { + x = uint64(b[0]) + b = b[1:] + } else if len(b) >= 2 && b[1] < 128 { + x = uint64(b[0]&0x7f) + uint64(b[1])<<7 + b = b[2:] + } else { + var n int + x, n = decodeVarint(b) + if n == 0 { + return io.ErrUnexpectedEOF + } + b = b[n:] + } + tag := x >> 3 + wire := int(x) & 7 + + // Dispatch on the tag to one of the unmarshal* functions below. + var f unmarshalFieldInfo + if tag < uint64(len(u.dense)) { + f = u.dense[tag] + } else { + f = u.sparse[tag] + } + if fn := f.unmarshal; fn != nil { + var err error + b, err = fn(b, m.offset(f.field), wire) + if err == nil { + reqMask |= f.reqMask + continue + } + if r, ok := err.(*RequiredNotSetError); ok { + // Remember this error, but keep parsing. We need to produce + // a full parse even if a required field is missing. + if errLater == nil { + errLater = r + } + reqMask |= f.reqMask + continue + } + if err != errInternalBadWireType { + if err == errInvalidUTF8 { + if errLater == nil { + fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name + errLater = &invalidUTF8Error{fullName} + } + continue + } + return err + } + // Fragments with bad wire type are treated as unknown fields. + } + + // Unknown tag. + if !u.unrecognized.IsValid() { + // Don't keep unrecognized data; just skip it. + var err error + b, err = skipField(b, wire) + if err != nil { + return err + } + continue + } + // Keep unrecognized data around. + // maybe in extensions, maybe in the unrecognized field. + z := m.offset(u.unrecognized).toBytes() + var emap map[int32]Extension + var e Extension + for _, r := range u.extensionRanges { + if uint64(r.Start) <= tag && tag <= uint64(r.End) { + if u.extensions.IsValid() { + mp := m.offset(u.extensions).toExtensions() + emap = mp.extensionsWrite() + e = emap[int32(tag)] + z = &e.enc + break + } + if u.oldExtensions.IsValid() { + p := m.offset(u.oldExtensions).toOldExtensions() + emap = *p + if emap == nil { + emap = map[int32]Extension{} + *p = emap + } + e = emap[int32(tag)] + z = &e.enc + break + } + if u.bytesExtensions.IsValid() { + z = m.offset(u.bytesExtensions).toBytes() + break + } + panic("no extensions field available") + } + } + // Use wire type to skip data. + var err error + b0 := b + b, err = skipField(b, wire) + if err != nil { + return err + } + *z = encodeVarint(*z, tag<<3|uint64(wire)) + *z = append(*z, b0[:len(b0)-len(b)]...) + + if emap != nil { + emap[int32(tag)] = e + } + } + if reqMask != u.reqMask && errLater == nil { + // A required field of this message is missing. + for _, n := range u.reqFields { + if reqMask&1 == 0 { + errLater = &RequiredNotSetError{n} + } + reqMask >>= 1 + } + } + return errLater +} + +// computeUnmarshalInfo fills in u with information for use +// in unmarshaling protocol buffers of type u.typ. +func (u *unmarshalInfo) computeUnmarshalInfo() { + u.lock.Lock() + defer u.lock.Unlock() + if u.initialized != 0 { + return + } + t := u.typ + n := t.NumField() + + // Set up the "not found" value for the unrecognized byte buffer. + // This is the default for proto3. + u.unrecognized = invalidField + u.extensions = invalidField + u.oldExtensions = invalidField + u.bytesExtensions = invalidField + + // List of the generated type and offset for each oneof field. + type oneofField struct { + ityp reflect.Type // interface type of oneof field + field field // offset in containing message + } + var oneofFields []oneofField + + for i := 0; i < n; i++ { + f := t.Field(i) + if f.Name == "XXX_unrecognized" { + // The byte slice used to hold unrecognized input is special. + if f.Type != reflect.TypeOf(([]byte)(nil)) { + panic("bad type for XXX_unrecognized field: " + f.Type.Name()) + } + u.unrecognized = toField(&f) + continue + } + if f.Name == "XXX_InternalExtensions" { + // Ditto here. + if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) { + panic("bad type for XXX_InternalExtensions field: " + f.Type.Name()) + } + u.extensions = toField(&f) + if f.Tag.Get("protobuf_messageset") == "1" { + u.isMessageSet = true + } + continue + } + if f.Name == "XXX_extensions" { + // An older form of the extensions field. + if f.Type == reflect.TypeOf((map[int32]Extension)(nil)) { + u.oldExtensions = toField(&f) + continue + } else if f.Type == reflect.TypeOf(([]byte)(nil)) { + u.bytesExtensions = toField(&f) + continue + } + panic("bad type for XXX_extensions field: " + f.Type.Name()) + } + if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" { + continue + } + + oneof := f.Tag.Get("protobuf_oneof") + if oneof != "" { + oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)}) + // The rest of oneof processing happens below. + continue + } + + tags := f.Tag.Get("protobuf") + tagArray := strings.Split(tags, ",") + if len(tagArray) < 2 { + panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags) + } + tag, err := strconv.Atoi(tagArray[1]) + if err != nil { + panic("protobuf tag field not an integer: " + tagArray[1]) + } + + name := "" + for _, tag := range tagArray[3:] { + if strings.HasPrefix(tag, "name=") { + name = tag[5:] + } + } + + // Extract unmarshaling function from the field (its type and tags). + unmarshal := fieldUnmarshaler(&f) + + // Required field? + var reqMask uint64 + if tagArray[2] == "req" { + bit := len(u.reqFields) + u.reqFields = append(u.reqFields, name) + reqMask = uint64(1) << uint(bit) + // TODO: if we have more than 64 required fields, we end up + // not verifying that all required fields are present. + // Fix this, perhaps using a count of required fields? + } + + // Store the info in the correct slot in the message. + u.setTag(tag, toField(&f), unmarshal, reqMask, name) + } + + // Find any types associated with oneof fields. + // gogo: len(oneofFields) > 0 is needed for embedded oneof messages, without a marshaler and unmarshaler + if len(oneofFields) > 0 { + var oneofImplementers []interface{} + switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) { + case oneofFuncsIface: + _, _, _, oneofImplementers = m.XXX_OneofFuncs() + case oneofWrappersIface: + oneofImplementers = m.XXX_OneofWrappers() + } + for _, v := range oneofImplementers { + tptr := reflect.TypeOf(v) // *Msg_X + typ := tptr.Elem() // Msg_X + + f := typ.Field(0) // oneof implementers have one field + baseUnmarshal := fieldUnmarshaler(&f) + tags := strings.Split(f.Tag.Get("protobuf"), ",") + fieldNum, err := strconv.Atoi(tags[1]) + if err != nil { + panic("protobuf tag field not an integer: " + tags[1]) + } + var name string + for _, tag := range tags { + if strings.HasPrefix(tag, "name=") { + name = strings.TrimPrefix(tag, "name=") + break + } + } + + // Find the oneof field that this struct implements. + // Might take O(n^2) to process all of the oneofs, but who cares. + for _, of := range oneofFields { + if tptr.Implements(of.ityp) { + // We have found the corresponding interface for this struct. + // That lets us know where this struct should be stored + // when we encounter it during unmarshaling. + unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal) + u.setTag(fieldNum, of.field, unmarshal, 0, name) + } + } + + } + } + + // Get extension ranges, if any. + fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray") + if fn.IsValid() { + if !u.extensions.IsValid() && !u.oldExtensions.IsValid() && !u.bytesExtensions.IsValid() { + panic("a message with extensions, but no extensions field in " + t.Name()) + } + u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange) + } + + // Explicitly disallow tag 0. This will ensure we flag an error + // when decoding a buffer of all zeros. Without this code, we + // would decode and skip an all-zero buffer of even length. + // [0 0] is [tag=0/wiretype=varint varint-encoded-0]. + u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) { + return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w) + }, 0, "") + + // Set mask for required field check. + u.reqMask = uint64(1)<= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here? + for len(u.dense) <= tag { + u.dense = append(u.dense, unmarshalFieldInfo{}) + } + u.dense[tag] = i + return + } + if u.sparse == nil { + u.sparse = map[uint64]unmarshalFieldInfo{} + } + u.sparse[uint64(tag)] = i +} + +// fieldUnmarshaler returns an unmarshaler for the given field. +func fieldUnmarshaler(f *reflect.StructField) unmarshaler { + if f.Type.Kind() == reflect.Map { + return makeUnmarshalMap(f) + } + return typeUnmarshaler(f.Type, f.Tag.Get("protobuf")) +} + +// typeUnmarshaler returns an unmarshaler for the given field type / field tag pair. +func typeUnmarshaler(t reflect.Type, tags string) unmarshaler { + tagArray := strings.Split(tags, ",") + encoding := tagArray[0] + name := "unknown" + ctype := false + isTime := false + isDuration := false + isWktPointer := false + proto3 := false + validateUTF8 := true + for _, tag := range tagArray[3:] { + if strings.HasPrefix(tag, "name=") { + name = tag[5:] + } + if tag == "proto3" { + proto3 = true + } + if strings.HasPrefix(tag, "customtype=") { + ctype = true + } + if tag == "stdtime" { + isTime = true + } + if tag == "stdduration" { + isDuration = true + } + if tag == "wktptr" { + isWktPointer = true + } + } + validateUTF8 = validateUTF8 && proto3 + + // Figure out packaging (pointer, slice, or both) + slice := false + pointer := false + if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { + slice = true + t = t.Elem() + } + if t.Kind() == reflect.Ptr { + pointer = true + t = t.Elem() + } + + if ctype { + if reflect.PtrTo(t).Implements(customType) { + if slice { + return makeUnmarshalCustomSlice(getUnmarshalInfo(t), name) + } + if pointer { + return makeUnmarshalCustomPtr(getUnmarshalInfo(t), name) + } + return makeUnmarshalCustom(getUnmarshalInfo(t), name) + } else { + panic(fmt.Sprintf("custom type: type: %v, does not implement the proto.custom interface", t)) + } + } + + if isTime { + if pointer { + if slice { + return makeUnmarshalTimePtrSlice(getUnmarshalInfo(t), name) + } + return makeUnmarshalTimePtr(getUnmarshalInfo(t), name) + } + if slice { + return makeUnmarshalTimeSlice(getUnmarshalInfo(t), name) + } + return makeUnmarshalTime(getUnmarshalInfo(t), name) + } + + if isDuration { + if pointer { + if slice { + return makeUnmarshalDurationPtrSlice(getUnmarshalInfo(t), name) + } + return makeUnmarshalDurationPtr(getUnmarshalInfo(t), name) + } + if slice { + return makeUnmarshalDurationSlice(getUnmarshalInfo(t), name) + } + return makeUnmarshalDuration(getUnmarshalInfo(t), name) + } + + if isWktPointer { + switch t.Kind() { + case reflect.Float64: + if pointer { + if slice { + return makeStdDoubleValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdDoubleValuePtrUnmarshaler(getUnmarshalInfo(t), name) + } + if slice { + return makeStdDoubleValueSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdDoubleValueUnmarshaler(getUnmarshalInfo(t), name) + case reflect.Float32: + if pointer { + if slice { + return makeStdFloatValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdFloatValuePtrUnmarshaler(getUnmarshalInfo(t), name) + } + if slice { + return makeStdFloatValueSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdFloatValueUnmarshaler(getUnmarshalInfo(t), name) + case reflect.Int64: + if pointer { + if slice { + return makeStdInt64ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdInt64ValuePtrUnmarshaler(getUnmarshalInfo(t), name) + } + if slice { + return makeStdInt64ValueSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdInt64ValueUnmarshaler(getUnmarshalInfo(t), name) + case reflect.Uint64: + if pointer { + if slice { + return makeStdUInt64ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdUInt64ValuePtrUnmarshaler(getUnmarshalInfo(t), name) + } + if slice { + return makeStdUInt64ValueSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdUInt64ValueUnmarshaler(getUnmarshalInfo(t), name) + case reflect.Int32: + if pointer { + if slice { + return makeStdInt32ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdInt32ValuePtrUnmarshaler(getUnmarshalInfo(t), name) + } + if slice { + return makeStdInt32ValueSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdInt32ValueUnmarshaler(getUnmarshalInfo(t), name) + case reflect.Uint32: + if pointer { + if slice { + return makeStdUInt32ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdUInt32ValuePtrUnmarshaler(getUnmarshalInfo(t), name) + } + if slice { + return makeStdUInt32ValueSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdUInt32ValueUnmarshaler(getUnmarshalInfo(t), name) + case reflect.Bool: + if pointer { + if slice { + return makeStdBoolValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdBoolValuePtrUnmarshaler(getUnmarshalInfo(t), name) + } + if slice { + return makeStdBoolValueSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdBoolValueUnmarshaler(getUnmarshalInfo(t), name) + case reflect.String: + if pointer { + if slice { + return makeStdStringValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdStringValuePtrUnmarshaler(getUnmarshalInfo(t), name) + } + if slice { + return makeStdStringValueSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdStringValueUnmarshaler(getUnmarshalInfo(t), name) + case uint8SliceType: + if pointer { + if slice { + return makeStdBytesValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdBytesValuePtrUnmarshaler(getUnmarshalInfo(t), name) + } + if slice { + return makeStdBytesValueSliceUnmarshaler(getUnmarshalInfo(t), name) + } + return makeStdBytesValueUnmarshaler(getUnmarshalInfo(t), name) + default: + panic(fmt.Sprintf("unknown wktpointer type %#v", t)) + } + } + + // We'll never have both pointer and slice for basic types. + if pointer && slice && t.Kind() != reflect.Struct { + panic("both pointer and slice for basic type in " + t.Name()) + } + + switch t.Kind() { + case reflect.Bool: + if pointer { + return unmarshalBoolPtr + } + if slice { + return unmarshalBoolSlice + } + return unmarshalBoolValue + case reflect.Int32: + switch encoding { + case "fixed32": + if pointer { + return unmarshalFixedS32Ptr + } + if slice { + return unmarshalFixedS32Slice + } + return unmarshalFixedS32Value + case "varint": + // this could be int32 or enum + if pointer { + return unmarshalInt32Ptr + } + if slice { + return unmarshalInt32Slice + } + return unmarshalInt32Value + case "zigzag32": + if pointer { + return unmarshalSint32Ptr + } + if slice { + return unmarshalSint32Slice + } + return unmarshalSint32Value + } + case reflect.Int64: + switch encoding { + case "fixed64": + if pointer { + return unmarshalFixedS64Ptr + } + if slice { + return unmarshalFixedS64Slice + } + return unmarshalFixedS64Value + case "varint": + if pointer { + return unmarshalInt64Ptr + } + if slice { + return unmarshalInt64Slice + } + return unmarshalInt64Value + case "zigzag64": + if pointer { + return unmarshalSint64Ptr + } + if slice { + return unmarshalSint64Slice + } + return unmarshalSint64Value + } + case reflect.Uint32: + switch encoding { + case "fixed32": + if pointer { + return unmarshalFixed32Ptr + } + if slice { + return unmarshalFixed32Slice + } + return unmarshalFixed32Value + case "varint": + if pointer { + return unmarshalUint32Ptr + } + if slice { + return unmarshalUint32Slice + } + return unmarshalUint32Value + } + case reflect.Uint64: + switch encoding { + case "fixed64": + if pointer { + return unmarshalFixed64Ptr + } + if slice { + return unmarshalFixed64Slice + } + return unmarshalFixed64Value + case "varint": + if pointer { + return unmarshalUint64Ptr + } + if slice { + return unmarshalUint64Slice + } + return unmarshalUint64Value + } + case reflect.Float32: + if pointer { + return unmarshalFloat32Ptr + } + if slice { + return unmarshalFloat32Slice + } + return unmarshalFloat32Value + case reflect.Float64: + if pointer { + return unmarshalFloat64Ptr + } + if slice { + return unmarshalFloat64Slice + } + return unmarshalFloat64Value + case reflect.Map: + panic("map type in typeUnmarshaler in " + t.Name()) + case reflect.Slice: + if pointer { + panic("bad pointer in slice case in " + t.Name()) + } + if slice { + return unmarshalBytesSlice + } + return unmarshalBytesValue + case reflect.String: + if validateUTF8 { + if pointer { + return unmarshalUTF8StringPtr + } + if slice { + return unmarshalUTF8StringSlice + } + return unmarshalUTF8StringValue + } + if pointer { + return unmarshalStringPtr + } + if slice { + return unmarshalStringSlice + } + return unmarshalStringValue + case reflect.Struct: + // message or group field + if !pointer { + switch encoding { + case "bytes": + if slice { + return makeUnmarshalMessageSlice(getUnmarshalInfo(t), name) + } + return makeUnmarshalMessage(getUnmarshalInfo(t), name) + } + } + switch encoding { + case "bytes": + if slice { + return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name) + } + return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name) + case "group": + if slice { + return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name) + } + return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name) + } + } + panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding)) +} + +// Below are all the unmarshalers for individual fields of various types. + +func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x) + *f.toInt64() = v + return b, nil +} + +func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x) + *f.toInt64Ptr() = &v + return b, nil +} + +func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x) + s := f.toInt64Slice() + *s = append(*s, v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x) + s := f.toInt64Slice() + *s = append(*s, v) + return b, nil +} + +func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x>>1) ^ int64(x)<<63>>63 + *f.toInt64() = v + return b, nil +} + +func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x>>1) ^ int64(x)<<63>>63 + *f.toInt64Ptr() = &v + return b, nil +} + +func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x>>1) ^ int64(x)<<63>>63 + s := f.toInt64Slice() + *s = append(*s, v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x>>1) ^ int64(x)<<63>>63 + s := f.toInt64Slice() + *s = append(*s, v) + return b, nil +} + +func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint64(x) + *f.toUint64() = v + return b, nil +} + +func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint64(x) + *f.toUint64Ptr() = &v + return b, nil +} + +func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint64(x) + s := f.toUint64Slice() + *s = append(*s, v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint64(x) + s := f.toUint64Slice() + *s = append(*s, v) + return b, nil +} + +func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x) + *f.toInt32() = v + return b, nil +} + +func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x) + f.setInt32Ptr(v) + return b, nil +} + +func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x) + f.appendInt32Slice(v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x) + f.appendInt32Slice(v) + return b, nil +} + +func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x>>1) ^ int32(x)<<31>>31 + *f.toInt32() = v + return b, nil +} + +func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x>>1) ^ int32(x)<<31>>31 + f.setInt32Ptr(v) + return b, nil +} + +func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x>>1) ^ int32(x)<<31>>31 + f.appendInt32Slice(v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x>>1) ^ int32(x)<<31>>31 + f.appendInt32Slice(v) + return b, nil +} + +func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint32(x) + *f.toUint32() = v + return b, nil +} + +func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint32(x) + *f.toUint32Ptr() = &v + return b, nil +} + +func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint32(x) + s := f.toUint32Slice() + *s = append(*s, v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint32(x) + s := f.toUint32Slice() + *s = append(*s, v) + return b, nil +} + +func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 + *f.toUint64() = v + return b[8:], nil +} + +func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 + *f.toUint64Ptr() = &v + return b[8:], nil +} + +func unmarshalFixed64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 + s := f.toUint64Slice() + *s = append(*s, v) + b = b[8:] + } + return res, nil + } + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 + s := f.toUint64Slice() + *s = append(*s, v) + return b[8:], nil +} + +func unmarshalFixedS64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 + *f.toInt64() = v + return b[8:], nil +} + +func unmarshalFixedS64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 + *f.toInt64Ptr() = &v + return b[8:], nil +} + +func unmarshalFixedS64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 + s := f.toInt64Slice() + *s = append(*s, v) + b = b[8:] + } + return res, nil + } + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 + s := f.toInt64Slice() + *s = append(*s, v) + return b[8:], nil +} + +func unmarshalFixed32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 + *f.toUint32() = v + return b[4:], nil +} + +func unmarshalFixed32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 + *f.toUint32Ptr() = &v + return b[4:], nil +} + +func unmarshalFixed32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 + s := f.toUint32Slice() + *s = append(*s, v) + b = b[4:] + } + return res, nil + } + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 + s := f.toUint32Slice() + *s = append(*s, v) + return b[4:], nil +} + +func unmarshalFixedS32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 + *f.toInt32() = v + return b[4:], nil +} + +func unmarshalFixedS32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 + f.setInt32Ptr(v) + return b[4:], nil +} + +func unmarshalFixedS32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 + f.appendInt32Slice(v) + b = b[4:] + } + return res, nil + } + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 + f.appendInt32Slice(v) + return b[4:], nil +} + +func unmarshalBoolValue(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + // Note: any length varint is allowed, even though any sane + // encoder will use one byte. + // See https://github.com/golang/protobuf/issues/76 + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + // TODO: check if x>1? Tests seem to indicate no. + v := x != 0 + *f.toBool() = v + return b[n:], nil +} + +func unmarshalBoolPtr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + v := x != 0 + *f.toBoolPtr() = &v + return b[n:], nil +} + +func unmarshalBoolSlice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + v := x != 0 + s := f.toBoolSlice() + *s = append(*s, v) + b = b[n:] + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + v := x != 0 + s := f.toBoolSlice() + *s = append(*s, v) + return b[n:], nil +} + +func unmarshalFloat64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) + *f.toFloat64() = v + return b[8:], nil +} + +func unmarshalFloat64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) + *f.toFloat64Ptr() = &v + return b[8:], nil +} + +func unmarshalFloat64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) + s := f.toFloat64Slice() + *s = append(*s, v) + b = b[8:] + } + return res, nil + } + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) + s := f.toFloat64Slice() + *s = append(*s, v) + return b[8:], nil +} + +func unmarshalFloat32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) + *f.toFloat32() = v + return b[4:], nil +} + +func unmarshalFloat32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) + *f.toFloat32Ptr() = &v + return b[4:], nil +} + +func unmarshalFloat32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) + s := f.toFloat32Slice() + *s = append(*s, v) + b = b[4:] + } + return res, nil + } + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) + s := f.toFloat32Slice() + *s = append(*s, v) + return b[4:], nil +} + +func unmarshalStringValue(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := string(b[:x]) + *f.toString() = v + return b[x:], nil +} + +func unmarshalStringPtr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := string(b[:x]) + *f.toStringPtr() = &v + return b[x:], nil +} + +func unmarshalStringSlice(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := string(b[:x]) + s := f.toStringSlice() + *s = append(*s, v) + return b[x:], nil +} + +func unmarshalUTF8StringValue(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := string(b[:x]) + *f.toString() = v + if !utf8.ValidString(v) { + return b[x:], errInvalidUTF8 + } + return b[x:], nil +} + +func unmarshalUTF8StringPtr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := string(b[:x]) + *f.toStringPtr() = &v + if !utf8.ValidString(v) { + return b[x:], errInvalidUTF8 + } + return b[x:], nil +} + +func unmarshalUTF8StringSlice(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := string(b[:x]) + s := f.toStringSlice() + *s = append(*s, v) + if !utf8.ValidString(v) { + return b[x:], errInvalidUTF8 + } + return b[x:], nil +} + +var emptyBuf [0]byte + +func unmarshalBytesValue(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + // The use of append here is a trick which avoids the zeroing + // that would be required if we used a make/copy pair. + // We append to emptyBuf instead of nil because we want + // a non-nil result even when the length is 0. + v := append(emptyBuf[:], b[:x]...) + *f.toBytes() = v + return b[x:], nil +} + +func unmarshalBytesSlice(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := append(emptyBuf[:], b[:x]...) + s := f.toBytesSlice() + *s = append(*s, v) + return b[x:], nil +} + +func makeUnmarshalMessagePtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + // First read the message field to see if something is there. + // The semantics of multiple submessages are weird. Instead of + // the last one winning (as it is for all other fields), multiple + // submessages are merged. + v := f.getPointer() + if v.isNil() { + v = valToPointer(reflect.New(sub.typ)) + f.setPointer(v) + } + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + return b[x:], err + } +} + +func makeUnmarshalMessageSlicePtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := valToPointer(reflect.New(sub.typ)) + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + f.appendPointer(v) + return b[x:], err + } +} + +func makeUnmarshalGroupPtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireStartGroup { + return b, errInternalBadWireType + } + x, y := findEndGroup(b) + if x < 0 { + return nil, io.ErrUnexpectedEOF + } + v := f.getPointer() + if v.isNil() { + v = valToPointer(reflect.New(sub.typ)) + f.setPointer(v) + } + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + return b[y:], err + } +} + +func makeUnmarshalGroupSlicePtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireStartGroup { + return b, errInternalBadWireType + } + x, y := findEndGroup(b) + if x < 0 { + return nil, io.ErrUnexpectedEOF + } + v := valToPointer(reflect.New(sub.typ)) + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + f.appendPointer(v) + return b[y:], err + } +} + +func makeUnmarshalMap(f *reflect.StructField) unmarshaler { + t := f.Type + kt := t.Key() + vt := t.Elem() + tagArray := strings.Split(f.Tag.Get("protobuf"), ",") + valTags := strings.Split(f.Tag.Get("protobuf_val"), ",") + for _, t := range tagArray { + if strings.HasPrefix(t, "customtype=") { + valTags = append(valTags, t) + } + if t == "stdtime" { + valTags = append(valTags, t) + } + if t == "stdduration" { + valTags = append(valTags, t) + } + if t == "wktptr" { + valTags = append(valTags, t) + } + } + unmarshalKey := typeUnmarshaler(kt, f.Tag.Get("protobuf_key")) + unmarshalVal := typeUnmarshaler(vt, strings.Join(valTags, ",")) + return func(b []byte, f pointer, w int) ([]byte, error) { + // The map entry is a submessage. Figure out how big it is. + if w != WireBytes { + return nil, fmt.Errorf("proto: bad wiretype for map field: got %d want %d", w, WireBytes) + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + r := b[x:] // unused data to return + b = b[:x] // data for map entry + + // Note: we could use #keys * #values ~= 200 functions + // to do map decoding without reflection. Probably not worth it. + // Maps will be somewhat slow. Oh well. + + // Read key and value from data. + var nerr nonFatal + k := reflect.New(kt) + v := reflect.New(vt) + for len(b) > 0 { + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + wire := int(x) & 7 + b = b[n:] + + var err error + switch x >> 3 { + case 1: + b, err = unmarshalKey(b, valToPointer(k), wire) + case 2: + b, err = unmarshalVal(b, valToPointer(v), wire) + default: + err = errInternalBadWireType // skip unknown tag + } + + if nerr.Merge(err) { + continue + } + if err != errInternalBadWireType { + return nil, err + } + + // Skip past unknown fields. + b, err = skipField(b, wire) + if err != nil { + return nil, err + } + } + + // Get map, allocate if needed. + m := f.asPointerTo(t).Elem() // an addressable map[K]T + if m.IsNil() { + m.Set(reflect.MakeMap(t)) + } + + // Insert into map. + m.SetMapIndex(k.Elem(), v.Elem()) + + return r, nerr.E + } +} + +// makeUnmarshalOneof makes an unmarshaler for oneof fields. +// for: +// message Msg { +// oneof F { +// int64 X = 1; +// float64 Y = 2; +// } +// } +// typ is the type of the concrete entry for a oneof case (e.g. Msg_X). +// ityp is the interface type of the oneof field (e.g. isMsg_F). +// unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64). +// Note that this function will be called once for each case in the oneof. +func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler { + sf := typ.Field(0) + field0 := toField(&sf) + return func(b []byte, f pointer, w int) ([]byte, error) { + // Allocate holder for value. + v := reflect.New(typ) + + // Unmarshal data into holder. + // We unmarshal into the first field of the holder object. + var err error + var nerr nonFatal + b, err = unmarshal(b, valToPointer(v).offset(field0), w) + if !nerr.Merge(err) { + return nil, err + } + + // Write pointer to holder into target field. + f.asPointerTo(ityp).Elem().Set(v) + + return b, nerr.E + } +} + +// Error used by decode internally. +var errInternalBadWireType = errors.New("proto: internal error: bad wiretype") + +// skipField skips past a field of type wire and returns the remaining bytes. +func skipField(b []byte, wire int) ([]byte, error) { + switch wire { + case WireVarint: + _, k := decodeVarint(b) + if k == 0 { + return b, io.ErrUnexpectedEOF + } + b = b[k:] + case WireFixed32: + if len(b) < 4 { + return b, io.ErrUnexpectedEOF + } + b = b[4:] + case WireFixed64: + if len(b) < 8 { + return b, io.ErrUnexpectedEOF + } + b = b[8:] + case WireBytes: + m, k := decodeVarint(b) + if k == 0 || uint64(len(b)-k) < m { + return b, io.ErrUnexpectedEOF + } + b = b[uint64(k)+m:] + case WireStartGroup: + _, i := findEndGroup(b) + if i == -1 { + return b, io.ErrUnexpectedEOF + } + b = b[i:] + default: + return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire) + } + return b, nil +} + +// findEndGroup finds the index of the next EndGroup tag. +// Groups may be nested, so the "next" EndGroup tag is the first +// unpaired EndGroup. +// findEndGroup returns the indexes of the start and end of the EndGroup tag. +// Returns (-1,-1) if it can't find one. +func findEndGroup(b []byte) (int, int) { + depth := 1 + i := 0 + for { + x, n := decodeVarint(b[i:]) + if n == 0 { + return -1, -1 + } + j := i + i += n + switch x & 7 { + case WireVarint: + _, k := decodeVarint(b[i:]) + if k == 0 { + return -1, -1 + } + i += k + case WireFixed32: + if len(b)-4 < i { + return -1, -1 + } + i += 4 + case WireFixed64: + if len(b)-8 < i { + return -1, -1 + } + i += 8 + case WireBytes: + m, k := decodeVarint(b[i:]) + if k == 0 { + return -1, -1 + } + i += k + if uint64(len(b)-i) < m { + return -1, -1 + } + i += int(m) + case WireStartGroup: + depth++ + case WireEndGroup: + depth-- + if depth == 0 { + return j, i + } + default: + return -1, -1 + } + } +} + +// encodeVarint appends a varint-encoded integer to b and returns the result. +func encodeVarint(b []byte, x uint64) []byte { + for x >= 1<<7 { + b = append(b, byte(x&0x7f|0x80)) + x >>= 7 + } + return append(b, byte(x)) +} + +// decodeVarint reads a varint-encoded integer from b. +// Returns the decoded integer and the number of bytes read. +// If there is an error, it returns 0,0. +func decodeVarint(b []byte) (uint64, int) { + var x, y uint64 + if len(b) == 0 { + goto bad + } + x = uint64(b[0]) + if x < 0x80 { + return x, 1 + } + x -= 0x80 + + if len(b) <= 1 { + goto bad + } + y = uint64(b[1]) + x += y << 7 + if y < 0x80 { + return x, 2 + } + x -= 0x80 << 7 + + if len(b) <= 2 { + goto bad + } + y = uint64(b[2]) + x += y << 14 + if y < 0x80 { + return x, 3 + } + x -= 0x80 << 14 + + if len(b) <= 3 { + goto bad + } + y = uint64(b[3]) + x += y << 21 + if y < 0x80 { + return x, 4 + } + x -= 0x80 << 21 + + if len(b) <= 4 { + goto bad + } + y = uint64(b[4]) + x += y << 28 + if y < 0x80 { + return x, 5 + } + x -= 0x80 << 28 + + if len(b) <= 5 { + goto bad + } + y = uint64(b[5]) + x += y << 35 + if y < 0x80 { + return x, 6 + } + x -= 0x80 << 35 + + if len(b) <= 6 { + goto bad + } + y = uint64(b[6]) + x += y << 42 + if y < 0x80 { + return x, 7 + } + x -= 0x80 << 42 + + if len(b) <= 7 { + goto bad + } + y = uint64(b[7]) + x += y << 49 + if y < 0x80 { + return x, 8 + } + x -= 0x80 << 49 + + if len(b) <= 8 { + goto bad + } + y = uint64(b[8]) + x += y << 56 + if y < 0x80 { + return x, 9 + } + x -= 0x80 << 56 + + if len(b) <= 9 { + goto bad + } + y = uint64(b[9]) + x += y << 63 + if y < 2 { + return x, 10 + } + +bad: + return 0, 0 +} diff --git a/vendor/github.com/gogo/protobuf/proto/table_unmarshal_gogo.go b/vendor/github.com/gogo/protobuf/proto/table_unmarshal_gogo.go new file mode 100644 index 00000000..00d6c7ad --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/table_unmarshal_gogo.go @@ -0,0 +1,385 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2018, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "io" + "reflect" +) + +func makeUnmarshalMessage(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + // First read the message field to see if something is there. + // The semantics of multiple submessages are weird. Instead of + // the last one winning (as it is for all other fields), multiple + // submessages are merged. + v := f // gogo: changed from v := f.getPointer() + if v.isNil() { + v = valToPointer(reflect.New(sub.typ)) + f.setPointer(v) + } + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + return b[x:], err + } +} + +func makeUnmarshalMessageSlice(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := valToPointer(reflect.New(sub.typ)) + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + f.appendRef(v, sub.typ) // gogo: changed from f.appendPointer(v) + return b[x:], err + } +} + +func makeUnmarshalCustomPtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.New(sub.typ)) + m := s.Interface().(custom) + if err := m.Unmarshal(b[:x]); err != nil { + return nil, err + } + return b[x:], nil + } +} + +func makeUnmarshalCustomSlice(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := reflect.New(sub.typ) + c := m.Interface().(custom) + if err := c.Unmarshal(b[:x]); err != nil { + return nil, err + } + v := valToPointer(m) + f.appendRef(v, sub.typ) + return b[x:], nil + } +} + +func makeUnmarshalCustom(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + + m := f.asPointerTo(sub.typ).Interface().(custom) + if err := m.Unmarshal(b[:x]); err != nil { + return nil, err + } + return b[x:], nil + } +} + +func makeUnmarshalTime(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := ×tamp{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + t, err := timestampFromProto(m) + if err != nil { + return nil, err + } + s := f.asPointerTo(sub.typ).Elem() + s.Set(reflect.ValueOf(t)) + return b[x:], nil + } +} + +func makeUnmarshalTimePtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := ×tamp{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + t, err := timestampFromProto(m) + if err != nil { + return nil, err + } + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.ValueOf(&t)) + return b[x:], nil + } +} + +func makeUnmarshalTimePtrSlice(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := ×tamp{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + t, err := timestampFromProto(m) + if err != nil { + return nil, err + } + slice := f.getSlice(reflect.PtrTo(sub.typ)) + newSlice := reflect.Append(slice, reflect.ValueOf(&t)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeUnmarshalTimeSlice(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := ×tamp{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + t, err := timestampFromProto(m) + if err != nil { + return nil, err + } + slice := f.getSlice(sub.typ) + newSlice := reflect.Append(slice, reflect.ValueOf(t)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeUnmarshalDurationPtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &duration{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + d, err := durationFromProto(m) + if err != nil { + return nil, err + } + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.ValueOf(&d)) + return b[x:], nil + } +} + +func makeUnmarshalDuration(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &duration{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + d, err := durationFromProto(m) + if err != nil { + return nil, err + } + s := f.asPointerTo(sub.typ).Elem() + s.Set(reflect.ValueOf(d)) + return b[x:], nil + } +} + +func makeUnmarshalDurationPtrSlice(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &duration{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + d, err := durationFromProto(m) + if err != nil { + return nil, err + } + slice := f.getSlice(reflect.PtrTo(sub.typ)) + newSlice := reflect.Append(slice, reflect.ValueOf(&d)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeUnmarshalDurationSlice(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &duration{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + d, err := durationFromProto(m) + if err != nil { + return nil, err + } + slice := f.getSlice(sub.typ) + newSlice := reflect.Append(slice, reflect.ValueOf(d)) + slice.Set(newSlice) + return b[x:], nil + } +} diff --git a/vendor/github.com/gogo/protobuf/proto/text.go b/vendor/github.com/gogo/protobuf/proto/text.go new file mode 100644 index 00000000..87416afe --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/text.go @@ -0,0 +1,930 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +// Functions for writing the text protocol buffer format. + +import ( + "bufio" + "bytes" + "encoding" + "errors" + "fmt" + "io" + "log" + "math" + "reflect" + "sort" + "strings" + "sync" + "time" +) + +var ( + newline = []byte("\n") + spaces = []byte(" ") + endBraceNewline = []byte("}\n") + backslashN = []byte{'\\', 'n'} + backslashR = []byte{'\\', 'r'} + backslashT = []byte{'\\', 't'} + backslashDQ = []byte{'\\', '"'} + backslashBS = []byte{'\\', '\\'} + posInf = []byte("inf") + negInf = []byte("-inf") + nan = []byte("nan") +) + +type writer interface { + io.Writer + WriteByte(byte) error +} + +// textWriter is an io.Writer that tracks its indentation level. +type textWriter struct { + ind int + complete bool // if the current position is a complete line + compact bool // whether to write out as a one-liner + w writer +} + +func (w *textWriter) WriteString(s string) (n int, err error) { + if !strings.Contains(s, "\n") { + if !w.compact && w.complete { + w.writeIndent() + } + w.complete = false + return io.WriteString(w.w, s) + } + // WriteString is typically called without newlines, so this + // codepath and its copy are rare. We copy to avoid + // duplicating all of Write's logic here. + return w.Write([]byte(s)) +} + +func (w *textWriter) Write(p []byte) (n int, err error) { + newlines := bytes.Count(p, newline) + if newlines == 0 { + if !w.compact && w.complete { + w.writeIndent() + } + n, err = w.w.Write(p) + w.complete = false + return n, err + } + + frags := bytes.SplitN(p, newline, newlines+1) + if w.compact { + for i, frag := range frags { + if i > 0 { + if err := w.w.WriteByte(' '); err != nil { + return n, err + } + n++ + } + nn, err := w.w.Write(frag) + n += nn + if err != nil { + return n, err + } + } + return n, nil + } + + for i, frag := range frags { + if w.complete { + w.writeIndent() + } + nn, err := w.w.Write(frag) + n += nn + if err != nil { + return n, err + } + if i+1 < len(frags) { + if err := w.w.WriteByte('\n'); err != nil { + return n, err + } + n++ + } + } + w.complete = len(frags[len(frags)-1]) == 0 + return n, nil +} + +func (w *textWriter) WriteByte(c byte) error { + if w.compact && c == '\n' { + c = ' ' + } + if !w.compact && w.complete { + w.writeIndent() + } + err := w.w.WriteByte(c) + w.complete = c == '\n' + return err +} + +func (w *textWriter) indent() { w.ind++ } + +func (w *textWriter) unindent() { + if w.ind == 0 { + log.Print("proto: textWriter unindented too far") + return + } + w.ind-- +} + +func writeName(w *textWriter, props *Properties) error { + if _, err := w.WriteString(props.OrigName); err != nil { + return err + } + if props.Wire != "group" { + return w.WriteByte(':') + } + return nil +} + +func requiresQuotes(u string) bool { + // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. + for _, ch := range u { + switch { + case ch == '.' || ch == '/' || ch == '_': + continue + case '0' <= ch && ch <= '9': + continue + case 'A' <= ch && ch <= 'Z': + continue + case 'a' <= ch && ch <= 'z': + continue + default: + return true + } + } + return false +} + +// isAny reports whether sv is a google.protobuf.Any message +func isAny(sv reflect.Value) bool { + type wkt interface { + XXX_WellKnownType() string + } + t, ok := sv.Addr().Interface().(wkt) + return ok && t.XXX_WellKnownType() == "Any" +} + +// writeProto3Any writes an expanded google.protobuf.Any message. +// +// It returns (false, nil) if sv value can't be unmarshaled (e.g. because +// required messages are not linked in). +// +// It returns (true, error) when sv was written in expanded format or an error +// was encountered. +func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) { + turl := sv.FieldByName("TypeUrl") + val := sv.FieldByName("Value") + if !turl.IsValid() || !val.IsValid() { + return true, errors.New("proto: invalid google.protobuf.Any message") + } + + b, ok := val.Interface().([]byte) + if !ok { + return true, errors.New("proto: invalid google.protobuf.Any message") + } + + parts := strings.Split(turl.String(), "/") + mt := MessageType(parts[len(parts)-1]) + if mt == nil { + return false, nil + } + m := reflect.New(mt.Elem()) + if err := Unmarshal(b, m.Interface().(Message)); err != nil { + return false, nil + } + w.Write([]byte("[")) + u := turl.String() + if requiresQuotes(u) { + writeString(w, u) + } else { + w.Write([]byte(u)) + } + if w.compact { + w.Write([]byte("]:<")) + } else { + w.Write([]byte("]: <\n")) + w.ind++ + } + if err := tm.writeStruct(w, m.Elem()); err != nil { + return true, err + } + if w.compact { + w.Write([]byte("> ")) + } else { + w.ind-- + w.Write([]byte(">\n")) + } + return true, nil +} + +func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { + if tm.ExpandAny && isAny(sv) { + if canExpand, err := tm.writeProto3Any(w, sv); canExpand { + return err + } + } + st := sv.Type() + sprops := GetProperties(st) + for i := 0; i < sv.NumField(); i++ { + fv := sv.Field(i) + props := sprops.Prop[i] + name := st.Field(i).Name + + if name == "XXX_NoUnkeyedLiteral" { + continue + } + + if strings.HasPrefix(name, "XXX_") { + // There are two XXX_ fields: + // XXX_unrecognized []byte + // XXX_extensions map[int32]proto.Extension + // The first is handled here; + // the second is handled at the bottom of this function. + if name == "XXX_unrecognized" && !fv.IsNil() { + if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { + return err + } + } + continue + } + if fv.Kind() == reflect.Ptr && fv.IsNil() { + // Field not filled in. This could be an optional field or + // a required field that wasn't filled in. Either way, there + // isn't anything we can show for it. + continue + } + if fv.Kind() == reflect.Slice && fv.IsNil() { + // Repeated field that is empty, or a bytes field that is unused. + continue + } + + if props.Repeated && fv.Kind() == reflect.Slice { + // Repeated field. + for j := 0; j < fv.Len(); j++ { + if err := writeName(w, props); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + v := fv.Index(j) + if v.Kind() == reflect.Ptr && v.IsNil() { + // A nil message in a repeated field is not valid, + // but we can handle that more gracefully than panicking. + if _, err := w.Write([]byte("\n")); err != nil { + return err + } + continue + } + if len(props.Enum) > 0 { + if err := tm.writeEnum(w, v, props); err != nil { + return err + } + } else if err := tm.writeAny(w, v, props); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + } + continue + } + if fv.Kind() == reflect.Map { + // Map fields are rendered as a repeated struct with key/value fields. + keys := fv.MapKeys() + sort.Sort(mapKeys(keys)) + for _, key := range keys { + val := fv.MapIndex(key) + if err := writeName(w, props); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + // open struct + if err := w.WriteByte('<'); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte('\n'); err != nil { + return err + } + } + w.indent() + // key + if _, err := w.WriteString("key:"); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + if err := tm.writeAny(w, key, props.MapKeyProp); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + // nil values aren't legal, but we can avoid panicking because of them. + if val.Kind() != reflect.Ptr || !val.IsNil() { + // value + if _, err := w.WriteString("value:"); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + if err := tm.writeAny(w, val, props.MapValProp); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + } + // close struct + w.unindent() + if err := w.WriteByte('>'); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + } + continue + } + if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { + // empty bytes field + continue + } + if props.proto3 && fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { + // proto3 non-repeated scalar field; skip if zero value + if isProto3Zero(fv) { + continue + } + } + + if fv.Kind() == reflect.Interface { + // Check if it is a oneof. + if st.Field(i).Tag.Get("protobuf_oneof") != "" { + // fv is nil, or holds a pointer to generated struct. + // That generated struct has exactly one field, + // which has a protobuf struct tag. + if fv.IsNil() { + continue + } + inner := fv.Elem().Elem() // interface -> *T -> T + tag := inner.Type().Field(0).Tag.Get("protobuf") + props = new(Properties) // Overwrite the outer props var, but not its pointee. + props.Parse(tag) + // Write the value in the oneof, not the oneof itself. + fv = inner.Field(0) + + // Special case to cope with malformed messages gracefully: + // If the value in the oneof is a nil pointer, don't panic + // in writeAny. + if fv.Kind() == reflect.Ptr && fv.IsNil() { + // Use errors.New so writeAny won't render quotes. + msg := errors.New("/* nil */") + fv = reflect.ValueOf(&msg).Elem() + } + } + } + + if err := writeName(w, props); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + + if len(props.Enum) > 0 { + if err := tm.writeEnum(w, fv, props); err != nil { + return err + } + } else if err := tm.writeAny(w, fv, props); err != nil { + return err + } + + if err := w.WriteByte('\n'); err != nil { + return err + } + } + + // Extensions (the XXX_extensions field). + pv := sv + if pv.CanAddr() { + pv = sv.Addr() + } else { + pv = reflect.New(sv.Type()) + pv.Elem().Set(sv) + } + if _, err := extendable(pv.Interface()); err == nil { + if err := tm.writeExtensions(w, pv); err != nil { + return err + } + } + + return nil +} + +var textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() + +// writeAny writes an arbitrary field. +func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { + v = reflect.Indirect(v) + + if props != nil { + if len(props.CustomType) > 0 { + custom, ok := v.Interface().(Marshaler) + if ok { + data, err := custom.Marshal() + if err != nil { + return err + } + if err := writeString(w, string(data)); err != nil { + return err + } + return nil + } + } else if len(props.CastType) > 0 { + if _, ok := v.Interface().(interface { + String() string + }); ok { + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + _, err := fmt.Fprintf(w, "%d", v.Interface()) + return err + } + } + } else if props.StdTime { + t, ok := v.Interface().(time.Time) + if !ok { + return fmt.Errorf("stdtime is not time.Time, but %T", v.Interface()) + } + tproto, err := timestampProto(t) + if err != nil { + return err + } + propsCopy := *props // Make a copy so that this is goroutine-safe + propsCopy.StdTime = false + err = tm.writeAny(w, reflect.ValueOf(tproto), &propsCopy) + return err + } else if props.StdDuration { + d, ok := v.Interface().(time.Duration) + if !ok { + return fmt.Errorf("stdtime is not time.Duration, but %T", v.Interface()) + } + dproto := durationProto(d) + propsCopy := *props // Make a copy so that this is goroutine-safe + propsCopy.StdDuration = false + err := tm.writeAny(w, reflect.ValueOf(dproto), &propsCopy) + return err + } + } + + // Floats have special cases. + if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { + x := v.Float() + var b []byte + switch { + case math.IsInf(x, 1): + b = posInf + case math.IsInf(x, -1): + b = negInf + case math.IsNaN(x): + b = nan + } + if b != nil { + _, err := w.Write(b) + return err + } + // Other values are handled below. + } + + // We don't attempt to serialise every possible value type; only those + // that can occur in protocol buffers. + switch v.Kind() { + case reflect.Slice: + // Should only be a []byte; repeated fields are handled in writeStruct. + if err := writeString(w, string(v.Bytes())); err != nil { + return err + } + case reflect.String: + if err := writeString(w, v.String()); err != nil { + return err + } + case reflect.Struct: + // Required/optional group/message. + var bra, ket byte = '<', '>' + if props != nil && props.Wire == "group" { + bra, ket = '{', '}' + } + if err := w.WriteByte(bra); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte('\n'); err != nil { + return err + } + } + w.indent() + if v.CanAddr() { + // Calling v.Interface on a struct causes the reflect package to + // copy the entire struct. This is racy with the new Marshaler + // since we atomically update the XXX_sizecache. + // + // Thus, we retrieve a pointer to the struct if possible to avoid + // a race since v.Interface on the pointer doesn't copy the struct. + // + // If v is not addressable, then we are not worried about a race + // since it implies that the binary Marshaler cannot possibly be + // mutating this value. + v = v.Addr() + } + if v.Type().Implements(textMarshalerType) { + text, err := v.Interface().(encoding.TextMarshaler).MarshalText() + if err != nil { + return err + } + if _, err = w.Write(text); err != nil { + return err + } + } else { + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + if err := tm.writeStruct(w, v); err != nil { + return err + } + } + w.unindent() + if err := w.WriteByte(ket); err != nil { + return err + } + default: + _, err := fmt.Fprint(w, v.Interface()) + return err + } + return nil +} + +// equivalent to C's isprint. +func isprint(c byte) bool { + return c >= 0x20 && c < 0x7f +} + +// writeString writes a string in the protocol buffer text format. +// It is similar to strconv.Quote except we don't use Go escape sequences, +// we treat the string as a byte sequence, and we use octal escapes. +// These differences are to maintain interoperability with the other +// languages' implementations of the text format. +func writeString(w *textWriter, s string) error { + // use WriteByte here to get any needed indent + if err := w.WriteByte('"'); err != nil { + return err + } + // Loop over the bytes, not the runes. + for i := 0; i < len(s); i++ { + var err error + // Divergence from C++: we don't escape apostrophes. + // There's no need to escape them, and the C++ parser + // copes with a naked apostrophe. + switch c := s[i]; c { + case '\n': + _, err = w.w.Write(backslashN) + case '\r': + _, err = w.w.Write(backslashR) + case '\t': + _, err = w.w.Write(backslashT) + case '"': + _, err = w.w.Write(backslashDQ) + case '\\': + _, err = w.w.Write(backslashBS) + default: + if isprint(c) { + err = w.w.WriteByte(c) + } else { + _, err = fmt.Fprintf(w.w, "\\%03o", c) + } + } + if err != nil { + return err + } + } + return w.WriteByte('"') +} + +func writeUnknownStruct(w *textWriter, data []byte) (err error) { + if !w.compact { + if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { + return err + } + } + b := NewBuffer(data) + for b.index < len(b.buf) { + x, err := b.DecodeVarint() + if err != nil { + _, ferr := fmt.Fprintf(w, "/* %v */\n", err) + return ferr + } + wire, tag := x&7, x>>3 + if wire == WireEndGroup { + w.unindent() + if _, werr := w.Write(endBraceNewline); werr != nil { + return werr + } + continue + } + if _, ferr := fmt.Fprint(w, tag); ferr != nil { + return ferr + } + if wire != WireStartGroup { + if err = w.WriteByte(':'); err != nil { + return err + } + } + if !w.compact || wire == WireStartGroup { + if err = w.WriteByte(' '); err != nil { + return err + } + } + switch wire { + case WireBytes: + buf, e := b.DecodeRawBytes(false) + if e == nil { + _, err = fmt.Fprintf(w, "%q", buf) + } else { + _, err = fmt.Fprintf(w, "/* %v */", e) + } + case WireFixed32: + x, err = b.DecodeFixed32() + err = writeUnknownInt(w, x, err) + case WireFixed64: + x, err = b.DecodeFixed64() + err = writeUnknownInt(w, x, err) + case WireStartGroup: + err = w.WriteByte('{') + w.indent() + case WireVarint: + x, err = b.DecodeVarint() + err = writeUnknownInt(w, x, err) + default: + _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) + } + if err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + } + return nil +} + +func writeUnknownInt(w *textWriter, x uint64, err error) error { + if err == nil { + _, err = fmt.Fprint(w, x) + } else { + _, err = fmt.Fprintf(w, "/* %v */", err) + } + return err +} + +type int32Slice []int32 + +func (s int32Slice) Len() int { return len(s) } +func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } +func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } + +// writeExtensions writes all the extensions in pv. +// pv is assumed to be a pointer to a protocol message struct that is extendable. +func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { + emap := extensionMaps[pv.Type().Elem()] + e := pv.Interface().(Message) + + var m map[int32]Extension + var mu sync.Locker + if em, ok := e.(extensionsBytes); ok { + eb := em.GetExtensions() + var err error + m, err = BytesToExtensionsMap(*eb) + if err != nil { + return err + } + mu = notLocker{} + } else if _, ok := e.(extendableProto); ok { + ep, _ := extendable(e) + m, mu = ep.extensionsRead() + if m == nil { + return nil + } + } + + // Order the extensions by ID. + // This isn't strictly necessary, but it will give us + // canonical output, which will also make testing easier. + + mu.Lock() + ids := make([]int32, 0, len(m)) + for id := range m { + ids = append(ids, id) + } + sort.Sort(int32Slice(ids)) + mu.Unlock() + + for _, extNum := range ids { + ext := m[extNum] + var desc *ExtensionDesc + if emap != nil { + desc = emap[extNum] + } + if desc == nil { + // Unknown extension. + if err := writeUnknownStruct(w, ext.enc); err != nil { + return err + } + continue + } + + pb, err := GetExtension(e, desc) + if err != nil { + return fmt.Errorf("failed getting extension: %v", err) + } + + // Repeated extensions will appear as a slice. + if !desc.repeated() { + if err := tm.writeExtension(w, desc.Name, pb); err != nil { + return err + } + } else { + v := reflect.ValueOf(pb) + for i := 0; i < v.Len(); i++ { + if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { + return err + } + } + } + } + return nil +} + +func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { + if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + return nil +} + +func (w *textWriter) writeIndent() { + if !w.complete { + return + } + remain := w.ind * 2 + for remain > 0 { + n := remain + if n > len(spaces) { + n = len(spaces) + } + w.w.Write(spaces[:n]) + remain -= n + } + w.complete = false +} + +// TextMarshaler is a configurable text format marshaler. +type TextMarshaler struct { + Compact bool // use compact text format (one line). + ExpandAny bool // expand google.protobuf.Any messages of known types +} + +// Marshal writes a given protocol buffer in text format. +// The only errors returned are from w. +func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error { + val := reflect.ValueOf(pb) + if pb == nil || val.IsNil() { + w.Write([]byte("")) + return nil + } + var bw *bufio.Writer + ww, ok := w.(writer) + if !ok { + bw = bufio.NewWriter(w) + ww = bw + } + aw := &textWriter{ + w: ww, + complete: true, + compact: tm.Compact, + } + + if etm, ok := pb.(encoding.TextMarshaler); ok { + text, err := etm.MarshalText() + if err != nil { + return err + } + if _, err = aw.Write(text); err != nil { + return err + } + if bw != nil { + return bw.Flush() + } + return nil + } + // Dereference the received pointer so we don't have outer < and >. + v := reflect.Indirect(val) + if err := tm.writeStruct(aw, v); err != nil { + return err + } + if bw != nil { + return bw.Flush() + } + return nil +} + +// Text is the same as Marshal, but returns the string directly. +func (tm *TextMarshaler) Text(pb Message) string { + var buf bytes.Buffer + tm.Marshal(&buf, pb) + return buf.String() +} + +var ( + defaultTextMarshaler = TextMarshaler{} + compactTextMarshaler = TextMarshaler{Compact: true} +) + +// TODO: consider removing some of the Marshal functions below. + +// MarshalText writes a given protocol buffer in text format. +// The only errors returned are from w. +func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) } + +// MarshalTextString is the same as MarshalText, but returns the string directly. +func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) } + +// CompactText writes a given protocol buffer in compact text format (one line). +func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) } + +// CompactTextString is the same as CompactText, but returns the string directly. +func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) } diff --git a/vendor/github.com/gogo/protobuf/proto/text_gogo.go b/vendor/github.com/gogo/protobuf/proto/text_gogo.go new file mode 100644 index 00000000..1d6c6aa0 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/text_gogo.go @@ -0,0 +1,57 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "fmt" + "reflect" +) + +func (tm *TextMarshaler) writeEnum(w *textWriter, v reflect.Value, props *Properties) error { + m, ok := enumStringMaps[props.Enum] + if !ok { + if err := tm.writeAny(w, v, props); err != nil { + return err + } + } + key := int32(0) + if v.Kind() == reflect.Ptr { + key = int32(v.Elem().Int()) + } else { + key = int32(v.Int()) + } + s, ok := m[key] + if !ok { + if err := tm.writeAny(w, v, props); err != nil { + return err + } + } + _, err := fmt.Fprint(w, s) + return err +} diff --git a/vendor/github.com/gogo/protobuf/proto/text_parser.go b/vendor/github.com/gogo/protobuf/proto/text_parser.go new file mode 100644 index 00000000..f85c0cc8 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/text_parser.go @@ -0,0 +1,1018 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +// Functions for parsing the Text protocol buffer format. +// TODO: message sets. + +import ( + "encoding" + "errors" + "fmt" + "reflect" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +// Error string emitted when deserializing Any and fields are already set +const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set" + +type ParseError struct { + Message string + Line int // 1-based line number + Offset int // 0-based byte offset from start of input +} + +func (p *ParseError) Error() string { + if p.Line == 1 { + // show offset only for first line + return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) + } + return fmt.Sprintf("line %d: %v", p.Line, p.Message) +} + +type token struct { + value string + err *ParseError + line int // line number + offset int // byte number from start of input, not start of line + unquoted string // the unquoted version of value, if it was a quoted string +} + +func (t *token) String() string { + if t.err == nil { + return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) + } + return fmt.Sprintf("parse error: %v", t.err) +} + +type textParser struct { + s string // remaining input + done bool // whether the parsing is finished (success or error) + backed bool // whether back() was called + offset, line int + cur token +} + +func newTextParser(s string) *textParser { + p := new(textParser) + p.s = s + p.line = 1 + p.cur.line = 1 + return p +} + +func (p *textParser) errorf(format string, a ...interface{}) *ParseError { + pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} + p.cur.err = pe + p.done = true + return pe +} + +// Numbers and identifiers are matched by [-+._A-Za-z0-9] +func isIdentOrNumberChar(c byte) bool { + switch { + case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': + return true + case '0' <= c && c <= '9': + return true + } + switch c { + case '-', '+', '.', '_': + return true + } + return false +} + +func isWhitespace(c byte) bool { + switch c { + case ' ', '\t', '\n', '\r': + return true + } + return false +} + +func isQuote(c byte) bool { + switch c { + case '"', '\'': + return true + } + return false +} + +func (p *textParser) skipWhitespace() { + i := 0 + for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { + if p.s[i] == '#' { + // comment; skip to end of line or input + for i < len(p.s) && p.s[i] != '\n' { + i++ + } + if i == len(p.s) { + break + } + } + if p.s[i] == '\n' { + p.line++ + } + i++ + } + p.offset += i + p.s = p.s[i:len(p.s)] + if len(p.s) == 0 { + p.done = true + } +} + +func (p *textParser) advance() { + // Skip whitespace + p.skipWhitespace() + if p.done { + return + } + + // Start of non-whitespace + p.cur.err = nil + p.cur.offset, p.cur.line = p.offset, p.line + p.cur.unquoted = "" + switch p.s[0] { + case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': + // Single symbol + p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] + case '"', '\'': + // Quoted string + i := 1 + for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { + if p.s[i] == '\\' && i+1 < len(p.s) { + // skip escaped char + i++ + } + i++ + } + if i >= len(p.s) || p.s[i] != p.s[0] { + p.errorf("unmatched quote") + return + } + unq, err := unquoteC(p.s[1:i], rune(p.s[0])) + if err != nil { + p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) + return + } + p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] + p.cur.unquoted = unq + default: + i := 0 + for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { + i++ + } + if i == 0 { + p.errorf("unexpected byte %#x", p.s[0]) + return + } + p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] + } + p.offset += len(p.cur.value) +} + +var ( + errBadUTF8 = errors.New("proto: bad UTF-8") +) + +func unquoteC(s string, quote rune) (string, error) { + // This is based on C++'s tokenizer.cc. + // Despite its name, this is *not* parsing C syntax. + // For instance, "\0" is an invalid quoted string. + + // Avoid allocation in trivial cases. + simple := true + for _, r := range s { + if r == '\\' || r == quote { + simple = false + break + } + } + if simple { + return s, nil + } + + buf := make([]byte, 0, 3*len(s)/2) + for len(s) > 0 { + r, n := utf8.DecodeRuneInString(s) + if r == utf8.RuneError && n == 1 { + return "", errBadUTF8 + } + s = s[n:] + if r != '\\' { + if r < utf8.RuneSelf { + buf = append(buf, byte(r)) + } else { + buf = append(buf, string(r)...) + } + continue + } + + ch, tail, err := unescape(s) + if err != nil { + return "", err + } + buf = append(buf, ch...) + s = tail + } + return string(buf), nil +} + +func unescape(s string) (ch string, tail string, err error) { + r, n := utf8.DecodeRuneInString(s) + if r == utf8.RuneError && n == 1 { + return "", "", errBadUTF8 + } + s = s[n:] + switch r { + case 'a': + return "\a", s, nil + case 'b': + return "\b", s, nil + case 'f': + return "\f", s, nil + case 'n': + return "\n", s, nil + case 'r': + return "\r", s, nil + case 't': + return "\t", s, nil + case 'v': + return "\v", s, nil + case '?': + return "?", s, nil // trigraph workaround + case '\'', '"', '\\': + return string(r), s, nil + case '0', '1', '2', '3', '4', '5', '6', '7': + if len(s) < 2 { + return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) + } + ss := string(r) + s[:2] + s = s[2:] + i, err := strconv.ParseUint(ss, 8, 8) + if err != nil { + return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss) + } + return string([]byte{byte(i)}), s, nil + case 'x', 'X', 'u', 'U': + var n int + switch r { + case 'x', 'X': + n = 2 + case 'u': + n = 4 + case 'U': + n = 8 + } + if len(s) < n { + return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n) + } + ss := s[:n] + s = s[n:] + i, err := strconv.ParseUint(ss, 16, 64) + if err != nil { + return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss) + } + if r == 'x' || r == 'X' { + return string([]byte{byte(i)}), s, nil + } + if i > utf8.MaxRune { + return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss) + } + return string(rune(i)), s, nil + } + return "", "", fmt.Errorf(`unknown escape \%c`, r) +} + +// Back off the parser by one token. Can only be done between calls to next(). +// It makes the next advance() a no-op. +func (p *textParser) back() { p.backed = true } + +// Advances the parser and returns the new current token. +func (p *textParser) next() *token { + if p.backed || p.done { + p.backed = false + return &p.cur + } + p.advance() + if p.done { + p.cur.value = "" + } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { + // Look for multiple quoted strings separated by whitespace, + // and concatenate them. + cat := p.cur + for { + p.skipWhitespace() + if p.done || !isQuote(p.s[0]) { + break + } + p.advance() + if p.cur.err != nil { + return &p.cur + } + cat.value += " " + p.cur.value + cat.unquoted += p.cur.unquoted + } + p.done = false // parser may have seen EOF, but we want to return cat + p.cur = cat + } + return &p.cur +} + +func (p *textParser) consumeToken(s string) error { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value != s { + p.back() + return p.errorf("expected %q, found %q", s, tok.value) + } + return nil +} + +// Return a RequiredNotSetError indicating which required field was not set. +func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError { + st := sv.Type() + sprops := GetProperties(st) + for i := 0; i < st.NumField(); i++ { + if !isNil(sv.Field(i)) { + continue + } + + props := sprops.Prop[i] + if props.Required { + return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)} + } + } + return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen +} + +// Returns the index in the struct for the named field, as well as the parsed tag properties. +func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) { + i, ok := sprops.decoderOrigNames[name] + if ok { + return i, sprops.Prop[i], true + } + return -1, nil, false +} + +// Consume a ':' from the input stream (if the next token is a colon), +// returning an error if a colon is needed but not present. +func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value != ":" { + // Colon is optional when the field is a group or message. + needColon := true + switch props.Wire { + case "group": + needColon = false + case "bytes": + // A "bytes" field is either a message, a string, or a repeated field; + // those three become *T, *string and []T respectively, so we can check for + // this field being a pointer to a non-string. + if typ.Kind() == reflect.Ptr { + // *T or *string + if typ.Elem().Kind() == reflect.String { + break + } + } else if typ.Kind() == reflect.Slice { + // []T or []*T + if typ.Elem().Kind() != reflect.Ptr { + break + } + } else if typ.Kind() == reflect.String { + // The proto3 exception is for a string field, + // which requires a colon. + break + } + needColon = false + } + if needColon { + return p.errorf("expected ':', found %q", tok.value) + } + p.back() + } + return nil +} + +func (p *textParser) readStruct(sv reflect.Value, terminator string) error { + st := sv.Type() + sprops := GetProperties(st) + reqCount := sprops.reqCount + var reqFieldErr error + fieldSet := make(map[string]bool) + // A struct is a sequence of "name: value", terminated by one of + // '>' or '}', or the end of the input. A name may also be + // "[extension]" or "[type/url]". + // + // The whole struct can also be an expanded Any message, like: + // [type/url] < ... struct contents ... > + for { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value == terminator { + break + } + if tok.value == "[" { + // Looks like an extension or an Any. + // + // TODO: Check whether we need to handle + // namespace rooted names (e.g. ".something.Foo"). + extName, err := p.consumeExtName() + if err != nil { + return err + } + + if s := strings.LastIndex(extName, "/"); s >= 0 { + // If it contains a slash, it's an Any type URL. + messageName := extName[s+1:] + mt := MessageType(messageName) + if mt == nil { + return p.errorf("unrecognized message %q in google.protobuf.Any", messageName) + } + tok = p.next() + if tok.err != nil { + return tok.err + } + // consume an optional colon + if tok.value == ":" { + tok = p.next() + if tok.err != nil { + return tok.err + } + } + var terminator string + switch tok.value { + case "<": + terminator = ">" + case "{": + terminator = "}" + default: + return p.errorf("expected '{' or '<', found %q", tok.value) + } + v := reflect.New(mt.Elem()) + if pe := p.readStruct(v.Elem(), terminator); pe != nil { + return pe + } + b, err := Marshal(v.Interface().(Message)) + if err != nil { + return p.errorf("failed to marshal message of type %q: %v", messageName, err) + } + if fieldSet["type_url"] { + return p.errorf(anyRepeatedlyUnpacked, "type_url") + } + if fieldSet["value"] { + return p.errorf(anyRepeatedlyUnpacked, "value") + } + sv.FieldByName("TypeUrl").SetString(extName) + sv.FieldByName("Value").SetBytes(b) + fieldSet["type_url"] = true + fieldSet["value"] = true + continue + } + + var desc *ExtensionDesc + // This could be faster, but it's functional. + // TODO: Do something smarter than a linear scan. + for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { + if d.Name == extName { + desc = d + break + } + } + if desc == nil { + return p.errorf("unrecognized extension %q", extName) + } + + props := &Properties{} + props.Parse(desc.Tag) + + typ := reflect.TypeOf(desc.ExtensionType) + if err := p.checkForColon(props, typ); err != nil { + return err + } + + rep := desc.repeated() + + // Read the extension structure, and set it in + // the value we're constructing. + var ext reflect.Value + if !rep { + ext = reflect.New(typ).Elem() + } else { + ext = reflect.New(typ.Elem()).Elem() + } + if err := p.readAny(ext, props); err != nil { + if _, ok := err.(*RequiredNotSetError); !ok { + return err + } + reqFieldErr = err + } + ep := sv.Addr().Interface().(Message) + if !rep { + SetExtension(ep, desc, ext.Interface()) + } else { + old, err := GetExtension(ep, desc) + var sl reflect.Value + if err == nil { + sl = reflect.ValueOf(old) // existing slice + } else { + sl = reflect.MakeSlice(typ, 0, 1) + } + sl = reflect.Append(sl, ext) + SetExtension(ep, desc, sl.Interface()) + } + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + continue + } + + // This is a normal, non-extension field. + name := tok.value + var dst reflect.Value + fi, props, ok := structFieldByName(sprops, name) + if ok { + dst = sv.Field(fi) + } else if oop, ok := sprops.OneofTypes[name]; ok { + // It is a oneof. + props = oop.Prop + nv := reflect.New(oop.Type.Elem()) + dst = nv.Elem().Field(0) + field := sv.Field(oop.Field) + if !field.IsNil() { + return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name) + } + field.Set(nv) + } + if !dst.IsValid() { + return p.errorf("unknown field name %q in %v", name, st) + } + + if dst.Kind() == reflect.Map { + // Consume any colon. + if err := p.checkForColon(props, dst.Type()); err != nil { + return err + } + + // Construct the map if it doesn't already exist. + if dst.IsNil() { + dst.Set(reflect.MakeMap(dst.Type())) + } + key := reflect.New(dst.Type().Key()).Elem() + val := reflect.New(dst.Type().Elem()).Elem() + + // The map entry should be this sequence of tokens: + // < key : KEY value : VALUE > + // However, implementations may omit key or value, and technically + // we should support them in any order. See b/28924776 for a time + // this went wrong. + + tok := p.next() + var terminator string + switch tok.value { + case "<": + terminator = ">" + case "{": + terminator = "}" + default: + return p.errorf("expected '{' or '<', found %q", tok.value) + } + for { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value == terminator { + break + } + switch tok.value { + case "key": + if err := p.consumeToken(":"); err != nil { + return err + } + if err := p.readAny(key, props.MapKeyProp); err != nil { + return err + } + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + case "value": + if err := p.checkForColon(props.MapValProp, dst.Type().Elem()); err != nil { + return err + } + if err := p.readAny(val, props.MapValProp); err != nil { + return err + } + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + default: + p.back() + return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) + } + } + + dst.SetMapIndex(key, val) + continue + } + + // Check that it's not already set if it's not a repeated field. + if !props.Repeated && fieldSet[name] { + return p.errorf("non-repeated field %q was repeated", name) + } + + if err := p.checkForColon(props, dst.Type()); err != nil { + return err + } + + // Parse into the field. + fieldSet[name] = true + if err := p.readAny(dst, props); err != nil { + if _, ok := err.(*RequiredNotSetError); !ok { + return err + } + reqFieldErr = err + } + if props.Required { + reqCount-- + } + + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + + } + + if reqCount > 0 { + return p.missingRequiredFieldError(sv) + } + return reqFieldErr +} + +// consumeExtName consumes extension name or expanded Any type URL and the +// following ']'. It returns the name or URL consumed. +func (p *textParser) consumeExtName() (string, error) { + tok := p.next() + if tok.err != nil { + return "", tok.err + } + + // If extension name or type url is quoted, it's a single token. + if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { + name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) + if err != nil { + return "", err + } + return name, p.consumeToken("]") + } + + // Consume everything up to "]" + var parts []string + for tok.value != "]" { + parts = append(parts, tok.value) + tok = p.next() + if tok.err != nil { + return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) + } + if p.done && tok.value != "]" { + return "", p.errorf("unclosed type_url or extension name") + } + } + return strings.Join(parts, ""), nil +} + +// consumeOptionalSeparator consumes an optional semicolon or comma. +// It is used in readStruct to provide backward compatibility. +func (p *textParser) consumeOptionalSeparator() error { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value != ";" && tok.value != "," { + p.back() + } + return nil +} + +func (p *textParser) readAny(v reflect.Value, props *Properties) error { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value == "" { + return p.errorf("unexpected EOF") + } + if len(props.CustomType) > 0 { + if props.Repeated { + t := reflect.TypeOf(v.Interface()) + if t.Kind() == reflect.Slice { + tc := reflect.TypeOf(new(Marshaler)) + ok := t.Elem().Implements(tc.Elem()) + if ok { + fv := v + flen := fv.Len() + if flen == fv.Cap() { + nav := reflect.MakeSlice(v.Type(), flen, 2*flen+1) + reflect.Copy(nav, fv) + fv.Set(nav) + } + fv.SetLen(flen + 1) + + // Read one. + p.back() + return p.readAny(fv.Index(flen), props) + } + } + } + if reflect.TypeOf(v.Interface()).Kind() == reflect.Ptr { + custom := reflect.New(props.ctype.Elem()).Interface().(Unmarshaler) + err := custom.Unmarshal([]byte(tok.unquoted)) + if err != nil { + return p.errorf("%v %v: %v", err, v.Type(), tok.value) + } + v.Set(reflect.ValueOf(custom)) + } else { + custom := reflect.New(reflect.TypeOf(v.Interface())).Interface().(Unmarshaler) + err := custom.Unmarshal([]byte(tok.unquoted)) + if err != nil { + return p.errorf("%v %v: %v", err, v.Type(), tok.value) + } + v.Set(reflect.Indirect(reflect.ValueOf(custom))) + } + return nil + } + if props.StdTime { + fv := v + p.back() + props.StdTime = false + tproto := ×tamp{} + err := p.readAny(reflect.ValueOf(tproto).Elem(), props) + props.StdTime = true + if err != nil { + return err + } + tim, err := timestampFromProto(tproto) + if err != nil { + return err + } + if props.Repeated { + t := reflect.TypeOf(v.Interface()) + if t.Kind() == reflect.Slice { + if t.Elem().Kind() == reflect.Ptr { + ts := fv.Interface().([]*time.Time) + ts = append(ts, &tim) + fv.Set(reflect.ValueOf(ts)) + return nil + } else { + ts := fv.Interface().([]time.Time) + ts = append(ts, tim) + fv.Set(reflect.ValueOf(ts)) + return nil + } + } + } + if reflect.TypeOf(v.Interface()).Kind() == reflect.Ptr { + v.Set(reflect.ValueOf(&tim)) + } else { + v.Set(reflect.Indirect(reflect.ValueOf(&tim))) + } + return nil + } + if props.StdDuration { + fv := v + p.back() + props.StdDuration = false + dproto := &duration{} + err := p.readAny(reflect.ValueOf(dproto).Elem(), props) + props.StdDuration = true + if err != nil { + return err + } + dur, err := durationFromProto(dproto) + if err != nil { + return err + } + if props.Repeated { + t := reflect.TypeOf(v.Interface()) + if t.Kind() == reflect.Slice { + if t.Elem().Kind() == reflect.Ptr { + ds := fv.Interface().([]*time.Duration) + ds = append(ds, &dur) + fv.Set(reflect.ValueOf(ds)) + return nil + } else { + ds := fv.Interface().([]time.Duration) + ds = append(ds, dur) + fv.Set(reflect.ValueOf(ds)) + return nil + } + } + } + if reflect.TypeOf(v.Interface()).Kind() == reflect.Ptr { + v.Set(reflect.ValueOf(&dur)) + } else { + v.Set(reflect.Indirect(reflect.ValueOf(&dur))) + } + return nil + } + switch fv := v; fv.Kind() { + case reflect.Slice: + at := v.Type() + if at.Elem().Kind() == reflect.Uint8 { + // Special case for []byte + if tok.value[0] != '"' && tok.value[0] != '\'' { + // Deliberately written out here, as the error after + // this switch statement would write "invalid []byte: ...", + // which is not as user-friendly. + return p.errorf("invalid string: %v", tok.value) + } + bytes := []byte(tok.unquoted) + fv.Set(reflect.ValueOf(bytes)) + return nil + } + // Repeated field. + if tok.value == "[" { + // Repeated field with list notation, like [1,2,3]. + for { + fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) + err := p.readAny(fv.Index(fv.Len()-1), props) + if err != nil { + return err + } + ntok := p.next() + if ntok.err != nil { + return ntok.err + } + if ntok.value == "]" { + break + } + if ntok.value != "," { + return p.errorf("Expected ']' or ',' found %q", ntok.value) + } + } + return nil + } + // One value of the repeated field. + p.back() + fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) + return p.readAny(fv.Index(fv.Len()-1), props) + case reflect.Bool: + // true/1/t/True or false/f/0/False. + switch tok.value { + case "true", "1", "t", "True": + fv.SetBool(true) + return nil + case "false", "0", "f", "False": + fv.SetBool(false) + return nil + } + case reflect.Float32, reflect.Float64: + v := tok.value + // Ignore 'f' for compatibility with output generated by C++, but don't + // remove 'f' when the value is "-inf" or "inf". + if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { + v = v[:len(v)-1] + } + if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { + fv.SetFloat(f) + return nil + } + case reflect.Int8: + if x, err := strconv.ParseInt(tok.value, 0, 8); err == nil { + fv.SetInt(x) + return nil + } + case reflect.Int16: + if x, err := strconv.ParseInt(tok.value, 0, 16); err == nil { + fv.SetInt(x) + return nil + } + case reflect.Int32: + if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { + fv.SetInt(x) + return nil + } + + if len(props.Enum) == 0 { + break + } + m, ok := enumValueMaps[props.Enum] + if !ok { + break + } + x, ok := m[tok.value] + if !ok { + break + } + fv.SetInt(int64(x)) + return nil + case reflect.Int64: + if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { + fv.SetInt(x) + return nil + } + + case reflect.Ptr: + // A basic field (indirected through pointer), or a repeated message/group + p.back() + fv.Set(reflect.New(fv.Type().Elem())) + return p.readAny(fv.Elem(), props) + case reflect.String: + if tok.value[0] == '"' || tok.value[0] == '\'' { + fv.SetString(tok.unquoted) + return nil + } + case reflect.Struct: + var terminator string + switch tok.value { + case "{": + terminator = "}" + case "<": + terminator = ">" + default: + return p.errorf("expected '{' or '<', found %q", tok.value) + } + // TODO: Handle nested messages which implement encoding.TextUnmarshaler. + return p.readStruct(fv, terminator) + case reflect.Uint8: + if x, err := strconv.ParseUint(tok.value, 0, 8); err == nil { + fv.SetUint(x) + return nil + } + case reflect.Uint16: + if x, err := strconv.ParseUint(tok.value, 0, 16); err == nil { + fv.SetUint(x) + return nil + } + case reflect.Uint32: + if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { + fv.SetUint(uint64(x)) + return nil + } + case reflect.Uint64: + if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { + fv.SetUint(x) + return nil + } + } + return p.errorf("invalid %v: %v", v.Type(), tok.value) +} + +// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb +// before starting to unmarshal, so any existing data in pb is always removed. +// If a required field is not set and no other error occurs, +// UnmarshalText returns *RequiredNotSetError. +func UnmarshalText(s string, pb Message) error { + if um, ok := pb.(encoding.TextUnmarshaler); ok { + return um.UnmarshalText([]byte(s)) + } + pb.Reset() + v := reflect.ValueOf(pb) + return newTextParser(s).readStruct(v.Elem(), "") +} diff --git a/vendor/github.com/gogo/protobuf/proto/timestamp.go b/vendor/github.com/gogo/protobuf/proto/timestamp.go new file mode 100644 index 00000000..9324f654 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/timestamp.go @@ -0,0 +1,113 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2016 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +// This file implements operations on google.protobuf.Timestamp. + +import ( + "errors" + "fmt" + "time" +) + +const ( + // Seconds field of the earliest valid Timestamp. + // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). + minValidSeconds = -62135596800 + // Seconds field just after the latest valid Timestamp. + // This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). + maxValidSeconds = 253402300800 +) + +// validateTimestamp determines whether a Timestamp is valid. +// A valid timestamp represents a time in the range +// [0001-01-01, 10000-01-01) and has a Nanos field +// in the range [0, 1e9). +// +// If the Timestamp is valid, validateTimestamp returns nil. +// Otherwise, it returns an error that describes +// the problem. +// +// Every valid Timestamp can be represented by a time.Time, but the converse is not true. +func validateTimestamp(ts *timestamp) error { + if ts == nil { + return errors.New("timestamp: nil Timestamp") + } + if ts.Seconds < minValidSeconds { + return fmt.Errorf("timestamp: %#v before 0001-01-01", ts) + } + if ts.Seconds >= maxValidSeconds { + return fmt.Errorf("timestamp: %#v after 10000-01-01", ts) + } + if ts.Nanos < 0 || ts.Nanos >= 1e9 { + return fmt.Errorf("timestamp: %#v: nanos not in range [0, 1e9)", ts) + } + return nil +} + +// TimestampFromProto converts a google.protobuf.Timestamp proto to a time.Time. +// It returns an error if the argument is invalid. +// +// Unlike most Go functions, if Timestamp returns an error, the first return value +// is not the zero time.Time. Instead, it is the value obtained from the +// time.Unix function when passed the contents of the Timestamp, in the UTC +// locale. This may or may not be a meaningful time; many invalid Timestamps +// do map to valid time.Times. +// +// A nil Timestamp returns an error. The first return value in that case is +// undefined. +func timestampFromProto(ts *timestamp) (time.Time, error) { + // Don't return the zero value on error, because corresponds to a valid + // timestamp. Instead return whatever time.Unix gives us. + var t time.Time + if ts == nil { + t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp + } else { + t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC() + } + return t, validateTimestamp(ts) +} + +// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto. +// It returns an error if the resulting Timestamp is invalid. +func timestampProto(t time.Time) (*timestamp, error) { + seconds := t.Unix() + nanos := int32(t.Sub(time.Unix(seconds, 0))) + ts := ×tamp{ + Seconds: seconds, + Nanos: nanos, + } + if err := validateTimestamp(ts); err != nil { + return nil, err + } + return ts, nil +} diff --git a/vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go b/vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go new file mode 100644 index 00000000..38439fa9 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go @@ -0,0 +1,49 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2016, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "reflect" + "time" +) + +var timeType = reflect.TypeOf((*time.Time)(nil)).Elem() + +type timestamp struct { + Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` + Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` +} + +func (m *timestamp) Reset() { *m = timestamp{} } +func (*timestamp) ProtoMessage() {} +func (*timestamp) String() string { return "timestamp" } + +func init() { + RegisterType((*timestamp)(nil), "gogo.protobuf.proto.timestamp") +} diff --git a/vendor/github.com/gogo/protobuf/proto/wrappers.go b/vendor/github.com/gogo/protobuf/proto/wrappers.go new file mode 100644 index 00000000..b175d1b6 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/wrappers.go @@ -0,0 +1,1888 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2018, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "io" + "reflect" +) + +func makeStdDoubleValueMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + t := ptr.asPointerTo(u.typ).Interface().(*float64) + v := &float64Value{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + t := ptr.asPointerTo(u.typ).Interface().(*float64) + v := &float64Value{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdDoubleValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*float64) + v := &float64Value{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*float64) + v := &float64Value{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdDoubleValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(float64) + v := &float64Value{t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(float64) + v := &float64Value{t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdDoubleValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*float64) + v := &float64Value{*t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*float64) + v := &float64Value{*t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdDoubleValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &float64Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(sub.typ).Elem() + s.Set(reflect.ValueOf(m.Value)) + return b[x:], nil + } +} + +func makeStdDoubleValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &float64Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.ValueOf(&m.Value)) + return b[x:], nil + } +} + +func makeStdDoubleValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &float64Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(reflect.PtrTo(sub.typ)) + newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdDoubleValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &float64Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(sub.typ) + newSlice := reflect.Append(slice, reflect.ValueOf(m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdFloatValueMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + t := ptr.asPointerTo(u.typ).Interface().(*float32) + v := &float32Value{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + t := ptr.asPointerTo(u.typ).Interface().(*float32) + v := &float32Value{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdFloatValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*float32) + v := &float32Value{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*float32) + v := &float32Value{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdFloatValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(float32) + v := &float32Value{t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(float32) + v := &float32Value{t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdFloatValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*float32) + v := &float32Value{*t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*float32) + v := &float32Value{*t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdFloatValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &float32Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(sub.typ).Elem() + s.Set(reflect.ValueOf(m.Value)) + return b[x:], nil + } +} + +func makeStdFloatValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &float32Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.ValueOf(&m.Value)) + return b[x:], nil + } +} + +func makeStdFloatValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &float32Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(reflect.PtrTo(sub.typ)) + newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdFloatValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &float32Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(sub.typ) + newSlice := reflect.Append(slice, reflect.ValueOf(m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdInt64ValueMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + t := ptr.asPointerTo(u.typ).Interface().(*int64) + v := &int64Value{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + t := ptr.asPointerTo(u.typ).Interface().(*int64) + v := &int64Value{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdInt64ValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*int64) + v := &int64Value{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*int64) + v := &int64Value{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdInt64ValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(int64) + v := &int64Value{t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(int64) + v := &int64Value{t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdInt64ValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*int64) + v := &int64Value{*t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*int64) + v := &int64Value{*t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdInt64ValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &int64Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(sub.typ).Elem() + s.Set(reflect.ValueOf(m.Value)) + return b[x:], nil + } +} + +func makeStdInt64ValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &int64Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.ValueOf(&m.Value)) + return b[x:], nil + } +} + +func makeStdInt64ValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &int64Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(reflect.PtrTo(sub.typ)) + newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdInt64ValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &int64Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(sub.typ) + newSlice := reflect.Append(slice, reflect.ValueOf(m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdUInt64ValueMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + t := ptr.asPointerTo(u.typ).Interface().(*uint64) + v := &uint64Value{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + t := ptr.asPointerTo(u.typ).Interface().(*uint64) + v := &uint64Value{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdUInt64ValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*uint64) + v := &uint64Value{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*uint64) + v := &uint64Value{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdUInt64ValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(uint64) + v := &uint64Value{t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(uint64) + v := &uint64Value{t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdUInt64ValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*uint64) + v := &uint64Value{*t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*uint64) + v := &uint64Value{*t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdUInt64ValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &uint64Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(sub.typ).Elem() + s.Set(reflect.ValueOf(m.Value)) + return b[x:], nil + } +} + +func makeStdUInt64ValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &uint64Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.ValueOf(&m.Value)) + return b[x:], nil + } +} + +func makeStdUInt64ValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &uint64Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(reflect.PtrTo(sub.typ)) + newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdUInt64ValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &uint64Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(sub.typ) + newSlice := reflect.Append(slice, reflect.ValueOf(m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdInt32ValueMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + t := ptr.asPointerTo(u.typ).Interface().(*int32) + v := &int32Value{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + t := ptr.asPointerTo(u.typ).Interface().(*int32) + v := &int32Value{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdInt32ValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*int32) + v := &int32Value{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*int32) + v := &int32Value{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdInt32ValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(int32) + v := &int32Value{t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(int32) + v := &int32Value{t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdInt32ValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*int32) + v := &int32Value{*t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*int32) + v := &int32Value{*t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdInt32ValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &int32Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(sub.typ).Elem() + s.Set(reflect.ValueOf(m.Value)) + return b[x:], nil + } +} + +func makeStdInt32ValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &int32Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.ValueOf(&m.Value)) + return b[x:], nil + } +} + +func makeStdInt32ValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &int32Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(reflect.PtrTo(sub.typ)) + newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdInt32ValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &int32Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(sub.typ) + newSlice := reflect.Append(slice, reflect.ValueOf(m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdUInt32ValueMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + t := ptr.asPointerTo(u.typ).Interface().(*uint32) + v := &uint32Value{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + t := ptr.asPointerTo(u.typ).Interface().(*uint32) + v := &uint32Value{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdUInt32ValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*uint32) + v := &uint32Value{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*uint32) + v := &uint32Value{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdUInt32ValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(uint32) + v := &uint32Value{t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(uint32) + v := &uint32Value{t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdUInt32ValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*uint32) + v := &uint32Value{*t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*uint32) + v := &uint32Value{*t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdUInt32ValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &uint32Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(sub.typ).Elem() + s.Set(reflect.ValueOf(m.Value)) + return b[x:], nil + } +} + +func makeStdUInt32ValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &uint32Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.ValueOf(&m.Value)) + return b[x:], nil + } +} + +func makeStdUInt32ValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &uint32Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(reflect.PtrTo(sub.typ)) + newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdUInt32ValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &uint32Value{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(sub.typ) + newSlice := reflect.Append(slice, reflect.ValueOf(m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdBoolValueMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + t := ptr.asPointerTo(u.typ).Interface().(*bool) + v := &boolValue{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + t := ptr.asPointerTo(u.typ).Interface().(*bool) + v := &boolValue{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdBoolValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*bool) + v := &boolValue{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*bool) + v := &boolValue{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdBoolValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(bool) + v := &boolValue{t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(bool) + v := &boolValue{t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdBoolValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*bool) + v := &boolValue{*t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*bool) + v := &boolValue{*t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdBoolValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &boolValue{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(sub.typ).Elem() + s.Set(reflect.ValueOf(m.Value)) + return b[x:], nil + } +} + +func makeStdBoolValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &boolValue{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.ValueOf(&m.Value)) + return b[x:], nil + } +} + +func makeStdBoolValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &boolValue{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(reflect.PtrTo(sub.typ)) + newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdBoolValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &boolValue{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(sub.typ) + newSlice := reflect.Append(slice, reflect.ValueOf(m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdStringValueMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + t := ptr.asPointerTo(u.typ).Interface().(*string) + v := &stringValue{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + t := ptr.asPointerTo(u.typ).Interface().(*string) + v := &stringValue{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdStringValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*string) + v := &stringValue{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*string) + v := &stringValue{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdStringValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(string) + v := &stringValue{t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(string) + v := &stringValue{t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdStringValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*string) + v := &stringValue{*t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*string) + v := &stringValue{*t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdStringValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &stringValue{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(sub.typ).Elem() + s.Set(reflect.ValueOf(m.Value)) + return b[x:], nil + } +} + +func makeStdStringValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &stringValue{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.ValueOf(&m.Value)) + return b[x:], nil + } +} + +func makeStdStringValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &stringValue{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(reflect.PtrTo(sub.typ)) + newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdStringValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &stringValue{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(sub.typ) + newSlice := reflect.Append(slice, reflect.ValueOf(m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdBytesValueMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + t := ptr.asPointerTo(u.typ).Interface().(*[]byte) + v := &bytesValue{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + t := ptr.asPointerTo(u.typ).Interface().(*[]byte) + v := &bytesValue{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdBytesValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*[]byte) + v := &bytesValue{*t} + siz := Size(v) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*[]byte) + v := &bytesValue{*t} + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeStdBytesValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().([]byte) + v := &bytesValue{t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().([]byte) + v := &bytesValue{t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdBytesValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*[]byte) + v := &bytesValue{*t} + siz := Size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*[]byte) + v := &bytesValue{*t} + siz := Size(v) + buf, err := Marshal(v) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeStdBytesValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &bytesValue{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(sub.typ).Elem() + s.Set(reflect.ValueOf(m.Value)) + return b[x:], nil + } +} + +func makeStdBytesValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &bytesValue{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.ValueOf(&m.Value)) + return b[x:], nil + } +} + +func makeStdBytesValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &bytesValue{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(reflect.PtrTo(sub.typ)) + newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeStdBytesValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &bytesValue{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + slice := f.getSlice(sub.typ) + newSlice := reflect.Append(slice, reflect.ValueOf(m.Value)) + slice.Set(newSlice) + return b[x:], nil + } +} diff --git a/vendor/github.com/gogo/protobuf/proto/wrappers_gogo.go b/vendor/github.com/gogo/protobuf/proto/wrappers_gogo.go new file mode 100644 index 00000000..c1cf7bf8 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/wrappers_gogo.go @@ -0,0 +1,113 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2018, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +type float64Value struct { + Value float64 `protobuf:"fixed64,1,opt,name=value,proto3" json:"value,omitempty"` +} + +func (m *float64Value) Reset() { *m = float64Value{} } +func (*float64Value) ProtoMessage() {} +func (*float64Value) String() string { return "float64" } + +type float32Value struct { + Value float32 `protobuf:"fixed32,1,opt,name=value,proto3" json:"value,omitempty"` +} + +func (m *float32Value) Reset() { *m = float32Value{} } +func (*float32Value) ProtoMessage() {} +func (*float32Value) String() string { return "float32" } + +type int64Value struct { + Value int64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` +} + +func (m *int64Value) Reset() { *m = int64Value{} } +func (*int64Value) ProtoMessage() {} +func (*int64Value) String() string { return "int64" } + +type uint64Value struct { + Value uint64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` +} + +func (m *uint64Value) Reset() { *m = uint64Value{} } +func (*uint64Value) ProtoMessage() {} +func (*uint64Value) String() string { return "uint64" } + +type int32Value struct { + Value int32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` +} + +func (m *int32Value) Reset() { *m = int32Value{} } +func (*int32Value) ProtoMessage() {} +func (*int32Value) String() string { return "int32" } + +type uint32Value struct { + Value uint32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` +} + +func (m *uint32Value) Reset() { *m = uint32Value{} } +func (*uint32Value) ProtoMessage() {} +func (*uint32Value) String() string { return "uint32" } + +type boolValue struct { + Value bool `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` +} + +func (m *boolValue) Reset() { *m = boolValue{} } +func (*boolValue) ProtoMessage() {} +func (*boolValue) String() string { return "bool" } + +type stringValue struct { + Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` +} + +func (m *stringValue) Reset() { *m = stringValue{} } +func (*stringValue) ProtoMessage() {} +func (*stringValue) String() string { return "string" } + +type bytesValue struct { + Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` +} + +func (m *bytesValue) Reset() { *m = bytesValue{} } +func (*bytesValue) ProtoMessage() {} +func (*bytesValue) String() string { return "[]byte" } + +func init() { + RegisterType((*float64Value)(nil), "gogo.protobuf.proto.DoubleValue") + RegisterType((*float32Value)(nil), "gogo.protobuf.proto.FloatValue") + RegisterType((*int64Value)(nil), "gogo.protobuf.proto.Int64Value") + RegisterType((*uint64Value)(nil), "gogo.protobuf.proto.UInt64Value") + RegisterType((*int32Value)(nil), "gogo.protobuf.proto.Int32Value") + RegisterType((*uint32Value)(nil), "gogo.protobuf.proto.UInt32Value") + RegisterType((*boolValue)(nil), "gogo.protobuf.proto.BoolValue") + RegisterType((*stringValue)(nil), "gogo.protobuf.proto.StringValue") + RegisterType((*bytesValue)(nil), "gogo.protobuf.proto.BytesValue") +} diff --git a/vendor/github.com/google/shlex/COPYING b/vendor/github.com/google/shlex/COPYING new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/github.com/google/shlex/COPYING @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/google/shlex/README b/vendor/github.com/google/shlex/README new file mode 100644 index 00000000..c86bcc06 --- /dev/null +++ b/vendor/github.com/google/shlex/README @@ -0,0 +1,2 @@ +go-shlex is a simple lexer for go that supports shell-style quoting, +commenting, and escaping. diff --git a/vendor/github.com/google/shlex/shlex.go b/vendor/github.com/google/shlex/shlex.go new file mode 100644 index 00000000..d98308bc --- /dev/null +++ b/vendor/github.com/google/shlex/shlex.go @@ -0,0 +1,416 @@ +/* +Copyright 2012 Google Inc. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +/* +Package shlex implements a simple lexer which splits input in to tokens using +shell-style rules for quoting and commenting. + +The basic use case uses the default ASCII lexer to split a string into sub-strings: + + shlex.Split("one \"two three\" four") -> []string{"one", "two three", "four"} + +To process a stream of strings: + + l := NewLexer(os.Stdin) + for ; token, err := l.Next(); err != nil { + // process token + } + +To access the raw token stream (which includes tokens for comments): + + t := NewTokenizer(os.Stdin) + for ; token, err := t.Next(); err != nil { + // process token + } + +*/ +package shlex + +import ( + "bufio" + "fmt" + "io" + "strings" +) + +// TokenType is a top-level token classification: A word, space, comment, unknown. +type TokenType int + +// runeTokenClass is the type of a UTF-8 character classification: A quote, space, escape. +type runeTokenClass int + +// the internal state used by the lexer state machine +type lexerState int + +// Token is a (type, value) pair representing a lexographical token. +type Token struct { + tokenType TokenType + value string +} + +// Equal reports whether tokens a, and b, are equal. +// Two tokens are equal if both their types and values are equal. A nil token can +// never be equal to another token. +func (a *Token) Equal(b *Token) bool { + if a == nil || b == nil { + return false + } + if a.tokenType != b.tokenType { + return false + } + return a.value == b.value +} + +// Named classes of UTF-8 runes +const ( + spaceRunes = " \t\r\n" + escapingQuoteRunes = `"` + nonEscapingQuoteRunes = "'" + escapeRunes = `\` + commentRunes = "#" +) + +// Classes of rune token +const ( + unknownRuneClass runeTokenClass = iota + spaceRuneClass + escapingQuoteRuneClass + nonEscapingQuoteRuneClass + escapeRuneClass + commentRuneClass + eofRuneClass +) + +// Classes of lexographic token +const ( + UnknownToken TokenType = iota + WordToken + SpaceToken + CommentToken +) + +// Lexer state machine states +const ( + startState lexerState = iota // no runes have been seen + inWordState // processing regular runes in a word + escapingState // we have just consumed an escape rune; the next rune is literal + escapingQuotedState // we have just consumed an escape rune within a quoted string + quotingEscapingState // we are within a quoted string that supports escaping ("...") + quotingState // we are within a string that does not support escaping ('...') + commentState // we are within a comment (everything following an unquoted or unescaped # +) + +// tokenClassifier is used for classifying rune characters. +type tokenClassifier map[rune]runeTokenClass + +func (typeMap tokenClassifier) addRuneClass(runes string, tokenType runeTokenClass) { + for _, runeChar := range runes { + typeMap[runeChar] = tokenType + } +} + +// newDefaultClassifier creates a new classifier for ASCII characters. +func newDefaultClassifier() tokenClassifier { + t := tokenClassifier{} + t.addRuneClass(spaceRunes, spaceRuneClass) + t.addRuneClass(escapingQuoteRunes, escapingQuoteRuneClass) + t.addRuneClass(nonEscapingQuoteRunes, nonEscapingQuoteRuneClass) + t.addRuneClass(escapeRunes, escapeRuneClass) + t.addRuneClass(commentRunes, commentRuneClass) + return t +} + +// ClassifyRune classifiees a rune +func (t tokenClassifier) ClassifyRune(runeVal rune) runeTokenClass { + return t[runeVal] +} + +// Lexer turns an input stream into a sequence of tokens. Whitespace and comments are skipped. +type Lexer Tokenizer + +// NewLexer creates a new lexer from an input stream. +func NewLexer(r io.Reader) *Lexer { + + return (*Lexer)(NewTokenizer(r)) +} + +// Next returns the next word, or an error. If there are no more words, +// the error will be io.EOF. +func (l *Lexer) Next() (string, error) { + for { + token, err := (*Tokenizer)(l).Next() + if err != nil { + return "", err + } + switch token.tokenType { + case WordToken: + return token.value, nil + case CommentToken: + // skip comments + default: + return "", fmt.Errorf("Unknown token type: %v", token.tokenType) + } + } +} + +// Tokenizer turns an input stream into a sequence of typed tokens +type Tokenizer struct { + input bufio.Reader + classifier tokenClassifier +} + +// NewTokenizer creates a new tokenizer from an input stream. +func NewTokenizer(r io.Reader) *Tokenizer { + input := bufio.NewReader(r) + classifier := newDefaultClassifier() + return &Tokenizer{ + input: *input, + classifier: classifier} +} + +// scanStream scans the stream for the next token using the internal state machine. +// It will panic if it encounters a rune which it does not know how to handle. +func (t *Tokenizer) scanStream() (*Token, error) { + state := startState + var tokenType TokenType + var value []rune + var nextRune rune + var nextRuneType runeTokenClass + var err error + + for { + nextRune, _, err = t.input.ReadRune() + nextRuneType = t.classifier.ClassifyRune(nextRune) + + if err == io.EOF { + nextRuneType = eofRuneClass + err = nil + } else if err != nil { + return nil, err + } + + switch state { + case startState: // no runes read yet + { + switch nextRuneType { + case eofRuneClass: + { + return nil, io.EOF + } + case spaceRuneClass: + { + } + case escapingQuoteRuneClass: + { + tokenType = WordToken + state = quotingEscapingState + } + case nonEscapingQuoteRuneClass: + { + tokenType = WordToken + state = quotingState + } + case escapeRuneClass: + { + tokenType = WordToken + state = escapingState + } + case commentRuneClass: + { + tokenType = CommentToken + state = commentState + } + default: + { + tokenType = WordToken + value = append(value, nextRune) + state = inWordState + } + } + } + case inWordState: // in a regular word + { + switch nextRuneType { + case eofRuneClass: + { + token := &Token{ + tokenType: tokenType, + value: string(value)} + return token, err + } + case spaceRuneClass: + { + token := &Token{ + tokenType: tokenType, + value: string(value)} + return token, err + } + case escapingQuoteRuneClass: + { + state = quotingEscapingState + } + case nonEscapingQuoteRuneClass: + { + state = quotingState + } + case escapeRuneClass: + { + state = escapingState + } + default: + { + value = append(value, nextRune) + } + } + } + case escapingState: // the rune after an escape character + { + switch nextRuneType { + case eofRuneClass: + { + err = fmt.Errorf("EOF found after escape character") + token := &Token{ + tokenType: tokenType, + value: string(value)} + return token, err + } + default: + { + state = inWordState + value = append(value, nextRune) + } + } + } + case escapingQuotedState: // the next rune after an escape character, in double quotes + { + switch nextRuneType { + case eofRuneClass: + { + err = fmt.Errorf("EOF found after escape character") + token := &Token{ + tokenType: tokenType, + value: string(value)} + return token, err + } + default: + { + state = quotingEscapingState + value = append(value, nextRune) + } + } + } + case quotingEscapingState: // in escaping double quotes + { + switch nextRuneType { + case eofRuneClass: + { + err = fmt.Errorf("EOF found when expecting closing quote") + token := &Token{ + tokenType: tokenType, + value: string(value)} + return token, err + } + case escapingQuoteRuneClass: + { + state = inWordState + } + case escapeRuneClass: + { + state = escapingQuotedState + } + default: + { + value = append(value, nextRune) + } + } + } + case quotingState: // in non-escaping single quotes + { + switch nextRuneType { + case eofRuneClass: + { + err = fmt.Errorf("EOF found when expecting closing quote") + token := &Token{ + tokenType: tokenType, + value: string(value)} + return token, err + } + case nonEscapingQuoteRuneClass: + { + state = inWordState + } + default: + { + value = append(value, nextRune) + } + } + } + case commentState: // in a comment + { + switch nextRuneType { + case eofRuneClass: + { + token := &Token{ + tokenType: tokenType, + value: string(value)} + return token, err + } + case spaceRuneClass: + { + if nextRune == '\n' { + state = startState + token := &Token{ + tokenType: tokenType, + value: string(value)} + return token, err + } else { + value = append(value, nextRune) + } + } + default: + { + value = append(value, nextRune) + } + } + } + default: + { + return nil, fmt.Errorf("Unexpected state: %v", state) + } + } + } +} + +// Next returns the next token in the stream. +func (t *Tokenizer) Next() (*Token, error) { + return t.scanStream() +} + +// Split partitions a string into a slice of strings. +func Split(s string) ([]string, error) { + l := NewLexer(strings.NewReader(s)) + subStrings := make([]string, 0) + for { + word, err := l.Next() + if err != nil { + if err == io.EOF { + return subStrings, nil + } + return subStrings, err + } + subStrings = append(subStrings, word) + } +} diff --git a/vendor/github.com/jackc/pgio/.travis.yml b/vendor/github.com/jackc/pgio/.travis.yml new file mode 100644 index 00000000..e176228e --- /dev/null +++ b/vendor/github.com/jackc/pgio/.travis.yml @@ -0,0 +1,9 @@ +language: go + +go: + - 1.x + - tip + +matrix: + allow_failures: + - go: tip diff --git a/vendor/github.com/jackc/pgio/LICENSE b/vendor/github.com/jackc/pgio/LICENSE new file mode 100644 index 00000000..c1c4f50f --- /dev/null +++ b/vendor/github.com/jackc/pgio/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2019 Jack Christensen + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/jackc/pgio/README.md b/vendor/github.com/jackc/pgio/README.md new file mode 100644 index 00000000..1952ed86 --- /dev/null +++ b/vendor/github.com/jackc/pgio/README.md @@ -0,0 +1,11 @@ +[![](https://godoc.org/github.com/jackc/pgio?status.svg)](https://godoc.org/github.com/jackc/pgio) +[![Build Status](https://travis-ci.org/jackc/pgio.svg)](https://travis-ci.org/jackc/pgio) + +# pgio + +Package pgio is a low-level toolkit building messages in the PostgreSQL wire protocol. + +pgio provides functions for appending integers to a []byte while doing byte +order conversion. + +Extracted from original implementation in https://github.com/jackc/pgx. diff --git a/vendor/github.com/jackc/pgio/doc.go b/vendor/github.com/jackc/pgio/doc.go new file mode 100644 index 00000000..ef2dcc7f --- /dev/null +++ b/vendor/github.com/jackc/pgio/doc.go @@ -0,0 +1,6 @@ +// Package pgio is a low-level toolkit building messages in the PostgreSQL wire protocol. +/* +pgio provides functions for appending integers to a []byte while doing byte +order conversion. +*/ +package pgio diff --git a/vendor/github.com/jackc/pgio/write.go b/vendor/github.com/jackc/pgio/write.go new file mode 100644 index 00000000..96aedf9d --- /dev/null +++ b/vendor/github.com/jackc/pgio/write.go @@ -0,0 +1,40 @@ +package pgio + +import "encoding/binary" + +func AppendUint16(buf []byte, n uint16) []byte { + wp := len(buf) + buf = append(buf, 0, 0) + binary.BigEndian.PutUint16(buf[wp:], n) + return buf +} + +func AppendUint32(buf []byte, n uint32) []byte { + wp := len(buf) + buf = append(buf, 0, 0, 0, 0) + binary.BigEndian.PutUint32(buf[wp:], n) + return buf +} + +func AppendUint64(buf []byte, n uint64) []byte { + wp := len(buf) + buf = append(buf, 0, 0, 0, 0, 0, 0, 0, 0) + binary.BigEndian.PutUint64(buf[wp:], n) + return buf +} + +func AppendInt16(buf []byte, n int16) []byte { + return AppendUint16(buf, uint16(n)) +} + +func AppendInt32(buf []byte, n int32) []byte { + return AppendUint32(buf, uint32(n)) +} + +func AppendInt64(buf []byte, n int64) []byte { + return AppendUint64(buf, uint64(n)) +} + +func SetInt32(buf []byte, n int32) { + binary.BigEndian.PutUint32(buf, uint32(n)) +} diff --git a/vendor/github.com/jackc/pglogrepl/LICENSE b/vendor/github.com/jackc/pglogrepl/LICENSE new file mode 100644 index 00000000..c1c4f50f --- /dev/null +++ b/vendor/github.com/jackc/pglogrepl/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2019 Jack Christensen + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/jackc/pglogrepl/README.md b/vendor/github.com/jackc/pglogrepl/README.md new file mode 100644 index 00000000..a7b1378b --- /dev/null +++ b/vendor/github.com/jackc/pglogrepl/README.md @@ -0,0 +1,66 @@ +[![](https://godoc.org/github.com/jackc/pglogrepl?status.svg)](https://godoc.org/github.com/jackc/pglogrepl) +[![CI](https://github.com/jackc/pglogrepl/actions/workflows/ci.yml/badge.svg)](https://github.com/jackc/pglogrepl/actions/workflows/ci.yml) + +# pglogrepl + +pglogrepl is a Go package for PostgreSQL logical replication. + +pglogrepl uses package github.com/jackc/pgx/v5/pgconn as its underlying PostgreSQL connection. + +Proper use of this package requires understanding the underlying PostgreSQL concepts. See +https://www.postgresql.org/docs/current/protocol-replication.html. + +## Example + +In `example/pglogrepl_demo`, there is an example demo program that connects to a database and logs all messages sent over logical replication. +In `example/pgphysrepl_demo`, there is an example demo program that connects to a database and logs all messages sent over physical replication. + +## Testing + +Testing requires a user with replication permission, a database to replicate, access allowed in `pg_hba.conf`, and +logical replication enabled in `postgresql.conf`. + +Create a database: + +``` +create database pglogrepl; +``` + +Create a user: + +``` +create user pglogrepl with replication password 'secret'; +``` + +If you're using PostgreSQL 15 or newer grant access to the public schema, just for these tests: + +``` +grant all on schema public to pglogrepl; +``` + +Add a replication line to your pg_hba.conf: + +``` +host replication pglogrepl 127.0.0.1/32 md5 +``` + +Change the following settings in your postgresql.conf: + +``` +wal_level=logical +max_wal_senders=5 +max_replication_slots=5 +``` + +To run the tests set `PGLOGREPL_TEST_CONN_STRING` environment variable with a replication connection string (URL or DSN). + +Since the base backup would request postgres to create a backup tar and stream it, this test cn be disabled with +``` +PGLOGREPL_SKIP_BASE_BACKUP=true +``` + +Example: + +``` +PGLOGREPL_TEST_CONN_STRING=postgres://pglogrepl:secret@127.0.0.1/pglogrepl?replication=database go test +``` diff --git a/vendor/github.com/jackc/pglogrepl/docker-compose.yml b/vendor/github.com/jackc/pglogrepl/docker-compose.yml new file mode 100644 index 00000000..84418df6 --- /dev/null +++ b/vendor/github.com/jackc/pglogrepl/docker-compose.yml @@ -0,0 +1,11 @@ +services: + postgres: + image: postgres:${POSTGRES_VERSION:-17}-alpine + restart: always + command: ["-c", "wal_level=logical", "-c", "max_wal_senders=10", "-c", "max_replication_slots=10"] + environment: + POSTGRES_USER: ${POSTGRES_USER:-pglogrepl} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-secret} + POSTGRES_DB: ${POSTGRES_DB:-pglogrepl} + POSTGRES_HOST_AUTH_METHOD: trust + network_mode: "host" diff --git a/vendor/github.com/jackc/pglogrepl/message.go b/vendor/github.com/jackc/pglogrepl/message.go new file mode 100644 index 00000000..63155329 --- /dev/null +++ b/vendor/github.com/jackc/pglogrepl/message.go @@ -0,0 +1,720 @@ +package pglogrepl + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "strconv" + "time" +) + +var ( + errMsgNotSupported = errors.New("replication message not supported") +) + +// MessageType indicates the type of a logical replication message. +type MessageType uint8 + +func (t MessageType) String() string { + switch t { + case MessageTypeBegin: + return "Begin" + case MessageTypeCommit: + return "Commit" + case MessageTypeOrigin: + return "Origin" + case MessageTypeRelation: + return "Relation" + case MessageTypeType: + return "Type" + case MessageTypeInsert: + return "Insert" + case MessageTypeUpdate: + return "Update" + case MessageTypeDelete: + return "Delete" + case MessageTypeTruncate: + return "Truncate" + case MessageTypeMessage: + return "Message" + case MessageTypeStreamStart: + return "StreamStart" + case MessageTypeStreamStop: + return "StreamStop" + case MessageTypeStreamCommit: + return "StreamCommit" + case MessageTypeStreamAbort: + return "StreamAbort" + default: + return "Unknown" + } +} + +// List of types of logical replication messages. +const ( + MessageTypeBegin MessageType = 'B' + MessageTypeMessage MessageType = 'M' + MessageTypeCommit MessageType = 'C' + MessageTypeOrigin MessageType = 'O' + MessageTypeRelation MessageType = 'R' + MessageTypeType MessageType = 'Y' + MessageTypeInsert MessageType = 'I' + MessageTypeUpdate MessageType = 'U' + MessageTypeDelete MessageType = 'D' + MessageTypeTruncate MessageType = 'T' + MessageTypeStreamStart MessageType = 'S' + MessageTypeStreamStop MessageType = 'E' + MessageTypeStreamCommit MessageType = 'c' + MessageTypeStreamAbort MessageType = 'A' +) + +// Message is a message received from server. +type Message interface { + Type() MessageType +} + +// MessageDecoder decodes message into struct. +type MessageDecoder interface { + Decode([]byte) error +} + +type baseMessage struct { + msgType MessageType +} + +// Type returns message type. +func (m *baseMessage) Type() MessageType { + return m.msgType +} + +// SetType sets message type. +// This method is added to help writing test code in application. +// The message type is still defined by message data. +func (m *baseMessage) SetType(t MessageType) { + m.msgType = t +} + +// Decode parse src into message struct. The src must contain the complete message starts after +// the first message type byte. +func (m *baseMessage) Decode(_ []byte) error { + return fmt.Errorf("message decode not implemented") +} + +func (m *baseMessage) lengthError(name string, expectedLen, actualLen int) error { + return fmt.Errorf("%s must have %d bytes, got %d bytes", name, expectedLen, actualLen) +} + +func (m *baseMessage) decodeStringError(name, field string) error { + return fmt.Errorf("%s.%s decode string error", name, field) +} + +func (m *baseMessage) decodeTupleDataError(name, field string, e error) error { + return fmt.Errorf("%s.%s decode tuple error: %s", name, field, e.Error()) +} + +func (m *baseMessage) invalidTupleTypeError(name, field string, e string, a byte) error { + return fmt.Errorf("%s.%s invalid tuple type value, expect %s, actual %c", name, field, e, a) +} + +// decodeString decode a string from src and returns the length of bytes being parsed. +// +// String type definition: https://www.postgresql.org/docs/current/protocol-message-types.html +// String(s) +// +// A null-terminated string (C-style string). There is no specific length limitation on strings. +// If s is specified it is the exact value that will appear, otherwise the value is variable. +// Eg. String, String("user"). +// +// If there is no null byte in src, return -1. +func (m *baseMessage) decodeString(src []byte) (string, int) { + end := bytes.IndexByte(src, byte(0)) + if end == -1 { + return "", -1 + } + // Trim the last null byte before converting it to a Golang string, then we can + // compare the result string with a Golang string literal. + return string(src[:end]), end + 1 +} + +func (m *baseMessage) decodeLSN(src []byte) (LSN, int) { + return LSN(binary.BigEndian.Uint64(src)), 8 +} + +func (m *baseMessage) decodeTime(src []byte) (time.Time, int) { + return pgTimeToTime(int64(binary.BigEndian.Uint64(src))), 8 +} + +func (m *baseMessage) decodeUint16(src []byte) (uint16, int) { + return binary.BigEndian.Uint16(src), 2 +} + +func (m *baseMessage) decodeUint32(src []byte) (uint32, int) { + return binary.BigEndian.Uint32(src), 4 +} + +func (m *baseMessage) decodeInt32(src []byte) (int32, int) { + asUint32, size := m.decodeUint32(src) + return int32(asUint32), size +} + +// BeginMessage is a begin message. +type BeginMessage struct { + baseMessage + //FinalLSN is the final LSN of the transaction. + FinalLSN LSN + // CommitTime is the commit timestamp of the transaction. + CommitTime time.Time + // Xid of the transaction. + Xid uint32 +} + +// Decode decodes the message from src. +func (m *BeginMessage) Decode(src []byte) error { + if len(src) < 20 { + return m.lengthError("BeginMessage", 20, len(src)) + } + var low, used int + m.FinalLSN, used = m.decodeLSN(src) + low += used + m.CommitTime, used = m.decodeTime(src[low:]) + low += used + m.Xid = binary.BigEndian.Uint32(src[low:]) + + m.SetType(MessageTypeBegin) + + return nil +} + +// CommitMessage is a commit message. +type CommitMessage struct { + baseMessage + // Flags currently unused (must be 0). + Flags uint8 + // CommitLSN is the LSN of the commit. + CommitLSN LSN + // TransactionEndLSN is the end LSN of the transaction. + TransactionEndLSN LSN + // CommitTime is the commit timestamp of the transaction + CommitTime time.Time +} + +// Decode decodes the message from src. +func (m *CommitMessage) Decode(src []byte) error { + if len(src) < 25 { + return m.lengthError("CommitMessage", 25, len(src)) + } + var low, used int + m.Flags = src[0] + low += 1 + m.CommitLSN, used = m.decodeLSN(src[low:]) + low += used + m.TransactionEndLSN, used = m.decodeLSN(src[low:]) + low += used + m.CommitTime, _ = m.decodeTime(src[low:]) + + m.SetType(MessageTypeCommit) + + return nil +} + +// OriginMessage is an origin message. +type OriginMessage struct { + baseMessage + // CommitLSN is the LSN of the commit on the origin server. + CommitLSN LSN + Name string +} + +// Decode decodes to message from src. +func (m *OriginMessage) Decode(src []byte) error { + if len(src) < 8 { + return m.lengthError("OriginMessage", 9, len(src)) + } + + var low, used int + m.CommitLSN, used = m.decodeLSN(src) + low += used + m.Name, used = m.decodeString(src[low:]) + if used < 0 { + return m.decodeStringError("OriginMessage", "Name") + } + + m.SetType(MessageTypeOrigin) + + return nil +} + +// RelationMessageColumn is one column in a RelationMessage. +type RelationMessageColumn struct { + // Flags for the column. Currently, it can be either 0 for no flags or 1 which marks the column as part of the key. + Flags uint8 + + Name string + + // DataType is the ID of the column's data type. + DataType uint32 + + // TypeModifier is type modifier of the column (atttypmod). + TypeModifier int32 +} + +// RelationMessage is a relation message. +type RelationMessage struct { + baseMessage + RelationID uint32 + Namespace string + RelationName string + ReplicaIdentity uint8 + ColumnNum uint16 + Columns []*RelationMessageColumn +} + +// Decode decodes to message from src. +func (m *RelationMessage) Decode(src []byte) error { + if len(src) < 7 { + return m.lengthError("RelationMessage", 7, len(src)) + } + + var low, used int + m.RelationID, used = m.decodeUint32(src) + low += used + + m.Namespace, used = m.decodeString(src[low:]) + if used < 0 { + return m.decodeStringError("RelationMessage", "Namespace") + } + low += used + + m.RelationName, used = m.decodeString(src[low:]) + if used < 0 { + return m.decodeStringError("RelationMessage", "RelationName") + } + low += used + + m.ReplicaIdentity = src[low] + low++ + + m.ColumnNum, used = m.decodeUint16(src[low:]) + low += used + + for i := 0; i < int(m.ColumnNum); i++ { + column := new(RelationMessageColumn) + column.Flags = src[low] + low++ + column.Name, used = m.decodeString(src[low:]) + if used < 0 { + return m.decodeStringError("RelationMessage", fmt.Sprintf("Column[%d].Name", i)) + } + low += used + + column.DataType, used = m.decodeUint32(src[low:]) + low += used + + column.TypeModifier, used = m.decodeInt32(src[low:]) + low += used + + m.Columns = append(m.Columns, column) + } + + m.SetType(MessageTypeRelation) + + return nil +} + +// TypeMessage is a type message. +type TypeMessage struct { + baseMessage + DataType uint32 + Namespace string + Name string +} + +// Decode decodes to message from src. +func (m *TypeMessage) Decode(src []byte) error { + if len(src) < 6 { + return m.lengthError("TypeMessage", 6, len(src)) + } + + var low, used int + m.DataType, used = m.decodeUint32(src) + low += used + + m.Namespace, used = m.decodeString(src[low:]) + if used < 0 { + return m.decodeStringError("TypeMessage", "Namespace") + } + low += used + + m.Name, used = m.decodeString(src[low:]) + if used < 0 { + return m.decodeStringError("TypeMessage", "Name") + } + + m.SetType(MessageTypeType) + + return nil +} + +// List of types of data in a tuple. +const ( + TupleDataTypeNull = uint8('n') + TupleDataTypeToast = uint8('u') + TupleDataTypeText = uint8('t') + TupleDataTypeBinary = uint8('b') +) + +// TupleDataColumn is a column in a TupleData. +type TupleDataColumn struct { + // DataType indicates how the data is stored. + // Byte1('n') Identifies the data as NULL value. + // Or + // Byte1('u') Identifies unchanged TOASTed value (the actual value is not sent). + // Or + // Byte1('t') Identifies the data as text formatted value. + // Or + // Byte1('b') Identifies the data as binary value. + DataType uint8 + Length uint32 + // Data is th value of the column, in text format. (A future release might support additional formats.) n is the above length. + Data []byte +} + +// Int64 parse column data as an int64 integer. +func (c *TupleDataColumn) Int64() (int64, error) { + if c.DataType != TupleDataTypeText { + return 0, fmt.Errorf("invalid column's data type, expect %c, actual %c", + TupleDataTypeText, c.DataType) + } + + return strconv.ParseInt(string(c.Data), 10, 64) +} + +// TupleData contains row change information. +type TupleData struct { + baseMessage + ColumnNum uint16 + Columns []*TupleDataColumn +} + +// Decode decodes to message from src. +func (m *TupleData) Decode(src []byte) (int, error) { + var low, used int + + m.ColumnNum, used = m.decodeUint16(src) + low += used + + for i := 0; i < int(m.ColumnNum); i++ { + column := new(TupleDataColumn) + column.DataType = src[low] + low += 1 + + switch column.DataType { + case TupleDataTypeText, TupleDataTypeBinary: + column.Length, used = m.decodeUint32(src[low:]) + low += used + + column.Data = make([]byte, int(column.Length)) + for j := 0; j < int(column.Length); j++ { + column.Data[j] = src[low+j] + } + low += int(column.Length) + case TupleDataTypeNull, TupleDataTypeToast: + } + + m.Columns = append(m.Columns, column) + } + + return low, nil +} + +// InsertMessage is a insert message +type InsertMessage struct { + baseMessage + // RelationID is the ID of the relation corresponding to the ID in the relation message. + RelationID uint32 + Tuple *TupleData +} + +// Decode decodes to message from src. +func (m *InsertMessage) Decode(src []byte) error { + if len(src) < 8 { + return m.lengthError("InsertMessage", 8, len(src)) + } + + var low, used int + + m.RelationID, used = m.decodeUint32(src) + low += used + + tupleType := src[low] + low += 1 + if tupleType != 'N' { + return m.invalidTupleTypeError("InsertMessage", "TupleType", "N", tupleType) + } + + m.Tuple = new(TupleData) + _, err := m.Tuple.Decode(src[low:]) + if err != nil { + return m.decodeTupleDataError("InsertMessage", "TupleData", err) + } + + m.SetType(MessageTypeInsert) + + return nil +} + +// List of types of UpdateMessage tuples. +const ( + UpdateMessageTupleTypeNone = uint8(0) + UpdateMessageTupleTypeKey = uint8('K') + UpdateMessageTupleTypeOld = uint8('O') + UpdateMessageTupleTypeNew = uint8('N') +) + +// UpdateMessage is a update message. +type UpdateMessage struct { + baseMessage + RelationID uint32 + + // OldTupleType + // Byte1('K'): + // Identifies the following TupleData submessage as a key. + // This field is optional and is only present if the update changed data + // in any of the column(s) that are part of the REPLICA IDENTITY index. + // + // Byte1('O'): + // Identifies the following TupleData submessage as an old tuple. + // This field is optional and is only present if table in which the update happened + // has REPLICA IDENTITY set to FULL. + // + // The Update message may contain either a 'K' message part or an 'O' message part + // or neither of them, but never both of them. + OldTupleType uint8 + OldTuple *TupleData + + // NewTuple is the contents of a new tuple. + // Byte1('N'): Identifies the following TupleData message as a new tuple. + NewTuple *TupleData +} + +// Decode decodes to message from src. +func (m *UpdateMessage) Decode(src []byte) (err error) { + if len(src) < 6 { + return m.lengthError("UpdateMessage", 6, len(src)) + } + + var low, used int + + m.RelationID, used = m.decodeUint32(src) + low += used + + tupleType := src[low] + low++ + + switch tupleType { + case UpdateMessageTupleTypeKey, UpdateMessageTupleTypeOld: + m.OldTupleType = tupleType + m.OldTuple = new(TupleData) + used, err = m.OldTuple.Decode(src[low:]) + if err != nil { + return m.decodeTupleDataError("UpdateMessage", "OldTuple", err) + } + low += used + low++ + fallthrough + case UpdateMessageTupleTypeNew: + m.NewTuple = new(TupleData) + _, err = m.NewTuple.Decode(src[low:]) + if err != nil { + return m.decodeTupleDataError("UpdateMessage", "NewTuple", err) + } + default: + return m.invalidTupleTypeError("UpdateMessage", "Tuple", "K/O/N", tupleType) + } + + m.SetType(MessageTypeUpdate) + + return nil +} + +// List of types of DeleteMessage tuples. +const ( + DeleteMessageTupleTypeKey = uint8('K') + DeleteMessageTupleTypeOld = uint8('O') +) + +// DeleteMessage is a delete message. +type DeleteMessage struct { + baseMessage + RelationID uint32 + // OldTupleType + // Byte1('K'): + // Identifies the following TupleData submessage as a key. + // This field is present if the table in which the delete has happened uses an index + // as REPLICA IDENTITY. + // + // Byte1('O') + // Identifies the following TupleData message as an old tuple. + // This field is present if the table in which the delete has happened has + // REPLICA IDENTITY set to FULL. + // + // The Delete message may contain either a 'K' message part or an 'O' message part, + // but never both of them. + OldTupleType uint8 + OldTuple *TupleData +} + +// Decode decodes a message from src. +func (m *DeleteMessage) Decode(src []byte) (err error) { + if len(src) < 4 { + return m.lengthError("DeleteMessage", 4, len(src)) + } + + var low, used int + + m.RelationID, used = m.decodeUint32(src) + low += used + + m.OldTupleType = src[low] + low++ + + switch m.OldTupleType { + case DeleteMessageTupleTypeKey, DeleteMessageTupleTypeOld: + m.OldTuple = new(TupleData) + _, err = m.OldTuple.Decode(src[low:]) + if err != nil { + return m.decodeTupleDataError("DeleteMessage", "OldTuple", err) + } + default: + return m.invalidTupleTypeError("DeleteMessage", "OldTupleType", "K/O", m.OldTupleType) + } + + m.SetType(MessageTypeDelete) + + return nil +} + +// List of truncate options. +const ( + TruncateOptionCascade = uint8(1) << iota + TruncateOptionRestartIdentity +) + +// TruncateMessage is a truncate message. +type TruncateMessage struct { + baseMessage + RelationNum uint32 + Option uint8 + RelationIDs []uint32 +} + +// Decode decodes to message from src. +func (m *TruncateMessage) Decode(src []byte) (err error) { + if len(src) < 9 { + return m.lengthError("TruncateMessage", 9, len(src)) + } + + var low, used int + m.RelationNum, used = m.decodeUint32(src) + low += used + + m.Option = src[low] + low++ + + m.RelationIDs = make([]uint32, m.RelationNum) + for i := 0; i < int(m.RelationNum); i++ { + m.RelationIDs[i], used = m.decodeUint32(src[low:]) + low += used + } + + m.SetType(MessageTypeTruncate) + + return nil +} + +// LogicalDecodingMessage is a logical decoding message. +type LogicalDecodingMessage struct { + baseMessage + + LSN LSN + Transactional bool + Prefix string + Content []byte +} + +// Decode decodes a message from src. +func (m *LogicalDecodingMessage) Decode(src []byte) (err error) { + if len(src) < 14 { + return m.lengthError("LogicalDecodingMessage", 14, len(src)) + } + + var low, used int + + flags := src[low] + m.Transactional = flags == 1 + low++ + + m.LSN, used = m.decodeLSN(src[low:]) + low += used + + m.Prefix, used = m.decodeString(src[low:]) + low += used + + contentLength, used := m.decodeUint32(src[low:]) + low += used + + m.Content = src[low : low+int(contentLength)] + + m.SetType(MessageTypeMessage) + + return nil +} + +// Parse parse a logical replication message. +func Parse(data []byte) (m Message, err error) { + var decoder MessageDecoder + msgType := MessageType(data[0]) + switch msgType { + case MessageTypeRelation: + decoder = new(RelationMessage) + case MessageTypeType: + decoder = new(TypeMessage) + case MessageTypeInsert: + decoder = new(InsertMessage) + case MessageTypeUpdate: + decoder = new(UpdateMessage) + case MessageTypeDelete: + decoder = new(DeleteMessage) + case MessageTypeTruncate: + decoder = new(TruncateMessage) + case MessageTypeMessage: + decoder = new(LogicalDecodingMessage) + default: + decoder = getCommonDecoder(msgType) + } + + if decoder == nil { + return nil, errMsgNotSupported + } + + if err = decoder.Decode(data[1:]); err != nil { + return nil, err + } + + return decoder.(Message), nil +} + +func getCommonDecoder(msgType MessageType) MessageDecoder { + var decoder MessageDecoder + switch msgType { + case MessageTypeBegin: + decoder = new(BeginMessage) + case MessageTypeCommit: + decoder = new(CommitMessage) + case MessageTypeOrigin: + decoder = new(OriginMessage) + } + + return decoder +} diff --git a/vendor/github.com/jackc/pglogrepl/messageV2.go b/vendor/github.com/jackc/pglogrepl/messageV2.go new file mode 100644 index 00000000..990e46f1 --- /dev/null +++ b/vendor/github.com/jackc/pglogrepl/messageV2.go @@ -0,0 +1,326 @@ +package pglogrepl + +import ( + "encoding/binary" + "time" +) + +// MessageDecoderV2 decodes message from V2 protocol into struct. +type MessageDecoderV2 interface { + MessageDecoder + DecodeV2(src []byte, inStream bool) error +} + +// StreamStartMessageV2 is a stream start message. +type StreamStartMessageV2 struct { + baseMessage + + Xid uint32 + // A value of 1 indicates this is the first stream segment for this XID, 0 for any other stream segment + FirstSegment uint8 +} + +// DecodeV2 decodes to message from V2 src. +func (m *StreamStartMessageV2) DecodeV2(src []byte, _ bool) (err error) { + if len(src) < 5 { + return m.lengthError("StreamStartMessageV2", 5, len(src)) + } + + var low, used int + m.Xid, used = m.decodeUint32(src) + low += used + m.FirstSegment = src[low] + + m.SetType(MessageTypeStreamStart) + + return nil +} + +// StreamStopMessageV2 is a stream stop message. +type StreamStopMessageV2 struct { + baseMessage +} + +// DecodeV2 decodes to message from V2 src. +func (m *StreamStopMessageV2) DecodeV2(_ []byte, _ bool) (err error) { + // stream stop has no data. + m.SetType(MessageTypeStreamStop) + + return nil +} + +// StreamCommitMessageV2 is a stream commit message. +type StreamCommitMessageV2 struct { + baseMessage + + Xid uint32 + Flags uint8 // currently unused + CommitLSN LSN + TransactionEndLSN LSN + CommitTime time.Time +} + +// DecodeV2 decodes to message from V2 src. +func (m *StreamCommitMessageV2) DecodeV2(src []byte, _ bool) (err error) { + if len(src) < 29 { + return m.lengthError("StreamCommitMessageV2", 29, len(src)) + } + var low, used int + m.Xid, used = m.decodeUint32(src) + low += used + m.Flags = src[low] + low += 1 + m.CommitLSN, used = m.decodeLSN(src[low:]) + low += used + m.TransactionEndLSN, used = m.decodeLSN(src[low:]) + low += used + m.CommitTime, _ = m.decodeTime(src[low:]) + + m.SetType(MessageTypeStreamCommit) + + return nil +} + +// StreamAbortMessageV2 is a stream abort message. +type StreamAbortMessageV2 struct { + baseMessage + + Xid uint32 + // Xid of the subtransaction (will be same as xid of the transaction for top-level transactions). + SubXid uint32 +} + +// DecodeV2 decodes to message from V2 src. +func (m *StreamAbortMessageV2) DecodeV2(src []byte, _ bool) (err error) { + if len(src) < 8 { + return m.lengthError("StreamAbortMessageV2", 8, len(src)) + } + + var low, used int + m.Xid, used = m.decodeUint32(src) + low += used + m.SubXid, _ = m.decodeUint32(src[low:]) + + m.SetType(MessageTypeStreamAbort) + + return nil +} + +// ParseV2 parse a logical replication message from protocol version #2 +// it accepts a slice of bytes read from PG and inStream parameter +// inStream must be true when StreamStartMessageV2 has been read +// it must be false after StreamStopMessageV2 has been read +func ParseV2(data []byte, inStream bool) (m Message, err error) { + var decoder MessageDecoder + msgType := MessageType(data[0]) + + switch msgType { + case MessageTypeStreamStart: + decoder = new(StreamStartMessageV2) + case MessageTypeStreamStop: + decoder = new(StreamStopMessageV2) + case MessageTypeStreamCommit: + decoder = new(StreamCommitMessageV2) + case MessageTypeStreamAbort: + decoder = new(StreamAbortMessageV2) + case MessageTypeMessage: + decoder = new(LogicalDecodingMessageV2) + case MessageTypeRelation: + decoder = new(RelationMessageV2) + case MessageTypeType: + decoder = new(TypeMessageV2) + case MessageTypeInsert: + decoder = new(InsertMessageV2) + case MessageTypeUpdate: + decoder = new(UpdateMessageV2) + case MessageTypeDelete: + decoder = new(DeleteMessageV2) + case MessageTypeTruncate: + decoder = new(TruncateMessageV2) + default: + decoder = getCommonDecoder(msgType) + } + + if decoder == nil { + return nil, errMsgNotSupported + } + + if v2, ok := decoder.(MessageDecoderV2); ok { + if err = v2.DecodeV2(data[1:], inStream); err != nil { + return nil, err + } + } else if err = decoder.Decode(data[1:]); err != nil { + return nil, err + } + + return decoder.(Message), nil +} + +// InStreamMessageV2WithXid is a V2 protocol message +type InStreamMessageV2WithXid struct { + // Xid of the transaction (only present for streamed transactions). + Xid uint32 +} + +// LogicalDecodingMessageV2 is a logical decoding message. +type LogicalDecodingMessageV2 struct { + LogicalDecodingMessage + InStreamMessageV2WithXid +} + +// DecodeV2 decodes to message from V2 src. +func (m *LogicalDecodingMessageV2) DecodeV2(src []byte, inStream bool) (err error) { + if !inStream { + return m.LogicalDecodingMessage.Decode(src) + } + + if len(src) < 18 { + return m.lengthError("LogicalDecodingMessage", 18, len(src)) + } + + src = readXidAndAdvance(src, &m.InStreamMessageV2WithXid, inStream) + + return m.LogicalDecodingMessage.Decode(src) +} + +// RelationMessageV2 is a relation message. +type RelationMessageV2 struct { + RelationMessage + InStreamMessageV2WithXid +} + +// DecodeV2 decodes to message from V2 src. +func (m *RelationMessageV2) DecodeV2(src []byte, inStream bool) (err error) { + if !inStream { + return m.RelationMessage.Decode(src) + } + + if len(src) < 11 { + return m.lengthError("RelationMessageV2", 11, len(src)) + } + + src = readXidAndAdvance(src, &m.InStreamMessageV2WithXid, inStream) + + return m.RelationMessage.Decode(src) +} + +// TypeMessageV2 is a type message. +type TypeMessageV2 struct { + TypeMessage + InStreamMessageV2WithXid +} + +// DecodeV2 decodes to message from V2 src. +func (m *TypeMessageV2) DecodeV2(src []byte, inStream bool) (err error) { + if !inStream { + return m.TypeMessage.Decode(src) + } + + if len(src) < 10 { + return m.lengthError("TypeMessageV2", 10, len(src)) + } + + src = readXidAndAdvance(src, &m.InStreamMessageV2WithXid, inStream) + + return m.TypeMessage.Decode(src) +} + +// InsertMessageV2 is an insert message. +type InsertMessageV2 struct { + InsertMessage + InStreamMessageV2WithXid +} + +// DecodeV2 decodes to message from V2 src. +func (m *InsertMessageV2) DecodeV2(src []byte, inStream bool) (err error) { + if !inStream { + return m.InsertMessage.Decode(src) + } + + if len(src) < 12 { + return m.lengthError("InsertMessageV2", 12, len(src)) + } + + src = readXidAndAdvance(src, &m.InStreamMessageV2WithXid, inStream) + + return m.InsertMessage.Decode(src) +} + +// UpdateMessageV2 is an update message. +type UpdateMessageV2 struct { + UpdateMessage + InStreamMessageV2WithXid +} + +// DecodeV2 decodes to message from V2 src. +func (m *UpdateMessageV2) DecodeV2(src []byte, inStream bool) (err error) { + if !inStream { + return m.UpdateMessage.Decode(src) + } + + if len(src) < 10 { + return m.lengthError("UpdateMessageV2", 10, len(src)) + } + + src = readXidAndAdvance(src, &m.InStreamMessageV2WithXid, inStream) + + return m.UpdateMessage.Decode(src) +} + +// DeleteMessageV2 is a delete message. +type DeleteMessageV2 struct { + DeleteMessage + InStreamMessageV2WithXid +} + +// DecodeV2 decodes to message from V2 src. +func (m *DeleteMessageV2) DecodeV2(src []byte, inStream bool) (err error) { + if !inStream { + return m.DeleteMessage.Decode(src) + } + + if len(src) < 8 { + return m.lengthError("DeleteMessageV2", 8, len(src)) + } + + src = readXidAndAdvance(src, &m.InStreamMessageV2WithXid, inStream) + + return m.DeleteMessage.Decode(src) +} + +// TruncateMessageV2 is a truncate message. +type TruncateMessageV2 struct { + TruncateMessage + InStreamMessageV2WithXid +} + +// DecodeV2 decodes to message from V2 src. +func (m *TruncateMessageV2) DecodeV2(src []byte, inStream bool) (err error) { + if !inStream { + return m.TruncateMessage.Decode(src) + } + + if len(src) < 13 { + return m.lengthError("TruncateMessageV2", 13, len(src)) + } + + src = readXidAndAdvance(src, &m.InStreamMessageV2WithXid, inStream) + + return m.TruncateMessage.Decode(src) +} + +func readXidAndAdvance(src []byte, mXid *InStreamMessageV2WithXid, inStream bool) []byte { + var xid uint32 + var used int + + if inStream { + xid, used = decodeUint32(src) + mXid.Xid = xid + } + + return src[used:] +} + +func decodeUint32(src []byte) (uint32, int) { + return binary.BigEndian.Uint32(src), 4 +} diff --git a/vendor/github.com/jackc/pglogrepl/pglogrepl.go b/vendor/github.com/jackc/pglogrepl/pglogrepl.go new file mode 100644 index 00000000..bd199b43 --- /dev/null +++ b/vendor/github.com/jackc/pglogrepl/pglogrepl.go @@ -0,0 +1,805 @@ +// Package pglogrepl implements PostgreSQL logical replication client functionality. +// +// pglogrepl uses package github.com/jackc/pgconn as its underlying PostgreSQL connection. +// Use pgconn to establish a connection to PostgreSQL and then use the pglogrepl functions +// on that connection. +// +// Proper use of this package requires understanding the underlying PostgreSQL concepts. +// See https://www.postgresql.org/docs/current/protocol-replication.html. +package pglogrepl + +import ( + "context" + "database/sql/driver" + "encoding/binary" + "fmt" + "strconv" + "strings" + "time" + + "github.com/jackc/pgio" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgproto3" +) + +const ( + XLogDataByteID = 'w' + PrimaryKeepaliveMessageByteID = 'k' + StandbyStatusUpdateByteID = 'r' +) + +type ReplicationMode int + +const ( + LogicalReplication ReplicationMode = iota + PhysicalReplication +) + +// String formats the mode into a postgres valid string +func (mode ReplicationMode) String() string { + if mode == LogicalReplication { + return "LOGICAL" + } else { + return "PHYSICAL" + } +} + +// LSN is a PostgreSQL Log Sequence Number. See https://www.postgresql.org/docs/current/datatype-pg-lsn.html. +type LSN uint64 + +// String formats the LSN value into the XXX/XXX format which is the text format used by PostgreSQL. +func (lsn LSN) String() string { + return fmt.Sprintf("%X/%X", uint32(lsn>>32), uint32(lsn)) +} + +func (lsn *LSN) decodeText(src string) error { + lsnValue, err := ParseLSN(src) + if err != nil { + return err + } + *lsn = lsnValue + + return nil +} + +// Scan implements the Scanner interface. +func (lsn *LSN) Scan(src interface{}) error { + if lsn == nil { + return nil + } + + switch v := src.(type) { + case uint64: + *lsn = LSN(v) + case string: + if err := lsn.decodeText(v); err != nil { + return err + } + case []byte: + if err := lsn.decodeText(string(v)); err != nil { + return err + } + default: + return fmt.Errorf("can not scan %T to LSN", src) + } + + return nil +} + +// Value implements the Valuer interface. +func (lsn LSN) Value() (driver.Value, error) { + return driver.Value(lsn.String()), nil +} + +// ParseLSN parses the given XXX/XXX text format LSN used by PostgreSQL. +func ParseLSN(s string) (LSN, error) { + var upperHalf uint64 + var lowerHalf uint64 + var nparsed int + nparsed, err := fmt.Sscanf(s, "%X/%X", &upperHalf, &lowerHalf) + if err != nil { + return 0, fmt.Errorf("failed to parse LSN: %w", err) + } + + if nparsed != 2 { + return 0, fmt.Errorf("failed to parsed LSN: %s", s) + } + + return LSN((upperHalf << 32) + lowerHalf), nil +} + +// IdentifySystemResult is the parsed result of the IDENTIFY_SYSTEM command. +type IdentifySystemResult struct { + SystemID string + Timeline int32 + XLogPos LSN + DBName string +} + +// IdentifySystem executes the IDENTIFY_SYSTEM command. +func IdentifySystem(ctx context.Context, conn *pgconn.PgConn) (IdentifySystemResult, error) { + return ParseIdentifySystem(conn.Exec(ctx, "IDENTIFY_SYSTEM")) +} + +// ParseIdentifySystem parses the result of the IDENTIFY_SYSTEM command. +func ParseIdentifySystem(mrr *pgconn.MultiResultReader) (IdentifySystemResult, error) { + var isr IdentifySystemResult + results, err := mrr.ReadAll() + if err != nil { + return isr, err + } + + if len(results) != 1 { + return isr, fmt.Errorf("expected 1 result set, got %d", len(results)) + } + + result := results[0] + if len(result.Rows) != 1 { + return isr, fmt.Errorf("expected 1 result row, got %d", len(result.Rows)) + } + + row := result.Rows[0] + if len(row) < 4 { + return isr, fmt.Errorf("expected at least 4 result columns, got %d", len(row)) + } + + isr.SystemID = string(row[0]) + timeline, err := strconv.ParseInt(string(row[1]), 10, 32) + if err != nil { + return isr, fmt.Errorf("failed to parse timeline: %w", err) + } + isr.Timeline = int32(timeline) + + isr.XLogPos, err = ParseLSN(string(row[2])) + if err != nil { + return isr, fmt.Errorf("failed to parse xlogpos as LSN: %w", err) + } + + isr.DBName = string(row[3]) + + return isr, nil +} + +// TimelineHistoryResult is the parsed result of the TIMELINE_HISTORY command. +type TimelineHistoryResult struct { + FileName string + Content []byte +} + +// TimelineHistory executes the TIMELINE_HISTORY command. +func TimelineHistory(ctx context.Context, conn *pgconn.PgConn, timeline int32) (TimelineHistoryResult, error) { + sql := fmt.Sprintf("TIMELINE_HISTORY %d", timeline) + return ParseTimelineHistory(conn.Exec(ctx, sql)) +} + +// ParseTimelineHistory parses the result of the TIMELINE_HISTORY command. +func ParseTimelineHistory(mrr *pgconn.MultiResultReader) (TimelineHistoryResult, error) { + var thr TimelineHistoryResult + results, err := mrr.ReadAll() + if err != nil { + return thr, err + } + + if len(results) != 1 { + return thr, fmt.Errorf("expected 1 result set, got %d", len(results)) + } + + result := results[0] + if len(result.Rows) != 1 { + return thr, fmt.Errorf("expected 1 result row, got %d", len(result.Rows)) + } + + row := result.Rows[0] + if len(row) != 2 { + return thr, fmt.Errorf("expected 2 result columns, got %d", len(row)) + } + + thr.FileName = string(row[0]) + thr.Content = row[1] + return thr, nil +} + +type CreateReplicationSlotOptions struct { + Temporary bool + SnapshotAction string + Mode ReplicationMode +} + +// CreateReplicationSlotResult is the parsed results the CREATE_REPLICATION_SLOT command. +type CreateReplicationSlotResult struct { + SlotName string + ConsistentPoint string + SnapshotName string + OutputPlugin string +} + +// CreateReplicationSlot creates a logical replication slot. +func CreateReplicationSlot( + ctx context.Context, + conn *pgconn.PgConn, + slotName string, + outputPlugin string, + options CreateReplicationSlotOptions, +) (CreateReplicationSlotResult, error) { + var temporaryString string + if options.Temporary { + temporaryString = "TEMPORARY" + } + sql := fmt.Sprintf("CREATE_REPLICATION_SLOT %s %s %s %s %s", slotName, temporaryString, options.Mode, outputPlugin, options.SnapshotAction) + return ParseCreateReplicationSlot(conn.Exec(ctx, sql)) +} + +// ParseCreateReplicationSlot parses the result of the CREATE_REPLICATION_SLOT command. +func ParseCreateReplicationSlot(mrr *pgconn.MultiResultReader) (CreateReplicationSlotResult, error) { + var crsr CreateReplicationSlotResult + results, err := mrr.ReadAll() + if err != nil { + return crsr, err + } + + if len(results) != 1 { + return crsr, fmt.Errorf("expected 1 result set, got %d", len(results)) + } + + result := results[0] + if len(result.Rows) != 1 { + return crsr, fmt.Errorf("expected 1 result row, got %d", len(result.Rows)) + } + + row := result.Rows[0] + if len(row) != 4 { + return crsr, fmt.Errorf("expected 4 result columns, got %d", len(row)) + } + + crsr.SlotName = string(row[0]) + crsr.ConsistentPoint = string(row[1]) + crsr.SnapshotName = string(row[2]) + crsr.OutputPlugin = string(row[3]) + + return crsr, nil +} + +type DropReplicationSlotOptions struct { + Wait bool +} + +// DropReplicationSlot drops a logical replication slot. +func DropReplicationSlot(ctx context.Context, conn *pgconn.PgConn, slotName string, options DropReplicationSlotOptions) error { + var waitString string + if options.Wait { + waitString = "WAIT" + } + sql := fmt.Sprintf("DROP_REPLICATION_SLOT %s %s", slotName, waitString) + _, err := conn.Exec(ctx, sql).ReadAll() + return err +} + +type StartReplicationOptions struct { + Timeline int32 // 0 means current server timeline + Mode ReplicationMode + PluginArgs []string +} + +type errEndTimeline struct { + nextTli int64 + nextTliStartpos LSN +} + +func (e errEndTimeline) Error() string { + return "start replication with a switch point" +} + +func (e errEndTimeline) ErrEndTimeline() (int64, LSN) { + return e.nextTli, e.nextTliStartpos +} + +func IsErrEndTimeline(err error) (int64, LSN, bool) { + e, ok := err.(interface{ ErrEndTimeline() (int64, LSN) }) + if !ok { + return 0, 0, false + } + nextTli, nextTliStartpos := e.ErrEndTimeline() + return nextTli, nextTliStartpos, true +} + +// StartReplication begins the replication process by executing the START_REPLICATION command. +func StartReplication(ctx context.Context, conn *pgconn.PgConn, slotName string, startLSN LSN, options StartReplicationOptions) error { + var timelineString string + if options.Timeline > 0 { + timelineString = fmt.Sprintf("TIMELINE %d", options.Timeline) + options.PluginArgs = append(options.PluginArgs, timelineString) + } + + sql := fmt.Sprintf("START_REPLICATION SLOT %s %s %s ", slotName, options.Mode, startLSN) + if options.Mode == LogicalReplication { + if len(options.PluginArgs) > 0 { + sql += fmt.Sprintf("(%s)", strings.Join(options.PluginArgs, ", ")) + } + } else { + sql += timelineString + } + + conn.Frontend().SendQuery(&pgproto3.Query{String: sql}) + err := conn.Frontend().Flush() + if err != nil { + return fmt.Errorf("failed to send START_REPLICATION: %w", err) + } + + var ( + nextTli int64 + nextTliStartpos LSN + ) + for { + msg, err := conn.ReceiveMessage(ctx) + if err != nil { + return fmt.Errorf("failed to receive message: %w", err) + } + + switch msg := msg.(type) { + case *pgproto3.NoticeResponse: + case *pgproto3.ErrorResponse: + return pgconn.ErrorResponseToPgError(msg) + case *pgproto3.CopyBothResponse: + // This signals the start of the replication stream. + return nil + case *pgproto3.RowDescription: + if options.Mode != PhysicalReplication { + return fmt.Errorf("received row RowDescription message in logical replication") + } + if len(msg.Fields) != 2 || string(msg.Fields[0].Name) != "next_tli" || string(msg.Fields[1].Name) != "next_tli_startpos" { + return fmt.Errorf("expected next timeline row description message") + } + case *pgproto3.DataRow: + if cnt := len(msg.Values); cnt != 2 { + return fmt.Errorf("expected next_tli and next_tli_startpos, got %d fields", cnt) + } + tmpNextTli, tmpNextTliStartpos := string(msg.Values[0]), string(msg.Values[1]) + nextTli, err = strconv.ParseInt(tmpNextTli, 10, 64) + if err != nil { + return err + } + nextTliStartpos, err = ParseLSN(tmpNextTliStartpos) + if err != nil { + return err + } + case *pgproto3.CommandComplete: + case *pgproto3.ReadyForQuery: + // if no next timeline switch result, maybe it was left on the connection + if nextTli > 0 && nextTliStartpos > 0 { + return errEndTimeline{nextTli: nextTli, nextTliStartpos: nextTliStartpos} + } + default: + return fmt.Errorf("unexpected response type: %T", msg) + } + } +} + +type BaseBackupOptions struct { + // Request information required to generate a progress report, but might as such have a negative impact on the performance. + Progress bool + // Sets the label of the backup. If none is specified, a backup label of 'wal-g' will be used. + Label string + // Request a fast checkpoint. + Fast bool + // Include the necessary WAL segments in the backup. This will include all the files between start and stop backup in the pg_wal directory of the base directory tar file. + WAL bool + // By default, the backup will wait until the last required WAL segment has been archived, or emit a warning if log archiving is not enabled. + // Specifying NOWAIT disables both the waiting and the warning, leaving the client responsible for ensuring the required log is available. + NoWait bool + // Limit (throttle) the maximum amount of data transferred from server to client per unit of time (kb/s). + MaxRate int32 + // Include information about symbolic links present in the directory pg_tblspc in a file named tablespace_map. + TablespaceMap bool + // Disable checksums being verified during a base backup. + // Note that NoVerifyChecksums=true is only supported since PG11 + NoVerifyChecksums bool +} + +func (bbo BaseBackupOptions) sql(serverVersion int) string { + var parts []string + if bbo.Label != "" { + parts = append(parts, "LABEL '"+strings.ReplaceAll(bbo.Label, "'", "''")+"'") + } + if bbo.Progress { + parts = append(parts, "PROGRESS") + } + if bbo.Fast { + if serverVersion >= 15 { + parts = append(parts, "CHECKPOINT 'fast'") + } else { + parts = append(parts, "FAST") + } + } + if bbo.WAL { + parts = append(parts, "WAL") + } + if bbo.NoWait { + if serverVersion >= 15 { + parts = append(parts, "WAIT false") + } else { + parts = append(parts, "NOWAIT") + } + } + if bbo.MaxRate >= 32 { + parts = append(parts, fmt.Sprintf("MAX_RATE %d", bbo.MaxRate)) + } + if bbo.TablespaceMap { + parts = append(parts, "TABLESPACE_MAP") + } + if bbo.NoVerifyChecksums { + if serverVersion >= 15 { + parts = append(parts, "VERIFY_CHECKSUMS false") + } else if serverVersion >= 11 { + parts = append(parts, "NOVERIFY_CHECKSUMS") + } + } + if serverVersion >= 15 { + return "BASE_BACKUP(" + strings.Join(parts, ", ") + ")" + } + return "BASE_BACKUP " + strings.Join(parts, " ") +} + +// BaseBackupTablespace represents a tablespace in the backup +type BaseBackupTablespace struct { + OID int32 + Location string + Size int8 +} + +// BaseBackupResult will hold the return values of the BaseBackup command +type BaseBackupResult struct { + LSN LSN + TimelineID int32 + Tablespaces []BaseBackupTablespace +} + +func serverMajorVersion(conn *pgconn.PgConn) (int, error) { + verString := conn.ParameterStatus("server_version") + dot := strings.IndexByte(verString, '.') + if dot == -1 { + return 0, fmt.Errorf("bad server version string: '%s'", verString) + } + return strconv.Atoi(verString[:dot]) +} + +// StartBaseBackup begins the process for copying a basebackup by executing the BASE_BACKUP command. +func StartBaseBackup(ctx context.Context, conn *pgconn.PgConn, options BaseBackupOptions) (result BaseBackupResult, err error) { + serverVersion, err := serverMajorVersion(conn) + if err != nil { + return result, err + } + sql := options.sql(serverVersion) + + conn.Frontend().SendQuery(&pgproto3.Query{String: sql}) + err = conn.Frontend().Flush() + if err != nil { + return result, fmt.Errorf("failed to send BASE_BACKUP: %w", err) + } + // From here Postgres returns result sets, but pgconn has no infrastructure to properly capture them. + // So we capture data low level with sub functions, before we return from this function when we get to the CopyData part. + result.LSN, result.TimelineID, err = getBaseBackupInfo(ctx, conn) + if err != nil { + return result, err + } + result.Tablespaces, err = getTableSpaceInfo(ctx, conn) + return result, err +} + +// getBaseBackupInfo returns the start or end position of the backup as returned by Postgres +func getBaseBackupInfo(ctx context.Context, conn *pgconn.PgConn) (start LSN, timelineID int32, err error) { + for { + msg, err := conn.ReceiveMessage(ctx) + if err != nil { + return start, timelineID, fmt.Errorf("failed to receive message: %w", err) + } + switch msg := msg.(type) { + case *pgproto3.RowDescription: + if len(msg.Fields) != 2 { + return start, timelineID, fmt.Errorf("expected 2 column headers, received: %d", len(msg.Fields)) + } + colName := string(msg.Fields[0].Name) + if colName != "recptr" { + return start, timelineID, fmt.Errorf("unexpected col name for recptr col: %s", colName) + } + colName = string(msg.Fields[1].Name) + if colName != "tli" { + return start, timelineID, fmt.Errorf("unexpected col name for tli col: %s", colName) + } + case *pgproto3.DataRow: + if len(msg.Values) != 2 { + return start, timelineID, fmt.Errorf("expected 2 columns, received: %d", len(msg.Values)) + } + colData := string(msg.Values[0]) + start, err = ParseLSN(colData) + if err != nil { + return start, timelineID, fmt.Errorf("cannot convert result to LSN: %s", colData) + } + colData = string(msg.Values[1]) + tli, err := strconv.Atoi(colData) + if err != nil { + return start, timelineID, fmt.Errorf("cannot convert timelineID to int: %s", colData) + } + timelineID = int32(tli) + case *pgproto3.NoticeResponse: + case *pgproto3.CommandComplete: + return start, timelineID, nil + case *pgproto3.ErrorResponse: + return start, timelineID, fmt.Errorf("error response sev=%q code=%q message=%q detail=%q position=%d", msg.Severity, msg.Code, msg.Message, msg.Detail, msg.Position) + default: + return start, timelineID, fmt.Errorf("unexpected response type: %T", msg) + } + } +} + +// getBaseBackupInfo returns the start or end position of the backup as returned by Postgres +func getTableSpaceInfo(ctx context.Context, conn *pgconn.PgConn) (tbss []BaseBackupTablespace, err error) { + for { + msg, err := conn.ReceiveMessage(ctx) + if err != nil { + return tbss, fmt.Errorf("failed to receive message: %w", err) + } + switch msg := msg.(type) { + case *pgproto3.RowDescription: + if len(msg.Fields) != 3 { + return tbss, fmt.Errorf("expected 3 column headers, received: %d", len(msg.Fields)) + } + colName := string(msg.Fields[0].Name) + if colName != "spcoid" { + return tbss, fmt.Errorf("unexpected col name for spcoid col: %s", colName) + } + colName = string(msg.Fields[1].Name) + if colName != "spclocation" { + return tbss, fmt.Errorf("unexpected col name for spclocation col: %s", colName) + } + colName = string(msg.Fields[2].Name) + if colName != "size" { + return tbss, fmt.Errorf("unexpected col name for size col: %s", colName) + } + case *pgproto3.DataRow: + if len(msg.Values) != 3 { + return tbss, fmt.Errorf("expected 3 columns, received: %d", len(msg.Values)) + } + if msg.Values[0] == nil { + continue + } + tbs := BaseBackupTablespace{} + colData := string(msg.Values[0]) + OID, err := strconv.Atoi(colData) + if err != nil { + return tbss, fmt.Errorf("cannot convert spcoid to int: %s", colData) + } + tbs.OID = int32(OID) + tbs.Location = string(msg.Values[1]) + if msg.Values[2] != nil { + colData := string(msg.Values[2]) + size, err := strconv.Atoi(colData) + if err != nil { + return tbss, fmt.Errorf("cannot convert size to int: %s", colData) + } + tbs.Size = int8(size) + } + tbss = append(tbss, tbs) + case *pgproto3.CommandComplete: + return tbss, nil + default: + return tbss, fmt.Errorf("unexpected response type: %T", msg) + } + } +} + +// NextTableSpace consumes some msgs so we are at start of CopyData +func NextTableSpace(ctx context.Context, conn *pgconn.PgConn) (err error) { + + for { + msg, err := conn.ReceiveMessage(ctx) + if err != nil { + return fmt.Errorf("failed to receive message: %w", err) + } + + switch msg := msg.(type) { + case *pgproto3.CopyOutResponse: + return nil + case *pgproto3.CopyData: + return nil + case *pgproto3.ErrorResponse: + return pgconn.ErrorResponseToPgError(msg) + case *pgproto3.NoticeResponse: + case *pgproto3.RowDescription: + + default: + return fmt.Errorf("unexpected response type: %T", msg) + } + } +} + +// FinishBaseBackup wraps up a backup after copying all results from the BASE_BACKUP command. +func FinishBaseBackup(ctx context.Context, conn *pgconn.PgConn) (result BaseBackupResult, err error) { + + // From here Postgres returns result sets, but pgconn has no infrastructure to properly capture them. + // So we capture data low level with sub functions, before we return from this function when we get to the CopyData part. + result.LSN, result.TimelineID, err = getBaseBackupInfo(ctx, conn) + if err != nil { + return result, err + } + + // Base_Backup done, server sends a command complete response + var ( + pack pgproto3.BackendMessage + ok bool + ) + pack, err = conn.ReceiveMessage(ctx) + if err != nil { + return + } + _, ok = pack.(*pgproto3.CommandComplete) + if !ok { + err = fmt.Errorf("expect command_complete, got %T", pack) + return + } + + // simple query done, server send a ready for query response + pack, err = conn.ReceiveMessage(ctx) + if err != nil { + return + } + _, ok = pack.(*pgproto3.ReadyForQuery) + if !ok { + err = fmt.Errorf("expect ready_for_query, got %T", pack) + return + } + return +} + +type PrimaryKeepaliveMessage struct { + ServerWALEnd LSN + ServerTime time.Time + ReplyRequested bool +} + +// ParsePrimaryKeepaliveMessage parses a Primary keepalive message from the server. +func ParsePrimaryKeepaliveMessage(buf []byte) (PrimaryKeepaliveMessage, error) { + var pkm PrimaryKeepaliveMessage + if len(buf) != 17 { + return pkm, fmt.Errorf("PrimaryKeepaliveMessage must be 17 bytes, got %d", len(buf)) + } + + pkm.ServerWALEnd = LSN(binary.BigEndian.Uint64(buf)) + pkm.ServerTime = pgTimeToTime(int64(binary.BigEndian.Uint64(buf[8:]))) + pkm.ReplyRequested = buf[16] != 0 + + return pkm, nil +} + +type XLogData struct { + WALStart LSN + ServerWALEnd LSN + ServerTime time.Time + WALData []byte +} + +// ParseXLogData parses a XLogData message from the server. +func ParseXLogData(buf []byte) (XLogData, error) { + var xld XLogData + if len(buf) < 24 { + return xld, fmt.Errorf("XLogData must be at least 24 bytes, got %d", len(buf)) + } + + xld.WALStart = LSN(binary.BigEndian.Uint64(buf)) + xld.ServerWALEnd = LSN(binary.BigEndian.Uint64(buf[8:])) + xld.ServerTime = pgTimeToTime(int64(binary.BigEndian.Uint64(buf[16:]))) + xld.WALData = buf[24:] + + return xld, nil +} + +// StandbyStatusUpdate is a message sent from the client that acknowledges receipt of WAL records. +type StandbyStatusUpdate struct { + WALWritePosition LSN // The WAL position that's been locally written + WALFlushPosition LSN // The WAL position that's been locally flushed + WALApplyPosition LSN // The WAL position that's been locally applied + ClientTime time.Time // Client system clock time + ReplyRequested bool // Request server to reply immediately. +} + +// SendStandbyStatusUpdate sends a StandbyStatusUpdate to the PostgreSQL server. +// +// The only required field in ssu is WALWritePosition. If WALFlushPosition is 0 then WALWritePosition will be assigned +// to it. If WALApplyPosition is 0 then WALWritePosition will be assigned to it. If ClientTime is the zero value then +// the current time will be assigned to it. +func SendStandbyStatusUpdate(_ context.Context, conn *pgconn.PgConn, ssu StandbyStatusUpdate) error { + if ssu.WALFlushPosition == 0 { + ssu.WALFlushPosition = ssu.WALWritePosition + } + if ssu.WALApplyPosition == 0 { + ssu.WALApplyPosition = ssu.WALWritePosition + } + if ssu.ClientTime == (time.Time{}) { + ssu.ClientTime = time.Now() + } + + data := make([]byte, 0, 34) + data = append(data, StandbyStatusUpdateByteID) + data = pgio.AppendUint64(data, uint64(ssu.WALWritePosition)) + data = pgio.AppendUint64(data, uint64(ssu.WALFlushPosition)) + data = pgio.AppendUint64(data, uint64(ssu.WALApplyPosition)) + data = pgio.AppendInt64(data, timeToPgTime(ssu.ClientTime)) + if ssu.ReplyRequested { + data = append(data, 1) + } else { + data = append(data, 0) + } + + cd := &pgproto3.CopyData{Data: data} + buf, err := cd.Encode(nil) + if err != nil { + return err + } + + return conn.Frontend().SendUnbufferedEncodedCopyData(buf) +} + +// CopyDoneResult is the parsed result as returned by the server after the client +// sends a CopyDone to the server to confirm ending the copy-both mode. +type CopyDoneResult struct { + Timeline int32 + LSN LSN +} + +// SendStandbyCopyDone sends a StandbyCopyDone to the PostgreSQL server +// to confirm ending the copy-both mode. +func SendStandbyCopyDone(_ context.Context, conn *pgconn.PgConn) (cdr *CopyDoneResult, err error) { + // I am suspicious that this is wildly wrong, but I'm pretty sure the previous + // code was wildly wrong too -- wttw + conn.Frontend().Send(&pgproto3.CopyDone{}) + err = conn.Frontend().Flush() + if err != nil { + return cdr, err + } + + for { + var msg pgproto3.BackendMessage + msg, err = conn.Frontend().Receive() + if err != nil { + return cdr, err + } + + switch m := msg.(type) { + case *pgproto3.CopyDone: + case *pgproto3.ParameterStatus, *pgproto3.NoticeResponse: + case *pgproto3.CommandComplete: + case *pgproto3.RowDescription: + case *pgproto3.DataRow: + // We are expecting just one row returned, with two columns timeline and LSN + // We should pay attention to RowDescription, but we'll take it on trust. + if len(m.Values) == 2 { + timeline, lerr := strconv.Atoi(string(m.Values[0])) + if lerr == nil { + lsn, lerr := ParseLSN(string(m.Values[1])) + if lerr == nil { + cdr = &CopyDoneResult{} + cdr.Timeline = int32(timeline) + cdr.LSN = lsn + } + } + } + case *pgproto3.EmptyQueryResponse: + case *pgproto3.ErrorResponse: + return cdr, pgconn.ErrorResponseToPgError(m) + case *pgproto3.ReadyForQuery: + // Should we eat the ReadyForQuery here, or not? + return cdr, err + } + } +} + +const microsecFromUnixEpochToY2K = 946684800 * 1000000 + +func pgTimeToTime(microsecSinceY2K int64) time.Time { + microsecSinceUnixEpoch := microsecFromUnixEpochToY2K + microsecSinceY2K + return time.Unix(0, microsecSinceUnixEpoch*1000) +} + +func timeToPgTime(t time.Time) int64 { + microsecSinceUnixEpoch := t.Unix()*1000000 + int64(t.Nanosecond())/1000 + return microsecSinceUnixEpoch - microsecFromUnixEpochToY2K +} diff --git a/vendor/github.com/jackc/pgx/v5/CHANGELOG.md b/vendor/github.com/jackc/pgx/v5/CHANGELOG.md index 63ee30d5..78de6db7 100644 --- a/vendor/github.com/jackc/pgx/v5/CHANGELOG.md +++ b/vendor/github.com/jackc/pgx/v5/CHANGELOG.md @@ -1,3 +1,52 @@ +# 5.5.4 (March 4, 2024) + +Fix CVE-2024-27304 + +SQL injection can occur if an attacker can cause a single query or bind message to exceed 4 GB in size. An integer +overflow in the calculated message size can cause the one large message to be sent as multiple messages under the +attacker's control. + +Thanks to Paul Gerste for reporting this issue. + +* Fix behavior of CollectRows to return empty slice if Rows are empty (Felix) +* Fix simple protocol encoding of json.RawMessage +* Fix *Pipeline.getResults should close pipeline on error +* Fix panic in TryFindUnderlyingTypeScanPlan (David Kurman) +* Fix deallocation of invalidated cached statements in a transaction +* Handle invalid sslkey file +* Fix scan float4 into sql.Scanner +* Fix pgtype.Bits not making copy of data from read buffer. This would cause the data to be corrupted by future reads. + +# 5.5.3 (February 3, 2024) + +* Fix: prepared statement already exists +* Improve CopyFrom auto-conversion of text-ish values +* Add ltree type support (Florent Viel) +* Make some properties of Batch and QueuedQuery public (Pavlo Golub) +* Add AppendRows function (Edoardo Spadolini) +* Optimize convert UUID [16]byte to string (Kirill Malikov) +* Fix: LargeObject Read and Write of more than ~1GB at a time (Mitar) + +# 5.5.2 (January 13, 2024) + +* Allow NamedArgs to start with underscore +* pgproto3: Maximum message body length support (jeremy.spriet) +* Upgrade golang.org/x/crypto to v0.17.0 +* Add snake_case support to RowToStructByName (Tikhon Fedulov) +* Fix: update description cache after exec prepare (James Hartig) +* Fix: pipeline checks if it is closed (James Hartig and Ryan Fowler) +* Fix: normalize timeout / context errors during TLS startup (Samuel Stauffer) +* Add OnPgError for easier centralized error handling (James Hartig) + +# 5.5.1 (December 9, 2023) + +* Add CopyFromFunc helper function. (robford) +* Add PgConn.Deallocate method that uses PostgreSQL protocol Close message. +* pgx uses new PgConn.Deallocate method. This allows deallocating statements to work in a failed transaction. This fixes a case where the prepared statement map could become invalid. +* Fix: Prefer driver.Valuer over json.Marshaler for json fields. (Jacopo) +* Fix: simple protocol SQL sanitizer previously panicked if an invalid $0 placeholder was used. This now returns an error instead. (maksymnevajdev) +* Add pgtype.Numeric.ScanScientific (Eshton Robateau) + # 5.5.0 (November 4, 2023) * Add CollectExactlyOneRow. (Julien GOTTELAND) diff --git a/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md b/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md index 3eb0da5b..6ed3205c 100644 --- a/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md +++ b/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md @@ -79,20 +79,11 @@ echo "listen_addresses = '127.0.0.1'" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql echo "port = $PGPORT" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf cat testsetup/postgresql_ssl.conf >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf cp testsetup/pg_hba.conf .testdb/$POSTGRESQL_DATA_DIR/pg_hba.conf -cp testsetup/ca.cnf .testdb -cp testsetup/localhost.cnf .testdb -cp testsetup/pgx_sslcert.cnf .testdb cd .testdb -# Generate a CA public / private key pair. -openssl genrsa -out ca.key 4096 -openssl req -x509 -config ca.cnf -new -nodes -key ca.key -sha256 -days 365 -subj '/O=pgx-test-root' -out ca.pem - -# Generate the certificate for localhost (the server). -openssl genrsa -out localhost.key 2048 -openssl req -new -config localhost.cnf -key localhost.key -out localhost.csr -openssl x509 -req -in localhost.csr -CA ca.pem -CAkey ca.key -CAcreateserial -out localhost.crt -days 364 -sha256 -extfile localhost.cnf -extensions v3_req +# Generate CA, server, and encrypted client certificates. +go run ../testsetup/generate_certs.go # Copy certificates to server directory and set permissions. cp ca.pem $POSTGRESQL_DATA_DIR/root.crt @@ -100,11 +91,6 @@ cp localhost.key $POSTGRESQL_DATA_DIR/server.key chmod 600 $POSTGRESQL_DATA_DIR/server.key cp localhost.crt $POSTGRESQL_DATA_DIR/server.crt -# Generate the certificate for client authentication. -openssl genrsa -des3 -out pgx_sslcert.key -passout pass:certpw 2048 -openssl req -new -config pgx_sslcert.cnf -key pgx_sslcert.key -passin pass:certpw -out pgx_sslcert.csr -openssl x509 -req -in pgx_sslcert.csr -CA ca.pem -CAkey ca.key -CAcreateserial -out pgx_sslcert.crt -days 363 -sha256 -extfile pgx_sslcert.cnf -extensions v3_req - cd .. ``` diff --git a/vendor/github.com/jackc/pgx/v5/README.md b/vendor/github.com/jackc/pgx/v5/README.md index 2a9efc23..49f2c3d7 100644 --- a/vendor/github.com/jackc/pgx/v5/README.md +++ b/vendor/github.com/jackc/pgx/v5/README.md @@ -92,7 +92,7 @@ See the presentation at Golang Estonia, [PGX Top to Bottom](https://www.youtube. ## Supported Go and PostgreSQL Versions -pgx supports the same versions of Go and PostgreSQL that are supported by their respective teams. For [Go](https://golang.org/doc/devel/release.html#policy) that is the two most recent major releases and for [PostgreSQL](https://www.postgresql.org/support/versioning/) the major releases in the last 5 years. This means pgx supports Go 1.20 and higher and PostgreSQL 11 and higher. pgx also is tested against the latest version of [CockroachDB](https://www.cockroachlabs.com/product/). +pgx supports the same versions of Go and PostgreSQL that are supported by their respective teams. For [Go](https://golang.org/doc/devel/release.html#policy) that is the two most recent major releases and for [PostgreSQL](https://www.postgresql.org/support/versioning/) the major releases in the last 5 years. This means pgx supports Go 1.20 and higher and PostgreSQL 12 and higher. pgx also is tested against the latest version of [CockroachDB](https://www.cockroachlabs.com/product/). ## Version Policy @@ -120,6 +120,7 @@ pgerrcode contains constants for the PostgreSQL error codes. * [github.com/jackc/pgx-gofrs-uuid](https://github.com/jackc/pgx-gofrs-uuid) * [github.com/jackc/pgx-shopspring-decimal](https://github.com/jackc/pgx-shopspring-decimal) +* [github.com/twpayne/pgx-geos](https://github.com/twpayne/pgx-geos) ([PostGIS](https://postgis.net/) and [GEOS](https://libgeos.org/) via [go-geos](https://github.com/twpayne/go-geos)) * [github.com/vgarvardt/pgx-google-uuid](https://github.com/vgarvardt/pgx-google-uuid) diff --git a/vendor/github.com/jackc/pgx/v5/batch.go b/vendor/github.com/jackc/pgx/v5/batch.go index 8f6ea4f0..b9b46d1d 100644 --- a/vendor/github.com/jackc/pgx/v5/batch.go +++ b/vendor/github.com/jackc/pgx/v5/batch.go @@ -10,8 +10,8 @@ import ( // QueuedQuery is a query that has been queued for execution via a Batch. type QueuedQuery struct { - query string - arguments []any + SQL string + Arguments []any fn batchItemFunc sd *pgconn.StatementDescription } @@ -57,22 +57,24 @@ func (qq *QueuedQuery) Exec(fn func(ct pgconn.CommandTag) error) { // Batch queries are a way of bundling multiple queries together to avoid // unnecessary network round trips. A Batch must only be sent once. type Batch struct { - queuedQueries []*QueuedQuery + QueuedQueries []*QueuedQuery } // Queue queues a query to batch b. query can be an SQL query or the name of a prepared statement. +// The only pgx option argument that is supported is QueryRewriter. Queries are executed using the +// connection's DefaultQueryExecMode. func (b *Batch) Queue(query string, arguments ...any) *QueuedQuery { qq := &QueuedQuery{ - query: query, - arguments: arguments, + SQL: query, + Arguments: arguments, } - b.queuedQueries = append(b.queuedQueries, qq) + b.QueuedQueries = append(b.QueuedQueries, qq) return qq } // Len returns number of queries that have been queued so far. func (b *Batch) Len() int { - return len(b.queuedQueries) + return len(b.QueuedQueries) } type BatchResults interface { @@ -225,9 +227,9 @@ func (br *batchResults) Close() error { } // Read and run fn for all remaining items - for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.queuedQueries) { - if br.b.queuedQueries[br.qqIdx].fn != nil { - err := br.b.queuedQueries[br.qqIdx].fn(br) + for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.QueuedQueries) { + if br.b.QueuedQueries[br.qqIdx].fn != nil { + err := br.b.QueuedQueries[br.qqIdx].fn(br) if err != nil { br.err = err } @@ -251,10 +253,10 @@ func (br *batchResults) earlyError() error { } func (br *batchResults) nextQueryAndArgs() (query string, args []any, ok bool) { - if br.b != nil && br.qqIdx < len(br.b.queuedQueries) { - bi := br.b.queuedQueries[br.qqIdx] - query = bi.query - args = bi.arguments + if br.b != nil && br.qqIdx < len(br.b.QueuedQueries) { + bi := br.b.QueuedQueries[br.qqIdx] + query = bi.SQL + args = bi.Arguments ok = true br.qqIdx++ } @@ -394,9 +396,9 @@ func (br *pipelineBatchResults) Close() error { } // Read and run fn for all remaining items - for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.queuedQueries) { - if br.b.queuedQueries[br.qqIdx].fn != nil { - err := br.b.queuedQueries[br.qqIdx].fn(br) + for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.QueuedQueries) { + if br.b.QueuedQueries[br.qqIdx].fn != nil { + err := br.b.QueuedQueries[br.qqIdx].fn(br) if err != nil { br.err = err } @@ -420,10 +422,10 @@ func (br *pipelineBatchResults) earlyError() error { } func (br *pipelineBatchResults) nextQueryAndArgs() (query string, args []any, ok bool) { - if br.b != nil && br.qqIdx < len(br.b.queuedQueries) { - bi := br.b.queuedQueries[br.qqIdx] - query = bi.query - args = bi.arguments + if br.b != nil && br.qqIdx < len(br.b.QueuedQueries) { + bi := br.b.QueuedQueries[br.qqIdx] + query = bi.SQL + args = bi.Arguments ok = true br.qqIdx++ } diff --git a/vendor/github.com/jackc/pgx/v5/conn.go b/vendor/github.com/jackc/pgx/v5/conn.go index 0426873c..fc72c732 100644 --- a/vendor/github.com/jackc/pgx/v5/conn.go +++ b/vendor/github.com/jackc/pgx/v5/conn.go @@ -338,17 +338,26 @@ func (c *Conn) Prepare(ctx context.Context, name, sql string) (sd *pgconn.Statem return sd, nil } -// Deallocate releases a prepared statement. +// Deallocate releases a prepared statement. Calling Deallocate on a non-existent prepared statement will succeed. func (c *Conn) Deallocate(ctx context.Context, name string) error { var psName string - if sd, ok := c.preparedStatements[name]; ok { - delete(c.preparedStatements, name) + sd := c.preparedStatements[name] + if sd != nil { psName = sd.Name } else { psName = name } - _, err := c.pgConn.Exec(ctx, "deallocate "+quoteIdentifier(psName)).ReadAll() - return err + + err := c.pgConn.Deallocate(ctx, psName) + if err != nil { + return err + } + + if sd != nil { + delete(c.preparedStatements, name) + } + + return nil } // DeallocateAll releases all previously prepared statements from the server and client, where it also resets the statement and description cache. @@ -466,7 +475,7 @@ optionLoop: if queryRewriter != nil { sql, arguments, err = queryRewriter.RewriteQuery(ctx, c, sql, arguments) if err != nil { - return pgconn.CommandTag{}, fmt.Errorf("rewrite query failed: %v", err) + return pgconn.CommandTag{}, fmt.Errorf("rewrite query failed: %w", err) } } @@ -504,6 +513,7 @@ optionLoop: if err != nil { return pgconn.CommandTag{}, err } + c.descriptionCache.Put(sd) } return c.execParams(ctx, sd, arguments) @@ -733,7 +743,7 @@ optionLoop: sql, args, err = queryRewriter.RewriteQuery(ctx, c, sql, args) if err != nil { rows := c.getRows(ctx, originalSQL, originalArgs) - err = fmt.Errorf("rewrite query failed: %v", err) + err = fmt.Errorf("rewrite query failed: %w", err) rows.fatal(err) return rows, err } @@ -893,15 +903,14 @@ func (c *Conn) SendBatch(ctx context.Context, b *Batch) (br BatchResults) { return &batchResults{ctx: ctx, conn: c, err: err} } - mode := c.config.DefaultQueryExecMode - - for _, bi := range b.queuedQueries { + for _, bi := range b.QueuedQueries { var queryRewriter QueryRewriter - sql := bi.query - arguments := bi.arguments + sql := bi.SQL + arguments := bi.Arguments optionLoop: for len(arguments) > 0 { + // Update Batch.Queue function comment when additional options are implemented switch arg := arguments[0].(type) { case QueryRewriter: queryRewriter = arg @@ -915,21 +924,23 @@ func (c *Conn) SendBatch(ctx context.Context, b *Batch) (br BatchResults) { var err error sql, arguments, err = queryRewriter.RewriteQuery(ctx, c, sql, arguments) if err != nil { - return &batchResults{ctx: ctx, conn: c, err: fmt.Errorf("rewrite query failed: %v", err)} + return &batchResults{ctx: ctx, conn: c, err: fmt.Errorf("rewrite query failed: %w", err)} } } - bi.query = sql - bi.arguments = arguments + bi.SQL = sql + bi.Arguments = arguments } + // TODO: changing mode per batch? Update Batch.Queue function comment when implemented + mode := c.config.DefaultQueryExecMode if mode == QueryExecModeSimpleProtocol { return c.sendBatchQueryExecModeSimpleProtocol(ctx, b) } // All other modes use extended protocol and thus can use prepared statements. - for _, bi := range b.queuedQueries { - if sd, ok := c.preparedStatements[bi.query]; ok { + for _, bi := range b.QueuedQueries { + if sd, ok := c.preparedStatements[bi.SQL]; ok { bi.sd = sd } } @@ -950,11 +961,11 @@ func (c *Conn) SendBatch(ctx context.Context, b *Batch) (br BatchResults) { func (c *Conn) sendBatchQueryExecModeSimpleProtocol(ctx context.Context, b *Batch) *batchResults { var sb strings.Builder - for i, bi := range b.queuedQueries { + for i, bi := range b.QueuedQueries { if i > 0 { sb.WriteByte(';') } - sql, err := c.sanitizeForSimpleQuery(bi.query, bi.arguments...) + sql, err := c.sanitizeForSimpleQuery(bi.SQL, bi.Arguments...) if err != nil { return &batchResults{ctx: ctx, conn: c, err: err} } @@ -973,21 +984,21 @@ func (c *Conn) sendBatchQueryExecModeSimpleProtocol(ctx context.Context, b *Batc func (c *Conn) sendBatchQueryExecModeExec(ctx context.Context, b *Batch) *batchResults { batch := &pgconn.Batch{} - for _, bi := range b.queuedQueries { + for _, bi := range b.QueuedQueries { sd := bi.sd if sd != nil { - err := c.eqb.Build(c.typeMap, sd, bi.arguments) + err := c.eqb.Build(c.typeMap, sd, bi.Arguments) if err != nil { return &batchResults{ctx: ctx, conn: c, err: err} } batch.ExecPrepared(sd.Name, c.eqb.ParamValues, c.eqb.ParamFormats, c.eqb.ResultFormats) } else { - err := c.eqb.Build(c.typeMap, nil, bi.arguments) + err := c.eqb.Build(c.typeMap, nil, bi.Arguments) if err != nil { return &batchResults{ctx: ctx, conn: c, err: err} } - batch.ExecParams(bi.query, c.eqb.ParamValues, nil, c.eqb.ParamFormats, c.eqb.ResultFormats) + batch.ExecParams(bi.SQL, c.eqb.ParamValues, nil, c.eqb.ParamFormats, c.eqb.ResultFormats) } } @@ -1012,18 +1023,18 @@ func (c *Conn) sendBatchQueryExecModeCacheStatement(ctx context.Context, b *Batc distinctNewQueries := []*pgconn.StatementDescription{} distinctNewQueriesIdxMap := make(map[string]int) - for _, bi := range b.queuedQueries { + for _, bi := range b.QueuedQueries { if bi.sd == nil { - sd := c.statementCache.Get(bi.query) + sd := c.statementCache.Get(bi.SQL) if sd != nil { bi.sd = sd } else { - if idx, present := distinctNewQueriesIdxMap[bi.query]; present { + if idx, present := distinctNewQueriesIdxMap[bi.SQL]; present { bi.sd = distinctNewQueries[idx] } else { sd = &pgconn.StatementDescription{ - Name: stmtcache.StatementName(bi.query), - SQL: bi.query, + Name: stmtcache.StatementName(bi.SQL), + SQL: bi.SQL, } distinctNewQueriesIdxMap[sd.SQL] = len(distinctNewQueries) distinctNewQueries = append(distinctNewQueries, sd) @@ -1044,17 +1055,17 @@ func (c *Conn) sendBatchQueryExecModeCacheDescribe(ctx context.Context, b *Batch distinctNewQueries := []*pgconn.StatementDescription{} distinctNewQueriesIdxMap := make(map[string]int) - for _, bi := range b.queuedQueries { + for _, bi := range b.QueuedQueries { if bi.sd == nil { - sd := c.descriptionCache.Get(bi.query) + sd := c.descriptionCache.Get(bi.SQL) if sd != nil { bi.sd = sd } else { - if idx, present := distinctNewQueriesIdxMap[bi.query]; present { + if idx, present := distinctNewQueriesIdxMap[bi.SQL]; present { bi.sd = distinctNewQueries[idx] } else { sd = &pgconn.StatementDescription{ - SQL: bi.query, + SQL: bi.SQL, } distinctNewQueriesIdxMap[sd.SQL] = len(distinctNewQueries) distinctNewQueries = append(distinctNewQueries, sd) @@ -1071,13 +1082,13 @@ func (c *Conn) sendBatchQueryExecModeDescribeExec(ctx context.Context, b *Batch) distinctNewQueries := []*pgconn.StatementDescription{} distinctNewQueriesIdxMap := make(map[string]int) - for _, bi := range b.queuedQueries { + for _, bi := range b.QueuedQueries { if bi.sd == nil { - if idx, present := distinctNewQueriesIdxMap[bi.query]; present { + if idx, present := distinctNewQueriesIdxMap[bi.SQL]; present { bi.sd = distinctNewQueries[idx] } else { sd := &pgconn.StatementDescription{ - SQL: bi.query, + SQL: bi.SQL, } distinctNewQueriesIdxMap[sd.SQL] = len(distinctNewQueries) distinctNewQueries = append(distinctNewQueries, sd) @@ -1143,11 +1154,11 @@ func (c *Conn) sendBatchExtendedWithDescription(ctx context.Context, b *Batch, d } // Queue the queries. - for _, bi := range b.queuedQueries { - err := c.eqb.Build(c.typeMap, bi.sd, bi.arguments) + for _, bi := range b.QueuedQueries { + err := c.eqb.Build(c.typeMap, bi.sd, bi.Arguments) if err != nil { // we wrap the error so we the user can understand which query failed inside the batch - err = fmt.Errorf("error building query %s: %w", bi.query, err) + err = fmt.Errorf("error building query %s: %w", bi.SQL, err) return &pipelineBatchResults{ctx: ctx, conn: c, err: err, closed: true} } @@ -1192,7 +1203,15 @@ func (c *Conn) sanitizeForSimpleQuery(sql string, args ...any) (string, error) { return sanitize.SanitizeSQL(sql, valueArgs...) } -// LoadType inspects the database for typeName and produces a pgtype.Type suitable for registration. +// LoadType inspects the database for typeName and produces a pgtype.Type suitable for registration. typeName must be +// the name of a type where the underlying type(s) is already understood by pgx. It is for derived types. In particular, +// typeName must be one of the following: +// - An array type name of a type that is already registered. e.g. "_foo" when "foo" is registered. +// - A composite type name where all field types are already registered. +// - A domain type name where the base type is already registered. +// - An enum type name. +// - A range type name where the element type is already registered. +// - A multirange type name where the element type is already registered. func (c *Conn) LoadType(ctx context.Context, typeName string) (*pgtype.Type, error) { var oid uint32 @@ -1335,17 +1354,17 @@ order by attnum`, } func (c *Conn) deallocateInvalidatedCachedStatements(ctx context.Context) error { - if c.pgConn.TxStatus() != 'I' { + if txStatus := c.pgConn.TxStatus(); txStatus != 'I' && txStatus != 'T' { return nil } if c.descriptionCache != nil { - c.descriptionCache.HandleInvalidated() + c.descriptionCache.RemoveInvalidated() } var invalidatedStatements []*pgconn.StatementDescription if c.statementCache != nil { - invalidatedStatements = c.statementCache.HandleInvalidated() + invalidatedStatements = c.statementCache.GetInvalidated() } if len(invalidatedStatements) == 0 { @@ -1357,7 +1376,6 @@ func (c *Conn) deallocateInvalidatedCachedStatements(ctx context.Context) error for _, sd := range invalidatedStatements { pipeline.SendDeallocate(sd.Name) - delete(c.preparedStatements, sd.Name) } err := pipeline.Sync() @@ -1370,5 +1388,10 @@ func (c *Conn) deallocateInvalidatedCachedStatements(ctx context.Context) error return fmt.Errorf("failed to deallocate cached statement(s): %w", err) } + c.statementCache.RemoveInvalidated() + for _, sd := range invalidatedStatements { + delete(c.preparedStatements, sd.Name) + } + return nil } diff --git a/vendor/github.com/jackc/pgx/v5/copy_from.go b/vendor/github.com/jackc/pgx/v5/copy_from.go index a2c227fd..abcd2239 100644 --- a/vendor/github.com/jackc/pgx/v5/copy_from.go +++ b/vendor/github.com/jackc/pgx/v5/copy_from.go @@ -64,6 +64,33 @@ func (cts *copyFromSlice) Err() error { return cts.err } +// CopyFromFunc returns a CopyFromSource interface that relies on nxtf for values. +// nxtf returns rows until it either signals an 'end of data' by returning row=nil and err=nil, +// or it returns an error. If nxtf returns an error, the copy is aborted. +func CopyFromFunc(nxtf func() (row []any, err error)) CopyFromSource { + return ©FromFunc{next: nxtf} +} + +type copyFromFunc struct { + next func() ([]any, error) + valueRow []any + err error +} + +func (g *copyFromFunc) Next() bool { + g.valueRow, g.err = g.next() + // only return true if valueRow exists and no error + return g.valueRow != nil && g.err == nil +} + +func (g *copyFromFunc) Values() ([]any, error) { + return g.valueRow, g.err +} + +func (g *copyFromFunc) Err() error { + return g.err +} + // CopyFromSource is the interface used by *Conn.CopyFrom as the source for copy data. type CopyFromSource interface { // Next returns true if there is another row and makes the next row data diff --git a/vendor/github.com/jackc/pgx/v5/doc.go b/vendor/github.com/jackc/pgx/v5/doc.go index 7486f42c..db99fc4c 100644 --- a/vendor/github.com/jackc/pgx/v5/doc.go +++ b/vendor/github.com/jackc/pgx/v5/doc.go @@ -187,7 +187,7 @@ implemented on top of pgconn. The Conn.PgConn() method can be used to access thi PgBouncer -By default pgx automatically uses prepared statements. Prepared statements are incompaptible with PgBouncer. This can be +By default pgx automatically uses prepared statements. Prepared statements are incompatible with PgBouncer. This can be disabled by setting a different QueryExecMode in ConnConfig.DefaultQueryExecMode. */ package pgx diff --git a/vendor/github.com/jackc/pgx/v5/extended_query_builder.go b/vendor/github.com/jackc/pgx/v5/extended_query_builder.go index 0bbdfbb5..9c9de5b2 100644 --- a/vendor/github.com/jackc/pgx/v5/extended_query_builder.go +++ b/vendor/github.com/jackc/pgx/v5/extended_query_builder.go @@ -36,7 +36,7 @@ func (eqb *ExtendedQueryBuilder) Build(m *pgtype.Map, sd *pgconn.StatementDescri for i := range args { err := eqb.appendParam(m, sd.ParamOIDs[i], -1, args[i]) if err != nil { - err = fmt.Errorf("failed to encode args[%d]: %v", i, err) + err = fmt.Errorf("failed to encode args[%d]: %w", i, err) return err } } diff --git a/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go b/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go index e9e6d228..08d24fe4 100644 --- a/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go +++ b/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go @@ -35,6 +35,11 @@ func (q *Query) Sanitize(args ...any) (string, error) { str = part case int: argIdx := part - 1 + + if argIdx < 0 { + return "", fmt.Errorf("first sql argument must be > 0") + } + if argIdx >= len(args) { return "", fmt.Errorf("insufficient arguments") } @@ -58,6 +63,10 @@ func (q *Query) Sanitize(args ...any) (string, error) { return "", fmt.Errorf("invalid arg type: %T", arg) } argUse[argIdx] = true + + // Prevent SQL injection via Line Comment Creation + // https://github.com/jackc/pgx/security/advisories/GHSA-m7wr-2xf7-cm9p + str = "(" + str + ")" default: return "", fmt.Errorf("invalid Part type: %T", part) } diff --git a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go index 859345fc..dec83f47 100644 --- a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go +++ b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go @@ -81,12 +81,16 @@ func (c *LRUCache) InvalidateAll() { c.l = list.New() } -// HandleInvalidated returns a slice of all statement descriptions invalidated since the last call to HandleInvalidated. -// Typically, the caller will then deallocate them. -func (c *LRUCache) HandleInvalidated() []*pgconn.StatementDescription { - invalidStmts := c.invalidStmts +// GetInvalidated returns a slice of all statement descriptions invalidated since the last call to RemoveInvalidated. +func (c *LRUCache) GetInvalidated() []*pgconn.StatementDescription { + return c.invalidStmts +} + +// RemoveInvalidated removes all invalidated statement descriptions. No other calls to Cache must be made between a +// call to GetInvalidated and RemoveInvalidated or RemoveInvalidated may remove statement descriptions that were +// never seen by the call to GetInvalidated. +func (c *LRUCache) RemoveInvalidated() { c.invalidStmts = nil - return invalidStmts } // Len returns the number of cached prepared statement descriptions. diff --git a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/stmtcache.go b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/stmtcache.go index b2940e23..d57bdd29 100644 --- a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/stmtcache.go +++ b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/stmtcache.go @@ -29,8 +29,13 @@ type Cache interface { // InvalidateAll invalidates all statement descriptions. InvalidateAll() - // HandleInvalidated returns a slice of all statement descriptions invalidated since the last call to HandleInvalidated. - HandleInvalidated() []*pgconn.StatementDescription + // GetInvalidated returns a slice of all statement descriptions invalidated since the last call to RemoveInvalidated. + GetInvalidated() []*pgconn.StatementDescription + + // RemoveInvalidated removes all invalidated statement descriptions. No other calls to Cache must be made between a + // call to GetInvalidated and RemoveInvalidated or RemoveInvalidated may remove statement descriptions that were + // never seen by the call to GetInvalidated. + RemoveInvalidated() // Len returns the number of cached prepared statement descriptions. Len() int diff --git a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/unlimited_cache.go b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/unlimited_cache.go index f5f59396..69641329 100644 --- a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/unlimited_cache.go +++ b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/unlimited_cache.go @@ -54,10 +54,16 @@ func (c *UnlimitedCache) InvalidateAll() { c.m = make(map[string]*pgconn.StatementDescription) } -func (c *UnlimitedCache) HandleInvalidated() []*pgconn.StatementDescription { - invalidStmts := c.invalidStmts +// GetInvalidated returns a slice of all statement descriptions invalidated since the last call to RemoveInvalidated. +func (c *UnlimitedCache) GetInvalidated() []*pgconn.StatementDescription { + return c.invalidStmts +} + +// RemoveInvalidated removes all invalidated statement descriptions. No other calls to Cache must be made between a +// call to GetInvalidated and RemoveInvalidated or RemoveInvalidated may remove statement descriptions that were +// never seen by the call to GetInvalidated. +func (c *UnlimitedCache) RemoveInvalidated() { c.invalidStmts = nil - return invalidStmts } // Len returns the number of cached prepared statement descriptions. diff --git a/vendor/github.com/jackc/pgx/v5/large_objects.go b/vendor/github.com/jackc/pgx/v5/large_objects.go index c238ab9c..a3028b63 100644 --- a/vendor/github.com/jackc/pgx/v5/large_objects.go +++ b/vendor/github.com/jackc/pgx/v5/large_objects.go @@ -6,6 +6,11 @@ import ( "io" ) +// The PostgreSQL wire protocol has a limit of 1 GB - 1 per message. See definition of +// PQ_LARGE_MESSAGE_LIMIT in the PostgreSQL source code. To allow for the other data +// in the message,maxLargeObjectMessageLength should be no larger than 1 GB - 1 KB. +var maxLargeObjectMessageLength = 1024*1024*1024 - 1024 + // LargeObjects is a structure used to access the large objects API. It is only valid within the transaction where it // was created. // @@ -68,32 +73,64 @@ type LargeObject struct { // Write writes p to the large object and returns the number of bytes written and an error if not all of p was written. func (o *LargeObject) Write(p []byte) (int, error) { - var n int - err := o.tx.QueryRow(o.ctx, "select lowrite($1, $2)", o.fd, p).Scan(&n) - if err != nil { - return n, err - } - - if n < 0 { - return 0, errors.New("failed to write to large object") + nTotal := 0 + for { + expected := len(p) - nTotal + if expected == 0 { + break + } else if expected > maxLargeObjectMessageLength { + expected = maxLargeObjectMessageLength + } + + var n int + err := o.tx.QueryRow(o.ctx, "select lowrite($1, $2)", o.fd, p[nTotal:nTotal+expected]).Scan(&n) + if err != nil { + return nTotal, err + } + + if n < 0 { + return nTotal, errors.New("failed to write to large object") + } + + nTotal += n + + if n < expected { + return nTotal, errors.New("short write to large object") + } else if n > expected { + return nTotal, errors.New("invalid write to large object") + } } - return n, nil + return nTotal, nil } // Read reads up to len(p) bytes into p returning the number of bytes read. func (o *LargeObject) Read(p []byte) (int, error) { - var res []byte - err := o.tx.QueryRow(o.ctx, "select loread($1, $2)", o.fd, len(p)).Scan(&res) - copy(p, res) - if err != nil { - return len(res), err + nTotal := 0 + for { + expected := len(p) - nTotal + if expected == 0 { + break + } else if expected > maxLargeObjectMessageLength { + expected = maxLargeObjectMessageLength + } + + var res []byte + err := o.tx.QueryRow(o.ctx, "select loread($1, $2)", o.fd, expected).Scan(&res) + copy(p[nTotal:], res) + nTotal += len(res) + if err != nil { + return nTotal, err + } + + if len(res) < expected { + return nTotal, io.EOF + } else if len(res) > expected { + return nTotal, errors.New("invalid read of large object") + } } - if len(res) < len(p) { - err = io.EOF - } - return len(res), err + return nTotal, nil } // Seek moves the current location pointer to the new location specified by offset. diff --git a/vendor/github.com/jackc/pgx/v5/named_args.go b/vendor/github.com/jackc/pgx/v5/named_args.go index 1bc32337..8367fc63 100644 --- a/vendor/github.com/jackc/pgx/v5/named_args.go +++ b/vendor/github.com/jackc/pgx/v5/named_args.go @@ -14,6 +14,9 @@ import ( // // conn.Query(ctx, "select * from widgets where foo = @foo and bar = @bar", pgx.NamedArgs{"foo": 1, "bar": 2}) // conn.Query(ctx, "select * from widgets where foo = $1 and bar = $2", 1, 2) +// +// Named placeholders are case sensitive and must start with a letter or underscore. Subsequent characters can be +// letters, numbers, or underscores. type NamedArgs map[string]any // RewriteQuery implements the QueryRewriter interface. @@ -80,7 +83,7 @@ func rawState(l *sqlLexer) stateFn { return doubleQuoteState case '@': nextRune, _ := utf8.DecodeRuneInString(l.src[l.pos:]) - if isLetter(nextRune) { + if isLetter(nextRune) || nextRune == '_' { if l.pos-l.start > 0 { l.parts = append(l.parts, l.src[l.start:l.pos-width]) } diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/config.go b/vendor/github.com/jackc/pgx/v5/pgconn/config.go index db0170e0..33a72257 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/config.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/config.go @@ -60,6 +60,11 @@ type Config struct { // OnNotification is a callback function called when a notification from the LISTEN/NOTIFY system is received. OnNotification NotificationHandler + // OnPgError is a callback function called when a Postgres error is received by the server. The default handler will close + // the connection on any FATAL errors. If you override this handler you should call the previously set handler or ensure + // that you close on FATAL errors by returning false. + OnPgError PgErrorHandler + createdByParseConfig bool // Used to enforce created by ParseConfig rule. } @@ -232,12 +237,12 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") { connStringSettings, err = parseURLSettings(connString) if err != nil { - return nil, &parseConfigError{connString: connString, msg: "failed to parse as URL", err: err} + return nil, &ParseConfigError{ConnString: connString, msg: "failed to parse as URL", err: err} } } else { connStringSettings, err = parseDSNSettings(connString) if err != nil { - return nil, &parseConfigError{connString: connString, msg: "failed to parse as DSN", err: err} + return nil, &ParseConfigError{ConnString: connString, msg: "failed to parse as DSN", err: err} } } } @@ -246,7 +251,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con if service, present := settings["service"]; present { serviceSettings, err := parseServiceSettings(settings["servicefile"], service) if err != nil { - return nil, &parseConfigError{connString: connString, msg: "failed to read service", err: err} + return nil, &ParseConfigError{ConnString: connString, msg: "failed to read service", err: err} } settings = mergeSettings(defaultSettings, envSettings, serviceSettings, connStringSettings) @@ -261,12 +266,19 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con BuildFrontend: func(r io.Reader, w io.Writer) *pgproto3.Frontend { return pgproto3.NewFrontend(r, w) }, + OnPgError: func(_ *PgConn, pgErr *PgError) bool { + // we want to automatically close any fatal errors + if strings.EqualFold(pgErr.Severity, "FATAL") { + return false + } + return true + }, } if connectTimeoutSetting, present := settings["connect_timeout"]; present { connectTimeout, err := parseConnectTimeoutSetting(connectTimeoutSetting) if err != nil { - return nil, &parseConfigError{connString: connString, msg: "invalid connect_timeout", err: err} + return nil, &ParseConfigError{ConnString: connString, msg: "invalid connect_timeout", err: err} } config.ConnectTimeout = connectTimeout config.DialFunc = makeConnectTimeoutDialFunc(connectTimeout) @@ -328,7 +340,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con port, err := parsePort(portStr) if err != nil { - return nil, &parseConfigError{connString: connString, msg: "invalid port", err: err} + return nil, &ParseConfigError{ConnString: connString, msg: "invalid port", err: err} } var tlsConfigs []*tls.Config @@ -340,7 +352,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con var err error tlsConfigs, err = configTLS(settings, host, options) if err != nil { - return nil, &parseConfigError{connString: connString, msg: "failed to configure TLS", err: err} + return nil, &ParseConfigError{ConnString: connString, msg: "failed to configure TLS", err: err} } } @@ -384,7 +396,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con case "any": // do nothing default: - return nil, &parseConfigError{connString: connString, msg: fmt.Sprintf("unknown target_session_attrs value: %v", tsa)} + return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("unknown target_session_attrs value: %v", tsa)} } return config, nil @@ -709,6 +721,9 @@ func configTLS(settings map[string]string, thisHost string, parseConfigOptions P return nil, fmt.Errorf("unable to read sslkey: %w", err) } block, _ := pem.Decode(buf) + if block == nil { + return nil, errors.New("failed to decode sslkey") + } var pemKey []byte var decryptedKey []byte var decryptedError error diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/errors.go b/vendor/github.com/jackc/pgx/v5/pgconn/errors.go index 3c54bbec..c315739a 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/errors.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/errors.go @@ -57,22 +57,23 @@ func (pe *PgError) SQLState() string { return pe.Code } -type connectError struct { - config *Config +// ConnectError is the error returned when a connection attempt fails. +type ConnectError struct { + Config *Config // The configuration that was used in the connection attempt. msg string err error } -func (e *connectError) Error() string { +func (e *ConnectError) Error() string { sb := &strings.Builder{} - fmt.Fprintf(sb, "failed to connect to `host=%s user=%s database=%s`: %s", e.config.Host, e.config.User, e.config.Database, e.msg) + fmt.Fprintf(sb, "failed to connect to `host=%s user=%s database=%s`: %s", e.Config.Host, e.Config.User, e.Config.Database, e.msg) if e.err != nil { fmt.Fprintf(sb, " (%s)", e.err.Error()) } return sb.String() } -func (e *connectError) Unwrap() error { +func (e *ConnectError) Unwrap() error { return e.err } @@ -88,33 +89,38 @@ func (e *connLockError) Error() string { return e.status } -type parseConfigError struct { - connString string +// ParseConfigError is the error returned when a connection string cannot be parsed. +type ParseConfigError struct { + ConnString string // The connection string that could not be parsed. msg string err error } -func (e *parseConfigError) Error() string { - connString := redactPW(e.connString) +func (e *ParseConfigError) Error() string { + // Now that ParseConfigError is public and ConnString is available to the developer, perhaps it would be better only + // return a static string. That would ensure that the error message cannot leak a password. The ConnString field would + // allow access to the original string if desired and Unwrap would allow access to the underlying error. + connString := redactPW(e.ConnString) if e.err == nil { return fmt.Sprintf("cannot parse `%s`: %s", connString, e.msg) } return fmt.Sprintf("cannot parse `%s`: %s (%s)", connString, e.msg, e.err.Error()) } -func (e *parseConfigError) Unwrap() error { +func (e *ParseConfigError) Unwrap() error { return e.err } func normalizeTimeoutError(ctx context.Context, err error) error { - if err, ok := err.(net.Error); ok && err.Timeout() { + var netErr net.Error + if errors.As(err, &netErr) && netErr.Timeout() { if ctx.Err() == context.Canceled { // Since the timeout was caused by a context cancellation, the actual error is context.Canceled not the timeout error. return context.Canceled } else if ctx.Err() == context.DeadlineExceeded { return &errTimeout{err: ctx.Err()} } else { - return &errTimeout{err: err} + return &errTimeout{err: netErr} } } return err diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go b/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go index 4ed90def..0bf03f33 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go @@ -52,6 +52,12 @@ type LookupFunc func(ctx context.Context, host string) (addrs []string, err erro // BuildFrontendFunc is a function that can be used to create Frontend implementation for connection. type BuildFrontendFunc func(r io.Reader, w io.Writer) *pgproto3.Frontend +// PgErrorHandler is a function that handles errors returned from Postgres. This function must return true to keep +// the connection open. Returning false will cause the connection to be closed immediately. You should return +// false on any FATAL-severity errors. This will not receive network errors. The *PgConn is provided so the handler is +// aware of the origin of the error, but it must not invoke any query method. +type PgErrorHandler func(*PgConn, *PgError) bool + // NoticeHandler is a function that can handle notices received from the PostgreSQL server. Notices can be received at // any time, usually during handling of a query response. The *PgConn is provided so the handler is aware of the origin // of the notice, but it must not invoke any query method. Be aware that this is distinct from LISTEN/NOTIFY @@ -146,11 +152,11 @@ func ConnectConfig(octx context.Context, config *Config) (pgConn *PgConn, err er ctx := octx fallbackConfigs, err = expandWithIPs(ctx, config.LookupFunc, fallbackConfigs) if err != nil { - return nil, &connectError{config: config, msg: "hostname resolving error", err: err} + return nil, &ConnectError{Config: config, msg: "hostname resolving error", err: err} } if len(fallbackConfigs) == 0 { - return nil, &connectError{config: config, msg: "hostname resolving error", err: errors.New("ip addr wasn't found")} + return nil, &ConnectError{Config: config, msg: "hostname resolving error", err: errors.New("ip addr wasn't found")} } foundBestServer := false @@ -172,7 +178,7 @@ func ConnectConfig(octx context.Context, config *Config) (pgConn *PgConn, err er foundBestServer = true break } else if pgerr, ok := err.(*PgError); ok { - err = &connectError{config: config, msg: "server error", err: pgerr} + err = &ConnectError{Config: config, msg: "server error", err: pgerr} const ERRCODE_INVALID_PASSWORD = "28P01" // wrong password const ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION = "28000" // wrong password or bad pg_hba.conf settings const ERRCODE_INVALID_CATALOG_NAME = "3D000" // db does not exist @@ -183,7 +189,7 @@ func ConnectConfig(octx context.Context, config *Config) (pgConn *PgConn, err er pgerr.Code == ERRCODE_INSUFFICIENT_PRIVILEGE { break } - } else if cerr, ok := err.(*connectError); ok { + } else if cerr, ok := err.(*ConnectError); ok { if _, ok := cerr.err.(*NotPreferredError); ok { fallbackConfig = fc } @@ -193,7 +199,7 @@ func ConnectConfig(octx context.Context, config *Config) (pgConn *PgConn, err er if !foundBestServer && fallbackConfig != nil { pgConn, err = connect(ctx, config, fallbackConfig, true) if pgerr, ok := err.(*PgError); ok { - err = &connectError{config: config, msg: "server error", err: pgerr} + err = &ConnectError{Config: config, msg: "server error", err: pgerr} } } @@ -205,7 +211,7 @@ func ConnectConfig(octx context.Context, config *Config) (pgConn *PgConn, err er err := config.AfterConnect(ctx, pgConn) if err != nil { pgConn.conn.Close() - return nil, &connectError{config: config, msg: "AfterConnect error", err: err} + return nil, &ConnectError{Config: config, msg: "AfterConnect error", err: err} } } @@ -277,7 +283,7 @@ func connect(ctx context.Context, config *Config, fallbackConfig *FallbackConfig network, address := NetworkAddress(fallbackConfig.Host, fallbackConfig.Port) netConn, err := config.DialFunc(ctx, network, address) if err != nil { - return nil, &connectError{config: config, msg: "dial error", err: normalizeTimeoutError(ctx, err)} + return nil, &ConnectError{Config: config, msg: "dial error", err: normalizeTimeoutError(ctx, err)} } pgConn.conn = netConn @@ -289,7 +295,7 @@ func connect(ctx context.Context, config *Config, fallbackConfig *FallbackConfig pgConn.contextWatcher.Unwatch() // Always unwatch `netConn` after TLS. if err != nil { netConn.Close() - return nil, &connectError{config: config, msg: "tls error", err: err} + return nil, &ConnectError{Config: config, msg: "tls error", err: normalizeTimeoutError(ctx, err)} } pgConn.conn = nbTLSConn @@ -330,7 +336,7 @@ func connect(ctx context.Context, config *Config, fallbackConfig *FallbackConfig pgConn.frontend.Send(&startupMsg) if err := pgConn.flushWithPotentialWriteReadDeadlock(); err != nil { pgConn.conn.Close() - return nil, &connectError{config: config, msg: "failed to write startup message", err: normalizeTimeoutError(ctx, err)} + return nil, &ConnectError{Config: config, msg: "failed to write startup message", err: normalizeTimeoutError(ctx, err)} } for { @@ -340,7 +346,7 @@ func connect(ctx context.Context, config *Config, fallbackConfig *FallbackConfig if err, ok := err.(*PgError); ok { return nil, err } - return nil, &connectError{config: config, msg: "failed to receive message", err: normalizeTimeoutError(ctx, err)} + return nil, &ConnectError{Config: config, msg: "failed to receive message", err: normalizeTimeoutError(ctx, err)} } switch msg := msg.(type) { @@ -353,26 +359,26 @@ func connect(ctx context.Context, config *Config, fallbackConfig *FallbackConfig err = pgConn.txPasswordMessage(pgConn.config.Password) if err != nil { pgConn.conn.Close() - return nil, &connectError{config: config, msg: "failed to write password message", err: err} + return nil, &ConnectError{Config: config, msg: "failed to write password message", err: err} } case *pgproto3.AuthenticationMD5Password: digestedPassword := "md5" + hexMD5(hexMD5(pgConn.config.Password+pgConn.config.User)+string(msg.Salt[:])) err = pgConn.txPasswordMessage(digestedPassword) if err != nil { pgConn.conn.Close() - return nil, &connectError{config: config, msg: "failed to write password message", err: err} + return nil, &ConnectError{Config: config, msg: "failed to write password message", err: err} } case *pgproto3.AuthenticationSASL: err = pgConn.scramAuth(msg.AuthMechanisms) if err != nil { pgConn.conn.Close() - return nil, &connectError{config: config, msg: "failed SASL auth", err: err} + return nil, &ConnectError{Config: config, msg: "failed SASL auth", err: err} } case *pgproto3.AuthenticationGSS: err = pgConn.gssAuth() if err != nil { pgConn.conn.Close() - return nil, &connectError{config: config, msg: "failed GSS auth", err: err} + return nil, &ConnectError{Config: config, msg: "failed GSS auth", err: err} } case *pgproto3.ReadyForQuery: pgConn.status = connStatusIdle @@ -390,7 +396,7 @@ func connect(ctx context.Context, config *Config, fallbackConfig *FallbackConfig return pgConn, nil } pgConn.conn.Close() - return nil, &connectError{config: config, msg: "ValidateConnect failed", err: err} + return nil, &ConnectError{Config: config, msg: "ValidateConnect failed", err: err} } } return pgConn, nil @@ -401,7 +407,7 @@ func connect(ctx context.Context, config *Config, fallbackConfig *FallbackConfig return nil, ErrorResponseToPgError(msg) default: pgConn.conn.Close() - return nil, &connectError{config: config, msg: "received unexpected message", err: err} + return nil, &ConnectError{Config: config, msg: "received unexpected message", err: err} } } } @@ -547,11 +553,12 @@ func (pgConn *PgConn) receiveMessage() (pgproto3.BackendMessage, error) { case *pgproto3.ParameterStatus: pgConn.parameterStatuses[msg.Name] = msg.Value case *pgproto3.ErrorResponse: - if msg.Severity == "FATAL" { + err := ErrorResponseToPgError(msg) + if pgConn.config.OnPgError != nil && !pgConn.config.OnPgError(pgConn, err) { pgConn.status = connStatusClosed pgConn.conn.Close() // Ignore error as the connection is already broken and there is already an error to return. close(pgConn.cleanupDone) - return nil, ErrorResponseToPgError(msg) + return nil, err } case *pgproto3.NoticeResponse: if pgConn.config.OnNotice != nil { @@ -813,6 +820,9 @@ type StatementDescription struct { // Prepare creates a prepared statement. If the name is empty, the anonymous prepared statement will be used. This // allows Prepare to also to describe statements without creating a server-side prepared statement. +// +// Prepare does not send a PREPARE statement to the server. It uses the PostgreSQL Parse and Describe protocol messages +// directly. func (pgConn *PgConn) Prepare(ctx context.Context, name, sql string, paramOIDs []uint32) (*StatementDescription, error) { if err := pgConn.lock(); err != nil { return nil, err @@ -869,6 +879,52 @@ readloop: return psd, nil } +// Deallocate deallocates a prepared statement. +// +// Deallocate does not send a DEALLOCATE statement to the server. It uses the PostgreSQL Close protocol message +// directly. This has slightly different behavior than executing DEALLOCATE statement. +// - Deallocate can succeed in an aborted transaction. +// - Deallocating a non-existent prepared statement is not an error. +func (pgConn *PgConn) Deallocate(ctx context.Context, name string) error { + if err := pgConn.lock(); err != nil { + return err + } + defer pgConn.unlock() + + if ctx != context.Background() { + select { + case <-ctx.Done(): + return newContextAlreadyDoneError(ctx) + default: + } + pgConn.contextWatcher.Watch(ctx) + defer pgConn.contextWatcher.Unwatch() + } + + pgConn.frontend.SendClose(&pgproto3.Close{ObjectType: 'S', Name: name}) + pgConn.frontend.SendSync(&pgproto3.Sync{}) + err := pgConn.flushWithPotentialWriteReadDeadlock() + if err != nil { + pgConn.asyncClose() + return err + } + + for { + msg, err := pgConn.receiveMessage() + if err != nil { + pgConn.asyncClose() + return normalizeTimeoutError(ctx, err) + } + + switch msg := msg.(type) { + case *pgproto3.ErrorResponse: + return ErrorResponseToPgError(msg) + case *pgproto3.ReadyForQuery: + return nil + } + } +} + // ErrorResponseToPgError converts a wire protocol error message to a *PgError. func ErrorResponseToPgError(msg *pgproto3.ErrorResponse) *PgError { return &PgError{ @@ -1618,25 +1674,55 @@ func (rr *ResultReader) concludeCommand(commandTag CommandTag, err error) { // Batch is a collection of queries that can be sent to the PostgreSQL server in a single round-trip. type Batch struct { buf []byte + err error } // ExecParams appends an ExecParams command to the batch. See PgConn.ExecParams for parameter descriptions. func (batch *Batch) ExecParams(sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats []int16, resultFormats []int16) { - batch.buf = (&pgproto3.Parse{Query: sql, ParameterOIDs: paramOIDs}).Encode(batch.buf) + if batch.err != nil { + return + } + + batch.buf, batch.err = (&pgproto3.Parse{Query: sql, ParameterOIDs: paramOIDs}).Encode(batch.buf) + if batch.err != nil { + return + } batch.ExecPrepared("", paramValues, paramFormats, resultFormats) } // ExecPrepared appends an ExecPrepared e command to the batch. See PgConn.ExecPrepared for parameter descriptions. func (batch *Batch) ExecPrepared(stmtName string, paramValues [][]byte, paramFormats []int16, resultFormats []int16) { - batch.buf = (&pgproto3.Bind{PreparedStatement: stmtName, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}).Encode(batch.buf) - batch.buf = (&pgproto3.Describe{ObjectType: 'P'}).Encode(batch.buf) - batch.buf = (&pgproto3.Execute{}).Encode(batch.buf) + if batch.err != nil { + return + } + + batch.buf, batch.err = (&pgproto3.Bind{PreparedStatement: stmtName, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}).Encode(batch.buf) + if batch.err != nil { + return + } + + batch.buf, batch.err = (&pgproto3.Describe{ObjectType: 'P'}).Encode(batch.buf) + if batch.err != nil { + return + } + + batch.buf, batch.err = (&pgproto3.Execute{}).Encode(batch.buf) + if batch.err != nil { + return + } } // ExecBatch executes all the queries in batch in a single round-trip. Execution is implicitly transactional unless a // transaction is already in progress or SQL contains transaction control statements. This is a simpler way of executing // multiple queries in a single round trip than using pipeline mode. func (pgConn *PgConn) ExecBatch(ctx context.Context, batch *Batch) *MultiResultReader { + if batch.err != nil { + return &MultiResultReader{ + closed: true, + err: batch.err, + } + } + if err := pgConn.lock(); err != nil { return &MultiResultReader{ closed: true, @@ -1662,7 +1748,13 @@ func (pgConn *PgConn) ExecBatch(ctx context.Context, batch *Batch) *MultiResultR pgConn.contextWatcher.Watch(ctx) } - batch.buf = (&pgproto3.Sync{}).Encode(batch.buf) + batch.buf, batch.err = (&pgproto3.Sync{}).Encode(batch.buf) + if batch.err != nil { + multiResult.closed = true + multiResult.err = batch.err + pgConn.unlock() + return multiResult + } pgConn.enterPotentialWriteReadDeadlock() defer pgConn.exitPotentialWriteReadDeadlock() @@ -1997,6 +2089,13 @@ func (p *Pipeline) Flush() error { // Sync establishes a synchronization point and flushes the queued requests. func (p *Pipeline) Sync() error { + if p.closed { + if p.err != nil { + return p.err + } + return errors.New("pipeline closed") + } + p.conn.frontend.SendSync(&pgproto3.Sync{}) err := p.Flush() if err != nil { @@ -2013,13 +2112,26 @@ func (p *Pipeline) Sync() error { // *PipelineSync. If an ErrorResponse is received from the server, results will be nil and err will be a *PgError. If no // results are available, results and err will both be nil. func (p *Pipeline) GetResults() (results any, err error) { + if p.closed { + if p.err != nil { + return nil, p.err + } + return nil, errors.New("pipeline closed") + } + if p.expectedReadyForQueryCount == 0 { return nil, nil } + return p.getResults() +} + +func (p *Pipeline) getResults() (results any, err error) { for { msg, err := p.conn.receiveMessage() if err != nil { + p.closed = true + p.err = err p.conn.asyncClose() return nil, normalizeTimeoutError(p.ctx, err) } @@ -2043,7 +2155,8 @@ func (p *Pipeline) GetResults() (results any, err error) { case *pgproto3.ParseComplete: peekedMsg, err := p.conn.peekMessage() if err != nil { - return nil, err + p.conn.asyncClose() + return nil, normalizeTimeoutError(p.ctx, err) } if _, ok := peekedMsg.(*pgproto3.ParameterDescription); ok { return p.getResultsPrepare() @@ -2103,6 +2216,7 @@ func (p *Pipeline) Close() error { if p.closed { return p.err } + p.closed = true if p.pendingSync { @@ -2115,7 +2229,7 @@ func (p *Pipeline) Close() error { } for p.expectedReadyForQueryCount > 0 { - _, err := p.GetResults() + _, err := p.getResults() if err != nil { p.err = err var pgErr *PgError diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_cleartext_password.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_cleartext_password.go index d8f98b9a..ac2962e9 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_cleartext_password.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_cleartext_password.go @@ -35,11 +35,10 @@ func (dst *AuthenticationCleartextPassword) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *AuthenticationCleartextPassword) Encode(dst []byte) []byte { - dst = append(dst, 'R') - dst = pgio.AppendInt32(dst, 8) +func (src *AuthenticationCleartextPassword) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'R') dst = pgio.AppendUint32(dst, AuthTypeCleartextPassword) - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss.go index 0d234222..178ef31d 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss.go @@ -27,11 +27,10 @@ func (a *AuthenticationGSS) Decode(src []byte) error { return nil } -func (a *AuthenticationGSS) Encode(dst []byte) []byte { - dst = append(dst, 'R') - dst = pgio.AppendInt32(dst, 4) +func (a *AuthenticationGSS) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'R') dst = pgio.AppendUint32(dst, AuthTypeGSS) - return dst + return finishMessage(dst, sp) } func (a *AuthenticationGSS) MarshalJSON() ([]byte, error) { diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss_continue.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss_continue.go index 63789dc1..2ba3f3b3 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss_continue.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss_continue.go @@ -31,12 +31,11 @@ func (a *AuthenticationGSSContinue) Decode(src []byte) error { return nil } -func (a *AuthenticationGSSContinue) Encode(dst []byte) []byte { - dst = append(dst, 'R') - dst = pgio.AppendInt32(dst, int32(len(a.Data))+8) +func (a *AuthenticationGSSContinue) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'R') dst = pgio.AppendUint32(dst, AuthTypeGSSCont) dst = append(dst, a.Data...) - return dst + return finishMessage(dst, sp) } func (a *AuthenticationGSSContinue) MarshalJSON() ([]byte, error) { diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_md5_password.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_md5_password.go index 5671c84c..854c6404 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_md5_password.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_md5_password.go @@ -38,12 +38,11 @@ func (dst *AuthenticationMD5Password) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *AuthenticationMD5Password) Encode(dst []byte) []byte { - dst = append(dst, 'R') - dst = pgio.AppendInt32(dst, 12) +func (src *AuthenticationMD5Password) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'R') dst = pgio.AppendUint32(dst, AuthTypeMD5Password) dst = append(dst, src.Salt[:]...) - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_ok.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_ok.go index 88d648ae..ec11d39f 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_ok.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_ok.go @@ -35,11 +35,10 @@ func (dst *AuthenticationOk) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *AuthenticationOk) Encode(dst []byte) []byte { - dst = append(dst, 'R') - dst = pgio.AppendInt32(dst, 8) +func (src *AuthenticationOk) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'R') dst = pgio.AppendUint32(dst, AuthTypeOk) - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl.go index 59650d4c..e66580f4 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl.go @@ -47,10 +47,8 @@ func (dst *AuthenticationSASL) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *AuthenticationSASL) Encode(dst []byte) []byte { - dst = append(dst, 'R') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) +func (src *AuthenticationSASL) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'R') dst = pgio.AppendUint32(dst, AuthTypeSASL) for _, s := range src.AuthMechanisms { @@ -59,9 +57,7 @@ func (src *AuthenticationSASL) Encode(dst []byte) []byte { } dst = append(dst, 0) - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_continue.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_continue.go index 2ce70a47..70fba4a6 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_continue.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_continue.go @@ -38,17 +38,11 @@ func (dst *AuthenticationSASLContinue) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *AuthenticationSASLContinue) Encode(dst []byte) []byte { - dst = append(dst, 'R') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) +func (src *AuthenticationSASLContinue) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'R') dst = pgio.AppendUint32(dst, AuthTypeSASLContinue) - dst = append(dst, src.Data...) - - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_final.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_final.go index a38a8b91..84976c2a 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_final.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_final.go @@ -38,17 +38,11 @@ func (dst *AuthenticationSASLFinal) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *AuthenticationSASLFinal) Encode(dst []byte) []byte { - dst = append(dst, 'R') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) +func (src *AuthenticationSASLFinal) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'R') dst = pgio.AppendUint32(dst, AuthTypeSASLFinal) - dst = append(dst, src.Data...) - - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Unmarshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/backend.go b/vendor/github.com/jackc/pgx/v5/pgproto3/backend.go index 6db77e4a..d146c338 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/backend.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/backend.go @@ -16,7 +16,8 @@ type Backend struct { // before it is actually transmitted (i.e. before Flush). tracer *tracer - wbuf []byte + wbuf []byte + encodeError error // Frontend message flyweights bind Bind @@ -38,6 +39,7 @@ type Backend struct { terminate Terminate bodyLen int + maxBodyLen int // maxBodyLen is the maximum length of a message body in octets. If a message body exceeds this length, Receive will return an error. msgType byte partialMsg bool authType uint32 @@ -54,11 +56,21 @@ func NewBackend(r io.Reader, w io.Writer) *Backend { return &Backend{cr: cr, w: w} } -// Send sends a message to the frontend (i.e. the client). The message is not guaranteed to be written until Flush is -// called. +// Send sends a message to the frontend (i.e. the client). The message is buffered until Flush is called. Any error +// encountered will be returned from Flush. func (b *Backend) Send(msg BackendMessage) { + if b.encodeError != nil { + return + } + prevLen := len(b.wbuf) - b.wbuf = msg.Encode(b.wbuf) + newBuf, err := msg.Encode(b.wbuf) + if err != nil { + b.encodeError = err + return + } + b.wbuf = newBuf + if b.tracer != nil { b.tracer.traceMessage('B', int32(len(b.wbuf)-prevLen), msg) } @@ -66,6 +78,12 @@ func (b *Backend) Send(msg BackendMessage) { // Flush writes any pending messages to the frontend (i.e. the client). func (b *Backend) Flush() error { + if err := b.encodeError; err != nil { + b.encodeError = nil + b.wbuf = b.wbuf[:0] + return &writeError{err: err, safeToRetry: true} + } + n, err := b.w.Write(b.wbuf) const maxLen = 1024 @@ -158,6 +176,9 @@ func (b *Backend) Receive() (FrontendMessage, error) { b.msgType = header[0] b.bodyLen = int(binary.BigEndian.Uint32(header[1:])) - 4 + if b.maxBodyLen > 0 && b.bodyLen > b.maxBodyLen { + return nil, &ExceededMaxBodyLenErr{b.maxBodyLen, b.bodyLen} + } b.partialMsg = true } @@ -260,3 +281,12 @@ func (b *Backend) SetAuthType(authType uint32) error { return nil } + +// SetMaxBodyLen sets the maximum length of a message body in octets. If a message body exceeds this length, Receive will return +// an error. This is useful for protecting against malicious clients that send large messages with the intent of +// causing memory exhaustion. +// The default value is 0. +// If maxBodyLen is 0, then no maximum is enforced. +func (b *Backend) SetMaxBodyLen(maxBodyLen int) { + b.maxBodyLen = maxBodyLen +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/backend_key_data.go b/vendor/github.com/jackc/pgx/v5/pgproto3/backend_key_data.go index 12c60817..23f5da67 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/backend_key_data.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/backend_key_data.go @@ -29,12 +29,11 @@ func (dst *BackendKeyData) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *BackendKeyData) Encode(dst []byte) []byte { - dst = append(dst, 'K') - dst = pgio.AppendUint32(dst, 12) +func (src *BackendKeyData) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'K') dst = pgio.AppendUint32(dst, src.ProcessID) dst = pgio.AppendUint32(dst, src.SecretKey) - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/bind.go b/vendor/github.com/jackc/pgx/v5/pgproto3/bind.go index fdd2d3b8..ad6ac48b 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/bind.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/bind.go @@ -5,7 +5,9 @@ import ( "encoding/binary" "encoding/hex" "encoding/json" + "errors" "fmt" + "math" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -108,21 +110,25 @@ func (dst *Bind) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Bind) Encode(dst []byte) []byte { - dst = append(dst, 'B') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) +func (src *Bind) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'B') dst = append(dst, src.DestinationPortal...) dst = append(dst, 0) dst = append(dst, src.PreparedStatement...) dst = append(dst, 0) + if len(src.ParameterFormatCodes) > math.MaxUint16 { + return nil, errors.New("too many parameter format codes") + } dst = pgio.AppendUint16(dst, uint16(len(src.ParameterFormatCodes))) for _, fc := range src.ParameterFormatCodes { dst = pgio.AppendInt16(dst, fc) } + if len(src.Parameters) > math.MaxUint16 { + return nil, errors.New("too many parameters") + } dst = pgio.AppendUint16(dst, uint16(len(src.Parameters))) for _, p := range src.Parameters { if p == nil { @@ -134,14 +140,15 @@ func (src *Bind) Encode(dst []byte) []byte { dst = append(dst, p...) } + if len(src.ResultFormatCodes) > math.MaxUint16 { + return nil, errors.New("too many result format codes") + } dst = pgio.AppendUint16(dst, uint16(len(src.ResultFormatCodes))) for _, fc := range src.ResultFormatCodes { dst = pgio.AppendInt16(dst, fc) } - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/bind_complete.go b/vendor/github.com/jackc/pgx/v5/pgproto3/bind_complete.go index 3be256c8..bacf30d8 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/bind_complete.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/bind_complete.go @@ -20,8 +20,8 @@ func (dst *BindComplete) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *BindComplete) Encode(dst []byte) []byte { - return append(dst, '2', 0, 0, 0, 4) +func (src *BindComplete) Encode(dst []byte) ([]byte, error) { + return append(dst, '2', 0, 0, 0, 4), nil } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/cancel_request.go b/vendor/github.com/jackc/pgx/v5/pgproto3/cancel_request.go index 8fcf8217..6b52dd97 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/cancel_request.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/cancel_request.go @@ -36,12 +36,12 @@ func (dst *CancelRequest) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 4 byte message length. -func (src *CancelRequest) Encode(dst []byte) []byte { +func (src *CancelRequest) Encode(dst []byte) ([]byte, error) { dst = pgio.AppendInt32(dst, 16) dst = pgio.AppendInt32(dst, cancelRequestCode) dst = pgio.AppendUint32(dst, src.ProcessID) dst = pgio.AppendUint32(dst, src.SecretKey) - return dst + return dst, nil } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/close.go b/vendor/github.com/jackc/pgx/v5/pgproto3/close.go index f99b5943..0b50f27c 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/close.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/close.go @@ -4,8 +4,6 @@ import ( "bytes" "encoding/json" "errors" - - "github.com/jackc/pgx/v5/internal/pgio" ) type Close struct { @@ -37,18 +35,12 @@ func (dst *Close) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Close) Encode(dst []byte) []byte { - dst = append(dst, 'C') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) - +func (src *Close) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'C') dst = append(dst, src.ObjectType) dst = append(dst, src.Name...) dst = append(dst, 0) - - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/close_complete.go b/vendor/github.com/jackc/pgx/v5/pgproto3/close_complete.go index 1d7b8f08..833f7a12 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/close_complete.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/close_complete.go @@ -20,8 +20,8 @@ func (dst *CloseComplete) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CloseComplete) Encode(dst []byte) []byte { - return append(dst, '3', 0, 0, 0, 4) +func (src *CloseComplete) Encode(dst []byte) ([]byte, error) { + return append(dst, '3', 0, 0, 0, 4), nil } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/command_complete.go b/vendor/github.com/jackc/pgx/v5/pgproto3/command_complete.go index 814027ca..eba70947 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/command_complete.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/command_complete.go @@ -3,8 +3,6 @@ package pgproto3 import ( "bytes" "encoding/json" - - "github.com/jackc/pgx/v5/internal/pgio" ) type CommandComplete struct { @@ -31,17 +29,11 @@ func (dst *CommandComplete) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CommandComplete) Encode(dst []byte) []byte { - dst = append(dst, 'C') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) - +func (src *CommandComplete) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'C') dst = append(dst, src.CommandTag...) dst = append(dst, 0) - - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_both_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_both_response.go index 8840a89e..99e1afea 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_both_response.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_both_response.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "encoding/json" "errors" + "math" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -44,19 +45,18 @@ func (dst *CopyBothResponse) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CopyBothResponse) Encode(dst []byte) []byte { - dst = append(dst, 'W') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) +func (src *CopyBothResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'W') dst = append(dst, src.OverallFormat) + if len(src.ColumnFormatCodes) > math.MaxUint16 { + return nil, errors.New("too many column format codes") + } dst = pgio.AppendUint16(dst, uint16(len(src.ColumnFormatCodes))) for _, fc := range src.ColumnFormatCodes { dst = pgio.AppendUint16(dst, fc) } - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_data.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_data.go index 59e3dd94..89ecdd4d 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_data.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_data.go @@ -3,8 +3,6 @@ package pgproto3 import ( "encoding/hex" "encoding/json" - - "github.com/jackc/pgx/v5/internal/pgio" ) type CopyData struct { @@ -25,11 +23,10 @@ func (dst *CopyData) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CopyData) Encode(dst []byte) []byte { - dst = append(dst, 'd') - dst = pgio.AppendInt32(dst, int32(4+len(src.Data))) +func (src *CopyData) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'd') dst = append(dst, src.Data...) - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_done.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_done.go index 0e13282b..040814db 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_done.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_done.go @@ -24,8 +24,8 @@ func (dst *CopyDone) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CopyDone) Encode(dst []byte) []byte { - return append(dst, 'c', 0, 0, 0, 4) +func (src *CopyDone) Encode(dst []byte) ([]byte, error) { + return append(dst, 'c', 0, 0, 0, 4), nil } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_fail.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_fail.go index 0041bbb1..72a85fd0 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_fail.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_fail.go @@ -3,8 +3,6 @@ package pgproto3 import ( "bytes" "encoding/json" - - "github.com/jackc/pgx/v5/internal/pgio" ) type CopyFail struct { @@ -28,17 +26,11 @@ func (dst *CopyFail) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CopyFail) Encode(dst []byte) []byte { - dst = append(dst, 'f') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) - +func (src *CopyFail) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'f') dst = append(dst, src.Message...) dst = append(dst, 0) - - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_in_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_in_response.go index 4584f7df..06cf99ce 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_in_response.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_in_response.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "encoding/json" "errors" + "math" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -44,20 +45,19 @@ func (dst *CopyInResponse) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CopyInResponse) Encode(dst []byte) []byte { - dst = append(dst, 'G') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) +func (src *CopyInResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'G') dst = append(dst, src.OverallFormat) + if len(src.ColumnFormatCodes) > math.MaxUint16 { + return nil, errors.New("too many column format codes") + } dst = pgio.AppendUint16(dst, uint16(len(src.ColumnFormatCodes))) for _, fc := range src.ColumnFormatCodes { dst = pgio.AppendUint16(dst, fc) } - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_out_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_out_response.go index 3175c6a4..549e916c 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_out_response.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_out_response.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "encoding/json" "errors" + "math" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -43,21 +44,20 @@ func (dst *CopyOutResponse) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CopyOutResponse) Encode(dst []byte) []byte { - dst = append(dst, 'H') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) +func (src *CopyOutResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'H') dst = append(dst, src.OverallFormat) + if len(src.ColumnFormatCodes) > math.MaxUint16 { + return nil, errors.New("too many column format codes") + } dst = pgio.AppendUint16(dst, uint16(len(src.ColumnFormatCodes))) for _, fc := range src.ColumnFormatCodes { dst = pgio.AppendUint16(dst, fc) } - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/data_row.go b/vendor/github.com/jackc/pgx/v5/pgproto3/data_row.go index 4de77977..fdfb0f7f 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/data_row.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/data_row.go @@ -4,6 +4,8 @@ import ( "encoding/binary" "encoding/hex" "encoding/json" + "errors" + "math" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -63,11 +65,12 @@ func (dst *DataRow) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *DataRow) Encode(dst []byte) []byte { - dst = append(dst, 'D') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) +func (src *DataRow) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'D') + if len(src.Values) > math.MaxUint16 { + return nil, errors.New("too many values") + } dst = pgio.AppendUint16(dst, uint16(len(src.Values))) for _, v := range src.Values { if v == nil { @@ -79,9 +82,7 @@ func (src *DataRow) Encode(dst []byte) []byte { dst = append(dst, v...) } - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/describe.go b/vendor/github.com/jackc/pgx/v5/pgproto3/describe.go index f131d1f4..89feff21 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/describe.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/describe.go @@ -4,8 +4,6 @@ import ( "bytes" "encoding/json" "errors" - - "github.com/jackc/pgx/v5/internal/pgio" ) type Describe struct { @@ -37,18 +35,12 @@ func (dst *Describe) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Describe) Encode(dst []byte) []byte { - dst = append(dst, 'D') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) - +func (src *Describe) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'D') dst = append(dst, src.ObjectType) dst = append(dst, src.Name...) dst = append(dst, 0) - - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/empty_query_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/empty_query_response.go index 2b85e744..cb6cca07 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/empty_query_response.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/empty_query_response.go @@ -20,8 +20,8 @@ func (dst *EmptyQueryResponse) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *EmptyQueryResponse) Encode(dst []byte) []byte { - return append(dst, 'I', 0, 0, 0, 4) +func (src *EmptyQueryResponse) Encode(dst []byte) ([]byte, error) { + return append(dst, 'I', 0, 0, 0, 4), nil } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/error_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/error_response.go index 45c9a981..6ef9bd06 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/error_response.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/error_response.go @@ -2,7 +2,6 @@ package pgproto3 import ( "bytes" - "encoding/binary" "encoding/json" "strconv" ) @@ -111,119 +110,113 @@ func (dst *ErrorResponse) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *ErrorResponse) Encode(dst []byte) []byte { - return append(dst, src.marshalBinary('E')...) +func (src *ErrorResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'E') + dst = src.appendFields(dst) + return finishMessage(dst, sp) } -func (src *ErrorResponse) marshalBinary(typeByte byte) []byte { - var bigEndian BigEndianBuf - buf := &bytes.Buffer{} - - buf.WriteByte(typeByte) - buf.Write(bigEndian.Uint32(0)) - +func (src *ErrorResponse) appendFields(dst []byte) []byte { if src.Severity != "" { - buf.WriteByte('S') - buf.WriteString(src.Severity) - buf.WriteByte(0) + dst = append(dst, 'S') + dst = append(dst, src.Severity...) + dst = append(dst, 0) } if src.SeverityUnlocalized != "" { - buf.WriteByte('V') - buf.WriteString(src.SeverityUnlocalized) - buf.WriteByte(0) + dst = append(dst, 'V') + dst = append(dst, src.SeverityUnlocalized...) + dst = append(dst, 0) } if src.Code != "" { - buf.WriteByte('C') - buf.WriteString(src.Code) - buf.WriteByte(0) + dst = append(dst, 'C') + dst = append(dst, src.Code...) + dst = append(dst, 0) } if src.Message != "" { - buf.WriteByte('M') - buf.WriteString(src.Message) - buf.WriteByte(0) + dst = append(dst, 'M') + dst = append(dst, src.Message...) + dst = append(dst, 0) } if src.Detail != "" { - buf.WriteByte('D') - buf.WriteString(src.Detail) - buf.WriteByte(0) + dst = append(dst, 'D') + dst = append(dst, src.Detail...) + dst = append(dst, 0) } if src.Hint != "" { - buf.WriteByte('H') - buf.WriteString(src.Hint) - buf.WriteByte(0) + dst = append(dst, 'H') + dst = append(dst, src.Hint...) + dst = append(dst, 0) } if src.Position != 0 { - buf.WriteByte('P') - buf.WriteString(strconv.Itoa(int(src.Position))) - buf.WriteByte(0) + dst = append(dst, 'P') + dst = append(dst, strconv.Itoa(int(src.Position))...) + dst = append(dst, 0) } if src.InternalPosition != 0 { - buf.WriteByte('p') - buf.WriteString(strconv.Itoa(int(src.InternalPosition))) - buf.WriteByte(0) + dst = append(dst, 'p') + dst = append(dst, strconv.Itoa(int(src.InternalPosition))...) + dst = append(dst, 0) } if src.InternalQuery != "" { - buf.WriteByte('q') - buf.WriteString(src.InternalQuery) - buf.WriteByte(0) + dst = append(dst, 'q') + dst = append(dst, src.InternalQuery...) + dst = append(dst, 0) } if src.Where != "" { - buf.WriteByte('W') - buf.WriteString(src.Where) - buf.WriteByte(0) + dst = append(dst, 'W') + dst = append(dst, src.Where...) + dst = append(dst, 0) } if src.SchemaName != "" { - buf.WriteByte('s') - buf.WriteString(src.SchemaName) - buf.WriteByte(0) + dst = append(dst, 's') + dst = append(dst, src.SchemaName...) + dst = append(dst, 0) } if src.TableName != "" { - buf.WriteByte('t') - buf.WriteString(src.TableName) - buf.WriteByte(0) + dst = append(dst, 't') + dst = append(dst, src.TableName...) + dst = append(dst, 0) } if src.ColumnName != "" { - buf.WriteByte('c') - buf.WriteString(src.ColumnName) - buf.WriteByte(0) + dst = append(dst, 'c') + dst = append(dst, src.ColumnName...) + dst = append(dst, 0) } if src.DataTypeName != "" { - buf.WriteByte('d') - buf.WriteString(src.DataTypeName) - buf.WriteByte(0) + dst = append(dst, 'd') + dst = append(dst, src.DataTypeName...) + dst = append(dst, 0) } if src.ConstraintName != "" { - buf.WriteByte('n') - buf.WriteString(src.ConstraintName) - buf.WriteByte(0) + dst = append(dst, 'n') + dst = append(dst, src.ConstraintName...) + dst = append(dst, 0) } if src.File != "" { - buf.WriteByte('F') - buf.WriteString(src.File) - buf.WriteByte(0) + dst = append(dst, 'F') + dst = append(dst, src.File...) + dst = append(dst, 0) } if src.Line != 0 { - buf.WriteByte('L') - buf.WriteString(strconv.Itoa(int(src.Line))) - buf.WriteByte(0) + dst = append(dst, 'L') + dst = append(dst, strconv.Itoa(int(src.Line))...) + dst = append(dst, 0) } if src.Routine != "" { - buf.WriteByte('R') - buf.WriteString(src.Routine) - buf.WriteByte(0) + dst = append(dst, 'R') + dst = append(dst, src.Routine...) + dst = append(dst, 0) } for k, v := range src.UnknownFields { - buf.WriteByte(k) - buf.WriteString(v) - buf.WriteByte(0) + dst = append(dst, k) + dst = append(dst, v...) + dst = append(dst, 0) } - buf.WriteByte(0) - - binary.BigEndian.PutUint32(buf.Bytes()[1:5], uint32(buf.Len()-1)) + dst = append(dst, 0) - return buf.Bytes() + return dst } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/execute.go b/vendor/github.com/jackc/pgx/v5/pgproto3/execute.go index a5fee7cb..31bc714d 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/execute.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/execute.go @@ -36,19 +36,12 @@ func (dst *Execute) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Execute) Encode(dst []byte) []byte { - dst = append(dst, 'E') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) - +func (src *Execute) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'E') dst = append(dst, src.Portal...) dst = append(dst, 0) - dst = pgio.AppendUint32(dst, src.MaxRows) - - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/flush.go b/vendor/github.com/jackc/pgx/v5/pgproto3/flush.go index 2725f689..e5dc1fbb 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/flush.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/flush.go @@ -20,8 +20,8 @@ func (dst *Flush) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Flush) Encode(dst []byte) []byte { - return append(dst, 'H', 0, 0, 0, 4) +func (src *Flush) Encode(dst []byte) ([]byte, error) { + return append(dst, 'H', 0, 0, 0, 4), nil } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/frontend.go b/vendor/github.com/jackc/pgx/v5/pgproto3/frontend.go index 60c34ef0..b41abbe1 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/frontend.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/frontend.go @@ -18,7 +18,8 @@ type Frontend struct { // idle. Setting and unsetting tracer provides equivalent functionality to PQtrace and PQuntrace in libpq. tracer *tracer - wbuf []byte + wbuf []byte + encodeError error // Backend message flyweights authenticationOk AuthenticationOk @@ -64,16 +65,26 @@ func NewFrontend(r io.Reader, w io.Writer) *Frontend { return &Frontend{cr: cr, w: w} } -// Send sends a message to the backend (i.e. the server). The message is not guaranteed to be written until Flush is -// called. +// Send sends a message to the backend (i.e. the server). The message is buffered until Flush is called. Any error +// encountered will be returned from Flush. // // Send can work with any FrontendMessage. Some commonly used message types such as Bind have specialized send methods // such as SendBind. These methods should be preferred when the type of message is known up front (e.g. when building an // extended query protocol query) as they may be faster due to knowing the type of msg rather than it being hidden // behind an interface. func (f *Frontend) Send(msg FrontendMessage) { + if f.encodeError != nil { + return + } + prevLen := len(f.wbuf) - f.wbuf = msg.Encode(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + if f.tracer != nil { f.tracer.traceMessage('F', int32(len(f.wbuf)-prevLen), msg) } @@ -81,6 +92,12 @@ func (f *Frontend) Send(msg FrontendMessage) { // Flush writes any pending messages to the backend (i.e. the server). func (f *Frontend) Flush() error { + if err := f.encodeError; err != nil { + f.encodeError = nil + f.wbuf = f.wbuf[:0] + return &writeError{err: err, safeToRetry: true} + } + if len(f.wbuf) == 0 { return nil } @@ -116,71 +133,141 @@ func (f *Frontend) Untrace() { f.tracer = nil } -// SendBind sends a Bind message to the backend (i.e. the server). The message is not guaranteed to be written until -// Flush is called. +// SendBind sends a Bind message to the backend (i.e. the server). The message is buffered until Flush is called. Any +// error encountered will be returned from Flush. func (f *Frontend) SendBind(msg *Bind) { + if f.encodeError != nil { + return + } + prevLen := len(f.wbuf) - f.wbuf = msg.Encode(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + if f.tracer != nil { f.tracer.traceBind('F', int32(len(f.wbuf)-prevLen), msg) } } -// SendParse sends a Parse message to the backend (i.e. the server). The message is not guaranteed to be written until -// Flush is called. +// SendParse sends a Parse message to the backend (i.e. the server). The message is buffered until Flush is called. Any +// error encountered will be returned from Flush. func (f *Frontend) SendParse(msg *Parse) { + if f.encodeError != nil { + return + } + prevLen := len(f.wbuf) - f.wbuf = msg.Encode(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + if f.tracer != nil { f.tracer.traceParse('F', int32(len(f.wbuf)-prevLen), msg) } } -// SendClose sends a Close message to the backend (i.e. the server). The message is not guaranteed to be written until -// Flush is called. +// SendClose sends a Close message to the backend (i.e. the server). The message is buffered until Flush is called. Any +// error encountered will be returned from Flush. func (f *Frontend) SendClose(msg *Close) { + if f.encodeError != nil { + return + } + prevLen := len(f.wbuf) - f.wbuf = msg.Encode(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + if f.tracer != nil { f.tracer.traceClose('F', int32(len(f.wbuf)-prevLen), msg) } } -// SendDescribe sends a Describe message to the backend (i.e. the server). The message is not guaranteed to be written until -// Flush is called. +// SendDescribe sends a Describe message to the backend (i.e. the server). The message is buffered until Flush is +// called. Any error encountered will be returned from Flush. func (f *Frontend) SendDescribe(msg *Describe) { + if f.encodeError != nil { + return + } + prevLen := len(f.wbuf) - f.wbuf = msg.Encode(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + if f.tracer != nil { f.tracer.traceDescribe('F', int32(len(f.wbuf)-prevLen), msg) } } -// SendExecute sends an Execute message to the backend (i.e. the server). The message is not guaranteed to be written until -// Flush is called. +// SendExecute sends an Execute message to the backend (i.e. the server). The message is buffered until Flush is called. +// Any error encountered will be returned from Flush. func (f *Frontend) SendExecute(msg *Execute) { + if f.encodeError != nil { + return + } + prevLen := len(f.wbuf) - f.wbuf = msg.Encode(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + if f.tracer != nil { f.tracer.TraceQueryute('F', int32(len(f.wbuf)-prevLen), msg) } } -// SendSync sends a Sync message to the backend (i.e. the server). The message is not guaranteed to be written until -// Flush is called. +// SendSync sends a Sync message to the backend (i.e. the server). The message is buffered until Flush is called. Any +// error encountered will be returned from Flush. func (f *Frontend) SendSync(msg *Sync) { + if f.encodeError != nil { + return + } + prevLen := len(f.wbuf) - f.wbuf = msg.Encode(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + if f.tracer != nil { f.tracer.traceSync('F', int32(len(f.wbuf)-prevLen), msg) } } -// SendQuery sends a Query message to the backend (i.e. the server). The message is not guaranteed to be written until -// Flush is called. +// SendQuery sends a Query message to the backend (i.e. the server). The message is buffered until Flush is called. Any +// error encountered will be returned from Flush. func (f *Frontend) SendQuery(msg *Query) { + if f.encodeError != nil { + return + } + prevLen := len(f.wbuf) - f.wbuf = msg.Encode(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + if f.tracer != nil { f.tracer.traceQuery('F', int32(len(f.wbuf)-prevLen), msg) } diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/function_call.go b/vendor/github.com/jackc/pgx/v5/pgproto3/function_call.go index 2c4f38df..7d83579f 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/function_call.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/function_call.go @@ -2,6 +2,8 @@ package pgproto3 import ( "encoding/binary" + "errors" + "math" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -71,15 +73,21 @@ func (dst *FunctionCall) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *FunctionCall) Encode(dst []byte) []byte { - dst = append(dst, 'F') - sp := len(dst) - dst = pgio.AppendUint32(dst, 0) // Unknown length, set it at the end +func (src *FunctionCall) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'F') dst = pgio.AppendUint32(dst, src.Function) + + if len(src.ArgFormatCodes) > math.MaxUint16 { + return nil, errors.New("too many arg format codes") + } dst = pgio.AppendUint16(dst, uint16(len(src.ArgFormatCodes))) for _, argFormatCode := range src.ArgFormatCodes { dst = pgio.AppendUint16(dst, argFormatCode) } + + if len(src.Arguments) > math.MaxUint16 { + return nil, errors.New("too many arguments") + } dst = pgio.AppendUint16(dst, uint16(len(src.Arguments))) for _, argument := range src.Arguments { if argument == nil { @@ -90,6 +98,5 @@ func (src *FunctionCall) Encode(dst []byte) []byte { } } dst = pgio.AppendUint16(dst, src.ResultFormatCode) - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - return dst + return finishMessage(dst, sp) } diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/function_call_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/function_call_response.go index 3d3606dd..1f273495 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/function_call_response.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/function_call_response.go @@ -39,10 +39,8 @@ func (dst *FunctionCallResponse) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *FunctionCallResponse) Encode(dst []byte) []byte { - dst = append(dst, 'V') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) +func (src *FunctionCallResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'V') if src.Result == nil { dst = pgio.AppendInt32(dst, -1) @@ -51,9 +49,7 @@ func (src *FunctionCallResponse) Encode(dst []byte) []byte { dst = append(dst, src.Result...) } - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/gss_enc_request.go b/vendor/github.com/jackc/pgx/v5/pgproto3/gss_enc_request.go index 30ffc08d..70cb20cd 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/gss_enc_request.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/gss_enc_request.go @@ -31,10 +31,10 @@ func (dst *GSSEncRequest) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 4 byte message length. -func (src *GSSEncRequest) Encode(dst []byte) []byte { +func (src *GSSEncRequest) Encode(dst []byte) ([]byte, error) { dst = pgio.AppendInt32(dst, 8) dst = pgio.AppendInt32(dst, gssEncReqNumber) - return dst + return dst, nil } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/gss_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/gss_response.go index 64bfbd04..10d93775 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/gss_response.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/gss_response.go @@ -2,8 +2,6 @@ package pgproto3 import ( "encoding/json" - - "github.com/jackc/pgx/v5/internal/pgio" ) type GSSResponse struct { @@ -18,11 +16,10 @@ func (g *GSSResponse) Decode(data []byte) error { return nil } -func (g *GSSResponse) Encode(dst []byte) []byte { - dst = append(dst, 'p') - dst = pgio.AppendInt32(dst, int32(4+len(g.Data))) +func (g *GSSResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'p') dst = append(dst, g.Data...) - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/no_data.go b/vendor/github.com/jackc/pgx/v5/pgproto3/no_data.go index d8f85d38..cbcaad40 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/no_data.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/no_data.go @@ -20,8 +20,8 @@ func (dst *NoData) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *NoData) Encode(dst []byte) []byte { - return append(dst, 'n', 0, 0, 0, 4) +func (src *NoData) Encode(dst []byte) ([]byte, error) { + return append(dst, 'n', 0, 0, 0, 4), nil } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/notice_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/notice_response.go index 4ac28a79..497aba6d 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/notice_response.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/notice_response.go @@ -12,6 +12,8 @@ func (dst *NoticeResponse) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *NoticeResponse) Encode(dst []byte) []byte { - return append(dst, (*ErrorResponse)(src).marshalBinary('N')...) +func (src *NoticeResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'N') + dst = (*ErrorResponse)(src).appendFields(dst) + return finishMessage(dst, sp) } diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/notification_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/notification_response.go index 228e0dac..243b6bf7 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/notification_response.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/notification_response.go @@ -45,20 +45,14 @@ func (dst *NotificationResponse) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *NotificationResponse) Encode(dst []byte) []byte { - dst = append(dst, 'A') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) - +func (src *NotificationResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'A') dst = pgio.AppendUint32(dst, src.PID) dst = append(dst, src.Channel...) dst = append(dst, 0) dst = append(dst, src.Payload...) dst = append(dst, 0) - - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_description.go b/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_description.go index 374d38a3..1ef27b75 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_description.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_description.go @@ -4,6 +4,8 @@ import ( "bytes" "encoding/binary" "encoding/json" + "errors" + "math" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -39,19 +41,18 @@ func (dst *ParameterDescription) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *ParameterDescription) Encode(dst []byte) []byte { - dst = append(dst, 't') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) +func (src *ParameterDescription) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 't') + if len(src.ParameterOIDs) > math.MaxUint16 { + return nil, errors.New("too many parameter oids") + } dst = pgio.AppendUint16(dst, uint16(len(src.ParameterOIDs))) for _, oid := range src.ParameterOIDs { dst = pgio.AppendUint32(dst, oid) } - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_status.go b/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_status.go index a303e453..9ee0720b 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_status.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_status.go @@ -3,8 +3,6 @@ package pgproto3 import ( "bytes" "encoding/json" - - "github.com/jackc/pgx/v5/internal/pgio" ) type ParameterStatus struct { @@ -37,19 +35,13 @@ func (dst *ParameterStatus) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *ParameterStatus) Encode(dst []byte) []byte { - dst = append(dst, 'S') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) - +func (src *ParameterStatus) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'S') dst = append(dst, src.Name...) dst = append(dst, 0) dst = append(dst, src.Value...) dst = append(dst, 0) - - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/parse.go b/vendor/github.com/jackc/pgx/v5/pgproto3/parse.go index b53200dc..6ba3486c 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/parse.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/parse.go @@ -4,6 +4,8 @@ import ( "bytes" "encoding/binary" "encoding/json" + "errors" + "math" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -52,24 +54,23 @@ func (dst *Parse) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Parse) Encode(dst []byte) []byte { - dst = append(dst, 'P') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) +func (src *Parse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'P') dst = append(dst, src.Name...) dst = append(dst, 0) dst = append(dst, src.Query...) dst = append(dst, 0) + if len(src.ParameterOIDs) > math.MaxUint16 { + return nil, errors.New("too many parameter oids") + } dst = pgio.AppendUint16(dst, uint16(len(src.ParameterOIDs))) for _, oid := range src.ParameterOIDs { dst = pgio.AppendUint32(dst, oid) } - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/parse_complete.go b/vendor/github.com/jackc/pgx/v5/pgproto3/parse_complete.go index 92c9498b..cff9e27d 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/parse_complete.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/parse_complete.go @@ -20,8 +20,8 @@ func (dst *ParseComplete) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *ParseComplete) Encode(dst []byte) []byte { - return append(dst, '1', 0, 0, 0, 4) +func (src *ParseComplete) Encode(dst []byte) ([]byte, error) { + return append(dst, '1', 0, 0, 0, 4), nil } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/password_message.go b/vendor/github.com/jackc/pgx/v5/pgproto3/password_message.go index 41f98692..d820d327 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/password_message.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/password_message.go @@ -3,8 +3,6 @@ package pgproto3 import ( "bytes" "encoding/json" - - "github.com/jackc/pgx/v5/internal/pgio" ) type PasswordMessage struct { @@ -32,14 +30,11 @@ func (dst *PasswordMessage) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *PasswordMessage) Encode(dst []byte) []byte { - dst = append(dst, 'p') - dst = pgio.AppendInt32(dst, int32(4+len(src.Password)+1)) - +func (src *PasswordMessage) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'p') dst = append(dst, src.Password...) dst = append(dst, 0) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/pgproto3.go b/vendor/github.com/jackc/pgx/v5/pgproto3/pgproto3.go index ef5a5489..480abfc0 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/pgproto3.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/pgproto3.go @@ -4,8 +4,14 @@ import ( "encoding/hex" "errors" "fmt" + + "github.com/jackc/pgx/v5/internal/pgio" ) +// maxMessageBodyLen is the maximum length of a message body in bytes. See PG_LARGE_MESSAGE_LIMIT in the PostgreSQL +// source. It is defined as (MaxAllocSize - 1). MaxAllocSize is defined as 0x3fffffff. +const maxMessageBodyLen = (0x3fffffff - 1) + // Message is the interface implemented by an object that can decode and encode // a particular PostgreSQL message. type Message interface { @@ -14,7 +20,7 @@ type Message interface { Decode(data []byte) error // Encode appends itself to dst and returns the new buffer. - Encode(dst []byte) []byte + Encode(dst []byte) ([]byte, error) } // FrontendMessage is a message sent by the frontend (i.e. the client). @@ -70,6 +76,15 @@ func (e *writeError) Unwrap() error { return e.err } +type ExceededMaxBodyLenErr struct { + MaxExpectedBodyLen int + ActualBodyLen int +} + +func (e *ExceededMaxBodyLenErr) Error() string { + return fmt.Sprintf("invalid body length: expected at most %d, but got %d", e.MaxExpectedBodyLen, e.ActualBodyLen) +} + // getValueFromJSON gets the value from a protocol message representation in JSON. func getValueFromJSON(v map[string]string) ([]byte, error) { if v == nil { @@ -83,3 +98,23 @@ func getValueFromJSON(v map[string]string) ([]byte, error) { } return nil, errors.New("unknown protocol representation") } + +// beginMessage begines a new message of type t. It appends the message type and a placeholder for the message length to +// dst. It returns the new buffer and the position of the message length placeholder. +func beginMessage(dst []byte, t byte) ([]byte, int) { + dst = append(dst, t) + sp := len(dst) + dst = pgio.AppendInt32(dst, -1) + return dst, sp +} + +// finishMessage finishes a message that was started with beginMessage. It computes the message length and writes it to +// dst[sp]. If the message length is too large it returns an error. Otherwise it returns the final message buffer. +func finishMessage(dst []byte, sp int) ([]byte, error) { + messageBodyLen := len(dst[sp:]) + if messageBodyLen > maxMessageBodyLen { + return nil, errors.New("message body too large") + } + pgio.SetInt32(dst[sp:], int32(messageBodyLen)) + return dst, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/portal_suspended.go b/vendor/github.com/jackc/pgx/v5/pgproto3/portal_suspended.go index 1a9e7bfb..9e2f8cbc 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/portal_suspended.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/portal_suspended.go @@ -20,8 +20,8 @@ func (dst *PortalSuspended) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *PortalSuspended) Encode(dst []byte) []byte { - return append(dst, 's', 0, 0, 0, 4) +func (src *PortalSuspended) Encode(dst []byte) ([]byte, error) { + return append(dst, 's', 0, 0, 0, 4), nil } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/query.go b/vendor/github.com/jackc/pgx/v5/pgproto3/query.go index e963a0ec..aebdfde8 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/query.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/query.go @@ -3,8 +3,6 @@ package pgproto3 import ( "bytes" "encoding/json" - - "github.com/jackc/pgx/v5/internal/pgio" ) type Query struct { @@ -28,14 +26,11 @@ func (dst *Query) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Query) Encode(dst []byte) []byte { - dst = append(dst, 'Q') - dst = pgio.AppendInt32(dst, int32(4+len(src.String)+1)) - +func (src *Query) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'Q') dst = append(dst, src.String...) dst = append(dst, 0) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/ready_for_query.go b/vendor/github.com/jackc/pgx/v5/pgproto3/ready_for_query.go index 67a39be3..a56af9fb 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/ready_for_query.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/ready_for_query.go @@ -25,8 +25,8 @@ func (dst *ReadyForQuery) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *ReadyForQuery) Encode(dst []byte) []byte { - return append(dst, 'Z', 0, 0, 0, 5, src.TxStatus) +func (src *ReadyForQuery) Encode(dst []byte) ([]byte, error) { + return append(dst, 'Z', 0, 0, 0, 5, src.TxStatus), nil } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/row_description.go b/vendor/github.com/jackc/pgx/v5/pgproto3/row_description.go index 6f6f0681..dc2a4ddf 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/row_description.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/row_description.go @@ -4,6 +4,8 @@ import ( "bytes" "encoding/binary" "encoding/json" + "errors" + "math" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -99,11 +101,12 @@ func (dst *RowDescription) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *RowDescription) Encode(dst []byte) []byte { - dst = append(dst, 'T') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) +func (src *RowDescription) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'T') + if len(src.Fields) > math.MaxUint16 { + return nil, errors.New("too many fields") + } dst = pgio.AppendUint16(dst, uint16(len(src.Fields))) for _, fd := range src.Fields { dst = append(dst, fd.Name...) @@ -117,9 +120,7 @@ func (src *RowDescription) Encode(dst []byte) []byte { dst = pgio.AppendInt16(dst, fd.Format) } - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_initial_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_initial_response.go index eeda4691..9eb1b6a4 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_initial_response.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_initial_response.go @@ -39,10 +39,8 @@ func (dst *SASLInitialResponse) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *SASLInitialResponse) Encode(dst []byte) []byte { - dst = append(dst, 'p') - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) +func (src *SASLInitialResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'p') dst = append(dst, []byte(src.AuthMechanism)...) dst = append(dst, 0) @@ -50,9 +48,7 @@ func (src *SASLInitialResponse) Encode(dst []byte) []byte { dst = pgio.AppendInt32(dst, int32(len(src.Data))) dst = append(dst, src.Data...) - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_response.go index 54c3d96f..1b604c25 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_response.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_response.go @@ -3,8 +3,6 @@ package pgproto3 import ( "encoding/hex" "encoding/json" - - "github.com/jackc/pgx/v5/internal/pgio" ) type SASLResponse struct { @@ -22,13 +20,10 @@ func (dst *SASLResponse) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *SASLResponse) Encode(dst []byte) []byte { - dst = append(dst, 'p') - dst = pgio.AppendInt32(dst, int32(4+len(src.Data))) - +func (src *SASLResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'p') dst = append(dst, src.Data...) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/ssl_request.go b/vendor/github.com/jackc/pgx/v5/pgproto3/ssl_request.go index 1b00c16b..b0fc2847 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/ssl_request.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/ssl_request.go @@ -31,10 +31,10 @@ func (dst *SSLRequest) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 4 byte message length. -func (src *SSLRequest) Encode(dst []byte) []byte { +func (src *SSLRequest) Encode(dst []byte) ([]byte, error) { dst = pgio.AppendInt32(dst, 8) dst = pgio.AppendInt32(dst, sslRequestNumber) - return dst + return dst, nil } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go b/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go index 65de4a36..3af4587d 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go @@ -64,7 +64,7 @@ func (dst *StartupMessage) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *StartupMessage) Encode(dst []byte) []byte { +func (src *StartupMessage) Encode(dst []byte) ([]byte, error) { sp := len(dst) dst = pgio.AppendInt32(dst, -1) @@ -77,9 +77,7 @@ func (src *StartupMessage) Encode(dst []byte) []byte { } dst = append(dst, 0) - pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) - - return dst + return finishMessage(dst, sp) } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/sync.go b/vendor/github.com/jackc/pgx/v5/pgproto3/sync.go index 5db8e07a..ea4fc959 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/sync.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/sync.go @@ -20,8 +20,8 @@ func (dst *Sync) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Sync) Encode(dst []byte) []byte { - return append(dst, 'S', 0, 0, 0, 4) +func (src *Sync) Encode(dst []byte) ([]byte, error) { + return append(dst, 'S', 0, 0, 0, 4), nil } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/terminate.go b/vendor/github.com/jackc/pgx/v5/pgproto3/terminate.go index 135191ea..35a9dc83 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/terminate.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/terminate.go @@ -20,8 +20,8 @@ func (dst *Terminate) Decode(src []byte) error { } // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Terminate) Encode(dst []byte) []byte { - return append(dst, 'X', 0, 0, 0, 4) +func (src *Terminate) Encode(dst []byte) ([]byte, error) { + return append(dst, 'X', 0, 0, 0, 4), nil } // MarshalJSON implements encoding/json.Marshaler. diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/array.go b/vendor/github.com/jackc/pgx/v5/pgtype/array.go index 73761956..06b824ad 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/array.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/array.go @@ -110,7 +110,7 @@ func parseUntypedTextArray(src string) (*untypedTextArray, error) { r, _, err := buf.ReadRune() if err != nil { - return nil, fmt.Errorf("invalid array: %v", err) + return nil, fmt.Errorf("invalid array: %w", err) } var explicitDimensions []ArrayDimension @@ -122,7 +122,7 @@ func parseUntypedTextArray(src string) (*untypedTextArray, error) { for { r, _, err = buf.ReadRune() if err != nil { - return nil, fmt.Errorf("invalid array: %v", err) + return nil, fmt.Errorf("invalid array: %w", err) } if r == '=' { @@ -133,12 +133,12 @@ func parseUntypedTextArray(src string) (*untypedTextArray, error) { lower, err := arrayParseInteger(buf) if err != nil { - return nil, fmt.Errorf("invalid array: %v", err) + return nil, fmt.Errorf("invalid array: %w", err) } r, _, err = buf.ReadRune() if err != nil { - return nil, fmt.Errorf("invalid array: %v", err) + return nil, fmt.Errorf("invalid array: %w", err) } if r != ':' { @@ -147,12 +147,12 @@ func parseUntypedTextArray(src string) (*untypedTextArray, error) { upper, err := arrayParseInteger(buf) if err != nil { - return nil, fmt.Errorf("invalid array: %v", err) + return nil, fmt.Errorf("invalid array: %w", err) } r, _, err = buf.ReadRune() if err != nil { - return nil, fmt.Errorf("invalid array: %v", err) + return nil, fmt.Errorf("invalid array: %w", err) } if r != ']' { @@ -164,12 +164,12 @@ func parseUntypedTextArray(src string) (*untypedTextArray, error) { r, _, err = buf.ReadRune() if err != nil { - return nil, fmt.Errorf("invalid array: %v", err) + return nil, fmt.Errorf("invalid array: %w", err) } } if r != '{' { - return nil, fmt.Errorf("invalid array, expected '{': %v", err) + return nil, fmt.Errorf("invalid array, expected '{' got %v", r) } implicitDimensions := []ArrayDimension{{LowerBound: 1, Length: 0}} @@ -178,7 +178,7 @@ func parseUntypedTextArray(src string) (*untypedTextArray, error) { for { r, _, err = buf.ReadRune() if err != nil { - return nil, fmt.Errorf("invalid array: %v", err) + return nil, fmt.Errorf("invalid array: %w", err) } if r == '{' { @@ -195,7 +195,7 @@ func parseUntypedTextArray(src string) (*untypedTextArray, error) { for { r, _, err = buf.ReadRune() if err != nil { - return nil, fmt.Errorf("invalid array: %v", err) + return nil, fmt.Errorf("invalid array: %w", err) } switch r { @@ -214,7 +214,7 @@ func parseUntypedTextArray(src string) (*untypedTextArray, error) { buf.UnreadRune() value, quoted, err := arrayParseValue(buf) if err != nil { - return nil, fmt.Errorf("invalid array value: %v", err) + return nil, fmt.Errorf("invalid array value: %w", err) } if currentDim == counterDim { implicitDimensions[currentDim].Length++ diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/bits.go b/vendor/github.com/jackc/pgx/v5/pgtype/bits.go index 30558118..e7a1d016 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/bits.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/bits.go @@ -176,8 +176,10 @@ func (scanPlanBinaryBitsToBitsScanner) Scan(src []byte, dst any) error { bitLen := int32(binary.BigEndian.Uint32(src)) rp := 4 + buf := make([]byte, len(src[rp:])) + copy(buf, src[rp:]) - return scanner.ScanBits(Bits{Bytes: src[rp:], Len: bitLen, Valid: true}) + return scanner.ScanBits(Bits{Bytes: buf, Len: bitLen, Valid: true}) } type scanPlanTextAnyToBitsScanner struct{} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go b/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go index 8bf367c1..b39d3fa1 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go @@ -231,7 +231,7 @@ func (w *uint64Wrapper) ScanNumeric(v Numeric) error { bi, err := v.toBigInt() if err != nil { - return fmt.Errorf("cannot scan into *uint64: %v", err) + return fmt.Errorf("cannot scan into *uint64: %w", err) } if !bi.IsUint64() { @@ -284,7 +284,7 @@ func (w *uintWrapper) ScanNumeric(v Numeric) error { bi, err := v.toBigInt() if err != nil { - return fmt.Errorf("cannot scan into *uint: %v", err) + return fmt.Errorf("cannot scan into *uint: %w", err) } if !bi.IsUint64() { diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/date.go b/vendor/github.com/jackc/pgx/v5/pgtype/date.go index 009fc0db..784b16de 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/date.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/date.go @@ -282,17 +282,17 @@ func (scanPlanTextAnyToDateScanner) Scan(src []byte, dst any) error { if match != nil { year, err := strconv.ParseInt(match[1], 10, 32) if err != nil { - return fmt.Errorf("BUG: cannot parse date that regexp matched (year): %v", err) + return fmt.Errorf("BUG: cannot parse date that regexp matched (year): %w", err) } month, err := strconv.ParseInt(match[2], 10, 32) if err != nil { - return fmt.Errorf("BUG: cannot parse date that regexp matched (month): %v", err) + return fmt.Errorf("BUG: cannot parse date that regexp matched (month): %w", err) } day, err := strconv.ParseInt(match[3], 10, 32) if err != nil { - return fmt.Errorf("BUG: cannot parse date that regexp matched (month): %v", err) + return fmt.Errorf("BUG: cannot parse date that regexp matched (month): %w", err) } // BC matched diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/float4.go b/vendor/github.com/jackc/pgx/v5/pgtype/float4.go index 91ca0147..8646d9d2 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/float4.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/float4.go @@ -297,12 +297,12 @@ func (c Float4Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, sr return nil, nil } - var n float64 + var n float32 err := codecScan(c, m, oid, format, src, &n) if err != nil { return nil, err } - return n, nil + return float64(n), nil } func (c Float4Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/json.go b/vendor/github.com/jackc/pgx/v5/pgtype/json.go index d332dd0d..99628092 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/json.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/json.go @@ -25,18 +25,26 @@ func (c JSONCodec) PlanEncode(m *Map, oid uint32, format int16, value any) Encod case []byte: return encodePlanJSONCodecEitherFormatByteSlice{} - // Must come before trying wrap encode plans because a pointer to a struct may be unwrapped to a struct that can be - // marshalled. - // - // https://github.com/jackc/pgx/issues/1681 - case json.Marshaler: - return encodePlanJSONCodecEitherFormatMarshal{} + // Handle json.RawMessage specifically because if it is run through json.Marshal it may be mutated. + // e.g. `{"foo": "bar"}` -> `{"foo":"bar"}`. + case json.RawMessage: + return encodePlanJSONCodecEitherFormatJSONRawMessage{} // Cannot rely on driver.Valuer being handled later because anything can be marshalled. // // https://github.com/jackc/pgx/issues/1430 + // + // Check for driver.Valuer must come before json.Marshaler so that it is guaranteed to beused + // when both are implemented https://github.com/jackc/pgx/issues/1805 case driver.Valuer: return &encodePlanDriverValuer{m: m, oid: oid, formatCode: format} + + // Must come before trying wrap encode plans because a pointer to a struct may be unwrapped to a struct that can be + // marshalled. + // + // https://github.com/jackc/pgx/issues/1681 + case json.Marshaler: + return encodePlanJSONCodecEitherFormatMarshal{} } // Because anything can be marshalled the normal wrapping in Map.PlanScan doesn't get a chance to run. So try the @@ -76,6 +84,18 @@ func (encodePlanJSONCodecEitherFormatByteSlice) Encode(value any, buf []byte) (n return buf, nil } +type encodePlanJSONCodecEitherFormatJSONRawMessage struct{} + +func (encodePlanJSONCodecEitherFormatJSONRawMessage) Encode(value any, buf []byte) (newBuf []byte, err error) { + jsonBytes := value.(json.RawMessage) + if jsonBytes == nil { + return nil, nil + } + + buf = append(buf, jsonBytes...) + return buf, nil +} + type encodePlanJSONCodecEitherFormatMarshal struct{} func (encodePlanJSONCodecEitherFormatMarshal) Encode(value any, buf []byte) (newBuf []byte, err error) { diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go b/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go new file mode 100644 index 00000000..6af31779 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go @@ -0,0 +1,122 @@ +package pgtype + +import ( + "database/sql/driver" + "fmt" +) + +type LtreeCodec struct{} + +func (l LtreeCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +// PreferredFormat returns the preferred format. +func (l LtreeCodec) PreferredFormat() int16 { + return TextFormatCode +} + +// PlanEncode returns an EncodePlan for encoding value into PostgreSQL format for oid and format. If no plan can be +// found then nil is returned. +func (l LtreeCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case TextFormatCode: + return (TextCodec)(l).PlanEncode(m, oid, format, value) + case BinaryFormatCode: + switch value.(type) { + case string: + return encodeLtreeCodecBinaryString{} + case []byte: + return encodeLtreeCodecBinaryByteSlice{} + case TextValuer: + return encodeLtreeCodecBinaryTextValuer{} + } + } + + return nil +} + +type encodeLtreeCodecBinaryString struct{} + +func (encodeLtreeCodecBinaryString) Encode(value any, buf []byte) (newBuf []byte, err error) { + ltree := value.(string) + buf = append(buf, 1) + return append(buf, ltree...), nil +} + +type encodeLtreeCodecBinaryByteSlice struct{} + +func (encodeLtreeCodecBinaryByteSlice) Encode(value any, buf []byte) (newBuf []byte, err error) { + ltree := value.([]byte) + buf = append(buf, 1) + return append(buf, ltree...), nil +} + +type encodeLtreeCodecBinaryTextValuer struct{} + +func (encodeLtreeCodecBinaryTextValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + t, err := value.(TextValuer).TextValue() + if err != nil { + return nil, err + } + if !t.Valid { + return nil, nil + } + + buf = append(buf, 1) + return append(buf, t.String...), nil +} + +// PlanScan returns a ScanPlan for scanning a PostgreSQL value into a destination with the same type as target. If +// no plan can be found then nil is returned. +func (l LtreeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case TextFormatCode: + return (TextCodec)(l).PlanScan(m, oid, format, target) + case BinaryFormatCode: + switch target.(type) { + case *string: + return scanPlanBinaryLtreeToString{} + case TextScanner: + return scanPlanBinaryLtreeToTextScanner{} + } + } + + return nil +} + +type scanPlanBinaryLtreeToString struct{} + +func (scanPlanBinaryLtreeToString) Scan(src []byte, target any) error { + version := src[0] + if version != 1 { + return fmt.Errorf("unsupported ltree version %d", version) + } + + p := (target).(*string) + *p = string(src[1:]) + + return nil +} + +type scanPlanBinaryLtreeToTextScanner struct{} + +func (scanPlanBinaryLtreeToTextScanner) Scan(src []byte, target any) error { + version := src[0] + if version != 1 { + return fmt.Errorf("unsupported ltree version %d", version) + } + + scanner := (target).(TextScanner) + return scanner.ScanText(Text{String: string(src[1:]), Valid: true}) +} + +// DecodeDatabaseSQLValue returns src decoded into a value compatible with the sql.Scanner interface. +func (l LtreeCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return (TextCodec)(l).DecodeDatabaseSQLValue(m, oid, format, src) +} + +// DecodeValue returns src decoded into its default format. +func (l LtreeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + return (TextCodec)(l).DecodeValue(m, oid, format, src) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go b/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go index 34950b34..e5763788 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go @@ -339,18 +339,18 @@ func parseUntypedTextMultirange(src []byte) ([]string, error) { r, _, err := buf.ReadRune() if err != nil { - return nil, fmt.Errorf("invalid array: %v", err) + return nil, fmt.Errorf("invalid array: %w", err) } if r != '{' { - return nil, fmt.Errorf("invalid multirange, expected '{': %v", err) + return nil, fmt.Errorf("invalid multirange, expected '{' got %v", r) } parseValueLoop: for { r, _, err = buf.ReadRune() if err != nil { - return nil, fmt.Errorf("invalid multirange: %v", err) + return nil, fmt.Errorf("invalid multirange: %w", err) } switch r { @@ -361,7 +361,7 @@ parseValueLoop: buf.UnreadRune() value, err := parseRange(buf) if err != nil { - return nil, fmt.Errorf("invalid multirange value: %v", err) + return nil, fmt.Errorf("invalid multirange value: %w", err) } elements = append(elements, value) } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go b/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go index 0e58fd07..4dbec786 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go @@ -119,6 +119,26 @@ func (n Numeric) Int64Value() (Int8, error) { return Int8{Int64: bi.Int64(), Valid: true}, nil } +func (n *Numeric) ScanScientific(src string) error { + if !strings.ContainsAny("eE", src) { + return scanPlanTextAnyToNumericScanner{}.Scan([]byte(src), n) + } + + if bigF, ok := new(big.Float).SetString(string(src)); ok { + smallF, _ := bigF.Float64() + src = strconv.FormatFloat(smallF, 'f', -1, 64) + } + + num, exp, err := parseNumericString(src) + if err != nil { + return err + } + + *n = Numeric{Int: num, Exp: exp, Valid: true} + + return nil +} + func (n *Numeric) toBigInt() (*big.Int, error) { if n.Exp == 0 { return n.Int, nil diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go index 4c2532d2..534ef6d1 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go @@ -81,6 +81,8 @@ const ( IntervalOID = 1186 IntervalArrayOID = 1187 NumericArrayOID = 1231 + TimetzOID = 1266 + TimetzArrayOID = 1270 BitOID = 1560 BitArrayOID = 1561 VarbitOID = 1562 @@ -559,7 +561,7 @@ func TryFindUnderlyingTypeScanPlan(dst any) (plan WrappedScanPlanNextSetter, nex } } - if nextDstType != nil && dstValue.Type() != nextDstType { + if nextDstType != nil && dstValue.Type() != nextDstType && dstValue.CanConvert(nextDstType) { return &underlyingTypeScanPlan{dstType: dstValue.Type(), nextDstType: nextDstType}, dstValue.Convert(nextDstType).Interface(), true } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go index 58f4b92c..c21ac081 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go @@ -1,6 +1,7 @@ package pgtype import ( + "encoding/json" "net" "net/netip" "reflect" @@ -173,6 +174,7 @@ func initDefaultMap() { registerDefaultPgTypeVariants[time.Time](defaultMap, "timestamptz") registerDefaultPgTypeVariants[time.Duration](defaultMap, "interval") registerDefaultPgTypeVariants[string](defaultMap, "text") + registerDefaultPgTypeVariants[json.RawMessage](defaultMap, "json") registerDefaultPgTypeVariants[[]byte](defaultMap, "bytea") registerDefaultPgTypeVariants[net.IP](defaultMap, "inet") diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/range.go b/vendor/github.com/jackc/pgx/v5/pgtype/range.go index 8f408f9f..16427ccc 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/range.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/range.go @@ -40,7 +40,7 @@ func parseUntypedTextRange(src string) (*untypedTextRange, error) { r, _, err := buf.ReadRune() if err != nil { - return nil, fmt.Errorf("invalid lower bound: %v", err) + return nil, fmt.Errorf("invalid lower bound: %w", err) } switch r { case '(': @@ -53,7 +53,7 @@ func parseUntypedTextRange(src string) (*untypedTextRange, error) { r, _, err = buf.ReadRune() if err != nil { - return nil, fmt.Errorf("invalid lower value: %v", err) + return nil, fmt.Errorf("invalid lower value: %w", err) } buf.UnreadRune() @@ -62,13 +62,13 @@ func parseUntypedTextRange(src string) (*untypedTextRange, error) { } else { utr.Lower, err = rangeParseValue(buf) if err != nil { - return nil, fmt.Errorf("invalid lower value: %v", err) + return nil, fmt.Errorf("invalid lower value: %w", err) } } r, _, err = buf.ReadRune() if err != nil { - return nil, fmt.Errorf("missing range separator: %v", err) + return nil, fmt.Errorf("missing range separator: %w", err) } if r != ',' { return nil, fmt.Errorf("missing range separator: %v", r) @@ -76,7 +76,7 @@ func parseUntypedTextRange(src string) (*untypedTextRange, error) { r, _, err = buf.ReadRune() if err != nil { - return nil, fmt.Errorf("invalid upper value: %v", err) + return nil, fmt.Errorf("invalid upper value: %w", err) } if r == ')' || r == ']' { @@ -85,12 +85,12 @@ func parseUntypedTextRange(src string) (*untypedTextRange, error) { buf.UnreadRune() utr.Upper, err = rangeParseValue(buf) if err != nil { - return nil, fmt.Errorf("invalid upper value: %v", err) + return nil, fmt.Errorf("invalid upper value: %w", err) } r, _, err = buf.ReadRune() if err != nil { - return nil, fmt.Errorf("missing upper bound: %v", err) + return nil, fmt.Errorf("missing upper bound: %w", err) } switch r { case ')': diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go index 8cfb3a63..684f1bf7 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go @@ -120,7 +120,7 @@ func (plan *encodePlanRangeCodecRangeValuerToBinary) Encode(value any, buf []byt buf, err = lowerPlan.Encode(lower, buf) if err != nil { - return nil, fmt.Errorf("failed to encode %v as element of range: %v", lower, err) + return nil, fmt.Errorf("failed to encode %v as element of range: %w", lower, err) } if buf == nil { return nil, fmt.Errorf("Lower cannot be NULL unless LowerType is Unbounded") @@ -144,7 +144,7 @@ func (plan *encodePlanRangeCodecRangeValuerToBinary) Encode(value any, buf []byt buf, err = upperPlan.Encode(upper, buf) if err != nil { - return nil, fmt.Errorf("failed to encode %v as element of range: %v", upper, err) + return nil, fmt.Errorf("failed to encode %v as element of range: %w", upper, err) } if buf == nil { return nil, fmt.Errorf("Upper cannot be NULL unless UpperType is Unbounded") @@ -194,7 +194,7 @@ func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) buf, err = lowerPlan.Encode(lower, buf) if err != nil { - return nil, fmt.Errorf("failed to encode %v as element of range: %v", lower, err) + return nil, fmt.Errorf("failed to encode %v as element of range: %w", lower, err) } if buf == nil { return nil, fmt.Errorf("Lower cannot be NULL unless LowerType is Unbounded") @@ -215,7 +215,7 @@ func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) buf, err = upperPlan.Encode(upper, buf) if err != nil { - return nil, fmt.Errorf("failed to encode %v as element of range: %v", upper, err) + return nil, fmt.Errorf("failed to encode %v as element of range: %w", upper, err) } if buf == nil { return nil, fmt.Errorf("Upper cannot be NULL unless UpperType is Unbounded") @@ -282,7 +282,7 @@ func (plan *scanPlanBinaryRangeToRangeScanner) Scan(src []byte, target any) erro err = lowerPlan.Scan(ubr.Lower, lowerTarget) if err != nil { - return fmt.Errorf("cannot scan into %v from range element: %v", lowerTarget, err) + return fmt.Errorf("cannot scan into %v from range element: %w", lowerTarget, err) } } @@ -294,7 +294,7 @@ func (plan *scanPlanBinaryRangeToRangeScanner) Scan(src []byte, target any) erro err = upperPlan.Scan(ubr.Upper, upperTarget) if err != nil { - return fmt.Errorf("cannot scan into %v from range element: %v", upperTarget, err) + return fmt.Errorf("cannot scan into %v from range element: %w", upperTarget, err) } } @@ -332,7 +332,7 @@ func (plan *scanPlanTextRangeToRangeScanner) Scan(src []byte, target any) error err = lowerPlan.Scan([]byte(utr.Lower), lowerTarget) if err != nil { - return fmt.Errorf("cannot scan into %v from range element: %v", lowerTarget, err) + return fmt.Errorf("cannot scan into %v from range element: %w", lowerTarget, err) } } @@ -344,7 +344,7 @@ func (plan *scanPlanTextRangeToRangeScanner) Scan(src []byte, target any) error err = upperPlan.Scan([]byte(utr.Upper), upperTarget) if err != nil { - return fmt.Errorf("cannot scan into %v from range element: %v", upperTarget, err) + return fmt.Errorf("cannot scan into %v from range element: %w", upperTarget, err) } } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go b/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go index b59d6e76..d57c0f2f 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go @@ -52,7 +52,19 @@ func parseUUID(src string) (dst [16]byte, err error) { // encodeUUID converts a uuid byte array to UUID standard string form. func encodeUUID(src [16]byte) string { - return fmt.Sprintf("%x-%x-%x-%x-%x", src[0:4], src[4:6], src[6:8], src[8:10], src[10:16]) + var buf [36]byte + + hex.Encode(buf[0:8], src[:4]) + buf[8] = '-' + hex.Encode(buf[9:13], src[4:6]) + buf[13] = '-' + hex.Encode(buf[14:18], src[6:8]) + buf[18] = '-' + hex.Encode(buf[19:23], src[8:10]) + buf[23] = '-' + hex.Encode(buf[24:], src[10:]) + + return string(buf[:]) } // Scan implements the database/sql Scanner interface. diff --git a/vendor/github.com/jackc/pgx/v5/rows.go b/vendor/github.com/jackc/pgx/v5/rows.go index 73efffa0..78ef5326 100644 --- a/vendor/github.com/jackc/pgx/v5/rows.go +++ b/vendor/github.com/jackc/pgx/v5/rows.go @@ -417,12 +417,10 @@ type CollectableRow interface { // RowToFunc is a function that scans or otherwise converts row to a T. type RowToFunc[T any] func(row CollectableRow) (T, error) -// CollectRows iterates through rows, calling fn for each row, and collecting the results into a slice of T. -func CollectRows[T any](rows Rows, fn RowToFunc[T]) ([]T, error) { +// AppendRows iterates through rows, calling fn for each row, and appending the results into a slice of T. +func AppendRows[T any, S ~[]T](slice S, rows Rows, fn RowToFunc[T]) (S, error) { defer rows.Close() - slice := []T{} - for rows.Next() { value, err := fn(rows) if err != nil { @@ -438,6 +436,11 @@ func CollectRows[T any](rows Rows, fn RowToFunc[T]) ([]T, error) { return slice, nil } +// CollectRows iterates through rows, calling fn for each row, and collecting the results into a slice of T. +func CollectRows[T any](rows Rows, fn RowToFunc[T]) ([]T, error) { + return AppendRows([]T{}, rows, fn) +} + // CollectOneRow calls fn for the first row in rows and returns the result. If no rows are found returns an error where errors.Is(ErrNoRows) is true. // CollectOneRow is to CollectRows as QueryRow is to Query. func CollectOneRow[T any](rows Rows, fn RowToFunc[T]) (T, error) { @@ -667,7 +670,12 @@ const structTagKey = "db" func fieldPosByName(fldDescs []pgconn.FieldDescription, field string) (i int) { i = -1 for i, desc := range fldDescs { - if strings.EqualFold(desc.Name, field) { + + // Snake case support. + field = strings.ReplaceAll(field, "_", "") + descName := strings.ReplaceAll(desc.Name, "_", "") + + if strings.EqualFold(descName, field) { return i } } diff --git a/vendor/github.com/jackc/pgx/v5/stdlib/sql.go b/vendor/github.com/jackc/pgx/v5/stdlib/sql.go index c5be1a3f..3d65e23a 100644 --- a/vendor/github.com/jackc/pgx/v5/stdlib/sql.go +++ b/vendor/github.com/jackc/pgx/v5/stdlib/sql.go @@ -21,17 +21,14 @@ // return err // } // -// db, err := stdlib.OpenDBFromPool(pool) -// if err != nil { -// return err -// } +// db := stdlib.OpenDBFromPool(pool) // // Or a pgx.ConnConfig can be used to set configuration not accessible via connection string. In this case the // pgx.ConnConfig must first be registered with the driver. This registration returns a connection string which is used // with sql.Open. // // connConfig, _ := pgx.ParseConfig(os.Getenv("DATABASE_URL")) -// connConfig.Logger = myLogger +// connConfig.Tracer = &tracelog.TraceLog{Logger: myLogger, LogLevel: tracelog.LogLevelInfo} // connStr := stdlib.RegisterConnConfig(connConfig) // db, _ := sql.Open("pgx", connStr) // @@ -840,7 +837,7 @@ func (r *Rows) Next(dest []driver.Value) error { var err error dest[i], err = r.valueFuncs[i](rv) if err != nil { - return fmt.Errorf("convert field %d failed: %v", i, err) + return fmt.Errorf("convert field %d failed: %w", i, err) } } else { dest[i] = nil diff --git a/vendor/github.com/jackc/pgx/v5/values.go b/vendor/github.com/jackc/pgx/v5/values.go index 19c642fa..cab717d0 100644 --- a/vendor/github.com/jackc/pgx/v5/values.go +++ b/vendor/github.com/jackc/pgx/v5/values.go @@ -55,7 +55,11 @@ func encodeCopyValue(m *pgtype.Map, buf []byte, oid uint32, arg any) ([]byte, er func tryScanStringCopyValueThenEncode(m *pgtype.Map, buf []byte, oid uint32, arg any) ([]byte, error) { s, ok := arg.(string) if !ok { - return nil, errors.New("not a string") + textBuf, err := m.Encode(oid, TextFormatCode, arg, nil) + if err != nil { + return nil, errors.New("not a string and cannot be encoded as text") + } + s = string(textBuf) } var v any diff --git a/vendor/github.com/microsoft/go-winio/.gitattributes b/vendor/github.com/microsoft/go-winio/.gitattributes new file mode 100644 index 00000000..94f480de --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf \ No newline at end of file diff --git a/vendor/github.com/microsoft/go-winio/.gitignore b/vendor/github.com/microsoft/go-winio/.gitignore new file mode 100644 index 00000000..815e2066 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/.gitignore @@ -0,0 +1,10 @@ +.vscode/ + +*.exe + +# testing +testdata + +# go workspaces +go.work +go.work.sum diff --git a/vendor/github.com/microsoft/go-winio/.golangci.yml b/vendor/github.com/microsoft/go-winio/.golangci.yml new file mode 100644 index 00000000..faedfe93 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/.golangci.yml @@ -0,0 +1,147 @@ +linters: + enable: + # style + - containedctx # struct contains a context + - dupl # duplicate code + - errname # erorrs are named correctly + - nolintlint # "//nolint" directives are properly explained + - revive # golint replacement + - unconvert # unnecessary conversions + - wastedassign + + # bugs, performance, unused, etc ... + - contextcheck # function uses a non-inherited context + - errorlint # errors not wrapped for 1.13 + - exhaustive # check exhaustiveness of enum switch statements + - gofmt # files are gofmt'ed + - gosec # security + - nilerr # returns nil even with non-nil error + - thelper # test helpers without t.Helper() + - unparam # unused function params + +issues: + exclude-dirs: + - pkg/etw/sample + + exclude-rules: + # err is very often shadowed in nested scopes + - linters: + - govet + text: '^shadow: declaration of "err" shadows declaration' + + # ignore long lines for skip autogen directives + - linters: + - revive + text: "^line-length-limit: " + source: "^//(go:generate|sys) " + + #TODO: remove after upgrading to go1.18 + # ignore comment spacing for nolint and sys directives + - linters: + - revive + text: "^comment-spacings: no space between comment delimiter and comment text" + source: "//(cspell:|nolint:|sys |todo)" + + # not on go 1.18 yet, so no any + - linters: + - revive + text: "^use-any: since GO 1.18 'interface{}' can be replaced by 'any'" + + # allow unjustified ignores of error checks in defer statements + - linters: + - nolintlint + text: "^directive `//nolint:errcheck` should provide explanation" + source: '^\s*defer ' + + # allow unjustified ignores of error lints for io.EOF + - linters: + - nolintlint + text: "^directive `//nolint:errorlint` should provide explanation" + source: '[=|!]= io.EOF' + + +linters-settings: + exhaustive: + default-signifies-exhaustive: true + govet: + enable-all: true + disable: + # struct order is often for Win32 compat + # also, ignore pointer bytes/GC issues for now until performance becomes an issue + - fieldalignment + nolintlint: + require-explanation: true + require-specific: true + revive: + # revive is more configurable than static check, so likely the preferred alternative to static-check + # (once the perf issue is solved: https://github.com/golangci/golangci-lint/issues/2997) + enable-all-rules: + true + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md + rules: + # rules with required arguments + - name: argument-limit + disabled: true + - name: banned-characters + disabled: true + - name: cognitive-complexity + disabled: true + - name: cyclomatic + disabled: true + - name: file-header + disabled: true + - name: function-length + disabled: true + - name: function-result-limit + disabled: true + - name: max-public-structs + disabled: true + # geneally annoying rules + - name: add-constant # complains about any and all strings and integers + disabled: true + - name: confusing-naming # we frequently use "Foo()" and "foo()" together + disabled: true + - name: flag-parameter # excessive, and a common idiom we use + disabled: true + - name: unhandled-error # warns over common fmt.Print* and io.Close; rely on errcheck instead + disabled: true + # general config + - name: line-length-limit + arguments: + - 140 + - name: var-naming + arguments: + - [] + - - CID + - CRI + - CTRD + - DACL + - DLL + - DOS + - ETW + - FSCTL + - GCS + - GMSA + - HCS + - HV + - IO + - LCOW + - LDAP + - LPAC + - LTSC + - MMIO + - NT + - OCI + - PMEM + - PWSH + - RX + - SACl + - SID + - SMB + - TX + - VHD + - VHDX + - VMID + - VPCI + - WCOW + - WIM diff --git a/vendor/github.com/microsoft/go-winio/CODEOWNERS b/vendor/github.com/microsoft/go-winio/CODEOWNERS new file mode 100644 index 00000000..ae1b4942 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/CODEOWNERS @@ -0,0 +1 @@ + * @microsoft/containerplat diff --git a/vendor/github.com/microsoft/go-winio/LICENSE b/vendor/github.com/microsoft/go-winio/LICENSE new file mode 100644 index 00000000..b8b569d7 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/vendor/github.com/microsoft/go-winio/README.md b/vendor/github.com/microsoft/go-winio/README.md new file mode 100644 index 00000000..7474b4f0 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/README.md @@ -0,0 +1,89 @@ +# go-winio [![Build Status](https://github.com/microsoft/go-winio/actions/workflows/ci.yml/badge.svg)](https://github.com/microsoft/go-winio/actions/workflows/ci.yml) + +This repository contains utilities for efficiently performing Win32 IO operations in +Go. Currently, this is focused on accessing named pipes and other file handles, and +for using named pipes as a net transport. + +This code relies on IO completion ports to avoid blocking IO on system threads, allowing Go +to reuse the thread to schedule another goroutine. This limits support to Windows Vista and +newer operating systems. This is similar to the implementation of network sockets in Go's net +package. + +Please see the LICENSE file for licensing information. + +## Contributing + +This project welcomes contributions and suggestions. +Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that +you have the right to, and actually do, grant us the rights to use your contribution. +For details, visit [Microsoft CLA](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether you need to +provide a CLA and decorate the PR appropriately (e.g., label, comment). +Simply follow the instructions provided by the bot. +You will only need to do this once across all repos using our CLA. + +Additionally, the pull request pipeline requires the following steps to be performed before +mergining. + +### Code Sign-Off + +We require that contributors sign their commits using [`git commit --signoff`][git-commit-s] +to certify they either authored the work themselves or otherwise have permission to use it in this project. + +A range of commits can be signed off using [`git rebase --signoff`][git-rebase-s]. + +Please see [the developer certificate](https://developercertificate.org) for more info, +as well as to make sure that you can attest to the rules listed. +Our CI uses the DCO Github app to ensure that all commits in a given PR are signed-off. + +### Linting + +Code must pass a linting stage, which uses [`golangci-lint`][lint]. +The linting settings are stored in [`.golangci.yaml`](./.golangci.yaml), and can be run +automatically with VSCode by adding the following to your workspace or folder settings: + +```json + "go.lintTool": "golangci-lint", + "go.lintOnSave": "package", +``` + +Additional editor [integrations options are also available][lint-ide]. + +Alternatively, `golangci-lint` can be [installed locally][lint-install] and run from the repo root: + +```shell +# use . or specify a path to only lint a package +# to show all lint errors, use flags "--max-issues-per-linter=0 --max-same-issues=0" +> golangci-lint run ./... +``` + +### Go Generate + +The pipeline checks that auto-generated code, via `go generate`, are up to date. + +This can be done for the entire repo: + +```shell +> go generate ./... +``` + +## Code of Conduct + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or +contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +## Special Thanks + +Thanks to [natefinch][natefinch] for the inspiration for this library. +See [npipe](https://github.com/natefinch/npipe) for another named pipe implementation. + +[lint]: https://golangci-lint.run/ +[lint-ide]: https://golangci-lint.run/usage/integrations/#editor-integration +[lint-install]: https://golangci-lint.run/usage/install/#local-installation + +[git-commit-s]: https://git-scm.com/docs/git-commit#Documentation/git-commit.txt--s +[git-rebase-s]: https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt---signoff + +[natefinch]: https://github.com/natefinch diff --git a/vendor/github.com/microsoft/go-winio/SECURITY.md b/vendor/github.com/microsoft/go-winio/SECURITY.md new file mode 100644 index 00000000..869fdfe2 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/SECURITY.md @@ -0,0 +1,41 @@ + + +## Security + +Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). + +If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. + +## Reporting Security Issues + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). + +If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). + +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). + +Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: + + * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. + +## Preferred Languages + +We prefer all communications to be in English. + +## Policy + +Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). + + diff --git a/vendor/github.com/microsoft/go-winio/backup.go b/vendor/github.com/microsoft/go-winio/backup.go new file mode 100644 index 00000000..b54341da --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/backup.go @@ -0,0 +1,287 @@ +//go:build windows +// +build windows + +package winio + +import ( + "encoding/binary" + "errors" + "fmt" + "io" + "os" + "runtime" + "unicode/utf16" + + "github.com/Microsoft/go-winio/internal/fs" + "golang.org/x/sys/windows" +) + +//sys backupRead(h windows.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupRead +//sys backupWrite(h windows.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupWrite + +const ( + BackupData = uint32(iota + 1) + BackupEaData + BackupSecurity + BackupAlternateData + BackupLink + BackupPropertyData + BackupObjectId //revive:disable-line:var-naming ID, not Id + BackupReparseData + BackupSparseBlock + BackupTxfsData +) + +const ( + StreamSparseAttributes = uint32(8) +) + +//nolint:revive // var-naming: ALL_CAPS +const ( + WRITE_DAC = windows.WRITE_DAC + WRITE_OWNER = windows.WRITE_OWNER + ACCESS_SYSTEM_SECURITY = windows.ACCESS_SYSTEM_SECURITY +) + +// BackupHeader represents a backup stream of a file. +type BackupHeader struct { + //revive:disable-next-line:var-naming ID, not Id + Id uint32 // The backup stream ID + Attributes uint32 // Stream attributes + Size int64 // The size of the stream in bytes + Name string // The name of the stream (for BackupAlternateData only). + Offset int64 // The offset of the stream in the file (for BackupSparseBlock only). +} + +type win32StreamID struct { + StreamID uint32 + Attributes uint32 + Size uint64 + NameSize uint32 +} + +// BackupStreamReader reads from a stream produced by the BackupRead Win32 API and produces a series +// of BackupHeader values. +type BackupStreamReader struct { + r io.Reader + bytesLeft int64 +} + +// NewBackupStreamReader produces a BackupStreamReader from any io.Reader. +func NewBackupStreamReader(r io.Reader) *BackupStreamReader { + return &BackupStreamReader{r, 0} +} + +// Next returns the next backup stream and prepares for calls to Read(). It skips the remainder of the current stream if +// it was not completely read. +func (r *BackupStreamReader) Next() (*BackupHeader, error) { + if r.bytesLeft > 0 { //nolint:nestif // todo: flatten this + if s, ok := r.r.(io.Seeker); ok { + // Make sure Seek on io.SeekCurrent sometimes succeeds + // before trying the actual seek. + if _, err := s.Seek(0, io.SeekCurrent); err == nil { + if _, err = s.Seek(r.bytesLeft, io.SeekCurrent); err != nil { + return nil, err + } + r.bytesLeft = 0 + } + } + if _, err := io.Copy(io.Discard, r); err != nil { + return nil, err + } + } + var wsi win32StreamID + if err := binary.Read(r.r, binary.LittleEndian, &wsi); err != nil { + return nil, err + } + hdr := &BackupHeader{ + Id: wsi.StreamID, + Attributes: wsi.Attributes, + Size: int64(wsi.Size), + } + if wsi.NameSize != 0 { + name := make([]uint16, int(wsi.NameSize/2)) + if err := binary.Read(r.r, binary.LittleEndian, name); err != nil { + return nil, err + } + hdr.Name = windows.UTF16ToString(name) + } + if wsi.StreamID == BackupSparseBlock { + if err := binary.Read(r.r, binary.LittleEndian, &hdr.Offset); err != nil { + return nil, err + } + hdr.Size -= 8 + } + r.bytesLeft = hdr.Size + return hdr, nil +} + +// Read reads from the current backup stream. +func (r *BackupStreamReader) Read(b []byte) (int, error) { + if r.bytesLeft == 0 { + return 0, io.EOF + } + if int64(len(b)) > r.bytesLeft { + b = b[:r.bytesLeft] + } + n, err := r.r.Read(b) + r.bytesLeft -= int64(n) + if err == io.EOF { + err = io.ErrUnexpectedEOF + } else if r.bytesLeft == 0 && err == nil { + err = io.EOF + } + return n, err +} + +// BackupStreamWriter writes a stream compatible with the BackupWrite Win32 API. +type BackupStreamWriter struct { + w io.Writer + bytesLeft int64 +} + +// NewBackupStreamWriter produces a BackupStreamWriter on top of an io.Writer. +func NewBackupStreamWriter(w io.Writer) *BackupStreamWriter { + return &BackupStreamWriter{w, 0} +} + +// WriteHeader writes the next backup stream header and prepares for calls to Write(). +func (w *BackupStreamWriter) WriteHeader(hdr *BackupHeader) error { + if w.bytesLeft != 0 { + return fmt.Errorf("missing %d bytes", w.bytesLeft) + } + name := utf16.Encode([]rune(hdr.Name)) + wsi := win32StreamID{ + StreamID: hdr.Id, + Attributes: hdr.Attributes, + Size: uint64(hdr.Size), + NameSize: uint32(len(name) * 2), + } + if hdr.Id == BackupSparseBlock { + // Include space for the int64 block offset + wsi.Size += 8 + } + if err := binary.Write(w.w, binary.LittleEndian, &wsi); err != nil { + return err + } + if len(name) != 0 { + if err := binary.Write(w.w, binary.LittleEndian, name); err != nil { + return err + } + } + if hdr.Id == BackupSparseBlock { + if err := binary.Write(w.w, binary.LittleEndian, hdr.Offset); err != nil { + return err + } + } + w.bytesLeft = hdr.Size + return nil +} + +// Write writes to the current backup stream. +func (w *BackupStreamWriter) Write(b []byte) (int, error) { + if w.bytesLeft < int64(len(b)) { + return 0, fmt.Errorf("too many bytes by %d", int64(len(b))-w.bytesLeft) + } + n, err := w.w.Write(b) + w.bytesLeft -= int64(n) + return n, err +} + +// BackupFileReader provides an io.ReadCloser interface on top of the BackupRead Win32 API. +type BackupFileReader struct { + f *os.File + includeSecurity bool + ctx uintptr +} + +// NewBackupFileReader returns a new BackupFileReader from a file handle. If includeSecurity is true, +// Read will attempt to read the security descriptor of the file. +func NewBackupFileReader(f *os.File, includeSecurity bool) *BackupFileReader { + r := &BackupFileReader{f, includeSecurity, 0} + return r +} + +// Read reads a backup stream from the file by calling the Win32 API BackupRead(). +func (r *BackupFileReader) Read(b []byte) (int, error) { + var bytesRead uint32 + err := backupRead(windows.Handle(r.f.Fd()), b, &bytesRead, false, r.includeSecurity, &r.ctx) + if err != nil { + return 0, &os.PathError{Op: "BackupRead", Path: r.f.Name(), Err: err} + } + runtime.KeepAlive(r.f) + if bytesRead == 0 { + return 0, io.EOF + } + return int(bytesRead), nil +} + +// Close frees Win32 resources associated with the BackupFileReader. It does not close +// the underlying file. +func (r *BackupFileReader) Close() error { + if r.ctx != 0 { + _ = backupRead(windows.Handle(r.f.Fd()), nil, nil, true, false, &r.ctx) + runtime.KeepAlive(r.f) + r.ctx = 0 + } + return nil +} + +// BackupFileWriter provides an io.WriteCloser interface on top of the BackupWrite Win32 API. +type BackupFileWriter struct { + f *os.File + includeSecurity bool + ctx uintptr +} + +// NewBackupFileWriter returns a new BackupFileWriter from a file handle. If includeSecurity is true, +// Write() will attempt to restore the security descriptor from the stream. +func NewBackupFileWriter(f *os.File, includeSecurity bool) *BackupFileWriter { + w := &BackupFileWriter{f, includeSecurity, 0} + return w +} + +// Write restores a portion of the file using the provided backup stream. +func (w *BackupFileWriter) Write(b []byte) (int, error) { + var bytesWritten uint32 + err := backupWrite(windows.Handle(w.f.Fd()), b, &bytesWritten, false, w.includeSecurity, &w.ctx) + if err != nil { + return 0, &os.PathError{Op: "BackupWrite", Path: w.f.Name(), Err: err} + } + runtime.KeepAlive(w.f) + if int(bytesWritten) != len(b) { + return int(bytesWritten), errors.New("not all bytes could be written") + } + return len(b), nil +} + +// Close frees Win32 resources associated with the BackupFileWriter. It does not +// close the underlying file. +func (w *BackupFileWriter) Close() error { + if w.ctx != 0 { + _ = backupWrite(windows.Handle(w.f.Fd()), nil, nil, true, false, &w.ctx) + runtime.KeepAlive(w.f) + w.ctx = 0 + } + return nil +} + +// OpenForBackup opens a file or directory, potentially skipping access checks if the backup +// or restore privileges have been acquired. +// +// If the file opened was a directory, it cannot be used with Readdir(). +func OpenForBackup(path string, access uint32, share uint32, createmode uint32) (*os.File, error) { + h, err := fs.CreateFile(path, + fs.AccessMask(access), + fs.FileShareMode(share), + nil, + fs.FileCreationDisposition(createmode), + fs.FILE_FLAG_BACKUP_SEMANTICS|fs.FILE_FLAG_OPEN_REPARSE_POINT, + 0, + ) + if err != nil { + err = &os.PathError{Op: "open", Path: path, Err: err} + return nil, err + } + return os.NewFile(uintptr(h), path), nil +} diff --git a/vendor/github.com/microsoft/go-winio/doc.go b/vendor/github.com/microsoft/go-winio/doc.go new file mode 100644 index 00000000..1f5bfe2d --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/doc.go @@ -0,0 +1,22 @@ +// This package provides utilities for efficiently performing Win32 IO operations in Go. +// Currently, this package is provides support for genreal IO and management of +// - named pipes +// - files +// - [Hyper-V sockets] +// +// This code is similar to Go's [net] package, and uses IO completion ports to avoid +// blocking IO on system threads, allowing Go to reuse the thread to schedule other goroutines. +// +// This limits support to Windows Vista and newer operating systems. +// +// Additionally, this package provides support for: +// - creating and managing GUIDs +// - writing to [ETW] +// - opening and manageing VHDs +// - parsing [Windows Image files] +// - auto-generating Win32 API code +// +// [Hyper-V sockets]: https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/user-guide/make-integration-service +// [ETW]: https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/event-tracing-for-windows--etw- +// [Windows Image files]: https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/work-with-windows-images +package winio diff --git a/vendor/github.com/microsoft/go-winio/ea.go b/vendor/github.com/microsoft/go-winio/ea.go new file mode 100644 index 00000000..e104dbdf --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/ea.go @@ -0,0 +1,137 @@ +package winio + +import ( + "bytes" + "encoding/binary" + "errors" +) + +type fileFullEaInformation struct { + NextEntryOffset uint32 + Flags uint8 + NameLength uint8 + ValueLength uint16 +} + +var ( + fileFullEaInformationSize = binary.Size(&fileFullEaInformation{}) + + errInvalidEaBuffer = errors.New("invalid extended attribute buffer") + errEaNameTooLarge = errors.New("extended attribute name too large") + errEaValueTooLarge = errors.New("extended attribute value too large") +) + +// ExtendedAttribute represents a single Windows EA. +type ExtendedAttribute struct { + Name string + Value []byte + Flags uint8 +} + +func parseEa(b []byte) (ea ExtendedAttribute, nb []byte, err error) { + var info fileFullEaInformation + err = binary.Read(bytes.NewReader(b), binary.LittleEndian, &info) + if err != nil { + err = errInvalidEaBuffer + return ea, nb, err + } + + nameOffset := fileFullEaInformationSize + nameLen := int(info.NameLength) + valueOffset := nameOffset + int(info.NameLength) + 1 + valueLen := int(info.ValueLength) + nextOffset := int(info.NextEntryOffset) + if valueLen+valueOffset > len(b) || nextOffset < 0 || nextOffset > len(b) { + err = errInvalidEaBuffer + return ea, nb, err + } + + ea.Name = string(b[nameOffset : nameOffset+nameLen]) + ea.Value = b[valueOffset : valueOffset+valueLen] + ea.Flags = info.Flags + if info.NextEntryOffset != 0 { + nb = b[info.NextEntryOffset:] + } + return ea, nb, err +} + +// DecodeExtendedAttributes decodes a list of EAs from a FILE_FULL_EA_INFORMATION +// buffer retrieved from BackupRead, ZwQueryEaFile, etc. +func DecodeExtendedAttributes(b []byte) (eas []ExtendedAttribute, err error) { + for len(b) != 0 { + ea, nb, err := parseEa(b) + if err != nil { + return nil, err + } + + eas = append(eas, ea) + b = nb + } + return eas, err +} + +func writeEa(buf *bytes.Buffer, ea *ExtendedAttribute, last bool) error { + if int(uint8(len(ea.Name))) != len(ea.Name) { + return errEaNameTooLarge + } + if int(uint16(len(ea.Value))) != len(ea.Value) { + return errEaValueTooLarge + } + entrySize := uint32(fileFullEaInformationSize + len(ea.Name) + 1 + len(ea.Value)) + withPadding := (entrySize + 3) &^ 3 + nextOffset := uint32(0) + if !last { + nextOffset = withPadding + } + info := fileFullEaInformation{ + NextEntryOffset: nextOffset, + Flags: ea.Flags, + NameLength: uint8(len(ea.Name)), + ValueLength: uint16(len(ea.Value)), + } + + err := binary.Write(buf, binary.LittleEndian, &info) + if err != nil { + return err + } + + _, err = buf.Write([]byte(ea.Name)) + if err != nil { + return err + } + + err = buf.WriteByte(0) + if err != nil { + return err + } + + _, err = buf.Write(ea.Value) + if err != nil { + return err + } + + _, err = buf.Write([]byte{0, 0, 0}[0 : withPadding-entrySize]) + if err != nil { + return err + } + + return nil +} + +// EncodeExtendedAttributes encodes a list of EAs into a FILE_FULL_EA_INFORMATION +// buffer for use with BackupWrite, ZwSetEaFile, etc. +func EncodeExtendedAttributes(eas []ExtendedAttribute) ([]byte, error) { + var buf bytes.Buffer + for i := range eas { + last := false + if i == len(eas)-1 { + last = true + } + + err := writeEa(&buf, &eas[i], last) + if err != nil { + return nil, err + } + } + return buf.Bytes(), nil +} diff --git a/vendor/github.com/microsoft/go-winio/file.go b/vendor/github.com/microsoft/go-winio/file.go new file mode 100644 index 00000000..fe82a180 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/file.go @@ -0,0 +1,320 @@ +//go:build windows +// +build windows + +package winio + +import ( + "errors" + "io" + "runtime" + "sync" + "sync/atomic" + "syscall" + "time" + + "golang.org/x/sys/windows" +) + +//sys cancelIoEx(file windows.Handle, o *windows.Overlapped) (err error) = CancelIoEx +//sys createIoCompletionPort(file windows.Handle, port windows.Handle, key uintptr, threadCount uint32) (newport windows.Handle, err error) = CreateIoCompletionPort +//sys getQueuedCompletionStatus(port windows.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) = GetQueuedCompletionStatus +//sys setFileCompletionNotificationModes(h windows.Handle, flags uint8) (err error) = SetFileCompletionNotificationModes +//sys wsaGetOverlappedResult(h windows.Handle, o *windows.Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) = ws2_32.WSAGetOverlappedResult + +var ( + ErrFileClosed = errors.New("file has already been closed") + ErrTimeout = &timeoutError{} +) + +type timeoutError struct{} + +func (*timeoutError) Error() string { return "i/o timeout" } +func (*timeoutError) Timeout() bool { return true } +func (*timeoutError) Temporary() bool { return true } + +type timeoutChan chan struct{} + +var ioInitOnce sync.Once +var ioCompletionPort windows.Handle + +// ioResult contains the result of an asynchronous IO operation. +type ioResult struct { + bytes uint32 + err error +} + +// ioOperation represents an outstanding asynchronous Win32 IO. +type ioOperation struct { + o windows.Overlapped + ch chan ioResult +} + +func initIO() { + h, err := createIoCompletionPort(windows.InvalidHandle, 0, 0, 0xffffffff) + if err != nil { + panic(err) + } + ioCompletionPort = h + go ioCompletionProcessor(h) +} + +// win32File implements Reader, Writer, and Closer on a Win32 handle without blocking in a syscall. +// It takes ownership of this handle and will close it if it is garbage collected. +type win32File struct { + handle windows.Handle + wg sync.WaitGroup + wgLock sync.RWMutex + closing atomic.Bool + socket bool + readDeadline deadlineHandler + writeDeadline deadlineHandler +} + +type deadlineHandler struct { + setLock sync.Mutex + channel timeoutChan + channelLock sync.RWMutex + timer *time.Timer + timedout atomic.Bool +} + +// makeWin32File makes a new win32File from an existing file handle. +func makeWin32File(h windows.Handle) (*win32File, error) { + f := &win32File{handle: h} + ioInitOnce.Do(initIO) + _, err := createIoCompletionPort(h, ioCompletionPort, 0, 0xffffffff) + if err != nil { + return nil, err + } + err = setFileCompletionNotificationModes(h, windows.FILE_SKIP_COMPLETION_PORT_ON_SUCCESS|windows.FILE_SKIP_SET_EVENT_ON_HANDLE) + if err != nil { + return nil, err + } + f.readDeadline.channel = make(timeoutChan) + f.writeDeadline.channel = make(timeoutChan) + return f, nil +} + +// Deprecated: use NewOpenFile instead. +func MakeOpenFile(h syscall.Handle) (io.ReadWriteCloser, error) { + return NewOpenFile(windows.Handle(h)) +} + +func NewOpenFile(h windows.Handle) (io.ReadWriteCloser, error) { + // If we return the result of makeWin32File directly, it can result in an + // interface-wrapped nil, rather than a nil interface value. + f, err := makeWin32File(h) + if err != nil { + return nil, err + } + return f, nil +} + +// closeHandle closes the resources associated with a Win32 handle. +func (f *win32File) closeHandle() { + f.wgLock.Lock() + // Atomically set that we are closing, releasing the resources only once. + if !f.closing.Swap(true) { + f.wgLock.Unlock() + // cancel all IO and wait for it to complete + _ = cancelIoEx(f.handle, nil) + f.wg.Wait() + // at this point, no new IO can start + windows.Close(f.handle) + f.handle = 0 + } else { + f.wgLock.Unlock() + } +} + +// Close closes a win32File. +func (f *win32File) Close() error { + f.closeHandle() + return nil +} + +// IsClosed checks if the file has been closed. +func (f *win32File) IsClosed() bool { + return f.closing.Load() +} + +// prepareIO prepares for a new IO operation. +// The caller must call f.wg.Done() when the IO is finished, prior to Close() returning. +func (f *win32File) prepareIO() (*ioOperation, error) { + f.wgLock.RLock() + if f.closing.Load() { + f.wgLock.RUnlock() + return nil, ErrFileClosed + } + f.wg.Add(1) + f.wgLock.RUnlock() + c := &ioOperation{} + c.ch = make(chan ioResult) + return c, nil +} + +// ioCompletionProcessor processes completed async IOs forever. +func ioCompletionProcessor(h windows.Handle) { + for { + var bytes uint32 + var key uintptr + var op *ioOperation + err := getQueuedCompletionStatus(h, &bytes, &key, &op, windows.INFINITE) + if op == nil { + panic(err) + } + op.ch <- ioResult{bytes, err} + } +} + +// todo: helsaawy - create an asyncIO version that takes a context + +// asyncIO processes the return value from ReadFile or WriteFile, blocking until +// the operation has actually completed. +func (f *win32File) asyncIO(c *ioOperation, d *deadlineHandler, bytes uint32, err error) (int, error) { + if err != windows.ERROR_IO_PENDING { //nolint:errorlint // err is Errno + return int(bytes), err + } + + if f.closing.Load() { + _ = cancelIoEx(f.handle, &c.o) + } + + var timeout timeoutChan + if d != nil { + d.channelLock.Lock() + timeout = d.channel + d.channelLock.Unlock() + } + + var r ioResult + select { + case r = <-c.ch: + err = r.err + if err == windows.ERROR_OPERATION_ABORTED { //nolint:errorlint // err is Errno + if f.closing.Load() { + err = ErrFileClosed + } + } else if err != nil && f.socket { + // err is from Win32. Query the overlapped structure to get the winsock error. + var bytes, flags uint32 + err = wsaGetOverlappedResult(f.handle, &c.o, &bytes, false, &flags) + } + case <-timeout: + _ = cancelIoEx(f.handle, &c.o) + r = <-c.ch + err = r.err + if err == windows.ERROR_OPERATION_ABORTED { //nolint:errorlint // err is Errno + err = ErrTimeout + } + } + + // runtime.KeepAlive is needed, as c is passed via native + // code to ioCompletionProcessor, c must remain alive + // until the channel read is complete. + // todo: (de)allocate *ioOperation via win32 heap functions, instead of needing to KeepAlive? + runtime.KeepAlive(c) + return int(r.bytes), err +} + +// Read reads from a file handle. +func (f *win32File) Read(b []byte) (int, error) { + c, err := f.prepareIO() + if err != nil { + return 0, err + } + defer f.wg.Done() + + if f.readDeadline.timedout.Load() { + return 0, ErrTimeout + } + + var bytes uint32 + err = windows.ReadFile(f.handle, b, &bytes, &c.o) + n, err := f.asyncIO(c, &f.readDeadline, bytes, err) + runtime.KeepAlive(b) + + // Handle EOF conditions. + if err == nil && n == 0 && len(b) != 0 { + return 0, io.EOF + } else if err == windows.ERROR_BROKEN_PIPE { //nolint:errorlint // err is Errno + return 0, io.EOF + } + return n, err +} + +// Write writes to a file handle. +func (f *win32File) Write(b []byte) (int, error) { + c, err := f.prepareIO() + if err != nil { + return 0, err + } + defer f.wg.Done() + + if f.writeDeadline.timedout.Load() { + return 0, ErrTimeout + } + + var bytes uint32 + err = windows.WriteFile(f.handle, b, &bytes, &c.o) + n, err := f.asyncIO(c, &f.writeDeadline, bytes, err) + runtime.KeepAlive(b) + return n, err +} + +func (f *win32File) SetReadDeadline(deadline time.Time) error { + return f.readDeadline.set(deadline) +} + +func (f *win32File) SetWriteDeadline(deadline time.Time) error { + return f.writeDeadline.set(deadline) +} + +func (f *win32File) Flush() error { + return windows.FlushFileBuffers(f.handle) +} + +func (f *win32File) Fd() uintptr { + return uintptr(f.handle) +} + +func (d *deadlineHandler) set(deadline time.Time) error { + d.setLock.Lock() + defer d.setLock.Unlock() + + if d.timer != nil { + if !d.timer.Stop() { + <-d.channel + } + d.timer = nil + } + d.timedout.Store(false) + + select { + case <-d.channel: + d.channelLock.Lock() + d.channel = make(chan struct{}) + d.channelLock.Unlock() + default: + } + + if deadline.IsZero() { + return nil + } + + timeoutIO := func() { + d.timedout.Store(true) + close(d.channel) + } + + now := time.Now() + duration := deadline.Sub(now) + if deadline.After(now) { + // Deadline is in the future, set a timer to wait + d.timer = time.AfterFunc(duration, timeoutIO) + } else { + // Deadline is in the past. Cancel all pending IO now. + timeoutIO() + } + return nil +} diff --git a/vendor/github.com/microsoft/go-winio/fileinfo.go b/vendor/github.com/microsoft/go-winio/fileinfo.go new file mode 100644 index 00000000..c860eb99 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/fileinfo.go @@ -0,0 +1,106 @@ +//go:build windows +// +build windows + +package winio + +import ( + "os" + "runtime" + "unsafe" + + "golang.org/x/sys/windows" +) + +// FileBasicInfo contains file access time and file attributes information. +type FileBasicInfo struct { + CreationTime, LastAccessTime, LastWriteTime, ChangeTime windows.Filetime + FileAttributes uint32 + _ uint32 // padding +} + +// alignedFileBasicInfo is a FileBasicInfo, but aligned to uint64 by containing +// uint64 rather than windows.Filetime. Filetime contains two uint32s. uint64 +// alignment is necessary to pass this as FILE_BASIC_INFO. +type alignedFileBasicInfo struct { + CreationTime, LastAccessTime, LastWriteTime, ChangeTime uint64 + FileAttributes uint32 + _ uint32 // padding +} + +// GetFileBasicInfo retrieves times and attributes for a file. +func GetFileBasicInfo(f *os.File) (*FileBasicInfo, error) { + bi := &alignedFileBasicInfo{} + if err := windows.GetFileInformationByHandleEx( + windows.Handle(f.Fd()), + windows.FileBasicInfo, + (*byte)(unsafe.Pointer(bi)), + uint32(unsafe.Sizeof(*bi)), + ); err != nil { + return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err} + } + runtime.KeepAlive(f) + // Reinterpret the alignedFileBasicInfo as a FileBasicInfo so it matches the + // public API of this module. The data may be unnecessarily aligned. + return (*FileBasicInfo)(unsafe.Pointer(bi)), nil +} + +// SetFileBasicInfo sets times and attributes for a file. +func SetFileBasicInfo(f *os.File, bi *FileBasicInfo) error { + // Create an alignedFileBasicInfo based on a FileBasicInfo. The copy is + // suitable to pass to GetFileInformationByHandleEx. + biAligned := *(*alignedFileBasicInfo)(unsafe.Pointer(bi)) + if err := windows.SetFileInformationByHandle( + windows.Handle(f.Fd()), + windows.FileBasicInfo, + (*byte)(unsafe.Pointer(&biAligned)), + uint32(unsafe.Sizeof(biAligned)), + ); err != nil { + return &os.PathError{Op: "SetFileInformationByHandle", Path: f.Name(), Err: err} + } + runtime.KeepAlive(f) + return nil +} + +// FileStandardInfo contains extended information for the file. +// FILE_STANDARD_INFO in WinBase.h +// https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_standard_info +type FileStandardInfo struct { + AllocationSize, EndOfFile int64 + NumberOfLinks uint32 + DeletePending, Directory bool +} + +// GetFileStandardInfo retrieves ended information for the file. +func GetFileStandardInfo(f *os.File) (*FileStandardInfo, error) { + si := &FileStandardInfo{} + if err := windows.GetFileInformationByHandleEx(windows.Handle(f.Fd()), + windows.FileStandardInfo, + (*byte)(unsafe.Pointer(si)), + uint32(unsafe.Sizeof(*si))); err != nil { + return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err} + } + runtime.KeepAlive(f) + return si, nil +} + +// FileIDInfo contains the volume serial number and file ID for a file. This pair should be +// unique on a system. +type FileIDInfo struct { + VolumeSerialNumber uint64 + FileID [16]byte +} + +// GetFileID retrieves the unique (volume, file ID) pair for a file. +func GetFileID(f *os.File) (*FileIDInfo, error) { + fileID := &FileIDInfo{} + if err := windows.GetFileInformationByHandleEx( + windows.Handle(f.Fd()), + windows.FileIdInfo, + (*byte)(unsafe.Pointer(fileID)), + uint32(unsafe.Sizeof(*fileID)), + ); err != nil { + return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err} + } + runtime.KeepAlive(f) + return fileID, nil +} diff --git a/vendor/github.com/microsoft/go-winio/hvsock.go b/vendor/github.com/microsoft/go-winio/hvsock.go new file mode 100644 index 00000000..c4fdd9d4 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/hvsock.go @@ -0,0 +1,582 @@ +//go:build windows +// +build windows + +package winio + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "os" + "time" + "unsafe" + + "golang.org/x/sys/windows" + + "github.com/Microsoft/go-winio/internal/socket" + "github.com/Microsoft/go-winio/pkg/guid" +) + +const afHVSock = 34 // AF_HYPERV + +// Well known Service and VM IDs +// https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/user-guide/make-integration-service#vmid-wildcards + +// HvsockGUIDWildcard is the wildcard VmId for accepting connections from all partitions. +func HvsockGUIDWildcard() guid.GUID { // 00000000-0000-0000-0000-000000000000 + return guid.GUID{} +} + +// HvsockGUIDBroadcast is the wildcard VmId for broadcasting sends to all partitions. +func HvsockGUIDBroadcast() guid.GUID { // ffffffff-ffff-ffff-ffff-ffffffffffff + return guid.GUID{ + Data1: 0xffffffff, + Data2: 0xffff, + Data3: 0xffff, + Data4: [8]uint8{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, + } +} + +// HvsockGUIDLoopback is the Loopback VmId for accepting connections to the same partition as the connector. +func HvsockGUIDLoopback() guid.GUID { // e0e16197-dd56-4a10-9195-5ee7a155a838 + return guid.GUID{ + Data1: 0xe0e16197, + Data2: 0xdd56, + Data3: 0x4a10, + Data4: [8]uint8{0x91, 0x95, 0x5e, 0xe7, 0xa1, 0x55, 0xa8, 0x38}, + } +} + +// HvsockGUIDSiloHost is the address of a silo's host partition: +// - The silo host of a hosted silo is the utility VM. +// - The silo host of a silo on a physical host is the physical host. +func HvsockGUIDSiloHost() guid.GUID { // 36bd0c5c-7276-4223-88ba-7d03b654c568 + return guid.GUID{ + Data1: 0x36bd0c5c, + Data2: 0x7276, + Data3: 0x4223, + Data4: [8]byte{0x88, 0xba, 0x7d, 0x03, 0xb6, 0x54, 0xc5, 0x68}, + } +} + +// HvsockGUIDChildren is the wildcard VmId for accepting connections from the connector's child partitions. +func HvsockGUIDChildren() guid.GUID { // 90db8b89-0d35-4f79-8ce9-49ea0ac8b7cd + return guid.GUID{ + Data1: 0x90db8b89, + Data2: 0xd35, + Data3: 0x4f79, + Data4: [8]uint8{0x8c, 0xe9, 0x49, 0xea, 0xa, 0xc8, 0xb7, 0xcd}, + } +} + +// HvsockGUIDParent is the wildcard VmId for accepting connections from the connector's parent partition. +// Listening on this VmId accepts connection from: +// - Inside silos: silo host partition. +// - Inside hosted silo: host of the VM. +// - Inside VM: VM host. +// - Physical host: Not supported. +func HvsockGUIDParent() guid.GUID { // a42e7cda-d03f-480c-9cc2-a4de20abb878 + return guid.GUID{ + Data1: 0xa42e7cda, + Data2: 0xd03f, + Data3: 0x480c, + Data4: [8]uint8{0x9c, 0xc2, 0xa4, 0xde, 0x20, 0xab, 0xb8, 0x78}, + } +} + +// hvsockVsockServiceTemplate is the Service GUID used for the VSOCK protocol. +func hvsockVsockServiceTemplate() guid.GUID { // 00000000-facb-11e6-bd58-64006a7986d3 + return guid.GUID{ + Data2: 0xfacb, + Data3: 0x11e6, + Data4: [8]uint8{0xbd, 0x58, 0x64, 0x00, 0x6a, 0x79, 0x86, 0xd3}, + } +} + +// An HvsockAddr is an address for a AF_HYPERV socket. +type HvsockAddr struct { + VMID guid.GUID + ServiceID guid.GUID +} + +type rawHvsockAddr struct { + Family uint16 + _ uint16 + VMID guid.GUID + ServiceID guid.GUID +} + +var _ socket.RawSockaddr = &rawHvsockAddr{} + +// Network returns the address's network name, "hvsock". +func (*HvsockAddr) Network() string { + return "hvsock" +} + +func (addr *HvsockAddr) String() string { + return fmt.Sprintf("%s:%s", &addr.VMID, &addr.ServiceID) +} + +// VsockServiceID returns an hvsock service ID corresponding to the specified AF_VSOCK port. +func VsockServiceID(port uint32) guid.GUID { + g := hvsockVsockServiceTemplate() // make a copy + g.Data1 = port + return g +} + +func (addr *HvsockAddr) raw() rawHvsockAddr { + return rawHvsockAddr{ + Family: afHVSock, + VMID: addr.VMID, + ServiceID: addr.ServiceID, + } +} + +func (addr *HvsockAddr) fromRaw(raw *rawHvsockAddr) { + addr.VMID = raw.VMID + addr.ServiceID = raw.ServiceID +} + +// Sockaddr returns a pointer to and the size of this struct. +// +// Implements the [socket.RawSockaddr] interface, and allows use in +// [socket.Bind] and [socket.ConnectEx]. +func (r *rawHvsockAddr) Sockaddr() (unsafe.Pointer, int32, error) { + return unsafe.Pointer(r), int32(unsafe.Sizeof(rawHvsockAddr{})), nil +} + +// Sockaddr interface allows use with `sockets.Bind()` and `.ConnectEx()`. +func (r *rawHvsockAddr) FromBytes(b []byte) error { + n := int(unsafe.Sizeof(rawHvsockAddr{})) + + if len(b) < n { + return fmt.Errorf("got %d, want %d: %w", len(b), n, socket.ErrBufferSize) + } + + copy(unsafe.Slice((*byte)(unsafe.Pointer(r)), n), b[:n]) + if r.Family != afHVSock { + return fmt.Errorf("got %d, want %d: %w", r.Family, afHVSock, socket.ErrAddrFamily) + } + + return nil +} + +// HvsockListener is a socket listener for the AF_HYPERV address family. +type HvsockListener struct { + sock *win32File + addr HvsockAddr +} + +var _ net.Listener = &HvsockListener{} + +// HvsockConn is a connected socket of the AF_HYPERV address family. +type HvsockConn struct { + sock *win32File + local, remote HvsockAddr +} + +var _ net.Conn = &HvsockConn{} + +func newHVSocket() (*win32File, error) { + fd, err := windows.Socket(afHVSock, windows.SOCK_STREAM, 1) + if err != nil { + return nil, os.NewSyscallError("socket", err) + } + f, err := makeWin32File(fd) + if err != nil { + windows.Close(fd) + return nil, err + } + f.socket = true + return f, nil +} + +// ListenHvsock listens for connections on the specified hvsock address. +func ListenHvsock(addr *HvsockAddr) (_ *HvsockListener, err error) { + l := &HvsockListener{addr: *addr} + + var sock *win32File + sock, err = newHVSocket() + if err != nil { + return nil, l.opErr("listen", err) + } + defer func() { + if err != nil { + _ = sock.Close() + } + }() + + sa := addr.raw() + err = socket.Bind(sock.handle, &sa) + if err != nil { + return nil, l.opErr("listen", os.NewSyscallError("socket", err)) + } + err = windows.Listen(sock.handle, 16) + if err != nil { + return nil, l.opErr("listen", os.NewSyscallError("listen", err)) + } + return &HvsockListener{sock: sock, addr: *addr}, nil +} + +func (l *HvsockListener) opErr(op string, err error) error { + return &net.OpError{Op: op, Net: "hvsock", Addr: &l.addr, Err: err} +} + +// Addr returns the listener's network address. +func (l *HvsockListener) Addr() net.Addr { + return &l.addr +} + +// Accept waits for the next connection and returns it. +func (l *HvsockListener) Accept() (_ net.Conn, err error) { + sock, err := newHVSocket() + if err != nil { + return nil, l.opErr("accept", err) + } + defer func() { + if sock != nil { + sock.Close() + } + }() + c, err := l.sock.prepareIO() + if err != nil { + return nil, l.opErr("accept", err) + } + defer l.sock.wg.Done() + + // AcceptEx, per documentation, requires an extra 16 bytes per address. + // + // https://docs.microsoft.com/en-us/windows/win32/api/mswsock/nf-mswsock-acceptex + const addrlen = uint32(16 + unsafe.Sizeof(rawHvsockAddr{})) + var addrbuf [addrlen * 2]byte + + var bytes uint32 + err = windows.AcceptEx(l.sock.handle, sock.handle, &addrbuf[0], 0 /* rxdatalen */, addrlen, addrlen, &bytes, &c.o) + if _, err = l.sock.asyncIO(c, nil, bytes, err); err != nil { + return nil, l.opErr("accept", os.NewSyscallError("acceptex", err)) + } + + conn := &HvsockConn{ + sock: sock, + } + // The local address returned in the AcceptEx buffer is the same as the Listener socket's + // address. However, the service GUID reported by GetSockName is different from the Listeners + // socket, and is sometimes the same as the local address of the socket that dialed the + // address, with the service GUID.Data1 incremented, but othertimes is different. + // todo: does the local address matter? is the listener's address or the actual address appropriate? + conn.local.fromRaw((*rawHvsockAddr)(unsafe.Pointer(&addrbuf[0]))) + conn.remote.fromRaw((*rawHvsockAddr)(unsafe.Pointer(&addrbuf[addrlen]))) + + // initialize the accepted socket and update its properties with those of the listening socket + if err = windows.Setsockopt(sock.handle, + windows.SOL_SOCKET, windows.SO_UPDATE_ACCEPT_CONTEXT, + (*byte)(unsafe.Pointer(&l.sock.handle)), int32(unsafe.Sizeof(l.sock.handle))); err != nil { + return nil, conn.opErr("accept", os.NewSyscallError("setsockopt", err)) + } + + sock = nil + return conn, nil +} + +// Close closes the listener, causing any pending Accept calls to fail. +func (l *HvsockListener) Close() error { + return l.sock.Close() +} + +// HvsockDialer configures and dials a Hyper-V Socket (ie, [HvsockConn]). +type HvsockDialer struct { + // Deadline is the time the Dial operation must connect before erroring. + Deadline time.Time + + // Retries is the number of additional connects to try if the connection times out, is refused, + // or the host is unreachable + Retries uint + + // RetryWait is the time to wait after a connection error to retry + RetryWait time.Duration + + rt *time.Timer // redial wait timer +} + +// Dial the Hyper-V socket at addr. +// +// See [HvsockDialer.Dial] for more information. +func Dial(ctx context.Context, addr *HvsockAddr) (conn *HvsockConn, err error) { + return (&HvsockDialer{}).Dial(ctx, addr) +} + +// Dial attempts to connect to the Hyper-V socket at addr, and returns a connection if successful. +// Will attempt (HvsockDialer).Retries if dialing fails, waiting (HvsockDialer).RetryWait between +// retries. +// +// Dialing can be cancelled either by providing (HvsockDialer).Deadline, or cancelling ctx. +func (d *HvsockDialer) Dial(ctx context.Context, addr *HvsockAddr) (conn *HvsockConn, err error) { + op := "dial" + // create the conn early to use opErr() + conn = &HvsockConn{ + remote: *addr, + } + + if !d.Deadline.IsZero() { + var cancel context.CancelFunc + ctx, cancel = context.WithDeadline(ctx, d.Deadline) + defer cancel() + } + + // preemptive timeout/cancellation check + if err = ctx.Err(); err != nil { + return nil, conn.opErr(op, err) + } + + sock, err := newHVSocket() + if err != nil { + return nil, conn.opErr(op, err) + } + defer func() { + if sock != nil { + sock.Close() + } + }() + + sa := addr.raw() + err = socket.Bind(sock.handle, &sa) + if err != nil { + return nil, conn.opErr(op, os.NewSyscallError("bind", err)) + } + + c, err := sock.prepareIO() + if err != nil { + return nil, conn.opErr(op, err) + } + defer sock.wg.Done() + var bytes uint32 + for i := uint(0); i <= d.Retries; i++ { + err = socket.ConnectEx( + sock.handle, + &sa, + nil, // sendBuf + 0, // sendDataLen + &bytes, + (*windows.Overlapped)(unsafe.Pointer(&c.o))) + _, err = sock.asyncIO(c, nil, bytes, err) + if i < d.Retries && canRedial(err) { + if err = d.redialWait(ctx); err == nil { + continue + } + } + break + } + if err != nil { + return nil, conn.opErr(op, os.NewSyscallError("connectex", err)) + } + + // update the connection properties, so shutdown can be used + if err = windows.Setsockopt( + sock.handle, + windows.SOL_SOCKET, + windows.SO_UPDATE_CONNECT_CONTEXT, + nil, // optvalue + 0, // optlen + ); err != nil { + return nil, conn.opErr(op, os.NewSyscallError("setsockopt", err)) + } + + // get the local name + var sal rawHvsockAddr + err = socket.GetSockName(sock.handle, &sal) + if err != nil { + return nil, conn.opErr(op, os.NewSyscallError("getsockname", err)) + } + conn.local.fromRaw(&sal) + + // one last check for timeout, since asyncIO doesn't check the context + if err = ctx.Err(); err != nil { + return nil, conn.opErr(op, err) + } + + conn.sock = sock + sock = nil + + return conn, nil +} + +// redialWait waits before attempting to redial, resetting the timer as appropriate. +func (d *HvsockDialer) redialWait(ctx context.Context) (err error) { + if d.RetryWait == 0 { + return nil + } + + if d.rt == nil { + d.rt = time.NewTimer(d.RetryWait) + } else { + // should already be stopped and drained + d.rt.Reset(d.RetryWait) + } + + select { + case <-ctx.Done(): + case <-d.rt.C: + return nil + } + + // stop and drain the timer + if !d.rt.Stop() { + <-d.rt.C + } + return ctx.Err() +} + +// assumes error is a plain, unwrapped windows.Errno provided by direct syscall. +func canRedial(err error) bool { + //nolint:errorlint // guaranteed to be an Errno + switch err { + case windows.WSAECONNREFUSED, windows.WSAENETUNREACH, windows.WSAETIMEDOUT, + windows.ERROR_CONNECTION_REFUSED, windows.ERROR_CONNECTION_UNAVAIL: + return true + default: + return false + } +} + +func (conn *HvsockConn) opErr(op string, err error) error { + // translate from "file closed" to "socket closed" + if errors.Is(err, ErrFileClosed) { + err = socket.ErrSocketClosed + } + return &net.OpError{Op: op, Net: "hvsock", Source: &conn.local, Addr: &conn.remote, Err: err} +} + +func (conn *HvsockConn) Read(b []byte) (int, error) { + c, err := conn.sock.prepareIO() + if err != nil { + return 0, conn.opErr("read", err) + } + defer conn.sock.wg.Done() + buf := windows.WSABuf{Buf: &b[0], Len: uint32(len(b))} + var flags, bytes uint32 + err = windows.WSARecv(conn.sock.handle, &buf, 1, &bytes, &flags, &c.o, nil) + n, err := conn.sock.asyncIO(c, &conn.sock.readDeadline, bytes, err) + if err != nil { + var eno windows.Errno + if errors.As(err, &eno) { + err = os.NewSyscallError("wsarecv", eno) + } + return 0, conn.opErr("read", err) + } else if n == 0 { + err = io.EOF + } + return n, err +} + +func (conn *HvsockConn) Write(b []byte) (int, error) { + t := 0 + for len(b) != 0 { + n, err := conn.write(b) + if err != nil { + return t + n, err + } + t += n + b = b[n:] + } + return t, nil +} + +func (conn *HvsockConn) write(b []byte) (int, error) { + c, err := conn.sock.prepareIO() + if err != nil { + return 0, conn.opErr("write", err) + } + defer conn.sock.wg.Done() + buf := windows.WSABuf{Buf: &b[0], Len: uint32(len(b))} + var bytes uint32 + err = windows.WSASend(conn.sock.handle, &buf, 1, &bytes, 0, &c.o, nil) + n, err := conn.sock.asyncIO(c, &conn.sock.writeDeadline, bytes, err) + if err != nil { + var eno windows.Errno + if errors.As(err, &eno) { + err = os.NewSyscallError("wsasend", eno) + } + return 0, conn.opErr("write", err) + } + return n, err +} + +// Close closes the socket connection, failing any pending read or write calls. +func (conn *HvsockConn) Close() error { + return conn.sock.Close() +} + +func (conn *HvsockConn) IsClosed() bool { + return conn.sock.IsClosed() +} + +// shutdown disables sending or receiving on a socket. +func (conn *HvsockConn) shutdown(how int) error { + if conn.IsClosed() { + return socket.ErrSocketClosed + } + + err := windows.Shutdown(conn.sock.handle, how) + if err != nil { + // If the connection was closed, shutdowns fail with "not connected" + if errors.Is(err, windows.WSAENOTCONN) || + errors.Is(err, windows.WSAESHUTDOWN) { + err = socket.ErrSocketClosed + } + return os.NewSyscallError("shutdown", err) + } + return nil +} + +// CloseRead shuts down the read end of the socket, preventing future read operations. +func (conn *HvsockConn) CloseRead() error { + err := conn.shutdown(windows.SHUT_RD) + if err != nil { + return conn.opErr("closeread", err) + } + return nil +} + +// CloseWrite shuts down the write end of the socket, preventing future write operations and +// notifying the other endpoint that no more data will be written. +func (conn *HvsockConn) CloseWrite() error { + err := conn.shutdown(windows.SHUT_WR) + if err != nil { + return conn.opErr("closewrite", err) + } + return nil +} + +// LocalAddr returns the local address of the connection. +func (conn *HvsockConn) LocalAddr() net.Addr { + return &conn.local +} + +// RemoteAddr returns the remote address of the connection. +func (conn *HvsockConn) RemoteAddr() net.Addr { + return &conn.remote +} + +// SetDeadline implements the net.Conn SetDeadline method. +func (conn *HvsockConn) SetDeadline(t time.Time) error { + // todo: implement `SetDeadline` for `win32File` + if err := conn.SetReadDeadline(t); err != nil { + return fmt.Errorf("set read deadline: %w", err) + } + if err := conn.SetWriteDeadline(t); err != nil { + return fmt.Errorf("set write deadline: %w", err) + } + return nil +} + +// SetReadDeadline implements the net.Conn SetReadDeadline method. +func (conn *HvsockConn) SetReadDeadline(t time.Time) error { + return conn.sock.SetReadDeadline(t) +} + +// SetWriteDeadline implements the net.Conn SetWriteDeadline method. +func (conn *HvsockConn) SetWriteDeadline(t time.Time) error { + return conn.sock.SetWriteDeadline(t) +} diff --git a/vendor/github.com/microsoft/go-winio/internal/fs/doc.go b/vendor/github.com/microsoft/go-winio/internal/fs/doc.go new file mode 100644 index 00000000..1f653881 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/internal/fs/doc.go @@ -0,0 +1,2 @@ +// This package contains Win32 filesystem functionality. +package fs diff --git a/vendor/github.com/microsoft/go-winio/internal/fs/fs.go b/vendor/github.com/microsoft/go-winio/internal/fs/fs.go new file mode 100644 index 00000000..0cd9621d --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/internal/fs/fs.go @@ -0,0 +1,262 @@ +//go:build windows + +package fs + +import ( + "golang.org/x/sys/windows" + + "github.com/Microsoft/go-winio/internal/stringbuffer" +) + +//go:generate go run github.com/Microsoft/go-winio/tools/mkwinsyscall -output zsyscall_windows.go fs.go + +// https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew +//sys CreateFile(name string, access AccessMask, mode FileShareMode, sa *windows.SecurityAttributes, createmode FileCreationDisposition, attrs FileFlagOrAttribute, templatefile windows.Handle) (handle windows.Handle, err error) [failretval==windows.InvalidHandle] = CreateFileW + +const NullHandle windows.Handle = 0 + +// AccessMask defines standard, specific, and generic rights. +// +// Used with CreateFile and NtCreateFile (and co.). +// +// Bitmask: +// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 +// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 +// +---------------+---------------+-------------------------------+ +// |G|G|G|G|Resvd|A| StandardRights| SpecificRights | +// |R|W|E|A| |S| | | +// +-+-------------+---------------+-------------------------------+ +// +// GR Generic Read +// GW Generic Write +// GE Generic Exectue +// GA Generic All +// Resvd Reserved +// AS Access Security System +// +// https://learn.microsoft.com/en-us/windows/win32/secauthz/access-mask +// +// https://learn.microsoft.com/en-us/windows/win32/secauthz/generic-access-rights +// +// https://learn.microsoft.com/en-us/windows/win32/fileio/file-access-rights-constants +type AccessMask = windows.ACCESS_MASK + +//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. +const ( + // Not actually any. + // + // For CreateFile: "query certain metadata such as file, directory, or device attributes without accessing that file or device" + // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew#parameters + FILE_ANY_ACCESS AccessMask = 0 + + GENERIC_READ AccessMask = 0x8000_0000 + GENERIC_WRITE AccessMask = 0x4000_0000 + GENERIC_EXECUTE AccessMask = 0x2000_0000 + GENERIC_ALL AccessMask = 0x1000_0000 + ACCESS_SYSTEM_SECURITY AccessMask = 0x0100_0000 + + // Specific Object Access + // from ntioapi.h + + FILE_READ_DATA AccessMask = (0x0001) // file & pipe + FILE_LIST_DIRECTORY AccessMask = (0x0001) // directory + + FILE_WRITE_DATA AccessMask = (0x0002) // file & pipe + FILE_ADD_FILE AccessMask = (0x0002) // directory + + FILE_APPEND_DATA AccessMask = (0x0004) // file + FILE_ADD_SUBDIRECTORY AccessMask = (0x0004) // directory + FILE_CREATE_PIPE_INSTANCE AccessMask = (0x0004) // named pipe + + FILE_READ_EA AccessMask = (0x0008) // file & directory + FILE_READ_PROPERTIES AccessMask = FILE_READ_EA + + FILE_WRITE_EA AccessMask = (0x0010) // file & directory + FILE_WRITE_PROPERTIES AccessMask = FILE_WRITE_EA + + FILE_EXECUTE AccessMask = (0x0020) // file + FILE_TRAVERSE AccessMask = (0x0020) // directory + + FILE_DELETE_CHILD AccessMask = (0x0040) // directory + + FILE_READ_ATTRIBUTES AccessMask = (0x0080) // all + + FILE_WRITE_ATTRIBUTES AccessMask = (0x0100) // all + + FILE_ALL_ACCESS AccessMask = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF) + FILE_GENERIC_READ AccessMask = (STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE) + FILE_GENERIC_WRITE AccessMask = (STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE) + FILE_GENERIC_EXECUTE AccessMask = (STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE) + + SPECIFIC_RIGHTS_ALL AccessMask = 0x0000FFFF + + // Standard Access + // from ntseapi.h + + DELETE AccessMask = 0x0001_0000 + READ_CONTROL AccessMask = 0x0002_0000 + WRITE_DAC AccessMask = 0x0004_0000 + WRITE_OWNER AccessMask = 0x0008_0000 + SYNCHRONIZE AccessMask = 0x0010_0000 + + STANDARD_RIGHTS_REQUIRED AccessMask = 0x000F_0000 + + STANDARD_RIGHTS_READ AccessMask = READ_CONTROL + STANDARD_RIGHTS_WRITE AccessMask = READ_CONTROL + STANDARD_RIGHTS_EXECUTE AccessMask = READ_CONTROL + + STANDARD_RIGHTS_ALL AccessMask = 0x001F_0000 +) + +type FileShareMode uint32 + +//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. +const ( + FILE_SHARE_NONE FileShareMode = 0x00 + FILE_SHARE_READ FileShareMode = 0x01 + FILE_SHARE_WRITE FileShareMode = 0x02 + FILE_SHARE_DELETE FileShareMode = 0x04 + FILE_SHARE_VALID_FLAGS FileShareMode = 0x07 +) + +type FileCreationDisposition uint32 + +//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. +const ( + // from winbase.h + + CREATE_NEW FileCreationDisposition = 0x01 + CREATE_ALWAYS FileCreationDisposition = 0x02 + OPEN_EXISTING FileCreationDisposition = 0x03 + OPEN_ALWAYS FileCreationDisposition = 0x04 + TRUNCATE_EXISTING FileCreationDisposition = 0x05 +) + +// Create disposition values for NtCreate* +type NTFileCreationDisposition uint32 + +//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. +const ( + // From ntioapi.h + + FILE_SUPERSEDE NTFileCreationDisposition = 0x00 + FILE_OPEN NTFileCreationDisposition = 0x01 + FILE_CREATE NTFileCreationDisposition = 0x02 + FILE_OPEN_IF NTFileCreationDisposition = 0x03 + FILE_OVERWRITE NTFileCreationDisposition = 0x04 + FILE_OVERWRITE_IF NTFileCreationDisposition = 0x05 + FILE_MAXIMUM_DISPOSITION NTFileCreationDisposition = 0x05 +) + +// CreateFile and co. take flags or attributes together as one parameter. +// Define alias until we can use generics to allow both +// +// https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants +type FileFlagOrAttribute uint32 + +//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. +const ( + // from winnt.h + + FILE_FLAG_WRITE_THROUGH FileFlagOrAttribute = 0x8000_0000 + FILE_FLAG_OVERLAPPED FileFlagOrAttribute = 0x4000_0000 + FILE_FLAG_NO_BUFFERING FileFlagOrAttribute = 0x2000_0000 + FILE_FLAG_RANDOM_ACCESS FileFlagOrAttribute = 0x1000_0000 + FILE_FLAG_SEQUENTIAL_SCAN FileFlagOrAttribute = 0x0800_0000 + FILE_FLAG_DELETE_ON_CLOSE FileFlagOrAttribute = 0x0400_0000 + FILE_FLAG_BACKUP_SEMANTICS FileFlagOrAttribute = 0x0200_0000 + FILE_FLAG_POSIX_SEMANTICS FileFlagOrAttribute = 0x0100_0000 + FILE_FLAG_OPEN_REPARSE_POINT FileFlagOrAttribute = 0x0020_0000 + FILE_FLAG_OPEN_NO_RECALL FileFlagOrAttribute = 0x0010_0000 + FILE_FLAG_FIRST_PIPE_INSTANCE FileFlagOrAttribute = 0x0008_0000 +) + +// NtCreate* functions take a dedicated CreateOptions parameter. +// +// https://learn.microsoft.com/en-us/windows/win32/api/Winternl/nf-winternl-ntcreatefile +// +// https://learn.microsoft.com/en-us/windows/win32/devnotes/nt-create-named-pipe-file +type NTCreateOptions uint32 + +//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. +const ( + // From ntioapi.h + + FILE_DIRECTORY_FILE NTCreateOptions = 0x0000_0001 + FILE_WRITE_THROUGH NTCreateOptions = 0x0000_0002 + FILE_SEQUENTIAL_ONLY NTCreateOptions = 0x0000_0004 + FILE_NO_INTERMEDIATE_BUFFERING NTCreateOptions = 0x0000_0008 + + FILE_SYNCHRONOUS_IO_ALERT NTCreateOptions = 0x0000_0010 + FILE_SYNCHRONOUS_IO_NONALERT NTCreateOptions = 0x0000_0020 + FILE_NON_DIRECTORY_FILE NTCreateOptions = 0x0000_0040 + FILE_CREATE_TREE_CONNECTION NTCreateOptions = 0x0000_0080 + + FILE_COMPLETE_IF_OPLOCKED NTCreateOptions = 0x0000_0100 + FILE_NO_EA_KNOWLEDGE NTCreateOptions = 0x0000_0200 + FILE_DISABLE_TUNNELING NTCreateOptions = 0x0000_0400 + FILE_RANDOM_ACCESS NTCreateOptions = 0x0000_0800 + + FILE_DELETE_ON_CLOSE NTCreateOptions = 0x0000_1000 + FILE_OPEN_BY_FILE_ID NTCreateOptions = 0x0000_2000 + FILE_OPEN_FOR_BACKUP_INTENT NTCreateOptions = 0x0000_4000 + FILE_NO_COMPRESSION NTCreateOptions = 0x0000_8000 +) + +type FileSQSFlag = FileFlagOrAttribute + +//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. +const ( + // from winbase.h + + SECURITY_ANONYMOUS FileSQSFlag = FileSQSFlag(SecurityAnonymous << 16) + SECURITY_IDENTIFICATION FileSQSFlag = FileSQSFlag(SecurityIdentification << 16) + SECURITY_IMPERSONATION FileSQSFlag = FileSQSFlag(SecurityImpersonation << 16) + SECURITY_DELEGATION FileSQSFlag = FileSQSFlag(SecurityDelegation << 16) + + SECURITY_SQOS_PRESENT FileSQSFlag = 0x0010_0000 + SECURITY_VALID_SQOS_FLAGS FileSQSFlag = 0x001F_0000 +) + +// GetFinalPathNameByHandle flags +// +// https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfinalpathnamebyhandlew#parameters +type GetFinalPathFlag uint32 + +//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. +const ( + GetFinalPathDefaultFlag GetFinalPathFlag = 0x0 + + FILE_NAME_NORMALIZED GetFinalPathFlag = 0x0 + FILE_NAME_OPENED GetFinalPathFlag = 0x8 + + VOLUME_NAME_DOS GetFinalPathFlag = 0x0 + VOLUME_NAME_GUID GetFinalPathFlag = 0x1 + VOLUME_NAME_NT GetFinalPathFlag = 0x2 + VOLUME_NAME_NONE GetFinalPathFlag = 0x4 +) + +// getFinalPathNameByHandle facilitates calling the Windows API GetFinalPathNameByHandle +// with the given handle and flags. It transparently takes care of creating a buffer of the +// correct size for the call. +// +// https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfinalpathnamebyhandlew +func GetFinalPathNameByHandle(h windows.Handle, flags GetFinalPathFlag) (string, error) { + b := stringbuffer.NewWString() + //TODO: can loop infinitely if Win32 keeps returning the same (or a larger) n? + for { + n, err := windows.GetFinalPathNameByHandle(h, b.Pointer(), b.Cap(), uint32(flags)) + if err != nil { + return "", err + } + // If the buffer wasn't large enough, n will be the total size needed (including null terminator). + // Resize and try again. + if n > b.Cap() { + b.ResizeTo(n) + continue + } + // If the buffer is large enough, n will be the size not including the null terminator. + // Convert to a Go string and return. + return b.String(), nil + } +} diff --git a/vendor/github.com/microsoft/go-winio/internal/fs/security.go b/vendor/github.com/microsoft/go-winio/internal/fs/security.go new file mode 100644 index 00000000..81760ac6 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/internal/fs/security.go @@ -0,0 +1,12 @@ +package fs + +// https://learn.microsoft.com/en-us/windows/win32/api/winnt/ne-winnt-security_impersonation_level +type SecurityImpersonationLevel int32 // C default enums underlying type is `int`, which is Go `int32` + +// Impersonation levels +const ( + SecurityAnonymous SecurityImpersonationLevel = 0 + SecurityIdentification SecurityImpersonationLevel = 1 + SecurityImpersonation SecurityImpersonationLevel = 2 + SecurityDelegation SecurityImpersonationLevel = 3 +) diff --git a/vendor/github.com/microsoft/go-winio/internal/fs/zsyscall_windows.go b/vendor/github.com/microsoft/go-winio/internal/fs/zsyscall_windows.go new file mode 100644 index 00000000..a94e234c --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/internal/fs/zsyscall_windows.go @@ -0,0 +1,61 @@ +//go:build windows + +// Code generated by 'go generate' using "github.com/Microsoft/go-winio/tools/mkwinsyscall"; DO NOT EDIT. + +package fs + +import ( + "syscall" + "unsafe" + + "golang.org/x/sys/windows" +) + +var _ unsafe.Pointer + +// Do the interface allocations only once for common +// Errno values. +const ( + errnoERROR_IO_PENDING = 997 +) + +var ( + errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) + errERROR_EINVAL error = syscall.EINVAL +) + +// errnoErr returns common boxed Errno values, to prevent +// allocations at runtime. +func errnoErr(e syscall.Errno) error { + switch e { + case 0: + return errERROR_EINVAL + case errnoERROR_IO_PENDING: + return errERROR_IO_PENDING + } + return e +} + +var ( + modkernel32 = windows.NewLazySystemDLL("kernel32.dll") + + procCreateFileW = modkernel32.NewProc("CreateFileW") +) + +func CreateFile(name string, access AccessMask, mode FileShareMode, sa *windows.SecurityAttributes, createmode FileCreationDisposition, attrs FileFlagOrAttribute, templatefile windows.Handle) (handle windows.Handle, err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(name) + if err != nil { + return + } + return _CreateFile(_p0, access, mode, sa, createmode, attrs, templatefile) +} + +func _CreateFile(name *uint16, access AccessMask, mode FileShareMode, sa *windows.SecurityAttributes, createmode FileCreationDisposition, attrs FileFlagOrAttribute, templatefile windows.Handle) (handle windows.Handle, err error) { + r0, _, e1 := syscall.SyscallN(procCreateFileW.Addr(), uintptr(unsafe.Pointer(name)), uintptr(access), uintptr(mode), uintptr(unsafe.Pointer(sa)), uintptr(createmode), uintptr(attrs), uintptr(templatefile)) + handle = windows.Handle(r0) + if handle == windows.InvalidHandle { + err = errnoErr(e1) + } + return +} diff --git a/vendor/github.com/microsoft/go-winio/internal/socket/rawaddr.go b/vendor/github.com/microsoft/go-winio/internal/socket/rawaddr.go new file mode 100644 index 00000000..7e82f9af --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/internal/socket/rawaddr.go @@ -0,0 +1,20 @@ +package socket + +import ( + "unsafe" +) + +// RawSockaddr allows structs to be used with [Bind] and [ConnectEx]. The +// struct must meet the Win32 sockaddr requirements specified here: +// https://docs.microsoft.com/en-us/windows/win32/winsock/sockaddr-2 +// +// Specifically, the struct size must be least larger than an int16 (unsigned short) +// for the address family. +type RawSockaddr interface { + // Sockaddr returns a pointer to the RawSockaddr and its struct size, allowing + // for the RawSockaddr's data to be overwritten by syscalls (if necessary). + // + // It is the callers responsibility to validate that the values are valid; invalid + // pointers or size can cause a panic. + Sockaddr() (unsafe.Pointer, int32, error) +} diff --git a/vendor/github.com/microsoft/go-winio/internal/socket/socket.go b/vendor/github.com/microsoft/go-winio/internal/socket/socket.go new file mode 100644 index 00000000..88580d97 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/internal/socket/socket.go @@ -0,0 +1,177 @@ +//go:build windows + +package socket + +import ( + "errors" + "fmt" + "net" + "sync" + "syscall" + "unsafe" + + "github.com/Microsoft/go-winio/pkg/guid" + "golang.org/x/sys/windows" +) + +//go:generate go run github.com/Microsoft/go-winio/tools/mkwinsyscall -output zsyscall_windows.go socket.go + +//sys getsockname(s windows.Handle, name unsafe.Pointer, namelen *int32) (err error) [failretval==socketError] = ws2_32.getsockname +//sys getpeername(s windows.Handle, name unsafe.Pointer, namelen *int32) (err error) [failretval==socketError] = ws2_32.getpeername +//sys bind(s windows.Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socketError] = ws2_32.bind + +const socketError = uintptr(^uint32(0)) + +var ( + // todo(helsaawy): create custom error types to store the desired vs actual size and addr family? + + ErrBufferSize = errors.New("buffer size") + ErrAddrFamily = errors.New("address family") + ErrInvalidPointer = errors.New("invalid pointer") + ErrSocketClosed = fmt.Errorf("socket closed: %w", net.ErrClosed) +) + +// todo(helsaawy): replace these with generics, ie: GetSockName[S RawSockaddr](s windows.Handle) (S, error) + +// GetSockName writes the local address of socket s to the [RawSockaddr] rsa. +// If rsa is not large enough, the [windows.WSAEFAULT] is returned. +func GetSockName(s windows.Handle, rsa RawSockaddr) error { + ptr, l, err := rsa.Sockaddr() + if err != nil { + return fmt.Errorf("could not retrieve socket pointer and size: %w", err) + } + + // although getsockname returns WSAEFAULT if the buffer is too small, it does not set + // &l to the correct size, so--apart from doubling the buffer repeatedly--there is no remedy + return getsockname(s, ptr, &l) +} + +// GetPeerName returns the remote address the socket is connected to. +// +// See [GetSockName] for more information. +func GetPeerName(s windows.Handle, rsa RawSockaddr) error { + ptr, l, err := rsa.Sockaddr() + if err != nil { + return fmt.Errorf("could not retrieve socket pointer and size: %w", err) + } + + return getpeername(s, ptr, &l) +} + +func Bind(s windows.Handle, rsa RawSockaddr) (err error) { + ptr, l, err := rsa.Sockaddr() + if err != nil { + return fmt.Errorf("could not retrieve socket pointer and size: %w", err) + } + + return bind(s, ptr, l) +} + +// "golang.org/x/sys/windows".ConnectEx and .Bind only accept internal implementations of the +// their sockaddr interface, so they cannot be used with HvsockAddr +// Replicate functionality here from +// https://cs.opensource.google/go/x/sys/+/master:windows/syscall_windows.go + +// The function pointers to `AcceptEx`, `ConnectEx` and `GetAcceptExSockaddrs` must be loaded at +// runtime via a WSAIoctl call: +// https://docs.microsoft.com/en-us/windows/win32/api/Mswsock/nc-mswsock-lpfn_connectex#remarks + +type runtimeFunc struct { + id guid.GUID + once sync.Once + addr uintptr + err error +} + +func (f *runtimeFunc) Load() error { + f.once.Do(func() { + var s windows.Handle + s, f.err = windows.Socket(windows.AF_INET, windows.SOCK_STREAM, windows.IPPROTO_TCP) + if f.err != nil { + return + } + defer windows.CloseHandle(s) //nolint:errcheck + + var n uint32 + f.err = windows.WSAIoctl(s, + windows.SIO_GET_EXTENSION_FUNCTION_POINTER, + (*byte)(unsafe.Pointer(&f.id)), + uint32(unsafe.Sizeof(f.id)), + (*byte)(unsafe.Pointer(&f.addr)), + uint32(unsafe.Sizeof(f.addr)), + &n, + nil, // overlapped + 0, // completionRoutine + ) + }) + return f.err +} + +var ( + // todo: add `AcceptEx` and `GetAcceptExSockaddrs` + WSAID_CONNECTEX = guid.GUID{ //revive:disable-line:var-naming ALL_CAPS + Data1: 0x25a207b9, + Data2: 0xddf3, + Data3: 0x4660, + Data4: [8]byte{0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e}, + } + + connectExFunc = runtimeFunc{id: WSAID_CONNECTEX} +) + +func ConnectEx( + fd windows.Handle, + rsa RawSockaddr, + sendBuf *byte, + sendDataLen uint32, + bytesSent *uint32, + overlapped *windows.Overlapped, +) error { + if err := connectExFunc.Load(); err != nil { + return fmt.Errorf("failed to load ConnectEx function pointer: %w", err) + } + ptr, n, err := rsa.Sockaddr() + if err != nil { + return err + } + return connectEx(fd, ptr, n, sendBuf, sendDataLen, bytesSent, overlapped) +} + +// BOOL LpfnConnectex( +// [in] SOCKET s, +// [in] const sockaddr *name, +// [in] int namelen, +// [in, optional] PVOID lpSendBuffer, +// [in] DWORD dwSendDataLength, +// [out] LPDWORD lpdwBytesSent, +// [in] LPOVERLAPPED lpOverlapped +// ) + +func connectEx( + s windows.Handle, + name unsafe.Pointer, + namelen int32, + sendBuf *byte, + sendDataLen uint32, + bytesSent *uint32, + overlapped *windows.Overlapped, +) (err error) { + r1, _, e1 := syscall.SyscallN(connectExFunc.addr, + uintptr(s), + uintptr(name), + uintptr(namelen), + uintptr(unsafe.Pointer(sendBuf)), + uintptr(sendDataLen), + uintptr(unsafe.Pointer(bytesSent)), + uintptr(unsafe.Pointer(overlapped)), + ) + + if r1 == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return err +} diff --git a/vendor/github.com/microsoft/go-winio/internal/socket/zsyscall_windows.go b/vendor/github.com/microsoft/go-winio/internal/socket/zsyscall_windows.go new file mode 100644 index 00000000..e1504126 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/internal/socket/zsyscall_windows.go @@ -0,0 +1,69 @@ +//go:build windows + +// Code generated by 'go generate' using "github.com/Microsoft/go-winio/tools/mkwinsyscall"; DO NOT EDIT. + +package socket + +import ( + "syscall" + "unsafe" + + "golang.org/x/sys/windows" +) + +var _ unsafe.Pointer + +// Do the interface allocations only once for common +// Errno values. +const ( + errnoERROR_IO_PENDING = 997 +) + +var ( + errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) + errERROR_EINVAL error = syscall.EINVAL +) + +// errnoErr returns common boxed Errno values, to prevent +// allocations at runtime. +func errnoErr(e syscall.Errno) error { + switch e { + case 0: + return errERROR_EINVAL + case errnoERROR_IO_PENDING: + return errERROR_IO_PENDING + } + return e +} + +var ( + modws2_32 = windows.NewLazySystemDLL("ws2_32.dll") + + procbind = modws2_32.NewProc("bind") + procgetpeername = modws2_32.NewProc("getpeername") + procgetsockname = modws2_32.NewProc("getsockname") +) + +func bind(s windows.Handle, name unsafe.Pointer, namelen int32) (err error) { + r1, _, e1 := syscall.SyscallN(procbind.Addr(), uintptr(s), uintptr(name), uintptr(namelen)) + if r1 == socketError { + err = errnoErr(e1) + } + return +} + +func getpeername(s windows.Handle, name unsafe.Pointer, namelen *int32) (err error) { + r1, _, e1 := syscall.SyscallN(procgetpeername.Addr(), uintptr(s), uintptr(name), uintptr(unsafe.Pointer(namelen))) + if r1 == socketError { + err = errnoErr(e1) + } + return +} + +func getsockname(s windows.Handle, name unsafe.Pointer, namelen *int32) (err error) { + r1, _, e1 := syscall.SyscallN(procgetsockname.Addr(), uintptr(s), uintptr(name), uintptr(unsafe.Pointer(namelen))) + if r1 == socketError { + err = errnoErr(e1) + } + return +} diff --git a/vendor/github.com/microsoft/go-winio/internal/stringbuffer/wstring.go b/vendor/github.com/microsoft/go-winio/internal/stringbuffer/wstring.go new file mode 100644 index 00000000..42ebc019 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/internal/stringbuffer/wstring.go @@ -0,0 +1,132 @@ +package stringbuffer + +import ( + "sync" + "unicode/utf16" +) + +// TODO: worth exporting and using in mkwinsyscall? + +// Uint16BufferSize is the buffer size in the pool, chosen somewhat arbitrarily to accommodate +// large path strings: +// MAX_PATH (260) + size of volume GUID prefix (49) + null terminator = 310. +const MinWStringCap = 310 + +// use *[]uint16 since []uint16 creates an extra allocation where the slice header +// is copied to heap and then referenced via pointer in the interface header that sync.Pool +// stores. +var pathPool = sync.Pool{ // if go1.18+ adds Pool[T], use that to store []uint16 directly + New: func() interface{} { + b := make([]uint16, MinWStringCap) + return &b + }, +} + +func newBuffer() []uint16 { return *(pathPool.Get().(*[]uint16)) } + +// freeBuffer copies the slice header data, and puts a pointer to that in the pool. +// This avoids taking a pointer to the slice header in WString, which can be set to nil. +func freeBuffer(b []uint16) { pathPool.Put(&b) } + +// WString is a wide string buffer ([]uint16) meant for storing UTF-16 encoded strings +// for interacting with Win32 APIs. +// Sizes are specified as uint32 and not int. +// +// It is not thread safe. +type WString struct { + // type-def allows casting to []uint16 directly, use struct to prevent that and allow adding fields in the future. + + // raw buffer + b []uint16 +} + +// NewWString returns a [WString] allocated from a shared pool with an +// initial capacity of at least [MinWStringCap]. +// Since the buffer may have been previously used, its contents are not guaranteed to be empty. +// +// The buffer should be freed via [WString.Free] +func NewWString() *WString { + return &WString{ + b: newBuffer(), + } +} + +func (b *WString) Free() { + if b.empty() { + return + } + freeBuffer(b.b) + b.b = nil +} + +// ResizeTo grows the buffer to at least c and returns the new capacity, freeing the +// previous buffer back into pool. +func (b *WString) ResizeTo(c uint32) uint32 { + // already sufficient (or n is 0) + if c <= b.Cap() { + return b.Cap() + } + + if c <= MinWStringCap { + c = MinWStringCap + } + // allocate at-least double buffer size, as is done in [bytes.Buffer] and other places + if c <= 2*b.Cap() { + c = 2 * b.Cap() + } + + b2 := make([]uint16, c) + if !b.empty() { + copy(b2, b.b) + freeBuffer(b.b) + } + b.b = b2 + return c +} + +// Buffer returns the underlying []uint16 buffer. +func (b *WString) Buffer() []uint16 { + if b.empty() { + return nil + } + return b.b +} + +// Pointer returns a pointer to the first uint16 in the buffer. +// If the [WString.Free] has already been called, the pointer will be nil. +func (b *WString) Pointer() *uint16 { + if b.empty() { + return nil + } + return &b.b[0] +} + +// String returns the returns the UTF-8 encoding of the UTF-16 string in the buffer. +// +// It assumes that the data is null-terminated. +func (b *WString) String() string { + // Using [windows.UTF16ToString] would require importing "golang.org/x/sys/windows" + // and would make this code Windows-only, which makes no sense. + // So copy UTF16ToString code into here. + // If other windows-specific code is added, switch to [windows.UTF16ToString] + + s := b.b + for i, v := range s { + if v == 0 { + s = s[:i] + break + } + } + return string(utf16.Decode(s)) +} + +// Cap returns the underlying buffer capacity. +func (b *WString) Cap() uint32 { + if b.empty() { + return 0 + } + return b.cap() +} + +func (b *WString) cap() uint32 { return uint32(cap(b.b)) } +func (b *WString) empty() bool { return b == nil || b.cap() == 0 } diff --git a/vendor/github.com/microsoft/go-winio/pipe.go b/vendor/github.com/microsoft/go-winio/pipe.go new file mode 100644 index 00000000..a2da6639 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/pipe.go @@ -0,0 +1,586 @@ +//go:build windows +// +build windows + +package winio + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "os" + "runtime" + "time" + "unsafe" + + "golang.org/x/sys/windows" + + "github.com/Microsoft/go-winio/internal/fs" +) + +//sys connectNamedPipe(pipe windows.Handle, o *windows.Overlapped) (err error) = ConnectNamedPipe +//sys createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *windows.SecurityAttributes) (handle windows.Handle, err error) [failretval==windows.InvalidHandle] = CreateNamedPipeW +//sys disconnectNamedPipe(pipe windows.Handle) (err error) = DisconnectNamedPipe +//sys getNamedPipeInfo(pipe windows.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) = GetNamedPipeInfo +//sys getNamedPipeHandleState(pipe windows.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW +//sys ntCreateNamedPipeFile(pipe *windows.Handle, access ntAccessMask, oa *objectAttributes, iosb *ioStatusBlock, share ntFileShareMode, disposition ntFileCreationDisposition, options ntFileOptions, typ uint32, readMode uint32, completionMode uint32, maxInstances uint32, inboundQuota uint32, outputQuota uint32, timeout *int64) (status ntStatus) = ntdll.NtCreateNamedPipeFile +//sys rtlNtStatusToDosError(status ntStatus) (winerr error) = ntdll.RtlNtStatusToDosErrorNoTeb +//sys rtlDosPathNameToNtPathName(name *uint16, ntName *unicodeString, filePart uintptr, reserved uintptr) (status ntStatus) = ntdll.RtlDosPathNameToNtPathName_U +//sys rtlDefaultNpAcl(dacl *uintptr) (status ntStatus) = ntdll.RtlDefaultNpAcl + +type PipeConn interface { + net.Conn + Disconnect() error + Flush() error +} + +// type aliases for mkwinsyscall code +type ( + ntAccessMask = fs.AccessMask + ntFileShareMode = fs.FileShareMode + ntFileCreationDisposition = fs.NTFileCreationDisposition + ntFileOptions = fs.NTCreateOptions +) + +type ioStatusBlock struct { + Status, Information uintptr +} + +// typedef struct _OBJECT_ATTRIBUTES { +// ULONG Length; +// HANDLE RootDirectory; +// PUNICODE_STRING ObjectName; +// ULONG Attributes; +// PVOID SecurityDescriptor; +// PVOID SecurityQualityOfService; +// } OBJECT_ATTRIBUTES; +// +// https://learn.microsoft.com/en-us/windows/win32/api/ntdef/ns-ntdef-_object_attributes +type objectAttributes struct { + Length uintptr + RootDirectory uintptr + ObjectName *unicodeString + Attributes uintptr + SecurityDescriptor *securityDescriptor + SecurityQoS uintptr +} + +type unicodeString struct { + Length uint16 + MaximumLength uint16 + Buffer uintptr +} + +// typedef struct _SECURITY_DESCRIPTOR { +// BYTE Revision; +// BYTE Sbz1; +// SECURITY_DESCRIPTOR_CONTROL Control; +// PSID Owner; +// PSID Group; +// PACL Sacl; +// PACL Dacl; +// } SECURITY_DESCRIPTOR, *PISECURITY_DESCRIPTOR; +// +// https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-security_descriptor +type securityDescriptor struct { + Revision byte + Sbz1 byte + Control uint16 + Owner uintptr + Group uintptr + Sacl uintptr //revive:disable-line:var-naming SACL, not Sacl + Dacl uintptr //revive:disable-line:var-naming DACL, not Dacl +} + +type ntStatus int32 + +func (status ntStatus) Err() error { + if status >= 0 { + return nil + } + return rtlNtStatusToDosError(status) +} + +var ( + // ErrPipeListenerClosed is returned for pipe operations on listeners that have been closed. + ErrPipeListenerClosed = net.ErrClosed + + errPipeWriteClosed = errors.New("pipe has been closed for write") +) + +type win32Pipe struct { + *win32File + path string +} + +var _ PipeConn = (*win32Pipe)(nil) + +type win32MessageBytePipe struct { + win32Pipe + writeClosed bool + readEOF bool +} + +type pipeAddress string + +func (f *win32Pipe) LocalAddr() net.Addr { + return pipeAddress(f.path) +} + +func (f *win32Pipe) RemoteAddr() net.Addr { + return pipeAddress(f.path) +} + +func (f *win32Pipe) SetDeadline(t time.Time) error { + if err := f.SetReadDeadline(t); err != nil { + return err + } + return f.SetWriteDeadline(t) +} + +func (f *win32Pipe) Disconnect() error { + return disconnectNamedPipe(f.win32File.handle) +} + +// CloseWrite closes the write side of a message pipe in byte mode. +func (f *win32MessageBytePipe) CloseWrite() error { + if f.writeClosed { + return errPipeWriteClosed + } + err := f.win32File.Flush() + if err != nil { + return err + } + _, err = f.win32File.Write(nil) + if err != nil { + return err + } + f.writeClosed = true + return nil +} + +// Write writes bytes to a message pipe in byte mode. Zero-byte writes are ignored, since +// they are used to implement CloseWrite(). +func (f *win32MessageBytePipe) Write(b []byte) (int, error) { + if f.writeClosed { + return 0, errPipeWriteClosed + } + if len(b) == 0 { + return 0, nil + } + return f.win32File.Write(b) +} + +// Read reads bytes from a message pipe in byte mode. A read of a zero-byte message on a message +// mode pipe will return io.EOF, as will all subsequent reads. +func (f *win32MessageBytePipe) Read(b []byte) (int, error) { + if f.readEOF { + return 0, io.EOF + } + n, err := f.win32File.Read(b) + if err == io.EOF { //nolint:errorlint + // If this was the result of a zero-byte read, then + // it is possible that the read was due to a zero-size + // message. Since we are simulating CloseWrite with a + // zero-byte message, ensure that all future Read() calls + // also return EOF. + f.readEOF = true + } else if err == windows.ERROR_MORE_DATA { //nolint:errorlint // err is Errno + // ERROR_MORE_DATA indicates that the pipe's read mode is message mode + // and the message still has more bytes. Treat this as a success, since + // this package presents all named pipes as byte streams. + err = nil + } + return n, err +} + +func (pipeAddress) Network() string { + return "pipe" +} + +func (s pipeAddress) String() string { + return string(s) +} + +// tryDialPipe attempts to dial the pipe at `path` until `ctx` cancellation or timeout. +func tryDialPipe(ctx context.Context, path *string, access fs.AccessMask, impLevel PipeImpLevel) (windows.Handle, error) { + for { + select { + case <-ctx.Done(): + return windows.Handle(0), ctx.Err() + default: + h, err := fs.CreateFile(*path, + access, + 0, // mode + nil, // security attributes + fs.OPEN_EXISTING, + fs.FILE_FLAG_OVERLAPPED|fs.SECURITY_SQOS_PRESENT|fs.FileSQSFlag(impLevel), + 0, // template file handle + ) + if err == nil { + return h, nil + } + if err != windows.ERROR_PIPE_BUSY { //nolint:errorlint // err is Errno + return h, &os.PathError{Err: err, Op: "open", Path: *path} + } + // Wait 10 msec and try again. This is a rather simplistic + // view, as we always try each 10 milliseconds. + time.Sleep(10 * time.Millisecond) + } + } +} + +// DialPipe connects to a named pipe by path, timing out if the connection +// takes longer than the specified duration. If timeout is nil, then we use +// a default timeout of 2 seconds. (We do not use WaitNamedPipe.) +func DialPipe(path string, timeout *time.Duration) (net.Conn, error) { + var absTimeout time.Time + if timeout != nil { + absTimeout = time.Now().Add(*timeout) + } else { + absTimeout = time.Now().Add(2 * time.Second) + } + ctx, cancel := context.WithDeadline(context.Background(), absTimeout) + defer cancel() + conn, err := DialPipeContext(ctx, path) + if errors.Is(err, context.DeadlineExceeded) { + return nil, ErrTimeout + } + return conn, err +} + +// DialPipeContext attempts to connect to a named pipe by `path` until `ctx` +// cancellation or timeout. +func DialPipeContext(ctx context.Context, path string) (net.Conn, error) { + return DialPipeAccess(ctx, path, uint32(fs.GENERIC_READ|fs.GENERIC_WRITE)) +} + +// PipeImpLevel is an enumeration of impersonation levels that may be set +// when calling DialPipeAccessImpersonation. +type PipeImpLevel uint32 + +const ( + PipeImpLevelAnonymous = PipeImpLevel(fs.SECURITY_ANONYMOUS) + PipeImpLevelIdentification = PipeImpLevel(fs.SECURITY_IDENTIFICATION) + PipeImpLevelImpersonation = PipeImpLevel(fs.SECURITY_IMPERSONATION) + PipeImpLevelDelegation = PipeImpLevel(fs.SECURITY_DELEGATION) +) + +// DialPipeAccess attempts to connect to a named pipe by `path` with `access` until `ctx` +// cancellation or timeout. +func DialPipeAccess(ctx context.Context, path string, access uint32) (net.Conn, error) { + return DialPipeAccessImpLevel(ctx, path, access, PipeImpLevelAnonymous) +} + +// DialPipeAccessImpLevel attempts to connect to a named pipe by `path` with +// `access` at `impLevel` until `ctx` cancellation or timeout. The other +// DialPipe* implementations use PipeImpLevelAnonymous. +func DialPipeAccessImpLevel(ctx context.Context, path string, access uint32, impLevel PipeImpLevel) (net.Conn, error) { + var err error + var h windows.Handle + h, err = tryDialPipe(ctx, &path, fs.AccessMask(access), impLevel) + if err != nil { + return nil, err + } + + var flags uint32 + err = getNamedPipeInfo(h, &flags, nil, nil, nil) + if err != nil { + return nil, err + } + + f, err := makeWin32File(h) + if err != nil { + windows.Close(h) + return nil, err + } + + // If the pipe is in message mode, return a message byte pipe, which + // supports CloseWrite(). + if flags&windows.PIPE_TYPE_MESSAGE != 0 { + return &win32MessageBytePipe{ + win32Pipe: win32Pipe{win32File: f, path: path}, + }, nil + } + return &win32Pipe{win32File: f, path: path}, nil +} + +type acceptResponse struct { + f *win32File + err error +} + +type win32PipeListener struct { + firstHandle windows.Handle + path string + config PipeConfig + acceptCh chan (chan acceptResponse) + closeCh chan int + doneCh chan int +} + +func makeServerPipeHandle(path string, sd []byte, c *PipeConfig, first bool) (windows.Handle, error) { + path16, err := windows.UTF16FromString(path) + if err != nil { + return 0, &os.PathError{Op: "open", Path: path, Err: err} + } + + var oa objectAttributes + oa.Length = unsafe.Sizeof(oa) + + var ntPath unicodeString + if err := rtlDosPathNameToNtPathName(&path16[0], + &ntPath, + 0, + 0, + ).Err(); err != nil { + return 0, &os.PathError{Op: "open", Path: path, Err: err} + } + defer windows.LocalFree(windows.Handle(ntPath.Buffer)) //nolint:errcheck + oa.ObjectName = &ntPath + oa.Attributes = windows.OBJ_CASE_INSENSITIVE + + // The security descriptor is only needed for the first pipe. + if first { + if sd != nil { + //todo: does `sdb` need to be allocated on the heap, or can go allocate it? + l := uint32(len(sd)) + sdb, err := windows.LocalAlloc(0, l) + if err != nil { + return 0, fmt.Errorf("LocalAlloc for security descriptor with of length %d: %w", l, err) + } + defer windows.LocalFree(windows.Handle(sdb)) //nolint:errcheck + copy((*[0xffff]byte)(unsafe.Pointer(sdb))[:], sd) + oa.SecurityDescriptor = (*securityDescriptor)(unsafe.Pointer(sdb)) + } else { + // Construct the default named pipe security descriptor. + var dacl uintptr + if err := rtlDefaultNpAcl(&dacl).Err(); err != nil { + return 0, fmt.Errorf("getting default named pipe ACL: %w", err) + } + defer windows.LocalFree(windows.Handle(dacl)) //nolint:errcheck + + sdb := &securityDescriptor{ + Revision: 1, + Control: windows.SE_DACL_PRESENT, + Dacl: dacl, + } + oa.SecurityDescriptor = sdb + } + } + + typ := uint32(windows.FILE_PIPE_REJECT_REMOTE_CLIENTS) + if c.MessageMode { + typ |= windows.FILE_PIPE_MESSAGE_TYPE + } + + disposition := fs.FILE_OPEN + access := fs.GENERIC_READ | fs.GENERIC_WRITE | fs.SYNCHRONIZE + if first { + disposition = fs.FILE_CREATE + // By not asking for read or write access, the named pipe file system + // will put this pipe into an initially disconnected state, blocking + // client connections until the next call with first == false. + access = fs.SYNCHRONIZE + } + + timeout := int64(-50 * 10000) // 50ms + + var ( + h windows.Handle + iosb ioStatusBlock + ) + err = ntCreateNamedPipeFile(&h, + access, + &oa, + &iosb, + fs.FILE_SHARE_READ|fs.FILE_SHARE_WRITE, + disposition, + 0, + typ, + 0, + 0, + 0xffffffff, + uint32(c.InputBufferSize), + uint32(c.OutputBufferSize), + &timeout).Err() + if err != nil { + return 0, &os.PathError{Op: "open", Path: path, Err: err} + } + + runtime.KeepAlive(ntPath) + return h, nil +} + +func (l *win32PipeListener) makeServerPipe() (*win32File, error) { + h, err := makeServerPipeHandle(l.path, nil, &l.config, false) + if err != nil { + return nil, err + } + f, err := makeWin32File(h) + if err != nil { + windows.Close(h) + return nil, err + } + return f, nil +} + +func (l *win32PipeListener) makeConnectedServerPipe() (*win32File, error) { + p, err := l.makeServerPipe() + if err != nil { + return nil, err + } + + // Wait for the client to connect. + ch := make(chan error) + go func(p *win32File) { + ch <- connectPipe(p) + }(p) + + select { + case err = <-ch: + if err != nil { + p.Close() + p = nil + } + case <-l.closeCh: + // Abort the connect request by closing the handle. + p.Close() + p = nil + err = <-ch + if err == nil || err == ErrFileClosed { //nolint:errorlint // err is Errno + err = ErrPipeListenerClosed + } + } + return p, err +} + +func (l *win32PipeListener) listenerRoutine() { + closed := false + for !closed { + select { + case <-l.closeCh: + closed = true + case responseCh := <-l.acceptCh: + var ( + p *win32File + err error + ) + for { + p, err = l.makeConnectedServerPipe() + // If the connection was immediately closed by the client, try + // again. + if err != windows.ERROR_NO_DATA { //nolint:errorlint // err is Errno + break + } + } + responseCh <- acceptResponse{p, err} + closed = err == ErrPipeListenerClosed //nolint:errorlint // err is Errno + } + } + windows.Close(l.firstHandle) + l.firstHandle = 0 + // Notify Close() and Accept() callers that the handle has been closed. + close(l.doneCh) +} + +// PipeConfig contain configuration for the pipe listener. +type PipeConfig struct { + // SecurityDescriptor contains a Windows security descriptor in SDDL format. + SecurityDescriptor string + + // MessageMode determines whether the pipe is in byte or message mode. In either + // case the pipe is read in byte mode by default. The only practical difference in + // this implementation is that CloseWrite() is only supported for message mode pipes; + // CloseWrite() is implemented as a zero-byte write, but zero-byte writes are only + // transferred to the reader (and returned as io.EOF in this implementation) + // when the pipe is in message mode. + MessageMode bool + + // InputBufferSize specifies the size of the input buffer, in bytes. + InputBufferSize int32 + + // OutputBufferSize specifies the size of the output buffer, in bytes. + OutputBufferSize int32 +} + +// ListenPipe creates a listener on a Windows named pipe path, e.g. \\.\pipe\mypipe. +// The pipe must not already exist. +func ListenPipe(path string, c *PipeConfig) (net.Listener, error) { + var ( + sd []byte + err error + ) + if c == nil { + c = &PipeConfig{} + } + if c.SecurityDescriptor != "" { + sd, err = SddlToSecurityDescriptor(c.SecurityDescriptor) + if err != nil { + return nil, err + } + } + h, err := makeServerPipeHandle(path, sd, c, true) + if err != nil { + return nil, err + } + l := &win32PipeListener{ + firstHandle: h, + path: path, + config: *c, + acceptCh: make(chan (chan acceptResponse)), + closeCh: make(chan int), + doneCh: make(chan int), + } + go l.listenerRoutine() + return l, nil +} + +func connectPipe(p *win32File) error { + c, err := p.prepareIO() + if err != nil { + return err + } + defer p.wg.Done() + + err = connectNamedPipe(p.handle, &c.o) + _, err = p.asyncIO(c, nil, 0, err) + if err != nil && err != windows.ERROR_PIPE_CONNECTED { //nolint:errorlint // err is Errno + return err + } + return nil +} + +func (l *win32PipeListener) Accept() (net.Conn, error) { + ch := make(chan acceptResponse) + select { + case l.acceptCh <- ch: + response := <-ch + err := response.err + if err != nil { + return nil, err + } + if l.config.MessageMode { + return &win32MessageBytePipe{ + win32Pipe: win32Pipe{win32File: response.f, path: l.path}, + }, nil + } + return &win32Pipe{win32File: response.f, path: l.path}, nil + case <-l.doneCh: + return nil, ErrPipeListenerClosed + } +} + +func (l *win32PipeListener) Close() error { + select { + case l.closeCh <- 1: + <-l.doneCh + case <-l.doneCh: + } + return nil +} + +func (l *win32PipeListener) Addr() net.Addr { + return pipeAddress(l.path) +} diff --git a/vendor/github.com/microsoft/go-winio/pkg/guid/guid.go b/vendor/github.com/microsoft/go-winio/pkg/guid/guid.go new file mode 100644 index 00000000..48ce4e92 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/pkg/guid/guid.go @@ -0,0 +1,232 @@ +// Package guid provides a GUID type. The backing structure for a GUID is +// identical to that used by the golang.org/x/sys/windows GUID type. +// There are two main binary encodings used for a GUID, the big-endian encoding, +// and the Windows (mixed-endian) encoding. See here for details: +// https://en.wikipedia.org/wiki/Universally_unique_identifier#Encoding +package guid + +import ( + "crypto/rand" + "crypto/sha1" //nolint:gosec // not used for secure application + "encoding" + "encoding/binary" + "fmt" + "strconv" +) + +//go:generate go run golang.org/x/tools/cmd/stringer -type=Variant -trimprefix=Variant -linecomment + +// Variant specifies which GUID variant (or "type") of the GUID. It determines +// how the entirety of the rest of the GUID is interpreted. +type Variant uint8 + +// The variants specified by RFC 4122 section 4.1.1. +const ( + // VariantUnknown specifies a GUID variant which does not conform to one of + // the variant encodings specified in RFC 4122. + VariantUnknown Variant = iota + VariantNCS + VariantRFC4122 // RFC 4122 + VariantMicrosoft + VariantFuture +) + +// Version specifies how the bits in the GUID were generated. For instance, a +// version 4 GUID is randomly generated, and a version 5 is generated from the +// hash of an input string. +type Version uint8 + +func (v Version) String() string { + return strconv.FormatUint(uint64(v), 10) +} + +var _ = (encoding.TextMarshaler)(GUID{}) +var _ = (encoding.TextUnmarshaler)(&GUID{}) + +// NewV4 returns a new version 4 (pseudorandom) GUID, as defined by RFC 4122. +func NewV4() (GUID, error) { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return GUID{}, err + } + + g := FromArray(b) + g.setVersion(4) // Version 4 means randomly generated. + g.setVariant(VariantRFC4122) + + return g, nil +} + +// NewV5 returns a new version 5 (generated from a string via SHA-1 hashing) +// GUID, as defined by RFC 4122. The RFC is unclear on the encoding of the name, +// and the sample code treats it as a series of bytes, so we do the same here. +// +// Some implementations, such as those found on Windows, treat the name as a +// big-endian UTF16 stream of bytes. If that is desired, the string can be +// encoded as such before being passed to this function. +func NewV5(namespace GUID, name []byte) (GUID, error) { + b := sha1.New() //nolint:gosec // not used for secure application + namespaceBytes := namespace.ToArray() + b.Write(namespaceBytes[:]) + b.Write(name) + + a := [16]byte{} + copy(a[:], b.Sum(nil)) + + g := FromArray(a) + g.setVersion(5) // Version 5 means generated from a string. + g.setVariant(VariantRFC4122) + + return g, nil +} + +func fromArray(b [16]byte, order binary.ByteOrder) GUID { + var g GUID + g.Data1 = order.Uint32(b[0:4]) + g.Data2 = order.Uint16(b[4:6]) + g.Data3 = order.Uint16(b[6:8]) + copy(g.Data4[:], b[8:16]) + return g +} + +func (g GUID) toArray(order binary.ByteOrder) [16]byte { + b := [16]byte{} + order.PutUint32(b[0:4], g.Data1) + order.PutUint16(b[4:6], g.Data2) + order.PutUint16(b[6:8], g.Data3) + copy(b[8:16], g.Data4[:]) + return b +} + +// FromArray constructs a GUID from a big-endian encoding array of 16 bytes. +func FromArray(b [16]byte) GUID { + return fromArray(b, binary.BigEndian) +} + +// ToArray returns an array of 16 bytes representing the GUID in big-endian +// encoding. +func (g GUID) ToArray() [16]byte { + return g.toArray(binary.BigEndian) +} + +// FromWindowsArray constructs a GUID from a Windows encoding array of bytes. +func FromWindowsArray(b [16]byte) GUID { + return fromArray(b, binary.LittleEndian) +} + +// ToWindowsArray returns an array of 16 bytes representing the GUID in Windows +// encoding. +func (g GUID) ToWindowsArray() [16]byte { + return g.toArray(binary.LittleEndian) +} + +func (g GUID) String() string { + return fmt.Sprintf( + "%08x-%04x-%04x-%04x-%012x", + g.Data1, + g.Data2, + g.Data3, + g.Data4[:2], + g.Data4[2:]) +} + +// FromString parses a string containing a GUID and returns the GUID. The only +// format currently supported is the `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` +// format. +func FromString(s string) (GUID, error) { + if len(s) != 36 { + return GUID{}, fmt.Errorf("invalid GUID %q", s) + } + if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { + return GUID{}, fmt.Errorf("invalid GUID %q", s) + } + + var g GUID + + data1, err := strconv.ParseUint(s[0:8], 16, 32) + if err != nil { + return GUID{}, fmt.Errorf("invalid GUID %q", s) + } + g.Data1 = uint32(data1) + + data2, err := strconv.ParseUint(s[9:13], 16, 16) + if err != nil { + return GUID{}, fmt.Errorf("invalid GUID %q", s) + } + g.Data2 = uint16(data2) + + data3, err := strconv.ParseUint(s[14:18], 16, 16) + if err != nil { + return GUID{}, fmt.Errorf("invalid GUID %q", s) + } + g.Data3 = uint16(data3) + + for i, x := range []int{19, 21, 24, 26, 28, 30, 32, 34} { + v, err := strconv.ParseUint(s[x:x+2], 16, 8) + if err != nil { + return GUID{}, fmt.Errorf("invalid GUID %q", s) + } + g.Data4[i] = uint8(v) + } + + return g, nil +} + +func (g *GUID) setVariant(v Variant) { + d := g.Data4[0] + switch v { + case VariantNCS: + d = (d & 0x7f) + case VariantRFC4122: + d = (d & 0x3f) | 0x80 + case VariantMicrosoft: + d = (d & 0x1f) | 0xc0 + case VariantFuture: + d = (d & 0x0f) | 0xe0 + case VariantUnknown: + fallthrough + default: + panic(fmt.Sprintf("invalid variant: %d", v)) + } + g.Data4[0] = d +} + +// Variant returns the GUID variant, as defined in RFC 4122. +func (g GUID) Variant() Variant { + b := g.Data4[0] + if b&0x80 == 0 { + return VariantNCS + } else if b&0xc0 == 0x80 { + return VariantRFC4122 + } else if b&0xe0 == 0xc0 { + return VariantMicrosoft + } else if b&0xe0 == 0xe0 { + return VariantFuture + } + return VariantUnknown +} + +func (g *GUID) setVersion(v Version) { + g.Data3 = (g.Data3 & 0x0fff) | (uint16(v) << 12) +} + +// Version returns the GUID version, as defined in RFC 4122. +func (g GUID) Version() Version { + return Version((g.Data3 & 0xF000) >> 12) +} + +// MarshalText returns the textual representation of the GUID. +func (g GUID) MarshalText() ([]byte, error) { + return []byte(g.String()), nil +} + +// UnmarshalText takes the textual representation of a GUID, and unmarhals it +// into this GUID. +func (g *GUID) UnmarshalText(text []byte) error { + g2, err := FromString(string(text)) + if err != nil { + return err + } + *g = g2 + return nil +} diff --git a/vendor/github.com/microsoft/go-winio/pkg/guid/guid_nonwindows.go b/vendor/github.com/microsoft/go-winio/pkg/guid/guid_nonwindows.go new file mode 100644 index 00000000..805bd354 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/pkg/guid/guid_nonwindows.go @@ -0,0 +1,16 @@ +//go:build !windows +// +build !windows + +package guid + +// GUID represents a GUID/UUID. It has the same structure as +// golang.org/x/sys/windows.GUID so that it can be used with functions expecting +// that type. It is defined as its own type as that is only available to builds +// targeted at `windows`. The representation matches that used by native Windows +// code. +type GUID struct { + Data1 uint32 + Data2 uint16 + Data3 uint16 + Data4 [8]byte +} diff --git a/vendor/github.com/microsoft/go-winio/pkg/guid/guid_windows.go b/vendor/github.com/microsoft/go-winio/pkg/guid/guid_windows.go new file mode 100644 index 00000000..27e45ee5 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/pkg/guid/guid_windows.go @@ -0,0 +1,13 @@ +//go:build windows +// +build windows + +package guid + +import "golang.org/x/sys/windows" + +// GUID represents a GUID/UUID. It has the same structure as +// golang.org/x/sys/windows.GUID so that it can be used with functions expecting +// that type. It is defined as its own type so that stringification and +// marshaling can be supported. The representation matches that used by native +// Windows code. +type GUID windows.GUID diff --git a/vendor/github.com/microsoft/go-winio/pkg/guid/variant_string.go b/vendor/github.com/microsoft/go-winio/pkg/guid/variant_string.go new file mode 100644 index 00000000..4076d313 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/pkg/guid/variant_string.go @@ -0,0 +1,27 @@ +// Code generated by "stringer -type=Variant -trimprefix=Variant -linecomment"; DO NOT EDIT. + +package guid + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[VariantUnknown-0] + _ = x[VariantNCS-1] + _ = x[VariantRFC4122-2] + _ = x[VariantMicrosoft-3] + _ = x[VariantFuture-4] +} + +const _Variant_name = "UnknownNCSRFC 4122MicrosoftFuture" + +var _Variant_index = [...]uint8{0, 7, 10, 18, 27, 33} + +func (i Variant) String() string { + if i >= Variant(len(_Variant_index)-1) { + return "Variant(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _Variant_name[_Variant_index[i]:_Variant_index[i+1]] +} diff --git a/vendor/github.com/microsoft/go-winio/privilege.go b/vendor/github.com/microsoft/go-winio/privilege.go new file mode 100644 index 00000000..d9b90b6e --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/privilege.go @@ -0,0 +1,196 @@ +//go:build windows +// +build windows + +package winio + +import ( + "bytes" + "encoding/binary" + "fmt" + "runtime" + "sync" + "unicode/utf16" + + "golang.org/x/sys/windows" +) + +//sys adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) [true] = advapi32.AdjustTokenPrivileges +//sys impersonateSelf(level uint32) (err error) = advapi32.ImpersonateSelf +//sys revertToSelf() (err error) = advapi32.RevertToSelf +//sys openThreadToken(thread windows.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) = advapi32.OpenThreadToken +//sys getCurrentThread() (h windows.Handle) = GetCurrentThread +//sys lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) = advapi32.LookupPrivilegeValueW +//sys lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) = advapi32.LookupPrivilegeNameW +//sys lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) = advapi32.LookupPrivilegeDisplayNameW + +const ( + //revive:disable-next-line:var-naming ALL_CAPS + SE_PRIVILEGE_ENABLED = windows.SE_PRIVILEGE_ENABLED + + //revive:disable-next-line:var-naming ALL_CAPS + ERROR_NOT_ALL_ASSIGNED windows.Errno = windows.ERROR_NOT_ALL_ASSIGNED + + SeBackupPrivilege = "SeBackupPrivilege" + SeRestorePrivilege = "SeRestorePrivilege" + SeSecurityPrivilege = "SeSecurityPrivilege" +) + +var ( + privNames = make(map[string]uint64) + privNameMutex sync.Mutex +) + +// PrivilegeError represents an error enabling privileges. +type PrivilegeError struct { + privileges []uint64 +} + +func (e *PrivilegeError) Error() string { + s := "Could not enable privilege " + if len(e.privileges) > 1 { + s = "Could not enable privileges " + } + for i, p := range e.privileges { + if i != 0 { + s += ", " + } + s += `"` + s += getPrivilegeName(p) + s += `"` + } + return s +} + +// RunWithPrivilege enables a single privilege for a function call. +func RunWithPrivilege(name string, fn func() error) error { + return RunWithPrivileges([]string{name}, fn) +} + +// RunWithPrivileges enables privileges for a function call. +func RunWithPrivileges(names []string, fn func() error) error { + privileges, err := mapPrivileges(names) + if err != nil { + return err + } + runtime.LockOSThread() + defer runtime.UnlockOSThread() + token, err := newThreadToken() + if err != nil { + return err + } + defer releaseThreadToken(token) + err = adjustPrivileges(token, privileges, SE_PRIVILEGE_ENABLED) + if err != nil { + return err + } + return fn() +} + +func mapPrivileges(names []string) ([]uint64, error) { + privileges := make([]uint64, 0, len(names)) + privNameMutex.Lock() + defer privNameMutex.Unlock() + for _, name := range names { + p, ok := privNames[name] + if !ok { + err := lookupPrivilegeValue("", name, &p) + if err != nil { + return nil, err + } + privNames[name] = p + } + privileges = append(privileges, p) + } + return privileges, nil +} + +// EnableProcessPrivileges enables privileges globally for the process. +func EnableProcessPrivileges(names []string) error { + return enableDisableProcessPrivilege(names, SE_PRIVILEGE_ENABLED) +} + +// DisableProcessPrivileges disables privileges globally for the process. +func DisableProcessPrivileges(names []string) error { + return enableDisableProcessPrivilege(names, 0) +} + +func enableDisableProcessPrivilege(names []string, action uint32) error { + privileges, err := mapPrivileges(names) + if err != nil { + return err + } + + p := windows.CurrentProcess() + var token windows.Token + err = windows.OpenProcessToken(p, windows.TOKEN_ADJUST_PRIVILEGES|windows.TOKEN_QUERY, &token) + if err != nil { + return err + } + + defer token.Close() + return adjustPrivileges(token, privileges, action) +} + +func adjustPrivileges(token windows.Token, privileges []uint64, action uint32) error { + var b bytes.Buffer + _ = binary.Write(&b, binary.LittleEndian, uint32(len(privileges))) + for _, p := range privileges { + _ = binary.Write(&b, binary.LittleEndian, p) + _ = binary.Write(&b, binary.LittleEndian, action) + } + prevState := make([]byte, b.Len()) + reqSize := uint32(0) + success, err := adjustTokenPrivileges(token, false, &b.Bytes()[0], uint32(len(prevState)), &prevState[0], &reqSize) + if !success { + return err + } + if err == ERROR_NOT_ALL_ASSIGNED { //nolint:errorlint // err is Errno + return &PrivilegeError{privileges} + } + return nil +} + +func getPrivilegeName(luid uint64) string { + var nameBuffer [256]uint16 + bufSize := uint32(len(nameBuffer)) + err := lookupPrivilegeName("", &luid, &nameBuffer[0], &bufSize) + if err != nil { + return fmt.Sprintf("", luid) + } + + var displayNameBuffer [256]uint16 + displayBufSize := uint32(len(displayNameBuffer)) + var langID uint32 + err = lookupPrivilegeDisplayName("", &nameBuffer[0], &displayNameBuffer[0], &displayBufSize, &langID) + if err != nil { + return fmt.Sprintf("", string(utf16.Decode(nameBuffer[:bufSize]))) + } + + return string(utf16.Decode(displayNameBuffer[:displayBufSize])) +} + +func newThreadToken() (windows.Token, error) { + err := impersonateSelf(windows.SecurityImpersonation) + if err != nil { + return 0, err + } + + var token windows.Token + err = openThreadToken(getCurrentThread(), windows.TOKEN_ADJUST_PRIVILEGES|windows.TOKEN_QUERY, false, &token) + if err != nil { + rerr := revertToSelf() + if rerr != nil { + panic(rerr) + } + return 0, err + } + return token, nil +} + +func releaseThreadToken(h windows.Token) { + err := revertToSelf() + if err != nil { + panic(err) + } + h.Close() +} diff --git a/vendor/github.com/microsoft/go-winio/reparse.go b/vendor/github.com/microsoft/go-winio/reparse.go new file mode 100644 index 00000000..67d1a104 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/reparse.go @@ -0,0 +1,131 @@ +//go:build windows +// +build windows + +package winio + +import ( + "bytes" + "encoding/binary" + "fmt" + "strings" + "unicode/utf16" + "unsafe" +) + +const ( + reparseTagMountPoint = 0xA0000003 + reparseTagSymlink = 0xA000000C +) + +type reparseDataBuffer struct { + ReparseTag uint32 + ReparseDataLength uint16 + Reserved uint16 + SubstituteNameOffset uint16 + SubstituteNameLength uint16 + PrintNameOffset uint16 + PrintNameLength uint16 +} + +// ReparsePoint describes a Win32 symlink or mount point. +type ReparsePoint struct { + Target string + IsMountPoint bool +} + +// UnsupportedReparsePointError is returned when trying to decode a non-symlink or +// mount point reparse point. +type UnsupportedReparsePointError struct { + Tag uint32 +} + +func (e *UnsupportedReparsePointError) Error() string { + return fmt.Sprintf("unsupported reparse point %x", e.Tag) +} + +// DecodeReparsePoint decodes a Win32 REPARSE_DATA_BUFFER structure containing either a symlink +// or a mount point. +func DecodeReparsePoint(b []byte) (*ReparsePoint, error) { + tag := binary.LittleEndian.Uint32(b[0:4]) + return DecodeReparsePointData(tag, b[8:]) +} + +func DecodeReparsePointData(tag uint32, b []byte) (*ReparsePoint, error) { + isMountPoint := false + switch tag { + case reparseTagMountPoint: + isMountPoint = true + case reparseTagSymlink: + default: + return nil, &UnsupportedReparsePointError{tag} + } + nameOffset := 8 + binary.LittleEndian.Uint16(b[4:6]) + if !isMountPoint { + nameOffset += 4 + } + nameLength := binary.LittleEndian.Uint16(b[6:8]) + name := make([]uint16, nameLength/2) + err := binary.Read(bytes.NewReader(b[nameOffset:nameOffset+nameLength]), binary.LittleEndian, &name) + if err != nil { + return nil, err + } + return &ReparsePoint{string(utf16.Decode(name)), isMountPoint}, nil +} + +func isDriveLetter(c byte) bool { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') +} + +// EncodeReparsePoint encodes a Win32 REPARSE_DATA_BUFFER structure describing a symlink or +// mount point. +func EncodeReparsePoint(rp *ReparsePoint) []byte { + // Generate an NT path and determine if this is a relative path. + var ntTarget string + relative := false + if strings.HasPrefix(rp.Target, `\\?\`) { + ntTarget = `\??\` + rp.Target[4:] + } else if strings.HasPrefix(rp.Target, `\\`) { + ntTarget = `\??\UNC\` + rp.Target[2:] + } else if len(rp.Target) >= 2 && isDriveLetter(rp.Target[0]) && rp.Target[1] == ':' { + ntTarget = `\??\` + rp.Target + } else { + ntTarget = rp.Target + relative = true + } + + // The paths must be NUL-terminated even though they are counted strings. + target16 := utf16.Encode([]rune(rp.Target + "\x00")) + ntTarget16 := utf16.Encode([]rune(ntTarget + "\x00")) + + size := int(unsafe.Sizeof(reparseDataBuffer{})) - 8 + size += len(ntTarget16)*2 + len(target16)*2 + + tag := uint32(reparseTagMountPoint) + if !rp.IsMountPoint { + tag = reparseTagSymlink + size += 4 // Add room for symlink flags + } + + data := reparseDataBuffer{ + ReparseTag: tag, + ReparseDataLength: uint16(size), + SubstituteNameOffset: 0, + SubstituteNameLength: uint16((len(ntTarget16) - 1) * 2), + PrintNameOffset: uint16(len(ntTarget16) * 2), + PrintNameLength: uint16((len(target16) - 1) * 2), + } + + var b bytes.Buffer + _ = binary.Write(&b, binary.LittleEndian, &data) + if !rp.IsMountPoint { + flags := uint32(0) + if relative { + flags |= 1 + } + _ = binary.Write(&b, binary.LittleEndian, flags) + } + + _ = binary.Write(&b, binary.LittleEndian, ntTarget16) + _ = binary.Write(&b, binary.LittleEndian, target16) + return b.Bytes() +} diff --git a/vendor/github.com/microsoft/go-winio/sd.go b/vendor/github.com/microsoft/go-winio/sd.go new file mode 100644 index 00000000..c3685e98 --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/sd.go @@ -0,0 +1,133 @@ +//go:build windows +// +build windows + +package winio + +import ( + "errors" + "fmt" + "unsafe" + + "golang.org/x/sys/windows" +) + +//sys lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) = advapi32.LookupAccountNameW +//sys lookupAccountSid(systemName *uint16, sid *byte, name *uint16, nameSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) = advapi32.LookupAccountSidW +//sys convertSidToStringSid(sid *byte, str **uint16) (err error) = advapi32.ConvertSidToStringSidW +//sys convertStringSidToSid(str *uint16, sid **byte) (err error) = advapi32.ConvertStringSidToSidW + +type AccountLookupError struct { + Name string + Err error +} + +func (e *AccountLookupError) Error() string { + if e.Name == "" { + return "lookup account: empty account name specified" + } + var s string + switch { + case errors.Is(e.Err, windows.ERROR_INVALID_SID): + s = "the security ID structure is invalid" + case errors.Is(e.Err, windows.ERROR_NONE_MAPPED): + s = "not found" + default: + s = e.Err.Error() + } + return "lookup account " + e.Name + ": " + s +} + +func (e *AccountLookupError) Unwrap() error { return e.Err } + +type SddlConversionError struct { + Sddl string + Err error +} + +func (e *SddlConversionError) Error() string { + return "convert " + e.Sddl + ": " + e.Err.Error() +} + +func (e *SddlConversionError) Unwrap() error { return e.Err } + +// LookupSidByName looks up the SID of an account by name +// +//revive:disable-next-line:var-naming SID, not Sid +func LookupSidByName(name string) (sid string, err error) { + if name == "" { + return "", &AccountLookupError{name, windows.ERROR_NONE_MAPPED} + } + + var sidSize, sidNameUse, refDomainSize uint32 + err = lookupAccountName(nil, name, nil, &sidSize, nil, &refDomainSize, &sidNameUse) + if err != nil && err != windows.ERROR_INSUFFICIENT_BUFFER { //nolint:errorlint // err is Errno + return "", &AccountLookupError{name, err} + } + sidBuffer := make([]byte, sidSize) + refDomainBuffer := make([]uint16, refDomainSize) + err = lookupAccountName(nil, name, &sidBuffer[0], &sidSize, &refDomainBuffer[0], &refDomainSize, &sidNameUse) + if err != nil { + return "", &AccountLookupError{name, err} + } + var strBuffer *uint16 + err = convertSidToStringSid(&sidBuffer[0], &strBuffer) + if err != nil { + return "", &AccountLookupError{name, err} + } + sid = windows.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(strBuffer))[:]) + _, _ = windows.LocalFree(windows.Handle(unsafe.Pointer(strBuffer))) + return sid, nil +} + +// LookupNameBySid looks up the name of an account by SID +// +//revive:disable-next-line:var-naming SID, not Sid +func LookupNameBySid(sid string) (name string, err error) { + if sid == "" { + return "", &AccountLookupError{sid, windows.ERROR_NONE_MAPPED} + } + + sidBuffer, err := windows.UTF16PtrFromString(sid) + if err != nil { + return "", &AccountLookupError{sid, err} + } + + var sidPtr *byte + if err = convertStringSidToSid(sidBuffer, &sidPtr); err != nil { + return "", &AccountLookupError{sid, err} + } + defer windows.LocalFree(windows.Handle(unsafe.Pointer(sidPtr))) //nolint:errcheck + + var nameSize, refDomainSize, sidNameUse uint32 + err = lookupAccountSid(nil, sidPtr, nil, &nameSize, nil, &refDomainSize, &sidNameUse) + if err != nil && err != windows.ERROR_INSUFFICIENT_BUFFER { //nolint:errorlint // err is Errno + return "", &AccountLookupError{sid, err} + } + + nameBuffer := make([]uint16, nameSize) + refDomainBuffer := make([]uint16, refDomainSize) + err = lookupAccountSid(nil, sidPtr, &nameBuffer[0], &nameSize, &refDomainBuffer[0], &refDomainSize, &sidNameUse) + if err != nil { + return "", &AccountLookupError{sid, err} + } + + name = windows.UTF16ToString(nameBuffer) + return name, nil +} + +func SddlToSecurityDescriptor(sddl string) ([]byte, error) { + sd, err := windows.SecurityDescriptorFromString(sddl) + if err != nil { + return nil, &SddlConversionError{Sddl: sddl, Err: err} + } + b := unsafe.Slice((*byte)(unsafe.Pointer(sd)), sd.Length()) + return b, nil +} + +func SecurityDescriptorToSddl(sd []byte) (string, error) { + if l := int(unsafe.Sizeof(windows.SECURITY_DESCRIPTOR{})); len(sd) < l { + return "", fmt.Errorf("SecurityDescriptor (%d) smaller than expected (%d): %w", len(sd), l, windows.ERROR_INCORRECT_SIZE) + } + s := (*windows.SECURITY_DESCRIPTOR)(unsafe.Pointer(&sd[0])) + return s.String(), nil +} diff --git a/vendor/github.com/microsoft/go-winio/syscall.go b/vendor/github.com/microsoft/go-winio/syscall.go new file mode 100644 index 00000000..a6ca111b --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/syscall.go @@ -0,0 +1,5 @@ +//go:build windows + +package winio + +//go:generate go run github.com/Microsoft/go-winio/tools/mkwinsyscall -output zsyscall_windows.go ./*.go diff --git a/vendor/github.com/microsoft/go-winio/zsyscall_windows.go b/vendor/github.com/microsoft/go-winio/zsyscall_windows.go new file mode 100644 index 00000000..89b66eda --- /dev/null +++ b/vendor/github.com/microsoft/go-winio/zsyscall_windows.go @@ -0,0 +1,378 @@ +//go:build windows + +// Code generated by 'go generate' using "github.com/Microsoft/go-winio/tools/mkwinsyscall"; DO NOT EDIT. + +package winio + +import ( + "syscall" + "unsafe" + + "golang.org/x/sys/windows" +) + +var _ unsafe.Pointer + +// Do the interface allocations only once for common +// Errno values. +const ( + errnoERROR_IO_PENDING = 997 +) + +var ( + errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) + errERROR_EINVAL error = syscall.EINVAL +) + +// errnoErr returns common boxed Errno values, to prevent +// allocations at runtime. +func errnoErr(e syscall.Errno) error { + switch e { + case 0: + return errERROR_EINVAL + case errnoERROR_IO_PENDING: + return errERROR_IO_PENDING + } + return e +} + +var ( + modadvapi32 = windows.NewLazySystemDLL("advapi32.dll") + modkernel32 = windows.NewLazySystemDLL("kernel32.dll") + modntdll = windows.NewLazySystemDLL("ntdll.dll") + modws2_32 = windows.NewLazySystemDLL("ws2_32.dll") + + procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges") + procConvertSidToStringSidW = modadvapi32.NewProc("ConvertSidToStringSidW") + procConvertStringSidToSidW = modadvapi32.NewProc("ConvertStringSidToSidW") + procImpersonateSelf = modadvapi32.NewProc("ImpersonateSelf") + procLookupAccountNameW = modadvapi32.NewProc("LookupAccountNameW") + procLookupAccountSidW = modadvapi32.NewProc("LookupAccountSidW") + procLookupPrivilegeDisplayNameW = modadvapi32.NewProc("LookupPrivilegeDisplayNameW") + procLookupPrivilegeNameW = modadvapi32.NewProc("LookupPrivilegeNameW") + procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW") + procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken") + procRevertToSelf = modadvapi32.NewProc("RevertToSelf") + procBackupRead = modkernel32.NewProc("BackupRead") + procBackupWrite = modkernel32.NewProc("BackupWrite") + procCancelIoEx = modkernel32.NewProc("CancelIoEx") + procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe") + procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort") + procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW") + procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe") + procGetCurrentThread = modkernel32.NewProc("GetCurrentThread") + procGetNamedPipeHandleStateW = modkernel32.NewProc("GetNamedPipeHandleStateW") + procGetNamedPipeInfo = modkernel32.NewProc("GetNamedPipeInfo") + procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus") + procSetFileCompletionNotificationModes = modkernel32.NewProc("SetFileCompletionNotificationModes") + procNtCreateNamedPipeFile = modntdll.NewProc("NtCreateNamedPipeFile") + procRtlDefaultNpAcl = modntdll.NewProc("RtlDefaultNpAcl") + procRtlDosPathNameToNtPathName_U = modntdll.NewProc("RtlDosPathNameToNtPathName_U") + procRtlNtStatusToDosErrorNoTeb = modntdll.NewProc("RtlNtStatusToDosErrorNoTeb") + procWSAGetOverlappedResult = modws2_32.NewProc("WSAGetOverlappedResult") +) + +func adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) { + var _p0 uint32 + if releaseAll { + _p0 = 1 + } + r0, _, e1 := syscall.SyscallN(procAdjustTokenPrivileges.Addr(), uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(input)), uintptr(outputSize), uintptr(unsafe.Pointer(output)), uintptr(unsafe.Pointer(requiredSize))) + success = r0 != 0 + if true { + err = errnoErr(e1) + } + return +} + +func convertSidToStringSid(sid *byte, str **uint16) (err error) { + r1, _, e1 := syscall.SyscallN(procConvertSidToStringSidW.Addr(), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(str))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func convertStringSidToSid(str *uint16, sid **byte) (err error) { + r1, _, e1 := syscall.SyscallN(procConvertStringSidToSidW.Addr(), uintptr(unsafe.Pointer(str)), uintptr(unsafe.Pointer(sid))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func impersonateSelf(level uint32) (err error) { + r1, _, e1 := syscall.SyscallN(procImpersonateSelf.Addr(), uintptr(level)) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(accountName) + if err != nil { + return + } + return _lookupAccountName(systemName, _p0, sid, sidSize, refDomain, refDomainSize, sidNameUse) +} + +func _lookupAccountName(systemName *uint16, accountName *uint16, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) { + r1, _, e1 := syscall.SyscallN(procLookupAccountNameW.Addr(), uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(accountName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(sidSize)), uintptr(unsafe.Pointer(refDomain)), uintptr(unsafe.Pointer(refDomainSize)), uintptr(unsafe.Pointer(sidNameUse))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func lookupAccountSid(systemName *uint16, sid *byte, name *uint16, nameSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) { + r1, _, e1 := syscall.SyscallN(procLookupAccountSidW.Addr(), uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameSize)), uintptr(unsafe.Pointer(refDomain)), uintptr(unsafe.Pointer(refDomainSize)), uintptr(unsafe.Pointer(sidNameUse))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(systemName) + if err != nil { + return + } + return _lookupPrivilegeDisplayName(_p0, name, buffer, size, languageId) +} + +func _lookupPrivilegeDisplayName(systemName *uint16, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) { + r1, _, e1 := syscall.SyscallN(procLookupPrivilegeDisplayNameW.Addr(), uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), uintptr(unsafe.Pointer(languageId))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(systemName) + if err != nil { + return + } + return _lookupPrivilegeName(_p0, luid, buffer, size) +} + +func _lookupPrivilegeName(systemName *uint16, luid *uint64, buffer *uint16, size *uint32) (err error) { + r1, _, e1 := syscall.SyscallN(procLookupPrivilegeNameW.Addr(), uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(luid)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(systemName) + if err != nil { + return + } + var _p1 *uint16 + _p1, err = syscall.UTF16PtrFromString(name) + if err != nil { + return + } + return _lookupPrivilegeValue(_p0, _p1, luid) +} + +func _lookupPrivilegeValue(systemName *uint16, name *uint16, luid *uint64) (err error) { + r1, _, e1 := syscall.SyscallN(procLookupPrivilegeValueW.Addr(), uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(luid))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func openThreadToken(thread windows.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) { + var _p0 uint32 + if openAsSelf { + _p0 = 1 + } + r1, _, e1 := syscall.SyscallN(procOpenThreadToken.Addr(), uintptr(thread), uintptr(accessMask), uintptr(_p0), uintptr(unsafe.Pointer(token))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func revertToSelf() (err error) { + r1, _, e1 := syscall.SyscallN(procRevertToSelf.Addr()) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func backupRead(h windows.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) { + var _p0 *byte + if len(b) > 0 { + _p0 = &b[0] + } + var _p1 uint32 + if abort { + _p1 = 1 + } + var _p2 uint32 + if processSecurity { + _p2 = 1 + } + r1, _, e1 := syscall.SyscallN(procBackupRead.Addr(), uintptr(h), uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(unsafe.Pointer(bytesRead)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(context))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func backupWrite(h windows.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) { + var _p0 *byte + if len(b) > 0 { + _p0 = &b[0] + } + var _p1 uint32 + if abort { + _p1 = 1 + } + var _p2 uint32 + if processSecurity { + _p2 = 1 + } + r1, _, e1 := syscall.SyscallN(procBackupWrite.Addr(), uintptr(h), uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(unsafe.Pointer(bytesWritten)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(context))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func cancelIoEx(file windows.Handle, o *windows.Overlapped) (err error) { + r1, _, e1 := syscall.SyscallN(procCancelIoEx.Addr(), uintptr(file), uintptr(unsafe.Pointer(o))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func connectNamedPipe(pipe windows.Handle, o *windows.Overlapped) (err error) { + r1, _, e1 := syscall.SyscallN(procConnectNamedPipe.Addr(), uintptr(pipe), uintptr(unsafe.Pointer(o))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func createIoCompletionPort(file windows.Handle, port windows.Handle, key uintptr, threadCount uint32) (newport windows.Handle, err error) { + r0, _, e1 := syscall.SyscallN(procCreateIoCompletionPort.Addr(), uintptr(file), uintptr(port), uintptr(key), uintptr(threadCount)) + newport = windows.Handle(r0) + if newport == 0 { + err = errnoErr(e1) + } + return +} + +func createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *windows.SecurityAttributes) (handle windows.Handle, err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(name) + if err != nil { + return + } + return _createNamedPipe(_p0, flags, pipeMode, maxInstances, outSize, inSize, defaultTimeout, sa) +} + +func _createNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *windows.SecurityAttributes) (handle windows.Handle, err error) { + r0, _, e1 := syscall.SyscallN(procCreateNamedPipeW.Addr(), uintptr(unsafe.Pointer(name)), uintptr(flags), uintptr(pipeMode), uintptr(maxInstances), uintptr(outSize), uintptr(inSize), uintptr(defaultTimeout), uintptr(unsafe.Pointer(sa))) + handle = windows.Handle(r0) + if handle == windows.InvalidHandle { + err = errnoErr(e1) + } + return +} + +func disconnectNamedPipe(pipe windows.Handle) (err error) { + r1, _, e1 := syscall.SyscallN(procDisconnectNamedPipe.Addr(), uintptr(pipe)) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func getCurrentThread() (h windows.Handle) { + r0, _, _ := syscall.SyscallN(procGetCurrentThread.Addr()) + h = windows.Handle(r0) + return +} + +func getNamedPipeHandleState(pipe windows.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) { + r1, _, e1 := syscall.SyscallN(procGetNamedPipeHandleStateW.Addr(), uintptr(pipe), uintptr(unsafe.Pointer(state)), uintptr(unsafe.Pointer(curInstances)), uintptr(unsafe.Pointer(maxCollectionCount)), uintptr(unsafe.Pointer(collectDataTimeout)), uintptr(unsafe.Pointer(userName)), uintptr(maxUserNameSize)) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func getNamedPipeInfo(pipe windows.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) { + r1, _, e1 := syscall.SyscallN(procGetNamedPipeInfo.Addr(), uintptr(pipe), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(outSize)), uintptr(unsafe.Pointer(inSize)), uintptr(unsafe.Pointer(maxInstances))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func getQueuedCompletionStatus(port windows.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) { + r1, _, e1 := syscall.SyscallN(procGetQueuedCompletionStatus.Addr(), uintptr(port), uintptr(unsafe.Pointer(bytes)), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(o)), uintptr(timeout)) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func setFileCompletionNotificationModes(h windows.Handle, flags uint8) (err error) { + r1, _, e1 := syscall.SyscallN(procSetFileCompletionNotificationModes.Addr(), uintptr(h), uintptr(flags)) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func ntCreateNamedPipeFile(pipe *windows.Handle, access ntAccessMask, oa *objectAttributes, iosb *ioStatusBlock, share ntFileShareMode, disposition ntFileCreationDisposition, options ntFileOptions, typ uint32, readMode uint32, completionMode uint32, maxInstances uint32, inboundQuota uint32, outputQuota uint32, timeout *int64) (status ntStatus) { + r0, _, _ := syscall.SyscallN(procNtCreateNamedPipeFile.Addr(), uintptr(unsafe.Pointer(pipe)), uintptr(access), uintptr(unsafe.Pointer(oa)), uintptr(unsafe.Pointer(iosb)), uintptr(share), uintptr(disposition), uintptr(options), uintptr(typ), uintptr(readMode), uintptr(completionMode), uintptr(maxInstances), uintptr(inboundQuota), uintptr(outputQuota), uintptr(unsafe.Pointer(timeout))) + status = ntStatus(r0) + return +} + +func rtlDefaultNpAcl(dacl *uintptr) (status ntStatus) { + r0, _, _ := syscall.SyscallN(procRtlDefaultNpAcl.Addr(), uintptr(unsafe.Pointer(dacl))) + status = ntStatus(r0) + return +} + +func rtlDosPathNameToNtPathName(name *uint16, ntName *unicodeString, filePart uintptr, reserved uintptr) (status ntStatus) { + r0, _, _ := syscall.SyscallN(procRtlDosPathNameToNtPathName_U.Addr(), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(ntName)), uintptr(filePart), uintptr(reserved)) + status = ntStatus(r0) + return +} + +func rtlNtStatusToDosError(status ntStatus) (winerr error) { + r0, _, _ := syscall.SyscallN(procRtlNtStatusToDosErrorNoTeb.Addr(), uintptr(status)) + if r0 != 0 { + winerr = syscall.Errno(r0) + } + return +} + +func wsaGetOverlappedResult(h windows.Handle, o *windows.Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) { + var _p0 uint32 + if wait { + _p0 = 1 + } + r1, _, e1 := syscall.SyscallN(procWSAGetOverlappedResult.Addr(), uintptr(h), uintptr(unsafe.Pointer(o)), uintptr(unsafe.Pointer(bytes)), uintptr(_p0), uintptr(unsafe.Pointer(flags))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} diff --git a/vendor/github.com/moby/docker-image-spec/LICENSE b/vendor/github.com/moby/docker-image-spec/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/vendor/github.com/moby/docker-image-spec/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/moby/docker-image-spec/specs-go/v1/image.go b/vendor/github.com/moby/docker-image-spec/specs-go/v1/image.go new file mode 100644 index 00000000..16726176 --- /dev/null +++ b/vendor/github.com/moby/docker-image-spec/specs-go/v1/image.go @@ -0,0 +1,54 @@ +package v1 + +import ( + "time" + + ocispec "github.com/opencontainers/image-spec/specs-go/v1" +) + +const DockerOCIImageMediaType = "application/vnd.docker.container.image.v1+json" + +// DockerOCIImage is a ocispec.Image extended with Docker specific Config. +type DockerOCIImage struct { + ocispec.Image + + // Shadow ocispec.Image.Config + Config DockerOCIImageConfig `json:"config,omitempty"` +} + +// DockerOCIImageConfig is a ocispec.ImageConfig extended with Docker specific fields. +type DockerOCIImageConfig struct { + ocispec.ImageConfig + + DockerOCIImageConfigExt +} + +// DockerOCIImageConfigExt contains Docker-specific fields in DockerImageConfig. +type DockerOCIImageConfigExt struct { + Healthcheck *HealthcheckConfig `json:",omitempty"` // Healthcheck describes how to check the container is healthy + + OnBuild []string `json:",omitempty"` // ONBUILD metadata that were defined on the image Dockerfile + Shell []string `json:",omitempty"` // Shell for shell-form of RUN, CMD, ENTRYPOINT +} + +// HealthcheckConfig holds configuration settings for the HEALTHCHECK feature. +type HealthcheckConfig struct { + // Test is the test to perform to check that the container is healthy. + // An empty slice means to inherit the default. + // The options are: + // {} : inherit healthcheck + // {"NONE"} : disable healthcheck + // {"CMD", args...} : exec arguments directly + // {"CMD-SHELL", command} : run command with system's default shell + Test []string `json:",omitempty"` + + // Zero means to inherit. Durations are expressed as integer nanoseconds. + Interval time.Duration `json:",omitempty"` // Interval is the time to wait between checks. + Timeout time.Duration `json:",omitempty"` // Timeout is the time to wait before considering the check to have hung. + StartPeriod time.Duration `json:",omitempty"` // The start period for the container to initialize before the retries starts to count down. + StartInterval time.Duration `json:",omitempty"` // The interval to attempt healthchecks at during the start period + + // Retries is the number of consecutive failures needed to consider a container as unhealthy. + // Zero means inherit. + Retries int `json:",omitempty"` +} diff --git a/vendor/github.com/moby/sys/user/LICENSE b/vendor/github.com/moby/sys/user/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/github.com/moby/sys/user/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/moby/sys/user/lookup_unix.go b/vendor/github.com/moby/sys/user/lookup_unix.go new file mode 100644 index 00000000..f95c1409 --- /dev/null +++ b/vendor/github.com/moby/sys/user/lookup_unix.go @@ -0,0 +1,157 @@ +//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris +// +build darwin dragonfly freebsd linux netbsd openbsd solaris + +package user + +import ( + "io" + "os" + "strconv" + + "golang.org/x/sys/unix" +) + +// Unix-specific path to the passwd and group formatted files. +const ( + unixPasswdPath = "/etc/passwd" + unixGroupPath = "/etc/group" +) + +// LookupUser looks up a user by their username in /etc/passwd. If the user +// cannot be found (or there is no /etc/passwd file on the filesystem), then +// LookupUser returns an error. +func LookupUser(username string) (User, error) { + return lookupUserFunc(func(u User) bool { + return u.Name == username + }) +} + +// LookupUid looks up a user by their user id in /etc/passwd. If the user cannot +// be found (or there is no /etc/passwd file on the filesystem), then LookupId +// returns an error. +func LookupUid(uid int) (User, error) { + return lookupUserFunc(func(u User) bool { + return u.Uid == uid + }) +} + +func lookupUserFunc(filter func(u User) bool) (User, error) { + // Get operating system-specific passwd reader-closer. + passwd, err := GetPasswd() + if err != nil { + return User{}, err + } + defer passwd.Close() + + // Get the users. + users, err := ParsePasswdFilter(passwd, filter) + if err != nil { + return User{}, err + } + + // No user entries found. + if len(users) == 0 { + return User{}, ErrNoPasswdEntries + } + + // Assume the first entry is the "correct" one. + return users[0], nil +} + +// LookupGroup looks up a group by its name in /etc/group. If the group cannot +// be found (or there is no /etc/group file on the filesystem), then LookupGroup +// returns an error. +func LookupGroup(groupname string) (Group, error) { + return lookupGroupFunc(func(g Group) bool { + return g.Name == groupname + }) +} + +// LookupGid looks up a group by its group id in /etc/group. If the group cannot +// be found (or there is no /etc/group file on the filesystem), then LookupGid +// returns an error. +func LookupGid(gid int) (Group, error) { + return lookupGroupFunc(func(g Group) bool { + return g.Gid == gid + }) +} + +func lookupGroupFunc(filter func(g Group) bool) (Group, error) { + // Get operating system-specific group reader-closer. + group, err := GetGroup() + if err != nil { + return Group{}, err + } + defer group.Close() + + // Get the users. + groups, err := ParseGroupFilter(group, filter) + if err != nil { + return Group{}, err + } + + // No user entries found. + if len(groups) == 0 { + return Group{}, ErrNoGroupEntries + } + + // Assume the first entry is the "correct" one. + return groups[0], nil +} + +func GetPasswdPath() (string, error) { + return unixPasswdPath, nil +} + +func GetPasswd() (io.ReadCloser, error) { + return os.Open(unixPasswdPath) +} + +func GetGroupPath() (string, error) { + return unixGroupPath, nil +} + +func GetGroup() (io.ReadCloser, error) { + return os.Open(unixGroupPath) +} + +// CurrentUser looks up the current user by their user id in /etc/passwd. If the +// user cannot be found (or there is no /etc/passwd file on the filesystem), +// then CurrentUser returns an error. +func CurrentUser() (User, error) { + return LookupUid(unix.Getuid()) +} + +// CurrentGroup looks up the current user's group by their primary group id's +// entry in /etc/passwd. If the group cannot be found (or there is no +// /etc/group file on the filesystem), then CurrentGroup returns an error. +func CurrentGroup() (Group, error) { + return LookupGid(unix.Getgid()) +} + +func currentUserSubIDs(fileName string) ([]SubID, error) { + u, err := CurrentUser() + if err != nil { + return nil, err + } + filter := func(entry SubID) bool { + return entry.Name == u.Name || entry.Name == strconv.Itoa(u.Uid) + } + return ParseSubIDFileFilter(fileName, filter) +} + +func CurrentUserSubUIDs() ([]SubID, error) { + return currentUserSubIDs("/etc/subuid") +} + +func CurrentUserSubGIDs() ([]SubID, error) { + return currentUserSubIDs("/etc/subgid") +} + +func CurrentProcessUIDMap() ([]IDMap, error) { + return ParseIDMapFile("/proc/self/uid_map") +} + +func CurrentProcessGIDMap() ([]IDMap, error) { + return ParseIDMapFile("/proc/self/gid_map") +} diff --git a/vendor/github.com/moby/sys/user/user.go b/vendor/github.com/moby/sys/user/user.go new file mode 100644 index 00000000..198c4936 --- /dev/null +++ b/vendor/github.com/moby/sys/user/user.go @@ -0,0 +1,604 @@ +package user + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "io" + "os" + "strconv" + "strings" +) + +const ( + minID = 0 + maxID = 1<<31 - 1 // for 32-bit systems compatibility +) + +var ( + // ErrNoPasswdEntries is returned if no matching entries were found in /etc/group. + ErrNoPasswdEntries = errors.New("no matching entries in passwd file") + // ErrNoGroupEntries is returned if no matching entries were found in /etc/passwd. + ErrNoGroupEntries = errors.New("no matching entries in group file") + // ErrRange is returned if a UID or GID is outside of the valid range. + ErrRange = fmt.Errorf("uids and gids must be in range %d-%d", minID, maxID) +) + +type User struct { + Name string + Pass string + Uid int + Gid int + Gecos string + Home string + Shell string +} + +type Group struct { + Name string + Pass string + Gid int + List []string +} + +// SubID represents an entry in /etc/sub{u,g}id +type SubID struct { + Name string + SubID int64 + Count int64 +} + +// IDMap represents an entry in /proc/PID/{u,g}id_map +type IDMap struct { + ID int64 + ParentID int64 + Count int64 +} + +func parseLine(line []byte, v ...interface{}) { + parseParts(bytes.Split(line, []byte(":")), v...) +} + +func parseParts(parts [][]byte, v ...interface{}) { + if len(parts) == 0 { + return + } + + for i, p := range parts { + // Ignore cases where we don't have enough fields to populate the arguments. + // Some configuration files like to misbehave. + if len(v) <= i { + break + } + + // Use the type of the argument to figure out how to parse it, scanf() style. + // This is legit. + switch e := v[i].(type) { + case *string: + *e = string(p) + case *int: + // "numbers", with conversion errors ignored because of some misbehaving configuration files. + *e, _ = strconv.Atoi(string(p)) + case *int64: + *e, _ = strconv.ParseInt(string(p), 10, 64) + case *[]string: + // Comma-separated lists. + if len(p) != 0 { + *e = strings.Split(string(p), ",") + } else { + *e = []string{} + } + default: + // Someone goof'd when writing code using this function. Scream so they can hear us. + panic(fmt.Sprintf("parseLine only accepts {*string, *int, *int64, *[]string} as arguments! %#v is not a pointer!", e)) + } + } +} + +func ParsePasswdFile(path string) ([]User, error) { + passwd, err := os.Open(path) + if err != nil { + return nil, err + } + defer passwd.Close() + return ParsePasswd(passwd) +} + +func ParsePasswd(passwd io.Reader) ([]User, error) { + return ParsePasswdFilter(passwd, nil) +} + +func ParsePasswdFileFilter(path string, filter func(User) bool) ([]User, error) { + passwd, err := os.Open(path) + if err != nil { + return nil, err + } + defer passwd.Close() + return ParsePasswdFilter(passwd, filter) +} + +func ParsePasswdFilter(r io.Reader, filter func(User) bool) ([]User, error) { + if r == nil { + return nil, errors.New("nil source for passwd-formatted data") + } + + var ( + s = bufio.NewScanner(r) + out = []User{} + ) + + for s.Scan() { + line := bytes.TrimSpace(s.Bytes()) + if len(line) == 0 { + continue + } + + // see: man 5 passwd + // name:password:UID:GID:GECOS:directory:shell + // Name:Pass:Uid:Gid:Gecos:Home:Shell + // root:x:0:0:root:/root:/bin/bash + // adm:x:3:4:adm:/var/adm:/bin/false + p := User{} + parseLine(line, &p.Name, &p.Pass, &p.Uid, &p.Gid, &p.Gecos, &p.Home, &p.Shell) + + if filter == nil || filter(p) { + out = append(out, p) + } + } + if err := s.Err(); err != nil { + return nil, err + } + + return out, nil +} + +func ParseGroupFile(path string) ([]Group, error) { + group, err := os.Open(path) + if err != nil { + return nil, err + } + + defer group.Close() + return ParseGroup(group) +} + +func ParseGroup(group io.Reader) ([]Group, error) { + return ParseGroupFilter(group, nil) +} + +func ParseGroupFileFilter(path string, filter func(Group) bool) ([]Group, error) { + group, err := os.Open(path) + if err != nil { + return nil, err + } + defer group.Close() + return ParseGroupFilter(group, filter) +} + +func ParseGroupFilter(r io.Reader, filter func(Group) bool) ([]Group, error) { + if r == nil { + return nil, errors.New("nil source for group-formatted data") + } + rd := bufio.NewReader(r) + out := []Group{} + + // Read the file line-by-line. + for { + var ( + isPrefix bool + wholeLine []byte + err error + ) + + // Read the next line. We do so in chunks (as much as reader's + // buffer is able to keep), check if we read enough columns + // already on each step and store final result in wholeLine. + for { + var line []byte + line, isPrefix, err = rd.ReadLine() + if err != nil { + // We should return no error if EOF is reached + // without a match. + if err == io.EOF { + err = nil + } + return out, err + } + + // Simple common case: line is short enough to fit in a + // single reader's buffer. + if !isPrefix && len(wholeLine) == 0 { + wholeLine = line + break + } + + wholeLine = append(wholeLine, line...) + + // Check if we read the whole line already. + if !isPrefix { + break + } + } + + // There's no spec for /etc/passwd or /etc/group, but we try to follow + // the same rules as the glibc parser, which allows comments and blank + // space at the beginning of a line. + wholeLine = bytes.TrimSpace(wholeLine) + if len(wholeLine) == 0 || wholeLine[0] == '#' { + continue + } + + // see: man 5 group + // group_name:password:GID:user_list + // Name:Pass:Gid:List + // root:x:0:root + // adm:x:4:root,adm,daemon + p := Group{} + parseLine(wholeLine, &p.Name, &p.Pass, &p.Gid, &p.List) + + if filter == nil || filter(p) { + out = append(out, p) + } + } +} + +type ExecUser struct { + Uid int + Gid int + Sgids []int + Home string +} + +// GetExecUserPath is a wrapper for GetExecUser. It reads data from each of the +// given file paths and uses that data as the arguments to GetExecUser. If the +// files cannot be opened for any reason, the error is ignored and a nil +// io.Reader is passed instead. +func GetExecUserPath(userSpec string, defaults *ExecUser, passwdPath, groupPath string) (*ExecUser, error) { + var passwd, group io.Reader + + if passwdFile, err := os.Open(passwdPath); err == nil { + passwd = passwdFile + defer passwdFile.Close() + } + + if groupFile, err := os.Open(groupPath); err == nil { + group = groupFile + defer groupFile.Close() + } + + return GetExecUser(userSpec, defaults, passwd, group) +} + +// GetExecUser parses a user specification string (using the passwd and group +// readers as sources for /etc/passwd and /etc/group data, respectively). In +// the case of blank fields or missing data from the sources, the values in +// defaults is used. +// +// GetExecUser will return an error if a user or group literal could not be +// found in any entry in passwd and group respectively. +// +// Examples of valid user specifications are: +// - "" +// - "user" +// - "uid" +// - "user:group" +// - "uid:gid +// - "user:gid" +// - "uid:group" +// +// It should be noted that if you specify a numeric user or group id, they will +// not be evaluated as usernames (only the metadata will be filled). So attempting +// to parse a user with user.Name = "1337" will produce the user with a UID of +// 1337. +func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) (*ExecUser, error) { + if defaults == nil { + defaults = new(ExecUser) + } + + // Copy over defaults. + user := &ExecUser{ + Uid: defaults.Uid, + Gid: defaults.Gid, + Sgids: defaults.Sgids, + Home: defaults.Home, + } + + // Sgids slice *cannot* be nil. + if user.Sgids == nil { + user.Sgids = []int{} + } + + // Allow for userArg to have either "user" syntax, or optionally "user:group" syntax + var userArg, groupArg string + parseLine([]byte(userSpec), &userArg, &groupArg) + + // Convert userArg and groupArg to be numeric, so we don't have to execute + // Atoi *twice* for each iteration over lines. + uidArg, uidErr := strconv.Atoi(userArg) + gidArg, gidErr := strconv.Atoi(groupArg) + + // Find the matching user. + users, err := ParsePasswdFilter(passwd, func(u User) bool { + if userArg == "" { + // Default to current state of the user. + return u.Uid == user.Uid + } + + if uidErr == nil { + // If the userArg is numeric, always treat it as a UID. + return uidArg == u.Uid + } + + return u.Name == userArg + }) + + // If we can't find the user, we have to bail. + if err != nil && passwd != nil { + if userArg == "" { + userArg = strconv.Itoa(user.Uid) + } + return nil, fmt.Errorf("unable to find user %s: %w", userArg, err) + } + + var matchedUserName string + if len(users) > 0 { + // First match wins, even if there's more than one matching entry. + matchedUserName = users[0].Name + user.Uid = users[0].Uid + user.Gid = users[0].Gid + user.Home = users[0].Home + } else if userArg != "" { + // If we can't find a user with the given username, the only other valid + // option is if it's a numeric username with no associated entry in passwd. + + if uidErr != nil { + // Not numeric. + return nil, fmt.Errorf("unable to find user %s: %w", userArg, ErrNoPasswdEntries) + } + user.Uid = uidArg + + // Must be inside valid uid range. + if user.Uid < minID || user.Uid > maxID { + return nil, ErrRange + } + + // Okay, so it's numeric. We can just roll with this. + } + + // On to the groups. If we matched a username, we need to do this because of + // the supplementary group IDs. + if groupArg != "" || matchedUserName != "" { + groups, err := ParseGroupFilter(group, func(g Group) bool { + // If the group argument isn't explicit, we'll just search for it. + if groupArg == "" { + // Check if user is a member of this group. + for _, u := range g.List { + if u == matchedUserName { + return true + } + } + return false + } + + if gidErr == nil { + // If the groupArg is numeric, always treat it as a GID. + return gidArg == g.Gid + } + + return g.Name == groupArg + }) + if err != nil && group != nil { + return nil, fmt.Errorf("unable to find groups for spec %v: %w", matchedUserName, err) + } + + // Only start modifying user.Gid if it is in explicit form. + if groupArg != "" { + if len(groups) > 0 { + // First match wins, even if there's more than one matching entry. + user.Gid = groups[0].Gid + } else { + // If we can't find a group with the given name, the only other valid + // option is if it's a numeric group name with no associated entry in group. + + if gidErr != nil { + // Not numeric. + return nil, fmt.Errorf("unable to find group %s: %w", groupArg, ErrNoGroupEntries) + } + user.Gid = gidArg + + // Must be inside valid gid range. + if user.Gid < minID || user.Gid > maxID { + return nil, ErrRange + } + + // Okay, so it's numeric. We can just roll with this. + } + } else if len(groups) > 0 { + // Supplementary group ids only make sense if in the implicit form. + user.Sgids = make([]int, len(groups)) + for i, group := range groups { + user.Sgids[i] = group.Gid + } + } + } + + return user, nil +} + +// GetAdditionalGroups looks up a list of groups by name or group id +// against the given /etc/group formatted data. If a group name cannot +// be found, an error will be returned. If a group id cannot be found, +// or the given group data is nil, the id will be returned as-is +// provided it is in the legal range. +func GetAdditionalGroups(additionalGroups []string, group io.Reader) ([]int, error) { + groups := []Group{} + if group != nil { + var err error + groups, err = ParseGroupFilter(group, func(g Group) bool { + for _, ag := range additionalGroups { + if g.Name == ag || strconv.Itoa(g.Gid) == ag { + return true + } + } + return false + }) + if err != nil { + return nil, fmt.Errorf("Unable to find additional groups %v: %w", additionalGroups, err) + } + } + + gidMap := make(map[int]struct{}) + for _, ag := range additionalGroups { + var found bool + for _, g := range groups { + // if we found a matched group either by name or gid, take the + // first matched as correct + if g.Name == ag || strconv.Itoa(g.Gid) == ag { + if _, ok := gidMap[g.Gid]; !ok { + gidMap[g.Gid] = struct{}{} + found = true + break + } + } + } + // we asked for a group but didn't find it. let's check to see + // if we wanted a numeric group + if !found { + gid, err := strconv.ParseInt(ag, 10, 64) + if err != nil { + // Not a numeric ID either. + return nil, fmt.Errorf("Unable to find group %s: %w", ag, ErrNoGroupEntries) + } + // Ensure gid is inside gid range. + if gid < minID || gid > maxID { + return nil, ErrRange + } + gidMap[int(gid)] = struct{}{} + } + } + gids := []int{} + for gid := range gidMap { + gids = append(gids, gid) + } + return gids, nil +} + +// GetAdditionalGroupsPath is a wrapper around GetAdditionalGroups +// that opens the groupPath given and gives it as an argument to +// GetAdditionalGroups. +func GetAdditionalGroupsPath(additionalGroups []string, groupPath string) ([]int, error) { + var group io.Reader + + if groupFile, err := os.Open(groupPath); err == nil { + group = groupFile + defer groupFile.Close() + } + return GetAdditionalGroups(additionalGroups, group) +} + +func ParseSubIDFile(path string) ([]SubID, error) { + subid, err := os.Open(path) + if err != nil { + return nil, err + } + defer subid.Close() + return ParseSubID(subid) +} + +func ParseSubID(subid io.Reader) ([]SubID, error) { + return ParseSubIDFilter(subid, nil) +} + +func ParseSubIDFileFilter(path string, filter func(SubID) bool) ([]SubID, error) { + subid, err := os.Open(path) + if err != nil { + return nil, err + } + defer subid.Close() + return ParseSubIDFilter(subid, filter) +} + +func ParseSubIDFilter(r io.Reader, filter func(SubID) bool) ([]SubID, error) { + if r == nil { + return nil, errors.New("nil source for subid-formatted data") + } + + var ( + s = bufio.NewScanner(r) + out = []SubID{} + ) + + for s.Scan() { + line := bytes.TrimSpace(s.Bytes()) + if len(line) == 0 { + continue + } + + // see: man 5 subuid + p := SubID{} + parseLine(line, &p.Name, &p.SubID, &p.Count) + + if filter == nil || filter(p) { + out = append(out, p) + } + } + if err := s.Err(); err != nil { + return nil, err + } + + return out, nil +} + +func ParseIDMapFile(path string) ([]IDMap, error) { + r, err := os.Open(path) + if err != nil { + return nil, err + } + defer r.Close() + return ParseIDMap(r) +} + +func ParseIDMap(r io.Reader) ([]IDMap, error) { + return ParseIDMapFilter(r, nil) +} + +func ParseIDMapFileFilter(path string, filter func(IDMap) bool) ([]IDMap, error) { + r, err := os.Open(path) + if err != nil { + return nil, err + } + defer r.Close() + return ParseIDMapFilter(r, filter) +} + +func ParseIDMapFilter(r io.Reader, filter func(IDMap) bool) ([]IDMap, error) { + if r == nil { + return nil, errors.New("nil source for idmap-formatted data") + } + + var ( + s = bufio.NewScanner(r) + out = []IDMap{} + ) + + for s.Scan() { + line := bytes.TrimSpace(s.Bytes()) + if len(line) == 0 { + continue + } + + // see: man 7 user_namespaces + p := IDMap{} + parseParts(bytes.Fields(line), &p.ID, &p.ParentID, &p.Count) + + if filter == nil || filter(p) { + out = append(out, p) + } + } + if err := s.Err(); err != nil { + return nil, err + } + + return out, nil +} diff --git a/vendor/github.com/moby/sys/user/user_fuzzer.go b/vendor/github.com/moby/sys/user/user_fuzzer.go new file mode 100644 index 00000000..e018eae6 --- /dev/null +++ b/vendor/github.com/moby/sys/user/user_fuzzer.go @@ -0,0 +1,43 @@ +//go:build gofuzz +// +build gofuzz + +package user + +import ( + "io" + "strings" +) + +func IsDivisbleBy(n int, divisibleby int) bool { + return (n % divisibleby) == 0 +} + +func FuzzUser(data []byte) int { + if len(data) == 0 { + return -1 + } + if !IsDivisbleBy(len(data), 5) { + return -1 + } + + var divided [][]byte + + chunkSize := len(data) / 5 + + for i := 0; i < len(data); i += chunkSize { + end := i + chunkSize + + divided = append(divided, data[i:end]) + } + + _, _ = ParsePasswdFilter(strings.NewReader(string(divided[0])), nil) + + var passwd, group io.Reader + + group = strings.NewReader(string(divided[1])) + _, _ = GetAdditionalGroups([]string{string(divided[2])}, group) + + passwd = strings.NewReader(string(divided[3])) + _, _ = GetExecUser(string(divided[4]), nil, passwd, group) + return 1 +} diff --git a/vendor/github.com/moby/term/.gitignore b/vendor/github.com/moby/term/.gitignore new file mode 100644 index 00000000..b0747ff0 --- /dev/null +++ b/vendor/github.com/moby/term/.gitignore @@ -0,0 +1,8 @@ +# if you want to ignore files created by your editor/tools, consider using a +# global .gitignore or .git/info/exclude see https://help.github.com/articles/ignoring-files +.* +!.github +!.gitignore +profile.out +# support running go modules in vendor mode for local development +vendor/ diff --git a/vendor/github.com/moby/term/LICENSE b/vendor/github.com/moby/term/LICENSE new file mode 100644 index 00000000..6d8d58fb --- /dev/null +++ b/vendor/github.com/moby/term/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2013-2018 Docker, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/moby/term/README.md b/vendor/github.com/moby/term/README.md new file mode 100644 index 00000000..0ce92cc3 --- /dev/null +++ b/vendor/github.com/moby/term/README.md @@ -0,0 +1,36 @@ +# term - utilities for dealing with terminals + +![Test](https://github.com/moby/term/workflows/Test/badge.svg) [![GoDoc](https://godoc.org/github.com/moby/term?status.svg)](https://godoc.org/github.com/moby/term) [![Go Report Card](https://goreportcard.com/badge/github.com/moby/term)](https://goreportcard.com/report/github.com/moby/term) + +term provides structures and helper functions to work with terminal (state, sizes). + +#### Using term + +```go +package main + +import ( + "log" + "os" + + "github.com/moby/term" +) + +func main() { + fd := os.Stdin.Fd() + if term.IsTerminal(fd) { + ws, err := term.GetWinsize(fd) + if err != nil { + log.Fatalf("term.GetWinsize: %s", err) + } + log.Printf("%d:%d\n", ws.Height, ws.Width) + } +} +``` + +## Contributing + +Want to hack on term? [Docker's contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md) apply. + +## Copyright and license +Code and documentation copyright 2015 Docker, inc. Code released under the Apache 2.0 license. Docs released under Creative commons. diff --git a/vendor/github.com/moby/term/ascii.go b/vendor/github.com/moby/term/ascii.go new file mode 100644 index 00000000..55873c05 --- /dev/null +++ b/vendor/github.com/moby/term/ascii.go @@ -0,0 +1,66 @@ +package term + +import ( + "fmt" + "strings" +) + +// ASCII list the possible supported ASCII key sequence +var ASCII = []string{ + "ctrl-@", + "ctrl-a", + "ctrl-b", + "ctrl-c", + "ctrl-d", + "ctrl-e", + "ctrl-f", + "ctrl-g", + "ctrl-h", + "ctrl-i", + "ctrl-j", + "ctrl-k", + "ctrl-l", + "ctrl-m", + "ctrl-n", + "ctrl-o", + "ctrl-p", + "ctrl-q", + "ctrl-r", + "ctrl-s", + "ctrl-t", + "ctrl-u", + "ctrl-v", + "ctrl-w", + "ctrl-x", + "ctrl-y", + "ctrl-z", + "ctrl-[", + "ctrl-\\", + "ctrl-]", + "ctrl-^", + "ctrl-_", +} + +// ToBytes converts a string representing a suite of key-sequence to the corresponding ASCII code. +func ToBytes(keys string) ([]byte, error) { + codes := []byte{} +next: + for _, key := range strings.Split(keys, ",") { + if len(key) != 1 { + for code, ctrl := range ASCII { + if ctrl == key { + codes = append(codes, byte(code)) + continue next + } + } + if key == "DEL" { + codes = append(codes, 127) + } else { + return nil, fmt.Errorf("Unknown character: '%s'", key) + } + } else { + codes = append(codes, key[0]) + } + } + return codes, nil +} diff --git a/vendor/github.com/moby/term/doc.go b/vendor/github.com/moby/term/doc.go new file mode 100644 index 00000000..c9bc0324 --- /dev/null +++ b/vendor/github.com/moby/term/doc.go @@ -0,0 +1,3 @@ +// Package term provides structures and helper functions to work with +// terminal (state, sizes). +package term diff --git a/vendor/github.com/moby/term/proxy.go b/vendor/github.com/moby/term/proxy.go new file mode 100644 index 00000000..c47756b8 --- /dev/null +++ b/vendor/github.com/moby/term/proxy.go @@ -0,0 +1,88 @@ +package term + +import ( + "io" +) + +// EscapeError is special error which returned by a TTY proxy reader's Read() +// method in case its detach escape sequence is read. +type EscapeError struct{} + +func (EscapeError) Error() string { + return "read escape sequence" +} + +// escapeProxy is used only for attaches with a TTY. It is used to proxy +// stdin keypresses from the underlying reader and look for the passed in +// escape key sequence to signal a detach. +type escapeProxy struct { + escapeKeys []byte + escapeKeyPos int + r io.Reader + buf []byte +} + +// NewEscapeProxy returns a new TTY proxy reader which wraps the given reader +// and detects when the specified escape keys are read, in which case the Read +// method will return an error of type EscapeError. +func NewEscapeProxy(r io.Reader, escapeKeys []byte) io.Reader { + return &escapeProxy{ + escapeKeys: escapeKeys, + r: r, + } +} + +func (r *escapeProxy) Read(buf []byte) (n int, err error) { + if len(r.escapeKeys) > 0 && r.escapeKeyPos == len(r.escapeKeys) { + return 0, EscapeError{} + } + + if len(r.buf) > 0 { + n = copy(buf, r.buf) + r.buf = r.buf[n:] + } + + nr, err := r.r.Read(buf[n:]) + n += nr + if len(r.escapeKeys) == 0 { + return n, err + } + + for i := 0; i < n; i++ { + if buf[i] == r.escapeKeys[r.escapeKeyPos] { + r.escapeKeyPos++ + + // Check if the full escape sequence is matched. + if r.escapeKeyPos == len(r.escapeKeys) { + n = i + 1 - r.escapeKeyPos + if n < 0 { + n = 0 + } + return n, EscapeError{} + } + continue + } + + // If we need to prepend a partial escape sequence from the previous + // read, make sure the new buffer size doesn't exceed len(buf). + // Otherwise, preserve any extra data in a buffer for the next read. + if i < r.escapeKeyPos { + preserve := make([]byte, 0, r.escapeKeyPos+n) + preserve = append(preserve, r.escapeKeys[:r.escapeKeyPos]...) + preserve = append(preserve, buf[:n]...) + n = copy(buf, preserve) + i += r.escapeKeyPos + r.buf = append(r.buf, preserve[n:]...) + } + r.escapeKeyPos = 0 + } + + // If we're in the middle of reading an escape sequence, make sure we don't + // let the caller read it. If later on we find that this is not the escape + // sequence, we'll prepend it back to buf. + n -= r.escapeKeyPos + if n < 0 { + n = 0 + } + return n, err +} diff --git a/vendor/github.com/moby/term/term.go b/vendor/github.com/moby/term/term.go new file mode 100644 index 00000000..f9d8988e --- /dev/null +++ b/vendor/github.com/moby/term/term.go @@ -0,0 +1,85 @@ +package term + +import "io" + +// State holds the platform-specific state / console mode for the terminal. +type State terminalState + +// Winsize represents the size of the terminal window. +type Winsize struct { + Height uint16 + Width uint16 + + // Only used on Unix + x uint16 + y uint16 +} + +// StdStreams returns the standard streams (stdin, stdout, stderr). +// +// On Windows, it attempts to turn on VT handling on all std handles if +// supported, or falls back to terminal emulation. On Unix, this returns +// the standard [os.Stdin], [os.Stdout] and [os.Stderr]. +func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { + return stdStreams() +} + +// GetFdInfo returns the file descriptor for an os.File and indicates whether the file represents a terminal. +func GetFdInfo(in interface{}) (fd uintptr, isTerminal bool) { + return getFdInfo(in) +} + +// GetWinsize returns the window size based on the specified file descriptor. +func GetWinsize(fd uintptr) (*Winsize, error) { + return getWinsize(fd) +} + +// SetWinsize tries to set the specified window size for the specified file +// descriptor. It is only implemented on Unix, and returns an error on Windows. +func SetWinsize(fd uintptr, ws *Winsize) error { + return setWinsize(fd, ws) +} + +// IsTerminal returns true if the given file descriptor is a terminal. +func IsTerminal(fd uintptr) bool { + return isTerminal(fd) +} + +// RestoreTerminal restores the terminal connected to the given file descriptor +// to a previous state. +func RestoreTerminal(fd uintptr, state *State) error { + return restoreTerminal(fd, state) +} + +// SaveState saves the state of the terminal connected to the given file descriptor. +func SaveState(fd uintptr) (*State, error) { + return saveState(fd) +} + +// DisableEcho applies the specified state to the terminal connected to the file +// descriptor, with echo disabled. +func DisableEcho(fd uintptr, state *State) error { + return disableEcho(fd, state) +} + +// SetRawTerminal puts the terminal connected to the given file descriptor into +// raw mode and returns the previous state. On UNIX, this is the equivalent of +// [MakeRaw], and puts both the input and output into raw mode. On Windows, it +// only puts the input into raw mode. +func SetRawTerminal(fd uintptr) (previousState *State, err error) { + return setRawTerminal(fd) +} + +// SetRawTerminalOutput puts the output of terminal connected to the given file +// descriptor into raw mode. On UNIX, this does nothing and returns nil for the +// state. On Windows, it disables LF -> CRLF translation. +func SetRawTerminalOutput(fd uintptr) (previousState *State, err error) { + return setRawTerminalOutput(fd) +} + +// MakeRaw puts the terminal (Windows Console) connected to the +// given file descriptor into raw mode and returns the previous state of +// the terminal so that it can be restored. +func MakeRaw(fd uintptr) (previousState *State, err error) { + return makeRaw(fd) +} diff --git a/vendor/github.com/moby/term/term_unix.go b/vendor/github.com/moby/term/term_unix.go new file mode 100644 index 00000000..2ec7706a --- /dev/null +++ b/vendor/github.com/moby/term/term_unix.go @@ -0,0 +1,98 @@ +//go:build !windows +// +build !windows + +package term + +import ( + "errors" + "io" + "os" + + "golang.org/x/sys/unix" +) + +// ErrInvalidState is returned if the state of the terminal is invalid. +// +// Deprecated: ErrInvalidState is no longer used. +var ErrInvalidState = errors.New("Invalid terminal state") + +// terminalState holds the platform-specific state / console mode for the terminal. +type terminalState struct { + termios unix.Termios +} + +func stdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { + return os.Stdin, os.Stdout, os.Stderr +} + +func getFdInfo(in interface{}) (uintptr, bool) { + var inFd uintptr + var isTerminalIn bool + if file, ok := in.(*os.File); ok { + inFd = file.Fd() + isTerminalIn = isTerminal(inFd) + } + return inFd, isTerminalIn +} + +func getWinsize(fd uintptr) (*Winsize, error) { + uws, err := unix.IoctlGetWinsize(int(fd), unix.TIOCGWINSZ) + ws := &Winsize{Height: uws.Row, Width: uws.Col, x: uws.Xpixel, y: uws.Ypixel} + return ws, err +} + +func setWinsize(fd uintptr, ws *Winsize) error { + return unix.IoctlSetWinsize(int(fd), unix.TIOCSWINSZ, &unix.Winsize{ + Row: ws.Height, + Col: ws.Width, + Xpixel: ws.x, + Ypixel: ws.y, + }) +} + +func isTerminal(fd uintptr) bool { + _, err := tcget(fd) + return err == nil +} + +func restoreTerminal(fd uintptr, state *State) error { + if state == nil { + return errors.New("invalid terminal state") + } + return tcset(fd, &state.termios) +} + +func saveState(fd uintptr) (*State, error) { + termios, err := tcget(fd) + if err != nil { + return nil, err + } + return &State{termios: *termios}, nil +} + +func disableEcho(fd uintptr, state *State) error { + newState := state.termios + newState.Lflag &^= unix.ECHO + + return tcset(fd, &newState) +} + +func setRawTerminal(fd uintptr) (*State, error) { + return makeRaw(fd) +} + +func setRawTerminalOutput(fd uintptr) (*State, error) { + return nil, nil +} + +func tcget(fd uintptr) (*unix.Termios, error) { + p, err := unix.IoctlGetTermios(int(fd), getTermios) + if err != nil { + return nil, err + } + return p, nil +} + +func tcset(fd uintptr, p *unix.Termios) error { + return unix.IoctlSetTermios(int(fd), setTermios, p) +} diff --git a/vendor/github.com/moby/term/term_windows.go b/vendor/github.com/moby/term/term_windows.go new file mode 100644 index 00000000..81ccff04 --- /dev/null +++ b/vendor/github.com/moby/term/term_windows.go @@ -0,0 +1,176 @@ +package term + +import ( + "fmt" + "io" + "os" + "os/signal" + + windowsconsole "github.com/moby/term/windows" + "golang.org/x/sys/windows" +) + +// terminalState holds the platform-specific state / console mode for the terminal. +type terminalState struct { + mode uint32 +} + +// vtInputSupported is true if winterm.ENABLE_VIRTUAL_TERMINAL_INPUT is supported by the console +var vtInputSupported bool + +func stdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { + // Turn on VT handling on all std handles, if possible. This might + // fail, in which case we will fall back to terminal emulation. + var ( + emulateStdin, emulateStdout, emulateStderr bool + + mode uint32 + ) + + fd := windows.Handle(os.Stdin.Fd()) + if err := windows.GetConsoleMode(fd, &mode); err == nil { + // Validate that winterm.ENABLE_VIRTUAL_TERMINAL_INPUT is supported, but do not set it. + if err = windows.SetConsoleMode(fd, mode|windows.ENABLE_VIRTUAL_TERMINAL_INPUT); err != nil { + emulateStdin = true + } else { + vtInputSupported = true + } + // Unconditionally set the console mode back even on failure because SetConsoleMode + // remembers invalid bits on input handles. + _ = windows.SetConsoleMode(fd, mode) + } + + fd = windows.Handle(os.Stdout.Fd()) + if err := windows.GetConsoleMode(fd, &mode); err == nil { + // Validate winterm.DISABLE_NEWLINE_AUTO_RETURN is supported, but do not set it. + if err = windows.SetConsoleMode(fd, mode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING|windows.DISABLE_NEWLINE_AUTO_RETURN); err != nil { + emulateStdout = true + } else { + _ = windows.SetConsoleMode(fd, mode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING) + } + } + + fd = windows.Handle(os.Stderr.Fd()) + if err := windows.GetConsoleMode(fd, &mode); err == nil { + // Validate winterm.DISABLE_NEWLINE_AUTO_RETURN is supported, but do not set it. + if err = windows.SetConsoleMode(fd, mode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING|windows.DISABLE_NEWLINE_AUTO_RETURN); err != nil { + emulateStderr = true + } else { + _ = windows.SetConsoleMode(fd, mode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING) + } + } + + if emulateStdin { + h := uint32(windows.STD_INPUT_HANDLE) + stdIn = windowsconsole.NewAnsiReader(int(h)) + } else { + stdIn = os.Stdin + } + + if emulateStdout { + h := uint32(windows.STD_OUTPUT_HANDLE) + stdOut = windowsconsole.NewAnsiWriter(int(h)) + } else { + stdOut = os.Stdout + } + + if emulateStderr { + h := uint32(windows.STD_ERROR_HANDLE) + stdErr = windowsconsole.NewAnsiWriter(int(h)) + } else { + stdErr = os.Stderr + } + + return stdIn, stdOut, stdErr +} + +func getFdInfo(in interface{}) (uintptr, bool) { + return windowsconsole.GetHandleInfo(in) +} + +func getWinsize(fd uintptr) (*Winsize, error) { + var info windows.ConsoleScreenBufferInfo + if err := windows.GetConsoleScreenBufferInfo(windows.Handle(fd), &info); err != nil { + return nil, err + } + + winsize := &Winsize{ + Width: uint16(info.Window.Right - info.Window.Left + 1), + Height: uint16(info.Window.Bottom - info.Window.Top + 1), + } + + return winsize, nil +} + +func setWinsize(fd uintptr, ws *Winsize) error { + return fmt.Errorf("not implemented on Windows") +} + +func isTerminal(fd uintptr) bool { + var mode uint32 + err := windows.GetConsoleMode(windows.Handle(fd), &mode) + return err == nil +} + +func restoreTerminal(fd uintptr, state *State) error { + return windows.SetConsoleMode(windows.Handle(fd), state.mode) +} + +func saveState(fd uintptr) (*State, error) { + var mode uint32 + + if err := windows.GetConsoleMode(windows.Handle(fd), &mode); err != nil { + return nil, err + } + + return &State{mode: mode}, nil +} + +func disableEcho(fd uintptr, state *State) error { + // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx + mode := state.mode + mode &^= windows.ENABLE_ECHO_INPUT + mode |= windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT + err := windows.SetConsoleMode(windows.Handle(fd), mode) + if err != nil { + return err + } + + // Register an interrupt handler to catch and restore prior state + restoreAtInterrupt(fd, state) + return nil +} + +func setRawTerminal(fd uintptr) (*State, error) { + oldState, err := MakeRaw(fd) + if err != nil { + return nil, err + } + + // Register an interrupt handler to catch and restore prior state + restoreAtInterrupt(fd, oldState) + return oldState, err +} + +func setRawTerminalOutput(fd uintptr) (*State, error) { + oldState, err := saveState(fd) + if err != nil { + return nil, err + } + + // Ignore failures, since winterm.DISABLE_NEWLINE_AUTO_RETURN might not be supported on this + // version of Windows. + _ = windows.SetConsoleMode(windows.Handle(fd), oldState.mode|windows.DISABLE_NEWLINE_AUTO_RETURN) + return oldState, err +} + +func restoreAtInterrupt(fd uintptr, state *State) { + sigchan := make(chan os.Signal, 1) + signal.Notify(sigchan, os.Interrupt) + + go func() { + _ = <-sigchan + _ = RestoreTerminal(fd, state) + os.Exit(0) + }() +} diff --git a/vendor/github.com/moby/term/termios_bsd.go b/vendor/github.com/moby/term/termios_bsd.go new file mode 100644 index 00000000..45f77e03 --- /dev/null +++ b/vendor/github.com/moby/term/termios_bsd.go @@ -0,0 +1,13 @@ +//go:build darwin || freebsd || openbsd || netbsd +// +build darwin freebsd openbsd netbsd + +package term + +import ( + "golang.org/x/sys/unix" +) + +const ( + getTermios = unix.TIOCGETA + setTermios = unix.TIOCSETA +) diff --git a/vendor/github.com/moby/term/termios_nonbsd.go b/vendor/github.com/moby/term/termios_nonbsd.go new file mode 100644 index 00000000..88b7b215 --- /dev/null +++ b/vendor/github.com/moby/term/termios_nonbsd.go @@ -0,0 +1,13 @@ +//go:build !darwin && !freebsd && !netbsd && !openbsd && !windows +// +build !darwin,!freebsd,!netbsd,!openbsd,!windows + +package term + +import ( + "golang.org/x/sys/unix" +) + +const ( + getTermios = unix.TCGETS + setTermios = unix.TCSETS +) diff --git a/vendor/github.com/moby/term/termios_unix.go b/vendor/github.com/moby/term/termios_unix.go new file mode 100644 index 00000000..60c82378 --- /dev/null +++ b/vendor/github.com/moby/term/termios_unix.go @@ -0,0 +1,35 @@ +//go:build !windows +// +build !windows + +package term + +import ( + "golang.org/x/sys/unix" +) + +// Termios is the Unix API for terminal I/O. +// +// Deprecated: use [unix.Termios]. +type Termios = unix.Termios + +func makeRaw(fd uintptr) (*State, error) { + termios, err := tcget(fd) + if err != nil { + return nil, err + } + + oldState := State{termios: *termios} + + termios.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON + termios.Oflag &^= unix.OPOST + termios.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN + termios.Cflag &^= unix.CSIZE | unix.PARENB + termios.Cflag |= unix.CS8 + termios.Cc[unix.VMIN] = 1 + termios.Cc[unix.VTIME] = 0 + + if err := tcset(fd, termios); err != nil { + return nil, err + } + return &oldState, nil +} diff --git a/vendor/github.com/moby/term/termios_windows.go b/vendor/github.com/moby/term/termios_windows.go new file mode 100644 index 00000000..5be4e760 --- /dev/null +++ b/vendor/github.com/moby/term/termios_windows.go @@ -0,0 +1,37 @@ +package term + +import "golang.org/x/sys/windows" + +func makeRaw(fd uintptr) (*State, error) { + state, err := SaveState(fd) + if err != nil { + return nil, err + } + + mode := state.mode + + // See + // -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx + // -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx + + // Disable these modes + mode &^= windows.ENABLE_ECHO_INPUT + mode &^= windows.ENABLE_LINE_INPUT + mode &^= windows.ENABLE_MOUSE_INPUT + mode &^= windows.ENABLE_WINDOW_INPUT + mode &^= windows.ENABLE_PROCESSED_INPUT + + // Enable these modes + mode |= windows.ENABLE_EXTENDED_FLAGS + mode |= windows.ENABLE_INSERT_MODE + mode |= windows.ENABLE_QUICK_EDIT_MODE + if vtInputSupported { + mode |= windows.ENABLE_VIRTUAL_TERMINAL_INPUT + } + + err = windows.SetConsoleMode(windows.Handle(fd), mode) + if err != nil { + return nil, err + } + return state, nil +} diff --git a/vendor/github.com/moby/term/windows/ansi_reader.go b/vendor/github.com/moby/term/windows/ansi_reader.go new file mode 100644 index 00000000..fb34c547 --- /dev/null +++ b/vendor/github.com/moby/term/windows/ansi_reader.go @@ -0,0 +1,252 @@ +//go:build windows +// +build windows + +package windowsconsole + +import ( + "bytes" + "errors" + "fmt" + "io" + "os" + "strings" + "unsafe" + + ansiterm "github.com/Azure/go-ansiterm" + "github.com/Azure/go-ansiterm/winterm" +) + +const ( + escapeSequence = ansiterm.KEY_ESC_CSI +) + +// ansiReader wraps a standard input file (e.g., os.Stdin) providing ANSI sequence translation. +type ansiReader struct { + file *os.File + fd uintptr + buffer []byte + cbBuffer int + command []byte +} + +// NewAnsiReader returns an io.ReadCloser that provides VT100 terminal emulation on top of a +// Windows console input handle. +func NewAnsiReader(nFile int) io.ReadCloser { + file, fd := winterm.GetStdFile(nFile) + return &ansiReader{ + file: file, + fd: fd, + command: make([]byte, 0, ansiterm.ANSI_MAX_CMD_LENGTH), + buffer: make([]byte, 0), + } +} + +// Close closes the wrapped file. +func (ar *ansiReader) Close() (err error) { + return ar.file.Close() +} + +// Fd returns the file descriptor of the wrapped file. +func (ar *ansiReader) Fd() uintptr { + return ar.fd +} + +// Read reads up to len(p) bytes of translated input events into p. +func (ar *ansiReader) Read(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + + // Previously read bytes exist, read as much as we can and return + if len(ar.buffer) > 0 { + originalLength := len(ar.buffer) + copiedLength := copy(p, ar.buffer) + + if copiedLength == originalLength { + ar.buffer = make([]byte, 0, len(p)) + } else { + ar.buffer = ar.buffer[copiedLength:] + } + + return copiedLength, nil + } + + // Read and translate key events + events, err := readInputEvents(ar, len(p)) + if err != nil { + return 0, err + } else if len(events) == 0 { + return 0, nil + } + + keyBytes := translateKeyEvents(events, []byte(escapeSequence)) + + // Save excess bytes and right-size keyBytes + if len(keyBytes) > len(p) { + ar.buffer = keyBytes[len(p):] + keyBytes = keyBytes[:len(p)] + } else if len(keyBytes) == 0 { + return 0, nil + } + + copiedLength := copy(p, keyBytes) + if copiedLength != len(keyBytes) { + return 0, errors.New("unexpected copy length encountered") + } + + return copiedLength, nil +} + +// readInputEvents polls until at least one event is available. +func readInputEvents(ar *ansiReader, maxBytes int) ([]winterm.INPUT_RECORD, error) { + // Determine the maximum number of records to retrieve + // -- Cast around the type system to obtain the size of a single INPUT_RECORD. + // unsafe.Sizeof requires an expression vs. a type-reference; the casting + // tricks the type system into believing it has such an expression. + recordSize := int(unsafe.Sizeof(*((*winterm.INPUT_RECORD)(unsafe.Pointer(&maxBytes))))) + countRecords := maxBytes / recordSize + if countRecords > ansiterm.MAX_INPUT_EVENTS { + countRecords = ansiterm.MAX_INPUT_EVENTS + } else if countRecords == 0 { + countRecords = 1 + } + + // Wait for and read input events + events := make([]winterm.INPUT_RECORD, countRecords) + nEvents := uint32(0) + eventsExist, err := winterm.WaitForSingleObject(ar.fd, winterm.WAIT_INFINITE) + if err != nil { + return nil, err + } + + if eventsExist { + err = winterm.ReadConsoleInput(ar.fd, events, &nEvents) + if err != nil { + return nil, err + } + } + + // Return a slice restricted to the number of returned records + return events[:nEvents], nil +} + +// KeyEvent Translation Helpers + +var arrowKeyMapPrefix = map[uint16]string{ + winterm.VK_UP: "%s%sA", + winterm.VK_DOWN: "%s%sB", + winterm.VK_RIGHT: "%s%sC", + winterm.VK_LEFT: "%s%sD", +} + +var keyMapPrefix = map[uint16]string{ + winterm.VK_UP: "\x1B[%sA", + winterm.VK_DOWN: "\x1B[%sB", + winterm.VK_RIGHT: "\x1B[%sC", + winterm.VK_LEFT: "\x1B[%sD", + winterm.VK_HOME: "\x1B[1%s~", // showkey shows ^[[1 + winterm.VK_END: "\x1B[4%s~", // showkey shows ^[[4 + winterm.VK_INSERT: "\x1B[2%s~", + winterm.VK_DELETE: "\x1B[3%s~", + winterm.VK_PRIOR: "\x1B[5%s~", + winterm.VK_NEXT: "\x1B[6%s~", + winterm.VK_F1: "", + winterm.VK_F2: "", + winterm.VK_F3: "\x1B[13%s~", + winterm.VK_F4: "\x1B[14%s~", + winterm.VK_F5: "\x1B[15%s~", + winterm.VK_F6: "\x1B[17%s~", + winterm.VK_F7: "\x1B[18%s~", + winterm.VK_F8: "\x1B[19%s~", + winterm.VK_F9: "\x1B[20%s~", + winterm.VK_F10: "\x1B[21%s~", + winterm.VK_F11: "\x1B[23%s~", + winterm.VK_F12: "\x1B[24%s~", +} + +// translateKeyEvents converts the input events into the appropriate ANSI string. +func translateKeyEvents(events []winterm.INPUT_RECORD, escapeSequence []byte) []byte { + var buffer bytes.Buffer + for _, event := range events { + if event.EventType == winterm.KEY_EVENT && event.KeyEvent.KeyDown != 0 { + buffer.WriteString(keyToString(&event.KeyEvent, escapeSequence)) + } + } + + return buffer.Bytes() +} + +// keyToString maps the given input event record to the corresponding string. +func keyToString(keyEvent *winterm.KEY_EVENT_RECORD, escapeSequence []byte) string { + if keyEvent.UnicodeChar == 0 { + return formatVirtualKey(keyEvent.VirtualKeyCode, keyEvent.ControlKeyState, escapeSequence) + } + + _, alt, control := getControlKeys(keyEvent.ControlKeyState) + if control { + // TODO(azlinux): Implement following control sequences + // -D Signals the end of input from the keyboard; also exits current shell. + // -H Deletes the first character to the left of the cursor. Also called the ERASE key. + // -Q Restarts printing after it has been stopped with -s. + // -S Suspends printing on the screen (does not stop the program). + // -U Deletes all characters on the current line. Also called the KILL key. + // -E Quits current command and creates a core + } + + // +Key generates ESC N Key + if !control && alt { + return ansiterm.KEY_ESC_N + strings.ToLower(string(rune(keyEvent.UnicodeChar))) + } + + return string(rune(keyEvent.UnicodeChar)) +} + +// formatVirtualKey converts a virtual key (e.g., up arrow) into the appropriate ANSI string. +func formatVirtualKey(key uint16, controlState uint32, escapeSequence []byte) string { + shift, alt, control := getControlKeys(controlState) + modifier := getControlKeysModifier(shift, alt, control) + + if format, ok := arrowKeyMapPrefix[key]; ok { + return fmt.Sprintf(format, escapeSequence, modifier) + } + + if format, ok := keyMapPrefix[key]; ok { + return fmt.Sprintf(format, modifier) + } + + return "" +} + +// getControlKeys extracts the shift, alt, and ctrl key states. +func getControlKeys(controlState uint32) (shift, alt, control bool) { + shift = 0 != (controlState & winterm.SHIFT_PRESSED) + alt = 0 != (controlState & (winterm.LEFT_ALT_PRESSED | winterm.RIGHT_ALT_PRESSED)) + control = 0 != (controlState & (winterm.LEFT_CTRL_PRESSED | winterm.RIGHT_CTRL_PRESSED)) + return shift, alt, control +} + +// getControlKeysModifier returns the ANSI modifier for the given combination of control keys. +func getControlKeysModifier(shift, alt, control bool) string { + if shift && alt && control { + return ansiterm.KEY_CONTROL_PARAM_8 + } + if alt && control { + return ansiterm.KEY_CONTROL_PARAM_7 + } + if shift && control { + return ansiterm.KEY_CONTROL_PARAM_6 + } + if control { + return ansiterm.KEY_CONTROL_PARAM_5 + } + if shift && alt { + return ansiterm.KEY_CONTROL_PARAM_4 + } + if alt { + return ansiterm.KEY_CONTROL_PARAM_3 + } + if shift { + return ansiterm.KEY_CONTROL_PARAM_2 + } + return "" +} diff --git a/vendor/github.com/moby/term/windows/ansi_writer.go b/vendor/github.com/moby/term/windows/ansi_writer.go new file mode 100644 index 00000000..4243307f --- /dev/null +++ b/vendor/github.com/moby/term/windows/ansi_writer.go @@ -0,0 +1,57 @@ +//go:build windows +// +build windows + +package windowsconsole + +import ( + "io" + "os" + + ansiterm "github.com/Azure/go-ansiterm" + "github.com/Azure/go-ansiterm/winterm" +) + +// ansiWriter wraps a standard output file (e.g., os.Stdout) providing ANSI sequence translation. +type ansiWriter struct { + file *os.File + fd uintptr + infoReset *winterm.CONSOLE_SCREEN_BUFFER_INFO + command []byte + escapeSequence []byte + inAnsiSequence bool + parser *ansiterm.AnsiParser +} + +// NewAnsiWriter returns an io.Writer that provides VT100 terminal emulation on top of a +// Windows console output handle. +func NewAnsiWriter(nFile int) io.Writer { + file, fd := winterm.GetStdFile(nFile) + info, err := winterm.GetConsoleScreenBufferInfo(fd) + if err != nil { + return nil + } + + parser := ansiterm.CreateParser("Ground", winterm.CreateWinEventHandler(fd, file)) + + return &ansiWriter{ + file: file, + fd: fd, + infoReset: info, + command: make([]byte, 0, ansiterm.ANSI_MAX_CMD_LENGTH), + escapeSequence: []byte(ansiterm.KEY_ESC_CSI), + parser: parser, + } +} + +func (aw *ansiWriter) Fd() uintptr { + return aw.fd +} + +// Write writes len(p) bytes from p to the underlying data stream. +func (aw *ansiWriter) Write(p []byte) (total int, err error) { + if len(p) == 0 { + return 0, nil + } + + return aw.parser.Parse(p) +} diff --git a/vendor/github.com/moby/term/windows/console.go b/vendor/github.com/moby/term/windows/console.go new file mode 100644 index 00000000..21e57bd5 --- /dev/null +++ b/vendor/github.com/moby/term/windows/console.go @@ -0,0 +1,43 @@ +//go:build windows +// +build windows + +package windowsconsole + +import ( + "os" + + "golang.org/x/sys/windows" +) + +// GetHandleInfo returns file descriptor and bool indicating whether the file is a console. +func GetHandleInfo(in interface{}) (uintptr, bool) { + switch t := in.(type) { + case *ansiReader: + return t.Fd(), true + case *ansiWriter: + return t.Fd(), true + } + + var inFd uintptr + var isTerminal bool + + if file, ok := in.(*os.File); ok { + inFd = file.Fd() + isTerminal = isConsole(inFd) + } + return inFd, isTerminal +} + +// IsConsole returns true if the given file descriptor is a Windows Console. +// The code assumes that GetConsoleMode will return an error for file descriptors that are not a console. +// +// Deprecated: use [windows.GetConsoleMode] or [golang.org/x/term.IsTerminal]. +func IsConsole(fd uintptr) bool { + return isConsole(fd) +} + +func isConsole(fd uintptr) bool { + var mode uint32 + err := windows.GetConsoleMode(windows.Handle(fd), &mode) + return err == nil +} diff --git a/vendor/github.com/moby/term/windows/doc.go b/vendor/github.com/moby/term/windows/doc.go new file mode 100644 index 00000000..54265fff --- /dev/null +++ b/vendor/github.com/moby/term/windows/doc.go @@ -0,0 +1,5 @@ +// These files implement ANSI-aware input and output streams for use by the Docker Windows client. +// When asked for the set of standard streams (e.g., stdin, stdout, stderr), the code will create +// and return pseudo-streams that convert ANSI sequences to / from Windows Console API calls. + +package windowsconsole diff --git a/vendor/github.com/opencontainers/go-digest/.mailmap b/vendor/github.com/opencontainers/go-digest/.mailmap new file mode 100644 index 00000000..eaf8b2f9 --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/.mailmap @@ -0,0 +1,4 @@ +Aaron Lehmann +Derek McGowan +Stephen J Day +Haibing Zhou diff --git a/vendor/github.com/opencontainers/go-digest/.pullapprove.yml b/vendor/github.com/opencontainers/go-digest/.pullapprove.yml new file mode 100644 index 00000000..b6165f83 --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/.pullapprove.yml @@ -0,0 +1,28 @@ +version: 2 + +requirements: + signed_off_by: + required: true + +always_pending: + title_regex: '^WIP' + explanation: 'Work in progress...' + +group_defaults: + required: 2 + approve_by_comment: + enabled: true + approve_regex: '^LGTM' + reject_regex: '^Rejected' + reset_on_push: + enabled: true + author_approval: + ignored: true + conditions: + branches: + - master + +groups: + go-digest: + teams: + - go-digest-maintainers diff --git a/vendor/github.com/opencontainers/go-digest/.travis.yml b/vendor/github.com/opencontainers/go-digest/.travis.yml new file mode 100644 index 00000000..5775f885 --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/.travis.yml @@ -0,0 +1,5 @@ +language: go +go: + - 1.12.x + - 1.13.x + - master diff --git a/vendor/github.com/opencontainers/go-digest/CONTRIBUTING.md b/vendor/github.com/opencontainers/go-digest/CONTRIBUTING.md new file mode 100644 index 00000000..e4d962ac --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/CONTRIBUTING.md @@ -0,0 +1,72 @@ +# Contributing to Docker open source projects + +Want to hack on this project? Awesome! Here are instructions to get you started. + +This project is a part of the [Docker](https://www.docker.com) project, and follows +the same rules and principles. If you're already familiar with the way +Docker does things, you'll feel right at home. + +Otherwise, go read Docker's +[contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md), +[issue triaging](https://github.com/docker/docker/blob/master/project/ISSUE-TRIAGE.md), +[review process](https://github.com/docker/docker/blob/master/project/REVIEWING.md) and +[branches and tags](https://github.com/docker/docker/blob/master/project/BRANCHES-AND-TAGS.md). + +For an in-depth description of our contribution process, visit the +contributors guide: [Understand how to contribute](https://docs.docker.com/opensource/workflow/make-a-contribution/) + +### Sign your work + +The sign-off is a simple line at the end of the explanation for the patch. Your +signature certifies that you wrote the patch or otherwise have the right to pass +it on as an open-source patch. The rules are pretty simple: if you can certify +the below (from [developercertificate.org](http://developercertificate.org/)): + +``` +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. +1 Letterman Drive +Suite D4700 +San Francisco, CA, 94129 + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +Then you just add a line to every git commit message: + + Signed-off-by: Joe Smith + +Use your real name (sorry, no pseudonyms or anonymous contributions.) + +If you set your `user.name` and `user.email` git configs, you can sign your +commit automatically with `git commit -s`. diff --git a/vendor/github.com/opencontainers/go-digest/LICENSE b/vendor/github.com/opencontainers/go-digest/LICENSE new file mode 100644 index 00000000..3ac8ab64 --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/LICENSE @@ -0,0 +1,192 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2019, 2020 OCI Contributors + Copyright 2016 Docker, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/opencontainers/go-digest/LICENSE.docs b/vendor/github.com/opencontainers/go-digest/LICENSE.docs new file mode 100644 index 00000000..e26cd4fc --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/LICENSE.docs @@ -0,0 +1,425 @@ +Attribution-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-ShareAlike 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-ShareAlike 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + l. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + m. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + + including for purposes of Section 3(b); and + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public licenses. +Notwithstanding, Creative Commons may elect to apply one of its public +licenses to material it publishes and in those instances will be +considered the "Licensor." Except for the limited purpose of indicating +that material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the public +licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/vendor/github.com/opencontainers/go-digest/MAINTAINERS b/vendor/github.com/opencontainers/go-digest/MAINTAINERS new file mode 100644 index 00000000..843b1b20 --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/MAINTAINERS @@ -0,0 +1,5 @@ +Derek McGowan (@dmcgowan) +Stephen Day (@stevvooe) +Vincent Batts (@vbatts) +Akihiro Suda (@AkihiroSuda) +Sebastiaan van Stijn (@thaJeztah) diff --git a/vendor/github.com/opencontainers/go-digest/README.md b/vendor/github.com/opencontainers/go-digest/README.md new file mode 100644 index 00000000..a1128720 --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/README.md @@ -0,0 +1,96 @@ +# go-digest + +[![GoDoc](https://godoc.org/github.com/opencontainers/go-digest?status.svg)](https://godoc.org/github.com/opencontainers/go-digest) [![Go Report Card](https://goreportcard.com/badge/github.com/opencontainers/go-digest)](https://goreportcard.com/report/github.com/opencontainers/go-digest) [![Build Status](https://travis-ci.org/opencontainers/go-digest.svg?branch=master)](https://travis-ci.org/opencontainers/go-digest) + +Common digest package used across the container ecosystem. + +Please see the [godoc](https://godoc.org/github.com/opencontainers/go-digest) for more information. + +# What is a digest? + +A digest is just a [hash](https://en.wikipedia.org/wiki/Hash_function). + +The most common use case for a digest is to create a content identifier for use in [Content Addressable Storage](https://en.wikipedia.org/wiki/Content-addressable_storage) systems: + +```go +id := digest.FromBytes([]byte("my content")) +``` + +In the example above, the id can be used to uniquely identify the byte slice "my content". +This allows two disparate applications to agree on a verifiable identifier without having to trust one another. + +An identifying digest can be verified, as follows: + +```go +if id != digest.FromBytes([]byte("my content")) { + return errors.New("the content has changed!") +} +``` + +A `Verifier` type can be used to handle cases where an `io.Reader` makes more sense: + +```go +rd := getContent() +verifier := id.Verifier() +io.Copy(verifier, rd) + +if !verifier.Verified() { + return errors.New("the content has changed!") +} +``` + +Using [Merkle DAGs](https://en.wikipedia.org/wiki/Merkle_tree), this can power a rich, safe, content distribution system. + +# Usage + +While the [godoc](https://godoc.org/github.com/opencontainers/go-digest) is considered the best resource, a few important items need to be called out when using this package. + +1. Make sure to import the hash implementations into your application or the package will panic. + You should have something like the following in the main (or other entrypoint) of your application: + + ```go + import ( + _ "crypto/sha256" + _ "crypto/sha512" + ) + ``` + This may seem inconvenient but it allows you replace the hash + implementations with others, such as https://github.com/stevvooe/resumable. + +2. Even though `digest.Digest` may be assemblable as a string, _always_ verify your input with `digest.Parse` or use `Digest.Validate` when accepting untrusted input. + While there are measures to avoid common problems, this will ensure you have valid digests in the rest of your application. + +3. While alternative encodings of hash values (digests) are possible (for example, base64), this package deals exclusively with hex-encoded digests. + +# Stability + +The Go API, at this stage, is considered stable, unless otherwise noted. + +As always, before using a package export, read the [godoc](https://godoc.org/github.com/opencontainers/go-digest). + +# Contributing + +This package is considered fairly complete. +It has been in production in thousands (millions?) of deployments and is fairly battle-hardened. +New additions will be met with skepticism. +If you think there is a missing feature, please file a bug clearly describing the problem and the alternatives you tried before submitting a PR. + +## Code of Conduct + +Participation in the OpenContainers community is governed by [OpenContainer's Code of Conduct][code-of-conduct]. + +## Security + +If you find an issue, please follow the [security][security] protocol to report it. + +# Copyright and license + +Copyright © 2019, 2020 OCI Contributors +Copyright © 2016 Docker, Inc. +All rights reserved, except as follows. +Code is released under the [Apache 2.0 license](LICENSE). +This `README.md` file and the [`CONTRIBUTING.md`](CONTRIBUTING.md) file are licensed under the Creative Commons Attribution 4.0 International License under the terms and conditions set forth in the file [`LICENSE.docs`](LICENSE.docs). +You may obtain a duplicate copy of the same license, titled CC BY-SA 4.0, at http://creativecommons.org/licenses/by-sa/4.0/. + +[security]: https://github.com/opencontainers/org/blob/master/security +[code-of-conduct]: https://github.com/opencontainers/org/blob/master/CODE_OF_CONDUCT.md diff --git a/vendor/github.com/opencontainers/go-digest/algorithm.go b/vendor/github.com/opencontainers/go-digest/algorithm.go new file mode 100644 index 00000000..490951dc --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/algorithm.go @@ -0,0 +1,193 @@ +// Copyright 2019, 2020 OCI Contributors +// Copyright 2017 Docker, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package digest + +import ( + "crypto" + "fmt" + "hash" + "io" + "regexp" +) + +// Algorithm identifies and implementation of a digester by an identifier. +// Note the that this defines both the hash algorithm used and the string +// encoding. +type Algorithm string + +// supported digest types +const ( + SHA256 Algorithm = "sha256" // sha256 with hex encoding (lower case only) + SHA384 Algorithm = "sha384" // sha384 with hex encoding (lower case only) + SHA512 Algorithm = "sha512" // sha512 with hex encoding (lower case only) + + // Canonical is the primary digest algorithm used with the distribution + // project. Other digests may be used but this one is the primary storage + // digest. + Canonical = SHA256 +) + +var ( + // TODO(stevvooe): Follow the pattern of the standard crypto package for + // registration of digests. Effectively, we are a registerable set and + // common symbol access. + + // algorithms maps values to hash.Hash implementations. Other algorithms + // may be available but they cannot be calculated by the digest package. + algorithms = map[Algorithm]crypto.Hash{ + SHA256: crypto.SHA256, + SHA384: crypto.SHA384, + SHA512: crypto.SHA512, + } + + // anchoredEncodedRegexps contains anchored regular expressions for hex-encoded digests. + // Note that /A-F/ disallowed. + anchoredEncodedRegexps = map[Algorithm]*regexp.Regexp{ + SHA256: regexp.MustCompile(`^[a-f0-9]{64}$`), + SHA384: regexp.MustCompile(`^[a-f0-9]{96}$`), + SHA512: regexp.MustCompile(`^[a-f0-9]{128}$`), + } +) + +// Available returns true if the digest type is available for use. If this +// returns false, Digester and Hash will return nil. +func (a Algorithm) Available() bool { + h, ok := algorithms[a] + if !ok { + return false + } + + // check availability of the hash, as well + return h.Available() +} + +func (a Algorithm) String() string { + return string(a) +} + +// Size returns number of bytes returned by the hash. +func (a Algorithm) Size() int { + h, ok := algorithms[a] + if !ok { + return 0 + } + return h.Size() +} + +// Set implemented to allow use of Algorithm as a command line flag. +func (a *Algorithm) Set(value string) error { + if value == "" { + *a = Canonical + } else { + // just do a type conversion, support is queried with Available. + *a = Algorithm(value) + } + + if !a.Available() { + return ErrDigestUnsupported + } + + return nil +} + +// Digester returns a new digester for the specified algorithm. If the algorithm +// does not have a digester implementation, nil will be returned. This can be +// checked by calling Available before calling Digester. +func (a Algorithm) Digester() Digester { + return &digester{ + alg: a, + hash: a.Hash(), + } +} + +// Hash returns a new hash as used by the algorithm. If not available, the +// method will panic. Check Algorithm.Available() before calling. +func (a Algorithm) Hash() hash.Hash { + if !a.Available() { + // Empty algorithm string is invalid + if a == "" { + panic(fmt.Sprintf("empty digest algorithm, validate before calling Algorithm.Hash()")) + } + + // NOTE(stevvooe): A missing hash is usually a programming error that + // must be resolved at compile time. We don't import in the digest + // package to allow users to choose their hash implementation (such as + // when using stevvooe/resumable or a hardware accelerated package). + // + // Applications that may want to resolve the hash at runtime should + // call Algorithm.Available before call Algorithm.Hash(). + panic(fmt.Sprintf("%v not available (make sure it is imported)", a)) + } + + return algorithms[a].New() +} + +// Encode encodes the raw bytes of a digest, typically from a hash.Hash, into +// the encoded portion of the digest. +func (a Algorithm) Encode(d []byte) string { + // TODO(stevvooe): Currently, all algorithms use a hex encoding. When we + // add support for back registration, we can modify this accordingly. + return fmt.Sprintf("%x", d) +} + +// FromReader returns the digest of the reader using the algorithm. +func (a Algorithm) FromReader(rd io.Reader) (Digest, error) { + digester := a.Digester() + + if _, err := io.Copy(digester.Hash(), rd); err != nil { + return "", err + } + + return digester.Digest(), nil +} + +// FromBytes digests the input and returns a Digest. +func (a Algorithm) FromBytes(p []byte) Digest { + digester := a.Digester() + + if _, err := digester.Hash().Write(p); err != nil { + // Writes to a Hash should never fail. None of the existing + // hash implementations in the stdlib or hashes vendored + // here can return errors from Write. Having a panic in this + // condition instead of having FromBytes return an error value + // avoids unnecessary error handling paths in all callers. + panic("write to hash function returned error: " + err.Error()) + } + + return digester.Digest() +} + +// FromString digests the string input and returns a Digest. +func (a Algorithm) FromString(s string) Digest { + return a.FromBytes([]byte(s)) +} + +// Validate validates the encoded portion string +func (a Algorithm) Validate(encoded string) error { + r, ok := anchoredEncodedRegexps[a] + if !ok { + return ErrDigestUnsupported + } + // Digests much always be hex-encoded, ensuring that their hex portion will + // always be size*2 + if a.Size()*2 != len(encoded) { + return ErrDigestInvalidLength + } + if r.MatchString(encoded) { + return nil + } + return ErrDigestInvalidFormat +} diff --git a/vendor/github.com/opencontainers/go-digest/digest.go b/vendor/github.com/opencontainers/go-digest/digest.go new file mode 100644 index 00000000..518b5e71 --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/digest.go @@ -0,0 +1,157 @@ +// Copyright 2019, 2020 OCI Contributors +// Copyright 2017 Docker, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package digest + +import ( + "fmt" + "hash" + "io" + "regexp" + "strings" +) + +// Digest allows simple protection of hex formatted digest strings, prefixed +// by their algorithm. Strings of type Digest have some guarantee of being in +// the correct format and it provides quick access to the components of a +// digest string. +// +// The following is an example of the contents of Digest types: +// +// sha256:7173b809ca12ec5dee4506cd86be934c4596dd234ee82c0662eac04a8c2c71dc +// +// This allows to abstract the digest behind this type and work only in those +// terms. +type Digest string + +// NewDigest returns a Digest from alg and a hash.Hash object. +func NewDigest(alg Algorithm, h hash.Hash) Digest { + return NewDigestFromBytes(alg, h.Sum(nil)) +} + +// NewDigestFromBytes returns a new digest from the byte contents of p. +// Typically, this can come from hash.Hash.Sum(...) or xxx.SumXXX(...) +// functions. This is also useful for rebuilding digests from binary +// serializations. +func NewDigestFromBytes(alg Algorithm, p []byte) Digest { + return NewDigestFromEncoded(alg, alg.Encode(p)) +} + +// NewDigestFromHex is deprecated. Please use NewDigestFromEncoded. +func NewDigestFromHex(alg, hex string) Digest { + return NewDigestFromEncoded(Algorithm(alg), hex) +} + +// NewDigestFromEncoded returns a Digest from alg and the encoded digest. +func NewDigestFromEncoded(alg Algorithm, encoded string) Digest { + return Digest(fmt.Sprintf("%s:%s", alg, encoded)) +} + +// DigestRegexp matches valid digest types. +var DigestRegexp = regexp.MustCompile(`[a-z0-9]+(?:[.+_-][a-z0-9]+)*:[a-zA-Z0-9=_-]+`) + +// DigestRegexpAnchored matches valid digest types, anchored to the start and end of the match. +var DigestRegexpAnchored = regexp.MustCompile(`^` + DigestRegexp.String() + `$`) + +var ( + // ErrDigestInvalidFormat returned when digest format invalid. + ErrDigestInvalidFormat = fmt.Errorf("invalid checksum digest format") + + // ErrDigestInvalidLength returned when digest has invalid length. + ErrDigestInvalidLength = fmt.Errorf("invalid checksum digest length") + + // ErrDigestUnsupported returned when the digest algorithm is unsupported. + ErrDigestUnsupported = fmt.Errorf("unsupported digest algorithm") +) + +// Parse parses s and returns the validated digest object. An error will +// be returned if the format is invalid. +func Parse(s string) (Digest, error) { + d := Digest(s) + return d, d.Validate() +} + +// FromReader consumes the content of rd until io.EOF, returning canonical digest. +func FromReader(rd io.Reader) (Digest, error) { + return Canonical.FromReader(rd) +} + +// FromBytes digests the input and returns a Digest. +func FromBytes(p []byte) Digest { + return Canonical.FromBytes(p) +} + +// FromString digests the input and returns a Digest. +func FromString(s string) Digest { + return Canonical.FromString(s) +} + +// Validate checks that the contents of d is a valid digest, returning an +// error if not. +func (d Digest) Validate() error { + s := string(d) + i := strings.Index(s, ":") + if i <= 0 || i+1 == len(s) { + return ErrDigestInvalidFormat + } + algorithm, encoded := Algorithm(s[:i]), s[i+1:] + if !algorithm.Available() { + if !DigestRegexpAnchored.MatchString(s) { + return ErrDigestInvalidFormat + } + return ErrDigestUnsupported + } + return algorithm.Validate(encoded) +} + +// Algorithm returns the algorithm portion of the digest. This will panic if +// the underlying digest is not in a valid format. +func (d Digest) Algorithm() Algorithm { + return Algorithm(d[:d.sepIndex()]) +} + +// Verifier returns a writer object that can be used to verify a stream of +// content against the digest. If the digest is invalid, the method will panic. +func (d Digest) Verifier() Verifier { + return hashVerifier{ + hash: d.Algorithm().Hash(), + digest: d, + } +} + +// Encoded returns the encoded portion of the digest. This will panic if the +// underlying digest is not in a valid format. +func (d Digest) Encoded() string { + return string(d[d.sepIndex()+1:]) +} + +// Hex is deprecated. Please use Digest.Encoded. +func (d Digest) Hex() string { + return d.Encoded() +} + +func (d Digest) String() string { + return string(d) +} + +func (d Digest) sepIndex() int { + i := strings.Index(string(d), ":") + + if i < 0 { + panic(fmt.Sprintf("no ':' separator in digest %q", d)) + } + + return i +} diff --git a/vendor/github.com/opencontainers/go-digest/digester.go b/vendor/github.com/opencontainers/go-digest/digester.go new file mode 100644 index 00000000..ede90775 --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/digester.go @@ -0,0 +1,40 @@ +// Copyright 2019, 2020 OCI Contributors +// Copyright 2017 Docker, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package digest + +import "hash" + +// Digester calculates the digest of written data. Writes should go directly +// to the return value of Hash, while calling Digest will return the current +// value of the digest. +type Digester interface { + Hash() hash.Hash // provides direct access to underlying hash instance. + Digest() Digest +} + +// digester provides a simple digester definition that embeds a hasher. +type digester struct { + alg Algorithm + hash hash.Hash +} + +func (d *digester) Hash() hash.Hash { + return d.hash +} + +func (d *digester) Digest() Digest { + return NewDigest(d.alg, d.hash) +} diff --git a/vendor/github.com/opencontainers/go-digest/doc.go b/vendor/github.com/opencontainers/go-digest/doc.go new file mode 100644 index 00000000..83d3a936 --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/doc.go @@ -0,0 +1,62 @@ +// Copyright 2019, 2020 OCI Contributors +// Copyright 2017 Docker, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package digest provides a generalized type to opaquely represent message +// digests and their operations within the registry. The Digest type is +// designed to serve as a flexible identifier in a content-addressable system. +// More importantly, it provides tools and wrappers to work with +// hash.Hash-based digests with little effort. +// +// Basics +// +// The format of a digest is simply a string with two parts, dubbed the +// "algorithm" and the "digest", separated by a colon: +// +// : +// +// An example of a sha256 digest representation follows: +// +// sha256:7173b809ca12ec5dee4506cd86be934c4596dd234ee82c0662eac04a8c2c71dc +// +// The "algorithm" portion defines both the hashing algorithm used to calculate +// the digest and the encoding of the resulting digest, which defaults to "hex" +// if not otherwise specified. Currently, all supported algorithms have their +// digests encoded in hex strings. +// +// In the example above, the string "sha256" is the algorithm and the hex bytes +// are the "digest". +// +// Because the Digest type is simply a string, once a valid Digest is +// obtained, comparisons are cheap, quick and simple to express with the +// standard equality operator. +// +// Verification +// +// The main benefit of using the Digest type is simple verification against a +// given digest. The Verifier interface, modeled after the stdlib hash.Hash +// interface, provides a common write sink for digest verification. After +// writing is complete, calling the Verifier.Verified method will indicate +// whether or not the stream of bytes matches the target digest. +// +// Missing Features +// +// In addition to the above, we intend to add the following features to this +// package: +// +// 1. A Digester type that supports write sink digest calculation. +// +// 2. Suspend and resume of ongoing digest calculations to support efficient digest verification in the registry. +// +package digest diff --git a/vendor/github.com/opencontainers/go-digest/verifiers.go b/vendor/github.com/opencontainers/go-digest/verifiers.go new file mode 100644 index 00000000..afef506f --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/verifiers.go @@ -0,0 +1,46 @@ +// Copyright 2019, 2020 OCI Contributors +// Copyright 2017 Docker, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package digest + +import ( + "hash" + "io" +) + +// Verifier presents a general verification interface to be used with message +// digests and other byte stream verifications. Users instantiate a Verifier +// from one of the various methods, write the data under test to it then check +// the result with the Verified method. +type Verifier interface { + io.Writer + + // Verified will return true if the content written to Verifier matches + // the digest. + Verified() bool +} + +type hashVerifier struct { + digest Digest + hash hash.Hash +} + +func (hv hashVerifier) Write(p []byte) (n int, err error) { + return hv.hash.Write(p) +} + +func (hv hashVerifier) Verified() bool { + return hv.digest == NewDigest(hv.digest.Algorithm(), hv.hash) +} diff --git a/vendor/github.com/opencontainers/image-spec/LICENSE b/vendor/github.com/opencontainers/image-spec/LICENSE new file mode 100644 index 00000000..9fdc20fd --- /dev/null +++ b/vendor/github.com/opencontainers/image-spec/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2016 The Linux Foundation. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/annotations.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/annotations.go new file mode 100644 index 00000000..581cf7cd --- /dev/null +++ b/vendor/github.com/opencontainers/image-spec/specs-go/v1/annotations.go @@ -0,0 +1,62 @@ +// Copyright 2016 The Linux Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1 + +const ( + // AnnotationCreated is the annotation key for the date and time on which the image was built (date-time string as defined by RFC 3339). + AnnotationCreated = "org.opencontainers.image.created" + + // AnnotationAuthors is the annotation key for the contact details of the people or organization responsible for the image (freeform string). + AnnotationAuthors = "org.opencontainers.image.authors" + + // AnnotationURL is the annotation key for the URL to find more information on the image. + AnnotationURL = "org.opencontainers.image.url" + + // AnnotationDocumentation is the annotation key for the URL to get documentation on the image. + AnnotationDocumentation = "org.opencontainers.image.documentation" + + // AnnotationSource is the annotation key for the URL to get source code for building the image. + AnnotationSource = "org.opencontainers.image.source" + + // AnnotationVersion is the annotation key for the version of the packaged software. + // The version MAY match a label or tag in the source code repository. + // The version MAY be Semantic versioning-compatible. + AnnotationVersion = "org.opencontainers.image.version" + + // AnnotationRevision is the annotation key for the source control revision identifier for the packaged software. + AnnotationRevision = "org.opencontainers.image.revision" + + // AnnotationVendor is the annotation key for the name of the distributing entity, organization or individual. + AnnotationVendor = "org.opencontainers.image.vendor" + + // AnnotationLicenses is the annotation key for the license(s) under which contained software is distributed as an SPDX License Expression. + AnnotationLicenses = "org.opencontainers.image.licenses" + + // AnnotationRefName is the annotation key for the name of the reference for a target. + // SHOULD only be considered valid when on descriptors on `index.json` within image layout. + AnnotationRefName = "org.opencontainers.image.ref.name" + + // AnnotationTitle is the annotation key for the human-readable title of the image. + AnnotationTitle = "org.opencontainers.image.title" + + // AnnotationDescription is the annotation key for the human-readable description of the software packaged in the image. + AnnotationDescription = "org.opencontainers.image.description" + + // AnnotationBaseImageDigest is the annotation key for the digest of the image's base image. + AnnotationBaseImageDigest = "org.opencontainers.image.base.digest" + + // AnnotationBaseImageName is the annotation key for the image reference of the image's base image. + AnnotationBaseImageName = "org.opencontainers.image.base.name" +) diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/config.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/config.go new file mode 100644 index 00000000..36b0aeb8 --- /dev/null +++ b/vendor/github.com/opencontainers/image-spec/specs-go/v1/config.go @@ -0,0 +1,111 @@ +// Copyright 2016 The Linux Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1 + +import ( + "time" + + digest "github.com/opencontainers/go-digest" +) + +// ImageConfig defines the execution parameters which should be used as a base when running a container using an image. +type ImageConfig struct { + // User defines the username or UID which the process in the container should run as. + User string `json:"User,omitempty"` + + // ExposedPorts a set of ports to expose from a container running this image. + ExposedPorts map[string]struct{} `json:"ExposedPorts,omitempty"` + + // Env is a list of environment variables to be used in a container. + Env []string `json:"Env,omitempty"` + + // Entrypoint defines a list of arguments to use as the command to execute when the container starts. + Entrypoint []string `json:"Entrypoint,omitempty"` + + // Cmd defines the default arguments to the entrypoint of the container. + Cmd []string `json:"Cmd,omitempty"` + + // Volumes is a set of directories describing where the process is likely write data specific to a container instance. + Volumes map[string]struct{} `json:"Volumes,omitempty"` + + // WorkingDir sets the current working directory of the entrypoint process in the container. + WorkingDir string `json:"WorkingDir,omitempty"` + + // Labels contains arbitrary metadata for the container. + Labels map[string]string `json:"Labels,omitempty"` + + // StopSignal contains the system call signal that will be sent to the container to exit. + StopSignal string `json:"StopSignal,omitempty"` + + // ArgsEscaped + // + // Deprecated: This field is present only for legacy compatibility with + // Docker and should not be used by new image builders. It is used by Docker + // for Windows images to indicate that the `Entrypoint` or `Cmd` or both, + // contains only a single element array, that is a pre-escaped, and combined + // into a single string `CommandLine`. If `true` the value in `Entrypoint` or + // `Cmd` should be used as-is to avoid double escaping. + // https://github.com/opencontainers/image-spec/pull/892 + ArgsEscaped bool `json:"ArgsEscaped,omitempty"` +} + +// RootFS describes a layer content addresses +type RootFS struct { + // Type is the type of the rootfs. + Type string `json:"type"` + + // DiffIDs is an array of layer content hashes (DiffIDs), in order from bottom-most to top-most. + DiffIDs []digest.Digest `json:"diff_ids"` +} + +// History describes the history of a layer. +type History struct { + // Created is the combined date and time at which the layer was created, formatted as defined by RFC 3339, section 5.6. + Created *time.Time `json:"created,omitempty"` + + // CreatedBy is the command which created the layer. + CreatedBy string `json:"created_by,omitempty"` + + // Author is the author of the build point. + Author string `json:"author,omitempty"` + + // Comment is a custom message set when creating the layer. + Comment string `json:"comment,omitempty"` + + // EmptyLayer is used to mark if the history item created a filesystem diff. + EmptyLayer bool `json:"empty_layer,omitempty"` +} + +// Image is the JSON structure which describes some basic information about the image. +// This provides the `application/vnd.oci.image.config.v1+json` mediatype when marshalled to JSON. +type Image struct { + // Created is the combined date and time at which the image was created, formatted as defined by RFC 3339, section 5.6. + Created *time.Time `json:"created,omitempty"` + + // Author defines the name and/or email address of the person or entity which created and is responsible for maintaining the image. + Author string `json:"author,omitempty"` + + // Platform describes the platform which the image in the manifest runs on. + Platform + + // Config defines the execution parameters which should be used as a base when running a container using the image. + Config ImageConfig `json:"config,omitempty"` + + // RootFS references the layer content addresses used by the image. + RootFS RootFS `json:"rootfs"` + + // History describes the history of each layer. + History []History `json:"history,omitempty"` +} diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/descriptor.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/descriptor.go new file mode 100644 index 00000000..1881b118 --- /dev/null +++ b/vendor/github.com/opencontainers/image-spec/specs-go/v1/descriptor.go @@ -0,0 +1,80 @@ +// Copyright 2016-2022 The Linux Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1 + +import digest "github.com/opencontainers/go-digest" + +// Descriptor describes the disposition of targeted content. +// This structure provides `application/vnd.oci.descriptor.v1+json` mediatype +// when marshalled to JSON. +type Descriptor struct { + // MediaType is the media type of the object this schema refers to. + MediaType string `json:"mediaType"` + + // Digest is the digest of the targeted content. + Digest digest.Digest `json:"digest"` + + // Size specifies the size in bytes of the blob. + Size int64 `json:"size"` + + // URLs specifies a list of URLs from which this object MAY be downloaded + URLs []string `json:"urls,omitempty"` + + // Annotations contains arbitrary metadata relating to the targeted content. + Annotations map[string]string `json:"annotations,omitempty"` + + // Data is an embedding of the targeted content. This is encoded as a base64 + // string when marshalled to JSON (automatically, by encoding/json). If + // present, Data can be used directly to avoid fetching the targeted content. + Data []byte `json:"data,omitempty"` + + // Platform describes the platform which the image in the manifest runs on. + // + // This should only be used when referring to a manifest. + Platform *Platform `json:"platform,omitempty"` + + // ArtifactType is the IANA media type of this artifact. + ArtifactType string `json:"artifactType,omitempty"` +} + +// Platform describes the platform which the image in the manifest runs on. +type Platform struct { + // Architecture field specifies the CPU architecture, for example + // `amd64` or `ppc64le`. + Architecture string `json:"architecture"` + + // OS specifies the operating system, for example `linux` or `windows`. + OS string `json:"os"` + + // OSVersion is an optional field specifying the operating system + // version, for example on Windows `10.0.14393.1066`. + OSVersion string `json:"os.version,omitempty"` + + // OSFeatures is an optional field specifying an array of strings, + // each listing a required OS feature (for example on Windows `win32k`). + OSFeatures []string `json:"os.features,omitempty"` + + // Variant is an optional field specifying a variant of the CPU, for + // example `v7` to specify ARMv7 when architecture is `arm`. + Variant string `json:"variant,omitempty"` +} + +// DescriptorEmptyJSON is the descriptor of a blob with content of `{}`. +var DescriptorEmptyJSON = Descriptor{ + MediaType: MediaTypeEmptyJSON, + Digest: `sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a`, + Size: 2, + Data: []byte(`{}`), +} diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/index.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/index.go new file mode 100644 index 00000000..e2bed9d4 --- /dev/null +++ b/vendor/github.com/opencontainers/image-spec/specs-go/v1/index.go @@ -0,0 +1,38 @@ +// Copyright 2016 The Linux Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1 + +import "github.com/opencontainers/image-spec/specs-go" + +// Index references manifests for various platforms. +// This structure provides `application/vnd.oci.image.index.v1+json` mediatype when marshalled to JSON. +type Index struct { + specs.Versioned + + // MediaType specifies the type of this document data structure e.g. `application/vnd.oci.image.index.v1+json` + MediaType string `json:"mediaType,omitempty"` + + // ArtifactType specifies the IANA media type of artifact when the manifest is used for an artifact. + ArtifactType string `json:"artifactType,omitempty"` + + // Manifests references platform specific manifests. + Manifests []Descriptor `json:"manifests"` + + // Subject is an optional link from the image manifest to another manifest forming an association between the image manifest and the other manifest. + Subject *Descriptor `json:"subject,omitempty"` + + // Annotations contains arbitrary metadata for the image index. + Annotations map[string]string `json:"annotations,omitempty"` +} diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/layout.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/layout.go new file mode 100644 index 00000000..c5503cb3 --- /dev/null +++ b/vendor/github.com/opencontainers/image-spec/specs-go/v1/layout.go @@ -0,0 +1,32 @@ +// Copyright 2016 The Linux Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1 + +const ( + // ImageLayoutFile is the file name containing ImageLayout in an OCI Image Layout + ImageLayoutFile = "oci-layout" + // ImageLayoutVersion is the version of ImageLayout + ImageLayoutVersion = "1.0.0" + // ImageIndexFile is the file name of the entry point for references and descriptors in an OCI Image Layout + ImageIndexFile = "index.json" + // ImageBlobsDir is the directory name containing content addressable blobs in an OCI Image Layout + ImageBlobsDir = "blobs" +) + +// ImageLayout is the structure in the "oci-layout" file, found in the root +// of an OCI Image-layout directory. +type ImageLayout struct { + Version string `json:"imageLayoutVersion"` +} diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/manifest.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/manifest.go new file mode 100644 index 00000000..26fec52a --- /dev/null +++ b/vendor/github.com/opencontainers/image-spec/specs-go/v1/manifest.go @@ -0,0 +1,41 @@ +// Copyright 2016-2022 The Linux Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1 + +import "github.com/opencontainers/image-spec/specs-go" + +// Manifest provides `application/vnd.oci.image.manifest.v1+json` mediatype structure when marshalled to JSON. +type Manifest struct { + specs.Versioned + + // MediaType specifies the type of this document data structure e.g. `application/vnd.oci.image.manifest.v1+json` + MediaType string `json:"mediaType,omitempty"` + + // ArtifactType specifies the IANA media type of artifact when the manifest is used for an artifact. + ArtifactType string `json:"artifactType,omitempty"` + + // Config references a configuration object for a container, by digest. + // The referenced configuration object is a JSON blob that the runtime uses to set up the container. + Config Descriptor `json:"config"` + + // Layers is an indexed list of layers referenced by the manifest. + Layers []Descriptor `json:"layers"` + + // Subject is an optional link from the image manifest to another manifest forming an association between the image manifest and the other manifest. + Subject *Descriptor `json:"subject,omitempty"` + + // Annotations contains arbitrary metadata for the image manifest. + Annotations map[string]string `json:"annotations,omitempty"` +} diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/mediatype.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/mediatype.go new file mode 100644 index 00000000..ce8313e7 --- /dev/null +++ b/vendor/github.com/opencontainers/image-spec/specs-go/v1/mediatype.go @@ -0,0 +1,85 @@ +// Copyright 2016 The Linux Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1 + +const ( + // MediaTypeDescriptor specifies the media type for a content descriptor. + MediaTypeDescriptor = "application/vnd.oci.descriptor.v1+json" + + // MediaTypeLayoutHeader specifies the media type for the oci-layout. + MediaTypeLayoutHeader = "application/vnd.oci.layout.header.v1+json" + + // MediaTypeImageIndex specifies the media type for an image index. + MediaTypeImageIndex = "application/vnd.oci.image.index.v1+json" + + // MediaTypeImageManifest specifies the media type for an image manifest. + MediaTypeImageManifest = "application/vnd.oci.image.manifest.v1+json" + + // MediaTypeImageConfig specifies the media type for the image configuration. + MediaTypeImageConfig = "application/vnd.oci.image.config.v1+json" + + // MediaTypeEmptyJSON specifies the media type for an unused blob containing the value "{}". + MediaTypeEmptyJSON = "application/vnd.oci.empty.v1+json" +) + +const ( + // MediaTypeImageLayer is the media type used for layers referenced by the manifest. + MediaTypeImageLayer = "application/vnd.oci.image.layer.v1.tar" + + // MediaTypeImageLayerGzip is the media type used for gzipped layers + // referenced by the manifest. + MediaTypeImageLayerGzip = "application/vnd.oci.image.layer.v1.tar+gzip" + + // MediaTypeImageLayerZstd is the media type used for zstd compressed + // layers referenced by the manifest. + MediaTypeImageLayerZstd = "application/vnd.oci.image.layer.v1.tar+zstd" +) + +// Non-distributable layer media-types. +// +// Deprecated: Non-distributable layers are deprecated, and not recommended +// for future use. Implementations SHOULD NOT produce new non-distributable +// layers. +// https://github.com/opencontainers/image-spec/pull/965 +const ( + // MediaTypeImageLayerNonDistributable is the media type for layers referenced by + // the manifest but with distribution restrictions. + // + // Deprecated: Non-distributable layers are deprecated, and not recommended + // for future use. Implementations SHOULD NOT produce new non-distributable + // layers. + // https://github.com/opencontainers/image-spec/pull/965 + MediaTypeImageLayerNonDistributable = "application/vnd.oci.image.layer.nondistributable.v1.tar" + + // MediaTypeImageLayerNonDistributableGzip is the media type for + // gzipped layers referenced by the manifest but with distribution + // restrictions. + // + // Deprecated: Non-distributable layers are deprecated, and not recommended + // for future use. Implementations SHOULD NOT produce new non-distributable + // layers. + // https://github.com/opencontainers/image-spec/pull/965 + MediaTypeImageLayerNonDistributableGzip = "application/vnd.oci.image.layer.nondistributable.v1.tar+gzip" + + // MediaTypeImageLayerNonDistributableZstd is the media type for zstd + // compressed layers referenced by the manifest but with distribution + // restrictions. + // + // Deprecated: Non-distributable layers are deprecated, and not recommended + // for future use. Implementations SHOULD NOT produce new non-distributable + // layers. + // https://github.com/opencontainers/image-spec/pull/965 + MediaTypeImageLayerNonDistributableZstd = "application/vnd.oci.image.layer.nondistributable.v1.tar+zstd" +) diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/version.go b/vendor/github.com/opencontainers/image-spec/specs-go/version.go new file mode 100644 index 00000000..7069ae44 --- /dev/null +++ b/vendor/github.com/opencontainers/image-spec/specs-go/version.go @@ -0,0 +1,32 @@ +// Copyright 2016 The Linux Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package specs + +import "fmt" + +const ( + // VersionMajor is for an API incompatible changes + VersionMajor = 1 + // VersionMinor is for functionality in a backwards-compatible manner + VersionMinor = 1 + // VersionPatch is for backwards-compatible bug fixes + VersionPatch = 0 + + // VersionDev indicates development branch. Releases will be empty string. + VersionDev = "" +) + +// Version is the specification version that the package types support. +var Version = fmt.Sprintf("%d.%d.%d%s", VersionMajor, VersionMinor, VersionPatch, VersionDev) diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/versioned.go b/vendor/github.com/opencontainers/image-spec/specs-go/versioned.go new file mode 100644 index 00000000..58a1510f --- /dev/null +++ b/vendor/github.com/opencontainers/image-spec/specs-go/versioned.go @@ -0,0 +1,23 @@ +// Copyright 2016 The Linux Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package specs + +// Versioned provides a struct with the manifest schemaVersion and mediaType. +// Incoming content with unknown schema version can be decoded against this +// struct to check the version. +type Versioned struct { + // SchemaVersion is the image manifest schema that this image follows + SchemaVersion int `json:"schemaVersion"` +} diff --git a/vendor/github.com/opencontainers/runc/LICENSE b/vendor/github.com/opencontainers/runc/LICENSE new file mode 100644 index 00000000..27448585 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2014 Docker, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/opencontainers/runc/NOTICE b/vendor/github.com/opencontainers/runc/NOTICE new file mode 100644 index 00000000..c29775c0 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/NOTICE @@ -0,0 +1,17 @@ +runc + +Copyright 2012-2015 Docker, Inc. + +This product includes software developed at Docker, Inc. (http://www.docker.com). + +The following is courtesy of our legal counsel: + + +Use and transfer of Docker may be subject to certain restrictions by the +United States and other governments. +It is your responsibility to ensure that your use and/or transfer does not +violate applicable laws. + +For more information, please see http://www.bis.doc.gov + +See also http://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_deprecated.go b/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_deprecated.go new file mode 100644 index 00000000..c6cd4434 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_deprecated.go @@ -0,0 +1,81 @@ +package user + +import ( + "io" + + "github.com/moby/sys/user" +) + +// LookupUser looks up a user by their username in /etc/passwd. If the user +// cannot be found (or there is no /etc/passwd file on the filesystem), then +// LookupUser returns an error. +func LookupUser(username string) (user.User, error) { + return user.LookupUser(username) +} + +// LookupUid looks up a user by their user id in /etc/passwd. If the user cannot +// be found (or there is no /etc/passwd file on the filesystem), then LookupId +// returns an error. +func LookupUid(uid int) (user.User, error) { //nolint:revive // ignore var-naming: func LookupUid should be LookupUID + return user.LookupUid(uid) +} + +// LookupGroup looks up a group by its name in /etc/group. If the group cannot +// be found (or there is no /etc/group file on the filesystem), then LookupGroup +// returns an error. +func LookupGroup(groupname string) (user.Group, error) { + return user.LookupGroup(groupname) +} + +// LookupGid looks up a group by its group id in /etc/group. If the group cannot +// be found (or there is no /etc/group file on the filesystem), then LookupGid +// returns an error. +func LookupGid(gid int) (user.Group, error) { + return user.LookupGid(gid) +} + +func GetPasswdPath() (string, error) { + return user.GetPasswdPath() +} + +func GetPasswd() (io.ReadCloser, error) { + return user.GetPasswd() +} + +func GetGroupPath() (string, error) { + return user.GetGroupPath() +} + +func GetGroup() (io.ReadCloser, error) { + return user.GetGroup() +} + +// CurrentUser looks up the current user by their user id in /etc/passwd. If the +// user cannot be found (or there is no /etc/passwd file on the filesystem), +// then CurrentUser returns an error. +func CurrentUser() (user.User, error) { + return user.CurrentUser() +} + +// CurrentGroup looks up the current user's group by their primary group id's +// entry in /etc/passwd. If the group cannot be found (or there is no +// /etc/group file on the filesystem), then CurrentGroup returns an error. +func CurrentGroup() (user.Group, error) { + return user.CurrentGroup() +} + +func CurrentUserSubUIDs() ([]user.SubID, error) { + return user.CurrentUserSubUIDs() +} + +func CurrentUserSubGIDs() ([]user.SubID, error) { + return user.CurrentUserSubGIDs() +} + +func CurrentProcessUIDMap() ([]user.IDMap, error) { + return user.CurrentProcessUIDMap() +} + +func CurrentProcessGIDMap() ([]user.IDMap, error) { + return user.CurrentProcessGIDMap() +} diff --git a/vendor/github.com/opencontainers/runc/libcontainer/user/user_deprecated.go b/vendor/github.com/opencontainers/runc/libcontainer/user/user_deprecated.go new file mode 100644 index 00000000..3c29f3d1 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/libcontainer/user/user_deprecated.go @@ -0,0 +1,146 @@ +// Package user is an alias for [github.com/moby/sys/user]. +// +// Deprecated: use [github.com/moby/sys/user]. +package user + +import ( + "io" + + "github.com/moby/sys/user" +) + +var ( + // ErrNoPasswdEntries is returned if no matching entries were found in /etc/group. + ErrNoPasswdEntries = user.ErrNoPasswdEntries + // ErrNoGroupEntries is returned if no matching entries were found in /etc/passwd. + ErrNoGroupEntries = user.ErrNoGroupEntries + // ErrRange is returned if a UID or GID is outside of the valid range. + ErrRange = user.ErrRange +) + +type ( + User = user.User + + Group = user.Group + + // SubID represents an entry in /etc/sub{u,g}id. + SubID = user.SubID + + // IDMap represents an entry in /proc/PID/{u,g}id_map. + IDMap = user.IDMap + + ExecUser = user.ExecUser +) + +func ParsePasswdFile(path string) ([]user.User, error) { + return user.ParsePasswdFile(path) +} + +func ParsePasswd(passwd io.Reader) ([]user.User, error) { + return user.ParsePasswd(passwd) +} + +func ParsePasswdFileFilter(path string, filter func(user.User) bool) ([]user.User, error) { + return user.ParsePasswdFileFilter(path, filter) +} + +func ParsePasswdFilter(r io.Reader, filter func(user.User) bool) ([]user.User, error) { + return user.ParsePasswdFilter(r, filter) +} + +func ParseGroupFile(path string) ([]user.Group, error) { + return user.ParseGroupFile(path) +} + +func ParseGroup(group io.Reader) ([]user.Group, error) { + return user.ParseGroup(group) +} + +func ParseGroupFileFilter(path string, filter func(user.Group) bool) ([]user.Group, error) { + return user.ParseGroupFileFilter(path, filter) +} + +func ParseGroupFilter(r io.Reader, filter func(user.Group) bool) ([]user.Group, error) { + return user.ParseGroupFilter(r, filter) +} + +// GetExecUserPath is a wrapper for GetExecUser. It reads data from each of the +// given file paths and uses that data as the arguments to GetExecUser. If the +// files cannot be opened for any reason, the error is ignored and a nil +// io.Reader is passed instead. +func GetExecUserPath(userSpec string, defaults *user.ExecUser, passwdPath, groupPath string) (*user.ExecUser, error) { + return user.GetExecUserPath(userSpec, defaults, passwdPath, groupPath) +} + +// GetExecUser parses a user specification string (using the passwd and group +// readers as sources for /etc/passwd and /etc/group data, respectively). In +// the case of blank fields or missing data from the sources, the values in +// defaults is used. +// +// GetExecUser will return an error if a user or group literal could not be +// found in any entry in passwd and group respectively. +// +// Examples of valid user specifications are: +// - "" +// - "user" +// - "uid" +// - "user:group" +// - "uid:gid +// - "user:gid" +// - "uid:group" +// +// It should be noted that if you specify a numeric user or group id, they will +// not be evaluated as usernames (only the metadata will be filled). So attempting +// to parse a user with user.Name = "1337" will produce the user with a UID of +// 1337. +func GetExecUser(userSpec string, defaults *user.ExecUser, passwd, group io.Reader) (*user.ExecUser, error) { + return user.GetExecUser(userSpec, defaults, passwd, group) +} + +// GetAdditionalGroups looks up a list of groups by name or group id +// against the given /etc/group formatted data. If a group name cannot +// be found, an error will be returned. If a group id cannot be found, +// or the given group data is nil, the id will be returned as-is +// provided it is in the legal range. +func GetAdditionalGroups(additionalGroups []string, group io.Reader) ([]int, error) { + return user.GetAdditionalGroups(additionalGroups, group) +} + +// GetAdditionalGroupsPath is a wrapper around GetAdditionalGroups +// that opens the groupPath given and gives it as an argument to +// GetAdditionalGroups. +func GetAdditionalGroupsPath(additionalGroups []string, groupPath string) ([]int, error) { + return user.GetAdditionalGroupsPath(additionalGroups, groupPath) +} + +func ParseSubIDFile(path string) ([]user.SubID, error) { + return user.ParseSubIDFile(path) +} + +func ParseSubID(subid io.Reader) ([]user.SubID, error) { + return user.ParseSubID(subid) +} + +func ParseSubIDFileFilter(path string, filter func(user.SubID) bool) ([]user.SubID, error) { + return user.ParseSubIDFileFilter(path, filter) +} + +func ParseSubIDFilter(r io.Reader, filter func(user.SubID) bool) ([]user.SubID, error) { + return user.ParseSubIDFilter(r, filter) +} + +func ParseIDMapFile(path string) ([]user.IDMap, error) { + return user.ParseIDMapFile(path) +} + +func ParseIDMap(r io.Reader) ([]user.IDMap, error) { + return user.ParseIDMap(r) +} + +func ParseIDMapFileFilter(path string, filter func(user.IDMap) bool) ([]user.IDMap, error) { + return user.ParseIDMapFileFilter(path, filter) +} + +func ParseIDMapFilter(r io.Reader, filter func(user.IDMap) bool) ([]user.IDMap, error) { + return user.ParseIDMapFilter(r, filter) +} diff --git a/vendor/github.com/ory/dockertest/v3/.gitignore b/vendor/github.com/ory/dockertest/v3/.gitignore new file mode 100644 index 00000000..78ca93dd --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/.gitignore @@ -0,0 +1,12 @@ +.bin/ +.idea/ +node_modules/ +*.iml +*.exe +.cover/ +vendor/ +go.list +cover.out +coverage.out +.vscode +.bin/ diff --git a/vendor/github.com/ory/dockertest/v3/.nancy-ignore b/vendor/github.com/ory/dockertest/v3/.nancy-ignore new file mode 100644 index 00000000..65714562 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/.nancy-ignore @@ -0,0 +1 @@ +CVE-2023-27561 # see https://github.com/sonatype-nexus-community/nancy/issues/273 diff --git a/vendor/github.com/ory/dockertest/v3/.prettierignore b/vendor/github.com/ory/dockertest/v3/.prettierignore new file mode 100644 index 00000000..15683604 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/.prettierignore @@ -0,0 +1,2 @@ +.github/pull_request_template.md +CONTRIBUTING.md diff --git a/vendor/github.com/ory/dockertest/v3/.reference-ignore b/vendor/github.com/ory/dockertest/v3/.reference-ignore new file mode 100644 index 00000000..eee2a89c --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/.reference-ignore @@ -0,0 +1,3 @@ +**/node_modules +docs +CHANGELOG.md diff --git a/vendor/github.com/ory/dockertest/v3/CODE_OF_CONDUCT.md b/vendor/github.com/ory/dockertest/v3/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..9cebaf35 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/CODE_OF_CONDUCT.md @@ -0,0 +1,145 @@ + + + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +- Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +- The use of sexualized language or imagery, and sexual attention or advances of + any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, + without their explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Open Source Community Support + +Ory Open source software is collaborative and based on contributions by +developers in the Ory community. There is no obligation from Ory to help with +individual problems. If Ory open source software is used in production in a +for-profit company or enterprise environment, we mandate a paid support contract +where Ory is obligated under their service level agreements (SLAs) to offer a +defined level of availability and responsibility. For more information about +paid support please contact us at sales@ory.sh. + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +[office@ory.sh](mailto:office@ory.sh). All complaints will be reviewed and +investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder][mozilla coc]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][faq]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[mozilla coc]: https://github.com/mozilla/diversity +[faq]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/vendor/github.com/ory/dockertest/v3/CONTRIBUTING.md b/vendor/github.com/ory/dockertest/v3/CONTRIBUTING.md new file mode 100644 index 00000000..0e0405fc --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/CONTRIBUTING.md @@ -0,0 +1,253 @@ + + + +# Contribute to Ory Dockertest + + + + +- [Introduction](#introduction) +- [FAQ](#faq) +- [How can I contribute?](#how-can-i-contribute) +- [Communication](#communication) +- [Contribute examples or community projects](#contribute-examples-or-community-projects) +- [Contribute code](#contribute-code) +- [Contribute documentation](#contribute-documentation) +- [Disclosing vulnerabilities](#disclosing-vulnerabilities) +- [Code style](#code-style) + - [Working with forks](#working-with-forks) +- [Conduct](#conduct) + + + +## Introduction + +_Please note_: We take Ory Dockertest's security and our users' trust very +seriously. If you believe you have found a security issue in Ory Dockertest, +please disclose it by contacting us at security@ory.sh. + +There are many ways in which you can contribute. The goal of this document is to +provide a high-level overview of how you can get involved in Ory. + +As a potential contributor, your changes and ideas are welcome at any hour of +the day or night, on weekdays, weekends, and holidays. Please do not ever +hesitate to ask a question or send a pull request. + +If you are unsure, just ask or submit the issue or pull request anyways. You +won't be yelled at for giving it your best effort. The worst that can happen is +that you'll be politely asked to change something. We appreciate any sort of +contributions and don't want a wall of rules to get in the way of that. + +That said, if you want to ensure that a pull request is likely to be merged, +talk to us! You can find out our thoughts and ensure that your contribution +won't clash with Ory +Dockertest's direction. A great way to +do this is via +[Ory Dockertest Discussions](https://github.com/orgs/ory/discussions) +or the [Ory Chat](https://www.ory.sh/chat). + +## FAQ + +- I am new to the community. Where can I find the + [Ory Community Code of Conduct?](https://github.com/ory/dockertest/blob/master/CODE_OF_CONDUCT.md) + +- I have a question. Where can I get + [answers to questions regarding Ory Dockertest?](#communication) + +- I would like to contribute but I am not sure how. Are there + [easy ways to contribute?](#how-can-i-contribute) + [Or good first issues?](https://github.com/search?l=&o=desc&q=label%3A%22help+wanted%22+label%3A%22good+first+issue%22+is%3Aopen+user%3Aory+user%3Aory-corp&s=updated&type=Issues) + +- I want to talk to other Ory Dockertest users. + [How can I become a part of the community?](#communication) + +- I would like to know what I am agreeing to when I contribute to Ory + Dockertest. + Does Ory have + [a Contributors License Agreement?](https://cla-assistant.io/ory/dockertest) + +- I would like updates about new versions of Ory Dockertest. + [How are new releases announced?](https://www.ory.sh/l/sign-up-newsletter) + +## How can I contribute? + +If you want to start to contribute code right away, take a look at the +[list of good first issues](https://github.com/ory/dockertest/labels/good%20first%20issue). + +There are many other ways you can contribute. Here are a few things you can do +to help out: + +- **Give us a star.** It may not seem like much, but it really makes a + difference. This is something that everyone can do to help out Ory Dockertest. + Github stars help the project gain visibility and stand out. + +- **Join the community.** Sometimes helping people can be as easy as listening + to their problems and offering a different perspective. Join our Slack, have a + look at discussions in the forum and take part in community events. More info + on this in [Communication](#communication). + +- **Answer discussions.** At all times, there are several unanswered discussions + on GitHub. You can see an + [overview here](https://github.com/discussions?discussions_q=is%3Aunanswered+org%3Aory+sort%3Aupdated-desc). + If you think you know an answer or can provide some information that might + help, please share it! Bonus: You get GitHub achievements for answered + discussions. + +- **Help with open issues.** We have a lot of open issues for Ory Dockertest and + some of them may lack necessary information, some are duplicates of older + issues. You can help out by guiding people through the process of filling out + the issue template, asking for clarifying information or pointing them to + existing issues that match their description of the problem. + +- **Review documentation changes.** Most documentation just needs a review for + proper spelling and grammar. If you think a document can be improved in any + way, feel free to hit the `edit` button at the top of the page. More info on + contributing to the documentation [here](#contribute-documentation). + +- **Help with tests.** Pull requests may lack proper tests or test plans. These + are needed for the change to be implemented safely. + +## Communication + +We use [Slack](https://www.ory.sh/chat). You are welcome to drop in and ask +questions, discuss bugs and feature requests, talk to other users of Ory, etc. + +Check out [Ory Dockertest Discussions](https://github.com/orgs/ory/discussions). This is a great place for +in-depth discussions and lots of code examples, logs and similar data. + +You can also join our community calls if you want to speak to the Ory team +directly or ask some questions. You can find more info and participate in +[Slack](https://www.ory.sh/chat) in the #community-call channel. + +If you want to receive regular notifications about updates to Ory Dockertest, +consider joining the mailing list. We will _only_ send you vital information on +the projects that you are interested in. + +Also, [follow us on Twitter](https://twitter.com/orycorp). + +## Contribute examples or community projects + +One of the most impactful ways to contribute is by adding code examples or other +Ory-related code. You can find an overview of community code in the +[awesome-ory](https://github.com/ory/awesome-ory) repository. + +_If you would like to contribute a new example, we would love to hear from you!_ + +Please [open a pull request at awesome-ory](https://github.com/ory/awesome-ory/) +to add your example or Ory-related project to the awesome-ory README. + +## Contribute code + +Unless you are fixing a known bug, we **strongly** recommend discussing it with +the core team via a GitHub issue or [in our chat](https://www.ory.sh/chat) +before getting started to ensure your work is consistent with Ory Dockertest's +roadmap and architecture. + +All contributions are made via pull requests. To make a pull request, you will +need a GitHub account; if you are unclear on this process, see GitHub's +documentation on [forking](https://help.github.com/articles/fork-a-repo) and +[pull requests](https://help.github.com/articles/using-pull-requests). Pull +requests should be targeted at the `master` branch. Before creating a pull +request, go through this checklist: + +1. Create a feature branch off of `master` so that changes do not get mixed up. +1. [Rebase](http://git-scm.com/book/en/Git-Branching-Rebasing) your local + changes against the `master` branch. +1. Run the full project test suite with the `go test -tags sqlite ./...` (or + equivalent) command and confirm that it passes. +1. Run `make format` +1. Add a descriptive prefix to commits. This ensures a uniform commit history + and helps structure the changelog. Please refer to this + [Convential Commits configuration](https://github.com/ory/dockertest/blob/master/.github/workflows/conventional_commits.yml) + for the list of accepted prefixes. You can read more about the Conventional + Commit specification + [at their site](https://www.conventionalcommits.org/en/v1.0.0/). + +If a pull request is not ready to be reviewed yet +[it should be marked as a "Draft"](https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request). + +Before your contributions can be reviewed you need to sign our +[Contributor License Agreement](https://cla-assistant.io/ory/dockertest). + +This agreement defines the terms under which your code is contributed to Ory. +More specifically it declares that you have the right to, and actually do, grant +us the rights to use your contribution. You can see the Apache 2.0 license under +which our projects are published +[here](https://github.com/ory/meta/blob/master/LICENSE). + +When pull requests fail the automated testing stages (for example unit or E2E +tests), authors are expected to update their pull requests to address the +failures until the tests pass. + +Pull requests eligible for review + +1. follow the repository's code formatting conventions; +2. include tests that prove that the change works as intended and does not add + regressions; +3. document the changes in the code and/or the project's documentation; +4. pass the CI pipeline; +5. have signed our + [Contributor License Agreement](https://cla-assistant.io/ory/dockertest); +6. include a proper git commit message following the + [Conventional Commit Specification](https://www.conventionalcommits.org/en/v1.0.0/). + +If all of these items are checked, the pull request is ready to be reviewed and +you should change the status to "Ready for review" and +[request review from a maintainer](https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/requesting-a-pull-request-review). + +Reviewers will approve the pull request once they are satisfied with the patch. + +## Contribute documentation + +Please provide documentation when changing, removing, or adding features. All +Ory Documentation resides in the +[Ory documentation repository](https://github.com/ory/docs/). For further +instructions please head over to the Ory Documentation +[README.md](https://github.com/ory/docs/blob/master/README.md). + +## Disclosing vulnerabilities + +Please disclose vulnerabilities exclusively to +[security@ory.sh](mailto:security@ory.sh). Do not use GitHub issues. + +## Code style + +Please run `make format` to format all source code following the Ory standard. + +### Working with forks + +```bash +# First you clone the original repository +git clone git@github.com:ory/ory/dockertest.git + +# Next you add a git remote that is your fork: +git remote add fork git@github.com:/ory/dockertest.git + +# Next you fetch the latest changes from origin for master: +git fetch origin +git checkout master +git pull --rebase + +# Next you create a new feature branch off of master: +git checkout my-feature-branch + +# Now you do your work and commit your changes: +git add -A +git commit -a -m "fix: this is the subject line" -m "This is the body line. Closes #123" + +# And the last step is pushing this to your fork +git push -u fork my-feature-branch +``` + +Now go to the project's GitHub Pull Request page and click "New pull request" + +## Conduct + +Whether you are a regular contributor or a newcomer, we care about making this +community a safe place for you and we've got your back. + +[Ory Community Code of Conduct](https://github.com/ory/dockertest/blob/master/CODE_OF_CONDUCT.md) + +We welcome discussion about creating a welcoming, safe, and productive +environment for the community. If you have any questions, feedback, or concerns +[please let us know](https://www.ory.sh/chat). diff --git a/vendor/github.com/ory/dockertest/v3/LICENSE b/vendor/github.com/ory/dockertest/v3/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/ory/dockertest/v3/Makefile b/vendor/github.com/ory/dockertest/v3/Makefile new file mode 100644 index 00000000..bac1ff11 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/Makefile @@ -0,0 +1,29 @@ +format: .bin/ory node_modules # formats the source code + .bin/ory dev headers copyright --type=open-source + gofmt -l -s -w . + npm exec -- prettier --write . + +help: + cat Makefile | grep '^[^ ]*:' | grep -v '^\.bin/' | grep -v '.SILENT:' | grep -v '^node_modules:' | grep -v help | sed 's/:.*#/#/' | column -s "#" -t + +licenses: .bin/licenses node_modules # checks open-source licenses + .bin/licenses + +.bin/licenses: Makefile + curl https://raw.githubusercontent.com/ory/ci/master/licenses/install | sh + +.bin/ory: Makefile + curl https://raw.githubusercontent.com/ory/meta/master/install.sh | bash -s -- -b .bin ory v0.3.2 + touch .bin/ory + +node_modules: package-lock.json + npm install + touch node_modules + +test: + go mod tidy + go vet -x . + go test -covermode=atomic -coverprofile="coverage.out" . + + +.DEFAULT_GOAL := help diff --git a/vendor/github.com/ory/dockertest/v3/README.md b/vendor/github.com/ory/dockertest/v3/README.md new file mode 100644 index 00000000..b2c610fd --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/README.md @@ -0,0 +1,260 @@ +

ORY Dockertest

+ +[![Build Status](https://travis-ci.org/ory/dockertest.svg)](https://travis-ci.org/ory/dockertest?branch=master) +[![Coverage Status](https://coveralls.io/repos/github/ory/dockertest/badge.svg?branch=v3)](https://coveralls.io/github/ory/dockertest?branch=v3) + +Use Docker to run your Golang integration tests against third party services on +**Microsoft Windows, Mac OSX and Linux**! + + + + +**Table of Contents** + +- [Why should I use Dockertest?](#why-should-i-use-dockertest) +- [Installing and using Dockertest](#installing-and-using-dockertest) + - [Using Dockertest](#using-dockertest) + - [Examples](#examples) +- [Troubleshoot & FAQ](#troubleshoot--faq) + - [Out of disk space](#out-of-disk-space) + - [Removing old containers](#removing-old-containers) + + + +## Why should I use Dockertest? + +When developing applications, it is often necessary to use services that talk to +a database system. Unit Testing these services can be cumbersome because mocking +database/DBAL is strenuous. Making slight changes to the schema implies +rewriting at least some, if not all of the mocks. The same goes for API changes +in the DBAL. To avoid this, it is smarter to test these specific services +against a real database that is destroyed after testing. Docker is the perfect +system for running unit tests as you can spin up containers in a few seconds and +kill them when the test completes. The Dockertest library provides easy to use +commands for spinning up Docker containers and using them for your tests. + +## Installing and using Dockertest + +Using Dockertest is straightforward and simple. Check the +[releases tab](https://github.com/ory/dockertest/releases) for available +releases. + +To install dockertest, run + +``` +go get -u github.com/ory/dockertest/v3 +``` + +### Using Dockertest + +```go +package dockertest_test + +import ( + "database/sql" + "fmt" + "log" + "os" + "testing" + + _ "github.com/go-sql-driver/mysql" + "github.com/ory/dockertest/v3" +) + +var db *sql.DB + +func TestMain(m *testing.M) { + // uses a sensible default on windows (tcp/http) and linux/osx (socket) + pool, err := dockertest.NewPool("") + if err != nil { + log.Fatalf("Could not construct pool: %s", err) + } + + // uses pool to try to connect to Docker + err = pool.Client.Ping() + if err != nil { + log.Fatalf("Could not connect to Docker: %s", err) + } + + // pulls an image, creates a container based on it and runs it + resource, err := pool.Run("mysql", "5.7", []string{"MYSQL_ROOT_PASSWORD=secret"}) + if err != nil { + log.Fatalf("Could not start resource: %s", err) + } + + // exponential backoff-retry, because the application in the container might not be ready to accept connections yet + if err := pool.Retry(func() error { + var err error + db, err = sql.Open("mysql", fmt.Sprintf("root:secret@(localhost:%s)/mysql", resource.GetPort("3306/tcp"))) + if err != nil { + return err + } + return db.Ping() + }); err != nil { + log.Fatalf("Could not connect to database: %s", err) + } + + // as of go1.15 testing.M returns the exit code of m.Run(), so it is safe to use defer here + defer func() { + if err := pool.Purge(resource); err != nil { + log.Fatalf("Could not purge resource: %s", err) + } + + }() + + m.Run() +} + +func TestSomething(t *testing.T) { + // db.Query() +} +``` + +### Examples + +We provide code examples for well known services in the [examples](examples/) +directory, check them out! + +## Troubleshoot & FAQ + +### Out of disk space + +Try cleaning up the images with +[docker-cleanup-volumes](https://github.com/chadoe/docker-cleanup-volumes). + +### Removing old containers + +Sometimes container clean up fails. Check out +[this stackoverflow question](http://stackoverflow.com/questions/21398087/how-to-delete-dockers-images) +on how to fix this. You may also set an absolute lifetime on containers: + +```go +resource.Expire(60) // Tell docker to hard kill the container in 60 seconds +``` + +To let stopped containers removed from file system automatically, use +`pool.RunWithOptions()` instead of `pool.Run()` with `config.AutoRemove` set to +true, e.g.: + +```go +postgres, err := pool.RunWithOptions(&dockertest.RunOptions{ + Repository: "postgres", + Tag: "11", + Env: []string{ + "POSTGRES_USER=test", + "POSTGRES_PASSWORD=test", + "listen_addresses = '*'", + }, +}, func(config *docker.HostConfig) { + // set AutoRemove to true so that stopped container goes away by itself + config.AutoRemove = true + config.RestartPolicy = docker.RestartPolicy{ + Name: "no", + } +}) +``` + +## Running dockertest in Gitlab CI + +### How to run dockertest on shared gitlab runners? + +You should add docker dind service to your job which starts in sibling +container. That means database will be available on host `docker`. +You app should be able to change db host through environment variable. + +Here is the simple example of `gitlab-ci.yml`: + +```yaml +stages: + - test +go-test: + stage: test + image: golang:1.15 + services: + - docker:dind + variables: + DOCKER_HOST: tcp://docker:2375 + DOCKER_DRIVER: overlay2 + YOUR_APP_DB_HOST: docker + script: + - go test ./... +``` + +Plus in the `pool.Retry` method that checks for connection readiness, you need +to use `$YOUR_APP_DB_HOST` instead of localhost. + +### How to run dockertest on group(custom) gitlab runners? + +Gitlab runner can be run in docker executor mode to save compatibility with +shared runners. +Here is the simple register command: + +```shell script +gitlab-runner register -n \ + --url https://gitlab.com/ \ + --registration-token $YOUR_TOKEN \ + --executor docker \ + --description "My Docker Runner" \ + --docker-image "docker:19.03.12" \ + --docker-privileged +``` + +You only need to instruct docker dind to start with disabled tls. +Add variable `DOCKER_TLS_CERTDIR: ""` to `gitlab-ci.yml` above. It will tell +docker daemon to start on 2375 port over http. + +## Running Dockertest Using GitHub Actions + +```yaml +name: Test with Docker + +on: [push] + +jobs: + test: + runs-on: ubuntu-latest + services: + dind: + image: docker:23.0-rc-dind-rootless + ports: + - 2375:2375 + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: "1.21" + + - name: Test with Docker + run: go test -v ./... +``` + +### How to run dockertest with remote Docker + +Use-case: locally installed docker CLI (client), docker daemon somewhere +remotely, environment properly set (ie: `DOCKER_HOST`, etc..). For example, +remote docker can be provisioned by docker-machine. + +Currently, dockertest in case of `resource.GetHostPort()` will return docker +host binding address (commonly - `localhost`) instead of remote docker host. +Universal solution is: + +```go +func getHostPort(resource *dockertest.Resource, id string) string { + dockerURL := os.Getenv("DOCKER_HOST") + if dockerURL == "" { + return resource.GetHostPort(id) + } + u, err := url.Parse(dockerURL) + if err != nil { + panic(err) + } + return u.Hostname() + ":" + resource.GetPort(id) +} +``` + +It will return the remote docker host concatenated with the allocated port in +case `DOCKER_HOST` env is defined. Otherwise, it will fall back to the embedded +behavior. diff --git a/vendor/github.com/ory/dockertest/v3/SECURITY.md b/vendor/github.com/ory/dockertest/v3/SECURITY.md new file mode 100644 index 00000000..61045148 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/SECURITY.md @@ -0,0 +1,56 @@ + + + +# Ory Security Policy + +This policy outlines Ory's security commitments and practices for users across +different licensing and deployment models. + +To learn more about Ory's security service level agreements (SLAs) and +processes, please [contact us](https://www.ory.sh/contact/). + +## Ory Network Users + +- **Security SLA:** Ory addresses vulnerabilities in the Ory Network according + to the following guidelines: + - Critical: Typically addressed within 14 days. + - High: Typically addressed within 30 days. + - Medium: Typically addressed within 90 days. + - Low: Typically addressed within 180 days. + - Informational: Addressed as necessary. + These timelines are targets and may vary based on specific circumstances. +- **Release Schedule:** Updates are deployed to the Ory Network as + vulnerabilities are resolved. +- **Version Support:** The Ory Network always runs the latest version, ensuring + up-to-date security fixes. + +## Ory Enterprise License Customers + +- **Security SLA:** Ory addresses vulnerabilities based on their severity: + - Critical: Typically addressed within 14 days. + - High: Typically addressed within 30 days. + - Medium: Typically addressed within 90 days. + - Low: Typically addressed within 180 days. + - Informational: Addressed as necessary. + These timelines are targets and may vary based on specific circumstances. +- **Release Schedule:** Updates are made available as vulnerabilities are + resolved. Ory works closely with enterprise customers to ensure timely updates + that align with their operational needs. +- **Version Support:** Ory may provide security support for multiple versions, + depending on the terms of the enterprise agreement. + +## Apache 2.0 License Users + +- **Security SLA:** Ory does not provide a formal SLA for security issues under + the Apache 2.0 License. +- **Release Schedule:** Releases prioritize new functionality and include fixes + for known security vulnerabilities at the time of release. While major + releases typically occur one to two times per year, Ory does not guarantee a + fixed release schedule. +- **Version Support:** Security patches are only provided for the latest release + version. + +## Reporting a Vulnerability + +For details on how to report security vulnerabilities, visit our +[security policy documentation](https://www.ory.sh/docs/ecosystem/security). diff --git a/vendor/github.com/ory/dockertest/v3/docker/AUTHORS b/vendor/github.com/ory/dockertest/v3/docker/AUTHORS new file mode 100644 index 00000000..464d9498 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/AUTHORS @@ -0,0 +1,192 @@ +# This is the official list of go-dockerclient authors for copyright purposes. + +Abhishek Chanda +Adam Bell-Hanssen +Adnan Khan +Adrien Kohlbecker +Aldrin Leal +Alex Dadgar +Alfonso Acosta +André Carvalho +Andreas Jaekle +Andrew Snodgrass +Andrews Medina +Andrey Sibiryov +Andy Goldstein +Anirudh Aithal +Antonio Murdaca +Artem Sidorenko +Arthur Rodrigues +Ben Marini +Ben McCann +Ben Parees +Benno van den Berg +Bradley Cicenas +Brendan Fosberry +Brian Lalor +Brian P. Hamachek +Brian Palmer +Bryan Boreham +Burke Libbey +Carlos Diaz-Padron +Carson A +Cássio Botaro +Cesar Wong +Cezar Sa Espinola +Changping Chen +Cheah Chu Yeow +cheneydeng +Chris Bednarski +Chris Stavropoulos +Christian Stewart +Christophe Mourette +Clayton Coleman +Clint Armstrong +CMGS +Colin Hebert +Craig Jellick +Damien Lespiau +Damon Wang +Dan Williams +Daniel, Dao Quang Minh +Daniel Garcia +Daniel Hiltgen +Daniel Nephin +Daniel Tsui +Darren Shepherd +Dave Choi +David Huie +Dawn Chen +Denis Makogon +Derek Petersen +Dinesh Subhraveti +Drew Wells +Ed +Elias G. Schneevoigt +Erez Horev +Eric Anderson +Eric J. Holmes +Eric Mountain +Erwin van Eyk +Ethan Mosbaugh +Ewout Prangsma +Fabio Rehm +Fatih Arslan +Felipe Oliveira +Flavia Missi +Florent Aide +Francisco Souza +Frank Groeneveld +George Moura +Grégoire Delattre +Guilherme Rezende +Guillermo Álvarez Fernández +Harry Zhang +He Simei +Isaac Schnitzer +Ivan Mikushin +James Bardin +James Nugent +Jamie Snell +Januar Wayong +Jari Kolehmainen +Jason Wilder +Jawher Moussa +Jean-Baptiste Dalido +Jeff Mitchell +Jeffrey Hulten +Jen Andre +Jérôme Laurens +Jim Minter +Johan Euphrosine +Johannes Scheuermann +John Hughes +Jorge Marey +Julian Einwag +Kamil Domanski +Karan Misra +Ken Herner +Kevin Lin +Kevin Xu +Kim, Hirokuni +Kostas Lekkas +Kyle Allan +Yunhee Lee +Liron Levin +Lior Yankovich +Liu Peng +Lorenz Leutgeb +Lucas Clemente +Lucas Weiblen +Lyon Hill +Mantas Matelis +Manuel Vogel +Marguerite des Trois Maisons +Mariusz Borsa +Martin Sweeney +Máximo Cuadros Ortiz +Michael Schmatz +Michal Fojtik +Mike Dillon +Mrunal Patel +Nate Jones +Nguyen Sy Thanh Son +Nicholas Van Wiggeren +Nick Ethier +niko83 +Omeid Matten +Orivej Desh +Paul Bellamy +Paul Morie +Paul Weil +Peter Edge +Peter Jihoon Kim +Peter Teich +Phil Lu +Philippe Lafoucrière +Radek Simko +Rafe Colton +Raphaël Pinson +Reed Allman +RJ Catalano +Rob Miller +Robbert Klarenbeek +Robert Williamson +Roman Khlystik +Russell Haering +Salvador Gironès +Sam Rijs +Sami Wagiaalla +Samuel Archambault +Samuel Karp +Sebastian Borza +Seth Jennings +Shane Xie +Silas Sewell +Simon Eskildsen +Simon Menke +Skolos +Soulou +Sridhar Ratnakumar +Steven Jack +Summer Mousa +Sunjin Lee +Sunny +Swaroop Ramachandra +Tarsis Azevedo +Tim Schindler +Timothy St. Clair +Tobi Knaup +Tom Wilkie +Tonic +ttyh061 +upccup +Victor Marmol +Vincenzo Prignano +Vlad Alexandru Ionescu +Weitao Zhou +Wiliam Souza +Ye Yin +Yosuke Otosu +Yu, Zou +Yuriy Bogdanov diff --git a/vendor/github.com/ory/dockertest/v3/docker/DOCKER-LICENSE b/vendor/github.com/ory/dockertest/v3/docker/DOCKER-LICENSE new file mode 100644 index 00000000..70663447 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/DOCKER-LICENSE @@ -0,0 +1,6 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +You can find the Docker license at the following link: +https://raw.githubusercontent.com/docker/docker/master/LICENSE diff --git a/vendor/github.com/ory/dockertest/v3/docker/LICENSE b/vendor/github.com/ory/dockertest/v3/docker/LICENSE new file mode 100644 index 00000000..f3ce3a9a --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2013-2018, go-dockerclient authors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/ory/dockertest/v3/docker/README.markdown b/vendor/github.com/ory/dockertest/v3/docker/README.markdown new file mode 100644 index 00000000..70c8256b --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/README.markdown @@ -0,0 +1,126 @@ +# go-dockerclient + +[![Travis Build Status](https://travis-ci.org/fsouza/go-dockerclient.svg?branch=master)](https://travis-ci.org/fsouza/go-dockerclient) +[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/4m374pti06ubg2l7?svg=true)](https://ci.appveyor.com/project/fsouza/go-dockerclient) +[![GoDoc](https://img.shields.io/badge/api-Godoc-blue.svg?style=flat-square)](https://godoc.org/github.com/fsouza/go-dockerclient) + +This package presents a client for the Docker remote API. It also provides +support for the extensions in the +[Swarm API](https://docs.docker.com/swarm/swarm-api/). + +This package also provides support for docker's network API, which is a simple +passthrough to the libnetwork remote API. Note that docker's network API is only +available in docker 1.8 and above, and only enabled in docker if +DOCKER_EXPERIMENTAL is defined during the docker build process. + +For more details, check the +[remote API documentation](http://docs.docker.com/engine/reference/api/docker_remote_api/). + +## Example + +```go +package main + +import ( + "fmt" + + "github.com/fsouza/go-dockerclient" +) + +func main() { + endpoint := "unix:///var/run/docker.sock" + client, err := docker.NewClient(endpoint) + if err != nil { + panic(err) + } + imgs, err := client.ListImages(docker.ListImagesOptions{All: false}) + if err != nil { + panic(err) + } + for _, img := range imgs { + fmt.Println("ID: ", img.ID) + fmt.Println("RepoTags: ", img.RepoTags) + fmt.Println("Created: ", img.Created) + fmt.Println("Size: ", img.Size) + fmt.Println("VirtualSize: ", img.VirtualSize) + fmt.Println("ParentId: ", img.ParentID) + } +} +``` + +## Using with TLS + +In order to instantiate the client for a TLS-enabled daemon, you should use +NewTLSClient, passing the endpoint and path for key and certificates as +parameters. + +```go +package main + +import ( + "fmt" + + "github.com/fsouza/go-dockerclient" +) + +func main() { + endpoint := "tcp://[ip]:[port]" + path := os.Getenv("DOCKER_CERT_PATH") + ca := fmt.Sprintf("%s/ca.pem", path) + cert := fmt.Sprintf("%s/cert.pem", path) + key := fmt.Sprintf("%s/key.pem", path) + client, _ := docker.NewTLSClient(endpoint, cert, key, ca) + // use client +} +``` + +If using [docker-machine](https://docs.docker.com/machine/), or another +application that exports environment variables `DOCKER_HOST`, +`DOCKER_TLS_VERIFY`, `DOCKER_CERT_PATH`, you can use NewClientFromEnv. + +```go +package main + +import ( + "fmt" + + "github.com/fsouza/go-dockerclient" +) + +func main() { + client, _ := docker.NewClientFromEnv() + // use client +} +``` + +See the documentation for more details. + +## Developing + +All development commands can be seen in the [Makefile](Makefile). + +Committed code must pass: + +- [golint](https://github.com/golang/lint) (with some exceptions, see the + Makefile). +- [go vet](https://golang.org/cmd/vet/) +- [gofmt](https://golang.org/cmd/gofmt) +- [go test](https://golang.org/cmd/go/#hdr-Test_packages) + +Running `make test` will check all of these. If your editor does not +automatically call `gofmt -s`, `make fmt` will format all go files in this +repository. + +## Using with Docker 1.9 and Go 1.4 + +There's a tag for using go-dockerclient with Docker 1.9 (which requires +compiling go-dockerclient with Go 1.4), the tag name is `docker-1.9/go-1.4`. + +The instructions below can be used to get a version of go-dockerclient that +compiles with Go 1.4: + +``` +% git clone -b docker-1.9/go-1.4 https://github.com/fsouza/go-dockerclient.git $GOPATH/src/github.com/fsouza/go-dockerclient +% git clone -b v1.9.1 https://github.com/docker/docker.git $GOPATH/src/github.com/docker/docker +% go get github.com/fsouza/go-dockerclient +``` diff --git a/vendor/github.com/ory/dockertest/v3/docker/auth.go b/vendor/github.com/ory/dockertest/v3/docker/auth.go new file mode 100644 index 00000000..149d1a23 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/auth.go @@ -0,0 +1,373 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2015 go-dockerclient 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 docker + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "errors" + "io" + "io/ioutil" + "os" + "os/exec" + "path" + "strings" +) + +// ErrCannotParseDockercfg is the error returned by NewAuthConfigurations when the dockercfg cannot be parsed. +var ErrCannotParseDockercfg = errors.New("Failed to read authentication from dockercfg") + +// AuthConfiguration represents authentication options to use in the PushImage +// method. It represents the authentication in the Docker index server. +type AuthConfiguration struct { + Username string `json:"username,omitempty"` + Password string `json:"password,omitempty"` + Email string `json:"email,omitempty"` + ServerAddress string `json:"serveraddress,omitempty"` + + // IdentityToken can be supplied with the identitytoken response of the AuthCheck call + // see https://pkg.go.dev/github.com/docker/docker/api/types?tab=doc#AuthConfig + // It can be used in place of password not in conjunction with it + IdentityToken string `json:"identitytoken,omitempty"` + + // RegistryToken can be supplied with the registrytoken + RegistryToken string `json:"registrytoken,omitempty"` +} + +func (c AuthConfiguration) isEmpty() bool { + return c == AuthConfiguration{} +} + +func (c AuthConfiguration) headerKey() string { + return "X-Registry-Auth" +} + +// AuthConfigurations represents authentication options to use for the +// PushImage method accommodating the new X-Registry-Config header +type AuthConfigurations struct { + Configs map[string]AuthConfiguration `json:"configs"` +} + +func (c AuthConfigurations) isEmpty() bool { + return len(c.Configs) == 0 +} + +func (AuthConfigurations) headerKey() string { + return "X-Registry-Config" +} + +// merge updates the configuration. If a key is defined in both maps, the one +// in c.Configs takes precedence. +func (c *AuthConfigurations) merge(other AuthConfigurations) { + for k, v := range other.Configs { + if c.Configs == nil { + c.Configs = make(map[string]AuthConfiguration) + } + if _, ok := c.Configs[k]; !ok { + c.Configs[k] = v + } + } +} + +// AuthConfigurations119 is used to serialize a set of AuthConfigurations +// for Docker API >= 1.19. +type AuthConfigurations119 map[string]AuthConfiguration + +func (c AuthConfigurations119) isEmpty() bool { + return len(c) == 0 +} + +func (c AuthConfigurations119) headerKey() string { + return "X-Registry-Config" +} + +// dockerConfig represents a registry authentation configuration from the +// .dockercfg file. +type dockerConfig struct { + Auth string `json:"auth"` + Email string `json:"email"` + IdentityToken string `json:"identitytoken"` + RegistryToken string `json:"registrytoken"` +} + +// NewAuthConfigurationsFromFile returns AuthConfigurations from a path containing JSON +// in the same format as the .dockercfg file. +func NewAuthConfigurationsFromFile(path string) (*AuthConfigurations, error) { + r, err := os.Open(path) + if err != nil { + return nil, err + } + return NewAuthConfigurations(r) +} + +func cfgPaths(dockerConfigEnv string, homeEnv string) []string { + var paths []string + if dockerConfigEnv != "" { + paths = append(paths, path.Join(dockerConfigEnv, "plaintext-passwords.json")) + paths = append(paths, path.Join(dockerConfigEnv, "config.json")) + } + if homeEnv != "" { + paths = append(paths, path.Join(homeEnv, ".docker", "plaintext-passwords.json")) + paths = append(paths, path.Join(homeEnv, ".docker", "config.json")) + paths = append(paths, path.Join(homeEnv, ".dockercfg")) + } + return paths +} + +// NewAuthConfigurationsFromDockerCfg returns AuthConfigurations from system +// config files. The following files are checked in the order listed: +// +// If the environment variable DOCKER_CONFIG is set to a non-empty string: +// +// - $DOCKER_CONFIG/plaintext-passwords.json +// - $DOCKER_CONFIG/config.json +// +// Otherwise, it looks for files in the $HOME directory and the legacy +// location: +// +// - $HOME/.docker/plaintext-passwords.json +// - $HOME/.docker/config.json +// - $HOME/.dockercfg +func NewAuthConfigurationsFromDockerCfg() (*AuthConfigurations, error) { + var err error + var auths *AuthConfigurations + var result *AuthConfigurations + + pathsToTry := cfgPaths(os.Getenv("DOCKER_CONFIG"), os.Getenv("HOME")) + if len(pathsToTry) < 1 { + return nil, errors.New("no docker configuration found") + } + + for _, path := range pathsToTry { + auths, err = NewAuthConfigurationsFromFile(path) + if err != nil { + continue + } + + if result == nil { + result = auths + } else { + result.merge(*auths) + } + } + + if result != nil { + return result, nil + + } + return nil, err +} + +// NewAuthConfigurations returns AuthConfigurations from a JSON encoded string in the +// same format as the .dockercfg file. +func NewAuthConfigurations(r io.Reader) (*AuthConfigurations, error) { + var auth *AuthConfigurations + confs, err := parseDockerConfig(r) + if err != nil { + return nil, err + } + auth, err = authConfigs(confs) + if err != nil { + return nil, err + } + return auth, nil +} + +func parseDockerConfig(r io.Reader) (map[string]dockerConfig, error) { + buf := new(bytes.Buffer) + buf.ReadFrom(r) + byteData := buf.Bytes() + + confsWrapper := struct { + Auths map[string]dockerConfig `json:"auths"` + }{} + if err := json.Unmarshal(byteData, &confsWrapper); err == nil { + if len(confsWrapper.Auths) > 0 { + return confsWrapper.Auths, nil + } + } + + var confs map[string]dockerConfig + if err := json.Unmarshal(byteData, &confs); err != nil { + return nil, err + } + return confs, nil +} + +// authConfigs converts a dockerConfigs map to a AuthConfigurations object. +func authConfigs(confs map[string]dockerConfig) (*AuthConfigurations, error) { + c := &AuthConfigurations{ + Configs: make(map[string]AuthConfiguration), + } + for reg, conf := range confs { + switch { + case conf.IdentityToken != "": + c.Configs[reg] = AuthConfiguration{ + IdentityToken: conf.IdentityToken, + } + case conf.RegistryToken != "": + c.Configs[reg] = AuthConfiguration{ + RegistryToken: conf.RegistryToken, + } + case conf.Auth != "": + // support both padded and unpadded encoding + data, err := base64.StdEncoding.DecodeString(conf.Auth) + if err != nil { + data, err = base64.StdEncoding.WithPadding(base64.NoPadding).DecodeString(conf.Auth) + } + if err != nil { + return nil, err + } + userpass := strings.SplitN(string(data), ":", 2) + if len(userpass) != 2 { + return nil, ErrCannotParseDockercfg + } + c.Configs[reg] = AuthConfiguration{ + Email: conf.Email, + Username: userpass[0], + Password: userpass[1], + ServerAddress: reg, + } + } + } + return c, nil +} + +// AuthStatus returns the authentication status for Docker API versions >= 1.23. +type AuthStatus struct { + Status string `json:"Status,omitempty" yaml:"Status,omitempty" toml:"Status,omitempty"` + IdentityToken string `json:"IdentityToken,omitempty" yaml:"IdentityToken,omitempty" toml:"IdentityToken,omitempty"` +} + +// AuthCheck validates the given credentials. It returns nil if successful. +// +// For Docker API versions >= 1.23, the AuthStatus struct will be populated, otherwise it will be empty.` +// +// See https://goo.gl/6nsZkH for more details. +func (c *Client) AuthCheck(conf *AuthConfiguration) (AuthStatus, error) { + var authStatus AuthStatus + if conf == nil { + return authStatus, errors.New("conf is nil") + } + resp, err := c.do("POST", "/auth", doOptions{data: conf}) + if err != nil { + return authStatus, err + } + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if err != nil { + return authStatus, err + } + if len(data) == 0 { + return authStatus, nil + } + if err := json.Unmarshal(data, &authStatus); err != nil { + return authStatus, err + } + return authStatus, nil +} + +// helperCredentials represents credentials commit from an helper +type helperCredentials struct { + Username string `json:"Username,omitempty"` + Secret string `json:"Secret,omitempty"` +} + +// NewAuthConfigurationsFromCredsHelpers returns AuthConfigurations from +// installed credentials helpers +func NewAuthConfigurationsFromCredsHelpers(registry string) (*AuthConfiguration, error) { + // Load docker configuration file in order to find a possible helper provider + pathsToTry := cfgPaths(os.Getenv("DOCKER_CONFIG"), os.Getenv("HOME")) + if len(pathsToTry) < 1 { + return nil, errors.New("no docker configuration found") + } + + provider, err := getHelperProviderFromDockerCfg(pathsToTry, registry) + if err != nil { + return nil, err + } + + c, err := getCredentialsFromHelper(provider, registry) + if err != nil { + return nil, err + } + + creds := new(AuthConfiguration) + creds.Username = c.Username + creds.Password = c.Secret + return creds, nil +} + +func getHelperProviderFromDockerCfg(pathsToTry []string, registry string) (string, error) { + for _, path := range pathsToTry { + content, err := ioutil.ReadFile(path) + if err != nil { + // if we can't read the file keep going + continue + } + + provider, err := parseCredsDockerConfig(content, registry) + if err != nil { + continue + } + if provider != "" { + return provider, nil + } + } + return "", errors.New("no docker credentials provider found") +} + +func parseCredsDockerConfig(config []byte, registry string) (string, error) { + creds := struct { + CredsStore string `json:"credsStore,omitempty"` + CredHelpers map[string]string `json:"credHelpers,omitempty"` + }{} + err := json.Unmarshal(config, &creds) + if err != nil { + return "", err + } + + provider, ok := creds.CredHelpers[registry] + if ok { + return provider, nil + } + return creds.CredsStore, nil +} + +// Run and parse the found credential helper +func getCredentialsFromHelper(provider string, registry string) (*helperCredentials, error) { + helpercreds, err := runDockerCredentialsHelper(provider, registry) + if err != nil { + return nil, err + } + + c := new(helperCredentials) + err = json.Unmarshal(helpercreds, c) + if err != nil { + return nil, err + } + + return c, nil +} + +func runDockerCredentialsHelper(provider string, registry string) ([]byte, error) { + cmd := exec.Command("docker-credential-"+provider, "get") + + var stdout bytes.Buffer + + cmd.Stdin = bytes.NewBuffer([]byte(registry)) + cmd.Stdout = &stdout + + err := cmd.Run() + if err != nil { + return nil, err + } + + return stdout.Bytes(), nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/change.go b/vendor/github.com/ory/dockertest/v3/docker/change.go new file mode 100644 index 00000000..eb806dd5 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/change.go @@ -0,0 +1,46 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2014 go-dockerclient 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 docker + +import "fmt" + +// ChangeType is a type for constants indicating the type of change +// in a container +type ChangeType int + +const ( + // ChangeModify is the ChangeType for container modifications + ChangeModify ChangeType = iota + + // ChangeAdd is the ChangeType for additions to a container + ChangeAdd + + // ChangeDelete is the ChangeType for deletions from a container + ChangeDelete +) + +// Change represents a change in a container. +// +// See https://goo.gl/Wo0JJp for more details. +type Change struct { + Path string + Kind ChangeType +} + +func (change *Change) String() string { + var kind string + switch change.Kind { + case ChangeModify: + kind = "C" + case ChangeAdd: + kind = "A" + case ChangeDelete: + kind = "D" + } + return fmt.Sprintf("%s %s", kind, change.Path) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/client.go b/vendor/github.com/ory/dockertest/v3/docker/client.go new file mode 100644 index 00000000..f84b1850 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/client.go @@ -0,0 +1,1171 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2013 go-dockerclient 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 docker provides a client for the Docker remote API. +// +// See https://goo.gl/o2v3rk for more details on the remote API. +package docker + +import ( + "bufio" + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httputil" + "net/url" + "os" + "path/filepath" + "reflect" + "runtime" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/ory/dockertest/v3/docker/opts" + "github.com/ory/dockertest/v3/docker/pkg/homedir" + "github.com/ory/dockertest/v3/docker/pkg/jsonmessage" + "github.com/ory/dockertest/v3/docker/pkg/stdcopy" +) + +const ( + userAgent = "go-dockerclient" + + unixProtocol = "unix" + namedPipeProtocol = "npipe" +) + +var ( + // ErrInvalidEndpoint is returned when the endpoint is not a valid HTTP URL. + ErrInvalidEndpoint = errors.New("invalid endpoint") + + // ErrConnectionRefused is returned when the client cannot connect to the given endpoint. + ErrConnectionRefused = errors.New("cannot connect to Docker endpoint") + + // ErrInactivityTimeout is returned when a streamable call has been inactive for some time. + ErrInactivityTimeout = errors.New("inactivity time exceeded timeout") + + apiVersion112, _ = NewAPIVersion("1.12") + apiVersion118, _ = NewAPIVersion("1.18") + apiVersion119, _ = NewAPIVersion("1.19") + apiVersion121, _ = NewAPIVersion("1.21") + apiVersion124, _ = NewAPIVersion("1.24") + apiVersion125, _ = NewAPIVersion("1.25") + apiVersion135, _ = NewAPIVersion("1.35") +) + +// APIVersion is an internal representation of a version of the Remote API. +type APIVersion []int + +// NewAPIVersion returns an instance of APIVersion for the given string. +// +// The given string must be in the form .., where , +// and are integer numbers. +func NewAPIVersion(input string) (APIVersion, error) { + if !strings.Contains(input, ".") { + return nil, fmt.Errorf("Unable to parse version %q", input) + } + raw := strings.Split(input, "-") + arr := strings.Split(raw[0], ".") + ret := make(APIVersion, len(arr)) + var err error + for i, val := range arr { + ret[i], err = strconv.Atoi(val) + if err != nil { + return nil, fmt.Errorf("Unable to parse version %q: %q is not an integer", input, val) + } + } + return ret, nil +} + +func (version APIVersion) String() string { + var str string + for i, val := range version { + str += strconv.Itoa(val) + if i < len(version)-1 { + str += "." + } + } + return str +} + +// LessThan is a function for comparing APIVersion structs +func (version APIVersion) LessThan(other APIVersion) bool { + return version.compare(other) < 0 +} + +// LessThanOrEqualTo is a function for comparing APIVersion structs +func (version APIVersion) LessThanOrEqualTo(other APIVersion) bool { + return version.compare(other) <= 0 +} + +// GreaterThan is a function for comparing APIVersion structs +func (version APIVersion) GreaterThan(other APIVersion) bool { + return version.compare(other) > 0 +} + +// GreaterThanOrEqualTo is a function for comparing APIVersion structs +func (version APIVersion) GreaterThanOrEqualTo(other APIVersion) bool { + return version.compare(other) >= 0 +} + +func (version APIVersion) compare(other APIVersion) int { + for i, v := range version { + if i <= len(other)-1 { + otherVersion := other[i] + + if v < otherVersion { + return -1 + } else if v > otherVersion { + return 1 + } + } + } + if len(version) > len(other) { + return 1 + } + if len(version) < len(other) { + return -1 + } + return 0 +} + +// Client is the basic type of this package. It provides methods for +// interaction with the API. +type Client struct { + SkipServerVersionCheck bool + HTTPClient *http.Client + TLSConfig *tls.Config + Dialer Dialer + + endpoint string + endpointURL *url.URL + eventMonitor *eventMonitoringState + + apiVersionMutex sync.RWMutex + requestedAPIVersion APIVersion + serverAPIVersion APIVersion + expectedAPIVersion APIVersion +} + +// Dialer is an interface that allows network connections to be dialed +// (net.Dialer fulfills this interface) and named pipes (a shim using +// winio.DialPipe) +type Dialer interface { + Dial(network, address string) (net.Conn, error) +} + +// NewClient returns a Client instance ready for communication with the given +// server endpoint. It will use the latest remote API version available in the +// server. +func NewClient(endpoint string) (*Client, error) { + client, err := NewVersionedClient(endpoint, "") + if err != nil { + return nil, err + } + client.SkipServerVersionCheck = true + return client, nil +} + +// NewTLSClient returns a Client instance ready for TLS communications with the givens +// server endpoint, key and certificates . It will use the latest remote API version +// available in the server. +func NewTLSClient(endpoint string, cert, key, ca string) (*Client, error) { + client, err := NewVersionedTLSClient(endpoint, cert, key, ca, "") + if err != nil { + return nil, err + } + client.SkipServerVersionCheck = true + return client, nil +} + +// NewTLSClientFromBytes returns a Client instance ready for TLS communications with the givens +// server endpoint, key and certificates (passed inline to the function as opposed to being +// read from a local file). It will use the latest remote API version available in the server. +func NewTLSClientFromBytes(endpoint string, certPEMBlock, keyPEMBlock, caPEMCert []byte) (*Client, error) { + client, err := NewVersionedTLSClientFromBytes(endpoint, certPEMBlock, keyPEMBlock, caPEMCert, "") + if err != nil { + return nil, err + } + client.SkipServerVersionCheck = true + return client, nil +} + +// NewVersionedClient returns a Client instance ready for communication with +// the given server endpoint, using a specific remote API version. +func NewVersionedClient(endpoint string, apiVersionString string) (*Client, error) { + u, err := parseEndpoint(endpoint, false) + if err != nil { + return nil, err + } + var requestedAPIVersion APIVersion + if strings.Contains(apiVersionString, ".") { + requestedAPIVersion, err = NewAPIVersion(apiVersionString) + if err != nil { + return nil, err + } + } + c := &Client{ + HTTPClient: defaultClient(), + Dialer: &net.Dialer{}, + endpoint: endpoint, + endpointURL: u, + eventMonitor: new(eventMonitoringState), + requestedAPIVersion: requestedAPIVersion, + } + c.initializeNativeClient(defaultTransport) + return c, nil +} + +// WithTransport replaces underlying HTTP client of Docker Client by accepting +// a function that returns pointer to a transport object. +func (c *Client) WithTransport(trFunc func() *http.Transport) { + c.initializeNativeClient(trFunc) +} + +// NewVersionnedTLSClient is like NewVersionedClient, but with ann extra n. +// +// Deprecated: Use NewVersionedTLSClient instead. +func NewVersionnedTLSClient(endpoint string, cert, key, ca, apiVersionString string) (*Client, error) { + return NewVersionedTLSClient(endpoint, cert, key, ca, apiVersionString) +} + +// NewVersionedTLSClient returns a Client instance ready for TLS communications with the givens +// server endpoint, key and certificates, using a specific remote API version. +func NewVersionedTLSClient(endpoint string, cert, key, ca, apiVersionString string) (*Client, error) { + var certPEMBlock []byte + var keyPEMBlock []byte + var caPEMCert []byte + if _, err := os.Stat(cert); !os.IsNotExist(err) { + certPEMBlock, err = os.ReadFile(cert) + if err != nil { + return nil, err + } + } + if _, err := os.Stat(key); !os.IsNotExist(err) { + keyPEMBlock, err = os.ReadFile(key) + if err != nil { + return nil, err + } + } + if _, err := os.Stat(ca); !os.IsNotExist(err) { + caPEMCert, err = os.ReadFile(ca) + if err != nil { + return nil, err + } + } + return NewVersionedTLSClientFromBytes(endpoint, certPEMBlock, keyPEMBlock, caPEMCert, apiVersionString) +} + +// NewClientFromEnv returns a Client instance ready for communication created from +// Docker's default logic for the environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, DOCKER_CERT_PATH, +// and DOCKER_API_VERSION. +// +// See https://github.com/docker/docker/blob/1f963af697e8df3a78217f6fdbf67b8123a7db94/docker/docker.go#L68. +// See https://github.com/docker/compose/blob/81707ef1ad94403789166d2fe042c8a718a4c748/compose/cli/docker_client.py#L7. +// See https://github.com/moby/moby/blob/28d7dba41d0c0d9c7f0dafcc79d3c59f2b3f5dc3/client/options.go#L51 +func NewClientFromEnv() (*Client, error) { + apiVersionString := os.Getenv("DOCKER_API_VERSION") + client, err := NewVersionedClientFromEnv(apiVersionString) + if err != nil { + return nil, err + } + client.SkipServerVersionCheck = apiVersionString == "" + return client, nil +} + +// NewVersionedClientFromEnv returns a Client instance ready for TLS communications created from +// Docker's default logic for the environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, and DOCKER_CERT_PATH, +// and using a specific remote API version. +// +// See https://github.com/docker/docker/blob/1f963af697e8df3a78217f6fdbf67b8123a7db94/docker/docker.go#L68. +// See https://github.com/docker/compose/blob/81707ef1ad94403789166d2fe042c8a718a4c748/compose/cli/docker_client.py#L7. +func NewVersionedClientFromEnv(apiVersionString string) (*Client, error) { + dockerEnv, err := getDockerEnv() + if err != nil { + return nil, err + } + dockerHost := dockerEnv.dockerHost + if dockerEnv.dockerTLSVerify { + parts := strings.SplitN(dockerEnv.dockerHost, "://", 2) + if len(parts) != 2 { + return nil, fmt.Errorf("could not split %s into two parts by ://", dockerHost) + } + cert := filepath.Join(dockerEnv.dockerCertPath, "cert.pem") + key := filepath.Join(dockerEnv.dockerCertPath, "key.pem") + ca := filepath.Join(dockerEnv.dockerCertPath, "ca.pem") + return NewVersionedTLSClient(dockerEnv.dockerHost, cert, key, ca, apiVersionString) + } + return NewVersionedClient(dockerEnv.dockerHost, apiVersionString) +} + +// NewVersionedTLSClientFromBytes returns a Client instance ready for TLS communications with the givens +// server endpoint, key and certificates (passed inline to the function as opposed to being +// read from a local file), using a specific remote API version. +func NewVersionedTLSClientFromBytes(endpoint string, certPEMBlock, keyPEMBlock, caPEMCert []byte, apiVersionString string) (*Client, error) { + u, err := parseEndpoint(endpoint, true) + if err != nil { + return nil, err + } + var requestedAPIVersion APIVersion + if strings.Contains(apiVersionString, ".") { + requestedAPIVersion, err = NewAPIVersion(apiVersionString) + if err != nil { + return nil, err + } + } + tlsConfig := &tls.Config{} + if certPEMBlock != nil && keyPEMBlock != nil { + tlsCert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) + if err != nil { + return nil, err + } + tlsConfig.Certificates = []tls.Certificate{tlsCert} + } + if caPEMCert == nil { + tlsConfig.InsecureSkipVerify = true + } else { + caPool := x509.NewCertPool() + if !caPool.AppendCertsFromPEM(caPEMCert) { + return nil, errors.New("Could not add RootCA pem") + } + tlsConfig.RootCAs = caPool + } + tr := defaultTransport() + tr.TLSClientConfig = tlsConfig + if err != nil { + return nil, err + } + c := &Client{ + HTTPClient: &http.Client{Transport: tr}, + TLSConfig: tlsConfig, + Dialer: &net.Dialer{}, + endpoint: endpoint, + endpointURL: u, + eventMonitor: new(eventMonitoringState), + requestedAPIVersion: requestedAPIVersion, + } + c.initializeNativeClient(defaultTransport) + return c, nil +} + +// SetTimeout takes a timeout and applies it to the HTTPClient. It should not +// be called concurrently with any other Client methods. +func (c *Client) SetTimeout(t time.Duration) { + if c.HTTPClient != nil { + c.HTTPClient.Timeout = t + } +} + +func (c *Client) checkAPIVersion() error { + c.apiVersionMutex.Lock() + defer c.apiVersionMutex.Unlock() + + if c.serverAPIVersion == nil { + serverAPIVersionString, err := c.getServerAPIVersionString() + if err != nil { + return err + } + c.serverAPIVersion, err = NewAPIVersion(serverAPIVersionString) + if err != nil { + return err + } + } + + if c.requestedAPIVersion == nil { + c.expectedAPIVersion = c.serverAPIVersion + } else { + c.expectedAPIVersion = c.requestedAPIVersion + } + + return nil +} + +// Endpoint returns the current endpoint. It's useful for getting the endpoint +// when using functions that get this data from the environment (like +// NewClientFromEnv. +func (c *Client) Endpoint() string { + return c.endpoint +} + +// Ping pings the docker server +// +// See https://goo.gl/wYfgY1 for more details. +func (c *Client) Ping() error { + return c.PingWithContext(context.Background()) +} + +// PingWithContext pings the docker server +// The context object can be used to cancel the ping request. +// +// See https://goo.gl/wYfgY1 for more details. +func (c *Client) PingWithContext(ctx context.Context) error { + path := "/_ping" + resp, err := c.do("GET", path, doOptions{context: ctx}) + if err != nil { + return err + } + if resp.StatusCode != http.StatusOK { + return newError(resp) + } + resp.Body.Close() + return nil +} + +func (c *Client) getServerAPIVersionString() (version string, err error) { + resp, err := c.do("GET", "/version", doOptions{}) + if err != nil { + return "", err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("Received unexpected status %d while trying to retrieve the server version", resp.StatusCode) + } + var versionResponse map[string]interface{} + if err := json.NewDecoder(resp.Body).Decode(&versionResponse); err != nil { + return "", err + } + if version, ok := (versionResponse["ApiVersion"]).(string); ok { + return version, nil + } + return "", nil +} + +type doOptions struct { + data interface{} + forceJSON bool + headers map[string]string + context context.Context +} + +func (c *Client) do(method, path string, doOptions doOptions) (*http.Response, error) { + var params io.Reader + if doOptions.data != nil || doOptions.forceJSON { + buf, err := json.Marshal(doOptions.data) + if err != nil { + return nil, err + } + params = bytes.NewBuffer(buf) + } + if path != "/version" && !c.SkipServerVersionCheck && c.expectedAPIVersion == nil { + err := c.checkAPIVersion() + if err != nil { + return nil, err + } + } + protocol := c.endpointURL.Scheme + var u string + switch protocol { + case unixProtocol, namedPipeProtocol: + u = c.getFakeNativeURL(path) + default: + u = c.getURL(path) + } + + req, err := http.NewRequest(method, u, params) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", userAgent) + if doOptions.data != nil { + req.Header.Set("Content-Type", "application/json") + } else if method == "POST" { + req.Header.Set("Content-Type", "plain/text") + } + + for k, v := range doOptions.headers { + req.Header.Set(k, v) + } + + ctx := doOptions.context + if ctx == nil { + ctx = context.Background() + } + + resp, err := c.HTTPClient.Do(req.WithContext(ctx)) + if err != nil { + if strings.Contains(err.Error(), "connection refused") { + return nil, ErrConnectionRefused + } + + return nil, chooseError(ctx, err) + } + if resp.StatusCode < 200 || resp.StatusCode >= 400 { + return nil, newError(resp) + } + return resp, nil +} + +type streamOptions struct { + setRawTerminal bool + rawJSONStream bool + useJSONDecoder bool + headers map[string]string + in io.Reader + stdout io.Writer + stderr io.Writer + reqSent chan struct{} + // timeout is the initial connection timeout + timeout time.Duration + // Timeout with no data is received, it's reset every time new data + // arrives + inactivityTimeout time.Duration + context context.Context +} + +// if error in context, return that instead of generic http error +func chooseError(ctx context.Context, err error) error { + select { + case <-ctx.Done(): + return ctx.Err() + default: + return err + } +} + +func (c *Client) stream(method, path string, streamOptions streamOptions) error { + if (method == "POST" || method == "PUT") && streamOptions.in == nil { + streamOptions.in = bytes.NewReader(nil) + } + if path != "/version" && !c.SkipServerVersionCheck && c.expectedAPIVersion == nil { + err := c.checkAPIVersion() + if err != nil { + return err + } + } + return c.streamURL(method, c.getURL(path), streamOptions) +} + +func (c *Client) streamURL(method, url string, streamOptions streamOptions) error { + if (method == http.MethodPost || method == http.MethodPut) && streamOptions.in == nil { + streamOptions.in = bytes.NewReader(nil) + } + if !c.SkipServerVersionCheck && c.expectedAPIVersion == nil { + err := c.checkAPIVersion() + if err != nil { + return err + } + } + + // make a sub-context so that our active cancellation does not affect parent + ctx := streamOptions.context + if ctx == nil { + ctx = context.Background() + } + subCtx, cancelRequest := context.WithCancel(ctx) + defer cancelRequest() + + req, err := http.NewRequestWithContext(ctx, method, url, streamOptions.in) + if err != nil { + return err + } + req.Header.Set("User-Agent", userAgent) + if method == "POST" { + req.Header.Set("Content-Type", "plain/text") + } + for key, val := range streamOptions.headers { + req.Header.Set(key, val) + } + var resp *http.Response + protocol := c.endpointURL.Scheme + address := c.endpointURL.Path + if streamOptions.stdout == nil { + streamOptions.stdout = io.Discard + } + if streamOptions.stderr == nil { + streamOptions.stderr = io.Discard + } + + if protocol == unixProtocol || protocol == namedPipeProtocol { + var dial net.Conn + dial, err = c.Dialer.Dial(protocol, address) + if err != nil { + return err + } + go func() { + <-subCtx.Done() + dial.Close() + }() + breader := bufio.NewReader(dial) + err = req.Write(dial) + if err != nil { + return chooseError(subCtx, err) + } + + // ReadResponse may hang if server does not replay + if streamOptions.timeout > 0 { + dial.SetDeadline(time.Now().Add(streamOptions.timeout)) + } + + if streamOptions.reqSent != nil { + close(streamOptions.reqSent) + } + if resp, err = http.ReadResponse(breader, req); err != nil { + // Cancel timeout for future I/O operations + if streamOptions.timeout > 0 { + dial.SetDeadline(time.Time{}) + } + if strings.Contains(err.Error(), "connection refused") { + return ErrConnectionRefused + } + + return chooseError(subCtx, err) + } + } else { + if resp, err = c.HTTPClient.Do(req.WithContext(subCtx)); err != nil { + if strings.Contains(err.Error(), "connection refused") { + return ErrConnectionRefused + } + return chooseError(subCtx, err) + } + if streamOptions.reqSent != nil { + close(streamOptions.reqSent) + } + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 400 { + return newError(resp) + } + var canceled uint32 + if streamOptions.inactivityTimeout > 0 { + var ch chan<- struct{} + resp.Body, ch = handleInactivityTimeout(resp.Body, streamOptions.inactivityTimeout, cancelRequest, &canceled) + defer close(ch) + } + err = handleStreamResponse(resp, &streamOptions) + if err != nil { + if atomic.LoadUint32(&canceled) != 0 { + return ErrInactivityTimeout + } + return chooseError(subCtx, err) + } + return nil +} + +func handleStreamResponse(resp *http.Response, streamOptions *streamOptions) error { + var err error + if !streamOptions.useJSONDecoder && resp.Header.Get("Content-Type") != "application/json" { + if streamOptions.setRawTerminal { + _, err = io.Copy(streamOptions.stdout, resp.Body) + } else { + _, err = stdcopy.StdCopy(streamOptions.stdout, streamOptions.stderr, resp.Body) + } + return err + } + // if we want to get raw json stream, just copy it back to output + // without decoding it + if streamOptions.rawJSONStream { + _, err = io.Copy(streamOptions.stdout, resp.Body) + return err + } + if st, ok := streamOptions.stdout.(stream); ok { + err = jsonmessage.DisplayJSONMessagesToStream(resp.Body, st, nil) + } else { + err = jsonmessage.DisplayJSONMessagesStream(resp.Body, streamOptions.stdout, 0, false, nil) + } + return err +} + +type stream interface { + io.Writer + FD() uintptr + IsTerminal() bool +} + +type proxyReader struct { + io.ReadCloser + calls uint64 +} + +func (p *proxyReader) callCount() uint64 { + return atomic.LoadUint64(&p.calls) +} + +func (p *proxyReader) Read(data []byte) (int, error) { + atomic.AddUint64(&p.calls, 1) + return p.ReadCloser.Read(data) +} + +func handleInactivityTimeout(reader io.ReadCloser, timeout time.Duration, cancelRequest func(), canceled *uint32) (io.ReadCloser, chan<- struct{}) { + done := make(chan struct{}) + proxyReader := &proxyReader{ReadCloser: reader} + go func() { + var lastCallCount uint64 + for { + select { + case <-time.After(timeout): + case <-done: + return + } + curCallCount := proxyReader.callCount() + if curCallCount == lastCallCount { + atomic.AddUint32(canceled, 1) + cancelRequest() + return + } + lastCallCount = curCallCount + } + }() + return proxyReader, done +} + +type hijackOptions struct { + success chan struct{} + setRawTerminal bool + in io.Reader + stdout io.Writer + stderr io.Writer + data interface{} +} + +// CloseWaiter is an interface with methods for closing the underlying resource +// and then waiting for it to finish processing. +type CloseWaiter interface { + io.Closer + Wait() error +} + +type waiterFunc func() error + +func (w waiterFunc) Wait() error { return w() } + +type closerFunc func() error + +func (c closerFunc) Close() error { return c() } + +func (c *Client) hijack(method, path string, hijackOptions hijackOptions) (CloseWaiter, error) { + if path != "/version" && !c.SkipServerVersionCheck && c.expectedAPIVersion == nil { + err := c.checkAPIVersion() + if err != nil { + return nil, err + } + } + var params io.Reader + if hijackOptions.data != nil { + buf, err := json.Marshal(hijackOptions.data) + if err != nil { + return nil, err + } + params = bytes.NewBuffer(buf) + } + req, err := http.NewRequest(method, c.getURL(path), params) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Connection", "Upgrade") + req.Header.Set("Upgrade", "tcp") + protocol := c.endpointURL.Scheme + address := c.endpointURL.Path + if protocol != unixProtocol && protocol != namedPipeProtocol { + protocol = "tcp" + address = c.endpointURL.Host + } + var dial net.Conn + if c.TLSConfig != nil && protocol != unixProtocol && protocol != namedPipeProtocol { + netDialer, ok := c.Dialer.(*net.Dialer) + if !ok { + return nil, ErrTLSNotSupported + } + dial, err = tlsDialWithDialer(netDialer, protocol, address, c.TLSConfig) + if err != nil { + return nil, err + } + } else { + dial, err = c.Dialer.Dial(protocol, address) + if err != nil { + return nil, err + } + } + + errs := make(chan error, 1) + quit := make(chan struct{}) + go func() { + //lint:ignore SA1019 the alternative doesn't quite work, so keep using the deprecated thing. + clientconn := httputil.NewClientConn(dial, nil) + defer clientconn.Close() + clientconn.Do(req) + if hijackOptions.success != nil { + hijackOptions.success <- struct{}{} + <-hijackOptions.success + } + rwc, br := clientconn.Hijack() + defer rwc.Close() + + errChanOut := make(chan error, 1) + errChanIn := make(chan error, 2) + if hijackOptions.stdout == nil && hijackOptions.stderr == nil { + close(errChanOut) + } else { + // Only copy if hijackOptions.stdout and/or hijackOptions.stderr is actually set. + // Otherwise, if the only stream you care about is stdin, your attach session + // will "hang" until the container terminates, even though you're not reading + // stdout/stderr + if hijackOptions.stdout == nil { + hijackOptions.stdout = io.Discard + } + if hijackOptions.stderr == nil { + hijackOptions.stderr = io.Discard + } + + go func() { + defer func() { + if hijackOptions.in != nil { + if closer, ok := hijackOptions.in.(io.Closer); ok { + closer.Close() + } + errChanIn <- nil + } + }() + + var err error + if hijackOptions.setRawTerminal { + _, err = io.Copy(hijackOptions.stdout, br) + } else { + _, err = stdcopy.StdCopy(hijackOptions.stdout, hijackOptions.stderr, br) + } + errChanOut <- err + }() + } + + go func() { + var err error + if hijackOptions.in != nil { + _, err = io.Copy(rwc, hijackOptions.in) + } + errChanIn <- err + rwc.(interface { + CloseWrite() error + }).CloseWrite() + }() + + var errIn error + select { + case errIn = <-errChanIn: + case <-quit: + } + + var errOut error + select { + case errOut = <-errChanOut: + case <-quit: + } + + if errIn != nil { + errs <- errIn + } else { + errs <- errOut + } + }() + + return struct { + closerFunc + waiterFunc + }{ + closerFunc(func() error { close(quit); return nil }), + waiterFunc(func() error { return <-errs }), + }, nil +} + +func (c *Client) getURL(path string) string { + urlStr := strings.TrimRight(c.endpointURL.String(), "/") + if c.endpointURL.Scheme == unixProtocol || c.endpointURL.Scheme == namedPipeProtocol { + urlStr = "" + } + if c.requestedAPIVersion != nil { + return fmt.Sprintf("%s/v%s%s", urlStr, c.requestedAPIVersion, path) + } + return fmt.Sprintf("%s%s", urlStr, path) +} + +func (c *Client) getPath(basepath string, opts interface{}) (string, error) { + queryStr, requiredAPIVersion := queryStringVersion(opts) + return c.pathVersionCheck(basepath, queryStr, requiredAPIVersion) +} + +func (c *Client) pathVersionCheck(basepath, queryStr string, requiredAPIVersion APIVersion) (string, error) { + urlStr := strings.TrimRight(c.endpointURL.String(), "/") + if c.endpointURL.Scheme == unixProtocol || c.endpointURL.Scheme == namedPipeProtocol { + urlStr = "" + } + if c.requestedAPIVersion != nil { + if c.requestedAPIVersion.GreaterThanOrEqualTo(requiredAPIVersion) { + return fmt.Sprintf("%s/v%s%s?%s", urlStr, c.requestedAPIVersion, basepath, queryStr), nil + } + return "", fmt.Errorf("API %s requires version %s, requested version %s is insufficient", + basepath, requiredAPIVersion, c.requestedAPIVersion) + } + if requiredAPIVersion != nil { + return fmt.Sprintf("%s/v%s%s?%s", urlStr, requiredAPIVersion, basepath, queryStr), nil + } + return fmt.Sprintf("%s%s?%s", urlStr, basepath, queryStr), nil +} + +// getFakeNativeURL returns the URL needed to make an HTTP request over a UNIX +// domain socket to the given path. +func (c *Client) getFakeNativeURL(path string) string { + u := *c.endpointURL // Copy. + + // Override URL so that net/http will not complain. + u.Scheme = "http" + u.Host = "unix.sock" // Doesn't matter what this is - it's not used. + u.Path = "" + urlStr := strings.TrimRight(u.String(), "/") + if c.requestedAPIVersion != nil { + return fmt.Sprintf("%s/v%s%s", urlStr, c.requestedAPIVersion, path) + } + return fmt.Sprintf("%s%s", urlStr, path) +} + +func queryStringVersion(opts interface{}) (string, APIVersion) { + if opts == nil { + return "", nil + } + value := reflect.ValueOf(opts) + if value.Kind() == reflect.Ptr { + value = value.Elem() + } + if value.Kind() != reflect.Struct { + return "", nil + } + var apiVersion APIVersion + items := url.Values(map[string][]string{}) + for i := 0; i < value.NumField(); i++ { + field := value.Type().Field(i) + if field.PkgPath != "" { + continue + } + key := field.Tag.Get("qs") + if key == "" { + key = strings.ToLower(field.Name) + } else if key == "-" { + continue + } + if addQueryStringValue(items, key, value.Field(i)) { + verstr := field.Tag.Get("ver") + if verstr != "" { + ver, _ := NewAPIVersion(verstr) + if apiVersion == nil { + apiVersion = ver + } else if ver.GreaterThan(apiVersion) { + apiVersion = ver + } + } + } + } + return items.Encode(), apiVersion +} + +func queryString(opts interface{}) string { + s, _ := queryStringVersion(opts) + return s +} + +func addQueryStringValue(items url.Values, key string, v reflect.Value) bool { + switch v.Kind() { + case reflect.Bool: + if v.Bool() { + items.Add(key, "1") + return true + } + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if v.Int() > 0 { + items.Add(key, strconv.FormatInt(v.Int(), 10)) + return true + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + if v.Uint() > 0 { + items.Add(key, strconv.FormatUint(v.Uint(), 10)) + return true + } + case reflect.Float32, reflect.Float64: + if v.Float() > 0 { + items.Add(key, strconv.FormatFloat(v.Float(), 'f', -1, 64)) + return true + } + case reflect.String: + if v.String() != "" { + items.Add(key, v.String()) + return true + } + case reflect.Ptr: + if !v.IsNil() { + if b, err := json.Marshal(v.Interface()); err == nil { + items.Add(key, string(b)) + return true + } + } + case reflect.Map: + if len(v.MapKeys()) > 0 { + if b, err := json.Marshal(v.Interface()); err == nil { + items.Add(key, string(b)) + return true + } + } + case reflect.Array, reflect.Slice: + vLen := v.Len() + var valuesAdded int + if vLen > 0 { + for i := 0; i < vLen; i++ { + if addQueryStringValue(items, key, v.Index(i)) { + valuesAdded++ + } + } + } + return valuesAdded > 0 + } + return false +} + +// Error represents failures in the API. It represents a failure from the API. +type Error struct { + Status int + Message string +} + +func newError(resp *http.Response) *Error { + type ErrMsg struct { + Message string `json:"message"` + } + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if err != nil { + return &Error{Status: resp.StatusCode, Message: fmt.Sprintf("cannot read body, err: %v", err)} + } + var emsg ErrMsg + err = json.Unmarshal(data, &emsg) + if err != nil { + return &Error{Status: resp.StatusCode, Message: string(data)} + } + return &Error{Status: resp.StatusCode, Message: emsg.Message} +} + +func (e *Error) Error() string { + return fmt.Sprintf("API error (%d): %s", e.Status, e.Message) +} + +func parseEndpoint(endpoint string, tls bool) (*url.URL, error) { + if endpoint != "" && !strings.Contains(endpoint, "://") { + endpoint = "tcp://" + endpoint + } + u, err := url.Parse(endpoint) + if err != nil { + return nil, ErrInvalidEndpoint + } + if tls && u.Scheme != "unix" { + u.Scheme = "https" + } + switch u.Scheme { + case unixProtocol, namedPipeProtocol: + return u, nil + case "http", "https", "tcp": + _, port, err := net.SplitHostPort(u.Host) + if err != nil { + if e, ok := err.(*net.AddrError); ok { + if e.Err == "missing port in address" { + return u, nil + } + } + return nil, ErrInvalidEndpoint + } + number, err := strconv.ParseInt(port, 10, 64) + if err == nil && number > 0 && number < 65536 { + if u.Scheme == "tcp" { + if tls { + u.Scheme = "https" + } else { + u.Scheme = "http" + } + } + return u, nil + } + return nil, ErrInvalidEndpoint + default: + return nil, ErrInvalidEndpoint + } +} + +type dockerEnv struct { + dockerHost string + dockerTLSVerify bool + dockerCertPath string +} + +func getDockerEnv() (*dockerEnv, error) { + dockerHost := os.Getenv("DOCKER_HOST") + var err error + if dockerHost == "" { + dockerHost = opts.DefaultHost + } + dockerTLSVerify := os.Getenv("DOCKER_TLS_VERIFY") != "" + var dockerCertPath string + if dockerTLSVerify { + dockerCertPath = os.Getenv("DOCKER_CERT_PATH") + if dockerCertPath == "" { + home := homedir.Get() + if home == "" { + return nil, errors.New("environment variable HOME must be set if DOCKER_CERT_PATH is not set") + } + dockerCertPath = filepath.Join(home, ".docker") + dockerCertPath, err = filepath.Abs(dockerCertPath) + if err != nil { + return nil, err + } + } + } + return &dockerEnv{ + dockerHost: dockerHost, + dockerTLSVerify: dockerTLSVerify, + dockerCertPath: dockerCertPath, + }, nil +} + +// defaultTransport returns a new http.Transport with similar default values to +// http.DefaultTransport, but with idle connections and keepalives disabled. +func defaultTransport() *http.Transport { + transport := defaultPooledTransport() + transport.DisableKeepAlives = true + transport.MaxIdleConnsPerHost = -1 + return transport +} + +// defaultPooledTransport returns a new http.Transport with similar default +// values to http.DefaultTransport. Do not use this for transient transports as +// it can leak file descriptors over time. Only use this for transports that +// will be re-used for the same host(s). +func defaultPooledTransport() *http.Transport { + transport := &http.Transport{ + Proxy: http.ProxyFromEnvironment, + DialContext: (&net.Dialer{ + Timeout: 30 * time.Second, + KeepAlive: 30 * time.Second, + }).DialContext, + MaxIdleConns: 100, + IdleConnTimeout: 90 * time.Second, + TLSHandshakeTimeout: 10 * time.Second, + ExpectContinueTimeout: 1 * time.Second, + MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1, + } + return transport +} + +// defaultClient returns a new http.Client with similar default values to +// http.Client, but with a non-shared Transport, idle connections disabled, and +// keepalives disabled. +func defaultClient() *http.Client { + return &http.Client{ + Transport: defaultTransport(), + } +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/client_unix.go b/vendor/github.com/ory/dockertest/v3/docker/client_unix.go new file mode 100644 index 00000000..f902e525 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/client_unix.go @@ -0,0 +1,33 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2016 go-dockerclient authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !windows +// +build !windows + +package docker + +import ( + "context" + "net" + "net/http" +) + +// initializeNativeClient initializes the native Unix domain socket client on +// Unix-style operating systems +func (c *Client) initializeNativeClient(trFunc func() *http.Transport) { + if c.endpointURL.Scheme != unixProtocol { + return + } + sockPath := c.endpointURL.Path + + tr := trFunc() + + tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + return c.Dialer.Dial(unixProtocol, sockPath) + } + c.HTTPClient.Transport = tr +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/client_windows.go b/vendor/github.com/ory/dockertest/v3/docker/client_windows.go new file mode 100644 index 00000000..eadb495f --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/client_windows.go @@ -0,0 +1,49 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2016 go-dockerclient authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build windows +// +build windows + +package docker + +import ( + "context" + "net" + "net/http" + "time" + + "github.com/Microsoft/go-winio" +) + +const namedPipeConnectTimeout = 2 * time.Second + +type pipeDialer struct { + dialFunc func(network, addr string) (net.Conn, error) +} + +func (p pipeDialer) Dial(network, address string) (net.Conn, error) { + return p.dialFunc(network, address) +} + +// initializeNativeClient initializes the native Named Pipe client for Windows +func (c *Client) initializeNativeClient(trFunc func() *http.Transport) { + if c.endpointURL.Scheme != namedPipeProtocol { + return + } + namedPipePath := c.endpointURL.Path + dialFunc := func(network, addr string) (net.Conn, error) { + timeout := namedPipeConnectTimeout + return winio.DialPipe(namedPipePath, &timeout) + } + tr := trFunc() + tr.Dial = dialFunc + tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + return dialFunc(network, addr) + } + c.Dialer = &pipeDialer{dialFunc} + c.HTTPClient.Transport = tr +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/container.go b/vendor/github.com/ory/dockertest/v3/docker/container.go new file mode 100644 index 00000000..0d7d3fe7 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/container.go @@ -0,0 +1,1626 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2013 go-dockerclient 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 docker + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/docker/go-units" +) + +// ErrContainerAlreadyExists is the error returned by CreateContainer when the +// container already exists. +var ErrContainerAlreadyExists = errors.New("container already exists") + +// ListContainersOptions specify parameters to the ListContainers function. +// +// See https://goo.gl/kaOHGw for more details. +type ListContainersOptions struct { + All bool + Size bool + Limit int + Since string + Before string + Filters map[string][]string + Context context.Context +} + +// APIPort is a type that represents a port mapping returned by the Docker API +type APIPort struct { + PrivatePort int64 `json:"PrivatePort,omitempty" yaml:"PrivatePort,omitempty" toml:"PrivatePort,omitempty"` + PublicPort int64 `json:"PublicPort,omitempty" yaml:"PublicPort,omitempty" toml:"PublicPort,omitempty"` + Type string `json:"Type,omitempty" yaml:"Type,omitempty" toml:"Type,omitempty"` + IP string `json:"IP,omitempty" yaml:"IP,omitempty" toml:"IP,omitempty"` +} + +// APIMount represents a mount point for a container. +type APIMount struct { + Name string `json:"Name,omitempty" yaml:"Name,omitempty" toml:"Name,omitempty"` + Source string `json:"Source,omitempty" yaml:"Source,omitempty" toml:"Source,omitempty"` + Destination string `json:"Destination,omitempty" yaml:"Destination,omitempty" toml:"Destination,omitempty"` + Driver string `json:"Driver,omitempty" yaml:"Driver,omitempty" toml:"Driver,omitempty"` + Mode string `json:"Mode,omitempty" yaml:"Mode,omitempty" toml:"Mode,omitempty"` + RW bool `json:"RW,omitempty" yaml:"RW,omitempty" toml:"RW,omitempty"` + Propagation string `json:"Propagation,omitempty" yaml:"Propagation,omitempty" toml:"Propagation,omitempty"` +} + +// APIContainers represents each container in the list returned by +// ListContainers. +type APIContainers struct { + ID string `json:"Id" yaml:"Id" toml:"Id"` + Image string `json:"Image,omitempty" yaml:"Image,omitempty" toml:"Image,omitempty"` + Command string `json:"Command,omitempty" yaml:"Command,omitempty" toml:"Command,omitempty"` + Created int64 `json:"Created,omitempty" yaml:"Created,omitempty" toml:"Created,omitempty"` + State string `json:"State,omitempty" yaml:"State,omitempty" toml:"State,omitempty"` + Status string `json:"Status,omitempty" yaml:"Status,omitempty" toml:"Status,omitempty"` + Ports []APIPort `json:"Ports,omitempty" yaml:"Ports,omitempty" toml:"Ports,omitempty"` + SizeRw int64 `json:"SizeRw,omitempty" yaml:"SizeRw,omitempty" toml:"SizeRw,omitempty"` + SizeRootFs int64 `json:"SizeRootFs,omitempty" yaml:"SizeRootFs,omitempty" toml:"SizeRootFs,omitempty"` + Names []string `json:"Names,omitempty" yaml:"Names,omitempty" toml:"Names,omitempty"` + Labels map[string]string `json:"Labels,omitempty" yaml:"Labels,omitempty" toml:"Labels,omitempty"` + Networks NetworkList `json:"NetworkSettings,omitempty" yaml:"NetworkSettings,omitempty" toml:"NetworkSettings,omitempty"` + Mounts []APIMount `json:"Mounts,omitempty" yaml:"Mounts,omitempty" toml:"Mounts,omitempty"` +} + +// NetworkList encapsulates a map of networks, as returned by the Docker API in +// ListContainers. +type NetworkList struct { + Networks map[string]ContainerNetwork `json:"Networks" yaml:"Networks,omitempty" toml:"Networks,omitempty"` +} + +// ListContainers returns a slice of containers matching the given criteria. +// +// See https://goo.gl/kaOHGw for more details. +func (c *Client) ListContainers(opts ListContainersOptions) ([]APIContainers, error) { + path := "/containers/json?" + queryString(opts) + resp, err := c.do("GET", path, doOptions{context: opts.Context}) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var containers []APIContainers + if err := json.NewDecoder(resp.Body).Decode(&containers); err != nil { + return nil, err + } + return containers, nil +} + +// Port represents the port number and the protocol, in the form +// /. For example: 80/tcp. +type Port string + +// Port returns the number of the port. +func (p Port) Port() string { + return strings.Split(string(p), "/")[0] +} + +// Proto returns the name of the protocol. +func (p Port) Proto() string { + parts := strings.Split(string(p), "/") + if len(parts) == 1 { + return "tcp" + } + return parts[1] +} + +// HealthCheck represents one check of health. +type HealthCheck struct { + Start time.Time `json:"Start,omitempty" yaml:"Start,omitempty" toml:"Start,omitempty"` + End time.Time `json:"End,omitempty" yaml:"End,omitempty" toml:"End,omitempty"` + ExitCode int `json:"ExitCode,omitempty" yaml:"ExitCode,omitempty" toml:"ExitCode,omitempty"` + Output string `json:"Output,omitempty" yaml:"Output,omitempty" toml:"Output,omitempty"` +} + +// Health represents the health of a container. +type Health struct { + Status string `json:"Status,omitempty" yaml:"Status,omitempty" toml:"Status,omitempty"` + FailingStreak int `json:"FailingStreak,omitempty" yaml:"FailingStreak,omitempty" toml:"FailingStreak,omitempty"` + Log []HealthCheck `json:"Log,omitempty" yaml:"Log,omitempty" toml:"Log,omitempty"` +} + +// State represents the state of a container. +type State struct { + Status string `json:"Status,omitempty" yaml:"Status,omitempty" toml:"Status,omitempty"` + Running bool `json:"Running,omitempty" yaml:"Running,omitempty" toml:"Running,omitempty"` + Paused bool `json:"Paused,omitempty" yaml:"Paused,omitempty" toml:"Paused,omitempty"` + Restarting bool `json:"Restarting,omitempty" yaml:"Restarting,omitempty" toml:"Restarting,omitempty"` + OOMKilled bool `json:"OOMKilled,omitempty" yaml:"OOMKilled,omitempty" toml:"OOMKilled,omitempty"` + RemovalInProgress bool `json:"RemovalInProgress,omitempty" yaml:"RemovalInProgress,omitempty" toml:"RemovalInProgress,omitempty"` + Dead bool `json:"Dead,omitempty" yaml:"Dead,omitempty" toml:"Dead,omitempty"` + Pid int `json:"Pid,omitempty" yaml:"Pid,omitempty" toml:"Pid,omitempty"` + ExitCode int `json:"ExitCode,omitempty" yaml:"ExitCode,omitempty" toml:"ExitCode,omitempty"` + Error string `json:"Error,omitempty" yaml:"Error,omitempty" toml:"Error,omitempty"` + StartedAt time.Time `json:"StartedAt,omitempty" yaml:"StartedAt,omitempty" toml:"StartedAt,omitempty"` + FinishedAt time.Time `json:"FinishedAt,omitempty" yaml:"FinishedAt,omitempty" toml:"FinishedAt,omitempty"` + Health Health `json:"Health,omitempty" yaml:"Health,omitempty" toml:"Health,omitempty"` +} + +// String returns a human-readable description of the state +func (s *State) String() string { + if s.Running { + if s.Paused { + return fmt.Sprintf("Up %s (Paused)", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt))) + } + if s.Restarting { + return fmt.Sprintf("Restarting (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt))) + } + + return fmt.Sprintf("Up %s", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt))) + } + + if s.RemovalInProgress { + return "Removal In Progress" + } + + if s.Dead { + return "Dead" + } + + if s.StartedAt.IsZero() { + return "Created" + } + + if s.FinishedAt.IsZero() { + return "" + } + + return fmt.Sprintf("Exited (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt))) +} + +// StateString returns a single string to describe state +func (s *State) StateString() string { + if s.Running { + if s.Paused { + return "paused" + } + if s.Restarting { + return "restarting" + } + return "running" + } + + if s.Dead { + return "dead" + } + + if s.StartedAt.IsZero() { + return "created" + } + + return "exited" +} + +// PortBinding represents the host/container port mapping as returned in the +// `docker inspect` json +type PortBinding struct { + HostIP string `json:"HostIp,omitempty" yaml:"HostIp,omitempty" toml:"HostIp,omitempty"` + HostPort string `json:"HostPort,omitempty" yaml:"HostPort,omitempty" toml:"HostPort,omitempty"` +} + +// PortMapping represents a deprecated field in the `docker inspect` output, +// and its value as found in NetworkSettings should always be nil +type PortMapping map[string]string + +// ContainerNetwork represents the networking settings of a container per network. +type ContainerNetwork struct { + Aliases []string `json:"Aliases,omitempty" yaml:"Aliases,omitempty" toml:"Aliases,omitempty"` + MacAddress string `json:"MacAddress,omitempty" yaml:"MacAddress,omitempty" toml:"MacAddress,omitempty"` + GlobalIPv6PrefixLen int `json:"GlobalIPv6PrefixLen,omitempty" yaml:"GlobalIPv6PrefixLen,omitempty" toml:"GlobalIPv6PrefixLen,omitempty"` + GlobalIPv6Address string `json:"GlobalIPv6Address,omitempty" yaml:"GlobalIPv6Address,omitempty" toml:"GlobalIPv6Address,omitempty"` + IPv6Gateway string `json:"IPv6Gateway,omitempty" yaml:"IPv6Gateway,omitempty" toml:"IPv6Gateway,omitempty"` + IPPrefixLen int `json:"IPPrefixLen,omitempty" yaml:"IPPrefixLen,omitempty" toml:"IPPrefixLen,omitempty"` + IPAddress string `json:"IPAddress,omitempty" yaml:"IPAddress,omitempty" toml:"IPAddress,omitempty"` + Gateway string `json:"Gateway,omitempty" yaml:"Gateway,omitempty" toml:"Gateway,omitempty"` + EndpointID string `json:"EndpointID,omitempty" yaml:"EndpointID,omitempty" toml:"EndpointID,omitempty"` + NetworkID string `json:"NetworkID,omitempty" yaml:"NetworkID,omitempty" toml:"NetworkID,omitempty"` +} + +// NetworkSettings contains network-related information about a container +type NetworkSettings struct { + Networks map[string]ContainerNetwork `json:"Networks,omitempty" yaml:"Networks,omitempty" toml:"Networks,omitempty"` + IPAddress string `json:"IPAddress,omitempty" yaml:"IPAddress,omitempty" toml:"IPAddress,omitempty"` + IPPrefixLen int `json:"IPPrefixLen,omitempty" yaml:"IPPrefixLen,omitempty" toml:"IPPrefixLen,omitempty"` + MacAddress string `json:"MacAddress,omitempty" yaml:"MacAddress,omitempty" toml:"MacAddress,omitempty"` + Gateway string `json:"Gateway,omitempty" yaml:"Gateway,omitempty" toml:"Gateway,omitempty"` + Bridge string `json:"Bridge,omitempty" yaml:"Bridge,omitempty" toml:"Bridge,omitempty"` + PortMapping map[string]PortMapping `json:"PortMapping,omitempty" yaml:"PortMapping,omitempty" toml:"PortMapping,omitempty"` + Ports map[Port][]PortBinding `json:"Ports,omitempty" yaml:"Ports,omitempty" toml:"Ports,omitempty"` + NetworkID string `json:"NetworkID,omitempty" yaml:"NetworkID,omitempty" toml:"NetworkID,omitempty"` + EndpointID string `json:"EndpointID,omitempty" yaml:"EndpointID,omitempty" toml:"EndpointID,omitempty"` + SandboxKey string `json:"SandboxKey,omitempty" yaml:"SandboxKey,omitempty" toml:"SandboxKey,omitempty"` + GlobalIPv6Address string `json:"GlobalIPv6Address,omitempty" yaml:"GlobalIPv6Address,omitempty" toml:"GlobalIPv6Address,omitempty"` + GlobalIPv6PrefixLen int `json:"GlobalIPv6PrefixLen,omitempty" yaml:"GlobalIPv6PrefixLen,omitempty" toml:"GlobalIPv6PrefixLen,omitempty"` + IPv6Gateway string `json:"IPv6Gateway,omitempty" yaml:"IPv6Gateway,omitempty" toml:"IPv6Gateway,omitempty"` + LinkLocalIPv6Address string `json:"LinkLocalIPv6Address,omitempty" yaml:"LinkLocalIPv6Address,omitempty" toml:"LinkLocalIPv6Address,omitempty"` + LinkLocalIPv6PrefixLen int `json:"LinkLocalIPv6PrefixLen,omitempty" yaml:"LinkLocalIPv6PrefixLen,omitempty" toml:"LinkLocalIPv6PrefixLen,omitempty"` + SecondaryIPAddresses []string `json:"SecondaryIPAddresses,omitempty" yaml:"SecondaryIPAddresses,omitempty" toml:"SecondaryIPAddresses,omitempty"` + SecondaryIPv6Addresses []string `json:"SecondaryIPv6Addresses,omitempty" yaml:"SecondaryIPv6Addresses,omitempty" toml:"SecondaryIPv6Addresses,omitempty"` +} + +// PortMappingAPI translates the port mappings as contained in NetworkSettings +// into the format in which they would appear when returned by the API +func (settings *NetworkSettings) PortMappingAPI() []APIPort { + var mapping []APIPort + for port, bindings := range settings.Ports { + p, _ := parsePort(port.Port()) + if len(bindings) == 0 { + mapping = append(mapping, APIPort{ + PrivatePort: int64(p), + Type: port.Proto(), + }) + continue + } + for _, binding := range bindings { + p, _ := parsePort(port.Port()) + h, _ := parsePort(binding.HostPort) + mapping = append(mapping, APIPort{ + PrivatePort: int64(p), + PublicPort: int64(h), + Type: port.Proto(), + IP: binding.HostIP, + }) + } + } + return mapping +} + +func parsePort(rawPort string) (int, error) { + port, err := strconv.ParseUint(rawPort, 10, 16) + if err != nil { + return 0, err + } + return int(port), nil +} + +// Config is the list of configuration options used when creating a container. +// Config does not contain the options that are specific to starting a container on a +// given host. Those are contained in HostConfig +type Config struct { + Hostname string `json:"Hostname,omitempty" yaml:"Hostname,omitempty" toml:"Hostname,omitempty"` + Domainname string `json:"Domainname,omitempty" yaml:"Domainname,omitempty" toml:"Domainname,omitempty"` + User string `json:"User,omitempty" yaml:"User,omitempty" toml:"User,omitempty"` + Memory int64 `json:"Memory,omitempty" yaml:"Memory,omitempty" toml:"Memory,omitempty"` + MemorySwap int64 `json:"MemorySwap,omitempty" yaml:"MemorySwap,omitempty" toml:"MemorySwap,omitempty"` + MemoryReservation int64 `json:"MemoryReservation,omitempty" yaml:"MemoryReservation,omitempty" toml:"MemoryReservation,omitempty"` + KernelMemory int64 `json:"KernelMemory,omitempty" yaml:"KernelMemory,omitempty" toml:"KernelMemory,omitempty"` + CPUShares int64 `json:"CpuShares,omitempty" yaml:"CpuShares,omitempty" toml:"CpuShares,omitempty"` + CPUSet string `json:"Cpuset,omitempty" yaml:"Cpuset,omitempty" toml:"Cpuset,omitempty"` + PortSpecs []string `json:"PortSpecs,omitempty" yaml:"PortSpecs,omitempty" toml:"PortSpecs,omitempty"` + ExposedPorts map[Port]struct{} `json:"ExposedPorts,omitempty" yaml:"ExposedPorts,omitempty" toml:"ExposedPorts,omitempty"` + PublishService string `json:"PublishService,omitempty" yaml:"PublishService,omitempty" toml:"PublishService,omitempty"` + StopSignal string `json:"StopSignal,omitempty" yaml:"StopSignal,omitempty" toml:"StopSignal,omitempty"` + StopTimeout int `json:"StopTimeout,omitempty" yaml:"StopTimeout,omitempty" toml:"StopTimeout,omitempty"` + Env []string `json:"Env,omitempty" yaml:"Env,omitempty" toml:"Env,omitempty"` + Cmd []string `json:"Cmd" yaml:"Cmd" toml:"Cmd"` + Shell []string `json:"Shell,omitempty" yaml:"Shell,omitempty" toml:"Shell,omitempty"` + Healthcheck *HealthConfig `json:"Healthcheck,omitempty" yaml:"Healthcheck,omitempty" toml:"Healthcheck,omitempty"` + DNS []string `json:"Dns,omitempty" yaml:"Dns,omitempty" toml:"Dns,omitempty"` // For Docker API v1.9 and below only + Image string `json:"Image,omitempty" yaml:"Image,omitempty" toml:"Image,omitempty"` + Volumes map[string]struct{} `json:"Volumes,omitempty" yaml:"Volumes,omitempty" toml:"Volumes,omitempty"` + VolumeDriver string `json:"VolumeDriver,omitempty" yaml:"VolumeDriver,omitempty" toml:"VolumeDriver,omitempty"` + WorkingDir string `json:"WorkingDir,omitempty" yaml:"WorkingDir,omitempty" toml:"WorkingDir,omitempty"` + MacAddress string `json:"MacAddress,omitempty" yaml:"MacAddress,omitempty" toml:"MacAddress,omitempty"` + Entrypoint []string `json:"Entrypoint" yaml:"Entrypoint" toml:"Entrypoint"` + SecurityOpts []string `json:"SecurityOpts,omitempty" yaml:"SecurityOpts,omitempty" toml:"SecurityOpts,omitempty"` + OnBuild []string `json:"OnBuild,omitempty" yaml:"OnBuild,omitempty" toml:"OnBuild,omitempty"` + Mounts []Mount `json:"Mounts,omitempty" yaml:"Mounts,omitempty" toml:"Mounts,omitempty"` + Labels map[string]string `json:"Labels,omitempty" yaml:"Labels,omitempty" toml:"Labels,omitempty"` + AttachStdin bool `json:"AttachStdin,omitempty" yaml:"AttachStdin,omitempty" toml:"AttachStdin,omitempty"` + AttachStdout bool `json:"AttachStdout,omitempty" yaml:"AttachStdout,omitempty" toml:"AttachStdout,omitempty"` + AttachStderr bool `json:"AttachStderr,omitempty" yaml:"AttachStderr,omitempty" toml:"AttachStderr,omitempty"` + ArgsEscaped bool `json:"ArgsEscaped,omitempty" yaml:"ArgsEscaped,omitempty" toml:"ArgsEscaped,omitempty"` + Tty bool `json:"Tty,omitempty" yaml:"Tty,omitempty" toml:"Tty,omitempty"` + OpenStdin bool `json:"OpenStdin,omitempty" yaml:"OpenStdin,omitempty" toml:"OpenStdin,omitempty"` + StdinOnce bool `json:"StdinOnce,omitempty" yaml:"StdinOnce,omitempty" toml:"StdinOnce,omitempty"` + NetworkDisabled bool `json:"NetworkDisabled,omitempty" yaml:"NetworkDisabled,omitempty" toml:"NetworkDisabled,omitempty"` + + // This is no longer used and has been kept here for backward + // compatibility, please use HostConfig.VolumesFrom. + VolumesFrom string `json:"VolumesFrom,omitempty" yaml:"VolumesFrom,omitempty" toml:"VolumesFrom,omitempty"` +} + +// HostMount represents a mount point in the container in HostConfig. +// +// It has been added in the version 1.25 of the Docker API +type HostMount struct { + Target string `json:"Target,omitempty" yaml:"Target,omitempty" toml:"Target,omitempty"` + Source string `json:"Source,omitempty" yaml:"Source,omitempty" toml:"Source,omitempty"` + Type string `json:"Type,omitempty" yaml:"Type,omitempty" toml:"Type,omitempty"` + ReadOnly bool `json:"ReadOnly,omitempty" yaml:"ReadOnly,omitempty" toml:"ReadOnly,omitempty"` + BindOptions *BindOptions `json:"BindOptions,omitempty" yaml:"BindOptions,omitempty" toml:"BindOptions,omitempty"` + VolumeOptions *VolumeOptions `json:"VolumeOptions,omitempty" yaml:"VolumeOptions,omitempty" toml:"VolumeOptions,omitempty"` + TempfsOptions *TempfsOptions `json:"TempfsOptions,omitempty" yaml:"TempfsOptions,omitempty" toml:"TempfsOptions,omitempty"` +} + +// BindOptions contains optional configuration for the bind type +type BindOptions struct { + Propagation string `json:"Propagation,omitempty" yaml:"Propagation,omitempty" toml:"Propagation,omitempty"` +} + +// VolumeOptions contains optional configuration for the volume type +type VolumeOptions struct { + NoCopy bool `json:"NoCopy,omitempty" yaml:"NoCopy,omitempty" toml:"NoCopy,omitempty"` + Labels map[string]string `json:"Labels,omitempty" yaml:"Labels,omitempty" toml:"Labels,omitempty"` + DriverConfig VolumeDriverConfig `json:"DriverConfig,omitempty" yaml:"DriverConfig,omitempty" toml:"DriverConfig,omitempty"` +} + +// TempfsOptions contains optional configuration for the tempfs type +type TempfsOptions struct { + SizeBytes int64 `json:"SizeBytes,omitempty" yaml:"SizeBytes,omitempty" toml:"SizeBytes,omitempty"` + Mode int `json:"Mode,omitempty" yaml:"Mode,omitempty" toml:"Mode,omitempty"` +} + +// VolumeDriverConfig holds a map of volume driver specific options +type VolumeDriverConfig struct { + Name string `json:"Name,omitempty" yaml:"Name,omitempty" toml:"Name,omitempty"` + Options map[string]string `json:"Options,omitempty" yaml:"Options,omitempty" toml:"Options,omitempty"` +} + +// Mount represents a mount point in the container. +// +// It has been added in the version 1.20 of the Docker API, available since +// Docker 1.8. +type Mount struct { + Name string + Source string + Destination string + Driver string + Mode string + RW bool +} + +// LogConfig defines the log driver type and the configuration for it. +type LogConfig struct { + Type string `json:"Type,omitempty" yaml:"Type,omitempty" toml:"Type,omitempty"` + Config map[string]string `json:"Config,omitempty" yaml:"Config,omitempty" toml:"Config,omitempty"` +} + +// ULimit defines system-wide resource limitations This can help a lot in +// system administration, e.g. when a user starts too many processes and +// therefore makes the system unresponsive for other users. +type ULimit struct { + Name string `json:"Name,omitempty" yaml:"Name,omitempty" toml:"Name,omitempty"` + Soft int64 `json:"Soft,omitempty" yaml:"Soft,omitempty" toml:"Soft,omitempty"` + Hard int64 `json:"Hard,omitempty" yaml:"Hard,omitempty" toml:"Hard,omitempty"` +} + +// SwarmNode containers information about which Swarm node the container is on. +type SwarmNode struct { + ID string `json:"ID,omitempty" yaml:"ID,omitempty" toml:"ID,omitempty"` + IP string `json:"IP,omitempty" yaml:"IP,omitempty" toml:"IP,omitempty"` + Addr string `json:"Addr,omitempty" yaml:"Addr,omitempty" toml:"Addr,omitempty"` + Name string `json:"Name,omitempty" yaml:"Name,omitempty" toml:"Name,omitempty"` + CPUs int64 `json:"CPUs,omitempty" yaml:"CPUs,omitempty" toml:"CPUs,omitempty"` + Memory int64 `json:"Memory,omitempty" yaml:"Memory,omitempty" toml:"Memory,omitempty"` + Labels map[string]string `json:"Labels,omitempty" yaml:"Labels,omitempty" toml:"Labels,omitempty"` +} + +// GraphDriver contains information about the GraphDriver used by the +// container. +type GraphDriver struct { + Name string `json:"Name,omitempty" yaml:"Name,omitempty" toml:"Name,omitempty"` + Data map[string]string `json:"Data,omitempty" yaml:"Data,omitempty" toml:"Data,omitempty"` +} + +// HealthConfig holds configuration settings for the HEALTHCHECK feature +// +// It has been added in the version 1.24 of the Docker API, available since +// Docker 1.12. +type HealthConfig struct { + // Test is the test to perform to check that the container is healthy. + // An empty slice means to inherit the default. + // The options are: + // {} : inherit healthcheck + // {"NONE"} : disable healthcheck + // {"CMD", args...} : exec arguments directly + // {"CMD-SHELL", command} : run command with system's default shell + Test []string `json:"Test,omitempty" yaml:"Test,omitempty" toml:"Test,omitempty"` + + // Zero means to inherit. Durations are expressed as integer nanoseconds. + Interval time.Duration `json:"Interval,omitempty" yaml:"Interval,omitempty" toml:"Interval,omitempty"` // Interval is the time to wait between checks. + Timeout time.Duration `json:"Timeout,omitempty" yaml:"Timeout,omitempty" toml:"Timeout,omitempty"` // Timeout is the time to wait before considering the check to have hung. + StartPeriod time.Duration `json:"StartPeriod,omitempty" yaml:"StartPeriod,omitempty" toml:"StartPeriod,omitempty"` // The start period for the container to initialize before the retries starts to count down. + + // Retries is the number of consecutive failures needed to consider a container as unhealthy. + // Zero means inherit. + Retries int `json:"Retries,omitempty" yaml:"Retries,omitempty" toml:"Retries,omitempty"` +} + +// Container is the type encompasing everything about a container - its config, +// hostconfig, etc. +type Container struct { + ID string `json:"Id" yaml:"Id" toml:"Id"` + + Created time.Time `json:"Created,omitempty" yaml:"Created,omitempty" toml:"Created,omitempty"` + + Path string `json:"Path,omitempty" yaml:"Path,omitempty" toml:"Path,omitempty"` + Args []string `json:"Args,omitempty" yaml:"Args,omitempty" toml:"Args,omitempty"` + + Config *Config `json:"Config,omitempty" yaml:"Config,omitempty" toml:"Config,omitempty"` + State State `json:"State,omitempty" yaml:"State,omitempty" toml:"State,omitempty"` + Image string `json:"Image,omitempty" yaml:"Image,omitempty" toml:"Image,omitempty"` + + Node *SwarmNode `json:"Node,omitempty" yaml:"Node,omitempty" toml:"Node,omitempty"` + + NetworkSettings *NetworkSettings `json:"NetworkSettings,omitempty" yaml:"NetworkSettings,omitempty" toml:"NetworkSettings,omitempty"` + + SysInitPath string `json:"SysInitPath,omitempty" yaml:"SysInitPath,omitempty" toml:"SysInitPath,omitempty"` + ResolvConfPath string `json:"ResolvConfPath,omitempty" yaml:"ResolvConfPath,omitempty" toml:"ResolvConfPath,omitempty"` + HostnamePath string `json:"HostnamePath,omitempty" yaml:"HostnamePath,omitempty" toml:"HostnamePath,omitempty"` + HostsPath string `json:"HostsPath,omitempty" yaml:"HostsPath,omitempty" toml:"HostsPath,omitempty"` + LogPath string `json:"LogPath,omitempty" yaml:"LogPath,omitempty" toml:"LogPath,omitempty"` + Name string `json:"Name,omitempty" yaml:"Name,omitempty" toml:"Name,omitempty"` + Driver string `json:"Driver,omitempty" yaml:"Driver,omitempty" toml:"Driver,omitempty"` + Mounts []Mount `json:"Mounts,omitempty" yaml:"Mounts,omitempty" toml:"Mounts,omitempty"` + + Volumes map[string]string `json:"Volumes,omitempty" yaml:"Volumes,omitempty" toml:"Volumes,omitempty"` + VolumesRW map[string]bool `json:"VolumesRW,omitempty" yaml:"VolumesRW,omitempty" toml:"VolumesRW,omitempty"` + HostConfig *HostConfig `json:"HostConfig,omitempty" yaml:"HostConfig,omitempty" toml:"HostConfig,omitempty"` + ExecIDs []string `json:"ExecIDs,omitempty" yaml:"ExecIDs,omitempty" toml:"ExecIDs,omitempty"` + GraphDriver *GraphDriver `json:"GraphDriver,omitempty" yaml:"GraphDriver,omitempty" toml:"GraphDriver,omitempty"` + + RestartCount int `json:"RestartCount,omitempty" yaml:"RestartCount,omitempty" toml:"RestartCount,omitempty"` + + AppArmorProfile string `json:"AppArmorProfile,omitempty" yaml:"AppArmorProfile,omitempty" toml:"AppArmorProfile,omitempty"` +} + +// UpdateContainerOptions specify parameters to the UpdateContainer function. +// +// See https://goo.gl/Y6fXUy for more details. +type UpdateContainerOptions struct { + BlkioWeight int `json:"BlkioWeight"` + CPUShares int `json:"CpuShares"` + CPUPeriod int `json:"CpuPeriod"` + CPURealtimePeriod int64 `json:"CpuRealtimePeriod"` + CPURealtimeRuntime int64 `json:"CpuRealtimeRuntime"` + CPUQuota int `json:"CpuQuota"` + CpusetCpus string `json:"CpusetCpus"` + CpusetMems string `json:"CpusetMems"` + Memory int `json:"Memory"` + MemorySwap int `json:"MemorySwap"` + MemoryReservation int `json:"MemoryReservation"` + KernelMemory int `json:"KernelMemory"` + RestartPolicy RestartPolicy `json:"RestartPolicy,omitempty"` + Context context.Context +} + +// UpdateContainer updates the container at ID with the options +// +// See https://goo.gl/Y6fXUy for more details. +func (c *Client) UpdateContainer(id string, opts UpdateContainerOptions) error { + resp, err := c.do("POST", fmt.Sprintf("/containers/"+id+"/update"), doOptions{ + data: opts, + forceJSON: true, + context: opts.Context, + }) + if err != nil { + return err + } + defer resp.Body.Close() + return nil +} + +// RenameContainerOptions specify parameters to the RenameContainer function. +// +// See https://goo.gl/46inai for more details. +type RenameContainerOptions struct { + // ID of container to rename + ID string `qs:"-"` + + // New name + Name string `json:"name,omitempty" yaml:"name,omitempty"` + Context context.Context +} + +// RenameContainer updates and existing containers name +// +// See https://goo.gl/46inai for more details. +func (c *Client) RenameContainer(opts RenameContainerOptions) error { + resp, err := c.do("POST", fmt.Sprintf("/containers/"+opts.ID+"/rename?%s", queryString(opts)), doOptions{ + context: opts.Context, + }) + if err != nil { + return err + } + resp.Body.Close() + return nil +} + +// InspectContainer returns information about a container by its ID. +// +// See https://goo.gl/FaI5JT for more details. +func (c *Client) InspectContainer(id string) (*Container, error) { + return c.inspectContainer(id, doOptions{}) +} + +// InspectContainerWithContext returns information about a container by its ID. +// The context object can be used to cancel the inspect request. +// +// See https://goo.gl/FaI5JT for more details. +func (c *Client) InspectContainerWithContext(id string, ctx context.Context) (*Container, error) { + return c.inspectContainer(id, doOptions{context: ctx}) +} + +func (c *Client) inspectContainer(id string, opts doOptions) (*Container, error) { + path := "/containers/" + id + "/json" + resp, err := c.do("GET", path, opts) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return nil, &NoSuchContainer{ID: id} + } + return nil, err + } + defer resp.Body.Close() + var container Container + if err := json.NewDecoder(resp.Body).Decode(&container); err != nil { + return nil, err + } + return &container, nil +} + +// ContainerChanges returns changes in the filesystem of the given container. +// +// See https://goo.gl/15KKzh for more details. +func (c *Client) ContainerChanges(id string) ([]Change, error) { + path := "/containers/" + id + "/changes" + resp, err := c.do("GET", path, doOptions{}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return nil, &NoSuchContainer{ID: id} + } + return nil, err + } + defer resp.Body.Close() + var changes []Change + if err := json.NewDecoder(resp.Body).Decode(&changes); err != nil { + return nil, err + } + return changes, nil +} + +// CreateContainerOptions specify parameters to the CreateContainer function. +// +// See https://goo.gl/tyzwVM for more details. +type CreateContainerOptions struct { + Name string + Config *Config `qs:"-"` + HostConfig *HostConfig `qs:"-"` + NetworkingConfig *NetworkingConfig `qs:"-"` + Context context.Context +} + +// CreateContainer creates a new container, returning the container instance, +// or an error in case of failure. +// +// The returned container instance contains only the container ID. To get more +// details about the container after creating it, use InspectContainer. +// +// See https://goo.gl/tyzwVM for more details. +func (c *Client) CreateContainer(opts CreateContainerOptions) (*Container, error) { + path := "/containers/create?" + queryString(opts) + resp, err := c.do( + "POST", + path, + doOptions{ + data: struct { + *Config + HostConfig *HostConfig `json:"HostConfig,omitempty" yaml:"HostConfig,omitempty" toml:"HostConfig,omitempty"` + NetworkingConfig *NetworkingConfig `json:"NetworkingConfig,omitempty" yaml:"NetworkingConfig,omitempty" toml:"NetworkingConfig,omitempty"` + }{ + opts.Config, + opts.HostConfig, + opts.NetworkingConfig, + }, + context: opts.Context, + }, + ) + + if e, ok := err.(*Error); ok { + if e.Status == http.StatusNotFound { + return nil, ErrNoSuchImage + } + if e.Status == http.StatusConflict { + return nil, ErrContainerAlreadyExists + } + // Workaround for 17.09 bug returning 400 instead of 409. + // See https://github.com/moby/moby/issues/35021 + if e.Status == http.StatusBadRequest && strings.Contains(e.Message, "Conflict.") { + return nil, ErrContainerAlreadyExists + } + } + + if err != nil { + return nil, err + } + defer resp.Body.Close() + var container Container + if err := json.NewDecoder(resp.Body).Decode(&container); err != nil { + return nil, err + } + + container.Name = opts.Name + + return &container, nil +} + +// KeyValuePair is a type for generic key/value pairs as used in the Lxc +// configuration +type KeyValuePair struct { + Key string `json:"Key,omitempty" yaml:"Key,omitempty" toml:"Key,omitempty"` + Value string `json:"Value,omitempty" yaml:"Value,omitempty" toml:"Value,omitempty"` +} + +// RestartPolicy represents the policy for automatically restarting a container. +// +// Possible values are: +// +// - always: the docker daemon will always restart the container +// - on-failure: the docker daemon will restart the container on failures, at +// most MaximumRetryCount times +// - unless-stopped: the docker daemon will always restart the container except +// when user has manually stopped the container +// - no: the docker daemon will not restart the container automatically +type RestartPolicy struct { + Name string `json:"Name,omitempty" yaml:"Name,omitempty" toml:"Name,omitempty"` + MaximumRetryCount int `json:"MaximumRetryCount,omitempty" yaml:"MaximumRetryCount,omitempty" toml:"MaximumRetryCount,omitempty"` +} + +// AlwaysRestart returns a restart policy that tells the Docker daemon to +// always restart the container. +func AlwaysRestart() RestartPolicy { + return RestartPolicy{Name: "always"} +} + +// RestartOnFailure returns a restart policy that tells the Docker daemon to +// restart the container on failures, trying at most maxRetry times. +func RestartOnFailure(maxRetry int) RestartPolicy { + return RestartPolicy{Name: "on-failure", MaximumRetryCount: maxRetry} +} + +// RestartUnlessStopped returns a restart policy that tells the Docker daemon to +// always restart the container except when user has manually stopped the container. +func RestartUnlessStopped() RestartPolicy { + return RestartPolicy{Name: "unless-stopped"} +} + +// NeverRestart returns a restart policy that tells the Docker daemon to never +// restart the container on failures. +func NeverRestart() RestartPolicy { + return RestartPolicy{Name: "no"} +} + +// Device represents a device mapping between the Docker host and the +// container. +type Device struct { + PathOnHost string `json:"PathOnHost,omitempty" yaml:"PathOnHost,omitempty" toml:"PathOnHost,omitempty"` + PathInContainer string `json:"PathInContainer,omitempty" yaml:"PathInContainer,omitempty" toml:"PathInContainer,omitempty"` + CgroupPermissions string `json:"CgroupPermissions,omitempty" yaml:"CgroupPermissions,omitempty" toml:"CgroupPermissions,omitempty"` +} + +// BlockWeight represents a relative device weight for an individual device inside +// of a container +type BlockWeight struct { + Path string `json:"Path,omitempty"` + Weight string `json:"Weight,omitempty"` +} + +// BlockLimit represents a read/write limit in IOPS or Bandwidth for a device +// inside of a container +type BlockLimit struct { + Path string `json:"Path,omitempty"` + Rate int64 `json:"Rate,omitempty"` +} + +// HostConfig contains the container options related to starting a container on +// a given host +type HostConfig struct { + Binds []string `json:"Binds,omitempty" yaml:"Binds,omitempty" toml:"Binds,omitempty"` + CapAdd []string `json:"CapAdd,omitempty" yaml:"CapAdd,omitempty" toml:"CapAdd,omitempty"` + CapDrop []string `json:"CapDrop,omitempty" yaml:"CapDrop,omitempty" toml:"CapDrop,omitempty"` + GroupAdd []string `json:"GroupAdd,omitempty" yaml:"GroupAdd,omitempty" toml:"GroupAdd,omitempty"` + ContainerIDFile string `json:"ContainerIDFile,omitempty" yaml:"ContainerIDFile,omitempty" toml:"ContainerIDFile,omitempty"` + LxcConf []KeyValuePair `json:"LxcConf,omitempty" yaml:"LxcConf,omitempty" toml:"LxcConf,omitempty"` + PortBindings map[Port][]PortBinding `json:"PortBindings,omitempty" yaml:"PortBindings,omitempty" toml:"PortBindings,omitempty"` + Links []string `json:"Links,omitempty" yaml:"Links,omitempty" toml:"Links,omitempty"` + DNS []string `json:"Dns,omitempty" yaml:"Dns,omitempty" toml:"Dns,omitempty"` // For Docker API v1.10 and above only + DNSOptions []string `json:"DnsOptions,omitempty" yaml:"DnsOptions,omitempty" toml:"DnsOptions,omitempty"` + DNSSearch []string `json:"DnsSearch,omitempty" yaml:"DnsSearch,omitempty" toml:"DnsSearch,omitempty"` + ExtraHosts []string `json:"ExtraHosts,omitempty" yaml:"ExtraHosts,omitempty" toml:"ExtraHosts,omitempty"` + VolumesFrom []string `json:"VolumesFrom,omitempty" yaml:"VolumesFrom,omitempty" toml:"VolumesFrom,omitempty"` + UsernsMode string `json:"UsernsMode,omitempty" yaml:"UsernsMode,omitempty" toml:"UsernsMode,omitempty"` + NetworkMode string `json:"NetworkMode,omitempty" yaml:"NetworkMode,omitempty" toml:"NetworkMode,omitempty"` + IpcMode string `json:"IpcMode,omitempty" yaml:"IpcMode,omitempty" toml:"IpcMode,omitempty"` + PidMode string `json:"PidMode,omitempty" yaml:"PidMode,omitempty" toml:"PidMode,omitempty"` + UTSMode string `json:"UTSMode,omitempty" yaml:"UTSMode,omitempty" toml:"UTSMode,omitempty"` + RestartPolicy RestartPolicy `json:"RestartPolicy,omitempty" yaml:"RestartPolicy,omitempty" toml:"RestartPolicy,omitempty"` + Devices []Device `json:"Devices,omitempty" yaml:"Devices,omitempty" toml:"Devices,omitempty"` + DeviceCgroupRules []string `json:"DeviceCgroupRules,omitempty" yaml:"DeviceCgroupRules,omitempty" toml:"DeviceCgroupRules,omitempty"` + LogConfig LogConfig `json:"LogConfig,omitempty" yaml:"LogConfig,omitempty" toml:"LogConfig,omitempty"` + SecurityOpt []string `json:"SecurityOpt,omitempty" yaml:"SecurityOpt,omitempty" toml:"SecurityOpt,omitempty"` + Cgroup string `json:"Cgroup,omitempty" yaml:"Cgroup,omitempty" toml:"Cgroup,omitempty"` + CgroupParent string `json:"CgroupParent,omitempty" yaml:"CgroupParent,omitempty" toml:"CgroupParent,omitempty"` + Memory int64 `json:"Memory,omitempty" yaml:"Memory,omitempty" toml:"Memory,omitempty"` + MemoryReservation int64 `json:"MemoryReservation,omitempty" yaml:"MemoryReservation,omitempty" toml:"MemoryReservation,omitempty"` + KernelMemory int64 `json:"KernelMemory,omitempty" yaml:"KernelMemory,omitempty" toml:"KernelMemory,omitempty"` + MemorySwap int64 `json:"MemorySwap,omitempty" yaml:"MemorySwap,omitempty" toml:"MemorySwap,omitempty"` + MemorySwappiness int64 `json:"MemorySwappiness,omitempty" yaml:"MemorySwappiness,omitempty" toml:"MemorySwappiness,omitempty"` + CPUShares int64 `json:"CpuShares,omitempty" yaml:"CpuShares,omitempty" toml:"CpuShares,omitempty"` + CPUSet string `json:"Cpuset,omitempty" yaml:"Cpuset,omitempty" toml:"Cpuset,omitempty"` + CPUSetCPUs string `json:"CpusetCpus,omitempty" yaml:"CpusetCpus,omitempty" toml:"CpusetCpus,omitempty"` + CPUSetMEMs string `json:"CpusetMems,omitempty" yaml:"CpusetMems,omitempty" toml:"CpusetMems,omitempty"` + CPUQuota int64 `json:"CpuQuota,omitempty" yaml:"CpuQuota,omitempty" toml:"CpuQuota,omitempty"` + CPUPeriod int64 `json:"CpuPeriod,omitempty" yaml:"CpuPeriod,omitempty" toml:"CpuPeriod,omitempty"` + CPURealtimePeriod int64 `json:"CpuRealtimePeriod,omitempty" yaml:"CpuRealtimePeriod,omitempty" toml:"CpuRealtimePeriod,omitempty"` + CPURealtimeRuntime int64 `json:"CpuRealtimeRuntime,omitempty" yaml:"CpuRealtimeRuntime,omitempty" toml:"CpuRealtimeRuntime,omitempty"` + BlkioWeight int64 `json:"BlkioWeight,omitempty" yaml:"BlkioWeight,omitempty" toml:"BlkioWeight,omitempty"` + BlkioWeightDevice []BlockWeight `json:"BlkioWeightDevice,omitempty" yaml:"BlkioWeightDevice,omitempty" toml:"BlkioWeightDevice,omitempty"` + BlkioDeviceReadBps []BlockLimit `json:"BlkioDeviceReadBps,omitempty" yaml:"BlkioDeviceReadBps,omitempty" toml:"BlkioDeviceReadBps,omitempty"` + BlkioDeviceReadIOps []BlockLimit `json:"BlkioDeviceReadIOps,omitempty" yaml:"BlkioDeviceReadIOps,omitempty" toml:"BlkioDeviceReadIOps,omitempty"` + BlkioDeviceWriteBps []BlockLimit `json:"BlkioDeviceWriteBps,omitempty" yaml:"BlkioDeviceWriteBps,omitempty" toml:"BlkioDeviceWriteBps,omitempty"` + BlkioDeviceWriteIOps []BlockLimit `json:"BlkioDeviceWriteIOps,omitempty" yaml:"BlkioDeviceWriteIOps,omitempty" toml:"BlkioDeviceWriteIOps,omitempty"` + Ulimits []ULimit `json:"Ulimits,omitempty" yaml:"Ulimits,omitempty" toml:"Ulimits,omitempty"` + VolumeDriver string `json:"VolumeDriver,omitempty" yaml:"VolumeDriver,omitempty" toml:"VolumeDriver,omitempty"` + OomScoreAdj int `json:"OomScoreAdj,omitempty" yaml:"OomScoreAdj,omitempty" toml:"OomScoreAdj,omitempty"` + PidsLimit int64 `json:"PidsLimit,omitempty" yaml:"PidsLimit,omitempty" toml:"PidsLimit,omitempty"` + ShmSize int64 `json:"ShmSize,omitempty" yaml:"ShmSize,omitempty" toml:"ShmSize,omitempty"` + Tmpfs map[string]string `json:"Tmpfs,omitempty" yaml:"Tmpfs,omitempty" toml:"Tmpfs,omitempty"` + Privileged bool `json:"Privileged,omitempty" yaml:"Privileged,omitempty" toml:"Privileged,omitempty"` + PublishAllPorts bool `json:"PublishAllPorts,omitempty" yaml:"PublishAllPorts,omitempty" toml:"PublishAllPorts,omitempty"` + ReadonlyRootfs bool `json:"ReadonlyRootfs,omitempty" yaml:"ReadonlyRootfs,omitempty" toml:"ReadonlyRootfs,omitempty"` + OOMKillDisable bool `json:"OomKillDisable,omitempty" yaml:"OomKillDisable,omitempty" toml:"OomKillDisable,omitempty"` + AutoRemove bool `json:"AutoRemove,omitempty" yaml:"AutoRemove,omitempty" toml:"AutoRemove,omitempty"` + StorageOpt map[string]string `json:"StorageOpt,omitempty" yaml:"StorageOpt,omitempty" toml:"StorageOpt,omitempty"` + Sysctls map[string]string `json:"Sysctls,omitempty" yaml:"Sysctls,omitempty" toml:"Sysctls,omitempty"` + CPUCount int64 `json:"CpuCount,omitempty" yaml:"CpuCount,omitempty"` + CPUPercent int64 `json:"CpuPercent,omitempty" yaml:"CpuPercent,omitempty"` + IOMaximumBandwidth int64 `json:"IOMaximumBandwidth,omitempty" yaml:"IOMaximumBandwidth,omitempty"` + IOMaximumIOps int64 `json:"IOMaximumIOps,omitempty" yaml:"IOMaximumIOps,omitempty"` + Mounts []HostMount `json:"Mounts,omitempty" yaml:"Mounts,omitempty" toml:"Mounts,omitempty"` + Init bool `json:",omitempty" yaml:",omitempty"` +} + +// NetworkingConfig represents the container's networking configuration for each of its interfaces +// Carries the networking configs specified in the `docker run` and `docker network connect` commands +type NetworkingConfig struct { + EndpointsConfig map[string]*EndpointConfig `json:"EndpointsConfig" yaml:"EndpointsConfig" toml:"EndpointsConfig"` // Endpoint configs for each connecting network +} + +// StartContainer starts a container, returning an error in case of failure. +// +// Passing the HostConfig to this method has been deprecated in Docker API 1.22 +// (Docker Engine 1.10.x) and totally removed in Docker API 1.24 (Docker Engine +// 1.12.x). The client will ignore the parameter when communicating with Docker +// API 1.24 or greater. +// +// See https://goo.gl/fbOSZy for more details. +func (c *Client) StartContainer(id string, hostConfig *HostConfig) error { + return c.startContainer(id, hostConfig, doOptions{}) +} + +// StartContainerWithContext starts a container, returning an error in case of +// failure. The context can be used to cancel the outstanding start container +// request. +// +// Passing the HostConfig to this method has been deprecated in Docker API 1.22 +// (Docker Engine 1.10.x) and totally removed in Docker API 1.24 (Docker Engine +// 1.12.x). The client will ignore the parameter when communicating with Docker +// API 1.24 or greater. +// +// See https://goo.gl/fbOSZy for more details. +func (c *Client) StartContainerWithContext(id string, hostConfig *HostConfig, ctx context.Context) error { + return c.startContainer(id, hostConfig, doOptions{context: ctx}) +} + +func (c *Client) startContainer(id string, hostConfig *HostConfig, opts doOptions) error { + path := "/containers/" + id + "/start" + + c.checkAPIVersion() + + if c.serverAPIVersion != nil && c.serverAPIVersion.LessThan(apiVersion124) { + opts.data = hostConfig + opts.forceJSON = true + } + resp, err := c.do("POST", path, opts) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return &NoSuchContainer{ID: id, Err: err} + } + return err + } + defer resp.Body.Close() + if resp.StatusCode == http.StatusNotModified { + return &ContainerAlreadyRunning{ID: id} + } + return nil +} + +// StopContainer stops a container, killing it after the given timeout (in +// seconds). +// +// See https://goo.gl/R9dZcV for more details. +func (c *Client) StopContainer(id string, timeout uint) error { + return c.stopContainer(id, timeout, doOptions{}) +} + +// StopContainerWithContext stops a container, killing it after the given +// timeout (in seconds). The context can be used to cancel the stop +// container request. +// +// See https://goo.gl/R9dZcV for more details. +func (c *Client) StopContainerWithContext(id string, timeout uint, ctx context.Context) error { + return c.stopContainer(id, timeout, doOptions{context: ctx}) +} + +func (c *Client) stopContainer(id string, timeout uint, opts doOptions) error { + path := fmt.Sprintf("/containers/%s/stop?t=%d", id, timeout) + resp, err := c.do("POST", path, opts) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return &NoSuchContainer{ID: id} + } + return err + } + defer resp.Body.Close() + if resp.StatusCode == http.StatusNotModified { + return &ContainerNotRunning{ID: id} + } + return nil +} + +// RestartContainer stops a container, killing it after the given timeout (in +// seconds), during the stop process. +// +// See https://goo.gl/MrAKQ5 for more details. +func (c *Client) RestartContainer(id string, timeout uint) error { + path := fmt.Sprintf("/containers/%s/restart?t=%d", id, timeout) + resp, err := c.do("POST", path, doOptions{}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return &NoSuchContainer{ID: id} + } + return err + } + resp.Body.Close() + return nil +} + +// PauseContainer pauses the given container. +// +// See https://goo.gl/D1Yaii for more details. +func (c *Client) PauseContainer(id string) error { + path := fmt.Sprintf("/containers/%s/pause", id) + resp, err := c.do("POST", path, doOptions{}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return &NoSuchContainer{ID: id} + } + return err + } + resp.Body.Close() + return nil +} + +// UnpauseContainer unpauses the given container. +// +// See https://goo.gl/sZ2faO for more details. +func (c *Client) UnpauseContainer(id string) error { + path := fmt.Sprintf("/containers/%s/unpause", id) + resp, err := c.do("POST", path, doOptions{}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return &NoSuchContainer{ID: id} + } + return err + } + resp.Body.Close() + return nil +} + +// TopResult represents the list of processes running in a container, as +// returned by /containers//top. +// +// See https://goo.gl/FLwpPl for more details. +type TopResult struct { + Titles []string + Processes [][]string +} + +// TopContainer returns processes running inside a container +// +// See https://goo.gl/FLwpPl for more details. +func (c *Client) TopContainer(id string, psArgs string) (TopResult, error) { + var args string + var result TopResult + if psArgs != "" { + args = fmt.Sprintf("?ps_args=%s", psArgs) + } + path := fmt.Sprintf("/containers/%s/top%s", id, args) + resp, err := c.do("GET", path, doOptions{}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return result, &NoSuchContainer{ID: id} + } + return result, err + } + defer resp.Body.Close() + err = json.NewDecoder(resp.Body).Decode(&result) + return result, err +} + +// Stats represents container statistics, returned by /containers//stats. +// +// See https://goo.gl/Dk3Xio for more details. +type Stats struct { + Read time.Time `json:"read,omitempty" yaml:"read,omitempty" toml:"read,omitempty"` + PreRead time.Time `json:"preread,omitempty" yaml:"preread,omitempty" toml:"preread,omitempty"` + NumProcs uint32 `json:"num_procs" yaml:"num_procs" toml:"num_procs"` + PidsStats struct { + Current uint64 `json:"current,omitempty" yaml:"current,omitempty"` + } `json:"pids_stats,omitempty" yaml:"pids_stats,omitempty" toml:"pids_stats,omitempty"` + Network NetworkStats `json:"network,omitempty" yaml:"network,omitempty" toml:"network,omitempty"` + Networks map[string]NetworkStats `json:"networks,omitempty" yaml:"networks,omitempty" toml:"networks,omitempty"` + MemoryStats struct { + Stats struct { + TotalPgmafault uint64 `json:"total_pgmafault,omitempty" yaml:"total_pgmafault,omitempty" toml:"total_pgmafault,omitempty"` + Cache uint64 `json:"cache,omitempty" yaml:"cache,omitempty" toml:"cache,omitempty"` + MappedFile uint64 `json:"mapped_file,omitempty" yaml:"mapped_file,omitempty" toml:"mapped_file,omitempty"` + TotalInactiveFile uint64 `json:"total_inactive_file,omitempty" yaml:"total_inactive_file,omitempty" toml:"total_inactive_file,omitempty"` + Pgpgout uint64 `json:"pgpgout,omitempty" yaml:"pgpgout,omitempty" toml:"pgpgout,omitempty"` + Rss uint64 `json:"rss,omitempty" yaml:"rss,omitempty" toml:"rss,omitempty"` + TotalMappedFile uint64 `json:"total_mapped_file,omitempty" yaml:"total_mapped_file,omitempty" toml:"total_mapped_file,omitempty"` + Writeback uint64 `json:"writeback,omitempty" yaml:"writeback,omitempty" toml:"writeback,omitempty"` + Unevictable uint64 `json:"unevictable,omitempty" yaml:"unevictable,omitempty" toml:"unevictable,omitempty"` + Pgpgin uint64 `json:"pgpgin,omitempty" yaml:"pgpgin,omitempty" toml:"pgpgin,omitempty"` + TotalUnevictable uint64 `json:"total_unevictable,omitempty" yaml:"total_unevictable,omitempty" toml:"total_unevictable,omitempty"` + Pgmajfault uint64 `json:"pgmajfault,omitempty" yaml:"pgmajfault,omitempty" toml:"pgmajfault,omitempty"` + TotalRss uint64 `json:"total_rss,omitempty" yaml:"total_rss,omitempty" toml:"total_rss,omitempty"` + TotalRssHuge uint64 `json:"total_rss_huge,omitempty" yaml:"total_rss_huge,omitempty" toml:"total_rss_huge,omitempty"` + TotalWriteback uint64 `json:"total_writeback,omitempty" yaml:"total_writeback,omitempty" toml:"total_writeback,omitempty"` + TotalInactiveAnon uint64 `json:"total_inactive_anon,omitempty" yaml:"total_inactive_anon,omitempty" toml:"total_inactive_anon,omitempty"` + RssHuge uint64 `json:"rss_huge,omitempty" yaml:"rss_huge,omitempty" toml:"rss_huge,omitempty"` + HierarchicalMemoryLimit uint64 `json:"hierarchical_memory_limit,omitempty" yaml:"hierarchical_memory_limit,omitempty" toml:"hierarchical_memory_limit,omitempty"` + TotalPgfault uint64 `json:"total_pgfault,omitempty" yaml:"total_pgfault,omitempty" toml:"total_pgfault,omitempty"` + TotalActiveFile uint64 `json:"total_active_file,omitempty" yaml:"total_active_file,omitempty" toml:"total_active_file,omitempty"` + ActiveAnon uint64 `json:"active_anon,omitempty" yaml:"active_anon,omitempty" toml:"active_anon,omitempty"` + TotalActiveAnon uint64 `json:"total_active_anon,omitempty" yaml:"total_active_anon,omitempty" toml:"total_active_anon,omitempty"` + TotalPgpgout uint64 `json:"total_pgpgout,omitempty" yaml:"total_pgpgout,omitempty" toml:"total_pgpgout,omitempty"` + TotalCache uint64 `json:"total_cache,omitempty" yaml:"total_cache,omitempty" toml:"total_cache,omitempty"` + InactiveAnon uint64 `json:"inactive_anon,omitempty" yaml:"inactive_anon,omitempty" toml:"inactive_anon,omitempty"` + ActiveFile uint64 `json:"active_file,omitempty" yaml:"active_file,omitempty" toml:"active_file,omitempty"` + Pgfault uint64 `json:"pgfault,omitempty" yaml:"pgfault,omitempty" toml:"pgfault,omitempty"` + InactiveFile uint64 `json:"inactive_file,omitempty" yaml:"inactive_file,omitempty" toml:"inactive_file,omitempty"` + TotalPgpgin uint64 `json:"total_pgpgin,omitempty" yaml:"total_pgpgin,omitempty" toml:"total_pgpgin,omitempty"` + HierarchicalMemswLimit uint64 `json:"hierarchical_memsw_limit,omitempty" yaml:"hierarchical_memsw_limit,omitempty" toml:"hierarchical_memsw_limit,omitempty"` + Swap uint64 `json:"swap,omitempty" yaml:"swap,omitempty" toml:"swap,omitempty"` + } `json:"stats,omitempty" yaml:"stats,omitempty" toml:"stats,omitempty"` + MaxUsage uint64 `json:"max_usage,omitempty" yaml:"max_usage,omitempty" toml:"max_usage,omitempty"` + Usage uint64 `json:"usage,omitempty" yaml:"usage,omitempty" toml:"usage,omitempty"` + Failcnt uint64 `json:"failcnt,omitempty" yaml:"failcnt,omitempty" toml:"failcnt,omitempty"` + Limit uint64 `json:"limit,omitempty" yaml:"limit,omitempty" toml:"limit,omitempty"` + Commit uint64 `json:"commitbytes,omitempty" yaml:"commitbytes,omitempty" toml:"privateworkingset,omitempty"` + CommitPeak uint64 `json:"commitpeakbytes,omitempty" yaml:"commitpeakbytes,omitempty" toml:"commitpeakbytes,omitempty"` + PrivateWorkingSet uint64 `json:"privateworkingset,omitempty" yaml:"privateworkingset,omitempty" toml:"privateworkingset,omitempty"` + } `json:"memory_stats,omitempty" yaml:"memory_stats,omitempty" toml:"memory_stats,omitempty"` + BlkioStats struct { + IOServiceBytesRecursive []BlkioStatsEntry `json:"io_service_bytes_recursive,omitempty" yaml:"io_service_bytes_recursive,omitempty" toml:"io_service_bytes_recursive,omitempty"` + IOServicedRecursive []BlkioStatsEntry `json:"io_serviced_recursive,omitempty" yaml:"io_serviced_recursive,omitempty" toml:"io_serviced_recursive,omitempty"` + IOQueueRecursive []BlkioStatsEntry `json:"io_queue_recursive,omitempty" yaml:"io_queue_recursive,omitempty" toml:"io_queue_recursive,omitempty"` + IOServiceTimeRecursive []BlkioStatsEntry `json:"io_service_time_recursive,omitempty" yaml:"io_service_time_recursive,omitempty" toml:"io_service_time_recursive,omitempty"` + IOWaitTimeRecursive []BlkioStatsEntry `json:"io_wait_time_recursive,omitempty" yaml:"io_wait_time_recursive,omitempty" toml:"io_wait_time_recursive,omitempty"` + IOMergedRecursive []BlkioStatsEntry `json:"io_merged_recursive,omitempty" yaml:"io_merged_recursive,omitempty" toml:"io_merged_recursive,omitempty"` + IOTimeRecursive []BlkioStatsEntry `json:"io_time_recursive,omitempty" yaml:"io_time_recursive,omitempty" toml:"io_time_recursive,omitempty"` + SectorsRecursive []BlkioStatsEntry `json:"sectors_recursive,omitempty" yaml:"sectors_recursive,omitempty" toml:"sectors_recursive,omitempty"` + } `json:"blkio_stats,omitempty" yaml:"blkio_stats,omitempty" toml:"blkio_stats,omitempty"` + CPUStats CPUStats `json:"cpu_stats,omitempty" yaml:"cpu_stats,omitempty" toml:"cpu_stats,omitempty"` + PreCPUStats CPUStats `json:"precpu_stats,omitempty"` + StorageStats struct { + ReadCountNormalized uint64 `json:"read_count_normalized,omitempty" yaml:"read_count_normalized,omitempty" toml:"read_count_normalized,omitempty"` + ReadSizeBytes uint64 `json:"read_size_bytes,omitempty" yaml:"read_size_bytes,omitempty" toml:"read_size_bytes,omitempty"` + WriteCountNormalized uint64 `json:"write_count_normalized,omitempty" yaml:"write_count_normalized,omitempty" toml:"write_count_normalized,omitempty"` + WriteSizeBytes uint64 `json:"write_size_bytes,omitempty" yaml:"write_size_bytes,omitempty" toml:"write_size_bytes,omitempty"` + } `json:"storage_stats,omitempty" yaml:"storage_stats,omitempty" toml:"storage_stats,omitempty"` +} + +// NetworkStats is a stats entry for network stats +type NetworkStats struct { + RxDropped uint64 `json:"rx_dropped,omitempty" yaml:"rx_dropped,omitempty" toml:"rx_dropped,omitempty"` + RxBytes uint64 `json:"rx_bytes,omitempty" yaml:"rx_bytes,omitempty" toml:"rx_bytes,omitempty"` + RxErrors uint64 `json:"rx_errors,omitempty" yaml:"rx_errors,omitempty" toml:"rx_errors,omitempty"` + TxPackets uint64 `json:"tx_packets,omitempty" yaml:"tx_packets,omitempty" toml:"tx_packets,omitempty"` + TxDropped uint64 `json:"tx_dropped,omitempty" yaml:"tx_dropped,omitempty" toml:"tx_dropped,omitempty"` + RxPackets uint64 `json:"rx_packets,omitempty" yaml:"rx_packets,omitempty" toml:"rx_packets,omitempty"` + TxErrors uint64 `json:"tx_errors,omitempty" yaml:"tx_errors,omitempty" toml:"tx_errors,omitempty"` + TxBytes uint64 `json:"tx_bytes,omitempty" yaml:"tx_bytes,omitempty" toml:"tx_bytes,omitempty"` +} + +// CPUStats is a stats entry for cpu stats +type CPUStats struct { + CPUUsage struct { + PercpuUsage []uint64 `json:"percpu_usage,omitempty" yaml:"percpu_usage,omitempty" toml:"percpu_usage,omitempty"` + UsageInUsermode uint64 `json:"usage_in_usermode,omitempty" yaml:"usage_in_usermode,omitempty" toml:"usage_in_usermode,omitempty"` + TotalUsage uint64 `json:"total_usage,omitempty" yaml:"total_usage,omitempty" toml:"total_usage,omitempty"` + UsageInKernelmode uint64 `json:"usage_in_kernelmode,omitempty" yaml:"usage_in_kernelmode,omitempty" toml:"usage_in_kernelmode,omitempty"` + } `json:"cpu_usage,omitempty" yaml:"cpu_usage,omitempty" toml:"cpu_usage,omitempty"` + SystemCPUUsage uint64 `json:"system_cpu_usage,omitempty" yaml:"system_cpu_usage,omitempty" toml:"system_cpu_usage,omitempty"` + OnlineCPUs uint64 `json:"online_cpus,omitempty" yaml:"online_cpus,omitempty" toml:"online_cpus,omitempty"` + ThrottlingData struct { + Periods uint64 `json:"periods,omitempty"` + ThrottledPeriods uint64 `json:"throttled_periods,omitempty"` + ThrottledTime uint64 `json:"throttled_time,omitempty"` + } `json:"throttling_data,omitempty" yaml:"throttling_data,omitempty" toml:"throttling_data,omitempty"` +} + +// BlkioStatsEntry is a stats entry for blkio_stats +type BlkioStatsEntry struct { + Major uint64 `json:"major,omitempty" yaml:"major,omitempty" toml:"major,omitempty"` + Minor uint64 `json:"minor,omitempty" yaml:"minor,omitempty" toml:"minor,omitempty"` + Op string `json:"op,omitempty" yaml:"op,omitempty" toml:"op,omitempty"` + Value uint64 `json:"value,omitempty" yaml:"value,omitempty" toml:"value,omitempty"` +} + +// StatsOptions specify parameters to the Stats function. +// +// See https://goo.gl/Dk3Xio for more details. +type StatsOptions struct { + ID string + Stats chan<- *Stats + Stream bool + // A flag that enables stopping the stats operation + Done <-chan bool + // Initial connection timeout + Timeout time.Duration + // Timeout with no data is received, it's reset every time new data + // arrives + InactivityTimeout time.Duration `qs:"-"` + Context context.Context +} + +// Stats sends container statistics for the given container to the given channel. +// +// This function is blocking, similar to a streaming call for logs, and should be run +// on a separate goroutine from the caller. Note that this function will block until +// the given container is removed, not just exited. When finished, this function +// will close the given channel. Alternatively, function can be stopped by +// signaling on the Done channel. +// +// See https://goo.gl/Dk3Xio for more details. +func (c *Client) Stats(opts StatsOptions) (retErr error) { + errC := make(chan error, 1) + readCloser, writeCloser := io.Pipe() + + defer func() { + close(opts.Stats) + + select { + case err := <-errC: + if err != nil && retErr == nil { + retErr = err + } + default: + // No errors + } + + if err := readCloser.Close(); err != nil && retErr == nil { + retErr = err + } + }() + + reqSent := make(chan struct{}) + go func() { + err := c.stream("GET", fmt.Sprintf("/containers/%s/stats?stream=%v", opts.ID, opts.Stream), streamOptions{ + rawJSONStream: true, + useJSONDecoder: true, + stdout: writeCloser, + timeout: opts.Timeout, + inactivityTimeout: opts.InactivityTimeout, + context: opts.Context, + reqSent: reqSent, + }) + if err != nil { + dockerError, ok := err.(*Error) + if ok { + if dockerError.Status == http.StatusNotFound { + err = &NoSuchContainer{ID: opts.ID} + } + } + } + if closeErr := writeCloser.Close(); closeErr != nil && err == nil { + err = closeErr + } + errC <- err + close(errC) + }() + + quit := make(chan struct{}) + defer close(quit) + go func() { + // block here waiting for the signal to stop function + select { + case <-opts.Done: + readCloser.Close() + case <-quit: + return + } + }() + + decoder := json.NewDecoder(readCloser) + stats := new(Stats) + <-reqSent + for err := decoder.Decode(stats); err != io.EOF; err = decoder.Decode(stats) { + if err != nil { + return err + } + opts.Stats <- stats + stats = new(Stats) + } + return nil +} + +// KillContainerOptions represents the set of options that can be used in a +// call to KillContainer. +// +// See https://goo.gl/JnTxXZ for more details. +type KillContainerOptions struct { + // The ID of the container. + ID string `qs:"-"` + + // The signal to send to the container. When omitted, Docker server + // will assume SIGKILL. + Signal Signal + Context context.Context +} + +// KillContainer sends a signal to a container, returning an error in case of +// failure. +// +// See https://goo.gl/JnTxXZ for more details. +func (c *Client) KillContainer(opts KillContainerOptions) error { + path := "/containers/" + opts.ID + "/kill" + "?" + queryString(opts) + resp, err := c.do("POST", path, doOptions{context: opts.Context}) + if err != nil { + e, ok := err.(*Error) + if !ok { + return err + } + switch e.Status { + case http.StatusNotFound: + return &NoSuchContainer{ID: opts.ID} + case http.StatusConflict: + return &ContainerNotRunning{ID: opts.ID} + default: + return err + } + } + resp.Body.Close() + return nil +} + +// RemoveContainerOptions encapsulates options to remove a container. +// +// See https://goo.gl/hL5IPC for more details. +type RemoveContainerOptions struct { + // The ID of the container. + ID string `qs:"-"` + + // A flag that indicates whether Docker should remove the volumes + // associated to the container. + RemoveVolumes bool `qs:"v"` + + // A flag that indicates whether Docker should remove the container + // even if it is currently running. + Force bool + Context context.Context +} + +// RemoveContainer removes a container, returning an error in case of failure. +// +// See https://goo.gl/hL5IPC for more details. +func (c *Client) RemoveContainer(opts RemoveContainerOptions) error { + path := "/containers/" + opts.ID + "?" + queryString(opts) + resp, err := c.do("DELETE", path, doOptions{context: opts.Context}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return &NoSuchContainer{ID: opts.ID} + } + return err + } + resp.Body.Close() + return nil +} + +// UploadToContainerOptions is the set of options that can be used when +// uploading an archive into a container. +// +// See https://goo.gl/g25o7u for more details. +type UploadToContainerOptions struct { + InputStream io.Reader `json:"-" qs:"-"` + Path string `qs:"path"` + NoOverwriteDirNonDir bool `qs:"noOverwriteDirNonDir"` + Context context.Context +} + +// UploadToContainer uploads a tar archive to be extracted to a path in the +// filesystem of the container. +// +// See https://goo.gl/g25o7u for more details. +func (c *Client) UploadToContainer(id string, opts UploadToContainerOptions) error { + url := fmt.Sprintf("/containers/%s/archive?", id) + queryString(opts) + + return c.stream("PUT", url, streamOptions{ + in: opts.InputStream, + context: opts.Context, + }) +} + +// DownloadFromContainerOptions is the set of options that can be used when +// downloading resources from a container. +// +// See https://goo.gl/W49jxK for more details. +type DownloadFromContainerOptions struct { + OutputStream io.Writer `json:"-" qs:"-"` + Path string `qs:"path"` + InactivityTimeout time.Duration `qs:"-"` + Context context.Context +} + +// DownloadFromContainer downloads a tar archive of files or folders in a container. +// +// See https://goo.gl/W49jxK for more details. +func (c *Client) DownloadFromContainer(id string, opts DownloadFromContainerOptions) error { + url := fmt.Sprintf("/containers/%s/archive?", id) + queryString(opts) + + return c.stream("GET", url, streamOptions{ + setRawTerminal: true, + stdout: opts.OutputStream, + inactivityTimeout: opts.InactivityTimeout, + context: opts.Context, + }) +} + +// CopyFromContainerOptions contains the set of options used for copying +// files from a container. +// +// Deprecated: Use DownloadFromContainerOptions and DownloadFromContainer instead. +type CopyFromContainerOptions struct { + OutputStream io.Writer `json:"-"` + Container string `json:"-"` + Resource string + Context context.Context `json:"-"` +} + +// CopyFromContainer copies files from a container. +// +// Deprecated: Use DownloadFromContainer and DownloadFromContainer instead. +func (c *Client) CopyFromContainer(opts CopyFromContainerOptions) error { + if opts.Container == "" { + return &NoSuchContainer{ID: opts.Container} + } + if c.serverAPIVersion == nil { + c.checkAPIVersion() + } + if c.serverAPIVersion != nil && c.serverAPIVersion.GreaterThanOrEqualTo(apiVersion124) { + return errors.New("go-dockerclient: CopyFromContainer is no longer available in Docker >= 1.12, use DownloadFromContainer instead") + } + url := fmt.Sprintf("/containers/%s/copy", opts.Container) + resp, err := c.do("POST", url, doOptions{ + data: opts, + context: opts.Context, + }) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return &NoSuchContainer{ID: opts.Container} + } + return err + } + defer resp.Body.Close() + _, err = io.Copy(opts.OutputStream, resp.Body) + return err +} + +// WaitContainer blocks until the given container stops, return the exit code +// of the container status. +// +// See https://goo.gl/4AGweZ for more details. +func (c *Client) WaitContainer(id string) (int, error) { + return c.waitContainer(id, doOptions{}) +} + +// WaitContainerWithContext blocks until the given container stops, return the exit code +// of the container status. The context object can be used to cancel the +// inspect request. +// +// See https://goo.gl/4AGweZ for more details. +func (c *Client) WaitContainerWithContext(id string, ctx context.Context) (int, error) { + return c.waitContainer(id, doOptions{context: ctx}) +} + +func (c *Client) waitContainer(id string, opts doOptions) (int, error) { + resp, err := c.do("POST", "/containers/"+id+"/wait", opts) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return 0, &NoSuchContainer{ID: id} + } + return 0, err + } + defer resp.Body.Close() + var r struct{ StatusCode int } + if err := json.NewDecoder(resp.Body).Decode(&r); err != nil { + return 0, err + } + return r.StatusCode, nil +} + +// CommitContainerOptions aggregates parameters to the CommitContainer method. +// +// See https://goo.gl/CzIguf for more details. +type CommitContainerOptions struct { + Container string + Repository string `qs:"repo"` + Tag string + Message string `qs:"comment"` + Author string + Changes []string `qs:"changes"` + Run *Config `qs:"-"` + Context context.Context +} + +// CommitContainer creates a new image from a container's changes. +// +// See https://goo.gl/CzIguf for more details. +func (c *Client) CommitContainer(opts CommitContainerOptions) (*Image, error) { + path := "/commit?" + queryString(opts) + resp, err := c.do("POST", path, doOptions{ + data: opts.Run, + context: opts.Context, + }) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return nil, &NoSuchContainer{ID: opts.Container} + } + return nil, err + } + defer resp.Body.Close() + var image Image + if err := json.NewDecoder(resp.Body).Decode(&image); err != nil { + return nil, err + } + return &image, nil +} + +// AttachToContainerOptions is the set of options that can be used when +// attaching to a container. +// +// See https://goo.gl/JF10Zk for more details. +type AttachToContainerOptions struct { + Container string `qs:"-"` + InputStream io.Reader `qs:"-"` + OutputStream io.Writer `qs:"-"` + ErrorStream io.Writer `qs:"-"` + + // If set, after a successful connect, a sentinel will be sent and then the + // client will block on receive before continuing. + // + // It must be an unbuffered channel. Using a buffered channel can lead + // to unexpected behavior. + Success chan struct{} + + // Use raw terminal? Usually true when the container contains a TTY. + RawTerminal bool `qs:"-"` + + // Get container logs, sending it to OutputStream. + Logs bool + + // Stream the response? + Stream bool + + // Attach to stdin, and use InputStream. + Stdin bool + + // Attach to stdout, and use OutputStream. + Stdout bool + + // Attach to stderr, and use ErrorStream. + Stderr bool +} + +// AttachToContainer attaches to a container, using the given options. +// +// See https://goo.gl/JF10Zk for more details. +func (c *Client) AttachToContainer(opts AttachToContainerOptions) error { + cw, err := c.AttachToContainerNonBlocking(opts) + if err != nil { + return err + } + return cw.Wait() +} + +// AttachToContainerNonBlocking attaches to a container, using the given options. +// This function does not block. +// +// See https://goo.gl/NKpkFk for more details. +func (c *Client) AttachToContainerNonBlocking(opts AttachToContainerOptions) (CloseWaiter, error) { + if opts.Container == "" { + return nil, &NoSuchContainer{ID: opts.Container} + } + path := "/containers/" + opts.Container + "/attach?" + queryString(opts) + return c.hijack("POST", path, hijackOptions{ + success: opts.Success, + setRawTerminal: opts.RawTerminal, + in: opts.InputStream, + stdout: opts.OutputStream, + stderr: opts.ErrorStream, + }) +} + +// LogsOptions represents the set of options used when getting logs from a +// container. +// +// See https://goo.gl/krK0ZH for more details. +type LogsOptions struct { + Context context.Context + Container string `qs:"-"` + OutputStream io.Writer `qs:"-"` + ErrorStream io.Writer `qs:"-"` + InactivityTimeout time.Duration `qs:"-"` + Tail string + + Since int64 + Follow bool + Stdout bool + Stderr bool + Timestamps bool + + // Use raw terminal? Usually true when the container contains a TTY. + RawTerminal bool `qs:"-"` +} + +// Logs gets stdout and stderr logs from the specified container. +// +// When LogsOptions.RawTerminal is set to false, go-dockerclient will multiplex +// the streams and send the containers stdout to LogsOptions.OutputStream, and +// stderr to LogsOptions.ErrorStream. +// +// When LogsOptions.RawTerminal is true, callers will get the raw stream on +// LogsOptions.OutputStream. The caller can use libraries such as dlog +// (github.com/ahmetalpbalkan/dlog). +// +// See https://goo.gl/krK0ZH for more details. +func (c *Client) Logs(opts LogsOptions) error { + if opts.Container == "" { + return &NoSuchContainer{ID: opts.Container} + } + if opts.Tail == "" { + opts.Tail = "all" + } + path := "/containers/" + opts.Container + "/logs?" + queryString(opts) + return c.stream("GET", path, streamOptions{ + setRawTerminal: opts.RawTerminal, + stdout: opts.OutputStream, + stderr: opts.ErrorStream, + inactivityTimeout: opts.InactivityTimeout, + context: opts.Context, + }) +} + +// ResizeContainerTTY resizes the terminal to the given height and width. +// +// See https://goo.gl/FImjeq for more details. +func (c *Client) ResizeContainerTTY(id string, height, width int) error { + params := make(url.Values) + params.Set("h", strconv.Itoa(height)) + params.Set("w", strconv.Itoa(width)) + resp, err := c.do("POST", "/containers/"+id+"/resize?"+params.Encode(), doOptions{}) + if err != nil { + return err + } + resp.Body.Close() + return nil +} + +// ExportContainerOptions is the set of parameters to the ExportContainer +// method. +// +// See https://goo.gl/yGJCIh for more details. +type ExportContainerOptions struct { + ID string + OutputStream io.Writer + InactivityTimeout time.Duration `qs:"-"` + Context context.Context +} + +// ExportContainer export the contents of container id as tar archive +// and prints the exported contents to stdout. +// +// See https://goo.gl/yGJCIh for more details. +func (c *Client) ExportContainer(opts ExportContainerOptions) error { + if opts.ID == "" { + return &NoSuchContainer{ID: opts.ID} + } + url := fmt.Sprintf("/containers/%s/export", opts.ID) + return c.stream("GET", url, streamOptions{ + setRawTerminal: true, + stdout: opts.OutputStream, + inactivityTimeout: opts.InactivityTimeout, + context: opts.Context, + }) +} + +// PruneContainersOptions specify parameters to the PruneContainers function. +// +// See https://goo.gl/wnkgDT for more details. +type PruneContainersOptions struct { + Filters map[string][]string + Context context.Context +} + +// PruneContainersResults specify results from the PruneContainers function. +// +// See https://goo.gl/wnkgDT for more details. +type PruneContainersResults struct { + ContainersDeleted []string + SpaceReclaimed int64 +} + +// PruneContainers deletes containers which are stopped. +// +// See https://goo.gl/wnkgDT for more details. +func (c *Client) PruneContainers(opts PruneContainersOptions) (*PruneContainersResults, error) { + path := "/containers/prune?" + queryString(opts) + resp, err := c.do("POST", path, doOptions{context: opts.Context}) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var results PruneContainersResults + if err := json.NewDecoder(resp.Body).Decode(&results); err != nil { + return nil, err + } + return &results, nil +} + +// NoSuchContainer is the error returned when a given container does not exist. +type NoSuchContainer struct { + ID string + Err error +} + +func (err *NoSuchContainer) Error() string { + if err.Err != nil { + return err.Err.Error() + } + return "No such container: " + err.ID +} + +// ContainerAlreadyRunning is the error returned when a given container is +// already running. +type ContainerAlreadyRunning struct { + ID string +} + +func (err *ContainerAlreadyRunning) Error() string { + return "Container already running: " + err.ID +} + +// ContainerNotRunning is the error returned when a given container is not +// running. +type ContainerNotRunning struct { + ID string +} + +func (err *ContainerNotRunning) Error() string { + return "Container not running: " + err.ID +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/distribution.go b/vendor/github.com/ory/dockertest/v3/docker/distribution.go new file mode 100644 index 00000000..3e610302 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/distribution.go @@ -0,0 +1,29 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2017 go-dockerclient 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 docker + +import ( + "encoding/json" + + "github.com/ory/dockertest/v3/docker/types/registry" +) + +// InspectDistribution returns image digest and platform information by contacting the registry +func (c *Client) InspectDistribution(name string) (*registry.DistributionInspect, error) { + path := "/distribution/" + name + "/json" + resp, err := c.do("GET", path, doOptions{}) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var distributionInspect registry.DistributionInspect + if err := json.NewDecoder(resp.Body).Decode(&distributionInspect); err != nil { + return nil, err + } + return &distributionInspect, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/env.go b/vendor/github.com/ory/dockertest/v3/docker/env.go new file mode 100644 index 00000000..b5c9edd3 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/env.go @@ -0,0 +1,175 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2014 Docker authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the DOCKER-LICENSE file. + +package docker + +import ( + "encoding/json" + "fmt" + "io" + "strconv" + "strings" +) + +// Env represents a list of key-pair represented in the form KEY=VALUE. +type Env []string + +// Get returns the string value of the given key. +func (env *Env) Get(key string) (value string) { + return env.Map()[key] +} + +// Exists checks whether the given key is defined in the internal Env +// representation. +func (env *Env) Exists(key string) bool { + _, exists := env.Map()[key] + return exists +} + +// GetBool returns a boolean representation of the given key. The key is false +// whenever its value if 0, no, false, none or an empty string. Any other value +// will be interpreted as true. +func (env *Env) GetBool(key string) (value bool) { + s := strings.ToLower(strings.Trim(env.Get(key), " \t")) + if s == "" || s == "0" || s == "no" || s == "false" || s == "none" { + return false + } + return true +} + +// SetBool defines a boolean value to the given key. +func (env *Env) SetBool(key string, value bool) { + if value { + env.Set(key, "1") + } else { + env.Set(key, "0") + } +} + +// GetInt returns the value of the provided key, converted to int. +// +// It the value cannot be represented as an integer, it returns -1. +func (env *Env) GetInt(key string) int { + return int(env.GetInt64(key)) +} + +// SetInt defines an integer value to the given key. +func (env *Env) SetInt(key string, value int) { + env.Set(key, strconv.Itoa(value)) +} + +// GetInt64 returns the value of the provided key, converted to int64. +// +// It the value cannot be represented as an integer, it returns -1. +func (env *Env) GetInt64(key string) int64 { + s := strings.Trim(env.Get(key), " \t") + val, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return -1 + } + return val +} + +// SetInt64 defines an integer (64-bit wide) value to the given key. +func (env *Env) SetInt64(key string, value int64) { + env.Set(key, strconv.FormatInt(value, 10)) +} + +// GetJSON unmarshals the value of the provided key in the provided iface. +// +// iface is a value that can be provided to the json.Unmarshal function. +func (env *Env) GetJSON(key string, iface interface{}) error { + sval := env.Get(key) + if sval == "" { + return nil + } + return json.Unmarshal([]byte(sval), iface) +} + +// SetJSON marshals the given value to JSON format and stores it using the +// provided key. +func (env *Env) SetJSON(key string, value interface{}) error { + sval, err := json.Marshal(value) + if err != nil { + return err + } + env.Set(key, string(sval)) + return nil +} + +// GetList returns a list of strings matching the provided key. It handles the +// list as a JSON representation of a list of strings. +// +// If the given key matches to a single string, it will return a list +// containing only the value that matches the key. +func (env *Env) GetList(key string) []string { + sval := env.Get(key) + if sval == "" { + return nil + } + var l []string + if err := json.Unmarshal([]byte(sval), &l); err != nil { + l = append(l, sval) + } + return l +} + +// SetList stores the given list in the provided key, after serializing it to +// JSON format. +func (env *Env) SetList(key string, value []string) error { + return env.SetJSON(key, value) +} + +// Set defines the value of a key to the given string. +func (env *Env) Set(key, value string) { + *env = append(*env, key+"="+value) +} + +// Decode decodes `src` as a json dictionary, and adds each decoded key-value +// pair to the environment. +// +// If `src` cannot be decoded as a json dictionary, an error is returned. +func (env *Env) Decode(src io.Reader) error { + m := make(map[string]interface{}) + if err := json.NewDecoder(src).Decode(&m); err != nil { + return err + } + for k, v := range m { + env.SetAuto(k, v) + } + return nil +} + +// SetAuto will try to define the Set* method to call based on the given value. +func (env *Env) SetAuto(key string, value interface{}) { + if fval, ok := value.(float64); ok { + env.SetInt64(key, int64(fval)) + } else if sval, ok := value.(string); ok { + env.Set(key, sval) + } else if val, err := json.Marshal(value); err == nil { + env.Set(key, string(val)) + } else { + env.Set(key, fmt.Sprintf("%v", value)) + } +} + +// Map returns the map representation of the env. +func (env *Env) Map() map[string]string { + if len(*env) == 0 { + return nil + } + m := make(map[string]string) + for _, kv := range *env { + parts := strings.SplitN(kv, "=", 2) + if len(parts) == 1 { + m[parts[0]] = "" + } else { + m[parts[0]] = parts[1] + } + } + return m +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/event.go b/vendor/github.com/ory/dockertest/v3/docker/event.go new file mode 100644 index 00000000..982ca1b2 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/event.go @@ -0,0 +1,413 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2014 go-dockerclient 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 docker + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "math" + "net" + "net/http" + "net/http/httputil" + "sync" + "sync/atomic" + "time" +) + +// APIEvents represents events coming from the Docker API +// The fields in the Docker API changed in API version 1.22, and +// events for more than images and containers are now fired off. +// To maintain forward and backward compatibility, go-dockerclient +// replicates the event in both the new and old format as faithfully as possible. +// +// For events that only exist in 1.22 in later, `Status` is filled in as +// `"Type:Action"` instead of just `Action` to allow for older clients to +// differentiate and not break if they rely on the pre-1.22 Status types. +// +// The transformEvent method can be consulted for more information about how +// events are translated from new/old API formats +type APIEvents struct { + // New API Fields in 1.22 + Action string `json:"action,omitempty"` + Type string `json:"type,omitempty"` + Actor APIActor `json:"actor,omitempty"` + + // Old API fields for < 1.22 + Status string `json:"status,omitempty"` + ID string `json:"id,omitempty"` + From string `json:"from,omitempty"` + + // Fields in both + Time int64 `json:"time,omitempty"` + TimeNano int64 `json:"timeNano,omitempty"` +} + +// APIActor represents an actor that accomplishes something for an event +type APIActor struct { + ID string `json:"id,omitempty"` + Attributes map[string]string `json:"attributes,omitempty"` +} + +type eventMonitoringState struct { + // `sync/atomic` expects the first word in an allocated struct to be 64-bit + // aligned on both ARM and x86-32. See https://goo.gl/zW7dgq for more details. + lastSeen int64 + sync.RWMutex + sync.WaitGroup + enabled bool + C chan *APIEvents + errC chan error + listeners []chan<- *APIEvents +} + +const ( + maxMonitorConnRetries = 5 + retryInitialWaitTime = 10. +) + +var ( + // ErrNoListeners is the error returned when no listeners are available + // to receive an event. + ErrNoListeners = errors.New("no listeners present to receive event") + + // ErrListenerAlreadyExists is the error returned when the listerner already + // exists. + ErrListenerAlreadyExists = errors.New("listener already exists for docker events") + + // ErrTLSNotSupported is the error returned when the client does not support + // TLS (this applies to the Windows named pipe client). + ErrTLSNotSupported = errors.New("tls not supported by this client") + + // EOFEvent is sent when the event listener receives an EOF error. + EOFEvent = &APIEvents{ + Type: "EOF", + Status: "EOF", + } +) + +// AddEventListener adds a new listener to container events in the Docker API. +// +// The parameter is a channel through which events will be sent. +func (c *Client) AddEventListener(listener chan<- *APIEvents) error { + var err error + if !c.eventMonitor.isEnabled() { + err = c.eventMonitor.enableEventMonitoring(c) + if err != nil { + return err + } + } + return c.eventMonitor.addListener(listener) +} + +// RemoveEventListener removes a listener from the monitor. +func (c *Client) RemoveEventListener(listener chan *APIEvents) error { + err := c.eventMonitor.removeListener(listener) + if err != nil { + return err + } + if c.eventMonitor.listernersCount() == 0 { + c.eventMonitor.disableEventMonitoring() + } + return nil +} + +func (eventState *eventMonitoringState) addListener(listener chan<- *APIEvents) error { + eventState.Lock() + defer eventState.Unlock() + if listenerExists(listener, &eventState.listeners) { + return ErrListenerAlreadyExists + } + eventState.Add(1) + eventState.listeners = append(eventState.listeners, listener) + return nil +} + +func (eventState *eventMonitoringState) removeListener(listener chan<- *APIEvents) error { + eventState.Lock() + defer eventState.Unlock() + if listenerExists(listener, &eventState.listeners) { + var newListeners []chan<- *APIEvents + for _, l := range eventState.listeners { + if l != listener { + newListeners = append(newListeners, l) + } + } + eventState.listeners = newListeners + eventState.Add(-1) + } + return nil +} + +func (eventState *eventMonitoringState) closeListeners() { + for _, l := range eventState.listeners { + close(l) + eventState.Add(-1) + } + eventState.listeners = nil +} + +func (eventState *eventMonitoringState) listernersCount() int { + eventState.RLock() + defer eventState.RUnlock() + return len(eventState.listeners) +} + +func listenerExists(a chan<- *APIEvents, list *[]chan<- *APIEvents) bool { + for _, b := range *list { + if b == a { + return true + } + } + return false +} + +func (eventState *eventMonitoringState) enableEventMonitoring(c *Client) error { + eventState.Lock() + defer eventState.Unlock() + if !eventState.enabled { + eventState.enabled = true + atomic.StoreInt64(&eventState.lastSeen, 0) + eventState.C = make(chan *APIEvents, 100) + eventState.errC = make(chan error, 1) + go eventState.monitorEvents(c) + } + return nil +} + +func (eventState *eventMonitoringState) disableEventMonitoring() error { + eventState.Lock() + defer eventState.Unlock() + + eventState.closeListeners() + + eventState.Wait() + + if eventState.enabled { + eventState.enabled = false + close(eventState.C) + close(eventState.errC) + } + return nil +} + +func (eventState *eventMonitoringState) monitorEvents(c *Client) { + const ( + noListenersTimeout = 5 * time.Second + noListenersInterval = 10 * time.Millisecond + noListenersMaxTries = noListenersTimeout / noListenersInterval + ) + + var err error + for i := time.Duration(0); i < noListenersMaxTries && eventState.noListeners(); i++ { + time.Sleep(10 * time.Millisecond) + } + + if eventState.noListeners() { + // terminate if no listener is available after 5 seconds. + // Prevents goroutine leak when RemoveEventListener is called + // right after AddEventListener. + eventState.disableEventMonitoring() + return + } + + if err = eventState.connectWithRetry(c); err != nil { + // terminate if connect failed + eventState.disableEventMonitoring() + return + } + for eventState.isEnabled() { + timeout := time.After(100 * time.Millisecond) + select { + case ev, ok := <-eventState.C: + if !ok { + return + } + if ev == EOFEvent { + eventState.disableEventMonitoring() + return + } + eventState.updateLastSeen(ev) + eventState.sendEvent(ev) + case err = <-eventState.errC: + if err == ErrNoListeners { + eventState.disableEventMonitoring() + return + } else if err != nil { + defer func() { go eventState.monitorEvents(c) }() + return + } + case <-timeout: + continue + } + } +} + +func (eventState *eventMonitoringState) connectWithRetry(c *Client) error { + var retries int + eventState.RLock() + eventChan := eventState.C + errChan := eventState.errC + eventState.RUnlock() + err := c.eventHijack(atomic.LoadInt64(&eventState.lastSeen), eventChan, errChan) + for ; err != nil && retries < maxMonitorConnRetries; retries++ { + waitTime := int64(retryInitialWaitTime * math.Pow(2, float64(retries))) + time.Sleep(time.Duration(waitTime) * time.Millisecond) + eventState.RLock() + eventChan = eventState.C + errChan = eventState.errC + eventState.RUnlock() + err = c.eventHijack(atomic.LoadInt64(&eventState.lastSeen), eventChan, errChan) + } + return err +} + +func (eventState *eventMonitoringState) noListeners() bool { + eventState.RLock() + defer eventState.RUnlock() + return len(eventState.listeners) == 0 +} + +func (eventState *eventMonitoringState) isEnabled() bool { + eventState.RLock() + defer eventState.RUnlock() + return eventState.enabled +} + +func (eventState *eventMonitoringState) sendEvent(event *APIEvents) { + eventState.RLock() + defer eventState.RUnlock() + eventState.Add(1) + defer eventState.Done() + if eventState.enabled { + if len(eventState.listeners) == 0 { + eventState.errC <- ErrNoListeners + return + } + + for _, listener := range eventState.listeners { + select { + case listener <- event: + default: + } + } + } +} + +func (eventState *eventMonitoringState) updateLastSeen(e *APIEvents) { + eventState.Lock() + defer eventState.Unlock() + if atomic.LoadInt64(&eventState.lastSeen) < e.Time { + atomic.StoreInt64(&eventState.lastSeen, e.Time) + } +} + +func (c *Client) eventHijack(startTime int64, eventChan chan *APIEvents, errChan chan error) error { + uri := "/events" + if startTime != 0 { + uri += fmt.Sprintf("?since=%d", startTime) + } + protocol := c.endpointURL.Scheme + address := c.endpointURL.Path + if protocol != "unix" && protocol != "npipe" { + protocol = "tcp" + address = c.endpointURL.Host + } + var dial net.Conn + var err error + if c.TLSConfig == nil { + dial, err = c.Dialer.Dial(protocol, address) + } else { + netDialer, ok := c.Dialer.(*net.Dialer) + if !ok { + return ErrTLSNotSupported + } + dial, err = tlsDialWithDialer(netDialer, protocol, address, c.TLSConfig) + } + if err != nil { + return err + } + conn := httputil.NewClientConn(dial, nil) + req, err := http.NewRequest("GET", uri, nil) + if err != nil { + return err + } + res, err := conn.Do(req) + if err != nil { + return err + } + go func(res *http.Response, conn *httputil.ClientConn) { + defer conn.Close() + defer res.Body.Close() + decoder := json.NewDecoder(res.Body) + for { + var event APIEvents + if err = decoder.Decode(&event); err != nil { + if err == io.EOF || err == io.ErrUnexpectedEOF { + c.eventMonitor.RLock() + if c.eventMonitor.enabled && c.eventMonitor.C == eventChan { + // Signal that we're exiting. + eventChan <- EOFEvent + } + c.eventMonitor.RUnlock() + break + } + errChan <- err + } + if event.Time == 0 { + continue + } + transformEvent(&event) + c.eventMonitor.RLock() + if c.eventMonitor.enabled && c.eventMonitor.C == eventChan { + eventChan <- &event + } + c.eventMonitor.RUnlock() + } + }(res, conn) + return nil +} + +// transformEvent takes an event and determines what version it is from +// then populates both versions of the event +func transformEvent(event *APIEvents) { + // if event version is <= 1.21 there will be no Action and no Type + if event.Action == "" && event.Type == "" { + event.Action = event.Status + event.Actor.ID = event.ID + event.Actor.Attributes = map[string]string{} + switch event.Status { + case "delete", "import", "pull", "push", "tag", "untag": + event.Type = "image" + default: + event.Type = "container" + if event.From != "" { + event.Actor.Attributes["image"] = event.From + } + } + } else { + if event.Status == "" { + if event.Type == "image" || event.Type == "container" { + event.Status = event.Action + } else { + // Because just the Status has been overloaded with different Types + // if an event is not for an image or a container, we prepend the type + // to avoid problems for people relying on actions being only for + // images and containers + event.Status = event.Type + ":" + event.Action + } + } + if event.ID == "" { + event.ID = event.Actor.ID + } + if event.From == "" { + event.From = event.Actor.Attributes["image"] + } + } +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/exec.go b/vendor/github.com/ory/dockertest/v3/docker/exec.go new file mode 100644 index 00000000..1efdfd21 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/exec.go @@ -0,0 +1,216 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2014 go-dockerclient 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 docker + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" +) + +// Exec is the type representing a `docker exec` instance and containing the +// instance ID +type Exec struct { + ID string `json:"Id,omitempty" yaml:"Id,omitempty"` +} + +// CreateExecOptions specify parameters to the CreateExecContainer function. +// +// See https://goo.gl/60TeBP for more details +type CreateExecOptions struct { + AttachStdin bool `json:"AttachStdin,omitempty" yaml:"AttachStdin,omitempty" toml:"AttachStdin,omitempty"` + AttachStdout bool `json:"AttachStdout,omitempty" yaml:"AttachStdout,omitempty" toml:"AttachStdout,omitempty"` + AttachStderr bool `json:"AttachStderr,omitempty" yaml:"AttachStderr,omitempty" toml:"AttachStderr,omitempty"` + Tty bool `json:"Tty,omitempty" yaml:"Tty,omitempty" toml:"Tty,omitempty"` + Env []string `json:"Env,omitempty" yaml:"Env,omitempty" toml:"Env,omitempty"` + Cmd []string `json:"Cmd,omitempty" yaml:"Cmd,omitempty" toml:"Cmd,omitempty"` + Container string `json:"Container,omitempty" yaml:"Container,omitempty" toml:"Container,omitempty"` + User string `json:"User,omitempty" yaml:"User,omitempty" toml:"User,omitempty"` + Context context.Context `json:"-"` + Privileged bool `json:"Privileged,omitempty" yaml:"Privileged,omitempty" toml:"Privileged,omitempty"` +} + +// CreateExec sets up an exec instance in a running container `id`, returning the exec +// instance, or an error in case of failure. +// +// See https://goo.gl/60TeBP for more details +func (c *Client) CreateExec(opts CreateExecOptions) (*Exec, error) { + if len(opts.Env) > 0 && c.serverAPIVersion.LessThan(apiVersion125) { + return nil, errors.New("exec configuration Env is only supported in API#1.25 and above") + } + path := fmt.Sprintf("/containers/%s/exec", opts.Container) + resp, err := c.do("POST", path, doOptions{data: opts, context: opts.Context}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return nil, &NoSuchContainer{ID: opts.Container} + } + return nil, err + } + defer resp.Body.Close() + var exec Exec + if err := json.NewDecoder(resp.Body).Decode(&exec); err != nil { + return nil, err + } + + return &exec, nil +} + +// StartExecOptions specify parameters to the StartExecContainer function. +// +// See https://goo.gl/1EeDWi for more details +type StartExecOptions struct { + InputStream io.Reader `qs:"-"` + OutputStream io.Writer `qs:"-"` + ErrorStream io.Writer `qs:"-"` + + Detach bool `json:"Detach,omitempty" yaml:"Detach,omitempty" toml:"Detach,omitempty"` + Tty bool `json:"Tty,omitempty" yaml:"Tty,omitempty" toml:"Tty,omitempty"` + + // Use raw terminal? Usually true when the container contains a TTY. + RawTerminal bool `qs:"-"` + + // If set, after a successful connect, a sentinel will be sent and then the + // client will block on receive before continuing. + // + // It must be an unbuffered channel. Using a buffered channel can lead + // to unexpected behavior. + Success chan struct{} `json:"-"` + + Context context.Context `json:"-"` +} + +// StartExec starts a previously set up exec instance id. If opts.Detach is +// true, it returns after starting the exec command. Otherwise, it sets up an +// interactive session with the exec command. +// +// See https://goo.gl/1EeDWi for more details +func (c *Client) StartExec(id string, opts StartExecOptions) error { + cw, err := c.StartExecNonBlocking(id, opts) + if err != nil { + return err + } + if cw != nil { + return cw.Wait() + } + return nil +} + +// StartExecNonBlocking starts a previously set up exec instance id. If opts.Detach is +// true, it returns after starting the exec command. Otherwise, it sets up an +// interactive session with the exec command. +// +// See https://goo.gl/1EeDWi for more details +func (c *Client) StartExecNonBlocking(id string, opts StartExecOptions) (CloseWaiter, error) { + if id == "" { + return nil, &NoSuchExec{ID: id} + } + + path := fmt.Sprintf("/exec/%s/start", id) + + if opts.Detach { + resp, err := c.do("POST", path, doOptions{data: opts, context: opts.Context}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return nil, &NoSuchExec{ID: id} + } + return nil, err + } + defer resp.Body.Close() + return nil, nil + } + + return c.hijack("POST", path, hijackOptions{ + success: opts.Success, + setRawTerminal: opts.RawTerminal, + in: opts.InputStream, + stdout: opts.OutputStream, + stderr: opts.ErrorStream, + data: opts, + }) +} + +// ResizeExecTTY resizes the tty session used by the exec command id. This API +// is valid only if Tty was specified as part of creating and starting the exec +// command. +// +// See https://goo.gl/Mo5bxx for more details +func (c *Client) ResizeExecTTY(id string, height, width int) error { + params := make(url.Values) + params.Set("h", strconv.Itoa(height)) + params.Set("w", strconv.Itoa(width)) + + path := fmt.Sprintf("/exec/%s/resize?%s", id, params.Encode()) + resp, err := c.do("POST", path, doOptions{}) + if err != nil { + return err + } + resp.Body.Close() + return nil +} + +// ExecProcessConfig is a type describing the command associated to a Exec +// instance. It's used in the ExecInspect type. +type ExecProcessConfig struct { + User string `json:"user,omitempty" yaml:"user,omitempty" toml:"user,omitempty"` + Privileged bool `json:"privileged,omitempty" yaml:"privileged,omitempty" toml:"privileged,omitempty"` + Tty bool `json:"tty,omitempty" yaml:"tty,omitempty" toml:"tty,omitempty"` + EntryPoint string `json:"entrypoint,omitempty" yaml:"entrypoint,omitempty" toml:"entrypoint,omitempty"` + Arguments []string `json:"arguments,omitempty" yaml:"arguments,omitempty" toml:"arguments,omitempty"` +} + +// ExecInspect is a type with details about a exec instance, including the +// exit code if the command has finished running. It's returned by a api +// call to /exec/(id)/json +// +// See https://goo.gl/ctMUiW for more details +type ExecInspect struct { + ID string `json:"ID,omitempty" yaml:"ID,omitempty" toml:"ID,omitempty"` + ExitCode int `json:"ExitCode,omitempty" yaml:"ExitCode,omitempty" toml:"ExitCode,omitempty"` + Running bool `json:"Running,omitempty" yaml:"Running,omitempty" toml:"Running,omitempty"` + OpenStdin bool `json:"OpenStdin,omitempty" yaml:"OpenStdin,omitempty" toml:"OpenStdin,omitempty"` + OpenStderr bool `json:"OpenStderr,omitempty" yaml:"OpenStderr,omitempty" toml:"OpenStderr,omitempty"` + OpenStdout bool `json:"OpenStdout,omitempty" yaml:"OpenStdout,omitempty" toml:"OpenStdout,omitempty"` + ProcessConfig ExecProcessConfig `json:"ProcessConfig,omitempty" yaml:"ProcessConfig,omitempty" toml:"ProcessConfig,omitempty"` + ContainerID string `json:"ContainerID,omitempty" yaml:"ContainerID,omitempty" toml:"ContainerID,omitempty"` + DetachKeys string `json:"DetachKeys,omitempty" yaml:"DetachKeys,omitempty" toml:"DetachKeys,omitempty"` + CanRemove bool `json:"CanRemove,omitempty" yaml:"CanRemove,omitempty" toml:"CanRemove,omitempty"` +} + +// InspectExec returns low-level information about the exec command id. +// +// See https://goo.gl/ctMUiW for more details +func (c *Client) InspectExec(id string) (*ExecInspect, error) { + path := fmt.Sprintf("/exec/%s/json", id) + resp, err := c.do("GET", path, doOptions{}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return nil, &NoSuchExec{ID: id} + } + return nil, err + } + defer resp.Body.Close() + var exec ExecInspect + if err := json.NewDecoder(resp.Body).Decode(&exec); err != nil { + return nil, err + } + return &exec, nil +} + +// NoSuchExec is the error returned when a given exec instance does not exist. +type NoSuchExec struct { + ID string +} + +func (err *NoSuchExec) Error() string { + return "No such exec instance: " + err.ID +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/image.go b/vendor/github.com/ory/dockertest/v3/docker/image.go new file mode 100644 index 00000000..ee7e5f53 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/image.go @@ -0,0 +1,763 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2013 go-dockerclient 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 docker + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "time" +) + +// APIImages represent an image returned in the ListImages call. +type APIImages struct { + ID string `json:"Id" yaml:"Id" toml:"Id"` + RepoTags []string `json:"RepoTags,omitempty" yaml:"RepoTags,omitempty" toml:"RepoTags,omitempty"` + Created int64 `json:"Created,omitempty" yaml:"Created,omitempty" toml:"Created,omitempty"` + Size int64 `json:"Size,omitempty" yaml:"Size,omitempty" toml:"Size,omitempty"` + VirtualSize int64 `json:"VirtualSize,omitempty" yaml:"VirtualSize,omitempty" toml:"VirtualSize,omitempty"` + ParentID string `json:"ParentId,omitempty" yaml:"ParentId,omitempty" toml:"ParentId,omitempty"` + RepoDigests []string `json:"RepoDigests,omitempty" yaml:"RepoDigests,omitempty" toml:"RepoDigests,omitempty"` + Labels map[string]string `json:"Labels,omitempty" yaml:"Labels,omitempty" toml:"Labels,omitempty"` +} + +// RootFS represents the underlying layers used by an image +type RootFS struct { + Type string `json:"Type,omitempty" yaml:"Type,omitempty" toml:"Type,omitempty"` + Layers []string `json:"Layers,omitempty" yaml:"Layers,omitempty" toml:"Layers,omitempty"` +} + +// Image is the type representing a docker image and its various properties +type Image struct { + ID string `json:"Id" yaml:"Id" toml:"Id"` + RepoTags []string `json:"RepoTags,omitempty" yaml:"RepoTags,omitempty" toml:"RepoTags,omitempty"` + Parent string `json:"Parent,omitempty" yaml:"Parent,omitempty" toml:"Parent,omitempty"` + Comment string `json:"Comment,omitempty" yaml:"Comment,omitempty" toml:"Comment,omitempty"` + Created time.Time `json:"Created,omitempty" yaml:"Created,omitempty" toml:"Created,omitempty"` + Container string `json:"Container,omitempty" yaml:"Container,omitempty" toml:"Container,omitempty"` + ContainerConfig Config `json:"ContainerConfig,omitempty" yaml:"ContainerConfig,omitempty" toml:"ContainerConfig,omitempty"` + DockerVersion string `json:"DockerVersion,omitempty" yaml:"DockerVersion,omitempty" toml:"DockerVersion,omitempty"` + Author string `json:"Author,omitempty" yaml:"Author,omitempty" toml:"Author,omitempty"` + Config *Config `json:"Config,omitempty" yaml:"Config,omitempty" toml:"Config,omitempty"` + Architecture string `json:"Architecture,omitempty" yaml:"Architecture,omitempty"` + Size int64 `json:"Size,omitempty" yaml:"Size,omitempty" toml:"Size,omitempty"` + VirtualSize int64 `json:"VirtualSize,omitempty" yaml:"VirtualSize,omitempty" toml:"VirtualSize,omitempty"` + RepoDigests []string `json:"RepoDigests,omitempty" yaml:"RepoDigests,omitempty" toml:"RepoDigests,omitempty"` + RootFS *RootFS `json:"RootFS,omitempty" yaml:"RootFS,omitempty" toml:"RootFS,omitempty"` + OS string `json:"Os,omitempty" yaml:"Os,omitempty" toml:"Os,omitempty"` +} + +// ImagePre012 serves the same purpose as the Image type except that it is for +// earlier versions of the Docker API (pre-012 to be specific) +type ImagePre012 struct { + ID string `json:"id"` + Parent string `json:"parent,omitempty"` + Comment string `json:"comment,omitempty"` + Created time.Time `json:"created"` + Container string `json:"container,omitempty"` + ContainerConfig Config `json:"container_config,omitempty"` + DockerVersion string `json:"docker_version,omitempty"` + Author string `json:"author,omitempty"` + Config *Config `json:"config,omitempty"` + Architecture string `json:"architecture,omitempty"` + Size int64 `json:"size,omitempty"` +} + +var ( + // ErrNoSuchImage is the error returned when the image does not exist. + ErrNoSuchImage = errors.New("no such image") + + // ErrMissingRepo is the error returned when the remote repository is + // missing. + ErrMissingRepo = errors.New("missing remote repository e.g. 'github.com/user/repo'") + + // ErrMissingOutputStream is the error returned when no output stream + // is provided to some calls, like BuildImage. + ErrMissingOutputStream = errors.New("missing output stream") + + // ErrMultipleContexts is the error returned when both a ContextDir and + // InputStream are provided in BuildImageOptions + ErrMultipleContexts = errors.New("image build may not be provided BOTH context dir and input stream") + + // ErrMustSpecifyNames is the error rreturned when the Names field on + // ExportImagesOptions is nil or empty + ErrMustSpecifyNames = errors.New("must specify at least one name to export") +) + +// ListImagesOptions specify parameters to the ListImages function. +// +// See https://goo.gl/BVzauZ for more details. +type ListImagesOptions struct { + Filters map[string][]string + All bool + Digests bool + Filter string + Context context.Context +} + +// ListImages returns the list of available images in the server. +// +// See https://goo.gl/BVzauZ for more details. +func (c *Client) ListImages(opts ListImagesOptions) ([]APIImages, error) { + path := "/images/json?" + queryString(opts) + resp, err := c.do("GET", path, doOptions{context: opts.Context}) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var images []APIImages + if err := json.NewDecoder(resp.Body).Decode(&images); err != nil { + return nil, err + } + return images, nil +} + +// ImageHistory represent a layer in an image's history returned by the +// ImageHistory call. +type ImageHistory struct { + ID string `json:"Id" yaml:"Id" toml:"Id"` + Tags []string `json:"Tags,omitempty" yaml:"Tags,omitempty" toml:"Tags,omitempty"` + Created int64 `json:"Created,omitempty" yaml:"Created,omitempty" toml:"Tags,omitempty"` + CreatedBy string `json:"CreatedBy,omitempty" yaml:"CreatedBy,omitempty" toml:"CreatedBy,omitempty"` + Size int64 `json:"Size,omitempty" yaml:"Size,omitempty" toml:"Size,omitempty"` + Comment string `json:"Comment,omitempty" yaml:"Comment,omitempty" toml:"Comment,omitempty"` +} + +// ImageHistory returns the history of the image by its name or ID. +// +// See https://goo.gl/fYtxQa for more details. +func (c *Client) ImageHistory(name string) ([]ImageHistory, error) { + resp, err := c.do("GET", "/images/"+name+"/history", doOptions{}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return nil, ErrNoSuchImage + } + return nil, err + } + defer resp.Body.Close() + var history []ImageHistory + if err := json.NewDecoder(resp.Body).Decode(&history); err != nil { + return nil, err + } + return history, nil +} + +// RemoveImage removes an image by its name or ID. +// +// See https://goo.gl/Vd2Pck for more details. +func (c *Client) RemoveImage(name string) error { + resp, err := c.do("DELETE", "/images/"+name, doOptions{}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return ErrNoSuchImage + } + return err + } + resp.Body.Close() + return nil +} + +// RemoveImageOptions present the set of options available for removing an image +// from a registry. +// +// See https://goo.gl/Vd2Pck for more details. +type RemoveImageOptions struct { + Force bool `qs:"force"` + NoPrune bool `qs:"noprune"` + Context context.Context +} + +// RemoveImageExtended removes an image by its name or ID. +// Extra params can be passed, see RemoveImageOptions +// +// See https://goo.gl/Vd2Pck for more details. +func (c *Client) RemoveImageExtended(name string, opts RemoveImageOptions) error { + uri := fmt.Sprintf("/images/%s?%s", name, queryString(&opts)) + resp, err := c.do("DELETE", uri, doOptions{context: opts.Context}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return ErrNoSuchImage + } + return err + } + resp.Body.Close() + return nil +} + +// InspectImage returns an image by its name or ID. +// +// See https://goo.gl/ncLTG8 for more details. +func (c *Client) InspectImage(name string) (*Image, error) { + resp, err := c.do("GET", "/images/"+name+"/json", doOptions{}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return nil, ErrNoSuchImage + } + return nil, err + } + defer resp.Body.Close() + + var image Image + + // if the caller elected to skip checking the server's version, assume it's the latest + if c.SkipServerVersionCheck || c.expectedAPIVersion.GreaterThanOrEqualTo(apiVersion112) { + if err := json.NewDecoder(resp.Body).Decode(&image); err != nil { + return nil, err + } + } else { + var imagePre012 ImagePre012 + if err := json.NewDecoder(resp.Body).Decode(&imagePre012); err != nil { + return nil, err + } + + image.ID = imagePre012.ID + image.Parent = imagePre012.Parent + image.Comment = imagePre012.Comment + image.Created = imagePre012.Created + image.Container = imagePre012.Container + image.ContainerConfig = imagePre012.ContainerConfig + image.DockerVersion = imagePre012.DockerVersion + image.Author = imagePre012.Author + image.Config = imagePre012.Config + image.Architecture = imagePre012.Architecture + image.Size = imagePre012.Size + } + + return &image, nil +} + +// PushImageOptions represents options to use in the PushImage method. +// +// See https://goo.gl/BZemGg for more details. +type PushImageOptions struct { + // Name of the image + Name string + + // Tag of the image + Tag string + + // Registry server to push the image + Registry string + + OutputStream io.Writer `qs:"-"` + RawJSONStream bool `qs:"-"` + InactivityTimeout time.Duration `qs:"-"` + + Context context.Context +} + +// PushImage pushes an image to a remote registry, logging progress to w. +// +// An empty instance of AuthConfiguration may be used for unauthenticated +// pushes. +// +// See https://goo.gl/BZemGg for more details. +func (c *Client) PushImage(opts PushImageOptions, auth AuthConfiguration) error { + if opts.Name == "" { + return ErrNoSuchImage + } + headers, err := headersWithAuth(auth) + if err != nil { + return err + } + name := opts.Name + opts.Name = "" + path := "/images/" + name + "/push?" + queryString(&opts) + return c.stream("POST", path, streamOptions{ + setRawTerminal: true, + rawJSONStream: opts.RawJSONStream, + headers: headers, + stdout: opts.OutputStream, + inactivityTimeout: opts.InactivityTimeout, + context: opts.Context, + }) +} + +// PullImageOptions present the set of options available for pulling an image +// from a registry. +// +// See https://goo.gl/qkoSsn for more details. +type PullImageOptions struct { + Repository string `qs:"fromImage"` + Tag string + Platform string + + // Only required for Docker Engine 1.9 or 1.10 w/ Remote API < 1.21 + // and Docker Engine < 1.9 + // This parameter was removed in Docker Engine 1.11 + Registry string + + OutputStream io.Writer `qs:"-"` + RawJSONStream bool `qs:"-"` + InactivityTimeout time.Duration `qs:"-"` + Context context.Context +} + +// PullImage pulls an image from a remote registry, logging progress to +// opts.OutputStream. +// +// See https://goo.gl/qkoSsn for more details. +func (c *Client) PullImage(opts PullImageOptions, auth AuthConfiguration) error { + if opts.Repository == "" { + return ErrNoSuchImage + } + + headers, err := headersWithAuth(auth) + if err != nil { + return err + } + if opts.Tag == "" && strings.Contains(opts.Repository, "@") { + parts := strings.SplitN(opts.Repository, "@", 2) + opts.Repository = parts[0] + opts.Tag = parts[1] + } + return c.createImage(&opts, headers, nil, opts.OutputStream, opts.RawJSONStream, opts.InactivityTimeout, opts.Context) +} + +func (c *Client) createImage(opts interface{}, headers map[string]string, in io.Reader, w io.Writer, rawJSONStream bool, timeout time.Duration, context context.Context) error { + url, err := c.getPath("/images/create", opts) + if err != nil { + return err + } + return c.streamURL(http.MethodPost, url, streamOptions{ + setRawTerminal: true, + headers: headers, + in: in, + stdout: w, + rawJSONStream: rawJSONStream, + inactivityTimeout: timeout, + context: context, + }) +} + +// LoadImageOptions represents the options for LoadImage Docker API Call +// +// See https://goo.gl/rEsBV3 for more details. +type LoadImageOptions struct { + InputStream io.Reader + OutputStream io.Writer + Context context.Context +} + +// LoadImage imports a tarball docker image +// +// See https://goo.gl/rEsBV3 for more details. +func (c *Client) LoadImage(opts LoadImageOptions) error { + return c.stream("POST", "/images/load", streamOptions{ + setRawTerminal: true, + in: opts.InputStream, + stdout: opts.OutputStream, + context: opts.Context, + }) +} + +// ExportImageOptions represent the options for ExportImage Docker API call. +// +// See https://goo.gl/AuySaA for more details. +type ExportImageOptions struct { + Name string + OutputStream io.Writer + InactivityTimeout time.Duration + Context context.Context +} + +// ExportImage exports an image (as a tar file) into the stream. +// +// See https://goo.gl/AuySaA for more details. +func (c *Client) ExportImage(opts ExportImageOptions) error { + return c.stream("GET", fmt.Sprintf("/images/%s/get", opts.Name), streamOptions{ + setRawTerminal: true, + stdout: opts.OutputStream, + inactivityTimeout: opts.InactivityTimeout, + context: opts.Context, + }) +} + +// ExportImagesOptions represent the options for ExportImages Docker API call +// +// See https://goo.gl/N9XlDn for more details. +type ExportImagesOptions struct { + Names []string + OutputStream io.Writer `qs:"-"` + InactivityTimeout time.Duration `qs:"-"` + Context context.Context +} + +// ExportImages exports one or more images (as a tar file) into the stream +// +// See https://goo.gl/N9XlDn for more details. +func (c *Client) ExportImages(opts ExportImagesOptions) error { + if opts.Names == nil || len(opts.Names) == 0 { + return ErrMustSpecifyNames + } + // API < 1.25 allows multiple name values + // 1.25 says name must be a comma separated list + var err error + var exporturl string + if c.requestedAPIVersion.GreaterThanOrEqualTo(apiVersion125) { + str := opts.Names[0] + for _, val := range opts.Names[1:] { + str += "," + val + } + exporturl, err = c.getPath("/images/get", ExportImagesOptions{ + Names: []string{str}, + OutputStream: opts.OutputStream, + InactivityTimeout: opts.InactivityTimeout, + Context: opts.Context, + }) + } else { + exporturl, err = c.getPath("/images/get", &opts) + } + if err != nil { + return err + } + return c.streamURL(http.MethodGet, exporturl, streamOptions{ + setRawTerminal: true, + stdout: opts.OutputStream, + inactivityTimeout: opts.InactivityTimeout, + }) +} + +// ImportImageOptions present the set of informations available for importing +// an image from a source file or the stdin. +// +// See https://goo.gl/qkoSsn for more details. +type ImportImageOptions struct { + Repository string `qs:"repo"` + Source string `qs:"fromSrc"` + Tag string `qs:"tag"` + + InputStream io.Reader `qs:"-"` + OutputStream io.Writer `qs:"-"` + RawJSONStream bool `qs:"-"` + InactivityTimeout time.Duration `qs:"-"` + Context context.Context +} + +// ImportImage imports an image from a url, a file or stdin +// +// See https://goo.gl/qkoSsn for more details. +func (c *Client) ImportImage(opts ImportImageOptions) error { + if opts.Repository == "" { + return ErrNoSuchImage + } + if opts.Source != "-" { + opts.InputStream = nil + } + if opts.Source != "-" && !isURL(opts.Source) { + f, err := os.Open(opts.Source) + if err != nil { + return err + } + opts.InputStream = f + opts.Source = "-" + } + return c.createImage(&opts, nil, opts.InputStream, opts.OutputStream, opts.RawJSONStream, opts.InactivityTimeout, opts.Context) +} + +// BuildImageOptions present the set of informations available for building an +// image from a tarfile with a Dockerfile in it. +// +// For more details about the Docker building process, see +// https://goo.gl/4nYHwV. +type BuildImageOptions struct { + Name string `qs:"t"` + Dockerfile string `qs:"dockerfile" ver:"1.25"` + NoCache bool `qs:"nocache"` + CacheFrom []string `qs:"-" ver:"1.25"` + SuppressOutput bool `qs:"q"` + Pull bool `qs:"pull" ver:"1.16"` + RmTmpContainer bool `qs:"rm"` + ForceRmTmpContainer bool `qs:"forcerm" ver:"1.12"` + RawJSONStream bool `qs:"-"` + Memory int64 `qs:"memory"` + Memswap int64 `qs:"memswap"` + ShmSize int64 `qs:"shmsize"` + CPUShares int64 `qs:"cpushares"` + CPUQuota int64 `qs:"cpuquota" ver:"1.21"` + CPUPeriod int64 `qs:"cpuperiod" ver:"1.21"` + CPUSetCPUs string `qs:"cpusetcpus"` + Labels map[string]string `qs:"labels"` + InputStream io.Reader `qs:"-"` + OutputStream io.Writer `qs:"-"` + ErrorStream io.Writer `qs:"-"` + Remote string `qs:"remote"` + Auth AuthConfiguration `qs:"-"` // for older docker X-Registry-Auth header + AuthConfigs AuthConfigurations `qs:"-"` // for newer docker X-Registry-Config header + ContextDir string `qs:"-"` + Ulimits []ULimit `qs:"-" ver:"1.18"` + BuildArgs []BuildArg `qs:"-" ver:"1.21"` + NetworkMode string `qs:"networkmode" ver:"1.25"` + InactivityTimeout time.Duration `qs:"-"` + CgroupParent string `qs:"cgroupparent"` + SecurityOpt []string `qs:"securityopt"` + Target string `gs:"target"` + Version string `qs:"version"` + Platform string `qs:"platform" ver:"1.32"` + Outputs string `qs:"outputs" ver:"1.40"` + ExtraHosts string `qs:"extrahosts" ver:"1.28"` + Context context.Context +} + +// BuildArg represents arguments that can be passed to the image when building +// it from a Dockerfile. +// +// For more details about the Docker building process, see +// https://goo.gl/4nYHwV. +type BuildArg struct { + Name string `json:"Name,omitempty" yaml:"Name,omitempty" toml:"Name,omitempty"` + Value string `json:"Value,omitempty" yaml:"Value,omitempty" toml:"Value,omitempty"` +} + +// BuildImage builds an image from a tarball's url or a Dockerfile in the input +// stream. +// +// See https://goo.gl/4nYHwV for more details. +func (c *Client) BuildImage(opts BuildImageOptions) error { + if opts.OutputStream == nil { + return ErrMissingOutputStream + } + headers, err := headersWithAuth(opts.Auth, c.versionedAuthConfigs(opts.AuthConfigs)) + if err != nil { + return err + } + + if opts.Remote != "" && opts.Name == "" { + opts.Name = opts.Remote + } + if opts.InputStream != nil || opts.ContextDir != "" { + headers["Content-Type"] = "application/tar" + } else if opts.Remote == "" { + return ErrMissingRepo + } + if opts.ContextDir != "" { + if opts.InputStream != nil { + return ErrMultipleContexts + } + var err error + if opts.InputStream, err = createTarStream(opts.ContextDir, opts.Dockerfile); err != nil { + return err + } + } + qs, ver := queryStringVersion(&opts) + + if len(opts.CacheFrom) > 0 { + if b, err := json.Marshal(opts.CacheFrom); err == nil { + item := url.Values(map[string][]string{}) + item.Add("cachefrom", string(b)) + qs = fmt.Sprintf("%s&%s", qs, item.Encode()) + if ver == nil || apiVersion125.GreaterThan(ver) { + ver = apiVersion125 + } + } + } + + if len(opts.Ulimits) > 0 { + if b, err := json.Marshal(opts.Ulimits); err == nil { + item := url.Values(map[string][]string{}) + item.Add("ulimits", string(b)) + qs = fmt.Sprintf("%s&%s", qs, item.Encode()) + if ver == nil || apiVersion118.GreaterThan(ver) { + ver = apiVersion118 + } + } + } + + if len(opts.BuildArgs) > 0 { + v := make(map[string]string) + for _, arg := range opts.BuildArgs { + v[arg.Name] = arg.Value + } + if b, err := json.Marshal(v); err == nil { + item := url.Values(map[string][]string{}) + item.Add("buildargs", string(b)) + qs = fmt.Sprintf("%s&%s", qs, item.Encode()) + if ver == nil || apiVersion121.GreaterThan(ver) { + ver = apiVersion121 + } + } + } + + buildURL, err := c.pathVersionCheck("/build", qs, ver) + if err != nil { + return err + } + + return c.streamURL(http.MethodPost, buildURL, streamOptions{ + setRawTerminal: true, + rawJSONStream: opts.RawJSONStream, + headers: headers, + in: opts.InputStream, + stdout: opts.OutputStream, + stderr: opts.ErrorStream, + inactivityTimeout: opts.InactivityTimeout, + context: opts.Context, + }) +} + +func (c *Client) versionedAuthConfigs(authConfigs AuthConfigurations) registryAuth { + if c.serverAPIVersion == nil { + c.checkAPIVersion() + } + if c.serverAPIVersion != nil && c.serverAPIVersion.GreaterThanOrEqualTo(apiVersion119) { + return AuthConfigurations119(authConfigs.Configs) + } + return authConfigs +} + +// TagImageOptions present the set of options to tag an image. +// +// See https://goo.gl/prHrvo for more details. +type TagImageOptions struct { + Repo string + Tag string + Force bool + Context context.Context +} + +// TagImage adds a tag to the image identified by the given name. +// +// See https://goo.gl/prHrvo for more details. +func (c *Client) TagImage(name string, opts TagImageOptions) error { + if name == "" { + return ErrNoSuchImage + } + resp, err := c.do("POST", "/images/"+name+"/tag?"+queryString(&opts), doOptions{ + context: opts.Context, + }) + + if err != nil { + return err + } + + defer resp.Body.Close() + + if resp.StatusCode == http.StatusNotFound { + return ErrNoSuchImage + } + + return err +} + +func isURL(u string) bool { + p, err := url.Parse(u) + if err != nil { + return false + } + return p.Scheme == "http" || p.Scheme == "https" +} + +func headersWithAuth(auths ...registryAuth) (map[string]string, error) { + var headers = make(map[string]string) + + for _, auth := range auths { + if auth.isEmpty() { + continue + } + data, err := json.Marshal(auth) + if err != nil { + return nil, err + } + headers[auth.headerKey()] = base64.URLEncoding.EncodeToString(data) + } + + return headers, nil +} + +// APIImageSearch reflect the result of a search on the Docker Hub. +// +// See https://goo.gl/KLO9IZ for more details. +type APIImageSearch struct { + Description string `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"` + IsOfficial bool `json:"is_official,omitempty" yaml:"is_official,omitempty" toml:"is_official,omitempty"` + IsAutomated bool `json:"is_automated,omitempty" yaml:"is_automated,omitempty" toml:"is_automated,omitempty"` + Name string `json:"name,omitempty" yaml:"name,omitempty" toml:"name,omitempty"` + StarCount int `json:"star_count,omitempty" yaml:"star_count,omitempty" toml:"star_count,omitempty"` +} + +// SearchImages search the docker hub with a specific given term. +// +// See https://goo.gl/KLO9IZ for more details. +func (c *Client) SearchImages(term string) ([]APIImageSearch, error) { + resp, err := c.do("GET", "/images/search?term="+term, doOptions{}) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var searchResult []APIImageSearch + if err := json.NewDecoder(resp.Body).Decode(&searchResult); err != nil { + return nil, err + } + return searchResult, nil +} + +// SearchImagesEx search the docker hub with a specific given term and authentication. +// +// See https://goo.gl/KLO9IZ for more details. +func (c *Client) SearchImagesEx(term string, auth AuthConfiguration) ([]APIImageSearch, error) { + headers, err := headersWithAuth(auth) + if err != nil { + return nil, err + } + + resp, err := c.do("GET", "/images/search?term="+term, doOptions{ + headers: headers, + }) + if err != nil { + return nil, err + } + + defer resp.Body.Close() + + var searchResult []APIImageSearch + if err := json.NewDecoder(resp.Body).Decode(&searchResult); err != nil { + return nil, err + } + + return searchResult, nil +} + +// PruneImagesOptions specify parameters to the PruneImages function. +// +// See https://goo.gl/qfZlbZ for more details. +type PruneImagesOptions struct { + Filters map[string][]string + Context context.Context +} + +// PruneImagesResults specify results from the PruneImages function. +// +// See https://goo.gl/qfZlbZ for more details. +type PruneImagesResults struct { + ImagesDeleted []struct{ Untagged, Deleted string } + SpaceReclaimed int64 +} + +// PruneImages deletes images which are unused. +// +// See https://goo.gl/qfZlbZ for more details. +func (c *Client) PruneImages(opts PruneImagesOptions) (*PruneImagesResults, error) { + path := "/images/prune?" + queryString(opts) + resp, err := c.do("POST", path, doOptions{context: opts.Context}) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var results PruneImagesResults + if err := json.NewDecoder(resp.Body).Decode(&results); err != nil { + return nil, err + } + return &results, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/misc.go b/vendor/github.com/ory/dockertest/v3/docker/misc.go new file mode 100644 index 00000000..ab3b5800 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/misc.go @@ -0,0 +1,181 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2013 go-dockerclient 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 docker + +import ( + "encoding/json" + "net" + "strings" +) + +// Version returns version information about the docker server. +// +// See https://goo.gl/mU7yje for more details. +func (c *Client) Version() (*Env, error) { + resp, err := c.do("GET", "/version", doOptions{}) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var env Env + if err := env.Decode(resp.Body); err != nil { + return nil, err + } + return &env, nil +} + +// DockerInfo contains information about the Docker server +// +// See https://goo.gl/bHUoz9 for more details. +type DockerInfo struct { + ID string + Containers int + ContainersRunning int + ContainersPaused int + ContainersStopped int + Images int + Driver string + DriverStatus [][2]string + SystemStatus [][2]string + Plugins PluginsInfo + MemoryLimit bool + SwapLimit bool + KernelMemory bool + CPUCfsPeriod bool `json:"CpuCfsPeriod"` + CPUCfsQuota bool `json:"CpuCfsQuota"` + CPUShares bool + CPUSet bool + IPv4Forwarding bool + BridgeNfIptables bool + BridgeNfIP6tables bool `json:"BridgeNfIp6tables"` + Debug bool + OomKillDisable bool + ExperimentalBuild bool + NFd int + NGoroutines int + SystemTime string + ExecutionDriver string + LoggingDriver string + CgroupDriver string + NEventsListener int + KernelVersion string + OperatingSystem string + OSType string + Architecture string + IndexServerAddress string + RegistryConfig *ServiceConfig + SecurityOptions []string + NCPU int + MemTotal int64 + DockerRootDir string + HTTPProxy string `json:"HttpProxy"` + HTTPSProxy string `json:"HttpsProxy"` + NoProxy string + Name string + Labels []string + ServerVersion string + ClusterStore string + ClusterAdvertise string + Isolation string + InitBinary string + DefaultRuntime string + LiveRestoreEnabled bool + //Swarm swarm.Info +} + +// PluginsInfo is a struct with the plugins registered with the docker daemon +// +// for more information, see: https://goo.gl/bHUoz9 +type PluginsInfo struct { + // List of Volume plugins registered + Volume []string + // List of Network plugins registered + Network []string + // List of Authorization plugins registered + Authorization []string +} + +// ServiceConfig stores daemon registry services configuration. +// +// for more information, see: https://goo.gl/7iFFDz +type ServiceConfig struct { + InsecureRegistryCIDRs []*NetIPNet + IndexConfigs map[string]*IndexInfo + Mirrors []string +} + +// NetIPNet is the net.IPNet type, which can be marshalled and +// unmarshalled to JSON. +// +// for more information, see: https://goo.gl/7iFFDz +type NetIPNet net.IPNet + +// MarshalJSON returns the JSON representation of the IPNet. +func (ipnet *NetIPNet) MarshalJSON() ([]byte, error) { + return json.Marshal((*net.IPNet)(ipnet).String()) +} + +// UnmarshalJSON sets the IPNet from a byte array of JSON. +func (ipnet *NetIPNet) UnmarshalJSON(b []byte) (err error) { + var ipnetStr string + if err = json.Unmarshal(b, &ipnetStr); err == nil { + var cidr *net.IPNet + if _, cidr, err = net.ParseCIDR(ipnetStr); err == nil { + *ipnet = NetIPNet(*cidr) + } + } + return +} + +// IndexInfo contains information about a registry. +// +// for more information, see: https://goo.gl/7iFFDz +type IndexInfo struct { + Name string + Mirrors []string + Secure bool + Official bool +} + +// Info returns system-wide information about the Docker server. +// +// See https://goo.gl/ElTHi2 for more details. +func (c *Client) Info() (*DockerInfo, error) { + resp, err := c.do("GET", "/info", doOptions{}) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var info DockerInfo + if err := json.NewDecoder(resp.Body).Decode(&info); err != nil { + return nil, err + } + return &info, nil +} + +// ParseRepositoryTag gets the name of the repository and returns it splitted +// in two parts: the repository and the tag. It ignores the digest when it is +// present. +// +// Some examples: +// +// localhost.localdomain:5000/samalba/hipache:latest -> localhost.localdomain:5000/samalba/hipache, latest +// localhost.localdomain:5000/samalba/hipache -> localhost.localdomain:5000/samalba/hipache, "" +// busybox:latest@sha256:4a731fb46adc5cefe3ae374a8b6020fc1b6ad667a279647766e9a3cd89f6fa92 -> busybox, latest +func ParseRepositoryTag(repoTag string) (repository string, tag string) { + parts := strings.SplitN(repoTag, "@", 2) + repoTag = parts[0] + n := strings.LastIndex(repoTag, ":") + if n < 0 { + return repoTag, "" + } + if tag := repoTag[n+1:]; !strings.Contains(tag, "/") { + return repoTag[:n], tag + } + return repoTag, "" +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/network.go b/vendor/github.com/ory/dockertest/v3/docker/network.go new file mode 100644 index 00000000..1d7c1009 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/network.go @@ -0,0 +1,324 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2015 go-dockerclient 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 docker + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" +) + +// ErrNetworkAlreadyExists is the error returned by CreateNetwork when the +// network already exists. +var ErrNetworkAlreadyExists = errors.New("network already exists") + +// Network represents a network. +// +// See https://goo.gl/6GugX3 for more details. +type Network struct { + Name string + ID string `json:"Id"` + Scope string + Driver string + IPAM IPAMOptions + Containers map[string]Endpoint + Options map[string]string + Internal bool + EnableIPv6 bool `json:"EnableIPv6"` + Labels map[string]string +} + +// Endpoint contains network resources allocated and used for a container in a network +// +// See https://goo.gl/6GugX3 for more details. +type Endpoint struct { + Name string + ID string `json:"EndpointID"` + MacAddress string + IPv4Address string + IPv6Address string +} + +// ListNetworks returns all networks. +// +// See https://goo.gl/6GugX3 for more details. +func (c *Client) ListNetworks() ([]Network, error) { + resp, err := c.do("GET", "/networks", doOptions{}) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var networks []Network + if err := json.NewDecoder(resp.Body).Decode(&networks); err != nil { + return nil, err + } + return networks, nil +} + +// NetworkFilterOpts is an aggregation of key=value that Docker +// uses to filter networks +type NetworkFilterOpts map[string]map[string]bool + +// FilteredListNetworks returns all networks with the filters applied +// +// See goo.gl/zd2mx4 for more details. +func (c *Client) FilteredListNetworks(opts NetworkFilterOpts) ([]Network, error) { + params, err := json.Marshal(opts) + if err != nil { + return nil, err + } + path := "/networks?filters=" + string(params) + resp, err := c.do("GET", path, doOptions{}) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var networks []Network + if err := json.NewDecoder(resp.Body).Decode(&networks); err != nil { + return nil, err + } + return networks, nil +} + +// NetworkInfo returns information about a network by its ID. +// +// See https://goo.gl/6GugX3 for more details. +func (c *Client) NetworkInfo(id string) (*Network, error) { + path := "/networks/" + id + resp, err := c.do("GET", path, doOptions{}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return nil, &NoSuchNetwork{ID: id} + } + return nil, err + } + defer resp.Body.Close() + var network Network + if err := json.NewDecoder(resp.Body).Decode(&network); err != nil { + return nil, err + } + return &network, nil +} + +// CreateNetworkOptions specify parameters to the CreateNetwork function and +// (for now) is the expected body of the "create network" http request message +// +// See https://goo.gl/6GugX3 for more details. +type CreateNetworkOptions struct { + Name string `json:"Name" yaml:"Name" toml:"Name"` + Driver string `json:"Driver" yaml:"Driver" toml:"Driver"` + IPAM *IPAMOptions `json:"IPAM,omitempty" yaml:"IPAM" toml:"IPAM"` + Options map[string]interface{} `json:"Options" yaml:"Options" toml:"Options"` + Labels map[string]string `json:"Labels" yaml:"Labels" toml:"Labels"` + CheckDuplicate bool `json:"CheckDuplicate" yaml:"CheckDuplicate" toml:"CheckDuplicate"` + Internal bool `json:"Internal" yaml:"Internal" toml:"Internal"` + EnableIPv6 bool `json:"EnableIPv6" yaml:"EnableIPv6" toml:"EnableIPv6"` + Context context.Context `json:"-"` +} + +// IPAMOptions controls IP Address Management when creating a network +// +// See https://goo.gl/T8kRVH for more details. +type IPAMOptions struct { + Driver string `json:"Driver" yaml:"Driver" toml:"Driver"` + Config []IPAMConfig `json:"Config" yaml:"Config" toml:"Config"` + Options map[string]string `json:"Options" yaml:"Options" toml:"Options"` +} + +// IPAMConfig represents IPAM configurations +// +// See https://goo.gl/T8kRVH for more details. +type IPAMConfig struct { + Subnet string `json:",omitempty"` + IPRange string `json:",omitempty"` + Gateway string `json:",omitempty"` + AuxAddress map[string]string `json:"AuxiliaryAddresses,omitempty"` +} + +// CreateNetwork creates a new network, returning the network instance, +// or an error in case of failure. +// +// See https://goo.gl/6GugX3 for more details. +func (c *Client) CreateNetwork(opts CreateNetworkOptions) (*Network, error) { + resp, err := c.do( + "POST", + "/networks/create", + doOptions{ + data: opts, + context: opts.Context, + }, + ) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + type createNetworkResponse struct { + ID string + } + var ( + network Network + cnr createNetworkResponse + ) + if err := json.NewDecoder(resp.Body).Decode(&cnr); err != nil { + return nil, err + } + + network.Name = opts.Name + network.ID = cnr.ID + network.Driver = opts.Driver + + return &network, nil +} + +// RemoveNetwork removes a network or returns an error in case of failure. +// +// See https://goo.gl/6GugX3 for more details. +func (c *Client) RemoveNetwork(id string) error { + resp, err := c.do("DELETE", "/networks/"+id, doOptions{}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return &NoSuchNetwork{ID: id} + } + return err + } + resp.Body.Close() + return nil +} + +// NetworkConnectionOptions specify parameters to the ConnectNetwork and +// DisconnectNetwork function. +// +// See https://goo.gl/RV7BJU for more details. +type NetworkConnectionOptions struct { + Container string + + // EndpointConfig is only applicable to the ConnectNetwork call + EndpointConfig *EndpointConfig `json:"EndpointConfig,omitempty"` + + // Force is only applicable to the DisconnectNetwork call + Force bool + + Context context.Context `json:"-"` +} + +// EndpointConfig stores network endpoint details +// +// See https://goo.gl/RV7BJU for more details. +type EndpointConfig struct { + IPAMConfig *EndpointIPAMConfig `json:"IPAMConfig,omitempty" yaml:"IPAMConfig,omitempty" toml:"IPAMConfig,omitempty"` + Links []string `json:"Links,omitempty" yaml:"Links,omitempty" toml:"Links,omitempty"` + Aliases []string `json:"Aliases,omitempty" yaml:"Aliases,omitempty" toml:"Aliases,omitempty"` + NetworkID string `json:"NetworkID,omitempty" yaml:"NetworkID,omitempty" toml:"NetworkID,omitempty"` + EndpointID string `json:"EndpointID,omitempty" yaml:"EndpointID,omitempty" toml:"EndpointID,omitempty"` + Gateway string `json:"Gateway,omitempty" yaml:"Gateway,omitempty" toml:"Gateway,omitempty"` + IPAddress string `json:"IPAddress,omitempty" yaml:"IPAddress,omitempty" toml:"IPAddress,omitempty"` + IPPrefixLen int `json:"IPPrefixLen,omitempty" yaml:"IPPrefixLen,omitempty" toml:"IPPrefixLen,omitempty"` + IPv6Gateway string `json:"IPv6Gateway,omitempty" yaml:"IPv6Gateway,omitempty" toml:"IPv6Gateway,omitempty"` + GlobalIPv6Address string `json:"GlobalIPv6Address,omitempty" yaml:"GlobalIPv6Address,omitempty" toml:"GlobalIPv6Address,omitempty"` + GlobalIPv6PrefixLen int `json:"GlobalIPv6PrefixLen,omitempty" yaml:"GlobalIPv6PrefixLen,omitempty" toml:"GlobalIPv6PrefixLen,omitempty"` + MacAddress string `json:"MacAddress,omitempty" yaml:"MacAddress,omitempty" toml:"MacAddress,omitempty"` +} + +// EndpointIPAMConfig represents IPAM configurations for an +// endpoint +// +// See https://goo.gl/RV7BJU for more details. +type EndpointIPAMConfig struct { + IPv4Address string `json:",omitempty"` + IPv6Address string `json:",omitempty"` +} + +// ConnectNetwork adds a container to a network or returns an error in case of +// failure. +// +// See https://goo.gl/6GugX3 for more details. +func (c *Client) ConnectNetwork(id string, opts NetworkConnectionOptions) error { + resp, err := c.do("POST", "/networks/"+id+"/connect", doOptions{ + data: opts, + context: opts.Context, + }) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return &NoSuchNetworkOrContainer{NetworkID: id, ContainerID: opts.Container} + } + return err + } + resp.Body.Close() + return nil +} + +// DisconnectNetwork removes a container from a network or returns an error in +// case of failure. +// +// See https://goo.gl/6GugX3 for more details. +func (c *Client) DisconnectNetwork(id string, opts NetworkConnectionOptions) error { + resp, err := c.do("POST", "/networks/"+id+"/disconnect", doOptions{data: opts}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return &NoSuchNetworkOrContainer{NetworkID: id, ContainerID: opts.Container} + } + return err + } + resp.Body.Close() + return nil +} + +// PruneNetworksOptions specify parameters to the PruneNetworks function. +// +// See https://goo.gl/kX0S9h for more details. +type PruneNetworksOptions struct { + Filters map[string][]string + Context context.Context +} + +// PruneNetworksResults specify results from the PruneNetworks function. +// +// See https://goo.gl/kX0S9h for more details. +type PruneNetworksResults struct { + NetworksDeleted []string +} + +// PruneNetworks deletes networks which are unused. +// +// See https://goo.gl/kX0S9h for more details. +func (c *Client) PruneNetworks(opts PruneNetworksOptions) (*PruneNetworksResults, error) { + path := "/networks/prune?" + queryString(opts) + resp, err := c.do("POST", path, doOptions{context: opts.Context}) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var results PruneNetworksResults + if err := json.NewDecoder(resp.Body).Decode(&results); err != nil { + return nil, err + } + return &results, nil +} + +// NoSuchNetwork is the error returned when a given network does not exist. +type NoSuchNetwork struct { + ID string +} + +func (err *NoSuchNetwork) Error() string { + return fmt.Sprintf("No such network: %s", err.ID) +} + +// NoSuchNetworkOrContainer is the error returned when a given network or +// container does not exist. +type NoSuchNetworkOrContainer struct { + NetworkID string + ContainerID string +} + +func (err *NoSuchNetworkOrContainer) Error() string { + return fmt.Sprintf("No such network (%s) or container (%s)", err.NetworkID, err.ContainerID) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/opts/env.go b/vendor/github.com/ory/dockertest/v3/docker/opts/env.go new file mode 100644 index 00000000..74101f4a --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/opts/env.go @@ -0,0 +1,49 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package opts + +import ( + "fmt" + "os" + "runtime" + "strings" +) + +// ValidateEnv validates an environment variable and returns it. +// If no value is specified, it returns the current value using os.Getenv. +// +// As on ParseEnvFile and related to #16585, environment variable names +// are not validate what so ever, it's up to application inside docker +// to validate them or not. +// +// The only validation here is to check if name is empty, per #25099 +func ValidateEnv(val string) (string, error) { + arr := strings.Split(val, "=") + if arr[0] == "" { + return "", fmt.Errorf("invalid environment variable: %s", val) + } + if len(arr) > 1 { + return val, nil + } + if !doesEnvExist(val) { + return val, nil + } + return fmt.Sprintf("%s=%s", val, os.Getenv(val)), nil +} + +func doesEnvExist(name string) bool { + for _, entry := range os.Environ() { + parts := strings.SplitN(entry, "=", 2) + if runtime.GOOS == "windows" { + // Environment variable are case-insensitive on Windows. PaTh, path and PATH are equivalent. + if strings.EqualFold(parts[0], name) { + return true + } + } + if parts[0] == name { + return true + } + } + return false +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/opts/hosts.go b/vendor/github.com/ory/dockertest/v3/docker/opts/hosts.go new file mode 100644 index 00000000..41aaf318 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/opts/hosts.go @@ -0,0 +1,190 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package opts + +import ( + "fmt" + "net" + "net/url" + "os" + "strconv" + "strings" +) + +const ( + dockerSocket = "/var/run/docker.sock" + podmanSocket = "/podman/podman.sock" +) + +var ( + // DefaultHTTPPort Default HTTP Port used if only the protocol is provided to -H flag e.g. dockerd -H tcp:// + // These are the IANA registered port numbers for use with Docker + // see http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml?search=docker + DefaultHTTPPort = 2375 // Default HTTP Port + // DefaultTLSHTTPPort Default HTTP Port used when TLS enabled + DefaultTLSHTTPPort = 2376 // Default TLS encrypted HTTP Port + // DefaultUnixSocket Path for the unix socket. + DefaultUnixSocket = getDefaultSocket() + // DefaultTCPHost constant defines the default host string used by docker on Windows + DefaultTCPHost = fmt.Sprintf("tcp://%s:%d", DefaultHTTPHost, DefaultHTTPPort) + // DefaultTLSHost constant defines the default host string used by docker for TLS sockets + DefaultTLSHost = fmt.Sprintf("tcp://%s:%d", DefaultHTTPHost, DefaultTLSHTTPPort) + // DefaultNamedPipe defines the default named pipe used by docker on Windows + DefaultNamedPipe = `//./pipe/docker_engine` +) + +// ValidateHost validates that the specified string is a valid host and returns it. +func ValidateHost(val string) (string, error) { + host := strings.TrimSpace(val) + // The empty string means default and is not handled by parseDaemonHost + if host != "" { + _, err := parseDaemonHost(host) + if err != nil { + return val, err + } + } + // Note: unlike most flag validators, we don't return the mutated value here + // we need to know what the user entered later (using ParseHost) to adjust for TLS + return val, nil +} + +// ParseHost and set defaults for a Daemon host string +func ParseHost(defaultToTLS bool, val string) (string, error) { + host := strings.TrimSpace(val) + if host == "" { + if defaultToTLS { + host = DefaultTLSHost + } else { + host = DefaultHost + } + } else { + var err error + host, err = parseDaemonHost(host) + if err != nil { + return val, err + } + } + return host, nil +} + +// parseDaemonHost parses the specified address and returns an address that will be used as the host. +// Depending of the address specified, this may return one of the global Default* strings defined in hosts.go. +func parseDaemonHost(addr string) (string, error) { + addrParts := strings.SplitN(addr, "://", 2) + if len(addrParts) == 1 && addrParts[0] != "" { + addrParts = []string{"tcp", addrParts[0]} + } + + switch addrParts[0] { + case "tcp": + return ParseTCPAddr(addrParts[1], DefaultTCPHost) + case "unix": + return parseSimpleProtoAddr("unix", addrParts[1], DefaultUnixSocket) + case "npipe": + return parseSimpleProtoAddr("npipe", addrParts[1], DefaultNamedPipe) + case "fd": + return addr, nil + default: + return "", fmt.Errorf("Invalid bind address format: %s", addr) + } +} + +// parseSimpleProtoAddr parses and validates that the specified address is a valid +// socket address for simple protocols like unix and npipe. It returns a formatted +// socket address, either using the address parsed from addr, or the contents of +// defaultAddr if addr is a blank string. +func parseSimpleProtoAddr(proto, addr, defaultAddr string) (string, error) { + addr = strings.TrimPrefix(addr, proto+"://") + if strings.Contains(addr, "://") { + return "", fmt.Errorf("Invalid proto, expected %s: %s", proto, addr) + } + if addr == "" { + addr = defaultAddr + } + return fmt.Sprintf("%s://%s", proto, addr), nil +} + +// ParseTCPAddr parses and validates that the specified address is a valid TCP +// address. It returns a formatted TCP address, either using the address parsed +// from tryAddr, or the contents of defaultAddr if tryAddr is a blank string. +// tryAddr is expected to have already been Trim()'d +// defaultAddr must be in the full `tcp://host:port` form +func ParseTCPAddr(tryAddr string, defaultAddr string) (string, error) { + if tryAddr == "" || tryAddr == "tcp://" { + return defaultAddr, nil + } + addr := strings.TrimPrefix(tryAddr, "tcp://") + if strings.Contains(addr, "://") || addr == "" { + return "", fmt.Errorf("Invalid proto, expected tcp: %s", tryAddr) + } + + defaultAddr = strings.TrimPrefix(defaultAddr, "tcp://") + defaultHost, defaultPort, err := net.SplitHostPort(defaultAddr) + if err != nil { + return "", err + } + // url.Parse fails for trailing colon on IPv6 brackets on Go 1.5, but + // not 1.4. See https://github.com/golang/go/issues/12200 and + // https://github.com/golang/go/issues/6530. + if strings.HasSuffix(addr, "]:") { + addr += defaultPort + } + + u, err := url.Parse("tcp://" + addr) + if err != nil { + return "", err + } + host, port, err := net.SplitHostPort(u.Host) + if err != nil { + // try port addition once + host, port, err = net.SplitHostPort(net.JoinHostPort(u.Host, defaultPort)) + } + if err != nil { + return "", fmt.Errorf("Invalid bind address format: %s", tryAddr) + } + + if host == "" { + host = defaultHost + } + if port == "" { + port = defaultPort + } + p, err := strconv.Atoi(port) + if err != nil && p == 0 { + return "", fmt.Errorf("Invalid bind address format: %s", tryAddr) + } + + return fmt.Sprintf("tcp://%s%s", net.JoinHostPort(host, port), u.Path), nil +} + +// ValidateExtraHost validates that the specified string is a valid extrahost and returns it. +// ExtraHost is in the form of name:ip where the ip has to be a valid ip (IPv4 or IPv6). +func ValidateExtraHost(val string) (string, error) { + // allow for IPv6 addresses in extra hosts by only splitting on first ":" + arr := strings.SplitN(val, ":", 2) + if len(arr) != 2 || len(arr[0]) == 0 { + return "", fmt.Errorf("bad format for add-host: %q", val) + } + if _, err := ValidateIPAddress(arr[1]); err != nil { + return "", fmt.Errorf("invalid IP address in add-host: %q", arr[1]) + } + return val, nil +} + +func getDefaultSocket() string { + _, err := os.Stat(dockerSocket) + if err == nil { + return dockerSocket + } + // see https://docs.podman.io/en/latest/markdown/podman-system-service.1.html#description + locations := []string{os.Getenv("XDG_RUNTIME_DIR"), "/run"} // rootless, rootful + for _, location := range locations { + _, err = os.Stat(location + podmanSocket) + if err == nil { + return location + podmanSocket + } + } + + return dockerSocket +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/opts/hosts_unix.go b/vendor/github.com/ory/dockertest/v3/docker/opts/hosts_unix.go new file mode 100644 index 00000000..2ce2e6de --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/opts/hosts_unix.go @@ -0,0 +1,12 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package opts + +import "fmt" + +// DefaultHost constant defines the default host string used by docker on other hosts than Windows +var DefaultHost = fmt.Sprintf("unix://%s", DefaultUnixSocket) diff --git a/vendor/github.com/ory/dockertest/v3/docker/opts/hosts_windows.go b/vendor/github.com/ory/dockertest/v3/docker/opts/hosts_windows.go new file mode 100644 index 00000000..f69da848 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/opts/hosts_windows.go @@ -0,0 +1,7 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package opts + +// DefaultHost constant defines the default host string used by docker on Windows +var DefaultHost = "npipe://" + DefaultNamedPipe diff --git a/vendor/github.com/ory/dockertest/v3/docker/opts/ip.go b/vendor/github.com/ory/dockertest/v3/docker/opts/ip.go new file mode 100644 index 00000000..3746c5da --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/opts/ip.go @@ -0,0 +1,50 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package opts + +import ( + "fmt" + "net" +) + +// IPOpt holds an IP. It is used to store values from CLI flags. +type IPOpt struct { + *net.IP +} + +// NewIPOpt creates a new IPOpt from a reference net.IP and a +// string representation of an IP. If the string is not a valid +// IP it will fallback to the specified reference. +func NewIPOpt(ref *net.IP, defaultVal string) *IPOpt { + o := &IPOpt{ + IP: ref, + } + o.Set(defaultVal) + return o +} + +// Set sets an IPv4 or IPv6 address from a given string. If the given +// string is not parsable as an IP address it returns an error. +func (o *IPOpt) Set(val string) error { + ip := net.ParseIP(val) + if ip == nil { + return fmt.Errorf("%s is not an ip address", val) + } + *o.IP = ip + return nil +} + +// String returns the IP address stored in the IPOpt. If stored IP is a +// nil pointer, it returns an empty string. +func (o *IPOpt) String() string { + if *o.IP == nil { + return "" + } + return o.IP.String() +} + +// Type returns the type of the option +func (o *IPOpt) Type() string { + return "ip" +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/opts/opts.go b/vendor/github.com/ory/dockertest/v3/docker/opts/opts.go new file mode 100644 index 00000000..99e1b40c --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/opts/opts.go @@ -0,0 +1,351 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package opts + +import ( + "fmt" + "net" + "path" + "regexp" + "strings" + + "github.com/docker/cli/cli/compose/loader" + units "github.com/docker/go-units" +) + +var ( + alphaRegexp = regexp.MustCompile(`[a-zA-Z]`) + domainRegexp = regexp.MustCompile(`^(:?(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]))(:?\.(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])))*)\.?\s*$`) +) + +// ListOpts holds a list of values and a validation function. +type ListOpts struct { + values *[]string + validator ValidatorFctType +} + +// NewListOpts creates a new ListOpts with the specified validator. +func NewListOpts(validator ValidatorFctType) ListOpts { + var values []string + return *NewListOptsRef(&values, validator) +} + +// NewListOptsRef creates a new ListOpts with the specified values and validator. +func NewListOptsRef(values *[]string, validator ValidatorFctType) *ListOpts { + return &ListOpts{ + values: values, + validator: validator, + } +} + +func (opts *ListOpts) String() string { + if len(*opts.values) == 0 { + return "" + } + return fmt.Sprintf("%v", *opts.values) +} + +// Set validates if needed the input value and adds it to the +// internal slice. +func (opts *ListOpts) Set(value string) error { + if opts.validator != nil { + v, err := opts.validator(value) + if err != nil { + return err + } + value = v + } + (*opts.values) = append((*opts.values), value) + return nil +} + +// Delete removes the specified element from the slice. +func (opts *ListOpts) Delete(key string) { + for i, k := range *opts.values { + if k == key { + (*opts.values) = append((*opts.values)[:i], (*opts.values)[i+1:]...) + return + } + } +} + +// GetMap returns the content of values in a map in order to avoid +// duplicates. +func (opts *ListOpts) GetMap() map[string]struct{} { + ret := make(map[string]struct{}) + for _, k := range *opts.values { + ret[k] = struct{}{} + } + return ret +} + +// GetAll returns the values of slice. +func (opts *ListOpts) GetAll() []string { + return (*opts.values) +} + +// GetAllOrEmpty returns the values of the slice +// or an empty slice when there are no values. +func (opts *ListOpts) GetAllOrEmpty() []string { + v := *opts.values + if v == nil { + return make([]string, 0) + } + return v +} + +// Get checks the existence of the specified key. +func (opts *ListOpts) Get(key string) bool { + for _, k := range *opts.values { + if k == key { + return true + } + } + return false +} + +// Len returns the amount of element in the slice. +func (opts *ListOpts) Len() int { + return len((*opts.values)) +} + +// Type returns a string name for this Option type +func (opts *ListOpts) Type() string { + return "list" +} + +// WithValidator returns the ListOpts with validator set. +func (opts *ListOpts) WithValidator(validator ValidatorFctType) *ListOpts { + opts.validator = validator + return opts +} + +// NamedOption is an interface that list and map options +// with names implement. +type NamedOption interface { + Name() string +} + +// NamedListOpts is a ListOpts with a configuration name. +// This struct is useful to keep reference to the assigned +// field name in the internal configuration struct. +type NamedListOpts struct { + name string + ListOpts +} + +var _ NamedOption = &NamedListOpts{} + +// NewNamedListOptsRef creates a reference to a new NamedListOpts struct. +func NewNamedListOptsRef(name string, values *[]string, validator ValidatorFctType) *NamedListOpts { + return &NamedListOpts{ + name: name, + ListOpts: *NewListOptsRef(values, validator), + } +} + +// Name returns the name of the NamedListOpts in the configuration. +func (o *NamedListOpts) Name() string { + return o.name +} + +// MapOpts holds a map of values and a validation function. +type MapOpts struct { + values map[string]string + validator ValidatorFctType +} + +// Set validates if needed the input value and add it to the +// internal map, by splitting on '='. +func (opts *MapOpts) Set(value string) error { + if opts.validator != nil { + v, err := opts.validator(value) + if err != nil { + return err + } + value = v + } + vals := strings.SplitN(value, "=", 2) + if len(vals) == 1 { + (opts.values)[vals[0]] = "" + } else { + (opts.values)[vals[0]] = vals[1] + } + return nil +} + +// GetAll returns the values of MapOpts as a map. +func (opts *MapOpts) GetAll() map[string]string { + return opts.values +} + +func (opts *MapOpts) String() string { + return fmt.Sprintf("%v", opts.values) +} + +// Type returns a string name for this Option type +func (opts *MapOpts) Type() string { + return "map" +} + +// NewMapOpts creates a new MapOpts with the specified map of values and a validator. +func NewMapOpts(values map[string]string, validator ValidatorFctType) *MapOpts { + if values == nil { + values = make(map[string]string) + } + return &MapOpts{ + values: values, + validator: validator, + } +} + +// NamedMapOpts is a MapOpts struct with a configuration name. +// This struct is useful to keep reference to the assigned +// field name in the internal configuration struct. +type NamedMapOpts struct { + name string + MapOpts +} + +var _ NamedOption = &NamedMapOpts{} + +// NewNamedMapOpts creates a reference to a new NamedMapOpts struct. +func NewNamedMapOpts(name string, values map[string]string, validator ValidatorFctType) *NamedMapOpts { + return &NamedMapOpts{ + name: name, + MapOpts: *NewMapOpts(values, validator), + } +} + +// Name returns the name of the NamedMapOpts in the configuration. +func (o *NamedMapOpts) Name() string { + return o.name +} + +// ValidatorFctType defines a validator function that returns a validated string and/or an error. +type ValidatorFctType func(val string) (string, error) + +// ValidatorFctListType defines a validator function that returns a validated list of string and/or an error +type ValidatorFctListType func(val string) ([]string, error) + +// ValidateIPAddress validates an Ip address. +func ValidateIPAddress(val string) (string, error) { + var ip = net.ParseIP(strings.TrimSpace(val)) + if ip != nil { + return ip.String(), nil + } + return "", fmt.Errorf("%s is not an ip address", val) +} + +// ValidateDNSSearch validates domain for resolvconf search configuration. +// A zero length domain is represented by a dot (.). +func ValidateDNSSearch(val string) (string, error) { + if val = strings.Trim(val, " "); val == "." { + return val, nil + } + return validateDomain(val) +} + +func validateDomain(val string) (string, error) { + if alphaRegexp.FindString(val) == "" { + return "", fmt.Errorf("%s is not a valid domain", val) + } + ns := domainRegexp.FindSubmatch([]byte(val)) + if len(ns) > 0 && len(ns[1]) < 255 { + return string(ns[1]), nil + } + return "", fmt.Errorf("%s is not a valid domain", val) +} + +// ValidateLabel validates that the specified string is a valid label, and returns it. +// Labels are in the form on key=value. +func ValidateLabel(val string) (string, error) { + if strings.Count(val, "=") < 1 { + return "", fmt.Errorf("bad attribute format: %s", val) + } + return val, nil +} + +// ValidateSingleGenericResource validates that a single entry in the +// generic resource list is valid. +// i.e 'GPU=UID1' is valid however 'GPU:UID1' or 'UID1' isn't +func ValidateSingleGenericResource(val string) (string, error) { + if strings.Count(val, "=") < 1 { + return "", fmt.Errorf("invalid node-generic-resource format `%s` expected `name=value`", val) + } + return val, nil +} + +// ParseLink parses and validates the specified string as a link format (name:alias) +func ParseLink(val string) (string, string, error) { + if val == "" { + return "", "", fmt.Errorf("empty string specified for links") + } + arr := strings.Split(val, ":") + if len(arr) > 2 { + return "", "", fmt.Errorf("bad format for links: %s", val) + } + if len(arr) == 1 { + return val, val, nil + } + // This is kept because we can actually get a HostConfig with links + // from an already created container and the format is not `foo:bar` + // but `/foo:/c1/bar` + if strings.HasPrefix(arr[0], "/") { + _, alias := path.Split(arr[1]) + return arr[0][1:], alias, nil + } + return arr[0], arr[1], nil +} + +// MemBytes is a type for human readable memory bytes (like 128M, 2g, etc) +type MemBytes int64 + +// String returns the string format of the human readable memory bytes +func (m *MemBytes) String() string { + // NOTE: In spf13/pflag/flag.go, "0" is considered as "zero value" while "0 B" is not. + // We return "0" in case value is 0 here so that the default value is hidden. + // (Sometimes "default 0 B" is actually misleading) + if m.Value() != 0 { + return units.BytesSize(float64(m.Value())) + } + return "0" +} + +// Set sets the value of the MemBytes by passing a string +func (m *MemBytes) Set(value string) error { + val, err := units.RAMInBytes(value) + *m = MemBytes(val) + return err +} + +// Type returns the type +func (m *MemBytes) Type() string { + return "bytes" +} + +// Value returns the value in int64 +func (m *MemBytes) Value() int64 { + return int64(*m) +} + +// UnmarshalJSON is the customized unmarshaler for MemBytes +func (m *MemBytes) UnmarshalJSON(s []byte) error { + if len(s) <= 2 || s[0] != '"' || s[len(s)-1] != '"' { + return fmt.Errorf("invalid size: %q", s) + } + val, err := units.RAMInBytes(string(s[1 : len(s)-1])) + *m = MemBytes(val) + return err +} + +// MountParser parses mount path. +func MountParser(mount string) (source, destination string, err error) { + spec, err := loader.ParseVolume(mount) + if err != nil { + return "", "", fmt.Errorf("Failed to parse mount: %w", err) + } + + return spec.Source, spec.Target, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/opts/opts_unix.go b/vendor/github.com/ory/dockertest/v3/docker/opts/opts_unix.go new file mode 100644 index 00000000..2dac59ba --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/opts/opts_unix.go @@ -0,0 +1,10 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package opts + +// DefaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. dockerd -H tcp://:8080 +const DefaultHTTPHost = "localhost" diff --git a/vendor/github.com/ory/dockertest/v3/docker/opts/opts_windows.go b/vendor/github.com/ory/dockertest/v3/docker/opts/opts_windows.go new file mode 100644 index 00000000..df4ee7b3 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/opts/opts_windows.go @@ -0,0 +1,59 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package opts + +// TODO Windows. Identify bug in GOLang 1.5.1+ and/or Windows Server 2016 TP5. +// @jhowardmsft, @swernli. +// +// On Windows, this mitigates a problem with the default options of running +// a docker client against a local docker daemon on TP5. +// +// What was found that if the default host is "localhost", even if the client +// (and daemon as this is local) is not physically on a network, and the DNS +// cache is flushed (ipconfig /flushdns), then the client will pause for +// exactly one second when connecting to the daemon for calls. For example +// using docker run windowsservercore cmd, the CLI will send a create followed +// by an attach. You see the delay between the attach finishing and the attach +// being seen by the daemon. +// +// Here's some daemon debug logs with additional debug spew put in. The +// AfterWriteJSON log is the very last thing the daemon does as part of the +// create call. The POST /attach is the second CLI call. Notice the second +// time gap. +// +// time="2015-11-06T13:38:37.259627400-08:00" level=debug msg="After createRootfs" +// time="2015-11-06T13:38:37.263626300-08:00" level=debug msg="After setHostConfig" +// time="2015-11-06T13:38:37.267631200-08:00" level=debug msg="before createContainerPl...." +// time="2015-11-06T13:38:37.271629500-08:00" level=debug msg=ToDiskLocking.... +// time="2015-11-06T13:38:37.275643200-08:00" level=debug msg="loggin event...." +// time="2015-11-06T13:38:37.277627600-08:00" level=debug msg="logged event...." +// time="2015-11-06T13:38:37.279631800-08:00" level=debug msg="In defer func" +// time="2015-11-06T13:38:37.282628100-08:00" level=debug msg="After daemon.create" +// time="2015-11-06T13:38:37.286651700-08:00" level=debug msg="return 2" +// time="2015-11-06T13:38:37.289629500-08:00" level=debug msg="Returned from daemon.ContainerCreate" +// time="2015-11-06T13:38:37.311629100-08:00" level=debug msg="After WriteJSON" +// ... 1 second gap here.... +// time="2015-11-06T13:38:38.317866200-08:00" level=debug msg="Calling POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach" +// time="2015-11-06T13:38:38.326882500-08:00" level=info msg="POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach?stderr=1&stdin=1&stdout=1&stream=1" +// +// We suspect this is either a bug introduced in GOLang 1.5.1, or that a change +// in GOLang 1.5.1 (from 1.4.3) is exposing a bug in Windows. In theory, +// the Windows networking stack is supposed to resolve "localhost" internally, +// without hitting DNS, or even reading the hosts file (which is why localhost +// is commented out in the hosts file on Windows). +// +// We have validated that working around this using the actual IPv4 localhost +// address does not cause the delay. +// +// This does not occur with the docker client built with 1.4.3 on the same +// Windows build, regardless of whether the daemon is built using 1.5.1 +// or 1.4.3. It does not occur on Linux. We also verified we see the same thing +// on a cross-compiled Windows binary (from Linux). +// +// Final note: This is a mitigation, not a 'real' fix. It is still susceptible +// to the delay if a user were to do 'docker run -H=tcp://localhost:2375...' +// explicitly. + +// DefaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. dockerd -H tcp://:8080 +const DefaultHTTPHost = "127.0.0.1" diff --git a/vendor/github.com/ory/dockertest/v3/docker/opts/quotedstring.go b/vendor/github.com/ory/dockertest/v3/docker/opts/quotedstring.go new file mode 100644 index 00000000..17957ea0 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/opts/quotedstring.go @@ -0,0 +1,40 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package opts + +// QuotedString is a string that may have extra quotes around the value. The +// quotes are stripped from the value. +type QuotedString struct { + value *string +} + +// Set sets a new value +func (s *QuotedString) Set(val string) error { + *s.value = trimQuotes(val) + return nil +} + +// Type returns the type of the value +func (s *QuotedString) Type() string { + return "string" +} + +func (s *QuotedString) String() string { + return *s.value +} + +func trimQuotes(value string) string { + lastIndex := len(value) - 1 + for _, char := range []byte{'\'', '"'} { + if value[0] == char && value[lastIndex] == char { + return value[1:lastIndex] + } + } + return value +} + +// NewQuotedString returns a new quoted string option +func NewQuotedString(value *string) *QuotedString { + return &QuotedString{value: value} +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/opts/runtime.go b/vendor/github.com/ory/dockertest/v3/docker/opts/runtime.go new file mode 100644 index 00000000..db6e9b77 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/opts/runtime.go @@ -0,0 +1,82 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package opts + +import ( + "fmt" + "strings" + + "github.com/ory/dockertest/v3/docker/types" +) + +// RuntimeOpt defines a map of Runtimes +type RuntimeOpt struct { + name string + stockRuntimeName string + values *map[string]types.Runtime +} + +// NewNamedRuntimeOpt creates a new RuntimeOpt +func NewNamedRuntimeOpt(name string, ref *map[string]types.Runtime, stockRuntime string) *RuntimeOpt { + if ref == nil { + ref = &map[string]types.Runtime{} + } + return &RuntimeOpt{name: name, values: ref, stockRuntimeName: stockRuntime} +} + +// Name returns the name of the NamedListOpts in the configuration. +func (o *RuntimeOpt) Name() string { + return o.name +} + +// Set validates and updates the list of Runtimes +func (o *RuntimeOpt) Set(val string) error { + parts := strings.SplitN(val, "=", 2) + if len(parts) != 2 { + return fmt.Errorf("invalid runtime argument: %s", val) + } + + parts[0] = strings.TrimSpace(parts[0]) + parts[1] = strings.TrimSpace(parts[1]) + if parts[0] == "" || parts[1] == "" { + return fmt.Errorf("invalid runtime argument: %s", val) + } + + parts[0] = strings.ToLower(parts[0]) + if parts[0] == o.stockRuntimeName { + return fmt.Errorf("runtime name '%s' is reserved", o.stockRuntimeName) + } + + if _, ok := (*o.values)[parts[0]]; ok { + return fmt.Errorf("runtime '%s' was already defined", parts[0]) + } + + (*o.values)[parts[0]] = types.Runtime{Path: parts[1]} + + return nil +} + +// String returns Runtime values as a string. +func (o *RuntimeOpt) String() string { + var out []string + for k := range *o.values { + out = append(out, k) + } + + return fmt.Sprintf("%v", out) +} + +// GetMap returns a map of Runtimes (name: path) +func (o *RuntimeOpt) GetMap() map[string]types.Runtime { + if o.values != nil { + return *o.values + } + + return map[string]types.Runtime{} +} + +// Type returns the type of the option +func (o *RuntimeOpt) Type() string { + return "runtime" +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/opts/ulimit.go b/vendor/github.com/ory/dockertest/v3/docker/opts/ulimit.go new file mode 100644 index 00000000..5161f002 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/opts/ulimit.go @@ -0,0 +1,84 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package opts + +import ( + "fmt" + + "github.com/docker/go-units" +) + +// UlimitOpt defines a map of Ulimits +type UlimitOpt struct { + values *map[string]*units.Ulimit +} + +// NewUlimitOpt creates a new UlimitOpt +func NewUlimitOpt(ref *map[string]*units.Ulimit) *UlimitOpt { + if ref == nil { + ref = &map[string]*units.Ulimit{} + } + return &UlimitOpt{ref} +} + +// Set validates a Ulimit and sets its name as a key in UlimitOpt +func (o *UlimitOpt) Set(val string) error { + l, err := units.ParseUlimit(val) + if err != nil { + return err + } + + (*o.values)[l.Name] = l + + return nil +} + +// String returns Ulimit values as a string. +func (o *UlimitOpt) String() string { + var out []string + for _, v := range *o.values { + out = append(out, v.String()) + } + + return fmt.Sprintf("%v", out) +} + +// GetList returns a slice of pointers to Ulimits. +func (o *UlimitOpt) GetList() []*units.Ulimit { + var ulimits []*units.Ulimit + for _, v := range *o.values { + ulimits = append(ulimits, v) + } + + return ulimits +} + +// Type returns the option type +func (o *UlimitOpt) Type() string { + return "ulimit" +} + +// NamedUlimitOpt defines a named map of Ulimits +type NamedUlimitOpt struct { + name string + UlimitOpt +} + +var _ NamedOption = &NamedUlimitOpt{} + +// NewNamedUlimitOpt creates a new NamedUlimitOpt +func NewNamedUlimitOpt(name string, ref *map[string]*units.Ulimit) *NamedUlimitOpt { + if ref == nil { + ref = &map[string]*units.Ulimit{} + } + return &NamedUlimitOpt{ + name: name, + UlimitOpt: *NewUlimitOpt(ref), + } +} + +// Name returns the option name +func (o *NamedUlimitOpt) Name() string { + return o.name +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/README.md b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/README.md new file mode 100644 index 00000000..7307d969 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/README.md @@ -0,0 +1 @@ +This code provides helper functions for dealing with archive files. diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive.go new file mode 100644 index 00000000..dcfbcdbb --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive.go @@ -0,0 +1,1285 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "archive/tar" + "bufio" + "bytes" + "compress/bzip2" + "compress/gzip" + "context" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "syscall" + + "github.com/ory/dockertest/v3/docker/pkg/fileutils" + "github.com/ory/dockertest/v3/docker/pkg/idtools" + "github.com/ory/dockertest/v3/docker/pkg/ioutils" + "github.com/ory/dockertest/v3/docker/pkg/pools" + "github.com/ory/dockertest/v3/docker/pkg/system" + "github.com/sirupsen/logrus" +) + +var unpigzPath string + +func init() { + if path, err := exec.LookPath("unpigz"); err != nil { + logrus.Debug("unpigz binary not found in PATH, falling back to go gzip library") + } else { + logrus.Debugf("Using unpigz binary found at path %s", path) + unpigzPath = path + } +} + +type ( + // Compression is the state represents if compressed or not. + Compression int + // WhiteoutFormat is the format of whiteouts unpacked + WhiteoutFormat int + + // TarOptions wraps the tar options. + TarOptions struct { + IncludeFiles []string + ExcludePatterns []string + Compression Compression + NoLchown bool + UIDMaps []idtools.IDMap + GIDMaps []idtools.IDMap + ChownOpts *idtools.IDPair + IncludeSourceDir bool + // WhiteoutFormat is the expected on disk format for whiteout files. + // This format will be converted to the standard format on pack + // and from the standard format on unpack. + WhiteoutFormat WhiteoutFormat + // When unpacking, specifies whether overwriting a directory with a + // non-directory is allowed and vice versa. + NoOverwriteDirNonDir bool + // For each include when creating an archive, the included name will be + // replaced with the matching name from this map. + RebaseNames map[string]string + InUserNS bool + } +) + +// Archiver implements the Archiver interface and allows the reuse of most utility functions of +// this package with a pluggable Untar function. Also, to facilitate the passing of specific id +// mappings for untar, an Archiver can be created with maps which will then be passed to Untar operations. +type Archiver struct { + Untar func(io.Reader, string, *TarOptions) error + IDMappingsVar *idtools.IDMappings +} + +// NewDefaultArchiver returns a new Archiver without any IDMappings +func NewDefaultArchiver() *Archiver { + return &Archiver{Untar: Untar, IDMappingsVar: &idtools.IDMappings{}} +} + +// breakoutError is used to differentiate errors related to breaking out +// When testing archive breakout in the unit tests, this error is expected +// in order for the test to pass. +type breakoutError error + +const ( + // Uncompressed represents the uncompressed. + Uncompressed Compression = iota + // Bzip2 is bzip2 compression algorithm. + Bzip2 + // Gzip is gzip compression algorithm. + Gzip + // Xz is xz compression algorithm. + Xz +) + +const ( + // AUFSWhiteoutFormat is the default format for whiteouts + AUFSWhiteoutFormat WhiteoutFormat = iota + // OverlayWhiteoutFormat formats whiteout according to the overlay + // standard. + OverlayWhiteoutFormat +) + +const ( + modeISDIR = 040000 // Directory + modeISFIFO = 010000 // FIFO + modeISREG = 0100000 // Regular file + modeISLNK = 0120000 // Symbolic link + modeISBLK = 060000 // Block special file + modeISCHR = 020000 // Character special file + modeISSOCK = 0140000 // Socket +) + +// IsArchivePath checks if the (possibly compressed) file at the given path +// starts with a tar file header. +func IsArchivePath(path string) bool { + file, err := os.Open(path) + if err != nil { + return false + } + defer file.Close() + rdr, err := DecompressStream(file) + if err != nil { + return false + } + r := tar.NewReader(rdr) + _, err = r.Next() + return err == nil +} + +// DetectCompression detects the compression algorithm of the source. +func DetectCompression(source []byte) Compression { + for compression, m := range map[Compression][]byte{ + Bzip2: {0x42, 0x5A, 0x68}, + Gzip: {0x1F, 0x8B, 0x08}, + Xz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00}, + } { + if len(source) < len(m) { + logrus.Debug("Len too short") + continue + } + if bytes.Equal(m, source[:len(m)]) { + return compression + } + } + return Uncompressed +} + +func xzDecompress(ctx context.Context, archive io.Reader) (io.ReadCloser, error) { + args := []string{"xz", "-d", "-c", "-q"} + + return cmdStream(exec.CommandContext(ctx, args[0], args[1:]...), archive) +} + +func gzDecompress(ctx context.Context, buf io.Reader) (io.ReadCloser, error) { + if unpigzPath == "" { + return gzip.NewReader(buf) + } + + disablePigzEnv := os.Getenv("MOBY_DISABLE_PIGZ") + if disablePigzEnv != "" { + if disablePigz, err := strconv.ParseBool(disablePigzEnv); err != nil { + return nil, err + } else if disablePigz { + return gzip.NewReader(buf) + } + } + + return cmdStream(exec.CommandContext(ctx, unpigzPath, "-d", "-c"), buf) +} + +func wrapReadCloser(readBuf io.ReadCloser, cancel context.CancelFunc) io.ReadCloser { + return ioutils.NewReadCloserWrapper(readBuf, func() error { + cancel() + return readBuf.Close() + }) +} + +// DecompressStream decompresses the archive and returns a ReaderCloser with the decompressed archive. +func DecompressStream(archive io.Reader) (io.ReadCloser, error) { + p := pools.BufioReader32KPool + buf := p.Get(archive) + bs, err := buf.Peek(10) + if err != nil && err != io.EOF { + // Note: we'll ignore any io.EOF error because there are some odd + // cases where the layer.tar file will be empty (zero bytes) and + // that results in an io.EOF from the Peek() call. So, in those + // cases we'll just treat it as a non-compressed stream and + // that means just create an empty layer. + // See Issue 18170 + return nil, err + } + + compression := DetectCompression(bs) + switch compression { + case Uncompressed: + readBufWrapper := p.NewReadCloserWrapper(buf, buf) + return readBufWrapper, nil + case Gzip: + ctx, cancel := context.WithCancel(context.Background()) + + gzReader, err := gzDecompress(ctx, buf) + if err != nil { + cancel() + return nil, err + } + readBufWrapper := p.NewReadCloserWrapper(buf, gzReader) + return wrapReadCloser(readBufWrapper, cancel), nil + case Bzip2: + bz2Reader := bzip2.NewReader(buf) + readBufWrapper := p.NewReadCloserWrapper(buf, bz2Reader) + return readBufWrapper, nil + case Xz: + ctx, cancel := context.WithCancel(context.Background()) + + xzReader, err := xzDecompress(ctx, buf) + if err != nil { + cancel() + return nil, err + } + readBufWrapper := p.NewReadCloserWrapper(buf, xzReader) + return wrapReadCloser(readBufWrapper, cancel), nil + default: + return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) + } +} + +// CompressStream compresses the dest with specified compression algorithm. +func CompressStream(dest io.Writer, compression Compression) (io.WriteCloser, error) { + p := pools.BufioWriter32KPool + buf := p.Get(dest) + switch compression { + case Uncompressed: + writeBufWrapper := p.NewWriteCloserWrapper(buf, buf) + return writeBufWrapper, nil + case Gzip: + gzWriter := gzip.NewWriter(dest) + writeBufWrapper := p.NewWriteCloserWrapper(buf, gzWriter) + return writeBufWrapper, nil + case Bzip2, Xz: + // archive/bzip2 does not support writing, and there is no xz support at all + // However, this is not a problem as docker only currently generates gzipped tars + return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) + default: + return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) + } +} + +// TarModifierFunc is a function that can be passed to ReplaceFileTarWrapper to +// modify the contents or header of an entry in the archive. If the file already +// exists in the archive the TarModifierFunc will be called with the Header and +// a reader which will return the files content. If the file does not exist both +// header and content will be nil. +type TarModifierFunc func(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) + +// ReplaceFileTarWrapper converts inputTarStream to a new tar stream. Files in the +// tar stream are modified if they match any of the keys in mods. +func ReplaceFileTarWrapper(inputTarStream io.ReadCloser, mods map[string]TarModifierFunc) io.ReadCloser { + pipeReader, pipeWriter := io.Pipe() + + go func() { + tarReader := tar.NewReader(inputTarStream) + tarWriter := tar.NewWriter(pipeWriter) + defer inputTarStream.Close() + defer tarWriter.Close() + + modify := func(name string, original *tar.Header, modifier TarModifierFunc, tarReader io.Reader) error { + header, data, err := modifier(name, original, tarReader) + switch { + case err != nil: + return err + case header == nil: + return nil + } + + header.Name = name + header.Size = int64(len(data)) + if err := tarWriter.WriteHeader(header); err != nil { + return err + } + if len(data) != 0 { + if _, err := tarWriter.Write(data); err != nil { + return err + } + } + return nil + } + + var err error + var originalHeader *tar.Header + for { + originalHeader, err = tarReader.Next() + if err == io.EOF { + break + } + if err != nil { + pipeWriter.CloseWithError(err) + return + } + + modifier, ok := mods[originalHeader.Name] + if !ok { + // No modifiers for this file, copy the header and data + if err := tarWriter.WriteHeader(originalHeader); err != nil { + pipeWriter.CloseWithError(err) + return + } + if _, err := pools.Copy(tarWriter, tarReader); err != nil { + pipeWriter.CloseWithError(err) + return + } + continue + } + delete(mods, originalHeader.Name) + + if err := modify(originalHeader.Name, originalHeader, modifier, tarReader); err != nil { + pipeWriter.CloseWithError(err) + return + } + } + + // Apply the modifiers that haven't matched any files in the archive + for name, modifier := range mods { + if err := modify(name, nil, modifier, nil); err != nil { + pipeWriter.CloseWithError(err) + return + } + } + + pipeWriter.Close() + + }() + return pipeReader +} + +// Extension returns the extension of a file that uses the specified compression algorithm. +func (compression *Compression) Extension() string { + switch *compression { + case Uncompressed: + return "tar" + case Bzip2: + return "tar.bz2" + case Gzip: + return "tar.gz" + case Xz: + return "tar.xz" + } + return "" +} + +// FileInfoHeader creates a populated Header from fi. +// Compared to archive pkg this function fills in more information. +// Also, regardless of Go version, this function fills file type bits (e.g. hdr.Mode |= modeISDIR), +// which have been deleted since Go 1.9 archive/tar. +func FileInfoHeader(name string, fi os.FileInfo, link string) (*tar.Header, error) { + hdr, err := tar.FileInfoHeader(fi, link) + if err != nil { + return nil, err + } + hdr.Mode = fillGo18FileTypeBits(int64(chmodTarEntry(os.FileMode(hdr.Mode))), fi) + name, err = canonicalTarName(name, fi.IsDir()) + if err != nil { + return nil, fmt.Errorf("tar: cannot canonicalize path: %v", err) + } + hdr.Name = name + if err := setHeaderForSpecialDevice(hdr, name, fi.Sys()); err != nil { + return nil, err + } + return hdr, nil +} + +// fillGo18FileTypeBits fills type bits which have been removed on Go 1.9 archive/tar +// https://github.com/golang/go/commit/66b5a2f +func fillGo18FileTypeBits(mode int64, fi os.FileInfo) int64 { + fm := fi.Mode() + switch { + case fm.IsRegular(): + mode |= modeISREG + case fi.IsDir(): + mode |= modeISDIR + case fm&os.ModeSymlink != 0: + mode |= modeISLNK + case fm&os.ModeDevice != 0: + if fm&os.ModeCharDevice != 0 { + mode |= modeISCHR + } else { + mode |= modeISBLK + } + case fm&os.ModeNamedPipe != 0: + mode |= modeISFIFO + case fm&os.ModeSocket != 0: + mode |= modeISSOCK + } + return mode +} + +// ReadSecurityXattrToTarHeader reads security.capability xattr from filesystem +// to a tar header +func ReadSecurityXattrToTarHeader(path string, hdr *tar.Header) error { + capability, _ := system.Lgetxattr(path, "security.capability") + if capability != nil { + hdr.Xattrs = make(map[string]string) + hdr.Xattrs["security.capability"] = string(capability) + } + return nil +} + +type tarWhiteoutConverter interface { + ConvertWrite(*tar.Header, string, os.FileInfo) (*tar.Header, error) + ConvertRead(*tar.Header, string) (bool, error) +} + +type tarAppender struct { + TarWriter *tar.Writer + Buffer *bufio.Writer + + // for hardlink mapping + SeenFiles map[uint64]string + IDMappings *idtools.IDMappings + ChownOpts *idtools.IDPair + + // For packing and unpacking whiteout files in the + // non standard format. The whiteout files defined + // by the AUFS standard are used as the tar whiteout + // standard. + WhiteoutConverter tarWhiteoutConverter +} + +func newTarAppender(idMapping *idtools.IDMappings, writer io.Writer, chownOpts *idtools.IDPair) *tarAppender { + return &tarAppender{ + SeenFiles: make(map[uint64]string), + TarWriter: tar.NewWriter(writer), + Buffer: pools.BufioWriter32KPool.Get(nil), + IDMappings: idMapping, + ChownOpts: chownOpts, + } +} + +// canonicalTarName provides a platform-independent and consistent posix-style +// path for files and directories to be archived regardless of the platform. +func canonicalTarName(name string, isDir bool) (string, error) { + name, err := CanonicalTarNameForPath(name) + if err != nil { + return "", err + } + + // suffix with '/' for directories + if isDir && !strings.HasSuffix(name, "/") { + name += "/" + } + return name, nil +} + +// addTarFile adds to the tar archive a file from `path` as `name` +func (ta *tarAppender) addTarFile(path, name string) error { + fi, err := os.Lstat(path) + if err != nil { + return err + } + + var link string + if fi.Mode()&os.ModeSymlink != 0 { + var err error + link, err = os.Readlink(path) + if err != nil { + return err + } + } + + hdr, err := FileInfoHeader(name, fi, link) + if err != nil { + return err + } + if err := ReadSecurityXattrToTarHeader(path, hdr); err != nil { + return err + } + + // if it's not a directory and has more than 1 link, + // it's hard linked, so set the type flag accordingly + if !fi.IsDir() && hasHardlinks(fi) { + inode, err := getInodeFromStat(fi.Sys()) + if err != nil { + return err + } + // a link should have a name that it links too + // and that linked name should be first in the tar archive + if oldpath, ok := ta.SeenFiles[inode]; ok { + hdr.Typeflag = tar.TypeLink + hdr.Linkname = oldpath + hdr.Size = 0 // This Must be here for the writer math to add up! + } else { + ta.SeenFiles[inode] = name + } + } + + //check whether the file is overlayfs whiteout + //if yes, skip re-mapping container ID mappings. + isOverlayWhiteout := fi.Mode()&os.ModeCharDevice != 0 && hdr.Devmajor == 0 && hdr.Devminor == 0 + + //handle re-mapping container ID mappings back to host ID mappings before + //writing tar headers/files. We skip whiteout files because they were written + //by the kernel and already have proper ownership relative to the host + if !isOverlayWhiteout && + !strings.HasPrefix(filepath.Base(hdr.Name), WhiteoutPrefix) && + !ta.IDMappings.Empty() { + fileIDPair, err := getFileUIDGID(fi.Sys()) + if err != nil { + return err + } + hdr.Uid, hdr.Gid, err = ta.IDMappings.ToContainer(fileIDPair) + if err != nil { + return err + } + } + + // explicitly override with ChownOpts + if ta.ChownOpts != nil { + hdr.Uid = ta.ChownOpts.UID + hdr.Gid = ta.ChownOpts.GID + } + + if ta.WhiteoutConverter != nil { + wo, err := ta.WhiteoutConverter.ConvertWrite(hdr, path, fi) + if err != nil { + return err + } + + // If a new whiteout file exists, write original hdr, then + // replace hdr with wo to be written after. Whiteouts should + // always be written after the original. Note the original + // hdr may have been updated to be a whiteout with returning + // a whiteout header + if wo != nil { + if err := ta.TarWriter.WriteHeader(hdr); err != nil { + return err + } + if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 { + return fmt.Errorf("tar: cannot use whiteout for non-empty file") + } + hdr = wo + } + } + + if err := ta.TarWriter.WriteHeader(hdr); err != nil { + return err + } + + if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 { + // We use system.OpenSequential to ensure we use sequential file + // access on Windows to avoid depleting the standby list. + // On Linux, this equates to a regular os.Open. + file, err := system.OpenSequential(path) + if err != nil { + return err + } + + ta.Buffer.Reset(ta.TarWriter) + defer ta.Buffer.Reset(nil) + _, err = io.Copy(ta.Buffer, file) + file.Close() + if err != nil { + return err + } + err = ta.Buffer.Flush() + if err != nil { + return err + } + } + + return nil +} + +func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, Lchown bool, chownOpts *idtools.IDPair, inUserns bool) error { + // hdr.Mode is in linux format, which we can use for sycalls, + // but for os.Foo() calls we need the mode converted to os.FileMode, + // so use hdrInfo.Mode() (they differ for e.g. setuid bits) + hdrInfo := hdr.FileInfo() + + switch hdr.Typeflag { + case tar.TypeDir: + // Create directory unless it exists as a directory already. + // In that case we just want to merge the two + if fi, err := os.Lstat(path); !(err == nil && fi.IsDir()) { + if err := os.Mkdir(path, hdrInfo.Mode()); err != nil { + return err + } + } + + case tar.TypeReg, tar.TypeRegA: + // Source is regular file. We use system.OpenFileSequential to use sequential + // file access to avoid depleting the standby list on Windows. + // On Linux, this equates to a regular os.OpenFile + file, err := system.OpenFileSequential(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode()) + if err != nil { + return err + } + if _, err := io.Copy(file, reader); err != nil { + file.Close() + return err + } + file.Close() + + case tar.TypeBlock, tar.TypeChar: + if inUserns { // cannot create devices in a userns + return nil + } + // Handle this is an OS-specific way + if err := handleTarTypeBlockCharFifo(hdr, path); err != nil { + return err + } + + case tar.TypeFifo: + // Handle this is an OS-specific way + if err := handleTarTypeBlockCharFifo(hdr, path); err != nil { + return err + } + + case tar.TypeLink: + targetPath := filepath.Join(extractDir, hdr.Linkname) + // check for hardlink breakout + if !strings.HasPrefix(targetPath, extractDir) { + return breakoutError(fmt.Errorf("invalid hardlink %q -> %q", targetPath, hdr.Linkname)) + } + if err := os.Link(targetPath, path); err != nil { + return err + } + + case tar.TypeSymlink: + // path -> hdr.Linkname = targetPath + // e.g. /extractDir/path/to/symlink -> ../2/file = /extractDir/path/2/file + targetPath := filepath.Join(filepath.Dir(path), hdr.Linkname) + + // the reason we don't need to check symlinks in the path (with FollowSymlinkInScope) is because + // that symlink would first have to be created, which would be caught earlier, at this very check: + if !strings.HasPrefix(targetPath, extractDir) { + return breakoutError(fmt.Errorf("invalid symlink %q -> %q", path, hdr.Linkname)) + } + if err := os.Symlink(hdr.Linkname, path); err != nil { + return err + } + + case tar.TypeXGlobalHeader: + logrus.Debug("PAX Global Extended Headers found and ignored") + return nil + + default: + return fmt.Errorf("unhandled tar header type %d", hdr.Typeflag) + } + + // Lchown is not supported on Windows. + if Lchown && runtime.GOOS != "windows" { + if chownOpts == nil { + chownOpts = &idtools.IDPair{UID: hdr.Uid, GID: hdr.Gid} + } + if err := os.Lchown(path, chownOpts.UID, chownOpts.GID); err != nil { + return err + } + } + + var errors []string + for key, value := range hdr.Xattrs { + if err := system.Lsetxattr(path, key, []byte(value), 0); err != nil { + if err == syscall.ENOTSUP { + // We ignore errors here because not all graphdrivers support + // xattrs *cough* old versions of AUFS *cough*. However only + // ENOTSUP should be emitted in that case, otherwise we still + // bail. + errors = append(errors, err.Error()) + continue + } + return err + } + + } + + if len(errors) > 0 { + logrus.WithFields(logrus.Fields{ + "errors": errors, + }).Warn("ignored xattrs in archive: underlying filesystem doesn't support them") + } + + // There is no LChmod, so ignore mode for symlink. Also, this + // must happen after chown, as that can modify the file mode + if err := handleLChmod(hdr, path, hdrInfo); err != nil { + return err + } + + aTime := hdr.AccessTime + if aTime.Before(hdr.ModTime) { + // Last access time should never be before last modified time. + aTime = hdr.ModTime + } + + // system.Chtimes doesn't support a NOFOLLOW flag atm + if hdr.Typeflag == tar.TypeLink { + if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { + if err := system.Chtimes(path, aTime, hdr.ModTime); err != nil { + return err + } + } + } else if hdr.Typeflag != tar.TypeSymlink { + if err := system.Chtimes(path, aTime, hdr.ModTime); err != nil { + return err + } + } else { + ts := []syscall.Timespec{timeToTimespec(aTime), timeToTimespec(hdr.ModTime)} + if err := system.LUtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform { + return err + } + } + return nil +} + +// Tar creates an archive from the directory at `path`, and returns it as a +// stream of bytes. +func Tar(path string, compression Compression) (io.ReadCloser, error) { + return TarWithOptions(path, &TarOptions{Compression: compression}) +} + +// TarWithOptions creates an archive from the directory at `path`, only including files whose relative +// paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`. +func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) { + + // Fix the source path to work with long path names. This is a no-op + // on platforms other than Windows. + srcPath = fixVolumePathPrefix(srcPath) + + pm, err := fileutils.NewPatternMatcher(options.ExcludePatterns) + if err != nil { + return nil, err + } + + pipeReader, pipeWriter := io.Pipe() + + compressWriter, err := CompressStream(pipeWriter, options.Compression) + if err != nil { + return nil, err + } + + go func() { + ta := newTarAppender( + idtools.NewIDMappingsFromMaps(options.UIDMaps, options.GIDMaps), + compressWriter, + options.ChownOpts, + ) + ta.WhiteoutConverter = getWhiteoutConverter(options.WhiteoutFormat) + + defer func() { + // Make sure to check the error on Close. + if err := ta.TarWriter.Close(); err != nil { + logrus.Errorf("Can't close tar writer: %s", err) + } + if err := compressWriter.Close(); err != nil { + logrus.Errorf("Can't close compress writer: %s", err) + } + if err := pipeWriter.Close(); err != nil { + logrus.Errorf("Can't close pipe writer: %s", err) + } + }() + + // this buffer is needed for the duration of this piped stream + defer pools.BufioWriter32KPool.Put(ta.Buffer) + + // In general we log errors here but ignore them because + // during e.g. a diff operation the container can continue + // mutating the filesystem and we can see transient errors + // from this + + stat, err := os.Lstat(srcPath) + if err != nil { + return + } + + if !stat.IsDir() { + // We can't later join a non-dir with any includes because the + // 'walk' will error if "file/." is stat-ed and "file" is not a + // directory. So, we must split the source path and use the + // basename as the include. + if len(options.IncludeFiles) > 0 { + logrus.Warn("Tar: Can't archive a file with includes") + } + + dir, base := SplitPathDirEntry(srcPath) + srcPath = dir + options.IncludeFiles = []string{base} + } + + if len(options.IncludeFiles) == 0 { + options.IncludeFiles = []string{"."} + } + + seen := make(map[string]bool) + + for _, include := range options.IncludeFiles { + rebaseName := options.RebaseNames[include] + + walkRoot := getWalkRoot(srcPath, include) + filepath.Walk(walkRoot, func(filePath string, f os.FileInfo, err error) error { + if err != nil { + logrus.Errorf("Tar: Can't stat file %s to tar: %s", srcPath, err) + return nil + } + + relFilePath, err := filepath.Rel(srcPath, filePath) + if err != nil || (!options.IncludeSourceDir && relFilePath == "." && f.IsDir()) { + // Error getting relative path OR we are looking + // at the source directory path. Skip in both situations. + return nil + } + + if options.IncludeSourceDir && include == "." && relFilePath != "." { + relFilePath = strings.Join([]string{".", relFilePath}, string(filepath.Separator)) + } + + skip := false + + // If "include" is an exact match for the current file + // then even if there's an "excludePatterns" pattern that + // matches it, don't skip it. IOW, assume an explicit 'include' + // is asking for that file no matter what - which is true + // for some files, like .dockerignore and Dockerfile (sometimes) + if include != relFilePath { + skip, err = pm.Matches(relFilePath) + if err != nil { + logrus.Errorf("Error matching %s: %v", relFilePath, err) + return err + } + } + + if skip { + // If we want to skip this file and its a directory + // then we should first check to see if there's an + // excludes pattern (e.g. !dir/file) that starts with this + // dir. If so then we can't skip this dir. + + // Its not a dir then so we can just return/skip. + if !f.IsDir() { + return nil + } + + // No exceptions (!...) in patterns so just skip dir + if !pm.Exclusions() { + return filepath.SkipDir + } + + dirSlash := relFilePath + string(filepath.Separator) + + for _, pat := range pm.Patterns() { + if !pat.Exclusion() { + continue + } + if strings.HasPrefix(pat.String()+string(filepath.Separator), dirSlash) { + // found a match - so can't skip this dir + return nil + } + } + + // No matching exclusion dir so just skip dir + return filepath.SkipDir + } + + if seen[relFilePath] { + return nil + } + seen[relFilePath] = true + + // Rename the base resource. + if rebaseName != "" { + var replacement string + if rebaseName != string(filepath.Separator) { + // Special case the root directory to replace with an + // empty string instead so that we don't end up with + // double slashes in the paths. + replacement = rebaseName + } + + relFilePath = strings.Replace(relFilePath, include, replacement, 1) + } + + if err := ta.addTarFile(filePath, relFilePath); err != nil { + logrus.Errorf("Can't add file %s to tar: %s", filePath, err) + // if pipe is broken, stop writing tar stream to it + if err == io.ErrClosedPipe { + return err + } + } + return nil + }) + } + }() + + return pipeReader, nil +} + +// Unpack unpacks the decompressedArchive to dest with options. +func Unpack(decompressedArchive io.Reader, dest string, options *TarOptions) error { + tr := tar.NewReader(decompressedArchive) + trBuf := pools.BufioReader32KPool.Get(nil) + defer pools.BufioReader32KPool.Put(trBuf) + + var dirs []*tar.Header + idMappings := idtools.NewIDMappingsFromMaps(options.UIDMaps, options.GIDMaps) + rootIDs := idMappings.RootPair() + whiteoutConverter := getWhiteoutConverter(options.WhiteoutFormat) + + // Iterate through the files in the archive. +loop: + for { + hdr, err := tr.Next() + if err == io.EOF { + // end of tar archive + break + } + if err != nil { + return err + } + + // Normalize name, for safety and for a simple is-root check + // This keeps "../" as-is, but normalizes "/../" to "/". Or Windows: + // This keeps "..\" as-is, but normalizes "\..\" to "\". + hdr.Name = filepath.Clean(hdr.Name) + + for _, exclude := range options.ExcludePatterns { + if strings.HasPrefix(hdr.Name, exclude) { + continue loop + } + } + + // After calling filepath.Clean(hdr.Name) above, hdr.Name will now be in + // the filepath format for the OS on which the daemon is running. Hence + // the check for a slash-suffix MUST be done in an OS-agnostic way. + if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { + // Not the root directory, ensure that the parent directory exists + parent := filepath.Dir(hdr.Name) + parentPath := filepath.Join(dest, parent) + if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { + err = idtools.MkdirAllAndChownNew(parentPath, 0777, rootIDs) + if err != nil { + return err + } + } + } + + path := filepath.Join(dest, hdr.Name) + rel, err := filepath.Rel(dest, path) + if err != nil { + return err + } + if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { + return breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) + } + + // If path exits we almost always just want to remove and replace it + // The only exception is when it is a directory *and* the file from + // the layer is also a directory. Then we want to merge them (i.e. + // just apply the metadata from the layer). + if fi, err := os.Lstat(path); err == nil { + if options.NoOverwriteDirNonDir && fi.IsDir() && hdr.Typeflag != tar.TypeDir { + // If NoOverwriteDirNonDir is true then we cannot replace + // an existing directory with a non-directory from the archive. + return fmt.Errorf("cannot overwrite directory %q with non-directory %q", path, dest) + } + + if options.NoOverwriteDirNonDir && !fi.IsDir() && hdr.Typeflag == tar.TypeDir { + // If NoOverwriteDirNonDir is true then we cannot replace + // an existing non-directory with a directory from the archive. + return fmt.Errorf("cannot overwrite non-directory %q with directory %q", path, dest) + } + + if fi.IsDir() && hdr.Name == "." { + continue + } + + if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) { + if err := os.RemoveAll(path); err != nil { + return err + } + } + } + trBuf.Reset(tr) + + if err := remapIDs(idMappings, hdr); err != nil { + return err + } + + if whiteoutConverter != nil { + writeFile, err := whiteoutConverter.ConvertRead(hdr, path) + if err != nil { + return err + } + if !writeFile { + continue + } + } + + if err := createTarFile(path, dest, hdr, trBuf, !options.NoLchown, options.ChownOpts, options.InUserNS); err != nil { + return err + } + + // Directory mtimes must be handled at the end to avoid further + // file creation in them to modify the directory mtime + if hdr.Typeflag == tar.TypeDir { + dirs = append(dirs, hdr) + } + } + + for _, hdr := range dirs { + path := filepath.Join(dest, hdr.Name) + + if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { + return err + } + } + return nil +} + +// Untar reads a stream of bytes from `archive`, parses it as a tar archive, +// and unpacks it into the directory at `dest`. +// The archive may be compressed with one of the following algorithms: +// +// identity (uncompressed), gzip, bzip2, xz. +// +// FIXME: specify behavior when target path exists vs. doesn't exist. +func Untar(tarArchive io.Reader, dest string, options *TarOptions) error { + return untarHandler(tarArchive, dest, options, true) +} + +// UntarUncompressed reads a stream of bytes from `archive`, parses it as a tar archive, +// and unpacks it into the directory at `dest`. +// The archive must be an uncompressed stream. +func UntarUncompressed(tarArchive io.Reader, dest string, options *TarOptions) error { + return untarHandler(tarArchive, dest, options, false) +} + +// Handler for teasing out the automatic decompression +func untarHandler(tarArchive io.Reader, dest string, options *TarOptions, decompress bool) error { + if tarArchive == nil { + return fmt.Errorf("Empty archive") + } + dest = filepath.Clean(dest) + if options == nil { + options = &TarOptions{} + } + if options.ExcludePatterns == nil { + options.ExcludePatterns = []string{} + } + + r := tarArchive + if decompress { + decompressedArchive, err := DecompressStream(tarArchive) + if err != nil { + return err + } + defer decompressedArchive.Close() + r = decompressedArchive + } + + return Unpack(r, dest, options) +} + +// TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other. +// If either Tar or Untar fails, TarUntar aborts and returns the error. +func (archiver *Archiver) TarUntar(src, dst string) error { + logrus.Debugf("TarUntar(%s %s)", src, dst) + archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed}) + if err != nil { + return err + } + defer archive.Close() + options := &TarOptions{ + UIDMaps: archiver.IDMappingsVar.UIDs(), + GIDMaps: archiver.IDMappingsVar.GIDs(), + } + return archiver.Untar(archive, dst, options) +} + +// UntarPath untar a file from path to a destination, src is the source tar file path. +func (archiver *Archiver) UntarPath(src, dst string) error { + archive, err := os.Open(src) + if err != nil { + return err + } + defer archive.Close() + options := &TarOptions{ + UIDMaps: archiver.IDMappingsVar.UIDs(), + GIDMaps: archiver.IDMappingsVar.GIDs(), + } + return archiver.Untar(archive, dst, options) +} + +// CopyWithTar creates a tar archive of filesystem path `src`, and +// unpacks it at filesystem path `dst`. +// The archive is streamed directly with fixed buffering and no +// intermediary disk IO. +func (archiver *Archiver) CopyWithTar(src, dst string) error { + srcSt, err := os.Stat(src) + if err != nil { + return err + } + if !srcSt.IsDir() { + return archiver.CopyFileWithTar(src, dst) + } + + // if this Archiver is set up with ID mapping we need to create + // the new destination directory with the remapped root UID/GID pair + // as owner + rootIDs := archiver.IDMappingsVar.RootPair() + // Create dst, copy src's content into it + logrus.Debugf("Creating dest directory: %s", dst) + if err := idtools.MkdirAllAndChownNew(dst, 0755, rootIDs); err != nil { + return err + } + logrus.Debugf("Calling TarUntar(%s, %s)", src, dst) + return archiver.TarUntar(src, dst) +} + +// CopyFileWithTar emulates the behavior of the 'cp' command-line +// for a single file. It copies a regular file from path `src` to +// path `dst`, and preserves all its metadata. +func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { + logrus.Debugf("CopyFileWithTar(%s, %s)", src, dst) + srcSt, err := os.Stat(src) + if err != nil { + return err + } + + if srcSt.IsDir() { + return fmt.Errorf("Can't copy a directory") + } + + // Clean up the trailing slash. This must be done in an operating + // system specific manner. + if dst[len(dst)-1] == os.PathSeparator { + dst = filepath.Join(dst, filepath.Base(src)) + } + // Create the holding directory if necessary + if err := system.MkdirAll(filepath.Dir(dst), 0700, ""); err != nil { + return err + } + + r, w := io.Pipe() + errC := make(chan error, 1) + + go func() { + defer close(errC) + + errC <- func() error { + defer w.Close() + + srcF, err := os.Open(src) + if err != nil { + return err + } + defer srcF.Close() + + hdr, err := tar.FileInfoHeader(srcSt, "") + if err != nil { + return err + } + hdr.Name = filepath.Base(dst) + hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) + + if err := remapIDs(archiver.IDMappingsVar, hdr); err != nil { + return err + } + + tw := tar.NewWriter(w) + defer tw.Close() + if err := tw.WriteHeader(hdr); err != nil { + return err + } + if _, err := io.Copy(tw, srcF); err != nil { + return err + } + return nil + }() + }() + defer func() { + if er := <-errC; err == nil && er != nil { + err = er + } + }() + + err = archiver.Untar(r, filepath.Dir(dst), nil) + if err != nil { + r.CloseWithError(err) + } + return err +} + +// IDMappings returns the IDMappings of the archiver. +func (archiver *Archiver) IDMappings() *idtools.IDMappings { + return archiver.IDMappingsVar +} + +func remapIDs(idMappings *idtools.IDMappings, hdr *tar.Header) error { + ids, err := idMappings.ToHost(idtools.IDPair{UID: hdr.Uid, GID: hdr.Gid}) + hdr.Uid, hdr.Gid = ids.UID, ids.GID + return err +} + +// cmdStream executes a command, and returns its stdout as a stream. +// If the command fails to run or doesn't complete successfully, an error +// will be returned, including anything written on stderr. +func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) { + cmd.Stdin = input + pipeR, pipeW := io.Pipe() + cmd.Stdout = pipeW + var errBuf bytes.Buffer + cmd.Stderr = &errBuf + + // Run the command and return the pipe + if err := cmd.Start(); err != nil { + return nil, err + } + + // Copy stdout to the returned pipe + go func() { + if err := cmd.Wait(); err != nil { + pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errBuf.String())) + } else { + pipeW.Close() + } + }() + + return pipeR, nil +} + +// NewTempArchive reads the content of src into a temporary file, and returns the contents +// of that file as an archive. The archive can only be read once - as soon as reading completes, +// the file will be deleted. +func NewTempArchive(src io.Reader, dir string) (*TempArchive, error) { + f, err := os.CreateTemp(dir, "") + if err != nil { + return nil, err + } + if _, err := io.Copy(f, src); err != nil { + return nil, err + } + if _, err := f.Seek(0, 0); err != nil { + return nil, err + } + st, err := f.Stat() + if err != nil { + return nil, err + } + size := st.Size() + return &TempArchive{File: f, Size: size}, nil +} + +// TempArchive is a temporary archive. The archive can only be read once - as soon as reading completes, +// the file will be deleted. +type TempArchive struct { + *os.File + Size int64 // Pre-computed from Stat().Size() as a convenience + read int64 + closed bool +} + +// Close closes the underlying file if it's still open, or does a no-op +// to allow callers to try to close the TempArchive multiple times safely. +func (archive *TempArchive) Close() error { + if archive.closed { + return nil + } + + archive.closed = true + + return archive.File.Close() +} + +func (archive *TempArchive) Read(data []byte) (int, error) { + n, err := archive.File.Read(data) + archive.read += int64(n) + if err != nil || archive.read == archive.Size { + archive.Close() + os.Remove(archive.File.Name()) + } + return n, err +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive_linux.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive_linux.go new file mode 100644 index 00000000..e751b09c --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive_linux.go @@ -0,0 +1,95 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "archive/tar" + "os" + "path/filepath" + "strings" + + "github.com/ory/dockertest/v3/docker/pkg/system" + "golang.org/x/sys/unix" +) + +func getWhiteoutConverter(format WhiteoutFormat) tarWhiteoutConverter { + if format == OverlayWhiteoutFormat { + return overlayWhiteoutConverter{} + } + return nil +} + +type overlayWhiteoutConverter struct{} + +func (overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, path string, fi os.FileInfo) (wo *tar.Header, err error) { + // convert whiteouts to AUFS format + if fi.Mode()&os.ModeCharDevice != 0 && hdr.Devmajor == 0 && hdr.Devminor == 0 { + // we just rename the file and make it normal + dir, filename := filepath.Split(hdr.Name) + hdr.Name = filepath.Join(dir, WhiteoutPrefix+filename) + hdr.Mode = 0600 + hdr.Typeflag = tar.TypeReg + hdr.Size = 0 + } + + if fi.Mode()&os.ModeDir != 0 { + // convert opaque dirs to AUFS format by writing an empty file with the prefix + opaque, err := system.Lgetxattr(path, "trusted.overlay.opaque") + if err != nil { + return nil, err + } + if len(opaque) == 1 && opaque[0] == 'y' { + if hdr.Xattrs != nil { + delete(hdr.Xattrs, "trusted.overlay.opaque") + } + + // create a header for the whiteout file + // it should inherit some properties from the parent, but be a regular file + wo = &tar.Header{ + Typeflag: tar.TypeReg, + Mode: hdr.Mode & int64(os.ModePerm), + Name: filepath.Join(hdr.Name, WhiteoutOpaqueDir), + Size: 0, + Uid: hdr.Uid, + Uname: hdr.Uname, + Gid: hdr.Gid, + Gname: hdr.Gname, + AccessTime: hdr.AccessTime, + ChangeTime: hdr.ChangeTime, + } + } + } + + return +} + +func (overlayWhiteoutConverter) ConvertRead(hdr *tar.Header, path string) (bool, error) { + base := filepath.Base(path) + dir := filepath.Dir(path) + + // if a directory is marked as opaque by the AUFS special file, we need to translate that to overlay + if base == WhiteoutOpaqueDir { + err := unix.Setxattr(dir, "trusted.overlay.opaque", []byte{'y'}, 0) + // don't write the file itself + return false, err + } + + // if a file was deleted and we are using overlay, we need to create a character device + if strings.HasPrefix(base, WhiteoutPrefix) { + originalBase := base[len(WhiteoutPrefix):] + originalPath := filepath.Join(dir, originalBase) + + if err := unix.Mknod(originalPath, unix.S_IFCHR, 0); err != nil { + return false, err + } + if err := os.Chown(originalPath, hdr.Uid, hdr.Gid); err != nil { + return false, err + } + + // don't write the file itself + return false, nil + } + + return true, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive_other.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive_other.go new file mode 100644 index 00000000..758d27c4 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive_other.go @@ -0,0 +1,11 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !linux +// +build !linux + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +func getWhiteoutConverter(format WhiteoutFormat) tarWhiteoutConverter { + return nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive_unix.go new file mode 100644 index 00000000..dba0f8ec --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive_unix.go @@ -0,0 +1,149 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "archive/tar" + "bufio" + "errors" + "fmt" + "os" + "path/filepath" + "syscall" + + "github.com/ory/dockertest/v3/docker/pkg/idtools" + "github.com/ory/dockertest/v3/docker/pkg/system" + "golang.org/x/sys/unix" +) + +// fixVolumePathPrefix does platform specific processing to ensure that if +// the path being passed in is not in a volume path format, convert it to one. +func fixVolumePathPrefix(srcPath string) string { + return srcPath +} + +// getWalkRoot calculates the root path when performing a TarWithOptions. +// We use a separate function as this is platform specific. On Linux, we +// can't use filepath.Join(srcPath,include) because this will clean away +// a trailing "." or "/" which may be important. +func getWalkRoot(srcPath string, include string) string { + return srcPath + string(filepath.Separator) + include +} + +// CanonicalTarNameForPath returns platform-specific filepath +// to canonical posix-style path for tar archival. p is relative +// path. +func CanonicalTarNameForPath(p string) (string, error) { + return p, nil // already unix-style +} + +// chmodTarEntry is used to adjust the file permissions used in tar header based +// on the platform the archival is done. + +func chmodTarEntry(perm os.FileMode) os.FileMode { + return perm // noop for unix as golang APIs provide perm bits correctly +} + +func setHeaderForSpecialDevice(hdr *tar.Header, name string, stat interface{}) (err error) { + s, ok := stat.(*syscall.Stat_t) + + if ok { + // Currently go does not fill in the major/minors + if s.Mode&unix.S_IFBLK != 0 || + s.Mode&unix.S_IFCHR != 0 { + hdr.Devmajor = int64(unix.Major(uint64(s.Rdev))) // nolint: unconvert + hdr.Devminor = int64(unix.Minor(uint64(s.Rdev))) // nolint: unconvert + } + } + + return +} + +func getInodeFromStat(stat interface{}) (inode uint64, err error) { + s, ok := stat.(*syscall.Stat_t) + + if ok { + inode = s.Ino + } + + return +} + +func getFileUIDGID(stat interface{}) (idtools.IDPair, error) { + s, ok := stat.(*syscall.Stat_t) + + if !ok { + return idtools.IDPair{}, errors.New("cannot convert stat value to syscall.Stat_t") + } + return idtools.IDPair{UID: int(s.Uid), GID: int(s.Gid)}, nil +} + +// handleTarTypeBlockCharFifo is an OS-specific helper function used by +// createTarFile to handle the following types of header: Block; Char; Fifo +func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { + if runningInUserNS() { + // cannot create a device if running in user namespace + return nil + } + + mode := uint32(hdr.Mode & 07777) + switch hdr.Typeflag { + case tar.TypeBlock: + mode |= unix.S_IFBLK + case tar.TypeChar: + mode |= unix.S_IFCHR + case tar.TypeFifo: + mode |= unix.S_IFIFO + } + + return system.Mknod(path, mode, int(system.Mkdev(hdr.Devmajor, hdr.Devminor))) +} + +func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error { + if hdr.Typeflag == tar.TypeLink { + if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { + if err := os.Chmod(path, hdrInfo.Mode()); err != nil { + return err + } + } + } else if hdr.Typeflag != tar.TypeSymlink { + if err := os.Chmod(path, hdrInfo.Mode()); err != nil { + return err + } + } + return nil +} + +// runningInUserNS detects whether we are currently running in a user namespace. +// Copied from github.com/opencontainers/runc/libcontainer/system/linux.go +// Copied from github.com/lxc/lxd/shared/util.go +func runningInUserNS() bool { + file, err := os.Open("/proc/self/uid_map") + if err != nil { + // This kernel-provided file only exists if user namespaces are supported + return false + } + defer file.Close() + + buf := bufio.NewReader(file) + l, _, err := buf.ReadLine() + if err != nil { + return false + } + + line := string(l) + var a, b, c int64 + fmt.Sscanf(line, "%d %d %d", &a, &b, &c) + /* + * We assume we are in the initial user namespace if we have a full + * range - 4294967295 uids starting at uid 0. + */ + if a == 0 && b == 0 && c == 4294967295 { + return false + } + return true +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive_windows.go new file mode 100644 index 00000000..bf940cc9 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/archive_windows.go @@ -0,0 +1,80 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "archive/tar" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/ory/dockertest/v3/docker/pkg/idtools" + "github.com/ory/dockertest/v3/docker/pkg/longpath" +) + +// fixVolumePathPrefix does platform specific processing to ensure that if +// the path being passed in is not in a volume path format, convert it to one. +func fixVolumePathPrefix(srcPath string) string { + return longpath.AddPrefix(srcPath) +} + +// getWalkRoot calculates the root path when performing a TarWithOptions. +// We use a separate function as this is platform specific. +func getWalkRoot(srcPath string, include string) string { + return filepath.Join(srcPath, include) +} + +// CanonicalTarNameForPath returns platform-specific filepath +// to canonical posix-style path for tar archival. p is relative +// path. +func CanonicalTarNameForPath(p string) (string, error) { + // windows: convert windows style relative path with backslashes + // into forward slashes. Since windows does not allow '/' or '\' + // in file names, it is mostly safe to replace however we must + // check just in case + if strings.Contains(p, "/") { + return "", fmt.Errorf("Windows path contains forward slash: %s", p) + } + return strings.Replace(p, string(os.PathSeparator), "/", -1), nil + +} + +// chmodTarEntry is used to adjust the file permissions used in tar header based +// on the platform the archival is done. +func chmodTarEntry(perm os.FileMode) os.FileMode { + //perm &= 0755 // this 0-ed out tar flags (like link, regular file, directory marker etc.) + permPart := perm & os.ModePerm + noPermPart := perm &^ os.ModePerm + // Add the x bit: make everything +x from windows + permPart |= 0111 + permPart &= 0755 + + return noPermPart | permPart +} + +func setHeaderForSpecialDevice(hdr *tar.Header, name string, stat interface{}) (err error) { + // do nothing. no notion of Rdev, Nlink in stat on Windows + return +} + +func getInodeFromStat(stat interface{}) (inode uint64, err error) { + // do nothing. no notion of Inode in stat on Windows + return +} + +// handleTarTypeBlockCharFifo is an OS-specific helper function used by +// createTarFile to handle the following types of header: Block; Char; Fifo +func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { + return nil +} + +func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error { + return nil +} + +func getFileUIDGID(stat interface{}) (idtools.IDPair, error) { + // no notion of file ownership mapping yet on Windows + return idtools.IDPair{0, 0}, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes.go new file mode 100644 index 00000000..842802ef --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes.go @@ -0,0 +1,443 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "archive/tar" + "bytes" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + "syscall" + "time" + + "github.com/ory/dockertest/v3/docker/pkg/idtools" + "github.com/ory/dockertest/v3/docker/pkg/pools" + "github.com/ory/dockertest/v3/docker/pkg/system" + "github.com/sirupsen/logrus" +) + +// ChangeType represents the change type. +type ChangeType int + +const ( + // ChangeModify represents the modify operation. + ChangeModify = iota + // ChangeAdd represents the add operation. + ChangeAdd + // ChangeDelete represents the delete operation. + ChangeDelete +) + +func (c ChangeType) String() string { + switch c { + case ChangeModify: + return "C" + case ChangeAdd: + return "A" + case ChangeDelete: + return "D" + } + return "" +} + +// Change represents a change, it wraps the change type and path. +// It describes changes of the files in the path respect to the +// parent layers. The change could be modify, add, delete. +// This is used for layer diff. +type Change struct { + Path string + Kind ChangeType +} + +func (change *Change) String() string { + return fmt.Sprintf("%s %s", change.Kind, change.Path) +} + +// for sort.Sort +type changesByPath []Change + +func (c changesByPath) Less(i, j int) bool { return c[i].Path < c[j].Path } +func (c changesByPath) Len() int { return len(c) } +func (c changesByPath) Swap(i, j int) { c[j], c[i] = c[i], c[j] } + +// Gnu tar and the go tar writer don't have sub-second mtime +// precision, which is problematic when we apply changes via tar +// files, we handle this by comparing for exact times, *or* same +// second count and either a or b having exactly 0 nanoseconds +func sameFsTime(a, b time.Time) bool { + return a == b || + (a.Unix() == b.Unix() && + (a.Nanosecond() == 0 || b.Nanosecond() == 0)) +} + +func sameFsTimeSpec(a, b syscall.Timespec) bool { + return a.Sec == b.Sec && + (a.Nsec == b.Nsec || a.Nsec == 0 || b.Nsec == 0) +} + +// Changes walks the path rw and determines changes for the files in the path, +// with respect to the parent layers +func Changes(layers []string, rw string) ([]Change, error) { + return changes(layers, rw, aufsDeletedFile, aufsMetadataSkip) +} + +func aufsMetadataSkip(path string) (skip bool, err error) { + skip, err = filepath.Match(string(os.PathSeparator)+WhiteoutMetaPrefix+"*", path) + if err != nil { + skip = true + } + return +} + +func aufsDeletedFile(root, path string, fi os.FileInfo) (string, error) { + f := filepath.Base(path) + + // If there is a whiteout, then the file was removed + if strings.HasPrefix(f, WhiteoutPrefix) { + originalFile := f[len(WhiteoutPrefix):] + return filepath.Join(filepath.Dir(path), originalFile), nil + } + + return "", nil +} + +type skipChange func(string) (bool, error) +type deleteChange func(string, string, os.FileInfo) (string, error) + +func changes(layers []string, rw string, dc deleteChange, sc skipChange) ([]Change, error) { + var ( + changes []Change + changedDirs = make(map[string]struct{}) + ) + + err := filepath.Walk(rw, func(path string, f os.FileInfo, err error) error { + if err != nil { + return err + } + + // Rebase path + path, err = filepath.Rel(rw, path) + if err != nil { + return err + } + + // As this runs on the daemon side, file paths are OS specific. + path = filepath.Join(string(os.PathSeparator), path) + + // Skip root + if path == string(os.PathSeparator) { + return nil + } + + if sc != nil { + if skip, err := sc(path); skip { + return err + } + } + + change := Change{ + Path: path, + } + + deletedFile, err := dc(rw, path, f) + if err != nil { + return err + } + + // Find out what kind of modification happened + if deletedFile != "" { + change.Path = deletedFile + change.Kind = ChangeDelete + } else { + // Otherwise, the file was added + change.Kind = ChangeAdd + + // ...Unless it already existed in a top layer, in which case, it's a modification + for _, layer := range layers { + stat, err := os.Stat(filepath.Join(layer, path)) + if err != nil && !os.IsNotExist(err) { + return err + } + if err == nil { + // The file existed in the top layer, so that's a modification + + // However, if it's a directory, maybe it wasn't actually modified. + // If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar + if stat.IsDir() && f.IsDir() { + if f.Size() == stat.Size() && f.Mode() == stat.Mode() && sameFsTime(f.ModTime(), stat.ModTime()) { + // Both directories are the same, don't record the change + return nil + } + } + change.Kind = ChangeModify + break + } + } + } + + // If /foo/bar/file.txt is modified, then /foo/bar must be part of the changed files. + // This block is here to ensure the change is recorded even if the + // modify time, mode and size of the parent directory in the rw and ro layers are all equal. + // Check https://github.com/docker/docker/pull/13590 for details. + if f.IsDir() { + changedDirs[path] = struct{}{} + } + if change.Kind == ChangeAdd || change.Kind == ChangeDelete { + parent := filepath.Dir(path) + if _, ok := changedDirs[parent]; !ok && parent != "/" { + changes = append(changes, Change{Path: parent, Kind: ChangeModify}) + changedDirs[parent] = struct{}{} + } + } + + // Record change + changes = append(changes, change) + return nil + }) + if err != nil && !os.IsNotExist(err) { + return nil, err + } + return changes, nil +} + +// FileInfo describes the information of a file. +type FileInfo struct { + parent *FileInfo + name string + stat *system.StatT + children map[string]*FileInfo + capability []byte + added bool +} + +// LookUp looks up the file information of a file. +func (info *FileInfo) LookUp(path string) *FileInfo { + // As this runs on the daemon side, file paths are OS specific. + parent := info + if path == string(os.PathSeparator) { + return info + } + + pathElements := strings.Split(path, string(os.PathSeparator)) + for _, elem := range pathElements { + if elem != "" { + child := parent.children[elem] + if child == nil { + return nil + } + parent = child + } + } + return parent +} + +func (info *FileInfo) path() string { + if info.parent == nil { + // As this runs on the daemon side, file paths are OS specific. + return string(os.PathSeparator) + } + return filepath.Join(info.parent.path(), info.name) +} + +func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) { + + sizeAtEntry := len(*changes) + + if oldInfo == nil { + // add + change := Change{ + Path: info.path(), + Kind: ChangeAdd, + } + *changes = append(*changes, change) + info.added = true + } + + // We make a copy so we can modify it to detect additions + // also, we only recurse on the old dir if the new info is a directory + // otherwise any previous delete/change is considered recursive + oldChildren := make(map[string]*FileInfo) + if oldInfo != nil && info.isDir() { + for k, v := range oldInfo.children { + oldChildren[k] = v + } + } + + for name, newChild := range info.children { + oldChild := oldChildren[name] + if oldChild != nil { + // change? + oldStat := oldChild.stat + newStat := newChild.stat + // Note: We can't compare inode or ctime or blocksize here, because these change + // when copying a file into a container. However, that is not generally a problem + // because any content change will change mtime, and any status change should + // be visible when actually comparing the stat fields. The only time this + // breaks down is if some code intentionally hides a change by setting + // back mtime + if statDifferent(oldStat, newStat) || + !bytes.Equal(oldChild.capability, newChild.capability) { + change := Change{ + Path: newChild.path(), + Kind: ChangeModify, + } + *changes = append(*changes, change) + newChild.added = true + } + + // Remove from copy so we can detect deletions + delete(oldChildren, name) + } + + newChild.addChanges(oldChild, changes) + } + for _, oldChild := range oldChildren { + // delete + change := Change{ + Path: oldChild.path(), + Kind: ChangeDelete, + } + *changes = append(*changes, change) + } + + // If there were changes inside this directory, we need to add it, even if the directory + // itself wasn't changed. This is needed to properly save and restore filesystem permissions. + // As this runs on the daemon side, file paths are OS specific. + if len(*changes) > sizeAtEntry && info.isDir() && !info.added && info.path() != string(os.PathSeparator) { + change := Change{ + Path: info.path(), + Kind: ChangeModify, + } + // Let's insert the directory entry before the recently added entries located inside this dir + *changes = append(*changes, change) // just to resize the slice, will be overwritten + copy((*changes)[sizeAtEntry+1:], (*changes)[sizeAtEntry:]) + (*changes)[sizeAtEntry] = change + } + +} + +// Changes add changes to file information. +func (info *FileInfo) Changes(oldInfo *FileInfo) []Change { + var changes []Change + + info.addChanges(oldInfo, &changes) + + return changes +} + +func newRootFileInfo() *FileInfo { + // As this runs on the daemon side, file paths are OS specific. + root := &FileInfo{ + name: string(os.PathSeparator), + children: make(map[string]*FileInfo), + } + return root +} + +// ChangesDirs compares two directories and generates an array of Change objects describing the changes. +// If oldDir is "", then all files in newDir will be Add-Changes. +func ChangesDirs(newDir, oldDir string) ([]Change, error) { + var ( + oldRoot, newRoot *FileInfo + ) + if oldDir == "" { + emptyDir, err := os.CreateTemp("", "empty") + if err != nil { + return nil, err + } + defer os.Remove(emptyDir.Name()) + oldDir = emptyDir.Name() + } + oldRoot, newRoot, err := collectFileInfoForChanges(oldDir, newDir) + if err != nil { + return nil, err + } + + return newRoot.Changes(oldRoot), nil +} + +// ChangesSize calculates the size in bytes of the provided changes, based on newDir. +func ChangesSize(newDir string, changes []Change) int64 { + var ( + size int64 + sf = make(map[uint64]struct{}) + ) + for _, change := range changes { + if change.Kind == ChangeModify || change.Kind == ChangeAdd { + file := filepath.Join(newDir, change.Path) + fileInfo, err := os.Lstat(file) + if err != nil { + logrus.Errorf("Can not stat %q: %s", file, err) + continue + } + + if fileInfo != nil && !fileInfo.IsDir() { + if hasHardlinks(fileInfo) { + inode := getIno(fileInfo) + if _, ok := sf[inode]; !ok { + size += fileInfo.Size() + sf[inode] = struct{}{} + } + } else { + size += fileInfo.Size() + } + } + } + } + return size +} + +// ExportChanges produces an Archive from the provided changes, relative to dir. +func ExportChanges(dir string, changes []Change, uidMaps, gidMaps []idtools.IDMap) (io.ReadCloser, error) { + reader, writer := io.Pipe() + go func() { + ta := newTarAppender(idtools.NewIDMappingsFromMaps(uidMaps, gidMaps), writer, nil) + + // this buffer is needed for the duration of this piped stream + defer pools.BufioWriter32KPool.Put(ta.Buffer) + + sort.Sort(changesByPath(changes)) + + // In general we log errors here but ignore them because + // during e.g. a diff operation the container can continue + // mutating the filesystem and we can see transient errors + // from this + for _, change := range changes { + if change.Kind == ChangeDelete { + whiteOutDir := filepath.Dir(change.Path) + whiteOutBase := filepath.Base(change.Path) + whiteOut := filepath.Join(whiteOutDir, WhiteoutPrefix+whiteOutBase) + timestamp := time.Now() + hdr := &tar.Header{ + Name: whiteOut[1:], + Size: 0, + ModTime: timestamp, + AccessTime: timestamp, + ChangeTime: timestamp, + } + if err := ta.TarWriter.WriteHeader(hdr); err != nil { + logrus.Debugf("Can't write whiteout header: %s", err) + } + } else { + path := filepath.Join(dir, change.Path) + if err := ta.addTarFile(path, change.Path[1:]); err != nil { + logrus.Debugf("Can't add file %s to tar: %s", path, err) + } + } + } + + // Make sure to check the error on Close. + if err := ta.TarWriter.Close(); err != nil { + logrus.Debugf("Can't close layer: %s", err) + } + if err := writer.Close(); err != nil { + logrus.Debugf("failed close Changes writer: %s", err) + } + }() + return reader, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes_linux.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes_linux.go new file mode 100644 index 00000000..9c62add4 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes_linux.go @@ -0,0 +1,316 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "sort" + "syscall" + "unsafe" + + "github.com/ory/dockertest/v3/docker/pkg/system" + "golang.org/x/sys/unix" +) + +// walker is used to implement collectFileInfoForChanges on linux. Where this +// method in general returns the entire contents of two directory trees, we +// optimize some FS calls out on linux. In particular, we take advantage of the +// fact that getdents(2) returns the inode of each file in the directory being +// walked, which, when walking two trees in parallel to generate a list of +// changes, can be used to prune subtrees without ever having to lstat(2) them +// directly. Eliminating stat calls in this way can save up to seconds on large +// images. +type walker struct { + dir1 string + dir2 string + root1 *FileInfo + root2 *FileInfo +} + +// collectFileInfoForChanges returns a complete representation of the trees +// rooted at dir1 and dir2, with one important exception: any subtree or +// leaf where the inode and device numbers are an exact match between dir1 +// and dir2 will be pruned from the results. This method is *only* to be used +// to generating a list of changes between the two directories, as it does not +// reflect the full contents. +func collectFileInfoForChanges(dir1, dir2 string) (*FileInfo, *FileInfo, error) { + w := &walker{ + dir1: dir1, + dir2: dir2, + root1: newRootFileInfo(), + root2: newRootFileInfo(), + } + + i1, err := os.Lstat(w.dir1) + if err != nil { + return nil, nil, err + } + i2, err := os.Lstat(w.dir2) + if err != nil { + return nil, nil, err + } + + if err := w.walk("/", i1, i2); err != nil { + return nil, nil, err + } + + return w.root1, w.root2, nil +} + +// Given a FileInfo, its path info, and a reference to the root of the tree +// being constructed, register this file with the tree. +func walkchunk(path string, fi os.FileInfo, dir string, root *FileInfo) error { + if fi == nil { + return nil + } + parent := root.LookUp(filepath.Dir(path)) + if parent == nil { + return fmt.Errorf("walkchunk: Unexpectedly no parent for %s", path) + } + info := &FileInfo{ + name: filepath.Base(path), + children: make(map[string]*FileInfo), + parent: parent, + } + cpath := filepath.Join(dir, path) + stat, err := system.FromStatT(fi.Sys().(*syscall.Stat_t)) + if err != nil { + return err + } + info.stat = stat + info.capability, _ = system.Lgetxattr(cpath, "security.capability") // lgetxattr(2): fs access + parent.children[info.name] = info + return nil +} + +// Walk a subtree rooted at the same path in both trees being iterated. For +// example, /docker/overlay/1234/a/b/c/d and /docker/overlay/8888/a/b/c/d +func (w *walker) walk(path string, i1, i2 os.FileInfo) (err error) { + // Register these nodes with the return trees, unless we're still at the + // (already-created) roots: + if path != "/" { + if err := walkchunk(path, i1, w.dir1, w.root1); err != nil { + return err + } + if err := walkchunk(path, i2, w.dir2, w.root2); err != nil { + return err + } + } + + is1Dir := i1 != nil && i1.IsDir() + is2Dir := i2 != nil && i2.IsDir() + + sameDevice := false + if i1 != nil && i2 != nil { + si1 := i1.Sys().(*syscall.Stat_t) + si2 := i2.Sys().(*syscall.Stat_t) + if si1.Dev == si2.Dev { + sameDevice = true + } + } + + // If these files are both non-existent, or leaves (non-dirs), we are done. + if !is1Dir && !is2Dir { + return nil + } + + // Fetch the names of all the files contained in both directories being walked: + var names1, names2 []nameIno + if is1Dir { + names1, err = readdirnames(filepath.Join(w.dir1, path)) // getdents(2): fs access + if err != nil { + return err + } + } + if is2Dir { + names2, err = readdirnames(filepath.Join(w.dir2, path)) // getdents(2): fs access + if err != nil { + return err + } + } + + // We have lists of the files contained in both parallel directories, sorted + // in the same order. Walk them in parallel, generating a unique merged list + // of all items present in either or both directories. + var names []string + ix1 := 0 + ix2 := 0 + + for { + if ix1 >= len(names1) { + break + } + if ix2 >= len(names2) { + break + } + + ni1 := names1[ix1] + ni2 := names2[ix2] + + switch bytes.Compare([]byte(ni1.name), []byte(ni2.name)) { + case -1: // ni1 < ni2 -- advance ni1 + // we will not encounter ni1 in names2 + names = append(names, ni1.name) + ix1++ + case 0: // ni1 == ni2 + if ni1.ino != ni2.ino || !sameDevice { + names = append(names, ni1.name) + } + ix1++ + ix2++ + case 1: // ni1 > ni2 -- advance ni2 + // we will not encounter ni2 in names1 + names = append(names, ni2.name) + ix2++ + } + } + for ix1 < len(names1) { + names = append(names, names1[ix1].name) + ix1++ + } + for ix2 < len(names2) { + names = append(names, names2[ix2].name) + ix2++ + } + + // For each of the names present in either or both of the directories being + // iterated, stat the name under each root, and recurse the pair of them: + for _, name := range names { + fname := filepath.Join(path, name) + var cInfo1, cInfo2 os.FileInfo + if is1Dir { + cInfo1, err = os.Lstat(filepath.Join(w.dir1, fname)) // lstat(2): fs access + if err != nil && !os.IsNotExist(err) { + return err + } + } + if is2Dir { + cInfo2, err = os.Lstat(filepath.Join(w.dir2, fname)) // lstat(2): fs access + if err != nil && !os.IsNotExist(err) { + return err + } + } + if err = w.walk(fname, cInfo1, cInfo2); err != nil { + return err + } + } + return nil +} + +// {name,inode} pairs used to support the early-pruning logic of the walker type +type nameIno struct { + name string + ino uint64 +} + +type nameInoSlice []nameIno + +func (s nameInoSlice) Len() int { return len(s) } +func (s nameInoSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s nameInoSlice) Less(i, j int) bool { return s[i].name < s[j].name } + +// readdirnames is a hacked-apart version of the Go stdlib code, exposing inode +// numbers further up the stack when reading directory contents. Unlike +// os.Readdirnames, which returns a list of filenames, this function returns a +// list of {filename,inode} pairs. +func readdirnames(dirname string) (names []nameIno, err error) { + var ( + size = 100 + buf = make([]byte, 4096) + nbuf int + bufp int + nb int + ) + + f, err := os.Open(dirname) + if err != nil { + return nil, err + } + defer f.Close() + + names = make([]nameIno, 0, size) // Empty with room to grow. + for { + // Refill the buffer if necessary + if bufp >= nbuf { + bufp = 0 + nbuf, err = unix.ReadDirent(int(f.Fd()), buf) // getdents on linux + if nbuf < 0 { + nbuf = 0 + } + if err != nil { + return nil, os.NewSyscallError("readdirent", err) + } + if nbuf <= 0 { + break // EOF + } + } + + // Drain the buffer + nb, names = parseDirent(buf[bufp:nbuf], names) + bufp += nb + } + + sl := nameInoSlice(names) + sort.Sort(sl) + return sl, nil +} + +// parseDirent is a minor modification of unix.ParseDirent (linux version) +// which returns {name,inode} pairs instead of just names. +func parseDirent(buf []byte, names []nameIno) (consumed int, newnames []nameIno) { + origlen := len(buf) + for len(buf) > 0 { + dirent := (*unix.Dirent)(unsafe.Pointer(&buf[0])) + buf = buf[dirent.Reclen:] + if dirent.Ino == 0 { // File absent in directory. + continue + } + bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) + var name = string(bytes[0:clen(bytes[:])]) + if name == "." || name == ".." { // Useless names + continue + } + names = append(names, nameIno{name, dirent.Ino}) + } + return origlen - len(buf), names +} + +func clen(n []byte) int { + for i := 0; i < len(n); i++ { + if n[i] == 0 { + return i + } + } + return len(n) +} + +// OverlayChanges walks the path rw and determines changes for the files in the path, +// with respect to the parent layers +func OverlayChanges(layers []string, rw string) ([]Change, error) { + return changes(layers, rw, overlayDeletedFile, nil) +} + +func overlayDeletedFile(root, path string, fi os.FileInfo) (string, error) { + if fi.Mode()&os.ModeCharDevice != 0 { + s := fi.Sys().(*syscall.Stat_t) + if unix.Major(uint64(s.Rdev)) == 0 && unix.Minor(uint64(s.Rdev)) == 0 { // nolint: unconvert + return path, nil + } + } + if fi.Mode()&os.ModeDir != 0 { + opaque, err := system.Lgetxattr(filepath.Join(root, path), "trusted.overlay.opaque") + if err != nil { + return "", err + } + if len(opaque) == 1 && opaque[0] == 'y' { + return path, nil + } + } + + return "", nil + +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes_other.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes_other.go new file mode 100644 index 00000000..0833fe67 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes_other.go @@ -0,0 +1,101 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !linux +// +build !linux + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + + "github.com/ory/dockertest/v3/docker/pkg/system" +) + +func collectFileInfoForChanges(oldDir, newDir string) (*FileInfo, *FileInfo, error) { + var ( + oldRoot, newRoot *FileInfo + err1, err2 error + errs = make(chan error, 2) + ) + go func() { + oldRoot, err1 = collectFileInfo(oldDir) + errs <- err1 + }() + go func() { + newRoot, err2 = collectFileInfo(newDir) + errs <- err2 + }() + + // block until both routines have returned + for i := 0; i < 2; i++ { + if err := <-errs; err != nil { + return nil, nil, err + } + } + + return oldRoot, newRoot, nil +} + +func collectFileInfo(sourceDir string) (*FileInfo, error) { + root := newRootFileInfo() + + err := filepath.Walk(sourceDir, func(path string, f os.FileInfo, err error) error { + if err != nil { + return err + } + + // Rebase path + relPath, err := filepath.Rel(sourceDir, path) + if err != nil { + return err + } + + // As this runs on the daemon side, file paths are OS specific. + relPath = filepath.Join(string(os.PathSeparator), relPath) + + // See https://github.com/golang/go/issues/9168 - bug in filepath.Join. + // Temporary workaround. If the returned path starts with two backslashes, + // trim it down to a single backslash. Only relevant on Windows. + if runtime.GOOS == "windows" { + if strings.HasPrefix(relPath, `\\`) { + relPath = relPath[1:] + } + } + + if relPath == string(os.PathSeparator) { + return nil + } + + parent := root.LookUp(filepath.Dir(relPath)) + if parent == nil { + return fmt.Errorf("collectFileInfo: Unexpectedly no parent for %s", relPath) + } + + info := &FileInfo{ + name: filepath.Base(relPath), + children: make(map[string]*FileInfo), + parent: parent, + } + + s, err := system.Lstat(path) + if err != nil { + return err + } + info.stat = s + + info.capability, _ = system.Lgetxattr(path, "security.capability") + + parent.children[info.name] = info + + return nil + }) + if err != nil { + return nil, err + } + return root, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes_unix.go new file mode 100644 index 00000000..fe749f23 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes_unix.go @@ -0,0 +1,41 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "os" + "syscall" + + "github.com/ory/dockertest/v3/docker/pkg/system" + "golang.org/x/sys/unix" +) + +func statDifferent(oldStat *system.StatT, newStat *system.StatT) bool { + // Don't look at size for dirs, its not a good measure of change + if oldStat.Mode() != newStat.Mode() || + oldStat.UID() != newStat.UID() || + oldStat.GID() != newStat.GID() || + oldStat.Rdev() != newStat.Rdev() || + // Don't look at size for dirs, its not a good measure of change + (oldStat.Mode()&unix.S_IFDIR != unix.S_IFDIR && + (!sameFsTimeSpec(oldStat.Mtim(), newStat.Mtim()) || (oldStat.Size() != newStat.Size()))) { + return true + } + return false +} + +func (info *FileInfo) isDir() bool { + return info.parent == nil || info.stat.Mode()&unix.S_IFDIR != 0 +} + +func getIno(fi os.FileInfo) uint64 { + return fi.Sys().(*syscall.Stat_t).Ino +} + +func hasHardlinks(fi os.FileInfo) bool { + return fi.Sys().(*syscall.Stat_t).Nlink > 1 +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes_windows.go new file mode 100644 index 00000000..e151579d --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/changes_windows.go @@ -0,0 +1,33 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "os" + + "github.com/ory/dockertest/v3/docker/pkg/system" +) + +func statDifferent(oldStat *system.StatT, newStat *system.StatT) bool { + + // Don't look at size for dirs, its not a good measure of change + if oldStat.Mtim() != newStat.Mtim() || + oldStat.Mode() != newStat.Mode() || + oldStat.Size() != newStat.Size() && !oldStat.Mode().IsDir() { + return true + } + return false +} + +func (info *FileInfo) isDir() bool { + return info.parent == nil || info.stat.Mode().IsDir() +} + +func getIno(fi os.FileInfo) (inode uint64) { + return +} + +func hasHardlinks(fi os.FileInfo) bool { + return false +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/copy.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/copy.go new file mode 100644 index 00000000..98fd482f --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/copy.go @@ -0,0 +1,474 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "archive/tar" + "errors" + "io" + "os" + "path/filepath" + "strings" + + "github.com/ory/dockertest/v3/docker/pkg/system" + "github.com/sirupsen/logrus" +) + +// Errors used or returned by this file. +var ( + ErrNotDirectory = errors.New("not a directory") + ErrDirNotExists = errors.New("no such directory") + ErrCannotCopyDir = errors.New("cannot copy directory") + ErrInvalidCopySource = errors.New("invalid copy source content") +) + +// PreserveTrailingDotOrSeparator returns the given cleaned path (after +// processing using any utility functions from the path or filepath stdlib +// packages) and appends a trailing `/.` or `/` if its corresponding original +// path (from before being processed by utility functions from the path or +// filepath stdlib packages) ends with a trailing `/.` or `/`. If the cleaned +// path already ends in a `.` path segment, then another is not added. If the +// clean path already ends in the separator, then another is not added. +func PreserveTrailingDotOrSeparator(cleanedPath string, originalPath string, sep byte) string { + // Ensure paths are in platform semantics + cleanedPath = strings.Replace(cleanedPath, "/", string(sep), -1) + originalPath = strings.Replace(originalPath, "/", string(sep), -1) + + if !specifiesCurrentDir(cleanedPath) && specifiesCurrentDir(originalPath) { + if !hasTrailingPathSeparator(cleanedPath, sep) { + // Add a separator if it doesn't already end with one (a cleaned + // path would only end in a separator if it is the root). + cleanedPath += string(sep) + } + cleanedPath += "." + } + + if !hasTrailingPathSeparator(cleanedPath, sep) && hasTrailingPathSeparator(originalPath, sep) { + cleanedPath += string(sep) + } + + return cleanedPath +} + +// assertsDirectory returns whether the given path is +// asserted to be a directory, i.e., the path ends with +// a trailing '/' or `/.`, assuming a path separator of `/`. +func assertsDirectory(path string, sep byte) bool { + return hasTrailingPathSeparator(path, sep) || specifiesCurrentDir(path) +} + +// hasTrailingPathSeparator returns whether the given +// path ends with the system's path separator character. +func hasTrailingPathSeparator(path string, sep byte) bool { + return len(path) > 0 && path[len(path)-1] == sep +} + +// specifiesCurrentDir returns whether the given path specifies +// a "current directory", i.e., the last path segment is `.`. +func specifiesCurrentDir(path string) bool { + return filepath.Base(path) == "." +} + +// SplitPathDirEntry splits the given path between its directory name and its +// basename by first cleaning the path but preserves a trailing "." if the +// original path specified the current directory. +func SplitPathDirEntry(path string) (dir, base string) { + cleanedPath := filepath.Clean(filepath.FromSlash(path)) + + if specifiesCurrentDir(path) { + cleanedPath += string(os.PathSeparator) + "." + } + + return filepath.Dir(cleanedPath), filepath.Base(cleanedPath) +} + +// TarResource archives the resource described by the given CopyInfo to a Tar +// archive. A non-nil error is returned if sourcePath does not exist or is +// asserted to be a directory but exists as another type of file. +// +// This function acts as a convenient wrapper around TarWithOptions, which +// requires a directory as the source path. TarResource accepts either a +// directory or a file path and correctly sets the Tar options. +func TarResource(sourceInfo CopyInfo) (content io.ReadCloser, err error) { + return TarResourceRebase(sourceInfo.Path, sourceInfo.RebaseName) +} + +// TarResourceRebase is like TarResource but renames the first path element of +// items in the resulting tar archive to match the given rebaseName if not "". +func TarResourceRebase(sourcePath, rebaseName string) (content io.ReadCloser, err error) { + sourcePath = normalizePath(sourcePath) + if _, err = os.Lstat(sourcePath); err != nil { + // Catches the case where the source does not exist or is not a + // directory if asserted to be a directory, as this also causes an + // error. + return + } + + // Separate the source path between its directory and + // the entry in that directory which we are archiving. + sourceDir, sourceBase := SplitPathDirEntry(sourcePath) + opts := TarResourceRebaseOpts(sourceBase, rebaseName) + + logrus.Debugf("copying %q from %q", sourceBase, sourceDir) + return TarWithOptions(sourceDir, opts) +} + +// TarResourceRebaseOpts does not preform the Tar, but instead just creates the rebase +// parameters to be sent to TarWithOptions (the TarOptions struct) +func TarResourceRebaseOpts(sourceBase string, rebaseName string) *TarOptions { + filter := []string{sourceBase} + return &TarOptions{ + Compression: Uncompressed, + IncludeFiles: filter, + IncludeSourceDir: true, + RebaseNames: map[string]string{ + sourceBase: rebaseName, + }, + } +} + +// CopyInfo holds basic info about the source +// or destination path of a copy operation. +type CopyInfo struct { + Path string + Exists bool + IsDir bool + RebaseName string +} + +// CopyInfoSourcePath stats the given path to create a CopyInfo +// struct representing that resource for the source of an archive copy +// operation. The given path should be an absolute local path. A source path +// has all symlinks evaluated that appear before the last path separator ("/" +// on Unix). As it is to be a copy source, the path must exist. +func CopyInfoSourcePath(path string, followLink bool) (CopyInfo, error) { + // normalize the file path and then evaluate the symbol link + // we will use the target file instead of the symbol link if + // followLink is set + path = normalizePath(path) + + resolvedPath, rebaseName, err := ResolveHostSourcePath(path, followLink) + if err != nil { + return CopyInfo{}, err + } + + stat, err := os.Lstat(resolvedPath) + if err != nil { + return CopyInfo{}, err + } + + return CopyInfo{ + Path: resolvedPath, + Exists: true, + IsDir: stat.IsDir(), + RebaseName: rebaseName, + }, nil +} + +// CopyInfoDestinationPath stats the given path to create a CopyInfo +// struct representing that resource for the destination of an archive copy +// operation. The given path should be an absolute local path. +func CopyInfoDestinationPath(path string) (info CopyInfo, err error) { + maxSymlinkIter := 10 // filepath.EvalSymlinks uses 255, but 10 already seems like a lot. + path = normalizePath(path) + originalPath := path + + stat, err := os.Lstat(path) + + if err == nil && stat.Mode()&os.ModeSymlink == 0 { + // The path exists and is not a symlink. + return CopyInfo{ + Path: path, + Exists: true, + IsDir: stat.IsDir(), + }, nil + } + + // While the path is a symlink. + for n := 0; err == nil && stat.Mode()&os.ModeSymlink != 0; n++ { + if n > maxSymlinkIter { + // Don't follow symlinks more than this arbitrary number of times. + return CopyInfo{}, errors.New("too many symlinks in " + originalPath) + } + + // The path is a symbolic link. We need to evaluate it so that the + // destination of the copy operation is the link target and not the + // link itself. This is notably different than CopyInfoSourcePath which + // only evaluates symlinks before the last appearing path separator. + // Also note that it is okay if the last path element is a broken + // symlink as the copy operation should create the target. + var linkTarget string + + linkTarget, err = os.Readlink(path) + if err != nil { + return CopyInfo{}, err + } + + if !system.IsAbs(linkTarget) { + // Join with the parent directory. + dstParent, _ := SplitPathDirEntry(path) + linkTarget = filepath.Join(dstParent, linkTarget) + } + + path = linkTarget + stat, err = os.Lstat(path) + } + + if err != nil { + // It's okay if the destination path doesn't exist. We can still + // continue the copy operation if the parent directory exists. + if !os.IsNotExist(err) { + return CopyInfo{}, err + } + + // Ensure destination parent dir exists. + dstParent, _ := SplitPathDirEntry(path) + + parentDirStat, err := os.Stat(dstParent) + if err != nil { + return CopyInfo{}, err + } + if !parentDirStat.IsDir() { + return CopyInfo{}, ErrNotDirectory + } + + return CopyInfo{Path: path}, nil + } + + // The path exists after resolving symlinks. + return CopyInfo{ + Path: path, + Exists: true, + IsDir: stat.IsDir(), + }, nil +} + +// PrepareArchiveCopy prepares the given srcContent archive, which should +// contain the archived resource described by srcInfo, to the destination +// described by dstInfo. Returns the possibly modified content archive along +// with the path to the destination directory which it should be extracted to. +func PrepareArchiveCopy(srcContent io.Reader, srcInfo, dstInfo CopyInfo) (dstDir string, content io.ReadCloser, err error) { + // Ensure in platform semantics + srcInfo.Path = normalizePath(srcInfo.Path) + dstInfo.Path = normalizePath(dstInfo.Path) + + // Separate the destination path between its directory and base + // components in case the source archive contents need to be rebased. + dstDir, dstBase := SplitPathDirEntry(dstInfo.Path) + _, srcBase := SplitPathDirEntry(srcInfo.Path) + + switch { + case dstInfo.Exists && dstInfo.IsDir: + // The destination exists as a directory. No alteration + // to srcContent is needed as its contents can be + // simply extracted to the destination directory. + return dstInfo.Path, io.NopCloser(srcContent), nil + case dstInfo.Exists && srcInfo.IsDir: + // The destination exists as some type of file and the source + // content is a directory. This is an error condition since + // you cannot copy a directory to an existing file location. + return "", nil, ErrCannotCopyDir + case dstInfo.Exists: + // The destination exists as some type of file and the source content + // is also a file. The source content entry will have to be renamed to + // have a basename which matches the destination path's basename. + if len(srcInfo.RebaseName) != 0 { + srcBase = srcInfo.RebaseName + } + return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil + case srcInfo.IsDir: + // The destination does not exist and the source content is an archive + // of a directory. The archive should be extracted to the parent of + // the destination path instead, and when it is, the directory that is + // created as a result should take the name of the destination path. + // The source content entries will have to be renamed to have a + // basename which matches the destination path's basename. + if len(srcInfo.RebaseName) != 0 { + srcBase = srcInfo.RebaseName + } + return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil + case assertsDirectory(dstInfo.Path, os.PathSeparator): + // The destination does not exist and is asserted to be created as a + // directory, but the source content is not a directory. This is an + // error condition since you cannot create a directory from a file + // source. + return "", nil, ErrDirNotExists + default: + // The last remaining case is when the destination does not exist, is + // not asserted to be a directory, and the source content is not an + // archive of a directory. It this case, the destination file will need + // to be created when the archive is extracted and the source content + // entry will have to be renamed to have a basename which matches the + // destination path's basename. + if len(srcInfo.RebaseName) != 0 { + srcBase = srcInfo.RebaseName + } + return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil + } + +} + +// RebaseArchiveEntries rewrites the given srcContent archive replacing +// an occurrence of oldBase with newBase at the beginning of entry names. +func RebaseArchiveEntries(srcContent io.Reader, oldBase, newBase string) io.ReadCloser { + if oldBase == string(os.PathSeparator) { + // If oldBase specifies the root directory, use an empty string as + // oldBase instead so that newBase doesn't replace the path separator + // that all paths will start with. + oldBase = "" + } + + rebased, w := io.Pipe() + + go func() { + srcTar := tar.NewReader(srcContent) + rebasedTar := tar.NewWriter(w) + + for { + hdr, err := srcTar.Next() + if err == io.EOF { + // Signals end of archive. + rebasedTar.Close() + w.Close() + return + } + if err != nil { + w.CloseWithError(err) + return + } + + hdr.Name = strings.Replace(hdr.Name, oldBase, newBase, 1) + if hdr.Typeflag == tar.TypeLink { + hdr.Linkname = strings.Replace(hdr.Linkname, oldBase, newBase, 1) + } + + if err = rebasedTar.WriteHeader(hdr); err != nil { + w.CloseWithError(err) + return + } + + if _, err = io.Copy(rebasedTar, srcTar); err != nil { + w.CloseWithError(err) + return + } + } + }() + + return rebased +} + +// TODO @gupta-ak. These might have to be changed in the future to be +// continuity driver aware as well to support LCOW. + +// CopyResource performs an archive copy from the given source path to the +// given destination path. The source path MUST exist and the destination +// path's parent directory must exist. +func CopyResource(srcPath, dstPath string, followLink bool) error { + var ( + srcInfo CopyInfo + err error + ) + + // Ensure in platform semantics + srcPath = normalizePath(srcPath) + dstPath = normalizePath(dstPath) + + // Clean the source and destination paths. + srcPath = PreserveTrailingDotOrSeparator(filepath.Clean(srcPath), srcPath, os.PathSeparator) + dstPath = PreserveTrailingDotOrSeparator(filepath.Clean(dstPath), dstPath, os.PathSeparator) + + if srcInfo, err = CopyInfoSourcePath(srcPath, followLink); err != nil { + return err + } + + content, err := TarResource(srcInfo) + if err != nil { + return err + } + defer content.Close() + + return CopyTo(content, srcInfo, dstPath) +} + +// CopyTo handles extracting the given content whose +// entries should be sourced from srcInfo to dstPath. +func CopyTo(content io.Reader, srcInfo CopyInfo, dstPath string) error { + // The destination path need not exist, but CopyInfoDestinationPath will + // ensure that at least the parent directory exists. + dstInfo, err := CopyInfoDestinationPath(normalizePath(dstPath)) + if err != nil { + return err + } + + dstDir, copyArchive, err := PrepareArchiveCopy(content, srcInfo, dstInfo) + if err != nil { + return err + } + defer copyArchive.Close() + + options := &TarOptions{ + NoLchown: true, + NoOverwriteDirNonDir: true, + } + + return Untar(copyArchive, dstDir, options) +} + +// ResolveHostSourcePath decides real path need to be copied with parameters such as +// whether to follow symbol link or not, if followLink is true, resolvedPath will return +// link target of any symbol link file, else it will only resolve symlink of directory +// but return symbol link file itself without resolving. +func ResolveHostSourcePath(path string, followLink bool) (resolvedPath, rebaseName string, err error) { + if followLink { + resolvedPath, err = filepath.EvalSymlinks(path) + if err != nil { + return + } + + resolvedPath, rebaseName = GetRebaseName(path, resolvedPath) + } else { + dirPath, basePath := filepath.Split(path) + + // if not follow symbol link, then resolve symbol link of parent dir + var resolvedDirPath string + resolvedDirPath, err = filepath.EvalSymlinks(dirPath) + if err != nil { + return + } + // resolvedDirPath will have been cleaned (no trailing path separators) so + // we can manually join it with the base path element. + resolvedPath = resolvedDirPath + string(filepath.Separator) + basePath + if hasTrailingPathSeparator(path, os.PathSeparator) && + filepath.Base(path) != filepath.Base(resolvedPath) { + rebaseName = filepath.Base(path) + } + } + return resolvedPath, rebaseName, nil +} + +// GetRebaseName normalizes and compares path and resolvedPath, +// return completed resolved path and rebased file name +func GetRebaseName(path, resolvedPath string) (string, string) { + // linkTarget will have been cleaned (no trailing path separators and dot) so + // we can manually join it with them + var rebaseName string + if specifiesCurrentDir(path) && + !specifiesCurrentDir(resolvedPath) { + resolvedPath += string(filepath.Separator) + "." + } + + if hasTrailingPathSeparator(path, os.PathSeparator) && + !hasTrailingPathSeparator(resolvedPath, os.PathSeparator) { + resolvedPath += string(filepath.Separator) + } + + if filepath.Base(path) != filepath.Base(resolvedPath) { + // In the case where the path had a trailing separator and a symlink + // evaluation has changed the last path component, we will need to + // rebase the name in the archive that is being copied to match the + // originally requested name. + rebaseName = filepath.Base(path) + } + return resolvedPath, rebaseName +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/copy_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/copy_unix.go new file mode 100644 index 00000000..197df99b --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/copy_unix.go @@ -0,0 +1,15 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "path/filepath" +) + +func normalizePath(path string) string { + return filepath.ToSlash(path) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/copy_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/copy_windows.go new file mode 100644 index 00000000..40a86ef5 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/copy_windows.go @@ -0,0 +1,12 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "path/filepath" +) + +func normalizePath(path string) string { + return filepath.FromSlash(path) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/diff.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/diff.go new file mode 100644 index 00000000..e8abad44 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/diff.go @@ -0,0 +1,258 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "archive/tar" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" + + "github.com/ory/dockertest/v3/docker/pkg/idtools" + "github.com/ory/dockertest/v3/docker/pkg/pools" + "github.com/ory/dockertest/v3/docker/pkg/system" + "github.com/sirupsen/logrus" +) + +// UnpackLayer unpack `layer` to a `dest`. The stream `layer` can be +// compressed or uncompressed. +// Returns the size in bytes of the contents of the layer. +func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, err error) { + tr := tar.NewReader(layer) + trBuf := pools.BufioReader32KPool.Get(tr) + defer pools.BufioReader32KPool.Put(trBuf) + + var dirs []*tar.Header + unpackedPaths := make(map[string]struct{}) + + if options == nil { + options = &TarOptions{} + } + if options.ExcludePatterns == nil { + options.ExcludePatterns = []string{} + } + idMappings := idtools.NewIDMappingsFromMaps(options.UIDMaps, options.GIDMaps) + + aufsTempdir := "" + aufsHardlinks := make(map[string]*tar.Header) + + // Iterate through the files in the archive. + for { + hdr, err := tr.Next() + if err == io.EOF { + // end of tar archive + break + } + if err != nil { + return 0, err + } + + size += hdr.Size + + // Normalize name, for safety and for a simple is-root check + hdr.Name = filepath.Clean(hdr.Name) + + // Windows does not support filenames with colons in them. Ignore + // these files. This is not a problem though (although it might + // appear that it is). Let's suppose a client is running docker pull. + // The daemon it points to is Windows. Would it make sense for the + // client to be doing a docker pull Ubuntu for example (which has files + // with colons in the name under /usr/share/man/man3)? No, absolutely + // not as it would really only make sense that they were pulling a + // Windows image. However, for development, it is necessary to be able + // to pull Linux images which are in the repository. + // + // TODO Windows. Once the registry is aware of what images are Windows- + // specific or Linux-specific, this warning should be changed to an error + // to cater for the situation where someone does manage to upload a Linux + // image but have it tagged as Windows inadvertently. + if runtime.GOOS == "windows" { + if strings.Contains(hdr.Name, ":") { + logrus.Warnf("Windows: Ignoring %s (is this a Linux image?)", hdr.Name) + continue + } + } + + // Note as these operations are platform specific, so must the slash be. + if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { + // Not the root directory, ensure that the parent directory exists. + // This happened in some tests where an image had a tarfile without any + // parent directories. + parent := filepath.Dir(hdr.Name) + parentPath := filepath.Join(dest, parent) + + if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { + err = system.MkdirAll(parentPath, 0600, "") + if err != nil { + return 0, err + } + } + } + + // Skip AUFS metadata dirs + if strings.HasPrefix(hdr.Name, WhiteoutMetaPrefix) { + // Regular files inside /.wh..wh.plnk can be used as hardlink targets + // We don't want this directory, but we need the files in them so that + // such hardlinks can be resolved. + if strings.HasPrefix(hdr.Name, WhiteoutLinkDir) && hdr.Typeflag == tar.TypeReg { + basename := filepath.Base(hdr.Name) + aufsHardlinks[basename] = hdr + if aufsTempdir == "" { + if aufsTempdir, err = os.MkdirTemp("", "dockerplnk"); err != nil { + return 0, err + } + defer os.RemoveAll(aufsTempdir) + } + if err := createTarFile(filepath.Join(aufsTempdir, basename), dest, hdr, tr, true, nil, options.InUserNS); err != nil { + return 0, err + } + } + + if hdr.Name != WhiteoutOpaqueDir { + continue + } + } + path := filepath.Join(dest, hdr.Name) + rel, err := filepath.Rel(dest, path) + if err != nil { + return 0, err + } + + // Note as these operations are platform specific, so must the slash be. + if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { + return 0, breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) + } + base := filepath.Base(path) + + if strings.HasPrefix(base, WhiteoutPrefix) { + dir := filepath.Dir(path) + if base == WhiteoutOpaqueDir { + _, err := os.Lstat(dir) + if err != nil { + return 0, err + } + err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + if err != nil { + if os.IsNotExist(err) { + err = nil // parent was deleted + } + return err + } + if path == dir { + return nil + } + if _, exists := unpackedPaths[path]; !exists { + err := os.RemoveAll(path) + return err + } + return nil + }) + if err != nil { + return 0, err + } + } else { + originalBase := base[len(WhiteoutPrefix):] + originalPath := filepath.Join(dir, originalBase) + if err := os.RemoveAll(originalPath); err != nil { + return 0, err + } + } + } else { + // If path exits we almost always just want to remove and replace it. + // The only exception is when it is a directory *and* the file from + // the layer is also a directory. Then we want to merge them (i.e. + // just apply the metadata from the layer). + if fi, err := os.Lstat(path); err == nil { + if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) { + if err := os.RemoveAll(path); err != nil { + return 0, err + } + } + } + + trBuf.Reset(tr) + srcData := io.Reader(trBuf) + srcHdr := hdr + + // Hard links into /.wh..wh.plnk don't work, as we don't extract that directory, so + // we manually retarget these into the temporary files we extracted them into + if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(filepath.Clean(hdr.Linkname), WhiteoutLinkDir) { + linkBasename := filepath.Base(hdr.Linkname) + srcHdr = aufsHardlinks[linkBasename] + if srcHdr == nil { + return 0, fmt.Errorf("Invalid aufs hardlink") + } + tmpFile, err := os.Open(filepath.Join(aufsTempdir, linkBasename)) + if err != nil { + return 0, err + } + defer tmpFile.Close() + srcData = tmpFile + } + + if err := remapIDs(idMappings, srcHdr); err != nil { + return 0, err + } + + if err := createTarFile(path, dest, srcHdr, srcData, true, nil, options.InUserNS); err != nil { + return 0, err + } + + // Directory mtimes must be handled at the end to avoid further + // file creation in them to modify the directory mtime + if hdr.Typeflag == tar.TypeDir { + dirs = append(dirs, hdr) + } + unpackedPaths[path] = struct{}{} + } + } + + for _, hdr := range dirs { + path := filepath.Join(dest, hdr.Name) + if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { + return 0, err + } + } + + return size, nil +} + +// ApplyLayer parses a diff in the standard layer format from `layer`, +// and applies it to the directory `dest`. The stream `layer` can be +// compressed or uncompressed. +// Returns the size in bytes of the contents of the layer. +func ApplyLayer(dest string, layer io.Reader) (int64, error) { + return applyLayerHandler(dest, layer, &TarOptions{}, true) +} + +// ApplyUncompressedLayer parses a diff in the standard layer format from +// `layer`, and applies it to the directory `dest`. The stream `layer` +// can only be uncompressed. +// Returns the size in bytes of the contents of the layer. +func ApplyUncompressedLayer(dest string, layer io.Reader, options *TarOptions) (int64, error) { + return applyLayerHandler(dest, layer, options, false) +} + +// do the bulk load of ApplyLayer, but allow for not calling DecompressStream +func applyLayerHandler(dest string, layer io.Reader, options *TarOptions, decompress bool) (int64, error) { + dest = filepath.Clean(dest) + + // We need to be able to set any perms + oldmask, err := system.Umask(0) + if err != nil { + return 0, err + } + defer system.Umask(oldmask) // ignore err, ErrNotSupportedPlatform + + if decompress { + layer, err = DecompressStream(layer) + if err != nil { + return 0, err + } + } + return UnpackLayer(dest, layer, options) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/time_linux.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/time_linux.go new file mode 100644 index 00000000..1a83d4a6 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/time_linux.go @@ -0,0 +1,19 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "syscall" + "time" +) + +func timeToTimespec(time time.Time) (ts syscall.Timespec) { + if time.IsZero() { + // Return UTIME_OMIT special value + ts.Sec = 0 + ts.Nsec = ((1 << 30) - 2) + return + } + return syscall.NsecToTimespec(time.UnixNano()) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/time_unsupported.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/time_unsupported.go new file mode 100644 index 00000000..071147ad --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/time_unsupported.go @@ -0,0 +1,20 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !linux +// +build !linux + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "syscall" + "time" +) + +func timeToTimespec(time time.Time) (ts syscall.Timespec) { + nsec := int64(0) + if !time.IsZero() { + nsec = time.UnixNano() + } + return syscall.NsecToTimespec(nsec) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/whiteouts.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/whiteouts.go new file mode 100644 index 00000000..6de59297 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/whiteouts.go @@ -0,0 +1,26 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +// Whiteouts are files with a special meaning for the layered filesystem. +// Docker uses AUFS whiteout files inside exported archives. In other +// filesystems these files are generated/handled on tar creation/extraction. + +// WhiteoutPrefix prefix means file is a whiteout. If this is followed by a +// filename this means that file has been removed from the base layer. +const WhiteoutPrefix = ".wh." + +// WhiteoutMetaPrefix prefix means whiteout has a special meaning and is not +// for removing an actual file. Normally these files are excluded from exported +// archives. +const WhiteoutMetaPrefix = WhiteoutPrefix + WhiteoutPrefix + +// WhiteoutLinkDir is a directory AUFS uses for storing hardlink links to other +// layers. Normally these should not go into exported archives and all changed +// hardlinks should be copied to the top layer. +const WhiteoutLinkDir = WhiteoutMetaPrefix + "plnk" + +// WhiteoutOpaqueDir file means directory has been made opaque - meaning +// readdir calls to this directory do not follow to lower layers. +const WhiteoutOpaqueDir = WhiteoutMetaPrefix + ".opq" diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/wrap.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/wrap.go new file mode 100644 index 00000000..48d04ef7 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/archive/wrap.go @@ -0,0 +1,62 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" + +import ( + "archive/tar" + "bytes" + "io" +) + +// Generate generates a new archive from the content provided +// as input. +// +// `files` is a sequence of path/content pairs. A new file is +// added to the archive for each pair. +// If the last pair is incomplete, the file is created with an +// empty content. For example: +// +// Generate("foo.txt", "hello world", "emptyfile") +// +// The above call will return an archive with 2 files: +// - ./foo.txt with content "hello world" +// - ./empty with empty content +// +// FIXME: stream content instead of buffering +// FIXME: specify permissions and other archive metadata +func Generate(input ...string) (io.Reader, error) { + files := parseStringPairs(input...) + buf := new(bytes.Buffer) + tw := tar.NewWriter(buf) + for _, file := range files { + name, content := file[0], file[1] + hdr := &tar.Header{ + Name: name, + Size: int64(len(content)), + } + if err := tw.WriteHeader(hdr); err != nil { + return nil, err + } + if _, err := tw.Write([]byte(content)); err != nil { + return nil, err + } + } + if err := tw.Close(); err != nil { + return nil, err + } + return buf, nil +} + +func parseStringPairs(input ...string) (output [][2]string) { + output = make([][2]string, 0, len(input)/2+1) + for i := 0; i < len(input); i += 2 { + var pair [2]string + pair[0] = input[i] + if i+1 < len(input) { + pair[1] = input[i+1] + } + output = append(output, pair) + } + return +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/fileutils/fileutils.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/fileutils/fileutils.go new file mode 100644 index 00000000..02032bf9 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/fileutils/fileutils.go @@ -0,0 +1,301 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package fileutils // import "github.com/ory/dockertest/v3/docker/pkg/fileutils" + +import ( + "errors" + "fmt" + "io" + "os" + "path/filepath" + "regexp" + "strings" + "text/scanner" + + "github.com/sirupsen/logrus" +) + +// PatternMatcher allows checking paths agaist a list of patterns +type PatternMatcher struct { + patterns []*Pattern + exclusions bool +} + +// NewPatternMatcher creates a new matcher object for specific patterns that can +// be used later to match against patterns against paths +func NewPatternMatcher(patterns []string) (*PatternMatcher, error) { + pm := &PatternMatcher{ + patterns: make([]*Pattern, 0, len(patterns)), + } + for _, p := range patterns { + // Eliminate leading and trailing whitespace. + p = strings.TrimSpace(p) + if p == "" { + continue + } + p = filepath.Clean(p) + newp := &Pattern{} + if p[0] == '!' { + if len(p) == 1 { + return nil, errors.New("illegal exclusion pattern: \"!\"") + } + newp.exclusion = true + p = p[1:] + pm.exclusions = true + } + // Do some syntax checking on the pattern. + // filepath's Match() has some really weird rules that are inconsistent + // so instead of trying to dup their logic, just call Match() for its + // error state and if there is an error in the pattern return it. + // If this becomes an issue we can remove this since its really only + // needed in the error (syntax) case - which isn't really critical. + if _, err := filepath.Match(p, "."); err != nil { + return nil, err + } + newp.cleanedPattern = p + newp.dirs = strings.Split(p, string(os.PathSeparator)) + pm.patterns = append(pm.patterns, newp) + } + return pm, nil +} + +// Matches matches path against all the patterns. Matches is not safe to be +// called concurrently +func (pm *PatternMatcher) Matches(file string) (bool, error) { + matched := false + file = filepath.FromSlash(file) + parentPath := filepath.Dir(file) + parentPathDirs := strings.Split(parentPath, string(os.PathSeparator)) + + for _, pattern := range pm.patterns { + negative := false + + if pattern.exclusion { + negative = true + } + + match, err := pattern.match(file) + if err != nil { + return false, err + } + + if !match && parentPath != "." { + // Check to see if the pattern matches one of our parent dirs. + if len(pattern.dirs) <= len(parentPathDirs) { + match, _ = pattern.match(strings.Join(parentPathDirs[:len(pattern.dirs)], string(os.PathSeparator))) + } + } + + if match { + matched = !negative + } + } + + if matched { + logrus.Debugf("Skipping excluded path: %s", file) + } + + return matched, nil +} + +// Exclusions returns true if any of the patterns define exclusions +func (pm *PatternMatcher) Exclusions() bool { + return pm.exclusions +} + +// Patterns returns array of active patterns +func (pm *PatternMatcher) Patterns() []*Pattern { + return pm.patterns +} + +// Pattern defines a single regexp used used to filter file paths. +type Pattern struct { + cleanedPattern string + dirs []string + regexp *regexp.Regexp + exclusion bool +} + +func (p *Pattern) String() string { + return p.cleanedPattern +} + +// Exclusion returns true if this pattern defines exclusion +func (p *Pattern) Exclusion() bool { + return p.exclusion +} + +func (p *Pattern) match(path string) (bool, error) { + + if p.regexp == nil { + if err := p.compile(); err != nil { + return false, filepath.ErrBadPattern + } + } + + b := p.regexp.MatchString(path) + + return b, nil +} + +func (p *Pattern) compile() error { + regStr := "^" + pattern := p.cleanedPattern + // Go through the pattern and convert it to a regexp. + // We use a scanner so we can support utf-8 chars. + var scan scanner.Scanner + scan.Init(strings.NewReader(pattern)) + + sl := string(os.PathSeparator) + escSL := sl + if sl == `\` { + escSL += `\` + } + + for scan.Peek() != scanner.EOF { + ch := scan.Next() + + if ch == '*' { + if scan.Peek() == '*' { + // is some flavor of "**" + scan.Next() + + // Treat **/ as ** so eat the "/" + if string(scan.Peek()) == sl { + scan.Next() + } + + if scan.Peek() == scanner.EOF { + // is "**EOF" - to align with .gitignore just accept all + regStr += ".*" + } else { + // is "**" + // Note that this allows for any # of /'s (even 0) because + // the .* will eat everything, even /'s + regStr += "(.*" + escSL + ")?" + } + } else { + // is "*" so map it to anything but "/" + regStr += "[^" + escSL + "]*" + } + } else if ch == '?' { + // "?" is any char except "/" + regStr += "[^" + escSL + "]" + } else if ch == '.' || ch == '$' { + // Escape some regexp special chars that have no meaning + // in golang's filepath.Match + regStr += `\` + string(ch) + } else if ch == '\\' { + // escape next char. Note that a trailing \ in the pattern + // will be left alone (but need to escape it) + if sl == `\` { + // On windows map "\" to "\\", meaning an escaped backslash, + // and then just continue because filepath.Match on + // Windows doesn't allow escaping at all + regStr += escSL + continue + } + if scan.Peek() != scanner.EOF { + regStr += `\` + string(scan.Next()) + } else { + regStr += `\` + } + } else { + regStr += string(ch) + } + } + + regStr += "$" + + re, err := regexp.Compile(regStr) + if err != nil { + return err + } + + p.regexp = re + return nil +} + +// Matches returns true if file matches any of the patterns +// and isn't excluded by any of the subsequent patterns. +func Matches(file string, patterns []string) (bool, error) { + pm, err := NewPatternMatcher(patterns) + if err != nil { + return false, err + } + file = filepath.Clean(file) + + if file == "." { + // Don't let them exclude everything, kind of silly. + return false, nil + } + + return pm.Matches(file) +} + +// CopyFile copies from src to dst until either EOF is reached +// on src or an error occurs. It verifies src exists and removes +// the dst if it exists. +func CopyFile(src, dst string) (int64, error) { + cleanSrc := filepath.Clean(src) + cleanDst := filepath.Clean(dst) + if cleanSrc == cleanDst { + return 0, nil + } + sf, err := os.Open(cleanSrc) + if err != nil { + return 0, err + } + defer sf.Close() + if err := os.Remove(cleanDst); err != nil && !os.IsNotExist(err) { + return 0, err + } + df, err := os.Create(cleanDst) + if err != nil { + return 0, err + } + defer df.Close() + return io.Copy(df, sf) +} + +// ReadSymlinkedDirectory returns the target directory of a symlink. +// The target of the symbolic link may not be a file. +func ReadSymlinkedDirectory(path string) (string, error) { + var realPath string + var err error + if realPath, err = filepath.Abs(path); err != nil { + return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err) + } + if realPath, err = filepath.EvalSymlinks(realPath); err != nil { + return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err) + } + realPathInfo, err := os.Stat(realPath) + if err != nil { + return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err) + } + if !realPathInfo.Mode().IsDir() { + return "", fmt.Errorf("canonical path points to a file '%s'", realPath) + } + return realPath, nil +} + +// CreateIfNotExists creates a file or a directory only if it does not already exist. +func CreateIfNotExists(path string, isDir bool) error { + if _, err := os.Stat(path); err != nil { + if os.IsNotExist(err) { + if isDir { + return os.MkdirAll(path, 0755) + } + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + return err + } + f, err := os.OpenFile(path, os.O_CREATE, 0755) + if err != nil { + return err + } + f.Close() + } + } + return nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/fileutils/fileutils_darwin.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/fileutils/fileutils_darwin.go new file mode 100644 index 00000000..7a948e68 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/fileutils/fileutils_darwin.go @@ -0,0 +1,30 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package fileutils // import "github.com/ory/dockertest/v3/docker/pkg/fileutils" + +import ( + "os" + "os/exec" + "strconv" + "strings" +) + +// GetTotalUsedFds returns the number of used File Descriptors by +// executing `lsof -p PID` +func GetTotalUsedFds() int { + pid := os.Getpid() + + cmd := exec.Command("lsof", "-p", strconv.Itoa(pid)) + + output, err := cmd.CombinedOutput() + if err != nil { + return -1 + } + + outputStr := strings.TrimSpace(string(output)) + + fds := strings.Split(outputStr, "\n") + + return len(fds) - 1 +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/fileutils/fileutils_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/fileutils/fileutils_unix.go new file mode 100644 index 00000000..7f836b46 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/fileutils/fileutils_unix.go @@ -0,0 +1,25 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux || freebsd +// +build linux freebsd + +package fileutils // import "github.com/ory/dockertest/v3/docker/pkg/fileutils" + +import ( + "fmt" + "os" + + "github.com/sirupsen/logrus" +) + +// GetTotalUsedFds Returns the number of used File Descriptors by +// reading it via /proc filesystem. +func GetTotalUsedFds() int { + if fds, err := os.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil { + logrus.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err) + } else { + return len(fds) + } + return -1 +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/fileutils/fileutils_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/fileutils/fileutils_windows.go new file mode 100644 index 00000000..f0f8cc42 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/fileutils/fileutils_windows.go @@ -0,0 +1,10 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package fileutils // import "github.com/ory/dockertest/v3/docker/pkg/fileutils" + +// GetTotalUsedFds Returns the number of used File Descriptors. Not supported +// on Windows. +func GetTotalUsedFds() int { + return -1 +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/homedir/homedir_linux.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/homedir/homedir_linux.go new file mode 100644 index 00000000..76e866fd --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/homedir/homedir_linux.go @@ -0,0 +1,24 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package homedir // import "github.com/ory/dockertest/v3/docker/pkg/homedir" + +import ( + "os" + + "github.com/ory/dockertest/v3/docker/pkg/idtools" +) + +// GetStatic returns the home directory for the current user without calling +// os/user.Current(). This is useful for static-linked binary on glibc-based +// system, because a call to os/user.Current() in a static binary leads to +// segfault due to a glibc issue that won't be fixed in a short term. +// (#29344, golang/go#13470, https://sourceware.org/bugzilla/show_bug.cgi?id=19341) +func GetStatic() (string, error) { + uid := os.Getuid() + usr, err := idtools.LookupUID(uid) + if err != nil { + return "", err + } + return usr.Home, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/homedir/homedir_others.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/homedir/homedir_others.go new file mode 100644 index 00000000..051f896c --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/homedir/homedir_others.go @@ -0,0 +1,17 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !linux +// +build !linux + +package homedir // import "github.com/ory/dockertest/v3/docker/pkg/homedir" + +import ( + "errors" +) + +// GetStatic is not needed for non-linux systems. +// (Precisely, it is needed only for glibc-based linux systems.) +func GetStatic() (string, error) { + return "", errors.New("homedir.GetStatic() is not supported on this system") +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/homedir/homedir_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/homedir/homedir_unix.go new file mode 100644 index 00000000..68f44002 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/homedir/homedir_unix.go @@ -0,0 +1,38 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package homedir // import "github.com/ory/dockertest/v3/docker/pkg/homedir" + +import ( + "os" + + "github.com/opencontainers/runc/libcontainer/user" +) + +// Key returns the env var name for the user's home dir based on +// the platform being run on +func Key() string { + return "HOME" +} + +// Get returns the home directory of the current user with the help of +// environment variables depending on the target operating system. +// Returned path should be used with "path/filepath" to form new paths. +func Get() string { + home := os.Getenv(Key()) + if home == "" { + if u, err := user.CurrentUser(); err == nil { + return u.Home + } + } + return home +} + +// GetShortcutString returns the string that is shortcut to user's home directory +// in the native shell of the platform running on. +func GetShortcutString() string { + return "~" +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/homedir/homedir_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/homedir/homedir_windows.go new file mode 100644 index 00000000..23f681bb --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/homedir/homedir_windows.go @@ -0,0 +1,27 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package homedir // import "github.com/ory/dockertest/v3/docker/pkg/homedir" + +import ( + "os" +) + +// Key returns the env var name for the user's home dir based on +// the platform being run on +func Key() string { + return "USERPROFILE" +} + +// Get returns the home directory of the current user with the help of +// environment variables depending on the target operating system. +// Returned path should be used with "path/filepath" to form new paths. +func Get() string { + return os.Getenv(Key()) +} + +// GetShortcutString returns the string that is shortcut to user's home directory +// in the native shell of the platform running on. +func GetShortcutString() string { + return "%USERPROFILE%" // be careful while using in format functions +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/idtools.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/idtools.go new file mode 100644 index 00000000..9cefe67b --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/idtools.go @@ -0,0 +1,269 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package idtools // import "github.com/ory/dockertest/v3/docker/pkg/idtools" + +import ( + "bufio" + "fmt" + "os" + "sort" + "strconv" + "strings" +) + +// IDMap contains a single entry for user namespace range remapping. An array +// of IDMap entries represents the structure that will be provided to the Linux +// kernel for creating a user namespace. +type IDMap struct { + ContainerID int `json:"container_id"` + HostID int `json:"host_id"` + Size int `json:"size"` +} + +type subIDRange struct { + Start int + Length int +} + +type ranges []subIDRange + +func (e ranges) Len() int { return len(e) } +func (e ranges) Swap(i, j int) { e[i], e[j] = e[j], e[i] } +func (e ranges) Less(i, j int) bool { return e[i].Start < e[j].Start } + +const ( + subuidFileName string = "/etc/subuid" + subgidFileName string = "/etc/subgid" +) + +// MkdirAllAndChown creates a directory (include any along the path) and then modifies +// ownership to the requested uid/gid. If the directory already exists, this +// function will still change ownership to the requested uid/gid pair. +func MkdirAllAndChown(path string, mode os.FileMode, owner IDPair) error { + return mkdirAs(path, mode, owner.UID, owner.GID, true, true) +} + +// MkdirAndChown creates a directory and then modifies ownership to the requested uid/gid. +// If the directory already exists, this function still changes ownership. +// Note that unlike os.Mkdir(), this function does not return IsExist error +// in case path already exists. +func MkdirAndChown(path string, mode os.FileMode, owner IDPair) error { + return mkdirAs(path, mode, owner.UID, owner.GID, false, true) +} + +// MkdirAllAndChownNew creates a directory (include any along the path) and then modifies +// ownership ONLY of newly created directories to the requested uid/gid. If the +// directories along the path exist, no change of ownership will be performed +func MkdirAllAndChownNew(path string, mode os.FileMode, owner IDPair) error { + return mkdirAs(path, mode, owner.UID, owner.GID, true, false) +} + +// GetRootUIDGID retrieves the remapped root uid/gid pair from the set of maps. +// If the maps are empty, then the root uid/gid will default to "real" 0/0 +func GetRootUIDGID(uidMap, gidMap []IDMap) (int, int, error) { + uid, err := toHost(0, uidMap) + if err != nil { + return -1, -1, err + } + gid, err := toHost(0, gidMap) + if err != nil { + return -1, -1, err + } + return uid, gid, nil +} + +// toContainer takes an id mapping, and uses it to translate a +// host ID to the remapped ID. If no map is provided, then the translation +// assumes a 1-to-1 mapping and returns the passed in id +func toContainer(hostID int, idMap []IDMap) (int, error) { + if idMap == nil { + return hostID, nil + } + for _, m := range idMap { + if (hostID >= m.HostID) && (hostID <= (m.HostID + m.Size - 1)) { + contID := m.ContainerID + (hostID - m.HostID) + return contID, nil + } + } + return -1, fmt.Errorf("Host ID %d cannot be mapped to a container ID", hostID) +} + +// toHost takes an id mapping and a remapped ID, and translates the +// ID to the mapped host ID. If no map is provided, then the translation +// assumes a 1-to-1 mapping and returns the passed in id # +func toHost(contID int, idMap []IDMap) (int, error) { + if idMap == nil { + return contID, nil + } + for _, m := range idMap { + if (contID >= m.ContainerID) && (contID <= (m.ContainerID + m.Size - 1)) { + hostID := m.HostID + (contID - m.ContainerID) + return hostID, nil + } + } + return -1, fmt.Errorf("Container ID %d cannot be mapped to a host ID", contID) +} + +// IDPair is a UID and GID pair +type IDPair struct { + UID int + GID int +} + +// IDMappings contains a mappings of UIDs and GIDs +type IDMappings struct { + uids []IDMap + gids []IDMap +} + +// NewIDMappings takes a requested user and group name and +// using the data from /etc/sub{uid,gid} ranges, creates the +// proper uid and gid remapping ranges for that user/group pair +func NewIDMappings(username, groupname string) (*IDMappings, error) { + subuidRanges, err := parseSubuid(username) + if err != nil { + return nil, err + } + subgidRanges, err := parseSubgid(groupname) + if err != nil { + return nil, err + } + if len(subuidRanges) == 0 { + return nil, fmt.Errorf("No subuid ranges found for user %q", username) + } + if len(subgidRanges) == 0 { + return nil, fmt.Errorf("No subgid ranges found for group %q", groupname) + } + + return &IDMappings{ + uids: createIDMap(subuidRanges), + gids: createIDMap(subgidRanges), + }, nil +} + +// NewIDMappingsFromMaps creates a new mapping from two slices +// Deprecated: this is a temporary shim while transitioning to IDMapping +func NewIDMappingsFromMaps(uids []IDMap, gids []IDMap) *IDMappings { + return &IDMappings{uids: uids, gids: gids} +} + +// RootPair returns a uid and gid pair for the root user. The error is ignored +// because a root user always exists, and the defaults are correct when the uid +// and gid maps are empty. +func (i *IDMappings) RootPair() IDPair { + uid, gid, _ := GetRootUIDGID(i.uids, i.gids) + return IDPair{UID: uid, GID: gid} +} + +// ToHost returns the host UID and GID for the container uid, gid. +// Remapping is only performed if the ids aren't already the remapped root ids +func (i *IDMappings) ToHost(pair IDPair) (IDPair, error) { + var err error + target := i.RootPair() + + if pair.UID != target.UID { + target.UID, err = toHost(pair.UID, i.uids) + if err != nil { + return target, err + } + } + + if pair.GID != target.GID { + target.GID, err = toHost(pair.GID, i.gids) + } + return target, err +} + +// ToContainer returns the container UID and GID for the host uid and gid +func (i *IDMappings) ToContainer(pair IDPair) (int, int, error) { + uid, err := toContainer(pair.UID, i.uids) + if err != nil { + return -1, -1, err + } + gid, err := toContainer(pair.GID, i.gids) + return uid, gid, err +} + +// Empty returns true if there are no id mappings +func (i *IDMappings) Empty() bool { + return len(i.uids) == 0 && len(i.gids) == 0 +} + +// UIDs return the UID mapping +// TODO: remove this once everything has been refactored to use pairs +func (i *IDMappings) UIDs() []IDMap { + return i.uids +} + +// GIDs return the UID mapping +// TODO: remove this once everything has been refactored to use pairs +func (i *IDMappings) GIDs() []IDMap { + return i.gids +} + +func createIDMap(subidRanges ranges) []IDMap { + idMap := []IDMap{} + + // sort the ranges by lowest ID first + sort.Sort(subidRanges) + containerID := 0 + for _, idrange := range subidRanges { + idMap = append(idMap, IDMap{ + ContainerID: containerID, + HostID: idrange.Start, + Size: idrange.Length, + }) + containerID = containerID + idrange.Length + } + return idMap +} + +func parseSubuid(username string) (ranges, error) { + return parseSubidFile(subuidFileName, username) +} + +func parseSubgid(username string) (ranges, error) { + return parseSubidFile(subgidFileName, username) +} + +// parseSubidFile will read the appropriate file (/etc/subuid or /etc/subgid) +// and return all found ranges for a specified username. If the special value +// "ALL" is supplied for username, then all ranges in the file will be returned +func parseSubidFile(path, username string) (ranges, error) { + var rangeList ranges + + subidFile, err := os.Open(path) + if err != nil { + return rangeList, err + } + defer subidFile.Close() + + s := bufio.NewScanner(subidFile) + for s.Scan() { + if err := s.Err(); err != nil { + return rangeList, err + } + + text := strings.TrimSpace(s.Text()) + if text == "" || strings.HasPrefix(text, "#") { + continue + } + parts := strings.Split(text, ":") + if len(parts) != 3 { + return rangeList, fmt.Errorf("Cannot parse subuid/gid information: Format not correct for %s file", path) + } + if parts[0] == username || username == "ALL" { + startid, err := strconv.Atoi(parts[1]) + if err != nil { + return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err) + } + length, err := strconv.Atoi(parts[2]) + if err != nil { + return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err) + } + rangeList = append(rangeList, subIDRange{startid, length}) + } + } + return rangeList, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/idtools_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/idtools_unix.go new file mode 100644 index 00000000..3144e6ef --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/idtools_unix.go @@ -0,0 +1,234 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package idtools // import "github.com/ory/dockertest/v3/docker/pkg/idtools" + +import ( + "bytes" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "sync" + "syscall" + + "github.com/opencontainers/runc/libcontainer/user" + "github.com/ory/dockertest/v3/docker/pkg/system" +) + +var ( + entOnce sync.Once + getentCmd string +) + +func mkdirAs(path string, mode os.FileMode, ownerUID, ownerGID int, mkAll, chownExisting bool) error { + // make an array containing the original path asked for, plus (for mkAll == true) + // all path components leading up to the complete path that don't exist before we MkdirAll + // so that we can chown all of them properly at the end. If chownExisting is false, we won't + // chown the full directory path if it exists + var paths []string + + stat, err := system.Stat(path) + if err == nil { + if !stat.IsDir() { + return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR} + } + if !chownExisting { + return nil + } + + // short-circuit--we were called with an existing directory and chown was requested + return lazyChown(path, ownerUID, ownerGID, stat) + } + + if os.IsNotExist(err) { + paths = []string{path} + } + + if mkAll { + // walk back to "/" looking for directories which do not exist + // and add them to the paths array for chown after creation + dirPath := path + for { + dirPath = filepath.Dir(dirPath) + if dirPath == "/" { + break + } + if _, err := os.Stat(dirPath); err != nil && os.IsNotExist(err) { + paths = append(paths, dirPath) + } + } + if err := system.MkdirAll(path, mode, ""); err != nil { + return err + } + } else { + if err := os.Mkdir(path, mode); err != nil && !os.IsExist(err) { + return err + } + } + // even if it existed, we will chown the requested path + any subpaths that + // didn't exist when we called MkdirAll + for _, pathComponent := range paths { + if err := lazyChown(pathComponent, ownerUID, ownerGID, nil); err != nil { + return err + } + } + return nil +} + +// CanAccess takes a valid (existing) directory and a uid, gid pair and determines +// if that uid, gid pair has access (execute bit) to the directory +func CanAccess(path string, pair IDPair) bool { + statInfo, err := system.Stat(path) + if err != nil { + return false + } + fileMode := os.FileMode(statInfo.Mode()) + permBits := fileMode.Perm() + return accessible(statInfo.UID() == uint32(pair.UID), + statInfo.GID() == uint32(pair.GID), permBits) +} + +func accessible(isOwner, isGroup bool, perms os.FileMode) bool { + if isOwner && (perms&0100 == 0100) { + return true + } + if isGroup && (perms&0010 == 0010) { + return true + } + if perms&0001 == 0001 { + return true + } + return false +} + +// LookupUser uses traditional local system files lookup (from libcontainer/user) on a username, +// followed by a call to `getent` for supporting host configured non-files passwd and group dbs +func LookupUser(username string) (user.User, error) { + // first try a local system files lookup using existing capabilities + usr, err := user.LookupUser(username) + if err == nil { + return usr, nil + } + // local files lookup failed; attempt to call `getent` to query configured passwd dbs + usr, err = getentUser(fmt.Sprintf("%s %s", "passwd", username)) + if err != nil { + return user.User{}, err + } + return usr, nil +} + +// LookupUID uses traditional local system files lookup (from libcontainer/user) on a uid, +// followed by a call to `getent` for supporting host configured non-files passwd and group dbs +func LookupUID(uid int) (user.User, error) { + // first try a local system files lookup using existing capabilities + usr, err := user.LookupUid(uid) + if err == nil { + return usr, nil + } + // local files lookup failed; attempt to call `getent` to query configured passwd dbs + return getentUser(fmt.Sprintf("%s %d", "passwd", uid)) +} + +func getentUser(args string) (user.User, error) { + reader, err := callGetent(args) + if err != nil { + return user.User{}, err + } + users, err := user.ParsePasswd(reader) + if err != nil { + return user.User{}, err + } + if len(users) == 0 { + return user.User{}, fmt.Errorf("getent failed to find passwd entry for %q", strings.Split(args, " ")[1]) + } + return users[0], nil +} + +// LookupGroup uses traditional local system files lookup (from libcontainer/user) on a group name, +// followed by a call to `getent` for supporting host configured non-files passwd and group dbs +func LookupGroup(groupname string) (user.Group, error) { + // first try a local system files lookup using existing capabilities + group, err := user.LookupGroup(groupname) + if err == nil { + return group, nil + } + // local files lookup failed; attempt to call `getent` to query configured group dbs + return getentGroup(fmt.Sprintf("%s %s", "group", groupname)) +} + +// LookupGID uses traditional local system files lookup (from libcontainer/user) on a group ID, +// followed by a call to `getent` for supporting host configured non-files passwd and group dbs +func LookupGID(gid int) (user.Group, error) { + // first try a local system files lookup using existing capabilities + group, err := user.LookupGid(gid) + if err == nil { + return group, nil + } + // local files lookup failed; attempt to call `getent` to query configured group dbs + return getentGroup(fmt.Sprintf("%s %d", "group", gid)) +} + +func getentGroup(args string) (user.Group, error) { + reader, err := callGetent(args) + if err != nil { + return user.Group{}, err + } + groups, err := user.ParseGroup(reader) + if err != nil { + return user.Group{}, err + } + if len(groups) == 0 { + return user.Group{}, fmt.Errorf("getent failed to find groups entry for %q", strings.Split(args, " ")[1]) + } + return groups[0], nil +} + +func callGetent(args string) (io.Reader, error) { + entOnce.Do(func() { getentCmd, _ = resolveBinary("getent") }) + // if no `getent` command on host, can't do anything else + if getentCmd == "" { + return nil, fmt.Errorf("") + } + out, err := execCmd(getentCmd, args) + if err != nil { + exitCode, errC := system.GetExitCode(err) + if errC != nil { + return nil, err + } + switch exitCode { + case 1: + return nil, fmt.Errorf("getent reported invalid parameters/database unknown") + case 2: + terms := strings.Split(args, " ") + return nil, fmt.Errorf("getent unable to find entry %q in %s database", terms[1], terms[0]) + case 3: + return nil, fmt.Errorf("getent database doesn't support enumeration") + default: + return nil, err + } + + } + return bytes.NewReader(out), nil +} + +// lazyChown performs a chown only if the uid/gid don't match what's requested +// Normally a Chown is a no-op if uid/gid match, but in some cases this can still cause an error, e.g. if the +// dir is on an NFS share, so don't call chown unless we absolutely must. +func lazyChown(p string, uid, gid int, stat *system.StatT) error { + if stat == nil { + var err error + stat, err = system.Stat(p) + if err != nil { + return err + } + } + if stat.UID() == uint32(uid) && stat.GID() == uint32(gid) { + return nil + } + return os.Chown(p, uid, gid) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/idtools_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/idtools_windows.go new file mode 100644 index 00000000..8a6458fa --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/idtools_windows.go @@ -0,0 +1,26 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package idtools // import "github.com/ory/dockertest/v3/docker/pkg/idtools" + +import ( + "os" + + "github.com/ory/dockertest/v3/docker/pkg/system" +) + +// Platforms such as Windows do not support the UID/GID concept. So make this +// just a wrapper around system.MkdirAll. +func mkdirAs(path string, mode os.FileMode, ownerUID, ownerGID int, mkAll, chownExisting bool) error { + if err := system.MkdirAll(path, mode, ""); err != nil { + return err + } + return nil +} + +// CanAccess takes a valid (existing) directory and a uid, gid pair and determines +// if that uid, gid pair has access (execute bit) to the directory +// Windows does not require/support this function, so always return true +func CanAccess(path string, pair IDPair) bool { + return true +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/usergroupadd_linux.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/usergroupadd_linux.go new file mode 100644 index 00000000..505ccd29 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/usergroupadd_linux.go @@ -0,0 +1,167 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package idtools // import "github.com/ory/dockertest/v3/docker/pkg/idtools" + +import ( + "fmt" + "regexp" + "sort" + "strconv" + "strings" + "sync" +) + +// add a user and/or group to Linux /etc/passwd, /etc/group using standard +// Linux distribution commands: +// adduser --system --shell /bin/false --disabled-login --disabled-password --no-create-home --group +// useradd -r -s /bin/false + +var ( + once sync.Once + userCommand string + + cmdTemplates = map[string]string{ + "adduser": "--system --shell /bin/false --no-create-home --disabled-login --disabled-password --group %s", + "useradd": "-r -s /bin/false %s", + "usermod": "-%s %d-%d %s", + } + + idOutRegexp = regexp.MustCompile(`uid=([0-9]+).*gid=([0-9]+)`) + // default length for a UID/GID subordinate range + defaultRangeLen = 65536 + defaultRangeStart = 100000 + userMod = "usermod" +) + +// AddNamespaceRangesUser takes a username and uses the standard system +// utility to create a system user/group pair used to hold the +// /etc/sub{uid,gid} ranges which will be used for user namespace +// mapping ranges in containers. +func AddNamespaceRangesUser(name string) (int, int, error) { + if err := addUser(name); err != nil { + return -1, -1, fmt.Errorf("Error adding user %q: %v", name, err) + } + + // Query the system for the created uid and gid pair + out, err := execCmd("id", name) + if err != nil { + return -1, -1, fmt.Errorf("Error trying to find uid/gid for new user %q: %v", name, err) + } + matches := idOutRegexp.FindStringSubmatch(strings.TrimSpace(string(out))) + if len(matches) != 3 { + return -1, -1, fmt.Errorf("Can't find uid, gid from `id` output: %q", string(out)) + } + uid, err := strconv.Atoi(matches[1]) + if err != nil { + return -1, -1, fmt.Errorf("Can't convert found uid (%s) to int: %v", matches[1], err) + } + gid, err := strconv.Atoi(matches[2]) + if err != nil { + return -1, -1, fmt.Errorf("Can't convert found gid (%s) to int: %v", matches[2], err) + } + + // Now we need to create the subuid/subgid ranges for our new user/group (system users + // do not get auto-created ranges in subuid/subgid) + + if err := createSubordinateRanges(name); err != nil { + return -1, -1, fmt.Errorf("Couldn't create subordinate ID ranges: %v", err) + } + return uid, gid, nil +} + +func addUser(userName string) error { + once.Do(func() { + // set up which commands are used for adding users/groups dependent on distro + if _, err := resolveBinary("adduser"); err == nil { + userCommand = "adduser" + } else if _, err := resolveBinary("useradd"); err == nil { + userCommand = "useradd" + } + }) + if userCommand == "" { + return fmt.Errorf("Cannot add user; no useradd/adduser binary found") + } + args := fmt.Sprintf(cmdTemplates[userCommand], userName) + out, err := execCmd(userCommand, args) + if err != nil { + return fmt.Errorf("Failed to add user with error: %v; output: %q", err, string(out)) + } + return nil +} + +func createSubordinateRanges(name string) error { + + // first, we should verify that ranges weren't automatically created + // by the distro tooling + ranges, err := parseSubuid(name) + if err != nil { + return fmt.Errorf("Error while looking for subuid ranges for user %q: %v", name, err) + } + if len(ranges) == 0 { + // no UID ranges; let's create one + startID, err := findNextUIDRange() + if err != nil { + return fmt.Errorf("Can't find available subuid range: %v", err) + } + out, err := execCmd(userMod, fmt.Sprintf(cmdTemplates[userMod], "v", startID, startID+defaultRangeLen-1, name)) + if err != nil { + return fmt.Errorf("Unable to add subuid range to user: %q; output: %s, err: %v", name, out, err) + } + } + + ranges, err = parseSubgid(name) + if err != nil { + return fmt.Errorf("Error while looking for subgid ranges for user %q: %v", name, err) + } + if len(ranges) == 0 { + // no GID ranges; let's create one + startID, err := findNextGIDRange() + if err != nil { + return fmt.Errorf("Can't find available subgid range: %v", err) + } + out, err := execCmd(userMod, fmt.Sprintf(cmdTemplates[userMod], "w", startID, startID+defaultRangeLen-1, name)) + if err != nil { + return fmt.Errorf("Unable to add subgid range to user: %q; output: %s, err: %v", name, out, err) + } + } + return nil +} + +func findNextUIDRange() (int, error) { + ranges, err := parseSubuid("ALL") + if err != nil { + return -1, fmt.Errorf("Couldn't parse all ranges in /etc/subuid file: %v", err) + } + sort.Sort(ranges) + return findNextRangeStart(ranges) +} + +func findNextGIDRange() (int, error) { + ranges, err := parseSubgid("ALL") + if err != nil { + return -1, fmt.Errorf("Couldn't parse all ranges in /etc/subgid file: %v", err) + } + sort.Sort(ranges) + return findNextRangeStart(ranges) +} + +func findNextRangeStart(rangeList ranges) (int, error) { + startID := defaultRangeStart + for _, arange := range rangeList { + if wouldOverlap(arange, startID) { + startID = arange.Start + arange.Length + } + } + return startID, nil +} + +func wouldOverlap(arange subIDRange, ID int) bool { + low := ID + high := ID + defaultRangeLen + if (low >= arange.Start && low <= arange.Start+arange.Length) || + (high <= arange.Start+arange.Length && high >= arange.Start) { + return true + } + return false +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/usergroupadd_unsupported.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/usergroupadd_unsupported.go new file mode 100644 index 00000000..65fb83c9 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/usergroupadd_unsupported.go @@ -0,0 +1,16 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !linux +// +build !linux + +package idtools // import "github.com/ory/dockertest/v3/docker/pkg/idtools" + +import "fmt" + +// AddNamespaceRangesUser takes a name and finds an unused uid, gid pair +// and calls the appropriate helper function to add the group and then +// the user to the group in /etc/group and /etc/passwd respectively. +func AddNamespaceRangesUser(name string) (int, int, error) { + return -1, -1, fmt.Errorf("No support for adding users or groups on this OS") +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/utils_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/utils_unix.go new file mode 100644 index 00000000..dea07537 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/idtools/utils_unix.go @@ -0,0 +1,36 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package idtools // import "github.com/ory/dockertest/v3/docker/pkg/idtools" + +import ( + "fmt" + "os/exec" + "path/filepath" + "strings" +) + +func resolveBinary(binname string) (string, error) { + binaryPath, err := exec.LookPath(binname) + if err != nil { + return "", err + } + resolvedPath, err := filepath.EvalSymlinks(binaryPath) + if err != nil { + return "", err + } + //only return no error if the final resolved binary basename + //matches what was searched for + if filepath.Base(resolvedPath) == binname { + return resolvedPath, nil + } + return "", fmt.Errorf("Binary %q does not resolve to a binary of that name in $PATH (%q)", binname, resolvedPath) +} + +func execCmd(cmd, args string) ([]byte, error) { + execCmd := exec.Command(cmd, strings.Split(args, " ")...) + return execCmd.CombinedOutput() +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/buffer.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/buffer.go new file mode 100644 index 00000000..52257525 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/buffer.go @@ -0,0 +1,54 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package ioutils // import "github.com/ory/dockertest/v3/docker/pkg/ioutils" + +import ( + "errors" + "io" +) + +var errBufferFull = errors.New("buffer is full") + +type fixedBuffer struct { + buf []byte + pos int + lastRead int +} + +func (b *fixedBuffer) Write(p []byte) (int, error) { + n := copy(b.buf[b.pos:cap(b.buf)], p) + b.pos += n + + if n < len(p) { + if b.pos == cap(b.buf) { + return n, errBufferFull + } + return n, io.ErrShortWrite + } + return n, nil +} + +func (b *fixedBuffer) Read(p []byte) (int, error) { + n := copy(p, b.buf[b.lastRead:b.pos]) + b.lastRead += n + return n, nil +} + +func (b *fixedBuffer) Len() int { + return b.pos - b.lastRead +} + +func (b *fixedBuffer) Cap() int { + return cap(b.buf) +} + +func (b *fixedBuffer) Reset() { + b.pos = 0 + b.lastRead = 0 + b.buf = b.buf[:0] +} + +func (b *fixedBuffer) String() string { + return string(b.buf[b.lastRead:b.pos]) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/bytespipe.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/bytespipe.go new file mode 100644 index 00000000..e2ba15e7 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/bytespipe.go @@ -0,0 +1,189 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package ioutils // import "github.com/ory/dockertest/v3/docker/pkg/ioutils" + +import ( + "errors" + "io" + "sync" +) + +// maxCap is the highest capacity to use in byte slices that buffer data. +const maxCap = 1e6 + +// minCap is the lowest capacity to use in byte slices that buffer data +const minCap = 64 + +// blockThreshold is the minimum number of bytes in the buffer which will cause +// a write to BytesPipe to block when allocating a new slice. +const blockThreshold = 1e6 + +var ( + // ErrClosed is returned when Write is called on a closed BytesPipe. + ErrClosed = errors.New("write to closed BytesPipe") + + bufPools = make(map[int]*sync.Pool) + bufPoolsLock sync.Mutex +) + +// BytesPipe is io.ReadWriteCloser which works similarly to pipe(queue). +// All written data may be read at most once. Also, BytesPipe allocates +// and releases new byte slices to adjust to current needs, so the buffer +// won't be overgrown after peak loads. +type BytesPipe struct { + mu sync.Mutex + wait *sync.Cond + buf []*fixedBuffer + bufLen int + closeErr error // error to return from next Read. set to nil if not closed. +} + +// NewBytesPipe creates new BytesPipe, initialized by specified slice. +// If buf is nil, then it will be initialized with slice which cap is 64. +// buf will be adjusted in a way that len(buf) == 0, cap(buf) == cap(buf). +func NewBytesPipe() *BytesPipe { + bp := &BytesPipe{} + bp.buf = append(bp.buf, getBuffer(minCap)) + bp.wait = sync.NewCond(&bp.mu) + return bp +} + +// Write writes p to BytesPipe. +// It can allocate new []byte slices in a process of writing. +func (bp *BytesPipe) Write(p []byte) (int, error) { + bp.mu.Lock() + + written := 0 +loop0: + for { + if bp.closeErr != nil { + bp.mu.Unlock() + return written, ErrClosed + } + + if len(bp.buf) == 0 { + bp.buf = append(bp.buf, getBuffer(64)) + } + // get the last buffer + b := bp.buf[len(bp.buf)-1] + + n, err := b.Write(p) + written += n + bp.bufLen += n + + // errBufferFull is an error we expect to get if the buffer is full + if err != nil && err != errBufferFull { + bp.wait.Broadcast() + bp.mu.Unlock() + return written, err + } + + // if there was enough room to write all then break + if len(p) == n { + break + } + + // more data: write to the next slice + p = p[n:] + + // make sure the buffer doesn't grow too big from this write + for bp.bufLen >= blockThreshold { + bp.wait.Wait() + if bp.closeErr != nil { + continue loop0 + } + } + + // add new byte slice to the buffers slice and continue writing + nextCap := b.Cap() * 2 + if nextCap > maxCap { + nextCap = maxCap + } + bp.buf = append(bp.buf, getBuffer(nextCap)) + } + bp.wait.Broadcast() + bp.mu.Unlock() + return written, nil +} + +// CloseWithError causes further reads from a BytesPipe to return immediately. +func (bp *BytesPipe) CloseWithError(err error) error { + bp.mu.Lock() + if err != nil { + bp.closeErr = err + } else { + bp.closeErr = io.EOF + } + bp.wait.Broadcast() + bp.mu.Unlock() + return nil +} + +// Close causes further reads from a BytesPipe to return immediately. +func (bp *BytesPipe) Close() error { + return bp.CloseWithError(nil) +} + +// Read reads bytes from BytesPipe. +// Data could be read only once. +func (bp *BytesPipe) Read(p []byte) (n int, err error) { + bp.mu.Lock() + if bp.bufLen == 0 { + if bp.closeErr != nil { + bp.mu.Unlock() + return 0, bp.closeErr + } + bp.wait.Wait() + if bp.bufLen == 0 && bp.closeErr != nil { + err := bp.closeErr + bp.mu.Unlock() + return 0, err + } + } + + for bp.bufLen > 0 { + b := bp.buf[0] + read, _ := b.Read(p) // ignore error since fixedBuffer doesn't really return an error + n += read + bp.bufLen -= read + + if b.Len() == 0 { + // it's empty so return it to the pool and move to the next one + returnBuffer(b) + bp.buf[0] = nil + bp.buf = bp.buf[1:] + } + + if len(p) == read { + break + } + + p = p[read:] + } + + bp.wait.Broadcast() + bp.mu.Unlock() + return +} + +func returnBuffer(b *fixedBuffer) { + b.Reset() + bufPoolsLock.Lock() + pool := bufPools[b.Cap()] + bufPoolsLock.Unlock() + if pool != nil { + pool.Put(b) + } +} + +func getBuffer(size int) *fixedBuffer { + bufPoolsLock.Lock() + pool, ok := bufPools[size] + if !ok { + pool = &sync.Pool{New: func() interface{} { return &fixedBuffer{buf: make([]byte, 0, size)} }} + bufPools[size] = pool + } + bufPoolsLock.Unlock() + return pool.Get().(*fixedBuffer) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/fswriters.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/fswriters.go new file mode 100644 index 00000000..ca3b09e2 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/fswriters.go @@ -0,0 +1,164 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package ioutils // import "github.com/ory/dockertest/v3/docker/pkg/ioutils" + +import ( + "io" + "os" + "path/filepath" +) + +// NewAtomicFileWriter returns WriteCloser so that writing to it writes to a +// temporary file and closing it atomically changes the temporary file to +// destination path. Writing and closing concurrently is not allowed. +func NewAtomicFileWriter(filename string, perm os.FileMode) (io.WriteCloser, error) { + f, err := os.CreateTemp(filepath.Dir(filename), ".tmp-"+filepath.Base(filename)) + if err != nil { + return nil, err + } + + abspath, err := filepath.Abs(filename) + if err != nil { + return nil, err + } + return &atomicFileWriter{ + f: f, + fn: abspath, + perm: perm, + }, nil +} + +// AtomicWriteFile atomically writes data to a file named by filename. +func AtomicWriteFile(filename string, data []byte, perm os.FileMode) error { + f, err := NewAtomicFileWriter(filename, perm) + if err != nil { + return err + } + n, err := f.Write(data) + if err == nil && n < len(data) { + err = io.ErrShortWrite + f.(*atomicFileWriter).writeErr = err + } + if err1 := f.Close(); err == nil { + err = err1 + } + return err +} + +type atomicFileWriter struct { + f *os.File + fn string + writeErr error + perm os.FileMode +} + +func (w *atomicFileWriter) Write(dt []byte) (int, error) { + n, err := w.f.Write(dt) + if err != nil { + w.writeErr = err + } + return n, err +} + +func (w *atomicFileWriter) Close() (retErr error) { + defer func() { + if retErr != nil || w.writeErr != nil { + os.Remove(w.f.Name()) + } + }() + if err := w.f.Sync(); err != nil { + w.f.Close() + return err + } + if err := w.f.Close(); err != nil { + return err + } + if err := os.Chmod(w.f.Name(), w.perm); err != nil { + return err + } + if w.writeErr == nil { + return os.Rename(w.f.Name(), w.fn) + } + return nil +} + +// AtomicWriteSet is used to atomically write a set +// of files and ensure they are visible at the same time. +// Must be committed to a new directory. +type AtomicWriteSet struct { + root string +} + +// NewAtomicWriteSet creates a new atomic write set to +// atomically create a set of files. The given directory +// is used as the base directory for storing files before +// commit. If no temporary directory is given the system +// default is used. +func NewAtomicWriteSet(tmpDir string) (*AtomicWriteSet, error) { + td, err := os.MkdirTemp(tmpDir, "write-set-") + if err != nil { + return nil, err + } + + return &AtomicWriteSet{ + root: td, + }, nil +} + +// WriteFile writes a file to the set, guaranteeing the file +// has been synced. +func (ws *AtomicWriteSet) WriteFile(filename string, data []byte, perm os.FileMode) error { + f, err := ws.FileWriter(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) + if err != nil { + return err + } + n, err := f.Write(data) + if err == nil && n < len(data) { + err = io.ErrShortWrite + } + if err1 := f.Close(); err == nil { + err = err1 + } + return err +} + +type syncFileCloser struct { + *os.File +} + +func (w syncFileCloser) Close() error { + err := w.File.Sync() + if err1 := w.File.Close(); err == nil { + err = err1 + } + return err +} + +// FileWriter opens a file writer inside the set. The file +// should be synced and closed before calling commit. +func (ws *AtomicWriteSet) FileWriter(name string, flag int, perm os.FileMode) (io.WriteCloser, error) { + f, err := os.OpenFile(filepath.Join(ws.root, name), flag, perm) + if err != nil { + return nil, err + } + return syncFileCloser{f}, nil +} + +// Cancel cancels the set and removes all temporary data +// created in the set. +func (ws *AtomicWriteSet) Cancel() error { + return os.RemoveAll(ws.root) +} + +// Commit moves all created files to the target directory. The +// target directory must not exist and the parent of the target +// directory must exist. +func (ws *AtomicWriteSet) Commit(target string) error { + return os.Rename(ws.root, target) +} + +// String returns the location the set is writing to. +func (ws *AtomicWriteSet) String() string { + return ws.root +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/readers.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/readers.go new file mode 100644 index 00000000..79178afa --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/readers.go @@ -0,0 +1,160 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package ioutils // import "github.com/ory/dockertest/v3/docker/pkg/ioutils" + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "io" +) + +// ReadCloserWrapper wraps an io.Reader, and implements an io.ReadCloser +// It calls the given callback function when closed. It should be constructed +// with NewReadCloserWrapper +type ReadCloserWrapper struct { + io.Reader + closer func() error +} + +// Close calls back the passed closer function +func (r *ReadCloserWrapper) Close() error { + return r.closer() +} + +// NewReadCloserWrapper returns a new io.ReadCloser. +func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser { + return &ReadCloserWrapper{ + Reader: r, + closer: closer, + } +} + +type readerErrWrapper struct { + reader io.Reader + closer func() +} + +func (r *readerErrWrapper) Read(p []byte) (int, error) { + n, err := r.reader.Read(p) + if err != nil { + r.closer() + } + return n, err +} + +// NewReaderErrWrapper returns a new io.Reader. +func NewReaderErrWrapper(r io.Reader, closer func()) io.Reader { + return &readerErrWrapper{ + reader: r, + closer: closer, + } +} + +// HashData returns the sha256 sum of src. +func HashData(src io.Reader) (string, error) { + h := sha256.New() + if _, err := io.Copy(h, src); err != nil { + return "", err + } + return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil +} + +// OnEOFReader wraps an io.ReadCloser and a function +// the function will run at the end of file or close the file. +type OnEOFReader struct { + Rc io.ReadCloser + Fn func() +} + +func (r *OnEOFReader) Read(p []byte) (n int, err error) { + n, err = r.Rc.Read(p) + if err == io.EOF { + r.runFunc() + } + return +} + +// Close closes the file and run the function. +func (r *OnEOFReader) Close() error { + err := r.Rc.Close() + r.runFunc() + return err +} + +func (r *OnEOFReader) runFunc() { + if fn := r.Fn; fn != nil { + fn() + r.Fn = nil + } +} + +// cancelReadCloser wraps an io.ReadCloser with a context for cancelling read +// operations. +type cancelReadCloser struct { + cancel func() + pR *io.PipeReader // Stream to read from + pW *io.PipeWriter +} + +// NewCancelReadCloser creates a wrapper that closes the ReadCloser when the +// context is cancelled. The returned io.ReadCloser must be closed when it is +// no longer needed. +func NewCancelReadCloser(ctx context.Context, in io.ReadCloser) io.ReadCloser { + pR, pW := io.Pipe() + + // Create a context used to signal when the pipe is closed + doneCtx, cancel := context.WithCancel(context.Background()) + + p := &cancelReadCloser{ + cancel: cancel, + pR: pR, + pW: pW, + } + + go func() { + _, err := io.Copy(pW, in) + select { + case <-ctx.Done(): + // If the context was closed, p.closeWithError + // was already called. Calling it again would + // change the error that Read returns. + default: + p.closeWithError(err) + } + in.Close() + }() + go func() { + for { + select { + case <-ctx.Done(): + p.closeWithError(ctx.Err()) + case <-doneCtx.Done(): + return + } + } + }() + + return p +} + +// Read wraps the Read method of the pipe that provides data from the wrapped +// ReadCloser. +func (p *cancelReadCloser) Read(buf []byte) (n int, err error) { + return p.pR.Read(buf) +} + +// closeWithError closes the wrapper and its underlying reader. It will +// cause future calls to Read to return err. +func (p *cancelReadCloser) closeWithError(err error) { + p.pW.CloseWithError(err) + p.cancel() +} + +// Close closes the wrapper its underlying reader. It will cause +// future calls to Read to return io.EOF. +func (p *cancelReadCloser) Close() error { + p.closeWithError(io.EOF) + return nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/temp_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/temp_unix.go new file mode 100644 index 00000000..aa4ef443 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/temp_unix.go @@ -0,0 +1,14 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package ioutils // import "github.com/ory/dockertest/v3/docker/pkg/ioutils" + +import "os" + +// TempDir on Unix systems is equivalent to os.MkdirTemp. +func TempDir(dir, prefix string) (string, error) { + return os.MkdirTemp(dir, prefix) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/temp_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/temp_windows.go new file mode 100644 index 00000000..269ff92d --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/temp_windows.go @@ -0,0 +1,19 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package ioutils // import "github.com/ory/dockertest/v3/docker/pkg/ioutils" + +import ( + "os" + + "github.com/ory/dockertest/v3/docker/pkg/longpath" +) + +// TempDir is the equivalent of os.MkdirTemp, except that the result is in Windows longpath format. +func TempDir(dir, prefix string) (string, error) { + tempDir, err := os.MkdirTemp(dir, prefix) + if err != nil { + return "", err + } + return longpath.AddPrefix(tempDir), nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/writeflusher.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/writeflusher.go new file mode 100644 index 00000000..0ad74ee1 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/writeflusher.go @@ -0,0 +1,95 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package ioutils // import "github.com/ory/dockertest/v3/docker/pkg/ioutils" + +import ( + "io" + "sync" +) + +// WriteFlusher wraps the Write and Flush operation ensuring that every write +// is a flush. In addition, the Close method can be called to intercept +// Read/Write calls if the targets lifecycle has already ended. +type WriteFlusher struct { + w io.Writer + flusher flusher + flushed chan struct{} + flushedOnce sync.Once + closed chan struct{} + closeLock sync.Mutex +} + +type flusher interface { + Flush() +} + +var errWriteFlusherClosed = io.EOF + +func (wf *WriteFlusher) Write(b []byte) (n int, err error) { + select { + case <-wf.closed: + return 0, errWriteFlusherClosed + default: + } + + n, err = wf.w.Write(b) + wf.Flush() // every write is a flush. + return n, err +} + +// Flush the stream immediately. +func (wf *WriteFlusher) Flush() { + select { + case <-wf.closed: + return + default: + } + + wf.flushedOnce.Do(func() { + close(wf.flushed) + }) + wf.flusher.Flush() +} + +// Flushed returns the state of flushed. +// If it's flushed, return true, or else it return false. +func (wf *WriteFlusher) Flushed() bool { + // BUG(stevvooe): Remove this method. Its use is inherently racy. Seems to + // be used to detect whether or a response code has been issued or not. + // Another hook should be used instead. + var flushed bool + select { + case <-wf.flushed: + flushed = true + default: + } + return flushed +} + +// Close closes the write flusher, disallowing any further writes to the +// target. After the flusher is closed, all calls to write or flush will +// result in an error. +func (wf *WriteFlusher) Close() error { + wf.closeLock.Lock() + defer wf.closeLock.Unlock() + + select { + case <-wf.closed: + return errWriteFlusherClosed + default: + close(wf.closed) + } + return nil +} + +// NewWriteFlusher returns a new WriteFlusher. +func NewWriteFlusher(w io.Writer) *WriteFlusher { + var fl flusher + if f, ok := w.(flusher); ok { + fl = f + } else { + fl = &NopFlusher{} + } + return &WriteFlusher{w: w, flusher: fl, closed: make(chan struct{}), flushed: make(chan struct{})} +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/writers.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/writers.go new file mode 100644 index 00000000..e60fdbc9 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/ioutils/writers.go @@ -0,0 +1,69 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package ioutils // import "github.com/ory/dockertest/v3/docker/pkg/ioutils" + +import "io" + +// NopWriter represents a type which write operation is nop. +type NopWriter struct{} + +func (*NopWriter) Write(buf []byte) (int, error) { + return len(buf), nil +} + +type nopWriteCloser struct { + io.Writer +} + +func (w *nopWriteCloser) Close() error { return nil } + +// NopWriteCloser returns a nopWriteCloser. +func NopWriteCloser(w io.Writer) io.WriteCloser { + return &nopWriteCloser{w} +} + +// NopFlusher represents a type which flush operation is nop. +type NopFlusher struct{} + +// Flush is a nop operation. +func (f *NopFlusher) Flush() {} + +type writeCloserWrapper struct { + io.Writer + closer func() error +} + +func (r *writeCloserWrapper) Close() error { + return r.closer() +} + +// NewWriteCloserWrapper returns a new io.WriteCloser. +func NewWriteCloserWrapper(r io.Writer, closer func() error) io.WriteCloser { + return &writeCloserWrapper{ + Writer: r, + closer: closer, + } +} + +// WriteCounter wraps a concrete io.Writer and hold a count of the number +// of bytes written to the writer during a "session". +// This can be convenient when write return is masked +// (e.g., json.Encoder.Encode()) +type WriteCounter struct { + Count int64 + Writer io.Writer +} + +// NewWriteCounter returns a new WriteCounter. +func NewWriteCounter(w io.Writer) *WriteCounter { + return &WriteCounter{ + Writer: w, + } +} + +func (wc *WriteCounter) Write(p []byte) (count int, err error) { + count, err = wc.Writer.Write(p) + wc.Count += int64(count) + return +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/jsonmessage/jsonmessage.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/jsonmessage/jsonmessage.go new file mode 100644 index 00000000..03a1bfd5 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/jsonmessage/jsonmessage.go @@ -0,0 +1,338 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package jsonmessage // import "github.com/ory/dockertest/v3/docker/pkg/jsonmessage" + +import ( + "encoding/json" + "fmt" + "io" + "os" + "strings" + "time" + + gotty "github.com/Nvveen/Gotty" + units "github.com/docker/go-units" + "github.com/moby/term" +) + +// RFC3339NanoFixed is time.RFC3339Nano with nanoseconds padded using zeros to +// ensure the formatted time isalways the same number of characters. +const RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00" + +// JSONError wraps a concrete Code and Message, `Code` is +// is an integer error code, `Message` is the error message. +type JSONError struct { + Code int `json:"code,omitempty"` + Message string `json:"message,omitempty"` +} + +func (e *JSONError) Error() string { + return e.Message +} + +// JSONProgress describes a Progress. terminalFd is the fd of the current terminal, +// Start is the initial value for the operation. Current is the current status and +// value of the progress made towards Total. Total is the end value describing when +// we made 100% progress for an operation. +type JSONProgress struct { + terminalFd uintptr + Current int64 `json:"current,omitempty"` + Total int64 `json:"total,omitempty"` + Start int64 `json:"start,omitempty"` + // If true, don't show xB/yB + HideCounts bool `json:"hidecounts,omitempty"` + Units string `json:"units,omitempty"` + nowFunc func() time.Time + winSize int +} + +func (p *JSONProgress) String() string { + var ( + width = p.width() + pbBox string + numbersBox string + timeLeftBox string + ) + if p.Current <= 0 && p.Total <= 0 { + return "" + } + if p.Total <= 0 { + switch p.Units { + case "": + current := units.HumanSize(float64(p.Current)) + return fmt.Sprintf("%8v", current) + default: + return fmt.Sprintf("%d %s", p.Current, p.Units) + } + } + + percentage := int(float64(p.Current)/float64(p.Total)*100) / 2 + if percentage > 50 { + percentage = 50 + } + if width > 110 { + // this number can't be negative gh#7136 + numSpaces := 0 + if 50-percentage > 0 { + numSpaces = 50 - percentage + } + pbBox = fmt.Sprintf("[%s>%s] ", strings.Repeat("=", percentage), strings.Repeat(" ", numSpaces)) + } + + switch { + case p.HideCounts: + case p.Units == "": // no units, use bytes + current := units.HumanSize(float64(p.Current)) + total := units.HumanSize(float64(p.Total)) + + numbersBox = fmt.Sprintf("%8v/%v", current, total) + + if p.Current > p.Total { + // remove total display if the reported current is wonky. + numbersBox = fmt.Sprintf("%8v", current) + } + default: + numbersBox = fmt.Sprintf("%d/%d %s", p.Current, p.Total, p.Units) + + if p.Current > p.Total { + // remove total display if the reported current is wonky. + numbersBox = fmt.Sprintf("%d %s", p.Current, p.Units) + } + } + + if p.Current > 0 && p.Start > 0 && percentage < 50 { + fromStart := p.now().Sub(time.Unix(p.Start, 0)) + perEntry := fromStart / time.Duration(p.Current) + left := time.Duration(p.Total-p.Current) * perEntry + left = (left / time.Second) * time.Second + + if width > 50 { + timeLeftBox = " " + left.String() + } + } + return pbBox + numbersBox + timeLeftBox +} + +// shim for testing +func (p *JSONProgress) now() time.Time { + if p.nowFunc == nil { + p.nowFunc = func() time.Time { + return time.Now().UTC() + } + } + return p.nowFunc() +} + +// shim for testing +func (p *JSONProgress) width() int { + if p.winSize != 0 { + return p.winSize + } + ws, err := term.GetWinsize(p.terminalFd) + if err == nil { + return int(ws.Width) + } + return 200 +} + +// JSONMessage defines a message struct. It describes +// the created time, where it from, status, ID of the +// message. It's used for docker events. +type JSONMessage struct { + Stream string `json:"stream,omitempty"` + Status string `json:"status,omitempty"` + Progress *JSONProgress `json:"progressDetail,omitempty"` + ProgressMessage string `json:"progress,omitempty"` //deprecated + ID string `json:"id,omitempty"` + From string `json:"from,omitempty"` + Time int64 `json:"time,omitempty"` + TimeNano int64 `json:"timeNano,omitempty"` + Error *JSONError `json:"errorDetail,omitempty"` + ErrorMessage string `json:"error,omitempty"` //deprecated + // Aux contains out-of-band data, such as digests for push signing and image id after building. + Aux *json.RawMessage `json:"aux,omitempty"` +} + +/* Satisfied by gotty.TermInfo as well as noTermInfo from below */ +type termInfo interface { + Parse(attr string, params ...interface{}) (string, error) +} + +type noTermInfo struct{} // canary used when no terminfo. + +func (ti *noTermInfo) Parse(attr string, params ...interface{}) (string, error) { + return "", fmt.Errorf("noTermInfo") +} + +func clearLine(out io.Writer, ti termInfo) { + // el2 (clear whole line) is not exposed by terminfo. + + // First clear line from beginning to cursor + if attr, err := ti.Parse("el1"); err == nil { + fmt.Fprintf(out, "%s", attr) + } else { + fmt.Fprintf(out, "\x1b[1K") + } + // Then clear line from cursor to end + if attr, err := ti.Parse("el"); err == nil { + fmt.Fprintf(out, "%s", attr) + } else { + fmt.Fprintf(out, "\x1b[K") + } +} + +func cursorUp(out io.Writer, ti termInfo, l int) { + if l == 0 { // Should never be the case, but be tolerant + return + } + if attr, err := ti.Parse("cuu", l); err == nil { + fmt.Fprintf(out, "%s", attr) + } else { + fmt.Fprintf(out, "\x1b[%dA", l) + } +} + +func cursorDown(out io.Writer, ti termInfo, l int) { + if l == 0 { // Should never be the case, but be tolerant + return + } + if attr, err := ti.Parse("cud", l); err == nil { + fmt.Fprintf(out, "%s", attr) + } else { + fmt.Fprintf(out, "\x1b[%dB", l) + } +} + +// Display displays the JSONMessage to `out`. `termInfo` is non-nil if `out` +// is a terminal. If this is the case, it will erase the entire current line +// when displaying the progressbar. +func (jm *JSONMessage) Display(out io.Writer, termInfo termInfo) error { + if jm.Error != nil { + if jm.Error.Code == 401 { + return fmt.Errorf("authentication is required") + } + return jm.Error + } + var endl string + if termInfo != nil && jm.Stream == "" && jm.Progress != nil { + clearLine(out, termInfo) + endl = "\r" + fmt.Fprint(out, endl) + } else if jm.Progress != nil && jm.Progress.String() != "" { //disable progressbar in non-terminal + return nil + } + if jm.TimeNano != 0 { + fmt.Fprintf(out, "%s ", time.Unix(0, jm.TimeNano).Format(RFC3339NanoFixed)) + } else if jm.Time != 0 { + fmt.Fprintf(out, "%s ", time.Unix(jm.Time, 0).Format(RFC3339NanoFixed)) + } + if jm.ID != "" { + fmt.Fprintf(out, "%s: ", jm.ID) + } + if jm.From != "" { + fmt.Fprintf(out, "(from %s) ", jm.From) + } + if jm.Progress != nil && termInfo != nil { + fmt.Fprintf(out, "%s %s%s", jm.Status, jm.Progress.String(), endl) + } else if jm.ProgressMessage != "" { //deprecated + fmt.Fprintf(out, "%s %s%s", jm.Status, jm.ProgressMessage, endl) + } else if jm.Stream != "" { + fmt.Fprintf(out, "%s%s", jm.Stream, endl) + } else { + fmt.Fprintf(out, "%s%s\n", jm.Status, endl) + } + return nil +} + +// DisplayJSONMessagesStream displays a json message stream from `in` to `out`, `isTerminal` +// describes if `out` is a terminal. If this is the case, it will print `\n` at the end of +// each line and move the cursor while displaying. +func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool, auxCallback func(*json.RawMessage)) error { + var ( + dec = json.NewDecoder(in) + ids = make(map[string]int) + ) + + var termInfo termInfo + + if isTerminal { + term := os.Getenv("TERM") + if term == "" { + term = "vt102" + } + + var err error + if termInfo, err = gotty.OpenTermInfo(term); err != nil { + termInfo = &noTermInfo{} + } + } + + for { + diff := 0 + var jm JSONMessage + if err := dec.Decode(&jm); err != nil { + if err == io.EOF { + break + } + return err + } + + if jm.Aux != nil { + if auxCallback != nil { + auxCallback(jm.Aux) + } + continue + } + + if jm.Progress != nil { + jm.Progress.terminalFd = terminalFd + } + if jm.ID != "" && (jm.Progress != nil || jm.ProgressMessage != "") { + line, ok := ids[jm.ID] + if !ok { + // NOTE: This approach of using len(id) to + // figure out the number of lines of history + // only works as long as we clear the history + // when we output something that's not + // accounted for in the map, such as a line + // with no ID. + line = len(ids) + ids[jm.ID] = line + if termInfo != nil { + fmt.Fprintf(out, "\n") + } + } + diff = len(ids) - line + if termInfo != nil { + cursorUp(out, termInfo, diff) + } + } else { + // When outputting something that isn't progress + // output, clear the history of previous lines. We + // don't want progress entries from some previous + // operation to be updated (for example, pull -a + // with multiple tags). + ids = make(map[string]int) + } + err := jm.Display(out, termInfo) + if jm.ID != "" && termInfo != nil { + cursorDown(out, termInfo, diff) + } + if err != nil { + return err + } + } + return nil +} + +type stream interface { + io.Writer + FD() uintptr + IsTerminal() bool +} + +// DisplayJSONMessagesToStream prints json messages to the output stream +func DisplayJSONMessagesToStream(in io.Reader, stream stream, auxCallback func(*json.RawMessage)) error { + return DisplayJSONMessagesStream(in, stream, stream.FD(), stream.IsTerminal(), auxCallback) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/longpath/longpath.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/longpath/longpath.go new file mode 100644 index 00000000..5889bab6 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/longpath/longpath.go @@ -0,0 +1,29 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// longpath introduces some constants and helper functions for handling long paths +// in Windows, which are expected to be prepended with `\\?\` and followed by either +// a drive letter, a UNC server\share, or a volume identifier. + +package longpath // import "github.com/ory/dockertest/v3/docker/pkg/longpath" + +import ( + "strings" +) + +// Prefix is the longpath prefix for Windows file paths. +const Prefix = `\\?\` + +// AddPrefix will add the Windows long path prefix to the path provided if +// it does not already have it. +func AddPrefix(path string) string { + if !strings.HasPrefix(path, Prefix) { + if strings.HasPrefix(path, `\\`) { + // This is a UNC path, so we need to add 'UNC' to the path as well. + path = Prefix + `UNC` + path[1:] + } else { + path = Prefix + path + } + } + return path +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/flags.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/flags.go new file mode 100644 index 00000000..5ef2a905 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/flags.go @@ -0,0 +1,152 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package mount // import "github.com/ory/dockertest/v3/docker/pkg/mount" + +import ( + "fmt" + "strings" +) + +var flags = map[string]struct { + clear bool + flag int +}{ + "defaults": {false, 0}, + "ro": {false, RDONLY}, + "rw": {true, RDONLY}, + "suid": {true, NOSUID}, + "nosuid": {false, NOSUID}, + "dev": {true, NODEV}, + "nodev": {false, NODEV}, + "exec": {true, NOEXEC}, + "noexec": {false, NOEXEC}, + "sync": {false, SYNCHRONOUS}, + "async": {true, SYNCHRONOUS}, + "dirsync": {false, DIRSYNC}, + "remount": {false, REMOUNT}, + "mand": {false, MANDLOCK}, + "nomand": {true, MANDLOCK}, + "atime": {true, NOATIME}, + "noatime": {false, NOATIME}, + "diratime": {true, NODIRATIME}, + "nodiratime": {false, NODIRATIME}, + "bind": {false, BIND}, + "rbind": {false, RBIND}, + "unbindable": {false, UNBINDABLE}, + "runbindable": {false, RUNBINDABLE}, + "private": {false, PRIVATE}, + "rprivate": {false, RPRIVATE}, + "shared": {false, SHARED}, + "rshared": {false, RSHARED}, + "slave": {false, SLAVE}, + "rslave": {false, RSLAVE}, + "relatime": {false, RELATIME}, + "norelatime": {true, RELATIME}, + "strictatime": {false, STRICTATIME}, + "nostrictatime": {true, STRICTATIME}, +} + +var validFlags = map[string]bool{ + "": true, + "size": true, + "mode": true, + "uid": true, + "gid": true, + "nr_inodes": true, + "nr_blocks": true, + "mpol": true, +} + +var propagationFlags = map[string]bool{ + "bind": true, + "rbind": true, + "unbindable": true, + "runbindable": true, + "private": true, + "rprivate": true, + "shared": true, + "rshared": true, + "slave": true, + "rslave": true, +} + +// MergeTmpfsOptions merge mount options to make sure there is no duplicate. +func MergeTmpfsOptions(options []string) ([]string, error) { + // We use collisions maps to remove duplicates. + // For flag, the key is the flag value (the key for propagation flag is -1) + // For data=value, the key is the data + flagCollisions := map[int]bool{} + dataCollisions := map[string]bool{} + + var newOptions []string + // We process in reverse order + for i := len(options) - 1; i >= 0; i-- { + option := options[i] + if option == "defaults" { + continue + } + if f, ok := flags[option]; ok && f.flag != 0 { + // There is only one propagation mode + key := f.flag + if propagationFlags[option] { + key = -1 + } + // Check to see if there is collision for flag + if !flagCollisions[key] { + // We prepend the option and add to collision map + newOptions = append([]string{option}, newOptions...) + flagCollisions[key] = true + } + continue + } + opt := strings.SplitN(option, "=", 2) + if len(opt) != 2 || !validFlags[opt[0]] { + return nil, fmt.Errorf("Invalid tmpfs option %q", opt) + } + if !dataCollisions[opt[0]] { + // We prepend the option and add to collision map + newOptions = append([]string{option}, newOptions...) + dataCollisions[opt[0]] = true + } + } + + return newOptions, nil +} + +// Parse fstab type mount options into mount() flags +// and device specific data +func parseOptions(options string) (int, string) { + var ( + flag int + data []string + ) + + for _, o := range strings.Split(options, ",") { + // If the option does not exist in the flags table or the flag + // is not supported on the platform, + // then it is a data value for a specific fs type + if f, exists := flags[o]; exists && f.flag != 0 { + if f.clear { + flag &= ^f.flag + } else { + flag |= f.flag + } + } else { + data = append(data, o) + } + } + return flag, strings.Join(data, ",") +} + +// ParseTmpfsOptions parse fstab type mount options into flags and data +func ParseTmpfsOptions(options string) (int, string, error) { + flags, data := parseOptions(options) + for _, o := range strings.Split(data, ",") { + opt := strings.SplitN(o, "=", 2) + if !validFlags[opt[0]] { + return 0, "", fmt.Errorf("Invalid tmpfs option %q", opt) + } + } + return flags, data, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/flags_freebsd.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/flags_freebsd.go new file mode 100644 index 00000000..a25396e2 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/flags_freebsd.go @@ -0,0 +1,53 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build freebsd && cgo +// +build freebsd,cgo + +package mount // import "github.com/ory/dockertest/v3/docker/pkg/mount" + +/* +#include +*/ +import "C" + +const ( + // RDONLY will mount the filesystem as read-only. + RDONLY = C.MNT_RDONLY + + // NOSUID will not allow set-user-identifier or set-group-identifier bits to + // take effect. + NOSUID = C.MNT_NOSUID + + // NOEXEC will not allow execution of any binaries on the mounted file system. + NOEXEC = C.MNT_NOEXEC + + // SYNCHRONOUS will allow any I/O to the file system to be done synchronously. + SYNCHRONOUS = C.MNT_SYNCHRONOUS + + // NOATIME will not update the file access time when reading from a file. + NOATIME = C.MNT_NOATIME +) + +// These flags are unsupported. +const ( + BIND = 0 + DIRSYNC = 0 + MANDLOCK = 0 + NODEV = 0 + NODIRATIME = 0 + UNBINDABLE = 0 + RUNBINDABLE = 0 + PRIVATE = 0 + RPRIVATE = 0 + SHARED = 0 + RSHARED = 0 + SLAVE = 0 + RSLAVE = 0 + RBIND = 0 + RELATIVE = 0 + RELATIME = 0 + REMOUNT = 0 + STRICTATIME = 0 + mntDetach = 0 +) diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/flags_linux.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/flags_linux.go new file mode 100644 index 00000000..8d109d85 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/flags_linux.go @@ -0,0 +1,90 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package mount // import "github.com/ory/dockertest/v3/docker/pkg/mount" + +import ( + "golang.org/x/sys/unix" +) + +const ( + // RDONLY will mount the file system read-only. + RDONLY = unix.MS_RDONLY + + // NOSUID will not allow set-user-identifier or set-group-identifier bits to + // take effect. + NOSUID = unix.MS_NOSUID + + // NODEV will not interpret character or block special devices on the file + // system. + NODEV = unix.MS_NODEV + + // NOEXEC will not allow execution of any binaries on the mounted file system. + NOEXEC = unix.MS_NOEXEC + + // SYNCHRONOUS will allow I/O to the file system to be done synchronously. + SYNCHRONOUS = unix.MS_SYNCHRONOUS + + // DIRSYNC will force all directory updates within the file system to be done + // synchronously. This affects the following system calls: create, link, + // unlink, symlink, mkdir, rmdir, mknod and rename. + DIRSYNC = unix.MS_DIRSYNC + + // REMOUNT will attempt to remount an already-mounted file system. This is + // commonly used to change the mount flags for a file system, especially to + // make a readonly file system writeable. It does not change device or mount + // point. + REMOUNT = unix.MS_REMOUNT + + // MANDLOCK will force mandatory locks on a filesystem. + MANDLOCK = unix.MS_MANDLOCK + + // NOATIME will not update the file access time when reading from a file. + NOATIME = unix.MS_NOATIME + + // NODIRATIME will not update the directory access time. + NODIRATIME = unix.MS_NODIRATIME + + // BIND remounts a subtree somewhere else. + BIND = unix.MS_BIND + + // RBIND remounts a subtree and all possible submounts somewhere else. + RBIND = unix.MS_BIND | unix.MS_REC + + // UNBINDABLE creates a mount which cannot be cloned through a bind operation. + UNBINDABLE = unix.MS_UNBINDABLE + + // RUNBINDABLE marks the entire mount tree as UNBINDABLE. + RUNBINDABLE = unix.MS_UNBINDABLE | unix.MS_REC + + // PRIVATE creates a mount which carries no propagation abilities. + PRIVATE = unix.MS_PRIVATE + + // RPRIVATE marks the entire mount tree as PRIVATE. + RPRIVATE = unix.MS_PRIVATE | unix.MS_REC + + // SLAVE creates a mount which receives propagation from its master, but not + // vice versa. + SLAVE = unix.MS_SLAVE + + // RSLAVE marks the entire mount tree as SLAVE. + RSLAVE = unix.MS_SLAVE | unix.MS_REC + + // SHARED creates a mount which provides the ability to create mirrors of + // that mount such that mounts and unmounts within any of the mirrors + // propagate to the other mirrors. + SHARED = unix.MS_SHARED + + // RSHARED marks the entire mount tree as SHARED. + RSHARED = unix.MS_SHARED | unix.MS_REC + + // RELATIME updates inode access times relative to modify or change time. + RELATIME = unix.MS_RELATIME + + // STRICTATIME allows to explicitly request full atime updates. This makes + // it possible for the kernel to default to relatime or noatime but still + // allow userspace to override it. + STRICTATIME = unix.MS_STRICTATIME + + mntDetach = unix.MNT_DETACH +) diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/flags_unsupported.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/flags_unsupported.go new file mode 100644 index 00000000..e1ead079 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/flags_unsupported.go @@ -0,0 +1,35 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build (!linux && !freebsd) || (freebsd && !cgo) +// +build !linux,!freebsd freebsd,!cgo + +package mount // import "github.com/ory/dockertest/v3/docker/pkg/mount" + +// These flags are unsupported. +const ( + BIND = 0 + DIRSYNC = 0 + MANDLOCK = 0 + NOATIME = 0 + NODEV = 0 + NODIRATIME = 0 + NOEXEC = 0 + NOSUID = 0 + UNBINDABLE = 0 + RUNBINDABLE = 0 + PRIVATE = 0 + RPRIVATE = 0 + SHARED = 0 + RSHARED = 0 + SLAVE = 0 + RSLAVE = 0 + RBIND = 0 + RELATIME = 0 + RELATIVE = 0 + REMOUNT = 0 + STRICTATIME = 0 + SYNCHRONOUS = 0 + RDONLY = 0 + mntDetach = 0 +) diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mount.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mount.go new file mode 100644 index 00000000..977c0db0 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mount.go @@ -0,0 +1,113 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package mount // import "github.com/ory/dockertest/v3/docker/pkg/mount" + +import ( + "sort" + "strings" + + "syscall" + + "github.com/sirupsen/logrus" +) + +// GetMounts retrieves a list of mounts for the current running process. +func GetMounts() ([]*Info, error) { + return parseMountTable() +} + +// Mounted determines if a specified mountpoint has been mounted. +// On Linux it looks at /proc/self/mountinfo. +func Mounted(mountpoint string) (bool, error) { + entries, err := parseMountTable() + if err != nil { + return false, err + } + + // Search the table for the mountpoint + for _, e := range entries { + if e.Mountpoint == mountpoint { + return true, nil + } + } + return false, nil +} + +// Mount will mount filesystem according to the specified configuration, on the +// condition that the target path is *not* already mounted. Options must be +// specified like the mount or fstab unix commands: "opt1=val1,opt2=val2". See +// flags.go for supported option flags. +func Mount(device, target, mType, options string) error { + flag, _ := parseOptions(options) + if flag&REMOUNT != REMOUNT { + if mounted, err := Mounted(target); err != nil || mounted { + return err + } + } + return ForceMount(device, target, mType, options) +} + +// ForceMount will mount a filesystem according to the specified configuration, +// *regardless* if the target path is not already mounted. Options must be +// specified like the mount or fstab unix commands: "opt1=val1,opt2=val2". See +// flags.go for supported option flags. +func ForceMount(device, target, mType, options string) error { + flag, data := parseOptions(options) + return mount(device, target, mType, uintptr(flag), data) +} + +// Unmount lazily unmounts a filesystem on supported platforms, otherwise +// does a normal unmount. +func Unmount(target string) error { + if mounted, err := Mounted(target); err != nil || !mounted { + return err + } + return unmount(target, mntDetach) +} + +// RecursiveUnmount unmounts the target and all mounts underneath, starting with +// the deepsest mount first. +func RecursiveUnmount(target string) error { + mounts, err := GetMounts() + if err != nil { + return err + } + + // Make the deepest mount be first + sort.Slice(mounts, func(i, j int) bool { + return len(mounts[i].Mountpoint) > len(mounts[j].Mountpoint) + }) + + for i, m := range mounts { + if !strings.HasPrefix(m.Mountpoint, target) { + continue + } + logrus.Debugf("Trying to unmount %s", m.Mountpoint) + err = unmount(m.Mountpoint, mntDetach) + if err != nil { + // If the error is EINVAL either this whole package is wrong (invalid flags passed to unmount(2)) or this is + // not a mountpoint (which is ok in this case). + // Meanwhile calling `Mounted()` is very expensive. + // + // We've purposefully used `syscall.EINVAL` here instead of `unix.EINVAL` to avoid platform branching + // Since `EINVAL` is defined for both Windows and Linux in the `syscall` package (and other platforms), + // this is nicer than defining a custom value that we can refer to in each platform file. + if err == syscall.EINVAL { + continue + } + if i == len(mounts)-1 { + if mounted, e := Mounted(m.Mountpoint); e != nil || mounted { + return err + } + continue + } + // This is some submount, we can ignore this error for now, the final unmount will fail if this is a real problem + logrus.WithError(err).Warnf("Failed to unmount submount %s", m.Mountpoint) + continue + } + + logrus.Debugf("Unmounted %s", m.Mountpoint) + } + return nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mounter_freebsd.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mounter_freebsd.go new file mode 100644 index 00000000..608c2e68 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mounter_freebsd.go @@ -0,0 +1,63 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package mount // import "github.com/ory/dockertest/v3/docker/pkg/mount" + +/* +#include +#include +#include +#include +#include +#include +*/ +import "C" + +import ( + "fmt" + "strings" + "unsafe" + + "golang.org/x/sys/unix" +) + +func allocateIOVecs(options []string) []C.struct_iovec { + out := make([]C.struct_iovec, len(options)) + for i, option := range options { + out[i].iov_base = unsafe.Pointer(C.CString(option)) + out[i].iov_len = C.size_t(len(option) + 1) + } + return out +} + +func mount(device, target, mType string, flag uintptr, data string) error { + isNullFS := false + + xs := strings.Split(data, ",") + for _, x := range xs { + if x == "bind" { + isNullFS = true + } + } + + options := []string{"fspath", target} + if isNullFS { + options = append(options, "fstype", "nullfs", "target", device) + } else { + options = append(options, "fstype", mType, "from", device) + } + rawOptions := allocateIOVecs(options) + for _, rawOption := range rawOptions { + defer C.free(rawOption.iov_base) + } + + if errno := C.nmount(&rawOptions[0], C.uint(len(options)), C.int(flag)); errno != 0 { + reason := C.GoString(C.strerror(*C.__error())) + return fmt.Errorf("Failed to call nmount: %s", reason) + } + return nil +} + +func unmount(target string, flag int) error { + return unix.Unmount(target, flag) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mounter_linux.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mounter_linux.go new file mode 100644 index 00000000..d4d90599 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mounter_linux.go @@ -0,0 +1,60 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package mount // import "github.com/ory/dockertest/v3/docker/pkg/mount" + +import ( + "golang.org/x/sys/unix" +) + +const ( + // ptypes is the set propagation types. + ptypes = unix.MS_SHARED | unix.MS_PRIVATE | unix.MS_SLAVE | unix.MS_UNBINDABLE + + // pflags is the full set valid flags for a change propagation call. + pflags = ptypes | unix.MS_REC | unix.MS_SILENT + + // broflags is the combination of bind and read only + broflags = unix.MS_BIND | unix.MS_RDONLY +) + +// isremount returns true if either device name or flags identify a remount request, false otherwise. +func isremount(device string, flags uintptr) bool { + switch { + // We treat device "" and "none" as a remount request to provide compatibility with + // requests that don't explicitly set MS_REMOUNT such as those manipulating bind mounts. + case flags&unix.MS_REMOUNT != 0, device == "", device == "none": + return true + default: + return false + } +} + +func mount(device, target, mType string, flags uintptr, data string) error { + oflags := flags &^ ptypes + if !isremount(device, flags) || data != "" { + // Initial call applying all non-propagation flags for mount + // or remount with changed data + if err := unix.Mount(device, target, mType, oflags, data); err != nil { + return err + } + } + + if flags&ptypes != 0 { + // Change the propagation type. + if err := unix.Mount("", target, "", flags&pflags, ""); err != nil { + return err + } + } + + if oflags&broflags == broflags { + // Remount the bind to apply read only. + return unix.Mount("", target, "", oflags|unix.MS_REMOUNT, "") + } + + return nil +} + +func unmount(target string, flag int) error { + return unix.Unmount(target, flag) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mounter_unsupported.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mounter_unsupported.go new file mode 100644 index 00000000..fae753ce --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mounter_unsupported.go @@ -0,0 +1,15 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build (!linux && !freebsd) || (freebsd && !cgo) +// +build !linux,!freebsd freebsd,!cgo + +package mount // import "github.com/ory/dockertest/v3/docker/pkg/mount" + +func mount(device, target, mType string, flag uintptr, data string) error { + panic("Not implemented") +} + +func unmount(target string, flag int) error { + panic("Not implemented") +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo.go new file mode 100644 index 00000000..f2bc773c --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo.go @@ -0,0 +1,43 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package mount // import "github.com/ory/dockertest/v3/docker/pkg/mount" + +// Info reveals information about a particular mounted filesystem. This +// struct is populated from the content in the /proc//mountinfo file. +type Info struct { + // ID is a unique identifier of the mount (may be reused after umount). + ID int + + // Parent indicates the ID of the mount parent (or of self for the top of the + // mount tree). + Parent int + + // Major indicates one half of the device ID which identifies the device class. + Major int + + // Minor indicates one half of the device ID which identifies a specific + // instance of device. + Minor int + + // Root of the mount within the filesystem. + Root string + + // Mountpoint indicates the mount point relative to the process's root. + Mountpoint string + + // Opts represents mount-specific options. + Opts string + + // Optional represents optional fields. + Optional string + + // Fstype indicates the type of filesystem, such as EXT3. + Fstype string + + // Source indicates filesystem specific information or "none". + Source string + + // VfsOpts represents per super block options. + VfsOpts string +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo_freebsd.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo_freebsd.go new file mode 100644 index 00000000..f9179844 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo_freebsd.go @@ -0,0 +1,44 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package mount // import "github.com/ory/dockertest/v3/docker/pkg/mount" + +/* +#include +#include +#include +*/ +import "C" + +import ( + "fmt" + "reflect" + "unsafe" +) + +// Parse /proc/self/mountinfo because comparing Dev and ino does not work from +// bind mounts. +func parseMountTable() ([]*Info, error) { + var rawEntries *C.struct_statfs + + count := int(C.getmntinfo(&rawEntries, C.MNT_WAIT)) + if count == 0 { + return nil, fmt.Errorf("Failed to call getmntinfo") + } + + var entries []C.struct_statfs + header := (*reflect.SliceHeader)(unsafe.Pointer(&entries)) + header.Cap = count + header.Len = count + header.Data = uintptr(unsafe.Pointer(rawEntries)) + + var out []*Info + for _, entry := range entries { + var mountinfo Info + mountinfo.Mountpoint = C.GoString(&entry.f_mntonname[0]) + mountinfo.Source = C.GoString(&entry.f_mntfromname[0]) + mountinfo.Fstype = C.GoString(&entry.f_fstypename[0]) + out = append(out, &mountinfo) + } + return out, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo_linux.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo_linux.go new file mode 100644 index 00000000..67204bdf --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo_linux.go @@ -0,0 +1,96 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package mount // import "github.com/ory/dockertest/v3/docker/pkg/mount" + +import ( + "bufio" + "fmt" + "io" + "os" + "strings" +) + +const ( + /* 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue + (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11) + + (1) mount ID: unique identifier of the mount (may be reused after umount) + (2) parent ID: ID of parent (or of self for the top of the mount tree) + (3) major:minor: value of st_dev for files on filesystem + (4) root: root of the mount within the filesystem + (5) mount point: mount point relative to the process's root + (6) mount options: per mount options + (7) optional fields: zero or more fields of the form "tag[:value]" + (8) separator: marks the end of the optional fields + (9) filesystem type: name of filesystem of the form "type[.subtype]" + (10) mount source: filesystem specific information or "none" + (11) super options: per super block options*/ + mountinfoFormat = "%d %d %d:%d %s %s %s %s" +) + +// Parse /proc/self/mountinfo because comparing Dev and ino does not work from +// bind mounts +func parseMountTable() ([]*Info, error) { + f, err := os.Open("/proc/self/mountinfo") + if err != nil { + return nil, err + } + defer f.Close() + + return parseInfoFile(f) +} + +func parseInfoFile(r io.Reader) ([]*Info, error) { + var ( + s = bufio.NewScanner(r) + out = []*Info{} + ) + + for s.Scan() { + if err := s.Err(); err != nil { + return nil, err + } + + var ( + p = &Info{} + text = s.Text() + optionalFields string + ) + + if _, err := fmt.Sscanf(text, mountinfoFormat, + &p.ID, &p.Parent, &p.Major, &p.Minor, + &p.Root, &p.Mountpoint, &p.Opts, &optionalFields); err != nil { + return nil, fmt.Errorf("Scanning '%s' failed: %s", text, err) + } + // Safe as mountinfo encodes mountpoints with spaces as \040. + index := strings.Index(text, " - ") + postSeparatorFields := strings.Fields(text[index+3:]) + if len(postSeparatorFields) < 3 { + return nil, fmt.Errorf("Error found less than 3 fields post '-' in %q", text) + } + + if optionalFields != "-" { + p.Optional = optionalFields + } + + p.Fstype = postSeparatorFields[0] + p.Source = postSeparatorFields[1] + p.VfsOpts = strings.Join(postSeparatorFields[2:], " ") + out = append(out, p) + } + return out, nil +} + +// PidMountInfo collects the mounts for a specific process ID. If the process +// ID is unknown, it is better to use `GetMounts` which will inspect +// "/proc/self/mountinfo" instead. +func PidMountInfo(pid int) ([]*Info, error) { + f, err := os.Open(fmt.Sprintf("/proc/%d/mountinfo", pid)) + if err != nil { + return nil, err + } + defer f.Close() + + return parseInfoFile(f) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo_unsupported.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo_unsupported.go new file mode 100644 index 00000000..e88bbb46 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo_unsupported.go @@ -0,0 +1,16 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build (!windows && !linux && !freebsd) || (freebsd && !cgo) +// +build !windows,!linux,!freebsd freebsd,!cgo + +package mount // import "github.com/ory/dockertest/v3/docker/pkg/mount" + +import ( + "fmt" + "runtime" +) + +func parseMountTable() ([]*Info, error) { + return nil, fmt.Errorf("mount.parseMountTable is not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo_windows.go new file mode 100644 index 00000000..cb1e9cef --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/mountinfo_windows.go @@ -0,0 +1,9 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package mount // import "github.com/ory/dockertest/v3/docker/pkg/mount" + +func parseMountTable() ([]*Info, error) { + // Do NOT return an error! + return nil, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/sharedsubtree_linux.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/sharedsubtree_linux.go new file mode 100644 index 00000000..10fdce6c --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/mount/sharedsubtree_linux.go @@ -0,0 +1,70 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package mount // import "github.com/ory/dockertest/v3/docker/pkg/mount" + +// MakeShared ensures a mounted filesystem has the SHARED mount option enabled. +// See the supported options in flags.go for further reference. +func MakeShared(mountPoint string) error { + return ensureMountedAs(mountPoint, "shared") +} + +// MakeRShared ensures a mounted filesystem has the RSHARED mount option enabled. +// See the supported options in flags.go for further reference. +func MakeRShared(mountPoint string) error { + return ensureMountedAs(mountPoint, "rshared") +} + +// MakePrivate ensures a mounted filesystem has the PRIVATE mount option enabled. +// See the supported options in flags.go for further reference. +func MakePrivate(mountPoint string) error { + return ensureMountedAs(mountPoint, "private") +} + +// MakeRPrivate ensures a mounted filesystem has the RPRIVATE mount option +// enabled. See the supported options in flags.go for further reference. +func MakeRPrivate(mountPoint string) error { + return ensureMountedAs(mountPoint, "rprivate") +} + +// MakeSlave ensures a mounted filesystem has the SLAVE mount option enabled. +// See the supported options in flags.go for further reference. +func MakeSlave(mountPoint string) error { + return ensureMountedAs(mountPoint, "slave") +} + +// MakeRSlave ensures a mounted filesystem has the RSLAVE mount option enabled. +// See the supported options in flags.go for further reference. +func MakeRSlave(mountPoint string) error { + return ensureMountedAs(mountPoint, "rslave") +} + +// MakeUnbindable ensures a mounted filesystem has the UNBINDABLE mount option +// enabled. See the supported options in flags.go for further reference. +func MakeUnbindable(mountPoint string) error { + return ensureMountedAs(mountPoint, "unbindable") +} + +// MakeRUnbindable ensures a mounted filesystem has the RUNBINDABLE mount +// option enabled. See the supported options in flags.go for further reference. +func MakeRUnbindable(mountPoint string) error { + return ensureMountedAs(mountPoint, "runbindable") +} + +func ensureMountedAs(mountPoint, options string) error { + mounted, err := Mounted(mountPoint) + if err != nil { + return err + } + + if !mounted { + if err := Mount(mountPoint, mountPoint, "none", "bind,rw"); err != nil { + return err + } + } + if _, err = Mounted(mountPoint); err != nil { + return err + } + + return ForceMount("", mountPoint, "none", options) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/pools/pools.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/pools/pools.go new file mode 100644 index 00000000..d3e13b4b --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/pools/pools.go @@ -0,0 +1,140 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Package pools provides a collection of pools which provide various +// data types with buffers. These can be used to lower the number of +// memory allocations and reuse buffers. +// +// New pools should be added to this package to allow them to be +// shared across packages. +// +// Utility functions which operate on pools should be added to this +// package to allow them to be reused. +package pools // import "github.com/ory/dockertest/v3/docker/pkg/pools" + +import ( + "bufio" + "io" + "sync" + + "github.com/ory/dockertest/v3/docker/pkg/ioutils" +) + +const buffer32K = 32 * 1024 + +var ( + // BufioReader32KPool is a pool which returns bufio.Reader with a 32K buffer. + BufioReader32KPool = newBufioReaderPoolWithSize(buffer32K) + // BufioWriter32KPool is a pool which returns bufio.Writer with a 32K buffer. + BufioWriter32KPool = newBufioWriterPoolWithSize(buffer32K) + buffer32KPool = newBufferPoolWithSize(buffer32K) +) + +// BufioReaderPool is a bufio reader that uses sync.Pool. +type BufioReaderPool struct { + pool sync.Pool +} + +// newBufioReaderPoolWithSize is unexported because new pools should be +// added here to be shared where required. +func newBufioReaderPoolWithSize(size int) *BufioReaderPool { + return &BufioReaderPool{ + pool: sync.Pool{ + New: func() interface{} { return bufio.NewReaderSize(nil, size) }, + }, + } +} + +// Get returns a bufio.Reader which reads from r. The buffer size is that of the pool. +func (bufPool *BufioReaderPool) Get(r io.Reader) *bufio.Reader { + buf := bufPool.pool.Get().(*bufio.Reader) + buf.Reset(r) + return buf +} + +// Put puts the bufio.Reader back into the pool. +func (bufPool *BufioReaderPool) Put(b *bufio.Reader) { + b.Reset(nil) + bufPool.pool.Put(b) +} + +type bufferPool struct { + pool sync.Pool +} + +func newBufferPoolWithSize(size int) *bufferPool { + return &bufferPool{ + pool: sync.Pool{ + New: func() interface{} { return make([]byte, size) }, + }, + } +} + +func (bp *bufferPool) Get() []byte { + return bp.pool.Get().([]byte) +} + +func (bp *bufferPool) Put(b []byte) { + bp.pool.Put(b) +} + +// Copy is a convenience wrapper which uses a buffer to avoid allocation in io.Copy. +func Copy(dst io.Writer, src io.Reader) (written int64, err error) { + buf := buffer32KPool.Get() + written, err = io.CopyBuffer(dst, src, buf) + buffer32KPool.Put(buf) + return +} + +// NewReadCloserWrapper returns a wrapper which puts the bufio.Reader back +// into the pool and closes the reader if it's an io.ReadCloser. +func (bufPool *BufioReaderPool) NewReadCloserWrapper(buf *bufio.Reader, r io.Reader) io.ReadCloser { + return ioutils.NewReadCloserWrapper(r, func() error { + if readCloser, ok := r.(io.ReadCloser); ok { + readCloser.Close() + } + bufPool.Put(buf) + return nil + }) +} + +// BufioWriterPool is a bufio writer that uses sync.Pool. +type BufioWriterPool struct { + pool sync.Pool +} + +// newBufioWriterPoolWithSize is unexported because new pools should be +// added here to be shared where required. +func newBufioWriterPoolWithSize(size int) *BufioWriterPool { + return &BufioWriterPool{ + pool: sync.Pool{ + New: func() interface{} { return bufio.NewWriterSize(nil, size) }, + }, + } +} + +// Get returns a bufio.Writer which writes to w. The buffer size is that of the pool. +func (bufPool *BufioWriterPool) Get(w io.Writer) *bufio.Writer { + buf := bufPool.pool.Get().(*bufio.Writer) + buf.Reset(w) + return buf +} + +// Put puts the bufio.Writer back into the pool. +func (bufPool *BufioWriterPool) Put(b *bufio.Writer) { + b.Reset(nil) + bufPool.pool.Put(b) +} + +// NewWriteCloserWrapper returns a wrapper which puts the bufio.Writer back +// into the pool and closes the writer if it's an io.Writecloser. +func (bufPool *BufioWriterPool) NewWriteCloserWrapper(buf *bufio.Writer, w io.Writer) io.WriteCloser { + return ioutils.NewWriteCloserWrapper(w, func() error { + buf.Flush() + if writeCloser, ok := w.(io.WriteCloser); ok { + writeCloser.Close() + } + bufPool.Put(buf) + return nil + }) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/stdcopy/stdcopy.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/stdcopy/stdcopy.go new file mode 100644 index 00000000..f6701984 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/stdcopy/stdcopy.go @@ -0,0 +1,193 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package stdcopy // import "github.com/ory/dockertest/v3/docker/pkg/stdcopy" + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "io" + "sync" +) + +// StdType is the type of standard stream +// a writer can multiplex to. +type StdType byte + +const ( + // Stdin represents standard input stream type. + Stdin StdType = iota + // Stdout represents standard output stream type. + Stdout + // Stderr represents standard error steam type. + Stderr + // Systemerr represents errors originating from the system that make it + // into the the multiplexed stream. + Systemerr + + stdWriterPrefixLen = 8 + stdWriterFdIndex = 0 + stdWriterSizeIndex = 4 + + startingBufLen = 32*1024 + stdWriterPrefixLen + 1 +) + +var bufPool = &sync.Pool{New: func() interface{} { return bytes.NewBuffer(nil) }} + +// stdWriter is wrapper of io.Writer with extra customized info. +type stdWriter struct { + io.Writer + prefix byte +} + +// Write sends the buffer to the underneath writer. +// It inserts the prefix header before the buffer, +// so stdcopy.StdCopy knows where to multiplex the output. +// It makes stdWriter to implement io.Writer. +func (w *stdWriter) Write(p []byte) (n int, err error) { + if w == nil || w.Writer == nil { + return 0, errors.New("Writer not instantiated") + } + if p == nil { + return 0, nil + } + + header := [stdWriterPrefixLen]byte{stdWriterFdIndex: w.prefix} + binary.BigEndian.PutUint32(header[stdWriterSizeIndex:], uint32(len(p))) + buf := bufPool.Get().(*bytes.Buffer) + buf.Write(header[:]) + buf.Write(p) + + n, err = w.Writer.Write(buf.Bytes()) + n -= stdWriterPrefixLen + if n < 0 { + n = 0 + } + + buf.Reset() + bufPool.Put(buf) + return +} + +// NewStdWriter instantiates a new Writer. +// Everything written to it will be encapsulated using a custom format, +// and written to the underlying `w` stream. +// This allows multiple write streams (e.g. stdout and stderr) to be muxed into a single connection. +// `t` indicates the id of the stream to encapsulate. +// It can be stdcopy.Stdin, stdcopy.Stdout, stdcopy.Stderr. +func NewStdWriter(w io.Writer, t StdType) io.Writer { + return &stdWriter{ + Writer: w, + prefix: byte(t), + } +} + +// StdCopy is a modified version of io.Copy. +// +// StdCopy will demultiplex `src`, assuming that it contains two streams, +// previously multiplexed together using a StdWriter instance. +// As it reads from `src`, StdCopy will write to `dstout` and `dsterr`. +// +// StdCopy will read until it hits EOF on `src`. It will then return a nil error. +// In other words: if `err` is non nil, it indicates a real underlying error. +// +// `written` will hold the total number of bytes written to `dstout` and `dsterr`. +func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) { + var ( + buf = make([]byte, startingBufLen) + bufLen = len(buf) + nr, nw int + er, ew error + out io.Writer + frameSize int + ) + + for { + // Make sure we have at least a full header + for nr < stdWriterPrefixLen { + var nr2 int + nr2, er = src.Read(buf[nr:]) + nr += nr2 + if er == io.EOF { + if nr < stdWriterPrefixLen { + return written, nil + } + break + } + if er != nil { + return 0, er + } + } + + stream := StdType(buf[stdWriterFdIndex]) + // Check the first byte to know where to write + switch stream { + case Stdin: + fallthrough + case Stdout: + // Write on stdout + out = dstout + case Stderr: + // Write on stderr + out = dsterr + case Systemerr: + // If we're on Systemerr, we won't write anywhere. + // NB: if this code changes later, make sure you don't try to write + // to outstream if Systemerr is the stream + out = nil + default: + return 0, fmt.Errorf("Unrecognized input header: %d", buf[stdWriterFdIndex]) + } + + // Retrieve the size of the frame + frameSize = int(binary.BigEndian.Uint32(buf[stdWriterSizeIndex : stdWriterSizeIndex+4])) + + // Check if the buffer is big enough to read the frame. + // Extend it if necessary. + if frameSize+stdWriterPrefixLen > bufLen { + buf = append(buf, make([]byte, frameSize+stdWriterPrefixLen-bufLen+1)...) + bufLen = len(buf) + } + + // While the amount of bytes read is less than the size of the frame + header, we keep reading + for nr < frameSize+stdWriterPrefixLen { + var nr2 int + nr2, er = src.Read(buf[nr:]) + nr += nr2 + if er == io.EOF { + if nr < frameSize+stdWriterPrefixLen { + return written, nil + } + break + } + if er != nil { + return 0, er + } + } + + // we might have an error from the source mixed up in our multiplexed + // stream. if we do, return it. + if stream == Systemerr { + return written, fmt.Errorf("error from daemon in stream: %s", string(buf[stdWriterPrefixLen:frameSize+stdWriterPrefixLen])) + } + + // Write the retrieved frame (without header) + nw, ew = out.Write(buf[stdWriterPrefixLen : frameSize+stdWriterPrefixLen]) + if ew != nil { + return 0, ew + } + + // If the frame has not been fully written: error + if nw != frameSize { + return 0, io.ErrShortWrite + } + written += int64(nw) + + // Move the rest of the buffer to the beginning + copy(buf, buf[frameSize+stdWriterPrefixLen:]) + // Move the index + nr -= frameSize + stdWriterPrefixLen + } +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/chtimes.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/chtimes.go new file mode 100644 index 00000000..39568a81 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/chtimes.go @@ -0,0 +1,34 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "os" + "time" +) + +// Chtimes changes the access time and modified time of a file at the given path +func Chtimes(name string, atime time.Time, mtime time.Time) error { + unixMinTime := time.Unix(0, 0) + unixMaxTime := maxTime + + // If the modified time is prior to the Unix Epoch, or after the + // end of Unix Time, os.Chtimes has undefined behavior + // default to Unix Epoch in this case, just in case + + if atime.Before(unixMinTime) || atime.After(unixMaxTime) { + atime = unixMinTime + } + + if mtime.Before(unixMinTime) || mtime.After(unixMaxTime) { + mtime = unixMinTime + } + + if err := os.Chtimes(name, atime, mtime); err != nil { + return err + } + + // Take platform specific action for setting create time. + return setCTime(name, mtime) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/chtimes_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/chtimes_unix.go new file mode 100644 index 00000000..d2c041d8 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/chtimes_unix.go @@ -0,0 +1,18 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "time" +) + +// setCTime will set the create time on a file. On Unix, the create +// time is updated as a side effect of setting the modified time, so +// no action is required. +func setCTime(path string, ctime time.Time) error { + return nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/chtimes_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/chtimes_windows.go new file mode 100644 index 00000000..aabc3f65 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/chtimes_windows.go @@ -0,0 +1,29 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "time" + + "golang.org/x/sys/windows" +) + +// setCTime will set the create time on a file. On Windows, this requires +// calling SetFileTime and explicitly including the create time. +func setCTime(path string, ctime time.Time) error { + ctimespec := windows.NsecToTimespec(ctime.UnixNano()) + pathp, e := windows.UTF16PtrFromString(path) + if e != nil { + return e + } + h, e := windows.CreateFile(pathp, + windows.FILE_WRITE_ATTRIBUTES, windows.FILE_SHARE_WRITE, nil, + windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS, 0) + if e != nil { + return e + } + defer windows.Close(h) + c := windows.NsecToFiletime(windows.TimespecToNsec(ctimespec)) + return windows.SetFileTime(h, &c, nil, nil) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/errors.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/errors.go new file mode 100644 index 00000000..b46dfa23 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/errors.go @@ -0,0 +1,16 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "errors" +) + +var ( + // ErrNotSupportedPlatform means the platform is not supported. + ErrNotSupportedPlatform = errors.New("platform and architecture is not supported") + + // ErrNotSupportedOperatingSystem means the operating system is not supported. + ErrNotSupportedOperatingSystem = errors.New("operating system is not supported") +) diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/exitcode.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/exitcode.go new file mode 100644 index 00000000..f1bc3c5f --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/exitcode.go @@ -0,0 +1,22 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "fmt" + "os/exec" + "syscall" +) + +// GetExitCode returns the ExitStatus of the specified error if its type is +// exec.ExitError, returns 0 and an error otherwise. +func GetExitCode(err error) (int, error) { + exitCode := 0 + if exiterr, ok := err.(*exec.ExitError); ok { + if procExit, ok := exiterr.Sys().(syscall.WaitStatus); ok { + return procExit.ExitStatus(), nil + } + } + return exitCode, fmt.Errorf("failed to get exit code") +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/filesys.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/filesys.go new file mode 100644 index 00000000..7cb0f608 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/filesys.go @@ -0,0 +1,70 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "os" + "path/filepath" +) + +// MkdirAllWithACL is a wrapper for MkdirAll on unix systems. +func MkdirAllWithACL(path string, perm os.FileMode, sddl string) error { + return MkdirAll(path, perm, sddl) +} + +// MkdirAll creates a directory named path along with any necessary parents, +// with permission specified by attribute perm for all dir created. +func MkdirAll(path string, perm os.FileMode, sddl string) error { + return os.MkdirAll(path, perm) +} + +// IsAbs is a platform-specific wrapper for filepath.IsAbs. +func IsAbs(path string) bool { + return filepath.IsAbs(path) +} + +// The functions below here are wrappers for the equivalents in the os and ioutils packages. +// They are passthrough on Unix platforms, and only relevant on Windows. + +// CreateSequential creates the named file with mode 0666 (before umask), truncating +// it if it already exists. If successful, methods on the returned +// File can be used for I/O; the associated file descriptor has mode +// O_RDWR. +// If there is an error, it will be of type *PathError. +func CreateSequential(name string) (*os.File, error) { + return os.Create(name) +} + +// OpenSequential opens the named file for reading. If successful, methods on +// the returned file can be used for reading; the associated file +// descriptor has mode O_RDONLY. +// If there is an error, it will be of type *PathError. +func OpenSequential(name string) (*os.File, error) { + return os.Open(name) +} + +// OpenFileSequential is the generalized open call; most users will use Open +// or Create instead. It opens the named file with specified flag +// (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful, +// methods on the returned File can be used for I/O. +// If there is an error, it will be of type *PathError. +func OpenFileSequential(name string, flag int, perm os.FileMode) (*os.File, error) { + return os.OpenFile(name, flag, perm) +} + +// TempFileSequential creates a new temporary file in the directory dir +// with a name beginning with prefix, opens the file for reading +// and writing, and returns the resulting *os.File. +// If dir is the empty string, TempFile uses the default directory +// for temporary files (see os.TempDir). +// Multiple programs calling TempFile simultaneously +// will not choose the same file. The caller can use f.Name() +// to find the pathname of the file. It is the caller's responsibility +// to remove the file when no longer needed. +func TempFileSequential(dir, prefix string) (f *os.File, err error) { + return os.CreateTemp(dir, prefix) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/filesys_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/filesys_windows.go new file mode 100644 index 00000000..332b17d1 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/filesys_windows.go @@ -0,0 +1,298 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "sync" + "syscall" + "time" + "unsafe" + + "golang.org/x/sys/windows" +) + +const ( + // SddlAdministratorsLocalSystem is local administrators plus NT AUTHORITY\System + SddlAdministratorsLocalSystem = "D:P(A;OICI;GA;;;BA)(A;OICI;GA;;;SY)" + // SddlNtvmAdministratorsLocalSystem is NT VIRTUAL MACHINE\Virtual Machines plus local administrators plus NT AUTHORITY\System + SddlNtvmAdministratorsLocalSystem = "D:P(A;OICI;GA;;;S-1-5-83-0)(A;OICI;GA;;;BA)(A;OICI;GA;;;SY)" +) + +// MkdirAllWithACL is a wrapper for MkdirAll that creates a directory +// with an appropriate SDDL defined ACL. +func MkdirAllWithACL(path string, perm os.FileMode, sddl string) error { + return mkdirall(path, true, sddl) +} + +// MkdirAll implementation that is volume path aware for Windows. +func MkdirAll(path string, _ os.FileMode, sddl string) error { + return mkdirall(path, false, sddl) +} + +// mkdirall is a custom version of os.MkdirAll modified for use on Windows +// so that it is both volume path aware, and can create a directory with +// a DACL. +func mkdirall(path string, applyACL bool, sddl string) error { + if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) { + return nil + } + + // The rest of this method is largely copied from os.MkdirAll and should be kept + // as-is to ensure compatibility. + + // Fast path: if we can tell whether path is a directory or file, stop with success or error. + dir, err := os.Stat(path) + if err == nil { + if dir.IsDir() { + return nil + } + return &os.PathError{ + Op: "mkdir", + Path: path, + Err: syscall.ENOTDIR, + } + } + + // Slow path: make sure parent exists and then call Mkdir for path. + i := len(path) + for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. + i-- + } + + j := i + for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. + j-- + } + + if j > 1 { + // Create parent + err = mkdirall(path[0:j-1], false, sddl) + if err != nil { + return err + } + } + + // Parent now exists; invoke os.Mkdir or mkdirWithACL and use its result. + if applyACL { + err = mkdirWithACL(path, sddl) + } else { + err = os.Mkdir(path, 0) + } + + if err != nil { + // Handle arguments like "foo/." by + // double-checking that directory doesn't exist. + dir, err1 := os.Lstat(path) + if err1 == nil && dir.IsDir() { + return nil + } + return err + } + return nil +} + +// mkdirWithACL creates a new directory. If there is an error, it will be of +// type *PathError. . +// +// This is a modified and combined version of os.Mkdir and windows.Mkdir +// in golang to cater for creating a directory am ACL permitting full +// access, with inheritance, to any subfolder/file for Built-in Administrators +// and Local System. +func mkdirWithACL(name string, sddl string) error { + sa := windows.SecurityAttributes{Length: 0} + sd, err := windows.SecurityDescriptorFromString(sddl) + if err != nil { + return &os.PathError{Op: "mkdir", Path: name, Err: err} + } + sa.Length = uint32(unsafe.Sizeof(sa)) + sa.InheritHandle = 1 + sa.SecurityDescriptor = sd + + namep, err := windows.UTF16PtrFromString(name) + if err != nil { + return &os.PathError{Op: "mkdir", Path: name, Err: err} + } + + e := windows.CreateDirectory(namep, &sa) + if e != nil { + return &os.PathError{Op: "mkdir", Path: name, Err: e} + } + return nil +} + +// IsAbs is a platform-specific wrapper for filepath.IsAbs. On Windows, +// golang filepath.IsAbs does not consider a path \windows\system32 as absolute +// as it doesn't start with a drive-letter/colon combination. However, in +// docker we need to verify things such as WORKDIR /windows/system32 in +// a Dockerfile (which gets translated to \windows\system32 when being processed +// by the daemon. This SHOULD be treated as absolute from a docker processing +// perspective. +func IsAbs(path string) bool { + if !filepath.IsAbs(path) { + if !strings.HasPrefix(path, string(os.PathSeparator)) { + return false + } + } + return true +} + +// The origin of the functions below here are the golang OS and windows packages, +// slightly modified to only cope with files, not directories due to the +// specific use case. +// +// The alteration is to allow a file on Windows to be opened with +// FILE_FLAG_SEQUENTIAL_SCAN (particular for docker load), to avoid eating +// the standby list, particularly when accessing large files such as layer.tar. + +// CreateSequential creates the named file with mode 0666 (before umask), truncating +// it if it already exists. If successful, methods on the returned +// File can be used for I/O; the associated file descriptor has mode +// O_RDWR. +// If there is an error, it will be of type *PathError. +func CreateSequential(name string) (*os.File, error) { + return OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0) +} + +// OpenSequential opens the named file for reading. If successful, methods on +// the returned file can be used for reading; the associated file +// descriptor has mode O_RDONLY. +// If there is an error, it will be of type *PathError. +func OpenSequential(name string) (*os.File, error) { + return OpenFileSequential(name, os.O_RDONLY, 0) +} + +// OpenFileSequential is the generalized open call; most users will use Open +// or Create instead. +// If there is an error, it will be of type *PathError. +func OpenFileSequential(name string, flag int, _ os.FileMode) (*os.File, error) { + if name == "" { + return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOENT} + } + r, errf := windowsOpenFileSequential(name, flag, 0) + if errf == nil { + return r, nil + } + return nil, &os.PathError{Op: "open", Path: name, Err: errf} +} + +func windowsOpenFileSequential(name string, flag int, _ os.FileMode) (file *os.File, err error) { + r, e := windowsOpenSequential(name, flag|windows.O_CLOEXEC, 0) + if e != nil { + return nil, e + } + return os.NewFile(uintptr(r), name), nil +} + +func makeInheritSa() *windows.SecurityAttributes { + var sa windows.SecurityAttributes + sa.Length = uint32(unsafe.Sizeof(sa)) + sa.InheritHandle = 1 + return &sa +} + +func windowsOpenSequential(path string, mode int, _ uint32) (fd windows.Handle, err error) { + if len(path) == 0 { + return windows.InvalidHandle, windows.ERROR_FILE_NOT_FOUND + } + pathp, err := windows.UTF16PtrFromString(path) + if err != nil { + return windows.InvalidHandle, err + } + var access uint32 + switch mode & (windows.O_RDONLY | windows.O_WRONLY | windows.O_RDWR) { + case windows.O_RDONLY: + access = windows.GENERIC_READ + case windows.O_WRONLY: + access = windows.GENERIC_WRITE + case windows.O_RDWR: + access = windows.GENERIC_READ | windows.GENERIC_WRITE + } + if mode&windows.O_CREAT != 0 { + access |= windows.GENERIC_WRITE + } + if mode&windows.O_APPEND != 0 { + access &^= windows.GENERIC_WRITE + access |= windows.FILE_APPEND_DATA + } + sharemode := uint32(windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE) + var sa *windows.SecurityAttributes + if mode&windows.O_CLOEXEC == 0 { + sa = makeInheritSa() + } + var createmode uint32 + switch { + case mode&(windows.O_CREAT|windows.O_EXCL) == (windows.O_CREAT | windows.O_EXCL): + createmode = windows.CREATE_NEW + case mode&(windows.O_CREAT|windows.O_TRUNC) == (windows.O_CREAT | windows.O_TRUNC): + createmode = windows.CREATE_ALWAYS + case mode&windows.O_CREAT == windows.O_CREAT: + createmode = windows.OPEN_ALWAYS + case mode&windows.O_TRUNC == windows.O_TRUNC: + createmode = windows.TRUNCATE_EXISTING + default: + createmode = windows.OPEN_EXISTING + } + // Use FILE_FLAG_SEQUENTIAL_SCAN rather than FILE_ATTRIBUTE_NORMAL as implemented in golang. + //https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx + const fileFlagSequentialScan = 0x08000000 // FILE_FLAG_SEQUENTIAL_SCAN + h, e := windows.CreateFile(pathp, access, sharemode, sa, createmode, fileFlagSequentialScan, 0) + return h, e +} + +// Helpers for TempFileSequential +var rand uint32 +var randmu sync.Mutex + +func reseed() uint32 { + return uint32(time.Now().UnixNano() + int64(os.Getpid())) +} +func nextSuffix() string { + randmu.Lock() + r := rand + if r == 0 { + r = reseed() + } + r = r*1664525 + 1013904223 // constants from Numerical Recipes + rand = r + randmu.Unlock() + return strconv.Itoa(int(1e9 + r%1e9))[1:] +} + +// TempFileSequential is a copy of os.CreateTemp, modified to use sequential +// file access. Below is the original comment from golang: +// TempFile creates a new temporary file in the directory dir +// with a name beginning with prefix, opens the file for reading +// and writing, and returns the resulting *os.File. +// If dir is the empty string, TempFile uses the default directory +// for temporary files (see os.TempDir). +// Multiple programs calling TempFile simultaneously +// will not choose the same file. The caller can use f.Name() +// to find the pathname of the file. It is the caller's responsibility +// to remove the file when no longer needed. +func TempFileSequential(dir, prefix string) (f *os.File, err error) { + if dir == "" { + dir = os.TempDir() + } + + nconflict := 0 + for i := 0; i < 10000; i++ { + name := filepath.Join(dir, prefix+nextSuffix()) + f, err = OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) + if os.IsExist(err) { + if nconflict++; nconflict > 10 { + randmu.Lock() + rand = reseed() + randmu.Unlock() + } + continue + } + break + } + return +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/init.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/init.go new file mode 100644 index 00000000..c1ce4fb3 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/init.go @@ -0,0 +1,25 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "syscall" + "time" + "unsafe" +) + +// Used by chtimes +var maxTime time.Time + +func init() { + // chtimes initialization + if unsafe.Sizeof(syscall.Timespec{}.Nsec) == 8 { + // This is a 64 bit timespec + // os.Chtimes limits time to the following + maxTime = time.Unix(0, 1<<63-1) + } else { + // This is a 32 bit timespec + maxTime = time.Unix(1<<31-1, 0) + } +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/init_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/init_unix.go new file mode 100644 index 00000000..8f8d2a7d --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/init_unix.go @@ -0,0 +1,11 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +// InitLCOW does nothing since LCOW is a windows only feature +func InitLCOW(experimental bool) { +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/init_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/init_windows.go new file mode 100644 index 00000000..4b2343ea --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/init_windows.go @@ -0,0 +1,15 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +// lcowSupported determines if Linux Containers on Windows are supported. +var lcowSupported = false + +// InitLCOW sets whether LCOW is supported or not +func InitLCOW(experimental bool) { + v := GetOSVersion() + if experimental && v.Build >= 16299 { + lcowSupported = true + } +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lcow.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lcow.go new file mode 100644 index 00000000..961c2d58 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lcow.go @@ -0,0 +1,72 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "fmt" + "runtime" + "strings" + + specs "github.com/opencontainers/image-spec/specs-go/v1" +) + +// ValidatePlatform determines if a platform structure is valid. +// TODO This is a temporary function - can be replaced by parsing from +// https://github.com/containerd/containerd/pull/1403/files at a later date. +// @jhowardmsft +func ValidatePlatform(platform *specs.Platform) error { + platform.Architecture = strings.ToLower(platform.Architecture) + platform.OS = strings.ToLower(platform.OS) + // Based on https://github.com/moby/moby/pull/34642#issuecomment-330375350, do + // not support anything except operating system. + if platform.Architecture != "" { + return fmt.Errorf("invalid platform architecture %q", platform.Architecture) + } + if platform.OS != "" { + if !(platform.OS == runtime.GOOS || (LCOWSupported() && platform.OS == "linux")) { + return fmt.Errorf("invalid platform os %q", platform.OS) + } + } + if len(platform.OSFeatures) != 0 { + return fmt.Errorf("invalid platform osfeatures %q", platform.OSFeatures) + } + if platform.OSVersion != "" { + return fmt.Errorf("invalid platform osversion %q", platform.OSVersion) + } + if platform.Variant != "" { + return fmt.Errorf("invalid platform variant %q", platform.Variant) + } + return nil +} + +// ParsePlatform parses a platform string in the format os[/arch[/variant] +// into an OCI image-spec platform structure. +// TODO This is a temporary function - can be replaced by parsing from +// https://github.com/containerd/containerd/pull/1403/files at a later date. +// @jhowardmsft +func ParsePlatform(in string) *specs.Platform { + p := &specs.Platform{} + elements := strings.SplitN(strings.ToLower(in), "/", 3) + if len(elements) == 3 { + p.Variant = elements[2] + } + if len(elements) >= 2 { + p.Architecture = elements[1] + } + if len(elements) >= 1 { + p.OS = elements[0] + } + return p +} + +// IsOSSupported determines if an operating system is supported by the host +func IsOSSupported(os string) bool { + if runtime.GOOS == os { + return true + } + if LCOWSupported() && os == "linux" { + return true + } + return false +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lcow_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lcow_unix.go new file mode 100644 index 00000000..2333c5b0 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lcow_unix.go @@ -0,0 +1,12 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +// LCOWSupported returns true if Linux containers on Windows are supported. +func LCOWSupported() bool { + return false +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lcow_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lcow_windows.go new file mode 100644 index 00000000..8db0f106 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lcow_windows.go @@ -0,0 +1,9 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +// LCOWSupported returns true if Linux containers on Windows are supported. +func LCOWSupported() bool { + return lcowSupported +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lstat_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lstat_unix.go new file mode 100644 index 00000000..2bdaad03 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lstat_unix.go @@ -0,0 +1,23 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "syscall" +) + +// Lstat takes a path to a file and returns +// a system.StatT type pertaining to that file. +// +// Throws an error if the file does not exist +func Lstat(path string) (*StatT, error) { + s := &syscall.Stat_t{} + if err := syscall.Lstat(path, s); err != nil { + return nil, err + } + return fromStatT(s) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lstat_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lstat_windows.go new file mode 100644 index 00000000..92dae7cc --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/lstat_windows.go @@ -0,0 +1,17 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import "os" + +// Lstat calls os.Lstat to get a fileinfo interface back. +// This is then copied into our own locally defined structure. +func Lstat(path string) (*StatT, error) { + fi, err := os.Lstat(path) + if err != nil { + return nil, err + } + + return fromStatT(&fi) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/meminfo.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/meminfo.go new file mode 100644 index 00000000..64713f3a --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/meminfo.go @@ -0,0 +1,20 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +// MemInfo contains memory statistics of the host system. +type MemInfo struct { + // Total usable RAM (i.e. physical RAM minus a few reserved bits and the + // kernel binary code). + MemTotal int64 + + // Amount of free memory. + MemFree int64 + + // Total amount of swap space available. + SwapTotal int64 + + // Amount of swap space that is currently unused. + SwapFree int64 +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/meminfo_linux.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/meminfo_linux.go new file mode 100644 index 00000000..2ebb2389 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/meminfo_linux.go @@ -0,0 +1,68 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "bufio" + "io" + "os" + "strconv" + "strings" + + "github.com/docker/go-units" +) + +// ReadMemInfo retrieves memory statistics of the host system and returns a +// MemInfo type. +func ReadMemInfo() (*MemInfo, error) { + file, err := os.Open("/proc/meminfo") + if err != nil { + return nil, err + } + defer file.Close() + return parseMemInfo(file) +} + +// parseMemInfo parses the /proc/meminfo file into +// a MemInfo object given an io.Reader to the file. +// Throws error if there are problems reading from the file +func parseMemInfo(reader io.Reader) (*MemInfo, error) { + meminfo := &MemInfo{} + scanner := bufio.NewScanner(reader) + for scanner.Scan() { + // Expected format: ["MemTotal:", "1234", "kB"] + parts := strings.Fields(scanner.Text()) + + // Sanity checks: Skip malformed entries. + if len(parts) < 3 || parts[2] != "kB" { + continue + } + + // Convert to bytes. + size, err := strconv.Atoi(parts[1]) + if err != nil { + continue + } + bytes := int64(size) * units.KiB + + switch parts[0] { + case "MemTotal:": + meminfo.MemTotal = bytes + case "MemFree:": + meminfo.MemFree = bytes + case "SwapTotal:": + meminfo.SwapTotal = bytes + case "SwapFree:": + meminfo.SwapFree = bytes + } + + } + + // Handle errors that may have occurred during the reading of the file. + if err := scanner.Err(); err != nil { + return nil, err + } + + return meminfo, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/meminfo_unsupported.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/meminfo_unsupported.go new file mode 100644 index 00000000..1faab2a8 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/meminfo_unsupported.go @@ -0,0 +1,12 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !linux && !windows +// +build !linux,!windows + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +// ReadMemInfo is not supported on platforms other than linux and windows. +func ReadMemInfo() (*MemInfo, error) { + return nil, ErrNotSupportedPlatform +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/meminfo_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/meminfo_windows.go new file mode 100644 index 00000000..caebcae5 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/meminfo_windows.go @@ -0,0 +1,49 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "unsafe" + + "golang.org/x/sys/windows" +) + +var ( + modkernel32 = windows.NewLazySystemDLL("kernel32.dll") + + procGlobalMemoryStatusEx = modkernel32.NewProc("GlobalMemoryStatusEx") +) + +// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx +// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366770(v=vs.85).aspx +type memorystatusex struct { + dwLength uint32 + dwMemoryLoad uint32 + ullTotalPhys uint64 + ullAvailPhys uint64 + ullTotalPageFile uint64 + ullAvailPageFile uint64 + ullTotalVirtual uint64 + ullAvailVirtual uint64 + ullAvailExtendedVirtual uint64 +} + +// ReadMemInfo retrieves memory statistics of the host system and returns a +// +// MemInfo type. +func ReadMemInfo() (*MemInfo, error) { + msi := &memorystatusex{ + dwLength: 64, + } + r1, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msi))) + if r1 == 0 { + return &MemInfo{}, nil + } + return &MemInfo{ + MemTotal: int64(msi.ullTotalPhys), + MemFree: int64(msi.ullAvailPhys), + SwapTotal: int64(msi.ullTotalPageFile), + SwapFree: int64(msi.ullAvailPageFile), + }, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/mknod.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/mknod.go new file mode 100644 index 00000000..4343b1dd --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/mknod.go @@ -0,0 +1,26 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows && !freebsd +// +build !windows,!freebsd + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "golang.org/x/sys/unix" +) + +// Mknod creates a filesystem node (file, device special file or named pipe) named path +// with attributes specified by mode and dev. +func Mknod(path string, mode uint32, dev int) error { + return unix.Mknod(path, mode, dev) +} + +// Mkdev is used to build the value of linux devices (in /dev/) which specifies major +// and minor number of the newly created device special file. +// Linux device nodes are a bit weird due to backwards compat with 16 bit device nodes. +// They are, from low to high: the lower 8 bits of the minor, then 12 bits of the major, +// then the top 12 bits of the minor. +func Mkdev(major int64, minor int64) uint32 { + return uint32(unix.Mkdev(uint32(major), uint32(minor))) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/mknod_freebsd.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/mknod_freebsd.go new file mode 100644 index 00000000..97eafda2 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/mknod_freebsd.go @@ -0,0 +1,26 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build freebsd +// +build freebsd + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "golang.org/x/sys/unix" +) + +// Mknod creates a filesystem node (file, device special file or named pipe) named path +// with attributes specified by mode and dev. +func Mknod(path string, mode uint32, dev int) error { + return unix.Mknod(path, mode, uint64(dev)) +} + +// Mkdev is used to build the value of linux devices (in /dev/) which specifies major +// and minor number of the newly created device special file. +// Linux device nodes are a bit weird due to backwards compat with 16 bit device nodes. +// They are, from low to high: the lower 8 bits of the minor, then 12 bits of the major, +// then the top 12 bits of the minor. +func Mkdev(major int64, minor int64) uint32 { + return uint32(unix.Mkdev(uint32(major), uint32(minor))) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/mknod_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/mknod_windows.go new file mode 100644 index 00000000..737f8f93 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/mknod_windows.go @@ -0,0 +1,17 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build windows +// +build windows + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +// Mknod is not implemented on Windows. +func Mknod(path string, mode uint32, dev int) error { + return ErrNotSupportedPlatform +} + +// Mkdev is not implemented on Windows. +func Mkdev(major int64, minor int64) uint32 { + panic("Mkdev not implemented on Windows.") +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/path.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/path.go new file mode 100644 index 00000000..13155778 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/path.go @@ -0,0 +1,63 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "fmt" + "path/filepath" + "runtime" + "strings" + + "github.com/containerd/continuity/pathdriver" +) + +const defaultUnixPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + +// DefaultPathEnv is unix style list of directories to search for +// executables. Each directory is separated from the next by a colon +// ':' character . +func DefaultPathEnv(os string) string { + if runtime.GOOS == "windows" { + if os != runtime.GOOS { + return defaultUnixPathEnv + } + // Deliberately empty on Windows containers on Windows as the default path will be set by + // the container. Docker has no context of what the default path should be. + return "" + } + return defaultUnixPathEnv + +} + +// CheckSystemDriveAndRemoveDriveLetter verifies that a path, if it includes a drive letter, +// is the system drive. +// On Linux: this is a no-op. +// On Windows: this does the following> +// CheckSystemDriveAndRemoveDriveLetter verifies and manipulates a Windows path. +// This is used, for example, when validating a user provided path in docker cp. +// If a drive letter is supplied, it must be the system drive. The drive letter +// is always removed. Also, it translates it to OS semantics (IOW / to \). We +// need the path in this syntax so that it can ultimately be concatenated with +// a Windows long-path which doesn't support drive-letters. Examples: +// C: --> Fail +// C:\ --> \ +// a --> a +// /a --> \a +// d:\ --> Fail +func CheckSystemDriveAndRemoveDriveLetter(path string, driver pathdriver.PathDriver) (string, error) { + if runtime.GOOS != "windows" || LCOWSupported() { + return path, nil + } + + if len(path) == 2 && string(path[1]) == ":" { + return "", fmt.Errorf("No relative path specified in %q", path) + } + if !driver.IsAbs(path) || len(path) < 2 { + return filepath.FromSlash(path), nil + } + if string(path[1]) == ":" && !strings.EqualFold(string(path[0]), "c") { + return "", fmt.Errorf("The specified path is not on the system drive (C:)") + } + return filepath.FromSlash(path[2:]), nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/process_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/process_unix.go new file mode 100644 index 00000000..406eb842 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/process_unix.go @@ -0,0 +1,28 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux || freebsd || darwin +// +build linux freebsd darwin + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "syscall" + + "golang.org/x/sys/unix" +) + +// IsProcessAlive returns true if process with a given pid is running. +func IsProcessAlive(pid int) bool { + err := unix.Kill(pid, syscall.Signal(0)) + if err == nil || err == unix.EPERM { + return true + } + + return false +} + +// KillProcess force-stops a process. +func KillProcess(pid int) { + unix.Kill(pid, unix.SIGKILL) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/process_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/process_windows.go new file mode 100644 index 00000000..7f3986ad --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/process_windows.go @@ -0,0 +1,21 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import "os" + +// IsProcessAlive returns true if process with a given pid is running. +func IsProcessAlive(pid int) bool { + _, err := os.FindProcess(pid) + + return err == nil +} + +// KillProcess force-stops a process. +func KillProcess(pid int) { + p, err := os.FindProcess(pid) + if err == nil { + p.Kill() + } +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/rm.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/rm.go new file mode 100644 index 00000000..08bcaf7f --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/rm.go @@ -0,0 +1,83 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "fmt" + "os" + "syscall" + "time" + + "github.com/ory/dockertest/v3/docker/pkg/mount" +) + +// EnsureRemoveAll wraps `os.RemoveAll` to check for specific errors that can +// often be remedied. +// Only use `EnsureRemoveAll` if you really want to make every effort to remove +// a directory. +// +// Because of the way `os.Remove` (and by extension `os.RemoveAll`) works, there +// can be a race between reading directory entries and then actually attempting +// to remove everything in the directory. +// These types of errors do not need to be returned since it's ok for the dir to +// be gone we can just retry the remove operation. +// +// This should not return a `os.ErrNotExist` kind of error under any circumstances +func EnsureRemoveAll(dir string) error { + notExistErr := make(map[string]bool) + + // track retries + exitOnErr := make(map[string]int) + maxRetry := 50 + + // Attempt to unmount anything beneath this dir first + mount.RecursiveUnmount(dir) + + for { + err := os.RemoveAll(dir) + if err == nil { + return err + } + + pe, ok := err.(*os.PathError) + if !ok { + return err + } + + if os.IsNotExist(err) { + if notExistErr[pe.Path] { + return err + } + notExistErr[pe.Path] = true + + // There is a race where some subdir can be removed but after the parent + // dir entries have been read. + // So the path could be from `os.Remove(subdir)` + // If the reported non-existent path is not the passed in `dir` we + // should just retry, but otherwise return with no error. + if pe.Path == dir { + return nil + } + continue + } + + if pe.Err != syscall.EBUSY { + return err + } + + if mounted, _ := mount.Mounted(pe.Path); mounted { + if e := mount.Unmount(pe.Path); e != nil { + if mounted, _ := mount.Mounted(pe.Path); mounted { + return fmt.Errorf("error while removing %s: %w", dir, e) + } + } + } + + if exitOnErr[pe.Path] == maxRetry { + return err + } + exitOnErr[pe.Path]++ + time.Sleep(100 * time.Millisecond) + } +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_darwin.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_darwin.go new file mode 100644 index 00000000..cba40a48 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_darwin.go @@ -0,0 +1,16 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import "syscall" + +// fromStatT converts a syscall.Stat_t type to a system.Stat_t type +func fromStatT(s *syscall.Stat_t) (*StatT, error) { + return &StatT{size: s.Size, + mode: uint32(s.Mode), + uid: s.Uid, + gid: s.Gid, + rdev: uint64(s.Rdev), + mtim: s.Mtimespec}, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_freebsd.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_freebsd.go new file mode 100644 index 00000000..cba40a48 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_freebsd.go @@ -0,0 +1,16 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import "syscall" + +// fromStatT converts a syscall.Stat_t type to a system.Stat_t type +func fromStatT(s *syscall.Stat_t) (*StatT, error) { + return &StatT{size: s.Size, + mode: uint32(s.Mode), + uid: s.Uid, + gid: s.Gid, + rdev: uint64(s.Rdev), + mtim: s.Mtimespec}, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_linux.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_linux.go new file mode 100644 index 00000000..b70d704f --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_linux.go @@ -0,0 +1,22 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import "syscall" + +// fromStatT converts a syscall.Stat_t type to a system.Stat_t type +func fromStatT(s *syscall.Stat_t) (*StatT, error) { + return &StatT{size: s.Size, + mode: s.Mode, + uid: s.Uid, + gid: s.Gid, + rdev: uint64(s.Rdev), + mtim: s.Mtim}, nil +} + +// FromStatT converts a syscall.Stat_t type to a system.Stat_t type +// This is exposed on Linux as pkg/archive/changes uses it. +func FromStatT(s *syscall.Stat_t) (*StatT, error) { + return fromStatT(s) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_openbsd.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_openbsd.go new file mode 100644 index 00000000..8117298a --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_openbsd.go @@ -0,0 +1,16 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import "syscall" + +// fromStatT converts a syscall.Stat_t type to a system.Stat_t type +func fromStatT(s *syscall.Stat_t) (*StatT, error) { + return &StatT{size: s.Size, + mode: uint32(s.Mode), + uid: s.Uid, + gid: s.Gid, + rdev: uint64(s.Rdev), + mtim: s.Mtim}, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_solaris.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_solaris.go new file mode 100644 index 00000000..8117298a --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_solaris.go @@ -0,0 +1,16 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import "syscall" + +// fromStatT converts a syscall.Stat_t type to a system.Stat_t type +func fromStatT(s *syscall.Stat_t) (*StatT, error) { + return &StatT{size: s.Size, + mode: uint32(s.Mode), + uid: s.Uid, + gid: s.Gid, + rdev: uint64(s.Rdev), + mtim: s.Mtim}, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_unix.go new file mode 100644 index 00000000..7e54f3a9 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_unix.go @@ -0,0 +1,69 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "syscall" +) + +// StatT type contains status of a file. It contains metadata +// like permission, owner, group, size, etc about a file. +type StatT struct { + mode uint32 + uid uint32 + gid uint32 + rdev uint64 + size int64 + mtim syscall.Timespec +} + +// Mode returns file's permission mode. +func (s StatT) Mode() uint32 { + return s.mode +} + +// UID returns file's user id of owner. +func (s StatT) UID() uint32 { + return s.uid +} + +// GID returns file's group id of owner. +func (s StatT) GID() uint32 { + return s.gid +} + +// Rdev returns file's device ID (if it's special file). +func (s StatT) Rdev() uint64 { + return s.rdev +} + +// Size returns file's size. +func (s StatT) Size() int64 { + return s.size +} + +// Mtim returns file's last modification time. +func (s StatT) Mtim() syscall.Timespec { + return s.mtim +} + +// IsDir reports whether s describes a directory. +func (s StatT) IsDir() bool { + return s.mode&syscall.S_IFDIR != 0 +} + +// Stat takes a path to a file and returns +// a system.StatT type pertaining to that file. +// +// Throws an error if the file does not exist +func Stat(path string) (*StatT, error) { + s := &syscall.Stat_t{} + if err := syscall.Stat(path, s); err != nil { + return nil, err + } + return fromStatT(s) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_windows.go new file mode 100644 index 00000000..a18b3aae --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/stat_windows.go @@ -0,0 +1,52 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "os" + "time" +) + +// StatT type contains status of a file. It contains metadata +// like permission, size, etc about a file. +type StatT struct { + mode os.FileMode + size int64 + mtim time.Time +} + +// Size returns file's size. +func (s StatT) Size() int64 { + return s.size +} + +// Mode returns file's permission mode. +func (s StatT) Mode() os.FileMode { + return os.FileMode(s.mode) +} + +// Mtim returns file's last modification time. +func (s StatT) Mtim() time.Time { + return time.Time(s.mtim) +} + +// Stat takes a path to a file and returns +// a system.StatT type pertaining to that file. +// +// Throws an error if the file does not exist +func Stat(path string) (*StatT, error) { + fi, err := os.Stat(path) + if err != nil { + return nil, err + } + return fromStatT(&fi) +} + +// fromStatT converts a os.FileInfo type to a system.StatT type +func fromStatT(fi *os.FileInfo) (*StatT, error) { + return &StatT{ + size: (*fi).Size(), + mode: (*fi).Mode(), + mtim: (*fi).ModTime()}, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/syscall_unix.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/syscall_unix.go new file mode 100644 index 00000000..a25a055d --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/syscall_unix.go @@ -0,0 +1,21 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux || freebsd +// +build linux freebsd + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import "golang.org/x/sys/unix" + +// Unmount is a platform-specific helper function to call +// the unmount syscall. +func Unmount(dest string) error { + return unix.Unmount(dest, 0) +} + +// CommandLineToArgv should not be used on Unix. +// It simply returns commandLine in the only element in the returned array. +func CommandLineToArgv(commandLine string) ([]string, error) { + return []string{commandLine}, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/syscall_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/syscall_windows.go new file mode 100644 index 00000000..c7cf78fa --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/syscall_windows.go @@ -0,0 +1,131 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "fmt" + "unsafe" + + "github.com/sirupsen/logrus" + "golang.org/x/sys/windows" +) + +var ( + ntuserApiset = windows.NewLazyDLL("ext-ms-win-ntuser-window-l1-1-0") + procGetVersionExW = modkernel32.NewProc("GetVersionExW") + procGetProductInfo = modkernel32.NewProc("GetProductInfo") +) + +// OSVersion is a wrapper for Windows version information +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724439(v=vs.85).aspx +type OSVersion struct { + Version uint32 + MajorVersion uint8 + MinorVersion uint8 + Build uint16 +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724833(v=vs.85).aspx +type osVersionInfoEx struct { + OSVersionInfoSize uint32 + MajorVersion uint32 + MinorVersion uint32 + BuildNumber uint32 + PlatformID uint32 + CSDVersion [128]uint16 + ServicePackMajor uint16 + ServicePackMinor uint16 + SuiteMask uint16 + ProductType byte + Reserve byte +} + +// GetOSVersion gets the operating system version on Windows. Note that +// docker.exe must be manifested to get the correct version information. +func GetOSVersion() OSVersion { + var err error + osv := OSVersion{} + osv.Version, err = windows.GetVersion() + if err != nil { + // GetVersion never fails. + panic(err) + } + osv.MajorVersion = uint8(osv.Version & 0xFF) + osv.MinorVersion = uint8(osv.Version >> 8 & 0xFF) + osv.Build = uint16(osv.Version >> 16) + return osv +} + +// ToString returns a textual representation of the version. +func (osv OSVersion) ToString() string { + return fmt.Sprintf("%d.%d.%d", osv.MajorVersion, osv.MinorVersion, osv.Build) +} + +// IsWindowsClient returns true if the SKU is client +// @engine maintainers - this function should not be removed or modified as it +// is used to enforce licensing restrictions on Windows. +func IsWindowsClient() bool { + osviex := &osVersionInfoEx{OSVersionInfoSize: 284} + r1, _, err := procGetVersionExW.Call(uintptr(unsafe.Pointer(osviex))) + if r1 == 0 { + logrus.Warnf("GetVersionExW failed - assuming server SKU: %v", err) + return false + } + const verNTWorkstation = 0x00000001 + return osviex.ProductType == verNTWorkstation +} + +// IsIoTCore returns true if the currently running image is based off of +// Windows 10 IoT Core. +// @engine maintainers - this function should not be removed or modified as it +// is used to enforce licensing restrictions on Windows. +func IsIoTCore() bool { + var returnedProductType uint32 + r1, _, err := procGetProductInfo.Call(6, 1, 0, 0, uintptr(unsafe.Pointer(&returnedProductType))) + if r1 == 0 { + logrus.Warnf("GetProductInfo failed - assuming this is not IoT: %v", err) + return false + } + const productIoTUAP = 0x0000007B + const productIoTUAPCommercial = 0x00000083 + return returnedProductType == productIoTUAP || returnedProductType == productIoTUAPCommercial +} + +// Unmount is a platform-specific helper function to call +// the unmount syscall. Not supported on Windows +func Unmount(dest string) error { + return nil +} + +// CommandLineToArgv wraps the Windows syscall to turn a commandline into an argument array. +func CommandLineToArgv(commandLine string) ([]string, error) { + var argc int32 + + argsPtr, err := windows.UTF16PtrFromString(commandLine) + if err != nil { + return nil, err + } + + argv, err := windows.CommandLineToArgv(argsPtr, &argc) + if err != nil { + return nil, err + } + defer windows.LocalFree(windows.Handle(uintptr(unsafe.Pointer(argv)))) + + newArgs := make([]string, argc) + for i, v := range (*argv)[:argc] { + newArgs[i] = string(windows.UTF16ToString((*v)[:])) + } + + return newArgs, nil +} + +// HasWin32KSupport determines whether containers that depend on win32k can +// run on this machine. Win32k is the driver used to implement windowing. +func HasWin32KSupport() bool { + // For now, check for ntuser API support on the host. In the future, a host + // may support win32k in containers even if the host does not support ntuser + // APIs. + return ntuserApiset.Load() == nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/umask.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/umask.go new file mode 100644 index 00000000..750b39a5 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/umask.go @@ -0,0 +1,17 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "golang.org/x/sys/unix" +) + +// Umask sets current process's file mode creation mask to newmask +// and returns oldmask. +func Umask(newmask int) (oldmask int, err error) { + return unix.Umask(newmask), nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/umask_windows.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/umask_windows.go new file mode 100644 index 00000000..7e4a3952 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/umask_windows.go @@ -0,0 +1,10 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +// Umask is not supported on the windows platform. +func Umask(newmask int) (oldmask int, err error) { + // should not be called on cli code path + return 0, ErrNotSupportedPlatform +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/utimes_freebsd.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/utimes_freebsd.go new file mode 100644 index 00000000..91ccd47c --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/utimes_freebsd.go @@ -0,0 +1,27 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "syscall" + "unsafe" + + "golang.org/x/sys/unix" +) + +// LUtimesNano is used to change access and modification time of the specified path. +// It's used for symbol link file because unix.UtimesNano doesn't support a NOFOLLOW flag atm. +func LUtimesNano(path string, ts []syscall.Timespec) error { + var _path *byte + _path, err := unix.BytePtrFromString(path) + if err != nil { + return err + } + + if _, _, err := unix.Syscall(unix.SYS_LUTIMES, uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), 0); err != 0 && err != unix.ENOSYS { + return err + } + + return nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/utimes_linux.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/utimes_linux.go new file mode 100644 index 00000000..5f45d866 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/utimes_linux.go @@ -0,0 +1,28 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import ( + "syscall" + "unsafe" + + "golang.org/x/sys/unix" +) + +// LUtimesNano is used to change access and modification time of the specified path. +// It's used for symbol link file because unix.UtimesNano doesn't support a NOFOLLOW flag atm. +func LUtimesNano(path string, ts []syscall.Timespec) error { + atFdCwd := unix.AT_FDCWD + + var _path *byte + _path, err := unix.BytePtrFromString(path) + if err != nil { + return err + } + if _, _, err := unix.Syscall6(unix.SYS_UTIMENSAT, uintptr(atFdCwd), uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), unix.AT_SYMLINK_NOFOLLOW, 0, 0); err != 0 && err != unix.ENOSYS { + return err + } + + return nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/utimes_unsupported.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/utimes_unsupported.go new file mode 100644 index 00000000..fc2dbc5f --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/utimes_unsupported.go @@ -0,0 +1,14 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !linux && !freebsd +// +build !linux,!freebsd + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import "syscall" + +// LUtimesNano is only supported on linux and freebsd. +func LUtimesNano(path string, ts []syscall.Timespec) error { + return ErrNotSupportedPlatform +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/xattrs_linux.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/xattrs_linux.go new file mode 100644 index 00000000..6767f167 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/xattrs_linux.go @@ -0,0 +1,32 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +import "golang.org/x/sys/unix" + +// Lgetxattr retrieves the value of the extended attribute identified by attr +// and associated with the given path in the file system. +// It will returns a nil slice and nil error if the xattr is not set. +func Lgetxattr(path string, attr string) ([]byte, error) { + dest := make([]byte, 128) + sz, errno := unix.Lgetxattr(path, attr, dest) + if errno == unix.ENODATA { + return nil, nil + } + if errno == unix.ERANGE { + dest = make([]byte, sz) + sz, errno = unix.Lgetxattr(path, attr, dest) + } + if errno != nil { + return nil, errno + } + + return dest[:sz], nil +} + +// Lsetxattr sets the value of the extended attribute identified by attr +// and associated with the given path in the file system. +func Lsetxattr(path string, attr string, data []byte, flags int) error { + return unix.Lsetxattr(path, attr, data, flags) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/pkg/system/xattrs_unsupported.go b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/xattrs_unsupported.go new file mode 100644 index 00000000..5a4fb1cd --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/pkg/system/xattrs_unsupported.go @@ -0,0 +1,17 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !linux +// +build !linux + +package system // import "github.com/ory/dockertest/v3/docker/pkg/system" + +// Lgetxattr is not supported on platforms other than linux. +func Lgetxattr(path string, attr string) ([]byte, error) { + return nil, ErrNotSupportedPlatform +} + +// Lsetxattr is not supported on platforms other than linux. +func Lsetxattr(path string, attr string, data []byte, flags int) error { + return ErrNotSupportedPlatform +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/plugin.go b/vendor/github.com/ory/dockertest/v3/docker/plugin.go new file mode 100644 index 00000000..9a4b160b --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/plugin.go @@ -0,0 +1,419 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2018 go-dockerclient 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 docker + +import ( + "context" + "encoding/json" + "io" + "net/http" +) + +// PluginPrivilege represents a privilege for a plugin. +type PluginPrivilege struct { + Name string `json:"Name,omitempty" yaml:"Name,omitempty" toml:"Name,omitempty"` + Description string `json:"Description,omitempty" yaml:"Description,omitempty" toml:"Description,omitempty"` + Value []string `json:"Value,omitempty" yaml:"Value,omitempty" toml:"Value,omitempty"` +} + +// InstallPluginOptions specify parameters to the InstallPlugins function. +// +// See https://goo.gl/C4t7Tz for more details. +type InstallPluginOptions struct { + Remote string + Name string + Plugins []PluginPrivilege `qs:"-"` + + Auth AuthConfiguration + + Context context.Context +} + +// InstallPlugins installs a plugin or returns an error in case of failure. +// +// See https://goo.gl/C4t7Tz for more details. +func (c *Client) InstallPlugins(opts InstallPluginOptions) error { + path := "/plugins/pull?" + queryString(opts) + resp, err := c.do("POST", path, doOptions{ + data: opts.Plugins, + context: opts.Context, + }) + if err != nil { + return err + } + defer resp.Body.Close() + return nil +} + +// PluginSettings stores plugin settings. +// +// See https://goo.gl/C4t7Tz for more details. +type PluginSettings struct { + Env []string `json:"Env,omitempty" yaml:"Env,omitempty" toml:"Env,omitempty"` + Args []string `json:"Args,omitempty" yaml:"Args,omitempty" toml:"Args,omitempty"` + Devices []string `json:"Devices,omitempty" yaml:"Devices,omitempty" toml:"Devices,omitempty"` +} + +// PluginInterface stores plugin interface. +// +// See https://goo.gl/C4t7Tz for more details. +type PluginInterface struct { + Types []string `json:"Types,omitempty" yaml:"Types,omitempty" toml:"Types,omitempty"` + Socket string `json:"Socket,omitempty" yaml:"Socket,omitempty" toml:"Socket,omitempty"` +} + +// PluginNetwork stores plugin network type. +// +// See https://goo.gl/C4t7Tz for more details. +type PluginNetwork struct { + Type string `json:"Type,omitempty" yaml:"Type,omitempty" toml:"Type,omitempty"` +} + +// PluginLinux stores plugin linux setting. +// +// See https://goo.gl/C4t7Tz for more details. +type PluginLinux struct { + Capabilities []string `json:"Capabilities,omitempty" yaml:"Capabilities,omitempty" toml:"Capabilities,omitempty"` + AllowAllDevices bool `json:"AllowAllDevices,omitempty" yaml:"AllowAllDevices,omitempty" toml:"AllowAllDevices,omitempty"` + Devices []PluginLinuxDevices `json:"Devices,omitempty" yaml:"Devices,omitempty" toml:"Devices,omitempty"` +} + +// PluginLinuxDevices stores plugin linux device setting. +// +// See https://goo.gl/C4t7Tz for more details. +type PluginLinuxDevices struct { + Name string `json:"Name,omitempty" yaml:"Name,omitempty" toml:"Name,omitempty"` + Description string `json:"Documentation,omitempty" yaml:"Documentation,omitempty" toml:"Documentation,omitempty"` + Settable []string `json:"Settable,omitempty" yaml:"Settable,omitempty" toml:"Settable,omitempty"` + Path string `json:"Path,omitempty" yaml:"Path,omitempty" toml:"Path,omitempty"` +} + +// PluginEnv stores plugin environment. +// +// See https://goo.gl/C4t7Tz for more details. +type PluginEnv struct { + Name string `json:"Name,omitempty" yaml:"Name,omitempty" toml:"Name,omitempty"` + Description string `json:"Description,omitempty" yaml:"Description,omitempty" toml:"Description,omitempty"` + Settable []string `json:"Settable,omitempty" yaml:"Settable,omitempty" toml:"Settable,omitempty"` + Value string `json:"Value,omitempty" yaml:"Value,omitempty" toml:"Value,omitempty"` +} + +// PluginArgs stores plugin arguments. +// +// See https://goo.gl/C4t7Tz for more details. +type PluginArgs struct { + Name string `json:"Name,omitempty" yaml:"Name,omitempty" toml:"Name,omitempty"` + Description string `json:"Description,omitempty" yaml:"Description,omitempty" toml:"Description,omitempty"` + Settable []string `json:"Settable,omitempty" yaml:"Settable,omitempty" toml:"Settable,omitempty"` + Value []string `json:"Value,omitempty" yaml:"Value,omitempty" toml:"Value,omitempty"` +} + +// PluginUser stores plugin user. +// +// See https://goo.gl/C4t7Tz for more details. +type PluginUser struct { + UID int32 `json:"UID,omitempty" yaml:"UID,omitempty" toml:"UID,omitempty"` + GID int32 `json:"GID,omitempty" yaml:"GID,omitempty" toml:"GID,omitempty"` +} + +// PluginConfig stores plugin config. +// +// See https://goo.gl/C4t7Tz for more details. +type PluginConfig struct { + Description string `json:"Description,omitempty" yaml:"Description,omitempty" toml:"Description,omitempty"` + Documentation string + Interface PluginInterface `json:"Interface,omitempty" yaml:"Interface,omitempty" toml:"Interface,omitempty"` + Entrypoint []string `json:"Entrypoint,omitempty" yaml:"Entrypoint,omitempty" toml:"Entrypoint,omitempty"` + WorkDir string `json:"WorkDir,omitempty" yaml:"WorkDir,omitempty" toml:"WorkDir,omitempty"` + User PluginUser `json:"User,omitempty" yaml:"User,omitempty" toml:"User,omitempty"` + Network PluginNetwork `json:"Network,omitempty" yaml:"Network,omitempty" toml:"Network,omitempty"` + Linux PluginLinux `json:"Linux,omitempty" yaml:"Linux,omitempty" toml:"Linux,omitempty"` + PropagatedMount string `json:"PropagatedMount,omitempty" yaml:"PropagatedMount,omitempty" toml:"PropagatedMount,omitempty"` + Mounts []Mount `json:"Mounts,omitempty" yaml:"Mounts,omitempty" toml:"Mounts,omitempty"` + Env []PluginEnv `json:"Env,omitempty" yaml:"Env,omitempty" toml:"Env,omitempty"` + Args PluginArgs `json:"Args,omitempty" yaml:"Args,omitempty" toml:"Args,omitempty"` +} + +// PluginDetail specify results from the ListPlugins function. +// +// See https://goo.gl/C4t7Tz for more details. +type PluginDetail struct { + ID string `json:"Id,omitempty" yaml:"Id,omitempty" toml:"Id,omitempty"` + Name string `json:"Name,omitempty" yaml:"Name,omitempty" toml:"Name,omitempty"` + Tag string `json:"Tag,omitempty" yaml:"Tag,omitempty" toml:"Tag,omitempty"` + Active bool `json:"Active,omitempty" yaml:"Active,omitempty" toml:"Active,omitempty"` + Settings PluginSettings `json:"Settings,omitempty" yaml:"Settings,omitempty" toml:"Settings,omitempty"` + Config PluginConfig `json:"Config,omitempty" yaml:"Config,omitempty" toml:"Config,omitempty"` +} + +// ListPlugins returns pluginDetails or an error. +// +// See https://goo.gl/C4t7Tz for more details. +func (c *Client) ListPlugins(ctx context.Context) ([]PluginDetail, error) { + resp, err := c.do("GET", "/plugins", doOptions{ + context: ctx, + }) + if err != nil { + return nil, err + } + defer resp.Body.Close() + pluginDetails := make([]PluginDetail, 0) + if err := json.NewDecoder(resp.Body).Decode(&pluginDetails); err != nil { + return nil, err + } + return pluginDetails, nil +} + +// ListFilteredPluginsOptions specify parameters to the ListFilteredPlugins function. +// +// See https://goo.gl/C4t7Tz for more details. +type ListFilteredPluginsOptions struct { + Filters map[string][]string + Context context.Context +} + +// ListFilteredPlugins returns pluginDetails or an error. +// +// See https://goo.gl/rmdmWg for more details. +func (c *Client) ListFilteredPlugins(opts ListFilteredPluginsOptions) ([]PluginDetail, error) { + path := "/plugins/json?" + queryString(opts) + resp, err := c.do("GET", path, doOptions{ + context: opts.Context, + }) + if err != nil { + return nil, err + } + defer resp.Body.Close() + pluginDetails := make([]PluginDetail, 0) + if err := json.NewDecoder(resp.Body).Decode(&pluginDetails); err != nil { + return nil, err + } + return pluginDetails, nil +} + +// GetPluginPrivileges returns pulginPrivileges or an error. +// +// See https://goo.gl/C4t7Tz for more details. +func (c *Client) GetPluginPrivileges(name string, ctx context.Context) ([]PluginPrivilege, error) { + resp, err := c.do("GET", "/plugins/privileges?remote="+name, doOptions{ + context: ctx, + }) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var pluginPrivileges []PluginPrivilege + if err := json.NewDecoder(resp.Body).Decode(&pluginPrivileges); err != nil { + return nil, err + } + return pluginPrivileges, nil +} + +// InspectPlugins returns a pluginDetail or an error. +// +// See https://goo.gl/C4t7Tz for more details. +func (c *Client) InspectPlugins(name string, ctx context.Context) (*PluginDetail, error) { + resp, err := c.do("GET", "/plugins/"+name+"/json", doOptions{ + context: ctx, + }) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return nil, &NoSuchPlugin{ID: name} + } + return nil, err + } + resp.Body.Close() + var pluginDetail PluginDetail + if err := json.NewDecoder(resp.Body).Decode(&pluginDetail); err != nil { + return nil, err + } + return &pluginDetail, nil +} + +// RemovePluginOptions specify parameters to the RemovePlugin function. +// +// See https://goo.gl/C4t7Tz for more details. +type RemovePluginOptions struct { + // The Name of the plugin. + Name string `qs:"-"` + + Force bool `qs:"force"` + Context context.Context +} + +// RemovePlugin returns a PluginDetail or an error. +// +// See https://goo.gl/C4t7Tz for more details. +func (c *Client) RemovePlugin(opts RemovePluginOptions) (*PluginDetail, error) { + path := "/plugins/" + opts.Name + "?" + queryString(opts) + resp, err := c.do("DELETE", path, doOptions{context: opts.Context}) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return nil, &NoSuchPlugin{ID: opts.Name} + } + return nil, err + } + resp.Body.Close() + var pluginDetail PluginDetail + if err := json.NewDecoder(resp.Body).Decode(&pluginDetail); err != nil { + return nil, err + } + return &pluginDetail, nil +} + +// EnablePluginOptions specify parameters to the EnablePlugin function. +// +// See https://goo.gl/C4t7Tz for more details. +type EnablePluginOptions struct { + // The Name of the plugin. + Name string `qs:"-"` + Timeout int64 `qs:"timeout"` + + Context context.Context +} + +// EnablePlugin enables plugin that opts point or returns an error. +// +// See https://goo.gl/C4t7Tz for more details. +func (c *Client) EnablePlugin(opts EnablePluginOptions) error { + path := "/plugins/" + opts.Name + "/enable?" + queryString(opts) + resp, err := c.do("POST", path, doOptions{context: opts.Context}) + if err != nil { + return err + } + defer resp.Body.Close() + return nil +} + +// DisablePluginOptions specify parameters to the DisablePlugin function. +// +// See https://goo.gl/C4t7Tz for more details. +type DisablePluginOptions struct { + // The Name of the plugin. + Name string `qs:"-"` + + Context context.Context +} + +// DisablePlugin disables plugin that opts point or returns an error. +// +// See https://goo.gl/C4t7Tz for more details. +func (c *Client) DisablePlugin(opts DisablePluginOptions) error { + path := "/plugins/" + opts.Name + "/disable" + resp, err := c.do("POST", path, doOptions{context: opts.Context}) + if err != nil { + return err + } + defer resp.Body.Close() + return nil +} + +// CreatePluginOptions specify parameters to the CreatePlugin function. +// +// See https://goo.gl/C4t7Tz for more details. +type CreatePluginOptions struct { + // The Name of the plugin. + Name string `qs:"name"` + // Path to tar containing plugin + Path string `qs:"-"` + + Context context.Context +} + +// CreatePlugin creates plugin that opts point or returns an error. +// +// See https://goo.gl/C4t7Tz for more details. +func (c *Client) CreatePlugin(opts CreatePluginOptions) (string, error) { + path := "/plugins/create?" + queryString(opts) + resp, err := c.do("POST", path, doOptions{ + data: opts.Path, + context: opts.Context}) + if err != nil { + return "", err + } + defer resp.Body.Close() + containerNameBytes, err := io.ReadAll(resp.Body) + if err != nil { + return "", err + } + return string(containerNameBytes), nil +} + +// PushPluginOptions specify parameters to PushPlugin function. +// +// See https://goo.gl/C4t7Tz for more details. +type PushPluginOptions struct { + // The Name of the plugin. + Name string + + Context context.Context +} + +// PushPlugin pushes plugin that opts point or returns an error. +// +// See https://goo.gl/C4t7Tz for more details. +func (c *Client) PushPlugin(opts PushPluginOptions) error { + path := "/plugins/" + opts.Name + "/push" + resp, err := c.do("POST", path, doOptions{context: opts.Context}) + if err != nil { + return err + } + defer resp.Body.Close() + return nil +} + +// ConfigurePluginOptions specify parameters to the ConfigurePlugin +// +// See https://goo.gl/C4t7Tz for more details. +type ConfigurePluginOptions struct { + // The Name of the plugin. + Name string `qs:"name"` + Envs []string + + Context context.Context +} + +// ConfigurePlugin configures plugin that opts point or returns an error. +// +// See https://goo.gl/C4t7Tz for more details. +func (c *Client) ConfigurePlugin(opts ConfigurePluginOptions) error { + path := "/plugins/" + opts.Name + "/set" + resp, err := c.do("POST", path, doOptions{ + data: opts.Envs, + context: opts.Context, + }) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return &NoSuchPlugin{ID: opts.Name} + } + return err + } + defer resp.Body.Close() + return nil +} + +// NoSuchPlugin is the error returned when a given plugin does not exist. +type NoSuchPlugin struct { + ID string + Err error +} + +func (err *NoSuchPlugin) Error() string { + if err.Err != nil { + return err.Err.Error() + } + return "No such plugin: " + err.ID +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/registry_auth.go b/vendor/github.com/ory/dockertest/v3/docker/registry_auth.go new file mode 100644 index 00000000..bcd1986f --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/registry_auth.go @@ -0,0 +1,13 @@ +// Copyright © 2023 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2013 go-dockerclient 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 docker + +type registryAuth interface { + isEmpty() bool + headerKey() string +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/signal.go b/vendor/github.com/ory/dockertest/v3/docker/signal.go new file mode 100644 index 00000000..05de9f1e --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/signal.go @@ -0,0 +1,52 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2014 go-dockerclient 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 docker + +// Signal represents a signal that can be send to the container on +// KillContainer call. +type Signal int + +// These values represent all signals available on Linux, where containers will +// be running. +const ( + SIGABRT = Signal(0x6) + SIGALRM = Signal(0xe) + SIGBUS = Signal(0x7) + SIGCHLD = Signal(0x11) + SIGCLD = Signal(0x11) + SIGCONT = Signal(0x12) + SIGFPE = Signal(0x8) + SIGHUP = Signal(0x1) + SIGILL = Signal(0x4) + SIGINT = Signal(0x2) + SIGIO = Signal(0x1d) + SIGIOT = Signal(0x6) + SIGKILL = Signal(0x9) + SIGPIPE = Signal(0xd) + SIGPOLL = Signal(0x1d) + SIGPROF = Signal(0x1b) + SIGPWR = Signal(0x1e) + SIGQUIT = Signal(0x3) + SIGSEGV = Signal(0xb) + SIGSTKFLT = Signal(0x10) + SIGSTOP = Signal(0x13) + SIGSYS = Signal(0x1f) + SIGTERM = Signal(0xf) + SIGTRAP = Signal(0x5) + SIGTSTP = Signal(0x14) + SIGTTIN = Signal(0x15) + SIGTTOU = Signal(0x16) + SIGUNUSED = Signal(0x1f) + SIGURG = Signal(0x17) + SIGUSR1 = Signal(0xa) + SIGUSR2 = Signal(0xc) + SIGVTALRM = Signal(0x1a) + SIGWINCH = Signal(0x1c) + SIGXCPU = Signal(0x18) + SIGXFSZ = Signal(0x19) +) diff --git a/vendor/github.com/ory/dockertest/v3/docker/tar.go b/vendor/github.com/ory/dockertest/v3/docker/tar.go new file mode 100644 index 00000000..d466731f --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/tar.go @@ -0,0 +1,124 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2014 go-dockerclient 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 docker + +import ( + "fmt" + "io" + "os" + "path" + "path/filepath" + "strings" + + "github.com/ory/dockertest/v3/docker/pkg/archive" + "github.com/ory/dockertest/v3/docker/pkg/fileutils" +) + +func createTarStream(srcPath, dockerfilePath string) (io.ReadCloser, error) { + srcPath, err := filepath.Abs(srcPath) + if err != nil { + return nil, err + } + + excludes, err := parseDockerignore(srcPath) + if err != nil { + return nil, err + } + + includes := []string{"."} + + // If .dockerignore mentions .dockerignore or the Dockerfile + // then make sure we send both files over to the daemon + // because Dockerfile is, obviously, needed no matter what, and + // .dockerignore is needed to know if either one needs to be + // removed. The deamon will remove them for us, if needed, after it + // parses the Dockerfile. + // + // https://github.com/docker/docker/issues/8330 + // + forceIncludeFiles := []string{".dockerignore", dockerfilePath} + + for _, includeFile := range forceIncludeFiles { + if includeFile == "" { + continue + } + keepThem, err := fileutils.Matches(includeFile, excludes) + if err != nil { + return nil, fmt.Errorf("cannot match .dockerfile: '%s', error: %s", includeFile, err) + } + if keepThem { + includes = append(includes, includeFile) + } + } + + if err := validateContextDirectory(srcPath, excludes); err != nil { + return nil, err + } + tarOpts := &archive.TarOptions{ + ExcludePatterns: excludes, + IncludeFiles: includes, + Compression: archive.Uncompressed, + NoLchown: true, + } + return archive.TarWithOptions(srcPath, tarOpts) +} + +// validateContextDirectory checks if all the contents of the directory +// can be read and returns an error if some files can't be read. +// Symlinks which point to non-existing files don't trigger an error +func validateContextDirectory(srcPath string, excludes []string) error { + return filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error { + // skip this directory/file if it's not in the path, it won't get added to the context + if relFilePath, relErr := filepath.Rel(srcPath, filePath); relErr != nil { + return relErr + } else if skip, matchErr := fileutils.Matches(relFilePath, excludes); matchErr != nil { + return matchErr + } else if skip { + if f.IsDir() { + return filepath.SkipDir + } + return nil + } + + if err != nil { + if os.IsPermission(err) { + return fmt.Errorf("can't stat '%s'", filePath) + } + if os.IsNotExist(err) { + return nil + } + return err + } + + // skip checking if symlinks point to non-existing files, such symlinks can be useful + // also skip named pipes, because they hanging on open + if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 { + return nil + } + + if !f.IsDir() { + currentFile, err := os.Open(filePath) + if err != nil && os.IsPermission(err) { + return fmt.Errorf("no permission to read from '%s'", filePath) + } + currentFile.Close() + } + return nil + }) +} + +func parseDockerignore(root string) ([]string, error) { + var excludes []string + ignore, err := os.ReadFile(path.Join(root, ".dockerignore")) + if err != nil && !os.IsNotExist(err) { + return excludes, fmt.Errorf("error reading .dockerignore: '%s'", err) + } + excludes = strings.Split(string(ignore), "\n") + + return excludes, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/tls.go b/vendor/github.com/ory/dockertest/v3/docker/tls.go new file mode 100644 index 00000000..ab99f17a --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/tls.go @@ -0,0 +1,121 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2014 go-dockerclient authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// +// The content is borrowed from Docker's own source code to provide a simple +// tls based dialer + +package docker + +import ( + "crypto/tls" + "errors" + "net" + "strings" + "time" +) + +type tlsClientCon struct { + *tls.Conn + rawConn net.Conn +} + +func (c *tlsClientCon) CloseWrite() error { + // Go standard tls.Conn doesn't provide the CloseWrite() method so we do it + // on its underlying connection. + if cwc, ok := c.rawConn.(interface { + CloseWrite() error + }); ok { + return cwc.CloseWrite() + } + return nil +} + +func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) { + // We want the Timeout and Deadline values from dialer to cover the + // whole process: TCP connection and TLS handshake. This means that we + // also need to start our own timers now. + timeout := dialer.Timeout + + if !dialer.Deadline.IsZero() { + deadlineTimeout := time.Until(dialer.Deadline) + if timeout == 0 || deadlineTimeout < timeout { + timeout = deadlineTimeout + } + } + + var errChannel chan error + + if timeout != 0 { + errChannel = make(chan error, 2) + time.AfterFunc(timeout, func() { + errChannel <- errors.New("") + }) + } + + rawConn, err := dialer.Dial(network, addr) + if err != nil { + return nil, err + } + + colonPos := strings.LastIndex(addr, ":") + if colonPos == -1 { + colonPos = len(addr) + } + hostname := addr[:colonPos] + + // If no ServerName is set, infer the ServerName + // from the hostname we're connecting to. + if config.ServerName == "" { + // Make a copy to avoid polluting argument or default. + config = copyTLSConfig(config) + config.ServerName = hostname + } + + conn := tls.Client(rawConn, config) + + if timeout == 0 { + err = conn.Handshake() + } else { + go func() { + errChannel <- conn.Handshake() + }() + + err = <-errChannel + } + + if err != nil { + rawConn.Close() + return nil, err + } + + // This is Docker difference with standard's crypto/tls package: returned a + // wrapper which holds both the TLS and raw connections. + return &tlsClientCon{conn, rawConn}, nil +} + +// this exists to silent an error message in go vet +func copyTLSConfig(cfg *tls.Config) *tls.Config { + return &tls.Config{ + Certificates: cfg.Certificates, + CipherSuites: cfg.CipherSuites, + ClientAuth: cfg.ClientAuth, + ClientCAs: cfg.ClientCAs, + ClientSessionCache: cfg.ClientSessionCache, + CurvePreferences: cfg.CurvePreferences, + InsecureSkipVerify: cfg.InsecureSkipVerify, + MaxVersion: cfg.MaxVersion, + MinVersion: cfg.MinVersion, + NameToCertificate: cfg.NameToCertificate, + NextProtos: cfg.NextProtos, + PreferServerCipherSuites: cfg.PreferServerCipherSuites, + Rand: cfg.Rand, + RootCAs: cfg.RootCAs, + ServerName: cfg.ServerName, + SessionTicketKey: cfg.SessionTicketKey, + SessionTicketsDisabled: cfg.SessionTicketsDisabled, + } +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/auth.go b/vendor/github.com/ory/dockertest/v3/docker/types/auth.go new file mode 100644 index 00000000..07317462 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/auth.go @@ -0,0 +1,25 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types // import "github.com/ory/dockertest/v3/docker/types" + +// AuthConfig contains authorization information for connecting to a Registry +type AuthConfig struct { + Username string `json:"username,omitempty"` + Password string `json:"password,omitempty"` + Auth string `json:"auth,omitempty"` + + // Email is an optional value associated with the username. + // This field is deprecated and will be removed in a later + // version of docker. + Email string `json:"email,omitempty"` + + ServerAddress string `json:"serveraddress,omitempty"` + + // IdentityToken is used to authenticate the user and get + // an access token for the registry. + IdentityToken string `json:"identitytoken,omitempty"` + + // RegistryToken is a bearer token to be sent to a registry + RegistryToken string `json:"registrytoken,omitempty"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/blkiodev/blkio.go b/vendor/github.com/ory/dockertest/v3/docker/types/blkiodev/blkio.go new file mode 100644 index 00000000..fdcbf696 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/blkiodev/blkio.go @@ -0,0 +1,26 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package blkiodev // import "github.com/ory/dockertest/v3/docker/types/blkiodev" + +import "fmt" + +// WeightDevice is a structure that holds device:weight pair +type WeightDevice struct { + Path string + Weight uint16 +} + +func (w *WeightDevice) String() string { + return fmt.Sprintf("%s:%d", w.Path, w.Weight) +} + +// ThrottleDevice is a structure that holds device:rate_per_second pair +type ThrottleDevice struct { + Path string + Rate uint64 +} + +func (t *ThrottleDevice) String() string { + return fmt.Sprintf("%s:%d", t.Path, t.Rate) +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/client.go b/vendor/github.com/ory/dockertest/v3/docker/types/client.go new file mode 100644 index 00000000..bbf82702 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/client.go @@ -0,0 +1,393 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types // import "github.com/ory/dockertest/v3/docker/types" + +import ( + "bufio" + "io" + "net" + + units "github.com/docker/go-units" + "github.com/ory/dockertest/v3/docker/types/container" + "github.com/ory/dockertest/v3/docker/types/filters" +) + +// CheckpointCreateOptions holds parameters to create a checkpoint from a container +type CheckpointCreateOptions struct { + CheckpointID string + CheckpointDir string + Exit bool +} + +// CheckpointListOptions holds parameters to list checkpoints for a container +type CheckpointListOptions struct { + CheckpointDir string +} + +// CheckpointDeleteOptions holds parameters to delete a checkpoint from a container +type CheckpointDeleteOptions struct { + CheckpointID string + CheckpointDir string +} + +// ContainerAttachOptions holds parameters to attach to a container. +type ContainerAttachOptions struct { + Stream bool + Stdin bool + Stdout bool + Stderr bool + DetachKeys string + Logs bool +} + +// ContainerCommitOptions holds parameters to commit changes into a container. +type ContainerCommitOptions struct { + Reference string + Comment string + Author string + Changes []string + Pause bool + Config *container.Config +} + +// ContainerExecInspect holds information returned by exec inspect. +type ContainerExecInspect struct { + ExecID string + ContainerID string + Running bool + ExitCode int + Pid int +} + +// ContainerListOptions holds parameters to list containers with. +type ContainerListOptions struct { + Quiet bool + Size bool + All bool + Latest bool + Since string + Before string + Limit int + Filters filters.Args +} + +// ContainerLogsOptions holds parameters to filter logs with. +type ContainerLogsOptions struct { + ShowStdout bool + ShowStderr bool + Since string + Until string + Timestamps bool + Follow bool + Tail string + Details bool +} + +// ContainerRemoveOptions holds parameters to remove containers. +type ContainerRemoveOptions struct { + RemoveVolumes bool + RemoveLinks bool + Force bool +} + +// ContainerStartOptions holds parameters to start containers. +type ContainerStartOptions struct { + CheckpointID string + CheckpointDir string +} + +// CopyToContainerOptions holds information +// about files to copy into a container +type CopyToContainerOptions struct { + AllowOverwriteDirWithFile bool + CopyUIDGID bool +} + +// EventsOptions holds parameters to filter events with. +type EventsOptions struct { + Since string + Until string + Filters filters.Args +} + +// NetworkListOptions holds parameters to filter the list of networks with. +type NetworkListOptions struct { + Filters filters.Args +} + +// HijackedResponse holds connection information for a hijacked request. +type HijackedResponse struct { + Conn net.Conn + Reader *bufio.Reader +} + +// Close closes the hijacked connection and reader. +func (h *HijackedResponse) Close() { + h.Conn.Close() +} + +// CloseWriter is an interface that implements structs +// that close input streams to prevent from writing. +type CloseWriter interface { + CloseWrite() error +} + +// CloseWrite closes a readWriter for writing. +func (h *HijackedResponse) CloseWrite() error { + if conn, ok := h.Conn.(CloseWriter); ok { + return conn.CloseWrite() + } + return nil +} + +// ImageBuildOptions holds the information +// necessary to build images. +type ImageBuildOptions struct { + Tags []string + SuppressOutput bool + RemoteContext string + NoCache bool + Remove bool + ForceRemove bool + PullParent bool + Isolation container.Isolation + CPUSetCPUs string + CPUSetMems string + CPUShares int64 + CPUQuota int64 + CPUPeriod int64 + Memory int64 + MemorySwap int64 + CgroupParent string + NetworkMode string + ShmSize int64 + Dockerfile string + Ulimits []*units.Ulimit + // BuildArgs needs to be a *string instead of just a string so that + // we can tell the difference between "" (empty string) and no value + // at all (nil). See the parsing of buildArgs in + // api/server/router/build/build_routes.go for even more info. + BuildArgs map[string]*string + AuthConfigs map[string]AuthConfig + Context io.Reader + Labels map[string]string + // squash the resulting image's layers to the parent + // preserves the original image and creates a new one from the parent with all + // the changes applied to a single layer + Squash bool + // CacheFrom specifies images that are used for matching cache. Images + // specified here do not need to have a valid parent chain to match cache. + CacheFrom []string + SecurityOpt []string + ExtraHosts []string // List of extra hosts + Target string + SessionID string + Platform string +} + +// ImageBuildResponse holds information +// returned by a server after building +// an image. +type ImageBuildResponse struct { + Body io.ReadCloser + OSType string +} + +// ImageCreateOptions holds information to create images. +type ImageCreateOptions struct { + RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry. + Platform string // Platform is the target platform of the image if it needs to be pulled from the registry. +} + +// ImageImportSource holds source information for ImageImport +type ImageImportSource struct { + Source io.Reader // Source is the data to send to the server to create this image from. You must set SourceName to "-" to leverage this. + SourceName string // SourceName is the name of the image to pull. Set to "-" to leverage the Source attribute. +} + +// ImageImportOptions holds information to import images from the client host. +type ImageImportOptions struct { + Tag string // Tag is the name to tag this image with. This attribute is deprecated. + Message string // Message is the message to tag the image with + Changes []string // Changes are the raw changes to apply to this image + Platform string // Platform is the target platform of the image +} + +// ImageListOptions holds parameters to filter the list of images with. +type ImageListOptions struct { + All bool + Filters filters.Args +} + +// ImageLoadResponse returns information to the client about a load process. +type ImageLoadResponse struct { + // Body must be closed to avoid a resource leak + Body io.ReadCloser + JSON bool +} + +// ImagePullOptions holds information to pull images. +type ImagePullOptions struct { + All bool + RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry + PrivilegeFunc RequestPrivilegeFunc + Platform string +} + +// RequestPrivilegeFunc is a function interface that +// clients can supply to retry operations after +// getting an authorization error. +// This function returns the registry authentication +// header value in base 64 format, or an error +// if the privilege request fails. +type RequestPrivilegeFunc func() (string, error) + +// ImagePushOptions holds information to push images. +type ImagePushOptions ImagePullOptions + +// ImageRemoveOptions holds parameters to remove images. +type ImageRemoveOptions struct { + Force bool + PruneChildren bool +} + +// ImageSearchOptions holds parameters to search images with. +type ImageSearchOptions struct { + RegistryAuth string + PrivilegeFunc RequestPrivilegeFunc + Filters filters.Args + Limit int +} + +// ResizeOptions holds parameters to resize a tty. +// It can be used to resize container ttys and +// exec process ttys too. +type ResizeOptions struct { + Height uint + Width uint +} + +// NodeListOptions holds parameters to list nodes with. +type NodeListOptions struct { + Filters filters.Args +} + +// NodeRemoveOptions holds parameters to remove nodes with. +type NodeRemoveOptions struct { + Force bool +} + +// ServiceCreateOptions contains the options to use when creating a service. +type ServiceCreateOptions struct { + // EncodedRegistryAuth is the encoded registry authorization credentials to + // use when updating the service. + // + // This field follows the format of the X-Registry-Auth header. + EncodedRegistryAuth string + + // QueryRegistry indicates whether the service update requires + // contacting a registry. A registry may be contacted to retrieve + // the image digest and manifest, which in turn can be used to update + // platform or other information about the service. + QueryRegistry bool +} + +// ServiceCreateResponse contains the information returned to a client +// on the creation of a new service. +type ServiceCreateResponse struct { + // ID is the ID of the created service. + ID string + // Warnings is a set of non-fatal warning messages to pass on to the user. + Warnings []string `json:",omitempty"` +} + +// Values for RegistryAuthFrom in ServiceUpdateOptions +const ( + RegistryAuthFromSpec = "spec" + RegistryAuthFromPreviousSpec = "previous-spec" +) + +// ServiceUpdateOptions contains the options to be used for updating services. +type ServiceUpdateOptions struct { + // EncodedRegistryAuth is the encoded registry authorization credentials to + // use when updating the service. + // + // This field follows the format of the X-Registry-Auth header. + EncodedRegistryAuth string + + // TODO(stevvooe): Consider moving the version parameter of ServiceUpdate + // into this field. While it does open API users up to racy writes, most + // users may not need that level of consistency in practice. + + // RegistryAuthFrom specifies where to find the registry authorization + // credentials if they are not given in EncodedRegistryAuth. Valid + // values are "spec" and "previous-spec". + RegistryAuthFrom string + + // Rollback indicates whether a server-side rollback should be + // performed. When this is set, the provided spec will be ignored. + // The valid values are "previous" and "none". An empty value is the + // same as "none". + Rollback string + + // QueryRegistry indicates whether the service update requires + // contacting a registry. A registry may be contacted to retrieve + // the image digest and manifest, which in turn can be used to update + // platform or other information about the service. + QueryRegistry bool +} + +// ServiceListOptions holds parameters to list services with. +type ServiceListOptions struct { + Filters filters.Args +} + +// ServiceInspectOptions holds parameters related to the "service inspect" +// operation. +type ServiceInspectOptions struct { + InsertDefaults bool +} + +// TaskListOptions holds parameters to list tasks with. +type TaskListOptions struct { + Filters filters.Args +} + +// PluginRemoveOptions holds parameters to remove plugins. +type PluginRemoveOptions struct { + Force bool +} + +// PluginEnableOptions holds parameters to enable plugins. +type PluginEnableOptions struct { + Timeout int +} + +// PluginDisableOptions holds parameters to disable plugins. +type PluginDisableOptions struct { + Force bool +} + +// PluginInstallOptions holds parameters to install a plugin. +type PluginInstallOptions struct { + Disabled bool + AcceptAllPermissions bool + RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry + RemoteRef string // RemoteRef is the plugin name on the registry + PrivilegeFunc RequestPrivilegeFunc + AcceptPermissionsFunc func(PluginPrivileges) (bool, error) + Args []string +} + +// SwarmUnlockKeyResponse contains the response for Engine API: +// GET /swarm/unlockkey +type SwarmUnlockKeyResponse struct { + // UnlockKey is the unlock key in ASCII-armored format. + UnlockKey string +} + +// PluginCreateOptions hold all options to plugin create. +type PluginCreateOptions struct { + RepoName string +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/configs.go b/vendor/github.com/ory/dockertest/v3/docker/types/configs.go new file mode 100644 index 00000000..0db754c4 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/configs.go @@ -0,0 +1,60 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types // import "github.com/ory/dockertest/v3/docker/types" + +import ( + "github.com/ory/dockertest/v3/docker/types/container" + "github.com/ory/dockertest/v3/docker/types/network" +) + +// configs holds structs used for internal communication between the +// frontend (such as an http server) and the backend (such as the +// docker daemon). + +// ContainerCreateConfig is the parameter set to ContainerCreate() +type ContainerCreateConfig struct { + Name string + Config *container.Config + HostConfig *container.HostConfig + NetworkingConfig *network.NetworkingConfig + AdjustCPUShares bool +} + +// ContainerRmConfig holds arguments for the container remove +// operation. This struct is used to tell the backend what operations +// to perform. +type ContainerRmConfig struct { + ForceRemove, RemoveVolume, RemoveLink bool +} + +// ExecConfig is a small subset of the Config struct that holds the configuration +// for the exec feature of docker. +type ExecConfig struct { + User string // User that will run the command + Privileged bool // Is the container in privileged mode + Tty bool // Attach standard streams to a tty. + AttachStdin bool // Attach the standard input, makes possible user interaction + AttachStderr bool // Attach the standard error + AttachStdout bool // Attach the standard output + Detach bool // Execute in detach mode + DetachKeys string // Escape keys for detach + Env []string // Environment variables + WorkingDir string // Working directory + Cmd []string // Execution commands and args +} + +// PluginRmConfig holds arguments for plugin remove. +type PluginRmConfig struct { + ForceRemove bool +} + +// PluginEnableConfig holds arguments for plugin enable +type PluginEnableConfig struct { + Timeout int +} + +// PluginDisableConfig holds arguments for plugin disable. +type PluginDisableConfig struct { + ForceDisable bool +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/container/config.go b/vendor/github.com/ory/dockertest/v3/docker/types/container/config.go new file mode 100644 index 00000000..d5eb9a2f --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/container/config.go @@ -0,0 +1,72 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package container // import "github.com/ory/dockertest/v3/docker/types/container" + +import ( + "time" + + "github.com/docker/go-connections/nat" + "github.com/ory/dockertest/v3/docker/types/strslice" +) + +// MinimumDuration puts a minimum on user configured duration. +// This is to prevent API error on time unit. For example, API may +// set 3 as healthcheck interval with intention of 3 seconds, but +// Docker interprets it as 3 nanoseconds. +const MinimumDuration = 1 * time.Millisecond + +// HealthConfig holds configuration settings for the HEALTHCHECK feature. +type HealthConfig struct { + // Test is the test to perform to check that the container is healthy. + // An empty slice means to inherit the default. + // The options are: + // {} : inherit healthcheck + // {"NONE"} : disable healthcheck + // {"CMD", args...} : exec arguments directly + // {"CMD-SHELL", command} : run command with system's default shell + Test []string `json:",omitempty"` + + // Zero means to inherit. Durations are expressed as integer nanoseconds. + Interval time.Duration `json:",omitempty"` // Interval is the time to wait between checks. + Timeout time.Duration `json:",omitempty"` // Timeout is the time to wait before considering the check to have hung. + StartPeriod time.Duration `json:",omitempty"` // The start period for the container to initialize before the retries starts to count down. + + // Retries is the number of consecutive failures needed to consider a container as unhealthy. + // Zero means inherit. + Retries int `json:",omitempty"` +} + +// Config contains the configuration data about a container. +// It should hold only portable information about the container. +// Here, "portable" means "independent from the host we are running on". +// Non-portable information *should* appear in HostConfig. +// All fields added to this struct must be marked `omitempty` to keep getting +// predictable hashes from the old `v1Compatibility` configuration. +type Config struct { + Hostname string // Hostname + Domainname string // Domainname + User string // User that will run the command(s) inside the container, also support user:group + AttachStdin bool // Attach the standard input, makes possible user interaction + AttachStdout bool // Attach the standard output + AttachStderr bool // Attach the standard error + ExposedPorts nat.PortSet `json:",omitempty"` // List of exposed ports + Tty bool // Attach standard streams to a tty, including stdin if it is not closed. + OpenStdin bool // Open stdin + StdinOnce bool // If true, close stdin after the 1 attached client disconnects. + Env []string // List of environment variable to set in the container + Cmd strslice.StrSlice // Command to run when starting the container + Healthcheck *HealthConfig `json:",omitempty"` // Healthcheck describes how to check the container is healthy + ArgsEscaped bool `json:",omitempty"` // True if command is already escaped (Windows specific) + Image string // Name of the image as it was passed by the operator (e.g. could be symbolic) + Volumes map[string]struct{} // List of volumes (mounts) used for the container + WorkingDir string // Current directory (PWD) in the command will be launched + Entrypoint strslice.StrSlice // Entrypoint to run when starting the container + NetworkDisabled bool `json:",omitempty"` // Is network disabled + MacAddress string `json:",omitempty"` // Mac Address of the container + OnBuild []string // ONBUILD metadata that were defined on the image Dockerfile + Labels map[string]string // List of labels set to this container + StopSignal string `json:",omitempty"` // Signal to stop a container + StopTimeout *int `json:",omitempty"` // Timeout (in seconds) to stop a container + Shell strslice.StrSlice `json:",omitempty"` // Shell for shell-form of RUN, CMD, ENTRYPOINT +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/container/container_changes.go b/vendor/github.com/ory/dockertest/v3/docker/types/container/container_changes.go new file mode 100644 index 00000000..cd538504 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/container/container_changes.go @@ -0,0 +1,24 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package container + +// ---------------------------------------------------------------------------- +// DO NOT EDIT THIS FILE +// This file was generated by `swagger generate operation` +// +// See hack/generate-swagger-api.sh +// ---------------------------------------------------------------------------- + +// ContainerChangeResponseItem change item in response to ContainerChanges operation +// swagger:model ContainerChangeResponseItem +type ContainerChangeResponseItem struct { + + // Kind of change + // Required: true + Kind uint8 `json:"Kind"` + + // Path to file that has changed + // Required: true + Path string `json:"Path"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/container/container_create.go b/vendor/github.com/ory/dockertest/v3/docker/types/container/container_create.go new file mode 100644 index 00000000..276264a7 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/container/container_create.go @@ -0,0 +1,24 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package container + +// ---------------------------------------------------------------------------- +// DO NOT EDIT THIS FILE +// This file was generated by `swagger generate operation` +// +// See hack/generate-swagger-api.sh +// ---------------------------------------------------------------------------- + +// ContainerCreateCreatedBody OK response to ContainerCreate operation +// swagger:model ContainerCreateCreatedBody +type ContainerCreateCreatedBody struct { + + // The ID of the created container + // Required: true + ID string `json:"Id"` + + // Warnings encountered when creating the container + // Required: true + Warnings []string `json:"Warnings"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/container/container_top.go b/vendor/github.com/ory/dockertest/v3/docker/types/container/container_top.go new file mode 100644 index 00000000..47711494 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/container/container_top.go @@ -0,0 +1,24 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package container + +// ---------------------------------------------------------------------------- +// DO NOT EDIT THIS FILE +// This file was generated by `swagger generate operation` +// +// See hack/generate-swagger-api.sh +// ---------------------------------------------------------------------------- + +// ContainerTopOKBody OK response to ContainerTop operation +// swagger:model ContainerTopOKBody +type ContainerTopOKBody struct { + + // Each process running in the container, where each is process is an array of values corresponding to the titles + // Required: true + Processes [][]string `json:"Processes"` + + // The ps column titles + // Required: true + Titles []string `json:"Titles"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/container/container_update.go b/vendor/github.com/ory/dockertest/v3/docker/types/container/container_update.go new file mode 100644 index 00000000..4c3f327c --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/container/container_update.go @@ -0,0 +1,20 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package container + +// ---------------------------------------------------------------------------- +// DO NOT EDIT THIS FILE +// This file was generated by `swagger generate operation` +// +// See hack/generate-swagger-api.sh +// ---------------------------------------------------------------------------- + +// ContainerUpdateOKBody OK response to ContainerUpdate operation +// swagger:model ContainerUpdateOKBody +type ContainerUpdateOKBody struct { + + // warnings + // Required: true + Warnings []string `json:"Warnings"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/container/container_wait.go b/vendor/github.com/ory/dockertest/v3/docker/types/container/container_wait.go new file mode 100644 index 00000000..67c75ad5 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/container/container_wait.go @@ -0,0 +1,32 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package container + +// ---------------------------------------------------------------------------- +// DO NOT EDIT THIS FILE +// This file was generated by `swagger generate operation` +// +// See hack/generate-swagger-api.sh +// ---------------------------------------------------------------------------- + +// ContainerWaitOKBodyError container waiting error, if any +// swagger:model ContainerWaitOKBodyError +type ContainerWaitOKBodyError struct { + + // Details of an error + Message string `json:"Message,omitempty"` +} + +// ContainerWaitOKBody OK response to ContainerWait operation +// swagger:model ContainerWaitOKBody +type ContainerWaitOKBody struct { + + // error + // Required: true + Error *ContainerWaitOKBodyError `json:"Error"` + + // Exit code of the container + // Required: true + StatusCode int64 `json:"StatusCode"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/container/host_config.go b/vendor/github.com/ory/dockertest/v3/docker/types/container/host_config.go new file mode 100644 index 00000000..e550e938 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/container/host_config.go @@ -0,0 +1,409 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package container // import "github.com/ory/dockertest/v3/docker/types/container" + +import ( + "strings" + + "github.com/docker/go-connections/nat" + "github.com/docker/go-units" + "github.com/ory/dockertest/v3/docker/types/blkiodev" + "github.com/ory/dockertest/v3/docker/types/mount" + "github.com/ory/dockertest/v3/docker/types/strslice" +) + +// Isolation represents the isolation technology of a container. The supported +// values are platform specific +type Isolation string + +// IsDefault indicates the default isolation technology of a container. On Linux this +// is the native driver. On Windows, this is a Windows Server Container. +func (i Isolation) IsDefault() bool { + return strings.ToLower(string(i)) == "default" || string(i) == "" +} + +// IsHyperV indicates the use of a Hyper-V partition for isolation +func (i Isolation) IsHyperV() bool { + return strings.ToLower(string(i)) == "hyperv" +} + +// IsProcess indicates the use of process isolation +func (i Isolation) IsProcess() bool { + return strings.ToLower(string(i)) == "process" +} + +const ( + // IsolationEmpty is unspecified (same behavior as default) + IsolationEmpty = Isolation("") + // IsolationDefault is the default isolation mode on current daemon + IsolationDefault = Isolation("default") + // IsolationProcess is process isolation mode + IsolationProcess = Isolation("process") + // IsolationHyperV is HyperV isolation mode + IsolationHyperV = Isolation("hyperv") +) + +// IpcMode represents the container ipc stack. +type IpcMode string + +// IsPrivate indicates whether the container uses its own private ipc namespace which can not be shared. +func (n IpcMode) IsPrivate() bool { + return n == "private" +} + +// IsHost indicates whether the container shares the host's ipc namespace. +func (n IpcMode) IsHost() bool { + return n == "host" +} + +// IsShareable indicates whether the container's ipc namespace can be shared with another container. +func (n IpcMode) IsShareable() bool { + return n == "shareable" +} + +// IsContainer indicates whether the container uses another container's ipc namespace. +func (n IpcMode) IsContainer() bool { + parts := strings.SplitN(string(n), ":", 2) + return len(parts) > 1 && parts[0] == "container" +} + +// IsNone indicates whether container IpcMode is set to "none". +func (n IpcMode) IsNone() bool { + return n == "none" +} + +// IsEmpty indicates whether container IpcMode is empty +func (n IpcMode) IsEmpty() bool { + return n == "" +} + +// Valid indicates whether the ipc mode is valid. +func (n IpcMode) Valid() bool { + return n.IsEmpty() || n.IsNone() || n.IsPrivate() || n.IsHost() || n.IsShareable() || n.IsContainer() +} + +// Container returns the name of the container ipc stack is going to be used. +func (n IpcMode) Container() string { + parts := strings.SplitN(string(n), ":", 2) + if len(parts) > 1 && parts[0] == "container" { + return parts[1] + } + return "" +} + +// NetworkMode represents the container network stack. +type NetworkMode string + +// IsNone indicates whether container isn't using a network stack. +func (n NetworkMode) IsNone() bool { + return n == "none" +} + +// IsDefault indicates whether container uses the default network stack. +func (n NetworkMode) IsDefault() bool { + return n == "default" +} + +// IsPrivate indicates whether container uses its private network stack. +func (n NetworkMode) IsPrivate() bool { + return !(n.IsHost() || n.IsContainer()) +} + +// IsContainer indicates whether container uses a container network stack. +func (n NetworkMode) IsContainer() bool { + parts := strings.SplitN(string(n), ":", 2) + return len(parts) > 1 && parts[0] == "container" +} + +// ConnectedContainer is the id of the container which network this container is connected to. +func (n NetworkMode) ConnectedContainer() string { + parts := strings.SplitN(string(n), ":", 2) + if len(parts) > 1 { + return parts[1] + } + return "" +} + +// UserDefined indicates user-created network +func (n NetworkMode) UserDefined() string { + if n.IsUserDefined() { + return string(n) + } + return "" +} + +// UsernsMode represents userns mode in the container. +type UsernsMode string + +// IsHost indicates whether the container uses the host's userns. +func (n UsernsMode) IsHost() bool { + return n == "host" +} + +// IsPrivate indicates whether the container uses the a private userns. +func (n UsernsMode) IsPrivate() bool { + return !(n.IsHost()) +} + +// Valid indicates whether the userns is valid. +func (n UsernsMode) Valid() bool { + parts := strings.Split(string(n), ":") + switch mode := parts[0]; mode { + case "", "host": + default: + return false + } + return true +} + +// CgroupSpec represents the cgroup to use for the container. +type CgroupSpec string + +// IsContainer indicates whether the container is using another container cgroup +func (c CgroupSpec) IsContainer() bool { + parts := strings.SplitN(string(c), ":", 2) + return len(parts) > 1 && parts[0] == "container" +} + +// Valid indicates whether the cgroup spec is valid. +func (c CgroupSpec) Valid() bool { + return c.IsContainer() || c == "" +} + +// Container returns the name of the container whose cgroup will be used. +func (c CgroupSpec) Container() string { + parts := strings.SplitN(string(c), ":", 2) + if len(parts) > 1 { + return parts[1] + } + return "" +} + +// UTSMode represents the UTS namespace of the container. +type UTSMode string + +// IsPrivate indicates whether the container uses its private UTS namespace. +func (n UTSMode) IsPrivate() bool { + return !(n.IsHost()) +} + +// IsHost indicates whether the container uses the host's UTS namespace. +func (n UTSMode) IsHost() bool { + return n == "host" +} + +// Valid indicates whether the UTS namespace is valid. +func (n UTSMode) Valid() bool { + parts := strings.Split(string(n), ":") + switch mode := parts[0]; mode { + case "", "host": + default: + return false + } + return true +} + +// PidMode represents the pid namespace of the container. +type PidMode string + +// IsPrivate indicates whether the container uses its own new pid namespace. +func (n PidMode) IsPrivate() bool { + return !(n.IsHost() || n.IsContainer()) +} + +// IsHost indicates whether the container uses the host's pid namespace. +func (n PidMode) IsHost() bool { + return n == "host" +} + +// IsContainer indicates whether the container uses a container's pid namespace. +func (n PidMode) IsContainer() bool { + parts := strings.SplitN(string(n), ":", 2) + return len(parts) > 1 && parts[0] == "container" +} + +// Valid indicates whether the pid namespace is valid. +func (n PidMode) Valid() bool { + parts := strings.Split(string(n), ":") + switch mode := parts[0]; mode { + case "", "host": + case "container": + if len(parts) != 2 || parts[1] == "" { + return false + } + default: + return false + } + return true +} + +// Container returns the name of the container whose pid namespace is going to be used. +func (n PidMode) Container() string { + parts := strings.SplitN(string(n), ":", 2) + if len(parts) > 1 { + return parts[1] + } + return "" +} + +// DeviceMapping represents the device mapping between the host and the container. +type DeviceMapping struct { + PathOnHost string + PathInContainer string + CgroupPermissions string +} + +// RestartPolicy represents the restart policies of the container. +type RestartPolicy struct { + Name string + MaximumRetryCount int +} + +// IsNone indicates whether the container has the "no" restart policy. +// This means the container will not automatically restart when exiting. +func (rp *RestartPolicy) IsNone() bool { + return rp.Name == "no" || rp.Name == "" +} + +// IsAlways indicates whether the container has the "always" restart policy. +// This means the container will automatically restart regardless of the exit status. +func (rp *RestartPolicy) IsAlways() bool { + return rp.Name == "always" +} + +// IsOnFailure indicates whether the container has the "on-failure" restart policy. +// This means the container will automatically restart of exiting with a non-zero exit status. +func (rp *RestartPolicy) IsOnFailure() bool { + return rp.Name == "on-failure" +} + +// IsUnlessStopped indicates whether the container has the +// "unless-stopped" restart policy. This means the container will +// automatically restart unless user has put it to stopped state. +func (rp *RestartPolicy) IsUnlessStopped() bool { + return rp.Name == "unless-stopped" +} + +// IsSame compares two RestartPolicy to see if they are the same +func (rp *RestartPolicy) IsSame(tp *RestartPolicy) bool { + return rp.Name == tp.Name && rp.MaximumRetryCount == tp.MaximumRetryCount +} + +// LogMode is a type to define the available modes for logging +// These modes affect how logs are handled when log messages start piling up. +type LogMode string + +// Available logging modes +const ( + LogModeUnset = "" + LogModeBlocking LogMode = "blocking" + LogModeNonBlock LogMode = "non-blocking" +) + +// LogConfig represents the logging configuration of the container. +type LogConfig struct { + Type string + Config map[string]string +} + +// Resources contains container's resources (cgroups config, ulimits...) +type Resources struct { + // Applicable to all platforms + CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers) + Memory int64 // Memory limit (in bytes) + NanoCPUs int64 `json:"NanoCpus"` // CPU quota in units of 10-9 CPUs. + + // Applicable to UNIX platforms + CgroupParent string // Parent cgroup. + BlkioWeight uint16 // Block IO weight (relative weight vs. other containers) + BlkioWeightDevice []*blkiodev.WeightDevice + BlkioDeviceReadBps []*blkiodev.ThrottleDevice + BlkioDeviceWriteBps []*blkiodev.ThrottleDevice + BlkioDeviceReadIOps []*blkiodev.ThrottleDevice + BlkioDeviceWriteIOps []*blkiodev.ThrottleDevice + CPUPeriod int64 `json:"CpuPeriod"` // CPU CFS (Completely Fair Scheduler) period + CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota + CPURealtimePeriod int64 `json:"CpuRealtimePeriod"` // CPU real-time period + CPURealtimeRuntime int64 `json:"CpuRealtimeRuntime"` // CPU real-time runtime + CpusetCpus string // CpusetCpus 0-2, 0,1 + CpusetMems string // CpusetMems 0-2, 0,1 + Devices []DeviceMapping // List of devices to map inside the container + DeviceCgroupRules []string // List of rule to be added to the device cgroup + DiskQuota int64 // Disk limit (in bytes) + KernelMemory int64 // Kernel memory limit (in bytes) + MemoryReservation int64 // Memory soft limit (in bytes) + MemorySwap int64 // Total memory usage (memory + swap); set `-1` to enable unlimited swap + MemorySwappiness *int64 // Tuning container memory swappiness behaviour + OomKillDisable *bool // Whether to disable OOM Killer or not + PidsLimit int64 // Setting pids limit for a container + Ulimits []*units.Ulimit // List of ulimits to be set in the container + + // Applicable to Windows + CPUCount int64 `json:"CpuCount"` // CPU count + CPUPercent int64 `json:"CpuPercent"` // CPU percent + IOMaximumIOps uint64 // Maximum IOps for the container system drive + IOMaximumBandwidth uint64 // Maximum IO in bytes per second for the container system drive +} + +// UpdateConfig holds the mutable attributes of a Container. +// Those attributes can be updated at runtime. +type UpdateConfig struct { + // Contains container's resources (cgroups, ulimits) + Resources + RestartPolicy RestartPolicy +} + +// HostConfig the non-portable Config structure of a container. +// Here, "non-portable" means "dependent of the host we are running on". +// Portable information *should* appear in Config. +type HostConfig struct { + // Applicable to all platforms + Binds []string // List of volume bindings for this container + ContainerIDFile string // File (path) where the containerId is written + LogConfig LogConfig // Configuration of the logs for this container + NetworkMode NetworkMode // Network mode to use for the container + PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host + RestartPolicy RestartPolicy // Restart policy to be used for the container + AutoRemove bool // Automatically remove container when it exits + VolumeDriver string // Name of the volume driver used to mount volumes + VolumesFrom []string // List of volumes to take from other container + + // Applicable to UNIX platforms + CapAdd strslice.StrSlice // List of kernel capabilities to add to the container + CapDrop strslice.StrSlice // List of kernel capabilities to remove from the container + DNS []string `json:"Dns"` // List of DNS server to lookup + DNSOptions []string `json:"DnsOptions"` // List of DNSOption to look for + DNSSearch []string `json:"DnsSearch"` // List of DNSSearch to look for + ExtraHosts []string // List of extra hosts + GroupAdd []string // List of additional groups that the container process will run as + IpcMode IpcMode // IPC namespace to use for the container + Cgroup CgroupSpec // Cgroup to use for the container + Links []string // List of links (in the name:alias form) + OomScoreAdj int // Container preference for OOM-killing + PidMode PidMode // PID namespace to use for the container + Privileged bool // Is the container in privileged mode + PublishAllPorts bool // Should docker publish all exposed port for the container + ReadonlyRootfs bool // Is the container root filesystem in read-only + SecurityOpt []string // List of string values to customize labels for MLS systems, such as SELinux. + StorageOpt map[string]string `json:",omitempty"` // Storage driver options per container. + Tmpfs map[string]string `json:",omitempty"` // List of tmpfs (mounts) used for the container + UTSMode UTSMode // UTS namespace to use for the container + UsernsMode UsernsMode // The user namespace to use for the container + ShmSize int64 // Total shm memory usage + Sysctls map[string]string `json:",omitempty"` // List of Namespaced sysctls used for the container + Runtime string `json:",omitempty"` // Runtime to use with this container + + // Applicable to Windows + ConsoleSize [2]uint // Initial console size (height,width) + Isolation Isolation // Isolation technology of the container (e.g. default, hyperv) + + // Contains container's resources (cgroups, ulimits) + Resources + + // Mounts specs used by the container + Mounts []mount.Mount `json:",omitempty"` + + // Run a custom init inside the container, if null, use the daemon's configured settings + Init *bool `json:",omitempty"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/container/hostconfig_unix.go b/vendor/github.com/ory/dockertest/v3/docker/types/container/hostconfig_unix.go new file mode 100644 index 00000000..8f8f8337 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/container/hostconfig_unix.go @@ -0,0 +1,45 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows +// +build !windows + +package container // import "github.com/ory/dockertest/v3/docker/types/container" + +// IsValid indicates if an isolation technology is valid +func (i Isolation) IsValid() bool { + return i.IsDefault() +} + +// NetworkName returns the name of the network stack. +func (n NetworkMode) NetworkName() string { + if n.IsBridge() { + return "bridge" + } else if n.IsHost() { + return "host" + } else if n.IsContainer() { + return "container" + } else if n.IsNone() { + return "none" + } else if n.IsDefault() { + return "default" + } else if n.IsUserDefined() { + return n.UserDefined() + } + return "" +} + +// IsBridge indicates whether container uses the bridge network stack +func (n NetworkMode) IsBridge() bool { + return n == "bridge" +} + +// IsHost indicates whether container uses the host network stack. +func (n NetworkMode) IsHost() bool { + return n == "host" +} + +// IsUserDefined indicates user-created network +func (n NetworkMode) IsUserDefined() bool { + return !n.IsDefault() && !n.IsBridge() && !n.IsHost() && !n.IsNone() && !n.IsContainer() +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/container/hostconfig_windows.go b/vendor/github.com/ory/dockertest/v3/docker/types/container/hostconfig_windows.go new file mode 100644 index 00000000..f3f13f8a --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/container/hostconfig_windows.go @@ -0,0 +1,43 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package container // import "github.com/ory/dockertest/v3/docker/types/container" + +// IsBridge indicates whether container uses the bridge network stack +// in windows it is given the name NAT +func (n NetworkMode) IsBridge() bool { + return n == "nat" +} + +// IsHost indicates whether container uses the host network stack. +// returns false as this is not supported by windows +func (n NetworkMode) IsHost() bool { + return false +} + +// IsUserDefined indicates user-created network +func (n NetworkMode) IsUserDefined() bool { + return !n.IsDefault() && !n.IsNone() && !n.IsBridge() && !n.IsContainer() +} + +// IsValid indicates if an isolation technology is valid +func (i Isolation) IsValid() bool { + return i.IsDefault() || i.IsHyperV() || i.IsProcess() +} + +// NetworkName returns the name of the network stack. +func (n NetworkMode) NetworkName() string { + if n.IsDefault() { + return "default" + } else if n.IsBridge() { + return "nat" + } else if n.IsNone() { + return "none" + } else if n.IsContainer() { + return "container" + } else if n.IsUserDefined() { + return n.UserDefined() + } + + return "" +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/container/waitcondition.go b/vendor/github.com/ory/dockertest/v3/docker/types/container/waitcondition.go new file mode 100644 index 00000000..78e56b80 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/container/waitcondition.go @@ -0,0 +1,25 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package container // import "github.com/ory/dockertest/v3/docker/types/container" + +// WaitCondition is a type used to specify a container state for which +// to wait. +type WaitCondition string + +// Possible WaitCondition Values. +// +// WaitConditionNotRunning (default) is used to wait for any of the non-running +// states: "created", "exited", "dead", "removing", or "removed". +// +// WaitConditionNextExit is used to wait for the next time the state changes +// to a non-running state. If the state is currently "created" or "exited", +// this would cause Wait() to block until either the container runs and exits +// or is removed. +// +// WaitConditionRemoved is used to wait for the container to be removed. +const ( + WaitConditionNotRunning WaitCondition = "not-running" + WaitConditionNextExit WaitCondition = "next-exit" + WaitConditionRemoved WaitCondition = "removed" +) diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/error_response.go b/vendor/github.com/ory/dockertest/v3/docker/types/error_response.go new file mode 100644 index 00000000..c62a6c7c --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/error_response.go @@ -0,0 +1,16 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// ErrorResponse Represents an error. +// swagger:model ErrorResponse +type ErrorResponse struct { + + // The error message. + // Required: true + Message string `json:"message"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/filters/parse.go b/vendor/github.com/ory/dockertest/v3/docker/types/filters/parse.go new file mode 100644 index 00000000..df2a9f43 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/filters/parse.go @@ -0,0 +1,354 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +/* +Package filters provides tools for encoding a mapping of keys to a set of +multiple values. +*/ +package filters // import "github.com/ory/dockertest/v3/docker/types/filters" + +import ( + "encoding/json" + "errors" + "regexp" + "strings" + + "github.com/ory/dockertest/v3/docker/types/versions" +) + +// Args stores a mapping of keys to a set of multiple values. +type Args struct { + fields map[string]map[string]bool +} + +// KeyValuePair are used to initialize a new Args +type KeyValuePair struct { + Key string + Value string +} + +// Arg creates a new KeyValuePair for initializing Args +func Arg(key, value string) KeyValuePair { + return KeyValuePair{Key: key, Value: value} +} + +// NewArgs returns a new Args populated with the initial args +func NewArgs(initialArgs ...KeyValuePair) Args { + args := Args{fields: map[string]map[string]bool{}} + for _, arg := range initialArgs { + args.Add(arg.Key, arg.Value) + } + return args +} + +// ParseFlag parses a key=value string and adds it to an Args. +// +// Deprecated: Use Args.Add() +func ParseFlag(arg string, prev Args) (Args, error) { + filters := prev + if len(arg) == 0 { + return filters, nil + } + + if !strings.Contains(arg, "=") { + return filters, ErrBadFormat + } + + f := strings.SplitN(arg, "=", 2) + + name := strings.ToLower(strings.TrimSpace(f[0])) + value := strings.TrimSpace(f[1]) + + filters.Add(name, value) + + return filters, nil +} + +// ErrBadFormat is an error returned when a filter is not in the form key=value +// +// Deprecated: this error will be removed in a future version +var ErrBadFormat = errors.New("bad format of filter (expected name=value)") + +// ToParam encodes the Args as args JSON encoded string +// +// Deprecated: use ToJSON +func ToParam(a Args) (string, error) { + return ToJSON(a) +} + +// MarshalJSON returns a JSON byte representation of the Args +func (args Args) MarshalJSON() ([]byte, error) { + if len(args.fields) == 0 { + return []byte{}, nil + } + return json.Marshal(args.fields) +} + +// ToJSON returns the Args as a JSON encoded string +func ToJSON(a Args) (string, error) { + if a.Len() == 0 { + return "", nil + } + buf, err := json.Marshal(a) + return string(buf), err +} + +// ToParamWithVersion encodes Args as a JSON string. If version is less than 1.22 +// then the encoded format will use an older legacy format where the values are a +// list of strings, instead of a set. +// +// Deprecated: Use ToJSON +func ToParamWithVersion(version string, a Args) (string, error) { + if a.Len() == 0 { + return "", nil + } + + if version != "" && versions.LessThan(version, "1.22") { + buf, err := json.Marshal(convertArgsToSlice(a.fields)) + return string(buf), err + } + + return ToJSON(a) +} + +// FromParam decodes a JSON encoded string into Args +// +// Deprecated: use FromJSON +func FromParam(p string) (Args, error) { + return FromJSON(p) +} + +// FromJSON decodes a JSON encoded string into Args +func FromJSON(p string) (Args, error) { + args := NewArgs() + + if p == "" { + return args, nil + } + + raw := []byte(p) + err := json.Unmarshal(raw, &args) + if err == nil { + return args, nil + } + + // Fallback to parsing arguments in the legacy slice format + deprecated := map[string][]string{} + if legacyErr := json.Unmarshal(raw, &deprecated); legacyErr != nil { + return args, err + } + + args.fields = deprecatedArgs(deprecated) + return args, nil +} + +// UnmarshalJSON populates the Args from JSON encode bytes +func (args Args) UnmarshalJSON(raw []byte) error { + if len(raw) == 0 { + return nil + } + return json.Unmarshal(raw, &args.fields) +} + +// Get returns the list of values associated with the key +func (args Args) Get(key string) []string { + values := args.fields[key] + if values == nil { + return make([]string, 0) + } + slice := make([]string, 0, len(values)) + for key := range values { + slice = append(slice, key) + } + return slice +} + +// Add a new value to the set of values +func (args Args) Add(key, value string) { + if _, ok := args.fields[key]; ok { + args.fields[key][value] = true + } else { + args.fields[key] = map[string]bool{value: true} + } +} + +// Del removes a value from the set +func (args Args) Del(key, value string) { + if _, ok := args.fields[key]; ok { + delete(args.fields[key], value) + if len(args.fields[key]) == 0 { + delete(args.fields, key) + } + } +} + +// Len returns the number of keys in the mapping +func (args Args) Len() int { + return len(args.fields) +} + +// MatchKVList returns true if all the pairs in sources exist as key=value +// pairs in the mapping at key, or if there are no values at key. +func (args Args) MatchKVList(key string, sources map[string]string) bool { + fieldValues := args.fields[key] + + //do not filter if there is no filter set or cannot determine filter + if len(fieldValues) == 0 { + return true + } + + if len(sources) == 0 { + return false + } + + for value := range fieldValues { + testKV := strings.SplitN(value, "=", 2) + + v, ok := sources[testKV[0]] + if !ok { + return false + } + if len(testKV) == 2 && testKV[1] != v { + return false + } + } + + return true +} + +// Match returns true if any of the values at key match the source string +func (args Args) Match(field, source string) bool { + if args.ExactMatch(field, source) { + return true + } + + fieldValues := args.fields[field] + for name2match := range fieldValues { + match, err := regexp.MatchString(name2match, source) + if err != nil { + continue + } + if match { + return true + } + } + return false +} + +// ExactMatch returns true if the source matches exactly one of the values. +func (args Args) ExactMatch(key, source string) bool { + fieldValues, ok := args.fields[key] + //do not filter if there is no filter set or cannot determine filter + if !ok || len(fieldValues) == 0 { + return true + } + + // try to match full name value to avoid O(N) regular expression matching + return fieldValues[source] +} + +// UniqueExactMatch returns true if there is only one value and the source +// matches exactly the value. +func (args Args) UniqueExactMatch(key, source string) bool { + fieldValues := args.fields[key] + //do not filter if there is no filter set or cannot determine filter + if len(fieldValues) == 0 { + return true + } + if len(args.fields[key]) != 1 { + return false + } + + // try to match full name value to avoid O(N) regular expression matching + return fieldValues[source] +} + +// FuzzyMatch returns true if the source matches exactly one value, or the +// source has one of the values as a prefix. +func (args Args) FuzzyMatch(key, source string) bool { + if args.ExactMatch(key, source) { + return true + } + + fieldValues := args.fields[key] + for prefix := range fieldValues { + if strings.HasPrefix(source, prefix) { + return true + } + } + return false +} + +// Include returns true if the key exists in the mapping +// +// Deprecated: use Contains +func (args Args) Include(field string) bool { + _, ok := args.fields[field] + return ok +} + +// Contains returns true if the key exists in the mapping +func (args Args) Contains(field string) bool { + _, ok := args.fields[field] + return ok +} + +type invalidFilter string + +func (e invalidFilter) Error() string { + return "Invalid filter '" + string(e) + "'" +} + +func (invalidFilter) InvalidParameter() {} + +// Validate compared the set of accepted keys against the keys in the mapping. +// An error is returned if any mapping keys are not in the accepted set. +func (args Args) Validate(accepted map[string]bool) error { + for name := range args.fields { + if !accepted[name] { + return invalidFilter(name) + } + } + return nil +} + +// WalkValues iterates over the list of values for a key in the mapping and calls +// op() for each value. If op returns an error the iteration stops and the +// error is returned. +func (args Args) WalkValues(field string, op func(value string) error) error { + if _, ok := args.fields[field]; !ok { + return nil + } + for v := range args.fields[field] { + if err := op(v); err != nil { + return err + } + } + return nil +} + +func deprecatedArgs(d map[string][]string) map[string]map[string]bool { + m := map[string]map[string]bool{} + for k, v := range d { + values := map[string]bool{} + for _, vv := range v { + values[vv] = true + } + m[k] = values + } + return m +} + +func convertArgsToSlice(f map[string]map[string]bool) map[string][]string { + m := map[string][]string{} + for k, v := range f { + values := []string{} + for kk := range v { + if v[kk] { + values = append(values, kk) + } + } + m[k] = values + } + return m +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/graph_driver_data.go b/vendor/github.com/ory/dockertest/v3/docker/types/graph_driver_data.go new file mode 100644 index 00000000..96a3ac4f --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/graph_driver_data.go @@ -0,0 +1,20 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// GraphDriverData Information about a container's graph driver. +// swagger:model GraphDriverData +type GraphDriverData struct { + + // data + // Required: true + Data map[string]string `json:"Data"` + + // name + // Required: true + Name string `json:"Name"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/id_response.go b/vendor/github.com/ory/dockertest/v3/docker/types/id_response.go new file mode 100644 index 00000000..11765036 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/id_response.go @@ -0,0 +1,16 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// IDResponse Response to an API call that returns just an Id +// swagger:model IdResponse +type IDResponse struct { + + // The id of the newly created object. + // Required: true + ID string `json:"Id"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/image_delete_response_item.go b/vendor/github.com/ory/dockertest/v3/docker/types/image_delete_response_item.go new file mode 100644 index 00000000..0c385a10 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/image_delete_response_item.go @@ -0,0 +1,18 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// ImageDeleteResponseItem image delete response item +// swagger:model ImageDeleteResponseItem +type ImageDeleteResponseItem struct { + + // The image ID of an image that was deleted + Deleted string `json:"Deleted,omitempty"` + + // The image ID of an image that was untagged + Untagged string `json:"Untagged,omitempty"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/image_summary.go b/vendor/github.com/ory/dockertest/v3/docker/types/image_summary.go new file mode 100644 index 00000000..78862f41 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/image_summary.go @@ -0,0 +1,52 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// ImageSummary image summary +// swagger:model ImageSummary +type ImageSummary struct { + + // containers + // Required: true + Containers int64 `json:"Containers"` + + // created + // Required: true + Created int64 `json:"Created"` + + // Id + // Required: true + ID string `json:"Id"` + + // labels + // Required: true + Labels map[string]string `json:"Labels"` + + // parent Id + // Required: true + ParentID string `json:"ParentId"` + + // repo digests + // Required: true + RepoDigests []string `json:"RepoDigests"` + + // repo tags + // Required: true + RepoTags []string `json:"RepoTags"` + + // shared size + // Required: true + SharedSize int64 `json:"SharedSize"` + + // size + // Required: true + Size int64 `json:"Size"` + + // virtual size + // Required: true + VirtualSize int64 `json:"VirtualSize"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/mount/mount.go b/vendor/github.com/ory/dockertest/v3/docker/types/mount/mount.go new file mode 100644 index 00000000..a9daabce --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/mount/mount.go @@ -0,0 +1,133 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package mount // import "github.com/ory/dockertest/v3/docker/types/mount" + +import ( + "os" +) + +// Type represents the type of a mount. +type Type string + +// Type constants +const ( + // TypeBind is the type for mounting host dir + TypeBind Type = "bind" + // TypeVolume is the type for remote storage volumes + TypeVolume Type = "volume" + // TypeTmpfs is the type for mounting tmpfs + TypeTmpfs Type = "tmpfs" + // TypeNamedPipe is the type for mounting Windows named pipes + TypeNamedPipe Type = "npipe" +) + +// Mount represents a mount (volume). +type Mount struct { + Type Type `json:",omitempty"` + // Source specifies the name of the mount. Depending on mount type, this + // may be a volume name or a host path, or even ignored. + // Source is not supported for tmpfs (must be an empty value) + Source string `json:",omitempty"` + Target string `json:",omitempty"` + ReadOnly bool `json:",omitempty"` + Consistency Consistency `json:",omitempty"` + + BindOptions *BindOptions `json:",omitempty"` + VolumeOptions *VolumeOptions `json:",omitempty"` + TmpfsOptions *TmpfsOptions `json:",omitempty"` +} + +// Propagation represents the propagation of a mount. +type Propagation string + +const ( + // PropagationRPrivate RPRIVATE + PropagationRPrivate Propagation = "rprivate" + // PropagationPrivate PRIVATE + PropagationPrivate Propagation = "private" + // PropagationRShared RSHARED + PropagationRShared Propagation = "rshared" + // PropagationShared SHARED + PropagationShared Propagation = "shared" + // PropagationRSlave RSLAVE + PropagationRSlave Propagation = "rslave" + // PropagationSlave SLAVE + PropagationSlave Propagation = "slave" +) + +// Propagations is the list of all valid mount propagations +var Propagations = []Propagation{ + PropagationRPrivate, + PropagationPrivate, + PropagationRShared, + PropagationShared, + PropagationRSlave, + PropagationSlave, +} + +// Consistency represents the consistency requirements of a mount. +type Consistency string + +const ( + // ConsistencyFull guarantees bind mount-like consistency + ConsistencyFull Consistency = "consistent" + // ConsistencyCached mounts can cache read data and FS structure + ConsistencyCached Consistency = "cached" + // ConsistencyDelegated mounts can cache read and written data and structure + ConsistencyDelegated Consistency = "delegated" + // ConsistencyDefault provides "consistent" behavior unless overridden + ConsistencyDefault Consistency = "default" +) + +// BindOptions defines options specific to mounts of type "bind". +type BindOptions struct { + Propagation Propagation `json:",omitempty"` +} + +// VolumeOptions represents the options for a mount of type volume. +type VolumeOptions struct { + NoCopy bool `json:",omitempty"` + Labels map[string]string `json:",omitempty"` + DriverConfig *Driver `json:",omitempty"` +} + +// Driver represents a volume driver. +type Driver struct { + Name string `json:",omitempty"` + Options map[string]string `json:",omitempty"` +} + +// TmpfsOptions defines options specific to mounts of type "tmpfs". +type TmpfsOptions struct { + // Size sets the size of the tmpfs, in bytes. + // + // This will be converted to an operating system specific value + // depending on the host. For example, on linux, it will be converted to + // use a 'k', 'm' or 'g' syntax. BSD, though not widely supported with + // docker, uses a straight byte value. + // + // Percentages are not supported. + SizeBytes int64 `json:",omitempty"` + // Mode of the tmpfs upon creation + Mode os.FileMode `json:",omitempty"` + + // TODO(stevvooe): There are several more tmpfs flags, specified in the + // daemon, that are accepted. Only the most basic are added for now. + // + // From docker/docker/pkg/mount/flags.go: + // + // var validFlags = map[string]bool{ + // "": true, + // "size": true, X + // "mode": true, X + // "uid": true, + // "gid": true, + // "nr_inodes": true, + // "nr_blocks": true, + // "mpol": true, + // } + // + // Some of these may be straightforward to add, but others, such as + // uid/gid have implications in a clustered system. +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/network/network.go b/vendor/github.com/ory/dockertest/v3/docker/types/network/network.go new file mode 100644 index 00000000..e6eb14da --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/network/network.go @@ -0,0 +1,111 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package network // import "github.com/ory/dockertest/v3/docker/types/network" + +// Address represents an IP address +type Address struct { + Addr string + PrefixLen int +} + +// IPAM represents IP Address Management +type IPAM struct { + Driver string + Options map[string]string //Per network IPAM driver options + Config []IPAMConfig +} + +// IPAMConfig represents IPAM configurations +type IPAMConfig struct { + Subnet string `json:",omitempty"` + IPRange string `json:",omitempty"` + Gateway string `json:",omitempty"` + AuxAddress map[string]string `json:"AuxiliaryAddresses,omitempty"` +} + +// EndpointIPAMConfig represents IPAM configurations for the endpoint +type EndpointIPAMConfig struct { + IPv4Address string `json:",omitempty"` + IPv6Address string `json:",omitempty"` + LinkLocalIPs []string `json:",omitempty"` +} + +// Copy makes a copy of the endpoint ipam config +func (cfg *EndpointIPAMConfig) Copy() *EndpointIPAMConfig { + cfgCopy := *cfg + cfgCopy.LinkLocalIPs = make([]string, 0, len(cfg.LinkLocalIPs)) + cfgCopy.LinkLocalIPs = append(cfgCopy.LinkLocalIPs, cfg.LinkLocalIPs...) + return &cfgCopy +} + +// PeerInfo represents one peer of an overlay network +type PeerInfo struct { + Name string + IP string +} + +// EndpointSettings stores the network endpoint details +type EndpointSettings struct { + // Configurations + IPAMConfig *EndpointIPAMConfig + Links []string + Aliases []string + // Operational data + NetworkID string + EndpointID string + Gateway string + IPAddress string + IPPrefixLen int + IPv6Gateway string + GlobalIPv6Address string + GlobalIPv6PrefixLen int + MacAddress string + DriverOpts map[string]string +} + +// Task carries the information about one backend task +type Task struct { + Name string + EndpointID string + EndpointIP string + Info map[string]string +} + +// ServiceInfo represents service parameters with the list of service's tasks +type ServiceInfo struct { + VIP string + Ports []string + LocalLBIndex int + Tasks []Task +} + +// Copy makes a deep copy of `EndpointSettings` +func (es *EndpointSettings) Copy() *EndpointSettings { + epCopy := *es + if es.IPAMConfig != nil { + epCopy.IPAMConfig = es.IPAMConfig.Copy() + } + + if es.Links != nil { + links := make([]string, 0, len(es.Links)) + epCopy.Links = append(links, es.Links...) + } + + if es.Aliases != nil { + aliases := make([]string, 0, len(es.Aliases)) + epCopy.Aliases = append(aliases, es.Aliases...) + } + return &epCopy +} + +// NetworkingConfig represents the container's networking configuration for each of its interfaces +// Carries the networking configs specified in the `docker run` and `docker network connect` commands +type NetworkingConfig struct { + EndpointsConfig map[string]*EndpointSettings // Endpoint configs for each connecting network +} + +// ConfigReference specifies the source which provides a network's configuration +type ConfigReference struct { + Network string +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/plugin.go b/vendor/github.com/ory/dockertest/v3/docker/types/plugin.go new file mode 100644 index 00000000..e8d5d386 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/plugin.go @@ -0,0 +1,203 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// Plugin A plugin for the Engine API +// swagger:model Plugin +type Plugin struct { + + // config + // Required: true + Config PluginConfig `json:"Config"` + + // True if the plugin is running. False if the plugin is not running, only installed. + // Required: true + Enabled bool `json:"Enabled"` + + // Id + ID string `json:"Id,omitempty"` + + // name + // Required: true + Name string `json:"Name"` + + // plugin remote reference used to push/pull the plugin + PluginReference string `json:"PluginReference,omitempty"` + + // settings + // Required: true + Settings PluginSettings `json:"Settings"` +} + +// PluginConfig The config of a plugin. +// swagger:model PluginConfig +type PluginConfig struct { + + // args + // Required: true + Args PluginConfigArgs `json:"Args"` + + // description + // Required: true + Description string `json:"Description"` + + // Docker Version used to create the plugin + DockerVersion string `json:"DockerVersion,omitempty"` + + // documentation + // Required: true + Documentation string `json:"Documentation"` + + // entrypoint + // Required: true + Entrypoint []string `json:"Entrypoint"` + + // env + // Required: true + Env []PluginEnv `json:"Env"` + + // interface + // Required: true + Interface PluginConfigInterface `json:"Interface"` + + // ipc host + // Required: true + IpcHost bool `json:"IpcHost"` + + // linux + // Required: true + Linux PluginConfigLinux `json:"Linux"` + + // mounts + // Required: true + Mounts []PluginMount `json:"Mounts"` + + // network + // Required: true + Network PluginConfigNetwork `json:"Network"` + + // pid host + // Required: true + PidHost bool `json:"PidHost"` + + // propagated mount + // Required: true + PropagatedMount string `json:"PropagatedMount"` + + // user + User PluginConfigUser `json:"User,omitempty"` + + // work dir + // Required: true + WorkDir string `json:"WorkDir"` + + // rootfs + Rootfs *PluginConfigRootfs `json:"rootfs,omitempty"` +} + +// PluginConfigArgs plugin config args +// swagger:model PluginConfigArgs +type PluginConfigArgs struct { + + // description + // Required: true + Description string `json:"Description"` + + // name + // Required: true + Name string `json:"Name"` + + // settable + // Required: true + Settable []string `json:"Settable"` + + // value + // Required: true + Value []string `json:"Value"` +} + +// PluginConfigInterface The interface between Docker and the plugin +// swagger:model PluginConfigInterface +type PluginConfigInterface struct { + + // socket + // Required: true + Socket string `json:"Socket"` + + // types + // Required: true + Types []PluginInterfaceType `json:"Types"` +} + +// PluginConfigLinux plugin config linux +// swagger:model PluginConfigLinux +type PluginConfigLinux struct { + + // allow all devices + // Required: true + AllowAllDevices bool `json:"AllowAllDevices"` + + // capabilities + // Required: true + Capabilities []string `json:"Capabilities"` + + // devices + // Required: true + Devices []PluginDevice `json:"Devices"` +} + +// PluginConfigNetwork plugin config network +// swagger:model PluginConfigNetwork +type PluginConfigNetwork struct { + + // type + // Required: true + Type string `json:"Type"` +} + +// PluginConfigRootfs plugin config rootfs +// swagger:model PluginConfigRootfs +type PluginConfigRootfs struct { + + // diff ids + DiffIds []string `json:"diff_ids"` + + // type + Type string `json:"type,omitempty"` +} + +// PluginConfigUser plugin config user +// swagger:model PluginConfigUser +type PluginConfigUser struct { + + // g ID + GID uint32 `json:"GID,omitempty"` + + // UID + UID uint32 `json:"UID,omitempty"` +} + +// PluginSettings Settings that can be modified by users. +// swagger:model PluginSettings +type PluginSettings struct { + + // args + // Required: true + Args []string `json:"Args"` + + // devices + // Required: true + Devices []PluginDevice `json:"Devices"` + + // env + // Required: true + Env []string `json:"Env"` + + // mounts + // Required: true + Mounts []PluginMount `json:"Mounts"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/plugin_device.go b/vendor/github.com/ory/dockertest/v3/docker/types/plugin_device.go new file mode 100644 index 00000000..a80af2cc --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/plugin_device.go @@ -0,0 +1,28 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// PluginDevice plugin device +// swagger:model PluginDevice +type PluginDevice struct { + + // description + // Required: true + Description string `json:"Description"` + + // name + // Required: true + Name string `json:"Name"` + + // path + // Required: true + Path *string `json:"Path"` + + // settable + // Required: true + Settable []string `json:"Settable"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/plugin_env.go b/vendor/github.com/ory/dockertest/v3/docker/types/plugin_env.go new file mode 100644 index 00000000..f5b8cc19 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/plugin_env.go @@ -0,0 +1,28 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// PluginEnv plugin env +// swagger:model PluginEnv +type PluginEnv struct { + + // description + // Required: true + Description string `json:"Description"` + + // name + // Required: true + Name string `json:"Name"` + + // settable + // Required: true + Settable []string `json:"Settable"` + + // value + // Required: true + Value *string `json:"Value"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/plugin_interface_type.go b/vendor/github.com/ory/dockertest/v3/docker/types/plugin_interface_type.go new file mode 100644 index 00000000..0b14bf8c --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/plugin_interface_type.go @@ -0,0 +1,24 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// PluginInterfaceType plugin interface type +// swagger:model PluginInterfaceType +type PluginInterfaceType struct { + + // capability + // Required: true + Capability string `json:"Capability"` + + // prefix + // Required: true + Prefix string `json:"Prefix"` + + // version + // Required: true + Version string `json:"Version"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/plugin_mount.go b/vendor/github.com/ory/dockertest/v3/docker/types/plugin_mount.go new file mode 100644 index 00000000..ef9a887a --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/plugin_mount.go @@ -0,0 +1,40 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// PluginMount plugin mount +// swagger:model PluginMount +type PluginMount struct { + + // description + // Required: true + Description string `json:"Description"` + + // destination + // Required: true + Destination string `json:"Destination"` + + // name + // Required: true + Name string `json:"Name"` + + // options + // Required: true + Options []string `json:"Options"` + + // settable + // Required: true + Settable []string `json:"Settable"` + + // source + // Required: true + Source *string `json:"Source"` + + // type + // Required: true + Type string `json:"Type"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/plugin_responses.go b/vendor/github.com/ory/dockertest/v3/docker/types/plugin_responses.go new file mode 100644 index 00000000..64842d4a --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/plugin_responses.go @@ -0,0 +1,74 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types // import "github.com/ory/dockertest/v3/docker/types" + +import ( + "encoding/json" + "fmt" + "sort" +) + +// PluginsListResponse contains the response for the Engine API +type PluginsListResponse []*Plugin + +// UnmarshalJSON implements json.Unmarshaler for PluginInterfaceType +func (t *PluginInterfaceType) UnmarshalJSON(p []byte) error { + versionIndex := len(p) + prefixIndex := 0 + if len(p) < 2 || p[0] != '"' || p[len(p)-1] != '"' { + return fmt.Errorf("%q is not a plugin interface type", p) + } + p = p[1 : len(p)-1] +loop: + for i, b := range p { + switch b { + case '.': + prefixIndex = i + case '/': + versionIndex = i + break loop + } + } + t.Prefix = string(p[:prefixIndex]) + t.Capability = string(p[prefixIndex+1 : versionIndex]) + if versionIndex < len(p) { + t.Version = string(p[versionIndex+1:]) + } + return nil +} + +// MarshalJSON implements json.Marshaler for PluginInterfaceType +func (t *PluginInterfaceType) MarshalJSON() ([]byte, error) { + return json.Marshal(t.String()) +} + +// String implements fmt.Stringer for PluginInterfaceType +func (t PluginInterfaceType) String() string { + return fmt.Sprintf("%s.%s/%s", t.Prefix, t.Capability, t.Version) +} + +// PluginPrivilege describes a permission the user has to accept +// upon installing a plugin. +type PluginPrivilege struct { + Name string + Description string + Value []string +} + +// PluginPrivileges is a list of PluginPrivilege +type PluginPrivileges []PluginPrivilege + +func (s PluginPrivileges) Len() int { + return len(s) +} + +func (s PluginPrivileges) Less(i, j int) bool { + return s[i].Name < s[j].Name +} + +func (s PluginPrivileges) Swap(i, j int) { + sort.Strings(s[i].Value) + sort.Strings(s[j].Value) + s[i], s[j] = s[j], s[i] +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/port.go b/vendor/github.com/ory/dockertest/v3/docker/types/port.go new file mode 100644 index 00000000..0c3bc3b9 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/port.go @@ -0,0 +1,26 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// Port An open port on a container +// swagger:model Port +type Port struct { + + // IP + IP string `json:"IP,omitempty"` + + // Port on the container + // Required: true + PrivatePort uint16 `json:"PrivatePort"` + + // Port exposed on the host + PublicPort uint16 `json:"PublicPort,omitempty"` + + // type + // Required: true + Type string `json:"Type"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/registry/authenticate.go b/vendor/github.com/ory/dockertest/v3/docker/types/registry/authenticate.go new file mode 100644 index 00000000..468ad180 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/registry/authenticate.go @@ -0,0 +1,24 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package registry // import "github.com/ory/dockertest/v3/docker/types/registry" + +// ---------------------------------------------------------------------------- +// DO NOT EDIT THIS FILE +// This file was generated by `swagger generate operation` +// +// See hack/generate-swagger-api.sh +// ---------------------------------------------------------------------------- + +// AuthenticateOKBody authenticate o k body +// swagger:model AuthenticateOKBody +type AuthenticateOKBody struct { + + // An opaque token used to authenticate a user after a successful login + // Required: true + IdentityToken string `json:"IdentityToken"` + + // The status of the authentication + // Required: true + Status string `json:"Status"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/registry/registry.go b/vendor/github.com/ory/dockertest/v3/docker/types/registry/registry.go new file mode 100644 index 00000000..fc8c5aae --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/registry/registry.go @@ -0,0 +1,123 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package registry // import "github.com/ory/dockertest/v3/docker/types/registry" + +import ( + "encoding/json" + "net" + + "github.com/opencontainers/image-spec/specs-go/v1" +) + +// ServiceConfig stores daemon registry services configuration. +type ServiceConfig struct { + AllowNondistributableArtifactsCIDRs []*NetIPNet + AllowNondistributableArtifactsHostnames []string + InsecureRegistryCIDRs []*NetIPNet `json:"InsecureRegistryCIDRs"` + IndexConfigs map[string]*IndexInfo `json:"IndexConfigs"` + Mirrors []string +} + +// NetIPNet is the net.IPNet type, which can be marshalled and +// unmarshalled to JSON +type NetIPNet net.IPNet + +// String returns the CIDR notation of ipnet +func (ipnet *NetIPNet) String() string { + return (*net.IPNet)(ipnet).String() +} + +// MarshalJSON returns the JSON representation of the IPNet +func (ipnet *NetIPNet) MarshalJSON() ([]byte, error) { + return json.Marshal((*net.IPNet)(ipnet).String()) +} + +// UnmarshalJSON sets the IPNet from a byte array of JSON +func (ipnet *NetIPNet) UnmarshalJSON(b []byte) (err error) { + var ipnetStr string + if err = json.Unmarshal(b, &ipnetStr); err == nil { + var cidr *net.IPNet + if _, cidr, err = net.ParseCIDR(ipnetStr); err == nil { + *ipnet = NetIPNet(*cidr) + } + } + return +} + +// IndexInfo contains information about a registry +// +// RepositoryInfo Examples: +// +// { +// "Index" : { +// "Name" : "docker.io", +// "Mirrors" : ["https://registry-2.docker.io/v1/", "https://registry-3.docker.io/v1/"], +// "Secure" : true, +// "Official" : true, +// }, +// "RemoteName" : "library/debian", +// "LocalName" : "debian", +// "CanonicalName" : "docker.io/debian" +// "Official" : true, +// } +// +// { +// "Index" : { +// "Name" : "127.0.0.1:5000", +// "Mirrors" : [], +// "Secure" : false, +// "Official" : false, +// }, +// "RemoteName" : "user/repo", +// "LocalName" : "127.0.0.1:5000/user/repo", +// "CanonicalName" : "127.0.0.1:5000/user/repo", +// "Official" : false, +// } +type IndexInfo struct { + // Name is the name of the registry, such as "docker.io" + Name string + // Mirrors is a list of mirrors, expressed as URIs + Mirrors []string + // Secure is set to false if the registry is part of the list of + // insecure registries. Insecure registries accept HTTP and/or accept + // HTTPS with certificates from unknown CAs. + Secure bool + // Official indicates whether this is an official registry + Official bool +} + +// SearchResult describes a search result returned from a registry +type SearchResult struct { + // StarCount indicates the number of stars this repository has + StarCount int `json:"star_count"` + // IsOfficial is true if the result is from an official repository. + IsOfficial bool `json:"is_official"` + // Name is the name of the repository + Name string `json:"name"` + // IsAutomated indicates whether the result is automated + IsAutomated bool `json:"is_automated"` + // Description is a textual description of the repository + Description string `json:"description"` +} + +// SearchResults lists a collection search results returned from a registry +type SearchResults struct { + // Query contains the query string that generated the search results + Query string `json:"query"` + // NumResults indicates the number of results the query returned + NumResults int `json:"num_results"` + // Results is a slice containing the actual results for the search + Results []SearchResult `json:"results"` +} + +// DistributionInspect describes the result obtained from contacting the +// registry to retrieve image metadata +type DistributionInspect struct { + // Descriptor contains information about the manifest, including + // the content addressable digest + Descriptor v1.Descriptor + // Platforms contains the list of platforms supported by the image, + // obtained by parsing the manifest + Platforms []v1.Platform +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/seccomp.go b/vendor/github.com/ory/dockertest/v3/docker/types/seccomp.go new file mode 100644 index 00000000..cd9b7bb0 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/seccomp.go @@ -0,0 +1,96 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types // import "github.com/ory/dockertest/v3/docker/types" + +// Seccomp represents the config for a seccomp profile for syscall restriction. +type Seccomp struct { + DefaultAction Action `json:"defaultAction"` + // Architectures is kept to maintain backward compatibility with the old + // seccomp profile. + Architectures []Arch `json:"architectures,omitempty"` + ArchMap []Architecture `json:"archMap,omitempty"` + Syscalls []*Syscall `json:"syscalls"` +} + +// Architecture is used to represent a specific architecture +// and its sub-architectures +type Architecture struct { + Arch Arch `json:"architecture"` + SubArches []Arch `json:"subArchitectures"` +} + +// Arch used for architectures +type Arch string + +// Additional architectures permitted to be used for system calls +// By default only the native architecture of the kernel is permitted +const ( + ArchX86 Arch = "SCMP_ARCH_X86" + ArchX86_64 Arch = "SCMP_ARCH_X86_64" + ArchX32 Arch = "SCMP_ARCH_X32" + ArchARM Arch = "SCMP_ARCH_ARM" + ArchAARCH64 Arch = "SCMP_ARCH_AARCH64" + ArchMIPS Arch = "SCMP_ARCH_MIPS" + ArchMIPS64 Arch = "SCMP_ARCH_MIPS64" + ArchMIPS64N32 Arch = "SCMP_ARCH_MIPS64N32" + ArchMIPSEL Arch = "SCMP_ARCH_MIPSEL" + ArchMIPSEL64 Arch = "SCMP_ARCH_MIPSEL64" + ArchMIPSEL64N32 Arch = "SCMP_ARCH_MIPSEL64N32" + ArchPPC Arch = "SCMP_ARCH_PPC" + ArchPPC64 Arch = "SCMP_ARCH_PPC64" + ArchPPC64LE Arch = "SCMP_ARCH_PPC64LE" + ArchS390 Arch = "SCMP_ARCH_S390" + ArchS390X Arch = "SCMP_ARCH_S390X" +) + +// Action taken upon Seccomp rule match +type Action string + +// Define actions for Seccomp rules +const ( + ActKill Action = "SCMP_ACT_KILL" + ActTrap Action = "SCMP_ACT_TRAP" + ActErrno Action = "SCMP_ACT_ERRNO" + ActTrace Action = "SCMP_ACT_TRACE" + ActAllow Action = "SCMP_ACT_ALLOW" +) + +// Operator used to match syscall arguments in Seccomp +type Operator string + +// Define operators for syscall arguments in Seccomp +const ( + OpNotEqual Operator = "SCMP_CMP_NE" + OpLessThan Operator = "SCMP_CMP_LT" + OpLessEqual Operator = "SCMP_CMP_LE" + OpEqualTo Operator = "SCMP_CMP_EQ" + OpGreaterEqual Operator = "SCMP_CMP_GE" + OpGreaterThan Operator = "SCMP_CMP_GT" + OpMaskedEqual Operator = "SCMP_CMP_MASKED_EQ" +) + +// Arg used for matching specific syscall arguments in Seccomp +type Arg struct { + Index uint `json:"index"` + Value uint64 `json:"value"` + ValueTwo uint64 `json:"valueTwo"` + Op Operator `json:"op"` +} + +// Filter is used to conditionally apply Seccomp rules +type Filter struct { + Caps []string `json:"caps,omitempty"` + Arches []string `json:"arches,omitempty"` +} + +// Syscall is used to match a group of syscalls in Seccomp +type Syscall struct { + Name string `json:"name,omitempty"` + Names []string `json:"names,omitempty"` + Action Action `json:"action"` + Args []*Arg `json:"args"` + Comment string `json:"comment"` + Includes Filter `json:"includes"` + Excludes Filter `json:"excludes"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/service_update_response.go b/vendor/github.com/ory/dockertest/v3/docker/types/service_update_response.go new file mode 100644 index 00000000..7489e738 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/service_update_response.go @@ -0,0 +1,15 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// ServiceUpdateResponse service update response +// swagger:model ServiceUpdateResponse +type ServiceUpdateResponse struct { + + // Optional warning messages + Warnings []string `json:"Warnings"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/stats.go b/vendor/github.com/ory/dockertest/v3/docker/types/stats.go new file mode 100644 index 00000000..0c9832b5 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/stats.go @@ -0,0 +1,184 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Package types is used for API stability in the types and response to the +// consumers of the API stats endpoint. +package types // import "github.com/ory/dockertest/v3/docker/types" + +import "time" + +// ThrottlingData stores CPU throttling stats of one running container. +// Not used on Windows. +type ThrottlingData struct { + // Number of periods with throttling active + Periods uint64 `json:"periods"` + // Number of periods when the container hits its throttling limit. + ThrottledPeriods uint64 `json:"throttled_periods"` + // Aggregate time the container was throttled for in nanoseconds. + ThrottledTime uint64 `json:"throttled_time"` +} + +// CPUUsage stores All CPU stats aggregated since container inception. +type CPUUsage struct { + // Total CPU time consumed. + // Units: nanoseconds (Linux) + // Units: 100's of nanoseconds (Windows) + TotalUsage uint64 `json:"total_usage"` + + // Total CPU time consumed per core (Linux). Not used on Windows. + // Units: nanoseconds. + PercpuUsage []uint64 `json:"percpu_usage,omitempty"` + + // Time spent by tasks of the cgroup in kernel mode (Linux). + // Time spent by all container processes in kernel mode (Windows). + // Units: nanoseconds (Linux). + // Units: 100's of nanoseconds (Windows). Not populated for Hyper-V Containers. + UsageInKernelmode uint64 `json:"usage_in_kernelmode"` + + // Time spent by tasks of the cgroup in user mode (Linux). + // Time spent by all container processes in user mode (Windows). + // Units: nanoseconds (Linux). + // Units: 100's of nanoseconds (Windows). Not populated for Hyper-V Containers + UsageInUsermode uint64 `json:"usage_in_usermode"` +} + +// CPUStats aggregates and wraps all CPU related info of container +type CPUStats struct { + // CPU Usage. Linux and Windows. + CPUUsage CPUUsage `json:"cpu_usage"` + + // System Usage. Linux only. + SystemUsage uint64 `json:"system_cpu_usage,omitempty"` + + // Online CPUs. Linux only. + OnlineCPUs uint32 `json:"online_cpus,omitempty"` + + // Throttling Data. Linux only. + ThrottlingData ThrottlingData `json:"throttling_data,omitempty"` +} + +// MemoryStats aggregates all memory stats since container inception on Linux. +// Windows returns stats for commit and private working set only. +type MemoryStats struct { + // Linux Memory Stats + + // current res_counter usage for memory + Usage uint64 `json:"usage,omitempty"` + // maximum usage ever recorded. + MaxUsage uint64 `json:"max_usage,omitempty"` + // TODO(vishh): Export these as stronger types. + // all the stats exported via memory.stat. + Stats map[string]uint64 `json:"stats,omitempty"` + // number of times memory usage hits limits. + Failcnt uint64 `json:"failcnt,omitempty"` + Limit uint64 `json:"limit,omitempty"` + + // Windows Memory Stats + // See https://technet.microsoft.com/en-us/magazine/ff382715.aspx + + // committed bytes + Commit uint64 `json:"commitbytes,omitempty"` + // peak committed bytes + CommitPeak uint64 `json:"commitpeakbytes,omitempty"` + // private working set + PrivateWorkingSet uint64 `json:"privateworkingset,omitempty"` +} + +// BlkioStatEntry is one small entity to store a piece of Blkio stats +// Not used on Windows. +type BlkioStatEntry struct { + Major uint64 `json:"major"` + Minor uint64 `json:"minor"` + Op string `json:"op"` + Value uint64 `json:"value"` +} + +// BlkioStats stores All IO service stats for data read and write. +// This is a Linux specific structure as the differences between expressing +// block I/O on Windows and Linux are sufficiently significant to make +// little sense attempting to morph into a combined structure. +type BlkioStats struct { + // number of bytes transferred to and from the block device + IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"` + IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive"` + IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive"` + IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive"` + IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive"` + IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive"` + IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive"` + SectorsRecursive []BlkioStatEntry `json:"sectors_recursive"` +} + +// StorageStats is the disk I/O stats for read/write on Windows. +type StorageStats struct { + ReadCountNormalized uint64 `json:"read_count_normalized,omitempty"` + ReadSizeBytes uint64 `json:"read_size_bytes,omitempty"` + WriteCountNormalized uint64 `json:"write_count_normalized,omitempty"` + WriteSizeBytes uint64 `json:"write_size_bytes,omitempty"` +} + +// NetworkStats aggregates the network stats of one container +type NetworkStats struct { + // Bytes received. Windows and Linux. + RxBytes uint64 `json:"rx_bytes"` + // Packets received. Windows and Linux. + RxPackets uint64 `json:"rx_packets"` + // Received errors. Not used on Windows. Note that we dont `omitempty` this + // field as it is expected in the >=v1.21 API stats structure. + RxErrors uint64 `json:"rx_errors"` + // Incoming packets dropped. Windows and Linux. + RxDropped uint64 `json:"rx_dropped"` + // Bytes sent. Windows and Linux. + TxBytes uint64 `json:"tx_bytes"` + // Packets sent. Windows and Linux. + TxPackets uint64 `json:"tx_packets"` + // Sent errors. Not used on Windows. Note that we dont `omitempty` this + // field as it is expected in the >=v1.21 API stats structure. + TxErrors uint64 `json:"tx_errors"` + // Outgoing packets dropped. Windows and Linux. + TxDropped uint64 `json:"tx_dropped"` + // Endpoint ID. Not used on Linux. + EndpointID string `json:"endpoint_id,omitempty"` + // Instance ID. Not used on Linux. + InstanceID string `json:"instance_id,omitempty"` +} + +// PidsStats contains the stats of a container's pids +type PidsStats struct { + // Current is the number of pids in the cgroup + Current uint64 `json:"current,omitempty"` + // Limit is the hard limit on the number of pids in the cgroup. + // A "Limit" of 0 means that there is no limit. + Limit uint64 `json:"limit,omitempty"` +} + +// Stats is Ultimate struct aggregating all types of stats of one container +type Stats struct { + // Common stats + Read time.Time `json:"read"` + PreRead time.Time `json:"preread"` + + // Linux specific stats, not populated on Windows. + PidsStats PidsStats `json:"pids_stats,omitempty"` + BlkioStats BlkioStats `json:"blkio_stats,omitempty"` + + // Windows specific stats, not populated on Linux. + NumProcs uint32 `json:"num_procs"` + StorageStats StorageStats `json:"storage_stats,omitempty"` + + // Shared stats + CPUStats CPUStats `json:"cpu_stats,omitempty"` + PreCPUStats CPUStats `json:"precpu_stats,omitempty"` // "Pre"="Previous" + MemoryStats MemoryStats `json:"memory_stats,omitempty"` +} + +// StatsJSON is newly used Networks +type StatsJSON struct { + Stats + + Name string `json:"name,omitempty"` + ID string `json:"id,omitempty"` + + // Networks request version >=1.21 + Networks map[string]NetworkStats `json:"networks,omitempty"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/strslice/strslice.go b/vendor/github.com/ory/dockertest/v3/docker/types/strslice/strslice.go new file mode 100644 index 00000000..d9d14723 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/strslice/strslice.go @@ -0,0 +1,33 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package strslice // import "github.com/ory/dockertest/v3/docker/types/strslice" + +import "encoding/json" + +// StrSlice represents a string or an array of strings. +// We need to override the json decoder to accept both options. +type StrSlice []string + +// UnmarshalJSON decodes the byte slice whether it's a string or an array of +// strings. This method is needed to implement json.Unmarshaler. +func (e *StrSlice) UnmarshalJSON(b []byte) error { + if len(b) == 0 { + // With no input, we preserve the existing value by returning nil and + // leaving the target alone. This allows defining default values for + // the type. + return nil + } + + p := make([]string, 0, 1) + if err := json.Unmarshal(b, &p); err != nil { + var s string + if err := json.Unmarshal(b, &s); err != nil { + return err + } + p = append(p, s) + } + + *e = p + return nil +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/types.go b/vendor/github.com/ory/dockertest/v3/docker/types/types.go new file mode 100644 index 00000000..e4ba633a --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/types.go @@ -0,0 +1,589 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types // import "github.com/ory/dockertest/v3/docker/types" + +import ( + "errors" + "fmt" + "io" + "os" + "strings" + "time" + + "github.com/docker/go-connections/nat" + "github.com/ory/dockertest/v3/docker/types/container" + "github.com/ory/dockertest/v3/docker/types/filters" + "github.com/ory/dockertest/v3/docker/types/mount" + "github.com/ory/dockertest/v3/docker/types/network" + "github.com/ory/dockertest/v3/docker/types/registry" +) + +// RootFS returns Image's RootFS description including the layer IDs. +type RootFS struct { + Type string + Layers []string `json:",omitempty"` + BaseLayer string `json:",omitempty"` +} + +// ImageInspect contains response of Engine API: +// GET "/images/{name:.*}/json" +type ImageInspect struct { + ID string `json:"Id"` + RepoTags []string + RepoDigests []string + Parent string + Comment string + Created string + Container string + ContainerConfig *container.Config + DockerVersion string + Author string + Config *container.Config + Architecture string + Os string + OsVersion string `json:",omitempty"` + Size int64 + VirtualSize int64 + GraphDriver GraphDriverData + RootFS RootFS + Metadata ImageMetadata +} + +// ImageMetadata contains engine-local data about the image +type ImageMetadata struct { + LastTagTime time.Time `json:",omitempty"` +} + +// Container contains response of Engine API: +// GET "/containers/json" +type Container struct { + ID string `json:"Id"` + Names []string + Image string + ImageID string + Command string + Created int64 + Ports []Port + SizeRw int64 `json:",omitempty"` + SizeRootFs int64 `json:",omitempty"` + Labels map[string]string + State string + Status string + HostConfig struct { + NetworkMode string `json:",omitempty"` + } + NetworkSettings *SummaryNetworkSettings + Mounts []MountPoint +} + +// CopyConfig contains request body of Engine API: +// POST "/containers/"+containerID+"/copy" +type CopyConfig struct { + Resource string +} + +// ContainerPathStat is used to encode the header from +// GET "/containers/{name:.*}/archive" +// "Name" is the file or directory name. +type ContainerPathStat struct { + Name string `json:"name"` + Size int64 `json:"size"` + Mode os.FileMode `json:"mode"` + Mtime time.Time `json:"mtime"` + LinkTarget string `json:"linkTarget"` +} + +// ContainerStats contains response of Engine API: +// GET "/stats" +type ContainerStats struct { + Body io.ReadCloser `json:"body"` + OSType string `json:"ostype"` +} + +// Ping contains response of Engine API: +// GET "/_ping" +type Ping struct { + APIVersion string + OSType string + Experimental bool +} + +// ComponentVersion describes the version information for a specific component. +type ComponentVersion struct { + Name string + Version string + Details map[string]string `json:",omitempty"` +} + +// Version contains response of Engine API: +// GET "/version" +type Version struct { + Platform struct{ Name string } `json:",omitempty"` + Components []ComponentVersion `json:",omitempty"` + + // The following fields are deprecated, they relate to the Engine component and are kept for backwards compatibility + + Version string + APIVersion string `json:"ApiVersion"` + MinAPIVersion string `json:"MinAPIVersion,omitempty"` + GitCommit string + GoVersion string + Os string + Arch string + KernelVersion string `json:",omitempty"` + Experimental bool `json:",omitempty"` + BuildTime string `json:",omitempty"` +} + +// Commit holds the Git-commit (SHA1) that a binary was built from, as reported +// in the version-string of external tools, such as containerd, or runC. +type Commit struct { + ID string // ID is the actual commit ID of external tool. + Expected string // Expected is the commit ID of external tool expected by dockerd as set at build time. +} + +// Info contains response of Engine API: +// GET "/info" +type Info struct { + ID string + Containers int + ContainersRunning int + ContainersPaused int + ContainersStopped int + Images int + Driver string + DriverStatus [][2]string + SystemStatus [][2]string + Plugins PluginsInfo + MemoryLimit bool + SwapLimit bool + KernelMemory bool + CPUCfsPeriod bool `json:"CpuCfsPeriod"` + CPUCfsQuota bool `json:"CpuCfsQuota"` + CPUShares bool + CPUSet bool + IPv4Forwarding bool + BridgeNfIptables bool + BridgeNfIP6tables bool `json:"BridgeNfIp6tables"` + Debug bool + NFd int + OomKillDisable bool + NGoroutines int + SystemTime string + LoggingDriver string + CgroupDriver string + NEventsListener int + KernelVersion string + OperatingSystem string + OSType string + Architecture string + IndexServerAddress string + RegistryConfig *registry.ServiceConfig + NCPU int + MemTotal int64 + //GenericResources []swarm.GenericResource + DockerRootDir string + HTTPProxy string `json:"HttpProxy"` + HTTPSProxy string `json:"HttpsProxy"` + NoProxy string + Name string + Labels []string + ExperimentalBuild bool + ServerVersion string + ClusterStore string + ClusterAdvertise string + Runtimes map[string]Runtime + DefaultRuntime string + //Swarm swarm.Info + // LiveRestoreEnabled determines whether containers should be kept + // running when the daemon is shutdown or upon daemon start if + // running containers are detected + LiveRestoreEnabled bool + Isolation container.Isolation + InitBinary string + ContainerdCommit Commit + RuncCommit Commit + InitCommit Commit + SecurityOptions []string +} + +// KeyValue holds a key/value pair +type KeyValue struct { + Key, Value string +} + +// SecurityOpt contains the name and options of a security option +type SecurityOpt struct { + Name string + Options []KeyValue +} + +// DecodeSecurityOptions decodes a security options string slice to a type safe +// SecurityOpt +func DecodeSecurityOptions(opts []string) ([]SecurityOpt, error) { + so := []SecurityOpt{} + for _, opt := range opts { + // support output from a < 1.13 docker daemon + if !strings.Contains(opt, "=") { + so = append(so, SecurityOpt{Name: opt}) + continue + } + secopt := SecurityOpt{} + split := strings.Split(opt, ",") + for _, s := range split { + kv := strings.SplitN(s, "=", 2) + if len(kv) != 2 { + return nil, fmt.Errorf("invalid security option %q", s) + } + if kv[0] == "" || kv[1] == "" { + return nil, errors.New("invalid empty security option") + } + if kv[0] == "name" { + secopt.Name = kv[1] + continue + } + secopt.Options = append(secopt.Options, KeyValue{Key: kv[0], Value: kv[1]}) + } + so = append(so, secopt) + } + return so, nil +} + +// PluginsInfo is a temp struct holding Plugins name +// registered with docker daemon. It is used by Info struct +type PluginsInfo struct { + // List of Volume plugins registered + Volume []string + // List of Network plugins registered + Network []string + // List of Authorization plugins registered + Authorization []string + // List of Log plugins registered + Log []string +} + +// ExecStartCheck is a temp struct used by execStart +// Config fields is part of ExecConfig in runconfig package +type ExecStartCheck struct { + // ExecStart will first check if it's detached + Detach bool + // Check if there's a tty + Tty bool +} + +// HealthcheckResult stores information about a single run of a healthcheck probe +type HealthcheckResult struct { + Start time.Time // Start is the time this check started + End time.Time // End is the time this check ended + ExitCode int // ExitCode meanings: 0=healthy, 1=unhealthy, 2=reserved (considered unhealthy), else=error running probe + Output string // Output from last check +} + +// Health states +const ( + NoHealthcheck = "none" // Indicates there is no healthcheck + Starting = "starting" // Starting indicates that the container is not yet ready + Healthy = "healthy" // Healthy indicates that the container is running correctly + Unhealthy = "unhealthy" // Unhealthy indicates that the container has a problem +) + +// Health stores information about the container's healthcheck results +type Health struct { + Status string // Status is one of Starting, Healthy or Unhealthy + FailingStreak int // FailingStreak is the number of consecutive failures + Log []*HealthcheckResult // Log contains the last few results (oldest first) +} + +// ContainerState stores container's running state +// it's part of ContainerJSONBase and will return by "inspect" command +type ContainerState struct { + Status string // String representation of the container state. Can be one of "created", "running", "paused", "restarting", "removing", "exited", or "dead" + Running bool + Paused bool + Restarting bool + OOMKilled bool + Dead bool + Pid int + ExitCode int + Error string + StartedAt string + FinishedAt string + Health *Health `json:",omitempty"` +} + +// ContainerNode stores information about the node that a container +// is running on. It's only available in Docker Swarm +type ContainerNode struct { + ID string + IPAddress string `json:"IP"` + Addr string + Name string + Cpus int + Memory int64 + Labels map[string]string +} + +// ContainerJSONBase contains response of Engine API: +// GET "/containers/{name:.*}/json" +type ContainerJSONBase struct { + ID string `json:"Id"` + Created string + Path string + Args []string + State *ContainerState + Image string + ResolvConfPath string + HostnamePath string + HostsPath string + LogPath string + Node *ContainerNode `json:",omitempty"` + Name string + RestartCount int + Driver string + Platform string + MountLabel string + ProcessLabel string + AppArmorProfile string + ExecIDs []string + HostConfig *container.HostConfig + GraphDriver GraphDriverData + SizeRw *int64 `json:",omitempty"` + SizeRootFs *int64 `json:",omitempty"` +} + +// ContainerJSON is newly used struct along with MountPoint +type ContainerJSON struct { + *ContainerJSONBase + Mounts []MountPoint + Config *container.Config + NetworkSettings *NetworkSettings +} + +// NetworkSettings exposes the network settings in the api +type NetworkSettings struct { + NetworkSettingsBase + DefaultNetworkSettings + Networks map[string]*network.EndpointSettings +} + +// SummaryNetworkSettings provides a summary of container's networks +// in /containers/json +type SummaryNetworkSettings struct { + Networks map[string]*network.EndpointSettings +} + +// NetworkSettingsBase holds basic information about networks +type NetworkSettingsBase struct { + Bridge string // Bridge is the Bridge name the network uses(e.g. `docker0`) + SandboxID string // SandboxID uniquely represents a container's network stack + HairpinMode bool // HairpinMode specifies if hairpin NAT should be enabled on the virtual interface + LinkLocalIPv6Address string // LinkLocalIPv6Address is an IPv6 unicast address using the link-local prefix + LinkLocalIPv6PrefixLen int // LinkLocalIPv6PrefixLen is the prefix length of an IPv6 unicast address + Ports nat.PortMap // Ports is a collection of PortBinding indexed by Port + SandboxKey string // SandboxKey identifies the sandbox + SecondaryIPAddresses []network.Address + SecondaryIPv6Addresses []network.Address +} + +// DefaultNetworkSettings holds network information +// during the 2 release deprecation period. +// It will be removed in Docker 1.11. +type DefaultNetworkSettings struct { + EndpointID string // EndpointID uniquely represents a service endpoint in a Sandbox + Gateway string // Gateway holds the gateway address for the network + GlobalIPv6Address string // GlobalIPv6Address holds network's global IPv6 address + GlobalIPv6PrefixLen int // GlobalIPv6PrefixLen represents mask length of network's global IPv6 address + IPAddress string // IPAddress holds the IPv4 address for the network + IPPrefixLen int // IPPrefixLen represents mask length of network's IPv4 address + IPv6Gateway string // IPv6Gateway holds gateway address specific for IPv6 + MacAddress string // MacAddress holds the MAC address for the network +} + +// MountPoint represents a mount point configuration inside the container. +// This is used for reporting the mountpoints in use by a container. +type MountPoint struct { + Type mount.Type `json:",omitempty"` + Name string `json:",omitempty"` + Source string + Destination string + Driver string `json:",omitempty"` + Mode string + RW bool + Propagation mount.Propagation +} + +// NetworkResource is the body of the "get network" http response message +type NetworkResource struct { + Name string // Name is the requested name of the network + ID string `json:"Id"` // ID uniquely identifies a network on a single machine + Created time.Time // Created is the time the network created + Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level) + Driver string // Driver is the Driver name used to create the network (e.g. `bridge`, `overlay`) + EnableIPv6 bool // EnableIPv6 represents whether to enable IPv6 + IPAM network.IPAM // IPAM is the network's IP Address Management + Internal bool // Internal represents if the network is used internal only + Attachable bool // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode. + Ingress bool // Ingress indicates the network is providing the routing-mesh for the swarm cluster. + ConfigFrom network.ConfigReference // ConfigFrom specifies the source which will provide the configuration for this network. + ConfigOnly bool // ConfigOnly networks are place-holder networks for network configurations to be used by other networks. ConfigOnly networks cannot be used directly to run containers or services. + Containers map[string]EndpointResource // Containers contains endpoints belonging to the network + Options map[string]string // Options holds the network specific options to use for when creating the network + Labels map[string]string // Labels holds metadata specific to the network being created + Peers []network.PeerInfo `json:",omitempty"` // List of peer nodes for an overlay network + Services map[string]network.ServiceInfo `json:",omitempty"` +} + +// EndpointResource contains network resources allocated and used for a container in a network +type EndpointResource struct { + Name string + EndpointID string + MacAddress string + IPv4Address string + IPv6Address string +} + +// NetworkCreate is the expected body of the "create network" http request message +type NetworkCreate struct { + // Check for networks with duplicate names. + // Network is primarily keyed based on a random ID and not on the name. + // Network name is strictly a user-friendly alias to the network + // which is uniquely identified using ID. + // And there is no guaranteed way to check for duplicates. + // Option CheckDuplicate is there to provide a best effort checking of any networks + // which has the same name but it is not guaranteed to catch all name collisions. + CheckDuplicate bool + Driver string + Scope string + EnableIPv6 bool + IPAM *network.IPAM + Internal bool + Attachable bool + Ingress bool + ConfigOnly bool + ConfigFrom *network.ConfigReference + Options map[string]string + Labels map[string]string +} + +// NetworkCreateRequest is the request message sent to the server for network create call. +type NetworkCreateRequest struct { + NetworkCreate + Name string +} + +// NetworkCreateResponse is the response message sent by the server for network create call +type NetworkCreateResponse struct { + ID string `json:"Id"` + Warning string +} + +// NetworkConnect represents the data to be used to connect a container to the network +type NetworkConnect struct { + Container string + EndpointConfig *network.EndpointSettings `json:",omitempty"` +} + +// NetworkDisconnect represents the data to be used to disconnect a container from the network +type NetworkDisconnect struct { + Container string + Force bool +} + +// NetworkInspectOptions holds parameters to inspect network +type NetworkInspectOptions struct { + Scope string + Verbose bool +} + +// Checkpoint represents the details of a checkpoint +type Checkpoint struct { + Name string // Name is the name of the checkpoint +} + +// Runtime describes an OCI runtime +type Runtime struct { + Path string `json:"path"` + Args []string `json:"runtimeArgs,omitempty"` +} + +// DiskUsage contains response of Engine API: +// GET "/system/df" +type DiskUsage struct { + LayersSize int64 + Images []*ImageSummary + Containers []*Container + Volumes []*Volume + BuilderSize int64 +} + +// ContainersPruneReport contains the response for Engine API: +// POST "/containers/prune" +type ContainersPruneReport struct { + ContainersDeleted []string + SpaceReclaimed uint64 +} + +// VolumesPruneReport contains the response for Engine API: +// POST "/volumes/prune" +type VolumesPruneReport struct { + VolumesDeleted []string + SpaceReclaimed uint64 +} + +// ImagesPruneReport contains the response for Engine API: +// POST "/images/prune" +type ImagesPruneReport struct { + ImagesDeleted []ImageDeleteResponseItem + SpaceReclaimed uint64 +} + +// BuildCachePruneReport contains the response for Engine API: +// POST "/build/prune" +type BuildCachePruneReport struct { + SpaceReclaimed uint64 +} + +// NetworksPruneReport contains the response for Engine API: +// POST "/networks/prune" +type NetworksPruneReport struct { + NetworksDeleted []string +} + +// SecretCreateResponse contains the information returned to a client +// on the creation of a new secret. +type SecretCreateResponse struct { + // ID is the id of the created secret. + ID string +} + +// SecretListOptions holds parameters to list secrets +type SecretListOptions struct { + Filters filters.Args +} + +// ConfigCreateResponse contains the information returned to a client +// on the creation of a new config. +type ConfigCreateResponse struct { + // ID is the id of the created config. + ID string +} + +// ConfigListOptions holds parameters to list configs +type ConfigListOptions struct { + Filters filters.Args +} + +// PushResult contains the tag, manifest digest, and manifest size from the +// push. It's used to signal this information to the trust code in the client +// so it can sign the manifest if necessary. +type PushResult struct { + Tag string + Digest string + Size int +} + +// BuildResult contains the image id of a successful build +type BuildResult struct { + ID string +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/versions/README.md b/vendor/github.com/ory/dockertest/v3/docker/types/versions/README.md new file mode 100644 index 00000000..d3b223c3 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/versions/README.md @@ -0,0 +1,25 @@ +# Legacy API type versions + +This package includes types for legacy API versions. The stable version of the +API types live in `api/types/*.go`. + +Consider moving a type here when you need to keep backwards compatibility in the +API. This legacy types are organized by the latest API version they appear in. +For instance, types in the `v1p19` package are valid for API versions below or +equal `1.19`. Types in the `v1p20` package are valid for the API version `1.20`, +since the versions below that will use the legacy types in `v1p19`. + +## Package name conventions + +The package name convention is to use `v` as a prefix for the version number and +`p`(patch) as a separator. We use this nomenclature due to a few restrictions in +the Go package name convention: + +1. We cannot use `.` because it's interpreted by the language, think of + `v1.20.CallFunction`. +2. We cannot use `_` because golint complains about it. The code is actually + valid, but it looks probably more weird: `v1_20.CallFunction`. + +For instance, if you want to modify a type that was available in the version +`1.21` of the API but it will have different fields in the version `1.22`, you +want to create a new package under `api/types/versions/v1p21`. diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/versions/compare.go b/vendor/github.com/ory/dockertest/v3/docker/types/versions/compare.go new file mode 100644 index 00000000..5d1ab05c --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/versions/compare.go @@ -0,0 +1,65 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package versions // import "github.com/ory/dockertest/v3/docker/types/versions" + +import ( + "strconv" + "strings" +) + +// compare compares two version strings +// returns -1 if v1 < v2, 1 if v1 > v2, 0 otherwise. +func compare(v1, v2 string) int { + var ( + currTab = strings.Split(v1, ".") + otherTab = strings.Split(v2, ".") + ) + + max := len(currTab) + if len(otherTab) > max { + max = len(otherTab) + } + for i := 0; i < max; i++ { + var currInt, otherInt int + + if len(currTab) > i { + currInt, _ = strconv.Atoi(currTab[i]) + } + if len(otherTab) > i { + otherInt, _ = strconv.Atoi(otherTab[i]) + } + if currInt > otherInt { + return 1 + } + if otherInt > currInt { + return -1 + } + } + return 0 +} + +// LessThan checks if a version is less than another +func LessThan(v, other string) bool { + return compare(v, other) == -1 +} + +// LessThanOrEqualTo checks if a version is less than or equal to another +func LessThanOrEqualTo(v, other string) bool { + return compare(v, other) <= 0 +} + +// GreaterThan checks if a version is greater than another +func GreaterThan(v, other string) bool { + return compare(v, other) == 1 +} + +// GreaterThanOrEqualTo checks if a version is greater than or equal to another +func GreaterThanOrEqualTo(v, other string) bool { + return compare(v, other) >= 0 +} + +// Equal checks if a version is equal to another +func Equal(v, other string) bool { + return compare(v, other) == 0 +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/types/volume.go b/vendor/github.com/ory/dockertest/v3/docker/types/volume.go new file mode 100644 index 00000000..d2199511 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/types/volume.go @@ -0,0 +1,72 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package types + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// Volume volume +// swagger:model Volume +type Volume struct { + + // Date/Time the volume was created. + CreatedAt string `json:"CreatedAt,omitempty"` + + // Name of the volume driver used by the volume. + // Required: true + Driver string `json:"Driver"` + + // User-defined key/value metadata. + // Required: true + Labels map[string]string `json:"Labels"` + + // Mount path of the volume on the host. + // Required: true + Mountpoint string `json:"Mountpoint"` + + // Name of the volume. + // Required: true + Name string `json:"Name"` + + // The driver specific options used when creating the volume. + // Required: true + Options map[string]string `json:"Options"` + + // The level at which the volume exists. Either `global` for cluster-wide, or `local` for machine level. + // Required: true + Scope string `json:"Scope"` + + // Low-level details about the volume, provided by the volume driver. + // Details are returned as a map with key/value pairs: + // `{"key":"value","key2":"value2"}`. + // + // The `Status` field is optional, and is omitted if the volume driver + // does not support this feature. + // + Status map[string]interface{} `json:"Status,omitempty"` + + // usage data + UsageData *VolumeUsageData `json:"UsageData,omitempty"` +} + +// VolumeUsageData Usage details about the volume. This information is used by the +// `GET /system/df` endpoint, and omitted in other endpoints. +// +// swagger:model VolumeUsageData +type VolumeUsageData struct { + + // The number of containers referencing this volume. This field + // is set to `-1` if the reference-count is not available. + // + // Required: true + RefCount int64 `json:"RefCount"` + + // Amount of disk space used by the volume (in bytes). This information + // is only available for volumes created with the `"local"` volume + // driver. For volumes created with other volume drivers, this field + // is set to `-1` ("not available") + // + // Required: true + Size int64 `json:"Size"` +} diff --git a/vendor/github.com/ory/dockertest/v3/docker/volume.go b/vendor/github.com/ory/dockertest/v3/docker/volume.go new file mode 100644 index 00000000..f5fae9f8 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/docker/volume.go @@ -0,0 +1,193 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +// Copyright 2015 go-dockerclient 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 docker + +import ( + "context" + "encoding/json" + "errors" + "net/http" +) + +var ( + // ErrNoSuchVolume is the error returned when the volume does not exist. + ErrNoSuchVolume = errors.New("no such volume") + + // ErrVolumeInUse is the error returned when the volume requested to be removed is still in use. + ErrVolumeInUse = errors.New("volume in use and cannot be removed") +) + +// Volume represents a volume. +// +// See https://goo.gl/3wgTsd for more details. +type Volume struct { + Name string `json:"Name" yaml:"Name" toml:"Name"` + Driver string `json:"Driver,omitempty" yaml:"Driver,omitempty" toml:"Driver,omitempty"` + Mountpoint string `json:"Mountpoint,omitempty" yaml:"Mountpoint,omitempty" toml:"Mountpoint,omitempty"` + Labels map[string]string `json:"Labels,omitempty" yaml:"Labels,omitempty" toml:"Labels,omitempty"` + Options map[string]string `json:"Options,omitempty" yaml:"Options,omitempty" toml:"Options,omitempty"` +} + +// ListVolumesOptions specify parameters to the ListVolumes function. +// +// See https://goo.gl/3wgTsd for more details. +type ListVolumesOptions struct { + Filters map[string][]string + Context context.Context +} + +// ListVolumes returns a list of available volumes in the server. +// +// See https://goo.gl/3wgTsd for more details. +func (c *Client) ListVolumes(opts ListVolumesOptions) ([]Volume, error) { + resp, err := c.do("GET", "/volumes?"+queryString(opts), doOptions{ + context: opts.Context, + }) + if err != nil { + return nil, err + } + defer resp.Body.Close() + m := make(map[string]interface{}) + if err = json.NewDecoder(resp.Body).Decode(&m); err != nil { + return nil, err + } + var volumes []Volume + volumesJSON, ok := m["Volumes"] + if !ok { + return volumes, nil + } + data, err := json.Marshal(volumesJSON) + if err != nil { + return nil, err + } + if err := json.Unmarshal(data, &volumes); err != nil { + return nil, err + } + return volumes, nil +} + +// CreateVolumeOptions specify parameters to the CreateVolume function. +// +// See https://goo.gl/qEhmEC for more details. +type CreateVolumeOptions struct { + Name string + Driver string + DriverOpts map[string]string + Context context.Context `json:"-"` + Labels map[string]string +} + +// CreateVolume creates a volume on the server. +// +// See https://goo.gl/qEhmEC for more details. +func (c *Client) CreateVolume(opts CreateVolumeOptions) (*Volume, error) { + resp, err := c.do("POST", "/volumes/create", doOptions{ + data: opts, + context: opts.Context, + }) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var volume Volume + if err := json.NewDecoder(resp.Body).Decode(&volume); err != nil { + return nil, err + } + return &volume, nil +} + +// InspectVolume returns a volume by its name. +// +// See https://goo.gl/GMjsMc for more details. +func (c *Client) InspectVolume(name string) (*Volume, error) { + resp, err := c.do("GET", "/volumes/"+name, doOptions{}) + if err != nil { + if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { + return nil, ErrNoSuchVolume + } + return nil, err + } + defer resp.Body.Close() + var volume Volume + if err := json.NewDecoder(resp.Body).Decode(&volume); err != nil { + return nil, err + } + return &volume, nil +} + +// RemoveVolume removes a volume by its name. +// +// Deprecated: Use RemoveVolumeWithOptions instead. +func (c *Client) RemoveVolume(name string) error { + return c.RemoveVolumeWithOptions(RemoveVolumeOptions{Name: name}) +} + +// RemoveVolumeOptions specify parameters to the RemoveVolumeWithOptions +// function. +// +// See https://goo.gl/nvd6qj for more details. +type RemoveVolumeOptions struct { + Context context.Context + Name string `qs:"-"` + Force bool +} + +// RemoveVolumeWithOptions removes a volume by its name and takes extra +// parameters. +// +// See https://goo.gl/nvd6qj for more details. +func (c *Client) RemoveVolumeWithOptions(opts RemoveVolumeOptions) error { + path := "/volumes/" + opts.Name + resp, err := c.do("DELETE", path+"?"+queryString(opts), doOptions{context: opts.Context}) + if err != nil { + if e, ok := err.(*Error); ok { + if e.Status == http.StatusNotFound { + return ErrNoSuchVolume + } + if e.Status == http.StatusConflict { + return ErrVolumeInUse + } + } + return err + } + defer resp.Body.Close() + return nil +} + +// PruneVolumesOptions specify parameters to the PruneVolumes function. +// +// See https://goo.gl/f9XDem for more details. +type PruneVolumesOptions struct { + Filters map[string][]string + Context context.Context +} + +// PruneVolumesResults specify results from the PruneVolumes function. +// +// See https://goo.gl/f9XDem for more details. +type PruneVolumesResults struct { + VolumesDeleted []string + SpaceReclaimed int64 +} + +// PruneVolumes deletes volumes which are unused. +// +// See https://goo.gl/f9XDem for more details. +func (c *Client) PruneVolumes(opts PruneVolumesOptions) (*PruneVolumesResults, error) { + path := "/volumes/prune?" + queryString(opts) + resp, err := c.do("POST", path, doOptions{context: opts.Context}) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var results PruneVolumesResults + if err := json.NewDecoder(resp.Body).Decode(&results); err != nil { + return nil, err + } + return &results, nil +} diff --git a/vendor/github.com/ory/dockertest/v3/dockertest.go b/vendor/github.com/ory/dockertest/v3/dockertest.go new file mode 100644 index 00000000..52bb08fb --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/dockertest.go @@ -0,0 +1,707 @@ +// Copyright © 2024 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package dockertest + +import ( + "errors" + "fmt" + "io" + "net" + "os" + "path/filepath" + "runtime" + "strings" + "time" + + "github.com/cenkalti/backoff/v4" + dc "github.com/ory/dockertest/v3/docker" + options "github.com/ory/dockertest/v3/docker/opts" +) + +var ( + ErrNotInContainer = errors.New("not running in container") +) + +// Pool represents a connection to the docker API and is used to create and remove docker images. +type Pool struct { + Client *dc.Client + MaxWait time.Duration +} + +// Network represents a docker network. +type Network struct { + pool *Pool + Network *dc.Network +} + +// Close removes network by calling pool.RemoveNetwork. +func (n *Network) Close() error { + return n.pool.RemoveNetwork(n) +} + +// Resource represents a docker container. +type Resource struct { + pool *Pool + Container *dc.Container +} + +// GetPort returns a resource's published port. You can use it to connect to the service via localhost, e.g. tcp://localhost:1231/ +func (r *Resource) GetPort(id string) string { + if r.Container == nil || r.Container.NetworkSettings == nil { + return "" + } + + m, ok := r.Container.NetworkSettings.Ports[dc.Port(id)] + if !ok || len(m) == 0 { + return "" + } + + return m[0].HostPort +} + +// GetBoundIP returns a resource's published IP address. +func (r *Resource) GetBoundIP(id string) string { + if r.Container == nil || r.Container.NetworkSettings == nil { + return "" + } + + m, ok := r.Container.NetworkSettings.Ports[dc.Port(id)] + if !ok || len(m) == 0 { + return "" + } + + ip := m[0].HostIP + if ip == "0.0.0.0" || ip == "" { + return "localhost" + } + return ip +} + +// GetHostPort returns a resource's published port with an address. +func (r *Resource) GetHostPort(portID string) string { + if r.Container == nil || r.Container.NetworkSettings == nil { + return "" + } + + m, ok := r.Container.NetworkSettings.Ports[dc.Port(portID)] + if !ok || len(m) == 0 { + return "" + } + + ip := m[0].HostIP + if ip == "0.0.0.0" || ip == "" { + ip = "localhost" + } + return net.JoinHostPort(ip, m[0].HostPort) +} + +type ExecOptions struct { + // Command environment, optional. + Env []string + + // StdIn will be attached as command stdin if provided. + StdIn io.Reader + + // StdOut will be attached as command stdout if provided. + StdOut io.Writer + + // StdErr will be attached as command stdout if provided. + StdErr io.Writer + + // Allocate TTY for command or not. + TTY bool +} + +// Exec executes command within container. +func (r *Resource) Exec(cmd []string, opts ExecOptions) (exitCode int, err error) { + exec, err := r.pool.Client.CreateExec(dc.CreateExecOptions{ + Container: r.Container.ID, + Cmd: cmd, + Env: opts.Env, + AttachStderr: true, + AttachStdout: true, + AttachStdin: opts.StdIn != nil, + Tty: opts.TTY, + }) + if err != nil { + return -1, fmt.Errorf("Create exec failed: %w", err) + } + + // Always attach stderr/stdout, even if not specified, to ensure that exec + // waits with opts.Detach as false (default) + // ref: https://github.com/fsouza/go-dockerclient/issues/838 + if opts.StdErr == nil { + opts.StdErr = io.Discard + } + if opts.StdOut == nil { + opts.StdOut = io.Discard + } + + err = r.pool.Client.StartExec(exec.ID, dc.StartExecOptions{ + InputStream: opts.StdIn, + OutputStream: opts.StdOut, + ErrorStream: opts.StdErr, + Tty: opts.TTY, + }) + if err != nil { + return -1, fmt.Errorf("Start exec failed: %w", err) + } + + inspectExec, err := r.pool.Client.InspectExec(exec.ID) + if err != nil { + return -1, fmt.Errorf("Inspect exec failed: %w", err) + } + + return inspectExec.ExitCode, nil +} + +// GetIPInNetwork returns container IP address in network. +func (r *Resource) GetIPInNetwork(network *Network) string { + if r.Container == nil || r.Container.NetworkSettings == nil { + return "" + } + + netCfg, ok := r.Container.NetworkSettings.Networks[network.Network.Name] + if !ok { + return "" + } + + return netCfg.IPAddress +} + +// ConnectToNetwork connects container to network. +func (r *Resource) ConnectToNetwork(network *Network) error { + err := r.pool.Client.ConnectNetwork( + network.Network.ID, + dc.NetworkConnectionOptions{Container: r.Container.ID}, + ) + if err != nil { + return fmt.Errorf("Failed to connect container to network: %w", err) + } + + // refresh internal representation + r.Container, err = r.pool.Client.InspectContainer(r.Container.ID) + if err != nil { + return fmt.Errorf("Failed to refresh container information: %w", err) + } + + network.Network, err = r.pool.Client.NetworkInfo(network.Network.ID) + if err != nil { + return fmt.Errorf("Failed to refresh network information: %w", err) + } + + return nil +} + +// DisconnectFromNetwork disconnects container from network. +func (r *Resource) DisconnectFromNetwork(network *Network) error { + err := r.pool.Client.DisconnectNetwork( + network.Network.ID, + dc.NetworkConnectionOptions{Container: r.Container.ID}, + ) + if err != nil { + return fmt.Errorf("Failed to connect container to network: %w", err) + } + + // refresh internal representation + r.Container, err = r.pool.Client.InspectContainer(r.Container.ID) + if err != nil { + return fmt.Errorf("Failed to refresh container information: %w", err) + } + + network.Network, err = r.pool.Client.NetworkInfo(network.Network.ID) + if err != nil { + return fmt.Errorf("Failed to refresh network information: %w", err) + } + + return nil +} + +// Close removes a container and linked volumes from docker by calling pool.Purge. +func (r *Resource) Close() error { + return r.pool.Purge(r) +} + +// Expire sets a resource's associated container to terminate after a period has passed +func (r *Resource) Expire(seconds uint) error { + go func() { + if err := r.pool.Client.StopContainer(r.Container.ID, seconds); err != nil { + // Error handling? + } + }() + return nil +} + +// NewTLSPool creates a new pool given an endpoint and the certificate path. This is required for endpoints that +// require TLS communication. +func NewTLSPool(endpoint, certpath string) (*Pool, error) { + ca := fmt.Sprintf("%s/ca.pem", certpath) + cert := fmt.Sprintf("%s/cert.pem", certpath) + key := fmt.Sprintf("%s/key.pem", certpath) + + client, err := dc.NewTLSClient(endpoint, cert, key, ca) + if err != nil { + return nil, err + } + + return &Pool{ + Client: client, + }, nil +} + +// NewPool creates a new pool. You can pass an empty string to use the default, which is taken from the environment +// variable DOCKER_HOST and DOCKER_URL, or from docker-machine if the environment variable DOCKER_MACHINE_NAME is set, +// or if neither is defined a sensible default for the operating system you are on. +// TLS pools are automatically configured if the DOCKER_CERT_PATH environment variable exists. +func NewPool(endpoint string) (*Pool, error) { + if endpoint == "" { + if os.Getenv("DOCKER_MACHINE_NAME") != "" { + client, err := dc.NewClientFromEnv() + if err != nil { + return nil, fmt.Errorf("failed to create client from environment: %w", err) + } + + return &Pool{Client: client}, nil + } + if os.Getenv("DOCKER_HOST") != "" { + endpoint = os.Getenv("DOCKER_HOST") + } else if os.Getenv("DOCKER_URL") != "" { + endpoint = os.Getenv("DOCKER_URL") + } else if runtime.GOOS == "windows" { + if _, err := os.Stat(`\\.\pipe\docker_engine`); err == nil { + endpoint = "npipe:////./pipe/docker_engine" + } else { + endpoint = "http://localhost:2375" + } + } else { + endpoint = options.DefaultHost + } + } + + if os.Getenv("DOCKER_CERT_PATH") != "" && shouldPreferTLS(endpoint) { + return NewTLSPool(endpoint, os.Getenv("DOCKER_CERT_PATH")) + } + + client, err := dc.NewClient(endpoint) + if err != nil { + return nil, err + } + + return &Pool{ + Client: client, + }, nil +} + +func shouldPreferTLS(endpoint string) bool { + return !strings.HasPrefix(endpoint, "http://") && !strings.HasPrefix(endpoint, "unix://") +} + +// RunOptions is used to pass in optional parameters when running a container. +type RunOptions struct { + Hostname string + Name string + Repository string + Tag string + Env []string + Entrypoint []string + Cmd []string + Mounts []string + Links []string + ExposedPorts []string + ExtraHosts []string + CapAdd []string + SecurityOpt []string + DNS []string + WorkingDir string + NetworkID string + Networks []*Network // optional networks to join + Labels map[string]string + Auth dc.AuthConfiguration + PortBindings map[dc.Port][]dc.PortBinding + Privileged bool + User string + Tty bool + Platform string +} + +// BuildOptions is used to pass in optional parameters when building a container +type BuildOptions struct { + Dockerfile string + ContextDir string + BuildArgs []dc.BuildArg + Platform string + // Version specifies the builder to use. "1" for classic, "2" for BuildKit + Version string + Auth dc.AuthConfigurations +} + +// BuildAndRunWithBuildOptions builds and starts a docker container. +// Optional modifier functions can be passed in order to change the hostconfig values not covered in RunOptions +func (d *Pool) BuildAndRunWithBuildOptions(buildOpts *BuildOptions, runOpts *RunOptions, hcOpts ...func(*dc.HostConfig)) (*Resource, error) { + err := d.Client.BuildImage(dc.BuildImageOptions{ + Name: runOpts.Name, + Dockerfile: buildOpts.Dockerfile, + OutputStream: io.Discard, + ContextDir: buildOpts.ContextDir, + BuildArgs: buildOpts.BuildArgs, + Platform: buildOpts.Platform, + Version: buildOpts.Version, + AuthConfigs: buildOpts.Auth, + }) + + if err != nil { + return nil, err + } + + runOpts.Repository = runOpts.Name + + return d.RunWithOptions(runOpts, hcOpts...) +} + +// BuildAndRunWithOptions builds and starts a docker container. +// Optional modifier functions can be passed in order to change the hostconfig values not covered in RunOptions +func (d *Pool) BuildAndRunWithOptions(dockerfilePath string, opts *RunOptions, hcOpts ...func(*dc.HostConfig)) (*Resource, error) { + // Set the Dockerfile folder as build context + dir, file := filepath.Split(dockerfilePath) + buildOpts := BuildOptions{Dockerfile: file, ContextDir: dir} + return d.BuildAndRunWithBuildOptions(&buildOpts, opts, hcOpts...) +} + +// BuildAndRun builds and starts a docker container +func (d *Pool) BuildAndRun(name, dockerfilePath string, env []string) (*Resource, error) { + return d.BuildAndRunWithOptions(dockerfilePath, &RunOptions{Name: name, Env: env}) +} + +// RunWithOptions starts a docker container. +// Optional modifier functions can be passed in order to change the hostconfig values not covered in RunOptions +// +// pool.RunWithOptions(&RunOptions{Repository: "mongo", Cmd: []string{"mongod", "--smallfiles"}}) +// pool.RunWithOptions(&RunOptions{Repository: "mongo", Cmd: []string{"mongod", "--smallfiles"}}, func(hostConfig *dc.HostConfig) { +// hostConfig.ShmSize = shmemsize +// }) +func (d *Pool) RunWithOptions(opts *RunOptions, hcOpts ...func(*dc.HostConfig)) (*Resource, error) { + repository := opts.Repository + tag := opts.Tag + env := opts.Env + cmd := opts.Cmd + ep := opts.Entrypoint + wd := opts.WorkingDir + var exp map[dc.Port]struct{} + + if len(opts.ExposedPorts) > 0 { + exp = map[dc.Port]struct{}{} + for _, p := range opts.ExposedPorts { + exp[dc.Port(p)] = struct{}{} + } + } + + mounts := []dc.Mount{} + + for _, m := range opts.Mounts { + s, d, err := options.MountParser(m) + if err != nil { + return nil, err + } + mounts = append(mounts, dc.Mount{ + Source: s, + Destination: d, + RW: true, + }) + } + + if tag == "" { + tag = "latest" + } + + networkingConfig := dc.NetworkingConfig{ + EndpointsConfig: map[string]*dc.EndpointConfig{}, + } + if opts.NetworkID != "" { + networkingConfig.EndpointsConfig[opts.NetworkID] = &dc.EndpointConfig{} + } + for _, network := range opts.Networks { + networkingConfig.EndpointsConfig[network.Network.ID] = &dc.EndpointConfig{} + } + + _, err := d.Client.InspectImage(fmt.Sprintf("%s:%s", repository, tag)) + if err != nil { + var ( + auth = opts.Auth + parts = strings.SplitN(repository, "/", 3) + empty = opts.Auth == dc.AuthConfiguration{} + ) + if empty && len(parts) == 3 { + res, err := dc.NewAuthConfigurationsFromCredsHelpers(parts[0]) + if err == nil { + auth = *res + } + } + + if err := d.Client.PullImage(dc.PullImageOptions{ + Repository: repository, + Tag: tag, + Platform: opts.Platform, + }, auth); err != nil { + return nil, err + } + } + + hostConfig := dc.HostConfig{ + PublishAllPorts: true, + Binds: opts.Mounts, + Links: opts.Links, + PortBindings: opts.PortBindings, + ExtraHosts: opts.ExtraHosts, + CapAdd: opts.CapAdd, + SecurityOpt: opts.SecurityOpt, + Privileged: opts.Privileged, + DNS: opts.DNS, + } + + for _, hostConfigOption := range hcOpts { + hostConfigOption(&hostConfig) + } + + c, err := d.Client.CreateContainer(dc.CreateContainerOptions{ + Name: opts.Name, + Config: &dc.Config{ + Hostname: opts.Hostname, + Image: fmt.Sprintf("%s:%s", repository, tag), + Env: env, + Entrypoint: ep, + Cmd: cmd, + Mounts: mounts, + ExposedPorts: exp, + WorkingDir: wd, + Labels: opts.Labels, + StopSignal: "SIGWINCH", // to support timeouts + User: opts.User, + Tty: opts.Tty, + }, + HostConfig: &hostConfig, + NetworkingConfig: &networkingConfig, + }) + if err != nil { + return nil, err + } + + if err := d.Client.StartContainer(c.ID, nil); err != nil { + return nil, err + } + + c, err = d.inspectContainerWithRetries(c.ID) + if err != nil { + return nil, err + } + + for _, network := range opts.Networks { + network.Network, err = d.Client.NetworkInfo(network.Network.ID) + if err != nil { + return nil, err + } + } + + return &Resource{ + pool: d, + Container: c, + }, nil +} + +// inspectContainerWithRetries will repeat the inspect call until the container has port bindings assigned. +func (d *Pool) inspectContainerWithRetries(id string) (*dc.Container, error) { + const maxRetries = 10 + var ( + retryNum int + c *dc.Container + err error + ) + for retryNum <= maxRetries { + if retryNum > 0 { + time.Sleep(100 * time.Millisecond) + } + c, err = d.Client.InspectContainer(id) + if err != nil { + return nil, err + } + if hasEmptyPortBindings := func() bool { + for _, bindings := range c.NetworkSettings.Ports { + if len(bindings) == 0 { + return true + } + } + return false + }(); !hasEmptyPortBindings { + return c, nil + } + retryNum++ + } + return c, err +} + +// Run starts a docker container. +// +// pool.Run("mysql", "5.3", []string{"FOO=BAR", "BAR=BAZ"}) +func (d *Pool) Run(repository, tag string, env []string) (*Resource, error) { + return d.RunWithOptions(&RunOptions{Repository: repository, Tag: tag, Env: env}) +} + +// ContainerByName finds a container with the given name and returns it if present +func (d *Pool) ContainerByName(containerName string) (*Resource, bool) { + containers, err := d.Client.ListContainers(dc.ListContainersOptions{ + All: true, + Filters: map[string][]string{ + "name": {containerName}, + }, + }) + + if err != nil { + return nil, false + } + + if len(containers) == 0 { + return nil, false + } + + c, err := d.Client.InspectContainer(containers[0].ID) + if err != nil { + return nil, false + } + + return &Resource{ + pool: d, + Container: c, + }, true +} + +// RemoveContainerByName find a container with the given name and removes it if present +func (d *Pool) RemoveContainerByName(containerName string) error { + containers, err := d.Client.ListContainers(dc.ListContainersOptions{ + All: true, + Filters: map[string][]string{ + "name": {containerName}, + }, + }) + if err != nil { + return fmt.Errorf("Error while listing containers with name %s: %w", containerName, err) + } + + if len(containers) == 0 { + return nil + } + + err = d.Client.RemoveContainer(dc.RemoveContainerOptions{ + ID: containers[0].ID, + Force: true, + RemoveVolumes: true, + }) + if err != nil { + return fmt.Errorf("Error while removing container with name %s: %w", containerName, err) + } + + return nil +} + +// Purge removes a container and linked volumes from docker. +func (d *Pool) Purge(r *Resource) error { + if err := d.Client.RemoveContainer(dc.RemoveContainerOptions{ID: r.Container.ID, Force: true, RemoveVolumes: true}); err != nil { + return err + } + + return nil +} + +// Retry is an exponential backoff retry helper. You can use it to wait for e.g. mysql to boot up. +func (d *Pool) Retry(op func() error) error { + if d.MaxWait == 0 { + d.MaxWait = time.Minute + } + bo := backoff.NewExponentialBackOff() + bo.MaxInterval = time.Second * 5 + bo.MaxElapsedTime = d.MaxWait + if err := backoff.Retry(op, bo); err != nil { + if bo.NextBackOff() == backoff.Stop { + return fmt.Errorf("reached retry deadline: %w", err) + } + + return err + } + + return nil +} + +// CurrentContainer returns current container descriptor if this function called within running container. +// It returns ErrNotInContainer as error if this function running not in container. +func (d *Pool) CurrentContainer() (*Resource, error) { + // docker daemon puts short container id into hostname + hostname, err := os.Hostname() + if err != nil { + return nil, fmt.Errorf("Get hostname failed: %w", err) + } + + container, err := d.Client.InspectContainer(hostname) + switch err.(type) { + case nil: + return &Resource{ + pool: d, + Container: container, + }, nil + case *dc.NoSuchContainer: + return nil, ErrNotInContainer + default: + return nil, err + } +} + +// CreateNetwork creates docker network. It's useful for linking multiple containers. +func (d *Pool) CreateNetwork(name string, opts ...func(config *dc.CreateNetworkOptions)) (*Network, error) { + var cfg dc.CreateNetworkOptions + cfg.Name = name + for _, opt := range opts { + opt(&cfg) + } + + network, err := d.Client.CreateNetwork(cfg) + if err != nil { + return nil, err + } + + return &Network{ + pool: d, + Network: network, + }, nil +} + +// NetworksByName returns a list of docker networks filtered by name +func (d *Pool) NetworksByName(name string) ([]Network, error) { + networks, err := d.Client.ListNetworks() + if err != nil { + return nil, err + } + + var foundNetworks []Network + for idx := range networks { + if networks[idx].Name == name { + foundNetworks = append(foundNetworks, + Network{ + pool: d, + Network: &networks[idx], + }, + ) + } + } + + return foundNetworks, nil +} + +// RemoveNetwork disconnects containers and removes provided network. +func (d *Pool) RemoveNetwork(network *Network) error { + for container := range network.Network.Containers { + _ = d.Client.DisconnectNetwork( + network.Network.ID, + dc.NetworkConnectionOptions{Container: container, Force: true}, + ) + } + + return d.Client.RemoveNetwork(network.Network.ID) +} diff --git a/vendor/github.com/ory/dockertest/v3/package-lock.json b/vendor/github.com/ory/dockertest/v3/package-lock.json new file mode 100644 index 00000000..dcdee9be --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/package-lock.json @@ -0,0 +1,1077 @@ +{ + "name": "dockertest", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "devDependencies": { + "license-checker": "^25.0.1", + "ory-prettier-styles": "1.3.0", + "prettier": "2.7.1" + } + }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", + "dev": true + }, + "node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/array-find-index": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", + "integrity": "sha512-M1HQyIXcBGtVywBt8WVdim+lrNaK7VHp99Qt5pSNziXznKHViIBbXWtfRTpEFpF/c4FdfxNAsCCwPp5phBYJtw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/asap": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", + "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", + "dev": true + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true + }, + "node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/debuglog": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/debuglog/-/debuglog-1.0.1.tgz", + "integrity": "sha512-syBZ+rnAK3EgMsH2aYEOLUW7mZSY9Gb+0wUMCFsZvcmiz+HigA0LOcq/HoQqVuGG+EKykunc7QG2bzrponfaSw==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/dezalgo": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/dezalgo/-/dezalgo-1.0.4.tgz", + "integrity": "sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==", + "dev": true, + "dependencies": { + "asap": "^2.0.0", + "wrappy": "1" + } + }, + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "dev": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.10", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz", + "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", + "dev": true + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/hosted-git-info": { + "version": "2.8.9", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", + "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", + "dev": true + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dev": true, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "node_modules/is-core-module": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", + "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", + "dev": true, + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true + }, + "node_modules/license-checker": { + "version": "25.0.1", + "resolved": "https://registry.npmjs.org/license-checker/-/license-checker-25.0.1.tgz", + "integrity": "sha512-mET5AIwl7MR2IAKYYoVBBpV0OnkKQ1xGj2IMMeEFIs42QAkEVjRtFZGWmQ28WeU7MP779iAgOaOy93Mn44mn6g==", + "dev": true, + "dependencies": { + "chalk": "^2.4.1", + "debug": "^3.1.0", + "mkdirp": "^0.5.1", + "nopt": "^4.0.1", + "read-installed": "~4.0.3", + "semver": "^5.5.0", + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0", + "spdx-satisfies": "^4.0.0", + "treeify": "^1.1.0" + }, + "bin": { + "license-checker": "bin/license-checker" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz", + "integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dev": true, + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "node_modules/nopt": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-4.0.3.tgz", + "integrity": "sha512-CvaGwVMztSMJLOeXPrez7fyfObdZqNUK1cPAEzLHrTybIua9pMdmmPR5YwtfNftIOMv3DPUhFaxsZMNTQO20Kg==", + "dev": true, + "dependencies": { + "abbrev": "1", + "osenv": "^0.1.4" + }, + "bin": { + "nopt": "bin/nopt.js" + } + }, + "node_modules/normalize-package-data": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", + "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", + "dev": true, + "dependencies": { + "hosted-git-info": "^2.1.4", + "resolve": "^1.10.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "node_modules/npm-normalize-package-bin": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-1.0.1.tgz", + "integrity": "sha512-EPfafl6JL5/rU+ot6P3gRSCpPDW5VmIzX959Ob1+ySFUuuYHWHekXpwdUZcKP5C+DS4GEtdJluwBjnsNDl+fSA==", + "dev": true + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/ory-prettier-styles": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/ory-prettier-styles/-/ory-prettier-styles-1.3.0.tgz", + "integrity": "sha512-Vfn0G6CyLaadwcCamwe1SQCf37ZQfBDgMrhRI70dE/2fbE3Q43/xu7K5c32I5FGt/EliroWty5yBjmdkj0eWug==", + "dev": true + }, + "node_modules/os-homedir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "integrity": "sha512-B5JU3cabzk8c67mRRd3ECmROafjYMXbuzlwtqdM8IbS8ktlTix8aFGb2bAGKrSRIlnfKwovGUUr72JUPyOb6kQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/osenv": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/osenv/-/osenv-0.1.5.tgz", + "integrity": "sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==", + "dev": true, + "dependencies": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "node_modules/prettier": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.7.1.tgz", + "integrity": "sha512-ujppO+MkdPqoVINuDFDRLClm7D78qbDt0/NR+wp5FqEZOoTNAjPHWj17QRhu7geIHJfcNhRk1XVQmF8Bp3ye+g==", + "dev": true, + "bin": { + "prettier": "bin-prettier.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/read-installed": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/read-installed/-/read-installed-4.0.3.tgz", + "integrity": "sha512-O03wg/IYuV/VtnK2h/KXEt9VIbMUFbk3ERG0Iu4FhLZw0EP0T9znqrYDGn6ncbEsXUFaUjiVAWXHzxwt3lhRPQ==", + "dev": true, + "dependencies": { + "debuglog": "^1.0.1", + "read-package-json": "^2.0.0", + "readdir-scoped-modules": "^1.0.0", + "semver": "2 || 3 || 4 || 5", + "slide": "~1.1.3", + "util-extend": "^1.0.1" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.2" + } + }, + "node_modules/read-package-json": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/read-package-json/-/read-package-json-2.1.2.tgz", + "integrity": "sha512-D1KmuLQr6ZSJS0tW8hf3WGpRlwszJOXZ3E8Yd/DNRaM5d+1wVRZdHlpGBLAuovjr28LbWvjpWkBHMxpRGGjzNA==", + "dev": true, + "dependencies": { + "glob": "^7.1.1", + "json-parse-even-better-errors": "^2.3.0", + "normalize-package-data": "^2.0.0", + "npm-normalize-package-bin": "^1.0.0" + } + }, + "node_modules/readdir-scoped-modules": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/readdir-scoped-modules/-/readdir-scoped-modules-1.1.0.tgz", + "integrity": "sha512-asaikDeqAQg7JifRsZn1NJZXo9E+VwlyCfbkZhwyISinqk5zNS6266HS5kah6P0SaQKGF6SkNnZVHUzHFYxYDw==", + "dev": true, + "dependencies": { + "debuglog": "^1.0.1", + "dezalgo": "^1.0.0", + "graceful-fs": "^4.1.2", + "once": "^1.3.0" + } + }, + "node_modules/resolve": { + "version": "1.22.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", + "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", + "dev": true, + "dependencies": { + "is-core-module": "^2.9.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true, + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/slide": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/slide/-/slide-1.1.6.tgz", + "integrity": "sha512-NwrtjCg+lZoqhFU8fOwl4ay2ei8PaqCBOUV3/ektPY9trO1yQ1oXEfmHAhKArUVUr/hOHvy5f6AdP17dCM0zMw==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/spdx-compare": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/spdx-compare/-/spdx-compare-1.0.0.tgz", + "integrity": "sha512-C1mDZOX0hnu0ep9dfmuoi03+eOdDoz2yvK79RxbcrVEG1NO1Ph35yW102DHWKN4pk80nwCgeMmSY5L25VE4D9A==", + "dev": true, + "dependencies": { + "array-find-index": "^1.0.2", + "spdx-expression-parse": "^3.0.0", + "spdx-ranges": "^2.0.0" + } + }, + "node_modules/spdx-correct": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.1.tgz", + "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", + "dev": true, + "dependencies": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-exceptions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz", + "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==", + "dev": true + }, + "node_modules/spdx-expression-parse": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", + "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "dev": true, + "dependencies": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-license-ids": { + "version": "3.0.12", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.12.tgz", + "integrity": "sha512-rr+VVSXtRhO4OHbXUiAF7xW3Bo9DuuF6C5jH+q/x15j2jniycgKbxU09Hr0WqlSLUs4i4ltHGXqTe7VHclYWyA==", + "dev": true + }, + "node_modules/spdx-ranges": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/spdx-ranges/-/spdx-ranges-2.1.1.tgz", + "integrity": "sha512-mcdpQFV7UDAgLpXEE/jOMqvK4LBoO0uTQg0uvXUewmEFhpiZx5yJSZITHB8w1ZahKdhfZqP5GPEOKLyEq5p8XA==", + "dev": true + }, + "node_modules/spdx-satisfies": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/spdx-satisfies/-/spdx-satisfies-4.0.1.tgz", + "integrity": "sha512-WVzZ/cXAzoNmjCWiEluEA3BjHp5tiUmmhn9MK+X0tBbR9sOqtC6UQwmgCNrAIZvNlMuBUYAaHYfb2oqlF9SwKA==", + "dev": true, + "dependencies": { + "spdx-compare": "^1.0.0", + "spdx-expression-parse": "^3.0.0", + "spdx-ranges": "^2.0.0" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/treeify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/treeify/-/treeify-1.1.0.tgz", + "integrity": "sha512-1m4RA7xVAJrSGrrXGs0L3YTwyvBs2S8PbRHaLZAkFw7JR8oIFwYtysxlBZhYIa7xSyiYJKZ3iGrrk55cGA3i9A==", + "dev": true, + "engines": { + "node": ">=0.6" + } + }, + "node_modules/util-extend": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/util-extend/-/util-extend-1.0.3.tgz", + "integrity": "sha512-mLs5zAK+ctllYBj+iAQvlDCwoxU/WDOUaJkcFudeiAX6OajC6BKXJUa9a+tbtkC11dz2Ufb7h0lyvIOVn4LADA==", + "dev": true + }, + "node_modules/validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "dev": true, + "dependencies": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + } + }, + "dependencies": { + "abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", + "dev": true + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "array-find-index": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", + "integrity": "sha512-M1HQyIXcBGtVywBt8WVdim+lrNaK7VHp99Qt5pSNziXznKHViIBbXWtfRTpEFpF/c4FdfxNAsCCwPp5phBYJtw==", + "dev": true + }, + "asap": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", + "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", + "dev": true + }, + "balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true + }, + "debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "debuglog": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/debuglog/-/debuglog-1.0.1.tgz", + "integrity": "sha512-syBZ+rnAK3EgMsH2aYEOLUW7mZSY9Gb+0wUMCFsZvcmiz+HigA0LOcq/HoQqVuGG+EKykunc7QG2bzrponfaSw==", + "dev": true + }, + "dezalgo": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/dezalgo/-/dezalgo-1.0.4.tgz", + "integrity": "sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==", + "dev": true, + "requires": { + "asap": "^2.0.0", + "wrappy": "1" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "graceful-fs": { + "version": "4.2.10", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz", + "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", + "dev": true + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true + }, + "hosted-git-info": { + "version": "2.8.9", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", + "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "is-core-module": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", + "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", + "dev": true, + "requires": { + "has": "^1.0.3" + } + }, + "json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true + }, + "license-checker": { + "version": "25.0.1", + "resolved": "https://registry.npmjs.org/license-checker/-/license-checker-25.0.1.tgz", + "integrity": "sha512-mET5AIwl7MR2IAKYYoVBBpV0OnkKQ1xGj2IMMeEFIs42QAkEVjRtFZGWmQ28WeU7MP779iAgOaOy93Mn44mn6g==", + "dev": true, + "requires": { + "chalk": "^2.4.1", + "debug": "^3.1.0", + "mkdirp": "^0.5.1", + "nopt": "^4.0.1", + "read-installed": "~4.0.3", + "semver": "^5.5.0", + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0", + "spdx-satisfies": "^4.0.0", + "treeify": "^1.1.0" + } + }, + "minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz", + "integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==", + "dev": true + }, + "mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dev": true, + "requires": { + "minimist": "^1.2.6" + } + }, + "ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "nopt": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-4.0.3.tgz", + "integrity": "sha512-CvaGwVMztSMJLOeXPrez7fyfObdZqNUK1cPAEzLHrTybIua9pMdmmPR5YwtfNftIOMv3DPUhFaxsZMNTQO20Kg==", + "dev": true, + "requires": { + "abbrev": "1", + "osenv": "^0.1.4" + } + }, + "normalize-package-data": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", + "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", + "dev": true, + "requires": { + "hosted-git-info": "^2.1.4", + "resolve": "^1.10.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "npm-normalize-package-bin": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-1.0.1.tgz", + "integrity": "sha512-EPfafl6JL5/rU+ot6P3gRSCpPDW5VmIzX959Ob1+ySFUuuYHWHekXpwdUZcKP5C+DS4GEtdJluwBjnsNDl+fSA==", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "ory-prettier-styles": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/ory-prettier-styles/-/ory-prettier-styles-1.3.0.tgz", + "integrity": "sha512-Vfn0G6CyLaadwcCamwe1SQCf37ZQfBDgMrhRI70dE/2fbE3Q43/xu7K5c32I5FGt/EliroWty5yBjmdkj0eWug==", + "dev": true + }, + "os-homedir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "integrity": "sha512-B5JU3cabzk8c67mRRd3ECmROafjYMXbuzlwtqdM8IbS8ktlTix8aFGb2bAGKrSRIlnfKwovGUUr72JUPyOb6kQ==", + "dev": true + }, + "os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", + "dev": true + }, + "osenv": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/osenv/-/osenv-0.1.5.tgz", + "integrity": "sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==", + "dev": true, + "requires": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true + }, + "path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "prettier": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.7.1.tgz", + "integrity": "sha512-ujppO+MkdPqoVINuDFDRLClm7D78qbDt0/NR+wp5FqEZOoTNAjPHWj17QRhu7geIHJfcNhRk1XVQmF8Bp3ye+g==", + "dev": true + }, + "read-installed": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/read-installed/-/read-installed-4.0.3.tgz", + "integrity": "sha512-O03wg/IYuV/VtnK2h/KXEt9VIbMUFbk3ERG0Iu4FhLZw0EP0T9znqrYDGn6ncbEsXUFaUjiVAWXHzxwt3lhRPQ==", + "dev": true, + "requires": { + "debuglog": "^1.0.1", + "graceful-fs": "^4.1.2", + "read-package-json": "^2.0.0", + "readdir-scoped-modules": "^1.0.0", + "semver": "2 || 3 || 4 || 5", + "slide": "~1.1.3", + "util-extend": "^1.0.1" + } + }, + "read-package-json": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/read-package-json/-/read-package-json-2.1.2.tgz", + "integrity": "sha512-D1KmuLQr6ZSJS0tW8hf3WGpRlwszJOXZ3E8Yd/DNRaM5d+1wVRZdHlpGBLAuovjr28LbWvjpWkBHMxpRGGjzNA==", + "dev": true, + "requires": { + "glob": "^7.1.1", + "json-parse-even-better-errors": "^2.3.0", + "normalize-package-data": "^2.0.0", + "npm-normalize-package-bin": "^1.0.0" + } + }, + "readdir-scoped-modules": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/readdir-scoped-modules/-/readdir-scoped-modules-1.1.0.tgz", + "integrity": "sha512-asaikDeqAQg7JifRsZn1NJZXo9E+VwlyCfbkZhwyISinqk5zNS6266HS5kah6P0SaQKGF6SkNnZVHUzHFYxYDw==", + "dev": true, + "requires": { + "debuglog": "^1.0.1", + "dezalgo": "^1.0.0", + "graceful-fs": "^4.1.2", + "once": "^1.3.0" + } + }, + "resolve": { + "version": "1.22.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", + "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", + "dev": true, + "requires": { + "is-core-module": "^2.9.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + } + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true + }, + "slide": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/slide/-/slide-1.1.6.tgz", + "integrity": "sha512-NwrtjCg+lZoqhFU8fOwl4ay2ei8PaqCBOUV3/ektPY9trO1yQ1oXEfmHAhKArUVUr/hOHvy5f6AdP17dCM0zMw==", + "dev": true + }, + "spdx-compare": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/spdx-compare/-/spdx-compare-1.0.0.tgz", + "integrity": "sha512-C1mDZOX0hnu0ep9dfmuoi03+eOdDoz2yvK79RxbcrVEG1NO1Ph35yW102DHWKN4pk80nwCgeMmSY5L25VE4D9A==", + "dev": true, + "requires": { + "array-find-index": "^1.0.2", + "spdx-expression-parse": "^3.0.0", + "spdx-ranges": "^2.0.0" + } + }, + "spdx-correct": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.1.tgz", + "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", + "dev": true, + "requires": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-exceptions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz", + "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==", + "dev": true + }, + "spdx-expression-parse": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", + "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "dev": true, + "requires": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-license-ids": { + "version": "3.0.12", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.12.tgz", + "integrity": "sha512-rr+VVSXtRhO4OHbXUiAF7xW3Bo9DuuF6C5jH+q/x15j2jniycgKbxU09Hr0WqlSLUs4i4ltHGXqTe7VHclYWyA==", + "dev": true + }, + "spdx-ranges": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/spdx-ranges/-/spdx-ranges-2.1.1.tgz", + "integrity": "sha512-mcdpQFV7UDAgLpXEE/jOMqvK4LBoO0uTQg0uvXUewmEFhpiZx5yJSZITHB8w1ZahKdhfZqP5GPEOKLyEq5p8XA==", + "dev": true + }, + "spdx-satisfies": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/spdx-satisfies/-/spdx-satisfies-4.0.1.tgz", + "integrity": "sha512-WVzZ/cXAzoNmjCWiEluEA3BjHp5tiUmmhn9MK+X0tBbR9sOqtC6UQwmgCNrAIZvNlMuBUYAaHYfb2oqlF9SwKA==", + "dev": true, + "requires": { + "spdx-compare": "^1.0.0", + "spdx-expression-parse": "^3.0.0", + "spdx-ranges": "^2.0.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true + }, + "treeify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/treeify/-/treeify-1.1.0.tgz", + "integrity": "sha512-1m4RA7xVAJrSGrrXGs0L3YTwyvBs2S8PbRHaLZAkFw7JR8oIFwYtysxlBZhYIa7xSyiYJKZ3iGrrk55cGA3i9A==", + "dev": true + }, + "util-extend": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/util-extend/-/util-extend-1.0.3.tgz", + "integrity": "sha512-mLs5zAK+ctllYBj+iAQvlDCwoxU/WDOUaJkcFudeiAX6OajC6BKXJUa9a+tbtkC11dz2Ufb7h0lyvIOVn4LADA==", + "dev": true + }, + "validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "dev": true, + "requires": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + } + } +} diff --git a/vendor/github.com/ory/dockertest/v3/package.json b/vendor/github.com/ory/dockertest/v3/package.json new file mode 100644 index 00000000..1a7cfdb3 --- /dev/null +++ b/vendor/github.com/ory/dockertest/v3/package.json @@ -0,0 +1,9 @@ +{ + "private": true, + "prettier": "ory-prettier-styles", + "devDependencies": { + "license-checker": "^25.0.1", + "ory-prettier-styles": "1.3.0", + "prettier": "2.7.1" + } +} diff --git a/vendor/github.com/pkg/errors/.gitignore b/vendor/github.com/pkg/errors/.gitignore new file mode 100644 index 00000000..daf913b1 --- /dev/null +++ b/vendor/github.com/pkg/errors/.gitignore @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/vendor/github.com/pkg/errors/.travis.yml b/vendor/github.com/pkg/errors/.travis.yml new file mode 100644 index 00000000..9159de03 --- /dev/null +++ b/vendor/github.com/pkg/errors/.travis.yml @@ -0,0 +1,10 @@ +language: go +go_import_path: github.com/pkg/errors +go: + - 1.11.x + - 1.12.x + - 1.13.x + - tip + +script: + - make check diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE new file mode 100644 index 00000000..835ba3e7 --- /dev/null +++ b/vendor/github.com/pkg/errors/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2015, Dave Cheney +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/errors/Makefile b/vendor/github.com/pkg/errors/Makefile new file mode 100644 index 00000000..ce9d7cde --- /dev/null +++ b/vendor/github.com/pkg/errors/Makefile @@ -0,0 +1,44 @@ +PKGS := github.com/pkg/errors +SRCDIRS := $(shell go list -f '{{.Dir}}' $(PKGS)) +GO := go + +check: test vet gofmt misspell unconvert staticcheck ineffassign unparam + +test: + $(GO) test $(PKGS) + +vet: | test + $(GO) vet $(PKGS) + +staticcheck: + $(GO) get honnef.co/go/tools/cmd/staticcheck + staticcheck -checks all $(PKGS) + +misspell: + $(GO) get github.com/client9/misspell/cmd/misspell + misspell \ + -locale GB \ + -error \ + *.md *.go + +unconvert: + $(GO) get github.com/mdempsky/unconvert + unconvert -v $(PKGS) + +ineffassign: + $(GO) get github.com/gordonklaus/ineffassign + find $(SRCDIRS) -name '*.go' | xargs ineffassign + +pedantic: check errcheck + +unparam: + $(GO) get mvdan.cc/unparam + unparam ./... + +errcheck: + $(GO) get github.com/kisielk/errcheck + errcheck $(PKGS) + +gofmt: + @echo Checking code is gofmted + @test -z "$(shell gofmt -s -l -d -e $(SRCDIRS) | tee /dev/stderr)" diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md new file mode 100644 index 00000000..54dfdcb1 --- /dev/null +++ b/vendor/github.com/pkg/errors/README.md @@ -0,0 +1,59 @@ +# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) [![Sourcegraph](https://sourcegraph.com/github.com/pkg/errors/-/badge.svg)](https://sourcegraph.com/github.com/pkg/errors?badge) + +Package errors provides simple error handling primitives. + +`go get github.com/pkg/errors` + +The traditional error handling idiom in Go is roughly akin to +```go +if err != nil { + return err +} +``` +which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. + +## Adding context to an error + +The errors.Wrap function returns a new error that adds context to the original error. For example +```go +_, err := ioutil.ReadAll(r) +if err != nil { + return errors.Wrap(err, "read failed") +} +``` +## Retrieving the cause of an error + +Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. +```go +type causer interface { + Cause() error +} +``` +`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: +```go +switch err := errors.Cause(err).(type) { +case *MyError: + // handle specifically +default: + // unknown error +} +``` + +[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). + +## Roadmap + +With the upcoming [Go2 error proposals](https://go.googlesource.com/proposal/+/master/design/go2draft.md) this package is moving into maintenance mode. The roadmap for a 1.0 release is as follows: + +- 0.9. Remove pre Go 1.9 and Go 1.10 support, address outstanding pull requests (if possible) +- 1.0. Final release. + +## Contributing + +Because of the Go2 errors changes, this package is not accepting proposals for new functionality. With that said, we welcome pull requests, bug fixes and issue reports. + +Before sending a PR, please discuss your change by raising an issue. + +## License + +BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml new file mode 100644 index 00000000..a932eade --- /dev/null +++ b/vendor/github.com/pkg/errors/appveyor.yml @@ -0,0 +1,32 @@ +version: build-{build}.{branch} + +clone_folder: C:\gopath\src\github.com\pkg\errors +shallow_clone: true # for startup speed + +environment: + GOPATH: C:\gopath + +platform: + - x64 + +# http://www.appveyor.com/docs/installed-software +install: + # some helpful output for debugging builds + - go version + - go env + # pre-installed MinGW at C:\MinGW is 32bit only + # but MSYS2 at C:\msys64 has mingw64 + - set PATH=C:\msys64\mingw64\bin;%PATH% + - gcc --version + - g++ --version + +build_script: + - go install -v ./... + +test_script: + - set PATH=C:\gopath\bin;%PATH% + - go test -v ./... + +#artifacts: +# - path: '%GOPATH%\bin\*.exe' +deploy: off diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go new file mode 100644 index 00000000..161aea25 --- /dev/null +++ b/vendor/github.com/pkg/errors/errors.go @@ -0,0 +1,288 @@ +// Package errors provides simple error handling primitives. +// +// The traditional error handling idiom in Go is roughly akin to +// +// if err != nil { +// return err +// } +// +// which when applied recursively up the call stack results in error reports +// without context or debugging information. The errors package allows +// programmers to add context to the failure path in their code in a way +// that does not destroy the original value of the error. +// +// Adding context to an error +// +// The errors.Wrap function returns a new error that adds context to the +// original error by recording a stack trace at the point Wrap is called, +// together with the supplied message. For example +// +// _, err := ioutil.ReadAll(r) +// if err != nil { +// return errors.Wrap(err, "read failed") +// } +// +// If additional control is required, the errors.WithStack and +// errors.WithMessage functions destructure errors.Wrap into its component +// operations: annotating an error with a stack trace and with a message, +// respectively. +// +// Retrieving the cause of an error +// +// Using errors.Wrap constructs a stack of errors, adding context to the +// preceding error. Depending on the nature of the error it may be necessary +// to reverse the operation of errors.Wrap to retrieve the original error +// for inspection. Any error value which implements this interface +// +// type causer interface { +// Cause() error +// } +// +// can be inspected by errors.Cause. errors.Cause will recursively retrieve +// the topmost error that does not implement causer, which is assumed to be +// the original cause. For example: +// +// switch err := errors.Cause(err).(type) { +// case *MyError: +// // handle specifically +// default: +// // unknown error +// } +// +// Although the causer interface is not exported by this package, it is +// considered a part of its stable public interface. +// +// Formatted printing of errors +// +// All error values returned from this package implement fmt.Formatter and can +// be formatted by the fmt package. The following verbs are supported: +// +// %s print the error. If the error has a Cause it will be +// printed recursively. +// %v see %s +// %+v extended format. Each Frame of the error's StackTrace will +// be printed in detail. +// +// Retrieving the stack trace of an error or wrapper +// +// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are +// invoked. This information can be retrieved with the following interface: +// +// type stackTracer interface { +// StackTrace() errors.StackTrace +// } +// +// The returned errors.StackTrace type is defined as +// +// type StackTrace []Frame +// +// The Frame type represents a call site in the stack trace. Frame supports +// the fmt.Formatter interface that can be used for printing information about +// the stack trace of this error. For example: +// +// if err, ok := err.(stackTracer); ok { +// for _, f := range err.StackTrace() { +// fmt.Printf("%+s:%d\n", f, f) +// } +// } +// +// Although the stackTracer interface is not exported by this package, it is +// considered a part of its stable public interface. +// +// See the documentation for Frame.Format for more details. +package errors + +import ( + "fmt" + "io" +) + +// New returns an error with the supplied message. +// New also records the stack trace at the point it was called. +func New(message string) error { + return &fundamental{ + msg: message, + stack: callers(), + } +} + +// Errorf formats according to a format specifier and returns the string +// as a value that satisfies error. +// Errorf also records the stack trace at the point it was called. +func Errorf(format string, args ...interface{}) error { + return &fundamental{ + msg: fmt.Sprintf(format, args...), + stack: callers(), + } +} + +// fundamental is an error that has a message and a stack, but no caller. +type fundamental struct { + msg string + *stack +} + +func (f *fundamental) Error() string { return f.msg } + +func (f *fundamental) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + io.WriteString(s, f.msg) + f.stack.Format(s, verb) + return + } + fallthrough + case 's': + io.WriteString(s, f.msg) + case 'q': + fmt.Fprintf(s, "%q", f.msg) + } +} + +// WithStack annotates err with a stack trace at the point WithStack was called. +// If err is nil, WithStack returns nil. +func WithStack(err error) error { + if err == nil { + return nil + } + return &withStack{ + err, + callers(), + } +} + +type withStack struct { + error + *stack +} + +func (w *withStack) Cause() error { return w.error } + +// Unwrap provides compatibility for Go 1.13 error chains. +func (w *withStack) Unwrap() error { return w.error } + +func (w *withStack) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + fmt.Fprintf(s, "%+v", w.Cause()) + w.stack.Format(s, verb) + return + } + fallthrough + case 's': + io.WriteString(s, w.Error()) + case 'q': + fmt.Fprintf(s, "%q", w.Error()) + } +} + +// Wrap returns an error annotating err with a stack trace +// at the point Wrap is called, and the supplied message. +// If err is nil, Wrap returns nil. +func Wrap(err error, message string) error { + if err == nil { + return nil + } + err = &withMessage{ + cause: err, + msg: message, + } + return &withStack{ + err, + callers(), + } +} + +// Wrapf returns an error annotating err with a stack trace +// at the point Wrapf is called, and the format specifier. +// If err is nil, Wrapf returns nil. +func Wrapf(err error, format string, args ...interface{}) error { + if err == nil { + return nil + } + err = &withMessage{ + cause: err, + msg: fmt.Sprintf(format, args...), + } + return &withStack{ + err, + callers(), + } +} + +// WithMessage annotates err with a new message. +// If err is nil, WithMessage returns nil. +func WithMessage(err error, message string) error { + if err == nil { + return nil + } + return &withMessage{ + cause: err, + msg: message, + } +} + +// WithMessagef annotates err with the format specifier. +// If err is nil, WithMessagef returns nil. +func WithMessagef(err error, format string, args ...interface{}) error { + if err == nil { + return nil + } + return &withMessage{ + cause: err, + msg: fmt.Sprintf(format, args...), + } +} + +type withMessage struct { + cause error + msg string +} + +func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } +func (w *withMessage) Cause() error { return w.cause } + +// Unwrap provides compatibility for Go 1.13 error chains. +func (w *withMessage) Unwrap() error { return w.cause } + +func (w *withMessage) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + fmt.Fprintf(s, "%+v\n", w.Cause()) + io.WriteString(s, w.msg) + return + } + fallthrough + case 's', 'q': + io.WriteString(s, w.Error()) + } +} + +// Cause returns the underlying cause of the error, if possible. +// An error value has a cause if it implements the following +// interface: +// +// type causer interface { +// Cause() error +// } +// +// If the error does not implement Cause, the original error will +// be returned. If the error is nil, nil will be returned without further +// investigation. +func Cause(err error) error { + type causer interface { + Cause() error + } + + for err != nil { + cause, ok := err.(causer) + if !ok { + break + } + err = cause.Cause() + } + return err +} diff --git a/vendor/github.com/pkg/errors/go113.go b/vendor/github.com/pkg/errors/go113.go new file mode 100644 index 00000000..be0d10d0 --- /dev/null +++ b/vendor/github.com/pkg/errors/go113.go @@ -0,0 +1,38 @@ +// +build go1.13 + +package errors + +import ( + stderrors "errors" +) + +// Is reports whether any error in err's chain matches target. +// +// The chain consists of err itself followed by the sequence of errors obtained by +// repeatedly calling Unwrap. +// +// An error is considered to match a target if it is equal to that target or if +// it implements a method Is(error) bool such that Is(target) returns true. +func Is(err, target error) bool { return stderrors.Is(err, target) } + +// As finds the first error in err's chain that matches target, and if so, sets +// target to that error value and returns true. +// +// The chain consists of err itself followed by the sequence of errors obtained by +// repeatedly calling Unwrap. +// +// An error matches target if the error's concrete value is assignable to the value +// pointed to by target, or if the error has a method As(interface{}) bool such that +// As(target) returns true. In the latter case, the As method is responsible for +// setting target. +// +// As will panic if target is not a non-nil pointer to either a type that implements +// error, or to any interface type. As returns false if err is nil. +func As(err error, target interface{}) bool { return stderrors.As(err, target) } + +// Unwrap returns the result of calling the Unwrap method on err, if err's +// type contains an Unwrap method returning error. +// Otherwise, Unwrap returns nil. +func Unwrap(err error) error { + return stderrors.Unwrap(err) +} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go new file mode 100644 index 00000000..779a8348 --- /dev/null +++ b/vendor/github.com/pkg/errors/stack.go @@ -0,0 +1,177 @@ +package errors + +import ( + "fmt" + "io" + "path" + "runtime" + "strconv" + "strings" +) + +// Frame represents a program counter inside a stack frame. +// For historical reasons if Frame is interpreted as a uintptr +// its value represents the program counter + 1. +type Frame uintptr + +// pc returns the program counter for this frame; +// multiple frames may have the same PC value. +func (f Frame) pc() uintptr { return uintptr(f) - 1 } + +// file returns the full path to the file that contains the +// function for this Frame's pc. +func (f Frame) file() string { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return "unknown" + } + file, _ := fn.FileLine(f.pc()) + return file +} + +// line returns the line number of source code of the +// function for this Frame's pc. +func (f Frame) line() int { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return 0 + } + _, line := fn.FileLine(f.pc()) + return line +} + +// name returns the name of this function, if known. +func (f Frame) name() string { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return "unknown" + } + return fn.Name() +} + +// Format formats the frame according to the fmt.Formatter interface. +// +// %s source file +// %d source line +// %n function name +// %v equivalent to %s:%d +// +// Format accepts flags that alter the printing of some verbs, as follows: +// +// %+s function name and path of source file relative to the compile time +// GOPATH separated by \n\t (\n\t) +// %+v equivalent to %+s:%d +func (f Frame) Format(s fmt.State, verb rune) { + switch verb { + case 's': + switch { + case s.Flag('+'): + io.WriteString(s, f.name()) + io.WriteString(s, "\n\t") + io.WriteString(s, f.file()) + default: + io.WriteString(s, path.Base(f.file())) + } + case 'd': + io.WriteString(s, strconv.Itoa(f.line())) + case 'n': + io.WriteString(s, funcname(f.name())) + case 'v': + f.Format(s, 's') + io.WriteString(s, ":") + f.Format(s, 'd') + } +} + +// MarshalText formats a stacktrace Frame as a text string. The output is the +// same as that of fmt.Sprintf("%+v", f), but without newlines or tabs. +func (f Frame) MarshalText() ([]byte, error) { + name := f.name() + if name == "unknown" { + return []byte(name), nil + } + return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil +} + +// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). +type StackTrace []Frame + +// Format formats the stack of Frames according to the fmt.Formatter interface. +// +// %s lists source files for each Frame in the stack +// %v lists the source file and line number for each Frame in the stack +// +// Format accepts flags that alter the printing of some verbs, as follows: +// +// %+v Prints filename, function, and line number for each Frame in the stack. +func (st StackTrace) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + switch { + case s.Flag('+'): + for _, f := range st { + io.WriteString(s, "\n") + f.Format(s, verb) + } + case s.Flag('#'): + fmt.Fprintf(s, "%#v", []Frame(st)) + default: + st.formatSlice(s, verb) + } + case 's': + st.formatSlice(s, verb) + } +} + +// formatSlice will format this StackTrace into the given buffer as a slice of +// Frame, only valid when called with '%s' or '%v'. +func (st StackTrace) formatSlice(s fmt.State, verb rune) { + io.WriteString(s, "[") + for i, f := range st { + if i > 0 { + io.WriteString(s, " ") + } + f.Format(s, verb) + } + io.WriteString(s, "]") +} + +// stack represents a stack of program counters. +type stack []uintptr + +func (s *stack) Format(st fmt.State, verb rune) { + switch verb { + case 'v': + switch { + case st.Flag('+'): + for _, pc := range *s { + f := Frame(pc) + fmt.Fprintf(st, "\n%+v", f) + } + } + } +} + +func (s *stack) StackTrace() StackTrace { + f := make([]Frame, len(*s)) + for i := 0; i < len(f); i++ { + f[i] = Frame((*s)[i]) + } + return f +} + +func callers() *stack { + const depth = 32 + var pcs [depth]uintptr + n := runtime.Callers(3, pcs[:]) + var st stack = pcs[0:n] + return &st +} + +// funcname removes the path prefix component of a function's name reported by func.Name(). +func funcname(name string) string { + i := strings.LastIndex(name, "/") + name = name[i+1:] + i = strings.Index(name, ".") + return name[i+1:] +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/.gitmodules b/vendor/github.com/santhosh-tekuri/jsonschema/v6/.gitmodules new file mode 100644 index 00000000..d14f5ea7 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/.gitmodules @@ -0,0 +1,4 @@ +[submodule "testdata/JSON-Schema-Test-Suite"] + path = testdata/JSON-Schema-Test-Suite + url = https://github.com/json-schema-org/JSON-Schema-Test-Suite.git + branch = main diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/.golangci.yml b/vendor/github.com/santhosh-tekuri/jsonschema/v6/.golangci.yml new file mode 100644 index 00000000..6534d531 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/.golangci.yml @@ -0,0 +1,7 @@ +version: "2" +linters: + enable: + - nakedret + - errname + - godot + - misspell diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/.pre-commit-hooks.yaml b/vendor/github.com/santhosh-tekuri/jsonschema/v6/.pre-commit-hooks.yaml new file mode 100644 index 00000000..695b502e --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/.pre-commit-hooks.yaml @@ -0,0 +1,7 @@ +- id: jsonschema-validate + name: Validate JSON against JSON Schema + description: ensure json files follow specified JSON Schema + entry: jv + language: golang + additional_dependencies: + - ./cmd/jv diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/.swp b/vendor/github.com/santhosh-tekuri/jsonschema/v6/.swp new file mode 100644 index 00000000..e5119003 Binary files /dev/null and b/vendor/github.com/santhosh-tekuri/jsonschema/v6/.swp differ diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/LICENSE b/vendor/github.com/santhosh-tekuri/jsonschema/v6/LICENSE new file mode 100644 index 00000000..19dc35b2 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/LICENSE @@ -0,0 +1,175 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. \ No newline at end of file diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/README.md b/vendor/github.com/santhosh-tekuri/jsonschema/v6/README.md new file mode 100644 index 00000000..1243b66c --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/README.md @@ -0,0 +1,88 @@ +# jsonschema v6.0.2 + +[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) +[![GoDoc](https://godoc.org/github.com/santhosh-tekuri/jsonschema?status.svg)](https://pkg.go.dev/github.com/santhosh-tekuri/jsonschema/v6) +[![Go Report Card](https://goreportcard.com/badge/github.com/santhosh-tekuri/jsonschema/v6)](https://goreportcard.com/report/github.com/santhosh-tekuri/jsonschema/v6) +[![Build Status](https://github.com/santhosh-tekuri/jsonschema/actions/workflows/go.yaml/badge.svg?branch=boon)](https://github.com/santhosh-tekuri/jsonschema/actions/workflows/go.yaml) +[![codecov](https://codecov.io/gh/santhosh-tekuri/jsonschema/branch/boon/graph/badge.svg?token=JMVj1pFT2l)](https://codecov.io/gh/santhosh-tekuri/jsonschema/tree/boon) + +see [godoc](https://pkg.go.dev/github.com/santhosh-tekuri/jsonschema/v6) for examples + +## Library Features + +- [x] pass [JSON-Schema-Test-Suite](https://github.com/json-schema-org/JSON-Schema-Test-Suite) excluding optional(compare with other impls at [bowtie](https://bowtie-json-schema.github.io/bowtie/#)) + - [x] [![draft-04](https://img.shields.io/endpoint?url=https://bowtie.report/badges/go-jsonschema/compliance/draft4.json)](https://bowtie.report/#/dialects/draft4) + - [x] [![draft-06](https://img.shields.io/endpoint?url=https://bowtie.report/badges/go-jsonschema/compliance/draft6.json)](https://bowtie.report/#/dialects/draft6) + - [x] [![draft-07](https://img.shields.io/endpoint?url=https://bowtie.report/badges/go-jsonschema/compliance/draft7.json)](https://bowtie.report/#/dialects/draft7) + - [x] [![draft/2019-09](https://img.shields.io/endpoint?url=https://bowtie.report/badges/go-jsonschema/compliance/draft2019-09.json)](https://bowtie.report/#/dialects/draft2019-09) + - [x] [![draft/2020-12](https://img.shields.io/endpoint?url=https://bowtie.report/badges/go-jsonschema/compliance/draft2020-12.json)](https://bowtie.report/#/dialects/draft2020-12) +- [x] detect infinite loop traps + - [x] `$schema` cycle + - [x] validation cycle +- [x] custom `$schema` url +- [x] vocabulary based validation +- [x] custom regex engine +- [x] format assertions + - [x] flag to enable in draft >= 2019-09 + - [x] custom format registration + - [x] built-in formats + - [x] regex, uuid + - [x] ipv4, ipv6 + - [x] hostname, email + - [x] date, time, date-time, duration + - [x] json-pointer, relative-json-pointer + - [x] uri, uri-reference, uri-template + - [x] iri, iri-reference + - [x] period, semver +- [x] content assertions + - [x] flag to enable in draft >= 7 + - [x] contentEncoding + - [x] base64 + - [x] custom + - [x] contentMediaType + - [x] application/json + - [x] custom + - [x] contentSchema +- [x] errors + - [x] introspectable + - [x] hierarchy + - [x] alternative display with `#` + - [x] output + - [x] flag + - [x] basic + - [x] detailed +- [x] custom vocabulary + - enable via `$vocabulary` for draft >=2019-19 + - enable via flag for draft <= 7 +- [x] mixed dialect support + +## CLI v0.7.0 + +to install: `go install github.com/santhosh-tekuri/jsonschema/cmd/jv@latest` + +Note that the cli is versioned independently. you can see it in git tags `cmd/jv/v0.7.0` + +``` +Usage: jv [OPTIONS] SCHEMA [INSTANCE...] + +Options: + -c, --assert-content Enable content assertions with draft >= 7 + -f, --assert-format Enable format assertions with draft >= 2019 + --cacert pem-file Use the specified pem-file to verify the peer. The file may contain multiple CA certificates + -d, --draft version Draft version used when '$schema' is missing. Valid values 4, 6, 7, 2019, 2020 (default 2020) + -h, --help Print help information + -k, --insecure Use insecure TLS connection + -o, --output format Output format. Valid values simple, alt, flag, basic, detailed (default "simple") + -q, --quiet Do not print errors + -v, --version Print build information +``` + +- [x] exit code `1` for validation errors, `2` for usage errors +- [x] validate both schema and multiple instances +- [x] support both json and yaml files +- [x] support standard input, use `-` +- [x] quite mode with parsable output +- [x] http(s) url support + - [x] custom certs for validation, use `--cacert` + - [x] flag to skip certificate verification, use `--insecure` + diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/compiler.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/compiler.go new file mode 100644 index 00000000..4da73610 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/compiler.go @@ -0,0 +1,332 @@ +package jsonschema + +import ( + "fmt" + "regexp" + "slices" +) + +// Compiler compiles json schema into *Schema. +type Compiler struct { + schemas map[urlPtr]*Schema + roots *roots + formats map[string]*Format + decoders map[string]*Decoder + mediaTypes map[string]*MediaType + assertFormat bool + assertContent bool +} + +// NewCompiler create Compiler Object. +func NewCompiler() *Compiler { + return &Compiler{ + schemas: map[urlPtr]*Schema{}, + roots: newRoots(), + formats: map[string]*Format{}, + decoders: map[string]*Decoder{}, + mediaTypes: map[string]*MediaType{}, + assertFormat: false, + assertContent: false, + } +} + +// DefaultDraft overrides the draft used to +// compile schemas without `$schema` field. +// +// By default, this library uses the latest +// draft supported. +// +// The use of this option is HIGHLY encouraged +// to ensure continued correct operation of your +// schema. The current default value will not stay +// the same overtime. +func (c *Compiler) DefaultDraft(d *Draft) { + c.roots.defaultDraft = d +} + +// AssertFormat always enables format assertions. +// +// Default Behavior: +// for draft-07: enabled. +// for draft/2019-09: disabled unless metaschema says `format` vocabulary is required. +// for draft/2020-12: disabled unless metaschema says `format-assertion` vocabulary is required. +func (c *Compiler) AssertFormat() { + c.assertFormat = true +} + +// AssertContent enables content assertions. +// +// Content assertions include keywords: +// - contentEncoding +// - contentMediaType +// - contentSchema +// +// Default behavior is always disabled. +func (c *Compiler) AssertContent() { + c.assertContent = true +} + +// RegisterFormat registers custom format. +// +// NOTE: +// - "regex" format can not be overridden +// - format assertions are disabled for draft >= 2019-09 +// see [Compiler.AssertFormat] +func (c *Compiler) RegisterFormat(f *Format) { + if f.Name != "regex" { + c.formats[f.Name] = f + } +} + +// RegisterContentEncoding registers custom contentEncoding. +// +// NOTE: content assertions are disabled by default. +// see [Compiler.AssertContent]. +func (c *Compiler) RegisterContentEncoding(d *Decoder) { + c.decoders[d.Name] = d +} + +// RegisterContentMediaType registers custom contentMediaType. +// +// NOTE: content assertions are disabled by default. +// see [Compiler.AssertContent]. +func (c *Compiler) RegisterContentMediaType(mt *MediaType) { + c.mediaTypes[mt.Name] = mt +} + +// RegisterVocabulary registers custom vocabulary. +// +// NOTE: +// - vocabularies are disabled for draft >= 2019-09 +// see [Compiler.AssertVocabs] +func (c *Compiler) RegisterVocabulary(vocab *Vocabulary) { + c.roots.vocabularies[vocab.URL] = vocab +} + +// AssertVocabs always enables user-defined vocabularies assertions. +// +// Default Behavior: +// for draft-07: enabled. +// for draft/2019-09: disabled unless metaschema enables a vocabulary. +// for draft/2020-12: disabled unless metaschema enables a vocabulary. +func (c *Compiler) AssertVocabs() { + c.roots.assertVocabs = true +} + +// AddResource adds schema resource which gets used later in reference +// resolution. +// +// The argument url can be file path or url. Any fragment in url is ignored. +// The argument doc must be valid json value. +func (c *Compiler) AddResource(url string, doc any) error { + uf, err := absolute(url) + if err != nil { + return err + } + if isMeta(string(uf.url)) { + return &ResourceExistsError{string(uf.url)} + } + if !c.roots.loader.add(uf.url, doc) { + return &ResourceExistsError{string(uf.url)} + } + return nil +} + +// UseLoader overrides the default [URLLoader] used +// to load schema resources. +func (c *Compiler) UseLoader(loader URLLoader) { + c.roots.loader.loader = loader +} + +// UseRegexpEngine changes the regexp-engine used. +// By default it uses regexp package from go standard +// library. +// +// NOTE: must be called before compiling any schemas. +func (c *Compiler) UseRegexpEngine(engine RegexpEngine) { + if engine == nil { + engine = goRegexpCompile + } + c.roots.regexpEngine = engine +} + +func (c *Compiler) enqueue(q *queue, up urlPtr) *Schema { + if sch, ok := c.schemas[up]; ok { + // already got compiled + return sch + } + if sch := q.get(up); sch != nil { + return sch + } + sch := newSchema(up) + q.append(sch) + return sch +} + +// MustCompile is like [Compile] but panics if compilation fails. +// It simplifies safe initialization of global variables holding +// compiled schema. +func (c *Compiler) MustCompile(loc string) *Schema { + sch, err := c.Compile(loc) + if err != nil { + panic(fmt.Sprintf("jsonschema: Compile(%q): %v", loc, err)) + } + return sch +} + +// Compile compiles json-schema at given loc. +func (c *Compiler) Compile(loc string) (*Schema, error) { + uf, err := absolute(loc) + if err != nil { + return nil, err + } + up, err := c.roots.resolveFragment(*uf) + if err != nil { + return nil, err + } + return c.doCompile(up) +} + +func (c *Compiler) doCompile(up urlPtr) (*Schema, error) { + q := &queue{} + compiled := 0 + + c.enqueue(q, up) + for q.len() > compiled { + sch := q.at(compiled) + if err := c.roots.ensureSubschema(sch.up); err != nil { + return nil, err + } + r := c.roots.roots[sch.up.url] + v, err := sch.up.lookup(r.doc) + if err != nil { + return nil, err + } + if err := c.compileValue(v, sch, r, q); err != nil { + return nil, err + } + compiled++ + } + for _, sch := range *q { + c.schemas[sch.up] = sch + } + return c.schemas[up], nil +} + +func (c *Compiler) compileValue(v any, sch *Schema, r *root, q *queue) error { + res := r.resource(sch.up.ptr) + sch.DraftVersion = res.dialect.draft.version + + base := urlPtr{sch.up.url, res.ptr} + sch.resource = c.enqueue(q, base) + + // if resource, enqueue dynamic anchors for compilation + if sch.DraftVersion >= 2020 && sch.up == sch.resource.up { + res := r.resource(sch.up.ptr) + for anchor, anchorPtr := range res.anchors { + if slices.Contains(res.dynamicAnchors, anchor) { + up := urlPtr{sch.up.url, anchorPtr} + danchorSch := c.enqueue(q, up) + if sch.dynamicAnchors == nil { + sch.dynamicAnchors = map[string]*Schema{} + } + sch.dynamicAnchors[string(anchor)] = danchorSch + } + } + } + + switch v := v.(type) { + case bool: + sch.Bool = &v + case map[string]any: + if err := c.compileObject(v, sch, r, q); err != nil { + return err + } + } + + sch.allPropsEvaluated = sch.AdditionalProperties != nil + if sch.DraftVersion < 2020 { + sch.allItemsEvaluated = sch.AdditionalItems != nil + switch items := sch.Items.(type) { + case *Schema: + sch.allItemsEvaluated = true + case []*Schema: + sch.numItemsEvaluated = len(items) + } + } else { + sch.allItemsEvaluated = sch.Items2020 != nil + sch.numItemsEvaluated = len(sch.PrefixItems) + } + + return nil +} + +func (c *Compiler) compileObject(obj map[string]any, sch *Schema, r *root, q *queue) error { + if len(obj) == 0 { + b := true + sch.Bool = &b + return nil + } + oc := objCompiler{ + c: c, + obj: obj, + up: sch.up, + r: r, + res: r.resource(sch.up.ptr), + q: q, + } + return oc.compile(sch) +} + +// queue -- + +type queue []*Schema + +func (q *queue) append(sch *Schema) { + *q = append(*q, sch) +} + +func (q *queue) at(i int) *Schema { + return (*q)[i] +} + +func (q *queue) len() int { + return len(*q) +} + +func (q *queue) get(up urlPtr) *Schema { + i := slices.IndexFunc(*q, func(sch *Schema) bool { return sch.up == up }) + if i != -1 { + return (*q)[i] + } + return nil +} + +// regexp -- + +// Regexp is the representation of compiled regular expression. +type Regexp interface { + fmt.Stringer + + // MatchString reports whether the string s contains + // any match of the regular expression. + MatchString(string) bool +} + +// RegexpEngine parses a regular expression and returns, +// if successful, a Regexp object that can be used to +// match against text. +type RegexpEngine func(string) (Regexp, error) + +func (re RegexpEngine) validate(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + _, err := re(s) + return err +} + +func goRegexpCompile(s string) (Regexp, error) { + return regexp.Compile(s) +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/content.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/content.go new file mode 100644 index 00000000..8d62e58b --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/content.go @@ -0,0 +1,51 @@ +package jsonschema + +import ( + "bytes" + "encoding/base64" + "encoding/json" +) + +// Decoder specifies how to decode specific contentEncoding. +type Decoder struct { + // Name of contentEncoding. + Name string + // Decode given string to byte array. + Decode func(string) ([]byte, error) +} + +var decoders = map[string]*Decoder{ + "base64": { + Name: "base64", + Decode: func(s string) ([]byte, error) { + return base64.StdEncoding.DecodeString(s) + }, + }, +} + +// MediaType specified how to validate bytes against specific contentMediaType. +type MediaType struct { + // Name of contentMediaType. + Name string + + // Validate checks whether bytes conform to this mediatype. + Validate func([]byte) error + + // UnmarshalJSON unmarshals bytes into json value. + // This must be nil if this mediatype is not compatible + // with json. + UnmarshalJSON func([]byte) (any, error) +} + +var mediaTypes = map[string]*MediaType{ + "application/json": { + Name: "application/json", + Validate: func(b []byte) error { + var v any + return json.Unmarshal(b, &v) + }, + UnmarshalJSON: func(b []byte) (any, error) { + return UnmarshalJSON(bytes.NewReader(b)) + }, + }, +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/draft.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/draft.go new file mode 100644 index 00000000..fd09bae8 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/draft.go @@ -0,0 +1,360 @@ +package jsonschema + +import ( + "fmt" + "slices" + "strings" +) + +// A Draft represents json-schema specification. +type Draft struct { + version int + url string + sch *Schema + id string // property name used to represent id + subschemas []SchemaPath // locations of subschemas + vocabPrefix string // prefix used for vocabulary + allVocabs map[string]*Schema // names of supported vocabs with its schemas + defaultVocabs []string // names of default vocabs +} + +// String returns the specification url. +func (d *Draft) String() string { + return d.url +} + +var ( + Draft4 = &Draft{ + version: 4, + url: "http://json-schema.org/draft-04/schema", + id: "id", + subschemas: []SchemaPath{ + // type agonistic + schemaPath("definitions/*"), + schemaPath("not"), + schemaPath("allOf/[]"), + schemaPath("anyOf/[]"), + schemaPath("oneOf/[]"), + // object + schemaPath("properties/*"), + schemaPath("additionalProperties"), + schemaPath("patternProperties/*"), + // array + schemaPath("items"), + schemaPath("items/[]"), + schemaPath("additionalItems"), + schemaPath("dependencies/*"), + }, + vocabPrefix: "", + allVocabs: map[string]*Schema{}, + defaultVocabs: []string{}, + } + + Draft6 = &Draft{ + version: 6, + url: "http://json-schema.org/draft-06/schema", + id: "$id", + subschemas: joinSubschemas(Draft4.subschemas, + schemaPath("propertyNames"), + schemaPath("contains"), + ), + vocabPrefix: "", + allVocabs: map[string]*Schema{}, + defaultVocabs: []string{}, + } + + Draft7 = &Draft{ + version: 7, + url: "http://json-schema.org/draft-07/schema", + id: "$id", + subschemas: joinSubschemas(Draft6.subschemas, + schemaPath("if"), + schemaPath("then"), + schemaPath("else"), + ), + vocabPrefix: "", + allVocabs: map[string]*Schema{}, + defaultVocabs: []string{}, + } + + Draft2019 = &Draft{ + version: 2019, + url: "https://json-schema.org/draft/2019-09/schema", + id: "$id", + subschemas: joinSubschemas(Draft7.subschemas, + schemaPath("$defs/*"), + schemaPath("dependentSchemas/*"), + schemaPath("unevaluatedProperties"), + schemaPath("unevaluatedItems"), + schemaPath("contentSchema"), + ), + vocabPrefix: "https://json-schema.org/draft/2019-09/vocab/", + allVocabs: map[string]*Schema{ + "core": nil, + "applicator": nil, + "validation": nil, + "meta-data": nil, + "format": nil, + "content": nil, + }, + defaultVocabs: []string{"core", "applicator", "validation"}, + } + + Draft2020 = &Draft{ + version: 2020, + url: "https://json-schema.org/draft/2020-12/schema", + id: "$id", + subschemas: joinSubschemas(Draft2019.subschemas, + schemaPath("prefixItems/[]"), + ), + vocabPrefix: "https://json-schema.org/draft/2020-12/vocab/", + allVocabs: map[string]*Schema{ + "core": nil, + "applicator": nil, + "unevaluated": nil, + "validation": nil, + "meta-data": nil, + "format-annotation": nil, + "format-assertion": nil, + "content": nil, + }, + defaultVocabs: []string{"core", "applicator", "unevaluated", "validation"}, + } + + draftLatest = Draft2020 +) + +func init() { + c := NewCompiler() + c.AssertFormat() + for _, d := range []*Draft{Draft4, Draft6, Draft7, Draft2019, Draft2020} { + d.sch = c.MustCompile(d.url) + for name := range d.allVocabs { + d.allVocabs[name] = c.MustCompile(strings.TrimSuffix(d.url, "schema") + "meta/" + name) + } + } +} + +func draftFromURL(url string) *Draft { + u, frag := split(url) + if frag != "" { + return nil + } + u, ok := strings.CutPrefix(u, "http://") + if !ok { + u, _ = strings.CutPrefix(u, "https://") + } + switch u { + case "json-schema.org/schema": + return draftLatest + case "json-schema.org/draft/2020-12/schema": + return Draft2020 + case "json-schema.org/draft/2019-09/schema": + return Draft2019 + case "json-schema.org/draft-07/schema": + return Draft7 + case "json-schema.org/draft-06/schema": + return Draft6 + case "json-schema.org/draft-04/schema": + return Draft4 + default: + return nil + } +} + +func (d *Draft) getID(obj map[string]any) string { + if d.version < 2019 { + if _, ok := obj["$ref"]; ok { + // All other properties in a "$ref" object MUST be ignored + return "" + } + } + + id, ok := strVal(obj, d.id) + if !ok { + return "" + } + id, _ = split(id) // ignore fragment + return id +} + +func (d *Draft) getVocabs(url url, doc any, vocabularies map[string]*Vocabulary) ([]string, error) { + if d.version < 2019 { + return nil, nil + } + obj, ok := doc.(map[string]any) + if !ok { + return nil, nil + } + v, ok := obj["$vocabulary"] + if !ok { + return nil, nil + } + obj, ok = v.(map[string]any) + if !ok { + return nil, nil + } + + var vocabs []string + for vocab, reqd := range obj { + if reqd, ok := reqd.(bool); !ok || !reqd { + continue + } + name, ok := strings.CutPrefix(vocab, d.vocabPrefix) + if ok { + if _, ok := d.allVocabs[name]; ok { + if !slices.Contains(vocabs, name) { + vocabs = append(vocabs, name) + continue + } + } + } + if _, ok := vocabularies[vocab]; !ok { + return nil, &UnsupportedVocabularyError{url.String(), vocab} + } + if !slices.Contains(vocabs, vocab) { + vocabs = append(vocabs, vocab) + } + } + if !slices.Contains(vocabs, "core") { + vocabs = append(vocabs, "core") + } + return vocabs, nil +} + +// -- + +type dialect struct { + draft *Draft + vocabs []string // nil means use draft.defaultVocabs +} + +func (d *dialect) hasVocab(name string) bool { + if name == "core" || d.draft.version < 2019 { + return true + } + if d.vocabs != nil { + return slices.Contains(d.vocabs, name) + } + return slices.Contains(d.draft.defaultVocabs, name) +} + +func (d *dialect) activeVocabs(assertVocabs bool, vocabularies map[string]*Vocabulary) []string { + if len(vocabularies) == 0 { + return d.vocabs + } + if d.draft.version < 2019 { + assertVocabs = true + } + if !assertVocabs { + return d.vocabs + } + var vocabs []string + if d.vocabs == nil { + vocabs = slices.Clone(d.draft.defaultVocabs) + } else { + vocabs = slices.Clone(d.vocabs) + } + for vocab := range vocabularies { + if !slices.Contains(vocabs, vocab) { + vocabs = append(vocabs, vocab) + } + } + return vocabs +} + +func (d *dialect) getSchema(assertVocabs bool, vocabularies map[string]*Vocabulary) *Schema { + vocabs := d.activeVocabs(assertVocabs, vocabularies) + if vocabs == nil { + return d.draft.sch + } + + var allOf []*Schema + for _, vocab := range vocabs { + sch := d.draft.allVocabs[vocab] + if sch == nil { + if v, ok := vocabularies[vocab]; ok { + sch = v.Schema + } + } + if sch != nil { + allOf = append(allOf, sch) + } + } + if !slices.Contains(vocabs, "core") { + sch := d.draft.allVocabs["core"] + if sch == nil { + sch = d.draft.sch + } + allOf = append(allOf, sch) + } + sch := &Schema{ + Location: "urn:mem:metaschema", + up: urlPtr{url("urn:mem:metaschema"), ""}, + DraftVersion: d.draft.version, + AllOf: allOf, + } + sch.resource = sch + if sch.DraftVersion >= 2020 { + sch.DynamicAnchor = "meta" + sch.dynamicAnchors = map[string]*Schema{ + "meta": sch, + } + } + return sch +} + +// -- + +type ParseIDError struct { + URL string +} + +func (e *ParseIDError) Error() string { + return fmt.Sprintf("error in parsing id at %q", e.URL) +} + +// -- + +type ParseAnchorError struct { + URL string +} + +func (e *ParseAnchorError) Error() string { + return fmt.Sprintf("error in parsing anchor at %q", e.URL) +} + +// -- + +type DuplicateIDError struct { + ID string + URL string + Ptr1 string + Ptr2 string +} + +func (e *DuplicateIDError) Error() string { + return fmt.Sprintf("duplicate id %q in %q at %q and %q", e.ID, e.URL, e.Ptr1, e.Ptr2) +} + +// -- + +type DuplicateAnchorError struct { + Anchor string + URL string + Ptr1 string + Ptr2 string +} + +func (e *DuplicateAnchorError) Error() string { + return fmt.Sprintf("duplicate anchor %q in %q at %q and %q", e.Anchor, e.URL, e.Ptr1, e.Ptr2) +} + +// -- + +func joinSubschemas(a1 []SchemaPath, a2 ...SchemaPath) []SchemaPath { + var a []SchemaPath + a = append(a, a1...) + a = append(a, a2...) + return a +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/format.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/format.go new file mode 100644 index 00000000..b78b22e2 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/format.go @@ -0,0 +1,708 @@ +package jsonschema + +import ( + "net/netip" + gourl "net/url" + "strconv" + "strings" + "time" +) + +// Format defined specific format. +type Format struct { + // Name of format. + Name string + + // Validate checks if given value is of this format. + Validate func(v any) error +} + +var formats = map[string]*Format{ + "json-pointer": {"json-pointer", validateJSONPointer}, + "relative-json-pointer": {"relative-json-pointer", validateRelativeJSONPointer}, + "uuid": {"uuid", validateUUID}, + "duration": {"duration", validateDuration}, + "period": {"period", validatePeriod}, + "ipv4": {"ipv4", validateIPV4}, + "ipv6": {"ipv6", validateIPV6}, + "hostname": {"hostname", validateHostname}, + "email": {"email", validateEmail}, + "date": {"date", validateDate}, + "time": {"time", validateTime}, + "date-time": {"date-time", validateDateTime}, + "uri": {"uri", validateURI}, + "iri": {"iri", validateURI}, + "uri-reference": {"uri-reference", validateURIReference}, + "iri-reference": {"iri-reference", validateURIReference}, + "uri-template": {"uri-template", validateURITemplate}, + "semver": {"semver", validateSemver}, +} + +// see https://www.rfc-editor.org/rfc/rfc6901#section-3 +func validateJSONPointer(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + if s == "" { + return nil + } + if !strings.HasPrefix(s, "/") { + return LocalizableError("not starting with /") + } + for _, tok := range strings.Split(s, "/")[1:] { + escape := false + for _, ch := range tok { + if escape { + escape = false + if ch != '0' && ch != '1' { + return LocalizableError("~ must be followed by 0 or 1") + } + continue + } + if ch == '~' { + escape = true + continue + } + switch { + case ch >= '\x00' && ch <= '\x2E': + case ch >= '\x30' && ch <= '\x7D': + case ch >= '\x7F' && ch <= '\U0010FFFF': + default: + return LocalizableError("invalid character %q", ch) + } + } + if escape { + return LocalizableError("~ must be followed by 0 or 1") + } + } + return nil +} + +// see https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01#section-3 +func validateRelativeJSONPointer(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + + // start with non-negative-integer + numDigits := 0 + for _, ch := range s { + if ch >= '0' && ch <= '9' { + numDigits++ + } else { + break + } + } + if numDigits == 0 { + return LocalizableError("must start with non-negative integer") + } + if numDigits > 1 && strings.HasPrefix(s, "0") { + return LocalizableError("starts with zero") + } + s = s[numDigits:] + + // followed by either json-pointer or '#' + if s == "#" { + return nil + } + return validateJSONPointer(s) +} + +// see https://datatracker.ietf.org/doc/html/rfc4122#page-4 +func validateUUID(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + + hexGroups := []int{8, 4, 4, 4, 12} + groups := strings.Split(s, "-") + if len(groups) != len(hexGroups) { + return LocalizableError("must have %d elements", len(hexGroups)) + } + for i, group := range groups { + if len(group) != hexGroups[i] { + return LocalizableError("element %d must be %d characters long", i+1, hexGroups[i]) + } + for _, ch := range group { + switch { + case ch >= '0' && ch <= '9': + case ch >= 'a' && ch <= 'f': + case ch >= 'A' && ch <= 'F': + default: + return LocalizableError("non-hex character %q", ch) + } + } + } + return nil +} + +// see https://datatracker.ietf.org/doc/html/rfc3339#appendix-A +func validateDuration(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + + // must start with 'P' + s, ok = strings.CutPrefix(s, "P") + if !ok { + return LocalizableError("must start with P") + } + if s == "" { + return LocalizableError("nothing after P") + } + + // dur-week + if s, ok := strings.CutSuffix(s, "W"); ok { + if s == "" { + return LocalizableError("no number in week") + } + for _, ch := range s { + if ch < '0' || ch > '9' { + return LocalizableError("invalid week") + } + } + return nil + } + + allUnits := []string{"YMD", "HMS"} + for i, s := range strings.Split(s, "T") { + if i != 0 && s == "" { + return LocalizableError("no time elements") + } + if i >= len(allUnits) { + return LocalizableError("more than one T") + } + units := allUnits[i] + for s != "" { + digitCount := 0 + for _, ch := range s { + if ch >= '0' && ch <= '9' { + digitCount++ + } else { + break + } + } + if digitCount == 0 { + return LocalizableError("missing number") + } + s = s[digitCount:] + if s == "" { + return LocalizableError("missing unit") + } + unit := s[0] + j := strings.IndexByte(units, unit) + if j == -1 { + if strings.IndexByte(allUnits[i], unit) != -1 { + return LocalizableError("unit %q out of order", unit) + } + return LocalizableError("invalid unit %q", unit) + } + units = units[j+1:] + s = s[1:] + } + } + + return nil +} + +func validateIPV4(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + groups := strings.Split(s, ".") + if len(groups) != 4 { + return LocalizableError("expected four decimals") + } + for _, group := range groups { + if len(group) > 1 && group[0] == '0' { + return LocalizableError("leading zeros") + } + n, err := strconv.Atoi(group) + if err != nil { + return err + } + if n < 0 || n > 255 { + return LocalizableError("decimal must be between 0 and 255") + } + } + return nil +} + +func validateIPV6(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + if !strings.Contains(s, ":") { + return LocalizableError("missing colon") + } + addr, err := netip.ParseAddr(s) + if err != nil { + return err + } + if addr.Zone() != "" { + return LocalizableError("zone id is not a part of ipv6 address") + } + return nil +} + +// see https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names +func validateHostname(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + + // entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters + s = strings.TrimSuffix(s, ".") + if len(s) > 253 { + return LocalizableError("more than 253 characters long") + } + + // Hostnames are composed of series of labels concatenated with dots, as are all domain names + for _, label := range strings.Split(s, ".") { + // Each label must be from 1 to 63 characters long + if len(label) < 1 || len(label) > 63 { + return LocalizableError("label must be 1 to 63 characters long") + } + + // labels must not start or end with a hyphen + if strings.HasPrefix(label, "-") { + return LocalizableError("label starts with hyphen") + } + if strings.HasSuffix(label, "-") { + return LocalizableError("label ends with hyphen") + } + + // labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner), + // the digits '0' through '9', and the hyphen ('-') + for _, ch := range label { + switch { + case ch >= 'a' && ch <= 'z': + case ch >= 'A' && ch <= 'Z': + case ch >= '0' && ch <= '9': + case ch == '-': + default: + return LocalizableError("invalid character %q", ch) + } + } + } + return nil +} + +// see https://en.wikipedia.org/wiki/Email_address +func validateEmail(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + // entire email address to be no more than 254 characters long + if len(s) > 254 { + return LocalizableError("more than 255 characters long") + } + + // email address is generally recognized as having two parts joined with an at-sign + at := strings.LastIndexByte(s, '@') + if at == -1 { + return LocalizableError("missing @") + } + local, domain := s[:at], s[at+1:] + + // local part may be up to 64 characters long + if len(local) > 64 { + return LocalizableError("local part more than 64 characters long") + } + + if len(local) > 1 && strings.HasPrefix(local, `"`) && strings.HasPrefix(local, `"`) { + // quoted + local := local[1 : len(local)-1] + if strings.IndexByte(local, '\\') != -1 || strings.IndexByte(local, '"') != -1 { + return LocalizableError("backslash and quote are not allowed within quoted local part") + } + } else { + // unquoted + if strings.HasPrefix(local, ".") { + return LocalizableError("starts with dot") + } + if strings.HasSuffix(local, ".") { + return LocalizableError("ends with dot") + } + + // consecutive dots not allowed + if strings.Contains(local, "..") { + return LocalizableError("consecutive dots") + } + + // check allowed chars + for _, ch := range local { + switch { + case ch >= 'a' && ch <= 'z': + case ch >= 'A' && ch <= 'Z': + case ch >= '0' && ch <= '9': + case strings.ContainsRune(".!#$%&'*+-/=?^_`{|}~", ch): + default: + return LocalizableError("invalid character %q", ch) + } + } + } + + // domain if enclosed in brackets, must match an IP address + if strings.HasPrefix(domain, "[") && strings.HasSuffix(domain, "]") { + domain = domain[1 : len(domain)-1] + if rem, ok := strings.CutPrefix(domain, "IPv6:"); ok { + if err := validateIPV6(rem); err != nil { + return LocalizableError("invalid ipv6 address: %v", err) + } + return nil + } + if err := validateIPV4(domain); err != nil { + return LocalizableError("invalid ipv4 address: %v", err) + } + return nil + } + + // domain must match the requirements for a hostname + if err := validateHostname(domain); err != nil { + return LocalizableError("invalid domain: %v", err) + } + + return nil +} + +// see see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6 +func validateDate(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + _, err := time.Parse("2006-01-02", s) + return err +} + +// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6 +// NOTE: golang time package does not support leap seconds. +func validateTime(v any) error { + str, ok := v.(string) + if !ok { + return nil + } + + // min: hh:mm:ssZ + if len(str) < 9 { + return LocalizableError("less than 9 characters long") + } + if str[2] != ':' || str[5] != ':' { + return LocalizableError("missing colon in correct place") + } + + // parse hh:mm:ss + var hms []int + for _, tok := range strings.SplitN(str[:8], ":", 3) { + i, err := strconv.Atoi(tok) + if err != nil { + return LocalizableError("invalid hour/min/sec") + } + if i < 0 { + return LocalizableError("non-positive hour/min/sec") + } + hms = append(hms, i) + } + if len(hms) != 3 { + return LocalizableError("missing hour/min/sec") + } + h, m, s := hms[0], hms[1], hms[2] + if h > 23 || m > 59 || s > 60 { + return LocalizableError("hour/min/sec out of range") + } + str = str[8:] + + // parse sec-frac if present + if rem, ok := strings.CutPrefix(str, "."); ok { + numDigits := 0 + for _, ch := range rem { + if ch >= '0' && ch <= '9' { + numDigits++ + } else { + break + } + } + if numDigits == 0 { + return LocalizableError("no digits in second fraction") + } + str = rem[numDigits:] + } + + if str != "z" && str != "Z" { + // parse time-numoffset + if len(str) != 6 { + return LocalizableError("offset must be 6 characters long") + } + var sign int + switch str[0] { + case '+': + sign = -1 + case '-': + sign = +1 + default: + return LocalizableError("offset must begin with plus/minus") + } + str = str[1:] + if str[2] != ':' { + return LocalizableError("missing colon in offset in correct place") + } + + var zhm []int + for _, tok := range strings.SplitN(str, ":", 2) { + i, err := strconv.Atoi(tok) + if err != nil { + return LocalizableError("invalid hour/min in offset") + } + if i < 0 { + return LocalizableError("non-positive hour/min in offset") + } + zhm = append(zhm, i) + } + zh, zm := zhm[0], zhm[1] + if zh > 23 || zm > 59 { + return LocalizableError("hour/min in offset out of range") + } + + // apply timezone + hm := (h*60 + m) + sign*(zh*60+zm) + if hm < 0 { + hm += 24 * 60 + } + h, m = hm/60, hm%60 + } + + // check leap second + if s >= 60 && (h != 23 || m != 59) { + return LocalizableError("invalid leap second") + } + + return nil +} + +// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6 +func validateDateTime(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + + // min: yyyy-mm-ddThh:mm:ssZ + if len(s) < 20 { + return LocalizableError("less than 20 characters long") + } + + if s[10] != 't' && s[10] != 'T' { + return LocalizableError("11th character must be t or T") + } + if err := validateDate(s[:10]); err != nil { + return LocalizableError("invalid date element: %v", err) + } + if err := validateTime(s[11:]); err != nil { + return LocalizableError("invalid time element: %v", err) + } + return nil +} + +func parseURL(s string) (*gourl.URL, error) { + u, err := gourl.Parse(s) + if err != nil { + return nil, err + } + + // gourl does not validate ipv6 host address + hostName := u.Hostname() + if strings.Contains(hostName, ":") { + if !strings.Contains(u.Host, "[") || !strings.Contains(u.Host, "]") { + return nil, LocalizableError("ipv6 address not enclosed in brackets") + } + if err := validateIPV6(hostName); err != nil { + return nil, LocalizableError("invalid ipv6 address: %v", err) + } + } + + return u, nil +} + +func validateURI(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + u, err := parseURL(s) + if err != nil { + return err + } + if !u.IsAbs() { + return LocalizableError("relative url") + } + return nil +} + +func validateURIReference(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + if strings.Contains(s, `\`) { + return LocalizableError(`contains \`) + } + _, err := parseURL(s) + return err +} + +func validateURITemplate(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + u, err := parseURL(s) + if err != nil { + return err + } + for _, tok := range strings.Split(u.RawPath, "/") { + tok, err = decode(tok) + if err != nil { + return LocalizableError("percent decode failed: %v", err) + } + want := true + for _, ch := range tok { + var got bool + switch ch { + case '{': + got = true + case '}': + got = false + default: + continue + } + if got != want { + return LocalizableError("nested curly braces") + } + want = !want + } + if !want { + return LocalizableError("no matching closing brace") + } + } + return nil +} + +func validatePeriod(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + + slash := strings.IndexByte(s, '/') + if slash == -1 { + return LocalizableError("missing slash") + } + + start, end := s[:slash], s[slash+1:] + if strings.HasPrefix(start, "P") { + if err := validateDuration(start); err != nil { + return LocalizableError("invalid start duration: %v", err) + } + if err := validateDateTime(end); err != nil { + return LocalizableError("invalid end date-time: %v", err) + } + } else { + if err := validateDateTime(start); err != nil { + return LocalizableError("invalid start date-time: %v", err) + } + if strings.HasPrefix(end, "P") { + if err := validateDuration(end); err != nil { + return LocalizableError("invalid end duration: %v", err) + } + } else if err := validateDateTime(end); err != nil { + return LocalizableError("invalid end date-time: %v", err) + } + } + + return nil +} + +// see https://semver.org/#backusnaur-form-grammar-for-valid-semver-versions +func validateSemver(v any) error { + s, ok := v.(string) + if !ok { + return nil + } + + // build -- + if i := strings.IndexByte(s, '+'); i != -1 { + build := s[i+1:] + if build == "" { + return LocalizableError("build is empty") + } + for _, buildID := range strings.Split(build, ".") { + if buildID == "" { + return LocalizableError("build identifier is empty") + } + for _, ch := range buildID { + switch { + case ch >= '0' && ch <= '9': + case (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '-': + default: + return LocalizableError("invalid character %q in build identifier", ch) + } + } + } + s = s[:i] + } + + // pre-release -- + if i := strings.IndexByte(s, '-'); i != -1 { + preRelease := s[i+1:] + for _, preReleaseID := range strings.Split(preRelease, ".") { + if preReleaseID == "" { + return LocalizableError("pre-release identifier is empty") + } + allDigits := true + for _, ch := range preReleaseID { + switch { + case ch >= '0' && ch <= '9': + case (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '-': + allDigits = false + default: + return LocalizableError("invalid character %q in pre-release identifier", ch) + } + } + if allDigits && len(preReleaseID) > 1 && preReleaseID[0] == '0' { + return LocalizableError("pre-release numeric identifier starts with zero") + } + } + s = s[:i] + } + + // versionCore -- + versions := strings.Split(s, ".") + if len(versions) != 3 { + return LocalizableError("versionCore must have 3 numbers separated by dot") + } + names := []string{"major", "minor", "patch"} + for i, version := range versions { + if version == "" { + return LocalizableError("%s is empty", names[i]) + } + if len(version) > 1 && version[0] == '0' { + return LocalizableError("%s starts with zero", names[i]) + } + for _, ch := range version { + if ch < '0' || ch > '9' { + return LocalizableError("%s contains non-digit", names[i]) + } + } + } + + return nil +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/go.work b/vendor/github.com/santhosh-tekuri/jsonschema/v6/go.work new file mode 100644 index 00000000..e7f4d93d --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/go.work @@ -0,0 +1,8 @@ +go 1.21.1 + +use ( + . + ./cmd/jv +) + +// replace github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 => ./ diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/go.work.sum b/vendor/github.com/santhosh-tekuri/jsonschema/v6/go.work.sum new file mode 100644 index 00000000..2b5b811d --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/go.work.sum @@ -0,0 +1,4 @@ +github.com/santhosh-tekuri/jsonschema/v6 v6.0.1/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/kind/kind.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/kind/kind.go new file mode 100644 index 00000000..a37fb0b9 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/kind/kind.go @@ -0,0 +1,651 @@ +package kind + +import ( + "fmt" + "math/big" + "strings" + + "golang.org/x/text/message" +) + +// -- + +type InvalidJsonValue struct { + Value any +} + +func (*InvalidJsonValue) KeywordPath() []string { + return nil +} + +func (k *InvalidJsonValue) LocalizedString(p *message.Printer) string { + return p.Sprintf("invalid jsonType %T", k.Value) +} + +// -- + +type Schema struct { + Location string +} + +func (*Schema) KeywordPath() []string { + return nil +} + +func (k *Schema) LocalizedString(p *message.Printer) string { + return p.Sprintf("jsonschema validation failed with %s", quote(k.Location)) +} + +// -- + +type Group struct{} + +func (*Group) KeywordPath() []string { + return nil +} + +func (*Group) LocalizedString(p *message.Printer) string { + return p.Sprintf("validation failed") +} + +// -- + +type Not struct{} + +func (*Not) KeywordPath() []string { + return nil +} + +func (*Not) LocalizedString(p *message.Printer) string { + return p.Sprintf("'not' failed") +} + +// -- + +type AllOf struct{} + +func (*AllOf) KeywordPath() []string { + return []string{"allOf"} +} + +func (*AllOf) LocalizedString(p *message.Printer) string { + return p.Sprintf("'allOf' failed") +} + +// -- + +type AnyOf struct{} + +func (*AnyOf) KeywordPath() []string { + return []string{"anyOf"} +} + +func (*AnyOf) LocalizedString(p *message.Printer) string { + return p.Sprintf("'anyOf' failed") +} + +// -- + +type OneOf struct { + // Subschemas gives indexes of Subschemas that have matched. + // Value nil, means none of the subschemas matched. + Subschemas []int +} + +func (*OneOf) KeywordPath() []string { + return []string{"oneOf"} +} + +func (k *OneOf) LocalizedString(p *message.Printer) string { + if len(k.Subschemas) == 0 { + return p.Sprintf("'oneOf' failed, none matched") + } + return p.Sprintf("'oneOf' failed, subschemas %d, %d matched", k.Subschemas[0], k.Subschemas[1]) +} + +//-- + +type FalseSchema struct{} + +func (*FalseSchema) KeywordPath() []string { + return nil +} + +func (*FalseSchema) LocalizedString(p *message.Printer) string { + return p.Sprintf("false schema") +} + +// -- + +type RefCycle struct { + URL string + KeywordLocation1 string + KeywordLocation2 string +} + +func (*RefCycle) KeywordPath() []string { + return nil +} + +func (k *RefCycle) LocalizedString(p *message.Printer) string { + return p.Sprintf("both %s and %s resolve to %q causing reference cycle", k.KeywordLocation1, k.KeywordLocation2, k.URL) +} + +// -- + +type Type struct { + Got string + Want []string +} + +func (*Type) KeywordPath() []string { + return []string{"type"} +} + +func (k *Type) LocalizedString(p *message.Printer) string { + want := strings.Join(k.Want, " or ") + return p.Sprintf("got %s, want %s", k.Got, want) +} + +// -- + +type Enum struct { + Got any + Want []any +} + +// KeywordPath implements jsonschema.ErrorKind. +func (*Enum) KeywordPath() []string { + return []string{"enum"} +} + +func (k *Enum) LocalizedString(p *message.Printer) string { + allPrimitive := true +loop: + for _, item := range k.Want { + switch item.(type) { + case []any, map[string]any: + allPrimitive = false + break loop + } + } + if allPrimitive { + if len(k.Want) == 1 { + return p.Sprintf("value must be %s", display(k.Want[0])) + } + var want []string + for _, v := range k.Want { + want = append(want, display(v)) + } + return p.Sprintf("value must be one of %s", strings.Join(want, ", ")) + } + return p.Sprintf("'enum' failed") +} + +// -- + +type Const struct { + Got any + Want any +} + +func (*Const) KeywordPath() []string { + return []string{"const"} +} + +func (k *Const) LocalizedString(p *message.Printer) string { + switch want := k.Want.(type) { + case []any, map[string]any: + return p.Sprintf("'const' failed") + default: + return p.Sprintf("value must be %s", display(want)) + } +} + +// -- + +type Format struct { + Got any + Want string + Err error +} + +func (*Format) KeywordPath() []string { + return []string{"format"} +} + +func (k *Format) LocalizedString(p *message.Printer) string { + return p.Sprintf("%s is not valid %s: %v", display(k.Got), k.Want, localizedError(k.Err, p)) +} + +// -- + +type Reference struct { + Keyword string + URL string +} + +func (k *Reference) KeywordPath() []string { + return []string{k.Keyword} +} + +func (*Reference) LocalizedString(p *message.Printer) string { + return p.Sprintf("validation failed") +} + +// -- + +type MinProperties struct { + Got, Want int +} + +func (*MinProperties) KeywordPath() []string { + return []string{"minProperties"} +} + +func (k *MinProperties) LocalizedString(p *message.Printer) string { + return p.Sprintf("minProperties: got %d, want %d", k.Got, k.Want) +} + +// -- + +type MaxProperties struct { + Got, Want int +} + +func (*MaxProperties) KeywordPath() []string { + return []string{"maxProperties"} +} + +func (k *MaxProperties) LocalizedString(p *message.Printer) string { + return p.Sprintf("maxProperties: got %d, want %d", k.Got, k.Want) +} + +// -- + +type MinItems struct { + Got, Want int +} + +func (*MinItems) KeywordPath() []string { + return []string{"minItems"} +} + +func (k *MinItems) LocalizedString(p *message.Printer) string { + return p.Sprintf("minItems: got %d, want %d", k.Got, k.Want) +} + +// -- + +type MaxItems struct { + Got, Want int +} + +func (*MaxItems) KeywordPath() []string { + return []string{"maxItems"} +} + +func (k *MaxItems) LocalizedString(p *message.Printer) string { + return p.Sprintf("maxItems: got %d, want %d", k.Got, k.Want) +} + +// -- + +type AdditionalItems struct { + Count int +} + +func (*AdditionalItems) KeywordPath() []string { + return []string{"additionalItems"} +} + +func (k *AdditionalItems) LocalizedString(p *message.Printer) string { + return p.Sprintf("last %d additionalItem(s) not allowed", k.Count) +} + +// -- + +type Required struct { + Missing []string +} + +func (*Required) KeywordPath() []string { + return []string{"required"} +} + +func (k *Required) LocalizedString(p *message.Printer) string { + if len(k.Missing) == 1 { + return p.Sprintf("missing property %s", quote(k.Missing[0])) + } + return p.Sprintf("missing properties %s", joinQuoted(k.Missing, ", ")) +} + +// -- + +type Dependency struct { + Prop string // dependency of prop that failed + Missing []string // missing props +} + +func (k *Dependency) KeywordPath() []string { + return []string{"dependency", k.Prop} +} + +func (k *Dependency) LocalizedString(p *message.Printer) string { + return p.Sprintf("properties %s required, if %s exists", joinQuoted(k.Missing, ", "), quote(k.Prop)) +} + +// -- + +type DependentRequired struct { + Prop string // dependency of prop that failed + Missing []string // missing props +} + +func (k *DependentRequired) KeywordPath() []string { + return []string{"dependentRequired", k.Prop} +} + +func (k *DependentRequired) LocalizedString(p *message.Printer) string { + return p.Sprintf("properties %s required, if %s exists", joinQuoted(k.Missing, ", "), quote(k.Prop)) +} + +// -- + +type AdditionalProperties struct { + Properties []string +} + +func (*AdditionalProperties) KeywordPath() []string { + return []string{"additionalProperties"} +} + +func (k *AdditionalProperties) LocalizedString(p *message.Printer) string { + return p.Sprintf("additional properties %s not allowed", joinQuoted(k.Properties, ", ")) +} + +// -- + +type PropertyNames struct { + Property string +} + +func (*PropertyNames) KeywordPath() []string { + return []string{"propertyNames"} +} + +func (k *PropertyNames) LocalizedString(p *message.Printer) string { + return p.Sprintf("invalid propertyName %s", quote(k.Property)) +} + +// -- + +type UniqueItems struct { + Duplicates [2]int +} + +func (*UniqueItems) KeywordPath() []string { + return []string{"uniqueItems"} +} + +func (k *UniqueItems) LocalizedString(p *message.Printer) string { + return p.Sprintf("items at %d and %d are equal", k.Duplicates[0], k.Duplicates[1]) +} + +// -- + +type Contains struct{} + +func (*Contains) KeywordPath() []string { + return []string{"contains"} +} + +func (*Contains) LocalizedString(p *message.Printer) string { + return p.Sprintf("no items match contains schema") +} + +// -- + +type MinContains struct { + Got []int + Want int +} + +func (*MinContains) KeywordPath() []string { + return []string{"minContains"} +} + +func (k *MinContains) LocalizedString(p *message.Printer) string { + if len(k.Got) == 0 { + return p.Sprintf("min %d items required to match contains schema, but none matched", k.Want) + } else { + got := fmt.Sprintf("%v", k.Got) + return p.Sprintf("min %d items required to match contains schema, but matched %d items at %v", k.Want, len(k.Got), got[1:len(got)-1]) + } +} + +// -- + +type MaxContains struct { + Got []int + Want int +} + +func (*MaxContains) KeywordPath() []string { + return []string{"maxContains"} +} + +func (k *MaxContains) LocalizedString(p *message.Printer) string { + got := fmt.Sprintf("%v", k.Got) + return p.Sprintf("max %d items required to match contains schema, but matched %d items at %v", k.Want, len(k.Got), got[1:len(got)-1]) +} + +// -- + +type MinLength struct { + Got, Want int +} + +func (*MinLength) KeywordPath() []string { + return []string{"minLength"} +} + +func (k *MinLength) LocalizedString(p *message.Printer) string { + return p.Sprintf("minLength: got %d, want %d", k.Got, k.Want) +} + +// -- + +type MaxLength struct { + Got, Want int +} + +func (*MaxLength) KeywordPath() []string { + return []string{"maxLength"} +} + +func (k *MaxLength) LocalizedString(p *message.Printer) string { + return p.Sprintf("maxLength: got %d, want %d", k.Got, k.Want) +} + +// -- + +type Pattern struct { + Got string + Want string +} + +func (*Pattern) KeywordPath() []string { + return []string{"pattern"} +} + +func (k *Pattern) LocalizedString(p *message.Printer) string { + return p.Sprintf("%s does not match pattern %s", quote(k.Got), quote(k.Want)) +} + +// -- + +type ContentEncoding struct { + Want string + Err error +} + +func (*ContentEncoding) KeywordPath() []string { + return []string{"contentEncoding"} +} + +func (k *ContentEncoding) LocalizedString(p *message.Printer) string { + return p.Sprintf("value is not %s encoded: %v", quote(k.Want), localizedError(k.Err, p)) +} + +// -- + +type ContentMediaType struct { + Got []byte + Want string + Err error +} + +func (*ContentMediaType) KeywordPath() []string { + return []string{"contentMediaType"} +} + +func (k *ContentMediaType) LocalizedString(p *message.Printer) string { + return p.Sprintf("value if not of mediatype %s: %v", quote(k.Want), k.Err) +} + +// -- + +type ContentSchema struct{} + +func (*ContentSchema) KeywordPath() []string { + return []string{"contentSchema"} +} + +func (*ContentSchema) LocalizedString(p *message.Printer) string { + return p.Sprintf("'contentSchema' failed") +} + +// -- + +type Minimum struct { + Got *big.Rat + Want *big.Rat +} + +func (*Minimum) KeywordPath() []string { + return []string{"minimum"} +} + +func (k *Minimum) LocalizedString(p *message.Printer) string { + got, _ := k.Got.Float64() + want, _ := k.Want.Float64() + return p.Sprintf("minimum: got %v, want %v", got, want) +} + +// -- + +type Maximum struct { + Got *big.Rat + Want *big.Rat +} + +func (*Maximum) KeywordPath() []string { + return []string{"maximum"} +} + +func (k *Maximum) LocalizedString(p *message.Printer) string { + got, _ := k.Got.Float64() + want, _ := k.Want.Float64() + return p.Sprintf("maximum: got %v, want %v", got, want) +} + +// -- + +type ExclusiveMinimum struct { + Got *big.Rat + Want *big.Rat +} + +func (*ExclusiveMinimum) KeywordPath() []string { + return []string{"exclusiveMinimum"} +} + +func (k *ExclusiveMinimum) LocalizedString(p *message.Printer) string { + got, _ := k.Got.Float64() + want, _ := k.Want.Float64() + return p.Sprintf("exclusiveMinimum: got %v, want %v", got, want) +} + +// -- + +type ExclusiveMaximum struct { + Got *big.Rat + Want *big.Rat +} + +func (*ExclusiveMaximum) KeywordPath() []string { + return []string{"exclusiveMaximum"} +} + +func (k *ExclusiveMaximum) LocalizedString(p *message.Printer) string { + got, _ := k.Got.Float64() + want, _ := k.Want.Float64() + return p.Sprintf("exclusiveMaximum: got %v, want %v", got, want) +} + +// -- + +type MultipleOf struct { + Got *big.Rat + Want *big.Rat +} + +func (*MultipleOf) KeywordPath() []string { + return []string{"multipleOf"} +} + +func (k *MultipleOf) LocalizedString(p *message.Printer) string { + got, _ := k.Got.Float64() + want, _ := k.Want.Float64() + return p.Sprintf("multipleOf: got %v, want %v", got, want) +} + +// -- + +func quote(s string) string { + s = fmt.Sprintf("%q", s) + s = strings.ReplaceAll(s, `\"`, `"`) + s = strings.ReplaceAll(s, `'`, `\'`) + return "'" + s[1:len(s)-1] + "'" +} + +func joinQuoted(arr []string, sep string) string { + var sb strings.Builder + for _, s := range arr { + if sb.Len() > 0 { + sb.WriteString(sep) + } + sb.WriteString(quote(s)) + } + return sb.String() +} + +// to be used only for primitive. +func display(v any) string { + switch v := v.(type) { + case string: + return quote(v) + case []any, map[string]any: + return "value" + default: + return fmt.Sprintf("%v", v) + } +} + +func localizedError(err error, p *message.Printer) string { + if err, ok := err.(interface{ LocalizedError(*message.Printer) string }); ok { + return err.LocalizedError(p) + } + return err.Error() +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/loader.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/loader.go new file mode 100644 index 00000000..ce0170e2 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/loader.go @@ -0,0 +1,266 @@ +package jsonschema + +import ( + "embed" + "encoding/json" + "errors" + "fmt" + "io" + "io/fs" + gourl "net/url" + "os" + "path/filepath" + "runtime" + "strings" +) + +// URLLoader knows how to load json from given url. +type URLLoader interface { + // Load loads json from given absolute url. + Load(url string) (any, error) +} + +// -- + +// FileLoader loads json file url. +type FileLoader struct{} + +func (l FileLoader) Load(url string) (any, error) { + path, err := l.ToFile(url) + if err != nil { + return nil, err + } + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + return UnmarshalJSON(f) +} + +// ToFile is helper method to convert file url to file path. +func (l FileLoader) ToFile(url string) (string, error) { + u, err := gourl.Parse(url) + if err != nil { + return "", err + } + if u.Scheme != "file" { + return "", fmt.Errorf("invalid file url: %s", u) + } + path := u.Path + if runtime.GOOS == "windows" { + path = strings.TrimPrefix(path, "/") + path = filepath.FromSlash(path) + } + return path, nil +} + +// -- + +// SchemeURLLoader delegates to other [URLLoaders] +// based on url scheme. +type SchemeURLLoader map[string]URLLoader + +func (l SchemeURLLoader) Load(url string) (any, error) { + u, err := gourl.Parse(url) + if err != nil { + return nil, err + } + ll, ok := l[u.Scheme] + if !ok { + return nil, &UnsupportedURLSchemeError{u.String()} + } + return ll.Load(url) +} + +// -- + +//go:embed metaschemas +var metaFS embed.FS + +func openMeta(url string) (fs.File, error) { + u, meta := strings.CutPrefix(url, "http://json-schema.org/") + if !meta { + u, meta = strings.CutPrefix(url, "https://json-schema.org/") + } + if meta { + if u == "schema" { + return openMeta(draftLatest.url) + } + f, err := metaFS.Open("metaschemas/" + u) + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + return nil, err + } + return f, err + } + return nil, nil + +} + +func isMeta(url string) bool { + f, err := openMeta(url) + if err != nil { + return true + } + if f != nil { + f.Close() + return true + } + return false +} + +func loadMeta(url string) (any, error) { + f, err := openMeta(url) + if err != nil { + return nil, err + } + if f == nil { + return nil, nil + } + defer f.Close() + return UnmarshalJSON(f) +} + +// -- + +type defaultLoader struct { + docs map[url]any // docs loaded so far + loader URLLoader +} + +func (l *defaultLoader) add(url url, doc any) bool { + if _, ok := l.docs[url]; ok { + return false + } + l.docs[url] = doc + return true +} + +func (l *defaultLoader) load(url url) (any, error) { + if doc, ok := l.docs[url]; ok { + return doc, nil + } + doc, err := loadMeta(url.String()) + if err != nil { + return nil, err + } + if doc != nil { + l.add(url, doc) + return doc, nil + } + if l.loader == nil { + return nil, &LoadURLError{url.String(), errors.New("no URLLoader set")} + } + doc, err = l.loader.Load(url.String()) + if err != nil { + return nil, &LoadURLError{URL: url.String(), Err: err} + } + l.add(url, doc) + return doc, nil +} + +func (l *defaultLoader) getDraft(up urlPtr, doc any, defaultDraft *Draft, cycle map[url]struct{}) (*Draft, error) { + obj, ok := doc.(map[string]any) + if !ok { + return defaultDraft, nil + } + sch, ok := strVal(obj, "$schema") + if !ok { + return defaultDraft, nil + } + if draft := draftFromURL(sch); draft != nil { + return draft, nil + } + sch, _ = split(sch) + if _, err := gourl.Parse(sch); err != nil { + return nil, &InvalidMetaSchemaURLError{up.String(), err} + } + schUrl := url(sch) + if up.ptr.isEmpty() && schUrl == up.url { + return nil, &UnsupportedDraftError{schUrl.String()} + } + if _, ok := cycle[schUrl]; ok { + return nil, &MetaSchemaCycleError{schUrl.String()} + } + cycle[schUrl] = struct{}{} + doc, err := l.load(schUrl) + if err != nil { + return nil, err + } + return l.getDraft(urlPtr{schUrl, ""}, doc, defaultDraft, cycle) +} + +func (l *defaultLoader) getMetaVocabs(doc any, draft *Draft, vocabularies map[string]*Vocabulary) ([]string, error) { + obj, ok := doc.(map[string]any) + if !ok { + return nil, nil + } + sch, ok := strVal(obj, "$schema") + if !ok { + return nil, nil + } + if draft := draftFromURL(sch); draft != nil { + return nil, nil + } + sch, _ = split(sch) + if _, err := gourl.Parse(sch); err != nil { + return nil, &ParseURLError{sch, err} + } + schUrl := url(sch) + doc, err := l.load(schUrl) + if err != nil { + return nil, err + } + return draft.getVocabs(schUrl, doc, vocabularies) +} + +// -- + +type LoadURLError struct { + URL string + Err error +} + +func (e *LoadURLError) Error() string { + return fmt.Sprintf("failing loading %q: %v", e.URL, e.Err) +} + +// -- + +type UnsupportedURLSchemeError struct { + url string +} + +func (e *UnsupportedURLSchemeError) Error() string { + return fmt.Sprintf("no URLLoader registered for %q", e.url) +} + +// -- + +type ResourceExistsError struct { + url string +} + +func (e *ResourceExistsError) Error() string { + return fmt.Sprintf("resource for %q already exists", e.url) +} + +// -- + +// UnmarshalJSON unmarshals into [any] without losing +// number precision using [json.Number]. +func UnmarshalJSON(r io.Reader) (any, error) { + decoder := json.NewDecoder(r) + decoder.UseNumber() + var doc any + if err := decoder.Decode(&doc); err != nil { + return nil, err + } + if _, err := decoder.Token(); err == nil || err != io.EOF { + return nil, fmt.Errorf("invalid character after top-level value") + } + return doc, nil +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft-04/schema b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft-04/schema new file mode 100644 index 00000000..b2a7ff0f --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft-04/schema @@ -0,0 +1,151 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "description": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "positiveInteger": { + "type": "integer", + "minimum": 0 + }, + "positiveIntegerDefault0": { + "allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ] + }, + "simpleTypes": { + "enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "minItems": 1, + "uniqueItems": true + } + }, + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uriref" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "multipleOf": { + "type": "number", + "minimum": 0, + "exclusiveMinimum": true + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "boolean", + "default": false + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "boolean", + "default": false + }, + "maxLength": { "$ref": "#/definitions/positiveInteger" }, + "minLength": { "$ref": "#/definitions/positiveIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { + "anyOf": [ + { "type": "boolean" }, + { "$ref": "#" } + ], + "default": {} + }, + "items": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/schemaArray" } + ], + "default": {} + }, + "maxItems": { "$ref": "#/definitions/positiveInteger" }, + "minItems": { "$ref": "#/definitions/positiveIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxProperties": { "$ref": "#/definitions/positiveInteger" }, + "minProperties": { "$ref": "#/definitions/positiveIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { + "anyOf": [ + { "type": "boolean" }, + { "$ref": "#" } + ], + "default": {} + }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/stringArray" } + ] + } + }, + "enum": { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + { "$ref": "#/definitions/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" }, + "format": { "type": "string" }, + "$ref": { "type": "string" } + }, + "dependencies": { + "exclusiveMaximum": [ "maximum" ], + "exclusiveMinimum": [ "minimum" ] + }, + "default": {} +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft-06/schema b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft-06/schema new file mode 100644 index 00000000..fa22ad1b --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft-06/schema @@ -0,0 +1,150 @@ +{ + "$schema": "http://json-schema.org/draft-06/schema#", + "$id": "http://json-schema.org/draft-06/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [ + { "$ref": "#/definitions/nonNegativeInteger" }, + { "default": 0 } + ] + }, + "simpleTypes": { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, + "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { "$ref": "#" }, + "items": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/schemaArray" } + ], + "default": {} + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": { "$ref": "#" }, + "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, + "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { "$ref": "#" }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/stringArray" } + ] + } + }, + "propertyNames": { "$ref": "#" }, + "const": {}, + "enum": { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + { "$ref": "#/definitions/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": { "type": "string" }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }, + "default": {} +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft-07/schema b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft-07/schema new file mode 100644 index 00000000..326759a6 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft-07/schema @@ -0,0 +1,172 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "http://json-schema.org/draft-07/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [ + { "$ref": "#/definitions/nonNegativeInteger" }, + { "default": 0 } + ] + }, + "simpleTypes": { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, + "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { "$ref": "#" }, + "items": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/schemaArray" } + ], + "default": true + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": { "$ref": "#" }, + "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, + "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { "$ref": "#" }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/stringArray" } + ] + } + }, + "propertyNames": { "$ref": "#" }, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + { "$ref": "#/definitions/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "if": { "$ref": "#" }, + "then": { "$ref": "#" }, + "else": { "$ref": "#" }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }, + "default": true +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/applicator b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/applicator new file mode 100644 index 00000000..857d2d49 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/applicator @@ -0,0 +1,55 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/applicator": true + }, + "$recursiveAnchor": true, + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "additionalItems": { "$recursiveRef": "#" }, + "unevaluatedItems": { "$recursiveRef": "#" }, + "items": { + "anyOf": [ + { "$recursiveRef": "#" }, + { "$ref": "#/$defs/schemaArray" } + ] + }, + "contains": { "$recursiveRef": "#" }, + "additionalProperties": { "$recursiveRef": "#" }, + "unevaluatedProperties": { "$recursiveRef": "#" }, + "properties": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { + "$recursiveRef": "#" + } + }, + "propertyNames": { "$recursiveRef": "#" }, + "if": { "$recursiveRef": "#" }, + "then": { "$recursiveRef": "#" }, + "else": { "$recursiveRef": "#" }, + "allOf": { "$ref": "#/$defs/schemaArray" }, + "anyOf": { "$ref": "#/$defs/schemaArray" }, + "oneOf": { "$ref": "#/$defs/schemaArray" }, + "not": { "$recursiveRef": "#" } + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$recursiveRef": "#" } + } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/content b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/content new file mode 100644 index 00000000..fa5d20b8 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/content @@ -0,0 +1,15 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "contentSchema": { "$recursiveRef": "#" } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/core b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/core new file mode 100644 index 00000000..bf573198 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/core @@ -0,0 +1,56 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true + }, + "$recursiveAnchor": true, + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$anchor": { + "type": "string", + "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveRef": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveAnchor": { + "type": "boolean", + "default": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/format b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/format new file mode 100644 index 00000000..fe553c23 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/format @@ -0,0 +1,13 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/format", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/format": true + }, + "$recursiveAnchor": true, + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "format": { "type": "string" } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/meta-data b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/meta-data new file mode 100644 index 00000000..5c95715c --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/meta-data @@ -0,0 +1,35 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/meta-data": true + }, + "$recursiveAnchor": true, + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/validation b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/validation new file mode 100644 index 00000000..f3525e07 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/meta/validation @@ -0,0 +1,97 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/validation": true + }, + "$recursiveAnchor": true, + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, + "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, + "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, + "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/$defs/stringArray" }, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "type": { + "anyOf": [ + { "$ref": "#/$defs/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/schema b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/schema new file mode 100644 index 00000000..f433389b --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2019-09/schema @@ -0,0 +1,41 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/schema", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "properties": { + "definitions": { + "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$recursiveRef": "#" }, + { "$ref": "meta/validation#/$defs/stringArray" } + ] + } + } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/applicator b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/applicator new file mode 100644 index 00000000..0ef24edc --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/applicator @@ -0,0 +1,47 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/applicator": true + }, + "$dynamicAnchor": "meta", + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "prefixItems": { "$ref": "#/$defs/schemaArray" }, + "items": { "$dynamicRef": "#meta" }, + "contains": { "$dynamicRef": "#meta" }, + "additionalProperties": { "$dynamicRef": "#meta" }, + "properties": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "default": {} + }, + "propertyNames": { "$dynamicRef": "#meta" }, + "if": { "$dynamicRef": "#meta" }, + "then": { "$dynamicRef": "#meta" }, + "else": { "$dynamicRef": "#meta" }, + "allOf": { "$ref": "#/$defs/schemaArray" }, + "anyOf": { "$ref": "#/$defs/schemaArray" }, + "oneOf": { "$ref": "#/$defs/schemaArray" }, + "not": { "$dynamicRef": "#meta" } + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$dynamicRef": "#meta" } + } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/content b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/content new file mode 100644 index 00000000..0330ff0a --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/content @@ -0,0 +1,15 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentEncoding": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentSchema": { "$dynamicRef": "#meta" } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/core b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/core new file mode 100644 index 00000000..c4de7005 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/core @@ -0,0 +1,50 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true + }, + "$dynamicAnchor": "meta", + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "$ref": "#/$defs/uriReferenceString", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { "$ref": "#/$defs/uriString" }, + "$ref": { "$ref": "#/$defs/uriReferenceString" }, + "$anchor": { "$ref": "#/$defs/anchorString" }, + "$dynamicRef": { "$ref": "#/$defs/uriReferenceString" }, + "$dynamicAnchor": { "$ref": "#/$defs/anchorString" }, + "$vocabulary": { + "type": "object", + "propertyNames": { "$ref": "#/$defs/uriString" }, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" } + } + }, + "$defs": { + "anchorString": { + "type": "string", + "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "uriReferenceString": { + "type": "string", + "format": "uri-reference" + } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/format-annotation b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/format-annotation new file mode 100644 index 00000000..0aa07d1c --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/format-annotation @@ -0,0 +1,13 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true + }, + "$dynamicAnchor": "meta", + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { + "format": { "type": "string" } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/format-assertion b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/format-assertion new file mode 100644 index 00000000..38613bff --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/format-assertion @@ -0,0 +1,13 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/format-assertion", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/format-assertion": true + }, + "$dynamicAnchor": "meta", + "title": "Format vocabulary meta-schema for assertion results", + "type": ["object", "boolean"], + "properties": { + "format": { "type": "string" } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/meta-data b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/meta-data new file mode 100644 index 00000000..30e28371 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/meta-data @@ -0,0 +1,35 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/meta-data": true + }, + "$dynamicAnchor": "meta", + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/unevaluated b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/unevaluated new file mode 100644 index 00000000..e9e093d1 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/unevaluated @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true + }, + "$dynamicAnchor": "meta", + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": { "$dynamicRef": "#meta" }, + "unevaluatedProperties": { "$dynamicRef": "#meta" } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/validation b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/validation new file mode 100644 index 00000000..4e016ed2 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/meta/validation @@ -0,0 +1,97 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/validation": true + }, + "$dynamicAnchor": "meta", + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "type": { + "anyOf": [ + { "$ref": "#/$defs/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, + "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, + "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, + "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/$defs/stringArray" }, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/schema b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/schema new file mode 100644 index 00000000..364f8ada --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/metaschemas/draft/2020-12/schema @@ -0,0 +1,57 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/schema", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/unevaluated"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format-annotation"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", + "properties": { + "definitions": { + "$comment": "\"definitions\" has been replaced by \"$defs\".", + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "deprecated": true, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$dynamicRef": "#meta" }, + { "$ref": "meta/validation#/$defs/stringArray" } + ] + }, + "deprecated": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/objcompiler.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/objcompiler.go new file mode 100644 index 00000000..f1494b13 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/objcompiler.go @@ -0,0 +1,549 @@ +package jsonschema + +import ( + "encoding/json" + "fmt" + "math/big" + "strconv" +) + +type objCompiler struct { + c *Compiler + obj map[string]any + up urlPtr + r *root + res *resource + q *queue +} + +func (c *objCompiler) compile(s *Schema) error { + // id -- + if id := c.res.dialect.draft.getID(c.obj); id != "" { + s.ID = id + } + + // anchor -- + if s.DraftVersion < 2019 { + // anchor is specified in id + id := c.string(c.res.dialect.draft.id) + if id != "" { + _, f := split(id) + if f != "" { + var err error + s.Anchor, err = decode(f) + if err != nil { + return &ParseAnchorError{URL: s.Location} + } + } + } + } else { + s.Anchor = c.string("$anchor") + } + + if err := c.compileDraft4(s); err != nil { + return err + } + if s.DraftVersion >= 6 { + if err := c.compileDraft6(s); err != nil { + return err + } + } + if s.DraftVersion >= 7 { + if err := c.compileDraft7(s); err != nil { + return err + } + } + if s.DraftVersion >= 2019 { + if err := c.compileDraft2019(s); err != nil { + return err + } + } + if s.DraftVersion >= 2020 { + if err := c.compileDraft2020(s); err != nil { + return err + } + } + + // vocabularies + vocabs := c.res.dialect.activeVocabs(c.c.roots.assertVocabs, c.c.roots.vocabularies) + for _, vocab := range vocabs { + v := c.c.roots.vocabularies[vocab] + if v == nil { + continue + } + ext, err := v.Compile(&CompilerContext{c}, c.obj) + if err != nil { + return err + } + if ext != nil { + s.Extensions = append(s.Extensions, ext) + } + } + + return nil +} + +func (c *objCompiler) compileDraft4(s *Schema) error { + var err error + + if c.hasVocab("core") { + if s.Ref, err = c.enqueueRef("$ref"); err != nil { + return err + } + if s.DraftVersion < 2019 && s.Ref != nil { + // All other properties in a "$ref" object MUST be ignored + return nil + } + } + + if c.hasVocab("applicator") { + s.AllOf = c.enqueueArr("allOf") + s.AnyOf = c.enqueueArr("anyOf") + s.OneOf = c.enqueueArr("oneOf") + s.Not = c.enqueueProp("not") + + if s.DraftVersion < 2020 { + if items, ok := c.obj["items"]; ok { + if _, ok := items.([]any); ok { + s.Items = c.enqueueArr("items") + s.AdditionalItems = c.enqueueAdditional("additionalItems") + } else { + s.Items = c.enqueueProp("items") + } + } + } + + s.Properties = c.enqueueMap("properties") + if m := c.enqueueMap("patternProperties"); m != nil { + s.PatternProperties = map[Regexp]*Schema{} + for pname, sch := range m { + re, err := c.c.roots.regexpEngine(pname) + if err != nil { + return &InvalidRegexError{c.up.format("patternProperties"), pname, err} + } + s.PatternProperties[re] = sch + } + } + s.AdditionalProperties = c.enqueueAdditional("additionalProperties") + + if m := c.objVal("dependencies"); m != nil { + s.Dependencies = map[string]any{} + for pname, pvalue := range m { + if arr, ok := pvalue.([]any); ok { + s.Dependencies[pname] = toStrings(arr) + } else { + ptr := c.up.ptr.append2("dependencies", pname) + s.Dependencies[pname] = c.enqueuePtr(ptr) + } + } + } + } + + if c.hasVocab("validation") { + if t, ok := c.obj["type"]; ok { + s.Types = newTypes(t) + } + if arr := c.arrVal("enum"); arr != nil { + s.Enum = newEnum(arr) + } + s.MultipleOf = c.numVal("multipleOf") + s.Maximum = c.numVal("maximum") + if c.boolean("exclusiveMaximum") { + s.ExclusiveMaximum = s.Maximum + s.Maximum = nil + } else { + s.ExclusiveMaximum = c.numVal("exclusiveMaximum") + } + s.Minimum = c.numVal("minimum") + if c.boolean("exclusiveMinimum") { + s.ExclusiveMinimum = s.Minimum + s.Minimum = nil + } else { + s.ExclusiveMinimum = c.numVal("exclusiveMinimum") + } + + s.MinLength = c.intVal("minLength") + s.MaxLength = c.intVal("maxLength") + if pat := c.strVal("pattern"); pat != nil { + s.Pattern, err = c.c.roots.regexpEngine(*pat) + if err != nil { + return &InvalidRegexError{c.up.format("pattern"), *pat, err} + } + } + + s.MinItems = c.intVal("minItems") + s.MaxItems = c.intVal("maxItems") + s.UniqueItems = c.boolean("uniqueItems") + + s.MaxProperties = c.intVal("maxProperties") + s.MinProperties = c.intVal("minProperties") + if arr := c.arrVal("required"); arr != nil { + s.Required = toStrings(arr) + } + } + + // format -- + if c.assertFormat(s.DraftVersion) { + if f := c.strVal("format"); f != nil { + if *f == "regex" { + s.Format = &Format{ + Name: "regex", + Validate: c.c.roots.regexpEngine.validate, + } + } else { + s.Format = c.c.formats[*f] + if s.Format == nil { + s.Format = formats[*f] + } + } + } + } + + // annotations -- + s.Title = c.string("title") + s.Description = c.string("description") + if v, ok := c.obj["default"]; ok { + s.Default = &v + } + + return nil +} + +func (c *objCompiler) compileDraft6(s *Schema) error { + if c.hasVocab("applicator") { + s.Contains = c.enqueueProp("contains") + s.PropertyNames = c.enqueueProp("propertyNames") + } + if c.hasVocab("validation") { + if v, ok := c.obj["const"]; ok { + s.Const = &v + } + } + return nil +} + +func (c *objCompiler) compileDraft7(s *Schema) error { + if c.hasVocab("applicator") { + s.If = c.enqueueProp("if") + if s.If != nil { + b := c.boolVal("if") + if b == nil || *b { + s.Then = c.enqueueProp("then") + } + if b == nil || !*b { + s.Else = c.enqueueProp("else") + } + } + } + + if c.c.assertContent { + if ce := c.strVal("contentEncoding"); ce != nil { + s.ContentEncoding = c.c.decoders[*ce] + if s.ContentEncoding == nil { + s.ContentEncoding = decoders[*ce] + } + } + if cm := c.strVal("contentMediaType"); cm != nil { + s.ContentMediaType = c.c.mediaTypes[*cm] + if s.ContentMediaType == nil { + s.ContentMediaType = mediaTypes[*cm] + } + } + } + + // annotations -- + s.Comment = c.string("$comment") + s.ReadOnly = c.boolean("readOnly") + s.WriteOnly = c.boolean("writeOnly") + if arr, ok := c.obj["examples"].([]any); ok { + s.Examples = arr + } + + return nil +} + +func (c *objCompiler) compileDraft2019(s *Schema) error { + var err error + + if c.hasVocab("core") { + if s.RecursiveRef, err = c.enqueueRef("$recursiveRef"); err != nil { + return err + } + s.RecursiveAnchor = c.boolean("$recursiveAnchor") + } + + if c.hasVocab("validation") { + if s.Contains != nil { + s.MinContains = c.intVal("minContains") + s.MaxContains = c.intVal("maxContains") + } + if m := c.objVal("dependentRequired"); m != nil { + s.DependentRequired = map[string][]string{} + for pname, pvalue := range m { + if arr, ok := pvalue.([]any); ok { + s.DependentRequired[pname] = toStrings(arr) + } + } + } + } + + if c.hasVocab("applicator") { + s.DependentSchemas = c.enqueueMap("dependentSchemas") + } + + var unevaluated bool + if s.DraftVersion == 2019 { + unevaluated = c.hasVocab("applicator") + } else { + unevaluated = c.hasVocab("unevaluated") + } + if unevaluated { + s.UnevaluatedItems = c.enqueueProp("unevaluatedItems") + s.UnevaluatedProperties = c.enqueueProp("unevaluatedProperties") + } + + if c.c.assertContent { + if s.ContentMediaType != nil && s.ContentMediaType.UnmarshalJSON != nil { + s.ContentSchema = c.enqueueProp("contentSchema") + } + } + + // annotations -- + s.Deprecated = c.boolean("deprecated") + + return nil +} + +func (c *objCompiler) compileDraft2020(s *Schema) error { + if c.hasVocab("core") { + sch, err := c.enqueueRef("$dynamicRef") + if err != nil { + return err + } + if sch != nil { + dref := c.strVal("$dynamicRef") + _, frag, err := splitFragment(*dref) + if err != nil { + return err + } + var anch string + if anchor, ok := frag.convert().(anchor); ok { + anch = string(anchor) + } + s.DynamicRef = &DynamicRef{sch, anch} + } + s.DynamicAnchor = c.string("$dynamicAnchor") + } + + if c.hasVocab("applicator") { + s.PrefixItems = c.enqueueArr("prefixItems") + s.Items2020 = c.enqueueProp("items") + } + + return nil +} + +// enqueue helpers -- + +func (c *objCompiler) enqueuePtr(ptr jsonPointer) *Schema { + up := urlPtr{c.up.url, ptr} + return c.c.enqueue(c.q, up) +} + +func (c *objCompiler) enqueueRef(pname string) (*Schema, error) { + ref := c.strVal(pname) + if ref == nil { + return nil, nil + } + baseURL := c.res.id + // baseURL := c.r.baseURL(c.up.ptr) + uf, err := baseURL.join(*ref) + if err != nil { + return nil, err + } + + up, err := c.r.resolve(*uf) + if err != nil { + return nil, err + } + if up != nil { + // local ref + return c.enqueuePtr(up.ptr), nil + } + + // remote ref + up_, err := c.c.roots.resolveFragment(*uf) + if err != nil { + return nil, err + } + return c.c.enqueue(c.q, up_), nil +} + +func (c *objCompiler) enqueueProp(pname string) *Schema { + if _, ok := c.obj[pname]; !ok { + return nil + } + ptr := c.up.ptr.append(pname) + return c.enqueuePtr(ptr) +} + +func (c *objCompiler) enqueueArr(pname string) []*Schema { + arr := c.arrVal(pname) + if arr == nil { + return nil + } + sch := make([]*Schema, len(arr)) + for i := range arr { + ptr := c.up.ptr.append2(pname, strconv.Itoa(i)) + sch[i] = c.enqueuePtr(ptr) + } + return sch +} + +func (c *objCompiler) enqueueMap(pname string) map[string]*Schema { + obj := c.objVal(pname) + if obj == nil { + return nil + } + sch := make(map[string]*Schema) + for k := range obj { + ptr := c.up.ptr.append2(pname, k) + sch[k] = c.enqueuePtr(ptr) + } + return sch +} + +func (c *objCompiler) enqueueAdditional(pname string) any { + if b := c.boolVal(pname); b != nil { + return *b + } + if sch := c.enqueueProp(pname); sch != nil { + return sch + } + return nil +} + +// -- + +func (c *objCompiler) hasVocab(name string) bool { + return c.res.dialect.hasVocab(name) +} + +func (c *objCompiler) assertFormat(draftVersion int) bool { + if c.c.assertFormat || draftVersion < 2019 { + return true + } + if draftVersion == 2019 { + return c.hasVocab("format") + } else { + return c.hasVocab("format-assertion") + } +} + +// value helpers -- + +func (c *objCompiler) boolVal(pname string) *bool { + v, ok := c.obj[pname] + if !ok { + return nil + } + b, ok := v.(bool) + if !ok { + return nil + } + return &b +} + +func (c *objCompiler) boolean(pname string) bool { + b := c.boolVal(pname) + return b != nil && *b +} + +func (c *objCompiler) strVal(pname string) *string { + v, ok := c.obj[pname] + if !ok { + return nil + } + s, ok := v.(string) + if !ok { + return nil + } + return &s +} + +func (c *objCompiler) string(pname string) string { + if s := c.strVal(pname); s != nil { + return *s + } + return "" +} + +func (c *objCompiler) numVal(pname string) *big.Rat { + v, ok := c.obj[pname] + if !ok { + return nil + } + switch v.(type) { + case json.Number, float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: + if n, ok := new(big.Rat).SetString(fmt.Sprint(v)); ok { + return n + } + } + return nil +} + +func (c *objCompiler) intVal(pname string) *int { + if n := c.numVal(pname); n != nil && n.IsInt() { + n := int(n.Num().Int64()) + return &n + } + return nil +} + +func (c *objCompiler) objVal(pname string) map[string]any { + v, ok := c.obj[pname] + if !ok { + return nil + } + obj, ok := v.(map[string]any) + if !ok { + return nil + } + return obj +} + +func (c *objCompiler) arrVal(pname string) []any { + v, ok := c.obj[pname] + if !ok { + return nil + } + arr, ok := v.([]any) + if !ok { + return nil + } + return arr +} + +// -- + +type InvalidRegexError struct { + URL string + Regex string + Err error +} + +func (e *InvalidRegexError) Error() string { + return fmt.Sprintf("invalid regex %q at %q: %v", e.Regex, e.URL, e.Err) +} + +// -- + +func toStrings(arr []any) []string { + var strings []string + for _, item := range arr { + if s, ok := item.(string); ok { + strings = append(strings, s) + } + } + return strings +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/output.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/output.go new file mode 100644 index 00000000..69d3f26d --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/output.go @@ -0,0 +1,216 @@ +package jsonschema + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/santhosh-tekuri/jsonschema/v6/kind" + "golang.org/x/text/language" + "golang.org/x/text/message" +) + +var defaultPrinter = message.NewPrinter(language.English) + +// format --- + +func (e *ValidationError) schemaURL() string { + if ref, ok := e.ErrorKind.(*kind.Reference); ok { + return ref.URL + } else { + return e.SchemaURL + } +} + +func (e *ValidationError) absoluteKeywordLocation() string { + var schemaURL string + var keywordPath []string + if ref, ok := e.ErrorKind.(*kind.Reference); ok { + schemaURL = ref.URL + keywordPath = nil + } else { + schemaURL = e.SchemaURL + keywordPath = e.ErrorKind.KeywordPath() + } + return fmt.Sprintf("%s%s", schemaURL, encode(jsonPtr(keywordPath))) +} + +func (e *ValidationError) skip() bool { + if len(e.Causes) == 1 { + _, ok := e.ErrorKind.(*kind.Reference) + return ok + } + return false +} + +func (e *ValidationError) display(sb *strings.Builder, verbose bool, indent int, absKwLoc string, p *message.Printer) { + if !e.skip() { + if indent > 0 { + sb.WriteByte('\n') + for i := 0; i < indent-1; i++ { + sb.WriteString(" ") + } + sb.WriteString("- ") + } + indent = indent + 1 + + prevAbsKwLoc := absKwLoc + absKwLoc = e.absoluteKeywordLocation() + + if _, ok := e.ErrorKind.(*kind.Schema); ok { + sb.WriteString(e.ErrorKind.LocalizedString(p)) + } else { + sb.WriteString(p.Sprintf("at %s", quote(jsonPtr(e.InstanceLocation)))) + if verbose { + schLoc := absKwLoc + if prevAbsKwLoc != "" { + pu, _ := split(prevAbsKwLoc) + u, f := split(absKwLoc) + if u == pu { + schLoc = fmt.Sprintf("S#%s", f) + } + } + fmt.Fprintf(sb, " [%s]", schLoc) + } + fmt.Fprintf(sb, ": %s", e.ErrorKind.LocalizedString(p)) + } + } + for _, cause := range e.Causes { + cause.display(sb, verbose, indent, absKwLoc, p) + } +} + +func (e *ValidationError) Error() string { + return e.LocalizedError(defaultPrinter) +} + +func (e *ValidationError) LocalizedError(p *message.Printer) string { + var sb strings.Builder + e.display(&sb, false, 0, "", p) + return sb.String() +} + +func (e *ValidationError) GoString() string { + return e.LocalizedGoString(defaultPrinter) +} + +func (e *ValidationError) LocalizedGoString(p *message.Printer) string { + var sb strings.Builder + e.display(&sb, true, 0, "", p) + return sb.String() +} + +func jsonPtr(tokens []string) string { + var sb strings.Builder + for _, tok := range tokens { + sb.WriteByte('/') + sb.WriteString(escape(tok)) + } + return sb.String() +} + +// -- + +// Flag is output format with simple boolean property valid. +type FlagOutput struct { + Valid bool `json:"valid"` +} + +// The `Flag` output format, merely the boolean result. +func (e *ValidationError) FlagOutput() *FlagOutput { + return &FlagOutput{Valid: false} +} + +// -- + +type OutputUnit struct { + Valid bool `json:"valid"` + KeywordLocation string `json:"keywordLocation"` + AbsoluteKeywordLocation string `json:"AbsoluteKeywordLocation,omitempty"` + InstanceLocation string `json:"instanceLocation"` + Error *OutputError `json:"error,omitempty"` + Errors []OutputUnit `json:"errors,omitempty"` +} + +type OutputError struct { + Kind ErrorKind + p *message.Printer +} + +func (k OutputError) String() string { + return k.Kind.LocalizedString(k.p) +} + +func (k OutputError) MarshalJSON() ([]byte, error) { + return json.Marshal(k.Kind.LocalizedString(k.p)) +} + +// The `Basic` structure, a flat list of output units. +func (e *ValidationError) BasicOutput() *OutputUnit { + return e.LocalizedBasicOutput(defaultPrinter) +} + +func (e *ValidationError) LocalizedBasicOutput(p *message.Printer) *OutputUnit { + out := e.output(true, false, "", "", p) + return &out +} + +// The `Detailed` structure, based on the schema. +func (e *ValidationError) DetailedOutput() *OutputUnit { + return e.LocalizedDetailedOutput(defaultPrinter) +} + +func (e *ValidationError) LocalizedDetailedOutput(p *message.Printer) *OutputUnit { + out := e.output(false, false, "", "", p) + return &out +} + +func (e *ValidationError) output(flatten, inRef bool, schemaURL, kwLoc string, p *message.Printer) OutputUnit { + if !inRef { + if _, ok := e.ErrorKind.(*kind.Reference); ok { + inRef = true + } + } + if schemaURL != "" { + kwLoc += e.SchemaURL[len(schemaURL):] + if ref, ok := e.ErrorKind.(*kind.Reference); ok { + kwLoc += jsonPtr(ref.KeywordPath()) + } + } + schemaURL = e.schemaURL() + + keywordLocation := kwLoc + if _, ok := e.ErrorKind.(*kind.Reference); !ok { + keywordLocation += jsonPtr(e.ErrorKind.KeywordPath()) + } + + out := OutputUnit{ + Valid: false, + InstanceLocation: jsonPtr(e.InstanceLocation), + KeywordLocation: keywordLocation, + } + if inRef { + out.AbsoluteKeywordLocation = e.absoluteKeywordLocation() + } + for _, cause := range e.Causes { + causeOut := cause.output(flatten, inRef, schemaURL, kwLoc, p) + if cause.skip() { + causeOut = causeOut.Errors[0] + } + if flatten { + errors := causeOut.Errors + causeOut.Errors = nil + causeOut.Error = &OutputError{cause.ErrorKind, p} + out.Errors = append(out.Errors, causeOut) + if len(errors) > 0 { + out.Errors = append(out.Errors, errors...) + } + } else { + out.Errors = append(out.Errors, causeOut) + } + } + if len(out.Errors) == 0 { + out.Error = &OutputError{e.ErrorKind, p} + } + return out +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/position.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/position.go new file mode 100644 index 00000000..576a2a47 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/position.go @@ -0,0 +1,142 @@ +package jsonschema + +import ( + "strconv" + "strings" +) + +// Position tells possible tokens in json. +type Position interface { + collect(v any, ptr jsonPointer) map[jsonPointer]any +} + +// -- + +type AllProp struct{} + +func (AllProp) collect(v any, ptr jsonPointer) map[jsonPointer]any { + obj, ok := v.(map[string]any) + if !ok { + return nil + } + m := map[jsonPointer]any{} + for pname, pvalue := range obj { + m[ptr.append(pname)] = pvalue + } + return m +} + +// -- + +type AllItem struct{} + +func (AllItem) collect(v any, ptr jsonPointer) map[jsonPointer]any { + arr, ok := v.([]any) + if !ok { + return nil + } + m := map[jsonPointer]any{} + for i, item := range arr { + m[ptr.append(strconv.Itoa(i))] = item + } + return m +} + +// -- + +type Prop string + +func (p Prop) collect(v any, ptr jsonPointer) map[jsonPointer]any { + obj, ok := v.(map[string]any) + if !ok { + return nil + } + pvalue, ok := obj[string(p)] + if !ok { + return nil + } + return map[jsonPointer]any{ + ptr.append(string(p)): pvalue, + } +} + +// -- + +type Item int + +func (i Item) collect(v any, ptr jsonPointer) map[jsonPointer]any { + arr, ok := v.([]any) + if !ok { + return nil + } + if i < 0 || int(i) >= len(arr) { + return nil + } + return map[jsonPointer]any{ + ptr.append(strconv.Itoa(int(i))): arr[int(i)], + } +} + +// -- + +// SchemaPath tells where to look for subschema inside keyword. +type SchemaPath []Position + +func schemaPath(path string) SchemaPath { + var sp SchemaPath + for _, tok := range strings.Split(path, "/") { + var pos Position + switch tok { + case "*": + pos = AllProp{} + case "[]": + pos = AllItem{} + default: + if i, err := strconv.Atoi(tok); err == nil { + pos = Item(i) + } else { + pos = Prop(tok) + } + } + sp = append(sp, pos) + } + return sp +} + +func (sp SchemaPath) collect(v any, ptr jsonPointer) map[jsonPointer]any { + if len(sp) == 0 { + return map[jsonPointer]any{ + ptr: v, + } + } + p, sp := sp[0], sp[1:] + m := p.collect(v, ptr) + mm := map[jsonPointer]any{} + for ptr, v := range m { + m = sp.collect(v, ptr) + for k, v := range m { + mm[k] = v + } + } + return mm +} + +func (sp SchemaPath) String() string { + var sb strings.Builder + for _, pos := range sp { + if sb.Len() != 0 { + sb.WriteByte('/') + } + switch pos := pos.(type) { + case AllProp: + sb.WriteString("*") + case AllItem: + sb.WriteString("[]") + case Prop: + sb.WriteString(string(pos)) + case Item: + sb.WriteString(strconv.Itoa(int(pos))) + } + } + return sb.String() +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/root.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/root.go new file mode 100644 index 00000000..a8b819ba --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/root.go @@ -0,0 +1,202 @@ +package jsonschema + +import ( + "fmt" + "slices" + "strings" +) + +type root struct { + url url + doc any + resources map[jsonPointer]*resource + subschemasProcessed map[jsonPointer]struct{} +} + +func (r *root) rootResource() *resource { + return r.resources[""] +} + +func (r *root) resource(ptr jsonPointer) *resource { + for { + if res, ok := r.resources[ptr]; ok { + return res + } + slash := strings.LastIndexByte(string(ptr), '/') + if slash == -1 { + break + } + ptr = ptr[:slash] + } + return r.rootResource() +} + +func (r *root) resolveFragmentIn(frag fragment, res *resource) (urlPtr, error) { + var ptr jsonPointer + switch f := frag.convert().(type) { + case jsonPointer: + ptr = res.ptr.concat(f) + case anchor: + aptr, ok := res.anchors[f] + if !ok { + return urlPtr{}, &AnchorNotFoundError{ + URL: r.url.String(), + Reference: (&urlFrag{res.id, frag}).String(), + } + } + ptr = aptr + } + return urlPtr{r.url, ptr}, nil +} + +func (r *root) resolveFragment(frag fragment) (urlPtr, error) { + return r.resolveFragmentIn(frag, r.rootResource()) +} + +// resolves urlFrag to urlPtr from root. +// returns nil if it is external. +func (r *root) resolve(uf urlFrag) (*urlPtr, error) { + var res *resource + if uf.url == r.url { + res = r.rootResource() + } else { + // look for resource with id==uf.url + for _, v := range r.resources { + if v.id == uf.url { + res = v + break + } + } + if res == nil { + return nil, nil // external url + } + } + up, err := r.resolveFragmentIn(uf.frag, res) + return &up, err +} + +func (r *root) collectAnchors(sch any, schPtr jsonPointer, res *resource) error { + obj, ok := sch.(map[string]any) + if !ok { + return nil + } + + addAnchor := func(anchor anchor) error { + ptr1, ok := res.anchors[anchor] + if ok { + if ptr1 == schPtr { + // anchor with same root_ptr already exists + return nil + } + return &DuplicateAnchorError{ + string(anchor), r.url.String(), string(ptr1), string(schPtr), + } + } + res.anchors[anchor] = schPtr + return nil + } + + if res.dialect.draft.version < 2019 { + if _, ok := obj["$ref"]; ok { + // All other properties in a "$ref" object MUST be ignored + return nil + } + // anchor is specified in id + if id, ok := strVal(obj, res.dialect.draft.id); ok { + _, frag, err := splitFragment(id) + if err != nil { + loc := urlPtr{r.url, schPtr} + return &ParseAnchorError{loc.String()} + } + if anchor, ok := frag.convert().(anchor); ok { + if err := addAnchor(anchor); err != nil { + return err + } + } + } + } + if res.dialect.draft.version >= 2019 { + if s, ok := strVal(obj, "$anchor"); ok { + if err := addAnchor(anchor(s)); err != nil { + return err + } + } + } + if res.dialect.draft.version >= 2020 { + if s, ok := strVal(obj, "$dynamicAnchor"); ok { + if err := addAnchor(anchor(s)); err != nil { + return err + } + res.dynamicAnchors = append(res.dynamicAnchors, anchor(s)) + } + } + + return nil +} + +func (r *root) clone() *root { + processed := map[jsonPointer]struct{}{} + for k := range r.subschemasProcessed { + processed[k] = struct{}{} + } + resources := map[jsonPointer]*resource{} + for k, v := range r.resources { + resources[k] = v.clone() + } + return &root{ + url: r.url, + doc: r.doc, + resources: resources, + subschemasProcessed: processed, + } +} + +// -- + +type resource struct { + ptr jsonPointer + id url + dialect dialect + anchors map[anchor]jsonPointer + dynamicAnchors []anchor +} + +func newResource(ptr jsonPointer, id url) *resource { + return &resource{ptr: ptr, id: id, anchors: make(map[anchor]jsonPointer)} +} + +func (res *resource) clone() *resource { + anchors := map[anchor]jsonPointer{} + for k, v := range res.anchors { + anchors[k] = v + } + return &resource{ + ptr: res.ptr, + id: res.id, + dialect: res.dialect, + anchors: anchors, + dynamicAnchors: slices.Clone(res.dynamicAnchors), + } +} + +//-- + +type UnsupportedVocabularyError struct { + URL string + Vocabulary string +} + +func (e *UnsupportedVocabularyError) Error() string { + return fmt.Sprintf("unsupported vocabulary %q in %q", e.Vocabulary, e.URL) +} + +// -- + +type AnchorNotFoundError struct { + URL string + Reference string +} + +func (e *AnchorNotFoundError) Error() string { + return fmt.Sprintf("anchor in %q not found in schema %q", e.Reference, e.URL) +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/roots.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/roots.go new file mode 100644 index 00000000..a8d0ef0c --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/roots.go @@ -0,0 +1,286 @@ +package jsonschema + +import ( + "fmt" + "strings" +) + +type roots struct { + defaultDraft *Draft + roots map[url]*root + loader defaultLoader + regexpEngine RegexpEngine + vocabularies map[string]*Vocabulary + assertVocabs bool +} + +func newRoots() *roots { + return &roots{ + defaultDraft: draftLatest, + roots: map[url]*root{}, + loader: defaultLoader{ + docs: map[url]any{}, + loader: FileLoader{}, + }, + regexpEngine: goRegexpCompile, + vocabularies: map[string]*Vocabulary{}, + } +} + +func (rr *roots) orLoad(u url) (*root, error) { + if r, ok := rr.roots[u]; ok { + return r, nil + } + doc, err := rr.loader.load(u) + if err != nil { + return nil, err + } + return rr.addRoot(u, doc) +} + +func (rr *roots) addRoot(u url, doc any) (*root, error) { + r := &root{ + url: u, + doc: doc, + resources: map[jsonPointer]*resource{}, + subschemasProcessed: map[jsonPointer]struct{}{}, + } + if err := rr.collectResources(r, doc, u, "", dialect{rr.defaultDraft, nil}); err != nil { + return nil, err + } + if !strings.HasPrefix(u.String(), "http://json-schema.org/") && + !strings.HasPrefix(u.String(), "https://json-schema.org/") { + if err := rr.validate(r, doc, ""); err != nil { + return nil, err + } + } + + rr.roots[u] = r + return r, nil +} + +func (rr *roots) resolveFragment(uf urlFrag) (urlPtr, error) { + r, err := rr.orLoad(uf.url) + if err != nil { + return urlPtr{}, err + } + return r.resolveFragment(uf.frag) +} + +func (rr *roots) collectResources(r *root, sch any, base url, schPtr jsonPointer, fallback dialect) error { + if _, ok := r.subschemasProcessed[schPtr]; ok { + return nil + } + if err := rr._collectResources(r, sch, base, schPtr, fallback); err != nil { + return err + } + r.subschemasProcessed[schPtr] = struct{}{} + return nil +} + +func (rr *roots) _collectResources(r *root, sch any, base url, schPtr jsonPointer, fallback dialect) error { + obj, ok := sch.(map[string]any) + if !ok { + if schPtr.isEmpty() { + // root resource + res := newResource(schPtr, base) + res.dialect = fallback + r.resources[schPtr] = res + } + return nil + } + + hasSchema := false + if sch, ok := obj["$schema"]; ok { + if _, ok := sch.(string); ok { + hasSchema = true + } + } + + draft, err := rr.loader.getDraft(urlPtr{r.url, schPtr}, sch, fallback.draft, map[url]struct{}{}) + if err != nil { + return err + } + id := draft.getID(obj) + if id == "" && !schPtr.isEmpty() { + // ignore $schema + draft = fallback.draft + hasSchema = false + id = draft.getID(obj) + } + + var res *resource + if id != "" { + uf, err := base.join(id) + if err != nil { + loc := urlPtr{r.url, schPtr} + return &ParseIDError{loc.String()} + } + base = uf.url + res = newResource(schPtr, base) + } else if schPtr.isEmpty() { + // root resource + res = newResource(schPtr, base) + } + + if res != nil { + found := false + for _, res := range r.resources { + if res.id == base { + found = true + if res.ptr != schPtr { + return &DuplicateIDError{base.String(), r.url.String(), string(schPtr), string(res.ptr)} + } + } + } + if !found { + if hasSchema { + vocabs, err := rr.loader.getMetaVocabs(sch, draft, rr.vocabularies) + if err != nil { + return err + } + res.dialect = dialect{draft, vocabs} + } else { + res.dialect = fallback + } + r.resources[schPtr] = res + } + } + + var baseRes *resource + for _, res := range r.resources { + if res.id == base { + baseRes = res + break + } + } + if baseRes == nil { + panic("baseres is nil") + } + + // found base resource + if err := r.collectAnchors(sch, schPtr, baseRes); err != nil { + return err + } + + // process subschemas + subschemas := map[jsonPointer]any{} + for _, sp := range draft.subschemas { + ss := sp.collect(obj, schPtr) + for k, v := range ss { + subschemas[k] = v + } + } + for _, vocab := range baseRes.dialect.activeVocabs(true, rr.vocabularies) { + if v := rr.vocabularies[vocab]; v != nil { + for _, sp := range v.Subschemas { + ss := sp.collect(obj, schPtr) + for k, v := range ss { + subschemas[k] = v + } + } + } + } + for ptr, v := range subschemas { + if err := rr.collectResources(r, v, base, ptr, baseRes.dialect); err != nil { + return err + } + } + + return nil +} + +func (rr *roots) ensureSubschema(up urlPtr) error { + r, err := rr.orLoad(up.url) + if err != nil { + return err + } + if _, ok := r.subschemasProcessed[up.ptr]; ok { + return nil + } + v, err := up.lookup(r.doc) + if err != nil { + return err + } + rClone := r.clone() + if err := rr.addSubschema(rClone, up.ptr); err != nil { + return err + } + if err := rr.validate(rClone, v, up.ptr); err != nil { + return err + } + rr.roots[r.url] = rClone + return nil +} + +func (rr *roots) addSubschema(r *root, ptr jsonPointer) error { + v, err := (&urlPtr{r.url, ptr}).lookup(r.doc) + if err != nil { + return err + } + base := r.resource(ptr) + baseURL := base.id + if err := rr.collectResources(r, v, baseURL, ptr, base.dialect); err != nil { + return err + } + + // collect anchors + if _, ok := r.resources[ptr]; !ok { + res := r.resource(ptr) + if err := r.collectAnchors(v, ptr, res); err != nil { + return err + } + } + return nil +} + +func (rr *roots) validate(r *root, v any, ptr jsonPointer) error { + dialect := r.resource(ptr).dialect + meta := dialect.getSchema(rr.assertVocabs, rr.vocabularies) + if err := meta.validate(v, rr.regexpEngine, meta, r.resources, rr.assertVocabs, rr.vocabularies); err != nil { + up := urlPtr{r.url, ptr} + return &SchemaValidationError{URL: up.String(), Err: err} + } + return nil +} + +// -- + +type InvalidMetaSchemaURLError struct { + URL string + Err error +} + +func (e *InvalidMetaSchemaURLError) Error() string { + return fmt.Sprintf("invalid $schema in %q: %v", e.URL, e.Err) +} + +// -- + +type UnsupportedDraftError struct { + URL string +} + +func (e *UnsupportedDraftError) Error() string { + return fmt.Sprintf("draft %q is not supported", e.URL) +} + +// -- + +type MetaSchemaCycleError struct { + URL string +} + +func (e *MetaSchemaCycleError) Error() string { + return fmt.Sprintf("cycle in resolving $schema in %q", e.URL) +} + +// -- + +type MetaSchemaMismatchError struct { + URL string +} + +func (e *MetaSchemaMismatchError) Error() string { + return fmt.Sprintf("$schema in %q does not match with $schema in root", e.URL) +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/schema.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/schema.go new file mode 100644 index 00000000..b4c1f37a --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/schema.go @@ -0,0 +1,254 @@ +package jsonschema + +import ( + "encoding/json" + "fmt" + "math/big" +) + +// Schema is the representation of a compiled +// jsonschema. +type Schema struct { + up urlPtr + resource *Schema + dynamicAnchors map[string]*Schema + allPropsEvaluated bool + allItemsEvaluated bool + numItemsEvaluated int + + DraftVersion int + Location string + + // type agnostic -- + Bool *bool // boolean schema + ID string + Ref *Schema + Anchor string + RecursiveRef *Schema + RecursiveAnchor bool + DynamicRef *DynamicRef + DynamicAnchor string // "" if not specified + Types *Types + Enum *Enum + Const *any + Not *Schema + AllOf []*Schema + AnyOf []*Schema + OneOf []*Schema + If *Schema + Then *Schema + Else *Schema + Format *Format + + // object -- + MaxProperties *int + MinProperties *int + Required []string + PropertyNames *Schema + Properties map[string]*Schema + PatternProperties map[Regexp]*Schema + AdditionalProperties any // nil or bool or *Schema + Dependencies map[string]any // value is []string or *Schema + DependentRequired map[string][]string + DependentSchemas map[string]*Schema + UnevaluatedProperties *Schema + + // array -- + MinItems *int + MaxItems *int + UniqueItems bool + Contains *Schema + MinContains *int + MaxContains *int + Items any // nil or []*Schema or *Schema + AdditionalItems any // nil or bool or *Schema + PrefixItems []*Schema + Items2020 *Schema + UnevaluatedItems *Schema + + // string -- + MinLength *int + MaxLength *int + Pattern Regexp + ContentEncoding *Decoder + ContentMediaType *MediaType + ContentSchema *Schema + + // number -- + Maximum *big.Rat + Minimum *big.Rat + ExclusiveMaximum *big.Rat + ExclusiveMinimum *big.Rat + MultipleOf *big.Rat + + Extensions []SchemaExt + + // annotations -- + Title string + Description string + Default *any + Comment string + ReadOnly bool + WriteOnly bool + Examples []any + Deprecated bool +} + +// -- + +type jsonType int + +const ( + invalidType jsonType = 0 + nullType jsonType = 1 << iota + booleanType + numberType + integerType + stringType + arrayType + objectType +) + +func typeOf(v any) jsonType { + switch v.(type) { + case nil: + return nullType + case bool: + return booleanType + case json.Number, float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: + return numberType + case string: + return stringType + case []any: + return arrayType + case map[string]any: + return objectType + default: + return invalidType + } +} + +func typeFromString(s string) jsonType { + switch s { + case "null": + return nullType + case "boolean": + return booleanType + case "number": + return numberType + case "integer": + return integerType + case "string": + return stringType + case "array": + return arrayType + case "object": + return objectType + } + return invalidType +} + +func (jt jsonType) String() string { + switch jt { + case nullType: + return "null" + case booleanType: + return "boolean" + case numberType: + return "number" + case integerType: + return "integer" + case stringType: + return "string" + case arrayType: + return "array" + case objectType: + return "object" + } + return "" +} + +// -- + +// Types encapsulates list of json value types. +type Types int + +func newTypes(v any) *Types { + var types Types + switch v := v.(type) { + case string: + types.Add(v) + case []any: + for _, item := range v { + if s, ok := item.(string); ok { + types.Add(s) + } + } + } + if types.IsEmpty() { + return nil + } + return &types +} + +func (tt Types) IsEmpty() bool { + return tt == 0 +} + +// Add specified json type. If typ is +// not valid json type it is ignored. +func (tt *Types) Add(typ string) { + tt.add(typeFromString(typ)) +} + +func (tt *Types) add(t jsonType) { + *tt = Types(int(*tt) | int(t)) +} + +func (tt Types) contains(t jsonType) bool { + return int(tt)&int(t) != 0 +} + +func (tt Types) ToStrings() []string { + types := []jsonType{ + nullType, booleanType, numberType, integerType, + stringType, arrayType, objectType, + } + var arr []string + for _, t := range types { + if tt.contains(t) { + arr = append(arr, t.String()) + } + } + return arr +} + +func (tt Types) String() string { + return fmt.Sprintf("%v", tt.ToStrings()) +} + +// -- + +type Enum struct { + Values []any + types Types +} + +func newEnum(arr []any) *Enum { + var types Types + for _, item := range arr { + types.add(typeOf(item)) + } + return &Enum{arr, types} +} + +// -- + +type DynamicRef struct { + Ref *Schema + Anchor string // "" if not specified +} + +func newSchema(up urlPtr) *Schema { + return &Schema{up: up, Location: up.String()} +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/util.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/util.go new file mode 100644 index 00000000..c6f8e775 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/util.go @@ -0,0 +1,464 @@ +package jsonschema + +import ( + "encoding/json" + "fmt" + "hash/maphash" + "math/big" + gourl "net/url" + "path/filepath" + "runtime" + "slices" + "strconv" + "strings" + + "github.com/santhosh-tekuri/jsonschema/v6/kind" + "golang.org/x/text/message" +) + +// -- + +type url (string) + +func (u url) String() string { + return string(u) +} + +func (u url) join(ref string) (*urlFrag, error) { + base, err := gourl.Parse(string(u)) + if err != nil { + return nil, &ParseURLError{URL: u.String(), Err: err} + } + + ref, frag, err := splitFragment(ref) + if err != nil { + return nil, err + } + refURL, err := gourl.Parse(ref) + if err != nil { + return nil, &ParseURLError{URL: ref, Err: err} + } + resolved := base.ResolveReference(refURL) + + // see https://github.com/golang/go/issues/66084 (net/url: ResolveReference ignores Opaque value) + if !refURL.IsAbs() && base.Opaque != "" { + resolved.Opaque = base.Opaque + } + + return &urlFrag{url: url(resolved.String()), frag: frag}, nil +} + +// -- + +type jsonPointer string + +func escape(tok string) string { + tok = strings.ReplaceAll(tok, "~", "~0") + tok = strings.ReplaceAll(tok, "/", "~1") + return tok +} + +func unescape(tok string) (string, bool) { + tilde := strings.IndexByte(tok, '~') + if tilde == -1 { + return tok, true + } + sb := new(strings.Builder) + for { + sb.WriteString(tok[:tilde]) + tok = tok[tilde+1:] + if tok == "" { + return "", false + } + switch tok[0] { + case '0': + sb.WriteByte('~') + case '1': + sb.WriteByte('/') + default: + return "", false + } + tok = tok[1:] + tilde = strings.IndexByte(tok, '~') + if tilde == -1 { + sb.WriteString(tok) + break + } + } + return sb.String(), true +} + +func (ptr jsonPointer) isEmpty() bool { + return string(ptr) == "" +} + +func (ptr jsonPointer) concat(next jsonPointer) jsonPointer { + return jsonPointer(fmt.Sprintf("%s%s", ptr, next)) +} + +func (ptr jsonPointer) append(tok string) jsonPointer { + return jsonPointer(fmt.Sprintf("%s/%s", ptr, escape(tok))) +} + +func (ptr jsonPointer) append2(tok1, tok2 string) jsonPointer { + return jsonPointer(fmt.Sprintf("%s/%s/%s", ptr, escape(tok1), escape(tok2))) +} + +// -- + +type anchor string + +// -- + +type fragment string + +func decode(frag string) (string, error) { + return gourl.PathUnescape(frag) +} + +// avoids escaping /. +func encode(frag string) string { + var sb strings.Builder + for i, tok := range strings.Split(frag, "/") { + if i > 0 { + sb.WriteByte('/') + } + sb.WriteString(gourl.PathEscape(tok)) + } + return sb.String() +} + +func splitFragment(str string) (string, fragment, error) { + u, f := split(str) + f, err := decode(f) + if err != nil { + return "", fragment(""), &ParseURLError{URL: str, Err: err} + } + return u, fragment(f), nil +} + +func split(str string) (string, string) { + hash := strings.IndexByte(str, '#') + if hash == -1 { + return str, "" + } + return str[:hash], str[hash+1:] +} + +func (frag fragment) convert() any { + str := string(frag) + if str == "" || strings.HasPrefix(str, "/") { + return jsonPointer(str) + } + return anchor(str) +} + +// -- + +type urlFrag struct { + url url + frag fragment +} + +func startsWithWindowsDrive(s string) bool { + if s != "" && strings.HasPrefix(s[1:], `:\`) { + return (s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[0] <= 'Z') + } + return false +} + +func absolute(input string) (*urlFrag, error) { + u, frag, err := splitFragment(input) + if err != nil { + return nil, err + } + + // if windows absolute file path, convert to file url + // because: net/url parses driver name as scheme + if runtime.GOOS == "windows" && startsWithWindowsDrive(u) { + u = "file:///" + filepath.ToSlash(u) + } + + gourl, err := gourl.Parse(u) + if err != nil { + return nil, &ParseURLError{URL: input, Err: err} + } + if gourl.IsAbs() { + return &urlFrag{url(u), frag}, nil + } + + // avoid filesystem api in wasm + if runtime.GOOS != "js" { + abs, err := filepath.Abs(u) + if err != nil { + return nil, &ParseURLError{URL: input, Err: err} + } + u = abs + } + if !strings.HasPrefix(u, "/") { + u = "/" + u + } + u = "file://" + filepath.ToSlash(u) + + _, err = gourl.Parse(u) + if err != nil { + return nil, &ParseURLError{URL: input, Err: err} + } + return &urlFrag{url: url(u), frag: frag}, nil +} + +func (uf *urlFrag) String() string { + return fmt.Sprintf("%s#%s", uf.url, encode(string(uf.frag))) +} + +// -- + +type urlPtr struct { + url url + ptr jsonPointer +} + +func (up *urlPtr) lookup(v any) (any, error) { + for _, tok := range strings.Split(string(up.ptr), "/")[1:] { + tok, ok := unescape(tok) + if !ok { + return nil, &InvalidJsonPointerError{up.String()} + } + switch val := v.(type) { + case map[string]any: + if pvalue, ok := val[tok]; ok { + v = pvalue + continue + } + case []any: + if index, err := strconv.Atoi(tok); err == nil { + if index >= 0 && index < len(val) { + v = val[index] + continue + } + } + } + return nil, &JSONPointerNotFoundError{up.String()} + } + return v, nil +} + +func (up *urlPtr) format(tok string) string { + return fmt.Sprintf("%s#%s/%s", up.url, encode(string(up.ptr)), encode(escape(tok))) +} + +func (up *urlPtr) String() string { + return fmt.Sprintf("%s#%s", up.url, encode(string(up.ptr))) +} + +// -- + +func minInt(i, j int) int { + if i < j { + return i + } + return j +} + +func strVal(obj map[string]any, prop string) (string, bool) { + v, ok := obj[prop] + if !ok { + return "", false + } + s, ok := v.(string) + return s, ok +} + +func isInteger(num any) bool { + rat, ok := new(big.Rat).SetString(fmt.Sprint(num)) + return ok && rat.IsInt() +} + +// quote returns single-quoted string. +// used for embedding quoted strings in json. +func quote(s string) string { + s = fmt.Sprintf("%q", s) + s = strings.ReplaceAll(s, `\"`, `"`) + s = strings.ReplaceAll(s, `'`, `\'`) + return "'" + s[1:len(s)-1] + "'" +} + +func equals(v1, v2 any) (bool, ErrorKind) { + switch v1 := v1.(type) { + case map[string]any: + v2, ok := v2.(map[string]any) + if !ok || len(v1) != len(v2) { + return false, nil + } + for k, val1 := range v1 { + val2, ok := v2[k] + if !ok { + return false, nil + } + if ok, k := equals(val1, val2); !ok || k != nil { + return ok, k + } + } + return true, nil + case []any: + v2, ok := v2.([]any) + if !ok || len(v1) != len(v2) { + return false, nil + } + for i := range v1 { + if ok, k := equals(v1[i], v2[i]); !ok || k != nil { + return ok, k + } + } + return true, nil + case nil: + return v2 == nil, nil + case bool: + v2, ok := v2.(bool) + return ok && v1 == v2, nil + case string: + v2, ok := v2.(string) + return ok && v1 == v2, nil + case json.Number, float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: + num1, ok1 := new(big.Rat).SetString(fmt.Sprint(v1)) + num2, ok2 := new(big.Rat).SetString(fmt.Sprint(v2)) + return ok1 && ok2 && num1.Cmp(num2) == 0, nil + default: + return false, &kind.InvalidJsonValue{Value: v1} + } +} + +func duplicates(arr []any) (int, int, ErrorKind) { + if len(arr) <= 20 { + for i := 1; i < len(arr); i++ { + for j := 0; j < i; j++ { + if ok, k := equals(arr[i], arr[j]); ok || k != nil { + return j, i, k + } + } + } + return -1, -1, nil + } + + m := make(map[uint64][]int) + h := new(maphash.Hash) + for i, item := range arr { + h.Reset() + writeHash(item, h) + hash := h.Sum64() + indexes, ok := m[hash] + if ok { + for _, j := range indexes { + if ok, k := equals(item, arr[j]); ok || k != nil { + return j, i, k + } + } + } + indexes = append(indexes, i) + m[hash] = indexes + } + return -1, -1, nil +} + +func writeHash(v any, h *maphash.Hash) ErrorKind { + switch v := v.(type) { + case map[string]any: + _ = h.WriteByte(0) + props := make([]string, 0, len(v)) + for prop := range v { + props = append(props, prop) + } + slices.Sort(props) + for _, prop := range props { + writeHash(prop, h) + writeHash(v[prop], h) + } + case []any: + _ = h.WriteByte(1) + for _, item := range v { + writeHash(item, h) + } + case nil: + _ = h.WriteByte(2) + case bool: + _ = h.WriteByte(3) + if v { + _ = h.WriteByte(1) + } else { + _ = h.WriteByte(0) + } + case string: + _ = h.WriteByte(4) + _, _ = h.WriteString(v) + case json.Number, float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: + _ = h.WriteByte(5) + num, _ := new(big.Rat).SetString(fmt.Sprint(v)) + _, _ = h.Write(num.Num().Bytes()) + _, _ = h.Write(num.Denom().Bytes()) + default: + return &kind.InvalidJsonValue{Value: v} + } + return nil +} + +// -- + +type ParseURLError struct { + URL string + Err error +} + +func (e *ParseURLError) Error() string { + return fmt.Sprintf("error in parsing %q: %v", e.URL, e.Err) +} + +// -- + +type InvalidJsonPointerError struct { + URL string +} + +func (e *InvalidJsonPointerError) Error() string { + return fmt.Sprintf("invalid json-pointer %q", e.URL) +} + +// -- + +type JSONPointerNotFoundError struct { + URL string +} + +func (e *JSONPointerNotFoundError) Error() string { + return fmt.Sprintf("json-pointer in %q not found", e.URL) +} + +// -- + +type SchemaValidationError struct { + URL string + Err error +} + +func (e *SchemaValidationError) Error() string { + return fmt.Sprintf("%q is not valid against metaschema: %v", e.URL, e.Err) +} + +// -- + +// LocalizableError is an error whose message is localizable. +func LocalizableError(format string, args ...any) error { + return &localizableError{format, args} +} + +type localizableError struct { + msg string + args []any +} + +func (e *localizableError) Error() string { + return fmt.Sprintf(e.msg, e.args...) +} + +func (e *localizableError) LocalizedError(p *message.Printer) string { + return p.Sprintf(e.msg, e.args...) +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/validator.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/validator.go new file mode 100644 index 00000000..e2ace37a --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/validator.go @@ -0,0 +1,975 @@ +package jsonschema + +import ( + "encoding/json" + "fmt" + "math/big" + "slices" + "strconv" + "unicode/utf8" + + "github.com/santhosh-tekuri/jsonschema/v6/kind" + "golang.org/x/text/message" +) + +func (sch *Schema) Validate(v any) error { + return sch.validate(v, nil, nil, nil, false, nil) +} + +func (sch *Schema) validate(v any, regexpEngine RegexpEngine, meta *Schema, resources map[jsonPointer]*resource, assertVocabs bool, vocabularies map[string]*Vocabulary) error { + vd := validator{ + v: v, + vloc: make([]string, 0, 8), + sch: sch, + scp: &scope{sch, "", 0, nil}, + uneval: unevalFrom(v, sch, false), + errors: nil, + boolResult: false, + regexpEngine: regexpEngine, + meta: meta, + resources: resources, + assertVocabs: assertVocabs, + vocabularies: vocabularies, + } + if _, err := vd.validate(); err != nil { + verr := err.(*ValidationError) + var causes []*ValidationError + if _, ok := verr.ErrorKind.(*kind.Group); ok { + causes = verr.Causes + } else { + causes = []*ValidationError{verr} + } + return &ValidationError{ + SchemaURL: sch.Location, + InstanceLocation: nil, + ErrorKind: &kind.Schema{Location: sch.Location}, + Causes: causes, + } + } + + return nil +} + +type validator struct { + v any + vloc []string + sch *Schema + scp *scope + uneval *uneval + errors []*ValidationError + boolResult bool // is interested to know valid or not (but not actuall error) + regexpEngine RegexpEngine + + // meta validation + meta *Schema // set only when validating with metaschema + resources map[jsonPointer]*resource // resources which should be validated with their dialect + assertVocabs bool + vocabularies map[string]*Vocabulary +} + +func (vd *validator) validate() (*uneval, error) { + s := vd.sch + v := vd.v + + // boolean -- + if s.Bool != nil { + if *s.Bool { + return vd.uneval, nil + } else { + return nil, vd.error(&kind.FalseSchema{}) + } + } + + // check cycle -- + if scp := vd.scp.checkCycle(); scp != nil { + return nil, vd.error(&kind.RefCycle{ + URL: s.Location, + KeywordLocation1: vd.scp.kwLoc(), + KeywordLocation2: scp.kwLoc(), + }) + } + + t := typeOf(v) + if t == invalidType { + return nil, vd.error(&kind.InvalidJsonValue{Value: v}) + } + + // type -- + if s.Types != nil && !s.Types.IsEmpty() { + matched := s.Types.contains(t) || (s.Types.contains(integerType) && t == numberType && isInteger(v)) + if !matched { + return nil, vd.error(&kind.Type{Got: t.String(), Want: s.Types.ToStrings()}) + } + } + + // const -- + if s.Const != nil { + ok, k := equals(v, *s.Const) + if k != nil { + return nil, vd.error(k) + } else if !ok { + return nil, vd.error(&kind.Const{Got: v, Want: *s.Const}) + } + } + + // enum -- + if s.Enum != nil { + matched := s.Enum.types.contains(typeOf(v)) + if matched { + matched = false + for _, item := range s.Enum.Values { + ok, k := equals(v, item) + if k != nil { + return nil, vd.error(k) + } else if ok { + matched = true + break + } + } + } + if !matched { + return nil, vd.error(&kind.Enum{Got: v, Want: s.Enum.Values}) + } + } + + // format -- + if s.Format != nil { + var err error + if s.Format.Name == "regex" && vd.regexpEngine != nil { + err = vd.regexpEngine.validate(v) + } else { + err = s.Format.Validate(v) + } + if err != nil { + return nil, vd.error(&kind.Format{Got: v, Want: s.Format.Name, Err: err}) + } + } + + // $ref -- + if s.Ref != nil { + err := vd.validateRef(s.Ref, "$ref") + if s.DraftVersion < 2019 { + return vd.uneval, err + } + if err != nil { + vd.addErr(err) + } + } + + // type specific validations -- + switch v := v.(type) { + case map[string]any: + vd.objValidate(v) + case []any: + vd.arrValidate(v) + case string: + vd.strValidate(v) + case json.Number, float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: + vd.numValidate(v) + } + + if len(vd.errors) == 0 || !vd.boolResult { + if s.DraftVersion >= 2019 { + vd.validateRefs() + } + vd.condValidate() + + for _, ext := range s.Extensions { + ext.Validate(&ValidatorContext{vd}, v) + } + + if s.DraftVersion >= 2019 { + vd.unevalValidate() + } + } + + switch len(vd.errors) { + case 0: + return vd.uneval, nil + case 1: + return nil, vd.errors[0] + default: + verr := vd.error(&kind.Group{}) + verr.Causes = vd.errors + return nil, verr + } +} + +func (vd *validator) objValidate(obj map[string]any) { + s := vd.sch + + // minProperties -- + if s.MinProperties != nil { + if len(obj) < *s.MinProperties { + vd.addError(&kind.MinProperties{Got: len(obj), Want: *s.MinProperties}) + } + } + + // maxProperties -- + if s.MaxProperties != nil { + if len(obj) > *s.MaxProperties { + vd.addError(&kind.MaxProperties{Got: len(obj), Want: *s.MaxProperties}) + } + } + + // required -- + if len(s.Required) > 0 { + if missing := vd.findMissing(obj, s.Required); missing != nil { + vd.addError(&kind.Required{Missing: missing}) + } + } + + if vd.boolResult && len(vd.errors) > 0 { + return + } + + // dependencies -- + for pname, dep := range s.Dependencies { + if _, ok := obj[pname]; ok { + switch dep := dep.(type) { + case []string: + if missing := vd.findMissing(obj, dep); missing != nil { + vd.addError(&kind.Dependency{Prop: pname, Missing: missing}) + } + case *Schema: + vd.addErr(vd.validateSelf(dep, "", false)) + } + } + } + + var additionalPros []string + for pname, pvalue := range obj { + if vd.boolResult && len(vd.errors) > 0 { + return + } + evaluated := false + + // properties -- + if sch, ok := s.Properties[pname]; ok { + evaluated = true + vd.addErr(vd.validateVal(sch, pvalue, pname)) + } + + // patternProperties -- + for regex, sch := range s.PatternProperties { + if regex.MatchString(pname) { + evaluated = true + vd.addErr(vd.validateVal(sch, pvalue, pname)) + } + } + + if !evaluated && s.AdditionalProperties != nil { + evaluated = true + switch additional := s.AdditionalProperties.(type) { + case bool: + if !additional { + additionalPros = append(additionalPros, pname) + } + case *Schema: + vd.addErr(vd.validateVal(additional, pvalue, pname)) + } + } + + if evaluated { + delete(vd.uneval.props, pname) + } + } + if len(additionalPros) > 0 { + vd.addError(&kind.AdditionalProperties{Properties: additionalPros}) + } + + if s.DraftVersion == 4 { + return + } + + // propertyNames -- + if s.PropertyNames != nil { + for pname := range obj { + sch, meta, resources := s.PropertyNames, vd.meta, vd.resources + res := vd.metaResource(sch) + if res != nil { + meta = res.dialect.getSchema(vd.assertVocabs, vd.vocabularies) + sch = meta + } + if err := sch.validate(pname, vd.regexpEngine, meta, resources, vd.assertVocabs, vd.vocabularies); err != nil { + verr := err.(*ValidationError) + verr.SchemaURL = s.PropertyNames.Location + verr.ErrorKind = &kind.PropertyNames{Property: pname} + vd.addErr(verr) + } + } + } + + if s.DraftVersion == 6 { + return + } + + // dependentSchemas -- + for pname, sch := range s.DependentSchemas { + if _, ok := obj[pname]; ok { + vd.addErr(vd.validateSelf(sch, "", false)) + } + } + + // dependentRequired -- + for pname, reqd := range s.DependentRequired { + if _, ok := obj[pname]; ok { + if missing := vd.findMissing(obj, reqd); missing != nil { + vd.addError(&kind.DependentRequired{Prop: pname, Missing: missing}) + } + } + } +} + +func (vd *validator) arrValidate(arr []any) { + s := vd.sch + + // minItems -- + if s.MinItems != nil { + if len(arr) < *s.MinItems { + vd.addError(&kind.MinItems{Got: len(arr), Want: *s.MinItems}) + } + } + + // maxItems -- + if s.MaxItems != nil { + if len(arr) > *s.MaxItems { + vd.addError(&kind.MaxItems{Got: len(arr), Want: *s.MaxItems}) + } + } + + // uniqueItems -- + if s.UniqueItems && len(arr) > 1 { + i, j, k := duplicates(arr) + if k != nil { + vd.addError(k) + } else if i != -1 { + vd.addError(&kind.UniqueItems{Duplicates: [2]int{i, j}}) + } + } + + if s.DraftVersion < 2020 { + evaluated := 0 + + // items -- + switch items := s.Items.(type) { + case *Schema: + for i, item := range arr { + vd.addErr(vd.validateVal(items, item, strconv.Itoa(i))) + } + evaluated = len(arr) + case []*Schema: + min := minInt(len(arr), len(items)) + for i, item := range arr[:min] { + vd.addErr(vd.validateVal(items[i], item, strconv.Itoa(i))) + } + evaluated = min + } + + // additionalItems -- + if s.AdditionalItems != nil { + switch additional := s.AdditionalItems.(type) { + case bool: + if !additional && evaluated != len(arr) { + vd.addError(&kind.AdditionalItems{Count: len(arr) - evaluated}) + } + case *Schema: + for i, item := range arr[evaluated:] { + vd.addErr(vd.validateVal(additional, item, strconv.Itoa(i))) + } + } + } + } else { + evaluated := minInt(len(s.PrefixItems), len(arr)) + + // prefixItems -- + for i, item := range arr[:evaluated] { + vd.addErr(vd.validateVal(s.PrefixItems[i], item, strconv.Itoa(i))) + } + + // items2020 -- + if s.Items2020 != nil { + for i, item := range arr[evaluated:] { + vd.addErr(vd.validateVal(s.Items2020, item, strconv.Itoa(i))) + } + } + } + + // contains -- + if s.Contains != nil { + var errors []*ValidationError + var matched []int + + for i, item := range arr { + if err := vd.validateVal(s.Contains, item, strconv.Itoa(i)); err != nil { + errors = append(errors, err.(*ValidationError)) + } else { + matched = append(matched, i) + if s.DraftVersion >= 2020 { + delete(vd.uneval.items, i) + } + } + } + + // minContains -- + if s.MinContains != nil { + if len(matched) < *s.MinContains { + vd.addErrors(errors, &kind.MinContains{Got: matched, Want: *s.MinContains}) + } + } else if len(matched) == 0 { + vd.addErrors(errors, &kind.Contains{}) + } + + // maxContains -- + if s.MaxContains != nil { + if len(matched) > *s.MaxContains { + vd.addError(&kind.MaxContains{Got: matched, Want: *s.MaxContains}) + } + } + } +} + +func (vd *validator) strValidate(str string) { + s := vd.sch + + strLen := -1 + if s.MinLength != nil || s.MaxLength != nil { + strLen = utf8.RuneCount([]byte(str)) + } + + // minLength -- + if s.MinLength != nil { + if strLen < *s.MinLength { + vd.addError(&kind.MinLength{Got: strLen, Want: *s.MinLength}) + } + } + + // maxLength -- + if s.MaxLength != nil { + if strLen > *s.MaxLength { + vd.addError(&kind.MaxLength{Got: strLen, Want: *s.MaxLength}) + } + } + + // pattern -- + if s.Pattern != nil { + if !s.Pattern.MatchString(str) { + vd.addError(&kind.Pattern{Got: str, Want: s.Pattern.String()}) + } + } + + if s.DraftVersion == 6 { + return + } + + var err error + + // contentEncoding -- + decoded := []byte(str) + if s.ContentEncoding != nil { + decoded, err = s.ContentEncoding.Decode(str) + if err != nil { + decoded = nil + vd.addError(&kind.ContentEncoding{Want: s.ContentEncoding.Name, Err: err}) + } + } + + var deserialized *any + if decoded != nil && s.ContentMediaType != nil { + if s.ContentSchema == nil { + err = s.ContentMediaType.Validate(decoded) + } else { + var value any + value, err = s.ContentMediaType.UnmarshalJSON(decoded) + if err == nil { + deserialized = &value + } + } + if err != nil { + vd.addError(&kind.ContentMediaType{ + Got: decoded, + Want: s.ContentMediaType.Name, + Err: err, + }) + } + } + + if deserialized != nil && s.ContentSchema != nil { + sch, meta, resources := s.ContentSchema, vd.meta, vd.resources + res := vd.metaResource(sch) + if res != nil { + meta = res.dialect.getSchema(vd.assertVocabs, vd.vocabularies) + sch = meta + } + if err = sch.validate(*deserialized, vd.regexpEngine, meta, resources, vd.assertVocabs, vd.vocabularies); err != nil { + verr := err.(*ValidationError) + verr.SchemaURL = s.Location + verr.ErrorKind = &kind.ContentSchema{} + vd.addErr(verr) + } + } +} + +func (vd *validator) numValidate(v any) { + s := vd.sch + + var numVal *big.Rat + num := func() *big.Rat { + if numVal == nil { + numVal, _ = new(big.Rat).SetString(fmt.Sprintf("%v", v)) + } + return numVal + } + + // minimum -- + if s.Minimum != nil && num().Cmp(s.Minimum) < 0 { + vd.addError(&kind.Minimum{Got: num(), Want: s.Minimum}) + } + + // maximum -- + if s.Maximum != nil && num().Cmp(s.Maximum) > 0 { + vd.addError(&kind.Maximum{Got: num(), Want: s.Maximum}) + } + + // exclusiveMinimum + if s.ExclusiveMinimum != nil && num().Cmp(s.ExclusiveMinimum) <= 0 { + vd.addError(&kind.ExclusiveMinimum{Got: num(), Want: s.ExclusiveMinimum}) + } + + // exclusiveMaximum + if s.ExclusiveMaximum != nil && num().Cmp(s.ExclusiveMaximum) >= 0 { + vd.addError(&kind.ExclusiveMaximum{Got: num(), Want: s.ExclusiveMaximum}) + } + + // multipleOf + if s.MultipleOf != nil { + if q := new(big.Rat).Quo(num(), s.MultipleOf); !q.IsInt() { + vd.addError(&kind.MultipleOf{Got: num(), Want: s.MultipleOf}) + } + } +} + +func (vd *validator) condValidate() { + s := vd.sch + + // not -- + if s.Not != nil { + if vd.validateSelf(s.Not, "", true) == nil { + vd.addError(&kind.Not{}) + } + } + + // allOf -- + if len(s.AllOf) > 0 { + var errors []*ValidationError + for _, sch := range s.AllOf { + if err := vd.validateSelf(sch, "", false); err != nil { + errors = append(errors, err.(*ValidationError)) + if vd.boolResult { + break + } + } + } + if len(errors) != 0 { + vd.addErrors(errors, &kind.AllOf{}) + } + } + + // anyOf + if len(s.AnyOf) > 0 { + var matched bool + var errors []*ValidationError + for _, sch := range s.AnyOf { + if err := vd.validateSelf(sch, "", false); err != nil { + errors = append(errors, err.(*ValidationError)) + } else { + matched = true + // for uneval, all schemas must be evaluated + if vd.uneval.isEmpty() { + break + } + } + } + if !matched { + vd.addErrors(errors, &kind.AnyOf{}) + } + } + + // oneOf + if len(s.OneOf) > 0 { + var matched = -1 + var errors []*ValidationError + for i, sch := range s.OneOf { + if err := vd.validateSelf(sch, "", matched != -1); err != nil { + if matched == -1 { + errors = append(errors, err.(*ValidationError)) + } + } else { + if matched == -1 { + matched = i + } else { + vd.addError(&kind.OneOf{Subschemas: []int{matched, i}}) + break + } + } + } + if matched == -1 { + vd.addErrors(errors, &kind.OneOf{Subschemas: nil}) + } + } + + // if, then, else -- + if s.If != nil { + if vd.validateSelf(s.If, "", true) == nil { + if s.Then != nil { + vd.addErr(vd.validateSelf(s.Then, "", false)) + } + } else if s.Else != nil { + vd.addErr(vd.validateSelf(s.Else, "", false)) + } + } +} + +func (vd *validator) unevalValidate() { + s := vd.sch + + // unevaluatedProperties + if obj, ok := vd.v.(map[string]any); ok && s.UnevaluatedProperties != nil { + for pname := range vd.uneval.props { + if pvalue, ok := obj[pname]; ok { + vd.addErr(vd.validateVal(s.UnevaluatedProperties, pvalue, pname)) + } + } + vd.uneval.props = nil + } + + // unevaluatedItems + if arr, ok := vd.v.([]any); ok && s.UnevaluatedItems != nil { + for i := range vd.uneval.items { + vd.addErr(vd.validateVal(s.UnevaluatedItems, arr[i], strconv.Itoa(i))) + } + vd.uneval.items = nil + } +} + +// validation helpers -- + +func (vd *validator) validateSelf(sch *Schema, refKw string, boolResult bool) error { + scp := vd.scp.child(sch, refKw, vd.scp.vid) + uneval := unevalFrom(vd.v, sch, !vd.uneval.isEmpty()) + subvd := validator{ + v: vd.v, + vloc: vd.vloc, + sch: sch, + scp: scp, + uneval: uneval, + errors: nil, + boolResult: vd.boolResult || boolResult, + regexpEngine: vd.regexpEngine, + meta: vd.meta, + resources: vd.resources, + assertVocabs: vd.assertVocabs, + vocabularies: vd.vocabularies, + } + subvd.handleMeta() + uneval, err := subvd.validate() + if err == nil { + vd.uneval.merge(uneval) + } + return err +} + +func (vd *validator) validateVal(sch *Schema, v any, vtok string) error { + vloc := append(vd.vloc, vtok) + scp := vd.scp.child(sch, "", vd.scp.vid+1) + uneval := unevalFrom(v, sch, false) + subvd := validator{ + v: v, + vloc: vloc, + sch: sch, + scp: scp, + uneval: uneval, + errors: nil, + boolResult: vd.boolResult, + regexpEngine: vd.regexpEngine, + meta: vd.meta, + resources: vd.resources, + assertVocabs: vd.assertVocabs, + vocabularies: vd.vocabularies, + } + subvd.handleMeta() + _, err := subvd.validate() + return err +} + +func (vd *validator) validateValue(sch *Schema, v any, vpath []string) error { + vloc := append(vd.vloc, vpath...) + scp := vd.scp.child(sch, "", vd.scp.vid+1) + uneval := unevalFrom(v, sch, false) + subvd := validator{ + v: v, + vloc: vloc, + sch: sch, + scp: scp, + uneval: uneval, + errors: nil, + boolResult: vd.boolResult, + regexpEngine: vd.regexpEngine, + meta: vd.meta, + resources: vd.resources, + assertVocabs: vd.assertVocabs, + vocabularies: vd.vocabularies, + } + subvd.handleMeta() + _, err := subvd.validate() + return err +} + +func (vd *validator) metaResource(sch *Schema) *resource { + if sch != vd.meta { + return nil + } + ptr := "" + for _, tok := range vd.instanceLocation() { + ptr += "/" + ptr += escape(tok) + } + return vd.resources[jsonPointer(ptr)] +} + +func (vd *validator) handleMeta() { + res := vd.metaResource(vd.sch) + if res == nil { + return + } + sch := res.dialect.getSchema(vd.assertVocabs, vd.vocabularies) + vd.meta = sch + vd.sch = sch +} + +// reference validation -- + +func (vd *validator) validateRef(sch *Schema, kw string) error { + err := vd.validateSelf(sch, kw, false) + if err != nil { + refErr := vd.error(&kind.Reference{Keyword: kw, URL: sch.Location}) + verr := err.(*ValidationError) + if _, ok := verr.ErrorKind.(*kind.Group); ok { + refErr.Causes = verr.Causes + } else { + refErr.Causes = append(refErr.Causes, verr) + } + return refErr + } + return nil +} + +func (vd *validator) resolveRecursiveAnchor(fallback *Schema) *Schema { + sch := fallback + scp := vd.scp + for scp != nil { + if scp.sch.resource.RecursiveAnchor { + sch = scp.sch + } + scp = scp.parent + } + return sch +} + +func (vd *validator) resolveDynamicAnchor(name string, fallback *Schema) *Schema { + sch := fallback + scp := vd.scp + for scp != nil { + if dsch, ok := scp.sch.resource.dynamicAnchors[name]; ok { + sch = dsch + } + scp = scp.parent + } + return sch +} + +func (vd *validator) validateRefs() { + // $recursiveRef -- + if sch := vd.sch.RecursiveRef; sch != nil { + if sch.RecursiveAnchor { + sch = vd.resolveRecursiveAnchor(sch) + } + vd.addErr(vd.validateRef(sch, "$recursiveRef")) + } + + // $dynamicRef -- + if dref := vd.sch.DynamicRef; dref != nil { + sch := dref.Ref // initial target + if dref.Anchor != "" { + // $dynamicRef includes anchor + if sch.DynamicAnchor == dref.Anchor { + // initial target has matching $dynamicAnchor + sch = vd.resolveDynamicAnchor(dref.Anchor, sch) + } + } + vd.addErr(vd.validateRef(sch, "$dynamicRef")) + } +} + +// error helpers -- + +func (vd *validator) instanceLocation() []string { + return slices.Clone(vd.vloc) +} + +func (vd *validator) error(kind ErrorKind) *ValidationError { + if vd.boolResult { + return &ValidationError{} + } + return &ValidationError{ + SchemaURL: vd.sch.Location, + InstanceLocation: vd.instanceLocation(), + ErrorKind: kind, + Causes: nil, + } +} + +func (vd *validator) addErr(err error) { + if err != nil { + vd.errors = append(vd.errors, err.(*ValidationError)) + } +} + +func (vd *validator) addError(kind ErrorKind) { + vd.errors = append(vd.errors, vd.error(kind)) +} + +func (vd *validator) addErrors(errors []*ValidationError, kind ErrorKind) { + err := vd.error(kind) + err.Causes = errors + vd.errors = append(vd.errors, err) +} + +func (vd *validator) findMissing(obj map[string]any, reqd []string) []string { + var missing []string + for _, pname := range reqd { + if _, ok := obj[pname]; !ok { + if vd.boolResult { + return []string{} // non-nil + } + missing = append(missing, pname) + } + } + return missing +} + +// -- + +type scope struct { + sch *Schema + + // if empty, compute from self.sch and self.parent.sch. + // not empty, only when there is a jump i.e, $ref, $XXXRef + refKeyword string + + // unique id of value being validated + // if two scopes validate same value, they will have + // same vid + vid int + + parent *scope +} + +func (sc *scope) child(sch *Schema, refKeyword string, vid int) *scope { + return &scope{sch, refKeyword, vid, sc} +} + +func (sc *scope) checkCycle() *scope { + scp := sc.parent + for scp != nil { + if scp.vid != sc.vid { + break + } + if scp.sch == sc.sch { + return scp + } + scp = scp.parent + } + return nil +} + +func (sc *scope) kwLoc() string { + var loc string + for sc.parent != nil { + if sc.refKeyword != "" { + loc = fmt.Sprintf("/%s%s", escape(sc.refKeyword), loc) + } else { + cur := sc.sch.Location + parent := sc.parent.sch.Location + loc = fmt.Sprintf("%s%s", cur[len(parent):], loc) + } + sc = sc.parent + } + return loc +} + +// -- + +type uneval struct { + props map[string]struct{} + items map[int]struct{} +} + +func unevalFrom(v any, sch *Schema, callerNeeds bool) *uneval { + uneval := &uneval{} + switch v := v.(type) { + case map[string]any: + if !sch.allPropsEvaluated && (callerNeeds || sch.UnevaluatedProperties != nil) { + uneval.props = map[string]struct{}{} + for k := range v { + uneval.props[k] = struct{}{} + } + } + case []any: + if !sch.allItemsEvaluated && (callerNeeds || sch.UnevaluatedItems != nil) && sch.numItemsEvaluated < len(v) { + uneval.items = map[int]struct{}{} + for i := sch.numItemsEvaluated; i < len(v); i++ { + uneval.items[i] = struct{}{} + } + } + } + return uneval +} + +func (ue *uneval) merge(other *uneval) { + for k := range ue.props { + if _, ok := other.props[k]; !ok { + delete(ue.props, k) + } + } + for i := range ue.items { + if _, ok := other.items[i]; !ok { + delete(ue.items, i) + } + } +} + +func (ue *uneval) isEmpty() bool { + return len(ue.props) == 0 && len(ue.items) == 0 +} + +// -- + +type ValidationError struct { + // absolute, dereferenced schema location. + SchemaURL string + + // location of the JSON value within the instance being validated. + InstanceLocation []string + + // kind of error + ErrorKind ErrorKind + + // holds nested errors + Causes []*ValidationError +} + +type ErrorKind interface { + KeywordPath() []string + LocalizedString(*message.Printer) string +} diff --git a/vendor/github.com/santhosh-tekuri/jsonschema/v6/vocab.go b/vendor/github.com/santhosh-tekuri/jsonschema/v6/vocab.go new file mode 100644 index 00000000..c81cb700 --- /dev/null +++ b/vendor/github.com/santhosh-tekuri/jsonschema/v6/vocab.go @@ -0,0 +1,111 @@ +package jsonschema + +// CompilerContext provides helpers for +// compiling a [Vocabulary]. +type CompilerContext struct { + c *objCompiler +} + +func (ctx *CompilerContext) Enqueue(schPath []string) *Schema { + ptr := ctx.c.up.ptr + for _, tok := range schPath { + ptr = ptr.append(tok) + } + return ctx.c.enqueuePtr(ptr) +} + +// Vocabulary defines a set of keywords, their syntax and +// their semantics. +type Vocabulary struct { + // URL identifier for this Vocabulary. + URL string + + // Schema that is used to validate the keywords that is introduced by this + // vocabulary. + Schema *Schema + + // Subschemas lists the possible locations of subschemas introduced by + // this vocabulary. + Subschemas []SchemaPath + + // Compile compiles the keywords(introduced by this vocabulary) in obj into [SchemaExt]. + // If obj does not contain any keywords introduced by this vocabulary, nil SchemaExt must + // be returned. + Compile func(ctx *CompilerContext, obj map[string]any) (SchemaExt, error) +} + +// -- + +// SchemaExt is compled form of vocabulary. +type SchemaExt interface { + // Validate validates v against and errors if any are reported + // to ctx. + Validate(ctx *ValidatorContext, v any) +} + +// ValidatorContext provides helpers for +// validating with [SchemaExt]. +type ValidatorContext struct { + vd *validator +} + +// ValueLocation returns location of value as jsonpath token array. +func (ctx *ValidatorContext) ValueLocation() []string { + return ctx.vd.vloc +} + +// Validate validates v with sch. vpath gives path of v from current context value. +func (ctx *ValidatorContext) Validate(sch *Schema, v any, vpath []string) error { + switch len(vpath) { + case 0: + return ctx.vd.validateSelf(sch, "", false) + case 1: + return ctx.vd.validateVal(sch, v, vpath[0]) + default: + return ctx.vd.validateValue(sch, v, vpath) + } +} + +// EvaluatedProp marks given property of current object as evaluated. +func (ctx *ValidatorContext) EvaluatedProp(pname string) { + delete(ctx.vd.uneval.props, pname) +} + +// EvaluatedItem marks items at given index of current array as evaluated. +func (ctx *ValidatorContext) EvaluatedItem(index int) { + delete(ctx.vd.uneval.items, index) +} + +// AddError reports validation-error of given kind. +func (ctx *ValidatorContext) AddError(k ErrorKind) { + ctx.vd.addError(k) +} + +// AddErrors reports validation-errors of given kind. +func (ctx *ValidatorContext) AddErrors(errors []*ValidationError, k ErrorKind) { + ctx.vd.addErrors(errors, k) +} + +// AddErr reports the given err. This is typically used to report +// the error created by subschema validation. +// +// NOTE that err must be of type *ValidationError. +func (ctx *ValidatorContext) AddErr(err error) { + ctx.vd.addErr(err) +} + +func (ctx *ValidatorContext) Equals(v1, v2 any) (bool, error) { + b, k := equals(v1, v2) + if k != nil { + return false, ctx.vd.error(k) + } + return b, nil +} + +func (ctx *ValidatorContext) Duplicates(arr []any) (int, int, error) { + i, j, k := duplicates(arr) + if k != nil { + return -1, -1, ctx.vd.error(k) + } + return i, j, nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/.gitignore b/vendor/github.com/stripe/stripe-go/v82/.gitignore new file mode 100644 index 00000000..d120a342 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/.gitignore @@ -0,0 +1,5 @@ +.DS_Store +.env +*.test +*.coverprofile +/.idea diff --git a/vendor/github.com/stripe/stripe-go/v82/API_VERSION b/vendor/github.com/stripe/stripe-go/v82/API_VERSION new file mode 100644 index 00000000..1116f63c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/API_VERSION @@ -0,0 +1 @@ +2025-06-30.basil \ No newline at end of file diff --git a/vendor/github.com/stripe/stripe-go/v82/CHANGELOG b/vendor/github.com/stripe/stripe-go/v82/CHANGELOG new file mode 100644 index 00000000..1d38c0c5 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/CHANGELOG @@ -0,0 +1 @@ +CHANGELOG has changed to be Markdown-formatted. Please see CHANGELOG.md. diff --git a/vendor/github.com/stripe/stripe-go/v82/CHANGELOG.md b/vendor/github.com/stripe/stripe-go/v82/CHANGELOG.md new file mode 100644 index 00000000..a486dfe6 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/CHANGELOG.md @@ -0,0 +1,4403 @@ +# Changelog + +## 82.3.0 - 2025-07-01 +* [#2078](https://github.com/stripe/stripe-go/pull/2078) Update generated code + * Add support for `Migrate` method on resource `Subscription` + * Add support for `CollectPaymentMethod` and `ConfirmPaymentIntent` methods on resource `TerminalReader` + * Add support for `CryptoPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `ProofOfAddress` on `AccountDocumentsParams` + * Add support for `MonthlyPayoutDays` and `WeeklyPayoutDays` on `AccountSettingsPayoutsScheduleParams` and `AccountSettingsPayoutsSchedule` + * Add support for `Crypto` on `ChargePaymentMethodDetails`, `ConfirmationTokenPaymentMethodDataParams`, `ConfirmationTokenPaymentMethodPreview`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `Subscriptions` on `CheckoutSessionPaymentMethodOptionsKlarnaParams`, `PaymentIntentConfirmPaymentMethodOptionsKlarnaParams`, and `PaymentIntentPaymentMethodOptionsKlarnaParams` + * Add support for `BillingMode` on `CheckoutSessionSubscriptionDataParams`, `InvoiceCreatePreviewScheduleDetailsParams`, `InvoiceCreatePreviewSubscriptionDetailsParams`, `QuoteSubscriptionDataParams`, `QuoteSubscriptionData`, `SubscriptionParams`, `SubscriptionScheduleParams`, `SubscriptionSchedule`, and `Subscription` + * Change type of `ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlan.Type`, `ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanParams.Type`, `InvoicePaymentSettingsPaymentMethodOptionsCardInstallmentsPlanParams.Type`, `PaymentIntentConfirmPaymentMethodOptionsCardInstallmentsPlanParams.Type`, `PaymentIntentPaymentMethodOptionsCardInstallmentsPlan.Type`, and `PaymentIntentPaymentMethodOptionsCardInstallmentsPlanParams.Type` from `literal('fixed_count')` to `enum('bonus'|'fixed_count'|'revolving')` + * Add support for new value `buut` on enum `ConfirmationTokenPaymentMethodPreviewIdeal.Bank` + * Add support for new value `BUUTNL2A` on enum `ConfirmationTokenPaymentMethodPreviewIdeal.BIC` + * Add support for new value `crypto` on enums `ConfirmationTokenPaymentMethodPreview.Type` and `PaymentMethod.Type` + * Change type of `Dispute.EnhancedEligibilityTypes` from `literal('visa_compelling_evidence_3')` to `enum('visa_compelling_evidence_3'|'visa_compliance')` + * Add support for new value `compliance` on enum `DisputePaymentMethodDetailsCard.CaseType` + * Add support for new value `terminal.reader.action_updated` on enum `Event.Type` + * Add support for `RelatedPerson` on `IdentityVerificationSessionParams` and `IdentityVerificationSession` + * Add support for `Matching` on `IdentityVerificationSessionOptions` + * Add support for new value `crypto` on enums `InvoicePaymentSettings.PaymentMethodTypes` and `SubscriptionPaymentSettings.PaymentMethodTypes` + * Add support for `Klarna` on `MandatePaymentMethodDetails`, `SetupIntentConfirmPaymentMethodOptionsParams`, `SetupIntentPaymentMethodOptionsParams`, and `SetupIntentPaymentMethodOptions` + * Add support for `OnDemand` on `PaymentIntentConfirmPaymentMethodOptionsKlarnaParams` and `PaymentIntentPaymentMethodOptionsKlarnaParams` + * Change type of `PaymentIntentConfirmPaymentMethodOptionsKlarnaParams.SetupFutureUsage`, `PaymentIntentPaymentMethodOptionsKlarna.SetupFutureUsage`, and `PaymentIntentPaymentMethodOptionsKlarnaParams.SetupFutureUsage` from `literal('none')` to `enum('none'|'off_session'|'on_session')` + * Add support for `Ua` on `TaxRegistrationCountryOptionsParams` and `TaxRegistrationCountryOptions` + * Change type of `TerminalLocationParams.DisplayName` from `string` to `emptyable(string)` + * Add support for `CollectPaymentMethod` and `ConfirmPaymentIntent` on `TerminalReaderAction` + * Add support for new values `collect_payment_method` and `confirm_payment_intent` on enum `TerminalReaderAction.Type` + * Add support for `Status` on `TreasuryFinancialAccountListParams` + * Add support for snapshot event `EventTypeTerminalReaderActionUpdated` with resource `TerminalReader` +* [#2082](https://github.com/stripe/stripe-go/pull/2082) Add form information to amount +* [#2076](https://github.com/stripe/stripe-go/pull/2076) Switch to use generated API versions and add major/monthly version constants + * Export constants for the major and monthly API versions + * e.g. `2025-05-28.basil` has major version `basil` and monthly version `2025-05-28` + +## 82.2.1 - 2025-06-04 +* [#2073](https://github.com/stripe/stripe-go/pull/2073) Update `DisputeReason` to include value `noncompliant` + * Adds `noncompliant` to `DisputeReason` enum +* [#2070](https://github.com/stripe/stripe-go/pull/2070) Fix failing telemetry test +* [#2068](https://github.com/stripe/stripe-go/pull/2068) Deduplicate telemetry strings + * Fixes a bug where telemetry strings could have duplicate values + +## 82.2.0 - 2025-05-29 + This release changes the pinned API version to `2025-05-28.basil`. + +* [#2063](https://github.com/stripe/stripe-go/pull/2063) Update generated code + * Add support for `AttachPayment` method on resource `Invoice` + * Add support for `CollectInputs` method on resource `TerminalReader` + * Add support for `SucceedInputCollection` and `TimeoutInputCollection` test helper methods on resource `TerminalReader` + * Add support for `PixPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `DisputesList` and `PaymentDisputes` on `AccountSessionComponentsParams` and `AccountSessionComponents` + * Add support for `RefundAndDisputePrefunding` on `Balance` + * Add support for `BalanceType` on `BalanceTransaction` + * Add support for `Location` and `Reader` on `ChargePaymentMethodDetailsAffirm` and `ChargePaymentMethodDetailsWechatPay` + * Add support for `PaymentMethodRemove` on `CheckoutSessionSavedPaymentMethodOptionsParams` + * Add support for `SetupFutureUsage` on `CheckoutSessionPaymentMethodOptionsNaverPay` + * Add support for `PostPaymentAmount` and `PrePaymentAmount` on `CreditNote` + * Add support for new value `mixed` on enum `CreditNote.Type` + * Add support for new value `invoice_payment.paid` on enum `Event.Type` + * Add support for `Sex`, `UnparsedPlaceOfBirth`, and `UnparsedSex` on `IdentityVerificationReportDocument` and `IdentityVerificationSessionVerifiedOutputs` + * Add support for `BillingThresholds` on `InvoiceCreatePreviewScheduleDetailsPhaseItemParams`, `InvoiceCreatePreviewScheduleDetailsPhaseParams`, `InvoiceCreatePreviewSubscriptionDetailsItemParams`, `SubscriptionItemParams`, `SubscriptionItem`, `SubscriptionParams`, `SubscriptionScheduleDefaultSettingsParams`, `SubscriptionScheduleDefaultSettings`, `SubscriptionSchedulePhaseItemParams`, `SubscriptionSchedulePhaseItem`, `SubscriptionSchedulePhaseParams`, `SubscriptionSchedulePhase`, and `Subscription` + * Add support for `Satispay` on `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptionsParams`, and `PaymentIntentPaymentMethodOptions` + * Add support for `CaptureMethod` on `PaymentIntentPaymentMethodOptionsBillie` + * Add support for `KakaoPay`, `KrCard`, `NaverPay`, `Payco`, and `SamsungPay` on `PaymentMethodConfigurationParams` and `PaymentMethodConfiguration` + * Add support for `NetworkDeclineCode` on `RefundDestinationDetailsPaypal` + * Add support for `Metadata` on `TaxCalculationLineItemParams` and `TaxCalculationLineItem` + * Add support for `ReturnURL` on `TerminalReaderActionProcessPaymentIntentProcessConfig` and `TerminalReaderProcessPaymentIntentProcessConfigParams` + * Add support for `CollectInputs` on `TerminalReaderAction` + * Add support for new value `collect_inputs` on enum `TerminalReaderAction.Type` + * Add support for new value `simulated_stripe_s700` on enum `TerminalReader.DeviceType` + * Add support for snapshot event `EventTypeInvoicePaymentPaid` with resource `InvoicePayment` + * Add support for error code `forwarding_api_upstream_error` on `Error`, `InvoiceLastFinalizationError`, `PaymentIntentLastPaymentError`, `SetupAttemptSetupError`, `SetupIntentLastSetupError`, and `StripeError` +* [#2062](https://github.com/stripe/stripe-go/pull/2062) Adds CONTRIBUTING.md + +## 82.1.0 - 2025-04-30 + +This release changes the pinned API version to `2025-04-30.basil`. + + ### 🎉 Introducing new Stripe Client +Starting with v82.1, the new `stripe.Client` type is replacing `client.API` to provide a more ergonomic, consistent, and less error-prone experience. You create the former using `stripe.NewClient(stripeKey)`. It’s almost a drop-in replacement, except for the differences listed below. + +1. Service method names now align with Stripe API docs. The `stripe.Client` uses `Create`, `Retrieve`, `Update`, and `Delete` (instead of `New`, `Get`, `Update`, and `Del`). +2. The first argument of each service method is a `context.Context`. +3. Parameter objects are now method-specific. For example, `CustomerCreateParams` and `CustomerDeleteParams` instead of simply `CustomerParams`. This allows us to put the right fields in the right methods at compile time. +4. Services are all version-namespaced for symmetry. E.g. `stripeClient.V1Accounts` and `stripeClient.V2Accounts`. +5. `List` methods return an `iter.Seq2`, so they can be ranged over without explicit calls to `Next`, `Current`, and `Err`. + + ### 🎉 Native support in Go for V2 APIs +```go +params := &stripe.V2CoreEventListParams{ObjectID: stripe.String("mtr_123")} +for event, err := range sc.V2CoreEvents.List(context.TODO(), params) { + // handle err + // process event object +} +``` +* All V2 APIs are now supported natively through the `stripe.Client` + +More details can be found at https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client + +* [#2029](https://github.com/stripe/stripe-go/pull/2029) Update generated code + * Add support for `MinorityOwnedBusinessDesignation` on `AccountBusinessProfileParams` and `AccountBusinessProfile` + * Add support for `RegistrationDate` on `AccountCompanyParams`, `AccountCompany`, and `TokenAccountCompanyParams` + * Add support for `USCfpbData` on `AccountParams`, `PersonParams`, `Person`, and `TokenPersonParams` + * Add support for new value `tax_id_prohibited` on enums `InvoiceLastFinalizationError.Code`, `PaymentIntentLastPaymentError.Code`, `SetupAttemptSetupError.Code`, `SetupIntentLastSetupError.Code`, and `StripeError.Code` + * Add support for new value `verification_legal_entity_structure_mismatch` on enums `BankAccountFutureRequirementsErrors.Code` and `BankAccountRequirementsErrors.Code` + * Add support for `TaxID` on `ChargeBillingDetails`, `ConfirmationTokenPaymentMethodDataBillingDetailsParams`, `ConfirmationTokenPaymentMethodPreviewBillingDetails`, `PaymentIntentConfirmPaymentMethodDataBillingDetailsParams`, `PaymentIntentPaymentMethodDataBillingDetailsParams`, `PaymentMethodBillingDetailsParams`, `PaymentMethodBillingDetails`, `SetupIntentConfirmPaymentMethodDataBillingDetailsParams`, `SetupIntentPaymentMethodDataBillingDetailsParams`, `TestHelpersConfirmationTokenPaymentMethodDataBillingDetailsParams`, and `TreasuryOutboundPaymentDestinationPaymentMethodDataBillingDetailsParams` + * Add support for `WalletOptions` on `CheckoutSessionParams` and `CheckoutSession` + * Add support for `Provider` on `CheckoutSessionAutomaticTax`, `InvoiceAutomaticTax`, and `QuoteAutomaticTax` + * Add support for new values `aw_tin`, `az_tin`, `bd_bin`, `bf_ifu`, `bj_ifu`, `cm_niu`, `cv_nif`, `et_tin`, `kg_tin`, and `la_tin` on enums `CheckoutSessionCustomerDetailsTaxIds.Type`, `TaxCalculationCustomerDetailsTaxId.Type`, `TaxId.Type`, and `TaxTransactionCustomerDetailsTaxId.Type` + * Add support for `PaymentMethodOptions` on `ConfirmationTokenParams` and `TestHelpersConfirmationTokenParams` + * Add support for `Installments` on `ConfirmationTokenPaymentMethodOptionsCard` + * Add support for `Context` on `Event` + * Add support for new value `affirm` on enums `InvoicePaymentSettings.PaymentMethodTypes` and `SubscriptionPaymentSettings.PaymentMethodTypes` + * Add support for `Billie` on `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptionsParams`, and `PaymentIntentPaymentMethodOptions` + * Add support for `Pix` on `PaymentMethodConfigurationParams` and `PaymentMethodConfiguration` + * Add support for `Klarna` on `PaymentMethodDomain` + * Add support for `PendingReason` on `Refund` + * Add support for `Aw`, `Az`, `Bd`, `Bf`, `Bj`, `Cm`, `Cv`, `ET`, `In`, `Kg`, `La`, and `Ph` on `TaxRegistrationCountryOptionsParams` and `TaxRegistrationCountryOptions` +* [#2022](https://github.com/stripe/stripe-go/pull/2022) Improved handling for enums in params + * You can now pass `string` enums into `stripe.String`. For example, `stripe.String(stripe.CurrencyUSD)` instead of `stripe.String(string(stripe.CurrencyUSD))` +* [#1916](https://github.com/stripe/stripe-go/pull/1916) perf: do not computing signature when timestamp is not valid +* [#1860](https://github.com/stripe/stripe-go/pull/1860) fix: typo in error +* [#2018](https://github.com/stripe/stripe-go/pull/2018) Backport beta fixes + +## 82.0.0 - 2025-04-01 +* [#1992](https://github.com/stripe/stripe-go/pull/1992) Support for APIs in the new API version 2025-03-31.basil + + This release changes the pinned API version to `2025-03-31.basil`. + + ### ⚠️ Breaking changes due to changes in the Stripe API + + Please review details for the breaking changes and alternatives in the [Stripe API changelog](https://docs.stripe.com/changelog/basil) before upgrading. + + * Remove support for resources `UsageRecordSummary` and `UsageRecord` + * Remove support for `New` method on resource `UsageRecord` + * Remove support for `List` method on resource `UsageRecordSummary` + * Remove support for `UpcomingLines` and `Upcoming` methods on resource `Invoice` + * Remove support for `UsageRecordSummaries` method on resource `SubscriptionItem` + * Remove support for `Invoice` on `Charge` and `PaymentIntent` + * Remove support for `ShippingDetails` on `CheckoutSession` + * Remove support for `Carrier`, `Phone`, and `TrackingNumber` on `CheckoutSessionCollectedInformationShippingDetails` + * Remove support for `Refund` on `CreditNoteParams`, `CreditNotePreviewLinesParams`, `CreditNotePreviewParams`, and `CreditNote` + * Remove support for `TaxAmounts` on `CreditNoteLineItem`, `CreditNote`, and `InvoiceLineItem` + * Remove support for `AmountExcludingTax` and `UnitAmountExcludingTax` on `CreditNoteLineItem` and `InvoiceLineItem` + * Remove support for `Coupon` on `CustomerParams`, `InvoiceCreatePreviewParams`, `InvoiceCreatePreviewScheduleDetailsPhasesParams`, `SubscriptionParams`, `SubscriptionSchedulePhasesParams`, and `SubscriptionSchedulePhases` + * Remove support for `PromotionCode` on `CustomerParams` and `SubscriptionParams` + * Remove support for `Price` on `InvoiceAddLinesLinesParams`, `InvoiceItemParams`, `InvoiceItem`, `InvoiceLineItemParams`, `InvoiceLineItem`, and `InvoiceUpdateLinesLinesParams` + * Remove support for `BillingThresholds` on `InvoiceCreatePreviewScheduleDetailsPhasesItemsParams`, `InvoiceCreatePreviewScheduleDetailsPhasesParams`, `InvoiceCreatePreviewSubscriptionDetailsItemsParams`, `SubscriptionItemParams`, `SubscriptionItem`, `SubscriptionItemsParams`, `SubscriptionParams`, `SubscriptionScheduleDefaultSettingsParams`, `SubscriptionScheduleDefaultSettings`, `SubscriptionSchedulePhasesItemsParams`, `SubscriptionSchedulePhasesItems`, `SubscriptionSchedulePhasesParams`, `SubscriptionSchedulePhases`, and `Subscription` + * Remove support for `ApplicationFeeAmount`, `Charge`, `PaidOutOfBand`, `Paid`, `PaymentIntent`, `Quote`, `Subscription`, `SubscriptionDetails`, `SubscriptionProrationDate`, `Tax`, `TotalTaxAmounts`, and `TransferData` on `Invoice` + * Remove support for `Discount` on `Invoice` and `Subscription` + * Remove support for `InvoiceItem`, `ProrationDetails`, `Proration`, `TaxRates`, and `Type` on `InvoiceLineItem` + * Remove support for `Plan` and `SubscriptionItem` on `InvoiceItem` and `InvoiceLineItem` + * Remove support for `UnitAmount` on `InvoiceItemParams` and `InvoiceItem` + * Remove support for `Subscription` and `UnitAmountDecimal` on `InvoiceItem` + * Remove support for `NaverPay` on `PaymentMethodParams` + * Remove support for `AggregateUsage` on `PlanParams`, `Plan`, `PriceRecurringParams`, and `PriceRecurring` + * Remove support for `CurrentPeriodEnd` and `CurrentPeriodStart` on `Subscription` + + ### ⚠️ Other Breaking changes in the SDK + + * [#1999](https://github.com/stripe/stripe-go/pull/1999) Upgrade to go 1.18 + * Go version 1.18 or later is now required to address security vulnerabilities in Go <= 1.17. In particular, HTTP/2 is enabled now by default for all users (it was disabled for Go <= 1.14). + * [#1998](https://github.com/stripe/stripe-go/pull/1998) Breaking changes to support V2 + * Renamed the `stripe.Amount` type in the `stripe.Balance` object to `stripe.BalanceAmount` + * Changed the signature of the `CallRaw` method in the `stripe.Backend` interface to accept a `[]byte` instead of `*form.Values` in its fourth argument. Call sites can safely replace a `*form.Values` argument `v` with `[]byte(v.Encode())` (`Encode` is `nil`-safe). + + ### Additions to Stripe API + + * Add support for new resource `InvoicePayment` + * Add support for `Get` and `List` methods on resource `InvoicePayment` + * Add support for `BilliePayments`, `NzBankAccountBECSDebitPayments`, and `SatispayPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `HostedPaymentMethodSave` on `AccountSettingsInvoicesParams` and `AccountSettingsInvoices` + * Add support for `Invoices` on `AccountSettingsParams` + * Add support for new values `forwarding_api_retryable_upstream_error` and `setup_intent_mobile_wallet_unsupported` on enums `InvoiceLastFinalizationError.Code`, `PaymentIntentLastPaymentError.Code`, `SetupAttemptSetupError.Code`, `SetupIntentLastSetupError.Code`, and `StripeError.Code` + * Add support for new values `stripe_balance_payment_debit_reversal` and `stripe_balance_payment_debit` on enum `BalanceTransaction.Type` + * Add support for new values `information_missing`, `invalid_signator`, `verification_failed_authorizer_authority`, and `verification_rejected_ownership_exemption_reason` on enums `BankAccountFutureRequirementsErrors.Code` and `BankAccountRequirementsErrors.Code` + * Add support for new value `last` on enum `BillingMeterDefaultAggregation.Formula` + * Add support for `PresentmentDetails` on `Charge`, `CheckoutSession`, `PaymentIntent`, and `Refund` + * Add support for `Billie` and `Satispay` on `ChargePaymentMethodDetails`, `ConfirmationTokenPaymentMethodDataParams`, `ConfirmationTokenPaymentMethodPreview`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentMethodConfigurationParams`, `PaymentMethodConfiguration`, `PaymentMethodParams`, `PaymentMethod`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `NzBankAccount` on `ChargePaymentMethodDetails`, `ConfirmationTokenPaymentMethodDataParams`, `ConfirmationTokenPaymentMethodPreview`, `MandatePaymentMethodDetails`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodConfigurationParams`, `PaymentMethodConfiguration`, `PaymentMethodParams`, `PaymentMethod`, `SetupAttemptPaymentMethodDetails`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `OptionalItems` on `CheckoutSessionParams`, `CheckoutSession`, `PaymentLinkParams`, and `PaymentLink` + * Add support for `Permissions` on `CheckoutSessionParams` and `CheckoutSession` + * Add support for `ShippingOptions` on `CheckoutSessionParams` + * Add support for new value `custom` on enum `CheckoutSession.UIMode` + * Add support for `BuyerID` on `ConfirmationTokenPaymentMethodPreviewNaverPay` and `PaymentMethodNaverPay` + * Add support for new values `billie`, `nz_bank_account`, and `satispay` on enums `ConfirmationTokenPaymentMethodPreview.Type` and `PaymentMethod.Type` + * Add support for `Refunds` on `CreditNoteParams`, `CreditNotePreviewLinesParams`, `CreditNotePreviewParams`, and `CreditNote` + * Add support for `TotalTaxes` on `CreditNote` and `Invoice` + * Add support for `Taxes` on `CreditNoteLineItem` and `InvoiceLineItem` + * Add support for `TaxabilityReason` on `InvoiceAddLinesLinesTaxAmountsParams`, `InvoiceLineItemTaxAmountsParams`, and `InvoiceUpdateLinesLinesTaxAmountsParams` + * Add support for `JurisdictionLevel` on `InvoiceAddLinesLinesTaxAmountsTaxRateDataParams`, `InvoiceLineItemTaxAmountsTaxRateDataParams`, and `InvoiceUpdateLinesLinesTaxAmountsTaxRateDataParams` + * Add support for `AmountOverpaid`, `ConfirmationSecret`, and `Payments` on `Invoice` + * Add support for `Parent` on `InvoiceItem`, `InvoiceLineItem`, and `Invoice` + * Add support for new values `klarna` and `nz_bank_account` on enums `InvoicePaymentSettings.PaymentMethodTypes` and `SubscriptionPaymentSettings.PaymentMethodTypes` + * Add support for `CheckoutSession` on `CustomerBalanceTransaction` + * Add support for new values `checkout_session_subscription_payment_canceled` and `checkout_session_subscription_payment` on enum `CustomerBalanceTransaction.Type` + * Add support for new value `invoice.overpaid` on enum `Event.Type` + * Add support for `Pricing` on `InvoiceAddLinesLinesParams`, `InvoiceItemParams`, `InvoiceItem`, `InvoiceLineItemParams`, `InvoiceLineItem`, and `InvoiceUpdateLinesLinesParams` + * Add support for `Wifi` on `TerminalConfigurationParams` and `TerminalConfiguration` + * Add support for `NzBankTransfer` on `RefundDestinationDetails` + * Add support for new value `canceled` on enum `Review.ClosedReason` + * Add support for `CurrentPeriodEnd` and `CurrentPeriodStart` on `SubscriptionItem` + * Add support for `NaverPay` on `MandatePaymentMethodDetails` and `SetupAttemptPaymentMethodDetails` + * Add support for `SetupFutureUsage` on `PaymentIntentConfirmPaymentMethodOptionsNaverPayParams`, `PaymentIntentPaymentMethodOptionsNaverPayParams`, and `PaymentIntentPaymentMethodOptionsNaverPay` + * Add support for new value `expired` on enum `PaymentIntent.CancellationReason` + * Add support for `DefaultValue` on `PaymentLinkCustomFieldsDropdownParams`, `PaymentLinkCustomFieldsDropdown`, `PaymentLinkCustomFieldsNumericParams`, `PaymentLinkCustomFieldsNumeric`, `PaymentLinkCustomFieldsTextParams`, and `PaymentLinkCustomFieldsText` + * Add support for new values `billie` and `satispay` on enum `PaymentLink.PaymentMethodTypes` + +## 81.4.0 - 2025-02-24 +* [#1986](https://github.com/stripe/stripe-go/pull/1986) Update generated code + * Add support for `Prices` on `BillingCreditBalanceSummaryFilterApplicabilityScopeParams`, `BillingCreditGrantApplicabilityConfigScopeParams`, and `BillingCreditGrantApplicabilityConfigScope` + * Add support for `Priority` on `BillingCreditGrantParams` and `BillingCreditGrant` + * Add support for `TargetDate` on `CheckoutSessionPaymentMethodOptionsAcssDebitParams`, `CheckoutSessionPaymentMethodOptionsAcssDebit`, `CheckoutSessionPaymentMethodOptionsAuBecsDebitParams`, `CheckoutSessionPaymentMethodOptionsAuBecsDebit`, `CheckoutSessionPaymentMethodOptionsBacsDebitParams`, `CheckoutSessionPaymentMethodOptionsBacsDebit`, `CheckoutSessionPaymentMethodOptionsSepaDebitParams`, `CheckoutSessionPaymentMethodOptionsSepaDebit`, `CheckoutSessionPaymentMethodOptionsUsBankAccountParams`, `CheckoutSessionPaymentMethodOptionsUsBankAccount`, `PaymentIntentConfirmPaymentMethodOptionsAcssDebitParams`, `PaymentIntentConfirmPaymentMethodOptionsAuBecsDebitParams`, `PaymentIntentConfirmPaymentMethodOptionsBacsDebitParams`, `PaymentIntentConfirmPaymentMethodOptionsSepaDebitParams`, `PaymentIntentConfirmPaymentMethodOptionsUsBankAccountParams`, `PaymentIntentPaymentMethodOptionsAcssDebitParams`, `PaymentIntentPaymentMethodOptionsAcssDebit`, `PaymentIntentPaymentMethodOptionsAuBecsDebitParams`, `PaymentIntentPaymentMethodOptionsAuBecsDebit`, `PaymentIntentPaymentMethodOptionsBacsDebitParams`, `PaymentIntentPaymentMethodOptionsBacsDebit`, `PaymentIntentPaymentMethodOptionsSepaDebitParams`, `PaymentIntentPaymentMethodOptionsSepaDebit`, `PaymentIntentPaymentMethodOptionsUsBankAccountParams`, and `PaymentIntentPaymentMethodOptionsUsBankAccount` + * Add support for `Restrictions` on `CheckoutSessionPaymentMethodOptionsCardParams` and `CheckoutSessionPaymentMethodOptionsCard` + * Add support for `CollectedInformation` on `CheckoutSessionParams` and `CheckoutSession` + * Add support for `Metadata` on `ProductDefaultPriceDataParams` +* [#1988](https://github.com/stripe/stripe-go/pull/1988) add codeowners file +* [#1985](https://github.com/stripe/stripe-go/pull/1985) Add Stripe Client to example tests +* [#1982](https://github.com/stripe/stripe-go/pull/1982) Add usage data for stripe client usage + * Add telemetry for usage of the Stripe Client +* [#1984](https://github.com/stripe/stripe-go/pull/1984) Revert "Add GetParams methods to root params objects" +* [#1983](https://github.com/stripe/stripe-go/pull/1983) Add GetParams methods to root params objects + * Adds `nil`-safe `GetParams` methods to all top-level Params structs + +## 81.3.1 - 2025-02-03 +* [#1980](https://github.com/stripe/stripe-go/pull/1980) Update generated code + * ⚠️ Fix acronym `JPY` in TerminalConfiguration that were not correctly capitalized + +## 81.3.0 - 2025-01-27 +* [#1965](https://github.com/stripe/stripe-go/pull/1965) Update generated code + * Add support for `Close` method on resource `Treasury.FinancialAccount` + * Add support for `PayByBankPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `DirectorshipDeclaration` and `OwnershipExemptionReason` on `AccountCompanyParams`, `AccountCompany`, and `TokenAccountCompanyParams` + * Add support for `ProofOfUltimateBeneficialOwnership` on `AccountDocumentsParams` + * Add support for `FinancialAccount` on `AccountSessionComponentsParams`, `AccountSessionComponents`, and `TreasuryOutboundTransferDestinationPaymentMethodDetails` + * Add support for `FinancialAccountTransactions`, `IssuingCard`, and `IssuingCardsList` on `AccountSessionComponentsParams` and `AccountSessionComponents` + * Add support for `AdviceCode` on `ChargeOutcome`, `InvoiceLastFinalizationError`, `PaymentIntentLastPaymentError`, `SetupAttemptSetupError`, `SetupIntentLastSetupError`, and `StripeError` + * Add support for `PayByBank` on `ChargePaymentMethodDetails`, `CheckoutSessionPaymentMethodOptionsParams`, `ConfirmationTokenPaymentMethodDataParams`, `ConfirmationTokenPaymentMethodPreview`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodConfigurationParams`, `PaymentMethodConfiguration`, `PaymentMethodParams`, `PaymentMethod`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `Country` on `ChargePaymentMethodDetailsPaypal`, `ConfirmationTokenPaymentMethodPreviewPaypal`, and `PaymentMethodPaypal` + * Add support for `Discounts` on `CheckoutSession` + * Add support for new value `SD` on enums `CheckoutSessionShippingAddressCollectionAllowedCountries` and `PaymentLinkShippingAddressCollectionAllowedCountries` + * Add support for new value `pay_by_bank` on enums `ConfirmationTokenPaymentMethodPreviewType` and `PaymentMethodType` + * Add support for `PhoneNumberCollection` on `PaymentLinkParams` + * Add support for new value `pay_by_bank` on enum `PaymentLinkPaymentMethodTypes` + * Add support for `Jpy` on `TerminalConfigurationTippingParams` and `TerminalConfigurationTipping` + * Add support for `Nickname` on `TreasuryFinancialAccountParams` and `TreasuryFinancialAccount` + * Add support for `ForwardingSettings` on `TreasuryFinancialAccountParams` + * Add support for `IsDefault` on `TreasuryFinancialAccount` + * Add support for `DestinationPaymentMethodData` on `TreasuryOutboundTransferParams` + * Change type of `TreasuryOutboundTransferDestinationPaymentMethodDetailsType` from `literal('us_bank_account')` to `enum('financial_account'|'us_bank_account')` + * Add support for `OutboundTransfer` on `TreasuryReceivedCreditLinkedFlowsSourceFlowDetails` + * Add support for new value `outbound_transfer` on enum `TreasuryReceivedCreditLinkedFlowsSourceFlowDetailsType` +* [#1970](https://github.com/stripe/stripe-go/pull/1970) fix justfile ordering bug +* [#1969](https://github.com/stripe/stripe-go/pull/1969) pin CI and fix formatting +* [#1964](https://github.com/stripe/stripe-go/pull/1964) add justfile, update readme, remove coveralls +* [#1967](https://github.com/stripe/stripe-go/pull/1967) Added CONTRIBUTING.md file +* [#1962](https://github.com/stripe/stripe-go/pull/1962) Added pull request template + +## 81.2.0 - 2024-12-18 +* [#1957](https://github.com/stripe/stripe-go/pull/1957) This release changes the pinned API version to `2024-12-18.acacia`. + * Add support for `NetworkAdviceCode` and `NetworkDeclineCode` on `ChargeOutcome`, `InvoiceLastFinalizationError`, `PaymentIntentLastPaymentError`, `SetupAttemptSetupError`, `SetupIntentLastSetupError`, and `StripeError` + * Add support for new values `payout_minimum_balance_hold` and `payout_minimum_balance_release` on enum `BalanceTransactionType` + * Add support for `CreditsApplicationInvoiceVoided` on `BillingCreditBalanceTransactionCredit` + * Change type of `BillingCreditBalanceTransactionCreditType` from `literal('credits_granted')` to `enum('credits_application_invoice_voided'|'credits_granted')` + * Add support for `AllowRedisplay` on `Card` and `Source` + * Add support for `RegulatedStatus` on `Card`, `ChargePaymentMethodDetailsCard`, `ConfirmationTokenPaymentMethodPreviewCard`, and `PaymentMethodCard` + * Add support for `Funding` on `ChargePaymentMethodDetailsAmazonPay` and `ChargePaymentMethodDetailsRevolutPay` + * Add support for `NetworkTransactionID` on `ChargePaymentMethodDetailsCard` + * Add support for `ReferencePrefix` on `CheckoutSessionPaymentMethodOptionsBacsDebitMandateOptionsParams`, `CheckoutSessionPaymentMethodOptionsBacsDebitMandateOptions`, `CheckoutSessionPaymentMethodOptionsSepaDebitMandateOptionsParams`, `CheckoutSessionPaymentMethodOptionsSepaDebitMandateOptions`, `PaymentIntentConfirmPaymentMethodOptionsBacsDebitMandateOptionsParams`, `PaymentIntentConfirmPaymentMethodOptionsSepaDebitMandateOptionsParams`, `PaymentIntentPaymentMethodOptionsBacsDebitMandateOptionsParams`, `PaymentIntentPaymentMethodOptionsBacsDebitMandateOptions`, `PaymentIntentPaymentMethodOptionsSepaDebitMandateOptionsParams`, `PaymentIntentPaymentMethodOptionsSepaDebitMandateOptions`, `SetupIntentConfirmPaymentMethodOptionsBacsDebitMandateOptionsParams`, `SetupIntentConfirmPaymentMethodOptionsSepaDebitMandateOptionsParams`, `SetupIntentPaymentMethodOptionsBacsDebitMandateOptionsParams`, `SetupIntentPaymentMethodOptionsBacsDebitMandateOptions`, `SetupIntentPaymentMethodOptionsSepaDebitMandateOptionsParams`, and `SetupIntentPaymentMethodOptionsSepaDebitMandateOptions` + * Add support for new values `al_tin`, `am_tin`, `ao_tin`, `ba_tin`, `bb_tin`, `bs_tin`, `cd_nif`, `gn_nif`, `kh_tin`, `me_pib`, `mk_vat`, `mr_nif`, `np_pan`, `sn_ninea`, `sr_fin`, `tj_tin`, `ug_tin`, `zm_tin`, and `zw_tin` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, `TaxCalculationCustomerDetailsTaxIdsType`, `TaxIdType`, and `TaxTransactionCustomerDetailsTaxIdsType` + * Add support for `VisaCompliance` on `DisputeEvidenceDetailsEnhancedEligibility`, `DisputeEvidenceEnhancedEvidenceParams`, and `DisputeEvidenceEnhancedEvidence` + * Add support for new value `request_signature` on enum `ForwardingRequestReplacements` + * Add support for `AccountHolderAddress` and `BankAddress` on `FundingInstructionsBankTransferFinancialAddressesIban`, `FundingInstructionsBankTransferFinancialAddressesSortCode`, `FundingInstructionsBankTransferFinancialAddressesSpei`, `FundingInstructionsBankTransferFinancialAddressesZengin`, `PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressesIban`, `PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressesSortCode`, `PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressesSpei`, and `PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressesZengin` + * Add support for `AccountHolderName` on `FundingInstructionsBankTransferFinancialAddressesSpei` and `PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressesSpei` + * Add support for `DisabledReason` on `InvoiceAutomaticTax`, `SubscriptionAutomaticTax`, `SubscriptionScheduleDefaultSettingsAutomaticTax`, and `SubscriptionSchedulePhasesAutomaticTax` + * Add support for `TaxID` on `IssuingAuthorizationMerchantData` and `IssuingTransactionMerchantData` + * Add support for `TrialPeriodDays` on `PaymentLinkSubscriptionDataParams` + * Add support for `Al`, `Am`, `Ao`, `Ba`, `Bb`, `Bs`, `Cd`, `Gn`, `Kh`, `Me`, `Mk`, `Mr`, `Np`, `Pe`, `Sn`, `Sr`, `Tj`, `Ug`, `Uy`, `Zm`, and `Zw` on `TaxRegistrationCountryOptionsParams` and `TaxRegistrationCountryOptions` + +## 81.1.1 - 2024-12-05 +* [#1955](https://github.com/stripe/stripe-go/pull/1955) Temporarily add payment_method parameter to BankAccountParams + +## 81.1.0 - 2024-11-20 +* [#1951](https://github.com/stripe/stripe-go/pull/1951) This release changes the pinned API version to `2024-11-20.acacia`. + * Add support for `Respond` test helper method on resource `Issuing.Authorization` + * Add support for `Authorizer` on `AccountPersonsRelationshipParams` and `TokenPersonRelationshipParams` + * Change type of `AccountFutureRequirementsDisabledReason` and `AccountRequirementsDisabledReason` from `string` to `enum` + * Add support for `AdaptivePricing` on `CheckoutSessionParams` and `CheckoutSession` + * Add support for `MandateOptions` on `CheckoutSessionPaymentMethodOptionsBacsDebitParams`, `CheckoutSessionPaymentMethodOptionsBacsDebit`, `CheckoutSessionPaymentMethodOptionsSepaDebitParams`, and `CheckoutSessionPaymentMethodOptionsSepaDebit` + * Add support for `RequestExtendedAuthorization`, `RequestIncrementalAuthorization`, `RequestMulticapture`, and `RequestOvercapture` on `CheckoutSessionPaymentMethodOptionsCardParams` and `CheckoutSessionPaymentMethodOptionsCard` + * Add support for `CaptureMethod` on `CheckoutSessionPaymentMethodOptionsKakaoPayParams`, `CheckoutSessionPaymentMethodOptionsKrCardParams`, `CheckoutSessionPaymentMethodOptionsNaverPayParams`, `CheckoutSessionPaymentMethodOptionsPaycoParams`, and `CheckoutSessionPaymentMethodOptionsSamsungPayParams` + * Add support for new value `li_vat` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, `TaxCalculationCustomerDetailsTaxIdsType`, `TaxIdType`, and `TaxTransactionCustomerDetailsTaxIdsType` + * Add support for new value `subscribe` on enums `CheckoutSessionSubmitType` and `PaymentLinkSubmitType` + * Add support for new value `financial_account_statement` on enum `FilePurpose` + * Add support for `AccountHolderAddress`, `AccountHolderName`, `AccountType`, and `BankAddress` on `FundingInstructionsBankTransferFinancialAddressesAba`, `FundingInstructionsBankTransferFinancialAddressesSwift`, `PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressesAba`, and `PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressesSwift` + * Add support for `MerchantAmount` and `MerchantCurrency` on `IssuingAuthorizationParams` + * Add support for `FraudChallenges` and `VerifiedByFraudChallenge` on `IssuingAuthorization` + * Add support for new value `link` on enums `PaymentIntentPaymentMethodOptionsCardNetwork`, `SetupIntentPaymentMethodOptionsCardNetwork`, and `SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork` + * Add support for `SubmitType` on `PaymentLinkParams` + * Add support for `TraceID` on `Payout` + * Add support for `NetworkDeclineCode` on `RefundDestinationDetailsBlik` and `RefundDestinationDetailsSwish` + * Add support for new value `service_tax` on enums `TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType`, `TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType`, `TaxCalculationTaxBreakdownTaxRateDetailsTaxType`, `TaxRateTaxType`, and `TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType` + +## 81.0.0 - 2024-10-29 + +Historically, when upgrading webhooks to a new API version, you also had to upgrade your SDK version. Your webhook's API version needed to match the API version pinned by the SDK you were using to ensure successful deserialization of events. With the `2024-09-30.acacia` release, Stripe follows a [new API release process](https://stripe.com/blog/introducing-stripes-new-api-release-process). As a result, you can safely upgrade your webhook endpoints to any API version within a biannual release (like `acacia`) without upgrading the SDK. + +However, [a bug](https://github.com/stripe/stripe-go/pull/1940) in the `80.x.y` SDK releases meant that webhook version upgrades from the SDK's pinned `2024-09-30.acacia` version to the new `2024-10-28.acacia` version would fail. Therefore, we are shipping SDK support for `2024-10-28.acacia` as a major version to enforce the idea that an SDK upgrade is also required. Future API versions in the `acacia` line will be released as minor versions. + +* [#1931](https://github.com/stripe/stripe-go/pull/1931) This release changes the pinned API version to `2024-10-28.acacia`. + * Add support for new resource `V2.EventDestinations` + * Add support for `New`, `Retrieve`, `Update`, `List`, `Delete`, `Disable`, `Enable` and `Ping` methods on resource `V2.EventDestinations` + * Add support for `SubmitCard` test helper method on resource `Issuing.Card` + * Add support for `Groups` on `AccountParams` and `Account` + * Add support for `AlmaPayments`, `KakaoPayPayments`, `KrCardPayments`, `NaverPayPayments`, `PaycoPayments`, and `SamsungPayPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `DisableStripeUserAuthentication` on `AccountSessionComponentsAccountManagementFeaturesParams`, `AccountSessionComponentsAccountManagementFeatures`, `AccountSessionComponentsAccountOnboardingFeaturesParams`, `AccountSessionComponentsAccountOnboardingFeatures`, `AccountSessionComponentsBalancesFeaturesParams`, `AccountSessionComponentsBalancesFeatures`, `AccountSessionComponentsNotificationBannerFeaturesParams`, `AccountSessionComponentsNotificationBannerFeatures`, `AccountSessionComponentsPayoutsFeaturesParams`, and `AccountSessionComponentsPayoutsFeatures` + * Add support for `ScheduleAtPeriodEnd` on `BillingPortalConfigurationFeaturesSubscriptionUpdateParams` and `BillingPortalConfigurationFeaturesSubscriptionUpdate` + * Add support for `Alma` on `ChargePaymentMethodDetails`, `ConfirmationTokenPaymentMethodDataParams`, `ConfirmationTokenPaymentMethodPreview`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodConfigurationParams`, `PaymentMethodConfiguration`, `PaymentMethodParams`, `PaymentMethod`, `RefundDestinationDetails`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `KakaoPay` and `KrCard` on `ChargePaymentMethodDetails`, `CheckoutSessionPaymentMethodOptionsParams`, `CheckoutSessionPaymentMethodOptions`, `ConfirmationTokenPaymentMethodDataParams`, `ConfirmationTokenPaymentMethodPreview`, `MandatePaymentMethodDetails`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupAttemptPaymentMethodDetails`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `NaverPay` on `ChargePaymentMethodDetails`, `CheckoutSessionPaymentMethodOptionsParams`, `CheckoutSessionPaymentMethodOptions`, `ConfirmationTokenPaymentMethodDataParams`, `ConfirmationTokenPaymentMethodPreview`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `Payco` and `SamsungPay` on `ChargePaymentMethodDetails`, `CheckoutSessionPaymentMethodOptionsParams`, `CheckoutSessionPaymentMethodOptions`, `ConfirmationTokenPaymentMethodDataParams`, `ConfirmationTokenPaymentMethodPreview`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for new values `by_tin`, `ma_vat`, `md_vat`, `tz_vat`, `uz_tin`, and `uz_vat` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, `TaxCalculationCustomerDetailsTaxIdsType`, `TaxIdType`, and `TaxTransactionCustomerDetailsTaxIdsType` + * Add support for new values `alma`, `kakao_pay`, `kr_card`, `naver_pay`, `payco`, and `samsung_pay` on enums `ConfirmationTokenPaymentMethodPreviewType` and `PaymentMethodType` + * Add support for `EnhancedEvidence` on `DisputeEvidenceParams` and `DisputeEvidence` + * Add support for `EnhancedEligibilityTypes` on `Dispute` + * Add support for `EnhancedEligibility` on `DisputeEvidenceDetails` + * Add support for new values `issuing_transaction.purchase_details_receipt_updated` and `refund.failed` on enum `EventType` + * Add support for `Metadata` on `ForwardingRequestParams` and `ForwardingRequest` + * Add support for `AutomaticallyFinalizesAt` on `InvoiceParams` + * Add support for new values `jp_credit_transfer`, `kakao_pay`, `kr_card`, `naver_pay`, and `payco` on enums `InvoicePaymentSettingsPaymentMethodTypes` and `SubscriptionPaymentSettingsPaymentMethodTypes` + * Add support for new value `alma` on enum `PaymentLinkPaymentMethodTypes` + * Add support for `AmazonPay` on `PaymentMethodDomain` + * Change type of `RefundNextActionDisplayDetails` from `nullable(RefundNextActionDisplayDetails)` to `RefundNextActionDisplayDetails` + * Add support for new value `retail_delivery_fee` on enums `TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType`, `TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType`, `TaxCalculationTaxBreakdownTaxRateDetailsTaxType`, `TaxRateTaxType`, and `TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType` + * Add support for `FlatAmount` and `RateType` on `TaxCalculationTaxBreakdownTaxRateDetails` and `TaxRate` + * Add support for `By`, `Cr`, `Ec`, `Ma`, `Md`, `RU`, `Rs`, `Tz`, and `Uz` on `TaxRegistrationCountryOptionsParams` and `TaxRegistrationCountryOptions` + * Add support for new value `state_retail_delivery_fee` on enum `TaxRegistrationCountryOptionsUsType` + * Add support for `Pln` on `TerminalConfigurationTippingParams` and `TerminalConfigurationTipping` + +## 80.2.1 - 2024-10-29 +* [#1940](https://github.com/stripe/stripe-go/pull/1940) Update webhook API version validation + - Update webhook event processing to accept events from any API version within the supported major release + +## 80.2.0 - 2024-10-09 +* [#1929](https://github.com/stripe/stripe-go/pull/1929), [#1933](https://github.com/stripe/stripe-go/pull/1933) Remove rawrequests Post, Get, and Delete in favor of rawrequests.Client + * The individual `rawrequests` functions for Post, Get, and Delete methods are removed in favor of the client model which allows local configuration of backend and api key, which enables more flexible calls to new/preview/unsupported APIs. + +## 80.1.0 - 2024-10-03 +* [#1928](https://github.com/stripe/stripe-go/pull/1928) Update generated code + * Remove the support for resource `Margin` that was accidentally made public in the last release + +## 80.0.0 - 2024-10-01 +* [#1926](https://github.com/stripe/stripe-go/pull/1926) Support for APIs in the new API version 2024-09-30.acacia + + This release changes the pinned API version to `2024-09-30.acacia`. Please read the [API Changelog](https://docs.stripe.com/changelog/acacia#2024-09-30.acacia) and carefully review the API changes before upgrading. + + ### ⚠️ Breaking changes + + * Rename `usage_threshold_config` to `usage_threshold` on `BillingAlertParams` and `BillingAlert` + * Remove support for `filter` on `BillingAlertParams` and `BillingAlert`. Use the filters on the `usage_threshold` instead + * Remove support for `CustomerConsentCollected` on `TerminalReaderProcessSetupIntentParams` + + + ### Additions + * Add support for `CustomUnitAmount` on `ProductDefaultPriceDataParams` + * Add support for `AllowRedisplay` on `TerminalReaderProcessPaymentIntentProcessConfigParams` and `TerminalReaderProcessSetupIntentParams` + * Add support for new value `international_transaction` on enum `TreasuryReceivedCreditFailureCode` + * Add method [RawRequest()](https://github.com/stripe/stripe-go/tree/master?tab=readme-ov-file#custom-requests) that takes a HTTP method type, url and relevant parameters to make requests to the Stripe API that are not yet supported in the SDK. + +## 79.12.0 - 2024-09-18 +* [#1919](https://github.com/stripe/stripe-go/pull/1919) Update generated code + * Add support for new value `international_transaction` on enum `TreasuryReceivedDebitFailureCode` +* [#1918](https://github.com/stripe/stripe-go/pull/1918) Update generated code + * Add support for new value `verification_supportability` on enums `AccountFutureRequirementsErrorsCode`, `AccountRequirementsErrorsCode`, `BankAccountFutureRequirementsErrorsCode`, and `BankAccountRequirementsErrorsCode` + * Add support for new value `terminal_reader_invalid_location_for_activation` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Add support for `PayerDetails` on `ChargePaymentMethodDetailsKlarna` + * Add support for `AmazonPay` on `DisputePaymentMethodDetails` + * Add support for new value `amazon_pay` on enum `DisputePaymentMethodDetailsType` + * Add support for `AutomaticallyFinalizesAt` on `Invoice` + * Add support for `StateSalesTax` on `TaxRegistrationCountryOptionsUsParams` and `TaxRegistrationCountryOptionsUs` + +## 79.11.0 - 2024-09-12 +* [#1912](https://github.com/stripe/stripe-go/pull/1912) Update generated code + * Add support for new resource `InvoiceRenderingTemplate` + * Add support for `Archive`, `Get`, `List`, and `Unarchive` methods on resource `InvoiceRenderingTemplate` + * Add support for `Required` on `CheckoutSessionTaxIdCollectionParams`, `CheckoutSessionTaxIdCollection`, `PaymentLinkTaxIdCollectionParams`, and `PaymentLinkTaxIdCollection` + * Add support for `Template` on `CustomerInvoiceSettingsRenderingOptionsParams`, `CustomerInvoiceSettingsRenderingOptions`, `InvoiceRenderingParams`, and `InvoiceRendering` + * Add support for `TemplateVersion` on `InvoiceRenderingParams` and `InvoiceRendering` + * Add support for new value `submitted` on enum `IssuingCardShippingStatus` + +## 79.10.0 - 2024-09-05 +* [#1906](https://github.com/stripe/stripe-go/pull/1906) Update generated code + * Add support for `SubscriptionItem` and `Subscription` on `BillingAlertFilterParams` + +## 79.9.0 - 2024-08-29 +* [#1910](https://github.com/stripe/stripe-go/pull/1910) Generate SDK for OpenAPI spec version 1230 + * Add support for new value `hr_oib` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, `TaxCalculationCustomerDetailsTaxIdsType`, `TaxIdType`, and `TaxTransactionCustomerDetailsTaxIdsType` + * Add support for new value `issuing_regulatory_reporting` on enum `FilePurpose` + * Add support for `StatusDetails` on `TestHelpersTestClock` + +## 79.8.0 - 2024-08-15 +* [#1904](https://github.com/stripe/stripe-go/pull/1904) Update generated code + * Add support for `AuthorizationCode` on `ChargePaymentMethodDetailsCard` + * Add support for `Wallet` on `ChargePaymentMethodDetailsCardPresent`, `ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresent`, `ConfirmationTokenPaymentMethodPreviewCardPresent`, `PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresent`, and `PaymentMethodCardPresent` + * Add support for `MandateOptions` on `PaymentIntentConfirmPaymentMethodOptionsBacsDebitParams`, `PaymentIntentPaymentMethodOptionsBacsDebitParams`, and `PaymentIntentPaymentMethodOptionsBacsDebit` + * Add support for `BACSDebit` on `SetupIntentConfirmPaymentMethodOptionsParams`, `SetupIntentPaymentMethodOptionsParams`, and `SetupIntentPaymentMethodOptions` + * Add support for `Chips` on `TreasuryOutboundPaymentTrackingDetailsUsDomesticWireParams`, `TreasuryOutboundPaymentTrackingDetailsUsDomesticWire`, `TreasuryOutboundTransferTrackingDetailsUsDomesticWireParams`, and `TreasuryOutboundTransferTrackingDetailsUsDomesticWire` +* [#1903](https://github.com/stripe/stripe-go/pull/1903) Use pinned version of staticcheck + +## 79.7.0 - 2024-08-08 +* [#1899](https://github.com/stripe/stripe-go/pull/1899) Update generated code + * Add support for `Activate`, `Archive`, `Deactivate`, `Get`, `List`, and `New` methods on resource `Billing.Alert` + * Add support for `Get` method on resource `Tax.Calculation` + * Add support for new value `invalid_mandate_reference_prefix_format` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Add support for `Type` on `ChargePaymentMethodDetailsCardPresentOffline`, `ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentOffline`, `PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentOffline`, and `SetupAttemptPaymentMethodDetailsCardPresentOffline` + * Add support for `Offline` on `ConfirmationTokenPaymentMethodPreviewCardPresent` and `PaymentMethodCardPresent` + * Add support for `RelatedCustomer` on `IdentityVerificationSessionListParams`, `IdentityVerificationSessionParams`, and `IdentityVerificationSession` + * Add support for new value `girocard` on enums `PaymentIntentPaymentMethodOptionsCardNetwork`, `SetupIntentPaymentMethodOptionsCardNetwork`, and `SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork` + * Add support for new value `financial_addresses.aba.forwarding` on enums `TreasuryFinancialAccountActiveFeatures`, `TreasuryFinancialAccountPendingFeatures`, and `TreasuryFinancialAccountRestrictedFeatures` + +## 79.6.0 - 2024-08-01 +* [#1897](https://github.com/stripe/stripe-go/pull/1897) Update generated code + * Add support for new resources `Billing.AlertTriggered` and `Billing.Alert` + * Add support for new value `charge_exceeds_transaction_limit` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * ⚠️ Remove support for `AuthorizationCode` on `ChargePaymentMethodDetailsCard`. This was accidentally released last week. + * Add support for new value `billing.alert.triggered` on enum `EventType` +* [#1895](https://github.com/stripe/stripe-go/pull/1895) Fixed config override with GetBackendWithConfig + +## 79.5.0 - 2024-07-25 +* [#1896](https://github.com/stripe/stripe-go/pull/1896) Update generated code + * Add support for `TaxRegistrations` and `TaxSettings` on `AccountSessionComponentsParams` and `AccountSessionComponents` +* [#1892](https://github.com/stripe/stripe-go/pull/1892) Update generated code + * Add support for `Update` method on resource `Checkout.Session` + * Add support for `TransactionID` on `ChargePaymentMethodDetailsAffirm` + * Add support for `BuyerID` on `ChargePaymentMethodDetailsBlik` + * Add support for `AuthorizationCode` on `ChargePaymentMethodDetailsCard` + * Add support for `BrandProduct` on `ChargePaymentMethodDetailsCardPresent`, `ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresent`, `ConfirmationTokenPaymentMethodPreviewCardPresent`, `PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresent`, and `PaymentMethodCardPresent` + * Add support for `NetworkTransactionID` on `ChargePaymentMethodDetailsCardPresent`, `ChargePaymentMethodDetailsInteracPresent`, `ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresent`, and `PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresent` + * Add support for `CaseType` on `DisputePaymentMethodDetailsCard` + * Add support for new values `invoice.overdue` and `invoice.will_be_due` on enum `EventType` + * Add support for `TWINT` on `PaymentMethodConfigurationParams` and `PaymentMethodConfiguration` + +## 79.4.0 - 2024-07-18 +* [#1890](https://github.com/stripe/stripe-go/pull/1890) Update generated code + * Add support for `Customer` on `ConfirmationTokenPaymentMethodPreview` + * Add support for new value `issuing_dispute.funds_rescinded` on enum `EventType` + * Add support for new value `multibanco` on enums `InvoicePaymentSettingsPaymentMethodTypes` and `SubscriptionPaymentSettingsPaymentMethodTypes` + * Add support for new value `stripe_s700` on enum `TerminalReaderDeviceType` +* [#1888](https://github.com/stripe/stripe-go/pull/1888) Update changelog + +## 79.3.0 - 2024-07-11 +* [#1886](https://github.com/stripe/stripe-go/pull/1886) Update generated code + * ⚠️ Remove support for values `billing_policy_remote_function_response_invalid`, `billing_policy_remote_function_timeout`, `billing_policy_remote_function_unexpected_status_code`, and `billing_policy_remote_function_unreachable` from enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode`. + * ⚠️ Remove support for value `payment_intent_fx_quote_invalid` from enum `StripeErrorCode`. The was mistakenly released last week. + * Add support for `PaymentMethodOptions` on `ConfirmationToken` + * Add support for `PaymentElement` on `CustomerSessionComponentsParams` and `CustomerSessionComponents` + * Add support for `AddressValidation` on `IssuingCardShippingParams` and `IssuingCardShipping` + * Add support for `Shipping` on `IssuingCardParams` + +## 79.2.0 - 2024-07-05 +* [#1881](https://github.com/stripe/stripe-go/pull/1881) Update generated code + * Add support for `AddLines`, `RemoveLines`, and `UpdateLines` methods on resource `Invoice` + * Add support for new value `payment_intent_fx_quote_invalid` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Add support for `PostedAt` on `TaxTransactionCreateFromCalculationParams` and `TaxTransaction` + +## 79.1.0 - 2024-06-27 +* [#1879](https://github.com/stripe/stripe-go/pull/1879) Update generated code + * Add support for `Filters` on `CheckoutSessionPaymentMethodOptionsUsBankAccountFinancialConnections`, `InvoicePaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsParams`, `InvoicePaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnections`, `PaymentIntentConfirmPaymentMethodOptionsUsBankAccountFinancialConnectionsParams`, `PaymentIntentPaymentMethodOptionsUsBankAccountFinancialConnectionsParams`, `PaymentIntentPaymentMethodOptionsUsBankAccountFinancialConnections`, `SetupIntentConfirmPaymentMethodOptionsUsBankAccountFinancialConnectionsParams`, `SetupIntentPaymentMethodOptionsUsBankAccountFinancialConnectionsParams`, `SetupIntentPaymentMethodOptionsUsBankAccountFinancialConnections`, `SubscriptionPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsParams`, and `SubscriptionPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnections` + * Add support for `EmailType` on `CreditNoteParams`, `CreditNotePreviewLinesParams`, and `CreditNotePreviewParams` + * Add support for `AccountSubcategories` on `FinancialConnectionsSessionFiltersParams` and `FinancialConnectionsSessionFilters` + * Add support for new values `multibanco`, `twint`, and `zip` on enum `PaymentLinkPaymentMethodTypes` + * Add support for `RebootWindow` on `TerminalConfigurationParams` and `TerminalConfiguration` +* [#1880](https://github.com/stripe/stripe-go/pull/1880) Add object param to list method for BankAccount/Card + * Add support to `object` in `BankAccountListParams` and `CardListParams` + +## 79.0.0 - 2024-06-24 +* [#1878](https://github.com/stripe/stripe-go/pull/1878) Update generated code + + This release changes the pinned API version to 2024-06-20. Please read the [API Changelog](https://docs.stripe.com/changelog/2024-06-20) and carefully review the API changes before upgrading. + + ### ⚠️ Breaking changes + + * Remove the unused resource `PlatformTaxFee` + * Rename `VolumeDecimal` to `QuantityDecimal` on `IssuingTransactionPurchaseDetailsFuel`, `TestHelpersIssuingAuthorizationCapturePurchaseDetailsFuelParams`, `TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFuelParams`, and `TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFuelParams` + + ## Additions + + * Add support for `FinalizeAmount` test helper method on resource `Issuing.Authorization` + * Add support for new value `ch_uid` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, `TaxCalculationCustomerDetailsTaxIdsType`, `TaxIdType`, and `TaxTransactionCustomerDetailsTaxIdsType` + * Add support for `Fleet` on `IssuingAuthorizationParams`, `IssuingAuthorization`, `IssuingTransactionPurchaseDetails`, `TestHelpersIssuingAuthorizationCapturePurchaseDetailsParams`, `TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsParams`, and `TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsParams` + * Add support for `Fuel` on `IssuingAuthorizationParams` and `IssuingAuthorization` + * Add support for `IndustryProductCode` and `QuantityDecimal` on `IssuingTransactionPurchaseDetailsFuel`, `TestHelpersIssuingAuthorizationCapturePurchaseDetailsFuelParams`, `TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFuelParams`, and `TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFuelParams` + * Add support for new values `card_canceled`, `card_expired`, `cardholder_blocked`, `insecure_authorization_method`, and `pin_blocked` on enum `IssuingAuthorizationRequestHistoryReason` + +## 78.12.0 - 2024-06-17 +* [#1876](https://github.com/stripe/stripe-go/pull/1876) Update generated code + * Add support for `TaxIDCollection` on `PaymentLinkParams` + * Add support for new value `mobilepay` on enum `PaymentLinkPaymentMethodTypes` + +## 78.11.0 - 2024-06-13 +* [#1871](https://github.com/stripe/stripe-go/pull/1871) Update generated code + * Add support for `MultibancoPayments` and `TWINTPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `TWINT` on `ChargePaymentMethodDetails`, `ConfirmationTokenPaymentMethodDataParams`, `ConfirmationTokenPaymentMethodPreview`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `Multibanco` on `CheckoutSessionPaymentMethodOptionsParams`, `CheckoutSessionPaymentMethodOptions`, `ConfirmationTokenPaymentMethodDataParams`, `ConfirmationTokenPaymentMethodPreview`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodConfigurationParams`, `PaymentMethodConfiguration`, `PaymentMethodParams`, `PaymentMethod`, `RefundDestinationDetails`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for new value `de_stn` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, `TaxCalculationCustomerDetailsTaxIdsType`, `TaxIdType`, and `TaxTransactionCustomerDetailsTaxIdsType` + * Add support for new values `multibanco` and `twint` on enums `ConfirmationTokenPaymentMethodPreviewType` and `PaymentMethodType` + * Add support for `MultibancoDisplayDetails` on `PaymentIntentNextAction` + * Add support for `InvoiceSettings` on `Subscription` + +## 78.10.0 - 2024-06-06 +* [#1870](https://github.com/stripe/stripe-go/pull/1870) Update generated code + * Add support for `GBBankTransferPayments`, `JPBankTransferPayments`, `MXBankTransferPayments`, `SEPABankTransferPayments`, and `USBankTransferPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for new value `swish` on enums `InvoicePaymentSettingsPaymentMethodTypes` and `SubscriptionPaymentSettingsPaymentMethodTypes` + +## 78.9.0 - 2024-05-30 +* [#1868](https://github.com/stripe/stripe-go/pull/1868) Update generated code + * Add support for new value `verification_requires_additional_proof_of_registration` on enums `AccountFutureRequirementsErrorsCode`, `AccountRequirementsErrorsCode`, `BankAccountFutureRequirementsErrorsCode`, and `BankAccountRequirementsErrorsCode` + * Add support for `DefaultValue` on `CheckoutSessionCustomFieldsDropdownParams`, `CheckoutSessionCustomFieldsDropdown`, `CheckoutSessionCustomFieldsNumericParams`, `CheckoutSessionCustomFieldsNumeric`, `CheckoutSessionCustomFieldsTextParams`, and `CheckoutSessionCustomFieldsText` + * Add support for `GeneratedFrom` on `ConfirmationTokenPaymentMethodPreviewCard` and `PaymentMethodCard` + * Add support for new values `issuing_personalization_design.activated`, `issuing_personalization_design.deactivated`, `issuing_personalization_design.rejected`, and `issuing_personalization_design.updated` on enum `EventType` + +## 78.8.0 - 2024-05-23 +* [#1864](https://github.com/stripe/stripe-go/pull/1864) Update generated code + * Add support for `ExternalAccountCollection` on `AccountSessionComponentsBalancesFeaturesParams`, `AccountSessionComponentsBalancesFeatures`, `AccountSessionComponentsPayoutsFeaturesParams`, and `AccountSessionComponentsPayoutsFeatures` + * Add support for new value `terminal_reader_invalid_location_for_payment` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Add support for `PaymentMethodRemove` on `CheckoutSessionSavedPaymentMethodOptions` + +## 78.7.0 - 2024-05-16 +* [#1862](https://github.com/stripe/stripe-go/pull/1862) Update generated code + * Add support for `FeeSource` on `ApplicationFee` + * Add support for `NetAvailable` on `BalanceInstantAvailable` + * Add support for `PreferredLocales` on `ChargePaymentMethodDetailsCardPresent`, `ConfirmationTokenPaymentMethodPreviewCardPresent`, and `PaymentMethodCardPresent` + * Add support for `Klarna` on `DisputePaymentMethodDetails` + * Add support for new value `klarna` on enum `DisputePaymentMethodDetailsType` + * Add support for `Archived` and `LookupKey` on `EntitlementsFeatureListParams` + * Add support for `NoValidAuthorization` on `IssuingDisputeEvidenceParams` and `IssuingDisputeEvidence` + * Add support for `LossReason` on `IssuingDispute` + * Add support for new value `no_valid_authorization` on enum `IssuingDisputeEvidenceReason` + * Add support for `Routing` on `PaymentIntentConfirmPaymentMethodOptionsCardPresentParams`, `PaymentIntentPaymentMethodOptionsCardPresentParams`, and `PaymentIntentPaymentMethodOptionsCardPresent` + * Add support for `ApplicationFeeAmount` and `ApplicationFee` on `Payout` + * Add support for `StripeS700` on `TerminalConfigurationParams` and `TerminalConfiguration` + +## 78.6.0 - 2024-05-09 +* [#1858](https://github.com/stripe/stripe-go/pull/1858) Update generated code + * Add support for `Update` test helper method on resources `Treasury.OutboundPayment` and `Treasury.OutboundTransfer` + * Add support for `AllowRedisplay` on `ConfirmationTokenPaymentMethodPreview` and `PaymentMethod` + * Add support for new values `treasury.outbound_payment.tracking_details_updated` and `treasury.outbound_transfer.tracking_details_updated` on enum `EventType` + * Add support for `PreviewMode` on `InvoiceCreatePreviewParams`, `InvoiceUpcomingLinesParams`, and `InvoiceUpcomingParams` + * Add support for `TrackingDetails` on `TreasuryOutboundPayment` and `TreasuryOutboundTransfer` +* [#1859](https://github.com/stripe/stripe-go/pull/1859) Update method descriptions to reflect OpenAPI + +## 78.5.0 - 2024-05-02 +* [#1853](https://github.com/stripe/stripe-go/pull/1853) Update generated code + * Add support for new value `shipping_address_invalid` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Add support for `Paypal` on `DisputePaymentMethodDetails` + * Change type of `DisputePaymentMethodDetailsType` from `literal('card')` to `enum('card'|'paypal')` + * Change type of `EntitlementsFeatureMetadataParams` from `map(string: string)` to `emptyable(map(string: string))` + * Add support for `PaymentMethodTypes` on `PaymentIntentConfirmParams` + * Add support for `ShipFromDetails` on `TaxCalculationParams`, `TaxCalculation`, and `TaxTransaction` + * Add support for `Bh`, `Eg`, `Ge`, `Ke`, `Kz`, `Ng`, and `Om` on `TaxRegistrationCountryOptionsParams` and `TaxRegistrationCountryOptions` +* [#1856](https://github.com/stripe/stripe-go/pull/1856) Deprecate Go methods and Params + - Mark as deprecated the `Approve` and `Decline` methods on `issuing/authorization/client.go`. Instead, [respond directly to the webhook request to approve an authorization](https://stripe.com/docs/issuing/controls/real-time-authorizations#authorization-handling). + - Mark as deprecated the `persistent_token` property on `ConfirmationTokenPaymentMethodPreviewLink.persistent_token`, `PaymentIntentPaymentMethodOptionsLink`, `PaymentIntentPaymentMethodOptionsLinkParams`, `PaymentMethodLink`, `SetupIntentPaymentMethodOptionsCard`, `SetupIntentPaymentMethodOptionsLinkParams`. This is a legacy parameter that no longer has any function. + +## 78.4.0 - 2024-04-25 +* [#1852](https://github.com/stripe/stripe-go/pull/1852) Update generated code + * Add support for `SetupFutureUsage` on `CheckoutSessionPaymentMethodOptionsAmazonPay`, `CheckoutSessionPaymentMethodOptionsRevolutPay`, `PaymentIntentPaymentMethodOptionsAmazonPay`, and `PaymentIntentPaymentMethodOptionsRevolutPay` + * Change type of `EntitlementsActiveEntitlementFeature` from `string` to `*EntitlementsFeature` + * Remove support for inadvertently released identity verification features `Email` and `Phone` on `IdentityVerificationSessionOptionsParams` + * Add support for new values `amazon_pay` and `revolut_pay` on enums `InvoicePaymentSettingsPaymentMethodTypes` and `SubscriptionPaymentSettingsPaymentMethodTypes` + * Add support for `AmazonPay` and `RevolutPay` on `MandatePaymentMethodDetails` and `SetupAttemptPaymentMethodDetails` + * Add support for `EndingBefore`, `Limit`, and `StartingAfter` on `PaymentMethodConfigurationListParams` + * Add support for `Mobilepay` on `PaymentMethodConfigurationParams` and `PaymentMethodConfiguration` + +## 78.3.0 - 2024-04-18 +* [#1849](https://github.com/stripe/stripe-go/pull/1849) Update generated code + * Add support for `CreatePreview` method on resource `Invoice` + * Add support for `PaymentMethodData` on `CheckoutSessionParams` + * Add support for `SavedPaymentMethodOptions` on `CheckoutSessionParams` and `CheckoutSession` + * Add support for `Mobilepay` on `CheckoutSessionPaymentMethodOptionsParams` and `CheckoutSessionPaymentMethodOptions` + * Add support for `AllowRedisplay` on `ConfirmationTokenPaymentMethodDataParams`, `CustomerListPaymentMethodsParams`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentMethodParams`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `ScheduleDetails` and `SubscriptionDetails` on `InvoiceUpcomingLinesParams` and `InvoiceUpcomingParams` + +## 78.2.0 - 2024-04-16 +* [#1847](https://github.com/stripe/stripe-go/pull/1847) Update generated code + * Add support for new resource `Entitlements.ActiveEntitlementSummary` + * Add support for `Balances` and `PayoutsList` on `AccountSessionComponentsParams` and `AccountSessionComponents` + * Add support for new value `entitlements.active_entitlement_summary.updated` on enum `EventType` + * Remove support for `Config` on `ForwardingRequestParams` and `ForwardingRequest`. This field is no longer used by the Forwarding Request API. + * Add support for `CaptureMethod` on `PaymentIntentConfirmPaymentMethodOptionsRevolutPayParams`, `PaymentIntentPaymentMethodOptionsRevolutPayParams`, and `PaymentIntentPaymentMethodOptionsRevolutPay` + * Add support for `Swish` on `PaymentMethodConfigurationParams` and `PaymentMethodConfiguration` + +## 78.1.0 - 2024-04-11 +* [#1846](https://github.com/stripe/stripe-go/pull/1846) Update generated code + * Add support for `AccountManagement` and `NotificationBanner` on `AccountSessionComponentsParams` and `AccountSessionComponents` + * Add support for `ExternalAccountCollection` on `AccountSessionComponentsAccountOnboardingFeaturesParams` and `AccountSessionComponentsAccountOnboardingFeatures` + * Add support for new values `billing_policy_remote_function_response_invalid`, `billing_policy_remote_function_timeout`, `billing_policy_remote_function_unexpected_status_code`, and `billing_policy_remote_function_unreachable` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Change type of `BillingMeterEventAdjustmentCancel` from `BillingMeterResourceBillingMeterEventAdjustmentCancel` to `nullable(BillingMeterResourceBillingMeterEventAdjustmentCancel)` + * Add support for `AmazonPay` on `ChargePaymentMethodDetails`, `CheckoutSessionPaymentMethodOptionsParams`, `CheckoutSessionPaymentMethodOptions`, `ConfirmationTokenPaymentMethodDataParams`, `ConfirmationTokenPaymentMethodPreview`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodConfigurationParams`, `PaymentMethodConfiguration`, `PaymentMethodParams`, `PaymentMethod`, `RefundDestinationDetails`, `SetupIntentConfirmPaymentMethodDataParams`, `SetupIntentConfirmPaymentMethodOptionsParams`, `SetupIntentPaymentMethodDataParams`, `SetupIntentPaymentMethodOptionsParams`, and `SetupIntentPaymentMethodOptions` + * Add support for new values `bh_vat`, `kz_bin`, `ng_tin`, and `om_vat` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, `TaxCalculationCustomerDetailsTaxIdsType`, `TaxIdType`, and `TaxTransactionCustomerDetailsTaxIdsType` + * Add support for new value `ownership` on enums `CheckoutSessionPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch`, `InvoicePaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch`, `PaymentIntentPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch`, `SetupIntentPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch`, and `SubscriptionPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch` + * Add support for new value `amazon_pay` on enums `ConfirmationTokenPaymentMethodPreviewType` and `PaymentMethodType` + * Add support for `NextRefreshAvailableAt` on `FinancialConnectionsAccountOwnershipRefresh` + * Add support for new value `ownership` on enums `InvoicePaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsPermissions` and `SubscriptionPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsPermissions` + +## 78.0.0 - 2024-04-10 +* [#1841](https://github.com/stripe/stripe-go/pull/1841) + + * This release changes the pinned API version to `2024-04-10`. Please read the [API Changelog](https://docs.stripe.com/changelog/2024-04-10) and carefully review the API changes before upgrading. + + ### ⚠️ Breaking changes + + * When no `x-stripe-should-retry` header is set in the response, the library now retries all requests with `status >= 500`, not just non-POST methods. + * Change the type on the status of TerminalReader object from string to enum with values of `TerminalReaderStatusOffline` and `TerminalReaderStatusOnline` + * Rename `Features` to `MarketingFeatures` on `ProductCreateOptions`, `ProductUpdateOptions`, and `Product`. + + #### ⚠️ Removal of enum values, properties and events that are no longer part of the publicly documented Stripe API + * Remove `SubscriptionPause` from `BillingPortalConfigurationFeatures ` and `BillingPortalConfigurationFeaturesParams ` as the feature to pause subscription on the portal has been deprecated. + * Remove deprecated values for the `BalanceTransactionType` enum by removing the below constants + * `BalanceTransactionTypeObligationInbound` + * `BalanceTransactionTypeObligationPayout` + * `BalanceTransactionTypeObligationPayoutFailure` + * `BalanceTransactionTypeObligationReversalOutbound` + * Remove deprecated value for the `ClimateSupplierRemovalPathway` enum by removing the constant `ClimateSupplierRemovalPathwayVarious` + * Remove deprecated events types + * `EventTypeInvoiceItemUpdated` + * `EventTypeOrderCreated` + * `EventTypeRecipientCreated` + * `EventTypeRecipientDeleted` + * `EventTypeRecipientUpdated` + * `EventTypeSKUCreated` + * `EventTypeSKUDeleted` + * Remove the field `RequestIncrementalAuthorization` on the `PaymentIntentPaymentMethodOptionsCardPresentParams` struct - this was shipped by mistake + * Remove support for `id_bank_transfer`, `multibanco, netbanking`, `pay_by_bank`, and `upi` on `PaymentMethodConfiguration`. TODO - List the affected types and constants + * Remove deprecated value for the `SetupIntentPaymentMethodOptionsCardRequestThreeDSecure` enum by removing the constant `SetupIntentPaymentMethodOptionsCardRequestThreeDSecureChallengeOnly` + * Remove deprecated value for the `TaxRateTaxType` enum by removing the constant `TaxRateTaxTypeServiceTax` + * Remove `PaymentIntentPaymentMethodData*Params` in favor of reusing existing `PaymentMethodData*Params` for all the payment method types. + * Remove `PaymentIntentPaymentMethodDataBLIKParams` in favor of `PaymentMethodDataBLIKParams` + * Remove `PaymentIntentPaymentMethodDataCashAppParams` in favor of `PaymentMethodDataCashAppParams` + * Remove `PaymentIntentPaymentMethodDataCustomerBalanceParams` in favor of `PaymentMethodDataCustomerBalanceParams` + * Remove `PaymentIntentPaymentMethodDataKonbiniParams` in favor of `PaymentMethodDataKonbiniParams` + * Remove `PaymentIntentPaymentMethodDataLinkParams` in favor of `PaymentMethodDataLinkParams` + * Remove `PaymentIntentPaymentMethodDataPayNowParams` in favor of `PaymentMethodDataPayNowParams` + * Remove `PaymentIntentPaymentMethodDataPaypalParams` in favor of `PaymentMethodDataPaypalParams` + * Remove `PaymentIntentPaymentMethodDataPixParams` in favor of `PaymentMethodDataPixParams` + * Remove `PaymentIntentPaymentMethodDataPromptPayParams` in favor of `PaymentMethodDataPromptPayParams` + * Remove `PaymentIntentPaymentMethodDataRevolutPayParams` in favor of `PaymentMethodDataRevolutPayParams` + * Remove `PaymentIntentPaymentMethodDataUSBankAccounParams` in favor of `PaymentMethodDataUSBankAccounParams` + * Remove `PaymentIntentPaymentMethodDataZipParams` in favor of `PaymentMethodDataZipParams` + * Remove the legacy field `InvoiceRenderingOptionsParams` in `Invoice`, `InvoiceParams`. Use `InvoiceRenderingParams` instead. + +## 76.25.0 - 2024-04-09 +* [#1844](https://github.com/stripe/stripe-go/pull/1844) Update generated code + * Add support for new resources `Entitlements.ActiveEntitlement` and `Entitlements.Feature` + * Add support for `Get` and `List` methods on resource `ActiveEntitlement` + * Add support for `Get`, `List`, `New`, and `Update` methods on resource `Feature` + * Add support for `Controller` on `AccountParams` + * Add support for `Fees`, `Losses`, `RequirementCollection`, and `StripeDashboard` on `AccountController` + * Add support for new value `none` on enum `AccountType` + * Add support for `EventName` on `BillingMeterEventAdjustmentParams` and `BillingMeterEventAdjustment` + * Add support for `Cancel` and `Type` on `BillingMeterEventAdjustment` + +## 76.24.0 - 2024-04-04 +* [#1838](https://github.com/stripe/stripe-go/pull/1838) Update generated code + * Change type of `CheckoutSessionPaymentMethodOptionsSwishReferenceParams` from `emptyable(string)` to `string` + * Add support for `SubscriptionItem` on `Discount` + * Add support for `Email` and `Phone` on `IdentityVerificationReport`, `IdentityVerificationSessionOptionsParams`, `IdentityVerificationSessionOptions`, and `IdentityVerificationSessionVerifiedOutputs` + * Add support for `VerificationFlow` on `IdentityVerificationReport`, `IdentityVerificationSessionParams`, and `IdentityVerificationSession` + * Add support for new value `verification_flow` on enums `IdentityVerificationReportType` and `IdentityVerificationSessionType` + * Add support for `ProvidedDetails` on `IdentityVerificationSessionParams` and `IdentityVerificationSession` + * Add support for new values `email_unverified_other`, `email_verification_declined`, `phone_unverified_other`, and `phone_verification_declined` on enum `IdentityVerificationSessionLastErrorCode` + * Add support for `PromotionCode` on `InvoiceDiscountsParams`, `InvoiceItemDiscountsParams`, and `QuoteDiscountsParams` + * Add support for `Discounts` on `InvoiceUpcomingLinesSubscriptionItemsParams`, `InvoiceUpcomingSubscriptionItemsParams`, `QuoteLineItemsParams`, `SubscriptionAddInvoiceItemsParams`, `SubscriptionItemParams`, `SubscriptionItem`, `SubscriptionItemsParams`, `SubscriptionParams`, `SubscriptionSchedulePhasesAddInvoiceItemsParams`, `SubscriptionSchedulePhasesAddInvoiceItems`, `SubscriptionSchedulePhasesItemsParams`, `SubscriptionSchedulePhasesItems`, `SubscriptionSchedulePhasesParams`, `SubscriptionSchedulePhases`, and `Subscription` + * Add support for `AllowedMerchantCountries` and `BlockedMerchantCountries` on `IssuingCardSpendingControlsParams`, `IssuingCardSpendingControls`, `IssuingCardholderSpendingControlsParams`, and `IssuingCardholderSpendingControls` + * Add support for `Zip` on `PaymentMethodConfigurationParams` and `PaymentMethodConfiguration` + * Add support for `Offline` on `SetupAttemptPaymentMethodDetailsCardPresent` + * Add support for `CardPresent` on `SetupIntentConfirmPaymentMethodOptionsParams`, `SetupIntentPaymentMethodOptionsParams`, and `SetupIntentPaymentMethodOptions` + * Add support for new value `mobile_phone_reader` on enum `TerminalReaderDeviceType` + +## 76.23.0 - 2024-03-28 +* [#1830](https://github.com/stripe/stripe-go/pull/1830) Update generated code + * Add support for new resources `Billing.MeterEventAdjustment`, `Billing.MeterEvent`, and `Billing.Meter` + * Add support for `Deactivate`, `Get`, `List`, `New`, `Reactivate`, and `Update` methods on resource `Meter` + * Add support for `New` method on resources `MeterEventAdjustment` and `MeterEvent` + * Add support for `AmazonPayPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for new value `verification_failed_representative_authority` on enums `AccountFutureRequirementsErrorsCode`, `AccountRequirementsErrorsCode`, `BankAccountFutureRequirementsErrorsCode`, and `BankAccountRequirementsErrorsCode` + * Add support for `DestinationOnBehalfOfChargeManagement` on `AccountSessionComponentsPaymentDetailsFeaturesParams`, `AccountSessionComponentsPaymentDetailsFeatures`, `AccountSessionComponentsPaymentsFeaturesParams`, and `AccountSessionComponentsPaymentsFeatures` + * Add support for `Mandate` on `ChargePaymentMethodDetailsUsBankAccount`, `TreasuryInboundTransferOriginPaymentMethodDetailsUsBankAccount`, `TreasuryOutboundPaymentDestinationPaymentMethodDetailsUsBankAccount`, and `TreasuryOutboundTransferDestinationPaymentMethodDetailsUsBankAccount` + * Add support for `SecondLine` on `IssuingCardParams` + * Add support for `Meter` on `PlanParams`, `Plan`, `PriceListRecurringParams`, `PriceRecurringParams`, and `PriceRecurring` + +## 76.22.0 - 2024-03-21 +* [#1828](https://github.com/stripe/stripe-go/pull/1828) Update generated code + * Add support for new resources `ConfirmationToken` and `Forwarding.Request` + * Add support for `Get` method on resource `ConfirmationToken` + * Add support for `Get`, `List`, and `New` methods on resource `Request` + * Add support for `MobilepayPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for new values `forwarding_api_inactive`, `forwarding_api_invalid_parameter`, `forwarding_api_upstream_connection_error`, and `forwarding_api_upstream_connection_timeout` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Add support for `Mobilepay` on `ChargePaymentMethodDetails`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `PaymentReference` on `ChargePaymentMethodDetailsUsBankAccount` + * Add support for `ConfirmationToken` on `PaymentIntentConfirmParams`, `PaymentIntentParams`, `SetupIntentConfirmParams`, and `SetupIntentParams` + * Add support for new value `mobilepay` on enum `PaymentMethodType` + * Add support for `Name` on `TerminalConfigurationParams` and `TerminalConfiguration` + * Add support for `Payout` on `TreasuryReceivedDebitLinkedFlows` + +## 76.21.0 - 2024-03-14 +* [#1824](https://github.com/stripe/stripe-go/pull/1824) Update generated code + * Add support for new resources `Issuing.PersonalizationDesign` and `Issuing.PhysicalBundle` + * Add support for `Get`, `List`, `New`, and `Update` methods on resource `PersonalizationDesign` + * Add support for `Get` and `List` methods on resource `PhysicalBundle` + * Add support for `PersonalizationDesign` on `IssuingCardListParams`, `IssuingCardParams`, and `IssuingCard` + * Change type of `SubscriptionApplicationFeePercentParams` from `number` to `emptyStringable(number)` + * Add support for `SEPADebit` on `SubscriptionPaymentSettingsPaymentMethodOptionsParams` and `SubscriptionPaymentSettingsPaymentMethodOptions` + +## 76.20.0 - 2024-03-07 +* [#1823](https://github.com/stripe/stripe-go/pull/1823) Update generated code + * Add support for `Documents` on `AccountSessionComponentsParams` and `AccountSessionComponents` + * Add support for `RequestThreeDSecure` on `CheckoutSessionPaymentMethodOptionsCardParams` and `CheckoutSessionPaymentMethodOptionsCard` + * Add support for `Created` on `CreditNoteListParams` + * Add support for `SEPADebit` on `InvoicePaymentSettingsPaymentMethodOptionsParams` and `InvoicePaymentSettingsPaymentMethodOptions` + +## 76.19.0 - 2024-02-29 +* [#1818](https://github.com/stripe/stripe-go/pull/1818) Update generated code + * Add support for `Number` on `InvoiceParams` + * Add support for `EnableCustomerCancellation` on `TerminalReaderActionProcessPaymentIntentProcessConfig`, `TerminalReaderActionProcessSetupIntentProcessConfig`, `TerminalReaderProcessPaymentIntentProcessConfigParams`, and `TerminalReaderProcessSetupIntentProcessConfigParams` + * Add support for `RefundPaymentConfig` on `TerminalReaderActionRefundPayment` and `TerminalReaderRefundPaymentParams` +* [#1820](https://github.com/stripe/stripe-go/pull/1820) Update README to use AddBetaVersion +* [#1817](https://github.com/stripe/stripe-go/pull/1817) Fix typo + +## 76.18.0 - 2024-02-22 +* [#1814](https://github.com/stripe/stripe-go/pull/1814) Update generated code + * Add support for `ClientReferenceID` on `IdentityVerificationReportListParams`, `IdentityVerificationReport`, `IdentityVerificationSessionListParams`, `IdentityVerificationSessionParams`, and `IdentityVerificationSession` + * Remove support for value `service_tax` from enum `TaxRateTaxType` + * Add support for `Created` on `TreasuryOutboundPaymentListParams` + +## 76.17.0 - 2024-02-15 +* [#1812](https://github.com/stripe/stripe-go/pull/1812) Update generated code + * Add support for `Networks` on `Card`, `PaymentMethodCardParams`, and `TokenCardParams` + * Add support for new value `no_voec` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, `TaxCalculationCustomerDetailsTaxIdsType`, `TaxIdType`, and `TaxTransactionCustomerDetailsTaxIdsType` + * Add support for new value `financial_connections.account.refreshed_ownership` on enum `EventType` + * Add support for `DisplayBrand` on `PaymentMethodCard` + +## 76.16.0 - 2024-02-08 +* [#1811](https://github.com/stripe/stripe-go/pull/1811) Update generated code + * Add support for new value `velobank` on enums `ChargePaymentMethodDetailsP24Bank` and `PaymentMethodP24Bank` + * Add support for `SetupFutureUsage` on `PaymentIntentConfirmPaymentMethodOptionsBlikParams`, `PaymentIntentPaymentMethodOptionsBlikParams`, and `PaymentIntentPaymentMethodOptionsBlik` + * Add support for `RequireCVCRecollection` on `PaymentIntentConfirmPaymentMethodOptionsCardParams`, `PaymentIntentPaymentMethodOptionsCardParams`, and `PaymentIntentPaymentMethodOptionsCard` + +## 76.15.0 - 2024-02-01 + Release specs are identical. +* [#1805](https://github.com/stripe/stripe-go/pull/1805) Update generated code + * Add support for Swish payment method throughout the API. + * Add support for `Relationship` on `AccountIndividualParams` and `TokenAccountIndividualParams` + * Add support for `Invoices` on `AccountSettingsParams` and `AccountSettings` + * Add support for `AccountTaxIDs` on `SubscriptionInvoiceSettingsParams`, `SubscriptionScheduleDefaultSettingsInvoiceSettingsParams`, `SubscriptionScheduleDefaultSettingsInvoiceSettings`, `SubscriptionSchedulePhasesInvoiceSettingsParams`, and `SubscriptionSchedulePhasesInvoiceSettings` + * Add support for `JurisdictionLevel` on `TaxRate` + +## 76.14.0 - 2024-01-25 +* [#1803](https://github.com/stripe/stripe-go/pull/1803) Update generated code + * Add support for `AnnualRevenue` and `EstimatedWorkerCount` on `AccountBusinessProfileParams` and `AccountBusinessProfile` + * Add support for new value `registered_charity` on enum `AccountCompanyStructure` + * Add support for `CollectionOptions` on `AccountLinkParams` + * Add support for `Liability` on `CheckoutSessionAutomaticTaxParams`, `CheckoutSessionAutomaticTax`, `PaymentLinkAutomaticTaxParams`, `PaymentLinkAutomaticTax`, `QuoteAutomaticTaxParams`, `QuoteAutomaticTax`, `SubscriptionScheduleDefaultSettingsAutomaticTaxParams`, `SubscriptionScheduleDefaultSettingsAutomaticTax`, `SubscriptionSchedulePhasesAutomaticTaxParams`, and `SubscriptionSchedulePhasesAutomaticTax` + * Add support for `Issuer` on `CheckoutSessionInvoiceCreationInvoiceDataParams`, `CheckoutSessionInvoiceCreationInvoiceData`, `PaymentLinkInvoiceCreationInvoiceDataParams`, `PaymentLinkInvoiceCreationInvoiceData`, `QuoteInvoiceSettingsParams`, `QuoteInvoiceSettings`, `SubscriptionScheduleDefaultSettingsInvoiceSettingsParams`, `SubscriptionScheduleDefaultSettingsInvoiceSettings`, `SubscriptionSchedulePhasesInvoiceSettingsParams`, and `SubscriptionSchedulePhasesInvoiceSettings` + * Add support for `InvoiceSettings` on `CheckoutSessionSubscriptionDataParams`, `PaymentLinkSubscriptionDataParams`, and `PaymentLinkSubscriptionData` + * Add support for `PromotionCode` on `InvoiceUpcomingDiscountsParams`, `InvoiceUpcomingInvoiceItemsDiscountsParams`, `InvoiceUpcomingLinesDiscountsParams`, and `InvoiceUpcomingLinesInvoiceItemsDiscountsParams` + * Add support for new value `challenge` on enums `InvoicePaymentSettingsPaymentMethodOptionsCardRequestThreeDSecure` and `SubscriptionPaymentSettingsPaymentMethodOptionsCardRequestThreeDSecure` + * Add support for `AccountType` on `PaymentMethodUsBankAccountParams` +* [#1800](https://github.com/stripe/stripe-go/pull/1800) Update generated code + +* [#1798](https://github.com/stripe/stripe-go/pull/1798) Update generated code + * Add support for new value `nn` on enums `ChargePaymentMethodDetailsIdealBank`, `PaymentMethodIdealBank`, and `SetupAttemptPaymentMethodDetailsIdealBank` + * Add support for `Issuer` on `InvoiceParams`, `InvoiceUpcomingLinesParams`, `InvoiceUpcomingParams`, and `Invoice` + * Add support for `Liability` on `InvoiceAutomaticTaxParams`, `InvoiceAutomaticTax`, `InvoiceUpcomingAutomaticTaxParams`, `InvoiceUpcomingLinesAutomaticTaxParams`, `SubscriptionAutomaticTaxParams`, and `SubscriptionAutomaticTax` + * Add support for `OnBehalfOf` on `InvoiceUpcomingLinesParams` and `InvoiceUpcomingParams` + * Add support for `PIN` on `IssuingCardParams` + * Add support for `RevocationReason` on `MandatePaymentMethodDetailsBacsDebit` + * Add support for `CustomerBalance` on `PaymentMethodConfigurationParams` and `PaymentMethodConfiguration` + * Add support for `InvoiceSettings` on `SubscriptionParams` + +## 76.13.0 - 2024-01-18 +* [#1800](https://github.com/stripe/stripe-go/pull/1800) Update generated code +* [#1798](https://github.com/stripe/stripe-go/pull/1798) Update generated code + * Add support for new value `nn` on enums `ChargePaymentMethodDetailsIdealBank`, `PaymentMethodIdealBank`, and `SetupAttemptPaymentMethodDetailsIdealBank` + * Add support for `Issuer` on `InvoiceParams`, `InvoiceUpcomingLinesParams`, `InvoiceUpcomingParams`, and `Invoice` + * Add support for `Liability` on `InvoiceAutomaticTaxParams`, `InvoiceAutomaticTax`, `InvoiceUpcomingAutomaticTaxParams`, `InvoiceUpcomingLinesAutomaticTaxParams`, `SubscriptionAutomaticTaxParams`, and `SubscriptionAutomaticTax` + * Add support for `OnBehalfOf` on `InvoiceUpcomingLinesParams` and `InvoiceUpcomingParams` + * Add support for `PIN` on `IssuingCardParams` + * Add support for `RevocationReason` on `MandatePaymentMethodDetailsBacsDebit` + * Add support for `CustomerBalance` on `PaymentMethodConfigurationParams` and `PaymentMethodConfiguration` + * Add support for `InvoiceSettings` on `SubscriptionParams` +* [#1796](https://github.com/stripe/stripe-go/pull/1796) Update generated code + * Add support for new resource `CustomerSession` + * Add support for `New` method on resource `CustomerSession` + * Remove support for values `obligation_inbound`, `obligation_payout_failure`, `obligation_payout`, and `obligation_reversal_outbound` from enum `BalanceTransactionType` + * Remove support for `Expand` on `BankAccountParams` and `CardParams` + * Add support for `AccountType`, `DefaultForCurrency`, and `Documents` on `BankAccountParams` and `CardParams` + * Remove support for `Owner` on `BankAccountParams` and `CardParams` + * Change type of `BankAccountAccountHolderTypeParams` and `CardAccountHolderTypeParams` from `enum('company'|'individual')` to `emptyStringable(enum('company'|'individual'))` + * Add support for new values `eps` and `p24` on enums `InvoicePaymentSettingsPaymentMethodTypes` and `SubscriptionPaymentSettingsPaymentMethodTypes` + * Add support for `BillingCycleAnchorConfig` on `SubscriptionParams` and `Subscription` + +## 76.12.0 - 2024-01-12 +* [#1796](https://github.com/stripe/stripe-go/pull/1796) Update generated code + * Add support for new resource `CustomerSession` + * Add support for `New` method on resource `CustomerSession` + * Remove support for values `obligation_inbound`, `obligation_payout_failure`, `obligation_payout`, and `obligation_reversal_outbound` from enum `BalanceTransactionType` + * Remove support for `Expand` on `BankAccountParams` and `CardParams` + * Add support for `AccountType`, `DefaultForCurrency`, and `Documents` on `BankAccountParams` and `CardParams` + * Remove support for `Owner` on `BankAccountParams` and `CardParams` + * Change type of `BankAccountAccountHolderTypeParams` and `CardAccountHolderTypeParams` from `enum('company'|'individual')` to `emptyStringable(enum('company'|'individual'))` + * Add support for new values `eps` and `p24` on enums `InvoicePaymentSettingsPaymentMethodTypes` and `SubscriptionPaymentSettingsPaymentMethodTypes` + * Add support for `BillingCycleAnchorConfig` on `SubscriptionParams` and `Subscription` + +## 76.11.0 - 2024-01-04 +* [#1792](https://github.com/stripe/stripe-go/pull/1792) Update generated code + * Add support for `Get` method on resource `Tax.Registration` + * Change type of `SubscriptionScheduleDefaultSettingsInvoiceSettings` from `nullable(InvoiceSettingSubscriptionScheduleSetting)` to `InvoiceSettingSubscriptionScheduleSetting` +* [#1790](https://github.com/stripe/stripe-go/pull/1790) Update generated code + * Add support for `CollectionMethod` on `MandatePaymentMethodDetailsUsBankAccount` + * Add support for `MandateOptions` on `PaymentIntentConfirmPaymentMethodOptionsUsBankAccountParams`, `PaymentIntentPaymentMethodOptionsUsBankAccountParams`, `PaymentIntentPaymentMethodOptionsUsBankAccount`, `SetupIntentConfirmPaymentMethodOptionsUsBankAccountParams`, `SetupIntentPaymentMethodOptionsUsBankAccountParams`, and `SetupIntentPaymentMethodOptionsUsBankAccount` +* [#1789](https://github.com/stripe/stripe-go/pull/1789) Update generated code + * Add support for new resource `FinancialConnections.Transaction` + * Add support for `Get` and `List` methods on resource `Transaction` + * Add support for `Subscribe` and `Unsubscribe` methods on resource `FinancialConnections.Account` + * Add support for `Features` on `AccountSessionComponentsPayoutsParams` + * Add support for `EditPayoutSchedule`, `InstantPayouts`, and `StandardPayouts` on `AccountSessionComponentsPayoutsFeatures` + * Change type of `CheckoutSessionPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetchParams`, `CheckoutSessionPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch`, `InvoicePaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetchParams`, `InvoicePaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch`, `PaymentIntentConfirmPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetchParams`, `PaymentIntentPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetchParams`, `PaymentIntentPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch`, `SetupIntentConfirmPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetchParams`, `SetupIntentPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetchParams`, `SetupIntentPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch`, `SubscriptionPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetchParams`, and `SubscriptionPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch` from `literal('balances')` to `enum('balances'|'transactions')` + * Add support for new value `financial_connections.account.refreshed_transactions` on enum `EventType` + * Add support for `Subscriptions` and `TransactionRefresh` on `FinancialConnectionsAccount` + * Add support for `NextRefreshAvailableAt` on `FinancialConnectionsAccountBalanceRefresh` + * Add support for new value `transactions` on enum `FinancialConnectionsSessionPrefetch` + * Add support for new value `unknown` on enum `IssuingAuthorizationVerificationDataAuthenticationExemptionType` + * Add support for new value `challenge` on enums `PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure` and `SetupIntentPaymentMethodOptionsCardRequestThreeDSecure` + * Add support for `RevolutPay` on `PaymentMethodConfigurationParams` and `PaymentMethodConfiguration` + * Change type of `QuoteInvoiceSettings` from `nullable(InvoiceSettingQuoteSetting)` to `InvoiceSettingQuoteSetting` + * Add support for `DestinationDetails` on `Refund` +* [#1788](https://github.com/stripe/stripe-go/pull/1788) Use gofmt to format and lint + +## 76.10.0 - 2023-12-22 +* [#1790](https://github.com/stripe/stripe-go/pull/1790) Update generated code + * Add support for `CollectionMethod` on `MandatePaymentMethodDetailsUsBankAccount` + * Add support for `MandateOptions` on `PaymentIntentConfirmPaymentMethodOptionsUsBankAccountParams`, `PaymentIntentPaymentMethodOptionsUsBankAccountParams`, `PaymentIntentPaymentMethodOptionsUsBankAccount`, `SetupIntentConfirmPaymentMethodOptionsUsBankAccountParams`, `SetupIntentPaymentMethodOptionsUsBankAccountParams`, and `SetupIntentPaymentMethodOptionsUsBankAccount` +* [#1789](https://github.com/stripe/stripe-go/pull/1789) Update generated code + * Add support for new resource `FinancialConnections.Transaction` + * Add support for `Get` and `List` methods on resource `Transaction` + * Add support for `Subscribe` and `Unsubscribe` methods on resource `FinancialConnections.Account` + * Add support for `Features` on `AccountSessionComponentsPayoutsParams` + * Add support for `EditPayoutSchedule`, `InstantPayouts`, and `StandardPayouts` on `AccountSessionComponentsPayoutsFeatures` + * Change type of `CheckoutSessionPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetchParams`, `CheckoutSessionPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch`, `InvoicePaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetchParams`, `InvoicePaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch`, `PaymentIntentConfirmPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetchParams`, `PaymentIntentPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetchParams`, `PaymentIntentPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch`, `SetupIntentConfirmPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetchParams`, `SetupIntentPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetchParams`, `SetupIntentPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch`, `SubscriptionPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetchParams`, and `SubscriptionPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsPrefetch` from `literal('balances')` to `enum('balances'|'transactions')` + * Add support for new value `financial_connections.account.refreshed_transactions` on enum `EventType` + * Add support for `Subscriptions` and `TransactionRefresh` on `FinancialConnectionsAccount` + * Add support for `NextRefreshAvailableAt` on `FinancialConnectionsAccountBalanceRefresh` + * Add support for new value `transactions` on enum `FinancialConnectionsSessionPrefetch` + * Add support for new value `unknown` on enum `IssuingAuthorizationVerificationDataAuthenticationExemptionType` + * Add support for new value `challenge` on enums `PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure` and `SetupIntentPaymentMethodOptionsCardRequestThreeDSecure` + * Add support for `RevolutPay` on `PaymentMethodConfigurationParams` and `PaymentMethodConfiguration` + * Change type of `QuoteInvoiceSettings` from `nullable(InvoiceSettingQuoteSetting)` to `InvoiceSettingQuoteSetting` + * Add support for `DestinationDetails` on `Refund` +* [#1788](https://github.com/stripe/stripe-go/pull/1788) Use gofmt to format and lint + +## 76.9.0 - 2023-12-14 +* [#1781](https://github.com/stripe/stripe-go/pull/1781) Update generated code + * Add support for `PaymentMethodReuseAgreement` on `CheckoutSessionConsentCollectionParams`, `CheckoutSessionConsentCollection`, `PaymentLinkConsentCollectionParams`, and `PaymentLinkConsentCollection` + * Add support for `AfterSubmit` on `CheckoutSessionCustomTextParams`, `CheckoutSessionCustomText`, `PaymentLinkCustomTextParams`, and `PaymentLinkCustomText` + * Add support for `Created` on `RadarEarlyFraudWarningListParams` + +* [#1780](https://github.com/stripe/stripe-go/pull/1780) Usage telemetry infrastructure + +## 76.8.0 - 2023-12-07 +* [#1775](https://github.com/stripe/stripe-go/pull/1775) Update generated code + * Add support for `PaymentDetails`, `Payments`, and `Payouts` on `AccountSessionComponentsParams` and `AccountSessionComponents` + * Add support for `Features` on `AccountSessionComponentsAccountOnboardingParams` and `AccountSessionComponentsAccountOnboarding` + * Add support for new values `customer_tax_location_invalid` and `financial_connections_no_successful_transaction_refresh` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Add support for new values `payment_network_reserve_hold` and `payment_network_reserve_release` on enum `BalanceTransactionType` + * Remove support for value `various` from enum `ClimateSupplierRemovalPathway` + * Remove support for values `challenge_only` and `challenge` from enum `PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure` + * Add support for `InactiveMessage` and `Restrictions` on `PaymentLinkParams` and `PaymentLink` + * Add support for `TransferGroup` on `PaymentLinkPaymentIntentDataParams` and `PaymentLinkPaymentIntentData` + * Add support for `TrialSettings` on `PaymentLinkSubscriptionDataParams` and `PaymentLinkSubscriptionData` +* [#1777](https://github.com/stripe/stripe-go/pull/1777) Add back PlanParams.ProductID + * Add back `PlanParams.ProductID`, which was mistakenly removed starting in v73.0.0. `ProductID` allows creation of a plan for an existing product by serializing `product` as a string . + +## 76.7.0 - 2023-11-30 +* [#1772](https://github.com/stripe/stripe-go/pull/1772) Update generated code + * Add support for new resources `Climate.Order`, `Climate.Product`, and `Climate.Supplier` + * Add support for `Cancel`, `Get`, `List`, `New`, and `Update` methods on resource `Order` + * Add support for `Get` and `List` methods on resources `Product` and `Supplier` + * Add support for new value `financial_connections_account_inactive` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Add support for new values `climate_order_purchase` and `climate_order_refund` on enum `BalanceTransactionType` + * Add support for `Created` on `CheckoutSessionListParams` + * Add support for `ValidateLocation` on `CustomerTaxParams` + * Add support for new values `climate.order.canceled`, `climate.order.created`, `climate.order.delayed`, `climate.order.delivered`, `climate.order.product_substituted`, `climate.product.created`, and `climate.product.pricing_updated` on enum `EventType` + * Add support for new value `challenge` on enums `PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure` and `SetupIntentPaymentMethodOptionsCardRequestThreeDSecure` + +## 76.6.0 - 2023-11-21 +* [#1769](https://github.com/stripe/stripe-go/pull/1769) Update generated code + * Add support for `ElectronicCommerceIndicator` on `ChargePaymentMethodDetailsCardThreeDSecure` and `SetupAttemptPaymentMethodDetailsCardThreeDSecure` + * Add support for `ExemptionIndicatorApplied` and `ExemptionIndicator` on `ChargePaymentMethodDetailsCardThreeDSecure` + * Add support for `TransactionID` on `ChargePaymentMethodDetailsCardThreeDSecure`, `IssuingAuthorizationNetworkData`, `IssuingTransactionNetworkData`, and `SetupAttemptPaymentMethodDetailsCardThreeDSecure` + * Add support for `Offline` on `ChargePaymentMethodDetailsCardPresent` + * Add support for `SystemTraceAuditNumber` on `IssuingAuthorizationNetworkData` + * Add support for `NetworkRiskScore` on `IssuingAuthorizationPendingRequest` and `IssuingAuthorizationRequestHistory` + * Add support for `RequestedAt` on `IssuingAuthorizationRequestHistory` + * Add support for `AuthorizationCode` on `IssuingTransactionNetworkData` + * Add support for `ThreeDSecure` on `PaymentIntentConfirmPaymentMethodOptionsCardParams`, `PaymentIntentPaymentMethodOptionsCardParams`, `SetupIntentConfirmPaymentMethodOptionsCardParams`, and `SetupIntentPaymentMethodOptionsCardParams` + +## 76.5.0 - 2023-11-16 +* [#1768](https://github.com/stripe/stripe-go/pull/1768) Update generated code + * Add support for `Status` on `CheckoutSessionListParams` +* [#1767](https://github.com/stripe/stripe-go/pull/1767) Update generated code + * Add support for `BACSDebitPayments` on `AccountSettingsParams` + * Add support for `ServiceUserNumber` on `AccountSettingsBacsDebitPayments` + * Add support for `CaptureBefore` on `ChargePaymentMethodDetailsCard` + * Add support for `Paypal` on `CheckoutSessionPaymentMethodOptions` + * Add support for `TaxAmounts` on `CreditNoteLinesParams`, `CreditNotePreviewLinesLinesParams`, and `CreditNotePreviewLinesParams` + * Add support for `NetworkData` on `IssuingTransaction` +* [#1764](https://github.com/stripe/stripe-go/pull/1764) Fix TestDo_RetryOnTimeout flakiness + +## 76.4.0 - 2023-11-09 +* [#1762](https://github.com/stripe/stripe-go/pull/1762) Update generated code + * Add support for new value `terminal_reader_hardware_fault` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Add support for `Metadata` on `QuoteSubscriptionDataParams` and `QuoteSubscriptionData` + +## 76.3.0 - 2023-11-02 +* [#1760](https://github.com/stripe/stripe-go/pull/1760) Update generated code + * Add support for new resource `Tax.Registration` + * Add support for `List`, `New`, and `Update` methods on resource `Registration` + * Add support for `RevolutPay` throughout the API + * Add support for new value `token_card_network_invalid` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Add support for new value `payment_unreconciled` on enum `BalanceTransactionType` + * Add support for `ABA` and `Swift` on `FundingInstructionsBankTransferFinancialAddresses` and `PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddresses` + * Add support for new values `ach`, `domestic_wire_us`, and `swift` on enums `FundingInstructionsBankTransferFinancialAddressesSupportedNetworks` and `PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressesSupportedNetworks` + * Add support for new values `aba` and `swift` on enums `FundingInstructionsBankTransferFinancialAddressesType` and `PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressesType` + * Add support for `URL` on `IssuingAuthorizationMerchantDataParams`, `IssuingAuthorizationMerchantData`, `IssuingTransactionMerchantData`, `TestHelpersIssuingTransactionCreateForceCaptureMerchantDataParams`, and `TestHelpersIssuingTransactionCreateUnlinkedRefundMerchantDataParams` + * Add support for `AuthenticationExemption` and `ThreeDSecure` on `IssuingAuthorizationVerificationDataParams` and `IssuingAuthorizationVerificationData` + * Add support for `Description` on `PaymentLinkPaymentIntentDataParams` and `PaymentLinkPaymentIntentData` + +## 76.2.0 - 2023-10-26 +* [#1759](https://github.com/stripe/stripe-go/pull/1759) Update generated code + * Add support for new value `balance_invalid_parameter` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + +## 76.1.0 - 2023-10-17 +* [#1756](https://github.com/stripe/stripe-go/pull/1756) Update generated code + * Add support for new value `invalid_dob_age_under_minimum` on enums `AccountFutureRequirementsErrorsCode`, `AccountRequirementsErrorsCode`, `BankAccountFutureRequirementsErrorsCode`, and `BankAccountRequirementsErrorsCode` + +## 76.0.0 - 2023-10-16 +* This release changes the pinned API version to `2023-10-16`. Please read the [API Changelog](https://docs.stripe.com/changelog/2023-10-16) and carefully review the API changes before upgrading `stripe-go`. +* [#1753](https://github.com/stripe/stripe-go/pull/1753) Update generated code + * Add support for `LegalGuardian` on `AccountPersonsRelationshipParams` and `TokenPersonRelationshipParams` + * Add support for new values `invalid_address_highway_contract_box`, `invalid_address_private_mailbox`, `invalid_business_profile_name_denylisted`, `invalid_business_profile_name`, `invalid_company_name_denylisted`, `invalid_dob_age_over_maximum`, `invalid_product_description_length`, `invalid_product_description_url_match`, `invalid_statement_descriptor_business_mismatch`, `invalid_statement_descriptor_denylisted`, `invalid_statement_descriptor_length`, `invalid_statement_descriptor_prefix_denylisted`, `invalid_statement_descriptor_prefix_mismatch`, `invalid_tax_id_format`, `invalid_tax_id`, `invalid_url_denylisted`, `invalid_url_format`, `invalid_url_length`, `invalid_url_web_presence_detected`, `invalid_url_website_business_information_mismatch`, `invalid_url_website_empty`, `invalid_url_website_inaccessible_geoblocked`, `invalid_url_website_inaccessible_password_protected`, `invalid_url_website_inaccessible`, `invalid_url_website_incomplete_cancellation_policy`, `invalid_url_website_incomplete_customer_service_details`, `invalid_url_website_incomplete_legal_restrictions`, `invalid_url_website_incomplete_refund_policy`, `invalid_url_website_incomplete_return_policy`, `invalid_url_website_incomplete_terms_and_conditions`, `invalid_url_website_incomplete_under_construction`, `invalid_url_website_incomplete`, and `invalid_url_website_other` on enums `AccountFutureRequirementsErrorsCode`, `AccountRequirementsErrorsCode`, `BankAccountFutureRequirementsErrorsCode`, and `BankAccountRequirementsErrorsCode` + * Add support for `AdditionalTOSAcceptances` on `TokenPersonParams` + +## 75.11.0 - 2023-10-16 +* [#1751](https://github.com/stripe/stripe-go/pull/1751) Update generated code + * Add support for new values `issuing_token.created` and `issuing_token.updated` on enum `EventType` +* [#1748](https://github.com/stripe/stripe-go/pull/1748) add NewBackendsWithConfig helper + +## 75.10.0 - 2023-10-11 +* [#1746](https://github.com/stripe/stripe-go/pull/1746) Update generated code + * Add support for `RedirectOnCompletion`, `ReturnURL`, and `UIMode` on `CheckoutSessionParams` and `CheckoutSession` + * Add support for `ClientSecret` on `CheckoutSession` + * Change type of `CheckoutSessionCustomFieldsDropdown` from `nullable(PaymentPagesCheckoutSessionCustomFieldsDropdown)` to `PaymentPagesCheckoutSessionCustomFieldsDropdown` + * Change type of `CheckoutSessionCustomFieldsNumeric` and `CheckoutSessionCustomFieldsText` from `nullable(PaymentPagesCheckoutSessionCustomFieldsNumeric)` to `PaymentPagesCheckoutSessionCustomFieldsNumeric` + * Add support for `PostalCode` on `IssuingAuthorizationVerificationData` + * Change type of `PaymentLinkCustomFieldsDropdown` from `nullable(PaymentLinksResourceCustomFieldsDropdown)` to `PaymentLinksResourceCustomFieldsDropdown` + * Change type of `PaymentLinkCustomFieldsNumeric` and `PaymentLinkCustomFieldsText` from `nullable(PaymentLinksResourceCustomFieldsNumeric)` to `PaymentLinksResourceCustomFieldsNumeric` + * Add support for `Offline` on `TerminalConfigurationParams` and `TerminalConfiguration` + +## 75.9.0 - 2023-10-05 +* [#1743](https://github.com/stripe/stripe-go/pull/1743) Update generated code + * Add support for new resource `Issuing.Token` + * Add support for `Get`, `List`, and `Update` methods on resource `Token` + * Add support for `AmountAuthorized`, `ExtendedAuthorization`, `IncrementalAuthorization`, `Multicapture`, and `Overcapture` on `ChargePaymentMethodDetailsCard` + * Add support for `Token` on `IssuingAuthorization` and `IssuingTransaction` + * Add support for `AuthorizationCode` on `IssuingAuthorizationRequestHistory` + * Add support for `RequestExtendedAuthorization`, `RequestMulticapture`, and `RequestOvercapture` on `PaymentIntentConfirmPaymentMethodOptionsCardParams`, `PaymentIntentPaymentMethodOptionsCardParams`, and `PaymentIntentPaymentMethodOptionsCard` + * Add support for `RequestIncrementalAuthorization` on `PaymentIntentConfirmPaymentMethodOptionsCardParams`, `PaymentIntentConfirmPaymentMethodOptionsCardPresentParams`, `PaymentIntentPaymentMethodOptionsCardParams`, `PaymentIntentPaymentMethodOptionsCardPresentParams`, and `PaymentIntentPaymentMethodOptionsCard` + * Add support for `FinalCapture` on `PaymentIntentCaptureParams` + * Add support for `Metadata` on `PaymentLinkPaymentIntentDataParams`, `PaymentLinkPaymentIntentData`, `PaymentLinkSubscriptionDataParams`, and `PaymentLinkSubscriptionData` + * Add support for `StatementDescriptorSuffix` and `StatementDescriptor` on `PaymentLinkPaymentIntentDataParams` and `PaymentLinkPaymentIntentData` + * Add support for `PaymentIntentData` and `SubscriptionData` on `PaymentLinkParams` + +## 75.8.0 - 2023-09-28 +* [#1741](https://github.com/stripe/stripe-go/pull/1741) Update generated code + * Add support for `Rendering` on `InvoiceParams` and `Invoice` + +## 75.7.0 - 2023-09-21 +* [#1738](https://github.com/stripe/stripe-go/pull/1738) Update generated code + * Add support for `TermsOfServiceAcceptance` on `CheckoutSessionCustomTextParams`, `CheckoutSessionCustomText`, `PaymentLinkCustomTextParams`, and `PaymentLinkCustomText` + +## 75.6.0 - 2023-09-14 +* [#1736](https://github.com/stripe/stripe-go/pull/1736) Update generated code + * Add support for new resource `PaymentMethodConfiguration` + * Add support for `Get`, `List`, `New`, and `Update` methods on resource `PaymentMethodConfiguration` + * Add support for `PaymentMethodConfiguration` on `CheckoutSessionParams`, `PaymentIntentParams`, and `SetupIntentParams` + * Add support for `PaymentMethodConfigurationDetails` on `CheckoutSession`, `PaymentIntent`, and `SetupIntent` +* [#1729](https://github.com/stripe/stripe-go/pull/1729) Update generated code + * Add support for `Capture`, `Expire`, `Increment`, `New`, and `Reverse` test helper methods on resource `Issuing.Authorization` + * Add support for `CreateForceCapture`, `CreateUnlinkedRefund`, and `Refund` test helper methods on resource `Issuing.Transaction` + * Add support for new value `stripe_tax_inactive` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Add support for `Nonce` on `EphemeralKeyParams` + * Add support for `CashbackAmount` on `IssuingAuthorizationAmountDetails`, `IssuingAuthorizationPendingRequestAmountDetails`, `IssuingAuthorizationRequestHistoryAmountDetails`, and `IssuingTransactionAmountDetails` + * Add support for `SerialNumber` on `TerminalReaderListParams` + +## 75.5.0 - 2023-09-13 +* [#1735](https://github.com/stripe/stripe-go/pull/1735) Bugfix: point files.New back to files.stripe.com +* [#1731](https://github.com/stripe/stripe-go/pull/1731) Delay calculation of Stripe-User-Agent + +## 75.4.0 - 2023-09-07 +* [#1724](https://github.com/stripe/stripe-go/pull/1724) Update generated code + * Add support for new resource `PaymentMethodDomain` + * Add support for `Get`, `List`, `New`, `Update`, and `Validate` methods on resource `PaymentMethodDomain` + * Add support for new value `n26` on enums `ChargePaymentMethodDetailsIdealBank`, `PaymentMethodIdealBank`, and `SetupAttemptPaymentMethodDetailsIdealBank` + * Add support for new value `NTSBDEB1` on enums `ChargePaymentMethodDetailsIdealBic`, `PaymentMethodIdealBic`, and `SetupAttemptPaymentMethodDetailsIdealBic` + * Add support for new values `treasury.credit_reversal.created`, `treasury.credit_reversal.posted`, `treasury.debit_reversal.completed`, `treasury.debit_reversal.created`, `treasury.debit_reversal.initial_credit_granted`, `treasury.financial_account.closed`, `treasury.financial_account.created`, `treasury.financial_account.features_status_updated`, `treasury.inbound_transfer.canceled`, `treasury.inbound_transfer.created`, `treasury.inbound_transfer.failed`, `treasury.inbound_transfer.succeeded`, `treasury.outbound_payment.canceled`, `treasury.outbound_payment.created`, `treasury.outbound_payment.expected_arrival_date_updated`, `treasury.outbound_payment.failed`, `treasury.outbound_payment.posted`, `treasury.outbound_payment.returned`, `treasury.outbound_transfer.canceled`, `treasury.outbound_transfer.created`, `treasury.outbound_transfer.expected_arrival_date_updated`, `treasury.outbound_transfer.failed`, `treasury.outbound_transfer.posted`, `treasury.outbound_transfer.returned`, `treasury.received_credit.created`, `treasury.received_credit.failed`, `treasury.received_credit.succeeded`, and `treasury.received_debit.created` on enum `EventType` + * Remove support for value `invoiceitem.updated` from enum `EventType` + * Add support for `Features` on `ProductParams` and `Product` + +## 75.3.0 - 2023-08-31 +* [#1722](https://github.com/stripe/stripe-go/pull/1722) Update generated code + * Add support for new resource `AccountSession` + * Add support for `New` method on resource `AccountSession` + * Add support for new values `obligation_inbound`, `obligation_outbound`, `obligation_payout_failure`, `obligation_payout`, `obligation_reversal_inbound`, and `obligation_reversal_outbound` on enum `BalanceTransactionType` + * Change type of `EventType` from `string` to `enum` + * Add support for `Application` on `PaymentLink` + +## 75.2.0 - 2023-08-24 +* [#1718](https://github.com/stripe/stripe-go/pull/1718) Update generated code + * Add support for `Retention` on `BillingPortalSessionFlowDataSubscriptionCancelParams` and `BillingPortalSessionFlowSubscriptionCancel` + * Add support for `Prefetch` on `CheckoutSessionPaymentMethodOptionsUsBankAccountFinancialConnectionsParams`, `CheckoutSessionPaymentMethodOptionsUsBankAccountFinancialConnections`, `FinancialConnectionsSessionParams`, `FinancialConnectionsSession`, `InvoicePaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsParams`, `InvoicePaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnections`, `PaymentIntentConfirmPaymentMethodOptionsUsBankAccountFinancialConnectionsParams`, `PaymentIntentPaymentMethodOptionsUsBankAccountFinancialConnectionsParams`, `PaymentIntentPaymentMethodOptionsUsBankAccountFinancialConnections`, `SetupIntentConfirmPaymentMethodOptionsUsBankAccountFinancialConnectionsParams`, `SetupIntentPaymentMethodOptionsUsBankAccountFinancialConnectionsParams`, `SetupIntentPaymentMethodOptionsUsBankAccountFinancialConnections`, `SubscriptionPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnectionsParams`, and `SubscriptionPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnections` + * Add support for `PaymentMethodDetails` on `Dispute` + * Add support for `BalanceTransaction ` on `CustomerCashBalanceTransaction.AdjustedForOverdraft` +* [#1717](https://github.com/stripe/stripe-go/pull/1717) Replace import placeholder before running formatting +* [#1716](https://github.com/stripe/stripe-go/pull/1716) Replace version placeholder with an actual version during format + +## 75.1.0 - 2023-08-17 +* [#1713](https://github.com/stripe/stripe-go/pull/1713) Update generated code + * Add support for `FlatAmount` on `TaxTransactionCreateReversalParams` +* [#1712](https://github.com/stripe/stripe-go/pull/1712) Fix link title to go migration guide + +## 75.0.0 - 2023-08-16 +* This release changes the pinned API version to `2023-08-16`. Please read the [API Changelog](https://docs.stripe.com/changelog/2023-08-16) and carefully review the API changes before upgrading `stripe-go`. +* More information is available in the [stripe-go v75 migration guide](https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v75) +* [#1705](https://github.com/stripe/stripe-go/pull/1705) Update generated code + * ⚠️Add support for new values `verification_directors_mismatch`, `verification_document_directors_mismatch`, `verification_extraneous_directors`, and `verification_missing_directors` on enums `AccountFutureRequirementsErrorsCode`, `AccountRequirementsErrorsCode`, `BankAccountFutureRequirementsErrorsCode`, and `BankAccountRequirementsErrorsCode` + * Remove support for `AvailableOn` on `BalanceTransactionListParams` + * Use of this parameter is discouraged. You may use [`.AddExtra`](https://github.com/stripe/stripe-go#parameters) if sending the parameter is still required. + * ⚠️Remove support for `Destination` on `Charge` + * Please use `TransferData` or `OnBehalfOf` instead. + * ⚠️Remove support for `AlternateStatementDescriptors` and `Dispute` on `Charge` + * Use of these parameters is discouraged. + * ⚠️Remove support for `ShippingRates` on `CheckoutSessionParams` + * Please use `ShippingParams` instead. + * ⚠️Remove support for `Coupon` and `TrialFromPlan` on `CheckoutSessionSubscriptionDataParams` + * Please [migrate to the Prices API](https://stripe.com/docs/billing/migration/migrating-prices), or use [`.AddExtra`](https://github.com/stripe/stripe-go#parameters) if sending the parameter is still required. + * ⚠️Remove support for value `charge_refunded` from enum `DisputeStatus` + * ⚠️Remove support for `BLIK` on `MandatePaymentMethodDetails`, `PaymentMethodParams`, `SetupAttemptPaymentMethodDetails`, `SetupIntentConfirmPaymentMethodOptionsParams`, `SetupIntentPaymentMethodOptionsParams`, and `SetupIntentPaymentMethodOptions` + * These fields were mistakenly released. + * ⚠️Remove support for `ACSSDebit`, `AUBECSDebit`, `Affirm`, `BACSDebit`, `CashApp`, `SEPADebit`, and `Zip` on `PaymentMethodParams` + * These fields were empty hashes. + * ⚠️Remove support for `Country` on `PaymentMethodLink` + * This field was not fully operational. + * ⚠️Remove support for `Recurring` on `PriceParams` + * This property should be set on create only. + * ⚠️Remove support for `Attributes`, `Caption`, and `DeactivateOn` on `ProductParams` and `Product` + * These fields are not fully operational. +* [#1699](https://github.com/stripe/stripe-go/pull/1699) + * Add `Metadata` and `Expand` to individual `Params` classes. + * `Expand`, `AddExpand`, `Metadata` and `AddMetadata` on embedded `Params` struct were deprecated. + Before: + + ```go + params := &stripe.AccountParams{ + Params: stripe.Params{ + Expand: []*string{stripe.String("business_profile")}, + Metadata: map[string]string{ + "order_id": "6735", + }, + }, + } + ``` + + After: + ```go + params := &stripe.AccountParams{ + Expand: []*string{stripe.String("business_profile")}, + Metadata: map[string]string{ + "order_id": "6735", + }, + } + ``` + You don't have to change your calls to `AddMetadata` and `AddExpand` + Before/After: + ```go + params.AddMetadata("order_id", "6735") + params.AddExpand("business_profile") + ``` + - ⚠️ Removed deprecated `excluded_territory`, `jurisdiction_unsupported`, `vat_exempt` taxability reasons: + - `CheckoutSessionShippingCostTaxTaxabilityReasonExcludedTerritory` + - `CheckoutSessionShippingCostTaxTaxabilityReasonJurisdictionUnsupported` + - `CheckoutSessionShippingCostTaxTaxabilityReasonVATExempt` + - `CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonExcludedTerritory` + - `CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonJurisdictionUnsupported` + - `CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonVATExempt` + - `CreditNoteShippingCostTaxTaxabilityReasonExcludedTerritory` + - `CreditNoteShippingCostTaxTaxabilityReasonJurisdictionUnsupported` + - `CreditNoteShippingCostTaxTaxabilityReasonVATExempt` + - `InvoiceShippingCostTaxTaxabilityReasonExcludedTerritory` + - `InvoiceShippingCostTaxTaxabilityReasonJurisdictionUnsupported` + - `InvoiceShippingCostTaxTaxabilityReasonVATExempt` + - `LineItemTaxTaxabilityReasonExcludedTerritory` + - `LineItemTaxTaxabilityReasonJurisdictionUnsupported` + - `LineItemTaxTaxabilityReasonVATExempt` + - `QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonExcludedTerritory` + - `QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonJurisdictionUnsupported` + - `QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonVATExempt` + - `QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonExcludedTerritory` + - `QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonJurisdictionUnsupported` + - `QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonVATExempt` + - `QuoteTotalDetailsBreakdownTaxTaxabilityReasonExcludedTerritory` + - `QuoteTotalDetailsBreakdownTaxTaxabilityReasonJurisdictionUnsupported` + - `QuoteTotalDetailsBreakdownTaxTaxabilityReasonVATExempt` + - ⚠️ Removed deprecated error code constant `ErrorCodeCardDeclinedRateLimitExceeded`, prefer `ErrorCodeCardDeclineRateLimitExceeded`. + - ⚠️ Removed deprecated error code constant `ErrorCodeInvalidSwipeData`. + - ⚠️ Removed deprecated error code constant `ErrorCodeInvoicePamentIntentRequiresAction` prefer `ErrorCodeInvoicePaymentIntentRequiresAction`. + - ⚠️ Removed deprecated error code constant `ErrorCodeSepaUnsupportedAccount`, prefer `ErrorCodeSEPAUnsupportedAccount`. + - ⚠️ Removed deprecated error code constant `ErrorCodeSkuInactive`, prefer `ErrorCodeSKUInactive`. + - ⚠️ Removed deprecated error code constant `ErrorCodeinstantPayoutsLimitExceeded`, prefer `ErrorCodeInstantPayoutsLimitExceeded`. + +## 74.30.0 - 2023-08-10 +* [#1702](https://github.com/stripe/stripe-go/pull/1702) Update generated code + * Add support for new values `incorporated_partnership` and `unincorporated_partnership` on enum `AccountCompanyStructure` + * Add support for new value `payment_reversal` on enum `BalanceTransactionType` + +## 74.29.0 - 2023-08-03 +* [#1700](https://github.com/stripe/stripe-go/pull/1700) Update generated code + * Add support for `PreferredSettlementSpeed` on `PaymentIntentConfirmPaymentMethodOptionsUsBankAccountParams`, `PaymentIntentPaymentMethodOptionsUsBankAccountParams`, and `PaymentIntentPaymentMethodOptionsUsBankAccount` +* [#1696](https://github.com/stripe/stripe-go/pull/1696) Update generated code + * Add support for new values `sepa_debit_fingerprint` and `us_bank_account_fingerprint` on enum `RadarValueListItemType` + +## 74.28.0 - 2023-07-28 +* [#1693](https://github.com/stripe/stripe-go/pull/1693) Update generated code + * Add support for `MonthlyEstimatedRevenue` on `AccountBusinessProfileParams` and `AccountBusinessProfile` + * Add support for `SubscriptionDetails` on `Invoice` + +## 74.27.0 - 2023-07-20 +* [#1691](https://github.com/stripe/stripe-go/pull/1691) Update generated code + * Add support for new value `ro_tin` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, `TaxCalculationCustomerDetailsTaxIdsType`, and `TaxTransactionCustomerDetailsTaxIdsType` + * Remove support for values `excluded_territory`, `jurisdiction_unsupported`, and `vat_exempt` from enums `CheckoutSessionShippingCostTaxesTaxabilityReason`, `CheckoutSessionTotalDetailsBreakdownTaxesTaxabilityReason`, `CreditNoteShippingCostTaxesTaxabilityReason`, `InvoiceShippingCostTaxesTaxabilityReason`, `LineItemTaxesTaxabilityReason`, `QuoteComputedRecurringTotalDetailsBreakdownTaxesTaxabilityReason`, `QuoteComputedUpfrontTotalDetailsBreakdownTaxesTaxabilityReason`, and `QuoteTotalDetailsBreakdownTaxesTaxabilityReason` + * Add support for `UseStripeSDK` on `SetupIntentConfirmParams` and `SetupIntentParams` + * Add support for new value `service_tax` on enum `TaxRateTaxType` +* [#1688](https://github.com/stripe/stripe-go/pull/1688) Update generated code + * Add support for new resource `Tax.Settings` + * Add support for `Get` and `Update` methods on resource `Settings` + * Add support for new value `invalid_tax_location` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Add support for `OrderID` on `ChargePaymentMethodDetailsAfterpayClearpay` + * Add support for `AllowRedirects` on `PaymentIntentAutomaticPaymentMethodsParams`, `PaymentIntentAutomaticPaymentMethods`, `SetupIntentAutomaticPaymentMethodsParams`, and `SetupIntentAutomaticPaymentMethods` + * Add support for new values `amusement_tax` and `communications_tax` on enums `TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType`, `TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType`, `TaxCalculationTaxBreakdownTaxRateDetailsTaxType`, and `TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType` + * Add support for `Product` on `TaxTransactionLineItem` + +## 74.26.0 - 2023-07-13 +* [#1688](https://github.com/stripe/stripe-go/pull/1688) Update generated code + * Add support for new resource `Tax.Settings` + * Add support for `Get` and `Update` methods on resource `Settings` + * Add support for new value `invalid_tax_location` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Add support for `OrderID` on `ChargePaymentMethodDetailsAfterpayClearpay` + * Add support for `AllowRedirects` on `PaymentIntentAutomaticPaymentMethodsParams`, `PaymentIntentAutomaticPaymentMethods`, `SetupIntentAutomaticPaymentMethodsParams`, and `SetupIntentAutomaticPaymentMethods` + * Add support for new values `amusement_tax` and `communications_tax` on enums `TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType`, `TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType`, `TaxCalculationTaxBreakdownTaxRateDetailsTaxType`, and `TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType` + * Add support for `Product` on `TaxTransactionLineItem` + +## 74.25.0 - 2023-07-06 +* [#1684](https://github.com/stripe/stripe-go/pull/1684) Update generated code + * Add support for `Numeric` and `Text` on `PaymentLinkCustomFields` + * Add support for `AutomaticTax` on `SubscriptionListParams` + +## 74.24.0 - 2023-06-29 +* [#1682](https://github.com/stripe/stripe-go/pull/1682) Update generated code + * Add support for new value `application_fees_not_allowed` on enums `InvoiceLastFinalizationErrorCode`, `PaymentIntentLastPaymentErrorCode`, `SetupAttemptSetupErrorCode`, `SetupIntentLastSetupErrorCode`, and `StripeErrorCode` + * Add support for new values `ad_nrt`, `ar_cuit`, `bo_tin`, `cn_tin`, `co_nit`, `cr_tin`, `do_rcn`, `ec_ruc`, `pe_ruc`, `rs_pib`, `sv_nit`, `uy_ruc`, `ve_rif`, and `vn_tin` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, `TaxCalculationCustomerDetailsTaxIdsType`, and `TaxTransactionCustomerDetailsTaxIdsType` + * Add support for `EffectiveAt` on `CreditNoteParams`, `CreditNotePreviewLinesParams`, `CreditNotePreviewParams`, `CreditNote`, `InvoiceParams`, and `Invoice` + +## 74.23.0 - 2023-06-22 +* [#1678](https://github.com/stripe/stripe-go/pull/1678) Update generated code + * Add support for `OnBehalfOf` on `Mandate` +* [#1680](https://github.com/stripe/stripe-go/pull/1680) Deserialization test + +## 74.22.0 - 2023-06-08 +* [#1670](https://github.com/stripe/stripe-go/pull/1670) Update generated code + * Add support for `TaxabilityReason` on `TaxCalculationTaxBreakdown` +* [#1668](https://github.com/stripe/stripe-go/pull/1668) Remove v71 migration guide, moved to wiki + +## 74.21.0 - 2023-06-01 +* [#1664](https://github.com/stripe/stripe-go/pull/1664) Update generated code + * Add support for `Numeric` and `Text` on `CheckoutSessionCustomFieldsParams` and `PaymentLinkCustomFieldsParams` + * Add support for `MaximumLength` and `MinimumLength` on `CheckoutSessionCustomFieldsNumeric` and `CheckoutSessionCustomFieldsText` + * Add support for new values `aba` and `swift` on enums `CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypes` and `PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypes` + * Add support for new value `us_bank_transfer` on enums `CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferType`, `PaymentIntentNextActionDisplayBankTransferInstructionsType`, and `PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferType` + * Add support for `PreferredLocales` on `IssuingCardholderParams` and `IssuingCardholder` + * Add support for `Description`, `IIN`, and `Issuer` on `PaymentMethodCardPresent` and `PaymentMethodInteracPresent` + * Add support for `PayerEmail` on `PaymentMethodPaypal` +* [#1662](https://github.com/stripe/stripe-go/pull/1662) Update generated code + * Add support for `ZipPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `Zip` on `ChargePaymentMethodDetails`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for new value `zip` on enum `PaymentMethodType` +* [#1661](https://github.com/stripe/stripe-go/pull/1661) Generate error codes +* [#1660](https://github.com/stripe/stripe-go/pull/1660) Update generated code + +## 74.20.0 - 2023-05-25 +* [#1662](https://github.com/stripe/stripe-go/pull/1662) Update generated code + * Add support for `ZipPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `Zip` on `ChargePaymentMethodDetails`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for new value `zip` on enum `PaymentMethodType` +* [#1661](https://github.com/stripe/stripe-go/pull/1661) Generate error codes +* [#1660](https://github.com/stripe/stripe-go/pull/1660) Update generated code + +## 74.19.0 - 2023-05-19 +* [#1657](https://github.com/stripe/stripe-go/pull/1657) Update generated code + * Add support for `SubscriptionUpdateConfirm` and `SubscriptionUpdate` on `BillingPortalSessionFlowDataParams` and `BillingPortalSessionFlow` + * Add support for new values `subscription_update_confirm` and `subscription_update` on enum `BillingPortalSessionFlowType` + * Add support for `Link` on `ChargePaymentMethodDetailsCardWallet` and `PaymentMethodCardWallet` + * Add support for `BuyerID` and `Cashtag` on `ChargePaymentMethodDetailsCashapp` and `PaymentMethodCashapp` + * Add support for new values `amusement_tax` and `communications_tax` on enum `TaxRateTaxType` + +## 74.18.0 - 2023-05-11 +* [#1656](https://github.com/stripe/stripe-go/pull/1656) Update generated code + Release specs are identical. +* [#1653](https://github.com/stripe/stripe-go/pull/1653) Update generated code + * Add support for `Paypal` on `ChargePaymentMethodDetails`, `CheckoutSessionPaymentMethodOptionsParams`, `MandatePaymentMethodDetails`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupAttemptPaymentMethodDetails`, `SetupIntentConfirmPaymentMethodDataParams`, `SetupIntentConfirmPaymentMethodOptionsParams`, `SetupIntentPaymentMethodDataParams`, `SetupIntentPaymentMethodOptionsParams`, and `SetupIntentPaymentMethodOptions` + * Add support for `NetworkToken` on `ChargePaymentMethodDetailsCard` + * Add support for `TaxabilityReason` and `TaxableAmount` on `CheckoutSessionShippingCostTaxes`, `CheckoutSessionTotalDetailsBreakdownTaxes`, `CreditNoteShippingCostTaxes`, `CreditNoteTaxAmounts`, `InvoiceShippingCostTaxes`, `InvoiceTotalTaxAmounts`, `LineItemTaxes`, `QuoteComputedRecurringTotalDetailsBreakdownTaxes`, `QuoteComputedUpfrontTotalDetailsBreakdownTaxes`, and `QuoteTotalDetailsBreakdownTaxes` + * Add support for new value `paypal` on enums `InvoicePaymentSettingsPaymentMethodTypes` and `SubscriptionPaymentSettingsPaymentMethodTypes` + * Add support for new value `eftpos_au` on enums `PaymentIntentPaymentMethodOptionsCardNetwork`, `SetupIntentPaymentMethodOptionsCardNetwork`, and `SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork` + * Add support for new value `paypal` on enum `PaymentLinkPaymentMethodTypes` + * Add support for `Brand`, `CardholderName`, `Country`, `ExpMonth`, `ExpYear`, `Fingerprint`, `Funding`, `Last4`, `Networks`, and `ReadMethod` on `PaymentMethodCardPresent` and `PaymentMethodInteracPresent` + * Add support for `PreferredLocales` on `PaymentMethodInteracPresent` + * Add support for new value `paypal` on enum `PaymentMethodType` + * Add support for `EffectivePercentage` on `TaxRate` + * Add support for `GBBankTransfer` and `JPBankTransfer` on `CustomerCashBalanceTransactionFundedBankTransfer ` + +## 74.17.0 - 2023-05-04 +* [#1652](https://github.com/stripe/stripe-go/pull/1652) Update generated code + * Add support for `Link` on `CheckoutSessionPaymentMethodOptionsParams` and `CheckoutSessionPaymentMethodOptions` + * Add support for `Brand`, `Country`, `Description`, `ExpMonth`, `ExpYear`, `Fingerprint`, `Funding`, `IIN`, `Issuer`, `Last4`, `Network`, and `Wallet` on `SetupAttemptPaymentMethodDetailsCard` + +## 74.16.0 - 2023-04-27 +* [#1644](https://github.com/stripe/stripe-go/pull/1644) Update generated code + * Add support for `BillingCycleAnchor` and `ProrationBehavior` on `CheckoutSessionSubscriptionDataParams` + * Add support for `TerminalID` on `IssuingAuthorizationMerchantData` and `IssuingTransactionMerchantData` + * Add support for `Metadata` on `PaymentIntentCaptureParams` + * Add support for `Checks` on `SetupAttemptPaymentMethodDetailsCard` + * Add support for `TaxBreakdown` on `TaxCalculationShippingCost` and `TaxTransactionShippingCost` +* [#1643](https://github.com/stripe/stripe-go/pull/1643) Update generated code + +* [#1640](https://github.com/stripe/stripe-go/pull/1640) Update generated code + * Release specs are identical. + +## 74.15.0 - 2023-04-06 +* [#1638](https://github.com/stripe/stripe-go/pull/1638) Update generated code + * Add support for new value `link` on enum `PaymentMethodCardWalletType` + * Add support for `Country` on `PaymentMethodLink` + * Add support for `StatusDetails` on `PaymentMethodUsBankAccount` + +## 74.14.0 - 2023-03-30 +* [#1635](https://github.com/stripe/stripe-go/pull/1635) Update generated code + * Remove support for `New` method on resource `Tax.Transaction` + * This is not a breaking change, as this method was deprecated before the Tax Transactions API was released in favor of the `CreateFromCalculation` method. + * Add support for `ExportLicenseID` and `ExportPurposeCode` on `AccountCompanyParams`, `AccountCompany`, and `TokenAccountCompanyParams` + * Remove support for value `deleted` from enum `InvoiceStatus` + * This is not a breaking change, as the value was never returned or accepted as input. + * Add support for `AmountTip` on `TestHelpersTerminalReaderPresentPaymentMethodParams` +* [#1633](https://github.com/stripe/stripe-go/pull/1633) Trigger workflow for tags +* [#1632](https://github.com/stripe/stripe-go/pull/1632) Update generated code (new) + Release specs are identical. +* [#1631](https://github.com/stripe/stripe-go/pull/1631) Update generated code (new) + Release specs are identical. + +## 74.13.0 - 2023-03-23 +* [#1624](https://github.com/stripe/stripe-go/pull/1624) Update generated code + * Add support for new resources `Tax.CalculationLineItem`, `Tax.Calculation`, `Tax.TransactionLineItem`, and `Tax.Transaction` + * Add support for `ListLineItems` and `New` methods on resource `Calculation` + * Add support for `CreateFromCalculation`, `CreateReversal`, `Get`, `ListLineItems`, and `New` methods on resource `Transaction` + * Add support for `CurrencyConversion` on `CheckoutSession` + * Add support for new value `link` on enum `PaymentLinkPaymentMethodTypes` + * Add support for `AutomaticPaymentMethods` on `SetupIntentParams` and `SetupIntent` + +## 74.12.0 - 2023-03-16 +* [#1622](https://github.com/stripe/stripe-go/pull/1622) API Updates + * Add support for `CashAppPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `FutureRequirements` and `Requirements` on `BankAccount` + * Add support for `CashApp` on `ChargePaymentMethodDetails`, `CheckoutSessionPaymentMethodOptionsParams`, `CheckoutSessionPaymentMethodOptions`, `MandatePaymentMethodDetails`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupAttemptPaymentMethodDetails`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `Country` on `ChargePaymentMethodDetailsLink` + * Add support for new value `cashapp` on enums `InvoicePaymentSettingsPaymentMethodTypes` and `SubscriptionPaymentSettingsPaymentMethodTypes` + * Add support for `PreferredLocale` on `PaymentIntentConfirmPaymentMethodOptionsAffirmParams`, `PaymentIntentPaymentMethodOptionsAffirmParams`, and `PaymentIntentPaymentMethodOptionsAffirm` + * Add support for new value `automatic_async` on enums `PaymentIntentCaptureMethod` and `PaymentLinkPaymentIntentDataCaptureMethod` + * Add support for `CashAppHandleRedirectOrDisplayQRCode` on `PaymentIntentNextAction` and `SetupIntentNextAction` + * Add support for new value `cashapp` on enum `PaymentLinkPaymentMethodTypes` + * Add support for new value `cashapp` on enum `PaymentMethodType` + + +* [#1619](https://github.com/stripe/stripe-go/pull/1619) Update generated code (new) + * Add support for `CashappPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `Cashapp` on `ChargePaymentMethodDetails`, `CheckoutSessionPaymentMethodOptionsParams`, `CheckoutSessionPaymentMethodOptions`, `MandatePaymentMethodDetails`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupAttemptPaymentMethodDetails`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for new value `cashapp` on enums `InvoicePaymentSettingsPaymentMethodTypes` and `SubscriptionPaymentSettingsPaymentMethodTypes` + * Add support for `PreferredLocale` on `PaymentIntentConfirmPaymentMethodOptionsAffirmParams`, `PaymentIntentPaymentMethodOptionsAffirmParams`, and `PaymentIntentPaymentMethodOptionsAffirm` + * Add support for `CashappHandleRedirectOrDisplayQRCode` on `PaymentIntentNextAction` and `SetupIntentNextAction` + * Add support for new value `cashapp` on enum `PaymentLinkPaymentMethodTypes` + * Add support for new value `cashapp` on enum `PaymentMethodType` +* [#1618](https://github.com/stripe/stripe-go/pull/1618) Install goimports before trying to run it + +## 74.11.0 - 2023-03-09 +* [#1616](https://github.com/stripe/stripe-go/pull/1616) API Updates + * Add support for `CardIssuing` on `IssuingCardholderIndividualParams` + * Add support for new value `requirements.past_due` on enum `IssuingCardholderRequirementsDisabledReason` + * Add support for `CancellationDetails` on `SubscriptionCancelParams`, `SubscriptionParams`, and `Subscription` + + +## 74.10.0 - 2023-03-02 +* [#1614](https://github.com/stripe/stripe-go/pull/1614) API Updates + * Add support for `ReconciliationStatus` on `Payout` + * Add support for new value `lease_tax` on enum `TaxRateTaxType` + +* [#1613](https://github.com/stripe/stripe-go/pull/1613) Update golang.org/x/net +* [#1611](https://github.com/stripe/stripe-go/pull/1611) Run goimports on generated test suite + +## 74.9.0 - 2023-02-23 +* [#1609](https://github.com/stripe/stripe-go/pull/1609) API Updates + * Add support for new value `yoursafe` on enums `ChargePaymentMethodDetailsIdealBank`, `PaymentMethodIdealBank`, and `SetupAttemptPaymentMethodDetailsIdealBank` + * Add support for new value `BITSNL2A` on enums `ChargePaymentMethodDetailsIdealBic`, `PaymentMethodIdealBic`, and `SetupAttemptPaymentMethodDetailsIdealBic` + * Add support for new value `igst` on enum `TaxRateTaxType` + +## 74.8.0 - 2023-02-16 +* [#1605](https://github.com/stripe/stripe-go/pull/1605) API Updates + * Add support for `RefundPayment` method on resource `Terminal.Reader` + * Add support for new value `name` on enum `BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdates` + * Add support for `CustomFields` on `CheckoutSessionParams`, `CheckoutSession`, `PaymentLinkParams`, and `PaymentLink` + * Add support for `InteracPresent` on `TestHelpersTerminalReaderPresentPaymentMethodParams` + * Change type of `TestHelpersTerminalReaderPresentPaymentMethodTypeParams` from `literal('card_present')` to `enum('card_present'|'interac_present')` + * Add support for `RefundPayment` on `TerminalReaderAction` + * Add support for new value `refund_payment` on enum `TerminalReaderActionType` +* [#1607](https://github.com/stripe/stripe-go/pull/1607) fix: deterministic encoding +* [#1603](https://github.com/stripe/stripe-go/pull/1603) Add an example of client mocking +* [#1604](https://github.com/stripe/stripe-go/pull/1604) Run lint on go 1.19 + +## 74.7.0 - 2023-02-02 +* [#1600](https://github.com/stripe/stripe-go/pull/1600) API Updates + * Add support for `Resume` method on resource `Subscription` + * Add support for `PaymentLink` on `CheckoutSessionListParams` + * Add support for `TrialSettings` on `CheckoutSessionSubscriptionDataParams`, `SubscriptionParams`, and `Subscription` + * Add support for new value `BE` on enums `CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransferCountry`, `InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransferCountry`, `PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransferCountry`, and `SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransferCountry` + * Add support for `ShippingCost` on `CreditNoteParams`, `CreditNotePreviewLinesParams`, `CreditNotePreviewParams`, `CreditNote`, `InvoiceParams`, and `Invoice` + * Add support for `AmountShipping` on `CreditNote` and `Invoice` + * Add support for `ShippingDetails` on `InvoiceParams` and `Invoice` + * Add support for `SubscriptionResumeAt` on `InvoiceUpcomingLinesParams` and `InvoiceUpcomingParams` + * Add support for `InvoiceCreation` on `PaymentLinkParams` and `PaymentLink` + * Add support for new value `paused` on enum `SubscriptionStatus` + * Add support for new value `funding_reversed` on enum `CustomerCashBalanceTransactionType` + +* [#1562](https://github.com/stripe/stripe-go/pull/1562) add missing verify with micro-deposits next action + +## 74.6.0 - 2023-01-19 +* [#1595](https://github.com/stripe/stripe-go/pull/1595) API Updates + * Add support for `VerificationSession` on `EphemeralKeyParams` + * Add missing enum values to `RefundStatus`, `PersonVerificationDetailsCode`, `PersonVerificationDocumentDetailsCode`, `AccountCompanyVerificationDocumentDetailsCode` . + + +## 74.5.0 - 2023-01-05 +* [#1588](https://github.com/stripe/stripe-go/pull/1588) API Updates + * Add support for `CardIssuing` on `IssuingCardholderIndividual` + +## 74.4.0 - 2022-12-22 +* [#1586](https://github.com/stripe/stripe-go/pull/1586) API Updates + * Add support for `UsingMerchantDefault` on `CashBalanceSettings` + * Change type of `CheckoutSessionCancelUrl` from `string` to `nullable(string)` + +## 74.3.0 - 2022-12-15 +* [#1584](https://github.com/stripe/stripe-go/pull/1584) API Updates + * Add support for new value `invoice_overpaid` on enum `CustomerBalanceTransactionType` +* [#1581](https://github.com/stripe/stripe-go/pull/1581) API Updates + + +## 74.2.0 - 2022-12-06 +* [#1579](https://github.com/stripe/stripe-go/pull/1579) API Updates + * Add support for `FlowData` on `BillingPortalSessionParams` + * Add support for `Flow` on `BillingPortalSession` +* [#1578](https://github.com/stripe/stripe-go/pull/1578) API Updates + * Add support for `IndiaInternationalPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `InvoiceCreation` on `CheckoutSessionParams` and `CheckoutSession` + * Add support for `Invoice` on `CheckoutSession` + * Add support for `Metadata` on `SubscriptionSchedulePhasesItemsParams` and `SubscriptionSchedulePhasesItems` +* [#1575](https://github.com/stripe/stripe-go/pull/1575) Add version to go reference path + +## 74.1.0 - 2022-11-17 +* [#1574](https://github.com/stripe/stripe-go/pull/1574) API Updates + * Add support for `CustomText` on `CheckoutSessionParams`, `CheckoutSession`, `PaymentLinkParams`, and `PaymentLink` + * Add support for `HostedInstructionsURL` on `PaymentIntentNextActionPaynowDisplayQrCode` and `PaymentIntentNextActionWechatPayDisplayQrCode` + + +## 74.0.0 - 2022-11-15 + +Breaking changes that arose during code generation of the library that we postponed for the next major version. For changes to the Stripe products, read more at https://docs.stripe.com/changelog/2022-11-15. + +"⚠️" symbol highlights breaking changes. + +⚠️ Removed +- Removed deprecated `sku` resource (#1557) +- Removed `lineitem.Product` property that was released by mistake. (#1555) +- Removed deprecated `CheckoutSessionSubscriptionDataParams.Items` field. (#1555) +- Removed deprecated `EphemeralKey.AssociatedObjects` field. (#1566) +- Removed deprecated `Amount`, `Currency`, `Description`, `Images`, `Name` properties from `CheckoutSessionLineItemParams` (https://github.com/stripe/stripe-go/pull/1570) +- Removed `Charges` field on `PaymentIntent` and replace it with `LatestCharge`. (https://github.com/stripe/stripe-go/pull/1570) +- Dropped support for Go versions less than 1.15 (#1554) +- Remove support for `TOSShownAndAccepted` on `CheckoutSessionPaymentMethodOptionsPaynowParams`. The property was mistakenly released and never worked ([#1571](https://github.com/stripe/stripe-go/pull/1571)). + +## 73.16.0 - 2022-11-08 +* [#1568](https://github.com/stripe/stripe-go/pull/1568) API Updates + * Add support for `ReasonMessage` on `IssuingAuthorizationRequestHistory` + * Add support for new value `webhook_error` on enum `IssuingAuthorizationRequestHistoryReason` + +## 73.15.0 - 2022-11-03 +* [#1563](https://github.com/stripe/stripe-go/pull/1563) API Updates + * Add support for `OnBehalfOf` on `CheckoutSessionSubscriptionDataParams`, `SubscriptionParams`, `SubscriptionScheduleDefaultSettingsParams`, `SubscriptionScheduleDefaultSettings`, `SubscriptionSchedulePhasesParams`, `SubscriptionSchedulePhases`, and `Subscription` + * Add support for new values `eg_tin`, `ph_tin`, and `tr_tin` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, `OrderTaxDetailsTaxIdsType`, and `TaxIdType` + * Add support for `TaxBehavior` and `TaxCode` on `InvoiceItemParams`, `InvoiceUpcomingInvoiceItemsParams`, and `InvoiceUpcomingLinesInvoiceItemsParams` + +## 73.14.0 - 2022-10-20 +* [#1560](https://github.com/stripe/stripe-go/pull/1560) API Updates + * Add support for new values `jp_trn` and `ke_pin` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, `OrderTaxDetailsTaxIdsType`, and `TaxIdType` + * Add support for `Tipping` on `TerminalReaderActionProcessPaymentIntentProcessConfig` and `TerminalReaderProcessPaymentIntentProcessConfigParams` + +## 73.13.0 - 2022-10-13 +* [#1558](https://github.com/stripe/stripe-go/pull/1558) API Updates + * Add support for `NetworkData` on `IssuingAuthorization` +* [#1553](https://github.com/stripe/stripe-go/pull/1553) Add RequestLogURL on Error + +## 73.12.0 - 2022-10-06 +* [#1551](https://github.com/stripe/stripe-go/pull/1551) API Updates + * Add support for new value `invalid_dob_age_under_18` on enums `AccountFutureRequirementsErrorsCode`, `AccountRequirementsErrorsCode`, `CapabilityFutureRequirementsErrorsCode`, `CapabilityRequirementsErrorsCode`, `PersonFutureRequirementsErrorsCode`, and `PersonRequirementsErrorsCode` + * Add support for new value `bank_of_china` on enums `ChargePaymentMethodDetailsFpxBank` and `PaymentMethodFpxBank` + * Add support for `Klarna` on `SetupAttemptPaymentMethodDetails` + +## 73.11.0 - 2022-09-29 +* [#1549](https://github.com/stripe/stripe-go/pull/1549) API Updates + * Change type of `ChargePaymentMethodDetailsCardPresentIncrementalAuthorizationSupported` and `ChargePaymentMethodDetailsCardPresentOvercaptureSupported` from `nullable(boolean)` to `boolean` + * Add support for `Created` on `CheckoutSession` + * Add support for `SetupFutureUsage` on `PaymentIntentConfirmPaymentMethodOptionsPixParams`, `PaymentIntentPaymentMethodOptionsPixParams`, and `PaymentIntentPaymentMethodOptionsPix` + * Deprecate `CheckoutSessionSubscriptionDataTransferDataParams.items` and `CheckoutSessionSubscriptionDataItemParams` (use the `line_items` param instead). This will be removed in the next major version. + + +## 73.10.0 - 2022-09-22 +* [#1547](https://github.com/stripe/stripe-go/pull/1547) API Updates + * Add support for `TermsOfService` on `CheckoutSessionConsentCollectionParams`, `CheckoutSessionConsentCollection`, `CheckoutSessionConsent`, `PaymentLinkConsentCollectionParams`, and `PaymentLinkConsentCollection` + * ⚠️ Remove support for `Plan` on `CheckoutSessionPaymentMethodOptionsCardInstallmentsParams`. The property was mistakenly released and never worked. + * Add support for `StatementDescriptor` on `PaymentIntentIncrementAuthorizationParams` + + +## 73.9.0 - 2022-09-15 +* [#1546](https://github.com/stripe/stripe-go/pull/1546) API Updates + * Add support for `Pix` on `ChargePaymentMethodDetails`, `CheckoutSessionPaymentMethodOptionsParams`, `CheckoutSessionPaymentMethodOptions`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `FromInvoice` on `InvoiceParams` and `Invoice` + * Add support for `LatestRevision` on `Invoice` + * Add support for `Amount` on `IssuingDisputeParams` + * Add support for `PixDisplayQRCode` on `PaymentIntentNextAction` + * Add support for new value `pix` on enum `PaymentLinkPaymentMethodTypes` + * Add support for new value `pix` on enum `PaymentMethodType` + * Add support for `Created` on `TreasuryCreditReversal` and `TreasuryDebitReversal` +* [#1545](https://github.com/stripe/stripe-go/pull/1545) Export UnsignedPayload/SignedPayload fields + +## 73.8.0 - 2022-09-09 +* [#1543](https://github.com/stripe/stripe-go/pull/1543) API Updates + * Add support for `RequireSignature` on `IssuingCardShippingParams` and `IssuingCardShipping` + +## 73.7.0 - 2022-09-06 +* [#1542](https://github.com/stripe/stripe-go/pull/1542) API Updates + * Add support for new value `terminal_reader_splashscreen` on enum `FilePurpose` + +## 73.6.0 - 2022-08-31 +* [#1541](https://github.com/stripe/stripe-go/pull/1541) API Updates + * Add support for `Description` on `PaymentLinkSubscriptionDataParams` and `PaymentLinkSubscriptionData` + +## 73.5.0 - 2022-08-26 +* [#1537](https://github.com/stripe/stripe-go/pull/1537) API Updates + * Add support for `LoginPage` on `BillingPortalConfigurationParams` and `BillingPortalConfiguration` + * Add support for new value `deutsche_bank_ag` on enums `ChargePaymentMethodDetailsEpsBank` and `PaymentMethodEpsBank` + * Add support for `Customs` and `PhoneNumber` on `IssuingCardShippingParams` and `IssuingCardShipping` + * Add support for `Description` on `QuoteSubscriptionDataParams`, `QuoteSubscriptionData`, `SubscriptionScheduleDefaultSettingsParams`, `SubscriptionScheduleDefaultSettings`, `SubscriptionSchedulePhasesParams`, and `SubscriptionSchedulePhases` +* [#1536](https://github.com/stripe/stripe-go/pull/1536) Add test coverage using coveralls +* [#1533](https://github.com/stripe/stripe-go/pull/1533) Update README.md to clarify that API version can only be change in beta + +## 73.4.0 - 2022-08-23 +* [#1532](https://github.com/stripe/stripe-go/pull/1532) API Updates + * Change type of `TreasuryOutboundTransferDestinationPaymentMethod` from `string` to `nullable(string)` + * Change return type of `FundCashBalance` method on `Customer` from `Customer` to `CustomerCashBalanceTransaction` + * This is technically a breaking change, but this return type was actually incorrect and so the result of this method did not deserialize correctly. + * Change return type of `RetrieveFeatures` and `UpdateFeatures` methods on `TreasuryFinancialAccount` from `TreasuryFinancialAccount` to `TreasuryFinancialAccountFeatures` + * This is technically a breaking change, but this return type was actually incorrect and so the result of this method did not deserialize correctly. +* [#1530](https://github.com/stripe/stripe-go/pull/1530) Add beta readme.md section + +## 73.3.0 - 2022-08-19 +* [#1528](https://github.com/stripe/stripe-go/pull/1528) API Updates + * Add support for new resource `CustomerCashBalanceTransaction` + * Remove support for value `paypal` from enum `OrderPaymentSettingsPaymentMethodTypes` + * Add support for `Currency` on `PaymentLink` + * Add support for `Network` on `SetupIntentConfirmPaymentMethodOptionsCardParams`, `SetupIntentPaymentMethodOptionsCardParams`, `SubscriptionPaymentSettingsPaymentMethodOptionsCardParams`, and `SubscriptionPaymentSettingsPaymentMethodOptionsCard` + * Change type of `TopupSource` from `$Source` to `nullable($Source)` +* [#1526](https://github.com/stripe/stripe-go/pull/1526) Add a support section to the readme + +## 73.2.0 - 2022-08-11 +* [#1524](https://github.com/stripe/stripe-go/pull/1524) API Updates + * Add support for `PaymentMethodCollection` on `CheckoutSessionParams`, `CheckoutSession`, `PaymentLinkParams`, and `PaymentLink` + + +## 73.1.0 - 2022-08-09 +* [#1522](https://github.com/stripe/stripe-go/pull/1522) API Updates + * Add support for `ProcessConfig` on `TerminalReaderActionProcessPaymentIntent` +* [#1282](https://github.com/stripe/stripe-go/pull/1282) Miscellaneous fixes to README.md +* [#1520](https://github.com/stripe/stripe-go/pull/1520) Add GenerateTestSignedPayload to test webhook signing +* [#1402](https://github.com/stripe/stripe-go/pull/1402) Update testify version +* [#1519](https://github.com/stripe/stripe-go/pull/1519) API Updates + * Add support for `ExpiresAt` on `AppsSecretParams` and `AppsSecret` + +## 73.0.1 - 2022-08-03 +* [#1517](https://github.com/stripe/stripe-go/pull/1517) Export ConstructEventOptions fields + +## 73.0.0 - 2022-08-02 + +This release includes breaking changes resulting from: + +* Moving to use the new API version "2022-08-01". To learn more about these changes to Stripe products, see https://docs.stripe.com/changelog/2022-08-01 +* Cleaning up the SDK to remove deprecated/unused APIs and rename classes/methods/properties to sync with product APIs. Read more detailed description at https://github.com/stripe/stripe-go/wiki/Migration-guide-for-v73. + +"⚠️" symbol highlights breaking changes. + +* [#1513](https://github.com/stripe/stripe-go/pull/1513) API Updates +* [#1512](https://github.com/stripe/stripe-go/pull/1512) Next major release changes + +### Added + +- Add `CheckoutSessionSetupIntentDataParams.Metadata`. +- Add Invoice `UpcomingLines` method. +- Add `ShippingCost` and `ShippingDetails` properties to `CheckoutSession` resource. +- Add `CheckoutSessionShippingCostTax` and `CheckoutSessionShippingCost` classes +- Add `IssuingCardCancellationReasonDesignRejected` constant to `IssuingCardCancellationReason`. +- Add `Validate` field to `Customer` resource. +- Add `Validate` field to `PaymentSourceParams`. +- Add `SetupAttemptPaymentMethodDetailsCardThreeDSecureResultExempted` constant in `SetupAttemptPaymentMethodDetailsCardThreeDSecureResult`. +- Add `SKUPackageDimensionsParams` and `SKUPackageDimensions`. +- Add dedicated structs for different payment sources and transfers. +- Add `Subscription.DeleteDiscount` methods. +- Add `SubscriptionItemUsageRecordSummariesParams` +- Add `UsageRecordSummary` `UsageRecordSummaries`, and `UsageRecordSummaryList` methods in `SubscriptionItem` +- Add `SubscriptionSchedulePhaseBillingCycleAnchor`, `SubscriptionSchedulePhaseBillingCycleAnchorAutomatic`, and `SubscriptionSchedulePhaseBillingCycleAnchorPhaseStart` +- Add `SubscriptionSchedulePhaseInvoiceSettings` and `SubscriptionSchedulePhaseInvoiceSettingsParams ` +- `TerminalLocation` `UnmarshalJSON` - make `TerminalLocation` expandable +* Add support for new value `invalid_tos_acceptance` on enums `AccountFutureRequirementsErrorsCode`, `AccountRequirementsErrorsCode`, `CapabilityFutureRequirementsErrorsCode`, `CapabilityRequirementsErrorsCode`, `PersonFutureRequirementsErrorsCode`, and `PersonRequirementsErrorsCode` +* Add support for `ShippingCost` and `ShippingDetails` on `CheckoutSession` + +### ⚠️ Changed + +- Rename files to be consistent with the library's naming conventions. + - `fee.go` to `applicationfee.go` + - `fee/client.go` to `applicationfee/client.go` + - `sub.go` to `subscription.go` + - `sub/client.go` to `subscription/client.go` + - `subitem.go` to `subscriptionitem.go` + - `subitem/client.go` to `subscriptionitem/client.go` + - `subschedule.go` to `subscriptionschedule.go` + - `subschedule/client.go` to `subscriptionschedule/client.go` + - `reversal.go` to `transferreversal.go` + - `reversal/client.go` to `transferreversal/client.go` + +- Change resource names on `client#API` to be plural to be consistent with the library's naming conventions: +- Rename structs, fields, enums, and methods to be consistent with the library's naming conventions and with the other Stripe SDKs. + - `Ach` to `ACH` + - `Acss` to `ACSS` + - `Bic` to `BIC` + - `Eps` to `EPS` + - `FEDEX` to `FedEx` + - `Iban` to `IBAN` + - `Ideal` to `IDEAL` + - `Sepa` to `SEPA` + - `Wechat` to `WeChat` + - `ExternalAccount` to `AccountExternalAccount` + - `InvoiceLine` to `InvoiceLineItem` + - `Person` structs/enums to use `Person` prefix + - and others (see Migration guide) + +- Change types of various fields in `Account`, `ApplicationFee`, `BalanceTransaction`, `BillingPortalConfiguration`, `Card`, `Charge`, `Customer`, `Discount`, `Invoice`, `Issuing Card`, `Issuing Dispute `, `Mandate `, `PaymentIntent`, `PaymentMethod`, `Payout`, `Plan `, `Plan `, `Refund`, `SetupIntent`, `Source`, `Source`, `Subscription`, `SubscriptionItem`, `SubscriptionSchedule`, `Terminal ConnectionToken`, `Terminal Location`, `Terminal Reader `, `Topup`, and `Transfer` (see Migration guide). + +- Update the Webhook `ConstructEvent,` `ConstructEventIgnoringTolerance` and `ConstructEventWithTolerance` functions to return an error when the webhook event's API version does not match the stripe-go library API version. +- Update `ErrorType`and `ErrorCode` values. +- Move `BalanceTransaction` iterator from `balance.go` to `balancetransaction.go` +- Fix `BalanceTransactionSource` `UnmarshalJSON` for when `BalanceTransactionSource.Type == "transfer_reversal"` (previously, we were checking if `Type == "reversal"`, which was always false) +- For BankAccount and Card client methods, check that exactly one of `params.Account` and `params.Customer` is set (previously they could both be set, but only one would be used, and it was different between BankAccount and Card) +- Replace `CardVerification` with field-specific enums (with the same values) +- Move `Del` from `discount/client.go` to `customer/client.go` and rename to `DeleteDiscount` +- Move `DelSub` from `discount/client.go` to `subscription/client.go` and rename to `DeleteDiscount` +- Add separate parameter struct for CreditNote `ListPreviewLines` (renamed to `PreviewLines`) method (`[CreditNoteLineItemListPreviewParams -> CreditNotePreviewParams].Lines` `CreditNoteLineParams` -> `CreditNotePreviewLineParams`) +- Replace `FeeRefundParams.ApplicationFee` with `FeeRefundParams.Fee` and `FeeRefundParams.ID` +- Add separate parameter struct for Invoice `GetNext` (renamed to `Upcoming`) method (`InvoiceUpcomingParams`, and nested params `InvoiceUpcomingLinesInvoiceItemPriceDataParams`, `InvoiceUpcomingLinesInvoiceItemDiscountParams`, `InvoiceUpcomingLinesDiscountParams`, `InvoiceUpcomingLinesInvoiceItemPeriodParams`). `Upcoming`-only fields `Coupon`, `CustomerDetails`, `InvoiceItems`, `Subscription`, `SubscriptionBillingCycleAnchor`, `Schedule`, `SubscriptionBillingCycleAnchor`, `SubscriptionBillingCycleAnchorNow`, `SubscriptionBillingCycleAnchorUnchanged`, `SubscriptionCancelAt`, `SubscriptionCancelAtPeriodEnd`, `SubscriptionCancelNow`, `SubscriptionDefaultTaxRates`, `SubscriptionItems`, `SubscriptionProrationBehavior`, `SubscriptionProrationDate`, `SubscriptionStartDate`, `SubscriptionTrialEnd`, `SubscriptionTrialEndNow`, and `SubscriptionTrialFromPlan` are removed from `InvoiceParams`. +- Add separate structs for `BillingDetails` and `BillingDetailsParams`: `PaymentMethodBillingDetails`, `PaymentMethodBillingDetailsParams` +- Add separate structs for `PaymentMethodCardNetwork`: `PaymentMethodCardNetworksAvailable`, `PaymentMethodCardNetworksPreferred` + +### Deprecated + +- The `SKU` resource has been deprecated. This will be replaced by https://stripe.com/docs/api/orders_v2. + +### ⚠️ Removed + +- Remove the legacy Orders API +- Remove `AccountCapability` enum definition. This was not referenced in the library. +- Remove `UnmarshalJSON` for resources that are not expandable: `BillingPortalSession`, `Capability`, `CheckoutSession`, `FileLink`, `InvoiceItem`, `LineItem`, `Person`, `WebhookEndpoint` +- Remove `AccountRejectReason` (was only referenced in `account/client_test.go`, actual `AccountRejectParams.Reason` is `*string`) +- Remove `AccountParams.RequestedCapabilities` (use Capabilities instead: https://stripe.com/docs/connect/account-capabilities) +- Remove `AccountSettingsParams.Dashboard` and `AccountSettingsDashboardParams` (Note: `Dashboard` are still available on `AccountSettings`, but it's not available as parameters for any of the methods) +- Remove `AccountCompany.RegistrationNumber` (Note: `RegistrationNumber` is still available on `AccountCompanyParams`, but is not returned in the response) +- Remove `BalanceTransactionStatus`. It was meant to be an enum, but none of the enum values were defined, so it was just an alias for string. +- Remove `CardParams.AccountType`. `AccountType` does not exist on any client method for Card. It does on BankAccount, which is similar. +- Remove `id` param from CheckoutSessions `ListLineItems`. Use `CheckoutSessionListLineItemsParams.Session` instead. +- Remove `CheckoutSessionLineItemPriceDataRecurringParams.AggregateUsage`, `CheckoutSessionLineItemPriceDataRecurringParams.TrialPeriodDays`, and `CheckoutSessionLineItemPriceDataRecurringParams.UsageType` +- Remove `CheckoutSessionPaymentIntentDataParams.Params`, `CheckoutSessionSetupIntentDataParams.Params`, `CheckoutSessionSubscriptionDataParams.Params`. `Params` should only be embedded in root method struct, and has extraneous fields not applicable to child/sub structs. +- Remove `CheckoutSessionTotalDetailsBreakdownTax.TaxRate`. Use `CheckoutSessionTotalDetailsBreakdownTax.Rate` +- Remove `CheckoutSessionTotalDetailsBreakdownTax.Deleted` +- Remove `CustomerParams.Token` +- Remove `Discount` `APIResource` embed +- Remove `DiscountParams` +- Remove `FilePurposeFoundersStockDocument` (`"founders_stock_document"` option for `File.Purpose`) +- Remove `InvoiceParams.Paid`. Use `invoice.status` to check for status. `invoice.status` is a read-only field. +- Remove `InvoiceParams.SubscriptionPlan` and `InvoiceParams.SubscriptionQuantity` (note: these would have been on `InvoiceUpcomingParams`) +- Remove `InvoiceListLinesParams.Customer` and `InvoiceListLinesParams.Subscription` (these are not available for Invoice `ListLines`, but are available for `List`) +- Remove `IssuingAuthorizationRequestHistoryViolatedAuthorizationControlEntity` and `IssuingAuthorizationRequestHistoryViolatedAuthorizationControlName` (unused enums) +- Remove `IssuingCardSpendingControlsParams.SpendingLimitsCurrency`. `issuing_card` has `currency`, and `issuing_card.spending_controls.spending_limits.amount` will use that currency +- Remove `IssuingDisputeEvidenceServiceNotAsDescribed.ProductDescription`, `IssuingDisputeEvidenceServiceNotAsDescribed.ProductType`, `IssuingDisputeEvidenceServiceNotAsDescribedParams.ProductDescription`, `IssuingDisputeEvidenceServiceNotAsDescribedParams.ProductType`, and `IssuingDisputeEvidenceServiceNotAsDescribedProductType`. `issuing_dispute.evidence.service_not_as_described` does not have `product_description` or `product_type`. `issuing_dispute.evidence.canceled` does. +- Remove `LineItemTax.TaxRate`. Use `LineItemTax.Rate` instead. +- Remove `LineItem.Deleted` +- Remove `LoginLink.RedirectURL` +- Remove `PaymentIntentOffSession` (unused enum) +- Remove `PaymentIntentConfirmParams.PaymentMethodTypes` +- Remove `PaymentMethodFPX.TransactionID` +- Remove `Payout.BankAccount` and `Payout.Card` (These fields were never populated, use `PayoutDestination.BankAccount` and `PayoutDestination.Card` instead) +- Remove `PlanParams.ProductID`. Use `PlanParams.Product.ID` instead. +- Remove `Shipping` and `ShippingRate` properties from `CheckoutSession` resource. Please use `ShippingCost` and `ShippingDetails` properties instead. +- Remove `DefaultCurrency` property from `Customer` resource. Please use `Currency` property instead. +- Remove `Updated` and `UpdatedBy` from `RadarValueList` +- Remove `Name` from `RadarValueListItem` +- Remove `ReviewReasonType` type from `Review` resource. Use `ReviewReason` instead +- Remove `SetupIntentCancellationReasonFailedInvoice` and `SetupIntentCancellationReasonFraudulent` values from `SetupIntentCancellationReason` +- Remove `SigmaScheduledQueryRun.Query`. The field was invalid +- Remove `SKUParams.Description` and `SKU.Description` +- Remove `SourceMandateAcceptanceStatus`, `SourceMandateAcceptanceStatusAccepted`, `SourceMandateAcceptanceStatusRefused`, `SourceMandateNotificationMethod`, `SourceMandateNotificationMethodEmail`, `SourceMandateNotificationMethodManual`, and `SourceMandateNotificationMethodNone` +- Remove `Source.TypeData` and SourceParams and replace with payment method-specific fields (AUBECSDebit, Bancontact, Card, CardPresent, EPS, Giropay, IDEAL, Klarna, Multibanco, P24, SEPACreditTransfer, SEPADebit, Sofort, ThreeDSecure, Wechat) and `Source.AppendTo` method +- Remove `SourceTransaction.CustomerData`. The field was deprecated +- Remove `SourceTransaction.TypeData` and `SourceTransaction.UnmarshalJSON`. Use payment specific fields - Remove `ACHCreditTransfer`, `CHFCreditTransfer`, `GBPCreditTransfer`, `PaperCheck`, and `SEPACreditTransfer` +- Remove `SubscriptionPaymentBehavior`, `SubscriptionPaymentBehaviorAllowIncomplete`, `SubscriptionPaymentBehaviorErrorIfIncomplete`, and `SubscriptionPaymentBehaviorPendingIfIncomplete` +- Remove `SubscriptionProrationBehavior`, `SubscriptionProrationBehaviorAlwaysInvoice`, `SubscriptionProrationBehaviorCreateProrations`, and `SubscriptionProrationBehaviorNone` +- Remove `SubscriptionStatusAll` +- Remove `SubscriptionParams.Card`, `SubscriptionParams.Plan`, and `SubscriptionParams.Quantity` +- Remove `Subscription.Plan` and `Subscription.Quantity` +- Remove `SubscriptionItemParams.ID`. The field was deprecated +- Remove `SubscriptionSchedulePhaseAddInvoiceItemPriceDataRecurringParams` and `SubscriptionSchedulePhaseAddInvoiceItemPriceDataParams` +- Remove `Del` method on `TaxRate` +- Remove `TerminalReaderGetParams`. Use `TerminalReaderParams` instead. +- Remove `TerminalReaderList.Location` and `TerminalReaderList.Status` (Not available for the list, but is available for individual `TerminalReader`s in `TerminalReaderList.Data`) +- Remove `Token.Email` and `TokenParams.Email` +- Remove `TopupParams.SetSource` +- Remove `WebhookEndpointListParams.Created` and `WebhookEndpointListParams.CreatedRange` (use `StartingAfter` from `ListParams`) +- Remove `WebhookEndpoint.Connected` + +## 72.122.0 - 2022-07-26 +* [#1508](https://github.com/stripe/stripe-go/pull/1508) API Updates + * Add support for new value `exempted` on enums `ChargePaymentMethodDetailsCardThreeDSecureResult` and `SetupAttemptPaymentMethodDetailsCardThreeDSecureResult` + * Add support for `CustomerBalance` on `CheckoutSessionPaymentMethodOptionsParams` and `CheckoutSessionPaymentMethodOptions` + +## 72.121.0 - 2022-07-25 +* [#1507](https://github.com/stripe/stripe-go/pull/1507) API Updates + * Add support for `Installments` on `CheckoutSessionPaymentMethodOptionsCardParams`, `CheckoutSessionPaymentMethodOptionsCard`, `InvoicePaymentSettingsPaymentMethodOptionsCardParams`, and `InvoicePaymentSettingsPaymentMethodOptionsCard` + * Add support for `DefaultCurrency` and `InvoiceCreditBalance` on `Customer` + * Add support for `Currency` on `InvoiceParams` + * Add support for `DefaultMandate` on `InvoicePaymentSettingsParams` and `InvoicePaymentSettings` + * Add support for `Mandate` on `InvoicePayParams` + + +## 72.120.0 - 2022-07-18 +* [#1497](https://github.com/stripe/stripe-go/pull/1497) API Updates + * Add support for `BLIKPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `BLIK` on `ChargePaymentMethodDetails`, `MandatePaymentMethodDetails`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupAttemptPaymentMethodDetails`, `SetupIntentConfirmPaymentMethodDataParams`, `SetupIntentConfirmPaymentMethodOptionsParams`, `SetupIntentPaymentMethodDataParams`, `SetupIntentPaymentMethodOptionsParams`, and `SetupIntentPaymentMethodOptions` + * Change type of `CheckoutSessionConsentCollectionPromotionsParams`, `CheckoutSessionConsentCollectionPromotions`, `PaymentLinkConsentCollectionPromotionsParams`, and `PaymentLinkConsentCollectionPromotions` from `literal('auto')` to `enum('auto'|'none')` + * Add support for new value `blik` on enum `PaymentLinkPaymentMethodTypes` + * Add support for new value `blik` on enum `PaymentMethodType` + +## 72.119.0 - 2022-07-12 +* [#1494](https://github.com/stripe/stripe-go/pull/1494) API Updates + * Add support for `CustomerDetails` on `CheckoutSessionListParams` + +## 72.118.0 - 2022-07-07 +* [#1492](https://github.com/stripe/stripe-go/pull/1492) API Updates + * Add support for `Currency` on `CheckoutSessionParams`, `InvoiceUpcomingLinesParams`, `InvoiceUpcomingParams`, `PaymentLinkParams`, `SubscriptionParams`, `SubscriptionSchedulePhasesParams`, `SubscriptionSchedulePhases`, and `Subscription` + * Add support for `CurrencyOptions` on `CheckoutSessionShippingOptionsShippingRateDataFixedAmountParams`, `CouponParams`, `Coupon`, `OrderShippingCostShippingRateDataFixedAmountParams`, `PriceParams`, `Price`, `ProductDefaultPriceDataParams`, `PromotionCodeRestrictionsParams`, `PromotionCodeRestrictions`, `ShippingRateFixedAmountParams`, and `ShippingRateFixedAmount` + * Add support for `Restrictions` on `PromotionCodeParams` + * Add support for `FixedAmount` and `TaxBehavior` on `ShippingRateParams` +* [#1491](https://github.com/stripe/stripe-go/pull/1491) API Updates + * Add support for `Customer` on `CheckoutSessionListParams` and `RefundParams` + * Add support for `Currency` and `Origin` on `RefundParams` + + +## 72.117.0 - 2022-06-29 +* [#1487](https://github.com/stripe/stripe-go/pull/1487) API Updates + * Add support for `DeliverCard`, `FailCard`, `ReturnCard`, and `ShipCard` test helper methods on resource `Issuing.Card` + * Change type of `PaymentLinkPaymentMethodTypesParams` and `PaymentLinkPaymentMethodTypes` from `literal('card')` to `enum` + * Add support for `HostedRegulatoryReceiptURL` on `TreasuryReceivedCredit` and `TreasuryReceivedDebit` + +* [#1483](https://github.com/stripe/stripe-go/pull/1483) Document use of undocumented parameters/properties + +## 72.116.0 - 2022-06-23 +* [#1484](https://github.com/stripe/stripe-go/pull/1484) API Updates + * Add support for `CaptureMethod` on `PaymentIntentConfirmParams` and `PaymentIntentParams` +* [#1481](https://github.com/stripe/stripe-go/pull/1481) API Updates + * Add support for `PromptPayPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `PromptPay` on `ChargePaymentMethodDetails`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `SubtotalExcludingTax` on `CreditNote` and `Invoice` + * Add support for `AmountExcludingTax` and `UnitAmountExcludingTax` on `CreditNoteLineItem` and `InvoiceLineItem` + * Add support for `RenderingOptions` on `InvoiceParams` + * Add support for `TotalExcludingTax` on `Invoice` + * Add support for new value `promptpay` on enums `InvoicePaymentSettingsPaymentMethodTypes` and `SubscriptionPaymentSettingsPaymentMethodTypes` + * Add support for `AutomaticPaymentMethods` on `OrderPaymentSettings` + * Add support for `PromptPayDisplayQRCode` on `PaymentIntentNextAction` + * Add support for new value `promptpay` on enum `PaymentMethodType` + +* [#1482](https://github.com/stripe/stripe-go/pull/1482) Use the generated API version + +## 72.115.0 - 2022-06-17 +* [#1477](https://github.com/stripe/stripe-go/pull/1477) API Updates + * Add support for `FundCashBalance` test helper method on resource `Customer` + * Add support for `StatementDescriptorPrefixKana` and `StatementDescriptorPrefixKanji` on `AccountSettingsCardPaymentsParams`, `AccountSettingsCardPayments`, and `AccountSettingsPayments` + * Add support for `StatementDescriptorSuffixKana` and `StatementDescriptorSuffixKanji` on `CheckoutSessionPaymentMethodOptionsCardParams`, `CheckoutSessionPaymentMethodOptionsCard`, `PaymentIntentConfirmPaymentMethodOptionsCardParams`, `PaymentIntentPaymentMethodOptionsCardParams`, and `PaymentIntentPaymentMethodOptionsCard` + * Add support for `TotalExcludingTax` on `CreditNote` + * Change type of `CustomerInvoiceSettingsRenderingOptionsParams` from `rendering_options_param` to `emptyStringable(rendering_options_param)` + * Add support for `RenderingOptions` on `CustomerInvoiceSettings` and `Invoice` +* [#1478](https://github.com/stripe/stripe-go/pull/1478) Fix test assert to allow beta versions +* [#1475](https://github.com/stripe/stripe-go/pull/1475) Trigger workflows on beta branches + +## 72.114.0 - 2022-06-09 +* [#1473](https://github.com/stripe/stripe-go/pull/1473) API Updates + * Add support for `Treasury` on `AccountSettingsParams` and `AccountSettings` + * Add support for `RenderingOptions` on `CustomerInvoiceSettingsParams` + * Add support for `EUBankTransfer` on `CustomerCreateFundingInstructionsBankTransferParams`, `InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams`, `InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer`, `OrderPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams`, `OrderPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer`, `PaymentIntentConfirmPaymentMethodOptionsCustomerBalanceBankTransferParams`, `PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferParams`, `PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransfer`, `SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams`, and `SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer` + * Change type of `CustomerCreateFundingInstructionsBankTransferRequestedAddressTypesParams` from `literal('zengin')` to `enum('iban'|'sort_code'|'spei'|'zengin')` + * Change type of `CustomerCreateFundingInstructionsBankTransferTypeParams`, `OrderPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferTypeParams`, `OrderPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferType`, `PaymentIntentConfirmPaymentMethodOptionsCustomerBalanceBankTransferTypeParams`, `PaymentIntentNextActionDisplayBankTransferInstructionsType`, `PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferTypeParams`, and `PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferType` from `literal('jp_bank_transfer')` to `enum('eu_bank_transfer'|'gb_bank_transfer'|'jp_bank_transfer'|'mx_bank_transfer')` + * Add support for `Iban`, `SortCode`, and `Spei` on `FundingInstructionsBankTransferFinancialAddresses` and `PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddresses` + * Add support for new values `bacs`, `fps`, and `spei` on enums `FundingInstructionsBankTransferFinancialAddressesSupportedNetworks` and `PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressesSupportedNetworks` + * Add support for new values `sort_code` and `spei` on enums `FundingInstructionsBankTransferFinancialAddressesType` and `PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressesType` + * Change type of `OrderPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypesParams`, `OrderPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypes`, `PaymentIntentConfirmPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypesParams`, `PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypesParams`, and `PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypes` from `literal('zengin')` to `enum` + * Add support for `CustomUnitAmount` on `PriceParams` and `Price` + +## 72.113.0 - 2022-06-08 +* [#1472](https://github.com/stripe/stripe-go/pull/1472) API Updates + * Add support for `Affirm`, `Bancontact`, `Card`, `Ideal`, `P24`, and `Sofort` on `CheckoutSessionPaymentMethodOptionsParams` and `CheckoutSessionPaymentMethodOptions` + * Add support for `AUBECSDebit`, `AfterpayClearpay`, `BACSDebit`, `EPS`, `FPX`, `Giropay`, `Grabpay`, `Klarna`, `PayNow`, and `SepaDebit` on `CheckoutSessionPaymentMethodOptionsParams` + * Add support for `SetupFutureUsage` on `CheckoutSessionPaymentMethodOptionsAcssDebitParams`, `CheckoutSessionPaymentMethodOptionsAcssDebit`, `CheckoutSessionPaymentMethodOptionsAfterpayClearpay`, `CheckoutSessionPaymentMethodOptionsAlipayParams`, `CheckoutSessionPaymentMethodOptionsAlipay`, `CheckoutSessionPaymentMethodOptionsAuBecsDebit`, `CheckoutSessionPaymentMethodOptionsBacsDebit`, `CheckoutSessionPaymentMethodOptionsBoletoParams`, `CheckoutSessionPaymentMethodOptionsBoleto`, `CheckoutSessionPaymentMethodOptionsEps`, `CheckoutSessionPaymentMethodOptionsFpx`, `CheckoutSessionPaymentMethodOptionsGiropay`, `CheckoutSessionPaymentMethodOptionsGrabpay`, `CheckoutSessionPaymentMethodOptionsKlarna`, `CheckoutSessionPaymentMethodOptionsKonbiniParams`, `CheckoutSessionPaymentMethodOptionsKonbini`, `CheckoutSessionPaymentMethodOptionsOxxoParams`, `CheckoutSessionPaymentMethodOptionsOxxo`, `CheckoutSessionPaymentMethodOptionsPaynow`, `CheckoutSessionPaymentMethodOptionsSepaDebit`, `CheckoutSessionPaymentMethodOptionsUsBankAccountParams`, `CheckoutSessionPaymentMethodOptionsUsBankAccount`, and `CheckoutSessionPaymentMethodOptionsWechatPayParams` + * Add support for `AttachToSelf` on `SetupAttempt`, `SetupIntentListParams`, and `SetupIntentParams` + * Add support for `FlowDirections` on `SetupAttempt` and `SetupIntentParams` +* [#1469](https://github.com/stripe/stripe-go/pull/1469) Add test for cash balance methods. + +## 72.112.0 - 2022-06-01 +* [#1471](https://github.com/stripe/stripe-go/pull/1471) API Updates + * Add support for `RadarOptions` on `ChargeParams`, `Charge`, `PaymentIntentConfirmParams`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentMethodParams`, `PaymentMethod`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `AccountHolderName`, `AccountNumber`, `AccountType`, `BankCode`, `BankName`, `BranchCode`, and `BranchName` on `FundingInstructionsBankTransferFinancialAddressesZengin` and `PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressesZengin` + * Change type of `OrderPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferType` and `PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferType` from `enum` to `literal('jp_bank_transfer')` + * Add support for `Network` on `SetupIntentPaymentMethodOptionsCard` + * Add support for new value `simulated_wisepos_e` on enum `TerminalReaderDeviceType` + +## 72.111.0 - 2022-05-26 +* [#1466](https://github.com/stripe/stripe-go/pull/1466) API Updates + * Add support for `AffirmPayments` and `LinkPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `IDNumberSecondary` on `AccountIndividualParams`, `PersonParams`, `TokenAccountIndividualParams`, and `TokenPersonParams` + * Add support for `HostedInstructionsURL` on `PaymentIntentNextActionDisplayBankTransferInstructions` + * Add support for `IDNumberSecondaryProvided` on `Person` + * Add support for `CardIssuing` on `TreasuryFinancialAccountFeaturesParams` and `TreasuryFinancialAccountUpdateFeaturesParams` + + +## 72.110.0 - 2022-05-23 +* [#1465](https://github.com/stripe/stripe-go/pull/1465) API Updates + * Add support for `Treasury` on `AccountCapabilitiesParams` and `AccountCapabilities` + +## 72.109.0 - 2022-05-23 +* [#1464](https://github.com/stripe/stripe-go/pull/1464) API Updates + * Add support for new resource `Apps.Secret` + * Add support for `Affirm` on `ChargePaymentMethodDetails`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupIntentConfirmPaymentMethodDataParams`, and `SetupIntentPaymentMethodDataParams` + * Add support for `Link` on `ChargePaymentMethodDetails`, `MandatePaymentMethodDetails`, `OrderPaymentSettingsPaymentMethodOptionsParams`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SetupAttemptPaymentMethodDetails`, `SetupIntentConfirmPaymentMethodDataParams`, `SetupIntentConfirmPaymentMethodOptionsParams`, `SetupIntentPaymentMethodDataParams`, `SetupIntentPaymentMethodOptionsParams`, and `SetupIntentPaymentMethodOptions` + * Add support for new value `link` on enums `InvoicePaymentSettingsPaymentMethodTypes` and `SubscriptionPaymentSettingsPaymentMethodTypes` + * Add support for new values `affirm` and `link` on enum `PaymentMethodType` + +## 72.108.0 - 2022-05-19 +* [#1463](https://github.com/stripe/stripe-go/pull/1463) API Updates + * Add support for new resources `Treasury.CreditReversal`, `Treasury.DebitReversal`, `Treasury.FinancialAccountFeatures`, `Treasury.FinancialAccount`, `Treasury.FlowDetails`, `Treasury.InboundTransfer`, `Treasury.OutboundPayment`, `Treasury.OutboundTransfer`, `Treasury.ReceivedCredit`, `Treasury.ReceivedDebit`, `Treasury.TransactionEntry`, and `Treasury.Transaction` + * Add support for `RetrievePaymentMethod` method on resource `Customer` + * Add support for `ListOwners` and `List` methods on resource `FinancialConnections.Account` + * Change type of `BillingPortalSessionReturnUrl` from `string` to `nullable(string)` + * Add support for `AUBECSDebit`, `AfterpayClearpay`, `BACSDebit`, `EPS`, `FPX`, `Giropay`, `Grabpay`, `Klarna`, `PayNow`, and `SepaDebit` on `CheckoutSessionPaymentMethodOptions` + * Add support for `Treasury` on `IssuingAuthorization`, `IssuingDisputeParams`, `IssuingDispute`, and `IssuingTransaction` + * Add support for `FinancialAccount` on `IssuingCardParams` and `IssuingCard` + * Add support for `ClientSecret` on `Order` + * Add support for `Networks` on `PaymentIntentConfirmPaymentMethodOptionsUsBankAccountParams`, `PaymentIntentPaymentMethodOptionsUsBankAccountParams`, `PaymentMethodUsBankAccount`, `SetupIntentConfirmPaymentMethodOptionsUsBankAccountParams`, and `SetupIntentPaymentMethodOptionsUsBankAccountParams` + * Add support for `AttachToSelf` and `FlowDirections` on `SetupIntent` + * Add support for `SaveDefaultPaymentMethod` on `SubscriptionPaymentSettingsParams` and `SubscriptionPaymentSettings` + * Add support for `CZK` on `TerminalConfigurationTippingParams` and `TerminalConfigurationTipping` +* [#1461](https://github.com/stripe/stripe-go/pull/1461) API Updates + * Add support for `Description` on `CheckoutSessionSubscriptionDataParams`, `SubscriptionParams`, and `Subscription` + * Add support for `ConsentCollection`, `PaymentIntentData`, `ShippingOptions`, `SubmitType`, and `TaxIDCollection` on `PaymentLinkParams` and `PaymentLink` + * Add support for `CustomerCreation` on `PaymentLinkParams` and `PaymentLink` + * Add support for `Metadata` on `SubscriptionSchedulePhasesParams` and `SubscriptionSchedulePhases` + +* [#1462](https://github.com/stripe/stripe-go/pull/1462) update build status label and remove outdated code coverage label + +## 72.107.0 - 2022-05-11 +* [#1459](https://github.com/stripe/stripe-go/pull/1459) API Updates + * Add support for `AmountDiscount`, `AmountTax`, and `Product` on `LineItem` + + +## 72.106.0 - 2022-05-05 +* [#1457](https://github.com/stripe/stripe-go/pull/1457) API Updates + * Add support for `DefaultPriceData` on `ProductParams` + * Add support for `DefaultPrice` on `ProductParams` and `Product` + * Add support for `InstructionsEmail` on `RefundParams` and `Refund` + + +## 72.105.0 - 2022-05-05 +* [#1455](https://github.com/stripe/stripe-go/pull/1455) API Updates + * Add support for new resources `FinancialConnections.AccountOwner`, `FinancialConnections.AccountOwnership`, `FinancialConnections.Account`, and `FinancialConnections.Session` + * Add support for `FinancialConnections` on `CheckoutSessionPaymentMethodOptionsUsBankAccountParams`, `CheckoutSessionPaymentMethodOptionsUsBankAccount`, `InvoicePaymentSettingsPaymentMethodOptionsUsBankAccountParams`, `InvoicePaymentSettingsPaymentMethodOptionsUsBankAccount`, `PaymentIntentConfirmPaymentMethodOptionsUsBankAccountParams`, `PaymentIntentPaymentMethodOptionsUsBankAccountParams`, `PaymentIntentPaymentMethodOptionsUsBankAccount`, `SetupIntentConfirmPaymentMethodOptionsUsBankAccountParams`, `SetupIntentPaymentMethodOptionsUsBankAccountParams`, `SetupIntentPaymentMethodOptionsUsBankAccount`, `SubscriptionPaymentSettingsPaymentMethodOptionsUsBankAccountParams`, and `SubscriptionPaymentSettingsPaymentMethodOptionsUsBankAccount` + * Add support for `FinancialConnectionsAccount` on `PaymentIntentConfirmPaymentMethodDataUsBankAccountParams`, `PaymentIntentPaymentMethodDataUsBankAccountParams`, `PaymentMethodUsBankAccountParams`, `PaymentMethodUsBankAccount`, `SetupIntentConfirmPaymentMethodDataUsBankAccountParams`, and `SetupIntentPaymentMethodDataUsBankAccountParams` + +* [#1454](https://github.com/stripe/stripe-go/pull/1454) API Updates + * Add support for `RegisteredAddress` on `AccountIndividualParams`, `PersonParams`, `Person`, `TokenAccountIndividualParams`, and `TokenPersonParams` + * Add support for `PaymentMethodData` on `SetupIntentConfirmParams` and `SetupIntentParams` + + +## 72.104.0 - 2022-05-03 +* [#1453](https://github.com/stripe/stripe-go/pull/1453) API Updates + * Add support for new resource `CashBalance` + * Change type of `BillingPortalConfigurationApplication` from `$Application` to `deletable($Application)` + * Add support for `Alipay` on `CheckoutSessionPaymentMethodOptionsParams` and `CheckoutSessionPaymentMethodOptions` + * Add support for new value `eu_oss_vat` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, and `TaxIdType` + * Add support for `CashBalance` on `Customer` + * Add support for `Application` on `Invoice`, `Quote`, `SubscriptionSchedule`, and `Subscription` + + +## 72.103.0 - 2022-04-21 +* [#1452](https://github.com/stripe/stripe-go/pull/1452) API Updates + * Add support for `Expire` test helper method on resource `Refund` + +## 72.102.0 - 2022-04-19 +* [#1451](https://github.com/stripe/stripe-go/pull/1451) API Updates + * Add support for new resources `FundingInstructions` and `Terminal.Configuration` + * Add support for `CreateFundingInstructions` method on resource `Customer` + * Add support for `CustomerBalance` on `ChargePaymentMethodDetails`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, and `PaymentMethod` + * Add support for `CashBalance` on `CustomerParams` + * Add support for `AmountDetails` on `PaymentIntent` + * Add support for `DisplayBankTransferInstructions` on `PaymentIntentNextAction` + * Add support for new value `customer_balance` on enum `PaymentMethodType` + * Add support for `ConfigurationOverrides` on `TerminalLocationParams` and `TerminalLocation` + +* [#1448](https://github.com/stripe/stripe-go/pull/1448) API Updates + * Add support for `IncrementAuthorization` method on resource `PaymentIntent` + * Add support for `IncrementalAuthorizationSupported` on `ChargePaymentMethodDetailsCardPresent` + * Add support for `RequestIncrementalAuthorizationSupport` on `PaymentIntentConfirmPaymentMethodOptionsCardPresentParams`, `PaymentIntentPaymentMethodOptionsCardPresentParams`, and `PaymentIntentPaymentMethodOptionsCardPresent` + +## 72.101.0 - 2022-04-08 +* [#1446](https://github.com/stripe/stripe-go/pull/1446) API Updates + * Add support for `ApplyCustomerBalance` method on resource `PaymentIntent` + +## 72.100.0 - 2022-04-04 +* [#1443](https://github.com/stripe/stripe-go/pull/1443) Add support for passing expansions in SearchParams. + +## 72.99.0 - 2022-04-01 +* [#1442](https://github.com/stripe/stripe-go/pull/1442) API Updates + * Add support for `BankTransferPayments` on `AccountCapabilitiesParams` and `AccountCapabilities` + * Add support for `CaptureBefore` on `ChargePaymentMethodDetailsCardPresent` + * Add support for `Address` and `Name` on `CheckoutSessionCustomerDetails` + * Add support for `CustomerBalance` on `InvoicePaymentSettingsPaymentMethodOptionsParams`, `InvoicePaymentSettingsPaymentMethodOptions`, `SubscriptionPaymentSettingsPaymentMethodOptionsParams`, and `SubscriptionPaymentSettingsPaymentMethodOptions` + * Add support for new value `customer_balance` on enums `InvoicePaymentSettingsPaymentMethodTypes` and `SubscriptionPaymentSettingsPaymentMethodTypes` + * Add support for `RequestExtendedAuthorization` on `PaymentIntentConfirmPaymentMethodOptionsCardPresentParams`, `PaymentIntentPaymentMethodOptionsCardPresentParams`, and `PaymentIntentPaymentMethodOptionsCardPresent` + +## 72.98.0 - 2022-03-30 +* [#1440](https://github.com/stripe/stripe-go/pull/1440) API Updates + * Add support for `CancelAction`, `ProcessPaymentIntent`, `ProcessSetupIntent`, and `SetReaderDisplay` methods on resource `Terminal.Reader` + * Add support for `Action` on `TerminalReader` + +## 72.97.0 - 2022-03-29 +* [#1439](https://github.com/stripe/stripe-go/pull/1439) API Updates + * Add support for Search API + * Add support for `Search` method on resources `Charge`, `Customer`, `Invoice`, `PaymentIntent`, `Price`, `Product`, and `Subscription` + +## 72.96.0 - 2022-03-25 +* [#1437](https://github.com/stripe/stripe-go/pull/1437) API Updates + * Add support for PayNow and US Bank Accounts Debits payments + * **Charge** ([API ref](https://stripe.com/docs/api/charges/object#charge_object-payment_method_details)) + * Add support for `PayNow` and `USBankAccount` on `ChargePaymentMethodDetails` + * **Mandate** ([API ref](https://stripe.com/docs/api/mandates/object#mandate_object-payment_method_details)) + * Add support for `USBankAccount` on `MandatePaymentMethodDetails` + * **Payment Intent** ([API ref](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-payment_method_options)) + * Add support for `PayNow` and `USBankAccount` on `PaymentIntentPaymentMethodOptions`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentConfirmPaymentMethodDataParams`, and `PaymentIntentConfirmPaymentMethodOptionsParams` + * Add support for `PayNowDisplayQRCode` on `PaymentIntentNextAction` + * **Setup Intent** ([API ref](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-payment_method_options)) + * Add support for `USBankAccount` on `SetupIntentPaymentMethodOptionsParams`, `SetupIntentPaymentMethodOptions`, and `SetupIntentConfirmPaymentMethodOptionsParams` + * **Setup Attempt** ([API ref](https://stripe.com/docs/api/setup_attempts/object#setup_attempt_object-payment_method_details)) + * Add support for `USBankAccount` on `SetupAttemptPaymentMethodDetails` + * **Payment Method** ([API ref](https://stripe.com/docs/api/payment_methods/object#payment_method_object-paynow)) + * Add support for `PayNow` and `USBankAccount` on `PaymentMethod` and `PaymentMethodParams` + * Add support for new values `paynow` and `us_bank_account` on enum `PaymentMethodType` + * **Checkout Session** ([API ref](https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-payment_method_types)) + * Add support for `USBankAccount` on `CheckoutSessionPaymentMethodOptionsParams` and `CheckoutSessionPaymentMethodOptions` + * **Invoice** ([API ref](https://stripe.com/docs/api/invoices/object#invoice_object-payment_settings-payment_method_types)) + * Add support for `USBankAccount` on `InvoicePaymentSettingsPaymentMethodOptions` and `InvoicePaymentSettingsPaymentMethodOptionsParams` + * Add support for new values `paynow` and `us_bank_account` on enum `InvoicePaymentSettingsPaymentMethodTypes` + * **Subscription** ([API ref](https://stripe.com/docs/api/subscriptions/object#subscription_object-payment_settings-payment_method_types)) + * Add support for `USBankAccount` on `SubscriptionPaymentSettingsPaymentMethodOptions` and `SubscriptionPaymentSettingsPaymentMethodOptionsParams` + * Add support for new values `paynow` and `us_bank_account` on enum `SubscriptionPaymentSettingsPaymentMethodTypes` + * **Account capabilities** ([API ref](https://stripe.com/docs/api/accounts/object#account_object-capabilities)) + * Add support for `PayNowPayments` and `USBankAccountAchPayments` on `AccountCapabilities` and `AccountCapabilitiesParams` + * Add support for `FailureBalanceTransaction` on `Charge` + * Add support for `TestClock` on `SubscriptionListParams` + * Add support for `CaptureMethod` on `PaymentIntentConfirmPaymentMethodOptionsAfterpayClearpayParams`, `PaymentIntentConfirmPaymentMethodOptionsCardParams`, `PaymentIntentConfirmPaymentMethodOptionsKlarnaParams`, `PaymentIntentPaymentMethodOptionsAfterpayClearpayParams`, `PaymentIntentPaymentMethodOptionsAfterpayClearpay`, `PaymentIntentPaymentMethodOptionsCardParams`, `PaymentIntentPaymentMethodOptionsCard`, `PaymentIntentPaymentMethodOptionsKlarnaParams`, `PaymentIntentPaymentMethodOptionsKlarna`, and `PaymentIntentTypeSpecificPaymentMethodOptionsClient` + * Add additional support for verify microdeposits on Payment Intent and Setup Intent ([API ref](https://stripe.com/docs/api/payment_intents/verify_microdeposits)) + * Add support for `DescriptorCode` on `PaymentIntentVerifyMicrodepositsParams` and `SetupIntentVerifyMicrodepositsParams` + * Add support for `MicrodepositType` on `PaymentIntentNextActionVerifyWithMicrodeposits` and `SetupIntentNextActionVerifyWithMicrodeposits` + * Add case for `ConnectCollectionTransfer` on `BalanceTransactionSource` `UnmarshalJSON` (fixes #1392) + * Add missing `PayoutFailureCode`s (fixes #1438) + +## 72.95.0 - 2022-03-23 +* [#1436](https://github.com/stripe/stripe-go/pull/1436) API Updates + * Add support for `Cancel` method on resource `Refund` + * Add support for new values `bg_uic`, `hu_tin`, and `si_tin` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, and `TaxIdType` + * Add support for `TestClock` on `QuoteListParams` + +## 72.94.0 - 2022-03-18 +* [#1433](https://github.com/stripe/stripe-go/pull/1433) API Updates + * Add support for `Status` on `Card` +* [#1432](https://github.com/stripe/stripe-go/pull/1432) Add StringSlice example to readme +* [#1324](https://github.com/stripe/stripe-go/pull/1324) Add support for SearchResult objects + +## 72.93.0 - 2022-03-11 +* [#1431](https://github.com/stripe/stripe-go/pull/1431) API Updates + * Add support for `Mandate` on `ChargePaymentMethodDetailsCard` + * Add support for `MandateOptions` on `SetupIntentPaymentMethodOptionsCardParams`, `PaymentIntentPaymentMethodOptionsCardParams`, `PaymentIntentConfirmPaymentMethodOptionsCardParams`, `PaymentIntentPaymentMethodOptionsCard`, SetupIntentConfirmPaymentMethodOptionsCardParams`, and `SetupIntentPaymentMethodOptionsCard` + * Add support for `CardAwaitNotification` on `PaymentIntentNextAction` + * Add support for `CustomerNotification` on `PaymentIntentProcessingCard` + +## 72.92.0 - 2022-03-09 +* [#1430](https://github.com/stripe/stripe-go/pull/1430) API Updates + * Add support for `TestClock` on `CustomerListParams` +* [#1429](https://github.com/stripe/stripe-go/pull/1429) Fix unmarshalling error on schedule create from subscription (ApplicationFeePercent) + +## 72.91.0 - 2022-03-02 +* [#1425](https://github.com/stripe/stripe-go/pull/1425) API Updates + * Add support for new resources `InvoiceLineProrationDetails` and `InvoiceLineProrationDetailsCreditedItems` + * Add support for `ProrationDetails` on `InvoiceLine` + + +## 72.90.0 - 2022-03-01 +* [#1423](https://github.com/stripe/stripe-go/pull/1423) [#1424](https://github.com/stripe/stripe-go/pull/1424) API Updates + * Add support for new resource `TestHelpers.TestClock` + * Add support for `TestClock` on `CustomerParams`, `Customer`, `Invoice`, `InvoiceItem`, `QuoteParams`, `Quote`, `Subscription`, and `SubscriptionSchedule` + * Add support for `PendingInvoiceItemsBehavior` on `InvoiceParams` + * Change type of `ProductUrlParams` from `string` to `emptyStringable(string)` + * Add support for `NextAction` on `Refund` + +## 72.89.0 - 2022-02-25 +* [#1422](https://github.com/stripe/stripe-go/pull/1422) API Updates + * Add support for `KonbiniPayments` on `AccountCapabilitiesParams`, and `AccountCapabilities` + `BillingPortalConfigurationBusinessProfileTermsOfServiceUrl` from `string` to `nullable(string)` + * Add support for `Konbini` on `ChargePaymentMethodDetails`, `CheckoutSessionPaymentMethodOptionsParams`, `CheckoutSessionPaymentMethodOptions`, `InvoicePaymentSettingsPaymentMethodOptionsParams`, `InvoicePaymentSettingsPaymentMethodOptionsParams`, `InvoicePaymentSettingsPaymentMethodOptions`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentConfirmPaymentMethodDataParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, `PaymentMethod`, `SubscriptionPaymentSettingsPaymentMethodOptionsParams`, and `SubscriptionPaymentSettingsPaymentMethodOptions` + * Add support for new value `konbini` on enums `InvoicePaymentSettingsPaymentMethodTypes` and `SubscriptionPaymentSettingsPaymentMethodTypes` + * Add support for `KonbiniDisplayDetails` on `PaymentIntentNextAction` + * Add support for new value `konbini` on enum `PaymentMethodType` +* [#1420](https://github.com/stripe/stripe-go/pull/1420) Generate enums in samples + +## 72.88.0 - 2022-02-23 +* [#1421](https://github.com/stripe/stripe-go/pull/1421) API Updates + * Add support for `SetupFutureUsage` on `PaymentIntentPaymentMethodOptions.*` + * Add support for new values `bbpos_wisepad3` and `stripe_m2` on enum `TerminalReaderDeviceType` + +## 72.87.0 - 2022-02-15 +* [#1419](https://github.com/stripe/stripe-go/pull/1419) Add tests for verify_microdeposits +* [#1416](https://github.com/stripe/stripe-go/pull/1416) API Updates + * Add support for `VerifyMicrodeposits` method on resources `PaymentIntent` and `SetupIntent` + * Add support for new value `grabpay` on enums `InvoicePaymentSettingsPaymentMethodTypes` and `SubscriptionPaymentSettingsPaymentMethodTypes` +* [#1415](https://github.com/stripe/stripe-go/pull/1415) API Updates + * Add support for `PIN` on `IssuingCardParams` +* [#1414](https://github.com/stripe/stripe-go/pull/1414) Add comments for deprecated error types + +## 72.86.0 - 2022-01-25 +* [#1411](https://github.com/stripe/stripe-go/pull/1411) API Updates + * Add support for `PhoneNumberCollection` on `PaymentLinkParams` and `PaymentLink` + * Add support for new value `is_vat` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, and `TaxIdType` +* [#1384](https://github.com/stripe/stripe-go/pull/1384) godoc is no more + +## 72.85.0 - 2022-01-20 +* [#1408](https://github.com/stripe/stripe-go/pull/1408) API Updates + * Add support for new resource `PaymentLink` + * Add support for `PaymentLink` on `CheckoutSession` + +## 72.84.0 - 2022-01-19 +* [#1407](https://github.com/stripe/stripe-go/pull/1407) API Updates + * Change type of `ChargeStatus` from `string` to `enum('failed'|'pending'|'succeeded')` + * Add support for `BACSDebit` and `EPS` on `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, and `PaymentIntentPaymentMethodOptions` + * Add support for `ImageURLPNG` and `ImageURLSVG` on `PaymentIntentNextActionWechatPayDisplayQRCode` + +* [#1405](https://github.com/stripe/stripe-go/pull/1405) Generate struct field docstrings + +## 72.83.0 - 2022-01-13 +* [#1404](https://github.com/stripe/stripe-go/pull/1404) API Updates + * Add support for `PaidOutOfBand` on `Invoice` + +## 72.82.0 - 2022-01-12 +* [#1403](https://github.com/stripe/stripe-go/pull/1403) API Updates + * Add support for `CustomerCreation` on `CheckoutSessionParams` and `CheckoutSession` + * Add support for `FPX` and `Grabpay` on `PaymentIntentPaymentMethodOptionsParams` and `PaymentIntentPaymentMethodOptions` + +* [#1399](https://github.com/stripe/stripe-go/pull/1399) API Updates + * Add support for `MandateOptions` on `SubscriptionPaymentSettingsPaymentMethodOptionsCardParams`, `SubscriptionPaymentSettingsPaymentMethodOptionsCardParams`, and `SubscriptionPaymentSettingsPaymentMethodOptionsCard` +* [#1401](https://github.com/stripe/stripe-go/pull/1401) Make source.go and client codegen-able + * Add support for `object` on `Source` (value is the string "source") + * Add support for `client_secret` on `SourceObjectParams` + * Add support for `parent` on `SourceSourceOrderItems` +* [#1400](https://github.com/stripe/stripe-go/pull/1400) Make paymentsource.go and client codegen-able + * Add support for `account_holder_name`, `account_holder_type`, `address_city`, `address_country`, `address_line1`, `address_line2`, `address_state`, `address_zip`, `exp_month`, `exp_year`, `name`, `owner` on `CustomerSourceParams` + * Add support for `PaymentSourceOwnerParams` + * Add support for `Object` on `SourceListParams` +* [#1396](https://github.com/stripe/stripe-go/pull/1396) Make bankaccount and card codegen-able + * Add support for `address_city`, `address_country`, `address_line1`, `address_line2`, `address_state`, `address_zip`, `exp_month`, `exp_year`, and `name` on `BankAccountParams` + * Add support for `account_holder_name`, `account_holder_type`, and `owner` on `CardParams` + * Add support for `account` on `Card` +* [#1398](https://github.com/stripe/stripe-go/pull/1398) Update docs URLs. + +## 72.81.0 - 2021-12-22 +* [#1397](https://github.com/stripe/stripe-go/pull/1397) API Updates + * Add support for `AUBECSDebit` on `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, and `PaymentIntentPaymentMethodOptions` + * Change type of `PaymentIntentProcessingType` from `string` to `literal('card')`. This is not considered a breaking change as the field was added in the same release. + +* [#1395](https://github.com/stripe/stripe-go/pull/1395) API Updates + * Add support for `Boleto` on `SetupAttemptPaymentMethodDetails` + +* [#1393](https://github.com/stripe/stripe-go/pull/1393) API Updates + * Add support for `Processing` on `PaymentIntent` + +## 72.80.0 - 2021-12-15 +* [#1391](https://github.com/stripe/stripe-go/pull/1391) API Updates + * Add support for new resource `PaymentIntentTypeSpecificPaymentMethodOptionsClient` + * Add support for `SetupFutureUsage` on `PaymentIntentPaymentMethodOptionsCardParams`, `PaymentIntentPaymentMethodOptionsCardParams`, `PaymentIntentConfirmPaymentMethodOptionsCardParams`, and `PaymentIntentPaymentMethodOptionsCard` + +## 72.79.0 - 2021-12-09 +* [#1390](https://github.com/stripe/stripe-go/pull/1390) API Updates + * Add support for `Metadata` on `BillingPortalConfiguration` +* [#1382](https://github.com/stripe/stripe-go/pull/1382) Add unwrap capability to Error +* [#1388](https://github.com/stripe/stripe-go/pull/1388) Codegen: `sourcetransaction.go` and `sourcetransaction/client.go` + * Add support for `Object` and `Status` on `SourceTransaction`. + +## 72.78.0 - 2021-12-09 +* [#1389](https://github.com/stripe/stripe-go/pull/1389) API Updates + * Add support for new values `ge_vat` and `ua_vat` on enums `CheckoutSessionCustomerDetailsTaxIdsType`, `InvoiceCustomerTaxIdsType`, and `TaxIdType` + +* [#1383](https://github.com/stripe/stripe-go/pull/1383) [#1379](https://github.com/stripe/stripe-go/pull/1379) [#1385](https://github.com/stripe/stripe-go/pull/1385) [#1386](https://github.com/stripe/stripe-go/pull/1386) Codegen-related updates + * Add support for `CancellationReason` and `ReceivedAt` on `IssuingDisputeEvidenceServiceNotAsDescribed` and `IssuingDisputeEvidenceServiceNotAsDescribedParams` + * Add support for `Created` on `IssuingDisputeListParams` + * Add support for `Object` on `Plan` + * Add support for `free_zone_establishment`, `free_zone_llc`, `llc`, and `sole_establishment` options for `AccountCompanyStructure` + * Add support for `AfterpayClearpayPayments` on `AccountCapabilitiesParams` + * Add support for `Created` and `CreatedRange` on `AccountListParams` + * Add support for `AfterpayClearpayPayments` and `BoletoPayments` on `AccountCapabilities` + * Add support for `Capability` and `Capabilities` method on Account client + * Add support for `none` and `renew` options for `SubscriptionScheduleEndBehavior` + * Add support for `"now"` string for `EndDate`, `StartDate`, and `TrialEnd` on `SubscriptionSchedulePhaseParams` + * Add support for `ProrationBehavior` on `SubscriptionSchedulePhase` + * Add support for `APIVersion` and `Object` on `Event` + * Add support for `Metadata` on `SubscriptionItemsParams` + * Add support for `'automatic_pending_invoice_item_invoice'` option for `InvoiceBillingReason` + * Add support for `'deleted'` option for `InvoiceStatus` + * Add support for `metadata` on `InvoiceUpcomingCustomerDetailsParams` + * Add support for `schedule` on `InvoiceParams` + * Add support for `created` on `Person` + +## 72.77.0 - 2021-11-19 +* [#1381](https://github.com/stripe/stripe-go/pull/1381) Add support for `Wallets` on `IssuingCard` + * Add support for `Wallets` on `IssuingCard` +* [#1380](https://github.com/stripe/stripe-go/pull/1380) API Updates + * Add support for `InteracPresent` on `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, and `PaymentIntentPaymentMethodOptions` + * Add support for new value `jct` on enum `TaxRateTaxType` + +## 72.76.0 - 2021-11-17 +* [#1377](https://github.com/stripe/stripe-go/pull/1377) API Updates + * Add support for `AutomaticPaymentMethods` on `PaymentIntentParams` and `PaymentIntent` + +## 72.75.0 - 2021-11-16 +* [#1375](https://github.com/stripe/stripe-go/pull/1375) API Updates + * Add support for new resource `ShippingRate` + * Add support for `ShippingOptions` on `CheckoutSessionParams` and `CheckoutSession` + * Add support for `ShippingRate` on `CheckoutSession` + +## 72.74.0 - 2021-11-11 +* [#1374](https://github.com/stripe/stripe-go/pull/1374) API Updates + * Add support for `Expire` method on resource `Checkout.Session` + * Add support for `Status` on `CheckoutSession` +* [#1373](https://github.com/stripe/stripe-go/pull/1373) [#1370](https://github.com/stripe/stripe-go/pull/1370) [#1369](https://github.com/stripe/stripe-go/pull/1369) Codegen-related updates + - Add support for `disabled` on `CapabilityStatus` +* Make more files codegen-able + - Add support for `acss_debit`, `au_becs_debit`, `bacs_debit`, and `sepa_debit` on `SetupAttemptPaymentMethodDetails` + - Add support for `setup_intent` on `SetupAttempt` + - Add support for `duplicate` option for `SetupIntentCancellationReason` + - Add support for `challenge_only` option for `SetupIntentPaymentMethodOptionsCardRequestThreeDSecure` + - Add support for `sepa_debit` on `SetupIntentPaymentMethodOptionsParams` and `SetupIntentPaymentMethodOptions` + - Add support for `client_secret` on `SetupIntentParams` + +## 72.73.1 - 2021-11-04 +* [#1371](https://github.com/stripe/stripe-go/pull/1371) API Updates + * Remove support for `OwnershipDeclarationShownAndSigned` on `TokenAccountParams`. This API was unused. + * Add support for `OwnershipDeclarationShownAndSigned` on `TokenAccountCompanyParams` + + +## 72.73.0 - 2021-11-01 +* [#1368](https://github.com/stripe/stripe-go/pull/1368) API Updates + * Add support for `OwnershipDeclaration` on `AccountCompanyParams`, `AccountCompanyParams`, `AccountCompany`, and `TokenAccountCompanyParams` + * Add support for `ProofOfRegistration` on `AccountDocumentsParams` and `AccountDocumentsParams` + * Add support for `OwnershipDeclarationShownAndSigned` on `TokenAccountParams` +* [#1366](https://github.com/stripe/stripe-go/pull/1366) Make File resource and client codegen-able + - Add support for `"selfie"` and `"identity_document_downloadable"` as `FilePurpose` options + - Add support for `title` field on `File` +* [#1365](https://github.com/stripe/stripe-go/pull/1365) Make paymentintent and paymentmethod codegen-able + * Fix `WechatPay` form name in `PaymentIntentPaymentMethodDataParams` + * Add support for `"challenge_only"` as `PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure` option + * Add support for `OffSessionOneOff` and `OffSessionRecurring` on `PaymentIntentConfirmParams` + * Add support for `BACSDebit`, `Bancontact`, `Giropay`, `InteracPresent`, `Metadata`, and `Sofort` on `PaymentIntentPaymentMethodDataParams` + * Add support for `CardPresent`, `Ideal`, `P24`, and `SepaDebit` on `PaymentIntentPaymentMethodOptionsParams` and `PaymentIntentPaymentMethodOptions` + * Add support for `ClientSecret`, `OffSessionOneOff`, and `OffSessionRecurring` on `PaymentIntentParams` + * Add support for `Object` on `PaymentIntent` + * Add support for `AmexExpressCheckout`, `ApplePay`, `GooglePay`, `Masterpass`, `SamsungPay`, and `VisaCheckout` on `PaymentMethodCardWallet` +* [#1364](https://github.com/stripe/stripe-go/pull/1364) Update references in test suite to be fully qualified. + +## 72.72.0 - 2021-10-20 +* [#1361](https://github.com/stripe/stripe-go/pull/1361) Bugfix: point client.API#Oauth to the Connect backend. +* [#1358](https://github.com/stripe/stripe-go/pull/1358) API Updates + * Add support for `BuyerID` on `ChargePaymentMethodDetailsAlipay` + +## 72.71.0 - 2021-10-15 +* [#1357](https://github.com/stripe/stripe-go/pull/1357) API Updates + * Change type of `UsageRecordTimestampParams` from `integer` to `literal('now') | integer` +* [#1356](https://github.com/stripe/stripe-go/pull/1356) Add generated test suite +* [#1355](https://github.com/stripe/stripe-go/pull/1355) Make order-related files codegen-able + * Add support for `SelectedShippingMethod` and `Status` on `OrderStatus` + * Add support for `Carrier` and `TrackingNumber` on `ShippingParams` + * Add support for `ExternalCouponCode` and `Object` on `Order` + * Add support for `Object` on `OrderItem` and `OrderReturn` + * Add support for `Deleted` and `Object` on `SKU` + +## 72.70.0 - 2021-10-11 +* [#1354](https://github.com/stripe/stripe-go/pull/1354) API Updates + * Add support for `PaymentMethodCategory` and `PreferredLocale` on `ChargePaymentMethodDetailsKlarna` + * Add support for `Klarna` on `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, and `PaymentMethod` + * Add support for new value `klarna` on enum `PaymentMethodType` + +## 72.69.0 - 2021-10-11 +* [#1352](https://github.com/stripe/stripe-go/pull/1352) API Updates + * Add support for `ListPaymentMethods` method on resource `Customer` +* [#1331](https://github.com/stripe/stripe-go/pull/1331) Add missing decline codes following official documentation. + +## 72.68.0 - 2021-10-07 +* [#1351](https://github.com/stripe/stripe-go/pull/1351) API Updates + * Add support for `PhoneNumberCollection` on `CheckoutSessionParams` and `CheckoutSession` + * Add support for `Phone` on `CheckoutSessionCustomerDetails` + * Add support for new value `customer_id` on enum `RadarValueListItemType` + * Add support for new value `bbpos_wisepos_e` on enum `TerminalReaderDeviceType` +* [#1350](https://github.com/stripe/stripe-go/pull/1350) [#1349](https://github.com/stripe/stripe-go/pull/1349) [#1347](https://github.com/stripe/stripe-go/pull/1347) [#1346](https://github.com/stripe/stripe-go/pull/1346) Codegen-related changes + * Add support for `Object` to `Token` + * Add support for `Object` on `Reversal` + +## 72.67.0 - 2021-09-29 +* [#1345](https://github.com/stripe/stripe-go/pull/1345) API Updates + * Add support for `KlarnaPayments` on `AccountCapabilitiesParams`, `AccountCapabilitiesParams`, and `AccountCapabilities` + +## 72.66.0 - 2021-09-28 +* [#1344](https://github.com/stripe/stripe-go/pull/1344) API Updates + * Add support for `AmountAuthorized` and `OvercaptureSupported` on `ChargePaymentMethodDetailsCardPresent` + +## 72.65.0 - 2021-09-16 +* [#1342](https://github.com/stripe/stripe-go/pull/1342) API Updates + * Add support for `Livemode` on `ReportingReportType`. + * Add support for `DefaultFor` on `CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsParams`, `CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptions`, `MandatePaymentMethodDetailsACSSDebit`, `SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsParams`, and `SetupIntentPaymentMethodOptionsACSSDebitMandateOptions`. + * Add support for `ACSSDebit` on `InvoicePaymentSettingsPaymentMethodOptionsParams`, `InvoicePaymentSettingsPaymentMethodOptionsParams`, `InvoicePaymentSettingsPaymentMethodOptions`, `SubscriptionPaymentSettingsPaymentMethodOptionsParams`, `SubscriptionPaymentSettingsPaymentMethodOptionsParams`, and `SubscriptionPaymentSettingsPaymentMethodOptions`. + * Add support for new value `acss_debit` on enums `InvoicePaymentSettingsPaymentMethodType` and `SubscriptionPaymentSettingsPaymentMethodType`. + * Add support for `FullNameAliases` on `PersonParams` and `Person`. +* [#1339](https://github.com/stripe/stripe-go/pull/1339) API Updates + * Add support for new value `rst` on enum `TaxRateTaxType` +* [#1336](https://github.com/stripe/stripe-go/pull/1336) Adding missing dispute reasons following official documentation (http… +* [#1337](https://github.com/stripe/stripe-go/pull/1337) Generated go test suites + +## 72.64.1 - 2021-09-03 +* [#1335](https://github.com/stripe/stripe-go/pull/1335) Bugfix: prop `form` annotation for `WechatPay` on `PaymentIntentPaymentMethodOptions` + +## 72.64.0 - 2021-09-01 +* [#1334](https://github.com/stripe/stripe-go/pull/1334) API Updates + * Add support for `FutureRequirements` on `Account`, `Capability`, and `Person` + * Add support for `Alternatives` on `AccountRequirements`, `CapabilityRequirements`, and `PersonRequirements` + +## 72.63.0 - 2021-09-01 +* [#1332](https://github.com/stripe/stripe-go/pull/1332) API Updates + * Add support for `AfterExpiration`, `ConsentCollection`, and `ExpiresAt` on `CheckoutSessionParams` and `CheckoutSession` + * Add support for `Consent` and `RecoveredFrom` on `CheckoutSession` + + +## 72.62.0 - 2021-08-27 +* [#1329](https://github.com/stripe/stripe-go/pull/1329) API Updates + * Add support for `CancellationReason` on `BillingPortalConfigurationFeaturesSubscriptionCancelParams`, `BillingPortalConfigurationFeaturesSubscriptionCancelParams`, and `BillingPortalConfigurationFeaturesSubscriptionCancel` + +## 72.61.0 - 2021-08-19 +* [#1328](https://github.com/stripe/stripe-go/pull/1328) API Updates + * Add support for new TaxId type: `au_arn` + * Add support for `InteracPresent` on `ChargePaymentMethodDetails` + * Add support for `SepaCreditTransfer` on `ChargePaymentMethodDetails` + * Codegen related changes: + * Moved `ShippingDetails` into `address.go` + * Add support for `Object` and `Order` to `Charge` + * Renamed `ReviewReasonType` enum to `ReviewReason` but added a type alias to preserve backwards compatibility +* [#1323](https://github.com/stripe/stripe-go/pull/1323) codegen: api.go + +## 72.60.0 - 2021-08-11 +* [#1325](https://github.com/stripe/stripe-go/pull/1325) API Updates + * Add support for `locale` on ` BillingPortalSessionParams` and ` BillingPortalSession` +* [#1317](https://github.com/stripe/stripe-go/pull/1317) codegen: charge, taxrate + * Add support for `ApplicationFee` on (Charge) `CaptureParams` + * Add support for `PreferredLanguage` on `ChargePaymentMethodDetailsSofort` + * Bugfix: correctly deserialize `amount` on `ChargeTransferData` + +## 72.59.0 - 2021-07-28 +* [#1322](https://github.com/stripe/stripe-go/pull/1322) API Updates + * Add support for `AccountType` on `BankAccount`, `BankAccountParams`, and `CardParams`. + * Add support for `CategoryCode` on `IssuingAuthorizationMerchantData`. + * Add const definition for value `redacted` on enum `ReviewClosedReason`. + +## 72.58.0 - 2021-07-22 +* [#1319](https://github.com/stripe/stripe-go/pull/1319) API Updates + * Add support for `payment_settings` on `Subscription` and `SubscriptionParams`. +* [#1320](https://github.com/stripe/stripe-go/pull/1320) Stop using uploads.stripe.com for the files backend. +* [#1318](https://github.com/stripe/stripe-go/pull/1318) API Updates + * Add support for `Wallet` on `IssuingTransaction` + * Add support for `Ideal` on `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentConfirmPaymentMethodOptionsParams`, and `PaymentIntentPaymentMethodOptions` +* [#1315](https://github.com/stripe/stripe-go/pull/1315) Explicit iter property + +## 72.57.0 - 2021-07-14 +* [#1314](https://github.com/stripe/stripe-go/pull/1314) API Updates + * Add support for `ListComputedUpfrontLineItems` method on resource `Quote` +* [#1312](https://github.com/stripe/stripe-go/pull/1312) codegen: 14 more files + * Add support for `BillingAddressCollection` to `CheckoutSession` + * Add support for `NetworkReasonCode` to `DisputeReason` + * Add support for `Object` to `EphemeralKey`, `ApplicationFee`, and `DisputeReason` + * Add support for `Description` to `Refund` + * Add const definition for value `blocked` on enum `IssuingCardholderStatus` + * Bugfix: add support for `Rate` on `CheckoutSessionTotalDetailsBreakdownTax` -- the existing field `TaxRate` has the wrong json annotation and should be deprecated. + +## 72.56.0 - 2021-07-09 +* [#1310](https://github.com/stripe/stripe-go/pull/1310) [#1283](https://github.com/stripe/stripe-go/pull/1283) API Updates + * Add support for new resource `Quote` + * Add support for `Quote` on `Invoice` + * Add support for new value `quote_accept` on enum `InvoiceBillingReason` +* [#1309](https://github.com/stripe/stripe-go/pull/1309) Fix deserialization of Error on Sigma ScheduledQueryRun (warning: this might be a minor breaking change if you attempted to reference this broken field) + +## 72.55.0 - 2021-06-30 +* [#1306](https://github.com/stripe/stripe-go/pull/1306) API Updates + * Add support for `boleto` on `InvoicePaymentSettingsPaymentMethodType`. + +## 72.54.0 - 2021-06-30 +* [#1304](https://github.com/stripe/stripe-go/pull/1304) Add support for Wechat Pay + * Add support for `WechatPay` on `ChargePaymentMethodDetails`, `CheckoutSessionPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodDataParams`, `PaymentIntentPaymentMethodOptionsParams`, `PaymentIntentPaymentMethodOptions`, `PaymentMethodParams`, and `PaymentMethod` + * Add support for new value `wechat_pay` on enums `InvoicePaymentSettingsPaymentMethodType` and `PaymentMethodType` + * Add support for `WechatPayDisplayQRCode`, `WechatPayRedirectToAndroidApp`, and `WechatPayRedirectToIOSApp` on `PaymentIntentNextAction` + +## 72.53.0 - 2021-06-29 +* [#1303](https://github.com/stripe/stripe-go/pull/1303) API Updates + * Add support for `Boleto` and `OXXO` on `CheckoutSessionPaymentMethodOptionsParams` and `CheckoutSessionPaymentMethodOptions` + * Add support for `BoletoPayments` on `AccountCapabilities` + +## 72.52.0 - 2021-06-25 +* [#1301](https://github.com/stripe/stripe-go/pull/1301) API Updates + * Add support for `boleto` as a `PaymentMethodType` + * Add support for `Boleto` on `ChargePaymentMethodDetails`, `PaymentMethod`, `PaymentMethodParams`, `PaymentIntentPaymentMethodOptions`, `PaymentIntentPaymentMethodDataParams`, and `PaymentIntentPaymentMethodOptionsParams` + * Add support for `BoletoDisplayDetails` on `PaymentIntentNextAction` + * Add support for `il_vat` on enums `CheckoutSessionCustomerDetailsTaxIDsType` and `TaxIDType` +* [#1299](https://github.com/stripe/stripe-go/pull/1299) API Updates + * Add support for new TaxId types: `ca_pst_mb`, `ca_pst_bc`, `ca_gst_hst`, and `ca_pst_sk`. + +## 72.51.0 - 2021-06-16 +* [#1298](https://github.com/stripe/stripe-go/pull/1298) API Updates + * Add checkout.Session.URL + +## 72.50.0 - 2021-06-07 +* [#1295](https://github.com/stripe/stripe-go/pull/1295) Add Secret to EphemeralKey as it now should be accessed directly +* [#1297](https://github.com/stripe/stripe-go/pull/1297) API Updates + * Add support for `TaxIDCollection` to `CheckoutSession` and `CheckoutSessionParams`. + +## 72.49.0 - 2021-06-04 +* [#1292](https://github.com/stripe/stripe-go/pull/1292) API Updates + * Add support for `Controller` to `Account` +* [#1287](https://github.com/stripe/stripe-go/pull/1287) [#1293](https://github.com/stripe/stripe-go/pull/1293) [#1290](https://github.com/stripe/stripe-go/pull/1290) codegen: 4 files + * Add missing enum members to `BalanceTransactionType`, `BalanceTransactionSourceType` + * Add support for `FeeRefund` and `Topup` to `BalanceTransactionSource` + * Add support for `Object` on `BalanceTransaction` and `Transfer` + * Removed a redundant form-encoding conversion for `UpTo` in `PriceTierParams.AppendTo` method + + +## 72.48.0 - 2021-06-04 +* [#1291](https://github.com/stripe/stripe-go/pull/1291) API Updates + * Add new resource `TaxCode`. + * Add support for `AutomaticTax` on `CheckoutSession`, `Invoice`, `Subscription`, and `SubscriptionScheduleDefaultSettings`. + * Add support for `CustomerUpdate` on `CheckoutSessionCustomerUpdateParams` + * Add support for `Tax` on `Customer` and `CustomerParams` + * Add support for `CustomerDetails` on `InvoiceParams` + * Add support for `TaxBehavior` on `Price`, `PriceParams`, `CheckoutSessionLineItemPriceDataParams`, `PriceParams`, `SubscriptionItemPriceDataParams`, `SubscriptionSchedulePhaseAutomaticTaxParams`,`SubscriptionSchedulePhaseAddInvoiceItemPriceDataParams`, and `InvoiceItemPriceDataParams` + * Add support for `TaxCode` on `CheckoutSessionLineItemPriceDataProductParams`, `Product`, `ProductParams`, `PlanProductParams` and `PriceProductDataParams` + +## 72.47.0 - 2021-05-26 +* [#1286](https://github.com/stripe/stripe-go/pull/1286) API Updates + * Added support for `Documents` to `PersonParams` + +## 72.46.0 - 2021-05-25 +* [#1285](https://github.com/stripe/stripe-go/pull/1285) API Updates + * Add support for Identity VerificationSession and VerificationReport APIs + +## 72.45.0 - 2021-05-06 +* [#1280](https://github.com/stripe/stripe-go/pull/1280) API Updates + * Added support for `reference` on `Charge.payment_method_details.afterpay_clearpay` + * Added support for `afterpay_clearpay` on `PaymentIntent.payment_method_options`. +* [#1279](https://github.com/stripe/stripe-go/pull/1279) API Updates + * Add support for `payment_intent` on `RadarEarlyFraudWarning` and `RadarEarlyFraudWarningListParams`. + +## 72.44.0 - 2021-05-05 +* [#1278](https://github.com/stripe/stripe-go/pull/1278) API updates + * Add support for `dhl` and `royal_mail` as enum members of `IssuingCardShippingCarrier`. + * Add support for `single_member_llc` as an enum member of `AccountCompanyStructure`. + +## 72.43.0 - 2021-04-19 +* [#1277](https://github.com/stripe/stripe-go/pull/1277), [#1276](https://github.com/stripe/stripe-go/pull/1276) Codegen-related changes + * Add missing `Object` field to several structs. + * Set `path` in `usagerecordsummary.List` only once, not once per iteration. + +## 72.42.0 - 2021-04-13 +* [#1275](https://github.com/stripe/stripe-go/pull/1275) Add support for ACSS debit payment method + * Add support for `acss_debit` as value for `PaymentMethodType`. + * Add support for `ACSSDebit` on `PaymentMethod`, `PaymentMethodParams`, `PaymentIntentPaymentMethodOptions`, `PaymentIntentPaymentMethodOptionsParams`, `MandatePaymentMethodDetails`, `SetupIntentPaymentMethodOptions`, and `SetupIntentPaymentOptionsParams`. + * Add support for `ACSSDebitPayments` on `AccountCapabilities` + * Add support for `PaymentMethodOptions` on `CheckoutSession` + * Add support for `verify_with_microdeposits` and `use_stripe_sdk` on `PaymentIntentNextAction` and `SetupIntentNextAction` + +## 72.41.1 - 2021-04-07 +* [#1274](https://github.com/stripe/stripe-go/pull/1274) Fix names of `SubscriptionScheduleStatus` constants (warning: this might be a minor breaking change if you'd been referencing a bad name) + +## 72.41.0 - 2021-04-02 +* [#1273](https://github.com/stripe/stripe-go/pull/1273) API Updates + * Add support for `SubscriptionPause` on `BillingPortalConfigurationFeatures` and `BillingPortalConfigurationFeaturesParams` +* [#1271](https://github.com/stripe/stripe-go/pull/1271) codegen: add several client.go files +* [#1269](https://github.com/stripe/stripe-go/pull/1269) codegen: 13 more files + * Add missing `Object` property to several structs + * Add support for `ExpiresAtNow` to `FileLinkParams` + * Add support for `SubscriptionItem` to `InvoiceItem` + * Add enum definitions for `TerminalReader.DeviceType` + * Add enum definitions for `Topup.status` + * Add support for `Amount`, `AmountRange`, and `Status` to `TopupListParams` + * Added custom `UnmarshalJSON` method for `Topup` +* [#1272](https://github.com/stripe/stripe-go/pull/1272) API Updates + * Add support for `TransferData` on `CheckoutSessionSubscriptionDataParams` + +## 72.40.0 - 2021-03-26 +* [#1270](https://github.com/stripe/stripe-go/pull/1270) add card_issuing.tos_acceptance to account.go + * Add support for `AccountSettingsParams.CardIssuing.TOSAcceptance` + * Add support for `AccountSettingsCardPayments.CardIssuing.TOSAcceptance` + +## 72.39.0 - 2021-03-22 +* [#1268](https://github.com/stripe/stripe-go/pull/1268) API Updates + * Add support for `ShippingRates` on `CheckoutSessionParams` + * Add support for `AmountShipping`on `CheckoutSessionTotalDetails` + +## 72.38.0 - 2021-03-16 +* [#1264](https://github.com/stripe/stripe-go/pull/1264), [#1261](https://github.com/stripe/stripe-go/pull/1261) Codegen-related changes + * Introduce missing `Object` and `Deleted` properties to many structs + * Add two missing members to `CustomerBalanceTransactionType` enum + * Add `DomainName` to `ApplePayDomainListParams` +* [#1250](https://github.com/stripe/stripe-go/pull/1250) Support `SubscriptionTrialEndNow` on the Retrieve Upcoming Invoice API + +## 72.37.0 - 2021-03-01 +* [#1257](https://github.com/stripe/stripe-go/pull/1257) Adds ErrorType idempotency_error + +## 72.36.0 - 2021-03-01 +* [#1259](https://github.com/stripe/stripe-go/pull/1259) Add configuration API to billingportal_session.go +* [#1253](https://github.com/stripe/stripe-go/pull/1253) Fix `LineItemTax` to deserialize `Rate` properly + +## 72.35.0 - 2021-02-24 +* [#1254](https://github.com/stripe/stripe-go/pull/1254) Add support for the billing portal configuration API + +## 72.34.0 - 2021-02-18 +* [#1252](https://github.com/stripe/stripe-go/pull/1252) API Updates + * Add support for `afterpay_clearpay` on `PaymentMethod`, `PaymentMethodParams`, `PaymentIntentPaymentMethodDataParams`, and `ChargePaymentMethodDetails` + * Add `afterpay_clearpay` as an enum member on `PaymentMethodType` + * Add support for `adjustable_quantity` on `CheckoutSessionLineItemParams` + * Add support for `on_behalf_of` on `InvoiceParams` and `Invoice` +* [#1249](https://github.com/stripe/stripe-go/pull/1249) Fix edge case panic in ParseID + +## 72.33.0 - 2021-02-09 +* [#1247](https://github.com/stripe/stripe-go/pull/1247) Added support for `payment_settings` to `Invoice` + +## 72.32.0 - 2021-02-03 +* [#1245](https://github.com/stripe/stripe-go/pull/1245) API Updates + * Add `nationality` to `Person` and `PersonParams` + - (TokenParams includes PersonParams, so this also allows it to be specified on token.Create) + * Add `gb_vat` as a member of `TaxIDType` and `CheckoutSessionCustomerDetailsTaxIDsType` +* [#1246](https://github.com/stripe/stripe-go/pull/1246) Add SubscriptionStartDate to InvoiceParams (to use with GetNext) +* [#1243](https://github.com/stripe/stripe-go/pull/1243) Added missing decline code 'invalid_expiry_month' + +## 72.31.0 - 2021-01-25 +* [#1228](https://github.com/stripe/stripe-go/pull/1228) Redact client_secret from logs + +## 72.30.0 - 2021-01-15 +* [#1241](https://github.com/stripe/stripe-go/pull/1241) Multiple API Changes + * Added support for `dynamic_tax_rates` on `CheckoutSessionParams.line_items` + * Added support for `customer_details` on `CheckoutSession` + * Added support for `type` on `IssuingTransactionListParams` + * Added support for `country` and `state` on `TaxRateParams` and `TaxRate` + +## 72.29.0 - 2021-01-11 +* [#1236](https://github.com/stripe/stripe-go/pull/1236) Add support for bank on eps/p24 +* [#1239](https://github.com/stripe/stripe-go/pull/1239) Add support for more verification documents in `Documents` on `Account`. + +## 72.28.0 - 2020-12-03 +* [#1234](https://github.com/stripe/stripe-go/pull/1234) Add support for `BankAccountOwnershipVerification` in `Documents` on `Account` + +## 72.27.0 - 2020-11-24 +* [#1230](https://github.com/stripe/stripe-go/pull/1230) Add support for `AccountTaxIDs` on `Invoice` + +## 72.26.0 - 2020-11-20 +* [#1227](https://github.com/stripe/stripe-go/pull/1227) Add support for Account and Person `Token` creation + +## 72.25.0 - 2020-11-20 +* [#1229](https://github.com/stripe/stripe-go/pull/1229) Add support for `GrabpayPayments` as a capability on `Account` + +## 72.24.0 - 2020-11-18 +* [#1224](https://github.com/stripe/stripe-go/pull/1224) Add support for GrabPay as a PaymentMethod +* [#1225](https://github.com/stripe/stripe-go/pull/1225) Fix bad comments to make the linter happy + +## 72.23.0 - 2020-11-09 +* [#1222](https://github.com/stripe/stripe-go/pull/1222) Add `LastFinalizationError` to `Invoice` and `PaymentMethodType` to `Error` +* [#1223](https://github.com/stripe/stripe-go/pull/1223) Properly deserialize `IssuingDispute` on `BalanceTransaction` + +## 72.22.0 - 2020-11-04 +* [#1221](https://github.com/stripe/stripe-go/pull/1221) Add support for `RegistrationNumber` in `Company` on `Account` + +## 72.21.0 - 2020-10-27 +* [#1220](https://github.com/stripe/stripe-go/pull/1220) Add `PreferredLocales` on `Charge` for payments made via Interac Present transactions + +## 72.20.0 - 2020-10-26 +* [#1218](https://github.com/stripe/stripe-go/pull/1218) Multiple API changes + * Add support for passing `CvcToken` in `PaymentIntentPaymentMethodOptionsCardOptions ` on `PaymentIntent` + * Add support for creating a CVC Token on `Token`. + +## 72.19.0 - 2020-10-23 +* [#1217](https://github.com/stripe/stripe-go/pull/1217) Add support for passing `Bank` for P24 on `PaymentIntent` or `PaymentMethod` + +## 72.18.0 - 2020-10-22 +* [#1215](https://github.com/stripe/stripe-go/pull/1215) Add missing constants for existing types on `PaymentMethod` +* [#1216](https://github.com/stripe/stripe-go/pull/1216) Support passing `TaxRates` when creating invoice items through `Subscription` or `SubscriptionSchedule` +* [#1214](https://github.com/stripe/stripe-go/pull/1214) Put a `Deprecated` notice on `TotalCount` + +## 72.17.0 - 2020-10-20 +* [#1212](https://github.com/stripe/stripe-go/pull/1212) Add `TaxIDTypeJPRN` and `TaxIDTypeRUKPP` on `TaxId` + +## 72.16.0 - 2020-10-14 +* [#1210](https://github.com/stripe/stripe-go/pull/1210) Add support for `Discounts` to `CheckoutSessionParams` + +## 72.15.0 - 2020-10-14 +* [#1208](https://github.com/stripe/stripe-go/pull/1208) Add support for the Payout Reverse API + +## 72.14.0 - 2020-10-12 +* [#1207](https://github.com/stripe/stripe-go/pull/1207) Add support for `Description`, `IIN` and `Issuer` on `Charge` for `CardPresent` and `InteracPresent + +## 72.13.0 - 2020-10-11 +* [#1206](https://github.com/stripe/stripe-go/pull/1206) Add support for `Mandate` in `ChargePaymentMethodDetailsSepaDebit` + +## 72.12.1 - 2020-10-09 +* [#1203](https://github.com/stripe/stripe-go/pull/1203) Bugfix: Balance.InstantAvailable should be of type Amount + +## 72.12.0 - 2020-10-08 +* [#1199](https://github.com/stripe/stripe-go/pull/1199) Support sepa_debit for bancontact, ideal, sofort + +## 72.11.0 - 2020-10-06 +* [#1200](https://github.com/stripe/stripe-go/pull/1200) Handle randomness error when generating idempotency keys + +## 72.10.0 - 2020-10-02 +* [#1195](https://github.com/stripe/stripe-go/pull/1195) Add support for new payments capabilities on `Account` + +## 72.9.0 - 2020-09-29 +* [#1194](https://github.com/stripe/stripe-go/pull/1194) Add support for the `SetupAttempt` resource and List API + +## 72.8.0 - 2020-09-28 +* [#1192](https://github.com/stripe/stripe-go/pull/1192) Add support for OXXO Payments capability on `Account` + +## 72.7.0 - 2020-09-24 +* [#1190](https://github.com/stripe/stripe-go/pull/1190) Add support for BalanceTransactionTypeContribution` on `BalanceTransaction` +* [#1183](https://github.com/stripe/stripe-go/pull/1183) Add support for OXXO on `PaymentIntent` and `PaymentMethod` + +## 72.6.0 - 2020-09-23 +* [#1189](https://github.com/stripe/stripe-go/pull/1189) When not retrying a request, log reason at info level + +## 72.5.0 - 2020-09-23 +* [#1187](https://github.com/stripe/stripe-go/pull/1187) Don't retry requests on context cancellation + a few other errors +* [#1188](https://github.com/stripe/stripe-go/pull/1188) Add support for `InstantAvailable` on `Balance` + +## 72.4.0 - 2020-09-21 +* [#1185](https://github.com/stripe/stripe-go/pull/1185) Add support for `AmountCaptured` on `Charge` +* [#1186](https://github.com/stripe/stripe-go/pull/1186) Add support for `CheckoutSession` on `Discount` + +## 72.3.0 - 2020-09-14 +* [#1182](https://github.com/stripe/stripe-go/pull/1182) Add `Metadata` on `WebhookEndpoint` + +## 72.2.0 - 2020-09-08 +* [#1180](https://github.com/stripe/stripe-go/pull/1180) Add support for Sofort on `PaymentMethod` and `PaymentIntent` + +## 72.1.0 - 2020-09-02 +* [#1178](https://github.com/stripe/stripe-go/pull/1178) Fix the constant names for `BankAccountAvailablePayoutMethod` +* [#1177](https://github.com/stripe/stripe-go/pull/1177) Add support for `AvailablePayoutMethods` on `BankAccount` +* [#1176](https://github.com/stripe/stripe-go/pull/1176) Add support for `PaymentStatus` on Checkout `Session` +* [#1174](https://github.com/stripe/stripe-go/pull/1174) Add support for the Issuing Dispute APIs + +## 72.0.0 - 2020-08-31 +* [#1170](https://github.com/stripe/stripe-go/pull/1170) Multiple API changes + * Move to latest API version `2020-08-27` + * Remove `Prorate` across Billing APIs in favor of `ProrationBehavior` + * Remove `TaxPercent` across Billing APIs in favor of `TaxRate`-related parameters and properties + * Remove `DisplayItems` on Checkout `Session` in favor of `LineItems` + * Remove `FailureURL` and `SuccessURL` on `AccountLink` in favor of `RefreshURL` and `ReturnURL` + * Remove `AccountLinkTypeCustomAccountUpdate ` and `AccountLinkTypeCustomAccountVerification ` on `AccountLink` in favor of `AccountLinkTypeAccountOnboarding ` and `AccountLinkTypeAccountUpdate ` + * Remove `Authenticated` and `Succeeded` on `ChargePaymentMethodDetailsCardThreeDSecure` + * Remove `Plan`, `Quantity`, `TaxPercent` and `TrialEnd` from `Customer` creation or update in favor of the Subscription API + * Rename `Plans` to `Items` on `SubscriptionSchedule` +* [#1171](https://github.com/stripe/stripe-go/pull/1171) Remove multiple deprecated APIs + * Remove support for the `Recipient` API + * Remove support for the `RecipientTransfer` API + * Remove support for the `BitcoinReceiver` API + * Remove support for the `ThreeDSecure` API which has been replaced by PaymentIntent and PaymentMethod + * Remove support for the `ExchangeRate` API which has never shipped publicly and is being reworked +* [#1172](https://github.com/stripe/stripe-go/pull/1172) Properly remove ThreeDSecure class entirely +* [#1173](https://github.com/stripe/stripe-go/pull/1173) Remove deprecated parameters `SavePaymentMethod` and `Source` on `PaymentIntent` + +## 71.48.0 - 2020-08-24 +* [#1153](https://github.com/stripe/stripe-go/pull/1153) Add support for `ServiceAgreement` in `AccountTOSAcceptance` on `Account` + +## 71.47.0 - 2020-08-19 +* [#1165](https://github.com/stripe/stripe-go/pull/1165) Add support for `ExpiresAt` on `File` + +## 71.46.0 - 2020-08-17 +* [#1163](https://github.com/stripe/stripe-go/pull/1163) Add support for `AmountDetails` on Issuing `Authorization` and `Transaction` + +## 71.45.0 - 2020-08-13 +* [#1160](https://github.com/stripe/stripe-go/pull/1160) Add support for `BankName` on `ChargePaymentMethodDetailsAcssDebit` +* [#1156](https://github.com/stripe/stripe-go/pull/1156) Re-enable HTTP/2 on the default HTTP client for Go 1.15+ + +## 71.44.0 - 2020-08-10 +* [#1148](https://github.com/stripe/stripe-go/pull/1148) Make original list object accessible on iterators + * This change is technically breaking in that an exported type, `stripe.Query`, changes from `type Query func(*Params, *form.Values) ([]interface{}, ListMeta, error)` to `type Query func(*Params, *form.Values) ([]interface{}, ListContainer, error)`. We've opted to ship this as a minor version anyway because although exported, `Query` is meant for internal use in other stripe-go packages and the vast majority of users are unlikely to be referencing it. If you are, please refer to the diff in https://github.com/stripe/stripe-go/pull/1148 for how to update callsites accordingly. If you think there is a major use of `Query` that we've likely overlooked, please open an issue. + +## 71.43.0 - 2020-08-07 +* [#1154](https://github.com/stripe/stripe-go/pull/1154) Add support for Alipay on `PaymentMethod` and `PaymentIntent` + +## 71.42.0 - 2020-08-05 +* [#1150](https://github.com/stripe/stripe-go/pull/1150) Add support for the PromotionCode resource and APIs + +## 71.41.0 - 2020-08-04 +* [#1152](https://github.com/stripe/stripe-go/pull/1152) Add support for `AccountType` in `ChargePaymentMethodDetailsCardPresentReceipt` + +## 71.40.0 - 2020-07-29 +* [#1136](https://github.com/stripe/stripe-go/pull/1136) Add support for multiple coupons on Billing APIs + * Add support for arrays of expandable API resources otherwise returning an array of strings by default + * Add custom deserialization to `Discount` to support expansion of the object + * Add support for `Id`, `Invoice` and `InvoiceItem` on `Discount`. + * Add support for `Discounts` on `Invoice`, `InvoiceItem` and `InvoiceLineItem` + * Add support for `DiscountAmounts` on `CreditNote`, `CreditNoteLineItem`, `InvoiceLineItem` + * Add support for `TotalDiscountAmounts` on `Invoice` + * Add `Object` to `Invoice`, `InvoiceLine`, `Discount` and `Coupon` + +## 71.39.0 - 2020-07-27 +* [#1142](https://github.com/stripe/stripe-go/pull/1142) Bug fix: Copy the JSON data of ephemeral keys to own buffer + +## 71.38.0 - 2020-07-27 +* [#1145](https://github.com/stripe/stripe-go/pull/1145) Fix `ApplicationFeePercent` on `SubscriptionSchedule` to support floats + +## 71.37.0 - 2020-07-25 +* [#1144](https://github.com/stripe/stripe-go/pull/1144) Add support for `FPXPayments` as a property on `AccountCapabilities` + +## 71.36.0 - 2020-07-24 +* [#1143](https://github.com/stripe/stripe-go/pull/1143) Add support for `FPXPayments` as a `Capability` on `Account` create and update + +## 71.35.0 - 2020-07-22 +* [#1140](https://github.com/stripe/stripe-go/pull/1140) Add support for `CartesBancairesPayments` as a `Capability` + +## 71.34.0 - 2020-07-20 +* [#1138](https://github.com/stripe/stripe-go/pull/1138) Add support for `Capabilities` on `Account` create and update + +## 71.33.0 - 2020-07-19 +* [#1137](https://github.com/stripe/stripe-go/pull/1137) Add support for `Title` on Sigma `ScheduledQueryRun` + +## 71.32.0 - 2020-07-17 +* [#1135](https://github.com/stripe/stripe-go/pull/1135) Add support for `PoliticalExposure` on `Person` + +## 71.31.0 - 2020-07-16 +* [#1133](https://github.com/stripe/stripe-go/pull/1133) Add support for `Deleted` on `LineItem` +* [#1134](https://github.com/stripe/stripe-go/pull/1134) Add support for new constants for `AccountLinkType` + +## 71.30.0 - 2020-07-15 +* [#1132](https://github.com/stripe/stripe-go/pull/1132) Add support for `AmountTotal`, `AmountSubtotal`, `Currency` and `TotalDetails` on Checkout `Session` + +## 71.29.0 - 2020-07-13 +* [#1131](https://github.com/stripe/stripe-go/pull/1131) Add `billing_cycle_anchor` to `default_settings` and `phases` for `SubscriptionSchedules` + +## 71.28.0 - 2020-06-23 +* [#1127](https://github.com/stripe/stripe-go/pull/1127) Add `FilePurposeDocumentProviderIdentityDocument` on `File` +* [#1126](https://github.com/stripe/stripe-go/pull/1126) Add support for `Discounts` on `LineItem` + +## 71.27.0 - 2020-06-18 +* [#1124](https://github.com/stripe/stripe-go/pull/1124) Add support for `RefreshURL` and `ReturnURL` on `AccountLink` + +## 71.26.0 - 2020-06-15 +* [#1090](https://github.com/stripe/stripe-go/pull/1090) Add support for `PaymentMethodData` on `PaymentIntent` + +## 71.25.1 - 2020-06-11 +* [#1123](https://github.com/stripe/stripe-go/pull/1123) Attach LastResponse after unmarshaling + +## 71.25.0 - 2020-06-11 +* [#1122](https://github.com/stripe/stripe-go/pull/1122) Add support for `Transaction` on Issuing `Dispute` +* [#1121](https://github.com/stripe/stripe-go/pull/1121) Add `Mandate`, `InstitutionNumber` and `TransitNumber` to `ChargePaymentMethodDetailsAcssDebit` + +## 71.24.0 - 2020-06-10 +* [#1120](https://github.com/stripe/stripe-go/pull/1120) Add support for Cartes Bancaires payments on `PaymentIntent` and `PaymentMethod` + +## 71.23.0 - 2020-06-09 +* [#1119](https://github.com/stripe/stripe-go/pull/1119) Add support for `TaxIDTypeIDNPWP` and `TaxIDTypeMYFRP` on `TaxId` + +## 71.22.0 - 2020-06-09 +* [#1118](https://github.com/stripe/stripe-go/pull/1118) Add missing information for BACS Debit in `PaymentMethod` + +## 71.21.0 - 2020-06-05 +* [#1117](https://github.com/stripe/stripe-go/pull/1117) Add `PaymentMethodIdealParams` to `PaymentMethodParams` + +## 71.20.0 - 2020-06-04 +* [#1116](https://github.com/stripe/stripe-go/pull/1116) Clean up the error deserialization and ensure `DeclineCode` is properly set. + +## 71.19.0 - 2020-06-03 +* [#1113](https://github.com/stripe/stripe-go/pull/1113) Add support for `TransferGroup` on Checkout `Session` + +## 71.18.0 - 2020-06-03 +* [#1110](https://github.com/stripe/stripe-go/pull/1110) Add support for reading SEPA and BACS debit settings on `Account` +* [#1111](https://github.com/stripe/stripe-go/pull/1111) Add support for Bancontact, EPS, Giropay and P24 on `PaymentMethod` +* [#1112](https://github.com/stripe/stripe-go/pull/1112) Add support for BACS Debit as a `Capability` on `Account` + +## 71.17.0 - 2020-05-29 +* [#1109](https://github.com/stripe/stripe-go/pull/1109) Add support for BACS Debit as a `PaymentMethod` + +## 71.16.0 - 2020-05-29 +* [#1108](https://github.com/stripe/stripe-go/pull/1108) Add `Metadata` and `Object` on `Topup` + +## 71.15.0 - 2020-05-28 +* [#1106](https://github.com/stripe/stripe-go/pull/1106) Add support for `ProductData` on `LineItems` for Checkout `Session` +* [#1105](https://github.com/stripe/stripe-go/pull/1105) Add `AuthenticationFlow` to `ChargePaymentMethodDetailsCardThreeDSecure` + +## 71.14.0 - 2020-05-22 +* [#1104](https://github.com/stripe/stripe-go/pull/1104) Add support for `TaxIDTypeAETRN`, `TaxIDTypeCLTIN` and `TaxIDTypeSAVAT` on `TaxId` +* [#1103](https://github.com/stripe/stripe-go/pull/1103) Add support for `Result` and `ResultReason` on `ChargePaymentMethodDetailsCardThreeDSecure` + +## 71.13.0 - 2020-05-20 +* [#1101](https://github.com/stripe/stripe-go/pull/1101) Multiple API Changes + * Add `BalanceTransactionTypeAnticipationRepayment` as a `Type` on `BalanceTransaction` + * Add `PaymentMethodTypeInteracPresent` as a `Type` on `PaymentMethod` + * Add `ChargePaymentMethodDetailsInteracPresent` on `Charge` + * Add `TransferData ` on `SubscriptionSchedule` + +## 71.12.0 - 2020-05-18 +* [#1099](https://github.com/stripe/stripe-go/pull/1099) Multiple API changes + * Add `issuing_dispute` as a `type` on `BalanceTransaction` + * Add `BalanceTransactions` as a a list of `BalanceTransaction` on Issuing `Dispute` + * Add `Fingerprint` and `TransactionId` in `ChargePaymentMethodDetailsAlipay` on `Charge` + * Add `Amount` in `InvoiceTransferData` and `InvoiceTransferDataParams` on `Invoice` + * Add `AmountPercent` in `SubscriptionTransferData` and `SubscriptionTransferDataParams` on `Subscription` + +## 71.11.1 - 2020-05-13 +* [#1097](https://github.com/stripe/stripe-go/pull/1097) Fixing `LineItems` to be `LineItemList` on Checkout `Session` + +## 71.11.0 - 2020-05-13 +* [#1096](https://github.com/stripe/stripe-go/pull/1096) Add support for `PurchaseDetails` on Issuing `Transaction` + +## 71.10.0 - 2020-05-12 +* [#1091](https://github.com/stripe/stripe-go/pull/1091) Add support for the `LineItem` resource and APIs + +## 71.9.0 - 2020-05-07 +* [#1093](https://github.com/stripe/stripe-go/pull/1093) Add support for `Metadata` for `PaymentIntentData` and `SubscriptionData` on Checkout `Session` +* [#1095](https://github.com/stripe/stripe-go/pull/1095) Add `SupportAddress` in `BusinessProfile` on `Account` creation and update +* [#1094](https://github.com/stripe/stripe-go/pull/1094) Fix parameters supported in `Recurring` for `PriceData` across the API + +## 71.8.0 - 2020-05-01 +* [#1089](https://github.com/stripe/stripe-go/pull/1089) Add support for `Issuing` in `Balance` + +## 71.7.0 - 2020-04-29 +* [#1087](https://github.com/stripe/stripe-go/pull/1087) Add support for Brazilian tax ids on `TaxID` +* [#1085](https://github.com/stripe/stripe-go/pull/1085) Add `Object` on `BankAccount` +* [#1065](https://github.com/stripe/stripe-go/pull/1065) Adding support for the `Price` resource and APIs + +## 71.6.0 - 2020-04-23 +* [#1083](https://github.com/stripe/stripe-go/pull/1083) Add support for `JCBPayments` and `CardIssuing` as a `Capability` +* [#1082](https://github.com/stripe/stripe-go/pull/1082) Add support for expandable `CVC` and `Number` on Issuing `Card` + +## 71.5.0 - 2020-04-22 +* [#1080](https://github.com/stripe/stripe-go/pull/1080) Remove spurious newline in logs + +## 71.4.0 - 2020-04-22 +* [#1079](https://github.com/stripe/stripe-go/pull/1079) Add support for `Coupon` when for subscriptions on Checkout + +## 71.3.0 - 2020-04-22 +* [#1078](https://github.com/stripe/stripe-go/pull/1078) Add missing error codes such as `ErrorCodeCardDeclinedRateLimitExceeded` +* [#1063](https://github.com/stripe/stripe-go/pull/1063) Add support for the `BillingPortal` namespace and the `Session` API and resource + +## 71.2.0 - 2020-04-21 +* [#1076](https://github.com/stripe/stripe-go/pull/1076) Add `Deleted` on `Invoice` + +## 71.1.0 - 2020-04-17 +* [#1074](https://github.com/stripe/stripe-go/pull/1074) Add `CardholderName` to `ChargePaymentMethodDetailsCardPresent` on `Charge` +* [#1075](https://github.com/stripe/stripe-go/pull/1075) Add new enum values for `AccountCompanyStructure` on `Account` + +## 71.0.0 - 2020-04-17 +Version 71 of stripe-go contains some major changes. Many of them are breaking, but only in minor ways. We've written [a migration guide](https://github.com/stripe/stripe-go/blob/master/v71_migration_guide.md) with more details to help with the upgrade. + +* [#1052](https://github.com/stripe/stripe-go/pull/1052) Remove all beta features from Issuing APIs +* [#1054](https://github.com/stripe/stripe-go/pull/1054) Make API response accessible on returned API structs +* [#1061](https://github.com/stripe/stripe-go/pull/1061) Start using Go Modules +* [#1068](https://github.com/stripe/stripe-go/pull/1068) Multiple breaking API changes + * `PaymentIntent` is now expandable on `Charge` + * `Percentage` was removed as a filter when listing `TaxRate` + * Removed `RenewalInterval` on `SubscriptionSchedule` + * Removed `Country` and `RoutingNumber` from `ChargePaymentMethodDetailsAcssDebit` +* [#1069](https://github.com/stripe/stripe-go/pull/1069) Default number of network retries to 2 +* [#1070](https://github.com/stripe/stripe-go/pull/1070) Clean up logging for next major + +## 70.15.0 - 2020-04-14 +* [#1066](https://github.com/stripe/stripe-go/pull/1066) Add support for `SecondaryColor` on `Account` + +## 70.14.0 - 2020-04-13 +* [#1062](https://github.com/stripe/stripe-go/pull/1062) Add `Description` on `WebhookEndpoint` + +## 70.13.0 - 2020-04-10 +* [#1060](https://github.com/stripe/stripe-go/pull/1060) Add support for `CancellationReason` on Issuing `Card` +* [#1058](https://github.com/stripe/stripe-go/pull/1058) Add support for `TaxIDTypeSGGST` on `TaxId` + +## 70.12.0 - 2020-04-09 +* [#1057](https://github.com/stripe/stripe-go/pull/1057) Add missing properties on `Review` + +## 70.11.0 - 2020-04-03 +* [#1056](https://github.com/stripe/stripe-go/pull/1056) Add `CalculatedStatementDescriptor` on `Charge` + +## 70.10.0 - 2020-03-30 +* [#1053](https://github.com/stripe/stripe-go/pull/1053) Add `AccountCapabilityCardIssuing` as a `Capability` + +## 70.9.0 - 2020-03-26 +* [#1050](https://github.com/stripe/stripe-go/pull/1050) Multiple API changes for Issuing + * Add support for `SpendingControls` on `Card` and `Cardholder` + * Add new values for `Reason` on `Authorization` + * Add new value for `Type` on `Cardholder` + * Add new value for `Service` on `Card` + * Mark many classes and other fields as deprecated for the next major + +## 70.8.0 - 2020-03-24 +* [#1049](https://github.com/stripe/stripe-go/pull/1049) Add support for `PauseCollection` on `Subscription` + +## 70.7.0 - 2020-03-23 +* [#1048](https://github.com/stripe/stripe-go/pull/1048) Add new capabilities for AU Becs Debit and tax reporting + +## 70.6.0 - 2020-03-20 +* [#1046](https://github.com/stripe/stripe-go/pull/1046) Add new fields to Issuing `Card` and `Authorization` + +## 70.5.0 - 2020-03-13 +* [#1044](https://github.com/stripe/stripe-go/pull/1044) Multiple changes for Issuing APIs + * Rename `Speed` to `Service` on Issuing `Card` + * Rename `WalletProvider` to `Wallet` and `AddressZipCheck` to `AddressPostalCodeCheck` on Issuing `Authorization` + * Mark `IsDefault` as deprecated on Issuing `Cardholder` + +## 70.4.0 - 2020-03-12 +* [#1043](https://github.com/stripe/stripe-go/pull/1043) Add support for `Shipping` and `ShippingAddressCollection` on Checkout `Session` + +## 70.3.0 - 2020-03-12 +* [#1042](https://github.com/stripe/stripe-go/pull/1042) Add support for `ThreeDSecure` on Issuing `Authorization` + +## 70.2.0 - 2020-03-04 +* [#1041](https://github.com/stripe/stripe-go/pull/1041) Add new reason values and `ExpiryCheck` for Issuing `authorization + +## 70.1.0 - 2020-03-04 +* [#1040](https://github.com/stripe/stripe-go/pull/1040) Add support for `Errors` in `Requirements` on `Account`, `Capability` and `Person` + +## 70.0.0 - 2020-03-03 +* [#1039](https://github.com/stripe/stripe-go/pull/1039) Multiple API changes: + * Move to latest API version `2020-03-02` + * Add support for `NextInvoiceSequence` on `Customer` + +## 69.4.0 - 2020-02-28 +* [#1038](https://github.com/stripe/stripe-go/pull/1038) Add `TaxIDTypeMYSST` for `TaxId` + +## 69.3.0 - 2020-02-24 +* [#1037](https://github.com/stripe/stripe-go/pull/1037) Add new enum values for `IssuingDisputeReason` + +## 69.2.0 - 2020-02-24 +* [#1036](https://github.com/stripe/stripe-go/pull/1036) Add support for listing Checkout `Session` and passing tax rate information + +## 69.1.0 - 2020-02-21 +* [#1035](https://github.com/stripe/stripe-go/pull/1035) Add support for `ProrationBehavior` on `SubscriptionSchedule` +* [#1034](https://github.com/stripe/stripe-go/pull/1034) Add support for `Timezone` on `ReportRun` + +## 69.0.0 - 2020-02-20 +* [#1033](https://github.com/stripe/stripe-go/pull/1033) Make `Subscription` expandable on `Invoice` + +## 68.20.0 - 2020-02-12 +* [#1029](https://github.com/stripe/stripe-go/pull/1029) Add support for `Amount` in `CheckoutSessionPaymentIntentDataTransferDataParams` + +## 68.19.0 - 2020-02-10 +* [#1027](https://github.com/stripe/stripe-go/pull/1027) Add new constants for `TaxIDType` +* [#1028](https://github.com/stripe/stripe-go/pull/1028) Add support for `StatementDescriptorSuffix` on Checkout `Session` + +## 68.18.0 - 2020-02-05 +* [#1026](https://github.com/stripe/stripe-go/pull/1026) Multiple changes on the `Balance` resource: + * Add support for `ConnectReserved` + * Add support for `SourceTypes` for a given type of balance. + * Add support for FPX balance as a constant. + +## 68.17.0 - 2020-02-03 +* [#1024](https://github.com/stripe/stripe-go/pull/1024) Add `FilePurposeAdditionalVerification` and `FilePurposeBusinessIcon` on `File` +* [#1018](https://github.com/stripe/stripe-go/pull/1018) Add support for `ErrorOnRequiresAction` on `PaymentIntent` + +## 68.16.0 - 2020-01-31 +* [#1023](https://github.com/stripe/stripe-go/pull/1023) Add support for `TaxIDTypeTHVAT` and `TaxIDTypeTWVAT` on `TaxId` + +## 68.15.0 - 2020-01-30 +* [#1022](https://github.com/stripe/stripe-go/pull/1022) Add support for `Structure` on `Account` + +## 68.14.0 - 2020-01-28 +* [#1021](https://github.com/stripe/stripe-go/pull/1021) Add support for `TaxIDTypeESCIF` on `TaxId` + +## 68.13.0 - 2020-01-24 +* [#1019](https://github.com/stripe/stripe-go/pull/1019) Add support for `Shipping.Speed` and `Shipping.TrackingURL` on `IssuingCard` + +## 68.12.0 - 2020-01-23 +* [#1017](https://github.com/stripe/stripe-go/pull/1017) Add new values for `TaxIDType` and fix `TaxIDTypeCHVAT` +* [#1015](https://github.com/stripe/stripe-go/pull/1015) Replace duplicate code in GetBackend method + +## 68.11.0 - 2020-01-17 +* [#1014](https://github.com/stripe/stripe-go/pull/1014) Add `Metadata` support on Checkout `Session` + +## 68.10.0 - 2020-01-15 +* [#1012](https://github.com/stripe/stripe-go/pull/1012) Adds `PendingUpdate` to `Subscription` + +## 68.9.0 - 2020-01-14 +* [#1013](https://github.com/stripe/stripe-go/pull/1013) Add support for `CreditNoteLineItem` + +## 68.8.0 - 2020-01-08 +* [#1011](https://github.com/stripe/stripe-go/pull/1011) Add support for `InvoiceItem` and fix `Livemode` on `InvoiceLine` + +## 68.7.0 - 2020-01-07 +* [#1008](https://github.com/stripe/stripe-go/pull/1008) Add `ReportingCategory` to `BalanceTransaction` + +## 68.6.0 - 2020-01-06 +* [#1009](https://github.com/stripe/stripe-go/pull/1009) Add constant for `TaxIDTypeSGUEN` on `TaxId` + +## 68.5.0 - 2020-01-03 +* [#1007](https://github.com/stripe/stripe-go/pull/1007) Add support for `SpendingLimitsCurrency` on Issuing `Card` and `Cardholder` + +## 68.4.0 - 2019-12-20 +* [#1006](https://github.com/stripe/stripe-go/pull/1006) Adds `ExecutivesProvided` to `Account` + +## 68.3.0 - 2019-12-19 +* [#1005](https://github.com/stripe/stripe-go/pull/1005) Add `Metadata` and `Livemode` to Terminal `Reader` and `Location' + +## 68.2.0 - 2019-12-09 +* [#1002](https://github.com/stripe/stripe-go/pull/1002) Add support for AU BECS Debit on PaymentMethod + +## 68.1.0 - 2019-12-04 +* [#1001](https://github.com/stripe/stripe-go/pull/1001) Add support for `Network` on `Charge` + +## 68.0.0 - 2019-12-03 +* [#1000](https://github.com/stripe/stripe-go/pull/1000) Multiple breaking changes: + * Pin to API version `2019-12-03` + * Rename `InvoiceBillingStatus` to `InvoiceStatus` for consistency + * Remove typo-ed field `OutOfBankdAmount` on `CreditNote` + * Remove deprecated `PaymentIntentPaymentMethodOptionsCardRequestThreeDSecureChallengeOnly` and `SetupIntentPaymentMethodOptionsCardRequestThreeDSecureChallengeOnly` from `PaymentIntent` and `SetupIntent`. + * Remove `OperatorAccount` on `TerminalLocationListParams` + +## 67.10.0 - 2019-12-02 +* [#999](https://github.com/stripe/stripe-go/pull/999) Add support for `Status` filter when listing `Invoice`s. + +## 67.9.0 - 2019-11-26 +* [#997](https://github.com/stripe/stripe-go/pull/997) Add new refund reason `RefundReasonExpiredUncapturedCharge` + +## 67.8.0 - 2019-11-26 +* [#998](https://github.com/stripe/stripe-go/pull/998) Add support for `CreditNote` preview + +## 67.7.0 - 2019-11-25 +* [#996](https://github.com/stripe/stripe-go/pull/996) Add support for `OutOfBandAmount` on `CreditNote` creation +* [#995](https://github.com/stripe/stripe-go/pull/995) Fix comment typos + +## 67.6.0 - 2019-11-22 +* [#994](https://github.com/stripe/stripe-go/pull/994) Support for the `now` on `StartDate` on Subscription Schedule creation + +## 67.5.0 - 2019-11-21 +* [#993](https://github.com/stripe/stripe-go/pull/993) Add `PaymentIntent` filter when listing `Dispute`s + +## 67.4.1 - 2019-11-19 +* [#991](https://github.com/stripe/stripe-go/pull/991) Add missing constant for PaymentMethod of type FPX + +## 67.4.0 - 2019-11-18 +* [#989](https://github.com/stripe/stripe-go/pull/989) Add support for `ViolatedAuthorizationControls` on Issuing `Authorization` + +## 67.3.0 - 2019-11-07 +* [#988](https://github.com/stripe/stripe-go/pull/988) Add `Company` and `Individual` to Issuing `Cardholder` + +## 67.2.0 - 2019-11-06 +* [#985](https://github.com/stripe/stripe-go/pull/985) Multiple API changes + * Add `Disputed` to `Charge` + * Add `PaymentIntent` to `Refund` and `Dispute` + * Add `Charge` to `DisputeListParams` + * Add `PaymentIntent` to `RefundListParams` and `RefundParams` + +## 67.1.0 - 2019-11-06 +* [#986](https://github.com/stripe/stripe-go/pull/986) Add support for iDEAL and SEPA debit on `PaymentMethod` + +## 67.0.0 - 2019-11-05 +* [#987](https://github.com/stripe/stripe-go/pull/987) Move to the latest API version and add new changes + * Move to API version `2019-11-05` + * Add `DefaultSettings` on `SubscritionSchedule` + * Remove `BillingThresholds`, `CollectionMethod`, `DefaultPaymentMethod` and `DefaultSource` and `invoice_settings` from `SubscriptionSchedule` + * `OffSession` on `PaymentIntent` is now always a boolean + +## 66.3.0 - 2019-11-04 +* [#984](https://github.com/stripe/stripe-go/pull/984) Add support for `UseStripeSDK` on `PaymentIntent` create and confirm + +## 66.2.0 - 2019-11-04 +* [#983](https://github.com/stripe/stripe-go/pull/983) Add support for cloning saved PaymentMethods +* [#980](https://github.com/stripe/stripe-go/pull/980) Improve docs for ephemeral keys + +## 66.1.1 - 2019-10-24 +* [#978](https://github.com/stripe/stripe-go/pull/978) Properly pass `Type` in `PaymentIntentPaymentMethodOptionsCardInstallmentsPlanParams` + * Note that this is technically a breaking change, however we've chosen to release it as a patch version as this shipped yesterday and is a new feature +* [#977](https://github.com/stripe/stripe-go/pull/977) Contributor Convenant + +## 66.1.0 - 2019-10-23 +* [#974](https://github.com/stripe/stripe-go/pull/974) Add support for installments on `PaymentIntent` and `Charge` +* [#975](https://github.com/stripe/stripe-go/pull/975) Add support for `PendingInvoiceItemInterval` on `Subscription` +* [#976](https://github.com/stripe/stripe-go/pull/976) Add `TaxIDTypeMXRFC` constant to `TaxIDType` + +## 66.0.0 - 2019-10-18 +* [#973](https://github.com/stripe/stripe-go/pull/973) Multiple breaking changes + * Pin to the latest API version `2019-10-17` + * Remove `RenewalBehavior` on `SubscriptionSchedule` + * Remove `RenewalBehavior` and `RenewalInterval` as parameters on `SubscriptionSchedule` + +## 65.2.0 - 2019-10-17 +* [#972](https://github.com/stripe/stripe-go/pull/972) Various API changes + * `Requirements` on Issuing `Cardholder` + * `PaymentMethodDetails.AuBecsDebit.Mandate` on `Charge` + * `PaymentBehavior` on `Subscription` creation can now take the value `pending_if_incomplete` + * `PaymentBehavior` on `SubscriptionItem` creation is now supported + * `SubscriptionData.TrialFromPlan` is now supported on Checkout `Session` creation + * New values for `TaxIDType` + +## 65.1.1 - 2019-10-11 +* [#970](https://github.com/stripe/stripe-go/pull/970) Properly deserialize `Fulfilled` on `StatusTransitions` in the `order` package + +## 65.1.0 - 2019-10-09 +* [#969](https://github.com/stripe/stripe-go/pull/969) Add `DeviceType` filter when listing Terminal `Reader`s + +## 65.0.0 - 2019-10-09 +* [#951](https://github.com/stripe/stripe-go/pull/951) Move to API version [`2019-10-08`](https://docs.stripe.com/changelog/2019-10-08) and other changes + * [#950](https://github.com/stripe/stripe-go/pull/950) Remove lossy "MarshalJSON" implementations + * [#962](https://github.com/stripe/stripe-go/pull/962) Removed deprecated properties and most todos + * Removed `GetBalanceTransaction` and `List` from the `balance` package. Prefer using `Get` and `List` in the `balancetransaction` package. + * Removed `ApplicationFee` from the `charge` and `paymentintent` packages. Prefer using `ApplicationFeeAmount`. + * Removed `TaxInfo` and related fields from the `customer` packager. Prefer using the `customertaxid` package. + * Removed unsupported `Customer` parameter on `PaymentMethodParams` and `PaymentMethodDetachParams` in the `paymentmethod` package. + * Removed `Billing` properties in the `invoice`, `sub` and `subschedule` packages. Prefer using `CollectionMethod`. + * Removed the `InvoiceBilling` type from the `invoice` package. Prefer using `InvoiceCollectionMethod`. + * Removed the `SubscriptionBilling` type from the `sub` package. Prefer using `SubscriptionCollectionMethod`. + * Removed deprecated constants for `PaymentIntentConfirmationMethod` in `paymentintent` package. + * Removed `OperatorAccount` from Terminal APIs. + * [#960](https://github.com/stripe/stripe-go/pull/960) Remove `issuerfraudrecord` package. Prefer using `earlyfraudwarning` + * [#968](https://github.com/stripe/stripe-go/pull/968) Rename `AccountOpener` to `Representative` and update to latest API version + +## 64.1.0 - 2019-10-09 +* [#967](https://github.com/stripe/stripe-go/pull/967) Add `Get` method to `OrderReturn` + +## 64.0.0 - 2019-10-08 +* ~[#968](https://github.com/stripe/stripe-go/pull/968) Update to latest API version [`2019-10-08`](https://docs.stripe.com/changelog/2019-10-08)~ + * **Note:** This release is actually a no-op as we failed to merge the changes. Please use 65.0.0 instead. + +## 63.5.0 - 2019-10-03 +* [#955](https://github.com/stripe/stripe-go/pull/955) Add FPX `PaymentMethod` Support +* [#966](https://github.com/stripe/stripe-go/pull/966) Add the `Account` field to `BankAccount` + +## 63.4.0 - 2019-09-30 +* [#952](https://github.com/stripe/stripe-go/pull/952) Add AU BECS Debit Support + +## 63.3.0 - 2019-09-30 +* [#964](https://github.com/stripe/stripe-go/pull/964) Add support for `Status` and `Location` filters when listing `Reader`s + +## 63.2.2 - 2019-09-26 +* [#963](https://github.com/stripe/stripe-go/pull/963) Update `SourceSourceOrder` `Items` field to fix unmarshalling errors + +## 63.2.1 - 2019-09-25 +* [#961](https://github.com/stripe/stripe-go/pull/961) Properly tag `Customer` as deprecated in `PaymentMethodDetachParams` + +## 63.2.0 - 2019-09-25 +* [#959](https://github.com/stripe/stripe-go/pull/959) Mark `Customer` on `PaymentMethodDetachParams` as deprecated +* [#957](https://github.com/stripe/stripe-go/pull/957) Add missing error code + +## 63.1.1 - 2019-09-23 +* [#954](https://github.com/stripe/stripe-go/pull/954) Add support for `Stripe-Should-Retry` header + +## 63.1.0 - 2019-09-13 +* [#949](https://github.com/stripe/stripe-go/pull/949) Add support for `DeclineCode` on `Error` top-level + +## 63.0.0 - 2019-09-10 +* [#947](https://github.com/stripe/stripe-go/pull/947) Bump API version to [`2019-09-09`](https://docs.stripe.com/changelog/2019-09-09) + +## 62.10.0 - 2019-09-09 +* [#945](https://github.com/stripe/stripe-go/pull/945) Changes to `Account` and `Person` to represent identity verification state + +## 62.9.0 - 2019-09-04 +* [#943](https://github.com/stripe/stripe-go/pull/943) Add support for `Authentication` and `URL` on Issuing `Authorization` + +## 62.8.2 - 2019-08-29 +* [#939](https://github.com/stripe/stripe-go/pull/939) Also log error in case of non-`stripe.Error` + +## 62.8.1 - 2019-08-29 +* [#938](https://github.com/stripe/stripe-go/pull/938) Rearrange error logging so that 402 doesn't log an error + +## 62.8.0 - 2019-08-29 +* [#937](https://github.com/stripe/stripe-go/pull/937) Add support for `EndBehavior` on `SubscriptionSchedule` + +## 62.7.0 - 2019-08-27 +* [#935](https://github.com/stripe/stripe-go/pull/935) Retry requests on a 429 that's a lock timeout + +## 62.6.0 - 2019-08-26 +* [#934](https://github.com/stripe/stripe-go/pull/934) Add support for `SubscriptionBillingCycleAnchorNow` and `SubscriptionBillingCycleAnchorUnchanged` on `Invoice` +* [#933](https://github.com/stripe/stripe-go/pull/933) Add `PendingVerification` on `Account`, `Person` and `Capability` + +## 62.5.0 - 2019-08-23 +* [#930](https://github.com/stripe/stripe-go/pull/930) Add `FailureReason` to `Refund` + +## 62.4.0 - 2019-08-22 +* [#926](https://github.com/stripe/stripe-go/pull/926) Add support for decimal amounts on Billing resources + +## 62.3.0 - 2019-08-22 +* [#928](https://github.com/stripe/stripe-go/pull/928) Bring retry code in-line with current best practices + +## 62.2.0 - 2019-08-21 +* [#922](https://github.com/stripe/stripe-go/pull/922) A few Billing changes + * Add `Schedule` to `Subscription` + * Add missing parameters for the Upcoming Invoice API: `Schedule`, `SubscriptionCancelAt`, `SubscriptionCancelNow` + * Add missing properties and parameters for a `SubscriptionSchedule` phase: `BillingThresholds`, `CollectionMethod`, `DefaultPaymentMethod`, `InvoiceSettings` +* [#923](https://github.com/stripe/stripe-go/pull/923) Add support for `Mode` on Checkout `Session` + +## 62.1.2 - 2019-08-19 +* [#921](https://github.com/stripe/stripe-go/pull/921) Mark `Customer` as an invalid parameter on PaymentMethod creation + +## 62.1.1 - 2019-08-15 +* [#918](https://github.com/stripe/stripe-go/pull/918) Fix `RadarEarlyFraudWarnings` to use the proper API endpoint + +## 62.1.0 - 2019-08-15 +* [#916](https://github.com/stripe/stripe-go/pull/916) + * Add support for `PIN` on Issuing `Card` to reflect the status of a card's PIN + * Add support for `Executive` on Person create, update and list + +## 62.0.0 - 2019-08-14 +* [#915](https://github.com/stripe/stripe-go/pull/915) Move to API version [`2019-08-14`](https://docs.stripe.com/changelog/2019-08-14) and other changes + * Pin to API version `2019-08-14` + * Rename `AccountCapabilityPlatformPayments` to `AccountCapabilityTransfers` + * Add `Executive` in `PersonRelationship` + * Remove `PayentMethodOptions` as there was a typo which was fixed + * Make `OffSession` only support booleans on `PaymentIntent` + * Remove `PaymentIntentLastPaymentError` and use `Error` instead + * Move `DeclineCode` on `Error` to the `DeclineCode` type instead of `string` +* [#914](https://github.com/stripe/stripe-go/pull/914) Update webhook handler example to use `http.MaxBytesReader` + +## 61.27.0 - 2019-08-09 +* [#913](https://github.com/stripe/stripe-go/pull/913) Remove `SubscriptionScheduleRevision` + * Note that this is technically a breaking change, however we've chosen to release it as a minor version in light of the fact that this resource and its API methods were virtually unused. + +## 61.26.0 - 2019-08-08 +* [#911](https://github.com/stripe/stripe-go/pull/911) + * Add support for `PaymentMethodDetails.Card.Moto` on `Charge` + * Add support `StatementDescriptorSuffix` on `Charge` and `PaymentIntent` + * Add support `SubscriptionData.ApplicationFeePercent` on Checkout `Session` + +## 61.25.0 - 2019-07-30 +* [#910](https://github.com/stripe/stripe-go/pull/910) Add `balancetransaction` package with a `Get` and `List` methods + +## 61.24.0 - 2019-07-30 +* [#906](https://github.com/stripe/stripe-go/pull/906) Add decline code type and constants (for use with card errors) + +## 61.23.0 - 2019-07-29 +* [#879](https://github.com/stripe/stripe-go/pull/879) Add support for OAuth API endpoints + +## 61.22.0 - 2019-07-29 +* [#909](https://github.com/stripe/stripe-go/pull/909) Rename `PayentMethodOptions` to `PaymentMethodOptions` on `PaymentIntent` and `SetupIntent`. Keep the old name until the next major version for backwards-compatibility + +## 61.21.0 - 2019-07-26 +* [#904](https://github.com/stripe/stripe-go/pull/904) Add support for Klarna and source orders + +## 61.20.0 - 2019-07-25 +* [#897](https://github.com/stripe/stripe-go/pull/897) Add all missing error codes +* [#903](https://github.com/stripe/stripe-go/pull/903) Disable HTTP/2 by default (until underlying bug in Go's implementation is fixed) +* [#905](https://github.com/stripe/stripe-go/pull/905) Add missing `Authenticated` field for 3DS charges + +## 61.19.0 - 2019-07-22 +* [#902](https://github.com/stripe/stripe-go/pull/902) Add support for `StatementDescriptor` when capturing a `PaymentIntent` + +## 61.18.0 - 2019-07-19 +* [#898](https://github.com/stripe/stripe-go/pull/898) Add `Customer` filter when listing `CreditNote` +* [#899](https://github.com/stripe/stripe-go/pull/899) Add `OffSession` parameter when updating `SubscriptionItem` + +## 61.17.0 - 2019-07-17 +* [#895](https://github.com/stripe/stripe-go/pull/895) Add `VoidedAt` on `CreditNote` + +## 61.16.0 - 2019-07-16 +* [#894](https://github.com/stripe/stripe-go/pull/894) Introduce encoding for high precision decimal fields + +## 61.15.0 - 2019-07-15 +* [#893](https://github.com/stripe/stripe-go/pull/893) + * Add support for `PaymentMethodOptions` on `PaymentIntent` and `SetupIntent` + * Add missing parameters to `PaymentIntentConfirmParams` + +## 61.14.0 - 2019-07-15 +* [#891](https://github.com/stripe/stripe-go/pull/891) Various changes relaed to SCA for Billing + * Add support for `PendingSetupIntent` on `Subscription` + * Add support for `PaymentBehavior` on `Subscription` creation and update + * Add support for `PaymentBehavior` on `SubscriptionItem` update + * Add support for `OffSession` when paying an `Invoice` + * Add support for `OffSession` on `Subscription` creation and update + +## 61.13.0 - 2019-07-05 +* [#888](https://github.com/stripe/stripe-go/pull/888) Add support for `SetupFutureUsage` on `PaymentIntent` update and confirm +* [#890](https://github.com/stripe/stripe-go/pull/890) Add support for `SetupFutureUsage` on Checkout `Session` + +## 61.12.0 - 2019-07-01 +* [#887](https://github.com/stripe/stripe-go/pull/887) Allow `OffSession` to be a bool on `PaymentIntent` creation and confirmation + +## 61.11.0 - 2019-07-01 +* [#886](https://github.com/stripe/stripe-go/pull/886) Add `CardVerificationUnavailable` constant value + +## 61.10.0 - 2019-07-01 +* [#884](https://github.com/stripe/stripe-go/pull/884) Add support for the `SetupIntent` resource and APIs +* [#885](https://github.com/stripe/stripe-go/pull/885) Quick fix to the `NextAction` property on `SetupIntent` + +## 61.9.0 - 2019-06-27 +* [#882](https://github.com/stripe/stripe-go/pull/882) Add `DefaultPaymentMethod` and `DefaultSource` to `SubscriptionSchedule` + +## 61.8.0 - 2019-06-27 +* **Note:** This release was deleted after we merged some bad code. Please use 61.9.0 instead. + +## 61.7.1 - 2019-06-25 +* [#881](https://github.com/stripe/stripe-go/pull/881) Documentation fixes + +## 61.7.0 - 2019-06-25 +* [#880](https://github.com/stripe/stripe-go/pull/880) + * Add support for `CollectionMethod` on `Invoice`, `Subscription` and `SubscriptionSchedule` + * Add support for `UnifiedProration` on `InvoiceLine` + +## 61.6.0 - 2019-06-24 +* [#878](https://github.com/stripe/stripe-go/pull/878) Enable request latency telemetry by default + +## 61.5.0 - 2019-06-20 +* [#877](https://github.com/stripe/stripe-go/pull/877) Add `CancellationReason` to `PaymentIntent` + +## 61.4.0 - 2019-06-18 +* [#845](https://github.com/stripe/stripe-go/pull/845) Add support for `CustomerBalanceTransaction` resource and APIs +* [#875](https://github.com/stripe/stripe-go/pull/875) Add missing `Account` settings + +## 61.3.0 - 2019-06-18 +* [#874](https://github.com/stripe/stripe-go/pull/874) Log only to info on 402 errors from Stripe + +## 61.2.0 - 2019-06-14 +* [#870](https://github.com/stripe/stripe-go/pull/870) Add support for `MerchantAmount` `MerchantCurrency` to Issuing `Transaction` +* [#871](https://github.com/stripe/stripe-go/pull/871) Add support for `SubmitType` to Checkout `Session` + +## 61.1.0 - 2019-06-06 +* [#867](https://github.com/stripe/stripe-go/pull/867) Add support for `Location` on Terminal `ConnectionToken` +* [#868](https://github.com/stripe/stripe-go/pull/868) Add support for `Balance` and deprecate `AccountBalance` on Customer + +## 61.0.1 - 2019-05-24 +* [#865](https://github.com/stripe/stripe-go/pull/865) Fix `earlyfraudwarning` client + +## 61.0.0 - 2019-05-24 +* [#864](https://github.com/stripe/stripe-go/pull/864) Pin library to API version `2019-05-16` + +## 60.19.0 - 2019-05-24 +* [#862](https://github.com/stripe/stripe-go/pull/862) Add support for `radar.early_fraud_warning` resource + +## 60.18.0 - 2019-05-22 +* [#861](https://github.com/stripe/stripe-go/pull/861) Add new tax ID types: `TaxIDTypeINGST` and `TaxIDTypeNOVAT` + +## 60.17.0 - 2019-05-16 +* [#860](https://github.com/stripe/stripe-go/pull/860) Add `OffSession` parameter to payment intents + +## 60.16.0 - 2019-05-14 +* [#859](https://github.com/stripe/stripe-go/pull/859) Add missing `InvoiceSettings` to `Customer` + +## 60.15.0 - 2019-05-14 +* [#855](https://github.com/stripe/stripe-go/pull/855) Add support for the capability resource and APIs + +## 60.14.0 - 2019-05-10 +* [#858](https://github.com/stripe/stripe-go/pull/858) Add `StartDate` to `Subscription` + +## 60.13.2 - 2019-05-10 +* [#857](https://github.com/stripe/stripe-go/pull/857) Fix invoice's `PaymentIntent` so its JSON tag uses API snakecase + +## 60.13.1 - 2019-05-08 +* [#853](https://github.com/stripe/stripe-go/pull/853) Add paymentmethod package to the clients list + +## 60.13.0 - 2019-05-07 +* [#850](https://github.com/stripe/stripe-go/pull/850) `OperatorAccount` is now deprecated across all Terminal endpoints +* [#851](https://github.com/stripe/stripe-go/pull/851) Add `Customer` on the `Source` object + +## 60.12.2 - 2019-05-06 +* [#843](https://github.com/stripe/stripe-go/pull/843) Lock mutex while in `SetBackends` + +## 60.12.1 - 2019-05-06 +* [#848](https://github.com/stripe/stripe-go/pull/848) Fix `Items` on `CheckoutSessionSubscriptionDataParams` to be a slice + +## 60.12.0 - 2019-05-05 +* [#846](https://github.com/stripe/stripe-go/pull/846) Add support for the `PaymentIntent` filter on `ChargeListParams` + +## 60.11.0 - 2019-05-02 +* [#841](https://github.com/stripe/stripe-go/pull/841) Add support for the `Customer` filter on `PaymentIntentListParams` +* [#842](https://github.com/stripe/stripe-go/pull/842) Add support for replacing another Issuing `Card` on creation + +## 60.10.0 - 2019-04-30 +* [#839](https://github.com/stripe/stripe-go/pull/839) Add support for ACSS Debit in `PaymentMethodDetails` on `Charge` +* [#840](https://github.com/stripe/stripe-go/pull/840) Add support for `FileLinkData` on `File` creation + +## 60.9.0 - 2019-04-24 +* [#828](https://github.com/stripe/stripe-go/pull/828) Add support for the `TaxRate` resource and APIs + +## 60.8.0 - 2019-04-23 +* [#834](https://github.com/stripe/stripe-go/pull/834) Add support for the `TaxId` resource and APIs + +## 60.7.0 - 2019-04-18 +* [#823](https://github.com/stripe/stripe-go/pull/823) Add support for the `CreditNote` resource and APIs +* [#829](https://github.com/stripe/stripe-go/pull/829) Add support for `Address`, `Name`, `Phone` and `PreferredLocales` on `Customer` and related fields on `Invoice` + +## 60.6.0 - 2019-04-18 +* [#837](https://github.com/stripe/stripe-go/pull/837) Add helpers to go from `[]T` to `[]*T` for `string`, `int64`, `float64`, `bool` + +## 60.5.1 - 2019-04-16 +* [#836](https://github.com/stripe/stripe-go/pull/836) Fix `SpendingLimits` on `AuthorizationControlsParams` and `AuthorizationControls` to be a slice on Issuing `Card` and `Cardholder` + +## 60.5.0 - 2019-04-16 +* [#740](https://github.com/stripe/stripe-go/pull/740) Add support for the Checkout `Session` resource and APIs +* [#832](https://github.com/stripe/stripe-go/pull/832) Add support for `version` and `succeeded` properties in the `payment_method_details[card][three_d_secure]` hash for `Charge`. +* [#835](https://github.com/stripe/stripe-go/pull/835) Add support for passing `payment_method` on `Customer` creation + +## 60.4.0 - 2019-04-15 +* [#833](https://github.com/stripe/stripe-go/pull/833) Add more context when failing to unmarshal JSON + +## 60.3.0 - 2019-04-12 +* [#831](https://github.com/stripe/stripe-go/pull/831) Add support for `authorization_controls` on `Cardholder` and `authorization_controls[spending_limits]` added to `Card` too for Issuing resources + +## 60.2.0 - 2019-04-09 +* [#827](https://github.com/stripe/stripe-go/pull/827) Add support for `confirmation_method` on `PaymentIntent` creation + +## 60.1.0 - 2019-04-09 +* [#824](https://github.com/stripe/stripe-go/pull/824) Add support for `PaymentIntent` and `PaymentMethod` on `Customer`, `Subscription` and `Invoice`. + +## 60.0.1 - 2019-04-02 +* [#825](https://github.com/stripe/stripe-go/pull/825) Fix the API for usage record summary listing + +## 60.0.0 - 2019-03-27 +* [#820](https://github.com/stripe/stripe-go/pull/820) Add various missing parameters + * On `PIIParams` the previous `PersonalIDNumber` is fixed to `IDNumber` which we're releasing as a minor breaking change even though the old version probably didn't work correctly + +## 59.1.0 - 2019-03-22 +* [#819](https://github.com/stripe/stripe-go/pull/819) Add default level prefixes in messages from `LeveledLogger` + +## 59.0.0 - 2019-03-22 +* [#818](https://github.com/stripe/stripe-go/pull/818) Implement leveled logging (very minor breaking change -- only a couple properties were removed from the internal `BackendImplementation`) + +## 58.1.0 - 2019-03-19 +* [#815](https://github.com/stripe/stripe-go/pull/815) Add support for passing token on account or person creation + +## 58.0.0 - 2019-03-19 +* [#811](https://github.com/stripe/stripe-go/pull/811) Add support for API version 2019-03-14 +* [#814](https://github.com/stripe/stripe-go/pull/814) Properly override API version if it's set in the request + +## 57.8.0 - 2019-03-18 +* [#806](https://github.com/stripe/stripe-go/pull/806) Add support for the `PaymentMethod` resource and APIs +* [#812](https://github.com/stripe/stripe-go/pull/812) Add support for deleting a Terminal `Location` and `Reader` + +## 57.7.0 - 2019-03-13 +* [#810](https://github.com/stripe/stripe-go/pull/810) Add support for `columns` on `ReportRun` and `default_columns` on `ReportType`. + +## 57.6.0 - 2019-03-06 +* [#808](https://github.com/stripe/stripe-go/pull/808) Add support for `backdate_start_date` and `cancel_at` on `Subscription`. + +## 57.5.0 - 2019-03-05 +* [#807](https://github.com/stripe/stripe-go/pull/807) Add support for `current_period_end` and `current_period_start` filters when listing `Invoice`. + +## 57.4.0 - 2019-03-04 +* [#798](https://github.com/stripe/stripe-go/pull/798) Properly support serialization of `Event`. + +## 57.3.0 - 2019-02-28 +* [#803](https://github.com/stripe/stripe-go/pull/803) Add support for `api_version` on `WebhookEndpoint`. + +## 57.2.0 - 2019-02-27 +* [#795](https://github.com/stripe/stripe-go/pull/795) Add support for `created` and `status_transitions` on `Invoice` +* [#802](https://github.com/stripe/stripe-go/pull/802) Add support for `latest_invoice` on `Subscription` + +## 57.1.1 - 2019-02-26 +* [#800](https://github.com/stripe/stripe-go/pull/800) Add `UsageRecordSummaries` to the list of clients. + +## 57.1.0 - 2019-02-22 +* [#796](https://github.com/stripe/stripe-go/pull/796) Correct `InvoiceItems` in `InvoiceParams` to be a slice of structs instead of a struct (this is technically a breaking change, but the previous implementation was non-functional, so we're releasing it as a minor version) + +## 57.0.1 - 2019-02-20 +* [#794](https://github.com/stripe/stripe-go/pull/794) Properly pin to API version `2019-02-19`. The previous major version incorrectly stayed on API version `2019-02-11` which prevented requests to manage Connected accounts from working and charges to have the new statement descriptor behavior. + +## 57.0.0 - 2019-02-19 +**Important:** This version is non-functional and has been yanked in favor of 57.0.1. +* [#782](https://github.com/stripe/stripe-go/pull/782) Changes related to the new API version `2019-02-19`: + * The library is now pinned to API version `2019-02-19` + * Numerous changes to the `Account` resource and APIs: + * The `legal_entity` property on the Account API resource has been replaced with `individual`, `company`, and `business_type` + * The `verification` hash has been replaced with a `requirements` hash + * Multiple top-level properties were moved to the `settings` hash + * The `keys` property on `Account` has been removed. Platforms should authenticate as their connected accounts with their own key via the `Stripe-Account` [header](https://stripe.com/docs/connect/authentication#authentication-via-the-stripe-account-header) + * The `requested_capabilities` property on `Account` creation is now required for accounts in the US + * The deprecated parameter `save_source_to_customer` on `PaymentIntent` has now been removed. Use `save_payment_method` instead + +## 56.1.0 - 2019-02-18 +* [#737](https://github.com/stripe/stripe-go/pull/737) Add support for setting `request_capabilities` and retrieving `capabilities` on `Account` +* [#793](https://github.com/stripe/stripe-go/pull/793) Add support for `save_payment_method` on `PaymentIntent` + +## 56.0.0 - 2019-02-13 +* [#785](https://github.com/stripe/stripe-go/pull/785) Changes to the Payment Intent APIs for the next API version +* [#789](https://github.com/stripe/stripe-go/pull/789) Allow API arrays to be emptied by setting an empty array + +## 55.15.0 - 2019-02-12 +* [#764](https://github.com/stripe/stripe-go/pull/764) Add support for `transfer_data[destination]` on `Invoice` and `Subscription` +* [#784](https://github.com/stripe/stripe-go/pull/784) + * Add support for `SubscriptionSchedule` and `SubscriptionScheduleRevision` + * Add support for `payment_method_types` on `PaymentIntent` +* [#787](https://github.com/stripe/stripe-go/pull/787) Add support for `transfer_data[amount]` on `Charge` + +## 55.14.0 - 2019-01-25 +* [#765](https://github.com/stripe/stripe-go/pull/765) Add support for `destination_payment_refund` and `source_refund` on the `Reversal` resource + +## 55.13.0 - 2019-01-17 +* [#779](https://github.com/stripe/stripe-go/pull/779) Add support for `receipt_url` on `Charge` + +## 55.12.0 - 2019-01-17 +* [#766](https://github.com/stripe/stripe-go/pull/766) Add optional support for sending request telemetry to Stripe + +## 55.11.0 - 2019-01-17 +* [#776](https://github.com/stripe/stripe-go/pull/776) Add support for billing thresholds + +## 55.10.0 - 2019-01-16 +* [#773](https://github.com/stripe/stripe-go/pull/773) Add support for `custom_fields` and `footer` on `Invoice` +* [#774](https://github.com/stripe/stripe-go/pull/774) Revert Go module support + +## 55.9.0 - 2019-01-15 +* [#769](https://github.com/stripe/stripe-go/pull/769) Add field `Amount` to `IssuingTransaction` + +## 55.8.0 - 2019-01-09 +* [#763](https://github.com/stripe/stripe-go/pull/763) Add `application_fee_amount` to `Charge` and on charge create and capture params + +## 55.7.0 - 2019-01-09 +* [#738](https://github.com/stripe/stripe-go/pull/738) Add support for the account link resource + +## 55.6.0 - 2019-01-09 +* [#762](https://github.com/stripe/stripe-go/pull/762) Add support for new invoice items parameters when retrieving an upcoming invoice + +## 55.5.0 - 2019-01-07 +* [#744](https://github.com/stripe/stripe-go/pull/744) Add support for `transfer_data[destination]` on Charge struct and params +* [#746](https://github.com/stripe/stripe-go/pull/746) Add support for `wallet_provider` on the Issuing Authorization + +## 55.4.0 - 2019-01-07 +* [#745](https://github.com/stripe/stripe-go/pull/745) Add support for `pending` parameter when listing invoice items + +## 55.3.0 - 2019-01-02 +* [#742](https://github.com/stripe/stripe-go/pull/742) Add field `FraudType` to `IssuerFraudRecord` + +## 55.2.0 - 2018-12-31 +* [#741](https://github.com/stripe/stripe-go/pull/741) Add missing parameters `InvoiceNow` and `Prorate` for subscription cancellation + +## 55.1.0 - 2018-12-27 +* [#743](https://github.com/stripe/stripe-go/pull/743) Add support for `clear_usage` on `SubscriptionItem` deletion + +## 55.0.0 - 2018-12-13 +* [#739](https://github.com/stripe/stripe-go/pull/739) Use `ApplicationFee` struct for `FeeRefund.Fee` (minor breaking change) + +## 54.2.0 - 2018-11-30 +* [#734](https://github.com/stripe/stripe-go/pull/734) Put `/v1/` prefix as part of all paths instead of URL + +## 54.1.1 - 2018-11-30 +* [#733](https://github.com/stripe/stripe-go/pull/733) Fix malformed URL generated for the uploads API when using `NewBackends` + +## 54.1.0 - 2018-11-28 +* [#730](https://github.com/stripe/stripe-go/pull/730) Add support for the Review resource +* [#731](https://github.com/stripe/stripe-go/pull/731) Add missing properties on the Refund resource + +## 54.0.0 - 2018-11-27 +* [#721](https://github.com/stripe/stripe-go/pull/721) Add support for `RadarValueList` and `RadarValueListItem` +* [#721](https://github.com/stripe/stripe-go/pull/721) Remove `Closed` and `Forgiven` from `InvoiceParams` +* [#721](https://github.com/stripe/stripe-go/pull/721) Add `PaidOutOfBand` to `InvoicePayParams` + +## 53.4.0 - 2018-11-26 +* [#728](https://github.com/stripe/stripe-go/pull/728) Add `IssuingCard` to `EphemeralKeyParams` + +## 53.3.0 - 2018-11-26 +* [#727](https://github.com/stripe/stripe-go/pull/727) Add support for `TransferData` on payment intent create and update + +## 53.2.0 - 2018-11-21 +* [#725](https://github.com/stripe/stripe-go/pull/725) Improved error deserialization + +## 53.1.0 - 2018-11-15 +* [#723](https://github.com/stripe/stripe-go/pull/723) Add support for `last_payment_error` on `PaymentIntent`. +* [#724](https://github.com/stripe/stripe-go/pull/724) Add support for `transfer_data[destination]` on `PaymentIntent`. + +## 53.0.1 - 2018-11-12 +* [#714](https://github.com/stripe/stripe-go/pull/714) Fix bug in retry logic that would cause the client to panic + +## 53.0.0 - 2018-11-08 +* [#716](https://github.com/stripe/stripe-go/pull/716) Drop support for Go 1.8. +* [#715](https://github.com/stripe/stripe-go/pull/715) Ship changes to the `PaymentIntent` resource to match the final layout. +* [#717](https://github.com/stripe/stripe-go/pull/717) Add support for `flat_amount` on `Plan` tiers. +* [#718](https://github.com/stripe/stripe-go/pull/718) Add support for `supported_transfer_countries` on `CountrySpec`. +* [#720](https://github.com/stripe/stripe-go/pull/720) Add support for `review` on `PaymentIntent`. +* [#707](https://github.com/stripe/stripe-go/pull/707) Add new invoice methods and fixes to the Issuing Cardholder resource (multiple breaking changes) + * Move to API version 2018-11-08. + * Add support for new API methods, properties and parameters for `Invoice`. + * Add support for `default_source` on `Subscription` and `Invoice`. + +## 52.1.0 - 2018-10-31 +* [#705](https://github.com/stripe/stripe-go/pull/705) Add support for the `Person` resource +* [#706](https://github.com/stripe/stripe-go/pull/706) Add support for the `WebhookEndpoint` resource + +## 52.0.0 - 2018-10-29 +* [#711](https://github.com/stripe/stripe-go/pull/711) Set `Request.GetBody` when making requests +* [#711](https://github.com/stripe/stripe-go/pull/711) Drop support for Go 1.7 (hasn't been supported by Go core since the release of Go 1.9 in August 2017) + +## 51.4.0 - 2018-10-19 +* [#708](https://github.com/stripe/stripe-go/pull/708) Add Stripe Terminal endpoints to master to `client.API` + +## 51.3.0 - 2018-10-09 +* [#704](https://github.com/stripe/stripe-go/pull/704) Add support for `subscription_cancel_at_period_end` on the Upcoming Invoice API. + +## 51.2.0 - 2018-10-09 +* [#702](https://github.com/stripe/stripe-go/pull/702) Add support for `delivery_success` filter when listing Events. + +## 51.1.0 - 2018-10-03 +* [#700](https://github.com/stripe/stripe-go/pull/700) Add support for `on_behalf_of` on Subscription and Charge resources. + +## 51.0.0 - 2018-09-27 +* [#698](https://github.com/stripe/stripe-go/pull/698) Move to API version 2018-09-24 + * Rename `FileUpload` to `File` (and all `FileUpload*` structs to `File*`) + * Fix file links client + +## 50.0.0 - 2018-09-24 +* [#695](https://github.com/stripe/stripe-go/pull/695) Rename `Transaction` to `DisputedTransaction` in `IssuingDisputeParams` (minor breaking change) +* [#695](https://github.com/stripe/stripe-go/pull/695) Add support for Stripe Terminal + +## 49.2.0 - 2018-09-24 +* [#697](https://github.com/stripe/stripe-go/pull/697) Fix `number` JSON tag on the `IssuingCardDetails` resource. + +## 49.1.0 - 2018-09-11 +* [#694](https://github.com/stripe/stripe-go/pull/694) Add `ErrorCodeResourceMissing` error code constant + +## 49.0.0 - 2018-09-11 +* [#693](https://github.com/stripe/stripe-go/pull/693) Change `Product` under `Plan` from a string to a full `Product` struct pointer (this is a minor breaking change -- upgrade by changing to `plan.Product.ID`) + +## 48.3.0 - 2018-09-06 +* [#691](https://github.com/stripe/stripe-go/pull/691) Add `InvoicePrefix` to `Customer` and `CustomerParams` + +## 48.2.0 - 2018-09-05 +* [#690](https://github.com/stripe/stripe-go/pull/690) Add support for reporting resources + +## 48.1.0 - 2018-09-05 +* [#683](https://github.com/stripe/stripe-go/pull/683) Add `StatusTransitions` filter parameters to `OrderListParams` + +## 48.0.0 - 2018-09-05 +* [#681](https://github.com/stripe/stripe-go/pull/681) Handle deserialization of `OrderItem` parent into an object if expanded (minor breaking change) + +## 47.0.0 - 2018-09-04 +* New major version for better compatibility with Go's new module system (no breaking changes) + +## 46.1.0 - 2018-09-04 +* [#688](https://github.com/stripe/stripe-go/pull/688) Encode `Params` in `AppendToAsSourceOrExternalAccount` (bug fix) +* [#689](https://github.com/stripe/stripe-go/pull/689) Add `go.mod` for the new module system + +## 46.0.0 - 2018-09-04 +* [#686](https://github.com/stripe/stripe-go/pull/686) Add `Mandate` and `Receiver` to `SourceObjectParams` and change `Date` on `SourceMandateAcceptance` to `int64` (minor breaking change) + +## 45.0.0 - 2018-08-30 +* [#680](https://github.com/stripe/stripe-go/pull/680) Change `SubscriptionTaxPercent` on `Invoice` from `int64` to `float64` (minor breaking change) + +## 44.0.0 - 2018-08-28 +* [#678](https://github.com/stripe/stripe-go/pull/678) Allow payment intent capture to take its own parameters + +## 43.1.1 - 2018-08-28 +* [#675](https://github.com/stripe/stripe-go/pull/675) Fix incorrectly encoded parameter in `UsageRecordSummaryListParams` + +## 43.1.0 - 2018-08-28 +* [#669](https://github.com/stripe/stripe-go/pull/669) Add `AuthorizationCode` to `Charge` +* [#671](https://github.com/stripe/stripe-go/pull/671) Fix deserialization of `TaxID` on `CustomerTaxInfo` + +## 43.0.0 - 2018-08-23 +* [#668](https://github.com/stripe/stripe-go/pull/668) Move to API version 2018-08-23 + * Add `TaxInfo` and `TaxInfoVerification` to `Customer` + * Rename `Amount` to `UnitAmount` on `PlanTierParams` + * Remove `BusinessVATID` from `Customer` + * Remove `AtPeriodEnd` from `SubscriptionCancelParams` + +## 42.3.0 - 2018-08-23 +* [#667](https://github.com/stripe/stripe-go/pull/667) Add `Forgive` to `InvoicePayParams` + +## 42.2.0 - 2018-08-22 +* [#666](https://github.com/stripe/stripe-go/pull/666) Add `Subscription` to `SubscriptionItem` + +## 42.1.0 - 2018-08-22 +* [#664](https://github.com/stripe/stripe-go/pull/664) Add `AvailablePayoutMethods` to `Card` + +## 42.0.0 - 2018-08-20 +* [#663](https://github.com/stripe/stripe-go/pull/663) Add support for usage record summaries and rename `Live` on `IssuerFraudRecord, `SourceTransaction`, and `UsageRecord` to `Livemode` (a minor breaking change) + +## 41.0.0 - 2018-08-17 +* [#659](https://github.com/stripe/stripe-go/pull/659) Remove mutating Bitcoin receiver API calls (these were no longer functional anyway) +* [#661](https://github.com/stripe/stripe-go/pull/661) Correct `IssuingCardShipping`'s type to `int64` +* [#662](https://github.com/stripe/stripe-go/pull/662) Rename `IssuingCardShipping`'s `Eta` to `ETA` + +## 40.2.0 - 2018-08-15 +* [#657](https://github.com/stripe/stripe-go/pull/657) Use integer-indexed encoding for all arrays + +## 40.1.0 - 2018-08-10 +* [#656](https://github.com/stripe/stripe-go/pull/656) Expose new `ValidatePayload` functions for validating incoming payloads without constructing an event + +## 40.0.2 - 2018-08-07 +* [#652](https://github.com/stripe/stripe-go/pull/652) Change the type of `FileUpload.Links` to `FileLinkList` (this is a bug fix given that the previous type would never have worked) + +## 40.0.1 - 2018-08-07 +* [#653](https://github.com/stripe/stripe-go/pull/653) All `BackendImplementation`s should sleep by default on retries + +## 40.0.0 - 2018-08-06 +* [#648](https://github.com/stripe/stripe-go/pull/648) Introduce buffers so a request's body can be read multiple times (this modifies the interface of a few exported internal functions so it's technically breaking, but it will probably not be breaking for most users) +* [#649](https://github.com/stripe/stripe-go/pull/649) Rename `BackendConfiguration` to `BackendImplementation` (likewise, technically breaking, but minor) +* [#650](https://github.com/stripe/stripe-go/pull/650) Export `webhook.ComputeSignature` + +## 39.0.0 - 2018-08-04 +* [#646](https://github.com/stripe/stripe-go/pull/646) Set request body before every retry (this modifies the interface of a few exported internal functions so it's technically breaking, but it will probably not be breaking for most users) + +## 38.2.0 - 2018-08-03 +* [#644](https://github.com/stripe/stripe-go/pull/644) Add support for file links +* [#645](https://github.com/stripe/stripe-go/pull/645) Add support for `Cancel` to topups + +## 38.1.0 - 2018-08-01 +* [#643](https://github.com/stripe/stripe-go/pull/643) Bug fix and various code/logging improvements to retry code + +## 38.0.0 - 2018-07-30 +* [#641](https://github.com/stripe/stripe-go/pull/641) Minor breaking changes to correct a few naming inconsistencies: + * `IdentityVerificationDetailsCodeScanIdCountryNotSupported` becomes `IdentityVerificationDetailsCodeScanIDCountryNotSupported` + * `IdentityVerificationDetailsCodeScanIdTypeNotSupported` becomes `IdentityVerificationDetailsCodeScanIDTypeNotSupported` + * `BitcoinUri` on `BitcoinReceiver` becomes `BitcoinURI` + * `NetworkId` on `IssuingAuthorization` becomes `NetworkID` + +## 37.0.0 - 2018-07-30 +* [#637](https://github.com/stripe/stripe-go/pull/637) Add support for Sigma scheduled query runs +* [#639](https://github.com/stripe/stripe-go/pull/639) Move to API version `2018-07-27` (breaking) + * Remove `SKUs` from `Product` + * Subscription creation and update can no longer take a source + * Change `PercentOff` on coupon struct and params from integer to float +* [#640](https://github.com/stripe/stripe-go/pull/640) Add missing field `Created` to `Account` + +## 36.3.0 - 2018-07-27 +* [#636](https://github.com/stripe/stripe-go/pull/636) Add `RiskScore` to `ChargeOutcome` + +## 36.2.0 - 2018-07-26 +* [#635](https://github.com/stripe/stripe-go/pull/635) Add support for Stripe Issuing + +## 36.1.2 - 2018-07-24 +* [#633](https://github.com/stripe/stripe-go/pull/633) Fix encoding of list params for bank accounts and cards + +## 36.1.1 - 2018-07-17 +* [#627](https://github.com/stripe/stripe-go/pull/627) Wire an `http.Client` from `NewBackends` through to backends + +## 36.1.0 - 2018-07-11 +* [#624](https://github.com/stripe/stripe-go/pull/624) Add `AutoAdvance` for `Invoice` + +## 36.0.0 - 2018-07-09 +* [#606](https://github.com/stripe/stripe-go/pull/606) Add support for payment intents +* [#623](https://github.com/stripe/stripe-go/pull/623) Changed `Payout.Destination` from `string` to `*PayoutDestination` to support expanding (minor breaking change) + +## 35.13.0 - 2018-07-06 +* [#622](https://github.com/stripe/stripe-go/pull/622) Correct position of `DeclineChargeOn` (it was added accidentally on `LegalEntityParams` when it should have been on `AccountParams`) + +## 35.12.0 - 2018-07-05 +* [#620](https://github.com/stripe/stripe-go/pull/620) Add support for `Quantity` and `UnitAmount` to `InvoiceItemParams` and `Quantity` to `InvoiceItem` + +## 35.11.0 - 2018-07-05 +* [#618](https://github.com/stripe/stripe-go/pull/618) Add support for `DeclineChargeOn` to `Account` and `AccountParams` + +## 35.10.0 - 2018-07-04 +* [#616](https://github.com/stripe/stripe-go/pull/616) Adding missing clients to the `API` struct including a `UsageRecords` entry + +## 35.9.0 - 2018-07-03 +* [#611](https://github.com/stripe/stripe-go/pull/611) Introduce `GetBackendWithConfig` and make logging configurable per backend + +## 35.8.0 - 2018-06-28 +* [#607](https://github.com/stripe/stripe-go/pull/607) Add support for `PartnerID` from `stripe.SetAppInfo` + +## 35.7.0 - 2018-06-26 +* [#604](https://github.com/stripe/stripe-go/pull/604) Add extra parameters `CustomerReference` and `ShippingFromZip` to `ChargeLevel3Params` and `ChargeLevel3` + +## 35.6.0 - 2018-06-25 +* [#603](https://github.com/stripe/stripe-go/pull/603) Add support for Level III data on charge creation + +## 35.5.0 - 2018-06-22 +* [#601](https://github.com/stripe/stripe-go/pull/601) Add missing parameters for retrieving an upcoming invoice + +## 35.4.0 - 2018-06-21 +* [#599](https://github.com/stripe/stripe-go/pull/599) Add `ExchangeRate` to `BalanceTransaction` + +## 35.3.0 - 2018-06-20 +* [#596](https://github.com/stripe/stripe-go/pull/596) Add `Type` to `ProductListParams` so that products can be listed by type + +## 35.2.0 - 2018-06-19 +* [#595](https://github.com/stripe/stripe-go/pull/595) Add `Product` to `PlanListParams` so that plans can be listed by product + +## 35.1.0 - 2018-06-17 +* [#592](https://github.com/stripe/stripe-go/pull/592) Add `Name` field to `Coupon` and `CouponParams` + +## 35.0.0 - 2018-06-15 +* [#557](https://github.com/stripe/stripe-go/pull/557) Add automatic retries for intermittent errors (enabling using `BackendConfiguration.SetMaxNetworkRetries`) +* [#589](https://github.com/stripe/stripe-go/pull/589) Fix all `Get` methods to support standardized parameter structs + remove some deprecated functions + * `IssuerFraudRecordListParams` now uses `*string` for `Charge` (set it using `stripe.String` like elsewhere) + * `event.Get` now takes `stripe.EventParams` instead of `Params` for consistency + * The `Get` method for `countryspec`, `exchangerate`, `issuerfraudrecord` now take an extra params struct parameter to be consistent and allow setting a connected account (use `stripe.CountrySpecParams`, `stripe.ExchangeRateParams`, and `IssuerFraudRecordParams`) + * `charge.MarkFraudulent` and `charge.MarkSafe` have been removed; use `charge.Update` instead + * `charge.CloseDispute` and `charge.UpdateDispute` have been removed; use `dispute.Update` or `dispute.Close` instead + * `loginlink.New` now properly passes its params struct into its API call + +## 34.3.0 - 2018-06-14 +* [#587](https://github.com/stripe/stripe-go/pull/587) Use `net/http` constants instead of string literals for HTTP verbs (this is an internal cleanup and should not affect library behavior) + +## 34.2.0 - 2018-06-14 +* [#581](https://github.com/stripe/stripe-go/pull/581) Push parameter encoding into `BackendConfiguration.Call` (this is an internal cleanup and should not affect library behavior) + +## 34.1.0 - 2018-06-13 +* [#586](https://github.com/stripe/stripe-go/pull/586) Add `AmountPaid`, `AmountRemaining`, `BillingReason` (including new `InvoiceBillingReason` and constants), and `SubscriptionProrationDate` to `Invoice` + +## 34.0.0 - 2018-06-12 +* [#585](https://github.com/stripe/stripe-go/pull/585) Remove `File` in favor of `FileUpload`, and consolidating both classes which were already nearly identical except `MIMEType` has been replaced by `Type` (this is technically a breaking change, but quite a small one) + +## 33.1.0 - 2018-06-12 +* [#578](https://github.com/stripe/stripe-go/pull/578) Improve expansion parsing by not discarding unmarshal errors + +## 33.0.0 - 2018-06-11 +* [#583](https://github.com/stripe/stripe-go/pull/583) Add new account constants, rename one, and fix `DueBy` (this is technically a breaking change, but quite a small one) + +## 32.4.1 - 2018-06-11 +* [#582](https://github.com/stripe/stripe-go/pull/582) Fix unmarshaling of `LegalEntity` (specifically when we have `legal_entity[additional_owners][][verification]`) so that it comes out as a struct + +## 32.4.0 - 2018-06-07 +* [#577](https://github.com/stripe/stripe-go/pull/577) Add `DocumentBack` to account legal entity identity verification parameters and response + +## 32.3.0 - 2018-06-07 +* [#576](https://github.com/stripe/stripe-go/pull/576) Fix plan transform usage to use `BucketSize` instead of `DivideBy`; note this is technically a breaking API change, but we've released it as a minor because the previous manifestation didn't work + +## 32.2.0 - 2018-06-06 +* [#571](https://github.com/stripe/stripe-go/pull/571) Add `HostedInvoiceURL` and `InvoicePDF` to `Invoice` +* [#573](https://github.com/stripe/stripe-go/pull/573) Add `FormatURLPath` helper to allow safer URL path building + +## 32.1.0 - 2018-06-06 +* [#572](https://github.com/stripe/stripe-go/pull/572) Add `Active` to plan parameters and response + +## 32.0.1 - 2018-06-06 +* [#569](https://github.com/stripe/stripe-go/pull/569) Fix unmarshaling of expanded transaction sources in balance transactions + +## 32.0.0 - 2018-06-06 +* [#544](https://github.com/stripe/stripe-go/pull/544) **MAJOR** changes that make all fields on parameter structs pointers, and rename many fields on parameter and response structs to be consistent with naming in the REST API; we've written [a migration guide with complete details](https://github.com/stripe/stripe-go/blob/master/v32_migration_guide.md) to help with the upgrade + +## 31.0.0 - 2018-06-06 +* [#566](https://github.com/stripe/stripe-go/pull/566) Support `DisputeParams` in `dispute.Close` + +## 30.8.1 - 2018-05-24 +* [#562](https://github.com/stripe/stripe-go/pull/562) Add `go.mod` for vgo support + +## 30.8.0 - 2018-05-22 +* [#558](https://github.com/stripe/stripe-go/pull/558) Add `SubscriptionItem` to `InvoiceLine` + +## 30.7.0 - 2018-05-09 +* [#552](https://github.com/stripe/stripe-go/pull/552) Add support for issuer fraud records + +## 30.6.1 - 2018-05-04 +* [#550](https://github.com/stripe/stripe-go/pull/550) Append standard `Params` as well as card options when encoding `CardParams` + +## 30.6.0 - 2018-04-17 +* [#546](https://github.com/stripe/stripe-go/pull/546) Add `SubParams.TrialFromPlan` and `SubItemsParams.ClearUsage` + +## 30.5.0 - 2018-04-09 +* [#543](https://github.com/stripe/stripe-go/pull/543) Support listing orders by customer (add `Customer` to `OrderListParams`) + +## 30.4.0 - 2018-04-06 +* [#541](https://github.com/stripe/stripe-go/pull/541) Add `Mandate` on `Source` (and associated mandate structs) + +## 30.3.0 - 2018-04-02 +* [#538](https://github.com/stripe/stripe-go/pull/538) Introduce flexible billing primitives for subscriptions + +## 30.2.0 - 2018-03-23 +* [#535](https://github.com/stripe/stripe-go/pull/535) Add constant for redirect status `not_required` (`RedirectFlowStatusNotRequired`) + +## 30.1.0 - 2018-03-17 +* [#534](https://github.com/stripe/stripe-go/pull/534) Add `AmountZero` to `InvoiceItemParams` + +## 30.0.0 - 2018-03-14 +* [#533](https://github.com/stripe/stripe-go/pull/533) Make `DestPayment` under `Transfer` expandable by changing it from a string to a `Charge` + +## 29.3.1 - 2018-03-08 +* [#530](https://github.com/stripe/stripe-go/pull/530) Fix mixed up types in `CountrySpec.SupportedBankAccountCurrencies` + +## 29.3.0 - 2018-03-01 +* [#527](https://github.com/stripe/stripe-go/pull/527) Add `MaidenName`, `PersonalIDNumber`, `PersonalIDNumberProvided` fields to `Owner` struct + +## 29.2.0 - 2018-02-26 +* [#525](https://github.com/stripe/stripe-go/pull/525) Support shipping carrier and tracking number in orders +* [#526](https://github.com/stripe/stripe-go/pull/526) Fix ignored `commonParams` when returning an order + +## 29.1.1 - 2018-02-21 +* [#522](https://github.com/stripe/stripe-go/pull/522) Bump API version and fix creating plans with a product + +## 29.1.0 - 2018-02-21 +* [#520](https://github.com/stripe/stripe-go/pull/520) Add support for topups + +## 29.0.1 - 2018-02-16 +**WARNING:** Please use 29.1.1 instead. +* [#519](https://github.com/stripe/stripe-go/pull/519) Correct the implementation of `PaymentSource.MarshalJSON` to also handle bank account sources + +## 29.0.0 - 2018-02-14 +**WARNING:** Please use 29.1.1 instead. +* [#518](https://github.com/stripe/stripe-go/pull/518) Bump API version to 2018-02-06 and add support for Product & Plan API + +## 28.12.0 - 2018-02-09 +* [#517](https://github.com/stripe/stripe-go/pull/517) Add `BillingCycleAnchor` to `Sub` and `BillingCycleAnchorUnchanged` to `SubParams` + +## 28.11.0 - 2018-01-29 +* [#516](https://github.com/stripe/stripe-go/pull/516) Add `AmountZero` to `PlanParams` to it's possible to send zero values when creating or updating a plan + +## 28.10.1 - 2018-01-18 +* [#512](https://github.com/stripe/stripe-go/pull/512) Encode empty values found in maps (like `Meta`) + +## 28.10.0 - 2018-01-09 +* [#509](https://github.com/stripe/stripe-go/pull/509) Plumb through additional possible errors when unmarshaling polymorphic types (please test your integrations while upgrading) + +## 28.9.0 - 2018-01-08 +* [#506](https://github.com/stripe/stripe-go/pull/506) Add support for recursing into slices in `event.GetObjValue` + +## 28.8.0 - 2017-12-12 +* [#500](https://github.com/stripe/stripe-go/pull/500) Support sharing for bank accounts and cards (adds `ID` field to bank account and charge parameters) + +## 28.7.0 - 2017-12-05 +* [#494](https://github.com/stripe/stripe-go/pull/494) Add `Automatic` to `Payout` struct + +## 28.6.1 - 2017-11-02 +* [#492](https://github.com/stripe/stripe-go/pull/492) Correct name of user agent header used to send Go version to Stripe's API + +## 28.6.0 - 2017-10-31 +* [#491](https://github.com/stripe/stripe-go/pull/491) Support for exchange rates APIs + +## 28.5.0 - 2017-10-27 +* [#488](https://github.com/stripe/stripe-go/pull/488) Support for listing source transactions + +## 28.4.2 - 2017-10-25 +* [#486](https://github.com/stripe/stripe-go/pull/486) Send the required `object=bank_account` parameter when adding a bank account through an account +* [#487](https://github.com/stripe/stripe-go/pull/487) Make bank account's `account_holder_name` and `account_holder_type` parameters truly optional + +## 28.4.1 - 2017-10-24 +* [#484](https://github.com/stripe/stripe-go/pull/484) Error early when params not specified for card-related API calls + +## 28.4.0 - 2017-10-19 +* [#477](https://github.com/stripe/stripe-go/pull/477) Support context on API requests with `Params.Context` and `ListParams.Context` + +## 28.3.2 - 2017-10-19 +* [#479](https://github.com/stripe/stripe-go/pull/479) Pass token in only one of `external_account` *or* source when appending card + +## 28.3.1 - 2017-10-17 +* [#476](https://github.com/stripe/stripe-go/pull/476) Make initializing new backends concurrency-safe + +## 28.3.0 - 2017-10-10 +* [#359](https://github.com/stripe/stripe-go/pull/359) Add support for verify sources (added `Values` on `SourceVerifyParams`) + +## 28.2.0 - 2017-10-09 +* [#472](https://github.com/stripe/stripe-go/pull/472) Add support for `statement_descriptor` in source objects +* [#473](https://github.com/stripe/stripe-go/pull/473) Add support for detaching sources from customers + +## 28.1.0 - 2017-10-05 +* [#471](https://github.com/stripe/stripe-go/pull/471) Add support for `RedirectFlow.FailureReason` for sources + +## 28.0.1 - 2017-10-03 +* [#468](https://github.com/stripe/stripe-go/pull/468) Fix encoding of pointer-based scalars (e.g. `Active *bool` in `Product`) +* [#470](https://github.com/stripe/stripe-go/pull/470) Fix concurrent race in `form` package's encoding caches + +## 28.0.0 - 2017-09-27 +* [#467](https://github.com/stripe/stripe-go/pull/467) Change `Product.Get` to include `ProductParams` for request metadata +* [#467](https://github.com/stripe/stripe-go/pull/467) Fix sending extra parameters on product and SKU requests + +## 27.0.2 - 2017-09-26 +* [#465](https://github.com/stripe/stripe-go/pull/465) Fix encoding of `CVC` parameter in `CardParams` + +## 27.0.1 - 2017-09-20 +* [#461](https://github.com/stripe/stripe-go/pull/461) Fix encoding of `TypeData` under sources + +## 27.0.0 - 2017-09-19 +* [#458](https://github.com/stripe/stripe-go/pull/458) Remove `ChargeParams.Token` (this seems like it was added accidentally) + +## 26.0.0 - 2017-09-17 +* Introduce `form` package so it's no longer necessary to build conditional structures to encode parameters -- this may result in parameters that were set but previously not encoded to now be encoded so **PLEASE TEST CAREFULLY WHEN UPGRADING**! +* Alphabetize all struct fields -- this may result in position-based struct initialization to fail if it was being used +* Switch to stripe-mock for testing (test suite now runs completely!) +* Remote Displayer interface and Display implementations +* Add `FraudDetails` to `ChargeParams` +* Remove `FraudReport` from `ChargeParams` (use `FraudDetails` instead) + +## 25.2.0 - 2017-09-13 +* Add `OnBehalfOf` to charge parameters. +* Add `OnBehalfOf` to subscription parameters. + +## 25.1.0 - 2017-09-06 +* Use bearer token authentication for API requests + +## 25.0.0 - 2017-08-21 +* All `Del` methods now take params as second argument (which may be `nil`) +* Product `Delete` has been renamed to `Del` for consistency +* Product `Delete` now returns `(*Product, error)` for consistency +* SKU `Delete` has been renamed to `Del` for consistency +* SKU `Delete` now returns `(*SKU, error)` for consistency + +## 24.3.0 - 2017-08-08 +* Add `FeeZero` to invoice and `TaxPercentZero` to subscription for zeroing values + +## 24.2.0 - 2017-07-25 +* Add "range queries" for supported parameters (e.g. `created[gte]=123`) + +## 24.1.0 - 2017-07-17 +* Add metadata to subscription items + +## 24.0.0 - 2017-06-27 + `Pay` on invoice now takes specific pay parameters + +## 23.2.1 - 2017-06-26 +* Fix bank account retrieval when using a customer ID + +## 23.2.0 - 2017-06-26 +* Support sharing path while creating a source + +## 23.1.0 - 2017-06-26 +* Add LoginLinks to client list + +## 23.0.0 - 2017-06-23 + plan.Del now takes `stripe.PlanParams` as a second argument + +## 22.6.0 - 2017-06-19 +* Support for ephemeral keys + +## 22.5.0 - 2017-06-15 +* Support for checking webhook signatures + +## 22.4.1 - 2017-06-15 +* Fix returned type of subscription items list +* Note: I meant to release this as 22.3.1, but I'm leaving it as it was released + +## 22.3.0 - 2017-06-14 +* Fix parameters for subscription items list + +## 22.2.0 - 2017-06-13 +* Support subscription items when getting upcoming invoice +* Support setting subscription's quantity to zero when getting upcoming invoice + +## 22.1.1 - 2017-06-12 +* Handle `deleted` parameter when updating subscription items in a subscription + +## 22.1.0 - 2017-05-25 +* Change `Logger` to a `log.Logger`-like interface so other loggers are usable + +## 22.0.0 - 2017-05-25 +* Add support for login links +* Add support for new `Type` for accounts +* Make `Event` `Request` (renamed from `Req`) a struct with a new idempotency key +* Rename `Event` `UserID` to `Account` + +## 21.5.1 - 2017-05-23 +* Fix plan update so `TrialPeriod` parameter is sent + +## 21.5.0 - 2017-05-15 +* Implement `Get` for `RequestValues` + +## 21.4.1 - 2017-05-11 +* Pass extra parameters to API calls on bank account deletion + +## 21.4.0 - 2017-05-04 +* Add `Billing` and `DueDate` filters to invoice listing +* Add `Billing` filter to subscription listing + +## 21.3.0 - 2017-05-02 +* Add `DetailsCode` to `IdentityVerification` + +## 21.2.0 - 2017-04-19 +* Send user agent information with `X-Stripe-Client-User-Agent` +* Add `stripe.SetAppInfo` for plugin authors to register app information + +## 21.1.0 - 2017-04-12 +* Allow coupon to be specified when creating orders +* No longer require that items have descriptions when creating orders + +## 21.0.0 - 2017-04-07 +* Balances are now retrieved by payout instead of by transfer + +## 20.0.0 - 2017-04-06 +* Bump API version to 2017-04-06: https://docs.stripe.com/changelog/2017-04-06 +* Add support for payouts and recipient transfers +* Change the transfer resource to support its new format +* Deprecate recipient creation +* Disputes under charges are now expandable and collapsed by default +* Rules under charge outcomes are now expandable and collapsed by default + +## 19.17.0 - 2017-04-06 +* Please see 20.0.0 (bad release) + +## 19.16.0 - 2017-03-23 +* Allow the ID of an identity document to be passed into an account owner update + +## 19.15.0 - 2017-03-22 +* Add `ShippingCarrier` to dispute evidence + +## 19.14.0 - 2017-03-20 +* Add `Period`, `Plan`, and `Quantity` to `InvoiceItem` + +## 19.13.0 - 2017-03-20 +* Add `AdditionalOwnersEmpty` to allow additional owners to be unset + +## 19.12.0 - 2017-03-17 +* Add new form of file upload using `io.FileReader` and filename + +## 19.11.0 - 2017-03-13 +* Add `Token` to `SourceObjectParams` + +## 19.10.0 - 2017-03-13 +* Add `CouponEmpty` (allowing a coupon to be cleared) to customer parameters +* Add `CouponEmpty` (allowing a coupon to be cleared) to subscription parameters + +## 19.9.0 - 2017-03-08 +* Add missing value "all" to subscription statuses + +## 19.8.0 - 2017-03-02 +* Add subscription items client to main `client.API` struct + +## 19.7.0 - 2017-03-01 +* Add `Statement` (statement descriptor) to `CaptureParams` + +## 19.6.0 - 2017-02-22 +* Add new parameters for invoices and subscriptions + +## 19.5.0 - 2017-02-13 +* Add new rich `Destination` type to `ChargeParams` + +## 19.4.0 - 2017-02-03 +* Support Connect account as payment source + +## 19.3.0 - 2017-02-02 +* Add transfer group to charges and transfers + +## 19.2.0 - 2017-01-23 +* Add `Rule` to `ChargeOutcome` + +## 19.1.0 - 2017-01-18 +* Add support for updating sources + +## 19.0.2 - 2017-01-04 +* Fix subscription `trial_period_days` to be populated by the right value + +## 19.0.1 - 2016-12-08 +* Include verification document details when persisting `LegalEntity` + +## 19.0.0 - 2016-12-07 +* Remote `SubProrationDateNow` field from `InvoiceParams` + +## 18.14.1 - 2016-12-05 +* Truncate `tax_percent` at four decimals (e.g. 3.9750%) instead of two + +## 18.14.0 - 2016-11-23 +* Add retrieve method for 3-D Secure resources + +## 18.13.0 - 2016-11-15 +* Add `PaymentSource` to `API` + +## 18.12.0 - 2016-11-14 +* Allow bank accounts to be created as a customer source + +## 18.11.0 - 2016-11-14 +* Add `TrialPeriodEnd` to `SubParams` + +## 18.10.0 - 2016-11-09 +* Add `StatusTransitions` to `Order` + +## 18.9.0 - 2016-11-04 +* Add `Application` to `Charge` + +## 18.8.0 - 2016-10-24 +* Add `Review` to `Charge` for the charge reviews + +## 18.7.0 - 2016-10-18 +* Add `RiskLevel` to `ChargeOutcome` + +## 18.6.0 - 2016-10-18 +* Support for 403 status codes (permission denied) + +## 18.5.0 - 2016-10-18 +* Add `Status` to `SubListParams` to allow filtering subscriptions by status + +## 18.4.0 - 2016-10-14 +* Add `HasEvidence` and `PastDue` to `EvidenceDetails` + +## 18.3.0 - 2016-10-10 +* Add `NoDiscountable` to `InvoiceItemParams` + +## 18.2.0 - 2016-10-10 +* Add `BusinessLogo` to `Account` +* Add `ReceiptNumber` to `Charge` +* Add `DestPayment` to `Transfer` + +## 18.1.0 - 2016-10-04 +* Support for Apple Pay domains + +## 18.0.0 - 2016-10-03 +* Support for subscription items +* Correct `SourceTx` on `Transfer` to be a `SourceTransaction` +* Change `Charge` on `Resource` to be expandable (now a struct instead of string) + +## 17.5.0 - 2016-09-22 +* Support customer-related operations for bank accounts + +## 17.4.2 - 2016-09-19 +* Fix but where some parameters were not being included on order update + +## 17.4.1 - 2016-09-15 +* Fix bug that required a date of birth to be included on account update + +## 17.4.0 - 2016-09-13 +* Add missing Kana and Kanji address and name fields to account's legal entity +* Add `ReceiptNumber` and `Status` to `Refund` + +## 17.3.0 - 2016-09-07 +* Add support for sources endpoint + +## 17.2.0 - 2016-08-29 +* Add order returns to `API` + +## 17.1.0 - 2016-08-22 +* Add `DeactiveOn` to `Product` + +## 17.0.0 - 2016-08-18 +* Allow expansion of destination on transfers +* Allow expansion of sources on balance transactions + +## 16.8.0 - 2016-08-17 +* Add `OriginatingTransaction` to `Fee` + +## 16.7.1 - 2016-08-17 +* Allow params to be nil when retrieving a refund + +## 16.7.0 - 2016-08-11 +* Add support for 3-D Secure + +## 16.6.0 - 2016-08-09 +* Add `ReceiptNumber` to `Invoice` + +## 16.5.0 - 2016-08-08 +* Add `Meta` to `Account` + +## 16.4.0 - 2016-08-05 +* Allow the migration of recipients to accounts +* Add `MigratedTo` to `Recipient` + +## 16.3.1 - 2016-07-25 +* URL-escape the IDs of coupons and plans when making API requests + +## 16.3.0 - 2016-07-19 +* Add `NoClosed` to `InvoiceParams` to allow an invoice to be reopened + +## 16.2.1 - 2016-07-11 +* Consider `SubParams.QuantityZero` when updating a subscription + +## 16.2.0 - 2016-07-07 +* Upgrade API version to 2016-07-06 + +## 16.1.0 - 2016-07-07 +* Add `Returns` field to `Order` + +## 16.0.0 - 2016-06-30 +* Remove `Name` field on `SKU`; it's not actually supported +* Support updating `Product` on `SKU` + +## 15.6.0 - 2016-06-24 +* Allow product and SKU attributes to be updated + +## 15.5.0 - 2016-06-24 +* Add `TaxPercent` and `TaxPercentZero` to `CustomerParams` + +## 15.4.0 - 2016-06-20 +* Add `TokenizationMethod` to `Card` struct + +## 15.3.0 - 2016-06-15 +* Add `BalanceZero` to `CustomerParams` so that balance can be zeroed out + +## 15.2.0 - 2016-06-03 +* Add `ToValues` to `RequestValues` struct + +## 15.1.0 - 2016-05-26 +* Add `BusinessVatID` to customer creation parameters + +## 15.0.0 - 2016-05-24 +* Fix handling of nested objects in arrays in request parameters + +## 14.4.0 - 2016-05-24 +* Add granular error types in new `Err` field on `stripe.Error` + +## 14.3.0 - 2016-05-20 +* Allow Relay orders to be returned and add associated types + +## 14.2.3 - 2016-05-20 +* When creating a bank account token, only send routing number if it's been set + +## 14.2.2 - 2016-05-17 +* When creating a bank account, only send routing number if it's been set + +## 14.2.1 - 2016-05-17 +* Add missing SKU clinet to client API type + +## 14.2.0 - 2016-05-11 +* Add `Reversed` and `AmountReversed` fields to `Transfer` + +## 14.1.0 - 2016-05-05 +* Allow `default_for_currency` to be set when creating a card + +## 14.0.0 - 2016-05-04 +* Change the signature for `sub.Delete`. The customer ID is no longer required. + +## 13.12.0 - 2016-04-28 +* Add `Currency` to `Card` + +## 13.11.1 - 2016-04-22 +* Fix bug where new external accounts could not be marked default from token + +## 13.11.0 - 2016-04-21 +* Expose a number of list types that were previously internal (full list below) +* Expose `stripe.AccountList` +* Expose `stripe.TransactionList` +* Expose `stripe.BitcoinReceiverList` +* Expose `stripe.ChargeList` +* Expose `stripe.CountrySpecList` +* Expose `stripe.CouponList` +* Expose `stripe.CustomerList` +* Expose `stripe.DisputeList` +* Expose `stripe.EventList` +* Expose `stripe.FeeList` +* Expose `stripe.FileUploadList` +* Expose `stripe.InvoiceList` +* Expose `stripe.OrderList` +* Expose `stripe.ProductList` +* Expose `stripe.RecipientList` +* Expose `stripe.TransferList` +* Switch to use of `stripe.BitcoinTransactionList` +* Switch to use of `stripe.SKUList` + +## 13.10.1 - 2016-04-20 +* Add support for `TaxPercentZero` to invoice and subscription updates + +## 13.10.0 - 2016-04-19 +* Expose `stripe.PlanList` (previously an internal type) + +## 13.9.0 - 2016-04-18 +* Add `TaxPercentZero` struct to `InvoiceParams` +* Add `TaxPercentZero` to `SubParams` + +## 13.8.0 - 2016-04-12 +* Add `Outcome` struct to `Charge` + +## 13.7.0 - 2016-04-06 +* Add `Description`, `IIN`, and `Issuer` to `Card` + +## 13.6.0 - 2016-04-05 +* Add `SourceType` (and associated constants) to `Transfer` + +## 13.5.0 - 2016-03-29 +* Add `Meta` (metadata) to `BankAccount` + +## 13.4.0 - 2016-03-29 +* Add `Meta` (metadata) to `Card` + +## 13.3.0 - 2016-03-29 +* Add `DefaultCurrency` to `CountrySpec` + +## 13.2.0 - 2016-03-18 +* Add `SourceTransfer` to `Charge` +* Add `SourceTx` to `Transfer` + +## 13.1.0 - 2016-03-15 +* Add `Reject` on `Account` to support the new API feature + +## 13.0.0 - 2016-03-15 +* Upgrade API version to 2016-03-07 +* Remove `Account.BankAccounts` in favor of `ExternalAccounts` +* Remove `Account.Currencies` in favor of `CountrySpec` + +## 12.1.0 - 2016-02-04 +* Add `ListParams.StripeAccount` for making list calls on behalf of connected accounts +* Add `Params.StripeAccount` for symmetry with `ListParams.StripeAccount` +* Deprecate `Params.Account` in favor of `Params.StripeAccount` + +## 12.0.0 - 2016-02-02 +* Add support for fetching events for managed accounts (`event.Get` now takes `Params`) + +## 11.5.0 - 2016-02-26 +* Allow a `PII.PersonalIDNumber` number to be used to create a token + +## 11.4.0 - 2016-02-24 +* Add missing subscription fields to `InvoiceParams` for use with `invoice.GetNext` + +## 11.3.0 - 2016-02-19 +* Add `AccountHolderName` and `AccountHolderType` to bank accounts + +## 11.2.0 - 2016-02-11 +* Add support for `CountrySpec` +* Add `SSNProvided`, `PersonalIDProvided` and `BusinessTaxIDProvided` to `LegalEntity` + +## 11.1.2 - 2016-02-02 +* Fix card update method to correctly take expiration date + +## 11.1.1 - 2016-02-01 +* Fix recipient update so that it can take a bank token (like create) + +## 11.0.1 - 2016-01-11 +* Add missing field `country` to shipping details of `Charge` and `Customer` + +## 11.0.0 - 2016-01-07 +* Add missing field `Default` to `BankAccount` +* Add `OrderParams` parameter to `Order` retrieval +* Fix parameter bug when creating a new `Order` +* Support special value of 'now' for trial end when updating subscriptions + +## 10.3.0 - 2015-12-10 +* Allow an account to be referenced when creating a card + +## 10.2.0 - 2015-12-04 +* Add `Update` function on `Coupon` client so that metadata can be set + +## 10.1.0 - 2015-12-01 +* Add a verification routine for external accounts + +## 10.0.0 - 2015-11-30 +* Return models along with `error` when deleting resources with `Del` +* Fix bug where country parameter wasn't included for some account creation + +## 9.0.0 - 2015-11-13 +* Return model (`Sub`) when cancelling a subscription (`sub.Cancel`) + +## 8.0.0 - 2015-08-17 +* Add ability to list and retrieve refunds without a Charge + +## 7.0.0 - 2015-08-03 +* Add ability to list and retrieve disputes + +## 6.8.0 - 2015-07-29 +* Add ability to delete an account + +## 6.7.1 - 2015-07-17 +* Bug fixes + +## 6.7.0 - 2015-07-16 +* Expand logging object +* Move proration date to subscription update +* Send country when creating/updating account + +## 6.6.0 - 2015-07-06 +* Add request ID to errors + +## 6.5.0 - 2015-07-06 +* Update bank account creation API +* Add destination, application fee, transfer to Charge struct +* Add missing fields to invoice line item +* Rename deprecated customer param value + +## 6.4.2 - 2015-06-23 +* Add BusinessUrl, BusinessUrl, BusinessPrimaryColor, SupportEmail, and +* SupportUrl to Account. + +## 6.4.1 - 2015-06-16 +* Change card.dynamic_last_four to card.dynamic_last4 + +## 6.4.0 - 2015-05-28 +* Rename customer.default_card -> default_source + +## 6.3.0 - 2015-05-19 +* Add shipping address to charges +* Expose card.dynamic_last_four +* Expose account.tos_acceptance +* Bug fixes +* Bump API version to most recent one + +## 6.2.0 - 2015-04-09 +* Bug fixes +* Add Extra to parameters + +## 6.1.0 - 2015-03-17 +* Add TaxPercent for subscriptions +* Event bug fixes + +## 6.0.0 - 2015-03-15 +* Add more operations for /accounts endpoint +* Add /transfers/reversals endpoint +* Add /accounts/bank_accounts endpoint +* Add support for Stripe-Account header + +## 5.1.0 - 2015-02-25 +* Add new dispute status `warning_closed` +* Add SubParams.TrialEndNow to support `trial_end = "now"` + +## 5.0.1 - 2015-02-25 +* Fix URL for upcoming invoices + +## 5.0.0 - 2015-02-19 +* Bump to API version 2014-02-18 +* Change Card, DefaultCard, Cards to Source, DefaultSource, Sources in Stripe response objects +* Add paymentsource package for manipulating Customer's sources +* Support Update action for Bitcoin Receivers + +## 4.4.3 - 2015-02-08 +* Modify NewIdempotencyKey() algorithm to increase likelihood of randomness + +## 4.4.2 - 2015-01-24 +* Add BankAccountParams.Token +* Add Token.ClientIP +* Add LogLevel + +## 4.4.0 - 2015-01-20 +* Add Bitcoin support + +## 4.3.0 - 2015-01-13 +* Added support for listing FileUploads +* Mime parameter on FileUpload has been changed to Type + +## 4.2.1 - 2014-12-28 +* Handle charges with customer card tokens + +## 4.2.0 - 2014-12-18 +* Add idempotency support + +## 4.1.0 - 2014-12-17 +* Bump to API version 2014-12-17. + +## 4.0.0 - 2014-12-16 +* Add FileUpload resource. This brings in a new endpoint (uploads.stripe.com) and thus makes changes to some of the existing interfaces. +* This also adds support for multipart content. + +## 3.1.0 - 2014-12-16 +* Add Charge.FraudDetails + +## 3.0.1 - 2014-12-15 +* Add timeout value to HTTP requests + +## 3.0.0 - 2014-12-05 +* Add Dispute.EvidenceDetails +* Remove Dispute.DueDate +* Change Dispute.Evidence from string to struct + +## 2.0.0 - 2014-11-26 +* Change List interface to .Next() and .Resource() +* Better error messages for Get() methods +* EventData.Raw contains the raw event message +* SubParams.QuantityZero can be used for free subscriptions + +## 1.0.3 - 2014-10-22 +* Add AddMeta method + +## 1.0.2 - 2014-09-23 +* Minor fixes + +## 1.0.1 - 2014-09-23 +* Linter-based updates + +## 1.0.0 - 2014-09-22 +* Initial version diff --git a/vendor/github.com/stripe/stripe-go/v82/CODE_OF_CONDUCT.md b/vendor/github.com/stripe/stripe-go/v82/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..349f5a0b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/CODE_OF_CONDUCT.md @@ -0,0 +1,77 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to make participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies within all project spaces, and it also applies when +an individual is representing the project or its community in public spaces. +Examples of representing a project or community include using an official +project e-mail address, posting via an official social media account, or acting +as an appointed representative at an online or offline event. Representation of +a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at conduct@stripe.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq + diff --git a/vendor/github.com/stripe/stripe-go/v82/CONTRIBUTING.md b/vendor/github.com/stripe/stripe-go/v82/CONTRIBUTING.md new file mode 100644 index 00000000..ac784b8d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/CONTRIBUTING.md @@ -0,0 +1,25 @@ + +# Contributing + +We welcome bug reports, feature requests, and code contributions in a pull request. + +For most pull requests, we request that you identify or create an associated issue that has the necessary context. We use these issues to reach agreement on an approach and save the PR author from having to redo work. Fixing typos or documentation issues likely do not need an issue; for any issue that introduces substantial code changes, changes the public interface, or if you aren't sure, please find or [create an issue](https://www.github.com/stripe/stripe-go/issues/new/choose). + +## Contributor License Agreement + +All contributors must sign the Contributor License Agreement (CLA) before we can accept their contribution. If you have not yet signed the agreement, you will be given an option to do so when you open a pull request. You can then sign by clicking on the badge in the comment from @CLAassistant. + +## Generated code + +This project has a combination of manually maintained code and code generated from our private code generator. If your contribution involves changes to generated code, please call this out in the issue or pull request as we will likely need to make a change to our code generator before accepting the contribution. + +To identify files with purely generated code, look for the comment `File generated from our OpenAPI spec.` at the start of the file. Generated blocks of code within hand-written files will be between comments that say `The beginning of the section generated from our OpenAPI spec` and `The end of the section generated from our OpenAPI spec`. + +## Compatibility with supported language and runtime versions + +This project supports [many different langauge and runtime versions](README.md#requirements) and we are unable to accept any contribution that does not work on _all_ supported versions. If, after discussing the approach in the associated issue, your change must use an API / feature that isn't available in all supported versions, please call this out explicitly in the issue or pull request so we can help figure out the best way forward. + +## Set up your dev environment + +Please refer to this project's [README.md](README.md#development) for instructions on how to set up your development environment. + diff --git a/vendor/github.com/stripe/stripe-go/v82/LICENSE b/vendor/github.com/stripe/stripe-go/v82/LICENSE new file mode 100644 index 00000000..2754f88e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014- Stripe, Inc. (https://stripe.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/stripe/stripe-go/v82/Makefile b/vendor/github.com/stripe/stripe-go/v82/Makefile new file mode 100644 index 00000000..38c31d95 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/Makefile @@ -0,0 +1,49 @@ +# NOTE: this file is deprecated and slated for deletion; prefer using the equivalent `just` commands. + +all: test bench vet lint check-gofmt ci-test + +bench: + go test -race -bench . -run "Benchmark" ./form + +build: + go build ./... + +check-gofmt: + scripts/gofmt.sh check + +lint: + staticcheck + +test: + go run scripts/test_with_stripe_mock/main.go -race ./... + +ci-test: test bench +vet: + go vet ./... + +coverage: + go run scripts/test_with_stripe_mock/main.go -covermode=count -coverprofile=combined.coverprofile ./... + +coveralls: + go install github.com/mattn/goveralls@latest && $(HOME)/go/bin/goveralls -service=github -coverprofile=combined.coverprofile + +clean: + find . -name \*.coverprofile -delete + +MAJOR_VERSION := $(shell echo $(VERSION) | sed 's/\..*//') +update-version: + @echo "$(VERSION)" > VERSION + @perl -pi -e 's|const clientversion = "[.\d\-\w]+"|const clientversion = "$(VERSION)"|' stripe.go + @perl -pi -e 's|github.com/stripe/stripe-go/v\d+|github.com/stripe/stripe-go/v$(MAJOR_VERSION)|' README.md + $(MAKE) normalize-imports + +codegen-format: normalize-imports + scripts/gofmt.sh + go install golang.org/x/tools/cmd/goimports@v0.24.0 && goimports -w example/generated_examples_test.go + +CURRENT_MAJOR_VERSION := $(shell cat VERSION | sed 's/\..*//') +normalize-imports: + @perl -pi -e 's|github.com/stripe/stripe-go/v\d+|github.com/stripe/stripe-go/v$(CURRENT_MAJOR_VERSION)|' go.mod + @find . -name '*.go' -exec perl -pi -e 's|github.com/stripe/stripe-go/(v\d+\|\[MAJOR_VERSION\])|github.com/stripe/stripe-go/v$(CURRENT_MAJOR_VERSION)|' {} + + +.PHONY: codegen-format update-version normalize-imports diff --git a/vendor/github.com/stripe/stripe-go/v82/OPENAPI_VERSION b/vendor/github.com/stripe/stripe-go/v82/OPENAPI_VERSION new file mode 100644 index 00000000..d8931ef8 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/OPENAPI_VERSION @@ -0,0 +1 @@ +v1819 \ No newline at end of file diff --git a/vendor/github.com/stripe/stripe-go/v82/README.md b/vendor/github.com/stripe/stripe-go/v82/README.md new file mode 100644 index 00000000..52a0f84a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/README.md @@ -0,0 +1,663 @@ +# Go Stripe + +[![Go Reference](https://pkg.go.dev/badge/github.com/stripe/stripe-go)](https://pkg.go.dev/github.com/stripe/stripe-go/v82) +[![Build Status](https://github.com/stripe/stripe-go/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/stripe/stripe-go/actions/workflows/ci.yml?query=branch%3Amaster) + +The official [Stripe][stripe] Go client library. + +## Requirements + +- Go 1.18 or later + +## Installation + +Make sure your project is using Go Modules (it will have a `go.mod` file in its +root if it already is): + +```sh +go mod init +``` + +Then, reference stripe-go in a Go program with `import`: + +```go +import ( + "github.com/stripe/stripe-go/v82" + "github.com/stripe/stripe-go/v82/customer" +) +``` + +Run any of the normal `go` commands (`build`/`install`/`test`). The Go +toolchain will resolve and fetch the stripe-go module automatically. + +Alternatively, you can also explicitly `go get` the package into a project: + +```bash +go get -u github.com/stripe/stripe-go/v82 +``` + +## Documentation + +For a comprehensive list of examples, check out the [API +documentation][api-docs]. + +For details on all the functionality in this library, see the [Go +documentation][goref]. + +Below are a few simple examples: + +### Customers + +```go +sc := stripe.NewClient(apiKey) +params := &stripe.CustomerCreateParams{ + Description: stripe.String("Stripe Developer"), + Email: stripe.String("gostripe@stripe.com"), + PreferredLocales: stripe.StringSlice([]string{"en", "es"}), +} + +c, err := sc.V1Customers.Create(context.TODO(), params) +``` + +### PaymentIntents + +```go +sc := stripe.NewClient(apiKey) +params := &stripe.PaymentIntentListParams{ + Customer: stripe.String(customer.ID), +} + +for pi, err := range sc.V1PaymentIntents.List(context.TODO(), params) { + // handle err + // do something +} +``` + +### Events + +```go +sc := stripe.NewClient(apiKey) +for e, err := range sc.V1Events.List(context.TODO(), nil) { + // access event data via e.GetObjectValue("resource_name_based_on_type", "resource_property_name") + // alternatively you can access values via e.Data.Object["resource_name_based_on_type"].(map[string]interface{})["resource_property_name"] + + // access previous attributes via e.GetPreviousValue("resource_name_based_on_type", "resource_property_name") + // alternatively you can access values via e.Data.PreviousAttributes["resource_name_based_on_type"].(map[string]interface{})["resource_property_name"] +} +``` + +Alternatively, you can use the `event.Data.Raw` property to unmarshal to the +appropriate struct. + +### Authentication with Connect + +There are two ways of authenticating requests when performing actions on behalf +of a connected account, one that uses the `Stripe-Account` header containing an +account's ID, and one that uses the account's keys. Usually the former is the +recommended approach. [See the documentation for more information][connect]. + +To use the `Stripe-Account` approach, use `SetStripeAccount()` on a `ListParams` +or `Params` class. For example: + +```go +// For a list request +listParams := &stripe.CustomerListParams{} +listParams.SetStripeAccount("acct_123") +``` + +To use a key, pass it into `stripe.NewClient`: + +```go +import ( + "github.com/stripe/stripe-go/v82" +) + +sc := stripe.NewClient("access_token") +``` + +### Google AppEngine + +If you're running the client in a Google AppEngine environment, you'll need to +create a per-request Stripe client since the `http.DefaultClient` is not +available. Here's a sample handler: + +```go +import ( + "fmt" + "net/http" + + "google.golang.org/appengine" + "google.golang.org/appengine/urlfetch" + + "github.com/stripe/stripe-go/v82" +) + +func handler(w http.ResponseWriter, r *http.Request) { + ctx := appengine.NewContext(r) + httpClient := urlfetch.Client(ctx) + + backends := stripe.NewBackends(httpClient) + sc := stripe.NewClient("sk_test_123", stripe.WithBackends(backends)) + + params := &stripe.CustomerCreateParams{ + Description: stripe.String("Stripe Developer"), + Email: stripe.String("gostripe@stripe.com"), + } + customer, err := sc.V1Customers.Create(ctx, params) + if err != nil { + fmt.Fprintf(w, "Could not create customer: %v", err) + return + } + fmt.Fprintf(w, "Customer created: %v", customer.ID) +} +``` + +## Usage + +While some resources may contain more/less APIs, the following pattern is +applied throughout the library for a given resource (like `Customer`). + +### With Stripe Client +The recommended pattern to access all Stripe resources is using `stripe.Client`. Below are some examples of how to use it to access the `Customer` resource. + +```go +import "github.com/stripe/stripe-go/v82" + +// Setup +sc := stripe.NewClient("sk_key") +// To set backends, e.g. for testing, or to customize use this instead: +// sc := stripe.NewClient("sk_key", stripe.WithBackends(backends)) + +// Create +c, err := sc.V1Customers.Create(context.TODO(), &stripe.CustomerCreateParams{}) + +// Retrieve +c, err := sc.V1Customers.Retrieve(context.TODO(), id, &stripe.CustomerRetrieveParams{}) + +// Update +c, err := sc.V1Customers.Update(context.TODO(), id, &stripe.CustomerUpdateParams{}) + +// Delete +c, err := sc.V1Customers.Delete(context.TODO(), id, &stripe.CustomerDeleteParams{}) + +// List +for c, err := range sc.Customers.List(context.TODO(), &stripe.CustomerListParams{}) { + // handle err + // do something +} +``` + +### `stripe.Client` vs legacy `client.API` pattern +We introduced `stripe.Client` in v82.1 of the Go SDK. The legacy client pattern used prior to that version (using `client.API`) is still available to use but is marked as deprecated. Review the [migration guide to use stripe.Client](https://github.com/stripe/stripe-go/wiki/Migration-guide-for-Stripe-Client) to help you move from the legacy pattern to `stripe.Client`. + +### Without a Client (Legacy) + +The legacy pattern to access Stripe APIs is the "resource pattern" shown below. We plan to deprecate this pattern in a future release. Note also that Stripe's V2 APIs are not supported by this pattern. + +```go +import ( + "github.com/stripe/stripe-go/v82" + "github.com/stripe/stripe-go/v82/customer" +) + +// Setup +stripe.Key = "sk_key" + +// Set backend (optional, useful for mocking) +// stripe.SetBackend("api", backend) + +// Create +c, err := customer.New(&stripe.CustomerParams{}) + +// Get +c, err := customer.Get(id, &stripe.CustomerParams{}) + +// Update +c, err := customer.Update(id, &stripe.CustomerParams{}) + +// Delete +c, err := customer.Del(id, &stripe.CustomerParams{}) + +// List +i := customer.List(&stripe.CustomerListParams{}) +for i.Next() { + c := i.Customer() + // do something +} + +if err := i.Err(); err != nil { + // handle +} +``` +## Other usage patterns + +### Accessing the Last Response + +Use `LastResponse` on any `APIResource` to look at the API response that +generated the current object: + +```go +coupon, err := sc.V1Coupons.Create(...) +requestID := coupon.LastResponse.RequestID +``` + +See the definition of [`APIResponse`][apiresponse] for available fields. + +Note that where API resources are nested in other API resources, only +`LastResponse` on the top-level resource is set. + +### Automatic Retries + +The library automatically retries requests on intermittent failures like on a +connection error, timeout, or on certain API responses like a status `409 +Conflict`. [Idempotency keys][idempotency-keys] are always added to requests to +make any such subsequent retries safe. + +By default, it will perform up to two retries. That number can be configured +with `MaxNetworkRetries`: + +```go +import ( + "github.com/stripe/stripe-go/v82" +) + +config := &stripe.BackendConfig{ + MaxNetworkRetries: stripe.Int64(0), // Zero retries +} + +backends := &stripe.NewBackendWithConfig(config) +sc := stripe.NewClient("sk_key", stripe.WithBackends(backends)) +coupon, err := sc.V1Coupons.Create(...) +``` + +### Configuring Logging + +By default, the library logs error messages only (which are sent to `stderr`). +Configure default logging using the global `DefaultLeveledLogger` variable: + +```go +stripe.DefaultLeveledLogger = &stripe.LeveledLogger{ + Level: stripe.LevelInfo, +} +``` + +Or on a per-backend basis: + +```go +config := &stripe.BackendConfig{ + LeveledLogger: &stripe.LeveledLogger{ + Level: stripe.LevelInfo, + }, +} +``` + +It's possible to use non-Stripe leveled loggers as well. Stripe expects loggers +to comply to the following interface: + +```go +type LeveledLoggerInterface interface { + Debugf(format string, v ...interface{}) + Errorf(format string, v ...interface{}) + Infof(format string, v ...interface{}) + Warnf(format string, v ...interface{}) +} +``` + +Some loggers like [Logrus][logrus] and Zap's [SugaredLogger][zapsugaredlogger] +support this interface out-of-the-box so it's possible to set +`DefaultLeveledLogger` to a `*logrus.Logger` or `*zap.SugaredLogger` directly. +For others it may be necessary to write a thin shim layer to support them. + +### Expanding Objects + +All [expandable objects][expandableobjects] in stripe-go take the form of a +full resource struct, but unless expansion is requested, only the `ID` field of +that struct is populated. Expansion is requested by calling `AddExpand` on +parameter structs. For example: + +```go +// +// *Without* expansion +// +c, _ := sc.V1Charges.Retrieve(context.TODO(), "ch_123", nil) + +c.Customer.ID // Only ID is populated +c.Customer.Name // All other fields are always empty + +// +// With expansion +// +p := &stripe.ChargeCreateParams{} +p.AddExpand("customer") +c, _ = sc.V1Charges.Retrieve(context.TODO(), "ch_123", p) + +c.Customer.ID // ID is still available +c.Customer.Name // Name is now also available (if it had a value) +``` + +### How to use undocumented parameters and properties + +stripe-go is a typed library and it supports all public properties or parameters. + +Stripe sometimes launches private beta features which introduce new properties or parameters that are not immediately public. These will not have typed accessors in the stripe-go library but can still be used. + +#### Parameters + +To pass undocumented parameters to Stripe using stripe-go you need to use the `AddExtra()` method, as shown below: + +```go +params := &stripe.CustomerCreateParams{ + Email: stripe.String("jenny.rosen@example.com") +} +params.AddExtra("secret_feature_enabled", "true") +params.AddExtra("secret_parameter[primary]","primary value") +params.AddExtra("secret_parameter[secondary]","secondary value") + +customer, err := sc.V1Customer.Create(context.TODO(), params) +``` + +#### Properties + +You can access undocumented properties returned by Stripe by querying the raw response JSON object. An example of this is shown below: + +```go +customer, _ = sc.V1Charges.Retrieve(context.TODO(), "cus_1234", nil); + +var rawData map[string]interface{} +_ = json.Unmarshal(customer.LastResponse.RawJSON, &rawData) + +secretFeatureEnabled, _ := string(rawData["secret_feature_enabled"].(bool)) + +secretParameter, ok := rawData["secret_parameter"].(map[string]interface{}) +if ok { + primary := secretParameter["primary"].(string) + secondary := secretParameter["secondary"].(string) +} +``` + +### Webhook signing + +Stripe can optionally sign the webhook events it sends to your endpoint, allowing you to validate that they were not sent by a third-party. You can read more about it [here](https://stripe.com/docs/webhooks/signatures). + +#### Testing Webhook signing + +You can use `stripe.GenerateTestSignedPayload` to mock webhook events that come from Stripe: + +```go +payload := map[string]interface{}{ + "id": "evt_test_webhook", + "object": "event", + "api_version": stripe.APIVersion, +} +testSecret := "whsec_test_secret" + +payloadBytes, err := json.Marshal(payload) + +signedPayload := stripe.GenerateTestSignedPayload(&webhook.UnsignedPayload{Payload: payloadBytes, Secret: testSecret}) +event, err := stripe.ConstructEvent(signedPayload.Payload, signedPayload.Header, signedPayload.Secret) + +if event.ID == payload["id"] { + // Do something with the mocked signed event +} else { + // Handle invalid event payload +} +``` + +### Writing a Plugin + +If you're writing a plugin that uses the library, we'd appreciate it if you +identified using `stripe.SetAppInfo`: + +```go +stripe.SetAppInfo(&stripe.AppInfo{ + Name: "MyAwesomePlugin", + URL: "https://myawesomeplugin.info", + Version: "1.2.34", +}) +``` + +This information is passed along when the library makes calls to the Stripe +API. Note that while `Name` is always required, `URL` and `Version` are +optional. + +### Telemetry + +By default, the library sends telemetry to Stripe regarding request latency and feature usage. These +numbers help Stripe improve the overall latency of its API for all users, and +improve popular features. + +You can disable this behavior if you prefer: + +```go +config := &stripe.BackendConfig{ + EnableTelemetry: stripe.Bool(false), +} +``` + +### Mocking clients for unit tests + +To mock a Stripe client for a unit tests using [GoMock](https://github.com/golang/mock): + +1. Generate a `Backend` type mock. + +``` +mockgen -destination=mocks/backend.go -package=mocks github.com/stripe/stripe-go/v82 Backend +``` + +2. Use the `Backend` mock to initialize and call methods on the client. + +```go + +import ( + "example/hello/mocks" + "testing" + + "github.com/golang/mock/gomock" + "github.com/stretchr/testify/assert" + "github.com/stripe/stripe-go/v82" +) + +func UseMockedStripeClient(t *testing.T) { + // Create a mock controller + mockCtrl := gomock.NewController(t) + defer mockCtrl.Finish() + // Create a mock stripe backend + mockBackend := mocks.NewMockBackend(mockCtrl) + backends := &stripe.Backends{API: mockBackend} + client := stripe.NewClient("sk_test", stripe.WithBackends(backends)) + + // Set up a mock call + mockBackend.EXPECT().Call("GET", "/v1/accounts/acc_123", gomock.Any(), gomock.Any(), gomock.Any()). + // Return nil error + Return(nil). + Do(func(method string, path string, key string, params stripe.ParamsContainer, v *stripe.Account) { + // Set the return value for the method + *v = stripe.Account{ + ID: "acc_123", + } + }).Times(1) + + // Call the client method + acc, _ := client.V1Accounts.GetByID(context.TODO(), "acc_123", nil) + + // Asset the result + assert.Equal(t, "acc_123", acc.ID) +} +``` + +### Public Preview SDKs + +Stripe has features in the [public preview phase](https://docs.stripe.com/release-phases) that can be accessed via versions of this package that have the `-beta.X` suffix like `82.2.0-beta.2`. +We would love for you to try these as we incrementally release new features and improve them based on your feedback. + +To install, choose the version that includes support for the preview feature you are interested in by reviewing the [releases page](https://github.com/stripe/stripe-go/releases/) and use it in your `go.mod` file: + +``` +require ( + ... + github.com/stripe/stripe-go/v82 + ... +) +``` + +> **Note** +> There can be breaking changes between two versions of the public preview SDKs without a bump in the major version. + +Some preview features require a name and version to be set in the `Stripe-Version` header like `feature_beta=v3`. If your preview feature has this requirement, use the `stripe.AddBetaVersion` function (available only in the public preview SDKs): + +```go +stripe.AddBetaVersion("feature_beta", "v3") +``` + +### Custom Request + +If you would like to send a request to an API that is: + +- undocumented (like a preview feature), or +- you prefer to bypass the method definitions in the library and specify your request details directly + +You can use the `rawrequest` package: + +```go +import ( + "encoding/json" + "fmt" + + "github.com/stripe/stripe-go/v82" + "github.com/stripe/stripe-go/v82/form" + "github.com/stripe/stripe-go/v82/rawrequest" +) + +func make_raw_request() error { + stripe.Key = "sk_test_123" + + b, err := stripe.GetRawRequestBackend(stripe.APIBackend) + if err != nil { + return err + } + + client := rawrequest.Client{B: b, Key: apiKey} + + payload := map[string]interface{}{ + "event_name": "hotdogs_eaten", + "payload": map[string]string{ + "value": "123", + "stripe_customer_id": "cus_Quq8itmW58RMet", + }, + } + + // for a v2 request, json encode the payload + body, err := json.Marshal(payload) + if err != nil { + return err + } + + v2_resp, err := client.RawRequest(http.MethodPost, "/v2/billing/meter_events", string(body), nil) + if err != nil { + return err + } + + var v2_response map[string]interface{} + err = json.Unmarshal(v2_resp.RawJSON, &v2_response) + if err != nil { + return err + } + fmt.Printf("%#v\n", v2_response) + + // for a v1 request, form encode the payload + formValues := &form.Values{} + form.AppendTo(formValues, payload) + content := formValues.Encode() + + v1_resp, err := client.RawRequest(http.MethodPost, "/v1/billing/meter_events", content, nil) + if err != nil { + return err + } + + var v1_response map[string]interface{} + err = json.Unmarshal(v1_resp.RawJSON, &v1_response) + if err != nil { + return err + } + fmt.Printf("%#v\n", v1_response) + + return nil +} + +``` + +See more examples in the [/example/v2 folder](example/v2). + +## Support + +New features and bug fixes are released on the latest major version of the Stripe Go client library. If you are on an older major version, we recommend that you upgrade to the latest in order to use the new features and bug fixes including those for security vulnerabilities. Older major versions of the package will continue to be available for use, but will not be receiving any updates. + +## Development + +Pull requests from the community are welcome. If you submit one, please keep +the following guidelines in mind: + +1. Code must be `go fmt` compliant. +2. All types, structs and funcs should be documented. +3. Ensure that `just test` succeeds. + +[Other contribution guidelines for this project](CONTRIBUTING.md) + +## Test + +We use [just](https://github.com/casey/just) for conveniently running development tasks. You can use them directly, or copy the commands out of the `justfile`. To our help docs, run `just`. + +This package depends on [stripe-mock][stripe-mock], so make sure to fetch and run it from a +background terminal ([stripe-mock's README][stripe-mock-usage] also contains +instructions for installing via Homebrew and other methods): + + go get -u github.com/stripe/stripe-mock + stripe-mock + +Run all tests: + +```sh +just test +# or: go test ./... +``` + +Run tests for one package: + +```sh +just test ./invoice +# or: go test ./invoice +``` + +Run a single test: + +```sh +just test ./invoice -run TestInvoiceGet +# or: go test ./invoice -run TestInvoiceGet +``` + +For any requests, bug or comments, please [open an issue][issues] or [submit a +pull request][pulls]. + +[api-docs]: https://stripe.com/docs/api/?lang=go +[api-changelog]: https://stripe.com/docs/upgrades +[apiresponse]: https://godoc.org/github.com/stripe/stripe-go#APIResponse +[connect]: https://stripe.com/docs/connect/authentication +[depgomodsupport]: https://github.com/golang/dep/pull/1963 +[expandableobjects]: https://stripe.com/docs/api/expanding_objects +[goref]: https://pkg.go.dev/github.com/stripe/stripe-go +[gomodrevert]: https://github.com/stripe/stripe-go/pull/774 +[gomodvsdep]: https://github.com/stripe/stripe-go/pull/712 +[idempotency-keys]: https://stripe.com/docs/api/idempotent_requests?lang=go +[issues]: https://github.com/stripe/stripe-go/issues/new +[logrus]: https://github.com/sirupsen/logrus/ +[modules]: https://github.com/golang/go/wiki/Modules +[package-management]: https://code.google.com/p/go-wiki/wiki/PackageManagementTools +[pulls]: https://github.com/stripe/stripe-go/pulls +[stripe]: https://stripe.com +[stripe-mock]: https://github.com/stripe/stripe-mock +[stripe-mock-usage]: https://github.com/stripe/stripe-mock#usage +[zapsugaredlogger]: https://godoc.org/go.uber.org/zap#SugaredLogger + + diff --git a/vendor/github.com/stripe/stripe-go/v82/VERSION b/vendor/github.com/stripe/stripe-go/v82/VERSION new file mode 100644 index 00000000..8a36784b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/VERSION @@ -0,0 +1 @@ +82.3.0 diff --git a/vendor/github.com/stripe/stripe-go/v82/account.go b/vendor/github.com/stripe/stripe-go/v82/account.go new file mode 100644 index 00000000..36940375 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/account.go @@ -0,0 +1,4024 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "encoding/json" + "github.com/stripe/stripe-go/v82/form" +) + +// Whether the business is a minority-owned, women-owned, and/or LGBTQI+-owned business. +type AccountBusinessProfileMinorityOwnedBusinessDesignation string + +// List of values that AccountBusinessProfileMinorityOwnedBusinessDesignation can take +const ( + AccountBusinessProfileMinorityOwnedBusinessDesignationLgbtqiOwnedBusiness AccountBusinessProfileMinorityOwnedBusinessDesignation = "lgbtqi_owned_business" + AccountBusinessProfileMinorityOwnedBusinessDesignationMinorityOwnedBusiness AccountBusinessProfileMinorityOwnedBusinessDesignation = "minority_owned_business" + AccountBusinessProfileMinorityOwnedBusinessDesignationNoneOfTheseApply AccountBusinessProfileMinorityOwnedBusinessDesignation = "none_of_these_apply" + AccountBusinessProfileMinorityOwnedBusinessDesignationPreferNotToAnswer AccountBusinessProfileMinorityOwnedBusinessDesignation = "prefer_not_to_answer" + AccountBusinessProfileMinorityOwnedBusinessDesignationWomenOwnedBusiness AccountBusinessProfileMinorityOwnedBusinessDesignation = "women_owned_business" +) + +// The business type. +type AccountBusinessType string + +// List of values that AccountBusinessType can take +const ( + AccountBusinessTypeCompany AccountBusinessType = "company" + AccountBusinessTypeGovernmentEntity AccountBusinessType = "government_entity" + AccountBusinessTypeIndividual AccountBusinessType = "individual" + AccountBusinessTypeNonProfit AccountBusinessType = "non_profit" +) + +// The status of the Canadian pre-authorized debits payments capability of the account, or whether the account can directly process Canadian pre-authorized debits charges. +type AccountCapabilityStatus string + +// List of values that AccountCapabilityStatus can take +const ( + AccountCapabilityStatusActive AccountCapabilityStatus = "active" + AccountCapabilityStatusInactive AccountCapabilityStatus = "inactive" + AccountCapabilityStatusPending AccountCapabilityStatus = "pending" +) + +// This value is used to determine if a business is exempt from providing ultimate beneficial owners. See [this support article](https://support.stripe.com/questions/exemption-from-providing-ownership-details) and [changelog](https://docs.stripe.com/changelog/acacia/2025-01-27/ownership-exemption-reason-accounts-api) for more details. +type AccountCompanyOwnershipExemptionReason string + +// List of values that AccountCompanyOwnershipExemptionReason can take +const ( + AccountCompanyOwnershipExemptionReasonQualifiedEntityExceedsOwnershipThreshold AccountCompanyOwnershipExemptionReason = "qualified_entity_exceeds_ownership_threshold" + AccountCompanyOwnershipExemptionReasonQualifiesAsFinancialInstitution AccountCompanyOwnershipExemptionReason = "qualifies_as_financial_institution" +) + +// The category identifying the legal structure of the company or legal entity. Also available for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`. See [Business structure](https://stripe.com/docs/connect/identity-verification#business-structure) for more details. +type AccountCompanyStructure string + +// List of values that AccountCompanyStructure can take +const ( + AccountCompanyStructureFreeZoneEstablishment AccountCompanyStructure = "free_zone_establishment" + AccountCompanyStructureFreeZoneLLC AccountCompanyStructure = "free_zone_llc" + AccountCompanyStructureGovernmentInstrumentality AccountCompanyStructure = "government_instrumentality" + AccountCompanyStructureGovernmentalUnit AccountCompanyStructure = "governmental_unit" + AccountCompanyStructureIncorporatedNonProfit AccountCompanyStructure = "incorporated_non_profit" + AccountCompanyStructureIncorporatedPartnership AccountCompanyStructure = "incorporated_partnership" + AccountCompanyStructureLimitedLiabilityPartnership AccountCompanyStructure = "limited_liability_partnership" + AccountCompanyStructureLLC AccountCompanyStructure = "llc" + AccountCompanyStructureMultiMemberLLC AccountCompanyStructure = "multi_member_llc" + AccountCompanyStructurePrivateCompany AccountCompanyStructure = "private_company" + AccountCompanyStructurePrivateCorporation AccountCompanyStructure = "private_corporation" + AccountCompanyStructurePrivatePartnership AccountCompanyStructure = "private_partnership" + AccountCompanyStructurePublicCompany AccountCompanyStructure = "public_company" + AccountCompanyStructurePublicCorporation AccountCompanyStructure = "public_corporation" + AccountCompanyStructurePublicPartnership AccountCompanyStructure = "public_partnership" + AccountCompanyStructureRegisteredCharity AccountCompanyStructure = "registered_charity" + AccountCompanyStructureSingleMemberLLC AccountCompanyStructure = "single_member_llc" + AccountCompanyStructureSoleEstablishment AccountCompanyStructure = "sole_establishment" + AccountCompanyStructureSoleProprietorship AccountCompanyStructure = "sole_proprietorship" + AccountCompanyStructureTaxExemptGovernmentInstrumentality AccountCompanyStructure = "tax_exempt_government_instrumentality" + AccountCompanyStructureUnincorporatedAssociation AccountCompanyStructure = "unincorporated_association" + AccountCompanyStructureUnincorporatedNonProfit AccountCompanyStructure = "unincorporated_non_profit" + AccountCompanyStructureUnincorporatedPartnership AccountCompanyStructure = "unincorporated_partnership" +) + +// One of `document_corrupt`, `document_expired`, `document_failed_copy`, `document_failed_greyscale`, `document_failed_other`, `document_failed_test_mode`, `document_fraudulent`, `document_incomplete`, `document_invalid`, `document_manipulated`, `document_not_readable`, `document_not_uploaded`, `document_type_not_supported`, or `document_too_large`. A machine-readable code specifying the verification state for this document. +type AccountCompanyVerificationDocumentDetailsCode string + +// List of values that AccountCompanyVerificationDocumentDetailsCode can take +const ( + AccountCompanyVerificationDocumentDetailsCodeDocumentCorrupt AccountCompanyVerificationDocumentDetailsCode = "document_corrupt" + AccountCompanyVerificationDocumentDetailsCodeDocumentExpired AccountCompanyVerificationDocumentDetailsCode = "document_expired" + AccountCompanyVerificationDocumentDetailsCodeDocumentFailedCopy AccountCompanyVerificationDocumentDetailsCode = "document_failed_copy" + AccountCompanyVerificationDocumentDetailsCodeDocumentFailedOther AccountCompanyVerificationDocumentDetailsCode = "document_failed_other" + AccountCompanyVerificationDocumentDetailsCodeDocumentFailedTestMode AccountCompanyVerificationDocumentDetailsCode = "document_failed_test_mode" + AccountCompanyVerificationDocumentDetailsCodeDocumentFailedGreyscale AccountCompanyVerificationDocumentDetailsCode = "document_failed_greyscale" + AccountCompanyVerificationDocumentDetailsCodeDocumentFraudulent AccountCompanyVerificationDocumentDetailsCode = "document_fraudulent" + AccountCompanyVerificationDocumentDetailsCodeDocumentInvalid AccountCompanyVerificationDocumentDetailsCode = "document_invalid" + AccountCompanyVerificationDocumentDetailsCodeDocumentIncomplete AccountCompanyVerificationDocumentDetailsCode = "document_incomplete" + AccountCompanyVerificationDocumentDetailsCodeDocumentManipulated AccountCompanyVerificationDocumentDetailsCode = "document_manipulated" + AccountCompanyVerificationDocumentDetailsCodeDocumentNotReadable AccountCompanyVerificationDocumentDetailsCode = "document_not_readable" + AccountCompanyVerificationDocumentDetailsCodeDocumentNotUploaded AccountCompanyVerificationDocumentDetailsCode = "document_not_uploaded" + AccountCompanyVerificationDocumentDetailsCodeDocumentTooLarge AccountCompanyVerificationDocumentDetailsCode = "document_too_large" + AccountCompanyVerificationDocumentDetailsCodeDocumentTypeNotSupported AccountCompanyVerificationDocumentDetailsCode = "document_type_not_supported" +) + +// A value indicating the responsible payer of a bundle of Stripe fees for pricing-control eligible products on this account. Learn more about [fee behavior on connected accounts](https://docs.stripe.com/connect/direct-charges-fee-payer-behavior). +type AccountControllerFeesPayer string + +// List of values that AccountControllerFeesPayer can take +const ( + AccountControllerFeesPayerAccount AccountControllerFeesPayer = "account" + AccountControllerFeesPayerApplication AccountControllerFeesPayer = "application" + AccountControllerFeesPayerApplicationCustom AccountControllerFeesPayer = "application_custom" + AccountControllerFeesPayerApplicationExpress AccountControllerFeesPayer = "application_express" +) + +// A value indicating who is liable when this account can't pay back negative balances from payments. +type AccountControllerLossesPayments string + +// List of values that AccountControllerLossesPayments can take +const ( + AccountControllerLossesPaymentsApplication AccountControllerLossesPayments = "application" + AccountControllerLossesPaymentsStripe AccountControllerLossesPayments = "stripe" +) + +// A value indicating responsibility for collecting requirements on this account. Only returned when the Connect application retrieving the resource controls the account. +type AccountControllerRequirementCollection string + +// List of values that AccountControllerRequirementCollection can take +const ( + AccountControllerRequirementCollectionApplication AccountControllerRequirementCollection = "application" + AccountControllerRequirementCollectionStripe AccountControllerRequirementCollection = "stripe" +) + +// A value indicating the Stripe dashboard this account has access to independent of the Connect application. +type AccountControllerStripeDashboardType string + +// List of values that AccountControllerStripeDashboardType can take +const ( + AccountControllerStripeDashboardTypeExpress AccountControllerStripeDashboardType = "express" + AccountControllerStripeDashboardTypeFull AccountControllerStripeDashboardType = "full" + AccountControllerStripeDashboardTypeNone AccountControllerStripeDashboardType = "none" +) + +// The controller type. Can be `application`, if a Connect application controls the account, or `account`, if the account controls itself. +type AccountControllerType string + +// List of values that AccountControllerType can take +const ( + AccountControllerTypeAccount AccountControllerType = "account" + AccountControllerTypeApplication AccountControllerType = "application" +) + +type AccountExternalAccountType string + +// List of values that AccountExternalAccountType can take +const ( + AccountExternalAccountTypeBankAccount AccountExternalAccountType = "bank_account" + AccountExternalAccountTypeCard AccountExternalAccountType = "card" +) + +// This is typed as an enum for consistency with `requirements.disabled_reason`. +type AccountFutureRequirementsDisabledReason string + +// List of values that AccountFutureRequirementsDisabledReason can take +const ( + AccountFutureRequirementsDisabledReasonActionRequiredRequestedCapabilities AccountFutureRequirementsDisabledReason = "action_required.requested_capabilities" + AccountFutureRequirementsDisabledReasonListed AccountFutureRequirementsDisabledReason = "listed" + AccountFutureRequirementsDisabledReasonOther AccountFutureRequirementsDisabledReason = "other" + AccountFutureRequirementsDisabledReasonPlatformPaused AccountFutureRequirementsDisabledReason = "platform_paused" + AccountFutureRequirementsDisabledReasonRejectedFraud AccountFutureRequirementsDisabledReason = "rejected.fraud" + AccountFutureRequirementsDisabledReasonRejectedIncompleteVerification AccountFutureRequirementsDisabledReason = "rejected.incomplete_verification" + AccountFutureRequirementsDisabledReasonRejectedListed AccountFutureRequirementsDisabledReason = "rejected.listed" + AccountFutureRequirementsDisabledReasonRejectedOther AccountFutureRequirementsDisabledReason = "rejected.other" + AccountFutureRequirementsDisabledReasonRejectedPlatformFraud AccountFutureRequirementsDisabledReason = "rejected.platform_fraud" + AccountFutureRequirementsDisabledReasonRejectedPlatformOther AccountFutureRequirementsDisabledReason = "rejected.platform_other" + AccountFutureRequirementsDisabledReasonRejectedPlatformTermsOfService AccountFutureRequirementsDisabledReason = "rejected.platform_terms_of_service" + AccountFutureRequirementsDisabledReasonRejectedTermsOfService AccountFutureRequirementsDisabledReason = "rejected.terms_of_service" + AccountFutureRequirementsDisabledReasonRequirementsPastDue AccountFutureRequirementsDisabledReason = "requirements.past_due" + AccountFutureRequirementsDisabledReasonRequirementsPendingVerification AccountFutureRequirementsDisabledReason = "requirements.pending_verification" + AccountFutureRequirementsDisabledReasonUnderReview AccountFutureRequirementsDisabledReason = "under_review" +) + +// If the account is disabled, this enum describes why. [Learn more about handling verification issues](https://stripe.com/docs/connect/handling-api-verification). +type AccountRequirementsDisabledReason string + +// List of values that AccountRequirementsDisabledReason can take +const ( + AccountRequirementsDisabledReasonActionRequiredRequestedCapabilities AccountRequirementsDisabledReason = "action_required.requested_capabilities" + AccountRequirementsDisabledReasonListed AccountRequirementsDisabledReason = "listed" + AccountRequirementsDisabledReasonOther AccountRequirementsDisabledReason = "other" + AccountRequirementsDisabledReasonPlatformPaused AccountRequirementsDisabledReason = "platform_paused" + AccountRequirementsDisabledReasonRejectedFraud AccountRequirementsDisabledReason = "rejected.fraud" + AccountRequirementsDisabledReasonRejectedIncompleteVerification AccountRequirementsDisabledReason = "rejected.incomplete_verification" + AccountRequirementsDisabledReasonRejectedListed AccountRequirementsDisabledReason = "rejected.listed" + AccountRequirementsDisabledReasonRejectedOther AccountRequirementsDisabledReason = "rejected.other" + AccountRequirementsDisabledReasonRejectedPlatformFraud AccountRequirementsDisabledReason = "rejected.platform_fraud" + AccountRequirementsDisabledReasonRejectedPlatformOther AccountRequirementsDisabledReason = "rejected.platform_other" + AccountRequirementsDisabledReasonRejectedPlatformTermsOfService AccountRequirementsDisabledReason = "rejected.platform_terms_of_service" + AccountRequirementsDisabledReasonRejectedTermsOfService AccountRequirementsDisabledReason = "rejected.terms_of_service" + AccountRequirementsDisabledReasonRequirementsPastDue AccountRequirementsDisabledReason = "requirements.past_due" + AccountRequirementsDisabledReasonRequirementsPendingVerification AccountRequirementsDisabledReason = "requirements.pending_verification" + AccountRequirementsDisabledReasonUnderReview AccountRequirementsDisabledReason = "under_review" +) + +// Whether payment methods should be saved when a payment is completed for a one-time invoices on a hosted invoice page. +type AccountSettingsInvoicesHostedPaymentMethodSave string + +// List of values that AccountSettingsInvoicesHostedPaymentMethodSave can take +const ( + AccountSettingsInvoicesHostedPaymentMethodSaveAlways AccountSettingsInvoicesHostedPaymentMethodSave = "always" + AccountSettingsInvoicesHostedPaymentMethodSaveNever AccountSettingsInvoicesHostedPaymentMethodSave = "never" + AccountSettingsInvoicesHostedPaymentMethodSaveOffer AccountSettingsInvoicesHostedPaymentMethodSave = "offer" +) + +// How frequently funds will be paid out. One of `manual` (payouts only created via API call), `daily`, `weekly`, or `monthly`. +type AccountSettingsPayoutsScheduleInterval string + +// List of values that AccountSettingsPayoutsScheduleInterval can take +const ( + AccountSettingsPayoutsScheduleIntervalDaily AccountSettingsPayoutsScheduleInterval = "daily" + AccountSettingsPayoutsScheduleIntervalManual AccountSettingsPayoutsScheduleInterval = "manual" + AccountSettingsPayoutsScheduleIntervalMonthly AccountSettingsPayoutsScheduleInterval = "monthly" + AccountSettingsPayoutsScheduleIntervalWeekly AccountSettingsPayoutsScheduleInterval = "weekly" +) + +// The days of the week when available funds are paid out, specified as an array, for example, [`monday`, `tuesday`]. Only shown if `interval` is weekly. +type AccountSettingsPayoutsScheduleWeeklyPayoutDay string + +// List of values that AccountSettingsPayoutsScheduleWeeklyPayoutDay can take +const ( + AccountSettingsPayoutsScheduleWeeklyPayoutDayFriday AccountSettingsPayoutsScheduleWeeklyPayoutDay = "friday" + AccountSettingsPayoutsScheduleWeeklyPayoutDayMonday AccountSettingsPayoutsScheduleWeeklyPayoutDay = "monday" + AccountSettingsPayoutsScheduleWeeklyPayoutDaySaturday AccountSettingsPayoutsScheduleWeeklyPayoutDay = "saturday" + AccountSettingsPayoutsScheduleWeeklyPayoutDaySunday AccountSettingsPayoutsScheduleWeeklyPayoutDay = "sunday" + AccountSettingsPayoutsScheduleWeeklyPayoutDayThursday AccountSettingsPayoutsScheduleWeeklyPayoutDay = "thursday" + AccountSettingsPayoutsScheduleWeeklyPayoutDayTuesday AccountSettingsPayoutsScheduleWeeklyPayoutDay = "tuesday" + AccountSettingsPayoutsScheduleWeeklyPayoutDayWednesday AccountSettingsPayoutsScheduleWeeklyPayoutDay = "wednesday" +) + +// The user's service agreement type +type AccountTOSAcceptanceServiceAgreement string + +// List of values that AccountTOSAcceptanceServiceAgreement can take +const ( + AccountTOSAcceptanceServiceAgreementFull AccountTOSAcceptanceServiceAgreement = "full" + AccountTOSAcceptanceServiceAgreementRecipient AccountTOSAcceptanceServiceAgreement = "recipient" +) + +// The Stripe account type. Can be `standard`, `express`, `custom`, or `none`. +type AccountType string + +// List of values that AccountType can take +const ( + AccountTypeCustom AccountType = "custom" + AccountTypeExpress AccountType = "express" + AccountTypeNone AccountType = "none" + AccountTypeStandard AccountType = "standard" +) + +// With [Connect](https://docs.stripe.com/connect), you can delete accounts you manage. +// +// Test-mode accounts can be deleted at any time. +// +// Live-mode accounts where Stripe is responsible for negative account balances cannot be deleted, which includes Standard accounts. Live-mode accounts where your platform is liable for negative account balances, which includes Custom and Express accounts, can be deleted when all [balances](https://docs.stripe.com/api/balance/balance_object) are zero. +// +// If you want to delete your own account, use the [account information tab in your account settings](https://dashboard.stripe.com/settings/account) instead. +type AccountParams struct { + Params `form:"*"` + // An [account token](https://stripe.com/docs/api#create_account_token), used to securely provide details to the account. + AccountToken *string `form:"account_token"` + // Business information about the account. + BusinessProfile *AccountBusinessProfileParams `form:"business_profile"` + // The business type. Once you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. + BusinessType *string `form:"business_type"` + // Each key of the dictionary represents a capability, and each capability + // maps to its settings (for example, whether it has been requested or not). Each + // capability is inactive until you have provided its specific + // requirements and Stripe has verified them. An account might have some + // of its requested capabilities be active and some be inactive. + // + // Required when [account.controller.stripe_dashboard.type](https://docs.stripe.com/api/accounts/create#create_account-controller-dashboard-type) + // is `none`, which includes Custom accounts. + Capabilities *AccountCapabilitiesParams `form:"capabilities"` + // Information about the company or business. This field is available for any `business_type`. Once you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. + Company *AccountCompanyParams `form:"company"` + // A hash of configuration describing the account controller's attributes. + Controller *AccountControllerParams `form:"controller"` + // The country in which the account holder resides, or in which the business is legally established. This should be an ISO 3166-1 alpha-2 country code. For example, if you are in the United States and the business for which you're creating an account is legally represented in Canada, you would use `CA` as the country for the account being created. Available countries include [Stripe's global markets](https://stripe.com/global) as well as countries where [cross-border payouts](https://stripe.com/docs/connect/cross-border-payouts) are supported. + Country *string `form:"country"` + // Three-letter ISO currency code representing the default currency for the account. This must be a currency that [Stripe supports in the account's country](https://docs.stripe.com/payouts). + DefaultCurrency *string `form:"default_currency"` + // Documents that may be submitted to satisfy various informational requests. + Documents *AccountDocumentsParams `form:"documents"` + // The email address of the account holder. This is only to make the account easier to identify to you. If [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts, Stripe doesn't email the account without your consent. + Email *string `form:"email"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A card or bank account to attach to the account for receiving [payouts](https://docs.stripe.com/connect/bank-debit-card-payouts) (you won't be able to use it for top-ups). You can provide either a token, like the ones returned by [Stripe.js](https://docs.stripe.com/js), or a dictionary, as documented in the `external_account` parameter for [bank account](https://docs.stripe.com/api#account_create_bank_account) creation. + // + // By default, providing an external account sets it as the new default external account for its currency, and deletes the old default if one exists. To add additional external accounts without replacing the existing default for the currency, use the [bank account](https://docs.stripe.com/api#account_create_bank_account) or [card creation](https://docs.stripe.com/api#account_create_card) APIs. After you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. + ExternalAccount *AccountExternalAccountParams `form:"external_account"` + // A hash of account group type to tokens. These are account groups this account should be added to. + Groups *AccountGroupsParams `form:"groups"` + // Information about the person represented by the account. This field is null unless `business_type` is set to `individual`. Once you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. + Individual *PersonParams `form:"individual"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Options for customizing how the account functions within Stripe. + Settings *AccountSettingsParams `form:"settings"` + // Details on the account's acceptance of the [Stripe Services Agreement](https://docs.stripe.com/connect/updating-accounts#tos-acceptance). This property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. This property defaults to a `full` service agreement when empty. + TOSAcceptance *AccountTOSAcceptanceParams `form:"tos_acceptance"` + // The type of Stripe account to create. May be one of `custom`, `express` or `standard`. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *AccountParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *AccountParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The applicant's gross annual revenue for its preceding fiscal year. +type AccountBusinessProfileAnnualRevenueParams struct { + // A non-negative integer representing the amount in the [smallest currency unit](https://docs.stripe.com/currencies#zero-decimal). + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The close-out date of the preceding fiscal year in ISO 8601 format. E.g. 2023-12-31 for the 31st of December, 2023. + FiscalYearEnd *string `form:"fiscal_year_end"` +} + +// An estimate of the monthly revenue of the business. Only accepted for accounts in Brazil and India. +type AccountBusinessProfileMonthlyEstimatedRevenueParams struct { + // A non-negative integer representing how much to charge in the [smallest currency unit](https://docs.stripe.com/currencies#zero-decimal). + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` +} + +// Business information about the account. +type AccountBusinessProfileParams struct { + // The applicant's gross annual revenue for its preceding fiscal year. + AnnualRevenue *AccountBusinessProfileAnnualRevenueParams `form:"annual_revenue"` + // An estimated upper bound of employees, contractors, vendors, etc. currently working for the business. + EstimatedWorkerCount *int64 `form:"estimated_worker_count"` + // [The merchant category code for the account](https://docs.stripe.com/connect/setting-mcc). MCCs are used to classify businesses based on the goods or services they provide. + MCC *string `form:"mcc"` + // Whether the business is a minority-owned, women-owned, and/or LGBTQI+-owned business. + MinorityOwnedBusinessDesignation []*string `form:"minority_owned_business_designation"` + // An estimate of the monthly revenue of the business. Only accepted for accounts in Brazil and India. + MonthlyEstimatedRevenue *AccountBusinessProfileMonthlyEstimatedRevenueParams `form:"monthly_estimated_revenue"` + // The customer-facing business name. + Name *string `form:"name"` + // Internal-only description of the product sold by, or service provided by, the business. Used by Stripe for risk and underwriting purposes. + ProductDescription *string `form:"product_description"` + // A publicly available mailing address for sending support issues to. + SupportAddress *AddressParams `form:"support_address"` + // A publicly available email address for sending support issues to. + SupportEmail *string `form:"support_email"` + // A publicly available phone number to call with support issues. + SupportPhone *string `form:"support_phone"` + // A publicly available website for handling support issues. + SupportURL *string `form:"support_url"` + // The business's publicly available website. + URL *string `form:"url"` +} + +// The acss_debit_payments capability. +type AccountCapabilitiesACSSDebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The affirm_payments capability. +type AccountCapabilitiesAffirmPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The afterpay_clearpay_payments capability. +type AccountCapabilitiesAfterpayClearpayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The alma_payments capability. +type AccountCapabilitiesAlmaPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The amazon_pay_payments capability. +type AccountCapabilitiesAmazonPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The au_becs_debit_payments capability. +type AccountCapabilitiesAUBECSDebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The bacs_debit_payments capability. +type AccountCapabilitiesBACSDebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The bancontact_payments capability. +type AccountCapabilitiesBancontactPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The bank_transfer_payments capability. +type AccountCapabilitiesBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The billie_payments capability. +type AccountCapabilitiesBilliePaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The blik_payments capability. +type AccountCapabilitiesBLIKPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The boleto_payments capability. +type AccountCapabilitiesBoletoPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The card_issuing capability. +type AccountCapabilitiesCardIssuingParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The card_payments capability. +type AccountCapabilitiesCardPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The cartes_bancaires_payments capability. +type AccountCapabilitiesCartesBancairesPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The cashapp_payments capability. +type AccountCapabilitiesCashAppPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The crypto_payments capability. +type AccountCapabilitiesCryptoPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The eps_payments capability. +type AccountCapabilitiesEPSPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The fpx_payments capability. +type AccountCapabilitiesFPXPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The gb_bank_transfer_payments capability. +type AccountCapabilitiesGBBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The giropay_payments capability. +type AccountCapabilitiesGiropayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The grabpay_payments capability. +type AccountCapabilitiesGrabpayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The ideal_payments capability. +type AccountCapabilitiesIDEALPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The india_international_payments capability. +type AccountCapabilitiesIndiaInternationalPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The jcb_payments capability. +type AccountCapabilitiesJCBPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The jp_bank_transfer_payments capability. +type AccountCapabilitiesJPBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The kakao_pay_payments capability. +type AccountCapabilitiesKakaoPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The klarna_payments capability. +type AccountCapabilitiesKlarnaPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The konbini_payments capability. +type AccountCapabilitiesKonbiniPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The kr_card_payments capability. +type AccountCapabilitiesKrCardPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The legacy_payments capability. +type AccountCapabilitiesLegacyPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The link_payments capability. +type AccountCapabilitiesLinkPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The mobilepay_payments capability. +type AccountCapabilitiesMobilepayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The multibanco_payments capability. +type AccountCapabilitiesMultibancoPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The mx_bank_transfer_payments capability. +type AccountCapabilitiesMXBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The naver_pay_payments capability. +type AccountCapabilitiesNaverPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The nz_bank_account_becs_debit_payments capability. +type AccountCapabilitiesNzBankAccountBECSDebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The oxxo_payments capability. +type AccountCapabilitiesOXXOPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The p24_payments capability. +type AccountCapabilitiesP24PaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The pay_by_bank_payments capability. +type AccountCapabilitiesPayByBankPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The payco_payments capability. +type AccountCapabilitiesPaycoPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The paynow_payments capability. +type AccountCapabilitiesPayNowPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The pix_payments capability. +type AccountCapabilitiesPixPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The promptpay_payments capability. +type AccountCapabilitiesPromptPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The revolut_pay_payments capability. +type AccountCapabilitiesRevolutPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The samsung_pay_payments capability. +type AccountCapabilitiesSamsungPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The satispay_payments capability. +type AccountCapabilitiesSatispayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The sepa_bank_transfer_payments capability. +type AccountCapabilitiesSEPABankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The sepa_debit_payments capability. +type AccountCapabilitiesSEPADebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The sofort_payments capability. +type AccountCapabilitiesSofortPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The swish_payments capability. +type AccountCapabilitiesSwishPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The tax_reporting_us_1099_k capability. +type AccountCapabilitiesTaxReportingUS1099KParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The tax_reporting_us_1099_misc capability. +type AccountCapabilitiesTaxReportingUS1099MISCParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The transfers capability. +type AccountCapabilitiesTransfersParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The treasury capability. +type AccountCapabilitiesTreasuryParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The twint_payments capability. +type AccountCapabilitiesTWINTPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The us_bank_account_ach_payments capability. +type AccountCapabilitiesUSBankAccountACHPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The us_bank_transfer_payments capability. +type AccountCapabilitiesUSBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The zip_payments capability. +type AccountCapabilitiesZipPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// Each key of the dictionary represents a capability, and each capability +// maps to its settings (for example, whether it has been requested or not). Each +// capability is inactive until you have provided its specific +// requirements and Stripe has verified them. An account might have some +// of its requested capabilities be active and some be inactive. +// +// Required when [account.controller.stripe_dashboard.type](https://docs.stripe.com/api/accounts/create#create_account-controller-dashboard-type) +// is `none`, which includes Custom accounts. +type AccountCapabilitiesParams struct { + // The acss_debit_payments capability. + ACSSDebitPayments *AccountCapabilitiesACSSDebitPaymentsParams `form:"acss_debit_payments"` + // The affirm_payments capability. + AffirmPayments *AccountCapabilitiesAffirmPaymentsParams `form:"affirm_payments"` + // The afterpay_clearpay_payments capability. + AfterpayClearpayPayments *AccountCapabilitiesAfterpayClearpayPaymentsParams `form:"afterpay_clearpay_payments"` + // The alma_payments capability. + AlmaPayments *AccountCapabilitiesAlmaPaymentsParams `form:"alma_payments"` + // The amazon_pay_payments capability. + AmazonPayPayments *AccountCapabilitiesAmazonPayPaymentsParams `form:"amazon_pay_payments"` + // The au_becs_debit_payments capability. + AUBECSDebitPayments *AccountCapabilitiesAUBECSDebitPaymentsParams `form:"au_becs_debit_payments"` + // The bacs_debit_payments capability. + BACSDebitPayments *AccountCapabilitiesBACSDebitPaymentsParams `form:"bacs_debit_payments"` + // The bancontact_payments capability. + BancontactPayments *AccountCapabilitiesBancontactPaymentsParams `form:"bancontact_payments"` + // The bank_transfer_payments capability. + BankTransferPayments *AccountCapabilitiesBankTransferPaymentsParams `form:"bank_transfer_payments"` + // The billie_payments capability. + BilliePayments *AccountCapabilitiesBilliePaymentsParams `form:"billie_payments"` + // The blik_payments capability. + BLIKPayments *AccountCapabilitiesBLIKPaymentsParams `form:"blik_payments"` + // The boleto_payments capability. + BoletoPayments *AccountCapabilitiesBoletoPaymentsParams `form:"boleto_payments"` + // The card_issuing capability. + CardIssuing *AccountCapabilitiesCardIssuingParams `form:"card_issuing"` + // The card_payments capability. + CardPayments *AccountCapabilitiesCardPaymentsParams `form:"card_payments"` + // The cartes_bancaires_payments capability. + CartesBancairesPayments *AccountCapabilitiesCartesBancairesPaymentsParams `form:"cartes_bancaires_payments"` + // The cashapp_payments capability. + CashAppPayments *AccountCapabilitiesCashAppPaymentsParams `form:"cashapp_payments"` + // The crypto_payments capability. + CryptoPayments *AccountCapabilitiesCryptoPaymentsParams `form:"crypto_payments"` + // The eps_payments capability. + EPSPayments *AccountCapabilitiesEPSPaymentsParams `form:"eps_payments"` + // The fpx_payments capability. + FPXPayments *AccountCapabilitiesFPXPaymentsParams `form:"fpx_payments"` + // The gb_bank_transfer_payments capability. + GBBankTransferPayments *AccountCapabilitiesGBBankTransferPaymentsParams `form:"gb_bank_transfer_payments"` + // The giropay_payments capability. + GiropayPayments *AccountCapabilitiesGiropayPaymentsParams `form:"giropay_payments"` + // The grabpay_payments capability. + GrabpayPayments *AccountCapabilitiesGrabpayPaymentsParams `form:"grabpay_payments"` + // The ideal_payments capability. + IDEALPayments *AccountCapabilitiesIDEALPaymentsParams `form:"ideal_payments"` + // The india_international_payments capability. + IndiaInternationalPayments *AccountCapabilitiesIndiaInternationalPaymentsParams `form:"india_international_payments"` + // The jcb_payments capability. + JCBPayments *AccountCapabilitiesJCBPaymentsParams `form:"jcb_payments"` + // The jp_bank_transfer_payments capability. + JPBankTransferPayments *AccountCapabilitiesJPBankTransferPaymentsParams `form:"jp_bank_transfer_payments"` + // The kakao_pay_payments capability. + KakaoPayPayments *AccountCapabilitiesKakaoPayPaymentsParams `form:"kakao_pay_payments"` + // The klarna_payments capability. + KlarnaPayments *AccountCapabilitiesKlarnaPaymentsParams `form:"klarna_payments"` + // The konbini_payments capability. + KonbiniPayments *AccountCapabilitiesKonbiniPaymentsParams `form:"konbini_payments"` + // The kr_card_payments capability. + KrCardPayments *AccountCapabilitiesKrCardPaymentsParams `form:"kr_card_payments"` + // The legacy_payments capability. + LegacyPayments *AccountCapabilitiesLegacyPaymentsParams `form:"legacy_payments"` + // The link_payments capability. + LinkPayments *AccountCapabilitiesLinkPaymentsParams `form:"link_payments"` + // The mobilepay_payments capability. + MobilepayPayments *AccountCapabilitiesMobilepayPaymentsParams `form:"mobilepay_payments"` + // The multibanco_payments capability. + MultibancoPayments *AccountCapabilitiesMultibancoPaymentsParams `form:"multibanco_payments"` + // The mx_bank_transfer_payments capability. + MXBankTransferPayments *AccountCapabilitiesMXBankTransferPaymentsParams `form:"mx_bank_transfer_payments"` + // The naver_pay_payments capability. + NaverPayPayments *AccountCapabilitiesNaverPayPaymentsParams `form:"naver_pay_payments"` + // The nz_bank_account_becs_debit_payments capability. + NzBankAccountBECSDebitPayments *AccountCapabilitiesNzBankAccountBECSDebitPaymentsParams `form:"nz_bank_account_becs_debit_payments"` + // The oxxo_payments capability. + OXXOPayments *AccountCapabilitiesOXXOPaymentsParams `form:"oxxo_payments"` + // The p24_payments capability. + P24Payments *AccountCapabilitiesP24PaymentsParams `form:"p24_payments"` + // The pay_by_bank_payments capability. + PayByBankPayments *AccountCapabilitiesPayByBankPaymentsParams `form:"pay_by_bank_payments"` + // The payco_payments capability. + PaycoPayments *AccountCapabilitiesPaycoPaymentsParams `form:"payco_payments"` + // The paynow_payments capability. + PayNowPayments *AccountCapabilitiesPayNowPaymentsParams `form:"paynow_payments"` + // The pix_payments capability. + PixPayments *AccountCapabilitiesPixPaymentsParams `form:"pix_payments"` + // The promptpay_payments capability. + PromptPayPayments *AccountCapabilitiesPromptPayPaymentsParams `form:"promptpay_payments"` + // The revolut_pay_payments capability. + RevolutPayPayments *AccountCapabilitiesRevolutPayPaymentsParams `form:"revolut_pay_payments"` + // The samsung_pay_payments capability. + SamsungPayPayments *AccountCapabilitiesSamsungPayPaymentsParams `form:"samsung_pay_payments"` + // The satispay_payments capability. + SatispayPayments *AccountCapabilitiesSatispayPaymentsParams `form:"satispay_payments"` + // The sepa_bank_transfer_payments capability. + SEPABankTransferPayments *AccountCapabilitiesSEPABankTransferPaymentsParams `form:"sepa_bank_transfer_payments"` + // The sepa_debit_payments capability. + SEPADebitPayments *AccountCapabilitiesSEPADebitPaymentsParams `form:"sepa_debit_payments"` + // The sofort_payments capability. + SofortPayments *AccountCapabilitiesSofortPaymentsParams `form:"sofort_payments"` + // The swish_payments capability. + SwishPayments *AccountCapabilitiesSwishPaymentsParams `form:"swish_payments"` + // The tax_reporting_us_1099_k capability. + TaxReportingUS1099K *AccountCapabilitiesTaxReportingUS1099KParams `form:"tax_reporting_us_1099_k"` + // The tax_reporting_us_1099_misc capability. + TaxReportingUS1099MISC *AccountCapabilitiesTaxReportingUS1099MISCParams `form:"tax_reporting_us_1099_misc"` + // The transfers capability. + Transfers *AccountCapabilitiesTransfersParams `form:"transfers"` + // The treasury capability. + Treasury *AccountCapabilitiesTreasuryParams `form:"treasury"` + // The twint_payments capability. + TWINTPayments *AccountCapabilitiesTWINTPaymentsParams `form:"twint_payments"` + // The us_bank_account_ach_payments capability. + USBankAccountACHPayments *AccountCapabilitiesUSBankAccountACHPaymentsParams `form:"us_bank_account_ach_payments"` + // The us_bank_transfer_payments capability. + USBankTransferPayments *AccountCapabilitiesUSBankTransferPaymentsParams `form:"us_bank_transfer_payments"` + // The zip_payments capability. + ZipPayments *AccountCapabilitiesZipPaymentsParams `form:"zip_payments"` +} + +// The Kana variation of the company's primary address (Japan only). +type AccountCompanyAddressKanaParams struct { + // City or ward. + City *string `form:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // Block or building number. + Line1 *string `form:"line1"` + // Building details. + Line2 *string `form:"line2"` + // Postal code. + PostalCode *string `form:"postal_code"` + // Prefecture. + State *string `form:"state"` + // Town or cho-me. + Town *string `form:"town"` +} + +// The Kanji variation of the company's primary address (Japan only). +type AccountCompanyAddressKanjiParams struct { + // City or ward. + City *string `form:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // Block or building number. + Line1 *string `form:"line1"` + // Building details. + Line2 *string `form:"line2"` + // Postal code. + PostalCode *string `form:"postal_code"` + // Prefecture. + State *string `form:"state"` + // Town or cho-me. + Town *string `form:"town"` +} + +// This hash is used to attest that the directors information provided to Stripe is both current and correct. +type AccountCompanyDirectorshipDeclarationParams struct { + // The Unix timestamp marking when the directorship declaration attestation was made. + Date *int64 `form:"date"` + // The IP address from which the directorship declaration attestation was made. + IP *string `form:"ip"` + // The user agent of the browser from which the directorship declaration attestation was made. + UserAgent *string `form:"user_agent"` +} + +// This hash is used to attest that the beneficial owner information provided to Stripe is both current and correct. +type AccountCompanyOwnershipDeclarationParams struct { + // The Unix timestamp marking when the beneficial owner attestation was made. + Date *int64 `form:"date"` + // The IP address from which the beneficial owner attestation was made. + IP *string `form:"ip"` + // The user agent of the browser from which the beneficial owner attestation was made. + UserAgent *string `form:"user_agent"` +} + +// When the business was incorporated or registered. +type AccountCompanyRegistrationDateParams struct { + // The day of registration, between 1 and 31. + Day *int64 `form:"day"` + // The month of registration, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of registration. + Year *int64 `form:"year"` +} + +// A document verifying the business. +type AccountCompanyVerificationDocumentParams struct { + // The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Back *string `form:"back"` + // The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Front *string `form:"front"` +} + +// Information on the verification state of the company. +type AccountCompanyVerificationParams struct { + // A document verifying the business. + Document *AccountCompanyVerificationDocumentParams `form:"document"` +} + +// Information about the company or business. This field is available for any `business_type`. Once you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. +type AccountCompanyParams struct { + // The company's primary address. + Address *AddressParams `form:"address"` + // The Kana variation of the company's primary address (Japan only). + AddressKana *AccountCompanyAddressKanaParams `form:"address_kana"` + // The Kanji variation of the company's primary address (Japan only). + AddressKanji *AccountCompanyAddressKanjiParams `form:"address_kanji"` + // This hash is used to attest that the directors information provided to Stripe is both current and correct. + DirectorshipDeclaration *AccountCompanyDirectorshipDeclarationParams `form:"directorship_declaration"` + // Whether the company's directors have been provided. Set this Boolean to `true` after creating all the company's directors with [the Persons API](https://docs.stripe.com/api/persons) for accounts with a `relationship.director` requirement. This value is not automatically set to `true` after creating directors, so it needs to be updated to indicate all directors have been provided. + DirectorsProvided *bool `form:"directors_provided"` + // Whether the company's executives have been provided. Set this Boolean to `true` after creating all the company's executives with [the Persons API](https://docs.stripe.com/api/persons) for accounts with a `relationship.executive` requirement. + ExecutivesProvided *bool `form:"executives_provided"` + // The export license ID number of the company, also referred as Import Export Code (India only). + ExportLicenseID *string `form:"export_license_id"` + // The purpose code to use for export transactions (India only). + ExportPurposeCode *string `form:"export_purpose_code"` + // The company's legal name. + Name *string `form:"name"` + // The Kana variation of the company's legal name (Japan only). + NameKana *string `form:"name_kana"` + // The Kanji variation of the company's legal name (Japan only). + NameKanji *string `form:"name_kanji"` + // This hash is used to attest that the beneficial owner information provided to Stripe is both current and correct. + OwnershipDeclaration *AccountCompanyOwnershipDeclarationParams `form:"ownership_declaration"` + // This parameter can only be used on Token creation. + OwnershipDeclarationShownAndSigned *bool `form:"ownership_declaration_shown_and_signed"` + // This value is used to determine if a business is exempt from providing ultimate beneficial owners. See [this support article](https://support.stripe.com/questions/exemption-from-providing-ownership-details) and [changelog](https://docs.stripe.com/changelog/acacia/2025-01-27/ownership-exemption-reason-accounts-api) for more details. + OwnershipExemptionReason *string `form:"ownership_exemption_reason"` + // Whether the company's owners have been provided. Set this Boolean to `true` after creating all the company's owners with [the Persons API](https://docs.stripe.com/api/persons) for accounts with a `relationship.owner` requirement. + OwnersProvided *bool `form:"owners_provided"` + // The company's phone number (used for verification). + Phone *string `form:"phone"` + // When the business was incorporated or registered. + RegistrationDate *AccountCompanyRegistrationDateParams `form:"registration_date"` + // The identification number given to a company when it is registered or incorporated, if distinct from the identification number used for filing taxes. (Examples are the CIN for companies and LLP IN for partnerships in India, and the Company Registration Number in Hong Kong). + RegistrationNumber *string `form:"registration_number"` + // The category identifying the legal structure of the company or legal entity. See [Business structure](https://docs.stripe.com/connect/identity-verification#business-structure) for more details. Pass an empty string to unset this value. + Structure *string `form:"structure"` + // The business ID number of the company, as appropriate for the company's country. (Examples are an Employer ID Number in the U.S., a Business Number in Canada, or a Company Number in the UK.) + TaxID *string `form:"tax_id"` + // The jurisdiction in which the `tax_id` is registered (Germany-based companies only). + TaxIDRegistrar *string `form:"tax_id_registrar"` + // The VAT number of the company. + VATID *string `form:"vat_id"` + // Information on the verification state of the company. + Verification *AccountCompanyVerificationParams `form:"verification"` +} + +// One or more documents that support the [Bank account ownership verification](https://support.stripe.com/questions/bank-account-ownership-verification) requirement. Must be a document associated with the account's primary active bank account that displays the last 4 digits of the account number, either a statement or a check. +type AccountDocumentsBankAccountOwnershipVerificationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of a company's license to operate. +type AccountDocumentsCompanyLicenseParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents showing the company's Memorandum of Association. +type AccountDocumentsCompanyMemorandumOfAssociationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// (Certain countries only) One or more documents showing the ministerial decree legalizing the company's establishment. +type AccountDocumentsCompanyMinisterialDecreeParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of a company's registration with the appropriate local authorities. +type AccountDocumentsCompanyRegistrationVerificationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of a company's tax ID. +type AccountDocumentsCompanyTaxIDVerificationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of address. +type AccountDocumentsProofOfAddressParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents showing the company's proof of registration with the national business registry. +type AccountDocumentsProofOfRegistrationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of ultimate beneficial ownership. +type AccountDocumentsProofOfUltimateBeneficialOwnershipParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// Documents that may be submitted to satisfy various informational requests. +type AccountDocumentsParams struct { + // One or more documents that support the [Bank account ownership verification](https://support.stripe.com/questions/bank-account-ownership-verification) requirement. Must be a document associated with the account's primary active bank account that displays the last 4 digits of the account number, either a statement or a check. + BankAccountOwnershipVerification *AccountDocumentsBankAccountOwnershipVerificationParams `form:"bank_account_ownership_verification"` + // One or more documents that demonstrate proof of a company's license to operate. + CompanyLicense *AccountDocumentsCompanyLicenseParams `form:"company_license"` + // One or more documents showing the company's Memorandum of Association. + CompanyMemorandumOfAssociation *AccountDocumentsCompanyMemorandumOfAssociationParams `form:"company_memorandum_of_association"` + // (Certain countries only) One or more documents showing the ministerial decree legalizing the company's establishment. + CompanyMinisterialDecree *AccountDocumentsCompanyMinisterialDecreeParams `form:"company_ministerial_decree"` + // One or more documents that demonstrate proof of a company's registration with the appropriate local authorities. + CompanyRegistrationVerification *AccountDocumentsCompanyRegistrationVerificationParams `form:"company_registration_verification"` + // One or more documents that demonstrate proof of a company's tax ID. + CompanyTaxIDVerification *AccountDocumentsCompanyTaxIDVerificationParams `form:"company_tax_id_verification"` + // One or more documents that demonstrate proof of address. + ProofOfAddress *AccountDocumentsProofOfAddressParams `form:"proof_of_address"` + // One or more documents showing the company's proof of registration with the national business registry. + ProofOfRegistration *AccountDocumentsProofOfRegistrationParams `form:"proof_of_registration"` + // One or more documents that demonstrate proof of ultimate beneficial ownership. + ProofOfUltimateBeneficialOwnership *AccountDocumentsProofOfUltimateBeneficialOwnershipParams `form:"proof_of_ultimate_beneficial_ownership"` +} + +// AccountExternalAccountParams are the parameters allowed to reference an +// external account when creating an account. It should either have Token set +// or everything else. +type AccountExternalAccountParams struct { + Params `form:"*"` + AccountNumber *string `form:"account_number"` + AccountHolderName *string `form:"account_holder_name"` + AccountHolderType *string `form:"account_holder_type"` + Country *string `form:"country"` + Currency *string `form:"currency"` + RoutingNumber *string `form:"routing_number"` + Token *string `form:"token"` +} + +// AppendTo implements custom encoding logic for AccountExternalAccountParams +// so that we can send the special required `object` field up along with the +// other specified parameters or the token value. +func (p *AccountExternalAccountParams) AppendTo(body *form.Values, keyParts []string) { + if p.Token != nil { + body.Add(form.FormatKey(keyParts), StringValue(p.Token)) + } else { + body.Add(form.FormatKey(append(keyParts, "object")), "bank_account") + } +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *AccountExternalAccountParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A hash of account group type to tokens. These are account groups this account should be added to. +type AccountGroupsParams struct { + // The group the account is in to determine their payments pricing, and null if the account is on customized pricing. [See the Platform pricing tool documentation](https://stripe.com/docs/connect/platform-pricing-tools) for details. + PaymentsPricing *string `form:"payments_pricing"` +} + +// Settings specific to Bacs Direct Debit payments. +type AccountSettingsBACSDebitPaymentsParams struct { + // The Bacs Direct Debit Display Name for this account. For payments made with Bacs Direct Debit, this name appears on the mandate as the statement descriptor. Mobile banking apps display it as the name of the business. To use custom branding, set the Bacs Direct Debit Display Name during or right after creation. Custom branding incurs an additional monthly fee for the platform. If you don't set the display name before requesting Bacs capability, it's automatically set as "Stripe" and the account is onboarded to Stripe branding, which is free. + DisplayName *string `form:"display_name"` +} + +// Settings used to apply the account's branding to email receipts, invoices, Checkout, and other products. +type AccountSettingsBrandingParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) An icon for the account. Must be square and at least 128px x 128px. + Icon *string `form:"icon"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) A logo for the account that will be used in Checkout instead of the icon and without the account's name next to it if provided. Must be at least 128px x 128px. + Logo *string `form:"logo"` + // A CSS hex color value representing the primary branding color for this account. + PrimaryColor *string `form:"primary_color"` + // A CSS hex color value representing the secondary branding color for this account. + SecondaryColor *string `form:"secondary_color"` +} + +// Details on the account's acceptance of the [Stripe Issuing Terms and Disclosures](https://docs.stripe.com/issuing/connect/tos_acceptance). +type AccountSettingsCardIssuingTOSAcceptanceParams struct { + // The Unix timestamp marking when the account representative accepted the service agreement. + Date *int64 `form:"date"` + // The IP address from which the account representative accepted the service agreement. + IP *string `form:"ip"` + // The user agent of the browser from which the account representative accepted the service agreement. + UserAgent *string `form:"user_agent"` +} + +// Settings specific to the account's use of the Card Issuing product. +type AccountSettingsCardIssuingParams struct { + // Details on the account's acceptance of the [Stripe Issuing Terms and Disclosures](https://docs.stripe.com/issuing/connect/tos_acceptance). + TOSAcceptance *AccountSettingsCardIssuingTOSAcceptanceParams `form:"tos_acceptance"` +} + +// Automatically declines certain charge types regardless of whether the card issuer accepted or declined the charge. +type AccountSettingsCardPaymentsDeclineOnParams struct { + // Whether Stripe automatically declines charges with an incorrect ZIP or postal code. This setting only applies when a ZIP or postal code is provided and they fail bank verification. + AVSFailure *bool `form:"avs_failure"` + // Whether Stripe automatically declines charges with an incorrect CVC. This setting only applies when a CVC is provided and it fails bank verification. + CVCFailure *bool `form:"cvc_failure"` +} + +// Settings specific to card charging on the account. +type AccountSettingsCardPaymentsParams struct { + // Automatically declines certain charge types regardless of whether the card issuer accepted or declined the charge. + DeclineOn *AccountSettingsCardPaymentsDeclineOnParams `form:"decline_on"` + // The default text that appears on credit card statements when a charge is made. This field prefixes any dynamic `statement_descriptor` specified on the charge. `statement_descriptor_prefix` is useful for maximizing descriptor space for the dynamic portion. + StatementDescriptorPrefix *string `form:"statement_descriptor_prefix"` + // The Kana variation of the default text that appears on credit card statements when a charge is made (Japan only). This field prefixes any dynamic `statement_descriptor_suffix_kana` specified on the charge. `statement_descriptor_prefix_kana` is useful for maximizing descriptor space for the dynamic portion. + StatementDescriptorPrefixKana *string `form:"statement_descriptor_prefix_kana"` + // The Kanji variation of the default text that appears on credit card statements when a charge is made (Japan only). This field prefixes any dynamic `statement_descriptor_suffix_kanji` specified on the charge. `statement_descriptor_prefix_kanji` is useful for maximizing descriptor space for the dynamic portion. + StatementDescriptorPrefixKanji *string `form:"statement_descriptor_prefix_kanji"` +} + +// Settings specific to the account's use of Invoices. +type AccountSettingsInvoicesParams struct { + // The list of default Account Tax IDs to automatically include on invoices. Account Tax IDs get added when an invoice is finalized. + DefaultAccountTaxIDs []*string `form:"default_account_tax_ids"` + // Whether payment methods should be saved when a payment is completed for a one-time invoices on a hosted invoice page. + HostedPaymentMethodSave *string `form:"hosted_payment_method_save"` +} + +// Settings that apply across payment methods for charging on the account. +type AccountSettingsPaymentsParams struct { + // The default text that appears on statements for non-card charges outside of Japan. For card charges, if you don't set a `statement_descriptor_prefix`, this text is also used as the statement descriptor prefix. In that case, if concatenating the statement descriptor suffix causes the combined statement descriptor to exceed 22 characters, we truncate the `statement_descriptor` text to limit the full descriptor to 22 characters. For more information about statement descriptors and their requirements, see the [account settings documentation](https://docs.stripe.com/get-started/account/statement-descriptors). + StatementDescriptor *string `form:"statement_descriptor"` + // The Kana variation of `statement_descriptor` used for charges in Japan. Japanese statement descriptors have [special requirements](https://docs.stripe.com/get-started/account/statement-descriptors#set-japanese-statement-descriptors). + StatementDescriptorKana *string `form:"statement_descriptor_kana"` + // The Kanji variation of `statement_descriptor` used for charges in Japan. Japanese statement descriptors have [special requirements](https://docs.stripe.com/get-started/account/statement-descriptors#set-japanese-statement-descriptors). + StatementDescriptorKanji *string `form:"statement_descriptor_kanji"` +} + +// Details on when funds from charges are available, and when they are paid out to an external account. For details, see our [Setting Bank and Debit Card Payouts](https://docs.stripe.com/connect/bank-transfers#payout-information) documentation. +type AccountSettingsPayoutsScheduleParams struct { + // The number of days charge funds are held before being paid out. May also be set to `minimum`, representing the lowest available value for the account country. Default is `minimum`. The `delay_days` parameter remains at the last configured value if `interval` is `manual`. [Learn more about controlling payout delay days](https://docs.stripe.com/connect/manage-payout-schedule). + DelayDays *int64 `form:"delay_days"` + DelayDaysMinimum *bool `form:"-"` // See custom AppendTo + // How frequently available funds are paid out. One of: `daily`, `manual`, `weekly`, or `monthly`. Default is `daily`. + Interval *string `form:"interval"` + // The day of the month when available funds are paid out, specified as a number between 1--31. Payouts nominally scheduled between the 29th and 31st of the month are instead sent on the last day of a shorter month. Required and applicable only if `interval` is `monthly`. + MonthlyAnchor *int64 `form:"monthly_anchor"` + // The days of the month when available funds are paid out, specified as an array of numbers between 1--31. Payouts nominally scheduled between the 29th and 31st of the month are instead sent on the last day of a shorter month. Required and applicable only if `interval` is `monthly` and `monthly_anchor` is not set. + MonthlyPayoutDays []*int64 `form:"monthly_payout_days"` + // The day of the week when available funds are paid out, specified as `monday`, `tuesday`, etc. (required and applicable only if `interval` is `weekly`.) + WeeklyAnchor *string `form:"weekly_anchor"` + // The days of the week when available funds are paid out, specified as an array, e.g., [`monday`, `tuesday`]. (required and applicable only if `interval` is `weekly` and `weekly_anchor` is not set.) + WeeklyPayoutDays []*string `form:"weekly_payout_days"` +} + +// AppendTo implements custom encoding logic for AccountSettingsPayoutsScheduleParams. +func (p *AccountSettingsPayoutsScheduleParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.DelayDaysMinimum) { + body.Add(form.FormatKey(append(keyParts, "delay_days")), "minimum") + } +} + +// Settings specific to the account's payouts. +type AccountSettingsPayoutsParams struct { + // A Boolean indicating whether Stripe should try to reclaim negative balances from an attached bank account. For details, see [Understanding Connect Account Balances](https://docs.stripe.com/connect/account-balances). + DebitNegativeBalances *bool `form:"debit_negative_balances"` + // Details on when funds from charges are available, and when they are paid out to an external account. For details, see our [Setting Bank and Debit Card Payouts](https://docs.stripe.com/connect/bank-transfers#payout-information) documentation. + Schedule *AccountSettingsPayoutsScheduleParams `form:"schedule"` + // The text that appears on the bank account statement for payouts. If not set, this defaults to the platform's bank descriptor as set in the Dashboard. + StatementDescriptor *string `form:"statement_descriptor"` +} + +// Details on the account's acceptance of the Stripe Treasury Services Agreement. +type AccountSettingsTreasuryTOSAcceptanceParams struct { + // The Unix timestamp marking when the account representative accepted the service agreement. + Date *int64 `form:"date"` + // The IP address from which the account representative accepted the service agreement. + IP *string `form:"ip"` + // The user agent of the browser from which the account representative accepted the service agreement. + UserAgent *string `form:"user_agent"` +} + +// Settings specific to the account's Treasury FinancialAccounts. +type AccountSettingsTreasuryParams struct { + // Details on the account's acceptance of the Stripe Treasury Services Agreement. + TOSAcceptance *AccountSettingsTreasuryTOSAcceptanceParams `form:"tos_acceptance"` +} + +// Options for customizing how the account functions within Stripe. +type AccountSettingsParams struct { + // Settings specific to Bacs Direct Debit payments. + BACSDebitPayments *AccountSettingsBACSDebitPaymentsParams `form:"bacs_debit_payments"` + // Settings used to apply the account's branding to email receipts, invoices, Checkout, and other products. + Branding *AccountSettingsBrandingParams `form:"branding"` + // Settings specific to the account's use of the Card Issuing product. + CardIssuing *AccountSettingsCardIssuingParams `form:"card_issuing"` + // Settings specific to card charging on the account. + CardPayments *AccountSettingsCardPaymentsParams `form:"card_payments"` + // Settings specific to the account's use of Invoices. + Invoices *AccountSettingsInvoicesParams `form:"invoices"` + // Settings that apply across payment methods for charging on the account. + Payments *AccountSettingsPaymentsParams `form:"payments"` + // Settings specific to the account's payouts. + Payouts *AccountSettingsPayoutsParams `form:"payouts"` + // Settings specific to the account's Treasury FinancialAccounts. + Treasury *AccountSettingsTreasuryParams `form:"treasury"` +} + +// Details on the account's acceptance of the [Stripe Services Agreement](https://docs.stripe.com/connect/updating-accounts#tos-acceptance). This property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. This property defaults to a `full` service agreement when empty. +type AccountTOSAcceptanceParams struct { + // The Unix timestamp marking when the account representative accepted their service agreement. + Date *int64 `form:"date"` + // The IP address from which the account representative accepted their service agreement. + IP *string `form:"ip"` + // The user's service agreement type. + ServiceAgreement *string `form:"service_agreement"` + // The user agent of the browser from which the account representative accepted their service agreement. + UserAgent *string `form:"user_agent"` +} + +// Returns a list of accounts connected to your platform via [Connect](https://docs.stripe.com/docs/connect). If you're not a platform, the list is empty. +type AccountListParams struct { + ListParams `form:"*"` + // Only return connected accounts that were created during the given date interval. + Created *int64 `form:"created"` + // Only return connected accounts that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *AccountListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A hash of configuration for who pays Stripe fees for product usage on this account. +type AccountControllerFeesParams struct { + // A value indicating the responsible payer of Stripe fees on this account. Defaults to `account`. Learn more about [fee behavior on connected accounts](https://docs.stripe.com/connect/direct-charges-fee-payer-behavior). + Payer *string `form:"payer"` +} + +// A hash of configuration for products that have negative balance liability, and whether Stripe or a Connect application is responsible for them. +type AccountControllerLossesParams struct { + // A value indicating who is liable when this account can't pay back negative balances resulting from payments. Defaults to `stripe`. + Payments *string `form:"payments"` +} + +// A hash of configuration for Stripe-hosted dashboards. +type AccountControllerStripeDashboardParams struct { + // Whether this account should have access to the full Stripe Dashboard (`full`), to the Express Dashboard (`express`), or to no Stripe-hosted dashboard (`none`). Defaults to `full`. + Type *string `form:"type"` +} + +// A hash of configuration describing the account controller's attributes. +type AccountControllerParams struct { + // A hash of configuration for who pays Stripe fees for product usage on this account. + Fees *AccountControllerFeesParams `form:"fees"` + // A hash of configuration for products that have negative balance liability, and whether Stripe or a Connect application is responsible for them. + Losses *AccountControllerLossesParams `form:"losses"` + // A value indicating responsibility for collecting updated information when requirements on the account are due or change. Defaults to `stripe`. + RequirementCollection *string `form:"requirement_collection"` + // A hash of configuration for Stripe-hosted dashboards. + StripeDashboard *AccountControllerStripeDashboardParams `form:"stripe_dashboard"` +} + +// With [Connect](https://docs.stripe.com/connect), you can reject accounts that you have flagged as suspicious. +// +// Only accounts where your platform is liable for negative account balances, which includes Custom and Express accounts, can be rejected. Test-mode accounts can be rejected at any time. Live-mode accounts can only be rejected after all balances are zero. +type AccountRejectParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The reason for rejecting the account. Can be `fraud`, `terms_of_service`, or `other`. + Reason *string `form:"reason"` +} + +// AddExpand appends a new field to expand. +func (p *AccountRejectParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// With [Connect](https://docs.stripe.com/connect), you can delete accounts you manage. +// +// Test-mode accounts can be deleted at any time. +// +// Live-mode accounts where Stripe is responsible for negative account balances cannot be deleted, which includes Standard accounts. Live-mode accounts where your platform is liable for negative account balances, which includes Custom and Express accounts, can be deleted when all [balances](https://docs.stripe.com/api/balance/balance_object) are zero. +// +// If you want to delete your own account, use the [account information tab in your account settings](https://dashboard.stripe.com/settings/account) instead. +type AccountDeleteParams struct { + Params `form:"*"` +} + +// Retrieves the details of an account. +type AccountRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *AccountRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The applicant's gross annual revenue for its preceding fiscal year. +type AccountUpdateBusinessProfileAnnualRevenueParams struct { + // A non-negative integer representing the amount in the [smallest currency unit](https://docs.stripe.com/currencies#zero-decimal). + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The close-out date of the preceding fiscal year in ISO 8601 format. E.g. 2023-12-31 for the 31st of December, 2023. + FiscalYearEnd *string `form:"fiscal_year_end"` +} + +// An estimate of the monthly revenue of the business. Only accepted for accounts in Brazil and India. +type AccountUpdateBusinessProfileMonthlyEstimatedRevenueParams struct { + // A non-negative integer representing how much to charge in the [smallest currency unit](https://docs.stripe.com/currencies#zero-decimal). + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` +} + +// Business information about the account. +type AccountUpdateBusinessProfileParams struct { + // The applicant's gross annual revenue for its preceding fiscal year. + AnnualRevenue *AccountUpdateBusinessProfileAnnualRevenueParams `form:"annual_revenue"` + // An estimated upper bound of employees, contractors, vendors, etc. currently working for the business. + EstimatedWorkerCount *int64 `form:"estimated_worker_count"` + // [The merchant category code for the account](https://docs.stripe.com/connect/setting-mcc). MCCs are used to classify businesses based on the goods or services they provide. + MCC *string `form:"mcc"` + // Whether the business is a minority-owned, women-owned, and/or LGBTQI+-owned business. + MinorityOwnedBusinessDesignation []*string `form:"minority_owned_business_designation"` + // An estimate of the monthly revenue of the business. Only accepted for accounts in Brazil and India. + MonthlyEstimatedRevenue *AccountUpdateBusinessProfileMonthlyEstimatedRevenueParams `form:"monthly_estimated_revenue"` + // The customer-facing business name. + Name *string `form:"name"` + // Internal-only description of the product sold by, or service provided by, the business. Used by Stripe for risk and underwriting purposes. + ProductDescription *string `form:"product_description"` + // A publicly available mailing address for sending support issues to. + SupportAddress *AddressParams `form:"support_address"` + // A publicly available email address for sending support issues to. + SupportEmail *string `form:"support_email"` + // A publicly available phone number to call with support issues. + SupportPhone *string `form:"support_phone"` + // A publicly available website for handling support issues. + SupportURL *string `form:"support_url"` + // The business's publicly available website. + URL *string `form:"url"` +} + +// The acss_debit_payments capability. +type AccountUpdateCapabilitiesACSSDebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The affirm_payments capability. +type AccountUpdateCapabilitiesAffirmPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The afterpay_clearpay_payments capability. +type AccountUpdateCapabilitiesAfterpayClearpayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The alma_payments capability. +type AccountUpdateCapabilitiesAlmaPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The amazon_pay_payments capability. +type AccountUpdateCapabilitiesAmazonPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The au_becs_debit_payments capability. +type AccountUpdateCapabilitiesAUBECSDebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The bacs_debit_payments capability. +type AccountUpdateCapabilitiesBACSDebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The bancontact_payments capability. +type AccountUpdateCapabilitiesBancontactPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The bank_transfer_payments capability. +type AccountUpdateCapabilitiesBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The billie_payments capability. +type AccountUpdateCapabilitiesBilliePaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The blik_payments capability. +type AccountUpdateCapabilitiesBLIKPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The boleto_payments capability. +type AccountUpdateCapabilitiesBoletoPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The card_issuing capability. +type AccountUpdateCapabilitiesCardIssuingParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The card_payments capability. +type AccountUpdateCapabilitiesCardPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The cartes_bancaires_payments capability. +type AccountUpdateCapabilitiesCartesBancairesPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The cashapp_payments capability. +type AccountUpdateCapabilitiesCashAppPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The crypto_payments capability. +type AccountUpdateCapabilitiesCryptoPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The eps_payments capability. +type AccountUpdateCapabilitiesEPSPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The fpx_payments capability. +type AccountUpdateCapabilitiesFPXPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The gb_bank_transfer_payments capability. +type AccountUpdateCapabilitiesGBBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The giropay_payments capability. +type AccountUpdateCapabilitiesGiropayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The grabpay_payments capability. +type AccountUpdateCapabilitiesGrabpayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The ideal_payments capability. +type AccountUpdateCapabilitiesIDEALPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The india_international_payments capability. +type AccountUpdateCapabilitiesIndiaInternationalPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The jcb_payments capability. +type AccountUpdateCapabilitiesJCBPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The jp_bank_transfer_payments capability. +type AccountUpdateCapabilitiesJPBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The kakao_pay_payments capability. +type AccountUpdateCapabilitiesKakaoPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The klarna_payments capability. +type AccountUpdateCapabilitiesKlarnaPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The konbini_payments capability. +type AccountUpdateCapabilitiesKonbiniPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The kr_card_payments capability. +type AccountUpdateCapabilitiesKrCardPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The legacy_payments capability. +type AccountUpdateCapabilitiesLegacyPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The link_payments capability. +type AccountUpdateCapabilitiesLinkPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The mobilepay_payments capability. +type AccountUpdateCapabilitiesMobilepayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The multibanco_payments capability. +type AccountUpdateCapabilitiesMultibancoPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The mx_bank_transfer_payments capability. +type AccountUpdateCapabilitiesMXBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The naver_pay_payments capability. +type AccountUpdateCapabilitiesNaverPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The nz_bank_account_becs_debit_payments capability. +type AccountUpdateCapabilitiesNzBankAccountBECSDebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The oxxo_payments capability. +type AccountUpdateCapabilitiesOXXOPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The p24_payments capability. +type AccountUpdateCapabilitiesP24PaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The pay_by_bank_payments capability. +type AccountUpdateCapabilitiesPayByBankPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The payco_payments capability. +type AccountUpdateCapabilitiesPaycoPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The paynow_payments capability. +type AccountUpdateCapabilitiesPayNowPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The pix_payments capability. +type AccountUpdateCapabilitiesPixPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The promptpay_payments capability. +type AccountUpdateCapabilitiesPromptPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The revolut_pay_payments capability. +type AccountUpdateCapabilitiesRevolutPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The samsung_pay_payments capability. +type AccountUpdateCapabilitiesSamsungPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The satispay_payments capability. +type AccountUpdateCapabilitiesSatispayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The sepa_bank_transfer_payments capability. +type AccountUpdateCapabilitiesSEPABankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The sepa_debit_payments capability. +type AccountUpdateCapabilitiesSEPADebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The sofort_payments capability. +type AccountUpdateCapabilitiesSofortPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The swish_payments capability. +type AccountUpdateCapabilitiesSwishPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The tax_reporting_us_1099_k capability. +type AccountUpdateCapabilitiesTaxReportingUS1099KParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The tax_reporting_us_1099_misc capability. +type AccountUpdateCapabilitiesTaxReportingUS1099MISCParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The transfers capability. +type AccountUpdateCapabilitiesTransfersParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The treasury capability. +type AccountUpdateCapabilitiesTreasuryParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The twint_payments capability. +type AccountUpdateCapabilitiesTWINTPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The us_bank_account_ach_payments capability. +type AccountUpdateCapabilitiesUSBankAccountACHPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The us_bank_transfer_payments capability. +type AccountUpdateCapabilitiesUSBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The zip_payments capability. +type AccountUpdateCapabilitiesZipPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// Each key of the dictionary represents a capability, and each capability +// maps to its settings (for example, whether it has been requested or not). Each +// capability is inactive until you have provided its specific +// requirements and Stripe has verified them. An account might have some +// of its requested capabilities be active and some be inactive. +// +// Required when [account.controller.stripe_dashboard.type](https://docs.stripe.com/api/accounts/create#create_account-controller-dashboard-type) +// is `none`, which includes Custom accounts. +type AccountUpdateCapabilitiesParams struct { + // The acss_debit_payments capability. + ACSSDebitPayments *AccountUpdateCapabilitiesACSSDebitPaymentsParams `form:"acss_debit_payments"` + // The affirm_payments capability. + AffirmPayments *AccountUpdateCapabilitiesAffirmPaymentsParams `form:"affirm_payments"` + // The afterpay_clearpay_payments capability. + AfterpayClearpayPayments *AccountUpdateCapabilitiesAfterpayClearpayPaymentsParams `form:"afterpay_clearpay_payments"` + // The alma_payments capability. + AlmaPayments *AccountUpdateCapabilitiesAlmaPaymentsParams `form:"alma_payments"` + // The amazon_pay_payments capability. + AmazonPayPayments *AccountUpdateCapabilitiesAmazonPayPaymentsParams `form:"amazon_pay_payments"` + // The au_becs_debit_payments capability. + AUBECSDebitPayments *AccountUpdateCapabilitiesAUBECSDebitPaymentsParams `form:"au_becs_debit_payments"` + // The bacs_debit_payments capability. + BACSDebitPayments *AccountUpdateCapabilitiesBACSDebitPaymentsParams `form:"bacs_debit_payments"` + // The bancontact_payments capability. + BancontactPayments *AccountUpdateCapabilitiesBancontactPaymentsParams `form:"bancontact_payments"` + // The bank_transfer_payments capability. + BankTransferPayments *AccountUpdateCapabilitiesBankTransferPaymentsParams `form:"bank_transfer_payments"` + // The billie_payments capability. + BilliePayments *AccountUpdateCapabilitiesBilliePaymentsParams `form:"billie_payments"` + // The blik_payments capability. + BLIKPayments *AccountUpdateCapabilitiesBLIKPaymentsParams `form:"blik_payments"` + // The boleto_payments capability. + BoletoPayments *AccountUpdateCapabilitiesBoletoPaymentsParams `form:"boleto_payments"` + // The card_issuing capability. + CardIssuing *AccountUpdateCapabilitiesCardIssuingParams `form:"card_issuing"` + // The card_payments capability. + CardPayments *AccountUpdateCapabilitiesCardPaymentsParams `form:"card_payments"` + // The cartes_bancaires_payments capability. + CartesBancairesPayments *AccountUpdateCapabilitiesCartesBancairesPaymentsParams `form:"cartes_bancaires_payments"` + // The cashapp_payments capability. + CashAppPayments *AccountUpdateCapabilitiesCashAppPaymentsParams `form:"cashapp_payments"` + // The crypto_payments capability. + CryptoPayments *AccountUpdateCapabilitiesCryptoPaymentsParams `form:"crypto_payments"` + // The eps_payments capability. + EPSPayments *AccountUpdateCapabilitiesEPSPaymentsParams `form:"eps_payments"` + // The fpx_payments capability. + FPXPayments *AccountUpdateCapabilitiesFPXPaymentsParams `form:"fpx_payments"` + // The gb_bank_transfer_payments capability. + GBBankTransferPayments *AccountUpdateCapabilitiesGBBankTransferPaymentsParams `form:"gb_bank_transfer_payments"` + // The giropay_payments capability. + GiropayPayments *AccountUpdateCapabilitiesGiropayPaymentsParams `form:"giropay_payments"` + // The grabpay_payments capability. + GrabpayPayments *AccountUpdateCapabilitiesGrabpayPaymentsParams `form:"grabpay_payments"` + // The ideal_payments capability. + IDEALPayments *AccountUpdateCapabilitiesIDEALPaymentsParams `form:"ideal_payments"` + // The india_international_payments capability. + IndiaInternationalPayments *AccountUpdateCapabilitiesIndiaInternationalPaymentsParams `form:"india_international_payments"` + // The jcb_payments capability. + JCBPayments *AccountUpdateCapabilitiesJCBPaymentsParams `form:"jcb_payments"` + // The jp_bank_transfer_payments capability. + JPBankTransferPayments *AccountUpdateCapabilitiesJPBankTransferPaymentsParams `form:"jp_bank_transfer_payments"` + // The kakao_pay_payments capability. + KakaoPayPayments *AccountUpdateCapabilitiesKakaoPayPaymentsParams `form:"kakao_pay_payments"` + // The klarna_payments capability. + KlarnaPayments *AccountUpdateCapabilitiesKlarnaPaymentsParams `form:"klarna_payments"` + // The konbini_payments capability. + KonbiniPayments *AccountUpdateCapabilitiesKonbiniPaymentsParams `form:"konbini_payments"` + // The kr_card_payments capability. + KrCardPayments *AccountUpdateCapabilitiesKrCardPaymentsParams `form:"kr_card_payments"` + // The legacy_payments capability. + LegacyPayments *AccountUpdateCapabilitiesLegacyPaymentsParams `form:"legacy_payments"` + // The link_payments capability. + LinkPayments *AccountUpdateCapabilitiesLinkPaymentsParams `form:"link_payments"` + // The mobilepay_payments capability. + MobilepayPayments *AccountUpdateCapabilitiesMobilepayPaymentsParams `form:"mobilepay_payments"` + // The multibanco_payments capability. + MultibancoPayments *AccountUpdateCapabilitiesMultibancoPaymentsParams `form:"multibanco_payments"` + // The mx_bank_transfer_payments capability. + MXBankTransferPayments *AccountUpdateCapabilitiesMXBankTransferPaymentsParams `form:"mx_bank_transfer_payments"` + // The naver_pay_payments capability. + NaverPayPayments *AccountUpdateCapabilitiesNaverPayPaymentsParams `form:"naver_pay_payments"` + // The nz_bank_account_becs_debit_payments capability. + NzBankAccountBECSDebitPayments *AccountUpdateCapabilitiesNzBankAccountBECSDebitPaymentsParams `form:"nz_bank_account_becs_debit_payments"` + // The oxxo_payments capability. + OXXOPayments *AccountUpdateCapabilitiesOXXOPaymentsParams `form:"oxxo_payments"` + // The p24_payments capability. + P24Payments *AccountUpdateCapabilitiesP24PaymentsParams `form:"p24_payments"` + // The pay_by_bank_payments capability. + PayByBankPayments *AccountUpdateCapabilitiesPayByBankPaymentsParams `form:"pay_by_bank_payments"` + // The payco_payments capability. + PaycoPayments *AccountUpdateCapabilitiesPaycoPaymentsParams `form:"payco_payments"` + // The paynow_payments capability. + PayNowPayments *AccountUpdateCapabilitiesPayNowPaymentsParams `form:"paynow_payments"` + // The pix_payments capability. + PixPayments *AccountUpdateCapabilitiesPixPaymentsParams `form:"pix_payments"` + // The promptpay_payments capability. + PromptPayPayments *AccountUpdateCapabilitiesPromptPayPaymentsParams `form:"promptpay_payments"` + // The revolut_pay_payments capability. + RevolutPayPayments *AccountUpdateCapabilitiesRevolutPayPaymentsParams `form:"revolut_pay_payments"` + // The samsung_pay_payments capability. + SamsungPayPayments *AccountUpdateCapabilitiesSamsungPayPaymentsParams `form:"samsung_pay_payments"` + // The satispay_payments capability. + SatispayPayments *AccountUpdateCapabilitiesSatispayPaymentsParams `form:"satispay_payments"` + // The sepa_bank_transfer_payments capability. + SEPABankTransferPayments *AccountUpdateCapabilitiesSEPABankTransferPaymentsParams `form:"sepa_bank_transfer_payments"` + // The sepa_debit_payments capability. + SEPADebitPayments *AccountUpdateCapabilitiesSEPADebitPaymentsParams `form:"sepa_debit_payments"` + // The sofort_payments capability. + SofortPayments *AccountUpdateCapabilitiesSofortPaymentsParams `form:"sofort_payments"` + // The swish_payments capability. + SwishPayments *AccountUpdateCapabilitiesSwishPaymentsParams `form:"swish_payments"` + // The tax_reporting_us_1099_k capability. + TaxReportingUS1099K *AccountUpdateCapabilitiesTaxReportingUS1099KParams `form:"tax_reporting_us_1099_k"` + // The tax_reporting_us_1099_misc capability. + TaxReportingUS1099MISC *AccountUpdateCapabilitiesTaxReportingUS1099MISCParams `form:"tax_reporting_us_1099_misc"` + // The transfers capability. + Transfers *AccountUpdateCapabilitiesTransfersParams `form:"transfers"` + // The treasury capability. + Treasury *AccountUpdateCapabilitiesTreasuryParams `form:"treasury"` + // The twint_payments capability. + TWINTPayments *AccountUpdateCapabilitiesTWINTPaymentsParams `form:"twint_payments"` + // The us_bank_account_ach_payments capability. + USBankAccountACHPayments *AccountUpdateCapabilitiesUSBankAccountACHPaymentsParams `form:"us_bank_account_ach_payments"` + // The us_bank_transfer_payments capability. + USBankTransferPayments *AccountUpdateCapabilitiesUSBankTransferPaymentsParams `form:"us_bank_transfer_payments"` + // The zip_payments capability. + ZipPayments *AccountUpdateCapabilitiesZipPaymentsParams `form:"zip_payments"` +} + +// The Kana variation of the company's primary address (Japan only). +type AccountUpdateCompanyAddressKanaParams struct { + // City or ward. + City *string `form:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // Block or building number. + Line1 *string `form:"line1"` + // Building details. + Line2 *string `form:"line2"` + // Postal code. + PostalCode *string `form:"postal_code"` + // Prefecture. + State *string `form:"state"` + // Town or cho-me. + Town *string `form:"town"` +} + +// The Kanji variation of the company's primary address (Japan only). +type AccountUpdateCompanyAddressKanjiParams struct { + // City or ward. + City *string `form:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // Block or building number. + Line1 *string `form:"line1"` + // Building details. + Line2 *string `form:"line2"` + // Postal code. + PostalCode *string `form:"postal_code"` + // Prefecture. + State *string `form:"state"` + // Town or cho-me. + Town *string `form:"town"` +} + +// This hash is used to attest that the directors information provided to Stripe is both current and correct. +type AccountUpdateCompanyDirectorshipDeclarationParams struct { + // The Unix timestamp marking when the directorship declaration attestation was made. + Date *int64 `form:"date"` + // The IP address from which the directorship declaration attestation was made. + IP *string `form:"ip"` + // The user agent of the browser from which the directorship declaration attestation was made. + UserAgent *string `form:"user_agent"` +} + +// This hash is used to attest that the beneficial owner information provided to Stripe is both current and correct. +type AccountUpdateCompanyOwnershipDeclarationParams struct { + // The Unix timestamp marking when the beneficial owner attestation was made. + Date *int64 `form:"date"` + // The IP address from which the beneficial owner attestation was made. + IP *string `form:"ip"` + // The user agent of the browser from which the beneficial owner attestation was made. + UserAgent *string `form:"user_agent"` +} +type AccountUpdateCompanyRegistrationDateParams struct { + // The day of registration, between 1 and 31. + Day *int64 `form:"day"` + // The month of registration, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of registration. + Year *int64 `form:"year"` +} + +// A document verifying the business. +type AccountUpdateCompanyVerificationDocumentParams struct { + // The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Back *string `form:"back"` + // The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Front *string `form:"front"` +} + +// Information on the verification state of the company. +type AccountUpdateCompanyVerificationParams struct { + // A document verifying the business. + Document *AccountUpdateCompanyVerificationDocumentParams `form:"document"` +} + +// Information about the company or business. This field is available for any `business_type`. Once you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. +type AccountUpdateCompanyParams struct { + // The company's primary address. + Address *AddressParams `form:"address"` + // The Kana variation of the company's primary address (Japan only). + AddressKana *AccountUpdateCompanyAddressKanaParams `form:"address_kana"` + // The Kanji variation of the company's primary address (Japan only). + AddressKanji *AccountUpdateCompanyAddressKanjiParams `form:"address_kanji"` + // This hash is used to attest that the directors information provided to Stripe is both current and correct. + DirectorshipDeclaration *AccountUpdateCompanyDirectorshipDeclarationParams `form:"directorship_declaration"` + // Whether the company's directors have been provided. Set this Boolean to `true` after creating all the company's directors with [the Persons API](https://docs.stripe.com/api/persons) for accounts with a `relationship.director` requirement. This value is not automatically set to `true` after creating directors, so it needs to be updated to indicate all directors have been provided. + DirectorsProvided *bool `form:"directors_provided"` + // Whether the company's executives have been provided. Set this Boolean to `true` after creating all the company's executives with [the Persons API](https://docs.stripe.com/api/persons) for accounts with a `relationship.executive` requirement. + ExecutivesProvided *bool `form:"executives_provided"` + // The export license ID number of the company, also referred as Import Export Code (India only). + ExportLicenseID *string `form:"export_license_id"` + // The purpose code to use for export transactions (India only). + ExportPurposeCode *string `form:"export_purpose_code"` + // The company's legal name. + Name *string `form:"name"` + // The Kana variation of the company's legal name (Japan only). + NameKana *string `form:"name_kana"` + // The Kanji variation of the company's legal name (Japan only). + NameKanji *string `form:"name_kanji"` + // This hash is used to attest that the beneficial owner information provided to Stripe is both current and correct. + OwnershipDeclaration *AccountUpdateCompanyOwnershipDeclarationParams `form:"ownership_declaration"` + // This value is used to determine if a business is exempt from providing ultimate beneficial owners. See [this support article](https://support.stripe.com/questions/exemption-from-providing-ownership-details) and [changelog](https://docs.stripe.com/changelog/acacia/2025-01-27/ownership-exemption-reason-accounts-api) for more details. + OwnershipExemptionReason *string `form:"ownership_exemption_reason"` + // Whether the company's owners have been provided. Set this Boolean to `true` after creating all the company's owners with [the Persons API](https://docs.stripe.com/api/persons) for accounts with a `relationship.owner` requirement. + OwnersProvided *bool `form:"owners_provided"` + // The company's phone number (used for verification). + Phone *string `form:"phone"` + RegistrationDate *AccountUpdateCompanyRegistrationDateParams `form:"registration_date"` + // The identification number given to a company when it is registered or incorporated, if distinct from the identification number used for filing taxes. (Examples are the CIN for companies and LLP IN for partnerships in India, and the Company Registration Number in Hong Kong). + RegistrationNumber *string `form:"registration_number"` + // The category identifying the legal structure of the company or legal entity. See [Business structure](https://docs.stripe.com/connect/identity-verification#business-structure) for more details. Pass an empty string to unset this value. + Structure *string `form:"structure"` + // The business ID number of the company, as appropriate for the company's country. (Examples are an Employer ID Number in the U.S., a Business Number in Canada, or a Company Number in the UK.) + TaxID *string `form:"tax_id"` + // The jurisdiction in which the `tax_id` is registered (Germany-based companies only). + TaxIDRegistrar *string `form:"tax_id_registrar"` + // The VAT number of the company. + VATID *string `form:"vat_id"` + // Information on the verification state of the company. + Verification *AccountUpdateCompanyVerificationParams `form:"verification"` +} + +// One or more documents that support the [Bank account ownership verification](https://support.stripe.com/questions/bank-account-ownership-verification) requirement. Must be a document associated with the account's primary active bank account that displays the last 4 digits of the account number, either a statement or a check. +type AccountUpdateDocumentsBankAccountOwnershipVerificationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of a company's license to operate. +type AccountUpdateDocumentsCompanyLicenseParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents showing the company's Memorandum of Association. +type AccountUpdateDocumentsCompanyMemorandumOfAssociationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// (Certain countries only) One or more documents showing the ministerial decree legalizing the company's establishment. +type AccountUpdateDocumentsCompanyMinisterialDecreeParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of a company's registration with the appropriate local authorities. +type AccountUpdateDocumentsCompanyRegistrationVerificationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of a company's tax ID. +type AccountUpdateDocumentsCompanyTaxIDVerificationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of address. +type AccountUpdateDocumentsProofOfAddressParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents showing the company's proof of registration with the national business registry. +type AccountUpdateDocumentsProofOfRegistrationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of ultimate beneficial ownership. +type AccountUpdateDocumentsProofOfUltimateBeneficialOwnershipParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// Documents that may be submitted to satisfy various informational requests. +type AccountUpdateDocumentsParams struct { + // One or more documents that support the [Bank account ownership verification](https://support.stripe.com/questions/bank-account-ownership-verification) requirement. Must be a document associated with the account's primary active bank account that displays the last 4 digits of the account number, either a statement or a check. + BankAccountOwnershipVerification *AccountUpdateDocumentsBankAccountOwnershipVerificationParams `form:"bank_account_ownership_verification"` + // One or more documents that demonstrate proof of a company's license to operate. + CompanyLicense *AccountUpdateDocumentsCompanyLicenseParams `form:"company_license"` + // One or more documents showing the company's Memorandum of Association. + CompanyMemorandumOfAssociation *AccountUpdateDocumentsCompanyMemorandumOfAssociationParams `form:"company_memorandum_of_association"` + // (Certain countries only) One or more documents showing the ministerial decree legalizing the company's establishment. + CompanyMinisterialDecree *AccountUpdateDocumentsCompanyMinisterialDecreeParams `form:"company_ministerial_decree"` + // One or more documents that demonstrate proof of a company's registration with the appropriate local authorities. + CompanyRegistrationVerification *AccountUpdateDocumentsCompanyRegistrationVerificationParams `form:"company_registration_verification"` + // One or more documents that demonstrate proof of a company's tax ID. + CompanyTaxIDVerification *AccountUpdateDocumentsCompanyTaxIDVerificationParams `form:"company_tax_id_verification"` + // One or more documents that demonstrate proof of address. + ProofOfAddress *AccountUpdateDocumentsProofOfAddressParams `form:"proof_of_address"` + // One or more documents showing the company's proof of registration with the national business registry. + ProofOfRegistration *AccountUpdateDocumentsProofOfRegistrationParams `form:"proof_of_registration"` + // One or more documents that demonstrate proof of ultimate beneficial ownership. + ProofOfUltimateBeneficialOwnership *AccountUpdateDocumentsProofOfUltimateBeneficialOwnershipParams `form:"proof_of_ultimate_beneficial_ownership"` +} + +// A card or bank account to attach to the account for receiving [payouts](https://docs.stripe.com/connect/bank-debit-card-payouts) (you won't be able to use it for top-ups). You can provide either a token, like the ones returned by [Stripe.js](https://docs.stripe.com/js), or a dictionary, as documented in the `external_account` parameter for [bank account](https://docs.stripe.com/api#account_create_bank_account) creation. +// +// By default, providing an external account sets it as the new default external account for its currency, and deletes the old default if one exists. To add additional external accounts without replacing the existing default for the currency, use the [bank account](https://docs.stripe.com/api#account_create_bank_account) or [card creation](https://docs.stripe.com/api#account_create_card) APIs. After you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. +type AccountUpdateExternalAccountParams struct { + // The name of the person or business that owns the bank account.This field is required when attaching the bank account to a `Customer` object. + AccountHolderName *string `form:"account_holder_name"` + // The type of entity that holds the account. It can be `company` or `individual`. This field is required when attaching the bank account to a `Customer` object. + AccountHolderType *string `form:"account_holder_type"` + // The account number for the bank account, in string form. Must be a checking account. + AccountNumber *string `form:"account_number"` + AddressCity *string `form:"address_city"` + AddressCountry *string `form:"address_country"` + AddressLine1 *string `form:"address_line1"` + AddressLine2 *string `form:"address_line2"` + AddressState *string `form:"address_state"` + AddressZip *string `form:"address_zip"` + // The country in which the bank account is located. + Country *string `form:"country"` + // The currency the bank account is in. This must be a country/currency pairing that [Stripe supports.](docs/payouts) + Currency *string `form:"currency"` + CVC *string `form:"cvc"` + DefaultForCurrency *bool `form:"default_for_currency"` + ExpMonth *int64 `form:"exp_month"` + ExpYear *int64 `form:"exp_year"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `form:"metadata"` + Name *string `form:"name"` + Number *string `form:"number"` + Object *string `form:"object"` + // The routing number, sort code, or other country-appropriate institution number for the bank account. For US bank accounts, this is required and should be the ACH routing number, not the wire routing number. If you are providing an IBAN for `account_number`, this field is not required. + RoutingNumber *string `form:"routing_number"` + Token *string `form:"token"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *AccountUpdateExternalAccountParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A hash of account group type to tokens. These are account groups this account should be added to. +type AccountUpdateGroupsParams struct { + // The group the account is in to determine their payments pricing, and null if the account is on customized pricing. [See the Platform pricing tool documentation](https://stripe.com/docs/connect/platform-pricing-tools) for details. + PaymentsPricing *string `form:"payments_pricing"` +} + +// Settings specific to Bacs Direct Debit payments. +type AccountUpdateSettingsBACSDebitPaymentsParams struct { + // The Bacs Direct Debit Display Name for this account. For payments made with Bacs Direct Debit, this name appears on the mandate as the statement descriptor. Mobile banking apps display it as the name of the business. To use custom branding, set the Bacs Direct Debit Display Name during or right after creation. Custom branding incurs an additional monthly fee for the platform. If you don't set the display name before requesting Bacs capability, it's automatically set as "Stripe" and the account is onboarded to Stripe branding, which is free. + DisplayName *string `form:"display_name"` +} + +// Settings used to apply the account's branding to email receipts, invoices, Checkout, and other products. +type AccountUpdateSettingsBrandingParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) An icon for the account. Must be square and at least 128px x 128px. + Icon *string `form:"icon"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) A logo for the account that will be used in Checkout instead of the icon and without the account's name next to it if provided. Must be at least 128px x 128px. + Logo *string `form:"logo"` + // A CSS hex color value representing the primary branding color for this account. + PrimaryColor *string `form:"primary_color"` + // A CSS hex color value representing the secondary branding color for this account. + SecondaryColor *string `form:"secondary_color"` +} + +// Details on the account's acceptance of the [Stripe Issuing Terms and Disclosures](https://docs.stripe.com/issuing/connect/tos_acceptance). +type AccountUpdateSettingsCardIssuingTOSAcceptanceParams struct { + // The Unix timestamp marking when the account representative accepted the service agreement. + Date *int64 `form:"date"` + // The IP address from which the account representative accepted the service agreement. + IP *string `form:"ip"` + // The user agent of the browser from which the account representative accepted the service agreement. + UserAgent *string `form:"user_agent"` +} + +// Settings specific to the account's use of the Card Issuing product. +type AccountUpdateSettingsCardIssuingParams struct { + // Details on the account's acceptance of the [Stripe Issuing Terms and Disclosures](https://docs.stripe.com/issuing/connect/tos_acceptance). + TOSAcceptance *AccountUpdateSettingsCardIssuingTOSAcceptanceParams `form:"tos_acceptance"` +} + +// Automatically declines certain charge types regardless of whether the card issuer accepted or declined the charge. +type AccountUpdateSettingsCardPaymentsDeclineOnParams struct { + // Whether Stripe automatically declines charges with an incorrect ZIP or postal code. This setting only applies when a ZIP or postal code is provided and they fail bank verification. + AVSFailure *bool `form:"avs_failure"` + // Whether Stripe automatically declines charges with an incorrect CVC. This setting only applies when a CVC is provided and it fails bank verification. + CVCFailure *bool `form:"cvc_failure"` +} + +// Settings specific to card charging on the account. +type AccountUpdateSettingsCardPaymentsParams struct { + // Automatically declines certain charge types regardless of whether the card issuer accepted or declined the charge. + DeclineOn *AccountUpdateSettingsCardPaymentsDeclineOnParams `form:"decline_on"` + // The default text that appears on credit card statements when a charge is made. This field prefixes any dynamic `statement_descriptor` specified on the charge. `statement_descriptor_prefix` is useful for maximizing descriptor space for the dynamic portion. + StatementDescriptorPrefix *string `form:"statement_descriptor_prefix"` + // The Kana variation of the default text that appears on credit card statements when a charge is made (Japan only). This field prefixes any dynamic `statement_descriptor_suffix_kana` specified on the charge. `statement_descriptor_prefix_kana` is useful for maximizing descriptor space for the dynamic portion. + StatementDescriptorPrefixKana *string `form:"statement_descriptor_prefix_kana"` + // The Kanji variation of the default text that appears on credit card statements when a charge is made (Japan only). This field prefixes any dynamic `statement_descriptor_suffix_kanji` specified on the charge. `statement_descriptor_prefix_kanji` is useful for maximizing descriptor space for the dynamic portion. + StatementDescriptorPrefixKanji *string `form:"statement_descriptor_prefix_kanji"` +} + +// Settings specific to the account's use of Invoices. +type AccountUpdateSettingsInvoicesParams struct { + // The list of default Account Tax IDs to automatically include on invoices. Account Tax IDs get added when an invoice is finalized. + DefaultAccountTaxIDs []*string `form:"default_account_tax_ids"` + // Whether payment methods should be saved when a payment is completed for a one-time invoices on a hosted invoice page. + HostedPaymentMethodSave *string `form:"hosted_payment_method_save"` +} + +// Settings that apply across payment methods for charging on the account. +type AccountUpdateSettingsPaymentsParams struct { + // The default text that appears on statements for non-card charges outside of Japan. For card charges, if you don't set a `statement_descriptor_prefix`, this text is also used as the statement descriptor prefix. In that case, if concatenating the statement descriptor suffix causes the combined statement descriptor to exceed 22 characters, we truncate the `statement_descriptor` text to limit the full descriptor to 22 characters. For more information about statement descriptors and their requirements, see the [account settings documentation](https://docs.stripe.com/get-started/account/statement-descriptors). + StatementDescriptor *string `form:"statement_descriptor"` + // The Kana variation of `statement_descriptor` used for charges in Japan. Japanese statement descriptors have [special requirements](https://docs.stripe.com/get-started/account/statement-descriptors#set-japanese-statement-descriptors). + StatementDescriptorKana *string `form:"statement_descriptor_kana"` + // The Kanji variation of `statement_descriptor` used for charges in Japan. Japanese statement descriptors have [special requirements](https://docs.stripe.com/get-started/account/statement-descriptors#set-japanese-statement-descriptors). + StatementDescriptorKanji *string `form:"statement_descriptor_kanji"` +} + +// Details on when funds from charges are available, and when they are paid out to an external account. For details, see our [Setting Bank and Debit Card Payouts](https://docs.stripe.com/connect/bank-transfers#payout-information) documentation. +type AccountUpdateSettingsPayoutsScheduleParams struct { + // The number of days charge funds are held before being paid out. May also be set to `minimum`, representing the lowest available value for the account country. Default is `minimum`. The `delay_days` parameter remains at the last configured value if `interval` is `manual`. [Learn more about controlling payout delay days](https://docs.stripe.com/connect/manage-payout-schedule). + DelayDays *int64 `form:"delay_days"` + DelayDaysMinimum *bool `form:"-"` // See custom AppendTo + // How frequently available funds are paid out. One of: `daily`, `manual`, `weekly`, or `monthly`. Default is `daily`. + Interval *string `form:"interval"` + // The day of the month when available funds are paid out, specified as a number between 1--31. Payouts nominally scheduled between the 29th and 31st of the month are instead sent on the last day of a shorter month. Required and applicable only if `interval` is `monthly`. + MonthlyAnchor *int64 `form:"monthly_anchor"` + // The days of the month when available funds are paid out, specified as an array of numbers between 1--31. Payouts nominally scheduled between the 29th and 31st of the month are instead sent on the last day of a shorter month. Required and applicable only if `interval` is `monthly` and `monthly_anchor` is not set. + MonthlyPayoutDays []*int64 `form:"monthly_payout_days"` + // The day of the week when available funds are paid out, specified as `monday`, `tuesday`, etc. (required and applicable only if `interval` is `weekly`.) + WeeklyAnchor *string `form:"weekly_anchor"` + // The days of the week when available funds are paid out, specified as an array, e.g., [`monday`, `tuesday`]. (required and applicable only if `interval` is `weekly` and `weekly_anchor` is not set.) + WeeklyPayoutDays []*string `form:"weekly_payout_days"` +} + +// AppendTo implements custom encoding logic for AccountUpdateSettingsPayoutsScheduleParams. +func (p *AccountUpdateSettingsPayoutsScheduleParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.DelayDaysMinimum) { + body.Add(form.FormatKey(append(keyParts, "delay_days")), "minimum") + } +} + +// Settings specific to the account's payouts. +type AccountUpdateSettingsPayoutsParams struct { + // A Boolean indicating whether Stripe should try to reclaim negative balances from an attached bank account. For details, see [Understanding Connect Account Balances](https://docs.stripe.com/connect/account-balances). + DebitNegativeBalances *bool `form:"debit_negative_balances"` + // Details on when funds from charges are available, and when they are paid out to an external account. For details, see our [Setting Bank and Debit Card Payouts](https://docs.stripe.com/connect/bank-transfers#payout-information) documentation. + Schedule *AccountUpdateSettingsPayoutsScheduleParams `form:"schedule"` + // The text that appears on the bank account statement for payouts. If not set, this defaults to the platform's bank descriptor as set in the Dashboard. + StatementDescriptor *string `form:"statement_descriptor"` +} + +// Details on the account's acceptance of the Stripe Treasury Services Agreement. +type AccountUpdateSettingsTreasuryTOSAcceptanceParams struct { + // The Unix timestamp marking when the account representative accepted the service agreement. + Date *int64 `form:"date"` + // The IP address from which the account representative accepted the service agreement. + IP *string `form:"ip"` + // The user agent of the browser from which the account representative accepted the service agreement. + UserAgent *string `form:"user_agent"` +} + +// Settings specific to the account's Treasury FinancialAccounts. +type AccountUpdateSettingsTreasuryParams struct { + // Details on the account's acceptance of the Stripe Treasury Services Agreement. + TOSAcceptance *AccountUpdateSettingsTreasuryTOSAcceptanceParams `form:"tos_acceptance"` +} + +// Options for customizing how the account functions within Stripe. +type AccountUpdateSettingsParams struct { + // Settings specific to Bacs Direct Debit payments. + BACSDebitPayments *AccountUpdateSettingsBACSDebitPaymentsParams `form:"bacs_debit_payments"` + // Settings used to apply the account's branding to email receipts, invoices, Checkout, and other products. + Branding *AccountUpdateSettingsBrandingParams `form:"branding"` + // Settings specific to the account's use of the Card Issuing product. + CardIssuing *AccountUpdateSettingsCardIssuingParams `form:"card_issuing"` + // Settings specific to card charging on the account. + CardPayments *AccountUpdateSettingsCardPaymentsParams `form:"card_payments"` + // Settings specific to the account's use of Invoices. + Invoices *AccountUpdateSettingsInvoicesParams `form:"invoices"` + // Settings that apply across payment methods for charging on the account. + Payments *AccountUpdateSettingsPaymentsParams `form:"payments"` + // Settings specific to the account's payouts. + Payouts *AccountUpdateSettingsPayoutsParams `form:"payouts"` + // Settings specific to the account's Treasury FinancialAccounts. + Treasury *AccountUpdateSettingsTreasuryParams `form:"treasury"` +} + +// Details on the account's acceptance of the [Stripe Services Agreement](https://docs.stripe.com/connect/updating-accounts#tos-acceptance). This property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. This property defaults to a `full` service agreement when empty. +type AccountUpdateTOSAcceptanceParams struct { + // The Unix timestamp marking when the account representative accepted their service agreement. + Date *int64 `form:"date"` + // The IP address from which the account representative accepted their service agreement. + IP *string `form:"ip"` + // The user's service agreement type. + ServiceAgreement *string `form:"service_agreement"` + // The user agent of the browser from which the account representative accepted their service agreement. + UserAgent *string `form:"user_agent"` +} + +// Updates a [connected account](https://docs.stripe.com/connect/accounts) by setting the values of the parameters passed. Any parameters not provided are +// left unchanged. +// +// For accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) +// is application, which includes Custom accounts, you can update any information on the account. +// +// For accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) +// is stripe, which includes Standard and Express accounts, you can update all information until you create +// an [Account Link or Account Session](https://docs.stripe.com/api/account_links) to start Connect onboarding, +// after which some properties can no longer be updated. +// +// To update your own account, use the [Dashboard](https://dashboard.stripe.com/settings/account). Refer to our +// [Connect](https://docs.stripe.com/docs/connect/updating-accounts) documentation to learn more about updating accounts. +type AccountUpdateParams struct { + Params `form:"*"` + // An [account token](https://stripe.com/docs/api#create_account_token), used to securely provide details to the account. + AccountToken *string `form:"account_token"` + // Business information about the account. + BusinessProfile *AccountUpdateBusinessProfileParams `form:"business_profile"` + // The business type. Once you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. + BusinessType *string `form:"business_type"` + // Each key of the dictionary represents a capability, and each capability + // maps to its settings (for example, whether it has been requested or not). Each + // capability is inactive until you have provided its specific + // requirements and Stripe has verified them. An account might have some + // of its requested capabilities be active and some be inactive. + // + // Required when [account.controller.stripe_dashboard.type](https://docs.stripe.com/api/accounts/create#create_account-controller-dashboard-type) + // is `none`, which includes Custom accounts. + Capabilities *AccountUpdateCapabilitiesParams `form:"capabilities"` + // Information about the company or business. This field is available for any `business_type`. Once you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. + Company *AccountUpdateCompanyParams `form:"company"` + // Three-letter ISO currency code representing the default currency for the account. This must be a currency that [Stripe supports in the account's country](https://docs.stripe.com/payouts). + DefaultCurrency *string `form:"default_currency"` + // Documents that may be submitted to satisfy various informational requests. + Documents *AccountUpdateDocumentsParams `form:"documents"` + // The email address of the account holder. This is only to make the account easier to identify to you. If [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts, Stripe doesn't email the account without your consent. + Email *string `form:"email"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A card or bank account to attach to the account for receiving [payouts](https://docs.stripe.com/connect/bank-debit-card-payouts) (you won't be able to use it for top-ups). You can provide either a token, like the ones returned by [Stripe.js](https://docs.stripe.com/js), or a dictionary, as documented in the `external_account` parameter for [bank account](https://docs.stripe.com/api#account_create_bank_account) creation. + // + // By default, providing an external account sets it as the new default external account for its currency, and deletes the old default if one exists. To add additional external accounts without replacing the existing default for the currency, use the [bank account](https://docs.stripe.com/api#account_create_bank_account) or [card creation](https://docs.stripe.com/api#account_create_card) APIs. After you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. + ExternalAccount *AccountExternalAccountParams `form:"external_account"` + // A hash of account group type to tokens. These are account groups this account should be added to. + Groups *AccountUpdateGroupsParams `form:"groups"` + // Information about the person represented by the account. This field is null unless `business_type` is set to `individual`. Once you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. + Individual *PersonParams `form:"individual"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Options for customizing how the account functions within Stripe. + Settings *AccountUpdateSettingsParams `form:"settings"` + // Details on the account's acceptance of the [Stripe Services Agreement](https://docs.stripe.com/connect/updating-accounts#tos-acceptance). This property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. This property defaults to a `full` service agreement when empty. + TOSAcceptance *AccountUpdateTOSAcceptanceParams `form:"tos_acceptance"` +} + +// AddExpand appends a new field to expand. +func (p *AccountUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *AccountUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The applicant's gross annual revenue for its preceding fiscal year. +type AccountCreateBusinessProfileAnnualRevenueParams struct { + // A non-negative integer representing the amount in the [smallest currency unit](https://docs.stripe.com/currencies#zero-decimal). + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The close-out date of the preceding fiscal year in ISO 8601 format. E.g. 2023-12-31 for the 31st of December, 2023. + FiscalYearEnd *string `form:"fiscal_year_end"` +} + +// An estimate of the monthly revenue of the business. Only accepted for accounts in Brazil and India. +type AccountCreateBusinessProfileMonthlyEstimatedRevenueParams struct { + // A non-negative integer representing how much to charge in the [smallest currency unit](https://docs.stripe.com/currencies#zero-decimal). + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` +} + +// Business information about the account. +type AccountCreateBusinessProfileParams struct { + // The applicant's gross annual revenue for its preceding fiscal year. + AnnualRevenue *AccountCreateBusinessProfileAnnualRevenueParams `form:"annual_revenue"` + // An estimated upper bound of employees, contractors, vendors, etc. currently working for the business. + EstimatedWorkerCount *int64 `form:"estimated_worker_count"` + // [The merchant category code for the account](https://docs.stripe.com/connect/setting-mcc). MCCs are used to classify businesses based on the goods or services they provide. + MCC *string `form:"mcc"` + // Whether the business is a minority-owned, women-owned, and/or LGBTQI+-owned business. + MinorityOwnedBusinessDesignation []*string `form:"minority_owned_business_designation"` + // An estimate of the monthly revenue of the business. Only accepted for accounts in Brazil and India. + MonthlyEstimatedRevenue *AccountCreateBusinessProfileMonthlyEstimatedRevenueParams `form:"monthly_estimated_revenue"` + // The customer-facing business name. + Name *string `form:"name"` + // Internal-only description of the product sold by, or service provided by, the business. Used by Stripe for risk and underwriting purposes. + ProductDescription *string `form:"product_description"` + // A publicly available mailing address for sending support issues to. + SupportAddress *AddressParams `form:"support_address"` + // A publicly available email address for sending support issues to. + SupportEmail *string `form:"support_email"` + // A publicly available phone number to call with support issues. + SupportPhone *string `form:"support_phone"` + // A publicly available website for handling support issues. + SupportURL *string `form:"support_url"` + // The business's publicly available website. + URL *string `form:"url"` +} + +// The acss_debit_payments capability. +type AccountCreateCapabilitiesACSSDebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The affirm_payments capability. +type AccountCreateCapabilitiesAffirmPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The afterpay_clearpay_payments capability. +type AccountCreateCapabilitiesAfterpayClearpayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The alma_payments capability. +type AccountCreateCapabilitiesAlmaPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The amazon_pay_payments capability. +type AccountCreateCapabilitiesAmazonPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The au_becs_debit_payments capability. +type AccountCreateCapabilitiesAUBECSDebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The bacs_debit_payments capability. +type AccountCreateCapabilitiesBACSDebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The bancontact_payments capability. +type AccountCreateCapabilitiesBancontactPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The bank_transfer_payments capability. +type AccountCreateCapabilitiesBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The billie_payments capability. +type AccountCreateCapabilitiesBilliePaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The blik_payments capability. +type AccountCreateCapabilitiesBLIKPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The boleto_payments capability. +type AccountCreateCapabilitiesBoletoPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The card_issuing capability. +type AccountCreateCapabilitiesCardIssuingParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The card_payments capability. +type AccountCreateCapabilitiesCardPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The cartes_bancaires_payments capability. +type AccountCreateCapabilitiesCartesBancairesPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The cashapp_payments capability. +type AccountCreateCapabilitiesCashAppPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The crypto_payments capability. +type AccountCreateCapabilitiesCryptoPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The eps_payments capability. +type AccountCreateCapabilitiesEPSPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The fpx_payments capability. +type AccountCreateCapabilitiesFPXPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The gb_bank_transfer_payments capability. +type AccountCreateCapabilitiesGBBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The giropay_payments capability. +type AccountCreateCapabilitiesGiropayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The grabpay_payments capability. +type AccountCreateCapabilitiesGrabpayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The ideal_payments capability. +type AccountCreateCapabilitiesIDEALPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The india_international_payments capability. +type AccountCreateCapabilitiesIndiaInternationalPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The jcb_payments capability. +type AccountCreateCapabilitiesJCBPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The jp_bank_transfer_payments capability. +type AccountCreateCapabilitiesJPBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The kakao_pay_payments capability. +type AccountCreateCapabilitiesKakaoPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The klarna_payments capability. +type AccountCreateCapabilitiesKlarnaPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The konbini_payments capability. +type AccountCreateCapabilitiesKonbiniPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The kr_card_payments capability. +type AccountCreateCapabilitiesKrCardPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The legacy_payments capability. +type AccountCreateCapabilitiesLegacyPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The link_payments capability. +type AccountCreateCapabilitiesLinkPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The mobilepay_payments capability. +type AccountCreateCapabilitiesMobilepayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The multibanco_payments capability. +type AccountCreateCapabilitiesMultibancoPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The mx_bank_transfer_payments capability. +type AccountCreateCapabilitiesMXBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The naver_pay_payments capability. +type AccountCreateCapabilitiesNaverPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The nz_bank_account_becs_debit_payments capability. +type AccountCreateCapabilitiesNzBankAccountBECSDebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The oxxo_payments capability. +type AccountCreateCapabilitiesOXXOPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The p24_payments capability. +type AccountCreateCapabilitiesP24PaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The pay_by_bank_payments capability. +type AccountCreateCapabilitiesPayByBankPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The payco_payments capability. +type AccountCreateCapabilitiesPaycoPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The paynow_payments capability. +type AccountCreateCapabilitiesPayNowPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The pix_payments capability. +type AccountCreateCapabilitiesPixPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The promptpay_payments capability. +type AccountCreateCapabilitiesPromptPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The revolut_pay_payments capability. +type AccountCreateCapabilitiesRevolutPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The samsung_pay_payments capability. +type AccountCreateCapabilitiesSamsungPayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The satispay_payments capability. +type AccountCreateCapabilitiesSatispayPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The sepa_bank_transfer_payments capability. +type AccountCreateCapabilitiesSEPABankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The sepa_debit_payments capability. +type AccountCreateCapabilitiesSEPADebitPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The sofort_payments capability. +type AccountCreateCapabilitiesSofortPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The swish_payments capability. +type AccountCreateCapabilitiesSwishPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The tax_reporting_us_1099_k capability. +type AccountCreateCapabilitiesTaxReportingUS1099KParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The tax_reporting_us_1099_misc capability. +type AccountCreateCapabilitiesTaxReportingUS1099MISCParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The transfers capability. +type AccountCreateCapabilitiesTransfersParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The treasury capability. +type AccountCreateCapabilitiesTreasuryParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The twint_payments capability. +type AccountCreateCapabilitiesTWINTPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The us_bank_account_ach_payments capability. +type AccountCreateCapabilitiesUSBankAccountACHPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The us_bank_transfer_payments capability. +type AccountCreateCapabilitiesUSBankTransferPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// The zip_payments capability. +type AccountCreateCapabilitiesZipPaymentsParams struct { + // Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + Requested *bool `form:"requested"` +} + +// Each key of the dictionary represents a capability, and each capability +// maps to its settings (for example, whether it has been requested or not). Each +// capability is inactive until you have provided its specific +// requirements and Stripe has verified them. An account might have some +// of its requested capabilities be active and some be inactive. +// +// Required when [account.controller.stripe_dashboard.type](https://docs.stripe.com/api/accounts/create#create_account-controller-dashboard-type) +// is `none`, which includes Custom accounts. +type AccountCreateCapabilitiesParams struct { + // The acss_debit_payments capability. + ACSSDebitPayments *AccountCreateCapabilitiesACSSDebitPaymentsParams `form:"acss_debit_payments"` + // The affirm_payments capability. + AffirmPayments *AccountCreateCapabilitiesAffirmPaymentsParams `form:"affirm_payments"` + // The afterpay_clearpay_payments capability. + AfterpayClearpayPayments *AccountCreateCapabilitiesAfterpayClearpayPaymentsParams `form:"afterpay_clearpay_payments"` + // The alma_payments capability. + AlmaPayments *AccountCreateCapabilitiesAlmaPaymentsParams `form:"alma_payments"` + // The amazon_pay_payments capability. + AmazonPayPayments *AccountCreateCapabilitiesAmazonPayPaymentsParams `form:"amazon_pay_payments"` + // The au_becs_debit_payments capability. + AUBECSDebitPayments *AccountCreateCapabilitiesAUBECSDebitPaymentsParams `form:"au_becs_debit_payments"` + // The bacs_debit_payments capability. + BACSDebitPayments *AccountCreateCapabilitiesBACSDebitPaymentsParams `form:"bacs_debit_payments"` + // The bancontact_payments capability. + BancontactPayments *AccountCreateCapabilitiesBancontactPaymentsParams `form:"bancontact_payments"` + // The bank_transfer_payments capability. + BankTransferPayments *AccountCreateCapabilitiesBankTransferPaymentsParams `form:"bank_transfer_payments"` + // The billie_payments capability. + BilliePayments *AccountCreateCapabilitiesBilliePaymentsParams `form:"billie_payments"` + // The blik_payments capability. + BLIKPayments *AccountCreateCapabilitiesBLIKPaymentsParams `form:"blik_payments"` + // The boleto_payments capability. + BoletoPayments *AccountCreateCapabilitiesBoletoPaymentsParams `form:"boleto_payments"` + // The card_issuing capability. + CardIssuing *AccountCreateCapabilitiesCardIssuingParams `form:"card_issuing"` + // The card_payments capability. + CardPayments *AccountCreateCapabilitiesCardPaymentsParams `form:"card_payments"` + // The cartes_bancaires_payments capability. + CartesBancairesPayments *AccountCreateCapabilitiesCartesBancairesPaymentsParams `form:"cartes_bancaires_payments"` + // The cashapp_payments capability. + CashAppPayments *AccountCreateCapabilitiesCashAppPaymentsParams `form:"cashapp_payments"` + // The crypto_payments capability. + CryptoPayments *AccountCreateCapabilitiesCryptoPaymentsParams `form:"crypto_payments"` + // The eps_payments capability. + EPSPayments *AccountCreateCapabilitiesEPSPaymentsParams `form:"eps_payments"` + // The fpx_payments capability. + FPXPayments *AccountCreateCapabilitiesFPXPaymentsParams `form:"fpx_payments"` + // The gb_bank_transfer_payments capability. + GBBankTransferPayments *AccountCreateCapabilitiesGBBankTransferPaymentsParams `form:"gb_bank_transfer_payments"` + // The giropay_payments capability. + GiropayPayments *AccountCreateCapabilitiesGiropayPaymentsParams `form:"giropay_payments"` + // The grabpay_payments capability. + GrabpayPayments *AccountCreateCapabilitiesGrabpayPaymentsParams `form:"grabpay_payments"` + // The ideal_payments capability. + IDEALPayments *AccountCreateCapabilitiesIDEALPaymentsParams `form:"ideal_payments"` + // The india_international_payments capability. + IndiaInternationalPayments *AccountCreateCapabilitiesIndiaInternationalPaymentsParams `form:"india_international_payments"` + // The jcb_payments capability. + JCBPayments *AccountCreateCapabilitiesJCBPaymentsParams `form:"jcb_payments"` + // The jp_bank_transfer_payments capability. + JPBankTransferPayments *AccountCreateCapabilitiesJPBankTransferPaymentsParams `form:"jp_bank_transfer_payments"` + // The kakao_pay_payments capability. + KakaoPayPayments *AccountCreateCapabilitiesKakaoPayPaymentsParams `form:"kakao_pay_payments"` + // The klarna_payments capability. + KlarnaPayments *AccountCreateCapabilitiesKlarnaPaymentsParams `form:"klarna_payments"` + // The konbini_payments capability. + KonbiniPayments *AccountCreateCapabilitiesKonbiniPaymentsParams `form:"konbini_payments"` + // The kr_card_payments capability. + KrCardPayments *AccountCreateCapabilitiesKrCardPaymentsParams `form:"kr_card_payments"` + // The legacy_payments capability. + LegacyPayments *AccountCreateCapabilitiesLegacyPaymentsParams `form:"legacy_payments"` + // The link_payments capability. + LinkPayments *AccountCreateCapabilitiesLinkPaymentsParams `form:"link_payments"` + // The mobilepay_payments capability. + MobilepayPayments *AccountCreateCapabilitiesMobilepayPaymentsParams `form:"mobilepay_payments"` + // The multibanco_payments capability. + MultibancoPayments *AccountCreateCapabilitiesMultibancoPaymentsParams `form:"multibanco_payments"` + // The mx_bank_transfer_payments capability. + MXBankTransferPayments *AccountCreateCapabilitiesMXBankTransferPaymentsParams `form:"mx_bank_transfer_payments"` + // The naver_pay_payments capability. + NaverPayPayments *AccountCreateCapabilitiesNaverPayPaymentsParams `form:"naver_pay_payments"` + // The nz_bank_account_becs_debit_payments capability. + NzBankAccountBECSDebitPayments *AccountCreateCapabilitiesNzBankAccountBECSDebitPaymentsParams `form:"nz_bank_account_becs_debit_payments"` + // The oxxo_payments capability. + OXXOPayments *AccountCreateCapabilitiesOXXOPaymentsParams `form:"oxxo_payments"` + // The p24_payments capability. + P24Payments *AccountCreateCapabilitiesP24PaymentsParams `form:"p24_payments"` + // The pay_by_bank_payments capability. + PayByBankPayments *AccountCreateCapabilitiesPayByBankPaymentsParams `form:"pay_by_bank_payments"` + // The payco_payments capability. + PaycoPayments *AccountCreateCapabilitiesPaycoPaymentsParams `form:"payco_payments"` + // The paynow_payments capability. + PayNowPayments *AccountCreateCapabilitiesPayNowPaymentsParams `form:"paynow_payments"` + // The pix_payments capability. + PixPayments *AccountCreateCapabilitiesPixPaymentsParams `form:"pix_payments"` + // The promptpay_payments capability. + PromptPayPayments *AccountCreateCapabilitiesPromptPayPaymentsParams `form:"promptpay_payments"` + // The revolut_pay_payments capability. + RevolutPayPayments *AccountCreateCapabilitiesRevolutPayPaymentsParams `form:"revolut_pay_payments"` + // The samsung_pay_payments capability. + SamsungPayPayments *AccountCreateCapabilitiesSamsungPayPaymentsParams `form:"samsung_pay_payments"` + // The satispay_payments capability. + SatispayPayments *AccountCreateCapabilitiesSatispayPaymentsParams `form:"satispay_payments"` + // The sepa_bank_transfer_payments capability. + SEPABankTransferPayments *AccountCreateCapabilitiesSEPABankTransferPaymentsParams `form:"sepa_bank_transfer_payments"` + // The sepa_debit_payments capability. + SEPADebitPayments *AccountCreateCapabilitiesSEPADebitPaymentsParams `form:"sepa_debit_payments"` + // The sofort_payments capability. + SofortPayments *AccountCreateCapabilitiesSofortPaymentsParams `form:"sofort_payments"` + // The swish_payments capability. + SwishPayments *AccountCreateCapabilitiesSwishPaymentsParams `form:"swish_payments"` + // The tax_reporting_us_1099_k capability. + TaxReportingUS1099K *AccountCreateCapabilitiesTaxReportingUS1099KParams `form:"tax_reporting_us_1099_k"` + // The tax_reporting_us_1099_misc capability. + TaxReportingUS1099MISC *AccountCreateCapabilitiesTaxReportingUS1099MISCParams `form:"tax_reporting_us_1099_misc"` + // The transfers capability. + Transfers *AccountCreateCapabilitiesTransfersParams `form:"transfers"` + // The treasury capability. + Treasury *AccountCreateCapabilitiesTreasuryParams `form:"treasury"` + // The twint_payments capability. + TWINTPayments *AccountCreateCapabilitiesTWINTPaymentsParams `form:"twint_payments"` + // The us_bank_account_ach_payments capability. + USBankAccountACHPayments *AccountCreateCapabilitiesUSBankAccountACHPaymentsParams `form:"us_bank_account_ach_payments"` + // The us_bank_transfer_payments capability. + USBankTransferPayments *AccountCreateCapabilitiesUSBankTransferPaymentsParams `form:"us_bank_transfer_payments"` + // The zip_payments capability. + ZipPayments *AccountCreateCapabilitiesZipPaymentsParams `form:"zip_payments"` +} + +// The Kana variation of the company's primary address (Japan only). +type AccountCreateCompanyAddressKanaParams struct { + // City or ward. + City *string `form:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // Block or building number. + Line1 *string `form:"line1"` + // Building details. + Line2 *string `form:"line2"` + // Postal code. + PostalCode *string `form:"postal_code"` + // Prefecture. + State *string `form:"state"` + // Town or cho-me. + Town *string `form:"town"` +} + +// The Kanji variation of the company's primary address (Japan only). +type AccountCreateCompanyAddressKanjiParams struct { + // City or ward. + City *string `form:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // Block or building number. + Line1 *string `form:"line1"` + // Building details. + Line2 *string `form:"line2"` + // Postal code. + PostalCode *string `form:"postal_code"` + // Prefecture. + State *string `form:"state"` + // Town or cho-me. + Town *string `form:"town"` +} + +// This hash is used to attest that the directors information provided to Stripe is both current and correct. +type AccountCreateCompanyDirectorshipDeclarationParams struct { + // The Unix timestamp marking when the directorship declaration attestation was made. + Date *int64 `form:"date"` + // The IP address from which the directorship declaration attestation was made. + IP *string `form:"ip"` + // The user agent of the browser from which the directorship declaration attestation was made. + UserAgent *string `form:"user_agent"` +} + +// This hash is used to attest that the beneficial owner information provided to Stripe is both current and correct. +type AccountCreateCompanyOwnershipDeclarationParams struct { + // The Unix timestamp marking when the beneficial owner attestation was made. + Date *int64 `form:"date"` + // The IP address from which the beneficial owner attestation was made. + IP *string `form:"ip"` + // The user agent of the browser from which the beneficial owner attestation was made. + UserAgent *string `form:"user_agent"` +} + +// When the business was incorporated or registered. +type AccountCreateCompanyRegistrationDateParams struct { + // The day of registration, between 1 and 31. + Day *int64 `form:"day"` + // The month of registration, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of registration. + Year *int64 `form:"year"` +} + +// A document verifying the business. +type AccountCreateCompanyVerificationDocumentParams struct { + // The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Back *string `form:"back"` + // The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Front *string `form:"front"` +} + +// Information on the verification state of the company. +type AccountCreateCompanyVerificationParams struct { + // A document verifying the business. + Document *AccountCreateCompanyVerificationDocumentParams `form:"document"` +} + +// Information about the company or business. This field is available for any `business_type`. Once you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. +type AccountCreateCompanyParams struct { + // The company's primary address. + Address *AddressParams `form:"address"` + // The Kana variation of the company's primary address (Japan only). + AddressKana *AccountCreateCompanyAddressKanaParams `form:"address_kana"` + // The Kanji variation of the company's primary address (Japan only). + AddressKanji *AccountCreateCompanyAddressKanjiParams `form:"address_kanji"` + // This hash is used to attest that the directors information provided to Stripe is both current and correct. + DirectorshipDeclaration *AccountCreateCompanyDirectorshipDeclarationParams `form:"directorship_declaration"` + // Whether the company's directors have been provided. Set this Boolean to `true` after creating all the company's directors with [the Persons API](https://docs.stripe.com/api/persons) for accounts with a `relationship.director` requirement. This value is not automatically set to `true` after creating directors, so it needs to be updated to indicate all directors have been provided. + DirectorsProvided *bool `form:"directors_provided"` + // Whether the company's executives have been provided. Set this Boolean to `true` after creating all the company's executives with [the Persons API](https://docs.stripe.com/api/persons) for accounts with a `relationship.executive` requirement. + ExecutivesProvided *bool `form:"executives_provided"` + // The export license ID number of the company, also referred as Import Export Code (India only). + ExportLicenseID *string `form:"export_license_id"` + // The purpose code to use for export transactions (India only). + ExportPurposeCode *string `form:"export_purpose_code"` + // The company's legal name. + Name *string `form:"name"` + // The Kana variation of the company's legal name (Japan only). + NameKana *string `form:"name_kana"` + // The Kanji variation of the company's legal name (Japan only). + NameKanji *string `form:"name_kanji"` + // This hash is used to attest that the beneficial owner information provided to Stripe is both current and correct. + OwnershipDeclaration *AccountCreateCompanyOwnershipDeclarationParams `form:"ownership_declaration"` + OwnershipDeclarationShownAndSigned *bool `form:"ownership_declaration_shown_and_signed"` + // This value is used to determine if a business is exempt from providing ultimate beneficial owners. See [this support article](https://support.stripe.com/questions/exemption-from-providing-ownership-details) and [changelog](https://docs.stripe.com/changelog/acacia/2025-01-27/ownership-exemption-reason-accounts-api) for more details. + OwnershipExemptionReason *string `form:"ownership_exemption_reason"` + // Whether the company's owners have been provided. Set this Boolean to `true` after creating all the company's owners with [the Persons API](https://docs.stripe.com/api/persons) for accounts with a `relationship.owner` requirement. + OwnersProvided *bool `form:"owners_provided"` + // The company's phone number (used for verification). + Phone *string `form:"phone"` + // When the business was incorporated or registered. + RegistrationDate *AccountCreateCompanyRegistrationDateParams `form:"registration_date"` + // The identification number given to a company when it is registered or incorporated, if distinct from the identification number used for filing taxes. (Examples are the CIN for companies and LLP IN for partnerships in India, and the Company Registration Number in Hong Kong). + RegistrationNumber *string `form:"registration_number"` + // The category identifying the legal structure of the company or legal entity. See [Business structure](https://docs.stripe.com/connect/identity-verification#business-structure) for more details. Pass an empty string to unset this value. + Structure *string `form:"structure"` + // The business ID number of the company, as appropriate for the company's country. (Examples are an Employer ID Number in the U.S., a Business Number in Canada, or a Company Number in the UK.) + TaxID *string `form:"tax_id"` + // The jurisdiction in which the `tax_id` is registered (Germany-based companies only). + TaxIDRegistrar *string `form:"tax_id_registrar"` + // The VAT number of the company. + VATID *string `form:"vat_id"` + // Information on the verification state of the company. + Verification *AccountCreateCompanyVerificationParams `form:"verification"` +} + +// A hash of configuration for who pays Stripe fees for product usage on this account. +type AccountCreateControllerFeesParams struct { + // A value indicating the responsible payer of Stripe fees on this account. Defaults to `account`. Learn more about [fee behavior on connected accounts](https://docs.stripe.com/connect/direct-charges-fee-payer-behavior). + Payer *string `form:"payer"` +} + +// A hash of configuration for products that have negative balance liability, and whether Stripe or a Connect application is responsible for them. +type AccountCreateControllerLossesParams struct { + // A value indicating who is liable when this account can't pay back negative balances resulting from payments. Defaults to `stripe`. + Payments *string `form:"payments"` +} + +// A hash of configuration for Stripe-hosted dashboards. +type AccountCreateControllerStripeDashboardParams struct { + // Whether this account should have access to the full Stripe Dashboard (`full`), to the Express Dashboard (`express`), or to no Stripe-hosted dashboard (`none`). Defaults to `full`. + Type *string `form:"type"` +} + +// A hash of configuration describing the account controller's attributes. +type AccountCreateControllerParams struct { + // A hash of configuration for who pays Stripe fees for product usage on this account. + Fees *AccountCreateControllerFeesParams `form:"fees"` + // A hash of configuration for products that have negative balance liability, and whether Stripe or a Connect application is responsible for them. + Losses *AccountCreateControllerLossesParams `form:"losses"` + // A value indicating responsibility for collecting updated information when requirements on the account are due or change. Defaults to `stripe`. + RequirementCollection *string `form:"requirement_collection"` + // A hash of configuration for Stripe-hosted dashboards. + StripeDashboard *AccountCreateControllerStripeDashboardParams `form:"stripe_dashboard"` +} + +// One or more documents that support the [Bank account ownership verification](https://support.stripe.com/questions/bank-account-ownership-verification) requirement. Must be a document associated with the account's primary active bank account that displays the last 4 digits of the account number, either a statement or a check. +type AccountCreateDocumentsBankAccountOwnershipVerificationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of a company's license to operate. +type AccountCreateDocumentsCompanyLicenseParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents showing the company's Memorandum of Association. +type AccountCreateDocumentsCompanyMemorandumOfAssociationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// (Certain countries only) One or more documents showing the ministerial decree legalizing the company's establishment. +type AccountCreateDocumentsCompanyMinisterialDecreeParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of a company's registration with the appropriate local authorities. +type AccountCreateDocumentsCompanyRegistrationVerificationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of a company's tax ID. +type AccountCreateDocumentsCompanyTaxIDVerificationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of address. +type AccountCreateDocumentsProofOfAddressParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents showing the company's proof of registration with the national business registry. +type AccountCreateDocumentsProofOfRegistrationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents that demonstrate proof of ultimate beneficial ownership. +type AccountCreateDocumentsProofOfUltimateBeneficialOwnershipParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// Documents that may be submitted to satisfy various informational requests. +type AccountCreateDocumentsParams struct { + // One or more documents that support the [Bank account ownership verification](https://support.stripe.com/questions/bank-account-ownership-verification) requirement. Must be a document associated with the account's primary active bank account that displays the last 4 digits of the account number, either a statement or a check. + BankAccountOwnershipVerification *AccountCreateDocumentsBankAccountOwnershipVerificationParams `form:"bank_account_ownership_verification"` + // One or more documents that demonstrate proof of a company's license to operate. + CompanyLicense *AccountCreateDocumentsCompanyLicenseParams `form:"company_license"` + // One or more documents showing the company's Memorandum of Association. + CompanyMemorandumOfAssociation *AccountCreateDocumentsCompanyMemorandumOfAssociationParams `form:"company_memorandum_of_association"` + // (Certain countries only) One or more documents showing the ministerial decree legalizing the company's establishment. + CompanyMinisterialDecree *AccountCreateDocumentsCompanyMinisterialDecreeParams `form:"company_ministerial_decree"` + // One or more documents that demonstrate proof of a company's registration with the appropriate local authorities. + CompanyRegistrationVerification *AccountCreateDocumentsCompanyRegistrationVerificationParams `form:"company_registration_verification"` + // One or more documents that demonstrate proof of a company's tax ID. + CompanyTaxIDVerification *AccountCreateDocumentsCompanyTaxIDVerificationParams `form:"company_tax_id_verification"` + // One or more documents that demonstrate proof of address. + ProofOfAddress *AccountCreateDocumentsProofOfAddressParams `form:"proof_of_address"` + // One or more documents showing the company's proof of registration with the national business registry. + ProofOfRegistration *AccountCreateDocumentsProofOfRegistrationParams `form:"proof_of_registration"` + // One or more documents that demonstrate proof of ultimate beneficial ownership. + ProofOfUltimateBeneficialOwnership *AccountCreateDocumentsProofOfUltimateBeneficialOwnershipParams `form:"proof_of_ultimate_beneficial_ownership"` +} + +// A card or bank account to attach to the account for receiving [payouts](https://docs.stripe.com/connect/bank-debit-card-payouts) (you won't be able to use it for top-ups). You can provide either a token, like the ones returned by [Stripe.js](https://docs.stripe.com/js), or a dictionary, as documented in the `external_account` parameter for [bank account](https://docs.stripe.com/api#account_create_bank_account) creation. +// +// By default, providing an external account sets it as the new default external account for its currency, and deletes the old default if one exists. To add additional external accounts without replacing the existing default for the currency, use the [bank account](https://docs.stripe.com/api#account_create_bank_account) or [card creation](https://docs.stripe.com/api#account_create_card) APIs. After you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. +type AccountCreateExternalAccountParams struct { + // The name of the person or business that owns the bank account.This field is required when attaching the bank account to a `Customer` object. + AccountHolderName *string `form:"account_holder_name"` + // The type of entity that holds the account. It can be `company` or `individual`. This field is required when attaching the bank account to a `Customer` object. + AccountHolderType *string `form:"account_holder_type"` + // The account number for the bank account, in string form. Must be a checking account. + AccountNumber *string `form:"account_number"` + AddressCity *string `form:"address_city"` + AddressCountry *string `form:"address_country"` + AddressLine1 *string `form:"address_line1"` + AddressLine2 *string `form:"address_line2"` + AddressState *string `form:"address_state"` + AddressZip *string `form:"address_zip"` + // The country in which the bank account is located. + Country *string `form:"country"` + // The currency the bank account is in. This must be a country/currency pairing that [Stripe supports.](docs/payouts) + Currency *string `form:"currency"` + CVC *string `form:"cvc"` + DefaultForCurrency *bool `form:"default_for_currency"` + ExpMonth *int64 `form:"exp_month"` + ExpYear *int64 `form:"exp_year"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `form:"metadata"` + Name *string `form:"name"` + Number *string `form:"number"` + Object *string `form:"object"` + // The routing number, sort code, or other country-appropriate institution number for the bank account. For US bank accounts, this is required and should be the ACH routing number, not the wire routing number. If you are providing an IBAN for `account_number`, this field is not required. + RoutingNumber *string `form:"routing_number"` + Token *string `form:"token"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *AccountCreateExternalAccountParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A hash of account group type to tokens. These are account groups this account should be added to. +type AccountCreateGroupsParams struct { + // The group the account is in to determine their payments pricing, and null if the account is on customized pricing. [See the Platform pricing tool documentation](https://stripe.com/docs/connect/platform-pricing-tools) for details. + PaymentsPricing *string `form:"payments_pricing"` +} + +// Settings specific to Bacs Direct Debit. +type AccountCreateSettingsBACSDebitPaymentsParams struct { + // The Bacs Direct Debit Display Name for this account. For payments made with Bacs Direct Debit, this name appears on the mandate as the statement descriptor. Mobile banking apps display it as the name of the business. To use custom branding, set the Bacs Direct Debit Display Name during or right after creation. Custom branding incurs an additional monthly fee for the platform. If you don't set the display name before requesting Bacs capability, it's automatically set as "Stripe" and the account is onboarded to Stripe branding, which is free. + DisplayName *string `form:"display_name"` +} + +// Settings used to apply the account's branding to email receipts, invoices, Checkout, and other products. +type AccountCreateSettingsBrandingParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) An icon for the account. Must be square and at least 128px x 128px. + Icon *string `form:"icon"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) A logo for the account that will be used in Checkout instead of the icon and without the account's name next to it if provided. Must be at least 128px x 128px. + Logo *string `form:"logo"` + // A CSS hex color value representing the primary branding color for this account. + PrimaryColor *string `form:"primary_color"` + // A CSS hex color value representing the secondary branding color for this account. + SecondaryColor *string `form:"secondary_color"` +} + +// Details on the account's acceptance of the [Stripe Issuing Terms and Disclosures](https://docs.stripe.com/issuing/connect/tos_acceptance). +type AccountCreateSettingsCardIssuingTOSAcceptanceParams struct { + // The Unix timestamp marking when the account representative accepted the service agreement. + Date *int64 `form:"date"` + // The IP address from which the account representative accepted the service agreement. + IP *string `form:"ip"` + // The user agent of the browser from which the account representative accepted the service agreement. + UserAgent *string `form:"user_agent"` +} + +// Settings specific to the account's use of the Card Issuing product. +type AccountCreateSettingsCardIssuingParams struct { + // Details on the account's acceptance of the [Stripe Issuing Terms and Disclosures](https://docs.stripe.com/issuing/connect/tos_acceptance). + TOSAcceptance *AccountCreateSettingsCardIssuingTOSAcceptanceParams `form:"tos_acceptance"` +} + +// Automatically declines certain charge types regardless of whether the card issuer accepted or declined the charge. +type AccountCreateSettingsCardPaymentsDeclineOnParams struct { + // Whether Stripe automatically declines charges with an incorrect ZIP or postal code. This setting only applies when a ZIP or postal code is provided and they fail bank verification. + AVSFailure *bool `form:"avs_failure"` + // Whether Stripe automatically declines charges with an incorrect CVC. This setting only applies when a CVC is provided and it fails bank verification. + CVCFailure *bool `form:"cvc_failure"` +} + +// Settings specific to card charging on the account. +type AccountCreateSettingsCardPaymentsParams struct { + // Automatically declines certain charge types regardless of whether the card issuer accepted or declined the charge. + DeclineOn *AccountCreateSettingsCardPaymentsDeclineOnParams `form:"decline_on"` + // The default text that appears on credit card statements when a charge is made. This field prefixes any dynamic `statement_descriptor` specified on the charge. `statement_descriptor_prefix` is useful for maximizing descriptor space for the dynamic portion. + StatementDescriptorPrefix *string `form:"statement_descriptor_prefix"` + // The Kana variation of the default text that appears on credit card statements when a charge is made (Japan only). This field prefixes any dynamic `statement_descriptor_suffix_kana` specified on the charge. `statement_descriptor_prefix_kana` is useful for maximizing descriptor space for the dynamic portion. + StatementDescriptorPrefixKana *string `form:"statement_descriptor_prefix_kana"` + // The Kanji variation of the default text that appears on credit card statements when a charge is made (Japan only). This field prefixes any dynamic `statement_descriptor_suffix_kanji` specified on the charge. `statement_descriptor_prefix_kanji` is useful for maximizing descriptor space for the dynamic portion. + StatementDescriptorPrefixKanji *string `form:"statement_descriptor_prefix_kanji"` +} + +// Settings specific to the account's use of Invoices. +type AccountCreateSettingsInvoicesParams struct { + // Whether payment methods should be saved when a payment is completed for a one-time invoices on a hosted invoice page. + HostedPaymentMethodSave *string `form:"hosted_payment_method_save"` +} + +// Settings that apply across payment methods for charging on the account. +type AccountCreateSettingsPaymentsParams struct { + // The default text that appears on statements for non-card charges outside of Japan. For card charges, if you don't set a `statement_descriptor_prefix`, this text is also used as the statement descriptor prefix. In that case, if concatenating the statement descriptor suffix causes the combined statement descriptor to exceed 22 characters, we truncate the `statement_descriptor` text to limit the full descriptor to 22 characters. For more information about statement descriptors and their requirements, see the [account settings documentation](https://docs.stripe.com/get-started/account/statement-descriptors). + StatementDescriptor *string `form:"statement_descriptor"` + // The Kana variation of `statement_descriptor` used for charges in Japan. Japanese statement descriptors have [special requirements](https://docs.stripe.com/get-started/account/statement-descriptors#set-japanese-statement-descriptors). + StatementDescriptorKana *string `form:"statement_descriptor_kana"` + // The Kanji variation of `statement_descriptor` used for charges in Japan. Japanese statement descriptors have [special requirements](https://docs.stripe.com/get-started/account/statement-descriptors#set-japanese-statement-descriptors). + StatementDescriptorKanji *string `form:"statement_descriptor_kanji"` +} + +// Details on when funds from charges are available, and when they are paid out to an external account. For details, see our [Setting Bank and Debit Card Payouts](https://docs.stripe.com/connect/bank-transfers#payout-information) documentation. +type AccountCreateSettingsPayoutsScheduleParams struct { + // The number of days charge funds are held before being paid out. May also be set to `minimum`, representing the lowest available value for the account country. Default is `minimum`. The `delay_days` parameter remains at the last configured value if `interval` is `manual`. [Learn more about controlling payout delay days](https://docs.stripe.com/connect/manage-payout-schedule). + DelayDays *int64 `form:"delay_days"` + DelayDaysMinimum *bool `form:"-"` // See custom AppendTo + // How frequently available funds are paid out. One of: `daily`, `manual`, `weekly`, or `monthly`. Default is `daily`. + Interval *string `form:"interval"` + // The day of the month when available funds are paid out, specified as a number between 1--31. Payouts nominally scheduled between the 29th and 31st of the month are instead sent on the last day of a shorter month. Required and applicable only if `interval` is `monthly`. + MonthlyAnchor *int64 `form:"monthly_anchor"` + // The days of the month when available funds are paid out, specified as an array of numbers between 1--31. Payouts nominally scheduled between the 29th and 31st of the month are instead sent on the last day of a shorter month. Required and applicable only if `interval` is `monthly` and `monthly_anchor` is not set. + MonthlyPayoutDays []*int64 `form:"monthly_payout_days"` + // The day of the week when available funds are paid out, specified as `monday`, `tuesday`, etc. (required and applicable only if `interval` is `weekly`.) + WeeklyAnchor *string `form:"weekly_anchor"` + // The days of the week when available funds are paid out, specified as an array, e.g., [`monday`, `tuesday`]. (required and applicable only if `interval` is `weekly` and `weekly_anchor` is not set.) + WeeklyPayoutDays []*string `form:"weekly_payout_days"` +} + +// AppendTo implements custom encoding logic for AccountCreateSettingsPayoutsScheduleParams. +func (p *AccountCreateSettingsPayoutsScheduleParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.DelayDaysMinimum) { + body.Add(form.FormatKey(append(keyParts, "delay_days")), "minimum") + } +} + +// Settings specific to the account's payouts. +type AccountCreateSettingsPayoutsParams struct { + // A Boolean indicating whether Stripe should try to reclaim negative balances from an attached bank account. For details, see [Understanding Connect Account Balances](https://docs.stripe.com/connect/account-balances). + DebitNegativeBalances *bool `form:"debit_negative_balances"` + // Details on when funds from charges are available, and when they are paid out to an external account. For details, see our [Setting Bank and Debit Card Payouts](https://docs.stripe.com/connect/bank-transfers#payout-information) documentation. + Schedule *AccountCreateSettingsPayoutsScheduleParams `form:"schedule"` + // The text that appears on the bank account statement for payouts. If not set, this defaults to the platform's bank descriptor as set in the Dashboard. + StatementDescriptor *string `form:"statement_descriptor"` +} + +// Details on the account's acceptance of the Stripe Treasury Services Agreement. +type AccountCreateSettingsTreasuryTOSAcceptanceParams struct { + // The Unix timestamp marking when the account representative accepted the service agreement. + Date *int64 `form:"date"` + // The IP address from which the account representative accepted the service agreement. + IP *string `form:"ip"` + // The user agent of the browser from which the account representative accepted the service agreement. + UserAgent *string `form:"user_agent"` +} + +// Settings specific to the account's Treasury FinancialAccounts. +type AccountCreateSettingsTreasuryParams struct { + // Details on the account's acceptance of the Stripe Treasury Services Agreement. + TOSAcceptance *AccountCreateSettingsTreasuryTOSAcceptanceParams `form:"tos_acceptance"` +} + +// Options for customizing how the account functions within Stripe. +type AccountCreateSettingsParams struct { + // Settings specific to Bacs Direct Debit. + BACSDebitPayments *AccountCreateSettingsBACSDebitPaymentsParams `form:"bacs_debit_payments"` + // Settings used to apply the account's branding to email receipts, invoices, Checkout, and other products. + Branding *AccountCreateSettingsBrandingParams `form:"branding"` + // Settings specific to the account's use of the Card Issuing product. + CardIssuing *AccountCreateSettingsCardIssuingParams `form:"card_issuing"` + // Settings specific to card charging on the account. + CardPayments *AccountCreateSettingsCardPaymentsParams `form:"card_payments"` + // Settings specific to the account's use of Invoices. + Invoices *AccountCreateSettingsInvoicesParams `form:"invoices"` + // Settings that apply across payment methods for charging on the account. + Payments *AccountCreateSettingsPaymentsParams `form:"payments"` + // Settings specific to the account's payouts. + Payouts *AccountCreateSettingsPayoutsParams `form:"payouts"` + // Settings specific to the account's Treasury FinancialAccounts. + Treasury *AccountCreateSettingsTreasuryParams `form:"treasury"` +} + +// Details on the account's acceptance of the [Stripe Services Agreement](https://docs.stripe.com/connect/updating-accounts#tos-acceptance). This property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. This property defaults to a `full` service agreement when empty. +type AccountCreateTOSAcceptanceParams struct { + // The Unix timestamp marking when the account representative accepted their service agreement. + Date *int64 `form:"date"` + // The IP address from which the account representative accepted their service agreement. + IP *string `form:"ip"` + // The user's service agreement type. + ServiceAgreement *string `form:"service_agreement"` + // The user agent of the browser from which the account representative accepted their service agreement. + UserAgent *string `form:"user_agent"` +} + +// With [Connect](https://docs.stripe.com/docs/connect), you can create Stripe accounts for your users. +// To do this, you'll first need to [register your platform](https://dashboard.stripe.com/account/applications/settings). +// +// If you've already collected information for your connected accounts, you [can prefill that information](https://docs.stripe.com/docs/connect/best-practices#onboarding) when +// creating the account. Connect Onboarding won't ask for the prefilled information during account onboarding. +// You can prefill any information on the account. +type AccountCreateParams struct { + Params `form:"*"` + // An [account token](https://stripe.com/docs/api#create_account_token), used to securely provide details to the account. + AccountToken *string `form:"account_token"` + // Business information about the account. + BusinessProfile *AccountCreateBusinessProfileParams `form:"business_profile"` + // The business type. Once you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. + BusinessType *string `form:"business_type"` + // Each key of the dictionary represents a capability, and each capability + // maps to its settings (for example, whether it has been requested or not). Each + // capability is inactive until you have provided its specific + // requirements and Stripe has verified them. An account might have some + // of its requested capabilities be active and some be inactive. + // + // Required when [account.controller.stripe_dashboard.type](https://docs.stripe.com/api/accounts/create#create_account-controller-dashboard-type) + // is `none`, which includes Custom accounts. + Capabilities *AccountCreateCapabilitiesParams `form:"capabilities"` + // Information about the company or business. This field is available for any `business_type`. Once you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. + Company *AccountCreateCompanyParams `form:"company"` + // A hash of configuration describing the account controller's attributes. + Controller *AccountCreateControllerParams `form:"controller"` + // The country in which the account holder resides, or in which the business is legally established. This should be an ISO 3166-1 alpha-2 country code. For example, if you are in the United States and the business for which you're creating an account is legally represented in Canada, you would use `CA` as the country for the account being created. Available countries include [Stripe's global markets](https://stripe.com/global) as well as countries where [cross-border payouts](https://stripe.com/docs/connect/cross-border-payouts) are supported. + Country *string `form:"country"` + // Three-letter ISO currency code representing the default currency for the account. This must be a currency that [Stripe supports in the account's country](https://docs.stripe.com/payouts). + DefaultCurrency *string `form:"default_currency"` + // Documents that may be submitted to satisfy various informational requests. + Documents *AccountCreateDocumentsParams `form:"documents"` + // The email address of the account holder. This is only to make the account easier to identify to you. If [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts, Stripe doesn't email the account without your consent. + Email *string `form:"email"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A card or bank account to attach to the account for receiving [payouts](https://docs.stripe.com/connect/bank-debit-card-payouts) (you won't be able to use it for top-ups). You can provide either a token, like the ones returned by [Stripe.js](https://docs.stripe.com/js), or a dictionary, as documented in the `external_account` parameter for [bank account](https://docs.stripe.com/api#account_create_bank_account) creation. + // + // By default, providing an external account sets it as the new default external account for its currency, and deletes the old default if one exists. To add additional external accounts without replacing the existing default for the currency, use the [bank account](https://docs.stripe.com/api#account_create_bank_account) or [card creation](https://docs.stripe.com/api#account_create_card) APIs. After you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. + ExternalAccount *AccountExternalAccountParams `form:"external_account"` + // A hash of account group type to tokens. These are account groups this account should be added to. + Groups *AccountCreateGroupsParams `form:"groups"` + // Information about the person represented by the account. This field is null unless `business_type` is set to `individual`. Once you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions), this property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. + Individual *PersonParams `form:"individual"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Options for customizing how the account functions within Stripe. + Settings *AccountCreateSettingsParams `form:"settings"` + // Details on the account's acceptance of the [Stripe Services Agreement](https://docs.stripe.com/connect/updating-accounts#tos-acceptance). This property can only be updated for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. This property defaults to a `full` service agreement when empty. + TOSAcceptance *AccountCreateTOSAcceptanceParams `form:"tos_acceptance"` + // The type of Stripe account to create. May be one of `custom`, `express` or `standard`. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *AccountCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *AccountCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The applicant's gross annual revenue for its preceding fiscal year. +type AccountBusinessProfileAnnualRevenue struct { + // A non-negative integer representing the amount in the [smallest currency unit](https://docs.stripe.com/currencies#zero-decimal). + Amount int64 `json:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // The close-out date of the preceding fiscal year in ISO 8601 format. E.g. 2023-12-31 for the 31st of December, 2023. + FiscalYearEnd string `json:"fiscal_year_end"` +} +type AccountBusinessProfileMonthlyEstimatedRevenue struct { + // A non-negative integer representing how much to charge in the [smallest currency unit](https://docs.stripe.com/currencies#zero-decimal). + Amount int64 `json:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` +} + +// Business information about the account. +type AccountBusinessProfile struct { + // The applicant's gross annual revenue for its preceding fiscal year. + AnnualRevenue *AccountBusinessProfileAnnualRevenue `json:"annual_revenue"` + // An estimated upper bound of employees, contractors, vendors, etc. currently working for the business. + EstimatedWorkerCount int64 `json:"estimated_worker_count"` + // [The merchant category code for the account](https://docs.stripe.com/connect/setting-mcc). MCCs are used to classify businesses based on the goods or services they provide. + MCC string `json:"mcc"` + // Whether the business is a minority-owned, women-owned, and/or LGBTQI+-owned business. + MinorityOwnedBusinessDesignation []AccountBusinessProfileMinorityOwnedBusinessDesignation `json:"minority_owned_business_designation"` + MonthlyEstimatedRevenue *AccountBusinessProfileMonthlyEstimatedRevenue `json:"monthly_estimated_revenue"` + // The customer-facing business name. + Name string `json:"name"` + // Internal-only description of the product sold or service provided by the business. It's used by Stripe for risk and underwriting purposes. + ProductDescription string `json:"product_description"` + // A publicly available mailing address for sending support issues to. + SupportAddress *Address `json:"support_address"` + // A publicly available email address for sending support issues to. + SupportEmail string `json:"support_email"` + // A publicly available phone number to call with support issues. + SupportPhone string `json:"support_phone"` + // A publicly available website for handling support issues. + SupportURL string `json:"support_url"` + // The business's publicly available website. + URL string `json:"url"` +} +type AccountCapabilities struct { + // The status of the Canadian pre-authorized debits payments capability of the account, or whether the account can directly process Canadian pre-authorized debits charges. + ACSSDebitPayments AccountCapabilityStatus `json:"acss_debit_payments"` + // The status of the Affirm capability of the account, or whether the account can directly process Affirm charges. + AffirmPayments AccountCapabilityStatus `json:"affirm_payments"` + // The status of the Afterpay Clearpay capability of the account, or whether the account can directly process Afterpay Clearpay charges. + AfterpayClearpayPayments AccountCapabilityStatus `json:"afterpay_clearpay_payments"` + // The status of the Alma capability of the account, or whether the account can directly process Alma payments. + AlmaPayments AccountCapabilityStatus `json:"alma_payments"` + // The status of the AmazonPay capability of the account, or whether the account can directly process AmazonPay payments. + AmazonPayPayments AccountCapabilityStatus `json:"amazon_pay_payments"` + // The status of the BECS Direct Debit (AU) payments capability of the account, or whether the account can directly process BECS Direct Debit (AU) charges. + AUBECSDebitPayments AccountCapabilityStatus `json:"au_becs_debit_payments"` + // The status of the Bacs Direct Debits payments capability of the account, or whether the account can directly process Bacs Direct Debits charges. + BACSDebitPayments AccountCapabilityStatus `json:"bacs_debit_payments"` + // The status of the Bancontact payments capability of the account, or whether the account can directly process Bancontact charges. + BancontactPayments AccountCapabilityStatus `json:"bancontact_payments"` + // The status of the customer_balance payments capability of the account, or whether the account can directly process customer_balance charges. + BankTransferPayments AccountCapabilityStatus `json:"bank_transfer_payments"` + // The status of the Billie capability of the account, or whether the account can directly process Billie payments. + BilliePayments AccountCapabilityStatus `json:"billie_payments"` + // The status of the blik payments capability of the account, or whether the account can directly process blik charges. + BLIKPayments AccountCapabilityStatus `json:"blik_payments"` + // The status of the boleto payments capability of the account, or whether the account can directly process boleto charges. + BoletoPayments AccountCapabilityStatus `json:"boleto_payments"` + // The status of the card issuing capability of the account, or whether you can use Issuing to distribute funds on cards + CardIssuing AccountCapabilityStatus `json:"card_issuing"` + // The status of the card payments capability of the account, or whether the account can directly process credit and debit card charges. + CardPayments AccountCapabilityStatus `json:"card_payments"` + // The status of the Cartes Bancaires payments capability of the account, or whether the account can directly process Cartes Bancaires card charges in EUR currency. + CartesBancairesPayments AccountCapabilityStatus `json:"cartes_bancaires_payments"` + // The status of the Cash App Pay capability of the account, or whether the account can directly process Cash App Pay payments. + CashAppPayments AccountCapabilityStatus `json:"cashapp_payments"` + // The status of the Crypto capability of the account, or whether the account can directly process Crypto payments. + CryptoPayments AccountCapabilityStatus `json:"crypto_payments"` + // The status of the EPS payments capability of the account, or whether the account can directly process EPS charges. + EPSPayments AccountCapabilityStatus `json:"eps_payments"` + // The status of the FPX payments capability of the account, or whether the account can directly process FPX charges. + FPXPayments AccountCapabilityStatus `json:"fpx_payments"` + // The status of the GB customer_balance payments (GBP currency) capability of the account, or whether the account can directly process GB customer_balance charges. + GBBankTransferPayments AccountCapabilityStatus `json:"gb_bank_transfer_payments"` + // The status of the giropay payments capability of the account, or whether the account can directly process giropay charges. + GiropayPayments AccountCapabilityStatus `json:"giropay_payments"` + // The status of the GrabPay payments capability of the account, or whether the account can directly process GrabPay charges. + GrabpayPayments AccountCapabilityStatus `json:"grabpay_payments"` + // The status of the iDEAL payments capability of the account, or whether the account can directly process iDEAL charges. + IDEALPayments AccountCapabilityStatus `json:"ideal_payments"` + // The status of the india_international_payments capability of the account, or whether the account can process international charges (non INR) in India. + IndiaInternationalPayments AccountCapabilityStatus `json:"india_international_payments"` + // The status of the JCB payments capability of the account, or whether the account (Japan only) can directly process JCB credit card charges in JPY currency. + JCBPayments AccountCapabilityStatus `json:"jcb_payments"` + // The status of the Japanese customer_balance payments (JPY currency) capability of the account, or whether the account can directly process Japanese customer_balance charges. + JPBankTransferPayments AccountCapabilityStatus `json:"jp_bank_transfer_payments"` + // The status of the KakaoPay capability of the account, or whether the account can directly process KakaoPay payments. + KakaoPayPayments AccountCapabilityStatus `json:"kakao_pay_payments"` + // The status of the Klarna payments capability of the account, or whether the account can directly process Klarna charges. + KlarnaPayments AccountCapabilityStatus `json:"klarna_payments"` + // The status of the konbini payments capability of the account, or whether the account can directly process konbini charges. + KonbiniPayments AccountCapabilityStatus `json:"konbini_payments"` + // The status of the KrCard capability of the account, or whether the account can directly process KrCard payments. + KrCardPayments AccountCapabilityStatus `json:"kr_card_payments"` + // The status of the legacy payments capability of the account. + LegacyPayments AccountCapabilityStatus `json:"legacy_payments"` + // The status of the link_payments capability of the account, or whether the account can directly process Link charges. + LinkPayments AccountCapabilityStatus `json:"link_payments"` + // The status of the MobilePay capability of the account, or whether the account can directly process MobilePay charges. + MobilepayPayments AccountCapabilityStatus `json:"mobilepay_payments"` + // The status of the Multibanco payments capability of the account, or whether the account can directly process Multibanco charges. + MultibancoPayments AccountCapabilityStatus `json:"multibanco_payments"` + // The status of the Mexican customer_balance payments (MXN currency) capability of the account, or whether the account can directly process Mexican customer_balance charges. + MXBankTransferPayments AccountCapabilityStatus `json:"mx_bank_transfer_payments"` + // The status of the NaverPay capability of the account, or whether the account can directly process NaverPay payments. + NaverPayPayments AccountCapabilityStatus `json:"naver_pay_payments"` + // The status of the New Zealand BECS Direct Debit payments capability of the account, or whether the account can directly process New Zealand BECS Direct Debit charges. + NzBankAccountBECSDebitPayments AccountCapabilityStatus `json:"nz_bank_account_becs_debit_payments"` + // The status of the OXXO payments capability of the account, or whether the account can directly process OXXO charges. + OXXOPayments AccountCapabilityStatus `json:"oxxo_payments"` + // The status of the P24 payments capability of the account, or whether the account can directly process P24 charges. + P24Payments AccountCapabilityStatus `json:"p24_payments"` + // The status of the pay_by_bank payments capability of the account, or whether the account can directly process pay_by_bank charges. + PayByBankPayments AccountCapabilityStatus `json:"pay_by_bank_payments"` + // The status of the Payco capability of the account, or whether the account can directly process Payco payments. + PaycoPayments AccountCapabilityStatus `json:"payco_payments"` + // The status of the paynow payments capability of the account, or whether the account can directly process paynow charges. + PayNowPayments AccountCapabilityStatus `json:"paynow_payments"` + // The status of the pix payments capability of the account, or whether the account can directly process pix charges. + PixPayments AccountCapabilityStatus `json:"pix_payments"` + // The status of the promptpay payments capability of the account, or whether the account can directly process promptpay charges. + PromptPayPayments AccountCapabilityStatus `json:"promptpay_payments"` + // The status of the RevolutPay capability of the account, or whether the account can directly process RevolutPay payments. + RevolutPayPayments AccountCapabilityStatus `json:"revolut_pay_payments"` + // The status of the SamsungPay capability of the account, or whether the account can directly process SamsungPay payments. + SamsungPayPayments AccountCapabilityStatus `json:"samsung_pay_payments"` + // The status of the Satispay capability of the account, or whether the account can directly process Satispay payments. + SatispayPayments AccountCapabilityStatus `json:"satispay_payments"` + // The status of the SEPA customer_balance payments (EUR currency) capability of the account, or whether the account can directly process SEPA customer_balance charges. + SEPABankTransferPayments AccountCapabilityStatus `json:"sepa_bank_transfer_payments"` + // The status of the SEPA Direct Debits payments capability of the account, or whether the account can directly process SEPA Direct Debits charges. + SEPADebitPayments AccountCapabilityStatus `json:"sepa_debit_payments"` + // The status of the Sofort payments capability of the account, or whether the account can directly process Sofort charges. + SofortPayments AccountCapabilityStatus `json:"sofort_payments"` + // The status of the Swish capability of the account, or whether the account can directly process Swish payments. + SwishPayments AccountCapabilityStatus `json:"swish_payments"` + // The status of the tax reporting 1099-K (US) capability of the account. + TaxReportingUS1099K AccountCapabilityStatus `json:"tax_reporting_us_1099_k"` + // The status of the tax reporting 1099-MISC (US) capability of the account. + TaxReportingUS1099MISC AccountCapabilityStatus `json:"tax_reporting_us_1099_misc"` + // The status of the transfers capability of the account, or whether your platform can transfer funds to the account. + Transfers AccountCapabilityStatus `json:"transfers"` + // The status of the banking capability, or whether the account can have bank accounts. + Treasury AccountCapabilityStatus `json:"treasury"` + // The status of the TWINT capability of the account, or whether the account can directly process TWINT charges. + TWINTPayments AccountCapabilityStatus `json:"twint_payments"` + // The status of the US bank account ACH payments capability of the account, or whether the account can directly process US bank account charges. + USBankAccountACHPayments AccountCapabilityStatus `json:"us_bank_account_ach_payments"` + // The status of the US customer_balance payments (USD currency) capability of the account, or whether the account can directly process US customer_balance charges. + USBankTransferPayments AccountCapabilityStatus `json:"us_bank_transfer_payments"` + // The status of the Zip capability of the account, or whether the account can directly process Zip charges. + ZipPayments AccountCapabilityStatus `json:"zip_payments"` +} + +// The Kana variation of the company's primary address (Japan only). +type AccountCompanyAddressKana struct { + // City/Ward. + City string `json:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country string `json:"country"` + // Block/Building number. + Line1 string `json:"line1"` + // Building details. + Line2 string `json:"line2"` + // ZIP or postal code. + PostalCode string `json:"postal_code"` + // Prefecture. + State string `json:"state"` + // Town/cho-me. + Town string `json:"town"` +} + +// The Kanji variation of the company's primary address (Japan only). +type AccountCompanyAddressKanji struct { + // City/Ward. + City string `json:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country string `json:"country"` + // Block/Building number. + Line1 string `json:"line1"` + // Building details. + Line2 string `json:"line2"` + // ZIP or postal code. + PostalCode string `json:"postal_code"` + // Prefecture. + State string `json:"state"` + // Town/cho-me. + Town string `json:"town"` +} + +// This hash is used to attest that the director information provided to Stripe is both current and correct. +type AccountCompanyDirectorshipDeclaration struct { + // The Unix timestamp marking when the directorship declaration attestation was made. + Date int64 `json:"date"` + // The IP address from which the directorship declaration attestation was made. + IP string `json:"ip"` + // The user-agent string from the browser where the directorship declaration attestation was made. + UserAgent string `json:"user_agent"` +} + +// This hash is used to attest that the beneficial owner information provided to Stripe is both current and correct. +type AccountCompanyOwnershipDeclaration struct { + // The Unix timestamp marking when the beneficial owner attestation was made. + Date int64 `json:"date"` + // The IP address from which the beneficial owner attestation was made. + IP string `json:"ip"` + // The user-agent string from the browser where the beneficial owner attestation was made. + UserAgent string `json:"user_agent"` +} +type AccountCompanyRegistrationDate struct { + // The day of registration, between 1 and 31. + Day int64 `json:"day"` + // The month of registration, between 1 and 12. + Month int64 `json:"month"` + // The four-digit year of registration. + Year int64 `json:"year"` +} +type AccountCompanyVerificationDocument struct { + // The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. + Back *File `json:"back"` + // A user-displayable string describing the verification state of this document. + Details string `json:"details"` + // One of `document_corrupt`, `document_expired`, `document_failed_copy`, `document_failed_greyscale`, `document_failed_other`, `document_failed_test_mode`, `document_fraudulent`, `document_incomplete`, `document_invalid`, `document_manipulated`, `document_not_readable`, `document_not_uploaded`, `document_type_not_supported`, or `document_too_large`. A machine-readable code specifying the verification state for this document. + DetailsCode AccountCompanyVerificationDocumentDetailsCode `json:"details_code"` + // The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. + Front *File `json:"front"` +} + +// Information on the verification state of the company. +type AccountCompanyVerification struct { + Document *AccountCompanyVerificationDocument `json:"document"` +} +type AccountCompany struct { + Address *Address `json:"address"` + // The Kana variation of the company's primary address (Japan only). + AddressKana *AccountCompanyAddressKana `json:"address_kana"` + // The Kanji variation of the company's primary address (Japan only). + AddressKanji *AccountCompanyAddressKanji `json:"address_kanji"` + // This hash is used to attest that the director information provided to Stripe is both current and correct. + DirectorshipDeclaration *AccountCompanyDirectorshipDeclaration `json:"directorship_declaration"` + // Whether the company's directors have been provided. This Boolean will be `true` if you've manually indicated that all directors are provided via [the `directors_provided` parameter](https://stripe.com/docs/api/accounts/update#update_account-company-directors_provided). + DirectorsProvided bool `json:"directors_provided"` + // Whether the company's executives have been provided. This Boolean will be `true` if you've manually indicated that all executives are provided via [the `executives_provided` parameter](https://stripe.com/docs/api/accounts/update#update_account-company-executives_provided), or if Stripe determined that sufficient executives were provided. + ExecutivesProvided bool `json:"executives_provided"` + // The export license ID number of the company, also referred as Import Export Code (India only). + ExportLicenseID string `json:"export_license_id"` + // The purpose code to use for export transactions (India only). + ExportPurposeCode string `json:"export_purpose_code"` + // The company's legal name. Also available for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`. + Name string `json:"name"` + // The Kana variation of the company's legal name (Japan only). Also available for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`. + NameKana string `json:"name_kana"` + // The Kanji variation of the company's legal name (Japan only). Also available for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`. + NameKanji string `json:"name_kanji"` + // This hash is used to attest that the beneficial owner information provided to Stripe is both current and correct. + OwnershipDeclaration *AccountCompanyOwnershipDeclaration `json:"ownership_declaration"` + // This value is used to determine if a business is exempt from providing ultimate beneficial owners. See [this support article](https://support.stripe.com/questions/exemption-from-providing-ownership-details) and [changelog](https://docs.stripe.com/changelog/acacia/2025-01-27/ownership-exemption-reason-accounts-api) for more details. + OwnershipExemptionReason AccountCompanyOwnershipExemptionReason `json:"ownership_exemption_reason"` + // Whether the company's owners have been provided. This Boolean will be `true` if you've manually indicated that all owners are provided via [the `owners_provided` parameter](https://stripe.com/docs/api/accounts/update#update_account-company-owners_provided), or if Stripe determined that sufficient owners were provided. Stripe determines ownership requirements using both the number of owners provided and their total percent ownership (calculated by adding the `percent_ownership` of each owner together). + OwnersProvided bool `json:"owners_provided"` + // The company's phone number (used for verification). + Phone string `json:"phone"` + RegistrationDate *AccountCompanyRegistrationDate `json:"registration_date"` + // The category identifying the legal structure of the company or legal entity. Also available for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`. See [Business structure](https://stripe.com/docs/connect/identity-verification#business-structure) for more details. + Structure AccountCompanyStructure `json:"structure"` + // Whether the company's business ID number was provided. + TaxIDProvided bool `json:"tax_id_provided"` + // The jurisdiction in which the `tax_id` is registered (Germany-based companies only). + TaxIDRegistrar string `json:"tax_id_registrar"` + // Whether the company's business VAT number was provided. + VATIDProvided bool `json:"vat_id_provided"` + // Information on the verification state of the company. + Verification *AccountCompanyVerification `json:"verification"` +} +type AccountControllerFees struct { + // A value indicating the responsible payer of a bundle of Stripe fees for pricing-control eligible products on this account. Learn more about [fee behavior on connected accounts](https://docs.stripe.com/connect/direct-charges-fee-payer-behavior). + Payer AccountControllerFeesPayer `json:"payer"` +} +type AccountControllerLosses struct { + // A value indicating who is liable when this account can't pay back negative balances from payments. + Payments AccountControllerLossesPayments `json:"payments"` +} +type AccountControllerStripeDashboard struct { + // A value indicating the Stripe dashboard this account has access to independent of the Connect application. + Type AccountControllerStripeDashboardType `json:"type"` +} +type AccountController struct { + Fees *AccountControllerFees `json:"fees"` + // `true` if the Connect application retrieving the resource controls the account and can therefore exercise [platform controls](https://stripe.com/docs/connect/platform-controls-for-standard-accounts). Otherwise, this field is null. + IsController bool `json:"is_controller"` + Losses *AccountControllerLosses `json:"losses"` + // A value indicating responsibility for collecting requirements on this account. Only returned when the Connect application retrieving the resource controls the account. + RequirementCollection AccountControllerRequirementCollection `json:"requirement_collection"` + StripeDashboard *AccountControllerStripeDashboard `json:"stripe_dashboard"` + // The controller type. Can be `application`, if a Connect application controls the account, or `account`, if the account controls itself. + Type AccountControllerType `json:"type"` +} + +// Fields that are due and can be satisfied by providing the corresponding alternative fields instead. +type AccountFutureRequirementsAlternative struct { + // Fields that can be provided to satisfy all fields in `original_fields_due`. + AlternativeFieldsDue []string `json:"alternative_fields_due"` + // Fields that are due and can be satisfied by providing all fields in `alternative_fields_due`. + OriginalFieldsDue []string `json:"original_fields_due"` +} + +// Fields that are `currently_due` and need to be collected again because validation or verification failed. +type AccountFutureRequirementsError struct { + // The code for the type of error. + Code string `json:"code"` + // An informative message that indicates the error type and provides additional details about the error. + Reason string `json:"reason"` + // The specific user onboarding requirement field (in the requirements hash) that needs to be resolved. + Requirement string `json:"requirement"` +} +type AccountFutureRequirements struct { + // Fields that are due and can be satisfied by providing the corresponding alternative fields instead. + Alternatives []*AccountFutureRequirementsAlternative `json:"alternatives"` + // Date on which `future_requirements` becomes the main `requirements` hash and `future_requirements` becomes empty. After the transition, `currently_due` requirements may immediately become `past_due`, but the account may also be given a grace period depending on its enablement state prior to transitioning. + CurrentDeadline int64 `json:"current_deadline"` + // Fields that need to be collected to keep the account enabled. If not collected by `future_requirements[current_deadline]`, these fields will transition to the main `requirements` hash. + CurrentlyDue []string `json:"currently_due"` + // This is typed as an enum for consistency with `requirements.disabled_reason`. + DisabledReason AccountFutureRequirementsDisabledReason `json:"disabled_reason"` + // Fields that are `currently_due` and need to be collected again because validation or verification failed. + Errors []*AccountFutureRequirementsError `json:"errors"` + // Fields you must collect when all thresholds are reached. As they become required, they appear in `currently_due` as well. + EventuallyDue []string `json:"eventually_due"` + // Fields that weren't collected by `requirements.current_deadline`. These fields need to be collected to enable the capability on the account. New fields will never appear here; `future_requirements.past_due` will always be a subset of `requirements.past_due`. + PastDue []string `json:"past_due"` + // Fields that might become required depending on the results of verification or review. It's an empty array unless an asynchronous verification is pending. If verification fails, these fields move to `eventually_due` or `currently_due`. Fields might appear in `eventually_due` or `currently_due` and in `pending_verification` if verification fails but another verification is still pending. + PendingVerification []string `json:"pending_verification"` +} + +// The groups associated with the account. +type AccountGroups struct { + // The group the account is in to determine their payments pricing, and null if the account is on customized pricing. [See the Platform pricing tool documentation](https://stripe.com/docs/connect/platform-pricing-tools) for details. + PaymentsPricing string `json:"payments_pricing"` +} + +// Fields that are due and can be satisfied by providing the corresponding alternative fields instead. +type AccountRequirementsAlternative struct { + // Fields that can be provided to satisfy all fields in `original_fields_due`. + AlternativeFieldsDue []string `json:"alternative_fields_due"` + // Fields that are due and can be satisfied by providing all fields in `alternative_fields_due`. + OriginalFieldsDue []string `json:"original_fields_due"` +} + +// Fields that are `currently_due` and need to be collected again because validation or verification failed. +type AccountRequirementsError struct { + // The code for the type of error. + Code string `json:"code"` + // An informative message that indicates the error type and provides additional details about the error. + Reason string `json:"reason"` + // The specific user onboarding requirement field (in the requirements hash) that needs to be resolved. + Requirement string `json:"requirement"` +} +type AccountRequirements struct { + // Fields that are due and can be satisfied by providing the corresponding alternative fields instead. + Alternatives []*AccountRequirementsAlternative `json:"alternatives"` + // Date by which the fields in `currently_due` must be collected to keep the account enabled. These fields may disable the account sooner if the next threshold is reached before they are collected. + CurrentDeadline int64 `json:"current_deadline"` + // Fields that need to be collected to keep the account enabled. If not collected by `current_deadline`, these fields appear in `past_due` as well, and the account is disabled. + CurrentlyDue []string `json:"currently_due"` + // If the account is disabled, this enum describes why. [Learn more about handling verification issues](https://stripe.com/docs/connect/handling-api-verification). + DisabledReason AccountRequirementsDisabledReason `json:"disabled_reason"` + // Fields that are `currently_due` and need to be collected again because validation or verification failed. + Errors []*AccountRequirementsError `json:"errors"` + // Fields you must collect when all thresholds are reached. As they become required, they appear in `currently_due` as well, and `current_deadline` becomes set. + EventuallyDue []string `json:"eventually_due"` + // Fields that weren't collected by `current_deadline`. These fields need to be collected to enable the account. + PastDue []string `json:"past_due"` + // Fields that might become required depending on the results of verification or review. It's an empty array unless an asynchronous verification is pending. If verification fails, these fields move to `eventually_due`, `currently_due`, or `past_due`. Fields might appear in `eventually_due`, `currently_due`, or `past_due` and in `pending_verification` if verification fails but another verification is still pending. + PendingVerification []string `json:"pending_verification"` +} +type AccountSettingsBACSDebitPayments struct { + // The Bacs Direct Debit display name for this account. For payments made with Bacs Direct Debit, this name appears on the mandate as the statement descriptor. Mobile banking apps display it as the name of the business. To use custom branding, set the Bacs Direct Debit Display Name during or right after creation. Custom branding incurs an additional monthly fee for the platform. The fee appears 5 business days after requesting Bacs. If you don't set the display name before requesting Bacs capability, it's automatically set as "Stripe" and the account is onboarded to Stripe branding, which is free. + DisplayName string `json:"display_name"` + // The Bacs Direct Debit Service user number for this account. For payments made with Bacs Direct Debit, this number is a unique identifier of the account with our banking partners. + ServiceUserNumber string `json:"service_user_number"` +} +type AccountSettingsBranding struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) An icon for the account. Must be square and at least 128px x 128px. + Icon *File `json:"icon"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) A logo for the account that will be used in Checkout instead of the icon and without the account's name next to it if provided. Must be at least 128px x 128px. + Logo *File `json:"logo"` + // A CSS hex color value representing the primary branding color for this account + PrimaryColor string `json:"primary_color"` + // A CSS hex color value representing the secondary branding color for this account + SecondaryColor string `json:"secondary_color"` +} +type AccountSettingsCardIssuingTOSAcceptance struct { + // The Unix timestamp marking when the account representative accepted the service agreement. + Date int64 `json:"date"` + // The IP address from which the account representative accepted the service agreement. + IP string `json:"ip"` + // The user agent of the browser from which the account representative accepted the service agreement. + UserAgent string `json:"user_agent"` +} +type AccountSettingsCardIssuing struct { + TOSAcceptance *AccountSettingsCardIssuingTOSAcceptance `json:"tos_acceptance"` +} +type AccountSettingsCardPaymentsDeclineOn struct { + // Whether Stripe automatically declines charges with an incorrect ZIP or postal code. This setting only applies when a ZIP or postal code is provided and they fail bank verification. + AVSFailure bool `json:"avs_failure"` + // Whether Stripe automatically declines charges with an incorrect CVC. This setting only applies when a CVC is provided and it fails bank verification. + CVCFailure bool `json:"cvc_failure"` +} +type AccountSettingsCardPayments struct { + DeclineOn *AccountSettingsCardPaymentsDeclineOn `json:"decline_on"` + // The default text that appears on credit card statements when a charge is made. This field prefixes any dynamic `statement_descriptor` specified on the charge. `statement_descriptor_prefix` is useful for maximizing descriptor space for the dynamic portion. + StatementDescriptorPrefix string `json:"statement_descriptor_prefix"` + // The Kana variation of the default text that appears on credit card statements when a charge is made (Japan only). This field prefixes any dynamic `statement_descriptor_suffix_kana` specified on the charge. `statement_descriptor_prefix_kana` is useful for maximizing descriptor space for the dynamic portion. + StatementDescriptorPrefixKana string `json:"statement_descriptor_prefix_kana"` + // The Kanji variation of the default text that appears on credit card statements when a charge is made (Japan only). This field prefixes any dynamic `statement_descriptor_suffix_kanji` specified on the charge. `statement_descriptor_prefix_kanji` is useful for maximizing descriptor space for the dynamic portion. + StatementDescriptorPrefixKanji string `json:"statement_descriptor_prefix_kanji"` +} +type AccountSettingsDashboard struct { + // The display name for this account. This is used on the Stripe Dashboard to differentiate between accounts. + DisplayName string `json:"display_name"` + // The timezone used in the Stripe Dashboard for this account. A list of possible time zone values is maintained at the [IANA Time Zone Database](http://www.iana.org/time-zones). + Timezone string `json:"timezone"` +} +type AccountSettingsInvoices struct { + // The list of default Account Tax IDs to automatically include on invoices. Account Tax IDs get added when an invoice is finalized. + DefaultAccountTaxIDs []*TaxID `json:"default_account_tax_ids"` + // Whether payment methods should be saved when a payment is completed for a one-time invoices on a hosted invoice page. + HostedPaymentMethodSave AccountSettingsInvoicesHostedPaymentMethodSave `json:"hosted_payment_method_save"` +} +type AccountSettingsPayments struct { + // The default text that appears on credit card statements when a charge is made. This field prefixes any dynamic `statement_descriptor` specified on the charge. + StatementDescriptor string `json:"statement_descriptor"` + // The Kana variation of `statement_descriptor` used for charges in Japan. Japanese statement descriptors have [special requirements](https://docs.stripe.com/get-started/account/statement-descriptors#set-japanese-statement-descriptors). + StatementDescriptorKana string `json:"statement_descriptor_kana"` + // The Kanji variation of `statement_descriptor` used for charges in Japan. Japanese statement descriptors have [special requirements](https://docs.stripe.com/get-started/account/statement-descriptors#set-japanese-statement-descriptors). + StatementDescriptorKanji string `json:"statement_descriptor_kanji"` + // The Kana variation of `statement_descriptor_prefix` used for card charges in Japan. Japanese statement descriptors have [special requirements](https://docs.stripe.com/get-started/account/statement-descriptors#set-japanese-statement-descriptors). + StatementDescriptorPrefixKana string `json:"statement_descriptor_prefix_kana"` + // The Kanji variation of `statement_descriptor_prefix` used for card charges in Japan. Japanese statement descriptors have [special requirements](https://docs.stripe.com/get-started/account/statement-descriptors#set-japanese-statement-descriptors). + StatementDescriptorPrefixKanji string `json:"statement_descriptor_prefix_kanji"` +} +type AccountSettingsPayoutsSchedule struct { + // The number of days charges for the account will be held before being paid out. + DelayDays int64 `json:"delay_days"` + // How frequently funds will be paid out. One of `manual` (payouts only created via API call), `daily`, `weekly`, or `monthly`. + Interval AccountSettingsPayoutsScheduleInterval `json:"interval"` + // The day of the month funds will be paid out. Only shown if `interval` is monthly. Payouts scheduled between the 29th and 31st of the month are sent on the last day of shorter months. + MonthlyAnchor int64 `json:"monthly_anchor"` + // The days of the month funds will be paid out. Only shown if `interval` is monthly. Payouts scheduled between the 29th and 31st of the month are sent on the last day of shorter months. + MonthlyPayoutDays []int64 `json:"monthly_payout_days"` + // The day of the week funds will be paid out, of the style 'monday', 'tuesday', etc. Only shown if `interval` is weekly. + WeeklyAnchor string `json:"weekly_anchor"` + // The days of the week when available funds are paid out, specified as an array, for example, [`monday`, `tuesday`]. Only shown if `interval` is weekly. + WeeklyPayoutDays []AccountSettingsPayoutsScheduleWeeklyPayoutDay `json:"weekly_payout_days"` +} +type AccountSettingsPayouts struct { + // A Boolean indicating if Stripe should try to reclaim negative balances from an attached bank account. See [Understanding Connect account balances](https://docs.stripe.com/connect/account-balances) for details. The default value is `false` when [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts, otherwise `true`. + DebitNegativeBalances bool `json:"debit_negative_balances"` + Schedule *AccountSettingsPayoutsSchedule `json:"schedule"` + // The text that appears on the bank account statement for payouts. If not set, this defaults to the platform's bank descriptor as set in the Dashboard. + StatementDescriptor string `json:"statement_descriptor"` +} +type AccountSettingsSEPADebitPayments struct { + // SEPA creditor identifier that identifies the company making the payment. + CreditorID string `json:"creditor_id"` +} +type AccountSettingsTreasuryTOSAcceptance struct { + // The Unix timestamp marking when the account representative accepted the service agreement. + Date int64 `json:"date"` + // The IP address from which the account representative accepted the service agreement. + IP string `json:"ip"` + // The user agent of the browser from which the account representative accepted the service agreement. + UserAgent string `json:"user_agent"` +} +type AccountSettingsTreasury struct { + TOSAcceptance *AccountSettingsTreasuryTOSAcceptance `json:"tos_acceptance"` +} + +// Options for customizing how the account functions within Stripe. +type AccountSettings struct { + BACSDebitPayments *AccountSettingsBACSDebitPayments `json:"bacs_debit_payments"` + Branding *AccountSettingsBranding `json:"branding"` + CardIssuing *AccountSettingsCardIssuing `json:"card_issuing"` + CardPayments *AccountSettingsCardPayments `json:"card_payments"` + Dashboard *AccountSettingsDashboard `json:"dashboard"` + Invoices *AccountSettingsInvoices `json:"invoices"` + Payments *AccountSettingsPayments `json:"payments"` + Payouts *AccountSettingsPayouts `json:"payouts"` + SEPADebitPayments *AccountSettingsSEPADebitPayments `json:"sepa_debit_payments"` + Treasury *AccountSettingsTreasury `json:"treasury"` +} +type AccountTOSAcceptance struct { + // The Unix timestamp marking when the account representative accepted their service agreement + Date int64 `json:"date"` + // The IP address from which the account representative accepted their service agreement + IP string `json:"ip"` + // The user's service agreement type + ServiceAgreement AccountTOSAcceptanceServiceAgreement `json:"service_agreement"` + // The user agent of the browser from which the account representative accepted their service agreement + UserAgent string `json:"user_agent"` +} + +// This is an object representing a Stripe account. You can retrieve it to see +// properties on the account like its current requirements or if the account is +// enabled to make live charges or receive payouts. +// +// For accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) +// is `application`, which includes Custom accounts, the properties below are always +// returned. +// +// For accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) +// is `stripe`, which includes Standard and Express accounts, some properties are only returned +// until you create an [Account Link](https://docs.stripe.com/api/account_links) or [Account Session](https://docs.stripe.com/api/account_sessions) +// to start Connect Onboarding. Learn about the [differences between accounts](https://docs.stripe.com/connect/accounts). +type Account struct { + APIResource + // Business information about the account. + BusinessProfile *AccountBusinessProfile `json:"business_profile"` + // The business type. + BusinessType AccountBusinessType `json:"business_type"` + Capabilities *AccountCapabilities `json:"capabilities"` + // Whether the account can process charges. + ChargesEnabled bool `json:"charges_enabled"` + Company *AccountCompany `json:"company"` + Controller *AccountController `json:"controller"` + // The account's country. + Country string `json:"country"` + // Time at which the account was connected. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter ISO currency code representing the default currency for the account. This must be a currency that [Stripe supports in the account's country](https://stripe.com/docs/payouts). + DefaultCurrency Currency `json:"default_currency"` + Deleted bool `json:"deleted"` + // Whether account details have been submitted. Accounts with Stripe Dashboard access, which includes Standard accounts, cannot receive payouts before this is true. Accounts where this is false should be directed to [an onboarding flow](https://docs.stripe.com/connect/onboarding) to finish submitting account details. + DetailsSubmitted bool `json:"details_submitted"` + // An email address associated with the account. It's not used for authentication and Stripe doesn't market to this field without explicit approval from the platform. + Email string `json:"email"` + // External accounts (bank accounts and debit cards) currently attached to this account. External accounts are only returned for requests where `controller[is_controller]` is true. + ExternalAccounts *AccountExternalAccountList `json:"external_accounts"` + FutureRequirements *AccountFutureRequirements `json:"future_requirements"` + // The groups associated with the account. + Groups *AccountGroups `json:"groups"` + // Unique identifier for the object. + ID string `json:"id"` + // This is an object representing a person associated with a Stripe account. + // + // A platform can only access a subset of data in a person for an account where [account.controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`, which includes Standard and Express accounts, after creating an Account Link or Account Session to start Connect onboarding. + // + // See the [Standard onboarding](https://docs.stripe.com/connect/standard-accounts) or [Express onboarding](https://docs.stripe.com/connect/express-accounts) documentation for information about prefilling information and account onboarding steps. Learn more about [handling identity verification with the API](https://docs.stripe.com/connect/handling-api-verification#person-information). + Individual *Person `json:"individual"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Whether the funds in this account can be paid out. + PayoutsEnabled bool `json:"payouts_enabled"` + Requirements *AccountRequirements `json:"requirements"` + // Options for customizing how the account functions within Stripe. + Settings *AccountSettings `json:"settings"` + TOSAcceptance *AccountTOSAcceptance `json:"tos_acceptance"` + // The Stripe account type. Can be `standard`, `express`, `custom`, or `none`. + Type AccountType `json:"type"` +} +type AccountExternalAccount struct { + ID string `json:"id"` + Type AccountExternalAccountType `json:"object"` + + BankAccount *BankAccount `json:"-"` + Card *Card `json:"-"` +} + +// AccountList is a list of Accounts as retrieved from a list endpoint. +type AccountList struct { + APIResource + ListMeta + Data []*Account `json:"data"` +} + +// AccountExternalAccountList is a list of external accounts that may be either bank +// accounts or cards. +type AccountExternalAccountList struct { + APIResource + ListMeta + + // Values contains any external accounts (bank accounts and/or cards) + // currently attached to this account. + Data []*AccountExternalAccount `json:"data"` +} + +// UnmarshalJSON handles deserialization of an Account. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (a *Account) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + a.ID = id + return nil + } + + type account Account + var v account + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *a = Account(v) + return nil +} + +// UnmarshalJSON handles deserialization of an AccountExternalAccount. +// This custom unmarshaling is needed because the specific type of +// AccountExternalAccount it refers to is specified in the JSON +func (a *AccountExternalAccount) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + a.ID = id + return nil + } + + type accountExternalAccount AccountExternalAccount + var v accountExternalAccount + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *a = AccountExternalAccount(v) + var err error + + switch a.Type { + case AccountExternalAccountTypeBankAccount: + err = json.Unmarshal(data, &a.BankAccount) + case AccountExternalAccountTypeCard: + err = json.Unmarshal(data, &a.Card) + } + return err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/account_service.go b/vendor/github.com/stripe/stripe-go/v82/account_service.go new file mode 100644 index 00000000..5f5055ab --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/account_service.go @@ -0,0 +1,132 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1AccountService is used to invoke /v1/accounts APIs. +type v1AccountService struct { + B Backend + Key string +} + +// With [Connect](https://docs.stripe.com/docs/connect), you can create Stripe accounts for your users. +// To do this, you'll first need to [register your platform](https://dashboard.stripe.com/account/applications/settings). +// +// If you've already collected information for your connected accounts, you [can prefill that information](https://docs.stripe.com/docs/connect/best-practices#onboarding) when +// creating the account. Connect Onboarding won't ask for the prefilled information during account onboarding. +// You can prefill any information on the account. +func (c v1AccountService) Create(ctx context.Context, params *AccountCreateParams) (*Account, error) { + if params == nil { + params = &AccountCreateParams{} + } + params.Context = ctx + account := &Account{} + err := c.B.Call(http.MethodPost, "/v1/accounts", c.Key, params, account) + return account, err +} + +// Retrieves the details of an account. +func (c v1AccountService) Retrieve(ctx context.Context, params *AccountRetrieveParams) (*Account, error) { + if params == nil { + params = &AccountRetrieveParams{} + } + params.Context = ctx + account := &Account{} + err := c.B.Call(http.MethodGet, "/v1/account", c.Key, params, account) + return account, err +} + +// Retrieves the details of an account. +func (c v1AccountService) GetByID(ctx context.Context, id string, params *AccountRetrieveParams) (*Account, error) { + if params == nil { + params = &AccountRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/accounts/%s", id) + account := &Account{} + err := c.B.Call(http.MethodGet, path, c.Key, params, account) + return account, err +} + +// Updates a [connected account](https://docs.stripe.com/connect/accounts) by setting the values of the parameters passed. Any parameters not provided are +// left unchanged. +// +// For accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) +// is application, which includes Custom accounts, you can update any information on the account. +// +// For accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) +// is stripe, which includes Standard and Express accounts, you can update all information until you create +// an [Account Link or Account Session](https://docs.stripe.com/api/account_links) to start Connect onboarding, +// after which some properties can no longer be updated. +// +// To update your own account, use the [Dashboard](https://dashboard.stripe.com/settings/account). Refer to our +// [Connect](https://docs.stripe.com/docs/connect/updating-accounts) documentation to learn more about updating accounts. +func (c v1AccountService) Update(ctx context.Context, id string, params *AccountUpdateParams) (*Account, error) { + if params == nil { + params = &AccountUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/accounts/%s", id) + account := &Account{} + err := c.B.Call(http.MethodPost, path, c.Key, params, account) + return account, err +} + +// With [Connect](https://docs.stripe.com/connect), you can delete accounts you manage. +// +// Test-mode accounts can be deleted at any time. +// +// Live-mode accounts where Stripe is responsible for negative account balances cannot be deleted, which includes Standard accounts. Live-mode accounts where your platform is liable for negative account balances, which includes Custom and Express accounts, can be deleted when all [balances](https://docs.stripe.com/api/balance/balance_object) are zero. +// +// If you want to delete your own account, use the [account information tab in your account settings](https://dashboard.stripe.com/settings/account) instead. +func (c v1AccountService) Delete(ctx context.Context, id string, params *AccountDeleteParams) (*Account, error) { + if params == nil { + params = &AccountDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/accounts/%s", id) + account := &Account{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, account) + return account, err +} + +// With [Connect](https://docs.stripe.com/connect), you can reject accounts that you have flagged as suspicious. +// +// Only accounts where your platform is liable for negative account balances, which includes Custom and Express accounts, can be rejected. Test-mode accounts can be rejected at any time. Live-mode accounts can only be rejected after all balances are zero. +func (c v1AccountService) Reject(ctx context.Context, id string, params *AccountRejectParams) (*Account, error) { + if params == nil { + params = &AccountRejectParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/accounts/%s/reject", id) + account := &Account{} + err := c.B.Call(http.MethodPost, path, c.Key, params, account) + return account, err +} + +// Returns a list of accounts connected to your platform via [Connect](https://docs.stripe.com/docs/connect). If you're not a platform, the list is empty. +func (c v1AccountService) List(ctx context.Context, listParams *AccountListParams) Seq2[*Account, error] { + if listParams == nil { + listParams = &AccountListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Account, ListContainer, error) { + list := &AccountList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/accounts", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/accountlink.go b/vendor/github.com/stripe/stripe-go/v82/accountlink.go new file mode 100644 index 00000000..75fd1d8a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/accountlink.go @@ -0,0 +1,105 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Specifies the requirements that Stripe collects from connected accounts in the Connect Onboarding flow. +type AccountLinkCollectionOptionsParams struct { + // Specifies whether the platform collects only currently_due requirements (`currently_due`) or both currently_due and eventually_due requirements (`eventually_due`). If you don't specify `collection_options`, the default value is `currently_due`. + Fields *string `form:"fields"` + // Specifies whether the platform collects future_requirements in addition to requirements in Connect Onboarding. The default value is `omit`. + FutureRequirements *string `form:"future_requirements"` +} + +// AccountLinkType is the type of an account link. +type AccountLinkType string + +// List of values that AccountLinkType can take. +const ( + AccountLinkTypeAccountOnboarding AccountLinkType = "account_onboarding" + AccountLinkTypeAccountUpdate AccountLinkType = "account_update" +) + +// AccountLinkCollect describes what information the platform wants to collect with the account link. +type AccountLinkCollect string + +// List of values that AccountLinkCollect can take. +const ( + AccountLinkCollectCurrentlyDue AccountLinkCollect = "currently_due" + AccountLinkCollectEventuallyDue AccountLinkCollect = "eventually_due" +) + +// Creates an AccountLink object that includes a single-use Stripe URL that the platform can redirect their user to in order to take them through the Connect Onboarding flow. +type AccountLinkParams struct { + Params `form:"*"` + // The identifier of the account to create an account link for. + Account *string `form:"account"` + // The collect parameter is deprecated. Use `collection_options` instead. + Collect *string `form:"collect"` + // Specifies the requirements that Stripe collects from connected accounts in the Connect Onboarding flow. + CollectionOptions *AccountLinkCollectionOptionsParams `form:"collection_options"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The URL the user will be redirected to if the account link is expired, has been previously-visited, or is otherwise invalid. The URL you specify should attempt to generate a new account link with the same parameters used to create the original account link, then redirect the user to the new account link's URL so they can continue with Connect Onboarding. If a new account link cannot be generated or the redirect fails you should display a useful error to the user. + RefreshURL *string `form:"refresh_url"` + // The URL that the user will be redirected to upon leaving or completing the linked flow. + ReturnURL *string `form:"return_url"` + // The type of account link the user is requesting. Possible values are `account_onboarding` or `account_update`. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *AccountLinkParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Specifies the requirements that Stripe collects from connected accounts in the Connect Onboarding flow. +type AccountLinkCreateCollectionOptionsParams struct { + // Specifies whether the platform collects only currently_due requirements (`currently_due`) or both currently_due and eventually_due requirements (`eventually_due`). If you don't specify `collection_options`, the default value is `currently_due`. + Fields *string `form:"fields"` + // Specifies whether the platform collects future_requirements in addition to requirements in Connect Onboarding. The default value is `omit`. + FutureRequirements *string `form:"future_requirements"` +} + +// Creates an AccountLink object that includes a single-use Stripe URL that the platform can redirect their user to in order to take them through the Connect Onboarding flow. +type AccountLinkCreateParams struct { + Params `form:"*"` + // The identifier of the account to create an account link for. + Account *string `form:"account"` + // The collect parameter is deprecated. Use `collection_options` instead. + Collect *string `form:"collect"` + // Specifies the requirements that Stripe collects from connected accounts in the Connect Onboarding flow. + CollectionOptions *AccountLinkCreateCollectionOptionsParams `form:"collection_options"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The URL the user will be redirected to if the account link is expired, has been previously-visited, or is otherwise invalid. The URL you specify should attempt to generate a new account link with the same parameters used to create the original account link, then redirect the user to the new account link's URL so they can continue with Connect Onboarding. If a new account link cannot be generated or the redirect fails you should display a useful error to the user. + RefreshURL *string `form:"refresh_url"` + // The URL that the user will be redirected to upon leaving or completing the linked flow. + ReturnURL *string `form:"return_url"` + // The type of account link the user is requesting. Possible values are `account_onboarding` or `account_update`. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *AccountLinkCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Account Links are the means by which a Connect platform grants a connected account permission to access +// Stripe-hosted applications, such as Connect Onboarding. +// +// Related guide: [Connect Onboarding](https://stripe.com/docs/connect/custom/hosted-onboarding) +type AccountLink struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The timestamp at which this account link will expire. + ExpiresAt int64 `json:"expires_at"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The URL for the account link. + URL string `json:"url"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/accountlink_service.go b/vendor/github.com/stripe/stripe-go/v82/accountlink_service.go new file mode 100644 index 00000000..1c69987c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/accountlink_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1AccountLinkService is used to invoke /v1/account_links APIs. +type v1AccountLinkService struct { + B Backend + Key string +} + +// Creates an AccountLink object that includes a single-use Stripe URL that the platform can redirect their user to in order to take them through the Connect Onboarding flow. +func (c v1AccountLinkService) Create(ctx context.Context, params *AccountLinkCreateParams) (*AccountLink, error) { + if params == nil { + params = &AccountLinkCreateParams{} + } + params.Context = ctx + accountlink := &AccountLink{} + err := c.B.Call( + http.MethodPost, "/v1/account_links", c.Key, params, accountlink) + return accountlink, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/accountsession.go b/vendor/github.com/stripe/stripe-go/v82/accountsession.go new file mode 100644 index 00000000..765b2f4d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/accountsession.go @@ -0,0 +1,946 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The list of features enabled in the embedded component. +type AccountSessionComponentsAccountManagementFeaturesParams struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication *bool `form:"disable_stripe_user_authentication"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection *bool `form:"external_account_collection"` +} + +// Configuration for the [account management](https://docs.stripe.com/connect/supported-embedded-components/account-management/) embedded component. +type AccountSessionComponentsAccountManagementParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsAccountManagementFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsAccountOnboardingFeaturesParams struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication *bool `form:"disable_stripe_user_authentication"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection *bool `form:"external_account_collection"` +} + +// Configuration for the [account onboarding](https://docs.stripe.com/connect/supported-embedded-components/account-onboarding/) embedded component. +type AccountSessionComponentsAccountOnboardingParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsAccountOnboardingFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsBalancesFeaturesParams struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication *bool `form:"disable_stripe_user_authentication"` + // Whether to allow payout schedule to be changed. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + EditPayoutSchedule *bool `form:"edit_payout_schedule"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection *bool `form:"external_account_collection"` + // Whether to allow creation of instant payouts. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + InstantPayouts *bool `form:"instant_payouts"` + // Whether to allow creation of standard payouts. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + StandardPayouts *bool `form:"standard_payouts"` +} + +// Configuration for the [balances](https://docs.stripe.com/connect/supported-embedded-components/balances/) embedded component. +type AccountSessionComponentsBalancesParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsBalancesFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsDisputesListFeaturesParams struct { + // Whether to allow capturing and cancelling payment intents. This is `true` by default. + CapturePayments *bool `form:"capture_payments"` + // Whether connected accounts can manage destination charges that are created on behalf of them. This is `false` by default. + DestinationOnBehalfOfChargeManagement *bool `form:"destination_on_behalf_of_charge_management"` + // Whether responding to disputes is enabled, including submitting evidence and accepting disputes. This is `true` by default. + DisputeManagement *bool `form:"dispute_management"` + // Whether sending refunds is enabled. This is `true` by default. + RefundManagement *bool `form:"refund_management"` +} + +// Configuration for the [disputes list](https://docs.stripe.com/connect/supported-embedded-components/disputes-list/) embedded component. +type AccountSessionComponentsDisputesListParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsDisputesListFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsDocumentsFeaturesParams struct{} + +// Configuration for the [documents](https://docs.stripe.com/connect/supported-embedded-components/documents/) embedded component. +type AccountSessionComponentsDocumentsParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsDocumentsFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsFinancialAccountFeaturesParams struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication *bool `form:"disable_stripe_user_authentication"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection *bool `form:"external_account_collection"` + // Whether to allow sending money. + SendMoney *bool `form:"send_money"` + // Whether to allow transferring balance. + TransferBalance *bool `form:"transfer_balance"` +} + +// Configuration for the [financial account](https://docs.stripe.com/connect/supported-embedded-components/financial-account/) embedded component. +type AccountSessionComponentsFinancialAccountParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsFinancialAccountFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsFinancialAccountTransactionsFeaturesParams struct { + // Whether to allow card spend dispute management features. + CardSpendDisputeManagement *bool `form:"card_spend_dispute_management"` +} + +// Configuration for the [financial account transactions](https://docs.stripe.com/connect/supported-embedded-components/financial-account-transactions/) embedded component. +type AccountSessionComponentsFinancialAccountTransactionsParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsFinancialAccountTransactionsFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsIssuingCardFeaturesParams struct { + // Whether to allow cardholder management features. + CardholderManagement *bool `form:"cardholder_management"` + // Whether to allow card management features. + CardManagement *bool `form:"card_management"` + // Whether to allow card spend dispute management features. + CardSpendDisputeManagement *bool `form:"card_spend_dispute_management"` + // Whether to allow spend control management features. + SpendControlManagement *bool `form:"spend_control_management"` +} + +// Configuration for the [issuing card](https://docs.stripe.com/connect/supported-embedded-components/issuing-card/) embedded component. +type AccountSessionComponentsIssuingCardParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsIssuingCardFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsIssuingCardsListFeaturesParams struct { + // Whether to allow cardholder management features. + CardholderManagement *bool `form:"cardholder_management"` + // Whether to allow card management features. + CardManagement *bool `form:"card_management"` + // Whether to allow card spend dispute management features. + CardSpendDisputeManagement *bool `form:"card_spend_dispute_management"` + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication *bool `form:"disable_stripe_user_authentication"` + // Whether to allow spend control management features. + SpendControlManagement *bool `form:"spend_control_management"` +} + +// Configuration for the [issuing cards list](https://docs.stripe.com/connect/supported-embedded-components/issuing-cards-list/) embedded component. +type AccountSessionComponentsIssuingCardsListParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsIssuingCardsListFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsNotificationBannerFeaturesParams struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication *bool `form:"disable_stripe_user_authentication"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection *bool `form:"external_account_collection"` +} + +// Configuration for the [notification banner](https://docs.stripe.com/connect/supported-embedded-components/notification-banner/) embedded component. +type AccountSessionComponentsNotificationBannerParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsNotificationBannerFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsPaymentDetailsFeaturesParams struct { + // Whether to allow capturing and cancelling payment intents. This is `true` by default. + CapturePayments *bool `form:"capture_payments"` + // Whether connected accounts can manage destination charges that are created on behalf of them. This is `false` by default. + DestinationOnBehalfOfChargeManagement *bool `form:"destination_on_behalf_of_charge_management"` + // Whether responding to disputes is enabled, including submitting evidence and accepting disputes. This is `true` by default. + DisputeManagement *bool `form:"dispute_management"` + // Whether sending refunds is enabled. This is `true` by default. + RefundManagement *bool `form:"refund_management"` +} + +// Configuration for the [payment details](https://docs.stripe.com/connect/supported-embedded-components/payment-details/) embedded component. +type AccountSessionComponentsPaymentDetailsParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsPaymentDetailsFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsPaymentDisputesFeaturesParams struct { + // Whether connected accounts can manage destination charges that are created on behalf of them. This is `false` by default. + DestinationOnBehalfOfChargeManagement *bool `form:"destination_on_behalf_of_charge_management"` + // Whether responding to disputes is enabled, including submitting evidence and accepting disputes. This is `true` by default. + DisputeManagement *bool `form:"dispute_management"` + // Whether sending refunds is enabled. This is `true` by default. + RefundManagement *bool `form:"refund_management"` +} + +// Configuration for the [payment disputes](https://docs.stripe.com/connect/supported-embedded-components/payment-disputes/) embedded component. +type AccountSessionComponentsPaymentDisputesParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsPaymentDisputesFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsPaymentsFeaturesParams struct { + // Whether to allow capturing and cancelling payment intents. This is `true` by default. + CapturePayments *bool `form:"capture_payments"` + // Whether connected accounts can manage destination charges that are created on behalf of them. This is `false` by default. + DestinationOnBehalfOfChargeManagement *bool `form:"destination_on_behalf_of_charge_management"` + // Whether responding to disputes is enabled, including submitting evidence and accepting disputes. This is `true` by default. + DisputeManagement *bool `form:"dispute_management"` + // Whether sending refunds is enabled. This is `true` by default. + RefundManagement *bool `form:"refund_management"` +} + +// Configuration for the [payments](https://docs.stripe.com/connect/supported-embedded-components/payments/) embedded component. +type AccountSessionComponentsPaymentsParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsPaymentsFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsPayoutsFeaturesParams struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication *bool `form:"disable_stripe_user_authentication"` + // Whether to allow payout schedule to be changed. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + EditPayoutSchedule *bool `form:"edit_payout_schedule"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection *bool `form:"external_account_collection"` + // Whether to allow creation of instant payouts. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + InstantPayouts *bool `form:"instant_payouts"` + // Whether to allow creation of standard payouts. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + StandardPayouts *bool `form:"standard_payouts"` +} + +// Configuration for the [payouts](https://docs.stripe.com/connect/supported-embedded-components/payouts/) embedded component. +type AccountSessionComponentsPayoutsParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsPayoutsFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsPayoutsListFeaturesParams struct{} + +// Configuration for the [payouts list](https://docs.stripe.com/connect/supported-embedded-components/payouts-list/) embedded component. +type AccountSessionComponentsPayoutsListParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsPayoutsListFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsTaxRegistrationsFeaturesParams struct{} + +// Configuration for the [tax registrations](https://docs.stripe.com/connect/supported-embedded-components/tax-registrations/) embedded component. +type AccountSessionComponentsTaxRegistrationsParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsTaxRegistrationsFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionComponentsTaxSettingsFeaturesParams struct{} + +// Configuration for the [tax settings](https://docs.stripe.com/connect/supported-embedded-components/tax-settings/) embedded component. +type AccountSessionComponentsTaxSettingsParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionComponentsTaxSettingsFeaturesParams `form:"features"` +} + +// Each key of the dictionary represents an embedded component, and each embedded component maps to its configuration (e.g. whether it has been enabled or not). +type AccountSessionComponentsParams struct { + // Configuration for the [account management](https://docs.stripe.com/connect/supported-embedded-components/account-management/) embedded component. + AccountManagement *AccountSessionComponentsAccountManagementParams `form:"account_management"` + // Configuration for the [account onboarding](https://docs.stripe.com/connect/supported-embedded-components/account-onboarding/) embedded component. + AccountOnboarding *AccountSessionComponentsAccountOnboardingParams `form:"account_onboarding"` + // Configuration for the [balances](https://docs.stripe.com/connect/supported-embedded-components/balances/) embedded component. + Balances *AccountSessionComponentsBalancesParams `form:"balances"` + // Configuration for the [disputes list](https://docs.stripe.com/connect/supported-embedded-components/disputes-list/) embedded component. + DisputesList *AccountSessionComponentsDisputesListParams `form:"disputes_list"` + // Configuration for the [documents](https://docs.stripe.com/connect/supported-embedded-components/documents/) embedded component. + Documents *AccountSessionComponentsDocumentsParams `form:"documents"` + // Configuration for the [financial account](https://docs.stripe.com/connect/supported-embedded-components/financial-account/) embedded component. + FinancialAccount *AccountSessionComponentsFinancialAccountParams `form:"financial_account"` + // Configuration for the [financial account transactions](https://docs.stripe.com/connect/supported-embedded-components/financial-account-transactions/) embedded component. + FinancialAccountTransactions *AccountSessionComponentsFinancialAccountTransactionsParams `form:"financial_account_transactions"` + // Configuration for the [issuing card](https://docs.stripe.com/connect/supported-embedded-components/issuing-card/) embedded component. + IssuingCard *AccountSessionComponentsIssuingCardParams `form:"issuing_card"` + // Configuration for the [issuing cards list](https://docs.stripe.com/connect/supported-embedded-components/issuing-cards-list/) embedded component. + IssuingCardsList *AccountSessionComponentsIssuingCardsListParams `form:"issuing_cards_list"` + // Configuration for the [notification banner](https://docs.stripe.com/connect/supported-embedded-components/notification-banner/) embedded component. + NotificationBanner *AccountSessionComponentsNotificationBannerParams `form:"notification_banner"` + // Configuration for the [payment details](https://docs.stripe.com/connect/supported-embedded-components/payment-details/) embedded component. + PaymentDetails *AccountSessionComponentsPaymentDetailsParams `form:"payment_details"` + // Configuration for the [payment disputes](https://docs.stripe.com/connect/supported-embedded-components/payment-disputes/) embedded component. + PaymentDisputes *AccountSessionComponentsPaymentDisputesParams `form:"payment_disputes"` + // Configuration for the [payments](https://docs.stripe.com/connect/supported-embedded-components/payments/) embedded component. + Payments *AccountSessionComponentsPaymentsParams `form:"payments"` + // Configuration for the [payouts](https://docs.stripe.com/connect/supported-embedded-components/payouts/) embedded component. + Payouts *AccountSessionComponentsPayoutsParams `form:"payouts"` + // Configuration for the [payouts list](https://docs.stripe.com/connect/supported-embedded-components/payouts-list/) embedded component. + PayoutsList *AccountSessionComponentsPayoutsListParams `form:"payouts_list"` + // Configuration for the [tax registrations](https://docs.stripe.com/connect/supported-embedded-components/tax-registrations/) embedded component. + TaxRegistrations *AccountSessionComponentsTaxRegistrationsParams `form:"tax_registrations"` + // Configuration for the [tax settings](https://docs.stripe.com/connect/supported-embedded-components/tax-settings/) embedded component. + TaxSettings *AccountSessionComponentsTaxSettingsParams `form:"tax_settings"` +} + +// Creates a AccountSession object that includes a single-use token that the platform can use on their front-end to grant client-side API access. +type AccountSessionParams struct { + Params `form:"*"` + // The identifier of the account to create an Account Session for. + Account *string `form:"account"` + // Each key of the dictionary represents an embedded component, and each embedded component maps to its configuration (e.g. whether it has been enabled or not). + Components *AccountSessionComponentsParams `form:"components"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *AccountSessionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsAccountManagementFeaturesParams struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication *bool `form:"disable_stripe_user_authentication"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection *bool `form:"external_account_collection"` +} + +// Configuration for the [account management](https://docs.stripe.com/connect/supported-embedded-components/account-management/) embedded component. +type AccountSessionCreateComponentsAccountManagementParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsAccountManagementFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsAccountOnboardingFeaturesParams struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication *bool `form:"disable_stripe_user_authentication"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection *bool `form:"external_account_collection"` +} + +// Configuration for the [account onboarding](https://docs.stripe.com/connect/supported-embedded-components/account-onboarding/) embedded component. +type AccountSessionCreateComponentsAccountOnboardingParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsAccountOnboardingFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsBalancesFeaturesParams struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication *bool `form:"disable_stripe_user_authentication"` + // Whether to allow payout schedule to be changed. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + EditPayoutSchedule *bool `form:"edit_payout_schedule"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection *bool `form:"external_account_collection"` + // Whether to allow creation of instant payouts. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + InstantPayouts *bool `form:"instant_payouts"` + // Whether to allow creation of standard payouts. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + StandardPayouts *bool `form:"standard_payouts"` +} + +// Configuration for the [balances](https://docs.stripe.com/connect/supported-embedded-components/balances/) embedded component. +type AccountSessionCreateComponentsBalancesParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsBalancesFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsDisputesListFeaturesParams struct { + // Whether to allow capturing and cancelling payment intents. This is `true` by default. + CapturePayments *bool `form:"capture_payments"` + // Whether connected accounts can manage destination charges that are created on behalf of them. This is `false` by default. + DestinationOnBehalfOfChargeManagement *bool `form:"destination_on_behalf_of_charge_management"` + // Whether responding to disputes is enabled, including submitting evidence and accepting disputes. This is `true` by default. + DisputeManagement *bool `form:"dispute_management"` + // Whether sending refunds is enabled. This is `true` by default. + RefundManagement *bool `form:"refund_management"` +} + +// Configuration for the [disputes list](https://docs.stripe.com/connect/supported-embedded-components/disputes-list/) embedded component. +type AccountSessionCreateComponentsDisputesListParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsDisputesListFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsDocumentsFeaturesParams struct{} + +// Configuration for the [documents](https://docs.stripe.com/connect/supported-embedded-components/documents/) embedded component. +type AccountSessionCreateComponentsDocumentsParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsDocumentsFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsFinancialAccountFeaturesParams struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication *bool `form:"disable_stripe_user_authentication"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection *bool `form:"external_account_collection"` + // Whether to allow sending money. + SendMoney *bool `form:"send_money"` + // Whether to allow transferring balance. + TransferBalance *bool `form:"transfer_balance"` +} + +// Configuration for the [financial account](https://docs.stripe.com/connect/supported-embedded-components/financial-account/) embedded component. +type AccountSessionCreateComponentsFinancialAccountParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsFinancialAccountFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsFinancialAccountTransactionsFeaturesParams struct { + // Whether to allow card spend dispute management features. + CardSpendDisputeManagement *bool `form:"card_spend_dispute_management"` +} + +// Configuration for the [financial account transactions](https://docs.stripe.com/connect/supported-embedded-components/financial-account-transactions/) embedded component. +type AccountSessionCreateComponentsFinancialAccountTransactionsParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsFinancialAccountTransactionsFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsIssuingCardFeaturesParams struct { + // Whether to allow cardholder management features. + CardholderManagement *bool `form:"cardholder_management"` + // Whether to allow card management features. + CardManagement *bool `form:"card_management"` + // Whether to allow card spend dispute management features. + CardSpendDisputeManagement *bool `form:"card_spend_dispute_management"` + // Whether to allow spend control management features. + SpendControlManagement *bool `form:"spend_control_management"` +} + +// Configuration for the [issuing card](https://docs.stripe.com/connect/supported-embedded-components/issuing-card/) embedded component. +type AccountSessionCreateComponentsIssuingCardParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsIssuingCardFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsIssuingCardsListFeaturesParams struct { + // Whether to allow cardholder management features. + CardholderManagement *bool `form:"cardholder_management"` + // Whether to allow card management features. + CardManagement *bool `form:"card_management"` + // Whether to allow card spend dispute management features. + CardSpendDisputeManagement *bool `form:"card_spend_dispute_management"` + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication *bool `form:"disable_stripe_user_authentication"` + // Whether to allow spend control management features. + SpendControlManagement *bool `form:"spend_control_management"` +} + +// Configuration for the [issuing cards list](https://docs.stripe.com/connect/supported-embedded-components/issuing-cards-list/) embedded component. +type AccountSessionCreateComponentsIssuingCardsListParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsIssuingCardsListFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsNotificationBannerFeaturesParams struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication *bool `form:"disable_stripe_user_authentication"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection *bool `form:"external_account_collection"` +} + +// Configuration for the [notification banner](https://docs.stripe.com/connect/supported-embedded-components/notification-banner/) embedded component. +type AccountSessionCreateComponentsNotificationBannerParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsNotificationBannerFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsPaymentDetailsFeaturesParams struct { + // Whether to allow capturing and cancelling payment intents. This is `true` by default. + CapturePayments *bool `form:"capture_payments"` + // Whether connected accounts can manage destination charges that are created on behalf of them. This is `false` by default. + DestinationOnBehalfOfChargeManagement *bool `form:"destination_on_behalf_of_charge_management"` + // Whether responding to disputes is enabled, including submitting evidence and accepting disputes. This is `true` by default. + DisputeManagement *bool `form:"dispute_management"` + // Whether sending refunds is enabled. This is `true` by default. + RefundManagement *bool `form:"refund_management"` +} + +// Configuration for the [payment details](https://docs.stripe.com/connect/supported-embedded-components/payment-details/) embedded component. +type AccountSessionCreateComponentsPaymentDetailsParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsPaymentDetailsFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsPaymentDisputesFeaturesParams struct { + // Whether connected accounts can manage destination charges that are created on behalf of them. This is `false` by default. + DestinationOnBehalfOfChargeManagement *bool `form:"destination_on_behalf_of_charge_management"` + // Whether responding to disputes is enabled, including submitting evidence and accepting disputes. This is `true` by default. + DisputeManagement *bool `form:"dispute_management"` + // Whether sending refunds is enabled. This is `true` by default. + RefundManagement *bool `form:"refund_management"` +} + +// Configuration for the [payment disputes](https://docs.stripe.com/connect/supported-embedded-components/payment-disputes/) embedded component. +type AccountSessionCreateComponentsPaymentDisputesParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsPaymentDisputesFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsPaymentsFeaturesParams struct { + // Whether to allow capturing and cancelling payment intents. This is `true` by default. + CapturePayments *bool `form:"capture_payments"` + // Whether connected accounts can manage destination charges that are created on behalf of them. This is `false` by default. + DestinationOnBehalfOfChargeManagement *bool `form:"destination_on_behalf_of_charge_management"` + // Whether responding to disputes is enabled, including submitting evidence and accepting disputes. This is `true` by default. + DisputeManagement *bool `form:"dispute_management"` + // Whether sending refunds is enabled. This is `true` by default. + RefundManagement *bool `form:"refund_management"` +} + +// Configuration for the [payments](https://docs.stripe.com/connect/supported-embedded-components/payments/) embedded component. +type AccountSessionCreateComponentsPaymentsParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsPaymentsFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsPayoutsFeaturesParams struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication *bool `form:"disable_stripe_user_authentication"` + // Whether to allow payout schedule to be changed. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + EditPayoutSchedule *bool `form:"edit_payout_schedule"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection *bool `form:"external_account_collection"` + // Whether to allow creation of instant payouts. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + InstantPayouts *bool `form:"instant_payouts"` + // Whether to allow creation of standard payouts. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + StandardPayouts *bool `form:"standard_payouts"` +} + +// Configuration for the [payouts](https://docs.stripe.com/connect/supported-embedded-components/payouts/) embedded component. +type AccountSessionCreateComponentsPayoutsParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsPayoutsFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsPayoutsListFeaturesParams struct{} + +// Configuration for the [payouts list](https://docs.stripe.com/connect/supported-embedded-components/payouts-list/) embedded component. +type AccountSessionCreateComponentsPayoutsListParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsPayoutsListFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsTaxRegistrationsFeaturesParams struct{} + +// Configuration for the [tax registrations](https://docs.stripe.com/connect/supported-embedded-components/tax-registrations/) embedded component. +type AccountSessionCreateComponentsTaxRegistrationsParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsTaxRegistrationsFeaturesParams `form:"features"` +} + +// The list of features enabled in the embedded component. +type AccountSessionCreateComponentsTaxSettingsFeaturesParams struct{} + +// Configuration for the [tax settings](https://docs.stripe.com/connect/supported-embedded-components/tax-settings/) embedded component. +type AccountSessionCreateComponentsTaxSettingsParams struct { + // Whether the embedded component is enabled. + Enabled *bool `form:"enabled"` + // The list of features enabled in the embedded component. + Features *AccountSessionCreateComponentsTaxSettingsFeaturesParams `form:"features"` +} + +// Each key of the dictionary represents an embedded component, and each embedded component maps to its configuration (e.g. whether it has been enabled or not). +type AccountSessionCreateComponentsParams struct { + // Configuration for the [account management](https://docs.stripe.com/connect/supported-embedded-components/account-management/) embedded component. + AccountManagement *AccountSessionCreateComponentsAccountManagementParams `form:"account_management"` + // Configuration for the [account onboarding](https://docs.stripe.com/connect/supported-embedded-components/account-onboarding/) embedded component. + AccountOnboarding *AccountSessionCreateComponentsAccountOnboardingParams `form:"account_onboarding"` + // Configuration for the [balances](https://docs.stripe.com/connect/supported-embedded-components/balances/) embedded component. + Balances *AccountSessionCreateComponentsBalancesParams `form:"balances"` + // Configuration for the [disputes list](https://docs.stripe.com/connect/supported-embedded-components/disputes-list/) embedded component. + DisputesList *AccountSessionCreateComponentsDisputesListParams `form:"disputes_list"` + // Configuration for the [documents](https://docs.stripe.com/connect/supported-embedded-components/documents/) embedded component. + Documents *AccountSessionCreateComponentsDocumentsParams `form:"documents"` + // Configuration for the [financial account](https://docs.stripe.com/connect/supported-embedded-components/financial-account/) embedded component. + FinancialAccount *AccountSessionCreateComponentsFinancialAccountParams `form:"financial_account"` + // Configuration for the [financial account transactions](https://docs.stripe.com/connect/supported-embedded-components/financial-account-transactions/) embedded component. + FinancialAccountTransactions *AccountSessionCreateComponentsFinancialAccountTransactionsParams `form:"financial_account_transactions"` + // Configuration for the [issuing card](https://docs.stripe.com/connect/supported-embedded-components/issuing-card/) embedded component. + IssuingCard *AccountSessionCreateComponentsIssuingCardParams `form:"issuing_card"` + // Configuration for the [issuing cards list](https://docs.stripe.com/connect/supported-embedded-components/issuing-cards-list/) embedded component. + IssuingCardsList *AccountSessionCreateComponentsIssuingCardsListParams `form:"issuing_cards_list"` + // Configuration for the [notification banner](https://docs.stripe.com/connect/supported-embedded-components/notification-banner/) embedded component. + NotificationBanner *AccountSessionCreateComponentsNotificationBannerParams `form:"notification_banner"` + // Configuration for the [payment details](https://docs.stripe.com/connect/supported-embedded-components/payment-details/) embedded component. + PaymentDetails *AccountSessionCreateComponentsPaymentDetailsParams `form:"payment_details"` + // Configuration for the [payment disputes](https://docs.stripe.com/connect/supported-embedded-components/payment-disputes/) embedded component. + PaymentDisputes *AccountSessionCreateComponentsPaymentDisputesParams `form:"payment_disputes"` + // Configuration for the [payments](https://docs.stripe.com/connect/supported-embedded-components/payments/) embedded component. + Payments *AccountSessionCreateComponentsPaymentsParams `form:"payments"` + // Configuration for the [payouts](https://docs.stripe.com/connect/supported-embedded-components/payouts/) embedded component. + Payouts *AccountSessionCreateComponentsPayoutsParams `form:"payouts"` + // Configuration for the [payouts list](https://docs.stripe.com/connect/supported-embedded-components/payouts-list/) embedded component. + PayoutsList *AccountSessionCreateComponentsPayoutsListParams `form:"payouts_list"` + // Configuration for the [tax registrations](https://docs.stripe.com/connect/supported-embedded-components/tax-registrations/) embedded component. + TaxRegistrations *AccountSessionCreateComponentsTaxRegistrationsParams `form:"tax_registrations"` + // Configuration for the [tax settings](https://docs.stripe.com/connect/supported-embedded-components/tax-settings/) embedded component. + TaxSettings *AccountSessionCreateComponentsTaxSettingsParams `form:"tax_settings"` +} + +// Creates a AccountSession object that includes a single-use token that the platform can use on their front-end to grant client-side API access. +type AccountSessionCreateParams struct { + Params `form:"*"` + // The identifier of the account to create an Account Session for. + Account *string `form:"account"` + // Each key of the dictionary represents an embedded component, and each embedded component maps to its configuration (e.g. whether it has been enabled or not). + Components *AccountSessionCreateComponentsParams `form:"components"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *AccountSessionCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type AccountSessionComponentsAccountManagementFeatures struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication bool `json:"disable_stripe_user_authentication"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection bool `json:"external_account_collection"` +} +type AccountSessionComponentsAccountManagement struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsAccountManagementFeatures `json:"features"` +} +type AccountSessionComponentsAccountOnboardingFeatures struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication bool `json:"disable_stripe_user_authentication"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection bool `json:"external_account_collection"` +} +type AccountSessionComponentsAccountOnboarding struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsAccountOnboardingFeatures `json:"features"` +} +type AccountSessionComponentsBalancesFeatures struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication bool `json:"disable_stripe_user_authentication"` + // Whether to allow payout schedule to be changed. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + EditPayoutSchedule bool `json:"edit_payout_schedule"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection bool `json:"external_account_collection"` + // Whether to allow creation of instant payouts. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + InstantPayouts bool `json:"instant_payouts"` + // Whether to allow creation of standard payouts. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + StandardPayouts bool `json:"standard_payouts"` +} +type AccountSessionComponentsBalances struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsBalancesFeatures `json:"features"` +} +type AccountSessionComponentsDisputesListFeatures struct { + // Whether to allow capturing and cancelling payment intents. This is `true` by default. + CapturePayments bool `json:"capture_payments"` + // Whether connected accounts can manage destination charges that are created on behalf of them. This is `false` by default. + DestinationOnBehalfOfChargeManagement bool `json:"destination_on_behalf_of_charge_management"` + // Whether responding to disputes is enabled, including submitting evidence and accepting disputes. This is `true` by default. + DisputeManagement bool `json:"dispute_management"` + // Whether sending refunds is enabled. This is `true` by default. + RefundManagement bool `json:"refund_management"` +} +type AccountSessionComponentsDisputesList struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsDisputesListFeatures `json:"features"` +} +type AccountSessionComponentsDocumentsFeatures struct{} +type AccountSessionComponentsDocuments struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsDocumentsFeatures `json:"features"` +} +type AccountSessionComponentsFinancialAccountFeatures struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication bool `json:"disable_stripe_user_authentication"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection bool `json:"external_account_collection"` + // Whether to allow sending money. + SendMoney bool `json:"send_money"` + // Whether to allow transferring balance. + TransferBalance bool `json:"transfer_balance"` +} +type AccountSessionComponentsFinancialAccount struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsFinancialAccountFeatures `json:"features"` +} +type AccountSessionComponentsFinancialAccountTransactionsFeatures struct { + // Whether to allow card spend dispute management features. + CardSpendDisputeManagement bool `json:"card_spend_dispute_management"` +} +type AccountSessionComponentsFinancialAccountTransactions struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsFinancialAccountTransactionsFeatures `json:"features"` +} +type AccountSessionComponentsIssuingCardFeatures struct { + // Whether to allow cardholder management features. + CardholderManagement bool `json:"cardholder_management"` + // Whether to allow card management features. + CardManagement bool `json:"card_management"` + // Whether to allow card spend dispute management features. + CardSpendDisputeManagement bool `json:"card_spend_dispute_management"` + // Whether to allow spend control management features. + SpendControlManagement bool `json:"spend_control_management"` +} +type AccountSessionComponentsIssuingCard struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsIssuingCardFeatures `json:"features"` +} +type AccountSessionComponentsIssuingCardsListFeatures struct { + // Whether to allow cardholder management features. + CardholderManagement bool `json:"cardholder_management"` + // Whether to allow card management features. + CardManagement bool `json:"card_management"` + // Whether to allow card spend dispute management features. + CardSpendDisputeManagement bool `json:"card_spend_dispute_management"` + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication bool `json:"disable_stripe_user_authentication"` + // Whether to allow spend control management features. + SpendControlManagement bool `json:"spend_control_management"` +} +type AccountSessionComponentsIssuingCardsList struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsIssuingCardsListFeatures `json:"features"` +} +type AccountSessionComponentsNotificationBannerFeatures struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication bool `json:"disable_stripe_user_authentication"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection bool `json:"external_account_collection"` +} +type AccountSessionComponentsNotificationBanner struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsNotificationBannerFeatures `json:"features"` +} +type AccountSessionComponentsPaymentDetailsFeatures struct { + // Whether to allow capturing and cancelling payment intents. This is `true` by default. + CapturePayments bool `json:"capture_payments"` + // Whether connected accounts can manage destination charges that are created on behalf of them. This is `false` by default. + DestinationOnBehalfOfChargeManagement bool `json:"destination_on_behalf_of_charge_management"` + // Whether responding to disputes is enabled, including submitting evidence and accepting disputes. This is `true` by default. + DisputeManagement bool `json:"dispute_management"` + // Whether sending refunds is enabled. This is `true` by default. + RefundManagement bool `json:"refund_management"` +} +type AccountSessionComponentsPaymentDetails struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsPaymentDetailsFeatures `json:"features"` +} +type AccountSessionComponentsPaymentDisputesFeatures struct { + // Whether connected accounts can manage destination charges that are created on behalf of them. This is `false` by default. + DestinationOnBehalfOfChargeManagement bool `json:"destination_on_behalf_of_charge_management"` + // Whether responding to disputes is enabled, including submitting evidence and accepting disputes. This is `true` by default. + DisputeManagement bool `json:"dispute_management"` + // Whether sending refunds is enabled. This is `true` by default. + RefundManagement bool `json:"refund_management"` +} +type AccountSessionComponentsPaymentDisputes struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsPaymentDisputesFeatures `json:"features"` +} +type AccountSessionComponentsPaymentsFeatures struct { + // Whether to allow capturing and cancelling payment intents. This is `true` by default. + CapturePayments bool `json:"capture_payments"` + // Whether connected accounts can manage destination charges that are created on behalf of them. This is `false` by default. + DestinationOnBehalfOfChargeManagement bool `json:"destination_on_behalf_of_charge_management"` + // Whether responding to disputes is enabled, including submitting evidence and accepting disputes. This is `true` by default. + DisputeManagement bool `json:"dispute_management"` + // Whether sending refunds is enabled. This is `true` by default. + RefundManagement bool `json:"refund_management"` +} +type AccountSessionComponentsPayments struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsPaymentsFeatures `json:"features"` +} +type AccountSessionComponentsPayoutsFeatures struct { + // Whether Stripe user authentication is disabled. This value can only be `true` for accounts where `controller.requirement_collection` is `application` for the account. The default value is the opposite of the `external_account_collection` value. For example, if you don't set `external_account_collection`, it defaults to `true` and `disable_stripe_user_authentication` defaults to `false`. + DisableStripeUserAuthentication bool `json:"disable_stripe_user_authentication"` + // Whether to allow payout schedule to be changed. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + EditPayoutSchedule bool `json:"edit_payout_schedule"` + // Whether external account collection is enabled. This feature can only be `false` for accounts where you're responsible for collecting updated information when requirements are due or change, like Custom accounts. The default value for this feature is `true`. + ExternalAccountCollection bool `json:"external_account_collection"` + // Whether to allow creation of instant payouts. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + InstantPayouts bool `json:"instant_payouts"` + // Whether to allow creation of standard payouts. Defaults to `true` when `controller.losses.payments` is set to `stripe` for the account, otherwise `false`. + StandardPayouts bool `json:"standard_payouts"` +} +type AccountSessionComponentsPayouts struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsPayoutsFeatures `json:"features"` +} +type AccountSessionComponentsPayoutsListFeatures struct{} +type AccountSessionComponentsPayoutsList struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsPayoutsListFeatures `json:"features"` +} +type AccountSessionComponentsTaxRegistrationsFeatures struct{} +type AccountSessionComponentsTaxRegistrations struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsTaxRegistrationsFeatures `json:"features"` +} +type AccountSessionComponentsTaxSettingsFeatures struct{} +type AccountSessionComponentsTaxSettings struct { + // Whether the embedded component is enabled. + Enabled bool `json:"enabled"` + Features *AccountSessionComponentsTaxSettingsFeatures `json:"features"` +} +type AccountSessionComponents struct { + AccountManagement *AccountSessionComponentsAccountManagement `json:"account_management"` + AccountOnboarding *AccountSessionComponentsAccountOnboarding `json:"account_onboarding"` + Balances *AccountSessionComponentsBalances `json:"balances"` + DisputesList *AccountSessionComponentsDisputesList `json:"disputes_list"` + Documents *AccountSessionComponentsDocuments `json:"documents"` + FinancialAccount *AccountSessionComponentsFinancialAccount `json:"financial_account"` + FinancialAccountTransactions *AccountSessionComponentsFinancialAccountTransactions `json:"financial_account_transactions"` + IssuingCard *AccountSessionComponentsIssuingCard `json:"issuing_card"` + IssuingCardsList *AccountSessionComponentsIssuingCardsList `json:"issuing_cards_list"` + NotificationBanner *AccountSessionComponentsNotificationBanner `json:"notification_banner"` + PaymentDetails *AccountSessionComponentsPaymentDetails `json:"payment_details"` + PaymentDisputes *AccountSessionComponentsPaymentDisputes `json:"payment_disputes"` + Payments *AccountSessionComponentsPayments `json:"payments"` + Payouts *AccountSessionComponentsPayouts `json:"payouts"` + PayoutsList *AccountSessionComponentsPayoutsList `json:"payouts_list"` + TaxRegistrations *AccountSessionComponentsTaxRegistrations `json:"tax_registrations"` + TaxSettings *AccountSessionComponentsTaxSettings `json:"tax_settings"` +} + +// An AccountSession allows a Connect platform to grant access to a connected account in Connect embedded components. +// +// We recommend that you create an AccountSession each time you need to display an embedded component +// to your user. Do not save AccountSessions to your database as they expire relatively +// quickly, and cannot be used more than once. +// +// Related guide: [Connect embedded components](https://stripe.com/docs/connect/get-started-connect-embedded-components) +type AccountSession struct { + APIResource + // The ID of the account the AccountSession was created for + Account string `json:"account"` + // The client secret of this AccountSession. Used on the client to set up secure access to the given `account`. + // + // The client secret can be used to provide access to `account` from your frontend. It should not be stored, logged, or exposed to anyone other than the connected account. Make sure that you have TLS enabled on any page that includes the client secret. + // + // Refer to our docs to [setup Connect embedded components](https://stripe.com/docs/connect/get-started-connect-embedded-components) and learn about how `client_secret` should be handled. + ClientSecret string `json:"client_secret"` + Components *AccountSessionComponents `json:"components"` + // The timestamp at which this AccountSession will expire. + ExpiresAt int64 `json:"expires_at"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/accountsession_service.go b/vendor/github.com/stripe/stripe-go/v82/accountsession_service.go new file mode 100644 index 00000000..e892ae21 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/accountsession_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1AccountSessionService is used to invoke /v1/account_sessions APIs. +type v1AccountSessionService struct { + B Backend + Key string +} + +// Creates a AccountSession object that includes a single-use token that the platform can use on their front-end to grant client-side API access. +func (c v1AccountSessionService) Create(ctx context.Context, params *AccountSessionCreateParams) (*AccountSession, error) { + if params == nil { + params = &AccountSessionCreateParams{} + } + params.Context = ctx + accountsession := &AccountSession{} + err := c.B.Call( + http.MethodPost, "/v1/account_sessions", c.Key, params, accountsession) + return accountsession, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/address.go b/vendor/github.com/stripe/stripe-go/v82/address.go new file mode 100644 index 00000000..44c62f7f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/address.go @@ -0,0 +1,39 @@ +package stripe + +// AddressParams describes the common parameters for an Address. +type AddressParams struct { + City *string `form:"city"` + Country *string `form:"country"` + Line1 *string `form:"line1"` + Line2 *string `form:"line2"` + PostalCode *string `form:"postal_code"` + State *string `form:"state"` +} + +// Address describes common properties for an Address hash. +type Address struct { + City string `json:"city"` + Country string `json:"country"` + Line1 string `json:"line1"` + Line2 string `json:"line2"` + PostalCode string `json:"postal_code"` + State string `json:"state"` +} + +// ShippingDetailsParams is the structure containing shipping information as parameters +type ShippingDetailsParams struct { + Address *AddressParams `form:"address"` + Carrier *string `form:"carrier"` + Name *string `form:"name"` + Phone *string `form:"phone"` + TrackingNumber *string `form:"tracking_number"` +} + +// ShippingDetails is the structure containing shipping information. +type ShippingDetails struct { + Address *Address `json:"address"` + Carrier string `json:"carrier"` + Name string `json:"name"` + Phone string `json:"phone"` + TrackingNumber string `json:"tracking_number"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/amount.go b/vendor/github.com/stripe/stripe-go/v82/amount.go new file mode 100644 index 00000000..1a59832f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/amount.go @@ -0,0 +1,7 @@ +package stripe + +// Amount describes a monetary amount in a specific currency in minor units. +type Amount struct { + Currency Currency `form:"currency" json:"currency"` + Value int64 `form:"value" json:"value"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/api_version.go b/vendor/github.com/stripe/stripe-go/v82/api_version.go new file mode 100644 index 00000000..40b8edde --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/api_version.go @@ -0,0 +1,12 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +const ( + APIVersion string = "2025-06-30.basil" + APIMajorVersion string = "basil" +) diff --git a/vendor/github.com/stripe/stripe-go/v82/applepaydomain.go b/vendor/github.com/stripe/stripe-go/v82/applepaydomain.go new file mode 100644 index 00000000..e2daf048 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/applepaydomain.go @@ -0,0 +1,84 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Delete an apple pay domain. +type ApplePayDomainParams struct { + Params `form:"*"` + DomainName *string `form:"domain_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ApplePayDomainParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// List apple pay domains. +type ApplePayDomainListParams struct { + ListParams `form:"*"` + DomainName *string `form:"domain_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ApplePayDomainListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Delete an apple pay domain. +type ApplePayDomainDeleteParams struct { + Params `form:"*"` +} + +// Retrieve an apple pay domain. +type ApplePayDomainRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ApplePayDomainRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Create an apple pay domain. +type ApplePayDomainCreateParams struct { + Params `form:"*"` + DomainName *string `form:"domain_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ApplePayDomainCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type ApplePayDomain struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + Deleted bool `json:"deleted"` + DomainName string `json:"domain_name"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} + +// ApplePayDomainList is a list of ApplePayDomains as retrieved from a list endpoint. +type ApplePayDomainList struct { + APIResource + ListMeta + Data []*ApplePayDomain `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/applepaydomain_service.go b/vendor/github.com/stripe/stripe-go/v82/applepaydomain_service.go new file mode 100644 index 00000000..32e6b6bc --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/applepaydomain_service.go @@ -0,0 +1,73 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1ApplePayDomainService is used to invoke /v1/apple_pay/domains APIs. +type v1ApplePayDomainService struct { + B Backend + Key string +} + +// Create an apple pay domain. +func (c v1ApplePayDomainService) Create(ctx context.Context, params *ApplePayDomainCreateParams) (*ApplePayDomain, error) { + if params == nil { + params = &ApplePayDomainCreateParams{} + } + params.Context = ctx + applepaydomain := &ApplePayDomain{} + err := c.B.Call( + http.MethodPost, "/v1/apple_pay/domains", c.Key, params, applepaydomain) + return applepaydomain, err +} + +// Retrieve an apple pay domain. +func (c v1ApplePayDomainService) Retrieve(ctx context.Context, id string, params *ApplePayDomainRetrieveParams) (*ApplePayDomain, error) { + if params == nil { + params = &ApplePayDomainRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/apple_pay/domains/%s", id) + applepaydomain := &ApplePayDomain{} + err := c.B.Call(http.MethodGet, path, c.Key, params, applepaydomain) + return applepaydomain, err +} + +// Delete an apple pay domain. +func (c v1ApplePayDomainService) Delete(ctx context.Context, id string, params *ApplePayDomainDeleteParams) (*ApplePayDomain, error) { + if params == nil { + params = &ApplePayDomainDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/apple_pay/domains/%s", id) + applepaydomain := &ApplePayDomain{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, applepaydomain) + return applepaydomain, err +} + +// List apple pay domains. +func (c v1ApplePayDomainService) List(ctx context.Context, listParams *ApplePayDomainListParams) Seq2[*ApplePayDomain, error] { + if listParams == nil { + listParams = &ApplePayDomainListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*ApplePayDomain, ListContainer, error) { + list := &ApplePayDomainList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/apple_pay/domains", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/application.go b/vendor/github.com/stripe/stripe-go/v82/application.go new file mode 100644 index 00000000..1ab1abe0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/application.go @@ -0,0 +1,38 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +type Application struct { + Deleted bool `json:"deleted"` + // Unique identifier for the object. + ID string `json:"id"` + // The name of the application. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} + +// UnmarshalJSON handles deserialization of an Application. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (a *Application) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + a.ID = id + return nil + } + + type application Application + var v application + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *a = Application(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/applicationfee.go b/vendor/github.com/stripe/stripe-go/v82/applicationfee.go new file mode 100644 index 00000000..ae2e3e19 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/applicationfee.go @@ -0,0 +1,129 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Type of object that created the application fee. +type ApplicationFeeFeeSourceType string + +// List of values that ApplicationFeeFeeSourceType can take +const ( + ApplicationFeeFeeSourceTypeCharge ApplicationFeeFeeSourceType = "charge" + ApplicationFeeFeeSourceTypePayout ApplicationFeeFeeSourceType = "payout" +) + +// Returns a list of application fees you've previously collected. The application fees are returned in sorted order, with the most recent fees appearing first. +type ApplicationFeeListParams struct { + ListParams `form:"*"` + // Only return application fees for the charge specified by this charge ID. + Charge *string `form:"charge"` + // Only return applications fees that were created during the given date interval. + Created *int64 `form:"created"` + // Only return applications fees that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ApplicationFeeListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an application fee that your account has collected. The same information is returned when refunding the application fee. +type ApplicationFeeParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ApplicationFeeParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an application fee that your account has collected. The same information is returned when refunding the application fee. +type ApplicationFeeRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ApplicationFeeRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Polymorphic source of the application fee. Includes the ID of the object the application fee was created from. +type ApplicationFeeFeeSource struct { + // Charge ID that created this application fee. + Charge string `json:"charge"` + // Payout ID that created this application fee. + Payout string `json:"payout"` + // Type of object that created the application fee. + Type ApplicationFeeFeeSourceType `json:"type"` +} +type ApplicationFee struct { + APIResource + // ID of the Stripe account this fee was taken from. + Account *Account `json:"account"` + // Amount earned, in cents (or local equivalent). + Amount int64 `json:"amount"` + // Amount in cents (or local equivalent) refunded (can be less than the amount attribute on the fee if a partial refund was issued) + AmountRefunded int64 `json:"amount_refunded"` + // ID of the Connect application that earned the fee. + Application *Application `json:"application"` + // Balance transaction that describes the impact of this collected application fee on your account balance (not including refunds). + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + // ID of the charge that the application fee was taken from. + Charge *Charge `json:"charge"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // Polymorphic source of the application fee. Includes the ID of the object the application fee was created from. + FeeSource *ApplicationFeeFeeSource `json:"fee_source"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // ID of the corresponding charge on the platform account, if this fee was the result of a charge using the `destination` parameter. + OriginatingTransaction *Charge `json:"originating_transaction"` + // Whether the fee has been fully refunded. If the fee is only partially refunded, this attribute will still be false. + Refunded bool `json:"refunded"` + // A list of refunds that have been applied to the fee. + Refunds *FeeRefundList `json:"refunds"` +} + +// ApplicationFeeList is a list of ApplicationFees as retrieved from a list endpoint. +type ApplicationFeeList struct { + APIResource + ListMeta + Data []*ApplicationFee `json:"data"` +} + +// UnmarshalJSON handles deserialization of an ApplicationFee. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (a *ApplicationFee) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + a.ID = id + return nil + } + + type applicationFee ApplicationFee + var v applicationFee + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *a = ApplicationFee(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/applicationfee_service.go b/vendor/github.com/stripe/stripe-go/v82/applicationfee_service.go new file mode 100644 index 00000000..608406b3 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/applicationfee_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1ApplicationFeeService is used to invoke /v1/application_fees APIs. +type v1ApplicationFeeService struct { + B Backend + Key string +} + +// Retrieves the details of an application fee that your account has collected. The same information is returned when refunding the application fee. +func (c v1ApplicationFeeService) Retrieve(ctx context.Context, id string, params *ApplicationFeeRetrieveParams) (*ApplicationFee, error) { + if params == nil { + params = &ApplicationFeeRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/application_fees/%s", id) + applicationfee := &ApplicationFee{} + err := c.B.Call(http.MethodGet, path, c.Key, params, applicationfee) + return applicationfee, err +} + +// Returns a list of application fees you've previously collected. The application fees are returned in sorted order, with the most recent fees appearing first. +func (c v1ApplicationFeeService) List(ctx context.Context, listParams *ApplicationFeeListParams) Seq2[*ApplicationFee, error] { + if listParams == nil { + listParams = &ApplicationFeeListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*ApplicationFee, ListContainer, error) { + list := &ApplicationFeeList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/application_fees", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/apps_secret.go b/vendor/github.com/stripe/stripe-go/v82/apps_secret.go new file mode 100644 index 00000000..c394ec4d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/apps_secret.go @@ -0,0 +1,186 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The secret scope type. +type AppsSecretScopeType string + +// List of values that AppsSecretScopeType can take +const ( + AppsSecretScopeTypeAccount AppsSecretScopeType = "account" + AppsSecretScopeTypeUser AppsSecretScopeType = "user" +) + +// Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user. +type AppsSecretListScopeParams struct { + // The secret scope type. + Type *string `form:"type"` + // The user ID. This field is required if `type` is set to `user`, and should not be provided if `type` is set to `account`. + User *string `form:"user"` +} + +// List all secrets stored on the given scope. +type AppsSecretListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user. + Scope *AppsSecretListScopeParams `form:"scope"` +} + +// AddExpand appends a new field to expand. +func (p *AppsSecretListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user. +type AppsSecretScopeParams struct { + // The secret scope type. + Type *string `form:"type"` + // The user ID. This field is required if `type` is set to `user`, and should not be provided if `type` is set to `account`. + User *string `form:"user"` +} + +// Create or replace a secret in the secret store. +type AppsSecretParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The Unix timestamp for the expiry time of the secret, after which the secret deletes. + ExpiresAt *int64 `form:"expires_at"` + // A name for the secret that's unique within the scope. + Name *string `form:"name"` + // The plaintext secret value to be stored. + Payload *string `form:"payload"` + // Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user. + Scope *AppsSecretScopeParams `form:"scope"` +} + +// AddExpand appends a new field to expand. +func (p *AppsSecretParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user. +type AppsSecretFindScopeParams struct { + // The secret scope type. + Type *string `form:"type"` + // The user ID. This field is required if `type` is set to `user`, and should not be provided if `type` is set to `account`. + User *string `form:"user"` +} + +// Finds a secret in the secret store by name and scope. +type AppsSecretFindParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A name for the secret that's unique within the scope. + Name *string `form:"name"` + // Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user. + Scope *AppsSecretFindScopeParams `form:"scope"` +} + +// AddExpand appends a new field to expand. +func (p *AppsSecretFindParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user. +type AppsSecretDeleteWhereScopeParams struct { + // The secret scope type. + Type *string `form:"type"` + // The user ID. This field is required if `type` is set to `user`, and should not be provided if `type` is set to `account`. + User *string `form:"user"` +} + +// Deletes a secret from the secret store by name and scope. +type AppsSecretDeleteWhereParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A name for the secret that's unique within the scope. + Name *string `form:"name"` + // Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user. + Scope *AppsSecretDeleteWhereScopeParams `form:"scope"` +} + +// AddExpand appends a new field to expand. +func (p *AppsSecretDeleteWhereParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user. +type AppsSecretCreateScopeParams struct { + // The secret scope type. + Type *string `form:"type"` + // The user ID. This field is required if `type` is set to `user`, and should not be provided if `type` is set to `account`. + User *string `form:"user"` +} + +// Create or replace a secret in the secret store. +type AppsSecretCreateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The Unix timestamp for the expiry time of the secret, after which the secret deletes. + ExpiresAt *int64 `form:"expires_at"` + // A name for the secret that's unique within the scope. + Name *string `form:"name"` + // The plaintext secret value to be stored. + Payload *string `form:"payload"` + // Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user. + Scope *AppsSecretCreateScopeParams `form:"scope"` +} + +// AddExpand appends a new field to expand. +func (p *AppsSecretCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type AppsSecretScope struct { + // The secret scope type. + Type AppsSecretScopeType `json:"type"` + // The user ID, if type is set to "user" + User string `json:"user"` +} + +// Secret Store is an API that allows Stripe Apps developers to securely persist secrets for use by UI Extensions and app backends. +// +// The primary resource in Secret Store is a `secret`. Other apps can't view secrets created by an app. Additionally, secrets are scoped to provide further permission control. +// +// All Dashboard users and the app backend share `account` scoped secrets. Use the `account` scope for secrets that don't change per-user, like a third-party API key. +// +// A `user` scoped secret is accessible by the app backend and one specific Dashboard user. Use the `user` scope for per-user secrets like per-user OAuth tokens, where different users might have different permissions. +// +// Related guide: [Store data between page reloads](https://stripe.com/docs/stripe-apps/store-auth-data-custom-objects) +type AppsSecret struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // If true, indicates that this secret has been deleted + Deleted bool `json:"deleted"` + // The Unix timestamp for the expiry time of the secret, after which the secret deletes. + ExpiresAt int64 `json:"expires_at"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // A name for the secret that's unique within the scope. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The plaintext secret value to be stored. + Payload string `json:"payload"` + Scope *AppsSecretScope `json:"scope"` +} + +// AppsSecretList is a list of Secrets as retrieved from a list endpoint. +type AppsSecretList struct { + APIResource + ListMeta + Data []*AppsSecret `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/apps_secret_service.go b/vendor/github.com/stripe/stripe-go/v82/apps_secret_service.go new file mode 100644 index 00000000..999c9529 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/apps_secret_service.go @@ -0,0 +1,72 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1AppsSecretService is used to invoke /v1/apps/secrets APIs. +type v1AppsSecretService struct { + B Backend + Key string +} + +// Create or replace a secret in the secret store. +func (c v1AppsSecretService) Create(ctx context.Context, params *AppsSecretCreateParams) (*AppsSecret, error) { + if params == nil { + params = &AppsSecretCreateParams{} + } + params.Context = ctx + secret := &AppsSecret{} + err := c.B.Call(http.MethodPost, "/v1/apps/secrets", c.Key, params, secret) + return secret, err +} + +// Deletes a secret from the secret store by name and scope. +func (c v1AppsSecretService) DeleteWhere(ctx context.Context, params *AppsSecretDeleteWhereParams) (*AppsSecret, error) { + if params == nil { + params = &AppsSecretDeleteWhereParams{} + } + params.Context = ctx + secret := &AppsSecret{} + err := c.B.Call( + http.MethodPost, "/v1/apps/secrets/delete", c.Key, params, secret) + return secret, err +} + +// Finds a secret in the secret store by name and scope. +func (c v1AppsSecretService) Find(ctx context.Context, params *AppsSecretFindParams) (*AppsSecret, error) { + if params == nil { + params = &AppsSecretFindParams{} + } + params.Context = ctx + secret := &AppsSecret{} + err := c.B.Call( + http.MethodGet, "/v1/apps/secrets/find", c.Key, params, secret) + return secret, err +} + +// List all secrets stored on the given scope. +func (c v1AppsSecretService) List(ctx context.Context, listParams *AppsSecretListParams) Seq2[*AppsSecret, error] { + if listParams == nil { + listParams = &AppsSecretListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*AppsSecret, ListContainer, error) { + list := &AppsSecretList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/apps/secrets", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/balance.go b/vendor/github.com/stripe/stripe-go/v82/balance.go new file mode 100644 index 00000000..6847b9cd --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/balance.go @@ -0,0 +1,146 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// BalanceSourceType is the list of allowed values for the balance amount's source_type field keys. +type BalanceSourceType string + +// List of values that BalanceSourceType can take. +const ( + BalanceSourceTypeBankAccount BalanceSourceType = "bank_account" + BalanceSourceTypeCard BalanceSourceType = "card" + BalanceSourceTypeFPX BalanceSourceType = "fpx" +) + +// Retrieves the current account balance, based on the authentication that was used to make the request. +// +// For a sample request, see [Accounting for negative balances](https://docs.stripe.com/docs/connect/account-balances#accounting-for-negative-balances). +type BalanceParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BalanceParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the current account balance, based on the authentication that was used to make the request. +// +// For a sample request, see [Accounting for negative balances](https://docs.stripe.com/docs/connect/account-balances#accounting-for-negative-balances). +type BalanceRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BalanceRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Available funds that you can transfer or pay out automatically by Stripe or explicitly through the [Transfers API](https://stripe.com/docs/api#transfers) or [Payouts API](https://stripe.com/docs/api#payouts). You can find the available balance for each currency and payment type in the `source_types` property. +type BalanceAmount struct { + // Balance amount. + Amount int64 `json:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // Breakdown of balance by destination. + NetAvailable []*BalanceInstantAvailableNetAvailable `json:"net_available"` + SourceTypes map[BalanceSourceType]int64 `json:"source_types"` +} +type BalanceInstantAvailableNetAvailableSourceTypes struct { + // Amount coming from [legacy US ACH payments](https://docs.stripe.com/ach-deprecated). + BankAccount int64 `json:"bank_account"` + // Amount coming from most payment methods, including cards as well as [non-legacy bank debits](https://docs.stripe.com/payments/bank-debits). + Card int64 `json:"card"` + // Amount coming from [FPX](https://docs.stripe.com/payments/fpx), a Malaysian payment method. + FPX int64 `json:"fpx"` +} + +// Breakdown of balance by destination. +type BalanceInstantAvailableNetAvailable struct { + // Net balance amount, subtracting fees from platform-set pricing. + Amount int64 `json:"amount"` + // ID of the external account for this net balance (not expandable). + Destination string `json:"destination"` + SourceTypes *BalanceInstantAvailableNetAvailableSourceTypes `json:"source_types"` +} +type BalanceIssuing struct { + // Funds that are available for use. + Available []*BalanceAmount `json:"available"` +} +type BalanceRefundAndDisputePrefundingAvailableSourceTypes struct { + // Amount coming from [legacy US ACH payments](https://docs.stripe.com/ach-deprecated). + BankAccount int64 `json:"bank_account"` + // Amount coming from most payment methods, including cards as well as [non-legacy bank debits](https://docs.stripe.com/payments/bank-debits). + Card int64 `json:"card"` + // Amount coming from [FPX](https://docs.stripe.com/payments/fpx), a Malaysian payment method. + FPX int64 `json:"fpx"` +} + +// Funds that are available for use. +type BalanceRefundAndDisputePrefundingAvailable struct { + // Balance amount. + Amount int64 `json:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + SourceTypes *BalanceRefundAndDisputePrefundingAvailableSourceTypes `json:"source_types"` +} +type BalanceRefundAndDisputePrefundingPendingSourceTypes struct { + // Amount coming from [legacy US ACH payments](https://docs.stripe.com/ach-deprecated). + BankAccount int64 `json:"bank_account"` + // Amount coming from most payment methods, including cards as well as [non-legacy bank debits](https://docs.stripe.com/payments/bank-debits). + Card int64 `json:"card"` + // Amount coming from [FPX](https://docs.stripe.com/payments/fpx), a Malaysian payment method. + FPX int64 `json:"fpx"` +} + +// Funds that are pending +type BalanceRefundAndDisputePrefundingPending struct { + // Balance amount. + Amount int64 `json:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + SourceTypes *BalanceRefundAndDisputePrefundingPendingSourceTypes `json:"source_types"` +} +type BalanceRefundAndDisputePrefunding struct { + // Funds that are available for use. + Available []*BalanceRefundAndDisputePrefundingAvailable `json:"available"` + // Funds that are pending + Pending []*BalanceRefundAndDisputePrefundingPending `json:"pending"` +} + +// This is an object representing your Stripe balance. You can retrieve it to see +// the balance currently on your Stripe account. +// +// You can also retrieve the balance history, which contains a list of +// [transactions](https://stripe.com/docs/reporting/balance-transaction-types) that contributed to the balance +// (charges, payouts, and so forth). +// +// The available and pending amounts for each currency are broken down further by +// payment source types. +// +// Related guide: [Understanding Connect account balances](https://stripe.com/docs/connect/account-balances) +type Balance struct { + APIResource + // Available funds that you can transfer or pay out automatically by Stripe or explicitly through the [Transfers API](https://stripe.com/docs/api#transfers) or [Payouts API](https://stripe.com/docs/api#payouts). You can find the available balance for each currency and payment type in the `source_types` property. + Available []*BalanceAmount `json:"available"` + // Funds held due to negative balances on connected accounts where [account.controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. You can find the connect reserve balance for each currency and payment type in the `source_types` property. + ConnectReserved []*BalanceAmount `json:"connect_reserved"` + // Funds that you can pay out using Instant Payouts. + InstantAvailable []*BalanceAmount `json:"instant_available"` + Issuing *BalanceIssuing `json:"issuing"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Funds that aren't available in the balance yet. You can find the pending balance for each currency and each payment type in the `source_types` property. + Pending []*BalanceAmount `json:"pending"` + RefundAndDisputePrefunding *BalanceRefundAndDisputePrefunding `json:"refund_and_dispute_prefunding"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/balance_service.go b/vendor/github.com/stripe/stripe-go/v82/balance_service.go new file mode 100644 index 00000000..dfc0c0bc --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/balance_service.go @@ -0,0 +1,31 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1BalanceService is used to invoke /v1/balance APIs. +type v1BalanceService struct { + B Backend + Key string +} + +// Retrieves the current account balance, based on the authentication that was used to make the request. +// +// For a sample request, see [Accounting for negative balances](https://docs.stripe.com/docs/connect/account-balances#accounting-for-negative-balances). +func (c v1BalanceService) Retrieve(ctx context.Context, params *BalanceRetrieveParams) (*Balance, error) { + if params == nil { + params = &BalanceRetrieveParams{} + } + params.Context = ctx + balance := &Balance{} + err := c.B.Call(http.MethodGet, "/v1/balance", c.Key, params, balance) + return balance, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/balancetransaction.go b/vendor/github.com/stripe/stripe-go/v82/balancetransaction.go new file mode 100644 index 00000000..76fd7cdc --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/balancetransaction.go @@ -0,0 +1,344 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The balance that this transaction impacts. +type BalanceTransactionBalanceType string + +// List of values that BalanceTransactionBalanceType can take +const ( + BalanceTransactionBalanceTypeIssuing BalanceTransactionBalanceType = "issuing" + BalanceTransactionBalanceTypePayments BalanceTransactionBalanceType = "payments" + BalanceTransactionBalanceTypeRefundAndDisputePrefunding BalanceTransactionBalanceType = "refund_and_dispute_prefunding" +) + +// Learn more about how [reporting categories](https://stripe.com/docs/reports/reporting-categories) can help you understand balance transactions from an accounting perspective. +type BalanceTransactionReportingCategory string + +// List of values that BalanceTransactionReportingCategory can take +const ( + BalanceTransactionReportingCategoryAdvance BalanceTransactionReportingCategory = "advance" + BalanceTransactionReportingCategoryAdvanceFunding BalanceTransactionReportingCategory = "advance_funding" + BalanceTransactionReportingCategoryCharge BalanceTransactionReportingCategory = "charge" + BalanceTransactionReportingCategoryChargeFailure BalanceTransactionReportingCategory = "charge_failure" + BalanceTransactionReportingCategoryConnectCollectionTransfer BalanceTransactionReportingCategory = "connect_collection_transfer" + BalanceTransactionReportingCategoryConnectReservedFunds BalanceTransactionReportingCategory = "connect_reserved_funds" + BalanceTransactionReportingCategoryDispute BalanceTransactionReportingCategory = "dispute" + BalanceTransactionReportingCategoryDisputeReversal BalanceTransactionReportingCategory = "dispute_reversal" + BalanceTransactionReportingCategoryFee BalanceTransactionReportingCategory = "fee" + BalanceTransactionReportingCategoryIssuingAuthorizationHold BalanceTransactionReportingCategory = "issuing_authorization_hold" + BalanceTransactionReportingCategoryIssuingAuthorizationRelease BalanceTransactionReportingCategory = "issuing_authorization_release" + BalanceTransactionReportingCategoryIssuingTransaction BalanceTransactionReportingCategory = "issuing_transaction" + BalanceTransactionReportingCategoryOtherAdjustment BalanceTransactionReportingCategory = "other_adjustment" + BalanceTransactionReportingCategoryPartialCaptureReversal BalanceTransactionReportingCategory = "partial_capture_reversal" + BalanceTransactionReportingCategoryPayout BalanceTransactionReportingCategory = "payout" + BalanceTransactionReportingCategoryPayoutReversal BalanceTransactionReportingCategory = "payout_reversal" + BalanceTransactionReportingCategoryPlatformEarning BalanceTransactionReportingCategory = "platform_earning" + BalanceTransactionReportingCategoryPlatformEarningRefund BalanceTransactionReportingCategory = "platform_earning_refund" + BalanceTransactionReportingCategoryRefund BalanceTransactionReportingCategory = "refund" + BalanceTransactionReportingCategoryRefundFailure BalanceTransactionReportingCategory = "refund_failure" + BalanceTransactionReportingCategoryRiskReservedFunds BalanceTransactionReportingCategory = "risk_reserved_funds" + BalanceTransactionReportingCategoryTax BalanceTransactionReportingCategory = "tax" + BalanceTransactionReportingCategoryTopup BalanceTransactionReportingCategory = "topup" + BalanceTransactionReportingCategoryTopupReversal BalanceTransactionReportingCategory = "topup_reversal" + BalanceTransactionReportingCategoryTransfer BalanceTransactionReportingCategory = "transfer" + BalanceTransactionReportingCategoryTransferReversal BalanceTransactionReportingCategory = "transfer_reversal" +) + +type BalanceTransactionSourceType string + +// List of values that BalanceTransactionSourceType can take +const ( + BalanceTransactionSourceTypeApplicationFee BalanceTransactionSourceType = "application_fee" + BalanceTransactionSourceTypeCharge BalanceTransactionSourceType = "charge" + BalanceTransactionSourceTypeConnectCollectionTransfer BalanceTransactionSourceType = "connect_collection_transfer" + BalanceTransactionSourceTypeCustomerCashBalanceTransaction BalanceTransactionSourceType = "customer_cash_balance_transaction" + BalanceTransactionSourceTypeDispute BalanceTransactionSourceType = "dispute" + BalanceTransactionSourceTypeFeeRefund BalanceTransactionSourceType = "fee_refund" + BalanceTransactionSourceTypeIssuingAuthorization BalanceTransactionSourceType = "issuing.authorization" + BalanceTransactionSourceTypeIssuingDispute BalanceTransactionSourceType = "issuing.dispute" + BalanceTransactionSourceTypeIssuingTransaction BalanceTransactionSourceType = "issuing.transaction" + BalanceTransactionSourceTypePayout BalanceTransactionSourceType = "payout" + BalanceTransactionSourceTypeRefund BalanceTransactionSourceType = "refund" + BalanceTransactionSourceTypeReserveTransaction BalanceTransactionSourceType = "reserve_transaction" + BalanceTransactionSourceTypeTaxDeductedAtSource BalanceTransactionSourceType = "tax_deducted_at_source" + BalanceTransactionSourceTypeTopup BalanceTransactionSourceType = "topup" + BalanceTransactionSourceTypeTransfer BalanceTransactionSourceType = "transfer" + BalanceTransactionSourceTypeTransferReversal BalanceTransactionSourceType = "transfer_reversal" +) + +// The transaction's net funds status in the Stripe balance, which are either `available` or `pending`. +type BalanceTransactionStatus string + +// List of values that BalanceTransactionStatus can take +const ( + BalanceTransactionStatusAvailable BalanceTransactionStatus = "available" + BalanceTransactionStatusPending BalanceTransactionStatus = "pending" +) + +// Transaction type: `adjustment`, `advance`, `advance_funding`, `anticipation_repayment`, `application_fee`, `application_fee_refund`, `charge`, `climate_order_purchase`, `climate_order_refund`, `connect_collection_transfer`, `contribution`, `issuing_authorization_hold`, `issuing_authorization_release`, `issuing_dispute`, `issuing_transaction`, `obligation_outbound`, `obligation_reversal_inbound`, `payment`, `payment_failure_refund`, `payment_network_reserve_hold`, `payment_network_reserve_release`, `payment_refund`, `payment_reversal`, `payment_unreconciled`, `payout`, `payout_cancel`, `payout_failure`, `payout_minimum_balance_hold`, `payout_minimum_balance_release`, `refund`, `refund_failure`, `reserve_transaction`, `reserved_funds`, `stripe_fee`, `stripe_fx_fee`, `stripe_balance_payment_debit`, `stripe_balance_payment_debit_reversal`, `tax_fee`, `topup`, `topup_reversal`, `transfer`, `transfer_cancel`, `transfer_failure`, or `transfer_refund`. Learn more about [balance transaction types and what they represent](https://stripe.com/docs/reports/balance-transaction-types). To classify transactions for accounting purposes, consider `reporting_category` instead. +type BalanceTransactionType string + +// List of values that BalanceTransactionType can take +const ( + BalanceTransactionTypeAdjustment BalanceTransactionType = "adjustment" + BalanceTransactionTypeAdvance BalanceTransactionType = "advance" + BalanceTransactionTypeAdvanceFunding BalanceTransactionType = "advance_funding" + BalanceTransactionTypeAnticipationRepayment BalanceTransactionType = "anticipation_repayment" + BalanceTransactionTypeApplicationFee BalanceTransactionType = "application_fee" + BalanceTransactionTypeApplicationFeeRefund BalanceTransactionType = "application_fee_refund" + BalanceTransactionTypeCharge BalanceTransactionType = "charge" + BalanceTransactionTypeClimateOrderPurchase BalanceTransactionType = "climate_order_purchase" + BalanceTransactionTypeClimateOrderRefund BalanceTransactionType = "climate_order_refund" + BalanceTransactionTypeConnectCollectionTransfer BalanceTransactionType = "connect_collection_transfer" + BalanceTransactionTypeContribution BalanceTransactionType = "contribution" + BalanceTransactionTypeIssuingAuthorizationHold BalanceTransactionType = "issuing_authorization_hold" + BalanceTransactionTypeIssuingAuthorizationRelease BalanceTransactionType = "issuing_authorization_release" + BalanceTransactionTypeIssuingDispute BalanceTransactionType = "issuing_dispute" + BalanceTransactionTypeIssuingTransaction BalanceTransactionType = "issuing_transaction" + BalanceTransactionTypeObligationOutbound BalanceTransactionType = "obligation_outbound" + BalanceTransactionTypeObligationReversalInbound BalanceTransactionType = "obligation_reversal_inbound" + BalanceTransactionTypePayment BalanceTransactionType = "payment" + BalanceTransactionTypePaymentFailureRefund BalanceTransactionType = "payment_failure_refund" + BalanceTransactionTypePaymentNetworkReserveHold BalanceTransactionType = "payment_network_reserve_hold" + BalanceTransactionTypePaymentNetworkReserveRelease BalanceTransactionType = "payment_network_reserve_release" + BalanceTransactionTypePaymentRefund BalanceTransactionType = "payment_refund" + BalanceTransactionTypePaymentReversal BalanceTransactionType = "payment_reversal" + BalanceTransactionTypePaymentUnreconciled BalanceTransactionType = "payment_unreconciled" + BalanceTransactionTypePayout BalanceTransactionType = "payout" + BalanceTransactionTypePayoutCancel BalanceTransactionType = "payout_cancel" + BalanceTransactionTypePayoutFailure BalanceTransactionType = "payout_failure" + BalanceTransactionTypePayoutMinimumBalanceHold BalanceTransactionType = "payout_minimum_balance_hold" + BalanceTransactionTypePayoutMinimumBalanceRelease BalanceTransactionType = "payout_minimum_balance_release" + BalanceTransactionTypeRefund BalanceTransactionType = "refund" + BalanceTransactionTypeRefundFailure BalanceTransactionType = "refund_failure" + BalanceTransactionTypeReserveTransaction BalanceTransactionType = "reserve_transaction" + BalanceTransactionTypeReservedFunds BalanceTransactionType = "reserved_funds" + BalanceTransactionTypeStripeBalancePaymentDebit BalanceTransactionType = "stripe_balance_payment_debit" + BalanceTransactionTypeStripeBalancePaymentDebitReversal BalanceTransactionType = "stripe_balance_payment_debit_reversal" + BalanceTransactionTypeStripeFee BalanceTransactionType = "stripe_fee" + BalanceTransactionTypeStripeFxFee BalanceTransactionType = "stripe_fx_fee" + BalanceTransactionTypeTaxFee BalanceTransactionType = "tax_fee" + BalanceTransactionTypeTopup BalanceTransactionType = "topup" + BalanceTransactionTypeTopupReversal BalanceTransactionType = "topup_reversal" + BalanceTransactionTypeTransfer BalanceTransactionType = "transfer" + BalanceTransactionTypeTransferCancel BalanceTransactionType = "transfer_cancel" + BalanceTransactionTypeTransferFailure BalanceTransactionType = "transfer_failure" + BalanceTransactionTypeTransferRefund BalanceTransactionType = "transfer_refund" +) + +// Returns a list of transactions that have contributed to the Stripe account balance (e.g., charges, transfers, and so forth). The transactions are returned in sorted order, with the most recent transactions appearing first. +// +// Note that this endpoint was previously called “Balance history” and used the path /v1/balance/history. +type BalanceTransactionListParams struct { + ListParams `form:"*"` + // Only return transactions that were created during the given date interval. + Created *int64 `form:"created"` + // Only return transactions that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Only return transactions in a certain currency. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // For automatic Stripe payouts only, only returns transactions that were paid out on the specified payout ID. + Payout *string `form:"payout"` + // Only returns the original transaction. + Source *string `form:"source"` + // Only returns transactions of the given type. One of: `adjustment`, `advance`, `advance_funding`, `anticipation_repayment`, `application_fee`, `application_fee_refund`, `charge`, `climate_order_purchase`, `climate_order_refund`, `connect_collection_transfer`, `contribution`, `issuing_authorization_hold`, `issuing_authorization_release`, `issuing_dispute`, `issuing_transaction`, `obligation_outbound`, `obligation_reversal_inbound`, `payment`, `payment_failure_refund`, `payment_network_reserve_hold`, `payment_network_reserve_release`, `payment_refund`, `payment_reversal`, `payment_unreconciled`, `payout`, `payout_cancel`, `payout_failure`, `payout_minimum_balance_hold`, `payout_minimum_balance_release`, `refund`, `refund_failure`, `reserve_transaction`, `reserved_funds`, `stripe_fee`, `stripe_fx_fee`, `stripe_balance_payment_debit`, `stripe_balance_payment_debit_reversal`, `tax_fee`, `topup`, `topup_reversal`, `transfer`, `transfer_cancel`, `transfer_failure`, or `transfer_refund`. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *BalanceTransactionListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the balance transaction with the given ID. +// +// Note that this endpoint previously used the path /v1/balance/history/:id. +type BalanceTransactionParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BalanceTransactionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the balance transaction with the given ID. +// +// Note that this endpoint previously used the path /v1/balance/history/:id. +type BalanceTransactionRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BalanceTransactionRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Detailed breakdown of fees (in cents (or local equivalent)) paid for this transaction. +type BalanceTransactionFeeDetail struct { + // Amount of the fee, in cents. + Amount int64 `json:"amount"` + // ID of the Connect application that earned the fee. + Application string `json:"application"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // Type of the fee, one of: `application_fee`, `payment_method_passthrough_fee`, `stripe_fee` or `tax`. + Type string `json:"type"` +} + +// Balance transactions represent funds moving through your Stripe account. +// Stripe creates them for every type of transaction that enters or leaves your Stripe account balance. +// +// Related guide: [Balance transaction types](https://stripe.com/docs/reports/balance-transaction-types) +type BalanceTransaction struct { + APIResource + // Gross amount of this transaction (in cents (or local equivalent)). A positive value represents funds charged to another party, and a negative value represents funds sent to another party. + Amount int64 `json:"amount"` + // The date that the transaction's net funds become available in the Stripe balance. + AvailableOn int64 `json:"available_on"` + // The balance that this transaction impacts. + BalanceType BalanceTransactionBalanceType `json:"balance_type"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // If applicable, this transaction uses an exchange rate. If money converts from currency A to currency B, then the `amount` in currency A, multipled by the `exchange_rate`, equals the `amount` in currency B. For example, if you charge a customer 10.00 EUR, the PaymentIntent's `amount` is `1000` and `currency` is `eur`. If this converts to 12.34 USD in your Stripe account, the BalanceTransaction's `amount` is `1234`, its `currency` is `usd`, and the `exchange_rate` is `1.234`. + ExchangeRate float64 `json:"exchange_rate"` + // Fees (in cents (or local equivalent)) paid for this transaction. Represented as a positive integer when assessed. + Fee int64 `json:"fee"` + // Detailed breakdown of fees (in cents (or local equivalent)) paid for this transaction. + FeeDetails []*BalanceTransactionFeeDetail `json:"fee_details"` + // Unique identifier for the object. + ID string `json:"id"` + // Net impact to a Stripe balance (in cents (or local equivalent)). A positive value represents incrementing a Stripe balance, and a negative value decrementing a Stripe balance. You can calculate the net impact of a transaction on a balance by `amount` - `fee` + Net int64 `json:"net"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Learn more about how [reporting categories](https://stripe.com/docs/reports/reporting-categories) can help you understand balance transactions from an accounting perspective. + ReportingCategory BalanceTransactionReportingCategory `json:"reporting_category"` + // This transaction relates to the Stripe object. + Source *BalanceTransactionSource `json:"source"` + // The transaction's net funds status in the Stripe balance, which are either `available` or `pending`. + Status BalanceTransactionStatus `json:"status"` + // Transaction type: `adjustment`, `advance`, `advance_funding`, `anticipation_repayment`, `application_fee`, `application_fee_refund`, `charge`, `climate_order_purchase`, `climate_order_refund`, `connect_collection_transfer`, `contribution`, `issuing_authorization_hold`, `issuing_authorization_release`, `issuing_dispute`, `issuing_transaction`, `obligation_outbound`, `obligation_reversal_inbound`, `payment`, `payment_failure_refund`, `payment_network_reserve_hold`, `payment_network_reserve_release`, `payment_refund`, `payment_reversal`, `payment_unreconciled`, `payout`, `payout_cancel`, `payout_failure`, `payout_minimum_balance_hold`, `payout_minimum_balance_release`, `refund`, `refund_failure`, `reserve_transaction`, `reserved_funds`, `stripe_fee`, `stripe_fx_fee`, `stripe_balance_payment_debit`, `stripe_balance_payment_debit_reversal`, `tax_fee`, `topup`, `topup_reversal`, `transfer`, `transfer_cancel`, `transfer_failure`, or `transfer_refund`. Learn more about [balance transaction types and what they represent](https://stripe.com/docs/reports/balance-transaction-types). To classify transactions for accounting purposes, consider `reporting_category` instead. + Type BalanceTransactionType `json:"type"` +} +type BalanceTransactionSource struct { + ID string `json:"id"` + Type BalanceTransactionSourceType `json:"object"` + + ApplicationFee *ApplicationFee `json:"-"` + Charge *Charge `json:"-"` + ConnectCollectionTransfer *ConnectCollectionTransfer `json:"-"` + CustomerCashBalanceTransaction *CustomerCashBalanceTransaction `json:"-"` + Dispute *Dispute `json:"-"` + FeeRefund *FeeRefund `json:"-"` + IssuingAuthorization *IssuingAuthorization `json:"-"` + IssuingDispute *IssuingDispute `json:"-"` + IssuingTransaction *IssuingTransaction `json:"-"` + Payout *Payout `json:"-"` + Refund *Refund `json:"-"` + ReserveTransaction *ReserveTransaction `json:"-"` + TaxDeductedAtSource *TaxDeductedAtSource `json:"-"` + Topup *Topup `json:"-"` + Transfer *Transfer `json:"-"` + TransferReversal *TransferReversal `json:"-"` +} + +// BalanceTransactionList is a list of BalanceTransactions as retrieved from a list endpoint. +type BalanceTransactionList struct { + APIResource + ListMeta + Data []*BalanceTransaction `json:"data"` +} + +// UnmarshalJSON handles deserialization of a BalanceTransaction. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (b *BalanceTransaction) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + b.ID = id + return nil + } + + type balanceTransaction BalanceTransaction + var v balanceTransaction + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *b = BalanceTransaction(v) + return nil +} + +// UnmarshalJSON handles deserialization of a BalanceTransactionSource. +// This custom unmarshaling is needed because the specific type of +// BalanceTransactionSource it refers to is specified in the JSON +func (b *BalanceTransactionSource) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + b.ID = id + return nil + } + + type balanceTransactionSource BalanceTransactionSource + var v balanceTransactionSource + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *b = BalanceTransactionSource(v) + var err error + + switch b.Type { + case BalanceTransactionSourceTypeApplicationFee: + err = json.Unmarshal(data, &b.ApplicationFee) + case BalanceTransactionSourceTypeCharge: + err = json.Unmarshal(data, &b.Charge) + case BalanceTransactionSourceTypeConnectCollectionTransfer: + err = json.Unmarshal(data, &b.ConnectCollectionTransfer) + case BalanceTransactionSourceTypeCustomerCashBalanceTransaction: + err = json.Unmarshal(data, &b.CustomerCashBalanceTransaction) + case BalanceTransactionSourceTypeDispute: + err = json.Unmarshal(data, &b.Dispute) + case BalanceTransactionSourceTypeFeeRefund: + err = json.Unmarshal(data, &b.FeeRefund) + case BalanceTransactionSourceTypeIssuingAuthorization: + err = json.Unmarshal(data, &b.IssuingAuthorization) + case BalanceTransactionSourceTypeIssuingDispute: + err = json.Unmarshal(data, &b.IssuingDispute) + case BalanceTransactionSourceTypeIssuingTransaction: + err = json.Unmarshal(data, &b.IssuingTransaction) + case BalanceTransactionSourceTypePayout: + err = json.Unmarshal(data, &b.Payout) + case BalanceTransactionSourceTypeRefund: + err = json.Unmarshal(data, &b.Refund) + case BalanceTransactionSourceTypeReserveTransaction: + err = json.Unmarshal(data, &b.ReserveTransaction) + case BalanceTransactionSourceTypeTaxDeductedAtSource: + err = json.Unmarshal(data, &b.TaxDeductedAtSource) + case BalanceTransactionSourceTypeTopup: + err = json.Unmarshal(data, &b.Topup) + case BalanceTransactionSourceTypeTransfer: + err = json.Unmarshal(data, &b.Transfer) + case BalanceTransactionSourceTypeTransferReversal: + err = json.Unmarshal(data, &b.TransferReversal) + } + return err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/balancetransaction_service.go b/vendor/github.com/stripe/stripe-go/v82/balancetransaction_service.go new file mode 100644 index 00000000..65ff6b7a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/balancetransaction_service.go @@ -0,0 +1,53 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1BalanceTransactionService is used to invoke /v1/balance_transactions APIs. +type v1BalanceTransactionService struct { + B Backend + Key string +} + +// Retrieves the balance transaction with the given ID. +// +// Note that this endpoint previously used the path /v1/balance/history/:id. +func (c v1BalanceTransactionService) Retrieve(ctx context.Context, id string, params *BalanceTransactionRetrieveParams) (*BalanceTransaction, error) { + if params == nil { + params = &BalanceTransactionRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/balance_transactions/%s", id) + balancetransaction := &BalanceTransaction{} + err := c.B.Call(http.MethodGet, path, c.Key, params, balancetransaction) + return balancetransaction, err +} + +// Returns a list of transactions that have contributed to the Stripe account balance (e.g., charges, transfers, and so forth). The transactions are returned in sorted order, with the most recent transactions appearing first. +// +// Note that this endpoint was previously called “Balance history” and used the path /v1/balance/history. +func (c v1BalanceTransactionService) List(ctx context.Context, listParams *BalanceTransactionListParams) Seq2[*BalanceTransaction, error] { + if listParams == nil { + listParams = &BalanceTransactionListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*BalanceTransaction, ListContainer, error) { + list := &BalanceTransactionList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/balance_transactions", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/bankaccount.go b/vendor/github.com/stripe/stripe-go/v82/bankaccount.go new file mode 100644 index 00000000..c954359a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/bankaccount.go @@ -0,0 +1,647 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "encoding/json" + "github.com/stripe/stripe-go/v82/form" + "strconv" +) + +// The type of entity that holds the account. This can be either `individual` or `company`. +type BankAccountAccountHolderType string + +// List of values that BankAccountAccountHolderType can take +const ( + BankAccountAccountHolderTypeCompany BankAccountAccountHolderType = "company" + BankAccountAccountHolderTypeIndividual BankAccountAccountHolderType = "individual" +) + +// A set of available payout methods for this bank account. Only values from this set should be passed as the `method` when creating a payout. +type BankAccountAvailablePayoutMethod string + +// List of values that BankAccountAvailablePayoutMethod can take +const ( + BankAccountAvailablePayoutMethodInstant BankAccountAvailablePayoutMethod = "instant" + BankAccountAvailablePayoutMethodStandard BankAccountAvailablePayoutMethod = "standard" +) + +// The code for the type of error. +type BankAccountFutureRequirementsErrorCode string + +// List of values that BankAccountFutureRequirementsErrorCode can take +const ( + BankAccountFutureRequirementsErrorCodeInformationMissing BankAccountFutureRequirementsErrorCode = "information_missing" + BankAccountFutureRequirementsErrorCodeInvalidAddressCityStatePostalCode BankAccountFutureRequirementsErrorCode = "invalid_address_city_state_postal_code" + BankAccountFutureRequirementsErrorCodeInvalidAddressHighwayContractBox BankAccountFutureRequirementsErrorCode = "invalid_address_highway_contract_box" + BankAccountFutureRequirementsErrorCodeInvalidAddressPrivateMailbox BankAccountFutureRequirementsErrorCode = "invalid_address_private_mailbox" + BankAccountFutureRequirementsErrorCodeInvalidBusinessProfileName BankAccountFutureRequirementsErrorCode = "invalid_business_profile_name" + BankAccountFutureRequirementsErrorCodeInvalidBusinessProfileNameDenylisted BankAccountFutureRequirementsErrorCode = "invalid_business_profile_name_denylisted" + BankAccountFutureRequirementsErrorCodeInvalidCompanyNameDenylisted BankAccountFutureRequirementsErrorCode = "invalid_company_name_denylisted" + BankAccountFutureRequirementsErrorCodeInvalidDOBAgeOverMaximum BankAccountFutureRequirementsErrorCode = "invalid_dob_age_over_maximum" + BankAccountFutureRequirementsErrorCodeInvalidDOBAgeUnder18 BankAccountFutureRequirementsErrorCode = "invalid_dob_age_under_18" + BankAccountFutureRequirementsErrorCodeInvalidDOBAgeUnderMinimum BankAccountFutureRequirementsErrorCode = "invalid_dob_age_under_minimum" + BankAccountFutureRequirementsErrorCodeInvalidProductDescriptionLength BankAccountFutureRequirementsErrorCode = "invalid_product_description_length" + BankAccountFutureRequirementsErrorCodeInvalidProductDescriptionURLMatch BankAccountFutureRequirementsErrorCode = "invalid_product_description_url_match" + BankAccountFutureRequirementsErrorCodeInvalidRepresentativeCountry BankAccountFutureRequirementsErrorCode = "invalid_representative_country" + BankAccountFutureRequirementsErrorCodeInvalidSignator BankAccountFutureRequirementsErrorCode = "invalid_signator" + BankAccountFutureRequirementsErrorCodeInvalidStatementDescriptorBusinessMismatch BankAccountFutureRequirementsErrorCode = "invalid_statement_descriptor_business_mismatch" + BankAccountFutureRequirementsErrorCodeInvalidStatementDescriptorDenylisted BankAccountFutureRequirementsErrorCode = "invalid_statement_descriptor_denylisted" + BankAccountFutureRequirementsErrorCodeInvalidStatementDescriptorLength BankAccountFutureRequirementsErrorCode = "invalid_statement_descriptor_length" + BankAccountFutureRequirementsErrorCodeInvalidStatementDescriptorPrefixDenylisted BankAccountFutureRequirementsErrorCode = "invalid_statement_descriptor_prefix_denylisted" + BankAccountFutureRequirementsErrorCodeInvalidStatementDescriptorPrefixMismatch BankAccountFutureRequirementsErrorCode = "invalid_statement_descriptor_prefix_mismatch" + BankAccountFutureRequirementsErrorCodeInvalidStreetAddress BankAccountFutureRequirementsErrorCode = "invalid_street_address" + BankAccountFutureRequirementsErrorCodeInvalidTaxID BankAccountFutureRequirementsErrorCode = "invalid_tax_id" + BankAccountFutureRequirementsErrorCodeInvalidTaxIDFormat BankAccountFutureRequirementsErrorCode = "invalid_tax_id_format" + BankAccountFutureRequirementsErrorCodeInvalidTOSAcceptance BankAccountFutureRequirementsErrorCode = "invalid_tos_acceptance" + BankAccountFutureRequirementsErrorCodeInvalidURLDenylisted BankAccountFutureRequirementsErrorCode = "invalid_url_denylisted" + BankAccountFutureRequirementsErrorCodeInvalidURLFormat BankAccountFutureRequirementsErrorCode = "invalid_url_format" + BankAccountFutureRequirementsErrorCodeInvalidURLLength BankAccountFutureRequirementsErrorCode = "invalid_url_length" + BankAccountFutureRequirementsErrorCodeInvalidURLWebPresenceDetected BankAccountFutureRequirementsErrorCode = "invalid_url_web_presence_detected" + BankAccountFutureRequirementsErrorCodeInvalidURLWebsiteBusinessInformationMismatch BankAccountFutureRequirementsErrorCode = "invalid_url_website_business_information_mismatch" + BankAccountFutureRequirementsErrorCodeInvalidURLWebsiteEmpty BankAccountFutureRequirementsErrorCode = "invalid_url_website_empty" + BankAccountFutureRequirementsErrorCodeInvalidURLWebsiteInaccessible BankAccountFutureRequirementsErrorCode = "invalid_url_website_inaccessible" + BankAccountFutureRequirementsErrorCodeInvalidURLWebsiteInaccessibleGeoblocked BankAccountFutureRequirementsErrorCode = "invalid_url_website_inaccessible_geoblocked" + BankAccountFutureRequirementsErrorCodeInvalidURLWebsiteInaccessiblePasswordProtected BankAccountFutureRequirementsErrorCode = "invalid_url_website_inaccessible_password_protected" + BankAccountFutureRequirementsErrorCodeInvalidURLWebsiteIncomplete BankAccountFutureRequirementsErrorCode = "invalid_url_website_incomplete" + BankAccountFutureRequirementsErrorCodeInvalidURLWebsiteIncompleteCancellationPolicy BankAccountFutureRequirementsErrorCode = "invalid_url_website_incomplete_cancellation_policy" + BankAccountFutureRequirementsErrorCodeInvalidURLWebsiteIncompleteCustomerServiceDetails BankAccountFutureRequirementsErrorCode = "invalid_url_website_incomplete_customer_service_details" + BankAccountFutureRequirementsErrorCodeInvalidURLWebsiteIncompleteLegalRestrictions BankAccountFutureRequirementsErrorCode = "invalid_url_website_incomplete_legal_restrictions" + BankAccountFutureRequirementsErrorCodeInvalidURLWebsiteIncompleteRefundPolicy BankAccountFutureRequirementsErrorCode = "invalid_url_website_incomplete_refund_policy" + BankAccountFutureRequirementsErrorCodeInvalidURLWebsiteIncompleteReturnPolicy BankAccountFutureRequirementsErrorCode = "invalid_url_website_incomplete_return_policy" + BankAccountFutureRequirementsErrorCodeInvalidURLWebsiteIncompleteTermsAndConditions BankAccountFutureRequirementsErrorCode = "invalid_url_website_incomplete_terms_and_conditions" + BankAccountFutureRequirementsErrorCodeInvalidURLWebsiteIncompleteUnderConstruction BankAccountFutureRequirementsErrorCode = "invalid_url_website_incomplete_under_construction" + BankAccountFutureRequirementsErrorCodeInvalidURLWebsiteOther BankAccountFutureRequirementsErrorCode = "invalid_url_website_other" + BankAccountFutureRequirementsErrorCodeInvalidValueOther BankAccountFutureRequirementsErrorCode = "invalid_value_other" + BankAccountFutureRequirementsErrorCodeVerificationDirectorsMismatch BankAccountFutureRequirementsErrorCode = "verification_directors_mismatch" + BankAccountFutureRequirementsErrorCodeVerificationDocumentAddressMismatch BankAccountFutureRequirementsErrorCode = "verification_document_address_mismatch" + BankAccountFutureRequirementsErrorCodeVerificationDocumentAddressMissing BankAccountFutureRequirementsErrorCode = "verification_document_address_missing" + BankAccountFutureRequirementsErrorCodeVerificationDocumentCorrupt BankAccountFutureRequirementsErrorCode = "verification_document_corrupt" + BankAccountFutureRequirementsErrorCodeVerificationDocumentCountryNotSupported BankAccountFutureRequirementsErrorCode = "verification_document_country_not_supported" + BankAccountFutureRequirementsErrorCodeVerificationDocumentDirectorsMismatch BankAccountFutureRequirementsErrorCode = "verification_document_directors_mismatch" + BankAccountFutureRequirementsErrorCodeVerificationDocumentDOBMismatch BankAccountFutureRequirementsErrorCode = "verification_document_dob_mismatch" + BankAccountFutureRequirementsErrorCodeVerificationDocumentDuplicateType BankAccountFutureRequirementsErrorCode = "verification_document_duplicate_type" + BankAccountFutureRequirementsErrorCodeVerificationDocumentExpired BankAccountFutureRequirementsErrorCode = "verification_document_expired" + BankAccountFutureRequirementsErrorCodeVerificationDocumentFailedCopy BankAccountFutureRequirementsErrorCode = "verification_document_failed_copy" + BankAccountFutureRequirementsErrorCodeVerificationDocumentFailedGreyscale BankAccountFutureRequirementsErrorCode = "verification_document_failed_greyscale" + BankAccountFutureRequirementsErrorCodeVerificationDocumentFailedOther BankAccountFutureRequirementsErrorCode = "verification_document_failed_other" + BankAccountFutureRequirementsErrorCodeVerificationDocumentFailedTestMode BankAccountFutureRequirementsErrorCode = "verification_document_failed_test_mode" + BankAccountFutureRequirementsErrorCodeVerificationDocumentFraudulent BankAccountFutureRequirementsErrorCode = "verification_document_fraudulent" + BankAccountFutureRequirementsErrorCodeVerificationDocumentIDNumberMismatch BankAccountFutureRequirementsErrorCode = "verification_document_id_number_mismatch" + BankAccountFutureRequirementsErrorCodeVerificationDocumentIDNumberMissing BankAccountFutureRequirementsErrorCode = "verification_document_id_number_missing" + BankAccountFutureRequirementsErrorCodeVerificationDocumentIncomplete BankAccountFutureRequirementsErrorCode = "verification_document_incomplete" + BankAccountFutureRequirementsErrorCodeVerificationDocumentInvalid BankAccountFutureRequirementsErrorCode = "verification_document_invalid" + BankAccountFutureRequirementsErrorCodeVerificationDocumentIssueOrExpiryDateMissing BankAccountFutureRequirementsErrorCode = "verification_document_issue_or_expiry_date_missing" + BankAccountFutureRequirementsErrorCodeVerificationDocumentManipulated BankAccountFutureRequirementsErrorCode = "verification_document_manipulated" + BankAccountFutureRequirementsErrorCodeVerificationDocumentMissingBack BankAccountFutureRequirementsErrorCode = "verification_document_missing_back" + BankAccountFutureRequirementsErrorCodeVerificationDocumentMissingFront BankAccountFutureRequirementsErrorCode = "verification_document_missing_front" + BankAccountFutureRequirementsErrorCodeVerificationDocumentNameMismatch BankAccountFutureRequirementsErrorCode = "verification_document_name_mismatch" + BankAccountFutureRequirementsErrorCodeVerificationDocumentNameMissing BankAccountFutureRequirementsErrorCode = "verification_document_name_missing" + BankAccountFutureRequirementsErrorCodeVerificationDocumentNationalityMismatch BankAccountFutureRequirementsErrorCode = "verification_document_nationality_mismatch" + BankAccountFutureRequirementsErrorCodeVerificationDocumentNotReadable BankAccountFutureRequirementsErrorCode = "verification_document_not_readable" + BankAccountFutureRequirementsErrorCodeVerificationDocumentNotSigned BankAccountFutureRequirementsErrorCode = "verification_document_not_signed" + BankAccountFutureRequirementsErrorCodeVerificationDocumentNotUploaded BankAccountFutureRequirementsErrorCode = "verification_document_not_uploaded" + BankAccountFutureRequirementsErrorCodeVerificationDocumentPhotoMismatch BankAccountFutureRequirementsErrorCode = "verification_document_photo_mismatch" + BankAccountFutureRequirementsErrorCodeVerificationDocumentTooLarge BankAccountFutureRequirementsErrorCode = "verification_document_too_large" + BankAccountFutureRequirementsErrorCodeVerificationDocumentTypeNotSupported BankAccountFutureRequirementsErrorCode = "verification_document_type_not_supported" + BankAccountFutureRequirementsErrorCodeVerificationExtraneousDirectors BankAccountFutureRequirementsErrorCode = "verification_extraneous_directors" + BankAccountFutureRequirementsErrorCodeVerificationFailedAddressMatch BankAccountFutureRequirementsErrorCode = "verification_failed_address_match" + BankAccountFutureRequirementsErrorCodeVerificationFailedAuthorizerAuthority BankAccountFutureRequirementsErrorCode = "verification_failed_authorizer_authority" + BankAccountFutureRequirementsErrorCodeVerificationFailedBusinessIecNumber BankAccountFutureRequirementsErrorCode = "verification_failed_business_iec_number" + BankAccountFutureRequirementsErrorCodeVerificationFailedDocumentMatch BankAccountFutureRequirementsErrorCode = "verification_failed_document_match" + BankAccountFutureRequirementsErrorCodeVerificationFailedIDNumberMatch BankAccountFutureRequirementsErrorCode = "verification_failed_id_number_match" + BankAccountFutureRequirementsErrorCodeVerificationFailedKeyedIdentity BankAccountFutureRequirementsErrorCode = "verification_failed_keyed_identity" + BankAccountFutureRequirementsErrorCodeVerificationFailedKeyedMatch BankAccountFutureRequirementsErrorCode = "verification_failed_keyed_match" + BankAccountFutureRequirementsErrorCodeVerificationFailedNameMatch BankAccountFutureRequirementsErrorCode = "verification_failed_name_match" + BankAccountFutureRequirementsErrorCodeVerificationFailedOther BankAccountFutureRequirementsErrorCode = "verification_failed_other" + BankAccountFutureRequirementsErrorCodeVerificationFailedRepresentativeAuthority BankAccountFutureRequirementsErrorCode = "verification_failed_representative_authority" + BankAccountFutureRequirementsErrorCodeVerificationFailedResidentialAddress BankAccountFutureRequirementsErrorCode = "verification_failed_residential_address" + BankAccountFutureRequirementsErrorCodeVerificationFailedTaxIDMatch BankAccountFutureRequirementsErrorCode = "verification_failed_tax_id_match" + BankAccountFutureRequirementsErrorCodeVerificationFailedTaxIDNotIssued BankAccountFutureRequirementsErrorCode = "verification_failed_tax_id_not_issued" + BankAccountFutureRequirementsErrorCodeVerificationLegalEntityStructureMismatch BankAccountFutureRequirementsErrorCode = "verification_legal_entity_structure_mismatch" + BankAccountFutureRequirementsErrorCodeVerificationMissingDirectors BankAccountFutureRequirementsErrorCode = "verification_missing_directors" + BankAccountFutureRequirementsErrorCodeVerificationMissingExecutives BankAccountFutureRequirementsErrorCode = "verification_missing_executives" + BankAccountFutureRequirementsErrorCodeVerificationMissingOwners BankAccountFutureRequirementsErrorCode = "verification_missing_owners" + BankAccountFutureRequirementsErrorCodeVerificationRejectedOwnershipExemptionReason BankAccountFutureRequirementsErrorCode = "verification_rejected_ownership_exemption_reason" + BankAccountFutureRequirementsErrorCodeVerificationRequiresAdditionalMemorandumOfAssociations BankAccountFutureRequirementsErrorCode = "verification_requires_additional_memorandum_of_associations" + BankAccountFutureRequirementsErrorCodeVerificationRequiresAdditionalProofOfRegistration BankAccountFutureRequirementsErrorCode = "verification_requires_additional_proof_of_registration" + BankAccountFutureRequirementsErrorCodeVerificationSupportability BankAccountFutureRequirementsErrorCode = "verification_supportability" +) + +// The code for the type of error. +type BankAccountRequirementsErrorCode string + +// List of values that BankAccountRequirementsErrorCode can take +const ( + BankAccountRequirementsErrorCodeInformationMissing BankAccountRequirementsErrorCode = "information_missing" + BankAccountRequirementsErrorCodeInvalidAddressCityStatePostalCode BankAccountRequirementsErrorCode = "invalid_address_city_state_postal_code" + BankAccountRequirementsErrorCodeInvalidAddressHighwayContractBox BankAccountRequirementsErrorCode = "invalid_address_highway_contract_box" + BankAccountRequirementsErrorCodeInvalidAddressPrivateMailbox BankAccountRequirementsErrorCode = "invalid_address_private_mailbox" + BankAccountRequirementsErrorCodeInvalidBusinessProfileName BankAccountRequirementsErrorCode = "invalid_business_profile_name" + BankAccountRequirementsErrorCodeInvalidBusinessProfileNameDenylisted BankAccountRequirementsErrorCode = "invalid_business_profile_name_denylisted" + BankAccountRequirementsErrorCodeInvalidCompanyNameDenylisted BankAccountRequirementsErrorCode = "invalid_company_name_denylisted" + BankAccountRequirementsErrorCodeInvalidDOBAgeOverMaximum BankAccountRequirementsErrorCode = "invalid_dob_age_over_maximum" + BankAccountRequirementsErrorCodeInvalidDOBAgeUnder18 BankAccountRequirementsErrorCode = "invalid_dob_age_under_18" + BankAccountRequirementsErrorCodeInvalidDOBAgeUnderMinimum BankAccountRequirementsErrorCode = "invalid_dob_age_under_minimum" + BankAccountRequirementsErrorCodeInvalidProductDescriptionLength BankAccountRequirementsErrorCode = "invalid_product_description_length" + BankAccountRequirementsErrorCodeInvalidProductDescriptionURLMatch BankAccountRequirementsErrorCode = "invalid_product_description_url_match" + BankAccountRequirementsErrorCodeInvalidRepresentativeCountry BankAccountRequirementsErrorCode = "invalid_representative_country" + BankAccountRequirementsErrorCodeInvalidSignator BankAccountRequirementsErrorCode = "invalid_signator" + BankAccountRequirementsErrorCodeInvalidStatementDescriptorBusinessMismatch BankAccountRequirementsErrorCode = "invalid_statement_descriptor_business_mismatch" + BankAccountRequirementsErrorCodeInvalidStatementDescriptorDenylisted BankAccountRequirementsErrorCode = "invalid_statement_descriptor_denylisted" + BankAccountRequirementsErrorCodeInvalidStatementDescriptorLength BankAccountRequirementsErrorCode = "invalid_statement_descriptor_length" + BankAccountRequirementsErrorCodeInvalidStatementDescriptorPrefixDenylisted BankAccountRequirementsErrorCode = "invalid_statement_descriptor_prefix_denylisted" + BankAccountRequirementsErrorCodeInvalidStatementDescriptorPrefixMismatch BankAccountRequirementsErrorCode = "invalid_statement_descriptor_prefix_mismatch" + BankAccountRequirementsErrorCodeInvalidStreetAddress BankAccountRequirementsErrorCode = "invalid_street_address" + BankAccountRequirementsErrorCodeInvalidTaxID BankAccountRequirementsErrorCode = "invalid_tax_id" + BankAccountRequirementsErrorCodeInvalidTaxIDFormat BankAccountRequirementsErrorCode = "invalid_tax_id_format" + BankAccountRequirementsErrorCodeInvalidTOSAcceptance BankAccountRequirementsErrorCode = "invalid_tos_acceptance" + BankAccountRequirementsErrorCodeInvalidURLDenylisted BankAccountRequirementsErrorCode = "invalid_url_denylisted" + BankAccountRequirementsErrorCodeInvalidURLFormat BankAccountRequirementsErrorCode = "invalid_url_format" + BankAccountRequirementsErrorCodeInvalidURLLength BankAccountRequirementsErrorCode = "invalid_url_length" + BankAccountRequirementsErrorCodeInvalidURLWebPresenceDetected BankAccountRequirementsErrorCode = "invalid_url_web_presence_detected" + BankAccountRequirementsErrorCodeInvalidURLWebsiteBusinessInformationMismatch BankAccountRequirementsErrorCode = "invalid_url_website_business_information_mismatch" + BankAccountRequirementsErrorCodeInvalidURLWebsiteEmpty BankAccountRequirementsErrorCode = "invalid_url_website_empty" + BankAccountRequirementsErrorCodeInvalidURLWebsiteInaccessible BankAccountRequirementsErrorCode = "invalid_url_website_inaccessible" + BankAccountRequirementsErrorCodeInvalidURLWebsiteInaccessibleGeoblocked BankAccountRequirementsErrorCode = "invalid_url_website_inaccessible_geoblocked" + BankAccountRequirementsErrorCodeInvalidURLWebsiteInaccessiblePasswordProtected BankAccountRequirementsErrorCode = "invalid_url_website_inaccessible_password_protected" + BankAccountRequirementsErrorCodeInvalidURLWebsiteIncomplete BankAccountRequirementsErrorCode = "invalid_url_website_incomplete" + BankAccountRequirementsErrorCodeInvalidURLWebsiteIncompleteCancellationPolicy BankAccountRequirementsErrorCode = "invalid_url_website_incomplete_cancellation_policy" + BankAccountRequirementsErrorCodeInvalidURLWebsiteIncompleteCustomerServiceDetails BankAccountRequirementsErrorCode = "invalid_url_website_incomplete_customer_service_details" + BankAccountRequirementsErrorCodeInvalidURLWebsiteIncompleteLegalRestrictions BankAccountRequirementsErrorCode = "invalid_url_website_incomplete_legal_restrictions" + BankAccountRequirementsErrorCodeInvalidURLWebsiteIncompleteRefundPolicy BankAccountRequirementsErrorCode = "invalid_url_website_incomplete_refund_policy" + BankAccountRequirementsErrorCodeInvalidURLWebsiteIncompleteReturnPolicy BankAccountRequirementsErrorCode = "invalid_url_website_incomplete_return_policy" + BankAccountRequirementsErrorCodeInvalidURLWebsiteIncompleteTermsAndConditions BankAccountRequirementsErrorCode = "invalid_url_website_incomplete_terms_and_conditions" + BankAccountRequirementsErrorCodeInvalidURLWebsiteIncompleteUnderConstruction BankAccountRequirementsErrorCode = "invalid_url_website_incomplete_under_construction" + BankAccountRequirementsErrorCodeInvalidURLWebsiteOther BankAccountRequirementsErrorCode = "invalid_url_website_other" + BankAccountRequirementsErrorCodeInvalidValueOther BankAccountRequirementsErrorCode = "invalid_value_other" + BankAccountRequirementsErrorCodeVerificationDirectorsMismatch BankAccountRequirementsErrorCode = "verification_directors_mismatch" + BankAccountRequirementsErrorCodeVerificationDocumentAddressMismatch BankAccountRequirementsErrorCode = "verification_document_address_mismatch" + BankAccountRequirementsErrorCodeVerificationDocumentAddressMissing BankAccountRequirementsErrorCode = "verification_document_address_missing" + BankAccountRequirementsErrorCodeVerificationDocumentCorrupt BankAccountRequirementsErrorCode = "verification_document_corrupt" + BankAccountRequirementsErrorCodeVerificationDocumentCountryNotSupported BankAccountRequirementsErrorCode = "verification_document_country_not_supported" + BankAccountRequirementsErrorCodeVerificationDocumentDirectorsMismatch BankAccountRequirementsErrorCode = "verification_document_directors_mismatch" + BankAccountRequirementsErrorCodeVerificationDocumentDOBMismatch BankAccountRequirementsErrorCode = "verification_document_dob_mismatch" + BankAccountRequirementsErrorCodeVerificationDocumentDuplicateType BankAccountRequirementsErrorCode = "verification_document_duplicate_type" + BankAccountRequirementsErrorCodeVerificationDocumentExpired BankAccountRequirementsErrorCode = "verification_document_expired" + BankAccountRequirementsErrorCodeVerificationDocumentFailedCopy BankAccountRequirementsErrorCode = "verification_document_failed_copy" + BankAccountRequirementsErrorCodeVerificationDocumentFailedGreyscale BankAccountRequirementsErrorCode = "verification_document_failed_greyscale" + BankAccountRequirementsErrorCodeVerificationDocumentFailedOther BankAccountRequirementsErrorCode = "verification_document_failed_other" + BankAccountRequirementsErrorCodeVerificationDocumentFailedTestMode BankAccountRequirementsErrorCode = "verification_document_failed_test_mode" + BankAccountRequirementsErrorCodeVerificationDocumentFraudulent BankAccountRequirementsErrorCode = "verification_document_fraudulent" + BankAccountRequirementsErrorCodeVerificationDocumentIDNumberMismatch BankAccountRequirementsErrorCode = "verification_document_id_number_mismatch" + BankAccountRequirementsErrorCodeVerificationDocumentIDNumberMissing BankAccountRequirementsErrorCode = "verification_document_id_number_missing" + BankAccountRequirementsErrorCodeVerificationDocumentIncomplete BankAccountRequirementsErrorCode = "verification_document_incomplete" + BankAccountRequirementsErrorCodeVerificationDocumentInvalid BankAccountRequirementsErrorCode = "verification_document_invalid" + BankAccountRequirementsErrorCodeVerificationDocumentIssueOrExpiryDateMissing BankAccountRequirementsErrorCode = "verification_document_issue_or_expiry_date_missing" + BankAccountRequirementsErrorCodeVerificationDocumentManipulated BankAccountRequirementsErrorCode = "verification_document_manipulated" + BankAccountRequirementsErrorCodeVerificationDocumentMissingBack BankAccountRequirementsErrorCode = "verification_document_missing_back" + BankAccountRequirementsErrorCodeVerificationDocumentMissingFront BankAccountRequirementsErrorCode = "verification_document_missing_front" + BankAccountRequirementsErrorCodeVerificationDocumentNameMismatch BankAccountRequirementsErrorCode = "verification_document_name_mismatch" + BankAccountRequirementsErrorCodeVerificationDocumentNameMissing BankAccountRequirementsErrorCode = "verification_document_name_missing" + BankAccountRequirementsErrorCodeVerificationDocumentNationalityMismatch BankAccountRequirementsErrorCode = "verification_document_nationality_mismatch" + BankAccountRequirementsErrorCodeVerificationDocumentNotReadable BankAccountRequirementsErrorCode = "verification_document_not_readable" + BankAccountRequirementsErrorCodeVerificationDocumentNotSigned BankAccountRequirementsErrorCode = "verification_document_not_signed" + BankAccountRequirementsErrorCodeVerificationDocumentNotUploaded BankAccountRequirementsErrorCode = "verification_document_not_uploaded" + BankAccountRequirementsErrorCodeVerificationDocumentPhotoMismatch BankAccountRequirementsErrorCode = "verification_document_photo_mismatch" + BankAccountRequirementsErrorCodeVerificationDocumentTooLarge BankAccountRequirementsErrorCode = "verification_document_too_large" + BankAccountRequirementsErrorCodeVerificationDocumentTypeNotSupported BankAccountRequirementsErrorCode = "verification_document_type_not_supported" + BankAccountRequirementsErrorCodeVerificationExtraneousDirectors BankAccountRequirementsErrorCode = "verification_extraneous_directors" + BankAccountRequirementsErrorCodeVerificationFailedAddressMatch BankAccountRequirementsErrorCode = "verification_failed_address_match" + BankAccountRequirementsErrorCodeVerificationFailedAuthorizerAuthority BankAccountRequirementsErrorCode = "verification_failed_authorizer_authority" + BankAccountRequirementsErrorCodeVerificationFailedBusinessIecNumber BankAccountRequirementsErrorCode = "verification_failed_business_iec_number" + BankAccountRequirementsErrorCodeVerificationFailedDocumentMatch BankAccountRequirementsErrorCode = "verification_failed_document_match" + BankAccountRequirementsErrorCodeVerificationFailedIDNumberMatch BankAccountRequirementsErrorCode = "verification_failed_id_number_match" + BankAccountRequirementsErrorCodeVerificationFailedKeyedIdentity BankAccountRequirementsErrorCode = "verification_failed_keyed_identity" + BankAccountRequirementsErrorCodeVerificationFailedKeyedMatch BankAccountRequirementsErrorCode = "verification_failed_keyed_match" + BankAccountRequirementsErrorCodeVerificationFailedNameMatch BankAccountRequirementsErrorCode = "verification_failed_name_match" + BankAccountRequirementsErrorCodeVerificationFailedOther BankAccountRequirementsErrorCode = "verification_failed_other" + BankAccountRequirementsErrorCodeVerificationFailedRepresentativeAuthority BankAccountRequirementsErrorCode = "verification_failed_representative_authority" + BankAccountRequirementsErrorCodeVerificationFailedResidentialAddress BankAccountRequirementsErrorCode = "verification_failed_residential_address" + BankAccountRequirementsErrorCodeVerificationFailedTaxIDMatch BankAccountRequirementsErrorCode = "verification_failed_tax_id_match" + BankAccountRequirementsErrorCodeVerificationFailedTaxIDNotIssued BankAccountRequirementsErrorCode = "verification_failed_tax_id_not_issued" + BankAccountRequirementsErrorCodeVerificationLegalEntityStructureMismatch BankAccountRequirementsErrorCode = "verification_legal_entity_structure_mismatch" + BankAccountRequirementsErrorCodeVerificationMissingDirectors BankAccountRequirementsErrorCode = "verification_missing_directors" + BankAccountRequirementsErrorCodeVerificationMissingExecutives BankAccountRequirementsErrorCode = "verification_missing_executives" + BankAccountRequirementsErrorCodeVerificationMissingOwners BankAccountRequirementsErrorCode = "verification_missing_owners" + BankAccountRequirementsErrorCodeVerificationRejectedOwnershipExemptionReason BankAccountRequirementsErrorCode = "verification_rejected_ownership_exemption_reason" + BankAccountRequirementsErrorCodeVerificationRequiresAdditionalMemorandumOfAssociations BankAccountRequirementsErrorCode = "verification_requires_additional_memorandum_of_associations" + BankAccountRequirementsErrorCodeVerificationRequiresAdditionalProofOfRegistration BankAccountRequirementsErrorCode = "verification_requires_additional_proof_of_registration" + BankAccountRequirementsErrorCodeVerificationSupportability BankAccountRequirementsErrorCode = "verification_supportability" +) + +// For bank accounts, possible values are `new`, `validated`, `verified`, `verification_failed`, or `errored`. A bank account that hasn't had any activity or validation performed is `new`. If Stripe can determine that the bank account exists, its status will be `validated`. Note that there often isn't enough information to know (e.g., for smaller credit unions), and the validation is not always run. If customer bank account verification has succeeded, the bank account status will be `verified`. If the verification failed for any reason, such as microdeposit failure, the status will be `verification_failed`. If a payout sent to this bank account fails, we'll set the status to `errored` and will not continue to send [scheduled payouts](https://stripe.com/docs/payouts#payout-schedule) until the bank details are updated. +// +// For external accounts, possible values are `new`, `errored` and `verification_failed`. If a payout fails, the status is set to `errored` and scheduled payouts are stopped until account details are updated. In the US and India, if we can't [verify the owner of the bank account](https://support.stripe.com/questions/bank-account-ownership-verification), we'll set the status to `verification_failed`. Other validations aren't run against external accounts because they're only used for payouts. This means the other statuses don't apply. +type BankAccountStatus string + +// List of values that BankAccountStatus can take +const ( + BankAccountStatusErrored BankAccountStatus = "errored" + BankAccountStatusNew BankAccountStatus = "new" + BankAccountStatusValidated BankAccountStatus = "validated" + BankAccountStatusVerificationFailed BankAccountStatus = "verification_failed" + BankAccountStatusVerified BankAccountStatus = "verified" +) + +// Delete a specified external account for a given account. +type BankAccountParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // Token is a token referencing an external account like one returned from + // Stripe.js. + Token *string `form:"-"` // Included in URL + // Account is the identifier of the parent account under which bank + // accounts are nested. + Account *string `form:"-"` // Included in URL + // The name of the person or business that owns the bank account. + AccountHolderName *string `form:"account_holder_name"` + // The type of entity that holds the account. This can be either `individual` or `company`. + AccountHolderType *string `form:"account_holder_type"` + // The account number for the bank account, in string form. Must be a checking account. + AccountNumber *string `form:"account_number"` + // The bank account type. This can only be `checking` or `savings` in most countries. In Japan, this can only be `futsu` or `toza`. + AccountType *string `form:"account_type"` + // City/District/Suburb/Town/Village. + AddressCity *string `form:"address_city"` + // Billing address country, if provided when creating card. + AddressCountry *string `form:"address_country"` + // Address line 1 (Street address/PO Box/Company name). + AddressLine1 *string `form:"address_line1"` + // Address line 2 (Apartment/Suite/Unit/Building). + AddressLine2 *string `form:"address_line2"` + // State/County/Province/Region. + AddressState *string `form:"address_state"` + // ZIP or postal code. + AddressZip *string `form:"address_zip"` + // The country in which the bank account is located. + Country *string `form:"country"` + // The currency the bank account is in. This must be a country/currency pairing that [Stripe supports](https://stripe.com/docs/payouts). + Currency *string `form:"currency"` + // When set to true, this becomes the default external account for its currency. + DefaultForCurrency *bool `form:"default_for_currency"` + // Documents that may be submitted to satisfy various informational requests. + Documents *BankAccountDocumentsParams `form:"documents"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Two digit number representing the card's expiration month. + ExpMonth *string `form:"exp_month"` + // Four digit number representing the card's expiration year. + ExpYear *string `form:"exp_year"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Cardholder name. + Name *string `form:"name"` + // The ID of a Payment Method with a `type` of `us_bank_account`. The Payment Method's bank account information will be copied and + // returned as a Bank Account Token. This parameter is exclusive with respect to all other parameters in the `bank_account` hash. + // You must include the top-level `customer` parameter if the Payment Method is attached to a `Customer` object. If the Payment + // Method is not attached to a `Customer` object, it will be consumed and cannot be used again. You may not use Payment Methods which were + // created by a Setup Intent with `attach_to_self=true`. + // This is used for TokenParams.BankAccountParams only and will be removed in the next major version. + // **DO NOT USE THIS FOR OTHER METHODS.** + PaymentMethod *string `form:"payment_method"` + // The routing number, sort code, or other country-appropriate institution number for the bank account. For US bank accounts, this is required and should be the ACH routing number, not the wire routing number. If you are providing an IBAN for `account_number`, this field is not required. + RoutingNumber *string `form:"routing_number"` + // ID is used when tokenizing a bank account for shared customers + ID *string `form:"*"` +} + +// AppendToAsSourceOrExternalAccount appends the given BankAccountParams as +// either a source or external account. +// +// It may look like an AppendTo from the form package, but it's not, and is +// only used in the special case where we use `bankaccount.New`. It's needed +// because we have some weird encoding logic here that can't be handled by the +// form package (and it's special enough that it wouldn't be desirable to have +// it do so). +// +// This is not a pattern that we want to push forward, and this largely exists +// because the bank accounts endpoint is a little unusual. There is one other +// resource like it, which is cards. +func (p *BankAccountParams) AppendToAsSourceOrExternalAccount(body *form.Values) { + // Rather than being called in addition to `AppendTo`, this function + // *replaces* `AppendTo`, so we must also make sure to handle the encoding + // of `Params` so metadata and the like is included in the encoded payload. + form.AppendTo(body, p.Params) + + isCustomer := p.Customer != nil + + var sourceType string + if isCustomer { + sourceType = "source" + } else { + sourceType = "external_account" + } + + // Use token (if exists) or a dictionary containing a user’s bank account details. + if p.Token != nil { + body.Add(sourceType, StringValue(p.Token)) + + if p.DefaultForCurrency != nil { + body.Add( + "default_for_currency", strconv.FormatBool( + BoolValue(p.DefaultForCurrency))) + } + } else { + body.Add(sourceType+"[object]", "bank_account") + body.Add(sourceType+"[country]", StringValue(p.Country)) + body.Add(sourceType+"[account_number]", StringValue(p.AccountNumber)) + body.Add(sourceType+"[currency]", StringValue(p.Currency)) + + // These are optional and the API will fail if we try to send empty + // values in for them, so make sure to check that they're actually set + // before encoding them. + if p.AccountHolderName != nil { + body.Add(sourceType+"[account_holder_name]", StringValue(p.AccountHolderName)) + } + + if p.AccountHolderType != nil { + body.Add(sourceType+"[account_holder_type]", StringValue(p.AccountHolderType)) + } + + if p.RoutingNumber != nil { + body.Add(sourceType+"[routing_number]", StringValue(p.RoutingNumber)) + } + + if p.DefaultForCurrency != nil { + body.Add(sourceType+"[default_for_currency]", strconv.FormatBool(BoolValue(p.DefaultForCurrency))) + } + } +} + +// AddExpand appends a new field to expand. +func (p *BankAccountParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *BankAccountParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// One or more documents that support the [Bank account ownership verification](https://support.stripe.com/questions/bank-account-ownership-verification) requirement. Must be a document associated with the bank account that displays the last 4 digits of the account number, either a statement or a check. +type BankAccountDocumentsBankAccountOwnershipVerificationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// Documents that may be submitted to satisfy various informational requests. +type BankAccountDocumentsParams struct { + // One or more documents that support the [Bank account ownership verification](https://support.stripe.com/questions/bank-account-ownership-verification) requirement. Must be a document associated with the bank account that displays the last 4 digits of the account number, either a statement or a check. + BankAccountOwnershipVerification *BankAccountDocumentsBankAccountOwnershipVerificationParams `form:"bank_account_ownership_verification"` +} +type BankAccountListParams struct { + ListParams `form:"*"` + // The identifier of the parent customer under which the bank accounts are + // nested. Either Account or Customer should be populated. + Customer *string `form:"-"` // Included in URL + // The identifier of the parent account under which the bank accounts are + // nested. Either Account or Customer should be populated. + Account *string `form:"-"` // Included in URL + // Filter according to a particular object type. Valid values are "bank_account" or "card". + Object *string `form:"object"` +} + +// AppendTo implements custom encoding logic for BankAccountListParams +// so that we can send the special required `object` field up along with the +// other specified parameters. +func (p *BankAccountListParams) AppendTo(body *form.Values, keyParts []string) { + body.Add(form.FormatKey(append(keyParts, "object")), "bank_account") +} + +// Delete a specified external account for a given account. +type BankAccountDeleteParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL +} + +// One or more documents that support the [Bank account ownership verification](https://support.stripe.com/questions/bank-account-ownership-verification) requirement. Must be a document associated with the bank account that displays the last 4 digits of the account number, either a statement or a check. +type BankAccountUpdateDocumentsBankAccountOwnershipVerificationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// Documents that may be submitted to satisfy various informational requests. +type BankAccountUpdateDocumentsParams struct { + // One or more documents that support the [Bank account ownership verification](https://support.stripe.com/questions/bank-account-ownership-verification) requirement. Must be a document associated with the bank account that displays the last 4 digits of the account number, either a statement or a check. + BankAccountOwnershipVerification *BankAccountUpdateDocumentsBankAccountOwnershipVerificationParams `form:"bank_account_ownership_verification"` +} + +// Updates the metadata, account holder name, account holder type of a bank account belonging to +// a connected account and optionally sets it as the default for its currency. Other bank account +// details are not editable by design. +// +// You can only update bank accounts when [account.controller.requirement_collection is application, which includes Custom accounts](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection). +// +// You can re-enable a disabled bank account by performing an update call without providing any +// arguments or changes. +type BankAccountUpdateParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL + // The name of the person or business that owns the bank account. + AccountHolderName *string `form:"account_holder_name"` + // The type of entity that holds the account. This can be either `individual` or `company`. + AccountHolderType *string `form:"account_holder_type"` + // The bank account type. This can only be `checking` or `savings` in most countries. In Japan, this can only be `futsu` or `toza`. + AccountType *string `form:"account_type"` + // City/District/Suburb/Town/Village. + AddressCity *string `form:"address_city"` + // Billing address country, if provided when creating card. + AddressCountry *string `form:"address_country"` + // Address line 1 (Street address/PO Box/Company name). + AddressLine1 *string `form:"address_line1"` + // Address line 2 (Apartment/Suite/Unit/Building). + AddressLine2 *string `form:"address_line2"` + // State/County/Province/Region. + AddressState *string `form:"address_state"` + // ZIP or postal code. + AddressZip *string `form:"address_zip"` + // When set to true, this becomes the default external account for its currency. + DefaultForCurrency *bool `form:"default_for_currency"` + // Documents that may be submitted to satisfy various informational requests. + Documents *BankAccountUpdateDocumentsParams `form:"documents"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Two digit number representing the card's expiration month. + ExpMonth *string `form:"exp_month"` + // Four digit number representing the card's expiration year. + ExpYear *string `form:"exp_year"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Cardholder name. + Name *string `form:"name"` +} + +// AddExpand appends a new field to expand. +func (p *BankAccountUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *BankAccountUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// New creates a new bank account +type BankAccountCreateParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL + Customer *string `form:"-"` // Included in URL + Token *string `form:"-"` // Included in URL + // The account number for the bank account, in string form. Must be a checking account. + AccountNumber *string `form:"account_number"` + // The country in which the bank account is located. + Country *string `form:"country"` + // The currency the bank account is in. This must be a country/currency pairing that [Stripe supports](https://stripe.com/docs/payouts). + Currency *string `form:"currency"` + // The ID of a Payment Method with a `type` of `us_bank_account`. The Payment Method's bank account information will be copied and + // returned as a Bank Account Token. This parameter is exclusive with respect to all other parameters in the `bank_account` hash. + // You must include the top-level `customer` parameter if the Payment Method is attached to a `Customer` object. If the Payment + // Method is not attached to a `Customer` object, it will be consumed and cannot be used again. You may not use Payment Methods which were + // created by a Setup Intent with `attach_to_self=true`. + // This is used for TokenParams.BankAccountParams only and will be removed in the next major version. + // **DO NOT USE THIS FOR OTHER METHODS.** + PaymentMethod *string `form:"payment_method"` + // The routing number, sort code, or other country-appropriate institution number for the bank account. For US bank accounts, this is required and should be the ACH routing number, not the wire routing number. If you are providing an IBAN for `account_number`, this field is not required. + RoutingNumber *string `form:"routing_number"` +} + +// Get returns the details of a bank account. +type BankAccountRetrieveParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL +} + +// Fields that are `currently_due` and need to be collected again because validation or verification failed. +type BankAccountFutureRequirementsError struct { + // The code for the type of error. + Code BankAccountFutureRequirementsErrorCode `json:"code"` + // An informative message that indicates the error type and provides additional details about the error. + Reason string `json:"reason"` + // The specific user onboarding requirement field (in the requirements hash) that needs to be resolved. + Requirement string `json:"requirement"` +} + +// Information about the [upcoming new requirements for the bank account](https://stripe.com/docs/connect/custom-accounts/future-requirements), including what information needs to be collected, and by when. +type BankAccountFutureRequirements struct { + // Fields that need to be collected to keep the external account enabled. If not collected by `current_deadline`, these fields appear in `past_due` as well, and the account is disabled. + CurrentlyDue []string `json:"currently_due"` + // Fields that are `currently_due` and need to be collected again because validation or verification failed. + Errors []*BankAccountFutureRequirementsError `json:"errors"` + // Fields that weren't collected by `current_deadline`. These fields need to be collected to enable the external account. + PastDue []string `json:"past_due"` + // Fields that might become required depending on the results of verification or review. It's an empty array unless an asynchronous verification is pending. If verification fails, these fields move to `eventually_due`, `currently_due`, or `past_due`. Fields might appear in `eventually_due`, `currently_due`, or `past_due` and in `pending_verification` if verification fails but another verification is still pending. + PendingVerification []string `json:"pending_verification"` +} + +// Fields that are `currently_due` and need to be collected again because validation or verification failed. +type BankAccountRequirementsError struct { + // The code for the type of error. + Code BankAccountRequirementsErrorCode `json:"code"` + // An informative message that indicates the error type and provides additional details about the error. + Reason string `json:"reason"` + // The specific user onboarding requirement field (in the requirements hash) that needs to be resolved. + Requirement string `json:"requirement"` +} + +// Information about the requirements for the bank account, including what information needs to be collected. +type BankAccountRequirements struct { + // Fields that need to be collected to keep the external account enabled. If not collected by `current_deadline`, these fields appear in `past_due` as well, and the account is disabled. + CurrentlyDue []string `json:"currently_due"` + // Fields that are `currently_due` and need to be collected again because validation or verification failed. + Errors []*BankAccountRequirementsError `json:"errors"` + // Fields that weren't collected by `current_deadline`. These fields need to be collected to enable the external account. + PastDue []string `json:"past_due"` + // Fields that might become required depending on the results of verification or review. It's an empty array unless an asynchronous verification is pending. If verification fails, these fields move to `eventually_due`, `currently_due`, or `past_due`. Fields might appear in `eventually_due`, `currently_due`, or `past_due` and in `pending_verification` if verification fails but another verification is still pending. + PendingVerification []string `json:"pending_verification"` +} + +// These bank accounts are payment methods on `Customer` objects. +// +// On the other hand [External Accounts](https://docs.stripe.com/api#external_accounts) are transfer +// destinations on `Account` objects for connected accounts. +// They can be bank accounts or debit cards as well, and are documented in the links above. +// +// Related guide: [Bank debits and transfers](https://docs.stripe.com/payments/bank-debits-transfers) +type BankAccount struct { + APIResource + // The account this bank account belongs to. Only applicable on Accounts (not customers or recipients) This property is only available when returned as an [External Account](https://docs.stripe.com/api/external_account_bank_accounts/object) where [controller.is_controller](https://docs.stripe.com/api/accounts/object#account_object-controller-is_controller) is `true`. + Account *Account `json:"account"` + // The name of the person or business that owns the bank account. + AccountHolderName string `json:"account_holder_name"` + // The type of entity that holds the account. This can be either `individual` or `company`. + AccountHolderType BankAccountAccountHolderType `json:"account_holder_type"` + // The bank account type. This can only be `checking` or `savings` in most countries. In Japan, this can only be `futsu` or `toza`. + AccountType string `json:"account_type"` + // A set of available payout methods for this bank account. Only values from this set should be passed as the `method` when creating a payout. + AvailablePayoutMethods []BankAccountAvailablePayoutMethod `json:"available_payout_methods"` + // Name of the bank associated with the routing number (e.g., `WELLS FARGO`). + BankName string `json:"bank_name"` + // Two-letter ISO code representing the country the bank account is located in. + Country string `json:"country"` + // Three-letter [ISO code for the currency](https://stripe.com/docs/payouts) paid out to the bank account. + Currency Currency `json:"currency"` + // The ID of the customer that the bank account is associated with. + Customer *Customer `json:"customer"` + // Whether this bank account is the default external account for its currency. + DefaultForCurrency bool `json:"default_for_currency"` + Deleted bool `json:"deleted"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Information about the [upcoming new requirements for the bank account](https://stripe.com/docs/connect/custom-accounts/future-requirements), including what information needs to be collected, and by when. + FutureRequirements *BankAccountFutureRequirements `json:"future_requirements"` + // Unique identifier for the object. + ID string `json:"id"` + // The last four digits of the bank account number. + Last4 string `json:"last4"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Information about the requirements for the bank account, including what information needs to be collected. + Requirements *BankAccountRequirements `json:"requirements"` + // The routing transit number for the bank account. + RoutingNumber string `json:"routing_number"` + // For bank accounts, possible values are `new`, `validated`, `verified`, `verification_failed`, or `errored`. A bank account that hasn't had any activity or validation performed is `new`. If Stripe can determine that the bank account exists, its status will be `validated`. Note that there often isn't enough information to know (e.g., for smaller credit unions), and the validation is not always run. If customer bank account verification has succeeded, the bank account status will be `verified`. If the verification failed for any reason, such as microdeposit failure, the status will be `verification_failed`. If a payout sent to this bank account fails, we'll set the status to `errored` and will not continue to send [scheduled payouts](https://stripe.com/docs/payouts#payout-schedule) until the bank details are updated. + // + // For external accounts, possible values are `new`, `errored` and `verification_failed`. If a payout fails, the status is set to `errored` and scheduled payouts are stopped until account details are updated. In the US and India, if we can't [verify the owner of the bank account](https://support.stripe.com/questions/bank-account-ownership-verification), we'll set the status to `verification_failed`. Other validations aren't run against external accounts because they're only used for payouts. This means the other statuses don't apply. + Status BankAccountStatus `json:"status"` +} + +// BankAccountList is a list of BankAccounts as retrieved from a list endpoint. +type BankAccountList struct { + APIResource + ListMeta + Data []*BankAccount `json:"data"` +} + +// UnmarshalJSON handles deserialization of a BankAccount. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (b *BankAccount) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + b.ID = id + return nil + } + + type bankAccount BankAccount + var v bankAccount + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *b = BankAccount(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/bankaccount_service.go b/vendor/github.com/stripe/stripe-go/v82/bankaccount_service.go new file mode 100644 index 00000000..2259a1b1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/bankaccount_service.go @@ -0,0 +1,98 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1BankAccountService is used to invoke bankaccount related APIs. +type v1BankAccountService struct { + B Backend + Key string +} + +// New creates a new bank account +func (c v1BankAccountService) Create(ctx context.Context, params *BankAccountCreateParams) (*BankAccount, error) { + if params == nil { + params = &BankAccountCreateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/external_accounts", StringValue(params.Token), StringValue( + params.Customer), StringValue(params.Account)) + bankaccount := &BankAccount{} + err := c.B.Call(http.MethodPost, path, c.Key, params, bankaccount) + return bankaccount, err +} + +// Get returns the details of a bank account. +func (c v1BankAccountService) Retrieve(ctx context.Context, id string, params *BankAccountRetrieveParams) (*BankAccount, error) { + if params == nil { + params = &BankAccountRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/external_accounts/%s", StringValue(params.Account), id) + bankaccount := &BankAccount{} + err := c.B.Call(http.MethodGet, path, c.Key, params, bankaccount) + return bankaccount, err +} + +// Updates the metadata, account holder name, account holder type of a bank account belonging to +// a connected account and optionally sets it as the default for its currency. Other bank account +// details are not editable by design. +// +// You can only update bank accounts when [account.controller.requirement_collection is application, which includes Custom accounts](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection). +// +// You can re-enable a disabled bank account by performing an update call without providing any +// arguments or changes. +func (c v1BankAccountService) Update(ctx context.Context, id string, params *BankAccountUpdateParams) (*BankAccount, error) { + if params == nil { + params = &BankAccountUpdateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/external_accounts/%s", StringValue(params.Account), id) + bankaccount := &BankAccount{} + err := c.B.Call(http.MethodPost, path, c.Key, params, bankaccount) + return bankaccount, err +} + +// Delete a specified external account for a given account. +func (c v1BankAccountService) Delete(ctx context.Context, id string, params *BankAccountDeleteParams) (*BankAccount, error) { + if params == nil { + params = &BankAccountDeleteParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/external_accounts/%s", StringValue(params.Account), id) + bankaccount := &BankAccount{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, bankaccount) + return bankaccount, err +} +func (c v1BankAccountService) List(ctx context.Context, listParams *BankAccountListParams) Seq2[*BankAccount, error] { + if listParams == nil { + listParams = &BankAccountListParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/external_accounts", StringValue( + listParams.Account), StringValue(listParams.Customer)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*BankAccount, ListContainer, error) { + list := &BankAccountList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_alert.go b/vendor/github.com/stripe/stripe-go/v82/billing_alert.go new file mode 100644 index 00000000..c1e72259 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_alert.go @@ -0,0 +1,225 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Defines the type of the alert. +type BillingAlertAlertType string + +// List of values that BillingAlertAlertType can take +const ( + BillingAlertAlertTypeUsageThreshold BillingAlertAlertType = "usage_threshold" +) + +// Status of the alert. This can be active, inactive or archived. +type BillingAlertStatus string + +// List of values that BillingAlertStatus can take +const ( + BillingAlertStatusActive BillingAlertStatus = "active" + BillingAlertStatusArchived BillingAlertStatus = "archived" + BillingAlertStatusInactive BillingAlertStatus = "inactive" +) + +type BillingAlertUsageThresholdFilterType string + +// List of values that BillingAlertUsageThresholdFilterType can take +const ( + BillingAlertUsageThresholdFilterTypeCustomer BillingAlertUsageThresholdFilterType = "customer" +) + +// Defines how the alert will behave. +type BillingAlertUsageThresholdRecurrence string + +// List of values that BillingAlertUsageThresholdRecurrence can take +const ( + BillingAlertUsageThresholdRecurrenceOneTime BillingAlertUsageThresholdRecurrence = "one_time" +) + +// Lists billing active and inactive alerts +type BillingAlertListParams struct { + ListParams `form:"*"` + // Filter results to only include this type of alert. + AlertType *string `form:"alert_type"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Filter results to only include alerts with the given meter. + Meter *string `form:"meter"` +} + +// AddExpand appends a new field to expand. +func (p *BillingAlertListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The filters allows limiting the scope of this usage alert. You can only specify up to one filter at this time. +type BillingAlertUsageThresholdFilterParams struct { + // Limit the scope to this usage alert only to this customer. + Customer *string `form:"customer"` + // What type of filter is being applied to this usage alert. + Type *string `form:"type"` +} + +// The configuration of the usage threshold. +type BillingAlertUsageThresholdParams struct { + // The filters allows limiting the scope of this usage alert. You can only specify up to one filter at this time. + Filters []*BillingAlertUsageThresholdFilterParams `form:"filters"` + // Defines at which value the alert will fire. + GTE *int64 `form:"gte"` + // The [Billing Meter](https://docs.stripe.com/api/billing/meter) ID whose usage is monitored. + Meter *string `form:"meter"` + // Whether the alert should only fire only once, or once per billing cycle. + Recurrence *string `form:"recurrence"` +} + +// Creates a billing alert +type BillingAlertParams struct { + Params `form:"*"` + // The type of alert to create. + AlertType *string `form:"alert_type"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The title of the alert. + Title *string `form:"title"` + // The configuration of the usage threshold. + UsageThreshold *BillingAlertUsageThresholdParams `form:"usage_threshold"` +} + +// AddExpand appends a new field to expand. +func (p *BillingAlertParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Reactivates this alert, allowing it to trigger again. +type BillingAlertActivateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingAlertActivateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Archives this alert, removing it from the list view and APIs. This is non-reversible. +type BillingAlertArchiveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingAlertArchiveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Deactivates this alert, preventing it from triggering. +type BillingAlertDeactivateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingAlertDeactivateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The filters allows limiting the scope of this usage alert. You can only specify up to one filter at this time. +type BillingAlertCreateUsageThresholdFilterParams struct { + // Limit the scope to this usage alert only to this customer. + Customer *string `form:"customer"` + // What type of filter is being applied to this usage alert. + Type *string `form:"type"` +} + +// The configuration of the usage threshold. +type BillingAlertCreateUsageThresholdParams struct { + // The filters allows limiting the scope of this usage alert. You can only specify up to one filter at this time. + Filters []*BillingAlertCreateUsageThresholdFilterParams `form:"filters"` + // Defines at which value the alert will fire. + GTE *int64 `form:"gte"` + // The [Billing Meter](https://docs.stripe.com/api/billing/meter) ID whose usage is monitored. + Meter *string `form:"meter"` + // Whether the alert should only fire only once, or once per billing cycle. + Recurrence *string `form:"recurrence"` +} + +// Creates a billing alert +type BillingAlertCreateParams struct { + Params `form:"*"` + // The type of alert to create. + AlertType *string `form:"alert_type"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The title of the alert. + Title *string `form:"title"` + // The configuration of the usage threshold. + UsageThreshold *BillingAlertCreateUsageThresholdParams `form:"usage_threshold"` +} + +// AddExpand appends a new field to expand. +func (p *BillingAlertCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a billing alert given an ID +type BillingAlertRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingAlertRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The filters allow limiting the scope of this usage alert. You can only specify up to one filter at this time. +type BillingAlertUsageThresholdFilter struct { + // Limit the scope of the alert to this customer ID + Customer *Customer `json:"customer"` + Type BillingAlertUsageThresholdFilterType `json:"type"` +} + +// Encapsulates configuration of the alert to monitor usage on a specific [Billing Meter](https://stripe.com/docs/api/billing/meter). +type BillingAlertUsageThreshold struct { + // The filters allow limiting the scope of this usage alert. You can only specify up to one filter at this time. + Filters []*BillingAlertUsageThresholdFilter `json:"filters"` + // The value at which this alert will trigger. + GTE int64 `json:"gte"` + // The [Billing Meter](https://docs.stripe.com/api/billing/meter) ID whose usage is monitored. + Meter *BillingMeter `json:"meter"` + // Defines how the alert will behave. + Recurrence BillingAlertUsageThresholdRecurrence `json:"recurrence"` +} + +// A billing alert is a resource that notifies you when a certain usage threshold on a meter is crossed. For example, you might create a billing alert to notify you when a certain user made 100 API requests. +type BillingAlert struct { + APIResource + // Defines the type of the alert. + AlertType BillingAlertAlertType `json:"alert_type"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Status of the alert. This can be active, inactive or archived. + Status BillingAlertStatus `json:"status"` + // Title of the alert. + Title string `json:"title"` + // Encapsulates configuration of the alert to monitor usage on a specific [Billing Meter](https://stripe.com/docs/api/billing/meter). + UsageThreshold *BillingAlertUsageThreshold `json:"usage_threshold"` +} + +// BillingAlertList is a list of Alerts as retrieved from a list endpoint. +type BillingAlertList struct { + APIResource + ListMeta + Data []*BillingAlert `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_alert_service.go b/vendor/github.com/stripe/stripe-go/v82/billing_alert_service.go new file mode 100644 index 00000000..ffdb01e9 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_alert_service.go @@ -0,0 +1,96 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1BillingAlertService is used to invoke /v1/billing/alerts APIs. +type v1BillingAlertService struct { + B Backend + Key string +} + +// Creates a billing alert +func (c v1BillingAlertService) Create(ctx context.Context, params *BillingAlertCreateParams) (*BillingAlert, error) { + if params == nil { + params = &BillingAlertCreateParams{} + } + params.Context = ctx + alert := &BillingAlert{} + err := c.B.Call(http.MethodPost, "/v1/billing/alerts", c.Key, params, alert) + return alert, err +} + +// Retrieves a billing alert given an ID +func (c v1BillingAlertService) Retrieve(ctx context.Context, id string, params *BillingAlertRetrieveParams) (*BillingAlert, error) { + if params == nil { + params = &BillingAlertRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing/alerts/%s", id) + alert := &BillingAlert{} + err := c.B.Call(http.MethodGet, path, c.Key, params, alert) + return alert, err +} + +// Reactivates this alert, allowing it to trigger again. +func (c v1BillingAlertService) Activate(ctx context.Context, id string, params *BillingAlertActivateParams) (*BillingAlert, error) { + if params == nil { + params = &BillingAlertActivateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing/alerts/%s/activate", id) + alert := &BillingAlert{} + err := c.B.Call(http.MethodPost, path, c.Key, params, alert) + return alert, err +} + +// Archives this alert, removing it from the list view and APIs. This is non-reversible. +func (c v1BillingAlertService) Archive(ctx context.Context, id string, params *BillingAlertArchiveParams) (*BillingAlert, error) { + if params == nil { + params = &BillingAlertArchiveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing/alerts/%s/archive", id) + alert := &BillingAlert{} + err := c.B.Call(http.MethodPost, path, c.Key, params, alert) + return alert, err +} + +// Deactivates this alert, preventing it from triggering. +func (c v1BillingAlertService) Deactivate(ctx context.Context, id string, params *BillingAlertDeactivateParams) (*BillingAlert, error) { + if params == nil { + params = &BillingAlertDeactivateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing/alerts/%s/deactivate", id) + alert := &BillingAlert{} + err := c.B.Call(http.MethodPost, path, c.Key, params, alert) + return alert, err +} + +// Lists billing active and inactive alerts +func (c v1BillingAlertService) List(ctx context.Context, listParams *BillingAlertListParams) Seq2[*BillingAlert, error] { + if listParams == nil { + listParams = &BillingAlertListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*BillingAlert, ListContainer, error) { + list := &BillingAlertList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/billing/alerts", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_alerttriggered.go b/vendor/github.com/stripe/stripe-go/v82/billing_alerttriggered.go new file mode 100644 index 00000000..06554a4b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_alerttriggered.go @@ -0,0 +1,22 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +type BillingAlertTriggered struct { + // A billing alert is a resource that notifies you when a certain usage threshold on a meter is crossed. For example, you might create a billing alert to notify you when a certain user made 100 API requests. + Alert *BillingAlert `json:"alert"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // ID of customer for which the alert triggered + Customer string `json:"customer"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The value triggering the alert + Value int64 `json:"value"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_creditbalancesummary.go b/vendor/github.com/stripe/stripe-go/v82/billing_creditbalancesummary.go new file mode 100644 index 00000000..e06c6eb1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_creditbalancesummary.go @@ -0,0 +1,150 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The type of this amount. We currently only support `monetary` billing credits. +type BillingCreditBalanceSummaryBalanceAvailableBalanceType string + +// List of values that BillingCreditBalanceSummaryBalanceAvailableBalanceType can take +const ( + BillingCreditBalanceSummaryBalanceAvailableBalanceTypeMonetary BillingCreditBalanceSummaryBalanceAvailableBalanceType = "monetary" +) + +// The type of this amount. We currently only support `monetary` billing credits. +type BillingCreditBalanceSummaryBalanceLedgerBalanceType string + +// List of values that BillingCreditBalanceSummaryBalanceLedgerBalanceType can take +const ( + BillingCreditBalanceSummaryBalanceLedgerBalanceTypeMonetary BillingCreditBalanceSummaryBalanceLedgerBalanceType = "monetary" +) + +// A list of prices that the credit grant can apply to. We currently only support the `metered` prices. Cannot be used in combination with `price_type`. +type BillingCreditBalanceSummaryFilterApplicabilityScopePriceParams struct { + // The price ID this credit grant should apply to. + ID *string `form:"id"` +} + +// The billing credit applicability scope for which to fetch credit balance summary. +type BillingCreditBalanceSummaryFilterApplicabilityScopeParams struct { + // A list of prices that the credit grant can apply to. We currently only support the `metered` prices. Cannot be used in combination with `price_type`. + Prices []*BillingCreditBalanceSummaryFilterApplicabilityScopePriceParams `form:"prices"` + // The price type that credit grants can apply to. We currently only support the `metered` price type. Cannot be used in combination with `prices`. + PriceType *string `form:"price_type"` +} + +// The filter criteria for the credit balance summary. +type BillingCreditBalanceSummaryFilterParams struct { + // The billing credit applicability scope for which to fetch credit balance summary. + ApplicabilityScope *BillingCreditBalanceSummaryFilterApplicabilityScopeParams `form:"applicability_scope"` + // The credit grant for which to fetch credit balance summary. + CreditGrant *string `form:"credit_grant"` + // Specify the type of this filter. + Type *string `form:"type"` +} + +// Retrieves the credit balance summary for a customer. +type BillingCreditBalanceSummaryParams struct { + Params `form:"*"` + // The customer for which to fetch credit balance summary. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The filter criteria for the credit balance summary. + Filter *BillingCreditBalanceSummaryFilterParams `form:"filter"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditBalanceSummaryParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A list of prices that the credit grant can apply to. We currently only support the `metered` prices. Cannot be used in combination with `price_type`. +type BillingCreditBalanceSummaryRetrieveFilterApplicabilityScopePriceParams struct { + // The price ID this credit grant should apply to. + ID *string `form:"id"` +} + +// The billing credit applicability scope for which to fetch credit balance summary. +type BillingCreditBalanceSummaryRetrieveFilterApplicabilityScopeParams struct { + // A list of prices that the credit grant can apply to. We currently only support the `metered` prices. Cannot be used in combination with `price_type`. + Prices []*BillingCreditBalanceSummaryRetrieveFilterApplicabilityScopePriceParams `form:"prices"` + // The price type that credit grants can apply to. We currently only support the `metered` price type. Cannot be used in combination with `prices`. + PriceType *string `form:"price_type"` +} + +// The filter criteria for the credit balance summary. +type BillingCreditBalanceSummaryRetrieveFilterParams struct { + // The billing credit applicability scope for which to fetch credit balance summary. + ApplicabilityScope *BillingCreditBalanceSummaryRetrieveFilterApplicabilityScopeParams `form:"applicability_scope"` + // The credit grant for which to fetch credit balance summary. + CreditGrant *string `form:"credit_grant"` + // Specify the type of this filter. + Type *string `form:"type"` +} + +// Retrieves the credit balance summary for a customer. +type BillingCreditBalanceSummaryRetrieveParams struct { + Params `form:"*"` + // The customer for which to fetch credit balance summary. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The filter criteria for the credit balance summary. + Filter *BillingCreditBalanceSummaryRetrieveFilterParams `form:"filter"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditBalanceSummaryRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The monetary amount. +type BillingCreditBalanceSummaryBalanceAvailableBalanceMonetary struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // A positive integer representing the amount. + Value int64 `json:"value"` +} +type BillingCreditBalanceSummaryBalanceAvailableBalance struct { + // The monetary amount. + Monetary *BillingCreditBalanceSummaryBalanceAvailableBalanceMonetary `json:"monetary"` + // The type of this amount. We currently only support `monetary` billing credits. + Type BillingCreditBalanceSummaryBalanceAvailableBalanceType `json:"type"` +} + +// The monetary amount. +type BillingCreditBalanceSummaryBalanceLedgerBalanceMonetary struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // A positive integer representing the amount. + Value int64 `json:"value"` +} +type BillingCreditBalanceSummaryBalanceLedgerBalance struct { + // The monetary amount. + Monetary *BillingCreditBalanceSummaryBalanceLedgerBalanceMonetary `json:"monetary"` + // The type of this amount. We currently only support `monetary` billing credits. + Type BillingCreditBalanceSummaryBalanceLedgerBalanceType `json:"type"` +} + +// The billing credit balances. One entry per credit grant currency. If a customer only has credit grants in a single currency, then this will have a single balance entry. +type BillingCreditBalanceSummaryBalance struct { + AvailableBalance *BillingCreditBalanceSummaryBalanceAvailableBalance `json:"available_balance"` + LedgerBalance *BillingCreditBalanceSummaryBalanceLedgerBalance `json:"ledger_balance"` +} + +// Indicates the billing credit balance for billing credits granted to a customer. +type BillingCreditBalanceSummary struct { + APIResource + // The billing credit balances. One entry per credit grant currency. If a customer only has credit grants in a single currency, then this will have a single balance entry. + Balances []*BillingCreditBalanceSummaryBalance `json:"balances"` + // The customer the balance is for. + Customer *Customer `json:"customer"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_creditbalancesummary_service.go b/vendor/github.com/stripe/stripe-go/v82/billing_creditbalancesummary_service.go new file mode 100644 index 00000000..df0b2b1d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_creditbalancesummary_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1BillingCreditBalanceSummaryService is used to invoke /v1/billing/credit_balance_summary APIs. +type v1BillingCreditBalanceSummaryService struct { + B Backend + Key string +} + +// Retrieves the credit balance summary for a customer. +func (c v1BillingCreditBalanceSummaryService) Retrieve(ctx context.Context, params *BillingCreditBalanceSummaryRetrieveParams) (*BillingCreditBalanceSummary, error) { + if params == nil { + params = &BillingCreditBalanceSummaryRetrieveParams{} + } + params.Context = ctx + creditbalancesummary := &BillingCreditBalanceSummary{} + err := c.B.Call( + http.MethodGet, "/v1/billing/credit_balance_summary", c.Key, params, creditbalancesummary) + return creditbalancesummary, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_creditbalancetransaction.go b/vendor/github.com/stripe/stripe-go/v82/billing_creditbalancetransaction.go new file mode 100644 index 00000000..e7ad0b40 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_creditbalancetransaction.go @@ -0,0 +1,206 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The type of this amount. We currently only support `monetary` billing credits. +type BillingCreditBalanceTransactionCreditAmountType string + +// List of values that BillingCreditBalanceTransactionCreditAmountType can take +const ( + BillingCreditBalanceTransactionCreditAmountTypeMonetary BillingCreditBalanceTransactionCreditAmountType = "monetary" +) + +// The type of credit transaction. +type BillingCreditBalanceTransactionCreditType string + +// List of values that BillingCreditBalanceTransactionCreditType can take +const ( + BillingCreditBalanceTransactionCreditTypeCreditsApplicationInvoiceVoided BillingCreditBalanceTransactionCreditType = "credits_application_invoice_voided" + BillingCreditBalanceTransactionCreditTypeCreditsGranted BillingCreditBalanceTransactionCreditType = "credits_granted" +) + +// The type of this amount. We currently only support `monetary` billing credits. +type BillingCreditBalanceTransactionDebitAmountType string + +// List of values that BillingCreditBalanceTransactionDebitAmountType can take +const ( + BillingCreditBalanceTransactionDebitAmountTypeMonetary BillingCreditBalanceTransactionDebitAmountType = "monetary" +) + +// The type of debit transaction. +type BillingCreditBalanceTransactionDebitType string + +// List of values that BillingCreditBalanceTransactionDebitType can take +const ( + BillingCreditBalanceTransactionDebitTypeCreditsApplied BillingCreditBalanceTransactionDebitType = "credits_applied" + BillingCreditBalanceTransactionDebitTypeCreditsExpired BillingCreditBalanceTransactionDebitType = "credits_expired" + BillingCreditBalanceTransactionDebitTypeCreditsVoided BillingCreditBalanceTransactionDebitType = "credits_voided" +) + +// The type of credit balance transaction (credit or debit). +type BillingCreditBalanceTransactionType string + +// List of values that BillingCreditBalanceTransactionType can take +const ( + BillingCreditBalanceTransactionTypeCredit BillingCreditBalanceTransactionType = "credit" + BillingCreditBalanceTransactionTypeDebit BillingCreditBalanceTransactionType = "debit" +) + +// Retrieve a list of credit balance transactions. +type BillingCreditBalanceTransactionListParams struct { + ListParams `form:"*"` + // The credit grant for which to fetch credit balance transactions. + CreditGrant *string `form:"credit_grant"` + // The customer for which to fetch credit balance transactions. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditBalanceTransactionListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a credit balance transaction. +type BillingCreditBalanceTransactionParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditBalanceTransactionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a credit balance transaction. +type BillingCreditBalanceTransactionRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditBalanceTransactionRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The monetary amount. +type BillingCreditBalanceTransactionCreditAmountMonetary struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // A positive integer representing the amount. + Value int64 `json:"value"` +} +type BillingCreditBalanceTransactionCreditAmount struct { + // The monetary amount. + Monetary *BillingCreditBalanceTransactionCreditAmountMonetary `json:"monetary"` + // The type of this amount. We currently only support `monetary` billing credits. + Type BillingCreditBalanceTransactionCreditAmountType `json:"type"` +} + +// Details of the invoice to which the reinstated credits were originally applied. Only present if `type` is `credits_application_invoice_voided`. +type BillingCreditBalanceTransactionCreditCreditsApplicationInvoiceVoided struct { + // The invoice to which the reinstated billing credits were originally applied. + Invoice *Invoice `json:"invoice"` + // The invoice line item to which the reinstated billing credits were originally applied. + InvoiceLineItem string `json:"invoice_line_item"` +} + +// Credit details for this credit balance transaction. Only present if type is `credit`. +type BillingCreditBalanceTransactionCredit struct { + Amount *BillingCreditBalanceTransactionCreditAmount `json:"amount"` + // Details of the invoice to which the reinstated credits were originally applied. Only present if `type` is `credits_application_invoice_voided`. + CreditsApplicationInvoiceVoided *BillingCreditBalanceTransactionCreditCreditsApplicationInvoiceVoided `json:"credits_application_invoice_voided"` + // The type of credit transaction. + Type BillingCreditBalanceTransactionCreditType `json:"type"` +} + +// The monetary amount. +type BillingCreditBalanceTransactionDebitAmountMonetary struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // A positive integer representing the amount. + Value int64 `json:"value"` +} +type BillingCreditBalanceTransactionDebitAmount struct { + // The monetary amount. + Monetary *BillingCreditBalanceTransactionDebitAmountMonetary `json:"monetary"` + // The type of this amount. We currently only support `monetary` billing credits. + Type BillingCreditBalanceTransactionDebitAmountType `json:"type"` +} + +// Details of how the billing credits were applied to an invoice. Only present if `type` is `credits_applied`. +type BillingCreditBalanceTransactionDebitCreditsApplied struct { + // The invoice to which the billing credits were applied. + Invoice *Invoice `json:"invoice"` + // The invoice line item to which the billing credits were applied. + InvoiceLineItem string `json:"invoice_line_item"` +} + +// Debit details for this credit balance transaction. Only present if type is `debit`. +type BillingCreditBalanceTransactionDebit struct { + Amount *BillingCreditBalanceTransactionDebitAmount `json:"amount"` + // Details of how the billing credits were applied to an invoice. Only present if `type` is `credits_applied`. + CreditsApplied *BillingCreditBalanceTransactionDebitCreditsApplied `json:"credits_applied"` + // The type of debit transaction. + Type BillingCreditBalanceTransactionDebitType `json:"type"` +} + +// A credit balance transaction is a resource representing a transaction (either a credit or a debit) against an existing credit grant. +type BillingCreditBalanceTransaction struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Credit details for this credit balance transaction. Only present if type is `credit`. + Credit *BillingCreditBalanceTransactionCredit `json:"credit"` + // The credit grant associated with this credit balance transaction. + CreditGrant *BillingCreditGrant `json:"credit_grant"` + // Debit details for this credit balance transaction. Only present if type is `debit`. + Debit *BillingCreditBalanceTransactionDebit `json:"debit"` + // The effective time of this credit balance transaction. + EffectiveAt int64 `json:"effective_at"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // ID of the test clock this credit balance transaction belongs to. + TestClock *TestHelpersTestClock `json:"test_clock"` + // The type of credit balance transaction (credit or debit). + Type BillingCreditBalanceTransactionType `json:"type"` +} + +// BillingCreditBalanceTransactionList is a list of CreditBalanceTransactions as retrieved from a list endpoint. +type BillingCreditBalanceTransactionList struct { + APIResource + ListMeta + Data []*BillingCreditBalanceTransaction `json:"data"` +} + +// UnmarshalJSON handles deserialization of a BillingCreditBalanceTransaction. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (b *BillingCreditBalanceTransaction) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + b.ID = id + return nil + } + + type billingCreditBalanceTransaction BillingCreditBalanceTransaction + var v billingCreditBalanceTransaction + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *b = BillingCreditBalanceTransaction(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_creditbalancetransaction_service.go b/vendor/github.com/stripe/stripe-go/v82/billing_creditbalancetransaction_service.go new file mode 100644 index 00000000..185539cf --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_creditbalancetransaction_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1BillingCreditBalanceTransactionService is used to invoke /v1/billing/credit_balance_transactions APIs. +type v1BillingCreditBalanceTransactionService struct { + B Backend + Key string +} + +// Retrieves a credit balance transaction. +func (c v1BillingCreditBalanceTransactionService) Retrieve(ctx context.Context, id string, params *BillingCreditBalanceTransactionRetrieveParams) (*BillingCreditBalanceTransaction, error) { + if params == nil { + params = &BillingCreditBalanceTransactionRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing/credit_balance_transactions/%s", id) + creditbalancetransaction := &BillingCreditBalanceTransaction{} + err := c.B.Call(http.MethodGet, path, c.Key, params, creditbalancetransaction) + return creditbalancetransaction, err +} + +// Retrieve a list of credit balance transactions. +func (c v1BillingCreditBalanceTransactionService) List(ctx context.Context, listParams *BillingCreditBalanceTransactionListParams) Seq2[*BillingCreditBalanceTransaction, error] { + if listParams == nil { + listParams = &BillingCreditBalanceTransactionListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*BillingCreditBalanceTransaction, ListContainer, error) { + list := &BillingCreditBalanceTransactionList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/billing/credit_balance_transactions", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_creditgrant.go b/vendor/github.com/stripe/stripe-go/v82/billing_creditgrant.go new file mode 100644 index 00000000..769e84e1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_creditgrant.go @@ -0,0 +1,351 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The type of this amount. We currently only support `monetary` billing credits. +type BillingCreditGrantAmountType string + +// List of values that BillingCreditGrantAmountType can take +const ( + BillingCreditGrantAmountTypeMonetary BillingCreditGrantAmountType = "monetary" +) + +// The price type that credit grants can apply to. We currently only support the `metered` price type. This refers to prices that have a [Billing Meter](https://docs.stripe.com/api/billing/meter) attached to them. Cannot be used in combination with `prices`. +type BillingCreditGrantApplicabilityConfigScopePriceType string + +// List of values that BillingCreditGrantApplicabilityConfigScopePriceType can take +const ( + BillingCreditGrantApplicabilityConfigScopePriceTypeMetered BillingCreditGrantApplicabilityConfigScopePriceType = "metered" +) + +// The category of this credit grant. This is for tracking purposes and isn't displayed to the customer. +type BillingCreditGrantCategory string + +// List of values that BillingCreditGrantCategory can take +const ( + BillingCreditGrantCategoryPaid BillingCreditGrantCategory = "paid" + BillingCreditGrantCategoryPromotional BillingCreditGrantCategory = "promotional" +) + +// Retrieve a list of credit grants. +type BillingCreditGrantListParams struct { + ListParams `form:"*"` + // Only return credit grants for this customer. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditGrantListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The monetary amount. +type BillingCreditGrantAmountMonetaryParams struct { + // Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) of the `value` parameter. + Currency *string `form:"currency"` + // A positive integer representing the amount of the credit grant. + Value *int64 `form:"value"` +} + +// Amount of this credit grant. +type BillingCreditGrantAmountParams struct { + // The monetary amount. + Monetary *BillingCreditGrantAmountMonetaryParams `form:"monetary"` + // Specify the type of this amount. We currently only support `monetary` billing credits. + Type *string `form:"type"` +} + +// A list of prices that the credit grant can apply to. We currently only support the `metered` prices. Cannot be used in combination with `price_type`. +type BillingCreditGrantApplicabilityConfigScopePriceParams struct { + // The price ID this credit grant should apply to. + ID *string `form:"id"` +} + +// Specify the scope of this applicability config. +type BillingCreditGrantApplicabilityConfigScopeParams struct { + // A list of prices that the credit grant can apply to. We currently only support the `metered` prices. Cannot be used in combination with `price_type`. + Prices []*BillingCreditGrantApplicabilityConfigScopePriceParams `form:"prices"` + // The price type that credit grants can apply to. We currently only support the `metered` price type. Cannot be used in combination with `prices`. + PriceType *string `form:"price_type"` +} + +// Configuration specifying what this credit grant applies to. We currently only support `metered` prices that have a [Billing Meter](https://docs.stripe.com/api/billing/meter) attached to them. +type BillingCreditGrantApplicabilityConfigParams struct { + // Specify the scope of this applicability config. + Scope *BillingCreditGrantApplicabilityConfigScopeParams `form:"scope"` +} + +// Creates a credit grant. +type BillingCreditGrantParams struct { + Params `form:"*"` + // Amount of this credit grant. + Amount *BillingCreditGrantAmountParams `form:"amount"` + // Configuration specifying what this credit grant applies to. We currently only support `metered` prices that have a [Billing Meter](https://docs.stripe.com/api/billing/meter) attached to them. + ApplicabilityConfig *BillingCreditGrantApplicabilityConfigParams `form:"applicability_config"` + // The category of this credit grant. + Category *string `form:"category"` + // ID of the customer to receive the billing credits. + Customer *string `form:"customer"` + // The time when the billing credits become effective-when they're eligible for use. It defaults to the current timestamp if not specified. + EffectiveAt *int64 `form:"effective_at"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The time when the billing credits created by this credit grant expire. If set to empty, the billing credits never expire. + ExpiresAt *int64 `form:"expires_at"` + // Set of key-value pairs that you can attach to an object. You can use this to store additional information about the object (for example, cost basis) in a structured format. + Metadata map[string]string `form:"metadata"` + // A descriptive name shown in the Dashboard. + Name *string `form:"name"` + // The desired priority for applying this credit grant. If not specified, it will be set to the default value of 50. The highest priority is 0 and the lowest is 100. + Priority *int64 `form:"priority"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditGrantParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *BillingCreditGrantParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Expires a credit grant. +type BillingCreditGrantExpireParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditGrantExpireParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Voids a credit grant. +type BillingCreditGrantVoidGrantParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditGrantVoidGrantParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The monetary amount. +type BillingCreditGrantCreateAmountMonetaryParams struct { + // Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) of the `value` parameter. + Currency *string `form:"currency"` + // A positive integer representing the amount of the credit grant. + Value *int64 `form:"value"` +} + +// Amount of this credit grant. +type BillingCreditGrantCreateAmountParams struct { + // The monetary amount. + Monetary *BillingCreditGrantCreateAmountMonetaryParams `form:"monetary"` + // Specify the type of this amount. We currently only support `monetary` billing credits. + Type *string `form:"type"` +} + +// A list of prices that the credit grant can apply to. We currently only support the `metered` prices. Cannot be used in combination with `price_type`. +type BillingCreditGrantCreateApplicabilityConfigScopePriceParams struct { + // The price ID this credit grant should apply to. + ID *string `form:"id"` +} + +// Specify the scope of this applicability config. +type BillingCreditGrantCreateApplicabilityConfigScopeParams struct { + // A list of prices that the credit grant can apply to. We currently only support the `metered` prices. Cannot be used in combination with `price_type`. + Prices []*BillingCreditGrantCreateApplicabilityConfigScopePriceParams `form:"prices"` + // The price type that credit grants can apply to. We currently only support the `metered` price type. Cannot be used in combination with `prices`. + PriceType *string `form:"price_type"` +} + +// Configuration specifying what this credit grant applies to. We currently only support `metered` prices that have a [Billing Meter](https://docs.stripe.com/api/billing/meter) attached to them. +type BillingCreditGrantCreateApplicabilityConfigParams struct { + // Specify the scope of this applicability config. + Scope *BillingCreditGrantCreateApplicabilityConfigScopeParams `form:"scope"` +} + +// Creates a credit grant. +type BillingCreditGrantCreateParams struct { + Params `form:"*"` + // Amount of this credit grant. + Amount *BillingCreditGrantCreateAmountParams `form:"amount"` + // Configuration specifying what this credit grant applies to. We currently only support `metered` prices that have a [Billing Meter](https://docs.stripe.com/api/billing/meter) attached to them. + ApplicabilityConfig *BillingCreditGrantCreateApplicabilityConfigParams `form:"applicability_config"` + // The category of this credit grant. + Category *string `form:"category"` + // ID of the customer to receive the billing credits. + Customer *string `form:"customer"` + // The time when the billing credits become effective-when they're eligible for use. It defaults to the current timestamp if not specified. + EffectiveAt *int64 `form:"effective_at"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The time when the billing credits expire. If not specified, the billing credits don't expire. + ExpiresAt *int64 `form:"expires_at"` + // Set of key-value pairs that you can attach to an object. You can use this to store additional information about the object (for example, cost basis) in a structured format. + Metadata map[string]string `form:"metadata"` + // A descriptive name shown in the Dashboard. + Name *string `form:"name"` + // The desired priority for applying this credit grant. If not specified, it will be set to the default value of 50. The highest priority is 0 and the lowest is 100. + Priority *int64 `form:"priority"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditGrantCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *BillingCreditGrantCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves a credit grant. +type BillingCreditGrantRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditGrantRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates a credit grant. +type BillingCreditGrantUpdateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The time when the billing credits created by this credit grant expire. If set to empty, the billing credits never expire. + ExpiresAt *int64 `form:"expires_at"` + // Set of key-value pairs you can attach to an object. You can use this to store additional information about the object (for example, cost basis) in a structured format. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *BillingCreditGrantUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *BillingCreditGrantUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The monetary amount. +type BillingCreditGrantAmountMonetary struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // A positive integer representing the amount. + Value int64 `json:"value"` +} +type BillingCreditGrantAmount struct { + // The monetary amount. + Monetary *BillingCreditGrantAmountMonetary `json:"monetary"` + // The type of this amount. We currently only support `monetary` billing credits. + Type BillingCreditGrantAmountType `json:"type"` +} + +// The prices that credit grants can apply to. We currently only support `metered` prices. This refers to prices that have a [Billing Meter](https://docs.stripe.com/api/billing/meter) attached to them. Cannot be used in combination with `price_type`. +type BillingCreditGrantApplicabilityConfigScopePrice struct { + // Unique identifier for the object. + ID string `json:"id"` +} +type BillingCreditGrantApplicabilityConfigScope struct { + // The prices that credit grants can apply to. We currently only support `metered` prices. This refers to prices that have a [Billing Meter](https://docs.stripe.com/api/billing/meter) attached to them. Cannot be used in combination with `price_type`. + Prices []*BillingCreditGrantApplicabilityConfigScopePrice `json:"prices"` + // The price type that credit grants can apply to. We currently only support the `metered` price type. This refers to prices that have a [Billing Meter](https://docs.stripe.com/api/billing/meter) attached to them. Cannot be used in combination with `prices`. + PriceType BillingCreditGrantApplicabilityConfigScopePriceType `json:"price_type"` +} +type BillingCreditGrantApplicabilityConfig struct { + Scope *BillingCreditGrantApplicabilityConfigScope `json:"scope"` +} + +// A credit grant is an API resource that documents the allocation of some billing credits to a customer. +// +// Related guide: [Billing credits](https://docs.stripe.com/billing/subscriptions/usage-based/billing-credits) +type BillingCreditGrant struct { + APIResource + Amount *BillingCreditGrantAmount `json:"amount"` + ApplicabilityConfig *BillingCreditGrantApplicabilityConfig `json:"applicability_config"` + // The category of this credit grant. This is for tracking purposes and isn't displayed to the customer. + Category BillingCreditGrantCategory `json:"category"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // ID of the customer receiving the billing credits. + Customer *Customer `json:"customer"` + // The time when the billing credits become effective-when they're eligible for use. + EffectiveAt int64 `json:"effective_at"` + // The time when the billing credits expire. If not present, the billing credits don't expire. + ExpiresAt int64 `json:"expires_at"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // A descriptive name shown in dashboard. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The priority for applying this credit grant. The highest priority is 0 and the lowest is 100. + Priority int64 `json:"priority"` + // ID of the test clock this credit grant belongs to. + TestClock *TestHelpersTestClock `json:"test_clock"` + // Time at which the object was last updated. Measured in seconds since the Unix epoch. + Updated int64 `json:"updated"` + // The time when this credit grant was voided. If not present, the credit grant hasn't been voided. + VoidedAt int64 `json:"voided_at"` +} + +// BillingCreditGrantList is a list of CreditGrants as retrieved from a list endpoint. +type BillingCreditGrantList struct { + APIResource + ListMeta + Data []*BillingCreditGrant `json:"data"` +} + +// UnmarshalJSON handles deserialization of a BillingCreditGrant. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (b *BillingCreditGrant) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + b.ID = id + return nil + } + + type billingCreditGrant BillingCreditGrant + var v billingCreditGrant + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *b = BillingCreditGrant(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_creditgrant_service.go b/vendor/github.com/stripe/stripe-go/v82/billing_creditgrant_service.go new file mode 100644 index 00000000..419eb20b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_creditgrant_service.go @@ -0,0 +1,97 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1BillingCreditGrantService is used to invoke /v1/billing/credit_grants APIs. +type v1BillingCreditGrantService struct { + B Backend + Key string +} + +// Creates a credit grant. +func (c v1BillingCreditGrantService) Create(ctx context.Context, params *BillingCreditGrantCreateParams) (*BillingCreditGrant, error) { + if params == nil { + params = &BillingCreditGrantCreateParams{} + } + params.Context = ctx + creditgrant := &BillingCreditGrant{} + err := c.B.Call( + http.MethodPost, "/v1/billing/credit_grants", c.Key, params, creditgrant) + return creditgrant, err +} + +// Retrieves a credit grant. +func (c v1BillingCreditGrantService) Retrieve(ctx context.Context, id string, params *BillingCreditGrantRetrieveParams) (*BillingCreditGrant, error) { + if params == nil { + params = &BillingCreditGrantRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing/credit_grants/%s", id) + creditgrant := &BillingCreditGrant{} + err := c.B.Call(http.MethodGet, path, c.Key, params, creditgrant) + return creditgrant, err +} + +// Updates a credit grant. +func (c v1BillingCreditGrantService) Update(ctx context.Context, id string, params *BillingCreditGrantUpdateParams) (*BillingCreditGrant, error) { + if params == nil { + params = &BillingCreditGrantUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing/credit_grants/%s", id) + creditgrant := &BillingCreditGrant{} + err := c.B.Call(http.MethodPost, path, c.Key, params, creditgrant) + return creditgrant, err +} + +// Expires a credit grant. +func (c v1BillingCreditGrantService) Expire(ctx context.Context, id string, params *BillingCreditGrantExpireParams) (*BillingCreditGrant, error) { + if params == nil { + params = &BillingCreditGrantExpireParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing/credit_grants/%s/expire", id) + creditgrant := &BillingCreditGrant{} + err := c.B.Call(http.MethodPost, path, c.Key, params, creditgrant) + return creditgrant, err +} + +// Voids a credit grant. +func (c v1BillingCreditGrantService) VoidGrant(ctx context.Context, id string, params *BillingCreditGrantVoidGrantParams) (*BillingCreditGrant, error) { + if params == nil { + params = &BillingCreditGrantVoidGrantParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing/credit_grants/%s/void", id) + creditgrant := &BillingCreditGrant{} + err := c.B.Call(http.MethodPost, path, c.Key, params, creditgrant) + return creditgrant, err +} + +// Retrieve a list of credit grants. +func (c v1BillingCreditGrantService) List(ctx context.Context, listParams *BillingCreditGrantListParams) Seq2[*BillingCreditGrant, error] { + if listParams == nil { + listParams = &BillingCreditGrantListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*BillingCreditGrant, ListContainer, error) { + list := &BillingCreditGrantList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/billing/credit_grants", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_meter.go b/vendor/github.com/stripe/stripe-go/v82/billing_meter.go new file mode 100644 index 00000000..1e7cbc24 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_meter.go @@ -0,0 +1,271 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The method for mapping a meter event to a customer. +type BillingMeterCustomerMappingType string + +// List of values that BillingMeterCustomerMappingType can take +const ( + BillingMeterCustomerMappingTypeByID BillingMeterCustomerMappingType = "by_id" +) + +// Specifies how events are aggregated. +type BillingMeterDefaultAggregationFormula string + +// List of values that BillingMeterDefaultAggregationFormula can take +const ( + BillingMeterDefaultAggregationFormulaCount BillingMeterDefaultAggregationFormula = "count" + BillingMeterDefaultAggregationFormulaLast BillingMeterDefaultAggregationFormula = "last" + BillingMeterDefaultAggregationFormulaSum BillingMeterDefaultAggregationFormula = "sum" +) + +// The time window to pre-aggregate meter events for, if any. +type BillingMeterEventTimeWindow string + +// List of values that BillingMeterEventTimeWindow can take +const ( + BillingMeterEventTimeWindowDay BillingMeterEventTimeWindow = "day" + BillingMeterEventTimeWindowHour BillingMeterEventTimeWindow = "hour" +) + +// The meter's status. +type BillingMeterStatus string + +// List of values that BillingMeterStatus can take +const ( + BillingMeterStatusActive BillingMeterStatus = "active" + BillingMeterStatusInactive BillingMeterStatus = "inactive" +) + +// Retrieve a list of billing meters. +type BillingMeterListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Filter results to only include meters with the given status. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *BillingMeterListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Fields that specify how to map a meter event to a customer. +type BillingMeterCustomerMappingParams struct { + // The key in the meter event payload to use for mapping the event to a customer. + EventPayloadKey *string `form:"event_payload_key"` + // The method for mapping a meter event to a customer. Must be `by_id`. + Type *string `form:"type"` +} + +// The default settings to aggregate a meter's events with. +type BillingMeterDefaultAggregationParams struct { + // Specifies how events are aggregated. Allowed values are `count` to count the number of events, `sum` to sum each event's value and `last` to take the last event's value in the window. + Formula *string `form:"formula"` +} + +// Fields that specify how to calculate a meter event's value. +type BillingMeterValueSettingsParams struct { + // The key in the usage event payload to use as the value for this meter. For example, if the event payload contains usage on a `bytes_used` field, then set the event_payload_key to "bytes_used". + EventPayloadKey *string `form:"event_payload_key"` +} + +// Creates a billing meter. +type BillingMeterParams struct { + Params `form:"*"` + // Fields that specify how to map a meter event to a customer. + CustomerMapping *BillingMeterCustomerMappingParams `form:"customer_mapping"` + // The default settings to aggregate a meter's events with. + DefaultAggregation *BillingMeterDefaultAggregationParams `form:"default_aggregation"` + // The meter's name. Not visible to the customer. + DisplayName *string `form:"display_name"` + // The name of the meter event to record usage for. Corresponds with the `event_name` field on meter events. + EventName *string `form:"event_name"` + // The time window to pre-aggregate meter events for, if any. + EventTimeWindow *string `form:"event_time_window"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Fields that specify how to calculate a meter event's value. + ValueSettings *BillingMeterValueSettingsParams `form:"value_settings"` +} + +// AddExpand appends a new field to expand. +func (p *BillingMeterParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When a meter is deactivated, no more meter events will be accepted for this meter. You can't attach a deactivated meter to a price. +type BillingMeterDeactivateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingMeterDeactivateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When a meter is reactivated, events for this meter can be accepted and you can attach the meter to a price. +type BillingMeterReactivateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingMeterReactivateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Fields that specify how to map a meter event to a customer. +type BillingMeterCreateCustomerMappingParams struct { + // The key in the meter event payload to use for mapping the event to a customer. + EventPayloadKey *string `form:"event_payload_key"` + // The method for mapping a meter event to a customer. Must be `by_id`. + Type *string `form:"type"` +} + +// The default settings to aggregate a meter's events with. +type BillingMeterCreateDefaultAggregationParams struct { + // Specifies how events are aggregated. Allowed values are `count` to count the number of events, `sum` to sum each event's value and `last` to take the last event's value in the window. + Formula *string `form:"formula"` +} + +// Fields that specify how to calculate a meter event's value. +type BillingMeterCreateValueSettingsParams struct { + // The key in the usage event payload to use as the value for this meter. For example, if the event payload contains usage on a `bytes_used` field, then set the event_payload_key to "bytes_used". + EventPayloadKey *string `form:"event_payload_key"` +} + +// Creates a billing meter. +type BillingMeterCreateParams struct { + Params `form:"*"` + // Fields that specify how to map a meter event to a customer. + CustomerMapping *BillingMeterCreateCustomerMappingParams `form:"customer_mapping"` + // The default settings to aggregate a meter's events with. + DefaultAggregation *BillingMeterCreateDefaultAggregationParams `form:"default_aggregation"` + // The meter's name. Not visible to the customer. + DisplayName *string `form:"display_name"` + // The name of the meter event to record usage for. Corresponds with the `event_name` field on meter events. + EventName *string `form:"event_name"` + // The time window to pre-aggregate meter events for, if any. + EventTimeWindow *string `form:"event_time_window"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Fields that specify how to calculate a meter event's value. + ValueSettings *BillingMeterCreateValueSettingsParams `form:"value_settings"` +} + +// AddExpand appends a new field to expand. +func (p *BillingMeterCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a billing meter given an ID. +type BillingMeterRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingMeterRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates a billing meter. +type BillingMeterUpdateParams struct { + Params `form:"*"` + // The meter's name. Not visible to the customer. + DisplayName *string `form:"display_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingMeterUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type BillingMeterCustomerMapping struct { + // The key in the meter event payload to use for mapping the event to a customer. + EventPayloadKey string `json:"event_payload_key"` + // The method for mapping a meter event to a customer. + Type BillingMeterCustomerMappingType `json:"type"` +} +type BillingMeterDefaultAggregation struct { + // Specifies how events are aggregated. + Formula BillingMeterDefaultAggregationFormula `json:"formula"` +} +type BillingMeterStatusTransitions struct { + // The time the meter was deactivated, if any. Measured in seconds since Unix epoch. + DeactivatedAt int64 `json:"deactivated_at"` +} +type BillingMeterValueSettings struct { + // The key in the meter event payload to use as the value for this meter. + EventPayloadKey string `json:"event_payload_key"` +} + +// Meters specify how to aggregate meter events over a billing period. Meter events represent the actions that customers take in your system. Meters attach to prices and form the basis of the bill. +// +// Related guide: [Usage based billing](https://docs.stripe.com/billing/subscriptions/usage-based) +type BillingMeter struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + CustomerMapping *BillingMeterCustomerMapping `json:"customer_mapping"` + DefaultAggregation *BillingMeterDefaultAggregation `json:"default_aggregation"` + // The meter's name. + DisplayName string `json:"display_name"` + // The name of the meter event to record usage for. Corresponds with the `event_name` field on meter events. + EventName string `json:"event_name"` + // The time window to pre-aggregate meter events for, if any. + EventTimeWindow BillingMeterEventTimeWindow `json:"event_time_window"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The meter's status. + Status BillingMeterStatus `json:"status"` + StatusTransitions *BillingMeterStatusTransitions `json:"status_transitions"` + // Time at which the object was last updated. Measured in seconds since the Unix epoch. + Updated int64 `json:"updated"` + ValueSettings *BillingMeterValueSettings `json:"value_settings"` +} + +// BillingMeterList is a list of Meters as retrieved from a list endpoint. +type BillingMeterList struct { + APIResource + ListMeta + Data []*BillingMeter `json:"data"` +} + +// UnmarshalJSON handles deserialization of a BillingMeter. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (b *BillingMeter) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + b.ID = id + return nil + } + + type billingMeter BillingMeter + var v billingMeter + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *b = BillingMeter(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_meter_service.go b/vendor/github.com/stripe/stripe-go/v82/billing_meter_service.go new file mode 100644 index 00000000..6c4b5b3e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_meter_service.go @@ -0,0 +1,96 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1BillingMeterService is used to invoke /v1/billing/meters APIs. +type v1BillingMeterService struct { + B Backend + Key string +} + +// Creates a billing meter. +func (c v1BillingMeterService) Create(ctx context.Context, params *BillingMeterCreateParams) (*BillingMeter, error) { + if params == nil { + params = &BillingMeterCreateParams{} + } + params.Context = ctx + meter := &BillingMeter{} + err := c.B.Call(http.MethodPost, "/v1/billing/meters", c.Key, params, meter) + return meter, err +} + +// Retrieves a billing meter given an ID. +func (c v1BillingMeterService) Retrieve(ctx context.Context, id string, params *BillingMeterRetrieveParams) (*BillingMeter, error) { + if params == nil { + params = &BillingMeterRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing/meters/%s", id) + meter := &BillingMeter{} + err := c.B.Call(http.MethodGet, path, c.Key, params, meter) + return meter, err +} + +// Updates a billing meter. +func (c v1BillingMeterService) Update(ctx context.Context, id string, params *BillingMeterUpdateParams) (*BillingMeter, error) { + if params == nil { + params = &BillingMeterUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing/meters/%s", id) + meter := &BillingMeter{} + err := c.B.Call(http.MethodPost, path, c.Key, params, meter) + return meter, err +} + +// When a meter is deactivated, no more meter events will be accepted for this meter. You can't attach a deactivated meter to a price. +func (c v1BillingMeterService) Deactivate(ctx context.Context, id string, params *BillingMeterDeactivateParams) (*BillingMeter, error) { + if params == nil { + params = &BillingMeterDeactivateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing/meters/%s/deactivate", id) + meter := &BillingMeter{} + err := c.B.Call(http.MethodPost, path, c.Key, params, meter) + return meter, err +} + +// When a meter is reactivated, events for this meter can be accepted and you can attach the meter to a price. +func (c v1BillingMeterService) Reactivate(ctx context.Context, id string, params *BillingMeterReactivateParams) (*BillingMeter, error) { + if params == nil { + params = &BillingMeterReactivateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing/meters/%s/reactivate", id) + meter := &BillingMeter{} + err := c.B.Call(http.MethodPost, path, c.Key, params, meter) + return meter, err +} + +// Retrieve a list of billing meters. +func (c v1BillingMeterService) List(ctx context.Context, listParams *BillingMeterListParams) Seq2[*BillingMeter, error] { + if listParams == nil { + listParams = &BillingMeterListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*BillingMeter, ListContainer, error) { + list := &BillingMeterList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/billing/meters", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_meterevent.go b/vendor/github.com/stripe/stripe-go/v82/billing_meterevent.go new file mode 100644 index 00000000..227417b8 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_meterevent.go @@ -0,0 +1,66 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Creates a billing meter event. +type BillingMeterEventParams struct { + Params `form:"*"` + // The name of the meter event. Corresponds with the `event_name` field on a meter. + EventName *string `form:"event_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A unique identifier for the event. If not provided, one is generated. We recommend using UUID-like identifiers. We will enforce uniqueness within a rolling period of at least 24 hours. The enforcement of uniqueness primarily addresses issues arising from accidental retries or other problems occurring within extremely brief time intervals. This approach helps prevent duplicate entries and ensures data integrity in high-frequency operations. + Identifier *string `form:"identifier"` + // The payload of the event. This must contain the fields corresponding to a meter's `customer_mapping.event_payload_key` (default is `stripe_customer_id`) and `value_settings.event_payload_key` (default is `value`). Read more about the [payload](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage#payload-key-overrides). + Payload map[string]string `form:"payload"` + // The time of the event. Measured in seconds since the Unix epoch. Must be within the past 35 calendar days or up to 5 minutes in the future. Defaults to current timestamp if not specified. + Timestamp *int64 `form:"timestamp"` +} + +// AddExpand appends a new field to expand. +func (p *BillingMeterEventParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates a billing meter event. +type BillingMeterEventCreateParams struct { + Params `form:"*"` + // The name of the meter event. Corresponds with the `event_name` field on a meter. + EventName *string `form:"event_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A unique identifier for the event. If not provided, one is generated. We recommend using UUID-like identifiers. We will enforce uniqueness within a rolling period of at least 24 hours. The enforcement of uniqueness primarily addresses issues arising from accidental retries or other problems occurring within extremely brief time intervals. This approach helps prevent duplicate entries and ensures data integrity in high-frequency operations. + Identifier *string `form:"identifier"` + // The payload of the event. This must contain the fields corresponding to a meter's `customer_mapping.event_payload_key` (default is `stripe_customer_id`) and `value_settings.event_payload_key` (default is `value`). Read more about the [payload](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage#payload-key-overrides). + Payload map[string]string `form:"payload"` + // The time of the event. Measured in seconds since the Unix epoch. Must be within the past 35 calendar days or up to 5 minutes in the future. Defaults to current timestamp if not specified. + Timestamp *int64 `form:"timestamp"` +} + +// AddExpand appends a new field to expand. +func (p *BillingMeterEventCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Meter events represent actions that customers take in your system. You can use meter events to bill a customer based on their usage. Meter events are associated with billing meters, which define both the contents of the event's payload and how to aggregate those events. +type BillingMeterEvent struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The name of the meter event. Corresponds with the `event_name` field on a meter. + EventName string `json:"event_name"` + // A unique identifier for the event. + Identifier string `json:"identifier"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The payload of the event. This contains the fields corresponding to a meter's `customer_mapping.event_payload_key` (default is `stripe_customer_id`) and `value_settings.event_payload_key` (default is `value`). Read more about the [payload](https://stripe.com/docs/billing/subscriptions/usage-based/recording-usage#payload-key-overrides). + Payload map[string]string `json:"payload"` + // The timestamp passed in when creating the event. Measured in seconds since the Unix epoch. + Timestamp int64 `json:"timestamp"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_meterevent_service.go b/vendor/github.com/stripe/stripe-go/v82/billing_meterevent_service.go new file mode 100644 index 00000000..920efa84 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_meterevent_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1BillingMeterEventService is used to invoke /v1/billing/meter_events APIs. +type v1BillingMeterEventService struct { + B Backend + Key string +} + +// Creates a billing meter event. +func (c v1BillingMeterEventService) Create(ctx context.Context, params *BillingMeterEventCreateParams) (*BillingMeterEvent, error) { + if params == nil { + params = &BillingMeterEventCreateParams{} + } + params.Context = ctx + meterevent := &BillingMeterEvent{} + err := c.B.Call( + http.MethodPost, "/v1/billing/meter_events", c.Key, params, meterevent) + return meterevent, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_metereventadjustment.go b/vendor/github.com/stripe/stripe-go/v82/billing_metereventadjustment.go new file mode 100644 index 00000000..43a4abe7 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_metereventadjustment.go @@ -0,0 +1,95 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The meter event adjustment's status. +type BillingMeterEventAdjustmentStatus string + +// List of values that BillingMeterEventAdjustmentStatus can take +const ( + BillingMeterEventAdjustmentStatusComplete BillingMeterEventAdjustmentStatus = "complete" + BillingMeterEventAdjustmentStatusPending BillingMeterEventAdjustmentStatus = "pending" +) + +// Specifies whether to cancel a single event or a range of events for a time period. Time period cancellation is not supported yet. +type BillingMeterEventAdjustmentType string + +// List of values that BillingMeterEventAdjustmentType can take +const ( + BillingMeterEventAdjustmentTypeCancel BillingMeterEventAdjustmentType = "cancel" +) + +// Specifies which event to cancel. +type BillingMeterEventAdjustmentCancelParams struct { + // Unique identifier for the event. You can only cancel events within 24 hours of Stripe receiving them. + Identifier *string `form:"identifier"` +} + +// Creates a billing meter event adjustment. +type BillingMeterEventAdjustmentParams struct { + Params `form:"*"` + // Specifies which event to cancel. + Cancel *BillingMeterEventAdjustmentCancelParams `form:"cancel"` + // The name of the meter event. Corresponds with the `event_name` field on a meter. + EventName *string `form:"event_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Specifies whether to cancel a single event or a range of events for a time period. Time period cancellation is not supported yet. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *BillingMeterEventAdjustmentParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Specifies which event to cancel. +type BillingMeterEventAdjustmentCreateCancelParams struct { + // Unique identifier for the event. You can only cancel events within 24 hours of Stripe receiving them. + Identifier *string `form:"identifier"` +} + +// Creates a billing meter event adjustment. +type BillingMeterEventAdjustmentCreateParams struct { + Params `form:"*"` + // Specifies which event to cancel. + Cancel *BillingMeterEventAdjustmentCreateCancelParams `form:"cancel"` + // The name of the meter event. Corresponds with the `event_name` field on a meter. + EventName *string `form:"event_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Specifies whether to cancel a single event or a range of events for a time period. Time period cancellation is not supported yet. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *BillingMeterEventAdjustmentCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Specifies which event to cancel. +type BillingMeterEventAdjustmentCancel struct { + // Unique identifier for the event. + Identifier string `json:"identifier"` +} + +// A billing meter event adjustment is a resource that allows you to cancel a meter event. For example, you might create a billing meter event adjustment to cancel a meter event that was created in error or attached to the wrong customer. +type BillingMeterEventAdjustment struct { + APIResource + // Specifies which event to cancel. + Cancel *BillingMeterEventAdjustmentCancel `json:"cancel"` + // The name of the meter event. Corresponds with the `event_name` field on a meter. + EventName string `json:"event_name"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The meter event adjustment's status. + Status BillingMeterEventAdjustmentStatus `json:"status"` + // Specifies whether to cancel a single event or a range of events for a time period. Time period cancellation is not supported yet. + Type BillingMeterEventAdjustmentType `json:"type"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_metereventadjustment_service.go b/vendor/github.com/stripe/stripe-go/v82/billing_metereventadjustment_service.go new file mode 100644 index 00000000..e6541689 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_metereventadjustment_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1BillingMeterEventAdjustmentService is used to invoke /v1/billing/meter_event_adjustments APIs. +type v1BillingMeterEventAdjustmentService struct { + B Backend + Key string +} + +// Creates a billing meter event adjustment. +func (c v1BillingMeterEventAdjustmentService) Create(ctx context.Context, params *BillingMeterEventAdjustmentCreateParams) (*BillingMeterEventAdjustment, error) { + if params == nil { + params = &BillingMeterEventAdjustmentCreateParams{} + } + params.Context = ctx + metereventadjustment := &BillingMeterEventAdjustment{} + err := c.B.Call( + http.MethodPost, "/v1/billing/meter_event_adjustments", c.Key, params, metereventadjustment) + return metereventadjustment, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_metereventsummary.go b/vendor/github.com/stripe/stripe-go/v82/billing_metereventsummary.go new file mode 100644 index 00000000..c66ca6f0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_metereventsummary.go @@ -0,0 +1,56 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Retrieve a list of billing meter event summaries. +type BillingMeterEventSummaryListParams struct { + ListParams `form:"*"` + ID *string `form:"-"` // Included in URL + // The customer for which to fetch event summaries. + Customer *string `form:"customer"` + // The timestamp from when to stop aggregating meter events (exclusive). Must be aligned with minute boundaries. + EndTime *int64 `form:"end_time"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The timestamp from when to start aggregating meter events (inclusive). Must be aligned with minute boundaries. + StartTime *int64 `form:"start_time"` + // Specifies what granularity to use when generating event summaries. If not specified, a single event summary would be returned for the specified time range. For hourly granularity, start and end times must align with hour boundaries (e.g., 00:00, 01:00, ..., 23:00). For daily granularity, start and end times must align with UTC day boundaries (00:00 UTC). + ValueGroupingWindow *string `form:"value_grouping_window"` +} + +// AddExpand appends a new field to expand. +func (p *BillingMeterEventSummaryListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A billing meter event summary represents an aggregated view of a customer's billing meter events within a specified timeframe. It indicates how much +// usage was accrued by a customer for that period. +// +// Note: Meters events are aggregated asynchronously so the meter event summaries provide an eventually consistent view of the reported usage. +type BillingMeterEventSummary struct { + // Aggregated value of all the events within `start_time` (inclusive) and `end_time` (inclusive). The aggregation strategy is defined on meter via `default_aggregation`. + AggregatedValue float64 `json:"aggregated_value"` + // End timestamp for this event summary (exclusive). Must be aligned with minute boundaries. + EndTime int64 `json:"end_time"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // The meter associated with this event summary. + Meter string `json:"meter"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Start timestamp for this event summary (inclusive). Must be aligned with minute boundaries. + StartTime int64 `json:"start_time"` +} + +// BillingMeterEventSummaryList is a list of MeterEventSummaries as retrieved from a list endpoint. +type BillingMeterEventSummaryList struct { + APIResource + ListMeta + Data []*BillingMeterEventSummary `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billing_metereventsummary_service.go b/vendor/github.com/stripe/stripe-go/v82/billing_metereventsummary_service.go new file mode 100644 index 00000000..615bba40 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billing_metereventsummary_service.go @@ -0,0 +1,39 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1BillingMeterEventSummaryService is used to invoke /v1/billing/meters/{id}/event_summaries APIs. +type v1BillingMeterEventSummaryService struct { + B Backend + Key string +} + +// Retrieve a list of billing meter event summaries. +func (c v1BillingMeterEventSummaryService) List(ctx context.Context, listParams *BillingMeterEventSummaryListParams) Seq2[*BillingMeterEventSummary, error] { + if listParams == nil { + listParams = &BillingMeterEventSummaryListParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/billing/meters/%s/event_summaries", StringValue(listParams.ID)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*BillingMeterEventSummary, ListContainer, error) { + list := &BillingMeterEventSummaryList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billingportal_configuration.go b/vendor/github.com/stripe/stripe-go/v82/billingportal_configuration.go new file mode 100644 index 00000000..5194a4a0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billingportal_configuration.go @@ -0,0 +1,662 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The types of customer updates that are supported. When empty, customers are not updateable. +type BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdate string + +// List of values that BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdate can take +const ( + BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdateAddress BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdate = "address" + BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdateEmail BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdate = "email" + BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdateName BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdate = "name" + BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdatePhone BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdate = "phone" + BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdateShipping BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdate = "shipping" + BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdateTaxID BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdate = "tax_id" +) + +// Which cancellation reasons will be given as options to the customer. +type BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOption string + +// List of values that BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOption can take +const ( + BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOptionCustomerService BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOption = "customer_service" + BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOptionLowQuality BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOption = "low_quality" + BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOptionMissingFeatures BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOption = "missing_features" + BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOptionOther BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOption = "other" + BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOptionSwitchedService BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOption = "switched_service" + BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOptionTooComplex BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOption = "too_complex" + BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOptionTooExpensive BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOption = "too_expensive" + BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOptionUnused BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOption = "unused" +) + +// Whether to cancel subscriptions immediately or at the end of the billing period. +type BillingPortalConfigurationFeaturesSubscriptionCancelMode string + +// List of values that BillingPortalConfigurationFeaturesSubscriptionCancelMode can take +const ( + BillingPortalConfigurationFeaturesSubscriptionCancelModeAtPeriodEnd BillingPortalConfigurationFeaturesSubscriptionCancelMode = "at_period_end" + BillingPortalConfigurationFeaturesSubscriptionCancelModeImmediately BillingPortalConfigurationFeaturesSubscriptionCancelMode = "immediately" +) + +// Whether to create prorations when canceling subscriptions. Possible values are `none` and `create_prorations`. +type BillingPortalConfigurationFeaturesSubscriptionCancelProrationBehavior string + +// List of values that BillingPortalConfigurationFeaturesSubscriptionCancelProrationBehavior can take +const ( + BillingPortalConfigurationFeaturesSubscriptionCancelProrationBehaviorAlwaysInvoice BillingPortalConfigurationFeaturesSubscriptionCancelProrationBehavior = "always_invoice" + BillingPortalConfigurationFeaturesSubscriptionCancelProrationBehaviorCreateProrations BillingPortalConfigurationFeaturesSubscriptionCancelProrationBehavior = "create_prorations" + BillingPortalConfigurationFeaturesSubscriptionCancelProrationBehaviorNone BillingPortalConfigurationFeaturesSubscriptionCancelProrationBehavior = "none" +) + +// The types of subscription updates that are supported for items listed in the `products` attribute. When empty, subscriptions are not updateable. +type BillingPortalConfigurationFeaturesSubscriptionUpdateDefaultAllowedUpdate string + +// List of values that BillingPortalConfigurationFeaturesSubscriptionUpdateDefaultAllowedUpdate can take +const ( + BillingPortalConfigurationFeaturesSubscriptionUpdateDefaultAllowedUpdatePrice BillingPortalConfigurationFeaturesSubscriptionUpdateDefaultAllowedUpdate = "price" + BillingPortalConfigurationFeaturesSubscriptionUpdateDefaultAllowedUpdatePromotionCode BillingPortalConfigurationFeaturesSubscriptionUpdateDefaultAllowedUpdate = "promotion_code" + BillingPortalConfigurationFeaturesSubscriptionUpdateDefaultAllowedUpdateQuantity BillingPortalConfigurationFeaturesSubscriptionUpdateDefaultAllowedUpdate = "quantity" +) + +// Determines how to handle prorations resulting from subscription updates. Valid values are `none`, `create_prorations`, and `always_invoice`. Defaults to a value of `none` if you don't set it during creation. +type BillingPortalConfigurationFeaturesSubscriptionUpdateProrationBehavior string + +// List of values that BillingPortalConfigurationFeaturesSubscriptionUpdateProrationBehavior can take +const ( + BillingPortalConfigurationFeaturesSubscriptionUpdateProrationBehaviorAlwaysInvoice BillingPortalConfigurationFeaturesSubscriptionUpdateProrationBehavior = "always_invoice" + BillingPortalConfigurationFeaturesSubscriptionUpdateProrationBehaviorCreateProrations BillingPortalConfigurationFeaturesSubscriptionUpdateProrationBehavior = "create_prorations" + BillingPortalConfigurationFeaturesSubscriptionUpdateProrationBehaviorNone BillingPortalConfigurationFeaturesSubscriptionUpdateProrationBehavior = "none" +) + +// The type of condition. +type BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEndConditionType string + +// List of values that BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEndConditionType can take +const ( + BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEndConditionTypeDecreasingItemAmount BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEndConditionType = "decreasing_item_amount" + BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEndConditionTypeShorteningInterval BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEndConditionType = "shortening_interval" +) + +// Returns a list of configurations that describe the functionality of the customer portal. +type BillingPortalConfigurationListParams struct { + ListParams `form:"*"` + // Only return configurations that are active or inactive (e.g., pass `true` to only list active configurations). + Active *bool `form:"active"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return the default or non-default configurations (e.g., pass `true` to only list the default configuration). + IsDefault *bool `form:"is_default"` +} + +// AddExpand appends a new field to expand. +func (p *BillingPortalConfigurationListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The business information shown to customers in the portal. +type BillingPortalConfigurationBusinessProfileParams struct { + // The messaging shown to customers in the portal. + Headline *string `form:"headline"` + // A link to the business's publicly available privacy policy. + PrivacyPolicyURL *string `form:"privacy_policy_url"` + // A link to the business's publicly available terms of service. + TermsOfServiceURL *string `form:"terms_of_service_url"` +} + +// Information about updating the customer details in the portal. +type BillingPortalConfigurationFeaturesCustomerUpdateParams struct { + // The types of customer updates that are supported. When empty, customers are not updateable. + AllowedUpdates []*string `form:"allowed_updates"` + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` +} + +// Information about showing the billing history in the portal. +type BillingPortalConfigurationFeaturesInvoiceHistoryParams struct { + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` +} + +// Information about updating payment methods in the portal. +type BillingPortalConfigurationFeaturesPaymentMethodUpdateParams struct { + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` +} + +// Whether the cancellation reasons will be collected in the portal and which options are exposed to the customer +type BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonParams struct { + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` + // Which cancellation reasons will be given as options to the customer. + Options []*string `form:"options"` +} + +// Information about canceling subscriptions in the portal. +type BillingPortalConfigurationFeaturesSubscriptionCancelParams struct { + // Whether the cancellation reasons will be collected in the portal and which options are exposed to the customer + CancellationReason *BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonParams `form:"cancellation_reason"` + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` + // Whether to cancel subscriptions immediately or at the end of the billing period. + Mode *string `form:"mode"` + // Whether to create prorations when canceling subscriptions. Possible values are `none` and `create_prorations`, which is only compatible with `mode=immediately`. Passing `always_invoice` will result in an error. No prorations are generated when canceling a subscription at the end of its natural billing period. + ProrationBehavior *string `form:"proration_behavior"` +} + +// The list of up to 10 products that support subscription updates. +type BillingPortalConfigurationFeaturesSubscriptionUpdateProductParams struct { + // The list of price IDs for the product that a subscription can be updated to. + Prices []*string `form:"prices"` + // The product id. + Product *string `form:"product"` +} + +// List of conditions. When any condition is true, the update will be scheduled at the end of the current period. +type BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEndConditionParams struct { + // The type of condition. + Type *string `form:"type"` +} + +// Setting to control when an update should be scheduled at the end of the period instead of applying immediately. +type BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEndParams struct { + // List of conditions. When any condition is true, the update will be scheduled at the end of the current period. + Conditions []*BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEndConditionParams `form:"conditions"` +} + +// Information about updating subscriptions in the portal. +type BillingPortalConfigurationFeaturesSubscriptionUpdateParams struct { + // The types of subscription updates that are supported. When empty, subscriptions are not updateable. + DefaultAllowedUpdates []*string `form:"default_allowed_updates"` + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` + // The list of up to 10 products that support subscription updates. + Products []*BillingPortalConfigurationFeaturesSubscriptionUpdateProductParams `form:"products"` + // Determines how to handle prorations resulting from subscription updates. Valid values are `none`, `create_prorations`, and `always_invoice`. + ProrationBehavior *string `form:"proration_behavior"` + // Setting to control when an update should be scheduled at the end of the period instead of applying immediately. + ScheduleAtPeriodEnd *BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEndParams `form:"schedule_at_period_end"` +} + +// Information about the features available in the portal. +type BillingPortalConfigurationFeaturesParams struct { + // Information about updating the customer details in the portal. + CustomerUpdate *BillingPortalConfigurationFeaturesCustomerUpdateParams `form:"customer_update"` + // Information about showing the billing history in the portal. + InvoiceHistory *BillingPortalConfigurationFeaturesInvoiceHistoryParams `form:"invoice_history"` + // Information about updating payment methods in the portal. + PaymentMethodUpdate *BillingPortalConfigurationFeaturesPaymentMethodUpdateParams `form:"payment_method_update"` + // Information about canceling subscriptions in the portal. + SubscriptionCancel *BillingPortalConfigurationFeaturesSubscriptionCancelParams `form:"subscription_cancel"` + // Information about updating subscriptions in the portal. + SubscriptionUpdate *BillingPortalConfigurationFeaturesSubscriptionUpdateParams `form:"subscription_update"` +} + +// The hosted login page for this configuration. Learn more about the portal login page in our [integration docs](https://stripe.com/docs/billing/subscriptions/integrating-customer-portal#share). +type BillingPortalConfigurationLoginPageParams struct { + // Set to `true` to generate a shareable URL [`login_page.url`](https://stripe.com/docs/api/customer_portal/configuration#portal_configuration_object-login_page-url) that will take your customers to a hosted login page for the customer portal. + // + // Set to `false` to deactivate the `login_page.url`. + Enabled *bool `form:"enabled"` +} + +// Creates a configuration that describes the functionality and behavior of a PortalSession +type BillingPortalConfigurationParams struct { + Params `form:"*"` + // Whether the configuration is active and can be used to create portal sessions. + Active *bool `form:"active"` + // The business information shown to customers in the portal. + BusinessProfile *BillingPortalConfigurationBusinessProfileParams `form:"business_profile"` + // The default URL to redirect customers to when they click on the portal's link to return to your website. This can be [overriden](https://stripe.com/docs/api/customer_portal/sessions/create#create_portal_session-return_url) when creating the session. + DefaultReturnURL *string `form:"default_return_url"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Information about the features available in the portal. + Features *BillingPortalConfigurationFeaturesParams `form:"features"` + // The hosted login page for this configuration. Learn more about the portal login page in our [integration docs](https://stripe.com/docs/billing/subscriptions/integrating-customer-portal#share). + LoginPage *BillingPortalConfigurationLoginPageParams `form:"login_page"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *BillingPortalConfigurationParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *BillingPortalConfigurationParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The business information shown to customers in the portal. +type BillingPortalConfigurationCreateBusinessProfileParams struct { + // The messaging shown to customers in the portal. + Headline *string `form:"headline"` + // A link to the business's publicly available privacy policy. + PrivacyPolicyURL *string `form:"privacy_policy_url"` + // A link to the business's publicly available terms of service. + TermsOfServiceURL *string `form:"terms_of_service_url"` +} + +// Information about updating the customer details in the portal. +type BillingPortalConfigurationCreateFeaturesCustomerUpdateParams struct { + // The types of customer updates that are supported. When empty, customers are not updateable. + AllowedUpdates []*string `form:"allowed_updates"` + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` +} + +// Information about showing the billing history in the portal. +type BillingPortalConfigurationCreateFeaturesInvoiceHistoryParams struct { + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` +} + +// Information about updating payment methods in the portal. +type BillingPortalConfigurationCreateFeaturesPaymentMethodUpdateParams struct { + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` +} + +// Whether the cancellation reasons will be collected in the portal and which options are exposed to the customer +type BillingPortalConfigurationCreateFeaturesSubscriptionCancelCancellationReasonParams struct { + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` + // Which cancellation reasons will be given as options to the customer. + Options []*string `form:"options"` +} + +// Information about canceling subscriptions in the portal. +type BillingPortalConfigurationCreateFeaturesSubscriptionCancelParams struct { + // Whether the cancellation reasons will be collected in the portal and which options are exposed to the customer + CancellationReason *BillingPortalConfigurationCreateFeaturesSubscriptionCancelCancellationReasonParams `form:"cancellation_reason"` + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` + // Whether to cancel subscriptions immediately or at the end of the billing period. + Mode *string `form:"mode"` + // Whether to create prorations when canceling subscriptions. Possible values are `none` and `create_prorations`, which is only compatible with `mode=immediately`. Passing `always_invoice` will result in an error. No prorations are generated when canceling a subscription at the end of its natural billing period. + ProrationBehavior *string `form:"proration_behavior"` +} + +// The list of up to 10 products that support subscription updates. +type BillingPortalConfigurationCreateFeaturesSubscriptionUpdateProductParams struct { + // The list of price IDs for the product that a subscription can be updated to. + Prices []*string `form:"prices"` + // The product id. + Product *string `form:"product"` +} + +// List of conditions. When any condition is true, the update will be scheduled at the end of the current period. +type BillingPortalConfigurationCreateFeaturesSubscriptionUpdateScheduleAtPeriodEndConditionParams struct { + // The type of condition. + Type *string `form:"type"` +} + +// Setting to control when an update should be scheduled at the end of the period instead of applying immediately. +type BillingPortalConfigurationCreateFeaturesSubscriptionUpdateScheduleAtPeriodEndParams struct { + // List of conditions. When any condition is true, the update will be scheduled at the end of the current period. + Conditions []*BillingPortalConfigurationCreateFeaturesSubscriptionUpdateScheduleAtPeriodEndConditionParams `form:"conditions"` +} + +// Information about updating subscriptions in the portal. +type BillingPortalConfigurationCreateFeaturesSubscriptionUpdateParams struct { + // The types of subscription updates that are supported. When empty, subscriptions are not updateable. + DefaultAllowedUpdates []*string `form:"default_allowed_updates"` + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` + // The list of up to 10 products that support subscription updates. + Products []*BillingPortalConfigurationCreateFeaturesSubscriptionUpdateProductParams `form:"products"` + // Determines how to handle prorations resulting from subscription updates. Valid values are `none`, `create_prorations`, and `always_invoice`. + ProrationBehavior *string `form:"proration_behavior"` + // Setting to control when an update should be scheduled at the end of the period instead of applying immediately. + ScheduleAtPeriodEnd *BillingPortalConfigurationCreateFeaturesSubscriptionUpdateScheduleAtPeriodEndParams `form:"schedule_at_period_end"` +} + +// Information about the features available in the portal. +type BillingPortalConfigurationCreateFeaturesParams struct { + // Information about updating the customer details in the portal. + CustomerUpdate *BillingPortalConfigurationCreateFeaturesCustomerUpdateParams `form:"customer_update"` + // Information about showing the billing history in the portal. + InvoiceHistory *BillingPortalConfigurationCreateFeaturesInvoiceHistoryParams `form:"invoice_history"` + // Information about updating payment methods in the portal. + PaymentMethodUpdate *BillingPortalConfigurationCreateFeaturesPaymentMethodUpdateParams `form:"payment_method_update"` + // Information about canceling subscriptions in the portal. + SubscriptionCancel *BillingPortalConfigurationCreateFeaturesSubscriptionCancelParams `form:"subscription_cancel"` + // Information about updating subscriptions in the portal. + SubscriptionUpdate *BillingPortalConfigurationCreateFeaturesSubscriptionUpdateParams `form:"subscription_update"` +} + +// The hosted login page for this configuration. Learn more about the portal login page in our [integration docs](https://stripe.com/docs/billing/subscriptions/integrating-customer-portal#share). +type BillingPortalConfigurationCreateLoginPageParams struct { + // Set to `true` to generate a shareable URL [`login_page.url`](https://stripe.com/docs/api/customer_portal/configuration#portal_configuration_object-login_page-url) that will take your customers to a hosted login page for the customer portal. + Enabled *bool `form:"enabled"` +} + +// Creates a configuration that describes the functionality and behavior of a PortalSession +type BillingPortalConfigurationCreateParams struct { + Params `form:"*"` + // The business information shown to customers in the portal. + BusinessProfile *BillingPortalConfigurationCreateBusinessProfileParams `form:"business_profile"` + // The default URL to redirect customers to when they click on the portal's link to return to your website. This can be [overriden](https://stripe.com/docs/api/customer_portal/sessions/create#create_portal_session-return_url) when creating the session. + DefaultReturnURL *string `form:"default_return_url"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Information about the features available in the portal. + Features *BillingPortalConfigurationCreateFeaturesParams `form:"features"` + // The hosted login page for this configuration. Learn more about the portal login page in our [integration docs](https://stripe.com/docs/billing/subscriptions/integrating-customer-portal#share). + LoginPage *BillingPortalConfigurationCreateLoginPageParams `form:"login_page"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *BillingPortalConfigurationCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *BillingPortalConfigurationCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves a configuration that describes the functionality of the customer portal. +type BillingPortalConfigurationRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *BillingPortalConfigurationRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The business information shown to customers in the portal. +type BillingPortalConfigurationUpdateBusinessProfileParams struct { + // The messaging shown to customers in the portal. + Headline *string `form:"headline"` + // A link to the business's publicly available privacy policy. + PrivacyPolicyURL *string `form:"privacy_policy_url"` + // A link to the business's publicly available terms of service. + TermsOfServiceURL *string `form:"terms_of_service_url"` +} + +// Information about updating the customer details in the portal. +type BillingPortalConfigurationUpdateFeaturesCustomerUpdateParams struct { + // The types of customer updates that are supported. When empty, customers are not updateable. + AllowedUpdates []*string `form:"allowed_updates"` + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` +} + +// Information about showing the billing history in the portal. +type BillingPortalConfigurationUpdateFeaturesInvoiceHistoryParams struct { + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` +} + +// Information about updating payment methods in the portal. +type BillingPortalConfigurationUpdateFeaturesPaymentMethodUpdateParams struct { + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` +} + +// Whether the cancellation reasons will be collected in the portal and which options are exposed to the customer +type BillingPortalConfigurationUpdateFeaturesSubscriptionCancelCancellationReasonParams struct { + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` + // Which cancellation reasons will be given as options to the customer. + Options []*string `form:"options"` +} + +// Information about canceling subscriptions in the portal. +type BillingPortalConfigurationUpdateFeaturesSubscriptionCancelParams struct { + // Whether the cancellation reasons will be collected in the portal and which options are exposed to the customer + CancellationReason *BillingPortalConfigurationUpdateFeaturesSubscriptionCancelCancellationReasonParams `form:"cancellation_reason"` + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` + // Whether to cancel subscriptions immediately or at the end of the billing period. + Mode *string `form:"mode"` + // Whether to create prorations when canceling subscriptions. Possible values are `none` and `create_prorations`, which is only compatible with `mode=immediately`. Passing `always_invoice` will result in an error. No prorations are generated when canceling a subscription at the end of its natural billing period. + ProrationBehavior *string `form:"proration_behavior"` +} + +// The list of up to 10 products that support subscription updates. +type BillingPortalConfigurationUpdateFeaturesSubscriptionUpdateProductParams struct { + // The list of price IDs for the product that a subscription can be updated to. + Prices []*string `form:"prices"` + // The product id. + Product *string `form:"product"` +} + +// List of conditions. When any condition is true, the update will be scheduled at the end of the current period. +type BillingPortalConfigurationUpdateFeaturesSubscriptionUpdateScheduleAtPeriodEndConditionParams struct { + // The type of condition. + Type *string `form:"type"` +} + +// Setting to control when an update should be scheduled at the end of the period instead of applying immediately. +type BillingPortalConfigurationUpdateFeaturesSubscriptionUpdateScheduleAtPeriodEndParams struct { + // List of conditions. When any condition is true, the update will be scheduled at the end of the current period. + Conditions []*BillingPortalConfigurationUpdateFeaturesSubscriptionUpdateScheduleAtPeriodEndConditionParams `form:"conditions"` +} + +// Information about updating subscriptions in the portal. +type BillingPortalConfigurationUpdateFeaturesSubscriptionUpdateParams struct { + // The types of subscription updates that are supported. When empty, subscriptions are not updateable. + DefaultAllowedUpdates []*string `form:"default_allowed_updates"` + // Whether the feature is enabled. + Enabled *bool `form:"enabled"` + // The list of up to 10 products that support subscription updates. + Products []*BillingPortalConfigurationUpdateFeaturesSubscriptionUpdateProductParams `form:"products"` + // Determines how to handle prorations resulting from subscription updates. Valid values are `none`, `create_prorations`, and `always_invoice`. + ProrationBehavior *string `form:"proration_behavior"` + // Setting to control when an update should be scheduled at the end of the period instead of applying immediately. + ScheduleAtPeriodEnd *BillingPortalConfigurationUpdateFeaturesSubscriptionUpdateScheduleAtPeriodEndParams `form:"schedule_at_period_end"` +} + +// Information about the features available in the portal. +type BillingPortalConfigurationUpdateFeaturesParams struct { + // Information about updating the customer details in the portal. + CustomerUpdate *BillingPortalConfigurationUpdateFeaturesCustomerUpdateParams `form:"customer_update"` + // Information about showing the billing history in the portal. + InvoiceHistory *BillingPortalConfigurationUpdateFeaturesInvoiceHistoryParams `form:"invoice_history"` + // Information about updating payment methods in the portal. + PaymentMethodUpdate *BillingPortalConfigurationUpdateFeaturesPaymentMethodUpdateParams `form:"payment_method_update"` + // Information about canceling subscriptions in the portal. + SubscriptionCancel *BillingPortalConfigurationUpdateFeaturesSubscriptionCancelParams `form:"subscription_cancel"` + // Information about updating subscriptions in the portal. + SubscriptionUpdate *BillingPortalConfigurationUpdateFeaturesSubscriptionUpdateParams `form:"subscription_update"` +} + +// The hosted login page for this configuration. Learn more about the portal login page in our [integration docs](https://stripe.com/docs/billing/subscriptions/integrating-customer-portal#share). +type BillingPortalConfigurationUpdateLoginPageParams struct { + // Set to `true` to generate a shareable URL [`login_page.url`](https://stripe.com/docs/api/customer_portal/configuration#portal_configuration_object-login_page-url) that will take your customers to a hosted login page for the customer portal. + // + // Set to `false` to deactivate the `login_page.url`. + Enabled *bool `form:"enabled"` +} + +// Updates a configuration that describes the functionality of the customer portal. +type BillingPortalConfigurationUpdateParams struct { + Params `form:"*"` + // Whether the configuration is active and can be used to create portal sessions. + Active *bool `form:"active"` + // The business information shown to customers in the portal. + BusinessProfile *BillingPortalConfigurationUpdateBusinessProfileParams `form:"business_profile"` + // The default URL to redirect customers to when they click on the portal's link to return to your website. This can be [overriden](https://stripe.com/docs/api/customer_portal/sessions/create#create_portal_session-return_url) when creating the session. + DefaultReturnURL *string `form:"default_return_url"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Information about the features available in the portal. + Features *BillingPortalConfigurationUpdateFeaturesParams `form:"features"` + // The hosted login page for this configuration. Learn more about the portal login page in our [integration docs](https://stripe.com/docs/billing/subscriptions/integrating-customer-portal#share). + LoginPage *BillingPortalConfigurationUpdateLoginPageParams `form:"login_page"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *BillingPortalConfigurationUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *BillingPortalConfigurationUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +type BillingPortalConfigurationBusinessProfile struct { + // The messaging shown to customers in the portal. + Headline string `json:"headline"` + // A link to the business's publicly available privacy policy. + PrivacyPolicyURL string `json:"privacy_policy_url"` + // A link to the business's publicly available terms of service. + TermsOfServiceURL string `json:"terms_of_service_url"` +} +type BillingPortalConfigurationFeaturesCustomerUpdate struct { + // The types of customer updates that are supported. When empty, customers are not updateable. + AllowedUpdates []BillingPortalConfigurationFeaturesCustomerUpdateAllowedUpdate `json:"allowed_updates"` + // Whether the feature is enabled. + Enabled bool `json:"enabled"` +} +type BillingPortalConfigurationFeaturesInvoiceHistory struct { + // Whether the feature is enabled. + Enabled bool `json:"enabled"` +} +type BillingPortalConfigurationFeaturesPaymentMethodUpdate struct { + // Whether the feature is enabled. + Enabled bool `json:"enabled"` +} +type BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReason struct { + // Whether the feature is enabled. + Enabled bool `json:"enabled"` + // Which cancellation reasons will be given as options to the customer. + Options []BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReasonOption `json:"options"` +} +type BillingPortalConfigurationFeaturesSubscriptionCancel struct { + CancellationReason *BillingPortalConfigurationFeaturesSubscriptionCancelCancellationReason `json:"cancellation_reason"` + // Whether the feature is enabled. + Enabled bool `json:"enabled"` + // Whether to cancel subscriptions immediately or at the end of the billing period. + Mode BillingPortalConfigurationFeaturesSubscriptionCancelMode `json:"mode"` + // Whether to create prorations when canceling subscriptions. Possible values are `none` and `create_prorations`. + ProrationBehavior BillingPortalConfigurationFeaturesSubscriptionCancelProrationBehavior `json:"proration_behavior"` +} + +// The list of up to 10 products that support subscription updates. +type BillingPortalConfigurationFeaturesSubscriptionUpdateProduct struct { + // The list of price IDs which, when subscribed to, a subscription can be updated. + Prices []string `json:"prices"` + // The product ID. + Product string `json:"product"` +} + +// List of conditions. When any condition is true, an update will be scheduled at the end of the current period. +type BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEndCondition struct { + // The type of condition. + Type BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEndConditionType `json:"type"` +} +type BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEnd struct { + // List of conditions. When any condition is true, an update will be scheduled at the end of the current period. + Conditions []*BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEndCondition `json:"conditions"` +} +type BillingPortalConfigurationFeaturesSubscriptionUpdate struct { + // The types of subscription updates that are supported for items listed in the `products` attribute. When empty, subscriptions are not updateable. + DefaultAllowedUpdates []BillingPortalConfigurationFeaturesSubscriptionUpdateDefaultAllowedUpdate `json:"default_allowed_updates"` + // Whether the feature is enabled. + Enabled bool `json:"enabled"` + // The list of up to 10 products that support subscription updates. + Products []*BillingPortalConfigurationFeaturesSubscriptionUpdateProduct `json:"products"` + // Determines how to handle prorations resulting from subscription updates. Valid values are `none`, `create_prorations`, and `always_invoice`. Defaults to a value of `none` if you don't set it during creation. + ProrationBehavior BillingPortalConfigurationFeaturesSubscriptionUpdateProrationBehavior `json:"proration_behavior"` + ScheduleAtPeriodEnd *BillingPortalConfigurationFeaturesSubscriptionUpdateScheduleAtPeriodEnd `json:"schedule_at_period_end"` +} +type BillingPortalConfigurationFeatures struct { + CustomerUpdate *BillingPortalConfigurationFeaturesCustomerUpdate `json:"customer_update"` + InvoiceHistory *BillingPortalConfigurationFeaturesInvoiceHistory `json:"invoice_history"` + PaymentMethodUpdate *BillingPortalConfigurationFeaturesPaymentMethodUpdate `json:"payment_method_update"` + SubscriptionCancel *BillingPortalConfigurationFeaturesSubscriptionCancel `json:"subscription_cancel"` + SubscriptionUpdate *BillingPortalConfigurationFeaturesSubscriptionUpdate `json:"subscription_update"` +} +type BillingPortalConfigurationLoginPage struct { + // If `true`, a shareable `url` will be generated that will take your customers to a hosted login page for the customer portal. + // + // If `false`, the previously generated `url`, if any, will be deactivated. + Enabled bool `json:"enabled"` + // A shareable URL to the hosted portal login page. Your customers will be able to log in with their [email](https://stripe.com/docs/api/customers/object#customer_object-email) and receive a link to their customer portal. + URL string `json:"url"` +} + +// A portal configuration describes the functionality and behavior of a portal session. +type BillingPortalConfiguration struct { + APIResource + // Whether the configuration is active and can be used to create portal sessions. + Active bool `json:"active"` + // ID of the Connect Application that created the configuration. + Application *Application `json:"application"` + BusinessProfile *BillingPortalConfigurationBusinessProfile `json:"business_profile"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The default URL to redirect customers to when they click on the portal's link to return to your website. This can be [overriden](https://stripe.com/docs/api/customer_portal/sessions/create#create_portal_session-return_url) when creating the session. + DefaultReturnURL string `json:"default_return_url"` + Features *BillingPortalConfigurationFeatures `json:"features"` + // Unique identifier for the object. + ID string `json:"id"` + // Whether the configuration is the default. If `true`, this configuration can be managed in the Dashboard and portal sessions will use this configuration unless it is overriden when creating the session. + IsDefault bool `json:"is_default"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + LoginPage *BillingPortalConfigurationLoginPage `json:"login_page"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Time at which the object was last updated. Measured in seconds since the Unix epoch. + Updated int64 `json:"updated"` +} + +// BillingPortalConfigurationList is a list of Configurations as retrieved from a list endpoint. +type BillingPortalConfigurationList struct { + APIResource + ListMeta + Data []*BillingPortalConfiguration `json:"data"` +} + +// UnmarshalJSON handles deserialization of a BillingPortalConfiguration. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (b *BillingPortalConfiguration) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + b.ID = id + return nil + } + + type billingPortalConfiguration BillingPortalConfiguration + var v billingPortalConfiguration + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *b = BillingPortalConfiguration(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billingportal_configuration_service.go b/vendor/github.com/stripe/stripe-go/v82/billingportal_configuration_service.go new file mode 100644 index 00000000..18105163 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billingportal_configuration_service.go @@ -0,0 +1,73 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1BillingPortalConfigurationService is used to invoke /v1/billing_portal/configurations APIs. +type v1BillingPortalConfigurationService struct { + B Backend + Key string +} + +// Creates a configuration that describes the functionality and behavior of a PortalSession +func (c v1BillingPortalConfigurationService) Create(ctx context.Context, params *BillingPortalConfigurationCreateParams) (*BillingPortalConfiguration, error) { + if params == nil { + params = &BillingPortalConfigurationCreateParams{} + } + params.Context = ctx + configuration := &BillingPortalConfiguration{} + err := c.B.Call( + http.MethodPost, "/v1/billing_portal/configurations", c.Key, params, configuration) + return configuration, err +} + +// Retrieves a configuration that describes the functionality of the customer portal. +func (c v1BillingPortalConfigurationService) Retrieve(ctx context.Context, id string, params *BillingPortalConfigurationRetrieveParams) (*BillingPortalConfiguration, error) { + if params == nil { + params = &BillingPortalConfigurationRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing_portal/configurations/%s", id) + configuration := &BillingPortalConfiguration{} + err := c.B.Call(http.MethodGet, path, c.Key, params, configuration) + return configuration, err +} + +// Updates a configuration that describes the functionality of the customer portal. +func (c v1BillingPortalConfigurationService) Update(ctx context.Context, id string, params *BillingPortalConfigurationUpdateParams) (*BillingPortalConfiguration, error) { + if params == nil { + params = &BillingPortalConfigurationUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/billing_portal/configurations/%s", id) + configuration := &BillingPortalConfiguration{} + err := c.B.Call(http.MethodPost, path, c.Key, params, configuration) + return configuration, err +} + +// Returns a list of configurations that describe the functionality of the customer portal. +func (c v1BillingPortalConfigurationService) List(ctx context.Context, listParams *BillingPortalConfigurationListParams) Seq2[*BillingPortalConfiguration, error] { + if listParams == nil { + listParams = &BillingPortalConfigurationListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*BillingPortalConfiguration, ListContainer, error) { + list := &BillingPortalConfigurationList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/billing_portal/configurations", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billingportal_session.go b/vendor/github.com/stripe/stripe-go/v82/billingportal_session.go new file mode 100644 index 00000000..4c888318 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billingportal_session.go @@ -0,0 +1,397 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The specified type of behavior after the flow is completed. +type BillingPortalSessionFlowAfterCompletionType string + +// List of values that BillingPortalSessionFlowAfterCompletionType can take +const ( + BillingPortalSessionFlowAfterCompletionTypeHostedConfirmation BillingPortalSessionFlowAfterCompletionType = "hosted_confirmation" + BillingPortalSessionFlowAfterCompletionTypePortalHomepage BillingPortalSessionFlowAfterCompletionType = "portal_homepage" + BillingPortalSessionFlowAfterCompletionTypeRedirect BillingPortalSessionFlowAfterCompletionType = "redirect" +) + +// Type of retention strategy that will be used. +type BillingPortalSessionFlowSubscriptionCancelRetentionType string + +// List of values that BillingPortalSessionFlowSubscriptionCancelRetentionType can take +const ( + BillingPortalSessionFlowSubscriptionCancelRetentionTypeCouponOffer BillingPortalSessionFlowSubscriptionCancelRetentionType = "coupon_offer" +) + +// Type of flow that the customer will go through. +type BillingPortalSessionFlowType string + +// List of values that BillingPortalSessionFlowType can take +const ( + BillingPortalSessionFlowTypePaymentMethodUpdate BillingPortalSessionFlowType = "payment_method_update" + BillingPortalSessionFlowTypeSubscriptionCancel BillingPortalSessionFlowType = "subscription_cancel" + BillingPortalSessionFlowTypeSubscriptionUpdate BillingPortalSessionFlowType = "subscription_update" + BillingPortalSessionFlowTypeSubscriptionUpdateConfirm BillingPortalSessionFlowType = "subscription_update_confirm" +) + +// Configuration when `after_completion.type=hosted_confirmation`. +type BillingPortalSessionFlowDataAfterCompletionHostedConfirmationParams struct { + // A custom message to display to the customer after the flow is completed. + CustomMessage *string `form:"custom_message"` +} + +// Configuration when `after_completion.type=redirect`. +type BillingPortalSessionFlowDataAfterCompletionRedirectParams struct { + // The URL the customer will be redirected to after the flow is completed. + ReturnURL *string `form:"return_url"` +} + +// Behavior after the flow is completed. +type BillingPortalSessionFlowDataAfterCompletionParams struct { + // Configuration when `after_completion.type=hosted_confirmation`. + HostedConfirmation *BillingPortalSessionFlowDataAfterCompletionHostedConfirmationParams `form:"hosted_confirmation"` + // Configuration when `after_completion.type=redirect`. + Redirect *BillingPortalSessionFlowDataAfterCompletionRedirectParams `form:"redirect"` + // The specified behavior after the flow is completed. + Type *string `form:"type"` +} + +// Configuration when `retention.type=coupon_offer`. +type BillingPortalSessionFlowDataSubscriptionCancelRetentionCouponOfferParams struct { + // The ID of the coupon to be offered. + Coupon *string `form:"coupon"` +} + +// Specify a retention strategy to be used in the cancellation flow. +type BillingPortalSessionFlowDataSubscriptionCancelRetentionParams struct { + // Configuration when `retention.type=coupon_offer`. + CouponOffer *BillingPortalSessionFlowDataSubscriptionCancelRetentionCouponOfferParams `form:"coupon_offer"` + // Type of retention strategy to use with the customer. + Type *string `form:"type"` +} + +// Configuration when `flow_data.type=subscription_cancel`. +type BillingPortalSessionFlowDataSubscriptionCancelParams struct { + // Specify a retention strategy to be used in the cancellation flow. + Retention *BillingPortalSessionFlowDataSubscriptionCancelRetentionParams `form:"retention"` + // The ID of the subscription to be canceled. + Subscription *string `form:"subscription"` +} + +// Configuration when `flow_data.type=subscription_update`. +type BillingPortalSessionFlowDataSubscriptionUpdateParams struct { + // The ID of the subscription to be updated. + Subscription *string `form:"subscription"` +} + +// The coupon or promotion code to apply to this subscription update. +type BillingPortalSessionFlowDataSubscriptionUpdateConfirmDiscountParams struct { + // The ID of the coupon to apply to this subscription update. + Coupon *string `form:"coupon"` + // The ID of a promotion code to apply to this subscription update. + PromotionCode *string `form:"promotion_code"` +} + +// The [subscription item](https://stripe.com/docs/api/subscription_items) to be updated through this flow. Currently, only up to one may be specified and subscriptions with multiple items are not updatable. +type BillingPortalSessionFlowDataSubscriptionUpdateConfirmItemParams struct { + // The ID of the [subscription item](https://stripe.com/docs/api/subscriptions/object#subscription_object-items-data-id) to be updated. + ID *string `form:"id"` + // The price the customer should subscribe to through this flow. The price must also be included in the configuration's [`features.subscription_update.products`](https://stripe.com/docs/api/customer_portal/configuration#portal_configuration_object-features-subscription_update-products). + Price *string `form:"price"` + // [Quantity](https://stripe.com/docs/subscriptions/quantities) for this item that the customer should subscribe to through this flow. + Quantity *int64 `form:"quantity"` +} + +// Configuration when `flow_data.type=subscription_update_confirm`. +type BillingPortalSessionFlowDataSubscriptionUpdateConfirmParams struct { + // The coupon or promotion code to apply to this subscription update. + Discounts []*BillingPortalSessionFlowDataSubscriptionUpdateConfirmDiscountParams `form:"discounts"` + // The [subscription item](https://stripe.com/docs/api/subscription_items) to be updated through this flow. Currently, only up to one may be specified and subscriptions with multiple items are not updatable. + Items []*BillingPortalSessionFlowDataSubscriptionUpdateConfirmItemParams `form:"items"` + // The ID of the subscription to be updated. + Subscription *string `form:"subscription"` +} + +// Information about a specific flow for the customer to go through. See the [docs](https://stripe.com/docs/customer-management/portal-deep-links) to learn more about using customer portal deep links and flows. +type BillingPortalSessionFlowDataParams struct { + // Behavior after the flow is completed. + AfterCompletion *BillingPortalSessionFlowDataAfterCompletionParams `form:"after_completion"` + // Configuration when `flow_data.type=subscription_cancel`. + SubscriptionCancel *BillingPortalSessionFlowDataSubscriptionCancelParams `form:"subscription_cancel"` + // Configuration when `flow_data.type=subscription_update`. + SubscriptionUpdate *BillingPortalSessionFlowDataSubscriptionUpdateParams `form:"subscription_update"` + // Configuration when `flow_data.type=subscription_update_confirm`. + SubscriptionUpdateConfirm *BillingPortalSessionFlowDataSubscriptionUpdateConfirmParams `form:"subscription_update_confirm"` + // Type of flow that the customer will go through. + Type *string `form:"type"` +} + +// Creates a session of the customer portal. +type BillingPortalSessionParams struct { + Params `form:"*"` + // The ID of an existing [configuration](https://stripe.com/docs/api/customer_portal/configuration) to use for this session, describing its functionality and features. If not specified, the session uses the default configuration. + Configuration *string `form:"configuration"` + // The ID of an existing customer. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Information about a specific flow for the customer to go through. See the [docs](https://stripe.com/docs/customer-management/portal-deep-links) to learn more about using customer portal deep links and flows. + FlowData *BillingPortalSessionFlowDataParams `form:"flow_data"` + // The IETF language tag of the locale customer portal is displayed in. If blank or auto, the customer's `preferred_locales` or browser's locale is used. + Locale *string `form:"locale"` + // The `on_behalf_of` account to use for this session. When specified, only subscriptions and invoices with this `on_behalf_of` account appear in the portal. For more information, see the [docs](https://stripe.com/docs/connect/separate-charges-and-transfers#settlement-merchant). Use the [Accounts API](https://stripe.com/docs/api/accounts/object#account_object-settings-branding) to modify the `on_behalf_of` account's branding settings, which the portal displays. + OnBehalfOf *string `form:"on_behalf_of"` + // The default URL to redirect customers to when they click on the portal's link to return to your website. + ReturnURL *string `form:"return_url"` +} + +// AddExpand appends a new field to expand. +func (p *BillingPortalSessionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Configuration when `after_completion.type=hosted_confirmation`. +type BillingPortalSessionCreateFlowDataAfterCompletionHostedConfirmationParams struct { + // A custom message to display to the customer after the flow is completed. + CustomMessage *string `form:"custom_message"` +} + +// Configuration when `after_completion.type=redirect`. +type BillingPortalSessionCreateFlowDataAfterCompletionRedirectParams struct { + // The URL the customer will be redirected to after the flow is completed. + ReturnURL *string `form:"return_url"` +} + +// Behavior after the flow is completed. +type BillingPortalSessionCreateFlowDataAfterCompletionParams struct { + // Configuration when `after_completion.type=hosted_confirmation`. + HostedConfirmation *BillingPortalSessionCreateFlowDataAfterCompletionHostedConfirmationParams `form:"hosted_confirmation"` + // Configuration when `after_completion.type=redirect`. + Redirect *BillingPortalSessionCreateFlowDataAfterCompletionRedirectParams `form:"redirect"` + // The specified behavior after the flow is completed. + Type *string `form:"type"` +} + +// Configuration when `retention.type=coupon_offer`. +type BillingPortalSessionCreateFlowDataSubscriptionCancelRetentionCouponOfferParams struct { + // The ID of the coupon to be offered. + Coupon *string `form:"coupon"` +} + +// Specify a retention strategy to be used in the cancellation flow. +type BillingPortalSessionCreateFlowDataSubscriptionCancelRetentionParams struct { + // Configuration when `retention.type=coupon_offer`. + CouponOffer *BillingPortalSessionCreateFlowDataSubscriptionCancelRetentionCouponOfferParams `form:"coupon_offer"` + // Type of retention strategy to use with the customer. + Type *string `form:"type"` +} + +// Configuration when `flow_data.type=subscription_cancel`. +type BillingPortalSessionCreateFlowDataSubscriptionCancelParams struct { + // Specify a retention strategy to be used in the cancellation flow. + Retention *BillingPortalSessionCreateFlowDataSubscriptionCancelRetentionParams `form:"retention"` + // The ID of the subscription to be canceled. + Subscription *string `form:"subscription"` +} + +// Configuration when `flow_data.type=subscription_update`. +type BillingPortalSessionCreateFlowDataSubscriptionUpdateParams struct { + // The ID of the subscription to be updated. + Subscription *string `form:"subscription"` +} + +// The coupon or promotion code to apply to this subscription update. +type BillingPortalSessionCreateFlowDataSubscriptionUpdateConfirmDiscountParams struct { + // The ID of the coupon to apply to this subscription update. + Coupon *string `form:"coupon"` + // The ID of a promotion code to apply to this subscription update. + PromotionCode *string `form:"promotion_code"` +} + +// The [subscription item](https://stripe.com/docs/api/subscription_items) to be updated through this flow. Currently, only up to one may be specified and subscriptions with multiple items are not updatable. +type BillingPortalSessionCreateFlowDataSubscriptionUpdateConfirmItemParams struct { + // The ID of the [subscription item](https://stripe.com/docs/api/subscriptions/object#subscription_object-items-data-id) to be updated. + ID *string `form:"id"` + // The price the customer should subscribe to through this flow. The price must also be included in the configuration's [`features.subscription_update.products`](https://stripe.com/docs/api/customer_portal/configuration#portal_configuration_object-features-subscription_update-products). + Price *string `form:"price"` + // [Quantity](https://stripe.com/docs/subscriptions/quantities) for this item that the customer should subscribe to through this flow. + Quantity *int64 `form:"quantity"` +} + +// Configuration when `flow_data.type=subscription_update_confirm`. +type BillingPortalSessionCreateFlowDataSubscriptionUpdateConfirmParams struct { + // The coupon or promotion code to apply to this subscription update. + Discounts []*BillingPortalSessionCreateFlowDataSubscriptionUpdateConfirmDiscountParams `form:"discounts"` + // The [subscription item](https://stripe.com/docs/api/subscription_items) to be updated through this flow. Currently, only up to one may be specified and subscriptions with multiple items are not updatable. + Items []*BillingPortalSessionCreateFlowDataSubscriptionUpdateConfirmItemParams `form:"items"` + // The ID of the subscription to be updated. + Subscription *string `form:"subscription"` +} + +// Information about a specific flow for the customer to go through. See the [docs](https://stripe.com/docs/customer-management/portal-deep-links) to learn more about using customer portal deep links and flows. +type BillingPortalSessionCreateFlowDataParams struct { + // Behavior after the flow is completed. + AfterCompletion *BillingPortalSessionCreateFlowDataAfterCompletionParams `form:"after_completion"` + // Configuration when `flow_data.type=subscription_cancel`. + SubscriptionCancel *BillingPortalSessionCreateFlowDataSubscriptionCancelParams `form:"subscription_cancel"` + // Configuration when `flow_data.type=subscription_update`. + SubscriptionUpdate *BillingPortalSessionCreateFlowDataSubscriptionUpdateParams `form:"subscription_update"` + // Configuration when `flow_data.type=subscription_update_confirm`. + SubscriptionUpdateConfirm *BillingPortalSessionCreateFlowDataSubscriptionUpdateConfirmParams `form:"subscription_update_confirm"` + // Type of flow that the customer will go through. + Type *string `form:"type"` +} + +// Creates a session of the customer portal. +type BillingPortalSessionCreateParams struct { + Params `form:"*"` + // The ID of an existing [configuration](https://stripe.com/docs/api/customer_portal/configuration) to use for this session, describing its functionality and features. If not specified, the session uses the default configuration. + Configuration *string `form:"configuration"` + // The ID of an existing customer. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Information about a specific flow for the customer to go through. See the [docs](https://stripe.com/docs/customer-management/portal-deep-links) to learn more about using customer portal deep links and flows. + FlowData *BillingPortalSessionCreateFlowDataParams `form:"flow_data"` + // The IETF language tag of the locale customer portal is displayed in. If blank or auto, the customer's `preferred_locales` or browser's locale is used. + Locale *string `form:"locale"` + // The `on_behalf_of` account to use for this session. When specified, only subscriptions and invoices with this `on_behalf_of` account appear in the portal. For more information, see the [docs](https://stripe.com/docs/connect/separate-charges-and-transfers#settlement-merchant). Use the [Accounts API](https://stripe.com/docs/api/accounts/object#account_object-settings-branding) to modify the `on_behalf_of` account's branding settings, which the portal displays. + OnBehalfOf *string `form:"on_behalf_of"` + // The default URL to redirect customers to when they click on the portal's link to return to your website. + ReturnURL *string `form:"return_url"` +} + +// AddExpand appends a new field to expand. +func (p *BillingPortalSessionCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Configuration when `after_completion.type=hosted_confirmation`. +type BillingPortalSessionFlowAfterCompletionHostedConfirmation struct { + // A custom message to display to the customer after the flow is completed. + CustomMessage string `json:"custom_message"` +} + +// Configuration when `after_completion.type=redirect`. +type BillingPortalSessionFlowAfterCompletionRedirect struct { + // The URL the customer will be redirected to after the flow is completed. + ReturnURL string `json:"return_url"` +} +type BillingPortalSessionFlowAfterCompletion struct { + // Configuration when `after_completion.type=hosted_confirmation`. + HostedConfirmation *BillingPortalSessionFlowAfterCompletionHostedConfirmation `json:"hosted_confirmation"` + // Configuration when `after_completion.type=redirect`. + Redirect *BillingPortalSessionFlowAfterCompletionRedirect `json:"redirect"` + // The specified type of behavior after the flow is completed. + Type BillingPortalSessionFlowAfterCompletionType `json:"type"` +} + +// Configuration when `retention.type=coupon_offer`. +type BillingPortalSessionFlowSubscriptionCancelRetentionCouponOffer struct { + // The ID of the coupon to be offered. + Coupon string `json:"coupon"` +} + +// Specify a retention strategy to be used in the cancellation flow. +type BillingPortalSessionFlowSubscriptionCancelRetention struct { + // Configuration when `retention.type=coupon_offer`. + CouponOffer *BillingPortalSessionFlowSubscriptionCancelRetentionCouponOffer `json:"coupon_offer"` + // Type of retention strategy that will be used. + Type BillingPortalSessionFlowSubscriptionCancelRetentionType `json:"type"` +} + +// Configuration when `flow.type=subscription_cancel`. +type BillingPortalSessionFlowSubscriptionCancel struct { + // Specify a retention strategy to be used in the cancellation flow. + Retention *BillingPortalSessionFlowSubscriptionCancelRetention `json:"retention"` + // The ID of the subscription to be canceled. + Subscription string `json:"subscription"` +} + +// Configuration when `flow.type=subscription_update`. +type BillingPortalSessionFlowSubscriptionUpdate struct { + // The ID of the subscription to be updated. + Subscription string `json:"subscription"` +} + +// The coupon or promotion code to apply to this subscription update. +type BillingPortalSessionFlowSubscriptionUpdateConfirmDiscount struct { + // The ID of the coupon to apply to this subscription update. + Coupon string `json:"coupon"` + // The ID of a promotion code to apply to this subscription update. + PromotionCode string `json:"promotion_code"` +} + +// The [subscription item](https://stripe.com/docs/api/subscription_items) to be updated through this flow. Currently, only up to one may be specified and subscriptions with multiple items are not updatable. +type BillingPortalSessionFlowSubscriptionUpdateConfirmItem struct { + // The ID of the [subscription item](https://stripe.com/docs/api/subscriptions/object#subscription_object-items-data-id) to be updated. + ID string `json:"id"` + // The price the customer should subscribe to through this flow. The price must also be included in the configuration's [`features.subscription_update.products`](https://stripe.com/docs/api/customer_portal/configuration#portal_configuration_object-features-subscription_update-products). + Price string `json:"price"` + // [Quantity](https://stripe.com/docs/subscriptions/quantities) for this item that the customer should subscribe to through this flow. + Quantity int64 `json:"quantity"` +} + +// Configuration when `flow.type=subscription_update_confirm`. +type BillingPortalSessionFlowSubscriptionUpdateConfirm struct { + // The coupon or promotion code to apply to this subscription update. + Discounts []*BillingPortalSessionFlowSubscriptionUpdateConfirmDiscount `json:"discounts"` + // The [subscription item](https://stripe.com/docs/api/subscription_items) to be updated through this flow. Currently, only up to one may be specified and subscriptions with multiple items are not updatable. + Items []*BillingPortalSessionFlowSubscriptionUpdateConfirmItem `json:"items"` + // The ID of the subscription to be updated. + Subscription string `json:"subscription"` +} + +// Information about a specific flow for the customer to go through. See the [docs](https://stripe.com/docs/customer-management/portal-deep-links) to learn more about using customer portal deep links and flows. +type BillingPortalSessionFlow struct { + AfterCompletion *BillingPortalSessionFlowAfterCompletion `json:"after_completion"` + // Configuration when `flow.type=subscription_cancel`. + SubscriptionCancel *BillingPortalSessionFlowSubscriptionCancel `json:"subscription_cancel"` + // Configuration when `flow.type=subscription_update`. + SubscriptionUpdate *BillingPortalSessionFlowSubscriptionUpdate `json:"subscription_update"` + // Configuration when `flow.type=subscription_update_confirm`. + SubscriptionUpdateConfirm *BillingPortalSessionFlowSubscriptionUpdateConfirm `json:"subscription_update_confirm"` + // Type of flow that the customer will go through. + Type BillingPortalSessionFlowType `json:"type"` +} + +// The Billing customer portal is a Stripe-hosted UI for subscription and +// billing management. +// +// A portal configuration describes the functionality and features that you +// want to provide to your customers through the portal. +// +// A portal session describes the instantiation of the customer portal for +// a particular customer. By visiting the session's URL, the customer +// can manage their subscriptions and billing details. For security reasons, +// sessions are short-lived and will expire if the customer does not visit the URL. +// Create sessions on-demand when customers intend to manage their subscriptions +// and billing details. +// +// Related guide: [Customer management](https://docs.stripe.com/customer-management) +type BillingPortalSession struct { + APIResource + // The configuration used by this session, describing the features available. + Configuration *BillingPortalConfiguration `json:"configuration"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The ID of the customer for this session. + Customer string `json:"customer"` + // Information about a specific flow for the customer to go through. See the [docs](https://stripe.com/docs/customer-management/portal-deep-links) to learn more about using customer portal deep links and flows. + Flow *BillingPortalSessionFlow `json:"flow"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // The IETF language tag of the locale Customer Portal is displayed in. If blank or auto, the customer's `preferred_locales` or browser's locale is used. + Locale string `json:"locale"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The account for which the session was created on behalf of. When specified, only subscriptions and invoices with this `on_behalf_of` account appear in the portal. For more information, see the [docs](https://stripe.com/docs/connect/separate-charges-and-transfers#settlement-merchant). Use the [Accounts API](https://stripe.com/docs/api/accounts/object#account_object-settings-branding) to modify the `on_behalf_of` account's branding settings, which the portal displays. + OnBehalfOf string `json:"on_behalf_of"` + // The URL to redirect customers to when they click on the portal's link to return to your website. + ReturnURL string `json:"return_url"` + // The short-lived URL of the session that gives customers access to the customer portal. + URL string `json:"url"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/billingportal_session_service.go b/vendor/github.com/stripe/stripe-go/v82/billingportal_session_service.go new file mode 100644 index 00000000..d84bfb1a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/billingportal_session_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1BillingPortalSessionService is used to invoke /v1/billing_portal/sessions APIs. +type v1BillingPortalSessionService struct { + B Backend + Key string +} + +// Creates a session of the customer portal. +func (c v1BillingPortalSessionService) Create(ctx context.Context, params *BillingPortalSessionCreateParams) (*BillingPortalSession, error) { + if params == nil { + params = &BillingPortalSessionCreateParams{} + } + params.Context = ctx + session := &BillingPortalSession{} + err := c.B.Call( + http.MethodPost, "/v1/billing_portal/sessions", c.Key, params, session) + return session, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/capability.go b/vendor/github.com/stripe/stripe-go/v82/capability.go new file mode 100644 index 00000000..6b493b87 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/capability.go @@ -0,0 +1,203 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// This is typed as an enum for consistency with `requirements.disabled_reason`, but it safe to assume `future_requirements.disabled_reason` is null because fields in `future_requirements` will never disable the account. +type CapabilityFutureRequirementsDisabledReason string + +// List of values that CapabilityFutureRequirementsDisabledReason can take +const ( + CapabilityFutureRequirementsDisabledReasonOther CapabilityFutureRequirementsDisabledReason = "other" + CapabilityFutureRequirementsDisabledReasonPausedInactivity CapabilityFutureRequirementsDisabledReason = "paused.inactivity" + CapabilityFutureRequirementsDisabledReasonPendingOnboarding CapabilityFutureRequirementsDisabledReason = "pending.onboarding" + CapabilityFutureRequirementsDisabledReasonPendingReview CapabilityFutureRequirementsDisabledReason = "pending.review" + CapabilityFutureRequirementsDisabledReasonPlatformDisabled CapabilityFutureRequirementsDisabledReason = "platform_disabled" + CapabilityFutureRequirementsDisabledReasonPlatformPaused CapabilityFutureRequirementsDisabledReason = "platform_paused" + CapabilityFutureRequirementsDisabledReasonRejectedInactivity CapabilityFutureRequirementsDisabledReason = "rejected.inactivity" + CapabilityFutureRequirementsDisabledReasonRejectedOther CapabilityFutureRequirementsDisabledReason = "rejected.other" + CapabilityFutureRequirementsDisabledReasonRejectedUnsupportedBusiness CapabilityFutureRequirementsDisabledReason = "rejected.unsupported_business" + CapabilityFutureRequirementsDisabledReasonRequirementsFieldsNeeded CapabilityFutureRequirementsDisabledReason = "requirements.fields_needed" +) + +// Description of why the capability is disabled. [Learn more about handling verification issues](https://stripe.com/docs/connect/handling-api-verification). +type CapabilityDisabledReason string + +// List of values that CapabilityDisabledReason can take +const ( + CapabilityDisabledReasonOther CapabilityDisabledReason = "other" + CapabilityDisabledReasonPausedInactivity CapabilityDisabledReason = "paused.inactivity" + CapabilityDisabledReasonPendingOnboarding CapabilityDisabledReason = "pending.onboarding" + CapabilityDisabledReasonPendingReview CapabilityDisabledReason = "pending.review" + CapabilityDisabledReasonPlatformDisabled CapabilityDisabledReason = "platform_disabled" + CapabilityDisabledReasonPlatformPaused CapabilityDisabledReason = "platform_paused" + CapabilityDisabledReasonRejectedInactivity CapabilityDisabledReason = "rejected.inactivity" + CapabilityDisabledReasonRejectedOther CapabilityDisabledReason = "rejected.other" + CapabilityDisabledReasonRejectedUnsupportedBusiness CapabilityDisabledReason = "rejected.unsupported_business" + CapabilityDisabledReasonRequirementsFieldsNeeded CapabilityDisabledReason = "requirements.fields_needed" +) + +// The status of the capability. +type CapabilityStatus string + +// List of values that CapabilityStatus can take +const ( + CapabilityStatusActive CapabilityStatus = "active" + CapabilityStatusDisabled CapabilityStatus = "disabled" + CapabilityStatusInactive CapabilityStatus = "inactive" + CapabilityStatusPending CapabilityStatus = "pending" + CapabilityStatusUnrequested CapabilityStatus = "unrequested" +) + +// Returns a list of capabilities associated with the account. The capabilities are returned sorted by creation date, with the most recent capability appearing first. +type CapabilityListParams struct { + ListParams `form:"*"` + Account *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CapabilityListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves information about the specified Account Capability. +type CapabilityParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // To request a new capability for an account, pass true. There can be a delay before the requested capability becomes active. If the capability has any activation requirements, the response includes them in the `requirements` arrays. + // + // If a capability isn't permanent, you can remove it from the account by passing false. Some capabilities are permanent after they've been requested. Attempting to remove a permanent capability returns an error. + Requested *bool `form:"requested"` +} + +// AddExpand appends a new field to expand. +func (p *CapabilityParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves information about the specified Account Capability. +type CapabilityRetrieveParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CapabilityRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates an existing Account Capability. Request or remove a capability by updating its requested parameter. +type CapabilityUpdateParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // To request a new capability for an account, pass true. There can be a delay before the requested capability becomes active. If the capability has any activation requirements, the response includes them in the `requirements` arrays. + // + // If a capability isn't permanent, you can remove it from the account by passing false. Some capabilities are permanent after they've been requested. Attempting to remove a permanent capability returns an error. + Requested *bool `form:"requested"` +} + +// AddExpand appends a new field to expand. +func (p *CapabilityUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Fields that are due and can be satisfied by providing the corresponding alternative fields instead. +type CapabilityFutureRequirementsAlternative struct { + // Fields that can be provided to satisfy all fields in `original_fields_due`. + AlternativeFieldsDue []string `json:"alternative_fields_due"` + // Fields that are due and can be satisfied by providing all fields in `alternative_fields_due`. + OriginalFieldsDue []string `json:"original_fields_due"` +} + +// Fields that are `currently_due` and need to be collected again because validation or verification failed. +type CapabilityFutureRequirementsError struct { + // The code for the type of error. + Code string `json:"code"` + // An informative message that indicates the error type and provides additional details about the error. + Reason string `json:"reason"` + // The specific user onboarding requirement field (in the requirements hash) that needs to be resolved. + Requirement string `json:"requirement"` +} +type CapabilityFutureRequirements struct { + // Fields that are due and can be satisfied by providing the corresponding alternative fields instead. + Alternatives []*CapabilityFutureRequirementsAlternative `json:"alternatives"` + // Date on which `future_requirements` becomes the main `requirements` hash and `future_requirements` becomes empty. After the transition, `currently_due` requirements may immediately become `past_due`, but the account may also be given a grace period depending on the capability's enablement state prior to transitioning. + CurrentDeadline int64 `json:"current_deadline"` + // Fields that need to be collected to keep the capability enabled. If not collected by `future_requirements[current_deadline]`, these fields will transition to the main `requirements` hash. + CurrentlyDue []string `json:"currently_due"` + // This is typed as an enum for consistency with `requirements.disabled_reason`, but it safe to assume `future_requirements.disabled_reason` is null because fields in `future_requirements` will never disable the account. + DisabledReason CapabilityFutureRequirementsDisabledReason `json:"disabled_reason"` + // Fields that are `currently_due` and need to be collected again because validation or verification failed. + Errors []*CapabilityFutureRequirementsError `json:"errors"` + // Fields you must collect when all thresholds are reached. As they become required, they appear in `currently_due` as well. + EventuallyDue []string `json:"eventually_due"` + // Fields that weren't collected by `requirements.current_deadline`. These fields need to be collected to enable the capability on the account. New fields will never appear here; `future_requirements.past_due` will always be a subset of `requirements.past_due`. + PastDue []string `json:"past_due"` + // Fields that might become required depending on the results of verification or review. It's an empty array unless an asynchronous verification is pending. If verification fails, these fields move to `eventually_due` or `currently_due`. Fields might appear in `eventually_due` or `currently_due` and in `pending_verification` if verification fails but another verification is still pending. + PendingVerification []string `json:"pending_verification"` +} + +// Fields that are due and can be satisfied by providing the corresponding alternative fields instead. +type CapabilityRequirementsAlternative struct { + // Fields that can be provided to satisfy all fields in `original_fields_due`. + AlternativeFieldsDue []string `json:"alternative_fields_due"` + // Fields that are due and can be satisfied by providing all fields in `alternative_fields_due`. + OriginalFieldsDue []string `json:"original_fields_due"` +} +type CapabilityRequirements struct { + // Fields that are due and can be satisfied by providing the corresponding alternative fields instead. + Alternatives []*CapabilityRequirementsAlternative `json:"alternatives"` + // The date by which all required account information must be both submitted and verified. This includes fields listed in `currently_due` as well as those in `pending_verification`. If any required information is missing or unverified by this date, the account may be disabled. Note that `current_deadline` may change if additional `currently_due` requirements are requested. + CurrentDeadline int64 `json:"current_deadline"` + // Fields that need to be collected to keep the capability enabled. If not collected by `current_deadline`, these fields appear in `past_due` as well, and the capability is disabled. + CurrentlyDue []string `json:"currently_due"` + // Description of why the capability is disabled. [Learn more about handling verification issues](https://stripe.com/docs/connect/handling-api-verification). + DisabledReason CapabilityDisabledReason `json:"disabled_reason"` + // Fields that are `currently_due` and need to be collected again because validation or verification failed. + Errors []*AccountRequirementsError `json:"errors"` + // Fields you must collect when all thresholds are reached. As they become required, they appear in `currently_due` as well, and `current_deadline` becomes set. + EventuallyDue []string `json:"eventually_due"` + // Fields that weren't collected by `current_deadline`. These fields need to be collected to enable the capability on the account. + PastDue []string `json:"past_due"` + // Fields that might become required depending on the results of verification or review. It's an empty array unless an asynchronous verification is pending. If verification fails, these fields move to `eventually_due`, `currently_due`, or `past_due`. Fields might appear in `eventually_due`, `currently_due`, or `past_due` and in `pending_verification` if verification fails but another verification is still pending. + PendingVerification []string `json:"pending_verification"` +} + +// This is an object representing a capability for a Stripe account. +// +// Related guide: [Account capabilities](https://stripe.com/docs/connect/account-capabilities) +type Capability struct { + APIResource + // The account for which the capability enables functionality. + Account *Account `json:"account"` + FutureRequirements *CapabilityFutureRequirements `json:"future_requirements"` + // The identifier for the capability. + ID string `json:"id"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Whether the capability has been requested. + Requested bool `json:"requested"` + // Time at which the capability was requested. Measured in seconds since the Unix epoch. + RequestedAt int64 `json:"requested_at"` + Requirements *CapabilityRequirements `json:"requirements"` + // The status of the capability. + Status CapabilityStatus `json:"status"` +} + +// CapabilityList is a list of Capabilities as retrieved from a list endpoint. +type CapabilityList struct { + APIResource + ListMeta + Data []*Capability `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/capability_service.go b/vendor/github.com/stripe/stripe-go/v82/capability_service.go new file mode 100644 index 00000000..b589936a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/capability_service.go @@ -0,0 +1,65 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1CapabilityService is used to invoke /v1/accounts/{account}/capabilities APIs. +type v1CapabilityService struct { + B Backend + Key string +} + +// Retrieves information about the specified Account Capability. +func (c v1CapabilityService) Retrieve(ctx context.Context, id string, params *CapabilityRetrieveParams) (*Capability, error) { + if params == nil { + params = &CapabilityRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/capabilities/%s", StringValue(params.Account), id) + capability := &Capability{} + err := c.B.Call(http.MethodGet, path, c.Key, params, capability) + return capability, err +} + +// Updates an existing Account Capability. Request or remove a capability by updating its requested parameter. +func (c v1CapabilityService) Update(ctx context.Context, id string, params *CapabilityUpdateParams) (*Capability, error) { + if params == nil { + params = &CapabilityUpdateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/capabilities/%s", StringValue(params.Account), id) + capability := &Capability{} + err := c.B.Call(http.MethodPost, path, c.Key, params, capability) + return capability, err +} + +// Returns a list of capabilities associated with the account. The capabilities are returned sorted by creation date, with the most recent capability appearing first. +func (c v1CapabilityService) List(ctx context.Context, listParams *CapabilityListParams) Seq2[*Capability, error] { + if listParams == nil { + listParams = &CapabilityListParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/capabilities", StringValue(listParams.Account)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Capability, ListContainer, error) { + list := &CapabilityList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/card.go b/vendor/github.com/stripe/stripe-go/v82/card.go new file mode 100644 index 00000000..c3afec7a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/card.go @@ -0,0 +1,507 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "encoding/json" + "github.com/stripe/stripe-go/v82/form" + "strconv" +) + +// If `address_line1` was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. +type CardAddressLine1Check string + +// List of values that CardAddressLine1Check can take +const ( + CardAddressLine1CheckFail CardAddressLine1Check = "fail" + CardAddressLine1CheckPass CardAddressLine1Check = "pass" + CardAddressLine1CheckUnavailable CardAddressLine1Check = "unavailable" + CardAddressLine1CheckUnchecked CardAddressLine1Check = "unchecked" +) + +// If `address_zip` was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. +type CardAddressZipCheck string + +// List of values that CardAddressZipCheck can take +const ( + CardAddressZipCheckFail CardAddressZipCheck = "fail" + CardAddressZipCheckPass CardAddressZipCheck = "pass" + CardAddressZipCheckUnavailable CardAddressZipCheck = "unavailable" + CardAddressZipCheckUnchecked CardAddressZipCheck = "unchecked" +) + +// This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to “unspecified”. +type CardAllowRedisplay string + +// List of values that CardAllowRedisplay can take +const ( + CardAllowRedisplayAlways CardAllowRedisplay = "always" + CardAllowRedisplayLimited CardAllowRedisplay = "limited" + CardAllowRedisplayUnspecified CardAllowRedisplay = "unspecified" +) + +// A set of available payout methods for this card. Only values from this set should be passed as the `method` when creating a payout. +type CardAvailablePayoutMethod string + +// List of values that CardAvailablePayoutMethod can take +const ( + CardAvailablePayoutMethodInstant CardAvailablePayoutMethod = "instant" + CardAvailablePayoutMethodStandard CardAvailablePayoutMethod = "standard" +) + +// Card brand. Can be `American Express`, `Diners Club`, `Discover`, `Eftpos Australia`, `Girocard`, `JCB`, `MasterCard`, `UnionPay`, `Visa`, or `Unknown`. +type CardBrand string + +// List of values that CardBrand can take +const ( + CardBrandAmericanExpress CardBrand = "American Express" + CardBrandDiscover CardBrand = "Discover" + CardBrandDinersClub CardBrand = "Diners Club" + CardBrandJCB CardBrand = "JCB" + CardBrandMasterCard CardBrand = "MasterCard" + CardBrandUnknown CardBrand = "Unknown" + CardBrandUnionPay CardBrand = "UnionPay" + CardBrandVisa CardBrand = "Visa" +) + +// If a CVC was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. A result of unchecked indicates that CVC was provided but hasn't been checked yet. Checks are typically performed when attaching a card to a Customer object, or when creating a charge. For more details, see [Check if a card is valid without a charge](https://support.stripe.com/questions/check-if-a-card-is-valid-without-a-charge). +type CardCVCCheck string + +// List of values that CardCVCCheck can take +const ( + CardCVCCheckFail CardCVCCheck = "fail" + CardCVCCheckPass CardCVCCheck = "pass" + CardCVCCheckUnavailable CardCVCCheck = "unavailable" + CardCVCCheckUnchecked CardCVCCheck = "unchecked" +) + +// Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. +type CardFunding string + +// List of values that CardFunding can take +const ( + CardFundingCredit CardFunding = "credit" + CardFundingDebit CardFunding = "debit" + CardFundingPrepaid CardFunding = "prepaid" + CardFundingUnknown CardFunding = "unknown" +) + +// Status of a card based on the card issuer. +type CardRegulatedStatus string + +// List of values that CardRegulatedStatus can take +const ( + CardRegulatedStatusRegulated CardRegulatedStatus = "regulated" + CardRegulatedStatusUnregulated CardRegulatedStatus = "unregulated" +) + +// If the card number is tokenized, this is the method that was used. Can be `android_pay` (includes Google Pay), `apple_pay`, `masterpass`, `visa_checkout`, or null. +type CardTokenizationMethod string + +// List of values that CardTokenizationMethod can take +const ( + CardTokenizationMethodAndroidPay CardTokenizationMethod = "android_pay" + CardTokenizationMethodApplePay CardTokenizationMethod = "apple_pay" +) + +// cardSource is a string that's used to build card form parameters. It's a +// constant just to make mistakes less likely. +const cardSource = "source" + +// Delete a specified source for a given customer. +type CardParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL + Token *string `form:"-"` // Included in URL + Customer *string `form:"-"` // Included in URL + // The name of the person or business that owns the bank account. + AccountHolderName *string `form:"account_holder_name"` + // The type of entity that holds the account. This can be either `individual` or `company`. + AccountHolderType *string `form:"account_holder_type"` + // City/District/Suburb/Town/Village. + AddressCity *string `form:"address_city"` + // Billing address country, if provided when creating card. + AddressCountry *string `form:"address_country"` + // Address line 1 (Street address/PO Box/Company name). + AddressLine1 *string `form:"address_line1"` + // Address line 2 (Apartment/Suite/Unit/Building). + AddressLine2 *string `form:"address_line2"` + // State/County/Province/Region. + AddressState *string `form:"address_state"` + // ZIP or postal code. + AddressZip *string `form:"address_zip"` + // Required when adding a card to an account (not applicable to customers or recipients). The card (which must be a debit card) can be used as a transfer destination for funds in this currency. + Currency *string `form:"currency"` + // Card security code. Highly recommended to always include this value, but it's required only for accounts based in European countries. + CVC *string `form:"cvc"` + // Applicable only on accounts (not customers or recipients). If you set this to `true` (or if this is the first external account being added in this currency), this card will become the default external account for its currency. + DefaultForCurrency *bool `form:"default_for_currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Two digit number representing the card's expiration month. + ExpMonth *string `form:"exp_month"` + // Four digit number representing the card's expiration year. + ExpYear *string `form:"exp_year"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Cardholder name. + Name *string `form:"name"` + // The card number, as a string without any separators. + Number *string `form:"number"` + Owner *CardOwnerParams `form:"owner"` + // ID is used when tokenizing a card for shared customers + ID string `form:"*"` +} + +// AppendToAsCardSourceOrExternalAccount appends the given CardParams as either a +// card or external account. +// +// It may look like an AppendTo from the form package, but it's not, and is +// only used in the special case where we use `card.New`. It's needed because +// we have some weird encoding logic here that can't be handled by the form +// package (and it's special enough that it wouldn't be desirable to have it do +// so). +// +// This is not a pattern that we want to push forward, and this largely exists +// because the cards endpoint is a little unusual. There is one other resource +// like it, which is bank account. +func (p *CardParams) AppendToAsCardSourceOrExternalAccount(body *form.Values, keyParts []string) { + // Rather than being called in addition to `AppendTo`, this function + // *replaces* `AppendTo`, so we must also make sure to handle the encoding + // of `Params` so metadata and the like is included in the encoded payload. + form.AppendToPrefixed(body, p.Params, keyParts) + + if p.DefaultForCurrency != nil { + body.Add( + form.FormatKey( + append(keyParts, "default_for_currency")), strconv.FormatBool( + BoolValue(p.DefaultForCurrency))) + } + + if p.Token != nil { + if p.Account != nil { + body.Add(form.FormatKey(append(keyParts, "external_account")), StringValue(p.Token)) + } else { + body.Add(form.FormatKey(append(keyParts, cardSource)), StringValue(p.Token)) + } + } + + if p.Number != nil { + body.Add(form.FormatKey(append(keyParts, cardSource, "object")), "card") + body.Add(form.FormatKey(append(keyParts, cardSource, "number")), StringValue(p.Number)) + } + if p.CVC != nil { + body.Add( + form.FormatKey(append(keyParts, cardSource, "cvc")), StringValue(p.CVC)) + } + if p.Currency != nil { + body.Add( + form.FormatKey(append(keyParts, cardSource, "currency")), StringValue( + p.Currency)) + } + if p.ExpMonth != nil { + body.Add( + form.FormatKey(append(keyParts, cardSource, "exp_month")), StringValue( + p.ExpMonth)) + } + if p.ExpYear != nil { + body.Add( + form.FormatKey(append(keyParts, cardSource, "exp_year")), StringValue( + p.ExpYear)) + } + if p.Name != nil { + body.Add( + form.FormatKey(append(keyParts, cardSource, "name")), StringValue(p.Name)) + } + if p.AddressCity != nil { + body.Add( + form.FormatKey(append(keyParts, cardSource, "address_city")), StringValue( + p.AddressCity)) + } + if p.AddressCountry != nil { + body.Add( + form.FormatKey( + append(keyParts, cardSource, "address_country")), StringValue( + p.AddressCountry)) + } + if p.AddressLine1 != nil { + body.Add( + form.FormatKey( + append(keyParts, cardSource, "address_line1")), StringValue( + p.AddressLine1)) + } + if p.AddressLine2 != nil { + body.Add( + form.FormatKey( + append(keyParts, cardSource, "address_line2")), StringValue( + p.AddressLine2)) + } + if p.AddressState != nil { + body.Add( + form.FormatKey( + append(keyParts, cardSource, "address_state")), StringValue( + p.AddressState)) + } + if p.AddressZip != nil { + body.Add( + form.FormatKey(append(keyParts, cardSource, "address_zip")), StringValue( + p.AddressZip)) + } +} + +// AddExpand appends a new field to expand. +func (p *CardParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CardParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +type CardOwnerParams struct { + // Owner's address. + Address *AddressParams `form:"address"` + // Owner's email address. + Email *string `form:"email"` + // Owner's full name. + Name *string `form:"name"` + // Owner's phone number. + Phone *string `form:"phone"` +} +type CardListParams struct { + ListParams `form:"*"` + Customer *string `form:"-"` // Included in URL + Account *string `form:"-"` // Included in URL + Object *string `form:"object"` +} + +// AppendTo implements custom encoding logic for CardListParams +// so that we can send the special required `object` field up along with the +// other specified parameters. +func (p *CardListParams) AppendTo(body *form.Values, keyParts []string) { + if p.Account != nil || p.Customer != nil { + body.Add(form.FormatKey(append(keyParts, "object")), "card") + } +} + +// Delete a specified source for a given customer. +type CardDeleteParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CardDeleteParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type CardUpdateOwnerParams struct { + // Owner's address. + Address *AddressParams `form:"address"` + // Owner's email address. + Email *string `form:"email"` + // Owner's full name. + Name *string `form:"name"` + // Owner's phone number. + Phone *string `form:"phone"` +} + +// Update a specified source for a given customer. +type CardUpdateParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // The name of the person or business that owns the bank account. + AccountHolderName *string `form:"account_holder_name"` + // The type of entity that holds the account. This can be either `individual` or `company`. + AccountHolderType *string `form:"account_holder_type"` + // City/District/Suburb/Town/Village. + AddressCity *string `form:"address_city"` + // Billing address country, if provided when creating card. + AddressCountry *string `form:"address_country"` + // Address line 1 (Street address/PO Box/Company name). + AddressLine1 *string `form:"address_line1"` + // Address line 2 (Apartment/Suite/Unit/Building). + AddressLine2 *string `form:"address_line2"` + // State/County/Province/Region. + AddressState *string `form:"address_state"` + // ZIP or postal code. + AddressZip *string `form:"address_zip"` + // Required when adding a card to an account (not applicable to customers or recipients). The card (which must be a debit card) can be used as a transfer destination for funds in this currency. + Currency *string `form:"currency"` + // Card security code. Highly recommended to always include this value, but it's required only for accounts based in European countries. + CVC *string `form:"cvc"` + // Applicable only on accounts (not customers or recipients). If you set this to `true` (or if this is the first external account being added in this currency), this card will become the default external account for its currency. + DefaultForCurrency *bool `form:"default_for_currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Two digit number representing the card's expiration month. + ExpMonth *string `form:"exp_month"` + // Four digit number representing the card's expiration year. + ExpYear *string `form:"exp_year"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Cardholder name. + Name *string `form:"name"` + // The card number, as a string without any separators. + Number *string `form:"number"` + Owner *CardUpdateOwnerParams `form:"owner"` +} + +// AddExpand appends a new field to expand. +func (p *CardUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CardUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// New creates a new card +type CardCreateParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL + Customer *string `form:"-"` // Included in URL + Token *string `form:"-"` // Included in URL +} + +// Get returns the details of a card. +type CardRetrieveParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL +} +type CardNetworks struct { + // The preferred network for co-branded cards. Can be `cartes_bancaires`, `mastercard`, `visa` or `invalid_preference` if requested network is not valid for the card. + Preferred string `json:"preferred"` +} + +// You can store multiple cards on a customer in order to charge the customer +// later. You can also store multiple debit cards on a recipient in order to +// transfer to those cards later. +// +// Related guide: [Card payments with Sources](https://stripe.com/docs/sources/cards) +type Card struct { + APIResource + Account *Account `json:"account"` + // City/District/Suburb/Town/Village. + AddressCity string `json:"address_city"` + // Billing address country, if provided when creating card. + AddressCountry string `json:"address_country"` + // Address line 1 (Street address/PO Box/Company name). + AddressLine1 string `json:"address_line1"` + // If `address_line1` was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. + AddressLine1Check CardAddressLine1Check `json:"address_line1_check"` + // Address line 2 (Apartment/Suite/Unit/Building). + AddressLine2 string `json:"address_line2"` + // State/County/Province/Region. + AddressState string `json:"address_state"` + // ZIP or postal code. + AddressZip string `json:"address_zip"` + // If `address_zip` was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. + AddressZipCheck CardAddressZipCheck `json:"address_zip_check"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to “unspecified”. + AllowRedisplay CardAllowRedisplay `json:"allow_redisplay"` + // A set of available payout methods for this card. Only values from this set should be passed as the `method` when creating a payout. + AvailablePayoutMethods []CardAvailablePayoutMethod `json:"available_payout_methods"` + // Card brand. Can be `American Express`, `Diners Club`, `Discover`, `Eftpos Australia`, `Girocard`, `JCB`, `MasterCard`, `UnionPay`, `Visa`, or `Unknown`. + Brand CardBrand `json:"brand"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // Three-letter [ISO code for currency](https://www.iso.org/iso-4217-currency-codes.html) in lowercase. Must be a [supported currency](https://docs.stripe.com/currencies). Only applicable on accounts (not customers or recipients). The card can be used as a transfer destination for funds in this currency. This property is only available when returned as an [External Account](https://docs.stripe.com/api/external_account_cards/object) where [controller.is_controller](https://docs.stripe.com/api/accounts/object#account_object-controller-is_controller) is `true`. + Currency Currency `json:"currency"` + // The customer that this card belongs to. This attribute will not be in the card object if the card belongs to an account or recipient instead. + Customer *Customer `json:"customer"` + // If a CVC was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. A result of unchecked indicates that CVC was provided but hasn't been checked yet. Checks are typically performed when attaching a card to a Customer object, or when creating a charge. For more details, see [Check if a card is valid without a charge](https://support.stripe.com/questions/check-if-a-card-is-valid-without-a-charge). + CVCCheck CardCVCCheck `json:"cvc_check"` + // Whether this card is the default external account for its currency. This property is only available for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. + DefaultForCurrency bool `json:"default_for_currency"` + Deleted bool `json:"deleted"` + // Description is a succinct summary of the card's information. + // + // Please note that this field is for internal use only and is not returned + // as part of standard API requests. + // A high-level description of the type of cards issued in this range. (For internal use only and not typically available in standard API requests.) + Description string `json:"description"` + // (For tokenized numbers only.) The last four digits of the device account number. + DynamicLast4 string `json:"dynamic_last4"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + // Uniquely identifies this particular card number. You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + // + // *As of May 1, 2021, card fingerprint in India for Connect changed to allow two fingerprints for the same card---one for India and one for the rest of the world.* + Fingerprint string `json:"fingerprint"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding CardFunding `json:"funding"` + // Unique identifier for the object. + ID string `json:"id"` + // IIN is the card's "Issuer Identification Number". + // + // Please note that this field is for internal use only and is not returned + // as part of standard API requests. + // Issuer identification number of the card. (For internal use only and not typically available in standard API requests.) + IIN string `json:"iin"` + // Issuer is a bank or financial institution that provides the card. + // + // Please note that this field is for internal use only and is not returned + // as part of standard API requests. + // The name of the card's issuing bank. (For internal use only and not typically available in standard API requests.) + Issuer string `json:"issuer"` + // The last four digits of the card. + Last4 string `json:"last4"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // Cardholder name. + Name string `json:"name"` + Networks *CardNetworks `json:"networks"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Status of a card based on the card issuer. + RegulatedStatus CardRegulatedStatus `json:"regulated_status"` + // For external accounts that are cards, possible values are `new` and `errored`. If a payout fails, the status is set to `errored` and [scheduled payouts](https://stripe.com/docs/payouts#payout-schedule) are stopped until account details are updated. + Status string `json:"status"` + // If the card number is tokenized, this is the method that was used. Can be `android_pay` (includes Google Pay), `apple_pay`, `masterpass`, `visa_checkout`, or null. + TokenizationMethod CardTokenizationMethod `json:"tokenization_method"` +} + +// CardList is a list of Cards as retrieved from a list endpoint. +type CardList struct { + APIResource + ListMeta + Data []*Card `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Card. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (c *Card) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + c.ID = id + return nil + } + + type card Card + var v card + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *c = Card(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/card_service.go b/vendor/github.com/stripe/stripe-go/v82/card_service.go new file mode 100644 index 00000000..1c0b4800 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/card_service.go @@ -0,0 +1,91 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1CardService is used to invoke card related APIs. +type v1CardService struct { + B Backend + Key string +} + +// New creates a new card +func (c v1CardService) Create(ctx context.Context, params *CardCreateParams) (*Card, error) { + if params == nil { + params = &CardCreateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/external_accounts", StringValue(params.Token), StringValue( + params.Customer), StringValue(params.Account)) + card := &Card{} + err := c.B.Call(http.MethodPost, path, c.Key, params, card) + return card, err +} + +// Get returns the details of a card. +func (c v1CardService) Retrieve(ctx context.Context, id string, params *CardRetrieveParams) (*Card, error) { + if params == nil { + params = &CardRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/external_accounts/%s", StringValue(params.Account), id) + card := &Card{} + err := c.B.Call(http.MethodGet, path, c.Key, params, card) + return card, err +} + +// Update a specified source for a given customer. +func (c v1CardService) Update(ctx context.Context, id string, params *CardUpdateParams) (*Card, error) { + if params == nil { + params = &CardUpdateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/sources/%s", StringValue(params.Customer), id) + card := &Card{} + err := c.B.Call(http.MethodPost, path, c.Key, params, card) + return card, err +} + +// Delete a specified source for a given customer. +func (c v1CardService) Delete(ctx context.Context, id string, params *CardDeleteParams) (*Card, error) { + if params == nil { + params = &CardDeleteParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/sources/%s", StringValue(params.Customer), id) + card := &Card{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, card) + return card, err +} +func (c v1CardService) List(ctx context.Context, listParams *CardListParams) Seq2[*Card, error] { + if listParams == nil { + listParams = &CardListParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/external_accounts", StringValue( + listParams.Account), StringValue(listParams.Customer)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Card, ListContainer, error) { + list := &CardList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/cashbalance.go b/vendor/github.com/stripe/stripe-go/v82/cashbalance.go new file mode 100644 index 00000000..cd491593 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/cashbalance.go @@ -0,0 +1,92 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The configuration for how funds that land in the customer cash balance are reconciled. +type CashBalanceSettingsReconciliationMode string + +// List of values that CashBalanceSettingsReconciliationMode can take +const ( + CashBalanceSettingsReconciliationModeAutomatic CashBalanceSettingsReconciliationMode = "automatic" + CashBalanceSettingsReconciliationModeManual CashBalanceSettingsReconciliationMode = "manual" +) + +// Retrieves a customer's cash balance. +type CashBalanceParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A hash of settings for this cash balance. + Settings *CashBalanceSettingsParams `form:"settings"` + Customer *string `form:"-"` // Included in URL +} + +// AddExpand appends a new field to expand. +func (p *CashBalanceParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A hash of settings for this cash balance. +type CashBalanceSettingsParams struct { + // Controls how funds transferred by the customer are applied to payment intents and invoices. Valid options are `automatic`, `manual`, or `merchant_default`. For more information about these reconciliation modes, see [Reconciliation](https://stripe.com/docs/payments/customer-balance/reconciliation). + ReconciliationMode *string `form:"reconciliation_mode"` +} + +// Retrieves a customer's cash balance. +type CashBalanceRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + Customer *string `form:"-"` // Included in URL +} + +// AddExpand appends a new field to expand. +func (p *CashBalanceRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A hash of settings for this cash balance. +type CashBalanceUpdateSettingsParams struct { + // Controls how funds transferred by the customer are applied to payment intents and invoices. Valid options are `automatic`, `manual`, or `merchant_default`. For more information about these reconciliation modes, see [Reconciliation](https://stripe.com/docs/payments/customer-balance/reconciliation). + ReconciliationMode *string `form:"reconciliation_mode"` +} + +// Changes the settings on a customer's cash balance. +type CashBalanceUpdateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A hash of settings for this cash balance. + Settings *CashBalanceUpdateSettingsParams `form:"settings"` + Customer *string `form:"-"` // Included in URL +} + +// AddExpand appends a new field to expand. +func (p *CashBalanceUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type CashBalanceSettings struct { + // The configuration for how funds that land in the customer cash balance are reconciled. + ReconciliationMode CashBalanceSettingsReconciliationMode `json:"reconciliation_mode"` + // A flag to indicate if reconciliation mode returned is the user's default or is specific to this customer cash balance + UsingMerchantDefault bool `json:"using_merchant_default"` +} + +// A customer's `Cash balance` represents real funds. Customers can add funds to their cash balance by sending a bank transfer. These funds can be used for payment and can eventually be paid out to your bank account. +type CashBalance struct { + APIResource + // A hash of all cash balances available to this customer. You cannot delete a customer with any cash balances, even if the balance is 0. Amounts are represented in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Available map[string]int64 `json:"available"` + // The ID of the customer whose cash balance this object represents. + Customer string `json:"customer"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + Settings *CashBalanceSettings `json:"settings"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/cashbalance_service.go b/vendor/github.com/stripe/stripe-go/v82/cashbalance_service.go new file mode 100644 index 00000000..59da840d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/cashbalance_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "fmt" + "net/http" +) + +// v1CashBalanceService is used to invoke /v1/customers/{customer}/cash_balance APIs. +type v1CashBalanceService struct { + B Backend + Key string +} + +// Retrieves a customer's cash balance. +func (c v1CashBalanceService) Retrieve(ctx context.Context, params *CashBalanceRetrieveParams) (*CashBalance, error) { + if params == nil { + params = &CashBalanceRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/cash_balance", StringValue(params.Customer)) + cashbalance := &CashBalance{} + err := c.B.Call(http.MethodGet, path, c.Key, params, cashbalance) + return cashbalance, err +} + +// Changes the settings on a customer's cash balance. +func (c v1CashBalanceService) Update(ctx context.Context, params *CashBalanceUpdateParams) (*CashBalance, error) { + if params == nil || params.Customer == nil { + return nil, fmt.Errorf( + "params cannot be nil, and params.Customer must be set") + } + if params == nil { + params = &CashBalanceUpdateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/cash_balance", StringValue(params.Customer)) + cashbalance := &CashBalance{} + err := c.B.Call(http.MethodPost, path, c.Key, params, cashbalance) + return cashbalance, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/charge.go b/vendor/github.com/stripe/stripe-go/v82/charge.go new file mode 100644 index 00000000..705bccb7 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/charge.go @@ -0,0 +1,1836 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Assessments from Stripe. If set, the value is `fraudulent`. +type ChargeFraudStripeReport string + +// List of values that ChargeFraudStripeReport can take +const ( + ChargeFraudStripeReportFraudulent ChargeFraudStripeReport = "fraudulent" +) + +// Assessments reported by you. If set, possible values of are `safe` and `fraudulent`. +type ChargeFraudUserReport string + +// List of values that ChargeFraudUserReport can take +const ( + ChargeFraudUserReportFraudulent ChargeFraudUserReport = "fraudulent" + ChargeFraudUserReportSafe ChargeFraudUserReport = "safe" +) + +// An enumerated value providing a more detailed explanation on [how to proceed with an error](https://stripe.com/docs/declines#retrying-issuer-declines). +type ChargeOutcomeAdviceCode string + +// List of values that ChargeOutcomeAdviceCode can take +const ( + ChargeOutcomeAdviceCodeConfirmCardData ChargeOutcomeAdviceCode = "confirm_card_data" + ChargeOutcomeAdviceCodeDoNotTryAgain ChargeOutcomeAdviceCode = "do_not_try_again" + ChargeOutcomeAdviceCodeTryAgainLater ChargeOutcomeAdviceCode = "try_again_later" +) + +// funding type of the underlying payment method. +type ChargePaymentMethodDetailsAmazonPayFundingType string + +// List of values that ChargePaymentMethodDetailsAmazonPayFundingType can take +const ( + ChargePaymentMethodDetailsAmazonPayFundingTypeCard ChargePaymentMethodDetailsAmazonPayFundingType = "card" +) + +// If a address line1 was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. +type ChargePaymentMethodDetailsCardChecksAddressLine1Check string + +// List of values that ChargePaymentMethodDetailsCardChecksAddressLine1Check can take +const ( + ChargePaymentMethodDetailsCardChecksAddressLine1CheckFail ChargePaymentMethodDetailsCardChecksAddressLine1Check = "fail" + ChargePaymentMethodDetailsCardChecksAddressLine1CheckPass ChargePaymentMethodDetailsCardChecksAddressLine1Check = "pass" + ChargePaymentMethodDetailsCardChecksAddressLine1CheckUnavailable ChargePaymentMethodDetailsCardChecksAddressLine1Check = "unavailable" + ChargePaymentMethodDetailsCardChecksAddressLine1CheckUnchecked ChargePaymentMethodDetailsCardChecksAddressLine1Check = "unchecked" +) + +// If a address postal code was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. +type ChargePaymentMethodDetailsCardChecksAddressPostalCodeCheck string + +// List of values that ChargePaymentMethodDetailsCardChecksAddressPostalCodeCheck can take +const ( + ChargePaymentMethodDetailsCardChecksAddressPostalCodeCheckFail ChargePaymentMethodDetailsCardChecksAddressPostalCodeCheck = "fail" + ChargePaymentMethodDetailsCardChecksAddressPostalCodeCheckPass ChargePaymentMethodDetailsCardChecksAddressPostalCodeCheck = "pass" + ChargePaymentMethodDetailsCardChecksAddressPostalCodeCheckUnavailable ChargePaymentMethodDetailsCardChecksAddressPostalCodeCheck = "unavailable" + ChargePaymentMethodDetailsCardChecksAddressPostalCodeCheckUnchecked ChargePaymentMethodDetailsCardChecksAddressPostalCodeCheck = "unchecked" +) + +// If a CVC was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. +type ChargePaymentMethodDetailsCardChecksCVCCheck string + +// List of values that ChargePaymentMethodDetailsCardChecksCVCCheck can take +const ( + ChargePaymentMethodDetailsCardChecksCVCCheckFail ChargePaymentMethodDetailsCardChecksCVCCheck = "fail" + ChargePaymentMethodDetailsCardChecksCVCCheckPass ChargePaymentMethodDetailsCardChecksCVCCheck = "pass" + ChargePaymentMethodDetailsCardChecksCVCCheckUnavailable ChargePaymentMethodDetailsCardChecksCVCCheck = "unavailable" + ChargePaymentMethodDetailsCardChecksCVCCheckUnchecked ChargePaymentMethodDetailsCardChecksCVCCheck = "unchecked" +) + +// Indicates whether or not the capture window is extended beyond the standard authorization. +type ChargePaymentMethodDetailsCardExtendedAuthorizationStatus string + +// List of values that ChargePaymentMethodDetailsCardExtendedAuthorizationStatus can take +const ( + ChargePaymentMethodDetailsCardExtendedAuthorizationStatusDisabled ChargePaymentMethodDetailsCardExtendedAuthorizationStatus = "disabled" + ChargePaymentMethodDetailsCardExtendedAuthorizationStatusEnabled ChargePaymentMethodDetailsCardExtendedAuthorizationStatus = "enabled" +) + +// Indicates whether or not the incremental authorization feature is supported. +type ChargePaymentMethodDetailsCardIncrementalAuthorizationStatus string + +// List of values that ChargePaymentMethodDetailsCardIncrementalAuthorizationStatus can take +const ( + ChargePaymentMethodDetailsCardIncrementalAuthorizationStatusAvailable ChargePaymentMethodDetailsCardIncrementalAuthorizationStatus = "available" + ChargePaymentMethodDetailsCardIncrementalAuthorizationStatusUnavailable ChargePaymentMethodDetailsCardIncrementalAuthorizationStatus = "unavailable" +) + +// Indicates whether or not multiple captures are supported. +type ChargePaymentMethodDetailsCardMulticaptureStatus string + +// List of values that ChargePaymentMethodDetailsCardMulticaptureStatus can take +const ( + ChargePaymentMethodDetailsCardMulticaptureStatusAvailable ChargePaymentMethodDetailsCardMulticaptureStatus = "available" + ChargePaymentMethodDetailsCardMulticaptureStatusUnavailable ChargePaymentMethodDetailsCardMulticaptureStatus = "unavailable" +) + +// Identifies which network this charge was processed on. Can be `amex`, `cartes_bancaires`, `diners`, `discover`, `eftpos_au`, `interac`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. +type ChargePaymentMethodDetailsCardNetwork string + +// List of values that ChargePaymentMethodDetailsCardNetwork can take +const ( + ChargePaymentMethodDetailsCardNetworkAmex ChargePaymentMethodDetailsCardNetwork = "amex" + ChargePaymentMethodDetailsCardNetworkCartesBancaires ChargePaymentMethodDetailsCardNetwork = "cartes_bancaires" + ChargePaymentMethodDetailsCardNetworkDiners ChargePaymentMethodDetailsCardNetwork = "diners" + ChargePaymentMethodDetailsCardNetworkDiscover ChargePaymentMethodDetailsCardNetwork = "discover" + ChargePaymentMethodDetailsCardNetworkInterac ChargePaymentMethodDetailsCardNetwork = "interac" + ChargePaymentMethodDetailsCardNetworkJCB ChargePaymentMethodDetailsCardNetwork = "jcb" + ChargePaymentMethodDetailsCardNetworkMastercard ChargePaymentMethodDetailsCardNetwork = "mastercard" + ChargePaymentMethodDetailsCardNetworkUnionpay ChargePaymentMethodDetailsCardNetwork = "unionpay" + ChargePaymentMethodDetailsCardNetworkVisa ChargePaymentMethodDetailsCardNetwork = "visa" + ChargePaymentMethodDetailsCardNetworkUnknown ChargePaymentMethodDetailsCardNetwork = "unknown" +) + +// Indicates whether or not the authorized amount can be over-captured. +type ChargePaymentMethodDetailsCardOvercaptureStatus string + +// List of values that ChargePaymentMethodDetailsCardOvercaptureStatus can take +const ( + ChargePaymentMethodDetailsCardOvercaptureStatusAvailable ChargePaymentMethodDetailsCardOvercaptureStatus = "available" + ChargePaymentMethodDetailsCardOvercaptureStatusUnavailable ChargePaymentMethodDetailsCardOvercaptureStatus = "unavailable" +) + +// Status of a card based on the card issuer. +type ChargePaymentMethodDetailsCardRegulatedStatus string + +// List of values that ChargePaymentMethodDetailsCardRegulatedStatus can take +const ( + ChargePaymentMethodDetailsCardRegulatedStatusRegulated ChargePaymentMethodDetailsCardRegulatedStatus = "regulated" + ChargePaymentMethodDetailsCardRegulatedStatusUnregulated ChargePaymentMethodDetailsCardRegulatedStatus = "unregulated" +) + +// For authenticated transactions: how the customer was authenticated by +// the issuing bank. +type ChargePaymentMethodDetailsCardThreeDSecureAuthenticationFlow string + +// List of values that ChargePaymentMethodDetailsCardThreeDSecureAuthenticationFlow can take +const ( + ChargePaymentMethodDetailsCardThreeDSecureAuthenticationFlowChallenge ChargePaymentMethodDetailsCardThreeDSecureAuthenticationFlow = "challenge" + ChargePaymentMethodDetailsCardThreeDSecureAuthenticationFlowFrictionless ChargePaymentMethodDetailsCardThreeDSecureAuthenticationFlow = "frictionless" +) + +// The Electronic Commerce Indicator (ECI). A protocol-level field +// indicating what degree of authentication was performed. +type ChargePaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator string + +// List of values that ChargePaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator can take +const ( + ChargePaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator01 ChargePaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator = "01" + ChargePaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator02 ChargePaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator = "02" + ChargePaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator05 ChargePaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator = "05" + ChargePaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator06 ChargePaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator = "06" + ChargePaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator07 ChargePaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator = "07" +) + +// The exemption requested via 3DS and accepted by the issuer at authentication time. +type ChargePaymentMethodDetailsCardThreeDSecureExemptionIndicator string + +// List of values that ChargePaymentMethodDetailsCardThreeDSecureExemptionIndicator can take +const ( + ChargePaymentMethodDetailsCardThreeDSecureExemptionIndicatorLowRisk ChargePaymentMethodDetailsCardThreeDSecureExemptionIndicator = "low_risk" + ChargePaymentMethodDetailsCardThreeDSecureExemptionIndicatorNone ChargePaymentMethodDetailsCardThreeDSecureExemptionIndicator = "none" +) + +// Indicates the outcome of 3D Secure authentication. +type ChargePaymentMethodDetailsCardThreeDSecureResult string + +// List of values that ChargePaymentMethodDetailsCardThreeDSecureResult can take +const ( + ChargePaymentMethodDetailsCardThreeDSecureResultAttemptAcknowledged ChargePaymentMethodDetailsCardThreeDSecureResult = "attempt_acknowledged" + ChargePaymentMethodDetailsCardThreeDSecureResultAuthenticated ChargePaymentMethodDetailsCardThreeDSecureResult = "authenticated" + ChargePaymentMethodDetailsCardThreeDSecureResultExempted ChargePaymentMethodDetailsCardThreeDSecureResult = "exempted" + ChargePaymentMethodDetailsCardThreeDSecureResultFailed ChargePaymentMethodDetailsCardThreeDSecureResult = "failed" + ChargePaymentMethodDetailsCardThreeDSecureResultNotSupported ChargePaymentMethodDetailsCardThreeDSecureResult = "not_supported" + ChargePaymentMethodDetailsCardThreeDSecureResultProcessingError ChargePaymentMethodDetailsCardThreeDSecureResult = "processing_error" +) + +// Additional information about why 3D Secure succeeded or failed based +// on the `result`. +type ChargePaymentMethodDetailsCardThreeDSecureResultReason string + +// List of values that ChargePaymentMethodDetailsCardThreeDSecureResultReason can take +const ( + ChargePaymentMethodDetailsCardThreeDSecureResultReasonAbandoned ChargePaymentMethodDetailsCardThreeDSecureResultReason = "abandoned" + ChargePaymentMethodDetailsCardThreeDSecureResultReasonBypassed ChargePaymentMethodDetailsCardThreeDSecureResultReason = "bypassed" + ChargePaymentMethodDetailsCardThreeDSecureResultReasonCanceled ChargePaymentMethodDetailsCardThreeDSecureResultReason = "canceled" + ChargePaymentMethodDetailsCardThreeDSecureResultReasonCardNotEnrolled ChargePaymentMethodDetailsCardThreeDSecureResultReason = "card_not_enrolled" + ChargePaymentMethodDetailsCardThreeDSecureResultReasonNetworkNotSupported ChargePaymentMethodDetailsCardThreeDSecureResultReason = "network_not_supported" + ChargePaymentMethodDetailsCardThreeDSecureResultReasonProtocolError ChargePaymentMethodDetailsCardThreeDSecureResultReason = "protocol_error" + ChargePaymentMethodDetailsCardThreeDSecureResultReasonRejected ChargePaymentMethodDetailsCardThreeDSecureResultReason = "rejected" +) + +// Identifies which network this charge was processed on. Can be `amex`, `cartes_bancaires`, `diners`, `discover`, `eftpos_au`, `interac`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. +type ChargePaymentMethodDetailsCardPresentNetwork string + +// List of values that ChargePaymentMethodDetailsCardPresentNetwork can take +const ( + ChargePaymentMethodDetailsCardPresentNetworkAmex ChargePaymentMethodDetailsCardPresentNetwork = "amex" + ChargePaymentMethodDetailsCardPresentNetworkCartesBancaires ChargePaymentMethodDetailsCardPresentNetwork = "cartes_bancaires" + ChargePaymentMethodDetailsCardPresentNetworkDiners ChargePaymentMethodDetailsCardPresentNetwork = "diners" + ChargePaymentMethodDetailsCardPresentNetworkDiscover ChargePaymentMethodDetailsCardPresentNetwork = "discover" + ChargePaymentMethodDetailsCardPresentNetworkInterac ChargePaymentMethodDetailsCardPresentNetwork = "interac" + ChargePaymentMethodDetailsCardPresentNetworkJCB ChargePaymentMethodDetailsCardPresentNetwork = "jcb" + ChargePaymentMethodDetailsCardPresentNetworkMastercard ChargePaymentMethodDetailsCardPresentNetwork = "mastercard" + ChargePaymentMethodDetailsCardPresentNetworkUnionpay ChargePaymentMethodDetailsCardPresentNetwork = "unionpay" + ChargePaymentMethodDetailsCardPresentNetworkVisa ChargePaymentMethodDetailsCardPresentNetwork = "visa" + ChargePaymentMethodDetailsCardPresentNetworkUnknown ChargePaymentMethodDetailsCardPresentNetwork = "unknown" +) + +// The method used to process this payment method offline. Only deferred is allowed. +type ChargePaymentMethodDetailsCardPresentOfflineType string + +// List of values that ChargePaymentMethodDetailsCardPresentOfflineType can take +const ( + ChargePaymentMethodDetailsCardPresentOfflineTypeDeferred ChargePaymentMethodDetailsCardPresentOfflineType = "deferred" +) + +// The type of account being debited or credited +type ChargePaymentMethodDetailsCardPresentReceiptAccountType string + +// List of values that ChargePaymentMethodDetailsCardPresentReceiptAccountType can take +const ( + ChargePaymentMethodDetailsCardPresentReceiptAccountTypeChecking ChargePaymentMethodDetailsCardPresentReceiptAccountType = "checking" + ChargePaymentMethodDetailsCardPresentReceiptAccountTypeCredit ChargePaymentMethodDetailsCardPresentReceiptAccountType = "credit" + ChargePaymentMethodDetailsCardPresentReceiptAccountTypePrepaid ChargePaymentMethodDetailsCardPresentReceiptAccountType = "prepaid" + ChargePaymentMethodDetailsCardPresentReceiptAccountTypeUnknown ChargePaymentMethodDetailsCardPresentReceiptAccountType = "unknown" +) + +// The type of mobile wallet, one of `apple_pay`, `google_pay`, `samsung_pay`, or `unknown`. +type ChargePaymentMethodDetailsCardPresentWalletType string + +// List of values that ChargePaymentMethodDetailsCardPresentWalletType can take +const ( + ChargePaymentMethodDetailsCardPresentWalletTypeApplePay ChargePaymentMethodDetailsCardPresentWalletType = "apple_pay" + ChargePaymentMethodDetailsCardPresentWalletTypeGooglePay ChargePaymentMethodDetailsCardPresentWalletType = "google_pay" + ChargePaymentMethodDetailsCardPresentWalletTypeSamsungPay ChargePaymentMethodDetailsCardPresentWalletType = "samsung_pay" + ChargePaymentMethodDetailsCardPresentWalletTypeUnknown ChargePaymentMethodDetailsCardPresentWalletType = "unknown" +) + +// The blockchain network that the transaction was sent on. +type ChargePaymentMethodDetailsCryptoNetwork string + +// List of values that ChargePaymentMethodDetailsCryptoNetwork can take +const ( + ChargePaymentMethodDetailsCryptoNetworkBase ChargePaymentMethodDetailsCryptoNetwork = "base" + ChargePaymentMethodDetailsCryptoNetworkEthereum ChargePaymentMethodDetailsCryptoNetwork = "ethereum" + ChargePaymentMethodDetailsCryptoNetworkPolygon ChargePaymentMethodDetailsCryptoNetwork = "polygon" +) + +// The token currency that the transaction was sent with. +type ChargePaymentMethodDetailsCryptoTokenCurrency string + +// List of values that ChargePaymentMethodDetailsCryptoTokenCurrency can take +const ( + ChargePaymentMethodDetailsCryptoTokenCurrencyUsdc ChargePaymentMethodDetailsCryptoTokenCurrency = "usdc" + ChargePaymentMethodDetailsCryptoTokenCurrencyUsdg ChargePaymentMethodDetailsCryptoTokenCurrency = "usdg" + ChargePaymentMethodDetailsCryptoTokenCurrencyUsdp ChargePaymentMethodDetailsCryptoTokenCurrency = "usdp" +) + +// The Klarna payment method used for this transaction. +// Can be one of `pay_later`, `pay_now`, `pay_with_financing`, or `pay_in_installments` +type ChargePaymentMethodDetailsKlarnaPaymentMethodCategory string + +// List of values that ChargePaymentMethodDetailsKlarnaPaymentMethodCategory can take +const ( + ChargePaymentMethodDetailsKlarnaPaymentMethodCategoryPayLater ChargePaymentMethodDetailsKlarnaPaymentMethodCategory = "pay_later" + ChargePaymentMethodDetailsKlarnaPaymentMethodCategoryPayNow ChargePaymentMethodDetailsKlarnaPaymentMethodCategory = "pay_now" + ChargePaymentMethodDetailsKlarnaPaymentMethodCategoryPayWithFinancing ChargePaymentMethodDetailsKlarnaPaymentMethodCategory = "pay_with_financing" + ChargePaymentMethodDetailsKlarnaPaymentMethodCategoryPayInInstallments ChargePaymentMethodDetailsKlarnaPaymentMethodCategory = "pay_in_installments" +) + +// The name of the convenience store chain where the payment was completed. +type ChargePaymentMethodDetailsKonbiniStoreChain string + +// List of values that ChargePaymentMethodDetailsKonbiniStoreChain can take +const ( + ChargePaymentMethodDetailsKonbiniStoreChainFamilyMart ChargePaymentMethodDetailsKonbiniStoreChain = "familymart" + ChargePaymentMethodDetailsKonbiniStoreChainLawson ChargePaymentMethodDetailsKonbiniStoreChain = "lawson" + ChargePaymentMethodDetailsKonbiniStoreChainMinistop ChargePaymentMethodDetailsKonbiniStoreChain = "ministop" + ChargePaymentMethodDetailsKonbiniStoreChainSeicomart ChargePaymentMethodDetailsKonbiniStoreChain = "seicomart" +) + +// The local credit or debit card brand. +type ChargePaymentMethodDetailsKrCardBrand string + +// List of values that ChargePaymentMethodDetailsKrCardBrand can take +const ( + ChargePaymentMethodDetailsKrCardBrandBc ChargePaymentMethodDetailsKrCardBrand = "bc" + ChargePaymentMethodDetailsKrCardBrandCiti ChargePaymentMethodDetailsKrCardBrand = "citi" + ChargePaymentMethodDetailsKrCardBrandHana ChargePaymentMethodDetailsKrCardBrand = "hana" + ChargePaymentMethodDetailsKrCardBrandHyundai ChargePaymentMethodDetailsKrCardBrand = "hyundai" + ChargePaymentMethodDetailsKrCardBrandJeju ChargePaymentMethodDetailsKrCardBrand = "jeju" + ChargePaymentMethodDetailsKrCardBrandJeonbuk ChargePaymentMethodDetailsKrCardBrand = "jeonbuk" + ChargePaymentMethodDetailsKrCardBrandKakaobank ChargePaymentMethodDetailsKrCardBrand = "kakaobank" + ChargePaymentMethodDetailsKrCardBrandKbank ChargePaymentMethodDetailsKrCardBrand = "kbank" + ChargePaymentMethodDetailsKrCardBrandKdbbank ChargePaymentMethodDetailsKrCardBrand = "kdbbank" + ChargePaymentMethodDetailsKrCardBrandKookmin ChargePaymentMethodDetailsKrCardBrand = "kookmin" + ChargePaymentMethodDetailsKrCardBrandKwangju ChargePaymentMethodDetailsKrCardBrand = "kwangju" + ChargePaymentMethodDetailsKrCardBrandLotte ChargePaymentMethodDetailsKrCardBrand = "lotte" + ChargePaymentMethodDetailsKrCardBrandMg ChargePaymentMethodDetailsKrCardBrand = "mg" + ChargePaymentMethodDetailsKrCardBrandNh ChargePaymentMethodDetailsKrCardBrand = "nh" + ChargePaymentMethodDetailsKrCardBrandPost ChargePaymentMethodDetailsKrCardBrand = "post" + ChargePaymentMethodDetailsKrCardBrandSamsung ChargePaymentMethodDetailsKrCardBrand = "samsung" + ChargePaymentMethodDetailsKrCardBrandSavingsbank ChargePaymentMethodDetailsKrCardBrand = "savingsbank" + ChargePaymentMethodDetailsKrCardBrandShinhan ChargePaymentMethodDetailsKrCardBrand = "shinhan" + ChargePaymentMethodDetailsKrCardBrandShinhyup ChargePaymentMethodDetailsKrCardBrand = "shinhyup" + ChargePaymentMethodDetailsKrCardBrandSuhyup ChargePaymentMethodDetailsKrCardBrand = "suhyup" + ChargePaymentMethodDetailsKrCardBrandTossbank ChargePaymentMethodDetailsKrCardBrand = "tossbank" + ChargePaymentMethodDetailsKrCardBrandWoori ChargePaymentMethodDetailsKrCardBrand = "woori" +) + +// An array of conditions that are covered for the transaction, if applicable. +type ChargePaymentMethodDetailsPaypalSellerProtectionDisputeCategory string + +// List of values that ChargePaymentMethodDetailsPaypalSellerProtectionDisputeCategory can take +const ( + ChargePaymentMethodDetailsPaypalSellerProtectionDisputeCategoryFraudulent ChargePaymentMethodDetailsPaypalSellerProtectionDisputeCategory = "fraudulent" + ChargePaymentMethodDetailsPaypalSellerProtectionDisputeCategoryProductNotReceived ChargePaymentMethodDetailsPaypalSellerProtectionDisputeCategory = "product_not_received" +) + +// Indicates whether the transaction is eligible for PayPal's seller protection. +type ChargePaymentMethodDetailsPaypalSellerProtectionStatus string + +// List of values that ChargePaymentMethodDetailsPaypalSellerProtectionStatus can take +const ( + ChargePaymentMethodDetailsPaypalSellerProtectionStatusEligible ChargePaymentMethodDetailsPaypalSellerProtectionStatus = "eligible" + ChargePaymentMethodDetailsPaypalSellerProtectionStatusNotEligible ChargePaymentMethodDetailsPaypalSellerProtectionStatus = "not_eligible" + ChargePaymentMethodDetailsPaypalSellerProtectionStatusPartiallyEligible ChargePaymentMethodDetailsPaypalSellerProtectionStatus = "partially_eligible" +) + +// funding type of the underlying payment method. +type ChargePaymentMethodDetailsRevolutPayFundingType string + +// List of values that ChargePaymentMethodDetailsRevolutPayFundingType can take +const ( + ChargePaymentMethodDetailsRevolutPayFundingTypeCard ChargePaymentMethodDetailsRevolutPayFundingType = "card" +) + +// The type of transaction-specific details of the payment method used in the payment. See [PaymentMethod.type](https://stripe.com/docs/api/payment_methods/object#payment_method_object-type) for the full list of possible types. +// An additional hash is included on `payment_method_details` with a name matching this value. +// It contains information specific to the payment method. +type ChargePaymentMethodDetailsType string + +// List of values that ChargePaymentMethodDetailsType can take +const ( + ChargePaymentMethodDetailsTypeACHCreditTransfer ChargePaymentMethodDetailsType = "ach_credit_transfer" + ChargePaymentMethodDetailsTypeACHDebit ChargePaymentMethodDetailsType = "ach_debit" + ChargePaymentMethodDetailsTypeACSSDebit ChargePaymentMethodDetailsType = "acss_debit" + ChargePaymentMethodDetailsTypeAlipay ChargePaymentMethodDetailsType = "alipay" + ChargePaymentMethodDetailsTypeAUBECSDebit ChargePaymentMethodDetailsType = "au_becs_debit" + ChargePaymentMethodDetailsTypeBACSDebit ChargePaymentMethodDetailsType = "bacs_debit" + ChargePaymentMethodDetailsTypeBancontact ChargePaymentMethodDetailsType = "bancontact" + ChargePaymentMethodDetailsTypeCard ChargePaymentMethodDetailsType = "card" + ChargePaymentMethodDetailsTypeCardPresent ChargePaymentMethodDetailsType = "card_present" + ChargePaymentMethodDetailsTypeEPS ChargePaymentMethodDetailsType = "eps" + ChargePaymentMethodDetailsTypeFPX ChargePaymentMethodDetailsType = "fpx" + ChargePaymentMethodDetailsTypeGiropay ChargePaymentMethodDetailsType = "giropay" + ChargePaymentMethodDetailsTypeGrabpay ChargePaymentMethodDetailsType = "grabpay" + ChargePaymentMethodDetailsTypeIDEAL ChargePaymentMethodDetailsType = "ideal" + ChargePaymentMethodDetailsTypeInteracPresent ChargePaymentMethodDetailsType = "interac_present" + ChargePaymentMethodDetailsTypeKlarna ChargePaymentMethodDetailsType = "klarna" + ChargePaymentMethodDetailsTypeMultibanco ChargePaymentMethodDetailsType = "multibanco" + ChargePaymentMethodDetailsTypeP24 ChargePaymentMethodDetailsType = "p24" + ChargePaymentMethodDetailsTypeSEPADebit ChargePaymentMethodDetailsType = "sepa_debit" + ChargePaymentMethodDetailsTypeSofort ChargePaymentMethodDetailsType = "sofort" + ChargePaymentMethodDetailsTypeSwish ChargePaymentMethodDetailsType = "swish" + ChargePaymentMethodDetailsTypeStripeAccount ChargePaymentMethodDetailsType = "stripe_account" + ChargePaymentMethodDetailsTypeWeChat ChargePaymentMethodDetailsType = "wechat" +) + +// Account holder type: individual or company. +type ChargePaymentMethodDetailsUSBankAccountAccountHolderType string + +// List of values that ChargePaymentMethodDetailsUSBankAccountAccountHolderType can take +const ( + ChargePaymentMethodDetailsUSBankAccountAccountHolderTypeCompany ChargePaymentMethodDetailsUSBankAccountAccountHolderType = "company" + ChargePaymentMethodDetailsUSBankAccountAccountHolderTypeIndividual ChargePaymentMethodDetailsUSBankAccountAccountHolderType = "individual" +) + +// Account type: checkings or savings. Defaults to checking if omitted. +type ChargePaymentMethodDetailsUSBankAccountAccountType string + +// List of values that ChargePaymentMethodDetailsUSBankAccountAccountType can take +const ( + ChargePaymentMethodDetailsUSBankAccountAccountTypeChecking ChargePaymentMethodDetailsUSBankAccountAccountType = "checking" + ChargePaymentMethodDetailsUSBankAccountAccountTypeSavings ChargePaymentMethodDetailsUSBankAccountAccountType = "savings" +) + +// The status of the payment is either `succeeded`, `pending`, or `failed`. +type ChargeStatus string + +// List of values that ChargeStatus can take +const ( + ChargeStatusFailed ChargeStatus = "failed" + ChargeStatusPending ChargeStatus = "pending" + ChargeStatusSucceeded ChargeStatus = "succeeded" +) + +// Returns a list of charges you've previously created. The charges are returned in sorted order, with the most recent charges appearing first. +type ChargeListParams struct { + ListParams `form:"*"` + // Only return charges that were created during the given date interval. + Created *int64 `form:"created"` + // Only return charges that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Only return charges for the customer specified by this customer ID. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return charges that were created by the PaymentIntent specified by this PaymentIntent ID. + PaymentIntent *string `form:"payment_intent"` + // Only return charges for this transfer group, limited to 100. + TransferGroup *string `form:"transfer_group"` +} + +// AddExpand appends a new field to expand. +func (p *ChargeListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type ChargeDestinationParams struct { + // ID of an existing, connected Stripe account. + Account *string `form:"account"` + // The amount to transfer to the destination account without creating an `Application Fee` object. Cannot be combined with the `application_fee` parameter. Must be less than or equal to the charge amount. + Amount *int64 `form:"amount"` +} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type ChargeRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// An optional dictionary including the account to automatically transfer to as part of a destination charge. [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. +type ChargeTransferDataParams struct { + // The amount transferred to the destination account, if specified. By default, the entire charge amount is transferred to the destination account. + Amount *int64 `form:"amount"` + // This parameter can only be used on Charge creation. + // ID of an existing, connected Stripe account. + Destination *string `form:"destination"` +} +type ChargeLevel3LineItemParams struct { + DiscountAmount *int64 `form:"discount_amount"` + ProductCode *string `form:"product_code"` + ProductDescription *string `form:"product_description"` + Quantity *int64 `form:"quantity"` + TaxAmount *int64 `form:"tax_amount"` + UnitCost *int64 `form:"unit_cost"` +} +type ChargeLevel3Params struct { + CustomerReference *string `form:"customer_reference"` + LineItems []*ChargeLevel3LineItemParams `form:"line_items"` + MerchantReference *string `form:"merchant_reference"` + ShippingAddressZip *string `form:"shipping_address_zip"` + ShippingAmount *int64 `form:"shipping_amount"` + ShippingFromZip *string `form:"shipping_from_zip"` +} + +// This method is no longer recommended—use the [Payment Intents API](https://docs.stripe.com/docs/api/payment_intents) +// to initiate a new payment instead. Confirmation of the PaymentIntent creates the Charge +// object used to request payment. +type ChargeParams struct { + Params `form:"*"` + // Amount intended to be collected by this payment. A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + Amount *int64 `form:"amount"` + ApplicationFee *int64 `form:"application_fee"` + // A fee in cents (or local equivalent) that will be applied to the charge and transferred to the application owner's Stripe account. The request must be made with an OAuth key or the `Stripe-Account` header in order to take an application fee. For more information, see the application fees [documentation](https://stripe.com/docs/connect/direct-charges#collect-fees). + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // Whether to immediately capture the charge. Defaults to `true`. When `false`, the charge issues an authorization (or pre-authorization), and will need to be [captured](https://stripe.com/docs/api#capture_charge) later. Uncaptured charges expire after a set number of days (7 by default). For more information, see the [authorizing charges and settling later](https://stripe.com/docs/charges/placing-a-hold) documentation. + Capture *bool `form:"capture"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of an existing customer that will be associated with this request. This field may only be updated if there is no existing associated customer with this charge. + Customer *string `form:"customer"` + // An arbitrary string which you can attach to a `Charge` object. It is displayed when in the web interface alongside the charge. Note that if you use Stripe to send automatic email receipts to your customers, your receipt emails will include the `description` of the charge(s) that they are describing. + Description *string `form:"description"` + Destination *ChargeDestinationParams `form:"destination"` + ExchangeRate *float64 `form:"exchange_rate"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A set of key-value pairs you can attach to a charge giving information about its riskiness. If you believe a charge is fraudulent, include a `user_report` key with a value of `fraudulent`. If you believe a charge is safe, include a `user_report` key with a value of `safe`. Stripe will use the information you send to improve our fraud detection algorithms. + FraudDetails *ChargeFraudDetailsParams `form:"fraud_details"` + Level3 *ChargeLevel3Params `form:"level3"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The Stripe account ID for which these funds are intended. Automatically set if you use the `destination` parameter. For details, see [Creating Separate Charges and Transfers](https://stripe.com/docs/connect/separate-charges-and-transfers#settlement-merchant). + OnBehalfOf *string `form:"on_behalf_of"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *ChargeRadarOptionsParams `form:"radar_options"` + // The email address to which this charge's [receipt](https://stripe.com/docs/dashboard/receipts) will be sent. The receipt will not be sent until the charge is paid, and no receipts will be sent for test mode charges. If this charge is for a [Customer](https://stripe.com/docs/api/customers/object), the email address specified here will override the customer's email address. If `receipt_email` is specified for a charge in live mode, a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). + ReceiptEmail *string `form:"receipt_email"` + // Shipping information for the charge. Helps prevent fraud on charges for physical goods. + Shipping *ShippingDetailsParams `form:"shipping"` + Source *PaymentSourceSourceParams `form:"*"` // PaymentSourceSourceParams has custom encoding so brought to top level with "*" + // For a non-card charge, text that appears on the customer's statement as the statement descriptor. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + // + // For a card charge, this value is ignored unless you don't specify a `statement_descriptor_suffix`, in which case this value is used as the suffix. + StatementDescriptor *string `form:"statement_descriptor"` + // Provides information about a card charge. Concatenated to the account's [statement descriptor prefix](https://docs.stripe.com/get-started/account/statement-descriptors#static) to form the complete statement descriptor that appears on the customer's statement. If the account has no prefix value, the suffix is concatenated to the account's statement descriptor. + StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"` + // An optional dictionary including the account to automatically transfer to as part of a destination charge. [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. + TransferData *ChargeTransferDataParams `form:"transfer_data"` + // A string that identifies this transaction as part of a group. `transfer_group` may only be provided if it has not been set. See the [Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-options) for details. + TransferGroup *string `form:"transfer_group"` +} + +// SetSource adds valid sources to a ChargeParams object, +// returning an error for unsupported sources. +func (p *ChargeParams) SetSource(sp interface{}) error { + source, err := SourceParamsFor(sp) + p.Source = source + return err +} + +// AddExpand appends a new field to expand. +func (p *ChargeParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ChargeParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A set of key-value pairs you can attach to a charge giving information about its riskiness. If you believe a charge is fraudulent, include a `user_report` key with a value of `fraudulent`. If you believe a charge is safe, include a `user_report` key with a value of `safe`. Stripe will use the information you send to improve our fraud detection algorithms. +type ChargeFraudDetailsParams struct { + // Either `safe` or `fraudulent`. + UserReport *string `form:"user_report"` +} + +// Search for charges you've previously created using Stripe's [Search Query Language](https://docs.stripe.com/docs/search#search-query-language). +// Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating +// conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up +// to an hour behind during outages. Search functionality is not available to merchants in India. +type ChargeSearchParams struct { + SearchParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + Page *string `form:"page"` +} + +// AddExpand appends a new field to expand. +func (p *ChargeSearchParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// An optional dictionary including the account to automatically transfer to as part of a destination charge. [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. +type ChargeCaptureTransferDataParams struct { + // The amount transferred to the destination account, if specified. By default, the entire charge amount is transferred to the destination account. + Amount *int64 `form:"amount"` +} + +// Capture the payment of an existing, uncaptured charge that was created with the capture option set to false. +// +// Uncaptured payments expire a set number of days after they are created ([7 by default](https://docs.stripe.com/docs/charges/placing-a-hold)), after which they are marked as refunded and capture attempts will fail. +// +// Don't use this method to capture a PaymentIntent-initiated charge. Use [Capture a PaymentIntent](https://docs.stripe.com/docs/api/payment_intents/capture). +type ChargeCaptureParams struct { + Params `form:"*"` + // The amount to capture, which must be less than or equal to the original amount. + Amount *int64 `form:"amount"` + // An application fee to add on to this charge. + ApplicationFee *int64 `form:"application_fee"` + // An application fee amount to add on to this charge, which must be less than or equal to the original amount. + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + ExchangeRate *float64 `form:"exchange_rate"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The email address to send this charge's receipt to. This will override the previously-specified email address for this charge, if one was set. Receipts will not be sent in test mode. + ReceiptEmail *string `form:"receipt_email"` + // For a non-card charge, text that appears on the customer's statement as the statement descriptor. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + // + // For a card charge, this value is ignored unless you don't specify a `statement_descriptor_suffix`, in which case this value is used as the suffix. + StatementDescriptor *string `form:"statement_descriptor"` + // Provides information about a card charge. Concatenated to the account's [statement descriptor prefix](https://docs.stripe.com/get-started/account/statement-descriptors#static) to form the complete statement descriptor that appears on the customer's statement. If the account has no prefix value, the suffix is concatenated to the account's statement descriptor. + StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"` + // An optional dictionary including the account to automatically transfer to as part of a destination charge. [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. + TransferData *ChargeCaptureTransferDataParams `form:"transfer_data"` + // A string that identifies this transaction as part of a group. `transfer_group` may only be provided if it has not been set. See the [Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-options) for details. + TransferGroup *string `form:"transfer_group"` +} + +// AddExpand appends a new field to expand. +func (p *ChargeCaptureParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type ChargeCreateDestinationParams struct { + // ID of an existing, connected Stripe account. + Account *string `form:"account"` + // The amount to transfer to the destination account without creating an `Application Fee` object. Cannot be combined with the `application_fee` parameter. Must be less than or equal to the charge amount. + Amount *int64 `form:"amount"` +} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type ChargeCreateRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// An optional dictionary including the account to automatically transfer to as part of a destination charge. [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. +type ChargeCreateTransferDataParams struct { + // The amount transferred to the destination account, if specified. By default, the entire charge amount is transferred to the destination account. + Amount *int64 `form:"amount"` + // ID of an existing, connected Stripe account. + Destination *string `form:"destination"` +} +type ChargeCreateLevel3LineItemParams struct { + DiscountAmount *int64 `form:"discount_amount"` + ProductCode *string `form:"product_code"` + ProductDescription *string `form:"product_description"` + Quantity *int64 `form:"quantity"` + TaxAmount *int64 `form:"tax_amount"` + UnitCost *int64 `form:"unit_cost"` +} +type ChargeCreateLevel3Params struct { + CustomerReference *string `form:"customer_reference"` + LineItems []*ChargeCreateLevel3LineItemParams `form:"line_items"` + MerchantReference *string `form:"merchant_reference"` + ShippingAddressZip *string `form:"shipping_address_zip"` + ShippingAmount *int64 `form:"shipping_amount"` + ShippingFromZip *string `form:"shipping_from_zip"` +} + +// This method is no longer recommended—use the [Payment Intents API](https://docs.stripe.com/docs/api/payment_intents) +// to initiate a new payment instead. Confirmation of the PaymentIntent creates the Charge +// object used to request payment. +type ChargeCreateParams struct { + Params `form:"*"` + // Amount intended to be collected by this payment. A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + Amount *int64 `form:"amount"` + ApplicationFee *int64 `form:"application_fee"` + // A fee in cents (or local equivalent) that will be applied to the charge and transferred to the application owner's Stripe account. The request must be made with an OAuth key or the `Stripe-Account` header in order to take an application fee. For more information, see the application fees [documentation](https://stripe.com/docs/connect/direct-charges#collect-fees). + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // Whether to immediately capture the charge. Defaults to `true`. When `false`, the charge issues an authorization (or pre-authorization), and will need to be [captured](https://stripe.com/docs/api#capture_charge) later. Uncaptured charges expire after a set number of days (7 by default). For more information, see the [authorizing charges and settling later](https://stripe.com/docs/charges/placing-a-hold) documentation. + Capture *bool `form:"capture"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of an existing customer that will be charged in this request. + Customer *string `form:"customer"` + // An arbitrary string which you can attach to a `Charge` object. It is displayed when in the web interface alongside the charge. Note that if you use Stripe to send automatic email receipts to your customers, your receipt emails will include the `description` of the charge(s) that they are describing. + Description *string `form:"description"` + Destination *ChargeCreateDestinationParams `form:"destination"` + ExchangeRate *float64 `form:"exchange_rate"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + Level3 *ChargeCreateLevel3Params `form:"level3"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The Stripe account ID for which these funds are intended. Automatically set if you use the `destination` parameter. For details, see [Creating Separate Charges and Transfers](https://stripe.com/docs/connect/separate-charges-and-transfers#settlement-merchant). + OnBehalfOf *string `form:"on_behalf_of"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *ChargeCreateRadarOptionsParams `form:"radar_options"` + // The email address to which this charge's [receipt](https://stripe.com/docs/dashboard/receipts) will be sent. The receipt will not be sent until the charge is paid, and no receipts will be sent for test mode charges. If this charge is for a [Customer](https://stripe.com/docs/api/customers/object), the email address specified here will override the customer's email address. If `receipt_email` is specified for a charge in live mode, a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). + ReceiptEmail *string `form:"receipt_email"` + // Shipping information for the charge. Helps prevent fraud on charges for physical goods. + Shipping *ShippingDetailsParams `form:"shipping"` + Source *PaymentSourceSourceParams `form:"*"` // PaymentSourceSourceParams has custom encoding so brought to top level with "*" + // For a non-card charge, text that appears on the customer's statement as the statement descriptor. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + // + // For a card charge, this value is ignored unless you don't specify a `statement_descriptor_suffix`, in which case this value is used as the suffix. + StatementDescriptor *string `form:"statement_descriptor"` + // Provides information about a card charge. Concatenated to the account's [statement descriptor prefix](https://docs.stripe.com/get-started/account/statement-descriptors#static) to form the complete statement descriptor that appears on the customer's statement. If the account has no prefix value, the suffix is concatenated to the account's statement descriptor. + StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"` + // An optional dictionary including the account to automatically transfer to as part of a destination charge. [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. + TransferData *ChargeCreateTransferDataParams `form:"transfer_data"` + // A string that identifies this transaction as part of a group. For details, see [Grouping transactions](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-options). + TransferGroup *string `form:"transfer_group"` +} + +// SetSource adds valid sources to a ChargeCreateParams object, +// returning an error for unsupported sources. +func (p *ChargeCreateParams) SetSource(sp interface{}) error { + source, err := SourceParamsFor(sp) + p.Source = source + return err +} + +// AddExpand appends a new field to expand. +func (p *ChargeCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ChargeCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the details of a charge that has previously been created. Supply the unique charge ID that was returned from your previous request, and Stripe will return the corresponding charge information. The same information is returned when creating or refunding the charge. +type ChargeRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ChargeRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A set of key-value pairs you can attach to a charge giving information about its riskiness. If you believe a charge is fraudulent, include a `user_report` key with a value of `fraudulent`. If you believe a charge is safe, include a `user_report` key with a value of `safe`. Stripe will use the information you send to improve our fraud detection algorithms. +type ChargeUpdateFraudDetailsParams struct { + // Either `safe` or `fraudulent`. + UserReport *string `form:"user_report"` +} + +// Updates the specified charge by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +type ChargeUpdateParams struct { + Params `form:"*"` + // The ID of an existing customer that will be associated with this request. This field may only be updated if there is no existing associated customer with this charge. + Customer *string `form:"customer"` + // An arbitrary string which you can attach to a charge object. It is displayed when in the web interface alongside the charge. Note that if you use Stripe to send automatic email receipts to your customers, your receipt emails will include the `description` of the charge(s) that they are describing. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A set of key-value pairs you can attach to a charge giving information about its riskiness. If you believe a charge is fraudulent, include a `user_report` key with a value of `fraudulent`. If you believe a charge is safe, include a `user_report` key with a value of `safe`. Stripe will use the information you send to improve our fraud detection algorithms. + FraudDetails *ChargeUpdateFraudDetailsParams `form:"fraud_details"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // This is the email address that the receipt for this charge will be sent to. If this field is updated, then a new email receipt will be sent to the updated address. + ReceiptEmail *string `form:"receipt_email"` + // Shipping information for the charge. Helps prevent fraud on charges for physical goods. + Shipping *ShippingDetailsParams `form:"shipping"` + // A string that identifies this transaction as part of a group. `transfer_group` may only be provided if it has not been set. See the [Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-options) for details. + TransferGroup *string `form:"transfer_group"` +} + +// AddExpand appends a new field to expand. +func (p *ChargeUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ChargeUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +type ChargeBillingDetails struct { + // Billing address. + Address *Address `json:"address"` + // Email address. + Email string `json:"email"` + // Full name. + Name string `json:"name"` + // Billing phone number (including extension). + Phone string `json:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID string `json:"tax_id"` +} + +// Information on fraud assessments for the charge. +type ChargeFraudDetails struct { + // Assessments from Stripe. If set, the value is `fraudulent`. + StripeReport ChargeFraudStripeReport `json:"stripe_report"` + // Assessments reported by you. If set, possible values of are `safe` and `fraudulent`. + UserReport ChargeFraudUserReport `json:"user_report"` +} +type ChargeLevel3LineItem struct { + DiscountAmount int64 `json:"discount_amount"` + ProductCode string `json:"product_code"` + ProductDescription string `json:"product_description"` + Quantity int64 `json:"quantity"` + TaxAmount int64 `json:"tax_amount"` + UnitCost int64 `json:"unit_cost"` +} +type ChargeLevel3 struct { + CustomerReference string `json:"customer_reference"` + LineItems []*ChargeLevel3LineItem `json:"line_items"` + MerchantReference string `json:"merchant_reference"` + ShippingAddressZip string `json:"shipping_address_zip"` + ShippingAmount int64 `json:"shipping_amount"` + ShippingFromZip string `json:"shipping_from_zip"` +} + +// The ID of the Radar rule that matched the payment, if applicable. +type ChargeOutcomeRule struct { + // The action taken on the payment. + Action string `json:"action"` + // Unique identifier for the object. + ID string `json:"id"` + // The predicate to evaluate the payment against. + Predicate string `json:"predicate"` +} + +// Details about whether the payment was accepted, and why. See [understanding declines](https://stripe.com/docs/declines) for details. +type ChargeOutcome struct { + // An enumerated value providing a more detailed explanation on [how to proceed with an error](https://stripe.com/docs/declines#retrying-issuer-declines). + AdviceCode ChargeOutcomeAdviceCode `json:"advice_code"` + // For charges declined by the network, a 2 digit code which indicates the advice returned by the network on how to proceed with an error. + NetworkAdviceCode string `json:"network_advice_code"` + // For charges declined by the network, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. + NetworkDeclineCode string `json:"network_decline_code"` + // Possible values are `approved_by_network`, `declined_by_network`, `not_sent_to_network`, and `reversed_after_approval`. The value `reversed_after_approval` indicates the payment was [blocked by Stripe](https://stripe.com/docs/declines#blocked-payments) after bank authorization, and may temporarily appear as "pending" on a cardholder's statement. + NetworkStatus string `json:"network_status"` + // An enumerated value providing a more detailed explanation of the outcome's `type`. Charges blocked by Radar's default block rule have the value `highest_risk_level`. Charges placed in review by Radar's default review rule have the value `elevated_risk_level`. Charges authorized, blocked, or placed in review by custom rules have the value `rule`. See [understanding declines](https://stripe.com/docs/declines) for more details. + Reason string `json:"reason"` + // Stripe Radar's evaluation of the riskiness of the payment. Possible values for evaluated payments are `normal`, `elevated`, `highest`. For non-card payments, and card-based payments predating the public assignment of risk levels, this field will have the value `not_assessed`. In the event of an error in the evaluation, this field will have the value `unknown`. This field is only available with Radar. + RiskLevel string `json:"risk_level"` + // Stripe Radar's evaluation of the riskiness of the payment. Possible values for evaluated payments are between 0 and 100. For non-card payments, card-based payments predating the public assignment of risk scores, or in the event of an error during evaluation, this field will not be present. This field is only available with Radar for Fraud Teams. + RiskScore int64 `json:"risk_score"` + // The ID of the Radar rule that matched the payment, if applicable. + Rule *ChargeOutcomeRule `json:"rule"` + // A human-readable description of the outcome type and reason, designed for you (the recipient of the payment), not your customer. + SellerMessage string `json:"seller_message"` + // Possible values are `authorized`, `manual_review`, `issuer_declined`, `blocked`, and `invalid`. See [understanding declines](https://stripe.com/docs/declines) and [Radar reviews](https://stripe.com/docs/radar/reviews) for details. + Type string `json:"type"` +} + +// UnmarshalJSON handles deserialization of a ChargeOutcomeRule. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (c *ChargeOutcomeRule) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + c.ID = id + return nil + } + type chargeOutcomeRule ChargeOutcomeRule + var v chargeOutcomeRule + if err := json.Unmarshal(data, &v); err != nil { + return err + } + *c = ChargeOutcomeRule(v) + return nil +} + +type ChargePaymentMethodDetailsACHCreditTransfer struct { + // Account number to transfer funds to. + AccountNumber string `json:"account_number"` + // Name of the bank associated with the routing number. + BankName string `json:"bank_name"` + // Routing transit number for the bank account to transfer funds to. + RoutingNumber string `json:"routing_number"` + // SWIFT code of the bank associated with the routing number. + SwiftCode string `json:"swift_code"` +} +type ChargePaymentMethodDetailsACHDebit struct { + // Type of entity that holds the account. This can be either `individual` or `company`. + AccountHolderType BankAccountAccountHolderType `json:"account_holder_type"` + // Name of the bank associated with the bank account. + BankName string `json:"bank_name"` + // Two-letter ISO code representing the country the bank account is located in. + Country string `json:"country"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // Routing transit number of the bank account. + RoutingNumber string `json:"routing_number"` +} +type ChargePaymentMethodDetailsACSSDebit struct { + // Name of the bank associated with the bank account. + BankName string `json:"bank_name"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Institution number of the bank account + InstitutionNumber string `json:"institution_number"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // ID of the mandate used to make this payment. + Mandate string `json:"mandate"` + // Transit number of the bank account. + TransitNumber string `json:"transit_number"` +} +type ChargePaymentMethodDetailsAffirm struct { + // ID of the [location](https://stripe.com/docs/api/terminal/locations) that this transaction's reader is assigned to. + Location string `json:"location"` + // ID of the [reader](https://stripe.com/docs/api/terminal/readers) this transaction was made on. + Reader string `json:"reader"` + // The Affirm transaction ID associated with this payment. + TransactionID string `json:"transaction_id"` +} +type ChargePaymentMethodDetailsAfterpayClearpay struct { + // The Afterpay order ID associated with this payment intent. + OrderID string `json:"order_id"` + // Order identifier shown to the merchant in Afterpay's online portal. + Reference string `json:"reference"` +} +type ChargePaymentMethodDetailsAlipay struct { + // Uniquely identifies this particular Alipay account. You can use this attribute to check whether two Alipay accounts are the same. + BuyerID string `json:"buyer_id"` + // Uniquely identifies this particular Alipay account. You can use this attribute to check whether two Alipay accounts are the same. + Fingerprint string `json:"fingerprint"` + // Transaction ID of this particular Alipay transaction. + TransactionID string `json:"transaction_id"` +} +type ChargePaymentMethodDetailsAlma struct{} +type ChargePaymentMethodDetailsAmazonPayFundingCard struct { + // Card brand. Can be `amex`, `diners`, `discover`, `eftpos_au`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Brand string `json:"brand"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding string `json:"funding"` + // The last four digits of the card. + Last4 string `json:"last4"` +} +type ChargePaymentMethodDetailsAmazonPayFunding struct { + Card *ChargePaymentMethodDetailsAmazonPayFundingCard `json:"card"` + // funding type of the underlying payment method. + Type ChargePaymentMethodDetailsAmazonPayFundingType `json:"type"` +} +type ChargePaymentMethodDetailsAmazonPay struct { + Funding *ChargePaymentMethodDetailsAmazonPayFunding `json:"funding"` +} +type ChargePaymentMethodDetailsAUBECSDebit struct { + // Bank-State-Branch number of the bank account. + BSBNumber string `json:"bsb_number"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // ID of the mandate used to make this payment. + Mandate string `json:"mandate"` +} +type ChargePaymentMethodDetailsBACSDebit struct { + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // ID of the mandate used to make this payment. + Mandate string `json:"mandate"` + // Sort code of the bank account. (e.g., `10-20-30`) + SortCode string `json:"sort_code"` +} +type ChargePaymentMethodDetailsBancontact struct { + // Bank code of bank associated with the bank account. + BankCode string `json:"bank_code"` + // Name of the bank associated with the bank account. + BankName string `json:"bank_name"` + // Bank Identifier Code of the bank associated with the bank account. + BIC string `json:"bic"` + // The ID of the SEPA Direct Debit PaymentMethod which was generated by this Charge. + GeneratedSEPADebit *PaymentMethod `json:"generated_sepa_debit"` + // The mandate for the SEPA Direct Debit PaymentMethod which was generated by this Charge. + GeneratedSEPADebitMandate *Mandate `json:"generated_sepa_debit_mandate"` + // Last four characters of the IBAN. + IBANLast4 string `json:"iban_last4"` + // Preferred language of the Bancontact authorization page that the customer is redirected to. + // Can be one of `en`, `de`, `fr`, or `nl` + PreferredLanguage string `json:"preferred_language"` + // Owner's verified full name. Values are verified or provided by Bancontact directly + // (if supported) at the time of authorization or settlement. They cannot be set or mutated. + VerifiedName string `json:"verified_name"` +} +type ChargePaymentMethodDetailsBillie struct{} +type ChargePaymentMethodDetailsBLIK struct { + // A unique and immutable identifier assigned by BLIK to every buyer. + BuyerID string `json:"buyer_id"` +} +type ChargePaymentMethodDetailsBoleto struct { + // The tax ID of the customer (CPF for individuals consumers or CNPJ for businesses consumers) + TaxID string `json:"tax_id"` +} + +// Check results by Card networks on Card address and CVC at time of payment. +type ChargePaymentMethodDetailsCardChecks struct { + // If a address line1 was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + AddressLine1Check ChargePaymentMethodDetailsCardChecksAddressLine1Check `json:"address_line1_check"` + // If a address postal code was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + AddressPostalCodeCheck ChargePaymentMethodDetailsCardChecksAddressPostalCodeCheck `json:"address_postal_code_check"` + // If a CVC was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + CVCCheck ChargePaymentMethodDetailsCardChecksCVCCheck `json:"cvc_check"` +} +type ChargePaymentMethodDetailsCardExtendedAuthorization struct { + // Indicates whether or not the capture window is extended beyond the standard authorization. + Status ChargePaymentMethodDetailsCardExtendedAuthorizationStatus `json:"status"` +} +type ChargePaymentMethodDetailsCardIncrementalAuthorization struct { + // Indicates whether or not the incremental authorization feature is supported. + Status ChargePaymentMethodDetailsCardIncrementalAuthorizationStatus `json:"status"` +} + +// Installment details for this payment. +// +// For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). +type ChargePaymentMethodDetailsCardInstallments struct { + // Installment plan selected for the payment. + Plan *PaymentIntentPaymentMethodOptionsCardInstallmentsPlan `json:"plan"` +} +type ChargePaymentMethodDetailsCardMulticapture struct { + // Indicates whether or not multiple captures are supported. + Status ChargePaymentMethodDetailsCardMulticaptureStatus `json:"status"` +} + +// If this card has network token credentials, this contains the details of the network token credentials. +type ChargePaymentMethodDetailsCardNetworkToken struct { + // Indicates if Stripe used a network token, either user provided or Stripe managed when processing the transaction. + Used bool `json:"used"` +} +type ChargePaymentMethodDetailsCardOvercapture struct { + // The maximum amount that can be captured. + MaximumAmountCapturable int64 `json:"maximum_amount_capturable"` + // Indicates whether or not the authorized amount can be over-captured. + Status ChargePaymentMethodDetailsCardOvercaptureStatus `json:"status"` +} + +// Populated if this transaction used 3D Secure authentication. +type ChargePaymentMethodDetailsCardThreeDSecure struct { + // For authenticated transactions: how the customer was authenticated by + // the issuing bank. + AuthenticationFlow ChargePaymentMethodDetailsCardThreeDSecureAuthenticationFlow `json:"authentication_flow"` + // The Electronic Commerce Indicator (ECI). A protocol-level field + // indicating what degree of authentication was performed. + ElectronicCommerceIndicator ChargePaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator `json:"electronic_commerce_indicator"` + // The exemption requested via 3DS and accepted by the issuer at authentication time. + ExemptionIndicator ChargePaymentMethodDetailsCardThreeDSecureExemptionIndicator `json:"exemption_indicator"` + // Whether Stripe requested the value of `exemption_indicator` in the transaction. This will depend on + // the outcome of Stripe's internal risk assessment. + ExemptionIndicatorApplied bool `json:"exemption_indicator_applied"` + // Indicates the outcome of 3D Secure authentication. + Result ChargePaymentMethodDetailsCardThreeDSecureResult `json:"result"` + // Additional information about why 3D Secure succeeded or failed based + // on the `result`. + ResultReason ChargePaymentMethodDetailsCardThreeDSecureResultReason `json:"result_reason"` + // The 3D Secure 1 XID or 3D Secure 2 Directory Server Transaction ID + // (dsTransId) for this payment. + TransactionID string `json:"transaction_id"` + // The version of 3D Secure that was used. + Version string `json:"version"` +} +type ChargePaymentMethodDetailsCardWalletAmexExpressCheckout struct{} +type ChargePaymentMethodDetailsCardWalletApplePay struct{} +type ChargePaymentMethodDetailsCardWalletGooglePay struct{} +type ChargePaymentMethodDetailsCardWalletLink struct{} +type ChargePaymentMethodDetailsCardWalletMasterpass struct { + // Owner's verified billing address. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + BillingAddress *Address `json:"billing_address"` + // Owner's verified email. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Email string `json:"email"` + // Owner's verified full name. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Name string `json:"name"` + // Owner's verified shipping address. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + ShippingAddress *Address `json:"shipping_address"` +} +type ChargePaymentMethodDetailsCardWalletSamsungPay struct{} +type ChargePaymentMethodDetailsCardWalletVisaCheckout struct { + // Owner's verified billing address. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + BillingAddress *Address `json:"billing_address"` + // Owner's verified email. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Email string `json:"email"` + // Owner's verified full name. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Name string `json:"name"` + // Owner's verified shipping address. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + ShippingAddress *Address `json:"shipping_address"` +} + +// If this Card is part of a card wallet, this contains the details of the card wallet. +type ChargePaymentMethodDetailsCardWallet struct { + AmexExpressCheckout *ChargePaymentMethodDetailsCardWalletAmexExpressCheckout `json:"amex_express_checkout"` + ApplePay *ChargePaymentMethodDetailsCardWalletApplePay `json:"apple_pay"` + // (For tokenized numbers only.) The last four digits of the device account number. + DynamicLast4 string `json:"dynamic_last4"` + GooglePay *ChargePaymentMethodDetailsCardWalletGooglePay `json:"google_pay"` + Link *ChargePaymentMethodDetailsCardWalletLink `json:"link"` + Masterpass *ChargePaymentMethodDetailsCardWalletMasterpass `json:"masterpass"` + SamsungPay *ChargePaymentMethodDetailsCardWalletSamsungPay `json:"samsung_pay"` + // The type of the card wallet, one of `amex_express_checkout`, `apple_pay`, `google_pay`, `masterpass`, `samsung_pay`, `visa_checkout`, or `link`. An additional hash is included on the Wallet subhash with a name matching this value. It contains additional information specific to the card wallet type. + Type PaymentMethodCardWalletType `json:"type"` + VisaCheckout *ChargePaymentMethodDetailsCardWalletVisaCheckout `json:"visa_checkout"` +} +type ChargePaymentMethodDetailsCard struct { + // The authorized amount. + AmountAuthorized int64 `json:"amount_authorized"` + // Authorization code on the charge. + AuthorizationCode string `json:"authorization_code"` + // Card brand. Can be `amex`, `diners`, `discover`, `eftpos_au`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Brand PaymentMethodCardBrand `json:"brand"` + // When using manual capture, a future timestamp at which the charge will be automatically refunded if uncaptured. + CaptureBefore int64 `json:"capture_before"` + // Check results by Card networks on Card address and CVC at time of payment. + Checks *ChargePaymentMethodDetailsCardChecks `json:"checks"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + ExtendedAuthorization *ChargePaymentMethodDetailsCardExtendedAuthorization `json:"extended_authorization"` + // Uniquely identifies this particular card number. You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + // + // *As of May 1, 2021, card fingerprint in India for Connect changed to allow two fingerprints for the same card---one for India and one for the rest of the world.* + Fingerprint string `json:"fingerprint"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding CardFunding `json:"funding"` + IncrementalAuthorization *ChargePaymentMethodDetailsCardIncrementalAuthorization `json:"incremental_authorization"` + // Installment details for this payment. + // + // For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + Installments *ChargePaymentMethodDetailsCardInstallments `json:"installments"` + // The last four digits of the card. + Last4 string `json:"last4"` + // ID of the mandate used to make this payment or created by it. + Mandate string `json:"mandate"` + // True if this payment was marked as MOTO and out of scope for SCA. + MOTO bool `json:"moto"` + Multicapture *ChargePaymentMethodDetailsCardMulticapture `json:"multicapture"` + // Identifies which network this charge was processed on. Can be `amex`, `cartes_bancaires`, `diners`, `discover`, `eftpos_au`, `interac`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Network ChargePaymentMethodDetailsCardNetwork `json:"network"` + // If this card has network token credentials, this contains the details of the network token credentials. + NetworkToken *ChargePaymentMethodDetailsCardNetworkToken `json:"network_token"` + // This is used by the financial networks to identify a transaction. Visa calls this the Transaction ID, Mastercard calls this the Trace ID, and American Express calls this the Acquirer Reference Data. This value will be present if it is returned by the financial network in the authorization response, and null otherwise. + NetworkTransactionID string `json:"network_transaction_id"` + Overcapture *ChargePaymentMethodDetailsCardOvercapture `json:"overcapture"` + // Status of a card based on the card issuer. + RegulatedStatus ChargePaymentMethodDetailsCardRegulatedStatus `json:"regulated_status"` + // Populated if this transaction used 3D Secure authentication. + ThreeDSecure *ChargePaymentMethodDetailsCardThreeDSecure `json:"three_d_secure"` + // If this Card is part of a card wallet, this contains the details of the card wallet. + Wallet *ChargePaymentMethodDetailsCardWallet `json:"wallet"` + // Please note that the fields below are for internal use only and are not returned + // as part of standard API requests. + // A high-level description of the type of cards issued in this range. (For internal use only and not typically available in standard API requests.) + Description string `json:"description"` + // Issuer identification number of the card. (For internal use only and not typically available in standard API requests.) + IIN string `json:"iin"` + // The name of the card's issuing bank. (For internal use only and not typically available in standard API requests.) + Issuer string `json:"issuer"` +} + +// Details about payments collected offline. +type ChargePaymentMethodDetailsCardPresentOffline struct { + // Time at which the payment was collected while offline + StoredAt int64 `json:"stored_at"` + // The method used to process this payment method offline. Only deferred is allowed. + Type ChargePaymentMethodDetailsCardPresentOfflineType `json:"type"` +} + +// A collection of fields required to be displayed on receipts. Only required for EMV transactions. +type ChargePaymentMethodDetailsCardPresentReceipt struct { + // The type of account being debited or credited + AccountType ChargePaymentMethodDetailsCardPresentReceiptAccountType `json:"account_type"` + // The Application Cryptogram, a unique value generated by the card to authenticate the transaction with issuers. + ApplicationCryptogram string `json:"application_cryptogram"` + // The Application Identifier (AID) on the card used to determine which networks are eligible to process the transaction. Referenced from EMV tag 9F12, data encoded on the card's chip. + ApplicationPreferredName string `json:"application_preferred_name"` + // Identifier for this transaction. + AuthorizationCode string `json:"authorization_code"` + // EMV tag 8A. A code returned by the card issuer. + AuthorizationResponseCode string `json:"authorization_response_code"` + // Describes the method used by the cardholder to verify ownership of the card. One of the following: `approval`, `failure`, `none`, `offline_pin`, `offline_pin_and_signature`, `online_pin`, or `signature`. + CardholderVerificationMethod string `json:"cardholder_verification_method"` + // Similar to the application_preferred_name, identifying the applications (AIDs) available on the card. Referenced from EMV tag 84. + DedicatedFileName string `json:"dedicated_file_name"` + // A 5-byte string that records the checks and validations that occur between the card and the terminal. These checks determine how the terminal processes the transaction and what risk tolerance is acceptable. Referenced from EMV Tag 95. + TerminalVerificationResults string `json:"terminal_verification_results"` + // An indication of which steps were completed during the card read process. Referenced from EMV Tag 9B. + TransactionStatusInformation string `json:"transaction_status_information"` +} +type ChargePaymentMethodDetailsCardPresentWallet struct { + // The type of mobile wallet, one of `apple_pay`, `google_pay`, `samsung_pay`, or `unknown`. + Type ChargePaymentMethodDetailsCardPresentWalletType `json:"type"` +} +type ChargePaymentMethodDetailsCardPresent struct { + // The authorized amount + AmountAuthorized int64 `json:"amount_authorized"` + // Card brand. Can be `amex`, `diners`, `discover`, `eftpos_au`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Brand PaymentMethodCardBrand `json:"brand"` + // The [product code](https://stripe.com/docs/card-product-codes) that identifies the specific program or product associated with a card. + BrandProduct string `json:"brand_product"` + // When using manual capture, a future timestamp after which the charge will be automatically refunded if uncaptured. + CaptureBefore int64 `json:"capture_before"` + // The cardholder name as read from the card, in [ISO 7813](https://en.wikipedia.org/wiki/ISO/IEC_7813) format. May include alphanumeric characters, special characters and first/last name separator (`/`). In some cases, the cardholder name may not be available depending on how the issuer has configured the card. Cardholder name is typically not available on swipe or contactless payments, such as those made with Apple Pay and Google Pay. + CardholderName string `json:"cardholder_name"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // Authorization response cryptogram. + EmvAuthData string `json:"emv_auth_data"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + // Uniquely identifies this particular card number. You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + // + // *As of May 1, 2021, card fingerprint in India for Connect changed to allow two fingerprints for the same card---one for India and one for the rest of the world.* + Fingerprint string `json:"fingerprint"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding CardFunding `json:"funding"` + // ID of a card PaymentMethod generated from the card_present PaymentMethod that may be attached to a Customer for future transactions. Only present if it was possible to generate a card PaymentMethod. + GeneratedCard string `json:"generated_card"` + // Whether this [PaymentIntent](https://stripe.com/docs/api/payment_intents) is eligible for incremental authorizations. Request support using [request_incremental_authorization_support](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-payment_method_options-card_present-request_incremental_authorization_support). + IncrementalAuthorizationSupported bool `json:"incremental_authorization_supported"` + // The last four digits of the card. + Last4 string `json:"last4"` + // Identifies which network this charge was processed on. Can be `amex`, `cartes_bancaires`, `diners`, `discover`, `eftpos_au`, `interac`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Network ChargePaymentMethodDetailsCardPresentNetwork `json:"network"` + // This is used by the financial networks to identify a transaction. Visa calls this the Transaction ID, Mastercard calls this the Trace ID, and American Express calls this the Acquirer Reference Data. This value will be present if it is returned by the financial network in the authorization response, and null otherwise. + NetworkTransactionID string `json:"network_transaction_id"` + // Details about payments collected offline. + Offline *ChargePaymentMethodDetailsCardPresentOffline `json:"offline"` + // Defines whether the authorized amount can be over-captured or not + OvercaptureSupported bool `json:"overcapture_supported"` + // The languages that the issuing bank recommends using for localizing any customer-facing text, as read from the card. Referenced from EMV tag 5F2D, data encoded on the card's chip. + PreferredLocales []string `json:"preferred_locales"` + // How card details were read in this transaction. + ReadMethod string `json:"read_method"` + // A collection of fields required to be displayed on receipts. Only required for EMV transactions. + Receipt *ChargePaymentMethodDetailsCardPresentReceipt `json:"receipt"` + Wallet *ChargePaymentMethodDetailsCardPresentWallet `json:"wallet"` + // Please note that the fields below are for internal use only and are not returned + // as part of standard API requests. + // A high-level description of the type of cards issued in this range. (For internal use only and not typically available in standard API requests.) + Description string `json:"description"` + // Issuer identification number of the card. (For internal use only and not typically available in standard API requests.) + IIN string `json:"iin"` + // The name of the card's issuing bank. (For internal use only and not typically available in standard API requests.) + Issuer string `json:"issuer"` +} +type ChargePaymentMethodDetailsCashApp struct { + // A unique and immutable identifier assigned by Cash App to every buyer. + BuyerID string `json:"buyer_id"` + // A public identifier for buyers using Cash App. + Cashtag string `json:"cashtag"` +} +type ChargePaymentMethodDetailsCrypto struct { + // The wallet address of the customer. + BuyerAddress string `json:"buyer_address"` + // The blockchain network that the transaction was sent on. + Network ChargePaymentMethodDetailsCryptoNetwork `json:"network"` + // The token currency that the transaction was sent with. + TokenCurrency ChargePaymentMethodDetailsCryptoTokenCurrency `json:"token_currency"` + // The blockchain transaction hash of the crypto payment. + TransactionHash string `json:"transaction_hash"` +} +type ChargePaymentMethodDetailsCustomerBalance struct{} +type ChargePaymentMethodDetailsEPS struct { + // The customer's bank. Should be one of `arzte_und_apotheker_bank`, `austrian_anadi_bank_ag`, `bank_austria`, `bankhaus_carl_spangler`, `bankhaus_schelhammer_und_schattera_ag`, `bawag_psk_ag`, `bks_bank_ag`, `brull_kallmus_bank_ag`, `btv_vier_lander_bank`, `capital_bank_grawe_gruppe_ag`, `deutsche_bank_ag`, `dolomitenbank`, `easybank_ag`, `erste_bank_und_sparkassen`, `hypo_alpeadriabank_international_ag`, `hypo_noe_lb_fur_niederosterreich_u_wien`, `hypo_oberosterreich_salzburg_steiermark`, `hypo_tirol_bank_ag`, `hypo_vorarlberg_bank_ag`, `hypo_bank_burgenland_aktiengesellschaft`, `marchfelder_bank`, `oberbank_ag`, `raiffeisen_bankengruppe_osterreich`, `schoellerbank_ag`, `sparda_bank_wien`, `volksbank_gruppe`, `volkskreditbank_ag`, or `vr_bank_braunau`. + Bank string `json:"bank"` + // Owner's verified full name. Values are verified or provided by EPS directly + // (if supported) at the time of authorization or settlement. They cannot be set or mutated. + // EPS rarely provides this information so the attribute is usually empty. + VerifiedName string `json:"verified_name"` +} +type ChargePaymentMethodDetailsFPX struct { + // Account holder type, if provided. Can be one of `individual` or `company`. + AccountHolderType PaymentMethodFPXAccountHolderType `json:"account_holder_type"` + // The customer's bank. Can be one of `affin_bank`, `agrobank`, `alliance_bank`, `ambank`, `bank_islam`, `bank_muamalat`, `bank_rakyat`, `bsn`, `cimb`, `hong_leong_bank`, `hsbc`, `kfh`, `maybank2u`, `ocbc`, `public_bank`, `rhb`, `standard_chartered`, `uob`, `deutsche_bank`, `maybank2e`, `pb_enterprise`, or `bank_of_china`. + Bank string `json:"bank"` + // Unique transaction id generated by FPX for every request from the merchant + TransactionID string `json:"transaction_id"` +} +type ChargePaymentMethodDetailsGiropay struct { + // Bank code of bank associated with the bank account. + BankCode string `json:"bank_code"` + // Name of the bank associated with the bank account. + BankName string `json:"bank_name"` + // Bank Identifier Code of the bank associated with the bank account. + BIC string `json:"bic"` + // Owner's verified full name. Values are verified or provided by Giropay directly + // (if supported) at the time of authorization or settlement. They cannot be set or mutated. + // Giropay rarely provides this information so the attribute is usually empty. + VerifiedName string `json:"verified_name"` +} +type ChargePaymentMethodDetailsGrabpay struct { + // Unique transaction id generated by GrabPay + TransactionID string `json:"transaction_id"` +} +type ChargePaymentMethodDetailsIDEAL struct { + // The customer's bank. Can be one of `abn_amro`, `asn_bank`, `bunq`, `buut`, `handelsbanken`, `ing`, `knab`, `moneyou`, `n26`, `nn`, `rabobank`, `regiobank`, `revolut`, `sns_bank`, `triodos_bank`, `van_lanschot`, or `yoursafe`. + Bank string `json:"bank"` + // The Bank Identifier Code of the customer's bank. + BIC string `json:"bic"` + // The ID of the SEPA Direct Debit PaymentMethod which was generated by this Charge. + GeneratedSEPADebit *PaymentMethod `json:"generated_sepa_debit"` + // The mandate for the SEPA Direct Debit PaymentMethod which was generated by this Charge. + GeneratedSEPADebitMandate *Mandate `json:"generated_sepa_debit_mandate"` + // Last four characters of the IBAN. + IBANLast4 string `json:"iban_last4"` + // Owner's verified full name. Values are verified or provided by iDEAL directly + // (if supported) at the time of authorization or settlement. They cannot be set or mutated. + VerifiedName string `json:"verified_name"` +} + +// A collection of fields required to be displayed on receipts. Only required for EMV transactions. +type ChargePaymentMethodDetailsInteracPresentReceipt struct { + // The type of account being debited or credited + AccountType string `json:"account_type"` + // The Application Cryptogram, a unique value generated by the card to authenticate the transaction with issuers. + ApplicationCryptogram string `json:"application_cryptogram"` + // The Application Identifier (AID) on the card used to determine which networks are eligible to process the transaction. Referenced from EMV tag 9F12, data encoded on the card's chip. + ApplicationPreferredName string `json:"application_preferred_name"` + // Identifier for this transaction. + AuthorizationCode string `json:"authorization_code"` + // EMV tag 8A. A code returned by the card issuer. + AuthorizationResponseCode string `json:"authorization_response_code"` + // Describes the method used by the cardholder to verify ownership of the card. One of the following: `approval`, `failure`, `none`, `offline_pin`, `offline_pin_and_signature`, `online_pin`, or `signature`. + CardholderVerificationMethod string `json:"cardholder_verification_method"` + // Similar to the application_preferred_name, identifying the applications (AIDs) available on the card. Referenced from EMV tag 84. + DedicatedFileName string `json:"dedicated_file_name"` + // A 5-byte string that records the checks and validations that occur between the card and the terminal. These checks determine how the terminal processes the transaction and what risk tolerance is acceptable. Referenced from EMV Tag 95. + TerminalVerificationResults string `json:"terminal_verification_results"` + // An indication of which steps were completed during the card read process. Referenced from EMV Tag 9B. + TransactionStatusInformation string `json:"transaction_status_information"` +} +type ChargePaymentMethodDetailsInteracPresent struct { + // Card brand. Can be `interac`, `mastercard` or `visa`. + Brand string `json:"brand"` + // The cardholder name as read from the card, in [ISO 7813](https://en.wikipedia.org/wiki/ISO/IEC_7813) format. May include alphanumeric characters, special characters and first/last name separator (`/`). In some cases, the cardholder name may not be available depending on how the issuer has configured the card. Cardholder name is typically not available on swipe or contactless payments, such as those made with Apple Pay and Google Pay. + CardholderName string `json:"cardholder_name"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // Authorization response cryptogram. + EmvAuthData string `json:"emv_auth_data"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + // Uniquely identifies this particular card number. You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + // + // *As of May 1, 2021, card fingerprint in India for Connect changed to allow two fingerprints for the same card---one for India and one for the rest of the world.* + Fingerprint string `json:"fingerprint"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding string `json:"funding"` + // ID of a card PaymentMethod generated from the card_present PaymentMethod that may be attached to a Customer for future transactions. Only present if it was possible to generate a card PaymentMethod. + GeneratedCard string `json:"generated_card"` + // The last four digits of the card. + Last4 string `json:"last4"` + // Identifies which network this charge was processed on. Can be `amex`, `cartes_bancaires`, `diners`, `discover`, `eftpos_au`, `interac`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Network string `json:"network"` + // This is used by the financial networks to identify a transaction. Visa calls this the Transaction ID, Mastercard calls this the Trace ID, and American Express calls this the Acquirer Reference Data. This value will be present if it is returned by the financial network in the authorization response, and null otherwise. + NetworkTransactionID string `json:"network_transaction_id"` + // The languages that the issuing bank recommends using for localizing any customer-facing text, as read from the card. Referenced from EMV tag 5F2D, data encoded on the card's chip. + PreferredLocales []string `json:"preferred_locales"` + // How card details were read in this transaction. + ReadMethod string `json:"read_method"` + // A collection of fields required to be displayed on receipts. Only required for EMV transactions. + Receipt *ChargePaymentMethodDetailsInteracPresentReceipt `json:"receipt"` + // Please note that the fields below are for internal use only and are not returned + // as part of standard API requests. + // A high-level description of the type of cards issued in this range. (For internal use only and not typically available in standard API requests.) + Description string `json:"description"` + // Issuer identification number of the card. (For internal use only and not typically available in standard API requests.) + IIN string `json:"iin"` + // The name of the card's issuing bank. (For internal use only and not typically available in standard API requests.) + Issuer string `json:"issuer"` +} +type ChargePaymentMethodDetailsKakaoPay struct { + // A unique identifier for the buyer as determined by the local payment processor. + BuyerID string `json:"buyer_id"` +} + +// The payer's address +type ChargePaymentMethodDetailsKlarnaPayerDetailsAddress struct { + // The payer address country + Country string `json:"country"` +} + +// The payer details for this transaction. +type ChargePaymentMethodDetailsKlarnaPayerDetails struct { + // The payer's address + Address *ChargePaymentMethodDetailsKlarnaPayerDetailsAddress `json:"address"` +} +type ChargePaymentMethodDetailsKlarna struct { + // The payer details for this transaction. + PayerDetails *ChargePaymentMethodDetailsKlarnaPayerDetails `json:"payer_details"` + // The Klarna payment method used for this transaction. + // Can be one of `pay_later`, `pay_now`, `pay_with_financing`, or `pay_in_installments` + PaymentMethodCategory ChargePaymentMethodDetailsKlarnaPaymentMethodCategory `json:"payment_method_category"` + // Preferred language of the Klarna authorization page that the customer is redirected to. + // Can be one of `de-AT`, `en-AT`, `nl-BE`, `fr-BE`, `en-BE`, `de-DE`, `en-DE`, `da-DK`, `en-DK`, `es-ES`, `en-ES`, `fi-FI`, `sv-FI`, `en-FI`, `en-GB`, `en-IE`, `it-IT`, `en-IT`, `nl-NL`, `en-NL`, `nb-NO`, `en-NO`, `sv-SE`, `en-SE`, `en-US`, `es-US`, `fr-FR`, `en-FR`, `cs-CZ`, `en-CZ`, `ro-RO`, `en-RO`, `el-GR`, `en-GR`, `en-AU`, `en-NZ`, `en-CA`, `fr-CA`, `pl-PL`, `en-PL`, `pt-PT`, `en-PT`, `de-CH`, `fr-CH`, `it-CH`, or `en-CH` + PreferredLocale string `json:"preferred_locale"` +} + +// If the payment succeeded, this contains the details of the convenience store where the payment was completed. +type ChargePaymentMethodDetailsKonbiniStore struct { + // The name of the convenience store chain where the payment was completed. + Chain ChargePaymentMethodDetailsKonbiniStoreChain `json:"chain"` +} +type ChargePaymentMethodDetailsKonbini struct { + // If the payment succeeded, this contains the details of the convenience store where the payment was completed. + Store *ChargePaymentMethodDetailsKonbiniStore `json:"store"` +} +type ChargePaymentMethodDetailsKrCard struct { + // The local credit or debit card brand. + Brand ChargePaymentMethodDetailsKrCardBrand `json:"brand"` + // A unique identifier for the buyer as determined by the local payment processor. + BuyerID string `json:"buyer_id"` + // The last four digits of the card. This may not be present for American Express cards. + Last4 string `json:"last4"` +} +type ChargePaymentMethodDetailsLink struct { + // Two-letter ISO code representing the funding source country beneath the Link payment. + // You could use this attribute to get a sense of international fees. + Country string `json:"country"` +} + +// Internal card details +type ChargePaymentMethodDetailsMobilepayCard struct { + // Brand of the card used in the transaction + Brand string `json:"brand"` + // Two-letter ISO code representing the country of the card + Country string `json:"country"` + // Two digit number representing the card's expiration month + ExpMonth int64 `json:"exp_month"` + // Two digit number representing the card's expiration year + ExpYear int64 `json:"exp_year"` + // The last 4 digits of the card + Last4 string `json:"last4"` +} +type ChargePaymentMethodDetailsMobilepay struct { + // Internal card details + Card *ChargePaymentMethodDetailsMobilepayCard `json:"card"` +} +type ChargePaymentMethodDetailsMultibanco struct { + // Entity number associated with this Multibanco payment. + Entity string `json:"entity"` + // Reference number associated with this Multibanco payment. + Reference string `json:"reference"` +} +type ChargePaymentMethodDetailsNaverPay struct { + // A unique identifier for the buyer as determined by the local payment processor. + BuyerID string `json:"buyer_id"` +} +type ChargePaymentMethodDetailsNzBankAccount struct { + // The name on the bank account. Only present if the account holder name is different from the name of the authorized signatory collected in the PaymentMethod's billing details. + AccountHolderName string `json:"account_holder_name"` + // The numeric code for the bank account's bank. + BankCode string `json:"bank_code"` + // The name of the bank. + BankName string `json:"bank_name"` + // The numeric code for the bank account's bank branch. + BranchCode string `json:"branch_code"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // The suffix of the bank account number. + Suffix string `json:"suffix"` +} +type ChargePaymentMethodDetailsOXXO struct { + // OXXO reference number + Number string `json:"number"` +} +type ChargePaymentMethodDetailsP24 struct { + // The customer's bank. Can be one of `ing`, `citi_handlowy`, `tmobile_usbugi_bankowe`, `plus_bank`, `etransfer_pocztowy24`, `banki_spbdzielcze`, `bank_nowy_bfg_sa`, `getin_bank`, `velobank`, `blik`, `noble_pay`, `ideabank`, `envelobank`, `santander_przelew24`, `nest_przelew`, `mbank_mtransfer`, `inteligo`, `pbac_z_ipko`, `bnp_paribas`, `credit_agricole`, `toyota_bank`, `bank_pekao_sa`, `volkswagen_bank`, `bank_millennium`, `alior_bank`, or `boz`. + Bank string `json:"bank"` + // Unique reference for this Przelewy24 payment. + Reference string `json:"reference"` + // Owner's verified full name. Values are verified or provided by Przelewy24 directly + // (if supported) at the time of authorization or settlement. They cannot be set or mutated. + // Przelewy24 rarely provides this information so the attribute is usually empty. + VerifiedName string `json:"verified_name"` +} +type ChargePaymentMethodDetailsPayByBank struct{} +type ChargePaymentMethodDetailsPayco struct { + // A unique identifier for the buyer as determined by the local payment processor. + BuyerID string `json:"buyer_id"` +} +type ChargePaymentMethodDetailsPayNow struct { + // Reference number associated with this PayNow payment + Reference string `json:"reference"` +} + +// The level of protection offered as defined by PayPal Seller Protection for Merchants, for this transaction. +type ChargePaymentMethodDetailsPaypalSellerProtection struct { + // An array of conditions that are covered for the transaction, if applicable. + DisputeCategories []ChargePaymentMethodDetailsPaypalSellerProtectionDisputeCategory `json:"dispute_categories"` + // Indicates whether the transaction is eligible for PayPal's seller protection. + Status ChargePaymentMethodDetailsPaypalSellerProtectionStatus `json:"status"` +} +type ChargePaymentMethodDetailsPaypal struct { + // Two-letter ISO code representing the buyer's country. Values are provided by PayPal directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Country string `json:"country"` + // Owner's email. Values are provided by PayPal directly + // (if supported) at the time of authorization or settlement. They cannot be set or mutated. + PayerEmail string `json:"payer_email"` + // PayPal account PayerID. This identifier uniquely identifies the PayPal customer. + PayerID string `json:"payer_id"` + // Owner's full name. Values provided by PayPal directly + // (if supported) at the time of authorization or settlement. They cannot be set or mutated. + PayerName string `json:"payer_name"` + // The level of protection offered as defined by PayPal Seller Protection for Merchants, for this transaction. + SellerProtection *ChargePaymentMethodDetailsPaypalSellerProtection `json:"seller_protection"` + // A unique ID generated by PayPal for this transaction. + TransactionID string `json:"transaction_id"` +} +type ChargePaymentMethodDetailsPix struct { + // Unique transaction id generated by BCB + BankTransactionID string `json:"bank_transaction_id"` +} +type ChargePaymentMethodDetailsPromptPay struct { + // Bill reference generated by PromptPay + Reference string `json:"reference"` +} +type ChargePaymentMethodDetailsRevolutPayFundingCard struct { + // Card brand. Can be `amex`, `diners`, `discover`, `eftpos_au`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Brand string `json:"brand"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding string `json:"funding"` + // The last four digits of the card. + Last4 string `json:"last4"` +} +type ChargePaymentMethodDetailsRevolutPayFunding struct { + Card *ChargePaymentMethodDetailsRevolutPayFundingCard `json:"card"` + // funding type of the underlying payment method. + Type ChargePaymentMethodDetailsRevolutPayFundingType `json:"type"` +} +type ChargePaymentMethodDetailsRevolutPay struct { + Funding *ChargePaymentMethodDetailsRevolutPayFunding `json:"funding"` +} +type ChargePaymentMethodDetailsSamsungPay struct { + // A unique identifier for the buyer as determined by the local payment processor. + BuyerID string `json:"buyer_id"` +} +type ChargePaymentMethodDetailsSatispay struct{} +type ChargePaymentMethodDetailsSEPACreditTransfer struct { + // Name of the bank associated with the bank account. + BankName string `json:"bank_name"` + // Bank Identifier Code of the bank associated with the bank account. + BIC string `json:"bic"` + // IBAN of the bank account to transfer funds to. + IBAN string `json:"iban"` +} +type ChargePaymentMethodDetailsSEPADebit struct { + // Bank code of bank associated with the bank account. + BankCode string `json:"bank_code"` + // Branch code of bank associated with the bank account. + BranchCode string `json:"branch_code"` + // Two-letter ISO code representing the country the bank account is located in. + Country string `json:"country"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Last four characters of the IBAN. + Last4 string `json:"last4"` + // Find the ID of the mandate used for this payment under the [payment_method_details.sepa_debit.mandate](https://stripe.com/docs/api/charges/object#charge_object-payment_method_details-sepa_debit-mandate) property on the Charge. Use this mandate ID to [retrieve the Mandate](https://stripe.com/docs/api/mandates/retrieve). + Mandate string `json:"mandate"` +} +type ChargePaymentMethodDetailsSofort struct { + // Bank code of bank associated with the bank account. + BankCode string `json:"bank_code"` + // Name of the bank associated with the bank account. + BankName string `json:"bank_name"` + // Bank Identifier Code of the bank associated with the bank account. + BIC string `json:"bic"` + // Two-letter ISO code representing the country the bank account is located in. + Country string `json:"country"` + // The ID of the SEPA Direct Debit PaymentMethod which was generated by this Charge. + GeneratedSEPADebit *PaymentMethod `json:"generated_sepa_debit"` + // The mandate for the SEPA Direct Debit PaymentMethod which was generated by this Charge. + GeneratedSEPADebitMandate *Mandate `json:"generated_sepa_debit_mandate"` + // Last four characters of the IBAN. + IBANLast4 string `json:"iban_last4"` + // Preferred language of the SOFORT authorization page that the customer is redirected to. + // Can be one of `de`, `en`, `es`, `fr`, `it`, `nl`, or `pl` + PreferredLanguage string `json:"preferred_language"` + // Owner's verified full name. Values are verified or provided by SOFORT directly + // (if supported) at the time of authorization or settlement. They cannot be set or mutated. + VerifiedName string `json:"verified_name"` +} +type ChargePaymentMethodDetailsStripeAccount struct{} +type ChargePaymentMethodDetailsSwish struct { + // Uniquely identifies the payer's Swish account. You can use this attribute to check whether two Swish transactions were paid for by the same payer + Fingerprint string `json:"fingerprint"` + // Payer bank reference number for the payment + PaymentReference string `json:"payment_reference"` + // The last four digits of the Swish account phone number + VerifiedPhoneLast4 string `json:"verified_phone_last4"` +} +type ChargePaymentMethodDetailsTWINT struct{} +type ChargePaymentMethodDetailsUSBankAccount struct { + // Account holder type: individual or company. + AccountHolderType ChargePaymentMethodDetailsUSBankAccountAccountHolderType `json:"account_holder_type"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType ChargePaymentMethodDetailsUSBankAccountAccountType `json:"account_type"` + // Name of the bank associated with the bank account. + BankName string `json:"bank_name"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // ID of the mandate used to make this payment. + Mandate *Mandate `json:"mandate"` + // Reference number to locate ACH payments with customer's bank. + PaymentReference string `json:"payment_reference"` + // Routing number of the bank account. + RoutingNumber string `json:"routing_number"` +} +type ChargePaymentMethodDetailsWeChat struct{} +type ChargePaymentMethodDetailsWeChatPay struct { + // Uniquely identifies this particular WeChat Pay account. You can use this attribute to check whether two WeChat accounts are the same. + Fingerprint string `json:"fingerprint"` + // ID of the [location](https://stripe.com/docs/api/terminal/locations) that this transaction's reader is assigned to. + Location string `json:"location"` + // ID of the [reader](https://stripe.com/docs/api/terminal/readers) this transaction was made on. + Reader string `json:"reader"` + // Transaction ID of this particular WeChat Pay transaction. + TransactionID string `json:"transaction_id"` +} +type ChargePaymentMethodDetailsZip struct{} + +// Details about the payment method at the time of the transaction. +type ChargePaymentMethodDetails struct { + ACHCreditTransfer *ChargePaymentMethodDetailsACHCreditTransfer `json:"ach_credit_transfer"` + ACHDebit *ChargePaymentMethodDetailsACHDebit `json:"ach_debit"` + ACSSDebit *ChargePaymentMethodDetailsACSSDebit `json:"acss_debit"` + Affirm *ChargePaymentMethodDetailsAffirm `json:"affirm"` + AfterpayClearpay *ChargePaymentMethodDetailsAfterpayClearpay `json:"afterpay_clearpay"` + Alipay *ChargePaymentMethodDetailsAlipay `json:"alipay"` + Alma *ChargePaymentMethodDetailsAlma `json:"alma"` + AmazonPay *ChargePaymentMethodDetailsAmazonPay `json:"amazon_pay"` + AUBECSDebit *ChargePaymentMethodDetailsAUBECSDebit `json:"au_becs_debit"` + BACSDebit *ChargePaymentMethodDetailsBACSDebit `json:"bacs_debit"` + Bancontact *ChargePaymentMethodDetailsBancontact `json:"bancontact"` + Billie *ChargePaymentMethodDetailsBillie `json:"billie"` + BLIK *ChargePaymentMethodDetailsBLIK `json:"blik"` + Boleto *ChargePaymentMethodDetailsBoleto `json:"boleto"` + Card *ChargePaymentMethodDetailsCard `json:"card"` + CardPresent *ChargePaymentMethodDetailsCardPresent `json:"card_present"` + CashApp *ChargePaymentMethodDetailsCashApp `json:"cashapp"` + Crypto *ChargePaymentMethodDetailsCrypto `json:"crypto"` + CustomerBalance *ChargePaymentMethodDetailsCustomerBalance `json:"customer_balance"` + EPS *ChargePaymentMethodDetailsEPS `json:"eps"` + FPX *ChargePaymentMethodDetailsFPX `json:"fpx"` + Giropay *ChargePaymentMethodDetailsGiropay `json:"giropay"` + Grabpay *ChargePaymentMethodDetailsGrabpay `json:"grabpay"` + IDEAL *ChargePaymentMethodDetailsIDEAL `json:"ideal"` + InteracPresent *ChargePaymentMethodDetailsInteracPresent `json:"interac_present"` + KakaoPay *ChargePaymentMethodDetailsKakaoPay `json:"kakao_pay"` + Klarna *ChargePaymentMethodDetailsKlarna `json:"klarna"` + Konbini *ChargePaymentMethodDetailsKonbini `json:"konbini"` + KrCard *ChargePaymentMethodDetailsKrCard `json:"kr_card"` + Link *ChargePaymentMethodDetailsLink `json:"link"` + Mobilepay *ChargePaymentMethodDetailsMobilepay `json:"mobilepay"` + Multibanco *ChargePaymentMethodDetailsMultibanco `json:"multibanco"` + NaverPay *ChargePaymentMethodDetailsNaverPay `json:"naver_pay"` + NzBankAccount *ChargePaymentMethodDetailsNzBankAccount `json:"nz_bank_account"` + OXXO *ChargePaymentMethodDetailsOXXO `json:"oxxo"` + P24 *ChargePaymentMethodDetailsP24 `json:"p24"` + PayByBank *ChargePaymentMethodDetailsPayByBank `json:"pay_by_bank"` + Payco *ChargePaymentMethodDetailsPayco `json:"payco"` + PayNow *ChargePaymentMethodDetailsPayNow `json:"paynow"` + Paypal *ChargePaymentMethodDetailsPaypal `json:"paypal"` + Pix *ChargePaymentMethodDetailsPix `json:"pix"` + PromptPay *ChargePaymentMethodDetailsPromptPay `json:"promptpay"` + RevolutPay *ChargePaymentMethodDetailsRevolutPay `json:"revolut_pay"` + SamsungPay *ChargePaymentMethodDetailsSamsungPay `json:"samsung_pay"` + Satispay *ChargePaymentMethodDetailsSatispay `json:"satispay"` + SEPACreditTransfer *ChargePaymentMethodDetailsSEPACreditTransfer `json:"sepa_credit_transfer"` + SEPADebit *ChargePaymentMethodDetailsSEPADebit `json:"sepa_debit"` + Sofort *ChargePaymentMethodDetailsSofort `json:"sofort"` + StripeAccount *ChargePaymentMethodDetailsStripeAccount `json:"stripe_account"` + Swish *ChargePaymentMethodDetailsSwish `json:"swish"` + TWINT *ChargePaymentMethodDetailsTWINT `json:"twint"` + // The type of transaction-specific details of the payment method used in the payment. See [PaymentMethod.type](https://stripe.com/docs/api/payment_methods/object#payment_method_object-type) for the full list of possible types. + // An additional hash is included on `payment_method_details` with a name matching this value. + // It contains information specific to the payment method. + Type ChargePaymentMethodDetailsType `json:"type"` + USBankAccount *ChargePaymentMethodDetailsUSBankAccount `json:"us_bank_account"` + WeChat *ChargePaymentMethodDetailsWeChat `json:"wechat"` + WeChatPay *ChargePaymentMethodDetailsWeChatPay `json:"wechat_pay"` + Zip *ChargePaymentMethodDetailsZip `json:"zip"` +} +type ChargePresentmentDetails struct { + // Amount intended to be collected by this payment, denominated in presentment_currency. + PresentmentAmount int64 `json:"presentment_amount"` + // Currency presented to the customer during payment. + PresentmentCurrency Currency `json:"presentment_currency"` +} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type ChargeRadarOptions struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session string `json:"session"` +} + +// An optional dictionary including the account to automatically transfer to as part of a destination charge. [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. +type ChargeTransferData struct { + // The amount transferred to the destination account, if specified. By default, the entire charge amount is transferred to the destination account. + Amount int64 `json:"amount"` + // ID of an existing, connected Stripe account to transfer funds to if `transfer_data` was specified in the charge request. + Destination *Account `json:"destination"` +} + +// The `Charge` object represents a single attempt to move money into your Stripe account. +// PaymentIntent confirmation is the most common way to create Charges, but transferring +// money to a different Stripe account through Connect also creates Charges. +// Some legacy payment flows create Charges directly, which is not recommended for new integrations. +type Charge struct { + APIResource + // Amount intended to be collected by this payment. A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + Amount int64 `json:"amount"` + // Amount in cents (or local equivalent) captured (can be less than the amount attribute on the charge if a partial capture was made). + AmountCaptured int64 `json:"amount_captured"` + // Amount in cents (or local equivalent) refunded (can be less than the amount attribute on the charge if a partial refund was issued). + AmountRefunded int64 `json:"amount_refunded"` + // ID of the Connect application that created the charge. + Application *Application `json:"application"` + // The application fee (if any) for the charge. [See the Connect documentation](https://stripe.com/docs/connect/direct-charges#collect-fees) for details. + ApplicationFee *ApplicationFee `json:"application_fee"` + // The amount of the application fee (if any) requested for the charge. [See the Connect documentation](https://stripe.com/docs/connect/direct-charges#collect-fees) for details. + ApplicationFeeAmount int64 `json:"application_fee_amount"` + // Authorization code on the charge. + AuthorizationCode string `json:"authorization_code"` + // ID of the balance transaction that describes the impact of this charge on your account balance (not including refunds or disputes). + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + BillingDetails *ChargeBillingDetails `json:"billing_details"` + // The full statement descriptor that is passed to card networks, and that is displayed on your customers' credit card and bank statements. Allows you to see what the statement descriptor looks like after the static and dynamic portions are combined. This value only exists for card payments. + CalculatedStatementDescriptor string `json:"calculated_statement_descriptor"` + // If the charge was created without capturing, this Boolean represents whether it is still uncaptured or has since been captured. + Captured bool `json:"captured"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // ID of the customer this charge is for if one exists. + Customer *Customer `json:"customer"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // Whether the charge has been disputed. + Disputed bool `json:"disputed"` + // ID of the balance transaction that describes the reversal of the balance on your account due to payment failure. + FailureBalanceTransaction *BalanceTransaction `json:"failure_balance_transaction"` + // Error code explaining reason for charge failure if available (see [the errors section](https://stripe.com/docs/error-codes) for a list of codes). + FailureCode string `json:"failure_code"` + // Message to user further explaining reason for charge failure if available. + FailureMessage string `json:"failure_message"` + // Information on fraud assessments for the charge. + FraudDetails *ChargeFraudDetails `json:"fraud_details"` + // Unique identifier for the object. + ID string `json:"id"` + Level3 *ChargeLevel3 `json:"level3"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The account (if any) the charge was made on behalf of without triggering an automatic transfer. See the [Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers) for details. + OnBehalfOf *Account `json:"on_behalf_of"` + // Details about whether the payment was accepted, and why. See [understanding declines](https://stripe.com/docs/declines) for details. + Outcome *ChargeOutcome `json:"outcome"` + // `true` if the charge succeeded, or was successfully authorized for later capture. + Paid bool `json:"paid"` + // ID of the PaymentIntent associated with this charge, if one exists. + PaymentIntent *PaymentIntent `json:"payment_intent"` + // ID of the payment method used in this charge. + PaymentMethod string `json:"payment_method"` + // Details about the payment method at the time of the transaction. + PaymentMethodDetails *ChargePaymentMethodDetails `json:"payment_method_details"` + PresentmentDetails *ChargePresentmentDetails `json:"presentment_details"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *ChargeRadarOptions `json:"radar_options"` + // This is the email address that the receipt for this charge was sent to. + ReceiptEmail string `json:"receipt_email"` + // This is the transaction number that appears on email receipts sent for this charge. This attribute will be `null` until a receipt has been sent. + ReceiptNumber string `json:"receipt_number"` + // This is the URL to view the receipt for this charge. The receipt is kept up-to-date to the latest state of the charge, including any refunds. If the charge is for an Invoice, the receipt will be stylized as an Invoice receipt. + ReceiptURL string `json:"receipt_url"` + // Whether the charge has been fully refunded. If the charge is only partially refunded, this attribute will still be false. + Refunded bool `json:"refunded"` + // A list of refunds that have been applied to the charge. + Refunds *RefundList `json:"refunds"` + // ID of the review associated with this charge if one exists. + Review *Review `json:"review"` + // Shipping information for the charge. + Shipping *ShippingDetails `json:"shipping"` + // This is a legacy field that will be removed in the future. It contains the Source, Card, or BankAccount object used for the charge. For details about the payment method used for this charge, refer to `payment_method` or `payment_method_details` instead. + Source *PaymentSource `json:"source"` + // The transfer ID which created this charge. Only present if the charge came from another Stripe account. [See the Connect documentation](https://docs.stripe.com/connect/destination-charges) for details. + SourceTransfer *Transfer `json:"source_transfer"` + // For a non-card charge, text that appears on the customer's statement as the statement descriptor. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + // + // For a card charge, this value is ignored unless you don't specify a `statement_descriptor_suffix`, in which case this value is used as the suffix. + StatementDescriptor string `json:"statement_descriptor"` + // Provides information about a card charge. Concatenated to the account's [statement descriptor prefix](https://docs.stripe.com/get-started/account/statement-descriptors#static) to form the complete statement descriptor that appears on the customer's statement. If the account has no prefix value, the suffix is concatenated to the account's statement descriptor. + StatementDescriptorSuffix string `json:"statement_descriptor_suffix"` + // The status of the payment is either `succeeded`, `pending`, or `failed`. + Status ChargeStatus `json:"status"` + // ID of the transfer to the `destination` account (only applicable if the charge was created using the `destination` parameter). + Transfer *Transfer `json:"transfer"` + // An optional dictionary including the account to automatically transfer to as part of a destination charge. [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. + TransferData *ChargeTransferData `json:"transfer_data"` + // A string that identifies this transaction as part of a group. See the [Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-options) for details. + TransferGroup string `json:"transfer_group"` +} + +// ChargeList is a list of Charges as retrieved from a list endpoint. +type ChargeList struct { + APIResource + ListMeta + Data []*Charge `json:"data"` +} + +// ChargeSearchResult is a list of Charge search results as retrieved from a search endpoint. +type ChargeSearchResult struct { + APIResource + SearchMeta + Data []*Charge `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Charge. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (c *Charge) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + c.ID = id + return nil + } + + type charge Charge + var v charge + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *c = Charge(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/charge_service.go b/vendor/github.com/stripe/stripe-go/v82/charge_service.go new file mode 100644 index 00000000..f90b736a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/charge_service.go @@ -0,0 +1,110 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1ChargeService is used to invoke /v1/charges APIs. +type v1ChargeService struct { + B Backend + Key string +} + +// This method is no longer recommended—use the [Payment Intents API](https://docs.stripe.com/docs/api/payment_intents) +// to initiate a new payment instead. Confirmation of the PaymentIntent creates the Charge +// object used to request payment. +func (c v1ChargeService) Create(ctx context.Context, params *ChargeCreateParams) (*Charge, error) { + if params == nil { + params = &ChargeCreateParams{} + } + params.Context = ctx + charge := &Charge{} + err := c.B.Call(http.MethodPost, "/v1/charges", c.Key, params, charge) + return charge, err +} + +// Retrieves the details of a charge that has previously been created. Supply the unique charge ID that was returned from your previous request, and Stripe will return the corresponding charge information. The same information is returned when creating or refunding the charge. +func (c v1ChargeService) Retrieve(ctx context.Context, id string, params *ChargeRetrieveParams) (*Charge, error) { + if params == nil { + params = &ChargeRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/charges/%s", id) + charge := &Charge{} + err := c.B.Call(http.MethodGet, path, c.Key, params, charge) + return charge, err +} + +// Updates the specified charge by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +func (c v1ChargeService) Update(ctx context.Context, id string, params *ChargeUpdateParams) (*Charge, error) { + if params == nil { + params = &ChargeUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/charges/%s", id) + charge := &Charge{} + err := c.B.Call(http.MethodPost, path, c.Key, params, charge) + return charge, err +} + +// Capture the payment of an existing, uncaptured charge that was created with the capture option set to false. +// +// Uncaptured payments expire a set number of days after they are created ([7 by default](https://docs.stripe.com/docs/charges/placing-a-hold)), after which they are marked as refunded and capture attempts will fail. +// +// Don't use this method to capture a PaymentIntent-initiated charge. Use [Capture a PaymentIntent](https://docs.stripe.com/docs/api/payment_intents/capture). +func (c v1ChargeService) Capture(ctx context.Context, id string, params *ChargeCaptureParams) (*Charge, error) { + if params == nil { + params = &ChargeCaptureParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/charges/%s/capture", id) + charge := &Charge{} + err := c.B.Call(http.MethodPost, path, c.Key, params, charge) + return charge, err +} + +// Returns a list of charges you've previously created. The charges are returned in sorted order, with the most recent charges appearing first. +func (c v1ChargeService) List(ctx context.Context, listParams *ChargeListParams) Seq2[*Charge, error] { + if listParams == nil { + listParams = &ChargeListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Charge, ListContainer, error) { + list := &ChargeList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/charges", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// Search for charges you've previously created using Stripe's [Search Query Language](https://docs.stripe.com/docs/search#search-query-language). +// Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating +// conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up +// to an hour behind during outages. Search functionality is not available to merchants in India. +func (c v1ChargeService) Search(ctx context.Context, params *ChargeSearchParams) Seq2[*Charge, error] { + if params == nil { + params = &ChargeSearchParams{} + } + params.Context = ctx + return newV1SearchList(params, func(p *Params, b *form.Values) ([]*Charge, SearchContainer, error) { + list := &ChargeSearchResult{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/charges/search", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/checkout_session.go b/vendor/github.com/stripe/stripe-go/v82/checkout_session.go new file mode 100644 index 00000000..aceb1703 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/checkout_session.go @@ -0,0 +1,5453 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Type of the account referenced. +type CheckoutSessionAutomaticTaxLiabilityType string + +// List of values that CheckoutSessionAutomaticTaxLiabilityType can take +const ( + CheckoutSessionAutomaticTaxLiabilityTypeAccount CheckoutSessionAutomaticTaxLiabilityType = "account" + CheckoutSessionAutomaticTaxLiabilityTypeSelf CheckoutSessionAutomaticTaxLiabilityType = "self" +) + +// The status of the most recent automated tax calculation for this session. +type CheckoutSessionAutomaticTaxStatus string + +// List of values that CheckoutSessionAutomaticTaxStatus can take +const ( + CheckoutSessionAutomaticTaxStatusComplete CheckoutSessionAutomaticTaxStatus = "complete" + CheckoutSessionAutomaticTaxStatusFailed CheckoutSessionAutomaticTaxStatus = "failed" + CheckoutSessionAutomaticTaxStatusRequiresLocationInputs CheckoutSessionAutomaticTaxStatus = "requires_location_inputs" +) + +// Describes whether Checkout should collect the customer's billing address. Defaults to `auto`. +type CheckoutSessionBillingAddressCollection string + +// List of values that CheckoutSessionBillingAddressCollection can take +const ( + CheckoutSessionBillingAddressCollectionAuto CheckoutSessionBillingAddressCollection = "auto" + CheckoutSessionBillingAddressCollectionRequired CheckoutSessionBillingAddressCollection = "required" +) + +// If `opt_in`, the customer consents to receiving promotional communications +// from the merchant about this Checkout Session. +type CheckoutSessionConsentPromotions string + +// List of values that CheckoutSessionConsentPromotions can take +const ( + CheckoutSessionConsentPromotionsOptIn CheckoutSessionConsentPromotions = "opt_in" + CheckoutSessionConsentPromotionsOptOut CheckoutSessionConsentPromotions = "opt_out" +) + +// If `accepted`, the customer in this Checkout Session has agreed to the merchant's terms of service. +type CheckoutSessionConsentTermsOfService string + +// List of values that CheckoutSessionConsentTermsOfService can take +const ( + CheckoutSessionConsentTermsOfServiceAccepted CheckoutSessionConsentTermsOfService = "accepted" +) + +// Determines the position and visibility of the payment method reuse agreement in the UI. When set to `auto`, Stripe's defaults will be used. +// +// When set to `hidden`, the payment method reuse agreement text will always be hidden in the UI. +type CheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition string + +// List of values that CheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition can take +const ( + CheckoutSessionConsentCollectionPaymentMethodReuseAgreementPositionAuto CheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition = "auto" + CheckoutSessionConsentCollectionPaymentMethodReuseAgreementPositionHidden CheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition = "hidden" +) + +// If set to `auto`, enables the collection of customer consent for promotional communications. The Checkout +// Session will determine whether to display an option to opt into promotional communication +// from the merchant depending on the customer's locale. Only available to US merchants. +type CheckoutSessionConsentCollectionPromotions string + +// List of values that CheckoutSessionConsentCollectionPromotions can take +const ( + CheckoutSessionConsentCollectionPromotionsAuto CheckoutSessionConsentCollectionPromotions = "auto" + CheckoutSessionConsentCollectionPromotionsNone CheckoutSessionConsentCollectionPromotions = "none" +) + +// If set to `required`, it requires customers to accept the terms of service before being able to pay. +type CheckoutSessionConsentCollectionTermsOfService string + +// List of values that CheckoutSessionConsentCollectionTermsOfService can take +const ( + CheckoutSessionConsentCollectionTermsOfServiceNone CheckoutSessionConsentCollectionTermsOfService = "none" + CheckoutSessionConsentCollectionTermsOfServiceRequired CheckoutSessionConsentCollectionTermsOfService = "required" +) + +// The type of the label. +type CheckoutSessionCustomFieldLabelType string + +// List of values that CheckoutSessionCustomFieldLabelType can take +const ( + CheckoutSessionCustomFieldLabelTypeCustom CheckoutSessionCustomFieldLabelType = "custom" +) + +// The type of the field. +type CheckoutSessionCustomFieldType string + +// List of values that CheckoutSessionCustomFieldType can take +const ( + CheckoutSessionCustomFieldTypeDropdown CheckoutSessionCustomFieldType = "dropdown" + CheckoutSessionCustomFieldTypeNumeric CheckoutSessionCustomFieldType = "numeric" + CheckoutSessionCustomFieldTypeText CheckoutSessionCustomFieldType = "text" +) + +// Configure whether a Checkout Session creates a Customer when the Checkout Session completes. +type CheckoutSessionCustomerCreation string + +// List of values that CheckoutSessionCustomerCreation can take +const ( + CheckoutSessionCustomerCreationAlways CheckoutSessionCustomerCreation = "always" + CheckoutSessionCustomerCreationIfRequired CheckoutSessionCustomerCreation = "if_required" +) + +// The customer's tax exempt status after a completed Checkout Session. +type CheckoutSessionCustomerDetailsTaxExempt string + +// List of values that CheckoutSessionCustomerDetailsTaxExempt can take +const ( + CheckoutSessionCustomerDetailsTaxExemptExempt CheckoutSessionCustomerDetailsTaxExempt = "exempt" + CheckoutSessionCustomerDetailsTaxExemptNone CheckoutSessionCustomerDetailsTaxExempt = "none" + CheckoutSessionCustomerDetailsTaxExemptReverse CheckoutSessionCustomerDetailsTaxExempt = "reverse" +) + +// The type of the tax ID, one of `ad_nrt`, `ar_cuit`, `eu_vat`, `bo_tin`, `br_cnpj`, `br_cpf`, `cn_tin`, `co_nit`, `cr_tin`, `do_rcn`, `ec_ruc`, `eu_oss_vat`, `hr_oib`, `pe_ruc`, `ro_tin`, `rs_pib`, `sv_nit`, `uy_ruc`, `ve_rif`, `vn_tin`, `gb_vat`, `nz_gst`, `au_abn`, `au_arn`, `in_gst`, `no_vat`, `no_voec`, `za_vat`, `ch_vat`, `mx_rfc`, `sg_uen`, `ru_inn`, `ru_kpp`, `ca_bn`, `hk_br`, `es_cif`, `tw_vat`, `th_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `li_uid`, `li_vat`, `my_itn`, `us_ein`, `kr_brn`, `ca_qst`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `my_sst`, `sg_gst`, `ae_trn`, `cl_tin`, `sa_vat`, `id_npwp`, `my_frp`, `il_vat`, `ge_vat`, `ua_vat`, `is_vat`, `bg_uic`, `hu_tin`, `si_tin`, `ke_pin`, `tr_tin`, `eg_tin`, `ph_tin`, `al_tin`, `bh_vat`, `kz_bin`, `ng_tin`, `om_vat`, `de_stn`, `ch_uid`, `tz_vat`, `uz_vat`, `uz_tin`, `md_vat`, `ma_vat`, `by_tin`, `ao_tin`, `bs_tin`, `bb_tin`, `cd_nif`, `mr_nif`, `me_pib`, `zw_tin`, `ba_tin`, `gn_nif`, `mk_vat`, `sr_fin`, `sn_ninea`, `am_tin`, `np_pan`, `tj_tin`, `ug_tin`, `zm_tin`, `kh_tin`, `aw_tin`, `az_tin`, `bd_bin`, `bj_ifu`, `et_tin`, `kg_tin`, `la_tin`, `cm_niu`, `cv_nif`, `bf_ifu`, or `unknown` +type CheckoutSessionCustomerDetailsTaxIDType string + +// List of values that CheckoutSessionCustomerDetailsTaxIDType can take +const ( + CheckoutSessionCustomerDetailsTaxIDTypeADNRT CheckoutSessionCustomerDetailsTaxIDType = "ad_nrt" + CheckoutSessionCustomerDetailsTaxIDTypeAETRN CheckoutSessionCustomerDetailsTaxIDType = "ae_trn" + CheckoutSessionCustomerDetailsTaxIDTypeAlTin CheckoutSessionCustomerDetailsTaxIDType = "al_tin" + CheckoutSessionCustomerDetailsTaxIDTypeAmTin CheckoutSessionCustomerDetailsTaxIDType = "am_tin" + CheckoutSessionCustomerDetailsTaxIDTypeAoTin CheckoutSessionCustomerDetailsTaxIDType = "ao_tin" + CheckoutSessionCustomerDetailsTaxIDTypeARCUIT CheckoutSessionCustomerDetailsTaxIDType = "ar_cuit" + CheckoutSessionCustomerDetailsTaxIDTypeAUABN CheckoutSessionCustomerDetailsTaxIDType = "au_abn" + CheckoutSessionCustomerDetailsTaxIDTypeAUARN CheckoutSessionCustomerDetailsTaxIDType = "au_arn" + CheckoutSessionCustomerDetailsTaxIDTypeAwTin CheckoutSessionCustomerDetailsTaxIDType = "aw_tin" + CheckoutSessionCustomerDetailsTaxIDTypeAzTin CheckoutSessionCustomerDetailsTaxIDType = "az_tin" + CheckoutSessionCustomerDetailsTaxIDTypeBaTin CheckoutSessionCustomerDetailsTaxIDType = "ba_tin" + CheckoutSessionCustomerDetailsTaxIDTypeBbTin CheckoutSessionCustomerDetailsTaxIDType = "bb_tin" + CheckoutSessionCustomerDetailsTaxIDTypeBdBin CheckoutSessionCustomerDetailsTaxIDType = "bd_bin" + CheckoutSessionCustomerDetailsTaxIDTypeBfIfu CheckoutSessionCustomerDetailsTaxIDType = "bf_ifu" + CheckoutSessionCustomerDetailsTaxIDTypeBGUIC CheckoutSessionCustomerDetailsTaxIDType = "bg_uic" + CheckoutSessionCustomerDetailsTaxIDTypeBhVAT CheckoutSessionCustomerDetailsTaxIDType = "bh_vat" + CheckoutSessionCustomerDetailsTaxIDTypeBjIfu CheckoutSessionCustomerDetailsTaxIDType = "bj_ifu" + CheckoutSessionCustomerDetailsTaxIDTypeBOTIN CheckoutSessionCustomerDetailsTaxIDType = "bo_tin" + CheckoutSessionCustomerDetailsTaxIDTypeBRCNPJ CheckoutSessionCustomerDetailsTaxIDType = "br_cnpj" + CheckoutSessionCustomerDetailsTaxIDTypeBRCPF CheckoutSessionCustomerDetailsTaxIDType = "br_cpf" + CheckoutSessionCustomerDetailsTaxIDTypeBsTin CheckoutSessionCustomerDetailsTaxIDType = "bs_tin" + CheckoutSessionCustomerDetailsTaxIDTypeByTin CheckoutSessionCustomerDetailsTaxIDType = "by_tin" + CheckoutSessionCustomerDetailsTaxIDTypeCABN CheckoutSessionCustomerDetailsTaxIDType = "ca_bn" + CheckoutSessionCustomerDetailsTaxIDTypeCAGSTHST CheckoutSessionCustomerDetailsTaxIDType = "ca_gst_hst" + CheckoutSessionCustomerDetailsTaxIDTypeCAPSTBC CheckoutSessionCustomerDetailsTaxIDType = "ca_pst_bc" + CheckoutSessionCustomerDetailsTaxIDTypeCAPSTMB CheckoutSessionCustomerDetailsTaxIDType = "ca_pst_mb" + CheckoutSessionCustomerDetailsTaxIDTypeCAPSTSK CheckoutSessionCustomerDetailsTaxIDType = "ca_pst_sk" + CheckoutSessionCustomerDetailsTaxIDTypeCAQST CheckoutSessionCustomerDetailsTaxIDType = "ca_qst" + CheckoutSessionCustomerDetailsTaxIDTypeCdNif CheckoutSessionCustomerDetailsTaxIDType = "cd_nif" + CheckoutSessionCustomerDetailsTaxIDTypeCHUID CheckoutSessionCustomerDetailsTaxIDType = "ch_uid" + CheckoutSessionCustomerDetailsTaxIDTypeCHVAT CheckoutSessionCustomerDetailsTaxIDType = "ch_vat" + CheckoutSessionCustomerDetailsTaxIDTypeCLTIN CheckoutSessionCustomerDetailsTaxIDType = "cl_tin" + CheckoutSessionCustomerDetailsTaxIDTypeCmNiu CheckoutSessionCustomerDetailsTaxIDType = "cm_niu" + CheckoutSessionCustomerDetailsTaxIDTypeCNTIN CheckoutSessionCustomerDetailsTaxIDType = "cn_tin" + CheckoutSessionCustomerDetailsTaxIDTypeCONIT CheckoutSessionCustomerDetailsTaxIDType = "co_nit" + CheckoutSessionCustomerDetailsTaxIDTypeCRTIN CheckoutSessionCustomerDetailsTaxIDType = "cr_tin" + CheckoutSessionCustomerDetailsTaxIDTypeCvNif CheckoutSessionCustomerDetailsTaxIDType = "cv_nif" + CheckoutSessionCustomerDetailsTaxIDTypeDEStn CheckoutSessionCustomerDetailsTaxIDType = "de_stn" + CheckoutSessionCustomerDetailsTaxIDTypeDORCN CheckoutSessionCustomerDetailsTaxIDType = "do_rcn" + CheckoutSessionCustomerDetailsTaxIDTypeECRUC CheckoutSessionCustomerDetailsTaxIDType = "ec_ruc" + CheckoutSessionCustomerDetailsTaxIDTypeEGTIN CheckoutSessionCustomerDetailsTaxIDType = "eg_tin" + CheckoutSessionCustomerDetailsTaxIDTypeESCIF CheckoutSessionCustomerDetailsTaxIDType = "es_cif" + CheckoutSessionCustomerDetailsTaxIDTypeETTin CheckoutSessionCustomerDetailsTaxIDType = "et_tin" + CheckoutSessionCustomerDetailsTaxIDTypeEUOSSVAT CheckoutSessionCustomerDetailsTaxIDType = "eu_oss_vat" + CheckoutSessionCustomerDetailsTaxIDTypeEUVAT CheckoutSessionCustomerDetailsTaxIDType = "eu_vat" + CheckoutSessionCustomerDetailsTaxIDTypeGBVAT CheckoutSessionCustomerDetailsTaxIDType = "gb_vat" + CheckoutSessionCustomerDetailsTaxIDTypeGEVAT CheckoutSessionCustomerDetailsTaxIDType = "ge_vat" + CheckoutSessionCustomerDetailsTaxIDTypeGnNif CheckoutSessionCustomerDetailsTaxIDType = "gn_nif" + CheckoutSessionCustomerDetailsTaxIDTypeHKBR CheckoutSessionCustomerDetailsTaxIDType = "hk_br" + CheckoutSessionCustomerDetailsTaxIDTypeHROIB CheckoutSessionCustomerDetailsTaxIDType = "hr_oib" + CheckoutSessionCustomerDetailsTaxIDTypeHUTIN CheckoutSessionCustomerDetailsTaxIDType = "hu_tin" + CheckoutSessionCustomerDetailsTaxIDTypeIDNPWP CheckoutSessionCustomerDetailsTaxIDType = "id_npwp" + CheckoutSessionCustomerDetailsTaxIDTypeILVAT CheckoutSessionCustomerDetailsTaxIDType = "il_vat" + CheckoutSessionCustomerDetailsTaxIDTypeINGST CheckoutSessionCustomerDetailsTaxIDType = "in_gst" + CheckoutSessionCustomerDetailsTaxIDTypeISVAT CheckoutSessionCustomerDetailsTaxIDType = "is_vat" + CheckoutSessionCustomerDetailsTaxIDTypeJPCN CheckoutSessionCustomerDetailsTaxIDType = "jp_cn" + CheckoutSessionCustomerDetailsTaxIDTypeJPRN CheckoutSessionCustomerDetailsTaxIDType = "jp_rn" + CheckoutSessionCustomerDetailsTaxIDTypeJPTRN CheckoutSessionCustomerDetailsTaxIDType = "jp_trn" + CheckoutSessionCustomerDetailsTaxIDTypeKEPIN CheckoutSessionCustomerDetailsTaxIDType = "ke_pin" + CheckoutSessionCustomerDetailsTaxIDTypeKgTin CheckoutSessionCustomerDetailsTaxIDType = "kg_tin" + CheckoutSessionCustomerDetailsTaxIDTypeKhTin CheckoutSessionCustomerDetailsTaxIDType = "kh_tin" + CheckoutSessionCustomerDetailsTaxIDTypeKRBRN CheckoutSessionCustomerDetailsTaxIDType = "kr_brn" + CheckoutSessionCustomerDetailsTaxIDTypeKzBin CheckoutSessionCustomerDetailsTaxIDType = "kz_bin" + CheckoutSessionCustomerDetailsTaxIDTypeLaTin CheckoutSessionCustomerDetailsTaxIDType = "la_tin" + CheckoutSessionCustomerDetailsTaxIDTypeLIUID CheckoutSessionCustomerDetailsTaxIDType = "li_uid" + CheckoutSessionCustomerDetailsTaxIDTypeLiVAT CheckoutSessionCustomerDetailsTaxIDType = "li_vat" + CheckoutSessionCustomerDetailsTaxIDTypeMaVAT CheckoutSessionCustomerDetailsTaxIDType = "ma_vat" + CheckoutSessionCustomerDetailsTaxIDTypeMdVAT CheckoutSessionCustomerDetailsTaxIDType = "md_vat" + CheckoutSessionCustomerDetailsTaxIDTypeMePib CheckoutSessionCustomerDetailsTaxIDType = "me_pib" + CheckoutSessionCustomerDetailsTaxIDTypeMkVAT CheckoutSessionCustomerDetailsTaxIDType = "mk_vat" + CheckoutSessionCustomerDetailsTaxIDTypeMrNif CheckoutSessionCustomerDetailsTaxIDType = "mr_nif" + CheckoutSessionCustomerDetailsTaxIDTypeMXRFC CheckoutSessionCustomerDetailsTaxIDType = "mx_rfc" + CheckoutSessionCustomerDetailsTaxIDTypeMYFRP CheckoutSessionCustomerDetailsTaxIDType = "my_frp" + CheckoutSessionCustomerDetailsTaxIDTypeMYITN CheckoutSessionCustomerDetailsTaxIDType = "my_itn" + CheckoutSessionCustomerDetailsTaxIDTypeMYSST CheckoutSessionCustomerDetailsTaxIDType = "my_sst" + CheckoutSessionCustomerDetailsTaxIDTypeNgTin CheckoutSessionCustomerDetailsTaxIDType = "ng_tin" + CheckoutSessionCustomerDetailsTaxIDTypeNOVAT CheckoutSessionCustomerDetailsTaxIDType = "no_vat" + CheckoutSessionCustomerDetailsTaxIDTypeNOVOEC CheckoutSessionCustomerDetailsTaxIDType = "no_voec" + CheckoutSessionCustomerDetailsTaxIDTypeNpPan CheckoutSessionCustomerDetailsTaxIDType = "np_pan" + CheckoutSessionCustomerDetailsTaxIDTypeNZGST CheckoutSessionCustomerDetailsTaxIDType = "nz_gst" + CheckoutSessionCustomerDetailsTaxIDTypeOmVAT CheckoutSessionCustomerDetailsTaxIDType = "om_vat" + CheckoutSessionCustomerDetailsTaxIDTypePERUC CheckoutSessionCustomerDetailsTaxIDType = "pe_ruc" + CheckoutSessionCustomerDetailsTaxIDTypePHTIN CheckoutSessionCustomerDetailsTaxIDType = "ph_tin" + CheckoutSessionCustomerDetailsTaxIDTypeROTIN CheckoutSessionCustomerDetailsTaxIDType = "ro_tin" + CheckoutSessionCustomerDetailsTaxIDTypeRSPIB CheckoutSessionCustomerDetailsTaxIDType = "rs_pib" + CheckoutSessionCustomerDetailsTaxIDTypeRUINN CheckoutSessionCustomerDetailsTaxIDType = "ru_inn" + CheckoutSessionCustomerDetailsTaxIDTypeRUKPP CheckoutSessionCustomerDetailsTaxIDType = "ru_kpp" + CheckoutSessionCustomerDetailsTaxIDTypeSAVAT CheckoutSessionCustomerDetailsTaxIDType = "sa_vat" + CheckoutSessionCustomerDetailsTaxIDTypeSGGST CheckoutSessionCustomerDetailsTaxIDType = "sg_gst" + CheckoutSessionCustomerDetailsTaxIDTypeSGUEN CheckoutSessionCustomerDetailsTaxIDType = "sg_uen" + CheckoutSessionCustomerDetailsTaxIDTypeSITIN CheckoutSessionCustomerDetailsTaxIDType = "si_tin" + CheckoutSessionCustomerDetailsTaxIDTypeSnNinea CheckoutSessionCustomerDetailsTaxIDType = "sn_ninea" + CheckoutSessionCustomerDetailsTaxIDTypeSrFin CheckoutSessionCustomerDetailsTaxIDType = "sr_fin" + CheckoutSessionCustomerDetailsTaxIDTypeSVNIT CheckoutSessionCustomerDetailsTaxIDType = "sv_nit" + CheckoutSessionCustomerDetailsTaxIDTypeTHVAT CheckoutSessionCustomerDetailsTaxIDType = "th_vat" + CheckoutSessionCustomerDetailsTaxIDTypeTjTin CheckoutSessionCustomerDetailsTaxIDType = "tj_tin" + CheckoutSessionCustomerDetailsTaxIDTypeTRTIN CheckoutSessionCustomerDetailsTaxIDType = "tr_tin" + CheckoutSessionCustomerDetailsTaxIDTypeTWVAT CheckoutSessionCustomerDetailsTaxIDType = "tw_vat" + CheckoutSessionCustomerDetailsTaxIDTypeTzVAT CheckoutSessionCustomerDetailsTaxIDType = "tz_vat" + CheckoutSessionCustomerDetailsTaxIDTypeUAVAT CheckoutSessionCustomerDetailsTaxIDType = "ua_vat" + CheckoutSessionCustomerDetailsTaxIDTypeUgTin CheckoutSessionCustomerDetailsTaxIDType = "ug_tin" + CheckoutSessionCustomerDetailsTaxIDTypeUnknown CheckoutSessionCustomerDetailsTaxIDType = "unknown" + CheckoutSessionCustomerDetailsTaxIDTypeUSEIN CheckoutSessionCustomerDetailsTaxIDType = "us_ein" + CheckoutSessionCustomerDetailsTaxIDTypeUYRUC CheckoutSessionCustomerDetailsTaxIDType = "uy_ruc" + CheckoutSessionCustomerDetailsTaxIDTypeUzTin CheckoutSessionCustomerDetailsTaxIDType = "uz_tin" + CheckoutSessionCustomerDetailsTaxIDTypeUzVAT CheckoutSessionCustomerDetailsTaxIDType = "uz_vat" + CheckoutSessionCustomerDetailsTaxIDTypeVERIF CheckoutSessionCustomerDetailsTaxIDType = "ve_rif" + CheckoutSessionCustomerDetailsTaxIDTypeVNTIN CheckoutSessionCustomerDetailsTaxIDType = "vn_tin" + CheckoutSessionCustomerDetailsTaxIDTypeZAVAT CheckoutSessionCustomerDetailsTaxIDType = "za_vat" + CheckoutSessionCustomerDetailsTaxIDTypeZmTin CheckoutSessionCustomerDetailsTaxIDType = "zm_tin" + CheckoutSessionCustomerDetailsTaxIDTypeZwTin CheckoutSessionCustomerDetailsTaxIDType = "zw_tin" +) + +// Type of the account referenced. +type CheckoutSessionInvoiceCreationInvoiceDataIssuerType string + +// List of values that CheckoutSessionInvoiceCreationInvoiceDataIssuerType can take +const ( + CheckoutSessionInvoiceCreationInvoiceDataIssuerTypeAccount CheckoutSessionInvoiceCreationInvoiceDataIssuerType = "account" + CheckoutSessionInvoiceCreationInvoiceDataIssuerTypeSelf CheckoutSessionInvoiceCreationInvoiceDataIssuerType = "self" +) + +// The mode of the Checkout Session. +type CheckoutSessionMode string + +// List of values that CheckoutSessionMode can take +const ( + CheckoutSessionModePayment CheckoutSessionMode = "payment" + CheckoutSessionModeSetup CheckoutSessionMode = "setup" + CheckoutSessionModeSubscription CheckoutSessionMode = "subscription" +) + +// Configure whether a Checkout Session should collect a payment method. Defaults to `always`. +type CheckoutSessionPaymentMethodCollection string + +// List of values that CheckoutSessionPaymentMethodCollection can take +const ( + CheckoutSessionPaymentMethodCollectionAlways CheckoutSessionPaymentMethodCollection = "always" + CheckoutSessionPaymentMethodCollectionIfRequired CheckoutSessionPaymentMethodCollection = "if_required" +) + +// List of Stripe products where this mandate can be selected automatically. Returned when the Session is in `setup` mode. +type CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsDefaultFor string + +// List of values that CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsDefaultFor can take +const ( + CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsDefaultForInvoice CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsDefaultFor = "invoice" + CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsDefaultForSubscription CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsDefaultFor = "subscription" +) + +// Payment schedule for the mandate. +type CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule string + +// List of values that CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule can take +const ( + CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsPaymentScheduleCombined CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule = "combined" + CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsPaymentScheduleInterval CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule = "interval" + CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsPaymentScheduleSporadic CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule = "sporadic" +) + +// Transaction type of the mandate. +type CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsTransactionType string + +// List of values that CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsTransactionType can take +const ( + CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsTransactionTypeBusiness CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsTransactionType = "business" + CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsTransactionTypePersonal CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsTransactionType = "personal" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsACSSDebitSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsACSSDebitSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsACSSDebitSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsACSSDebitSetupFutureUsage = "none" + CheckoutSessionPaymentMethodOptionsACSSDebitSetupFutureUsageOffSession CheckoutSessionPaymentMethodOptionsACSSDebitSetupFutureUsage = "off_session" + CheckoutSessionPaymentMethodOptionsACSSDebitSetupFutureUsageOnSession CheckoutSessionPaymentMethodOptionsACSSDebitSetupFutureUsage = "on_session" +) + +// Bank account verification method. +type CheckoutSessionPaymentMethodOptionsACSSDebitVerificationMethod string + +// List of values that CheckoutSessionPaymentMethodOptionsACSSDebitVerificationMethod can take +const ( + CheckoutSessionPaymentMethodOptionsACSSDebitVerificationMethodAutomatic CheckoutSessionPaymentMethodOptionsACSSDebitVerificationMethod = "automatic" + CheckoutSessionPaymentMethodOptionsACSSDebitVerificationMethodInstant CheckoutSessionPaymentMethodOptionsACSSDebitVerificationMethod = "instant" + CheckoutSessionPaymentMethodOptionsACSSDebitVerificationMethodMicrodeposits CheckoutSessionPaymentMethodOptionsACSSDebitVerificationMethod = "microdeposits" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsAffirmSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsAffirmSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsAffirmSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsAffirmSetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsAfterpayClearpaySetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsAfterpayClearpaySetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsAfterpayClearpaySetupFutureUsageNone CheckoutSessionPaymentMethodOptionsAfterpayClearpaySetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsAlipaySetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsAlipaySetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsAlipaySetupFutureUsageNone CheckoutSessionPaymentMethodOptionsAlipaySetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsAmazonPaySetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsAmazonPaySetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsAmazonPaySetupFutureUsageNone CheckoutSessionPaymentMethodOptionsAmazonPaySetupFutureUsage = "none" + CheckoutSessionPaymentMethodOptionsAmazonPaySetupFutureUsageOffSession CheckoutSessionPaymentMethodOptionsAmazonPaySetupFutureUsage = "off_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsAUBECSDebitSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsAUBECSDebitSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsAUBECSDebitSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsAUBECSDebitSetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsBACSDebitSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsBACSDebitSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsBACSDebitSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsBACSDebitSetupFutureUsage = "none" + CheckoutSessionPaymentMethodOptionsBACSDebitSetupFutureUsageOffSession CheckoutSessionPaymentMethodOptionsBACSDebitSetupFutureUsage = "off_session" + CheckoutSessionPaymentMethodOptionsBACSDebitSetupFutureUsageOnSession CheckoutSessionPaymentMethodOptionsBACSDebitSetupFutureUsage = "on_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsBancontactSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsBancontactSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsBancontactSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsBancontactSetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsBoletoSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsBoletoSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsBoletoSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsBoletoSetupFutureUsage = "none" + CheckoutSessionPaymentMethodOptionsBoletoSetupFutureUsageOffSession CheckoutSessionPaymentMethodOptionsBoletoSetupFutureUsage = "off_session" + CheckoutSessionPaymentMethodOptionsBoletoSetupFutureUsageOnSession CheckoutSessionPaymentMethodOptionsBoletoSetupFutureUsage = "on_session" +) + +// Request ability to [capture beyond the standard authorization validity window](https://docs.stripe.com/payments/extended-authorization) for this CheckoutSession. +type CheckoutSessionPaymentMethodOptionsCardRequestExtendedAuthorization string + +// List of values that CheckoutSessionPaymentMethodOptionsCardRequestExtendedAuthorization can take +const ( + CheckoutSessionPaymentMethodOptionsCardRequestExtendedAuthorizationIfAvailable CheckoutSessionPaymentMethodOptionsCardRequestExtendedAuthorization = "if_available" + CheckoutSessionPaymentMethodOptionsCardRequestExtendedAuthorizationNever CheckoutSessionPaymentMethodOptionsCardRequestExtendedAuthorization = "never" +) + +// Request ability to [increment the authorization](https://docs.stripe.com/payments/incremental-authorization) for this CheckoutSession. +type CheckoutSessionPaymentMethodOptionsCardRequestIncrementalAuthorization string + +// List of values that CheckoutSessionPaymentMethodOptionsCardRequestIncrementalAuthorization can take +const ( + CheckoutSessionPaymentMethodOptionsCardRequestIncrementalAuthorizationIfAvailable CheckoutSessionPaymentMethodOptionsCardRequestIncrementalAuthorization = "if_available" + CheckoutSessionPaymentMethodOptionsCardRequestIncrementalAuthorizationNever CheckoutSessionPaymentMethodOptionsCardRequestIncrementalAuthorization = "never" +) + +// Request ability to make [multiple captures](https://docs.stripe.com/payments/multicapture) for this CheckoutSession. +type CheckoutSessionPaymentMethodOptionsCardRequestMulticapture string + +// List of values that CheckoutSessionPaymentMethodOptionsCardRequestMulticapture can take +const ( + CheckoutSessionPaymentMethodOptionsCardRequestMulticaptureIfAvailable CheckoutSessionPaymentMethodOptionsCardRequestMulticapture = "if_available" + CheckoutSessionPaymentMethodOptionsCardRequestMulticaptureNever CheckoutSessionPaymentMethodOptionsCardRequestMulticapture = "never" +) + +// Request ability to [overcapture](https://docs.stripe.com/payments/overcapture) for this CheckoutSession. +type CheckoutSessionPaymentMethodOptionsCardRequestOvercapture string + +// List of values that CheckoutSessionPaymentMethodOptionsCardRequestOvercapture can take +const ( + CheckoutSessionPaymentMethodOptionsCardRequestOvercaptureIfAvailable CheckoutSessionPaymentMethodOptionsCardRequestOvercapture = "if_available" + CheckoutSessionPaymentMethodOptionsCardRequestOvercaptureNever CheckoutSessionPaymentMethodOptionsCardRequestOvercapture = "never" +) + +// We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. +type CheckoutSessionPaymentMethodOptionsCardRequestThreeDSecure string + +// List of values that CheckoutSessionPaymentMethodOptionsCardRequestThreeDSecure can take +const ( + CheckoutSessionPaymentMethodOptionsCardRequestThreeDSecureAny CheckoutSessionPaymentMethodOptionsCardRequestThreeDSecure = "any" + CheckoutSessionPaymentMethodOptionsCardRequestThreeDSecureAutomatic CheckoutSessionPaymentMethodOptionsCardRequestThreeDSecure = "automatic" + CheckoutSessionPaymentMethodOptionsCardRequestThreeDSecureChallenge CheckoutSessionPaymentMethodOptionsCardRequestThreeDSecure = "challenge" +) + +// Specify the card brands to block in the Checkout Session. If a customer enters or selects a card belonging to a blocked brand, they can't complete the Session. +type CheckoutSessionPaymentMethodOptionsCardRestrictionsBrandsBlocked string + +// List of values that CheckoutSessionPaymentMethodOptionsCardRestrictionsBrandsBlocked can take +const ( + CheckoutSessionPaymentMethodOptionsCardRestrictionsBrandsBlockedAmericanExpress CheckoutSessionPaymentMethodOptionsCardRestrictionsBrandsBlocked = "american_express" + CheckoutSessionPaymentMethodOptionsCardRestrictionsBrandsBlockedDiscoverGlobalNetwork CheckoutSessionPaymentMethodOptionsCardRestrictionsBrandsBlocked = "discover_global_network" + CheckoutSessionPaymentMethodOptionsCardRestrictionsBrandsBlockedMastercard CheckoutSessionPaymentMethodOptionsCardRestrictionsBrandsBlocked = "mastercard" + CheckoutSessionPaymentMethodOptionsCardRestrictionsBrandsBlockedVisa CheckoutSessionPaymentMethodOptionsCardRestrictionsBrandsBlocked = "visa" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsCardSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsCardSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsCardSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsCardSetupFutureUsage = "none" + CheckoutSessionPaymentMethodOptionsCardSetupFutureUsageOffSession CheckoutSessionPaymentMethodOptionsCardSetupFutureUsage = "off_session" + CheckoutSessionPaymentMethodOptionsCardSetupFutureUsageOnSession CheckoutSessionPaymentMethodOptionsCardSetupFutureUsage = "on_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsCashAppSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsCashAppSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsCashAppSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsCashAppSetupFutureUsage = "none" +) + +// List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. +// +// Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. +type CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType string + +// List of values that CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType can take +const ( + CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypeABA CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType = "aba" + CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypeIBAN CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType = "iban" + CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypeSEPA CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType = "sepa" + CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypeSortCode CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType = "sort_code" + CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypeSpei CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType = "spei" + CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypeSwift CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType = "swift" + CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypeZengin CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType = "zengin" +) + +// The bank transfer type that this PaymentIntent is allowed to use for funding Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. +type CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferType string + +// List of values that CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferType can take +const ( + CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferTypeEUBankTransfer CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferType = "eu_bank_transfer" + CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferTypeGBBankTransfer CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferType = "gb_bank_transfer" + CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferTypeJPBankTransfer CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferType = "jp_bank_transfer" + CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferTypeMXBankTransfer CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferType = "mx_bank_transfer" + CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferTypeUSBankTransfer CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferType = "us_bank_transfer" +) + +// The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. +type CheckoutSessionPaymentMethodOptionsCustomerBalanceFundingType string + +// List of values that CheckoutSessionPaymentMethodOptionsCustomerBalanceFundingType can take +const ( + CheckoutSessionPaymentMethodOptionsCustomerBalanceFundingTypeBankTransfer CheckoutSessionPaymentMethodOptionsCustomerBalanceFundingType = "bank_transfer" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsCustomerBalanceSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsCustomerBalanceSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsCustomerBalanceSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsCustomerBalanceSetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsEPSSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsEPSSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsEPSSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsEPSSetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsFPXSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsFPXSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsFPXSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsFPXSetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsGiropaySetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsGiropaySetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsGiropaySetupFutureUsageNone CheckoutSessionPaymentMethodOptionsGiropaySetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsGrabpaySetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsGrabpaySetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsGrabpaySetupFutureUsageNone CheckoutSessionPaymentMethodOptionsGrabpaySetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsIDEALSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsIDEALSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsIDEALSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsIDEALSetupFutureUsage = "none" +) + +// Controls when the funds will be captured from the customer's account. +type CheckoutSessionPaymentMethodOptionsKakaoPayCaptureMethod string + +// List of values that CheckoutSessionPaymentMethodOptionsKakaoPayCaptureMethod can take +const ( + CheckoutSessionPaymentMethodOptionsKakaoPayCaptureMethodManual CheckoutSessionPaymentMethodOptionsKakaoPayCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsKakaoPaySetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsKakaoPaySetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsKakaoPaySetupFutureUsageNone CheckoutSessionPaymentMethodOptionsKakaoPaySetupFutureUsage = "none" + CheckoutSessionPaymentMethodOptionsKakaoPaySetupFutureUsageOffSession CheckoutSessionPaymentMethodOptionsKakaoPaySetupFutureUsage = "off_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsKlarnaSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsKlarnaSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsKlarnaSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsKlarnaSetupFutureUsage = "none" + CheckoutSessionPaymentMethodOptionsKlarnaSetupFutureUsageOffSession CheckoutSessionPaymentMethodOptionsKlarnaSetupFutureUsage = "off_session" + CheckoutSessionPaymentMethodOptionsKlarnaSetupFutureUsageOnSession CheckoutSessionPaymentMethodOptionsKlarnaSetupFutureUsage = "on_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsKonbiniSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsKonbiniSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsKonbiniSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsKonbiniSetupFutureUsage = "none" +) + +// Controls when the funds will be captured from the customer's account. +type CheckoutSessionPaymentMethodOptionsKrCardCaptureMethod string + +// List of values that CheckoutSessionPaymentMethodOptionsKrCardCaptureMethod can take +const ( + CheckoutSessionPaymentMethodOptionsKrCardCaptureMethodManual CheckoutSessionPaymentMethodOptionsKrCardCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsKrCardSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsKrCardSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsKrCardSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsKrCardSetupFutureUsage = "none" + CheckoutSessionPaymentMethodOptionsKrCardSetupFutureUsageOffSession CheckoutSessionPaymentMethodOptionsKrCardSetupFutureUsage = "off_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsLinkSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsLinkSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsLinkSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsLinkSetupFutureUsage = "none" + CheckoutSessionPaymentMethodOptionsLinkSetupFutureUsageOffSession CheckoutSessionPaymentMethodOptionsLinkSetupFutureUsage = "off_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsMobilepaySetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsMobilepaySetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsMobilepaySetupFutureUsageNone CheckoutSessionPaymentMethodOptionsMobilepaySetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsMultibancoSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsMultibancoSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsMultibancoSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsMultibancoSetupFutureUsage = "none" +) + +// Controls when the funds will be captured from the customer's account. +type CheckoutSessionPaymentMethodOptionsNaverPayCaptureMethod string + +// List of values that CheckoutSessionPaymentMethodOptionsNaverPayCaptureMethod can take +const ( + CheckoutSessionPaymentMethodOptionsNaverPayCaptureMethodManual CheckoutSessionPaymentMethodOptionsNaverPayCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsNaverPaySetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsNaverPaySetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsNaverPaySetupFutureUsageNone CheckoutSessionPaymentMethodOptionsNaverPaySetupFutureUsage = "none" + CheckoutSessionPaymentMethodOptionsNaverPaySetupFutureUsageOffSession CheckoutSessionPaymentMethodOptionsNaverPaySetupFutureUsage = "off_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsOXXOSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsOXXOSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsOXXOSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsOXXOSetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsP24SetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsP24SetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsP24SetupFutureUsageNone CheckoutSessionPaymentMethodOptionsP24SetupFutureUsage = "none" +) + +// Controls when the funds will be captured from the customer's account. +type CheckoutSessionPaymentMethodOptionsPaycoCaptureMethod string + +// List of values that CheckoutSessionPaymentMethodOptionsPaycoCaptureMethod can take +const ( + CheckoutSessionPaymentMethodOptionsPaycoCaptureMethodManual CheckoutSessionPaymentMethodOptionsPaycoCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsPayNowSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsPayNowSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsPayNowSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsPayNowSetupFutureUsage = "none" +) + +// Controls when the funds will be captured from the customer's account. +type CheckoutSessionPaymentMethodOptionsPaypalCaptureMethod string + +// List of values that CheckoutSessionPaymentMethodOptionsPaypalCaptureMethod can take +const ( + CheckoutSessionPaymentMethodOptionsPaypalCaptureMethodManual CheckoutSessionPaymentMethodOptionsPaypalCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsPaypalSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsPaypalSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsPaypalSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsPaypalSetupFutureUsage = "none" + CheckoutSessionPaymentMethodOptionsPaypalSetupFutureUsageOffSession CheckoutSessionPaymentMethodOptionsPaypalSetupFutureUsage = "off_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsRevolutPaySetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsRevolutPaySetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsRevolutPaySetupFutureUsageNone CheckoutSessionPaymentMethodOptionsRevolutPaySetupFutureUsage = "none" + CheckoutSessionPaymentMethodOptionsRevolutPaySetupFutureUsageOffSession CheckoutSessionPaymentMethodOptionsRevolutPaySetupFutureUsage = "off_session" +) + +// Controls when the funds will be captured from the customer's account. +type CheckoutSessionPaymentMethodOptionsSamsungPayCaptureMethod string + +// List of values that CheckoutSessionPaymentMethodOptionsSamsungPayCaptureMethod can take +const ( + CheckoutSessionPaymentMethodOptionsSamsungPayCaptureMethodManual CheckoutSessionPaymentMethodOptionsSamsungPayCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsSEPADebitSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsSEPADebitSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsSEPADebitSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsSEPADebitSetupFutureUsage = "none" + CheckoutSessionPaymentMethodOptionsSEPADebitSetupFutureUsageOffSession CheckoutSessionPaymentMethodOptionsSEPADebitSetupFutureUsage = "off_session" + CheckoutSessionPaymentMethodOptionsSEPADebitSetupFutureUsageOnSession CheckoutSessionPaymentMethodOptionsSEPADebitSetupFutureUsage = "on_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsSofortSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsSofortSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsSofortSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsSofortSetupFutureUsage = "none" +) + +// The account subcategories to use to filter for possible accounts to link. Valid subcategories are `checking` and `savings`. +type CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory string + +// List of values that CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory can take +const ( + CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategoryChecking CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory = "checking" + CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategorySavings CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory = "savings" +) + +// The list of permissions to request. The `payment_method` permission must be included. +type CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission string + +// List of values that CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission can take +const ( + CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionBalances CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "balances" + CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionOwnership CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "ownership" + CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionPaymentMethod CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "payment_method" + CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionTransactions CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "transactions" +) + +// Data features requested to be retrieved upon account creation. +type CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch string + +// List of values that CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch can take +const ( + CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchBalances CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "balances" + CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchOwnership CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "ownership" + CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchTransactions CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "transactions" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type CheckoutSessionPaymentMethodOptionsUSBankAccountSetupFutureUsage string + +// List of values that CheckoutSessionPaymentMethodOptionsUSBankAccountSetupFutureUsage can take +const ( + CheckoutSessionPaymentMethodOptionsUSBankAccountSetupFutureUsageNone CheckoutSessionPaymentMethodOptionsUSBankAccountSetupFutureUsage = "none" + CheckoutSessionPaymentMethodOptionsUSBankAccountSetupFutureUsageOffSession CheckoutSessionPaymentMethodOptionsUSBankAccountSetupFutureUsage = "off_session" + CheckoutSessionPaymentMethodOptionsUSBankAccountSetupFutureUsageOnSession CheckoutSessionPaymentMethodOptionsUSBankAccountSetupFutureUsage = "on_session" +) + +// Bank account verification method. +type CheckoutSessionPaymentMethodOptionsUSBankAccountVerificationMethod string + +// List of values that CheckoutSessionPaymentMethodOptionsUSBankAccountVerificationMethod can take +const ( + CheckoutSessionPaymentMethodOptionsUSBankAccountVerificationMethodAutomatic CheckoutSessionPaymentMethodOptionsUSBankAccountVerificationMethod = "automatic" + CheckoutSessionPaymentMethodOptionsUSBankAccountVerificationMethodInstant CheckoutSessionPaymentMethodOptionsUSBankAccountVerificationMethod = "instant" +) + +// The payment status of the Checkout Session, one of `paid`, `unpaid`, or `no_payment_required`. +// You can use this value to decide when to fulfill your customer's order. +type CheckoutSessionPaymentStatus string + +// List of values that CheckoutSessionPaymentStatus can take +const ( + CheckoutSessionPaymentStatusNoPaymentRequired CheckoutSessionPaymentStatus = "no_payment_required" + CheckoutSessionPaymentStatusPaid CheckoutSessionPaymentStatus = "paid" + CheckoutSessionPaymentStatusUnpaid CheckoutSessionPaymentStatus = "unpaid" +) + +// Determines which entity is allowed to update the shipping details. +// +// Default is `client_only`. Stripe Checkout client will automatically update the shipping details. If set to `server_only`, only your server is allowed to update the shipping details. +// +// When set to `server_only`, you must add the onShippingDetailsChange event handler when initializing the Stripe Checkout client and manually update the shipping details from your server using the Stripe API. +type CheckoutSessionPermissionsUpdateShippingDetails string + +// List of values that CheckoutSessionPermissionsUpdateShippingDetails can take +const ( + CheckoutSessionPermissionsUpdateShippingDetailsClientOnly CheckoutSessionPermissionsUpdateShippingDetails = "client_only" + CheckoutSessionPermissionsUpdateShippingDetailsServerOnly CheckoutSessionPermissionsUpdateShippingDetails = "server_only" +) + +// This parameter applies to `ui_mode: embedded`. Learn more about the [redirect behavior](https://stripe.com/docs/payments/checkout/custom-success-page?payment-ui=embedded-form) of embedded sessions. Defaults to `always`. +type CheckoutSessionRedirectOnCompletion string + +// List of values that CheckoutSessionRedirectOnCompletion can take +const ( + CheckoutSessionRedirectOnCompletionAlways CheckoutSessionRedirectOnCompletion = "always" + CheckoutSessionRedirectOnCompletionIfRequired CheckoutSessionRedirectOnCompletion = "if_required" + CheckoutSessionRedirectOnCompletionNever CheckoutSessionRedirectOnCompletion = "never" +) + +// Uses the `allow_redisplay` value of each saved payment method to filter the set presented to a returning customer. By default, only saved payment methods with 'allow_redisplay: ‘always' are shown in Checkout. +type CheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilter string + +// List of values that CheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilter can take +const ( + CheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilterAlways CheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilter = "always" + CheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilterLimited CheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilter = "limited" + CheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilterUnspecified CheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilter = "unspecified" +) + +// Enable customers to choose if they wish to remove their saved payment methods. Disabled by default. +type CheckoutSessionSavedPaymentMethodOptionsPaymentMethodRemove string + +// List of values that CheckoutSessionSavedPaymentMethodOptionsPaymentMethodRemove can take +const ( + CheckoutSessionSavedPaymentMethodOptionsPaymentMethodRemoveDisabled CheckoutSessionSavedPaymentMethodOptionsPaymentMethodRemove = "disabled" + CheckoutSessionSavedPaymentMethodOptionsPaymentMethodRemoveEnabled CheckoutSessionSavedPaymentMethodOptionsPaymentMethodRemove = "enabled" +) + +// Enable customers to choose if they wish to save their payment method for future use. Disabled by default. +type CheckoutSessionSavedPaymentMethodOptionsPaymentMethodSave string + +// List of values that CheckoutSessionSavedPaymentMethodOptionsPaymentMethodSave can take +const ( + CheckoutSessionSavedPaymentMethodOptionsPaymentMethodSaveDisabled CheckoutSessionSavedPaymentMethodOptionsPaymentMethodSave = "disabled" + CheckoutSessionSavedPaymentMethodOptionsPaymentMethodSaveEnabled CheckoutSessionSavedPaymentMethodOptionsPaymentMethodSave = "enabled" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type CheckoutSessionShippingCostTaxTaxabilityReason string + +// List of values that CheckoutSessionShippingCostTaxTaxabilityReason can take +const ( + CheckoutSessionShippingCostTaxTaxabilityReasonCustomerExempt CheckoutSessionShippingCostTaxTaxabilityReason = "customer_exempt" + CheckoutSessionShippingCostTaxTaxabilityReasonNotCollecting CheckoutSessionShippingCostTaxTaxabilityReason = "not_collecting" + CheckoutSessionShippingCostTaxTaxabilityReasonNotSubjectToTax CheckoutSessionShippingCostTaxTaxabilityReason = "not_subject_to_tax" + CheckoutSessionShippingCostTaxTaxabilityReasonNotSupported CheckoutSessionShippingCostTaxTaxabilityReason = "not_supported" + CheckoutSessionShippingCostTaxTaxabilityReasonPortionProductExempt CheckoutSessionShippingCostTaxTaxabilityReason = "portion_product_exempt" + CheckoutSessionShippingCostTaxTaxabilityReasonPortionReducedRated CheckoutSessionShippingCostTaxTaxabilityReason = "portion_reduced_rated" + CheckoutSessionShippingCostTaxTaxabilityReasonPortionStandardRated CheckoutSessionShippingCostTaxTaxabilityReason = "portion_standard_rated" + CheckoutSessionShippingCostTaxTaxabilityReasonProductExempt CheckoutSessionShippingCostTaxTaxabilityReason = "product_exempt" + CheckoutSessionShippingCostTaxTaxabilityReasonProductExemptHoliday CheckoutSessionShippingCostTaxTaxabilityReason = "product_exempt_holiday" + CheckoutSessionShippingCostTaxTaxabilityReasonProportionallyRated CheckoutSessionShippingCostTaxTaxabilityReason = "proportionally_rated" + CheckoutSessionShippingCostTaxTaxabilityReasonReducedRated CheckoutSessionShippingCostTaxTaxabilityReason = "reduced_rated" + CheckoutSessionShippingCostTaxTaxabilityReasonReverseCharge CheckoutSessionShippingCostTaxTaxabilityReason = "reverse_charge" + CheckoutSessionShippingCostTaxTaxabilityReasonStandardRated CheckoutSessionShippingCostTaxTaxabilityReason = "standard_rated" + CheckoutSessionShippingCostTaxTaxabilityReasonTaxableBasisReduced CheckoutSessionShippingCostTaxTaxabilityReason = "taxable_basis_reduced" + CheckoutSessionShippingCostTaxTaxabilityReasonZeroRated CheckoutSessionShippingCostTaxTaxabilityReason = "zero_rated" +) + +// The status of the Checkout Session, one of `open`, `complete`, or `expired`. +type CheckoutSessionStatus string + +// List of values that CheckoutSessionStatus can take +const ( + CheckoutSessionStatusComplete CheckoutSessionStatus = "complete" + CheckoutSessionStatusExpired CheckoutSessionStatus = "expired" + CheckoutSessionStatusOpen CheckoutSessionStatus = "open" +) + +// Describes the type of transaction being performed by Checkout in order to customize +// relevant text on the page, such as the submit button. `submit_type` can only be +// specified on Checkout Sessions in `payment` mode. If blank or `auto`, `pay` is used. +type CheckoutSessionSubmitType string + +// List of values that CheckoutSessionSubmitType can take +const ( + CheckoutSessionSubmitTypeAuto CheckoutSessionSubmitType = "auto" + CheckoutSessionSubmitTypeBook CheckoutSessionSubmitType = "book" + CheckoutSessionSubmitTypeDonate CheckoutSessionSubmitType = "donate" + CheckoutSessionSubmitTypePay CheckoutSessionSubmitType = "pay" + CheckoutSessionSubmitTypeSubscribe CheckoutSessionSubmitType = "subscribe" +) + +// Indicates whether a tax ID is required on the payment page +type CheckoutSessionTaxIDCollectionRequired string + +// List of values that CheckoutSessionTaxIDCollectionRequired can take +const ( + CheckoutSessionTaxIDCollectionRequiredIfSupported CheckoutSessionTaxIDCollectionRequired = "if_supported" + CheckoutSessionTaxIDCollectionRequiredNever CheckoutSessionTaxIDCollectionRequired = "never" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason string + +// List of values that CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason can take +const ( + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonCustomerExempt CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "customer_exempt" + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonNotCollecting CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "not_collecting" + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonNotSubjectToTax CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "not_subject_to_tax" + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonNotSupported CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "not_supported" + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonPortionProductExempt CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "portion_product_exempt" + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonPortionReducedRated CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "portion_reduced_rated" + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonPortionStandardRated CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "portion_standard_rated" + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonProductExempt CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "product_exempt" + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonProductExemptHoliday CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "product_exempt_holiday" + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonProportionallyRated CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "proportionally_rated" + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonReducedRated CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "reduced_rated" + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonReverseCharge CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "reverse_charge" + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonStandardRated CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "standard_rated" + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonTaxableBasisReduced CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "taxable_basis_reduced" + CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReasonZeroRated CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason = "zero_rated" +) + +// The UI mode of the Session. Defaults to `hosted`. +type CheckoutSessionUIMode string + +// List of values that CheckoutSessionUIMode can take +const ( + CheckoutSessionUIModeCustom CheckoutSessionUIMode = "custom" + CheckoutSessionUIModeEmbedded CheckoutSessionUIMode = "embedded" + CheckoutSessionUIModeHosted CheckoutSessionUIMode = "hosted" +) + +// Describes whether Checkout should display Link. Defaults to `auto`. +type CheckoutSessionWalletOptionsLinkDisplay string + +// List of values that CheckoutSessionWalletOptionsLinkDisplay can take +const ( + CheckoutSessionWalletOptionsLinkDisplayAuto CheckoutSessionWalletOptionsLinkDisplay = "auto" + CheckoutSessionWalletOptionsLinkDisplayNever CheckoutSessionWalletOptionsLinkDisplay = "never" +) + +// Only return the Checkout Sessions for the Customer details specified. +type CheckoutSessionListCustomerDetailsParams struct { + // Customer's email address. + Email *string `form:"email"` +} + +// Returns a list of Checkout Sessions. +type CheckoutSessionListParams struct { + ListParams `form:"*"` + // Only return Checkout Sessions that were created during the given date interval. + Created *int64 `form:"created"` + // Only return Checkout Sessions that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Only return the Checkout Sessions for the Customer specified. + Customer *string `form:"customer"` + // Only return the Checkout Sessions for the Customer details specified. + CustomerDetails *CheckoutSessionListCustomerDetailsParams `form:"customer_details"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return the Checkout Session for the PaymentIntent specified. + PaymentIntent *string `form:"payment_intent"` + // Only return the Checkout Sessions for the Payment Link specified. + PaymentLink *string `form:"payment_link"` + // Only return the Checkout Sessions matching the given status. + Status *string `form:"status"` + // Only return the Checkout Session for the subscription specified. + Subscription *string `form:"subscription"` +} + +// AddExpand appends a new field to expand. +func (p *CheckoutSessionListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Settings for price localization with [Adaptive Pricing](https://docs.stripe.com/payments/checkout/adaptive-pricing). +type CheckoutSessionAdaptivePricingParams struct { + // Set to `true` to enable [Adaptive Pricing](https://docs.stripe.com/payments/checkout/adaptive-pricing). Defaults to your [dashboard setting](https://dashboard.stripe.com/settings/adaptive-pricing). + Enabled *bool `form:"enabled"` +} + +// Configure a Checkout Session that can be used to recover an expired session. +type CheckoutSessionAfterExpirationRecoveryParams struct { + // Enables user redeemable promotion codes on the recovered Checkout Sessions. Defaults to `false` + AllowPromotionCodes *bool `form:"allow_promotion_codes"` + // If `true`, a recovery URL will be generated to recover this Checkout Session if it + // expires before a successful transaction is completed. It will be attached to the + // Checkout Session object upon expiration. + Enabled *bool `form:"enabled"` +} + +// Configure actions after a Checkout Session has expired. +type CheckoutSessionAfterExpirationParams struct { + // Configure a Checkout Session that can be used to recover an expired session. + Recovery *CheckoutSessionAfterExpirationRecoveryParams `form:"recovery"` +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type CheckoutSessionAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Settings for automatic tax lookup for this session and resulting payments, invoices, and subscriptions. +type CheckoutSessionAutomaticTaxParams struct { + // Set to `true` to [calculate tax automatically](https://docs.stripe.com/tax) using the customer's location. + // + // Enabling this parameter causes Checkout to collect any billing address information necessary for tax calculation. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *CheckoutSessionAutomaticTaxLiabilityParams `form:"liability"` +} + +// Determines the display of payment method reuse agreement text in the UI. If set to `hidden`, it will hide legal text related to the reuse of a payment method. +type CheckoutSessionConsentCollectionPaymentMethodReuseAgreementParams struct { + // Determines the position and visibility of the payment method reuse agreement in the UI. When set to `auto`, Stripe's + // defaults will be used. When set to `hidden`, the payment method reuse agreement text will always be hidden in the UI. + Position *string `form:"position"` +} + +// Configure fields for the Checkout Session to gather active consent from customers. +type CheckoutSessionConsentCollectionParams struct { + // Determines the display of payment method reuse agreement text in the UI. If set to `hidden`, it will hide legal text related to the reuse of a payment method. + PaymentMethodReuseAgreement *CheckoutSessionConsentCollectionPaymentMethodReuseAgreementParams `form:"payment_method_reuse_agreement"` + // If set to `auto`, enables the collection of customer consent for promotional communications. The Checkout + // Session will determine whether to display an option to opt into promotional communication + // from the merchant depending on the customer's locale. Only available to US merchants. + Promotions *string `form:"promotions"` + // If set to `required`, it requires customers to check a terms of service checkbox before being able to pay. + // There must be a valid terms of service URL set in your [Dashboard settings](https://dashboard.stripe.com/settings/public). + TermsOfService *string `form:"terms_of_service"` +} + +// The options available for the customer to select. Up to 200 options allowed. +type CheckoutSessionCustomFieldDropdownOptionParams struct { + // The label for the option, displayed to the customer. Up to 100 characters. + Label *string `form:"label"` + // The value for this option, not displayed to the customer, used by your integration to reconcile the option selected by the customer. Must be unique to this option, alphanumeric, and up to 100 characters. + Value *string `form:"value"` +} + +// Configuration for `type=dropdown` fields. +type CheckoutSessionCustomFieldDropdownParams struct { + // The value that will pre-fill the field on the payment page.Must match a `value` in the `options` array. + DefaultValue *string `form:"default_value"` + // The options available for the customer to select. Up to 200 options allowed. + Options []*CheckoutSessionCustomFieldDropdownOptionParams `form:"options"` +} + +// The label for the field, displayed to the customer. +type CheckoutSessionCustomFieldLabelParams struct { + // Custom text for the label, displayed to the customer. Up to 50 characters. + Custom *string `form:"custom"` + // The type of the label. + Type *string `form:"type"` +} + +// Configuration for `type=numeric` fields. +type CheckoutSessionCustomFieldNumericParams struct { + // The value that will pre-fill the field on the payment page. + DefaultValue *string `form:"default_value"` + // The maximum character length constraint for the customer's input. + MaximumLength *int64 `form:"maximum_length"` + // The minimum character length requirement for the customer's input. + MinimumLength *int64 `form:"minimum_length"` +} + +// Configuration for `type=text` fields. +type CheckoutSessionCustomFieldTextParams struct { + // The value that will pre-fill the field on the payment page. + DefaultValue *string `form:"default_value"` + // The maximum character length constraint for the customer's input. + MaximumLength *int64 `form:"maximum_length"` + // The minimum character length requirement for the customer's input. + MinimumLength *int64 `form:"minimum_length"` +} + +// Collect additional information from your customer using custom fields. Up to 3 fields are supported. +type CheckoutSessionCustomFieldParams struct { + // Configuration for `type=dropdown` fields. + Dropdown *CheckoutSessionCustomFieldDropdownParams `form:"dropdown"` + // String of your choice that your integration can use to reconcile this field. Must be unique to this field, alphanumeric, and up to 200 characters. + Key *string `form:"key"` + // The label for the field, displayed to the customer. + Label *CheckoutSessionCustomFieldLabelParams `form:"label"` + // Configuration for `type=numeric` fields. + Numeric *CheckoutSessionCustomFieldNumericParams `form:"numeric"` + // Whether the customer is required to complete the field before completing the Checkout Session. Defaults to `false`. + Optional *bool `form:"optional"` + // Configuration for `type=text` fields. + Text *CheckoutSessionCustomFieldTextParams `form:"text"` + // The type of the field. + Type *string `form:"type"` +} + +// Custom text that should be displayed after the payment confirmation button. +type CheckoutSessionCustomTextAfterSubmitParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed alongside shipping address collection. +type CheckoutSessionCustomTextShippingAddressParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed alongside the payment confirmation button. +type CheckoutSessionCustomTextSubmitParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed in place of the default terms of service agreement text. +type CheckoutSessionCustomTextTermsOfServiceAcceptanceParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Display additional text for your customers using custom text. +type CheckoutSessionCustomTextParams struct { + // Custom text that should be displayed after the payment confirmation button. + AfterSubmit *CheckoutSessionCustomTextAfterSubmitParams `form:"after_submit"` + // Custom text that should be displayed alongside shipping address collection. + ShippingAddress *CheckoutSessionCustomTextShippingAddressParams `form:"shipping_address"` + // Custom text that should be displayed alongside the payment confirmation button. + Submit *CheckoutSessionCustomTextSubmitParams `form:"submit"` + // Custom text that should be displayed in place of the default terms of service agreement text. + TermsOfServiceAcceptance *CheckoutSessionCustomTextTermsOfServiceAcceptanceParams `form:"terms_of_service_acceptance"` +} + +// Controls what fields on Customer can be updated by the Checkout Session. Can only be provided when `customer` is provided. +type CheckoutSessionCustomerUpdateParams struct { + // Describes whether Checkout saves the billing address onto `customer.address`. + // To always collect a full billing address, use `billing_address_collection`. Defaults to `never`. + Address *string `form:"address"` + // Describes whether Checkout saves the name onto `customer.name`. Defaults to `never`. + Name *string `form:"name"` + // Describes whether Checkout saves shipping information onto `customer.shipping`. + // To collect shipping information, use `shipping_address_collection`. Defaults to `never`. + Shipping *string `form:"shipping"` +} + +// The coupon or promotion code to apply to this Session. Currently, only up to one may be specified. +type CheckoutSessionDiscountParams struct { + // The ID of the coupon to apply to this Session. + Coupon *string `form:"coupon"` + // The ID of a promotion code to apply to this Session. + PromotionCode *string `form:"promotion_code"` +} + +// Default custom fields to be displayed on invoices for this customer. +type CheckoutSessionInvoiceCreationInvoiceDataCustomFieldParams struct { + // The name of the custom field. This may be up to 40 characters. + Name *string `form:"name"` + // The value of the custom field. This may be up to 140 characters. + Value *string `form:"value"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type CheckoutSessionInvoiceCreationInvoiceDataIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Default options for invoice PDF rendering for this customer. +type CheckoutSessionInvoiceCreationInvoiceDataRenderingOptionsParams struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + AmountTaxDisplay *string `form:"amount_tax_display"` +} + +// Parameters passed when creating invoices for payment-mode Checkout Sessions. +type CheckoutSessionInvoiceCreationInvoiceDataParams struct { + // The account tax IDs associated with the invoice. + AccountTaxIDs []*string `form:"account_tax_ids"` + // Default custom fields to be displayed on invoices for this customer. + CustomFields []*CheckoutSessionInvoiceCreationInvoiceDataCustomFieldParams `form:"custom_fields"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Default footer to be displayed on invoices for this customer. + Footer *string `form:"footer"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *CheckoutSessionInvoiceCreationInvoiceDataIssuerParams `form:"issuer"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Default options for invoice PDF rendering for this customer. + RenderingOptions *CheckoutSessionInvoiceCreationInvoiceDataRenderingOptionsParams `form:"rendering_options"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionInvoiceCreationInvoiceDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Generate a post-purchase Invoice for one-time payments. +type CheckoutSessionInvoiceCreationParams struct { + // Set to `true` to enable invoice creation. + Enabled *bool `form:"enabled"` + // Parameters passed when creating invoices for payment-mode Checkout Sessions. + InvoiceData *CheckoutSessionInvoiceCreationInvoiceDataParams `form:"invoice_data"` +} + +// When set, provides configuration for this item's quantity to be adjusted by the customer during Checkout. +type CheckoutSessionLineItemAdjustableQuantityParams struct { + // Set to true if the quantity can be adjusted to any non-negative integer. + Enabled *bool `form:"enabled"` + // The maximum quantity the customer can purchase for the Checkout Session. By default this value is 99. You can specify a value up to 999999. + Maximum *int64 `form:"maximum"` + // The minimum quantity the customer must purchase for the Checkout Session. By default this value is 0. + Minimum *int64 `form:"minimum"` +} + +// Data used to generate a new [Product](https://docs.stripe.com/api/products) object inline. One of `product` or `product_data` is required. +type CheckoutSessionLineItemPriceDataProductDataParams struct { + // The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + Description *string `form:"description"` + // A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + Images []*string `form:"images"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The product's name, meant to be displayable to the customer. + Name *string `form:"name"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionLineItemPriceDataProductDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The recurring components of a price such as `interval` and `interval_count`. +type CheckoutSessionLineItemPriceDataRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. +type CheckoutSessionLineItemPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. One of `product` or `product_data` is required. + Product *string `form:"product"` + // Data used to generate a new [Product](https://docs.stripe.com/api/products) object inline. One of `product` or `product_data` is required. + ProductData *CheckoutSessionLineItemPriceDataProductDataParams `form:"product_data"` + // The recurring components of a price such as `interval` and `interval_count`. + Recurring *CheckoutSessionLineItemPriceDataRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A non-negative integer in cents (or local equivalent) representing how much to charge. One of `unit_amount` or `unit_amount_decimal` is required. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// A list of items the customer is purchasing. Use this parameter to pass one-time or recurring [Prices](https://stripe.com/docs/api/prices). The parameter is required for `payment` and `subscription` mode. +// +// For `payment` mode, there is a maximum of 100 line items, however it is recommended to consolidate line items if there are more than a few dozen. +// +// For `subscription` mode, there is a maximum of 20 line items with recurring Prices and 20 line items with one-time Prices. Line items with one-time Prices will be on the initial invoice only. +type CheckoutSessionLineItemParams struct { + // When set, provides configuration for this item's quantity to be adjusted by the customer during Checkout. + AdjustableQuantity *CheckoutSessionLineItemAdjustableQuantityParams `form:"adjustable_quantity"` + // The [tax rates](https://stripe.com/docs/api/tax_rates) that will be applied to this line item depending on the customer's billing/shipping address. We currently support the following countries: US, GB, AU, and all countries in the EU. + DynamicTaxRates []*string `form:"dynamic_tax_rates"` + // The ID of the [Price](https://stripe.com/docs/api/prices) or [Plan](https://stripe.com/docs/api/plans) object. One of `price` or `price_data` is required. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *CheckoutSessionLineItemPriceDataParams `form:"price_data"` + // The quantity of the line item being purchased. Quantity should not be defined when `recurring.usage_type=metered`. + Quantity *int64 `form:"quantity"` + // The [tax rates](https://stripe.com/docs/api/tax_rates) which apply to this line item. + TaxRates []*string `form:"tax_rates"` +} + +// When set, provides configuration for the customer to adjust the quantity of the line item created when a customer chooses to add this optional item to their order. +type CheckoutSessionOptionalItemAdjustableQuantityParams struct { + // Set to true if the quantity can be adjusted to any non-negative integer. + Enabled *bool `form:"enabled"` + // The maximum quantity of this item the customer can purchase. By default this value is 99. You can specify a value up to 999999. + Maximum *int64 `form:"maximum"` + // The minimum quantity of this item the customer must purchase, if they choose to purchase it. Because this item is optional, the customer will always be able to remove it from their order, even if the `minimum` configured here is greater than 0. By default this value is 0. + Minimum *int64 `form:"minimum"` +} + +// A list of optional items the customer can add to their order at checkout. Use this parameter to pass one-time or recurring [Prices](https://stripe.com/docs/api/prices). +// +// There is a maximum of 10 optional items allowed on a Checkout Session, and the existing limits on the number of line items allowed on a Checkout Session apply to the combined number of line items and optional items. +// +// For `payment` mode, there is a maximum of 100 combined line items and optional items, however it is recommended to consolidate items if there are more than a few dozen. +// +// For `subscription` mode, there is a maximum of 20 line items and optional items with recurring Prices and 20 line items and optional items with one-time Prices. +type CheckoutSessionOptionalItemParams struct { + // When set, provides configuration for the customer to adjust the quantity of the line item created when a customer chooses to add this optional item to their order. + AdjustableQuantity *CheckoutSessionOptionalItemAdjustableQuantityParams `form:"adjustable_quantity"` + // The ID of the [Price](https://stripe.com/docs/api/prices) or [Plan](https://stripe.com/docs/api/plans) object. + Price *string `form:"price"` + // The initial quantity of the line item created when a customer chooses to add this optional item to their order. + Quantity *int64 `form:"quantity"` +} + +// The parameters used to automatically create a Transfer when the payment succeeds. +// For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). +type CheckoutSessionPaymentIntentDataTransferDataParams struct { + // The amount that will be transferred automatically when a charge succeeds. + Amount *int64 `form:"amount"` + // If specified, successful charges will be attributed to the destination + // account for tax reporting, and the funds from charges will be transferred + // to the destination account. The ID of the resulting transfer will be + // returned on the successful charge's `transfer` field. + Destination *string `form:"destination"` +} + +// A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in `payment` mode. +type CheckoutSessionPaymentIntentDataParams struct { + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. The amount of the application fee collected will be capped at the total amount captured. For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The Stripe account ID for which these funds are intended. For details, + // see the PaymentIntents [use case for connected + // accounts](https://docs.stripe.com/docs/payments/connected-accounts). + OnBehalfOf *string `form:"on_behalf_of"` + // Email address that the receipt for the resulting payment will be sent to. If `receipt_email` is specified for a payment in live mode, a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). + ReceiptEmail *string `form:"receipt_email"` + // Indicates that you intend to [make future payments](https://stripe.com/docs/payments/payment-intents#future-usage) with the payment + // method collected by this Checkout Session. + // + // When setting this to `on_session`, Checkout will show a notice to the + // customer that their payment details will be saved. + // + // When setting this to `off_session`, Checkout will show a notice to the + // customer that their payment details will be saved and used for future + // payments. + // + // If a Customer has been provided or Checkout creates a new Customer, + // Checkout will attach the payment method to the Customer. + // + // If Checkout does not create a Customer, the payment method is not attached + // to a Customer. To reuse the payment method, you can retrieve it from the + // Checkout Session's PaymentIntent. + // + // When processing card payments, Checkout also uses `setup_future_usage` + // to dynamically optimize your payment flow and comply with regional + // legislation and network rules, such as SCA. + SetupFutureUsage *string `form:"setup_future_usage"` + // Shipping information for this payment. + Shipping *ShippingDetailsParams `form:"shipping"` + // Text that appears on the customer's statement as the statement descriptor for a non-card charge. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + // + // Setting this value for a card charge returns an error. For card charges, set the [statement_descriptor_suffix](https://docs.stripe.com/get-started/account/statement-descriptors#dynamic) instead. + StatementDescriptor *string `form:"statement_descriptor"` + // Provides information about a card charge. Concatenated to the account's [statement descriptor prefix](https://docs.stripe.com/get-started/account/statement-descriptors#static) to form the complete statement descriptor that appears on the customer's statement. + StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"` + // The parameters used to automatically create a Transfer when the payment succeeds. + // For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + TransferData *CheckoutSessionPaymentIntentDataTransferDataParams `form:"transfer_data"` + // A string that identifies the resulting payment as part of a group. See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/connect/separate-charges-and-transfers) for details. + TransferGroup *string `form:"transfer_group"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionPaymentIntentDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// This parameter allows you to set some attributes on the payment method created during a Checkout session. +type CheckoutSessionPaymentMethodDataParams struct { + // Allow redisplay will be set on the payment method on confirmation and indicates whether this payment method can be shown again to the customer in a checkout flow. Only set this field if you wish to override the allow_redisplay value determined by Checkout. + AllowRedisplay *string `form:"allow_redisplay"` +} + +// Additional fields for Mandate creation +type CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsParams struct { + // A URL for custom mandate text to render during confirmation step. + // The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + // or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + CustomMandateURL *string `form:"custom_mandate_url"` + // List of Stripe products where this mandate can be selected automatically. Only usable in `setup` mode. + DefaultFor []*string `form:"default_for"` + // Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + IntervalDescription *string `form:"interval_description"` + // Payment schedule for the mandate. + PaymentSchedule *string `form:"payment_schedule"` + // Transaction type of the mandate. + TransactionType *string `form:"transaction_type"` +} + +// contains details about the ACSS Debit payment method options. +type CheckoutSessionPaymentMethodOptionsACSSDebitParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). This is only accepted for Checkout Sessions in `setup` mode. + Currency *string `form:"currency"` + // Additional fields for Mandate creation + MandateOptions *CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// contains details about the Affirm payment method options. +type CheckoutSessionPaymentMethodOptionsAffirmParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Afterpay Clearpay payment method options. +type CheckoutSessionPaymentMethodOptionsAfterpayClearpayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Alipay payment method options. +type CheckoutSessionPaymentMethodOptionsAlipayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the AmazonPay payment method options. +type CheckoutSessionPaymentMethodOptionsAmazonPayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the AU Becs Debit payment method options. +type CheckoutSessionPaymentMethodOptionsAUBECSDebitParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// Additional fields for Mandate creation +type CheckoutSessionPaymentMethodOptionsBACSDebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'DDIC' or 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// contains details about the Bacs Debit payment method options. +type CheckoutSessionPaymentMethodOptionsBACSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *CheckoutSessionPaymentMethodOptionsBACSDebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// contains details about the Bancontact payment method options. +type CheckoutSessionPaymentMethodOptionsBancontactParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Boleto payment method options. +type CheckoutSessionPaymentMethodOptionsBoletoParams struct { + // The number of calendar days before a Boleto voucher expires. For example, if you create a Boleto voucher on Monday and you set expires_after_days to 2, the Boleto invoice will expire on Wednesday at 23:59 America/Sao_Paulo time. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Installment options for card payments +type CheckoutSessionPaymentMethodOptionsCardInstallmentsParams struct { + // Setting to true enables installments for this Checkout Session. + // Setting to false will prevent any installment plan from applying to a payment. + Enabled *bool `form:"enabled"` +} + +// Restrictions to apply to the card payment method. For example, you can block specific card brands. +type CheckoutSessionPaymentMethodOptionsCardRestrictionsParams struct { + // Specify the card brands to block in the Checkout Session. If a customer enters or selects a card belonging to a blocked brand, they can't complete the Session. + BrandsBlocked []*string `form:"brands_blocked"` +} + +// contains details about the Card payment method options. +type CheckoutSessionPaymentMethodOptionsCardParams struct { + // Installment options for card payments + Installments *CheckoutSessionPaymentMethodOptionsCardInstallmentsParams `form:"installments"` + // Request ability to [capture beyond the standard authorization validity window](https://docs.stripe.com/payments/extended-authorization) for this CheckoutSession. + RequestExtendedAuthorization *string `form:"request_extended_authorization"` + // Request ability to [increment the authorization](https://docs.stripe.com/payments/incremental-authorization) for this CheckoutSession. + RequestIncrementalAuthorization *string `form:"request_incremental_authorization"` + // Request ability to make [multiple captures](https://docs.stripe.com/payments/multicapture) for this CheckoutSession. + RequestMulticapture *string `form:"request_multicapture"` + // Request ability to [overcapture](https://docs.stripe.com/payments/overcapture) for this CheckoutSession. + RequestOvercapture *string `form:"request_overcapture"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure *string `form:"request_three_d_secure"` + // Restrictions to apply to the card payment method. For example, you can block specific card brands. + Restrictions *CheckoutSessionPaymentMethodOptionsCardRestrictionsParams `form:"restrictions"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Provides information about a card payment that customers see on their statements. Concatenated with the Kana prefix (shortened Kana descriptor) or Kana statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 22 characters. + StatementDescriptorSuffixKana *string `form:"statement_descriptor_suffix_kana"` + // Provides information about a card payment that customers see on their statements. Concatenated with the Kanji prefix (shortened Kanji descriptor) or Kanji statement descriptor that's set on the account to form the complete statement descriptor. Maximum 17 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 17 characters. + StatementDescriptorSuffixKanji *string `form:"statement_descriptor_suffix_kanji"` +} + +// contains details about the Cashapp Pay payment method options. +type CheckoutSessionPaymentMethodOptionsCashAppParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Configuration for eu_bank_transfer funding type. +type CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country *string `form:"country"` +} + +// Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. +type CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferParams struct { + // Configuration for eu_bank_transfer funding type. + EUBankTransfer *CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams `form:"eu_bank_transfer"` + // List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. + // + // Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. + RequestedAddressTypes []*string `form:"requested_address_types"` + // The list of bank transfer types that this PaymentIntent is allowed to use for funding. + Type *string `form:"type"` +} + +// contains details about the Customer Balance payment method options. +type CheckoutSessionPaymentMethodOptionsCustomerBalanceParams struct { + // Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + BankTransfer *CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferParams `form:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType *string `form:"funding_type"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the EPS payment method options. +type CheckoutSessionPaymentMethodOptionsEPSParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the FPX payment method options. +type CheckoutSessionPaymentMethodOptionsFPXParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Giropay payment method options. +type CheckoutSessionPaymentMethodOptionsGiropayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Grabpay payment method options. +type CheckoutSessionPaymentMethodOptionsGrabpayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Ideal payment method options. +type CheckoutSessionPaymentMethodOptionsIDEALParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Kakao Pay payment method options. +type CheckoutSessionPaymentMethodOptionsKakaoPayParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Describes the upcoming charge for this subscription. +type CheckoutSessionPaymentMethodOptionsKlarnaSubscriptionNextBillingParams struct { + // The amount of the next charge for the subscription. + Amount *int64 `form:"amount"` + // The date of the next charge for the subscription in YYYY-MM-DD format. + Date *string `form:"date"` +} + +// Subscription details if the Checkout Session sets up a future subscription. +type CheckoutSessionPaymentMethodOptionsKlarnaSubscriptionParams struct { + // Unit of time between subscription charges. + Interval *string `form:"interval"` + // The number of intervals (specified in the `interval` attribute) between subscription charges. For example, `interval=month` and `interval_count=3` charges every 3 months. + IntervalCount *int64 `form:"interval_count"` + // Name for subscription. + Name *string `form:"name"` + // Describes the upcoming charge for this subscription. + NextBilling *CheckoutSessionPaymentMethodOptionsKlarnaSubscriptionNextBillingParams `form:"next_billing"` + // A non-customer-facing reference to correlate subscription charges in the Klarna app. Use a value that persists across subscription charges. + Reference *string `form:"reference"` +} + +// contains details about the Klarna payment method options. +type CheckoutSessionPaymentMethodOptionsKlarnaParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Subscription details if the Checkout Session sets up a future subscription. + Subscriptions []*CheckoutSessionPaymentMethodOptionsKlarnaSubscriptionParams `form:"subscriptions"` +} + +// contains details about the Konbini payment method options. +type CheckoutSessionPaymentMethodOptionsKonbiniParams struct { + // The number of calendar days (between 1 and 60) after which Konbini payment instructions will expire. For example, if a PaymentIntent is confirmed with Konbini and `expires_after_days` set to 2 on Monday JST, the instructions will expire on Wednesday 23:59:59 JST. Defaults to 3 days. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Korean card payment method options. +type CheckoutSessionPaymentMethodOptionsKrCardParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Link payment method options. +type CheckoutSessionPaymentMethodOptionsLinkParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Mobilepay payment method options. +type CheckoutSessionPaymentMethodOptionsMobilepayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Multibanco payment method options. +type CheckoutSessionPaymentMethodOptionsMultibancoParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Naver Pay payment method options. +type CheckoutSessionPaymentMethodOptionsNaverPayParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the OXXO payment method options. +type CheckoutSessionPaymentMethodOptionsOXXOParams struct { + // The number of calendar days before an OXXO voucher expires. For example, if you create an OXXO voucher on Monday and you set expires_after_days to 2, the OXXO invoice will expire on Wednesday at 23:59 America/Mexico_City time. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the P24 payment method options. +type CheckoutSessionPaymentMethodOptionsP24Params struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Confirm that the payer has accepted the P24 terms and conditions. + TOSShownAndAccepted *bool `form:"tos_shown_and_accepted"` +} + +// contains details about the Pay By Bank payment method options. +type CheckoutSessionPaymentMethodOptionsPayByBankParams struct{} + +// contains details about the PAYCO payment method options. +type CheckoutSessionPaymentMethodOptionsPaycoParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` +} + +// contains details about the PayNow payment method options. +type CheckoutSessionPaymentMethodOptionsPayNowParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the PayPal payment method options. +type CheckoutSessionPaymentMethodOptionsPaypalParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // [Preferred locale](https://stripe.com/docs/payments/paypal/supported-locales) of the PayPal checkout page that the customer is redirected to. + PreferredLocale *string `form:"preferred_locale"` + // A reference of the PayPal transaction visible to customer which is mapped to PayPal's invoice ID. This must be a globally unique ID if you have configured in your PayPal settings to block multiple payments per invoice ID. + Reference *string `form:"reference"` + // The risk correlation ID for an on-session payment using a saved PayPal payment method. + RiskCorrelationID *string `form:"risk_correlation_id"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Pix payment method options. +type CheckoutSessionPaymentMethodOptionsPixParams struct { + // The number of seconds (between 10 and 1209600) after which Pix payment will expire. Defaults to 86400 seconds. + ExpiresAfterSeconds *int64 `form:"expires_after_seconds"` +} + +// contains details about the RevolutPay payment method options. +type CheckoutSessionPaymentMethodOptionsRevolutPayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Samsung Pay payment method options. +type CheckoutSessionPaymentMethodOptionsSamsungPayParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` +} + +// Additional fields for Mandate creation +type CheckoutSessionPaymentMethodOptionsSEPADebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// contains details about the Sepa Debit payment method options. +type CheckoutSessionPaymentMethodOptionsSEPADebitParams struct { + // Additional fields for Mandate creation + MandateOptions *CheckoutSessionPaymentMethodOptionsSEPADebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// contains details about the Sofort payment method options. +type CheckoutSessionPaymentMethodOptionsSofortParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Swish payment method options. +type CheckoutSessionPaymentMethodOptionsSwishParams struct { + // The order reference that will be displayed to customers in the Swish application. Defaults to the `id` of the Payment Intent. + Reference *string `form:"reference"` +} + +// Additional fields for Financial Connections Session creation +type CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsParams struct { + // The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` +} + +// contains details about the Us Bank Account payment method options. +type CheckoutSessionPaymentMethodOptionsUSBankAccountParams struct { + // Additional fields for Financial Connections Session creation + FinancialConnections *CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsParams `form:"financial_connections"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// contains details about the WeChat Pay payment method options. +type CheckoutSessionPaymentMethodOptionsWeChatPayParams struct { + // The app ID registered with WeChat Pay. Only required when client is ios or android. + AppID *string `form:"app_id"` + // The client type that the end customer will pay from + Client *string `form:"client"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Payment-method-specific configuration. +type CheckoutSessionPaymentMethodOptionsParams struct { + // contains details about the ACSS Debit payment method options. + ACSSDebit *CheckoutSessionPaymentMethodOptionsACSSDebitParams `form:"acss_debit"` + // contains details about the Affirm payment method options. + Affirm *CheckoutSessionPaymentMethodOptionsAffirmParams `form:"affirm"` + // contains details about the Afterpay Clearpay payment method options. + AfterpayClearpay *CheckoutSessionPaymentMethodOptionsAfterpayClearpayParams `form:"afterpay_clearpay"` + // contains details about the Alipay payment method options. + Alipay *CheckoutSessionPaymentMethodOptionsAlipayParams `form:"alipay"` + // contains details about the AmazonPay payment method options. + AmazonPay *CheckoutSessionPaymentMethodOptionsAmazonPayParams `form:"amazon_pay"` + // contains details about the AU Becs Debit payment method options. + AUBECSDebit *CheckoutSessionPaymentMethodOptionsAUBECSDebitParams `form:"au_becs_debit"` + // contains details about the Bacs Debit payment method options. + BACSDebit *CheckoutSessionPaymentMethodOptionsBACSDebitParams `form:"bacs_debit"` + // contains details about the Bancontact payment method options. + Bancontact *CheckoutSessionPaymentMethodOptionsBancontactParams `form:"bancontact"` + // contains details about the Boleto payment method options. + Boleto *CheckoutSessionPaymentMethodOptionsBoletoParams `form:"boleto"` + // contains details about the Card payment method options. + Card *CheckoutSessionPaymentMethodOptionsCardParams `form:"card"` + // contains details about the Cashapp Pay payment method options. + CashApp *CheckoutSessionPaymentMethodOptionsCashAppParams `form:"cashapp"` + // contains details about the Customer Balance payment method options. + CustomerBalance *CheckoutSessionPaymentMethodOptionsCustomerBalanceParams `form:"customer_balance"` + // contains details about the EPS payment method options. + EPS *CheckoutSessionPaymentMethodOptionsEPSParams `form:"eps"` + // contains details about the FPX payment method options. + FPX *CheckoutSessionPaymentMethodOptionsFPXParams `form:"fpx"` + // contains details about the Giropay payment method options. + Giropay *CheckoutSessionPaymentMethodOptionsGiropayParams `form:"giropay"` + // contains details about the Grabpay payment method options. + Grabpay *CheckoutSessionPaymentMethodOptionsGrabpayParams `form:"grabpay"` + // contains details about the Ideal payment method options. + IDEAL *CheckoutSessionPaymentMethodOptionsIDEALParams `form:"ideal"` + // contains details about the Kakao Pay payment method options. + KakaoPay *CheckoutSessionPaymentMethodOptionsKakaoPayParams `form:"kakao_pay"` + // contains details about the Klarna payment method options. + Klarna *CheckoutSessionPaymentMethodOptionsKlarnaParams `form:"klarna"` + // contains details about the Konbini payment method options. + Konbini *CheckoutSessionPaymentMethodOptionsKonbiniParams `form:"konbini"` + // contains details about the Korean card payment method options. + KrCard *CheckoutSessionPaymentMethodOptionsKrCardParams `form:"kr_card"` + // contains details about the Link payment method options. + Link *CheckoutSessionPaymentMethodOptionsLinkParams `form:"link"` + // contains details about the Mobilepay payment method options. + Mobilepay *CheckoutSessionPaymentMethodOptionsMobilepayParams `form:"mobilepay"` + // contains details about the Multibanco payment method options. + Multibanco *CheckoutSessionPaymentMethodOptionsMultibancoParams `form:"multibanco"` + // contains details about the Naver Pay payment method options. + NaverPay *CheckoutSessionPaymentMethodOptionsNaverPayParams `form:"naver_pay"` + // contains details about the OXXO payment method options. + OXXO *CheckoutSessionPaymentMethodOptionsOXXOParams `form:"oxxo"` + // contains details about the P24 payment method options. + P24 *CheckoutSessionPaymentMethodOptionsP24Params `form:"p24"` + // contains details about the Pay By Bank payment method options. + PayByBank *CheckoutSessionPaymentMethodOptionsPayByBankParams `form:"pay_by_bank"` + // contains details about the PAYCO payment method options. + Payco *CheckoutSessionPaymentMethodOptionsPaycoParams `form:"payco"` + // contains details about the PayNow payment method options. + PayNow *CheckoutSessionPaymentMethodOptionsPayNowParams `form:"paynow"` + // contains details about the PayPal payment method options. + Paypal *CheckoutSessionPaymentMethodOptionsPaypalParams `form:"paypal"` + // contains details about the Pix payment method options. + Pix *CheckoutSessionPaymentMethodOptionsPixParams `form:"pix"` + // contains details about the RevolutPay payment method options. + RevolutPay *CheckoutSessionPaymentMethodOptionsRevolutPayParams `form:"revolut_pay"` + // contains details about the Samsung Pay payment method options. + SamsungPay *CheckoutSessionPaymentMethodOptionsSamsungPayParams `form:"samsung_pay"` + // contains details about the Sepa Debit payment method options. + SEPADebit *CheckoutSessionPaymentMethodOptionsSEPADebitParams `form:"sepa_debit"` + // contains details about the Sofort payment method options. + Sofort *CheckoutSessionPaymentMethodOptionsSofortParams `form:"sofort"` + // contains details about the Swish payment method options. + Swish *CheckoutSessionPaymentMethodOptionsSwishParams `form:"swish"` + // contains details about the Us Bank Account payment method options. + USBankAccount *CheckoutSessionPaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` + // contains details about the WeChat Pay payment method options. + WeChatPay *CheckoutSessionPaymentMethodOptionsWeChatPayParams `form:"wechat_pay"` +} + +// This property is used to set up permissions for various actions (e.g., update) on the CheckoutSession object. Can only be set when creating `embedded` or `custom` sessions. +// +// For specific permissions, please refer to their dedicated subsections, such as `permissions.update_shipping_details`. +type CheckoutSessionPermissionsParams struct { + // Determines which entity is allowed to update the shipping details. + // + // Default is `client_only`. Stripe Checkout client will automatically update the shipping details. If set to `server_only`, only your server is allowed to update the shipping details. + // + // When set to `server_only`, you must add the onShippingDetailsChange event handler when initializing the Stripe Checkout client and manually update the shipping details from your server using the Stripe API. + UpdateShippingDetails *string `form:"update_shipping_details"` +} + +// Controls phone number collection settings for the session. +// +// We recommend that you review your privacy policy and check with your legal contacts +// before using this feature. Learn more about [collecting phone numbers with Checkout](https://stripe.com/docs/payments/checkout/phone-numbers). +type CheckoutSessionPhoneNumberCollectionParams struct { + // Set to `true` to enable phone number collection. + // + // Can only be set in `payment` and `subscription` mode. + Enabled *bool `form:"enabled"` +} + +// Controls saved payment method settings for the session. Only available in `payment` and `subscription` mode. +type CheckoutSessionSavedPaymentMethodOptionsParams struct { + // Uses the `allow_redisplay` value of each saved payment method to filter the set presented to a returning customer. By default, only saved payment methods with 'allow_redisplay: ‘always' are shown in Checkout. + AllowRedisplayFilters []*string `form:"allow_redisplay_filters"` + // Enable customers to choose if they wish to remove their saved payment methods. Disabled by default. + PaymentMethodRemove *string `form:"payment_method_remove"` + // Enable customers to choose if they wish to save their payment method for future use. Disabled by default. + PaymentMethodSave *string `form:"payment_method_save"` +} + +// A subset of parameters to be passed to SetupIntent creation for Checkout Sessions in `setup` mode. +type CheckoutSessionSetupIntentDataParams struct { + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The Stripe account for which the setup is intended. + OnBehalfOf *string `form:"on_behalf_of"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionSetupIntentDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// When set, provides configuration for Checkout to collect a shipping address from a customer. +type CheckoutSessionShippingAddressCollectionParams struct { + // An array of two-letter ISO country codes representing which countries Checkout should provide as options for + // shipping locations. + AllowedCountries []*string `form:"allowed_countries"` +} + +// The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. +type CheckoutSessionShippingOptionShippingRateDataDeliveryEstimateMaximumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The lower bound of the estimated range. If empty, represents no lower bound. +type CheckoutSessionShippingOptionShippingRateDataDeliveryEstimateMinimumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. +type CheckoutSessionShippingOptionShippingRateDataDeliveryEstimateParams struct { + // The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. + Maximum *CheckoutSessionShippingOptionShippingRateDataDeliveryEstimateMaximumParams `form:"maximum"` + // The lower bound of the estimated range. If empty, represents no lower bound. + Minimum *CheckoutSessionShippingOptionShippingRateDataDeliveryEstimateMinimumParams `form:"minimum"` +} + +// Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type CheckoutSessionShippingOptionShippingRateDataFixedAmountCurrencyOptionsParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` +} + +// Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. +type CheckoutSessionShippingOptionShippingRateDataFixedAmountParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*CheckoutSessionShippingOptionShippingRateDataFixedAmountCurrencyOptionsParams `form:"currency_options"` +} + +// Parameters to be passed to Shipping Rate creation for this shipping option. +type CheckoutSessionShippingOptionShippingRateDataParams struct { + // The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. + DeliveryEstimate *CheckoutSessionShippingOptionShippingRateDataDeliveryEstimateParams `form:"delivery_estimate"` + // The name of the shipping rate, meant to be displayable to the customer. This will appear on CheckoutSessions. + DisplayName *string `form:"display_name"` + // Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. + FixedAmount *CheckoutSessionShippingOptionShippingRateDataFixedAmountParams `form:"fixed_amount"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. The Shipping tax code is `txcd_92010001`. + TaxCode *string `form:"tax_code"` + // The type of calculation to use on the shipping rate. + Type *string `form:"type"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionShippingOptionShippingRateDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The shipping rate options to apply to this Session. Up to a maximum of 5. +type CheckoutSessionShippingOptionParams struct { + // The ID of the Shipping Rate to use for this shipping option. + ShippingRate *string `form:"shipping_rate"` + // Parameters to be passed to Shipping Rate creation for this shipping option. + ShippingRateData *CheckoutSessionShippingOptionShippingRateDataParams `form:"shipping_rate_data"` +} + +// Controls how prorations and invoices for subscriptions are calculated and orchestrated. +type CheckoutSessionSubscriptionDataBillingModeParams struct { + Type *string `form:"type"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type CheckoutSessionSubscriptionDataInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type CheckoutSessionSubscriptionDataInvoiceSettingsParams struct { + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *CheckoutSessionSubscriptionDataInvoiceSettingsIssuerParams `form:"issuer"` +} + +// If specified, the funds from the subscription's invoices will be transferred to the destination and the ID of the resulting transfers will be found on the resulting charges. +type CheckoutSessionSubscriptionDataTransferDataParams struct { + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + AmountPercent *float64 `form:"amount_percent"` + // ID of an existing, connected Stripe account. + Destination *string `form:"destination"` +} + +// Defines how the subscription should behave when the user's free trial ends. +type CheckoutSessionSubscriptionDataTrialSettingsEndBehaviorParams struct { + // Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + MissingPaymentMethod *string `form:"missing_payment_method"` +} + +// Settings related to subscription trials. +type CheckoutSessionSubscriptionDataTrialSettingsParams struct { + // Defines how the subscription should behave when the user's free trial ends. + EndBehavior *CheckoutSessionSubscriptionDataTrialSettingsEndBehaviorParams `form:"end_behavior"` +} + +// A subset of parameters to be passed to subscription creation for Checkout Sessions in `subscription` mode. +type CheckoutSessionSubscriptionDataParams struct { + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. To use an application fee percent, the request must be made on behalf of another account, using the `Stripe-Account` header or an OAuth key. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + ApplicationFeePercent *float64 `form:"application_fee_percent"` + // A future timestamp to anchor the subscription's billing cycle for new subscriptions. + BillingCycleAnchor *int64 `form:"billing_cycle_anchor"` + // Controls how prorations and invoices for subscriptions are calculated and orchestrated. + BillingMode *CheckoutSessionSubscriptionDataBillingModeParams `form:"billing_mode"` + // The tax rates that will apply to any subscription item that does not have + // `tax_rates` set. Invoices created will have their `default_tax_rates` populated + // from the subscription. + DefaultTaxRates []*string `form:"default_tax_rates"` + // The subscription's description, meant to be displayable to the customer. + // Use this field to optionally store an explanation of the subscription + // for rendering in the [customer portal](https://stripe.com/docs/customer-management). + Description *string `form:"description"` + // All invoices will be billed using the specified settings. + InvoiceSettings *CheckoutSessionSubscriptionDataInvoiceSettingsParams `form:"invoice_settings"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The account on behalf of which to charge, for each of the subscription's invoices. + OnBehalfOf *string `form:"on_behalf_of"` + // Determines how to handle prorations resulting from the `billing_cycle_anchor`. If no value is passed, the default is `create_prorations`. + ProrationBehavior *string `form:"proration_behavior"` + // If specified, the funds from the subscription's invoices will be transferred to the destination and the ID of the resulting transfers will be found on the resulting charges. + TransferData *CheckoutSessionSubscriptionDataTransferDataParams `form:"transfer_data"` + // Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. Has to be at least 48 hours in the future. + TrialEnd *int64 `form:"trial_end"` + // Integer representing the number of trial period days before the customer is charged for the first time. Has to be at least 1. + TrialPeriodDays *int64 `form:"trial_period_days"` + // Settings related to subscription trials. + TrialSettings *CheckoutSessionSubscriptionDataTrialSettingsParams `form:"trial_settings"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionSubscriptionDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Controls tax ID collection during checkout. +type CheckoutSessionTaxIDCollectionParams struct { + // Enable tax ID collection during checkout. Defaults to `false`. + Enabled *bool `form:"enabled"` + // Describes whether a tax ID is required during checkout. Defaults to `never`. + Required *string `form:"required"` +} + +// contains details about the Link wallet options. +type CheckoutSessionWalletOptionsLinkParams struct { + // Specifies whether Checkout should display Link as a payment option. By default, Checkout will display all the supported wallets that the Checkout Session was created with. This is the `auto` behavior, and it is the default choice. + Display *string `form:"display"` +} + +// Wallet-specific configuration. +type CheckoutSessionWalletOptionsParams struct { + // contains details about the Link wallet options. + Link *CheckoutSessionWalletOptionsLinkParams `form:"link"` +} + +// Creates a Checkout Session object. +type CheckoutSessionParams struct { + Params `form:"*"` + // Settings for price localization with [Adaptive Pricing](https://docs.stripe.com/payments/checkout/adaptive-pricing). + AdaptivePricing *CheckoutSessionAdaptivePricingParams `form:"adaptive_pricing"` + // Configure actions after a Checkout Session has expired. + AfterExpiration *CheckoutSessionAfterExpirationParams `form:"after_expiration"` + // Enables user redeemable promotion codes. + AllowPromotionCodes *bool `form:"allow_promotion_codes"` + // Settings for automatic tax lookup for this session and resulting payments, invoices, and subscriptions. + AutomaticTax *CheckoutSessionAutomaticTaxParams `form:"automatic_tax"` + // Specify whether Checkout should collect the customer's billing address. Defaults to `auto`. + BillingAddressCollection *string `form:"billing_address_collection"` + // If set, Checkout displays a back button and customers will be directed to this URL if they decide to cancel payment and return to your website. This parameter is not allowed if ui_mode is `embedded` or `custom`. + CancelURL *string `form:"cancel_url"` + // A unique string to reference the Checkout Session. This can be a + // customer ID, a cart ID, or similar, and can be used to reconcile the + // session with your internal systems. + ClientReferenceID *string `form:"client_reference_id"` + // Information about the customer collected within the Checkout Session. Can only be set when updating `embedded` or `custom` sessions. + CollectedInformation *CheckoutSessionCollectedInformationParams `form:"collected_information"` + // Configure fields for the Checkout Session to gather active consent from customers. + ConsentCollection *CheckoutSessionConsentCollectionParams `form:"consent_collection"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). Required in `setup` mode when `payment_method_types` is not set. + Currency *string `form:"currency"` + // ID of an existing Customer, if one exists. In `payment` mode, the customer's most recently saved card + // payment method will be used to prefill the email, name, card details, and billing address + // on the Checkout page. In `subscription` mode, the customer's [default payment method](https://stripe.com/docs/api/customers/update#update_customer-invoice_settings-default_payment_method) + // will be used if it's a card, otherwise the most recently saved card will be used. A valid billing address, billing name and billing email are required on the payment method for Checkout to prefill the customer's card details. + // + // If the Customer already has a valid [email](https://stripe.com/docs/api/customers/object#customer_object-email) set, the email will be prefilled and not editable in Checkout. + // If the Customer does not have a valid `email`, Checkout will set the email entered during the session on the Customer. + // + // If blank for Checkout Sessions in `subscription` mode or with `customer_creation` set as `always` in `payment` mode, Checkout will create a new Customer object based on information provided during the payment flow. + // + // You can set [`payment_intent_data.setup_future_usage`](https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-payment_intent_data-setup_future_usage) to have Checkout automatically attach the payment method to the Customer you pass in for future reuse. + Customer *string `form:"customer"` + // Configure whether a Checkout Session creates a [Customer](https://stripe.com/docs/api/customers) during Session confirmation. + // + // When a Customer is not created, you can still retrieve email, address, and other customer data entered in Checkout + // with [customer_details](https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-customer_details). + // + // Sessions that don't create Customers instead are grouped by [guest customers](https://stripe.com/docs/payments/checkout/guest-customers) + // in the Dashboard. Promotion codes limited to first time customers will return invalid for these Sessions. + // + // Can only be set in `payment` and `setup` mode. + CustomerCreation *string `form:"customer_creation"` + // If provided, this value will be used when the Customer object is created. + // If not provided, customers will be asked to enter their email address. + // Use this parameter to prefill customer data if you already have an email + // on file. To access information about the customer once a session is + // complete, use the `customer` field. + CustomerEmail *string `form:"customer_email"` + // Controls what fields on Customer can be updated by the Checkout Session. Can only be provided when `customer` is provided. + CustomerUpdate *CheckoutSessionCustomerUpdateParams `form:"customer_update"` + // Collect additional information from your customer using custom fields. Up to 3 fields are supported. + CustomFields []*CheckoutSessionCustomFieldParams `form:"custom_fields"` + // Display additional text for your customers using custom text. + CustomText *CheckoutSessionCustomTextParams `form:"custom_text"` + // The coupon or promotion code to apply to this Session. Currently, only up to one may be specified. + Discounts []*CheckoutSessionDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The Epoch time in seconds at which the Checkout Session will expire. It can be anywhere from 30 minutes to 24 hours after Checkout Session creation. By default, this value is 24 hours from creation. + ExpiresAt *int64 `form:"expires_at"` + // Generate a post-purchase Invoice for one-time payments. + InvoiceCreation *CheckoutSessionInvoiceCreationParams `form:"invoice_creation"` + // A list of items the customer is purchasing. Use this parameter to pass one-time or recurring [Prices](https://stripe.com/docs/api/prices). The parameter is required for `payment` and `subscription` mode. + // + // For `payment` mode, there is a maximum of 100 line items, however it is recommended to consolidate line items if there are more than a few dozen. + // + // For `subscription` mode, there is a maximum of 20 line items with recurring Prices and 20 line items with one-time Prices. Line items with one-time Prices will be on the initial invoice only. + LineItems []*CheckoutSessionLineItemParams `form:"line_items"` + // The IETF language tag of the locale Checkout is displayed in. If blank or `auto`, the browser's locale is used. + Locale *string `form:"locale"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The mode of the Checkout Session. Pass `subscription` if the Checkout Session includes at least one recurring item. + Mode *string `form:"mode"` + // A list of optional items the customer can add to their order at checkout. Use this parameter to pass one-time or recurring [Prices](https://stripe.com/docs/api/prices). + // + // There is a maximum of 10 optional items allowed on a Checkout Session, and the existing limits on the number of line items allowed on a Checkout Session apply to the combined number of line items and optional items. + // + // For `payment` mode, there is a maximum of 100 combined line items and optional items, however it is recommended to consolidate items if there are more than a few dozen. + // + // For `subscription` mode, there is a maximum of 20 line items and optional items with recurring Prices and 20 line items and optional items with one-time Prices. + OptionalItems []*CheckoutSessionOptionalItemParams `form:"optional_items"` + // A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in `payment` mode. + PaymentIntentData *CheckoutSessionPaymentIntentDataParams `form:"payment_intent_data"` + // Specify whether Checkout should collect a payment method. When set to `if_required`, Checkout will not collect a payment method when the total due for the session is 0. + // This may occur if the Checkout Session includes a free trial or a discount. + // + // Can only be set in `subscription` mode. Defaults to `always`. + // + // If you'd like information on how to collect a payment method outside of Checkout, read the guide on configuring [subscriptions with a free trial](https://stripe.com/docs/payments/checkout/free-trials). + PaymentMethodCollection *string `form:"payment_method_collection"` + // The ID of the payment method configuration to use with this Checkout session. + PaymentMethodConfiguration *string `form:"payment_method_configuration"` + // This parameter allows you to set some attributes on the payment method created during a Checkout session. + PaymentMethodData *CheckoutSessionPaymentMethodDataParams `form:"payment_method_data"` + // Payment-method-specific configuration. + PaymentMethodOptions *CheckoutSessionPaymentMethodOptionsParams `form:"payment_method_options"` + // A list of the types of payment methods (e.g., `card`) this Checkout Session can accept. + // + // You can omit this attribute to manage your payment methods from the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). + // See [Dynamic Payment Methods](https://stripe.com/docs/payments/payment-methods/integration-options#using-dynamic-payment-methods) for more details. + // + // Read more about the supported payment methods and their requirements in our [payment + // method details guide](https://docs.stripe.com/docs/payments/checkout/payment-methods). + // + // If multiple payment methods are passed, Checkout will dynamically reorder them to + // prioritize the most relevant payment methods based on the customer's location and + // other characteristics. + PaymentMethodTypes []*string `form:"payment_method_types"` + // This property is used to set up permissions for various actions (e.g., update) on the CheckoutSession object. Can only be set when creating `embedded` or `custom` sessions. + // + // For specific permissions, please refer to their dedicated subsections, such as `permissions.update_shipping_details`. + Permissions *CheckoutSessionPermissionsParams `form:"permissions"` + // Controls phone number collection settings for the session. + // + // We recommend that you review your privacy policy and check with your legal contacts + // before using this feature. Learn more about [collecting phone numbers with Checkout](https://stripe.com/docs/payments/checkout/phone-numbers). + PhoneNumberCollection *CheckoutSessionPhoneNumberCollectionParams `form:"phone_number_collection"` + // This parameter applies to `ui_mode: embedded`. Learn more about the [redirect behavior](https://stripe.com/docs/payments/checkout/custom-success-page?payment-ui=embedded-form) of embedded sessions. Defaults to `always`. + RedirectOnCompletion *string `form:"redirect_on_completion"` + // The URL to redirect your customer back to after they authenticate or cancel their payment on the + // payment method's app or site. This parameter is required if `ui_mode` is `embedded` or `custom` + // and redirect-based payment methods are enabled on the session. + ReturnURL *string `form:"return_url"` + // Controls saved payment method settings for the session. Only available in `payment` and `subscription` mode. + SavedPaymentMethodOptions *CheckoutSessionSavedPaymentMethodOptionsParams `form:"saved_payment_method_options"` + // A subset of parameters to be passed to SetupIntent creation for Checkout Sessions in `setup` mode. + SetupIntentData *CheckoutSessionSetupIntentDataParams `form:"setup_intent_data"` + // When set, provides configuration for Checkout to collect a shipping address from a customer. + ShippingAddressCollection *CheckoutSessionShippingAddressCollectionParams `form:"shipping_address_collection"` + // The shipping rate options to apply to this Session. Up to a maximum of 5. + ShippingOptions []*CheckoutSessionShippingOptionParams `form:"shipping_options"` + // Describes the type of transaction being performed by Checkout in order + // to customize relevant text on the page, such as the submit button. + // `submit_type` can only be specified on Checkout Sessions in + // `payment` or `subscription` mode. If blank or `auto`, `pay` is used. + SubmitType *string `form:"submit_type"` + // A subset of parameters to be passed to subscription creation for Checkout Sessions in `subscription` mode. + SubscriptionData *CheckoutSessionSubscriptionDataParams `form:"subscription_data"` + // The URL to which Stripe should send customers when payment or setup + // is complete. + // This parameter is not allowed if ui_mode is `embedded` or `custom`. If you'd like to use + // information from the successful Checkout Session on your page, read the + // guide on [customizing your success page](https://stripe.com/docs/payments/checkout/custom-success-page). + SuccessURL *string `form:"success_url"` + // Controls tax ID collection during checkout. + TaxIDCollection *CheckoutSessionTaxIDCollectionParams `form:"tax_id_collection"` + // The UI mode of the Session. Defaults to `hosted`. + UIMode *string `form:"ui_mode"` + // Wallet-specific configuration. + WalletOptions *CheckoutSessionWalletOptionsParams `form:"wallet_options"` +} + +// AddExpand appends a new field to expand. +func (p *CheckoutSessionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The shipping details to apply to this Session. +type CheckoutSessionCollectedInformationShippingDetailsParams struct { + // The address of the customer + Address *AddressParams `form:"address"` + // The name of customer + Name *string `form:"name"` +} + +// Information about the customer collected within the Checkout Session. Can only be set when updating `embedded` or `custom` sessions. +type CheckoutSessionCollectedInformationParams struct { + // The shipping details to apply to this Session. + ShippingDetails *CheckoutSessionCollectedInformationShippingDetailsParams `form:"shipping_details"` +} + +// When retrieving a Checkout Session, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. +type CheckoutSessionListLineItemsParams struct { + ListParams `form:"*"` + Session *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CheckoutSessionListLineItemsParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A Checkout Session can be expired when it is in one of these statuses: open +// +// After it expires, a customer can't complete a Checkout Session and customers loading the Checkout Session see a message saying the Checkout Session is expired. +type CheckoutSessionExpireParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CheckoutSessionExpireParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Settings for price localization with [Adaptive Pricing](https://docs.stripe.com/payments/checkout/adaptive-pricing). +type CheckoutSessionCreateAdaptivePricingParams struct { + // Set to `true` to enable [Adaptive Pricing](https://docs.stripe.com/payments/checkout/adaptive-pricing). Defaults to your [dashboard setting](https://dashboard.stripe.com/settings/adaptive-pricing). + Enabled *bool `form:"enabled"` +} + +// Configure a Checkout Session that can be used to recover an expired session. +type CheckoutSessionCreateAfterExpirationRecoveryParams struct { + // Enables user redeemable promotion codes on the recovered Checkout Sessions. Defaults to `false` + AllowPromotionCodes *bool `form:"allow_promotion_codes"` + // If `true`, a recovery URL will be generated to recover this Checkout Session if it + // expires before a successful transaction is completed. It will be attached to the + // Checkout Session object upon expiration. + Enabled *bool `form:"enabled"` +} + +// Configure actions after a Checkout Session has expired. +type CheckoutSessionCreateAfterExpirationParams struct { + // Configure a Checkout Session that can be used to recover an expired session. + Recovery *CheckoutSessionCreateAfterExpirationRecoveryParams `form:"recovery"` +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type CheckoutSessionCreateAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Settings for automatic tax lookup for this session and resulting payments, invoices, and subscriptions. +type CheckoutSessionCreateAutomaticTaxParams struct { + // Set to `true` to [calculate tax automatically](https://docs.stripe.com/tax) using the customer's location. + // + // Enabling this parameter causes Checkout to collect any billing address information necessary for tax calculation. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *CheckoutSessionCreateAutomaticTaxLiabilityParams `form:"liability"` +} + +// Determines the display of payment method reuse agreement text in the UI. If set to `hidden`, it will hide legal text related to the reuse of a payment method. +type CheckoutSessionCreateConsentCollectionPaymentMethodReuseAgreementParams struct { + // Determines the position and visibility of the payment method reuse agreement in the UI. When set to `auto`, Stripe's + // defaults will be used. When set to `hidden`, the payment method reuse agreement text will always be hidden in the UI. + Position *string `form:"position"` +} + +// Configure fields for the Checkout Session to gather active consent from customers. +type CheckoutSessionCreateConsentCollectionParams struct { + // Determines the display of payment method reuse agreement text in the UI. If set to `hidden`, it will hide legal text related to the reuse of a payment method. + PaymentMethodReuseAgreement *CheckoutSessionCreateConsentCollectionPaymentMethodReuseAgreementParams `form:"payment_method_reuse_agreement"` + // If set to `auto`, enables the collection of customer consent for promotional communications. The Checkout + // Session will determine whether to display an option to opt into promotional communication + // from the merchant depending on the customer's locale. Only available to US merchants. + Promotions *string `form:"promotions"` + // If set to `required`, it requires customers to check a terms of service checkbox before being able to pay. + // There must be a valid terms of service URL set in your [Dashboard settings](https://dashboard.stripe.com/settings/public). + TermsOfService *string `form:"terms_of_service"` +} + +// The options available for the customer to select. Up to 200 options allowed. +type CheckoutSessionCreateCustomFieldDropdownOptionParams struct { + // The label for the option, displayed to the customer. Up to 100 characters. + Label *string `form:"label"` + // The value for this option, not displayed to the customer, used by your integration to reconcile the option selected by the customer. Must be unique to this option, alphanumeric, and up to 100 characters. + Value *string `form:"value"` +} + +// Configuration for `type=dropdown` fields. +type CheckoutSessionCreateCustomFieldDropdownParams struct { + // The value that will pre-fill the field on the payment page.Must match a `value` in the `options` array. + DefaultValue *string `form:"default_value"` + // The options available for the customer to select. Up to 200 options allowed. + Options []*CheckoutSessionCreateCustomFieldDropdownOptionParams `form:"options"` +} + +// The label for the field, displayed to the customer. +type CheckoutSessionCreateCustomFieldLabelParams struct { + // Custom text for the label, displayed to the customer. Up to 50 characters. + Custom *string `form:"custom"` + // The type of the label. + Type *string `form:"type"` +} + +// Configuration for `type=numeric` fields. +type CheckoutSessionCreateCustomFieldNumericParams struct { + // The value that will pre-fill the field on the payment page. + DefaultValue *string `form:"default_value"` + // The maximum character length constraint for the customer's input. + MaximumLength *int64 `form:"maximum_length"` + // The minimum character length requirement for the customer's input. + MinimumLength *int64 `form:"minimum_length"` +} + +// Configuration for `type=text` fields. +type CheckoutSessionCreateCustomFieldTextParams struct { + // The value that will pre-fill the field on the payment page. + DefaultValue *string `form:"default_value"` + // The maximum character length constraint for the customer's input. + MaximumLength *int64 `form:"maximum_length"` + // The minimum character length requirement for the customer's input. + MinimumLength *int64 `form:"minimum_length"` +} + +// Collect additional information from your customer using custom fields. Up to 3 fields are supported. +type CheckoutSessionCreateCustomFieldParams struct { + // Configuration for `type=dropdown` fields. + Dropdown *CheckoutSessionCreateCustomFieldDropdownParams `form:"dropdown"` + // String of your choice that your integration can use to reconcile this field. Must be unique to this field, alphanumeric, and up to 200 characters. + Key *string `form:"key"` + // The label for the field, displayed to the customer. + Label *CheckoutSessionCreateCustomFieldLabelParams `form:"label"` + // Configuration for `type=numeric` fields. + Numeric *CheckoutSessionCreateCustomFieldNumericParams `form:"numeric"` + // Whether the customer is required to complete the field before completing the Checkout Session. Defaults to `false`. + Optional *bool `form:"optional"` + // Configuration for `type=text` fields. + Text *CheckoutSessionCreateCustomFieldTextParams `form:"text"` + // The type of the field. + Type *string `form:"type"` +} + +// Custom text that should be displayed after the payment confirmation button. +type CheckoutSessionCreateCustomTextAfterSubmitParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed alongside shipping address collection. +type CheckoutSessionCreateCustomTextShippingAddressParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed alongside the payment confirmation button. +type CheckoutSessionCreateCustomTextSubmitParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed in place of the default terms of service agreement text. +type CheckoutSessionCreateCustomTextTermsOfServiceAcceptanceParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Display additional text for your customers using custom text. +type CheckoutSessionCreateCustomTextParams struct { + // Custom text that should be displayed after the payment confirmation button. + AfterSubmit *CheckoutSessionCreateCustomTextAfterSubmitParams `form:"after_submit"` + // Custom text that should be displayed alongside shipping address collection. + ShippingAddress *CheckoutSessionCreateCustomTextShippingAddressParams `form:"shipping_address"` + // Custom text that should be displayed alongside the payment confirmation button. + Submit *CheckoutSessionCreateCustomTextSubmitParams `form:"submit"` + // Custom text that should be displayed in place of the default terms of service agreement text. + TermsOfServiceAcceptance *CheckoutSessionCreateCustomTextTermsOfServiceAcceptanceParams `form:"terms_of_service_acceptance"` +} + +// Controls what fields on Customer can be updated by the Checkout Session. Can only be provided when `customer` is provided. +type CheckoutSessionCreateCustomerUpdateParams struct { + // Describes whether Checkout saves the billing address onto `customer.address`. + // To always collect a full billing address, use `billing_address_collection`. Defaults to `never`. + Address *string `form:"address"` + // Describes whether Checkout saves the name onto `customer.name`. Defaults to `never`. + Name *string `form:"name"` + // Describes whether Checkout saves shipping information onto `customer.shipping`. + // To collect shipping information, use `shipping_address_collection`. Defaults to `never`. + Shipping *string `form:"shipping"` +} + +// The coupon or promotion code to apply to this Session. Currently, only up to one may be specified. +type CheckoutSessionCreateDiscountParams struct { + // The ID of the coupon to apply to this Session. + Coupon *string `form:"coupon"` + // The ID of a promotion code to apply to this Session. + PromotionCode *string `form:"promotion_code"` +} + +// Default custom fields to be displayed on invoices for this customer. +type CheckoutSessionCreateInvoiceCreationInvoiceDataCustomFieldParams struct { + // The name of the custom field. This may be up to 40 characters. + Name *string `form:"name"` + // The value of the custom field. This may be up to 140 characters. + Value *string `form:"value"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type CheckoutSessionCreateInvoiceCreationInvoiceDataIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Default options for invoice PDF rendering for this customer. +type CheckoutSessionCreateInvoiceCreationInvoiceDataRenderingOptionsParams struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + AmountTaxDisplay *string `form:"amount_tax_display"` +} + +// Parameters passed when creating invoices for payment-mode Checkout Sessions. +type CheckoutSessionCreateInvoiceCreationInvoiceDataParams struct { + // The account tax IDs associated with the invoice. + AccountTaxIDs []*string `form:"account_tax_ids"` + // Default custom fields to be displayed on invoices for this customer. + CustomFields []*CheckoutSessionCreateInvoiceCreationInvoiceDataCustomFieldParams `form:"custom_fields"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Default footer to be displayed on invoices for this customer. + Footer *string `form:"footer"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *CheckoutSessionCreateInvoiceCreationInvoiceDataIssuerParams `form:"issuer"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Default options for invoice PDF rendering for this customer. + RenderingOptions *CheckoutSessionCreateInvoiceCreationInvoiceDataRenderingOptionsParams `form:"rendering_options"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionCreateInvoiceCreationInvoiceDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Generate a post-purchase Invoice for one-time payments. +type CheckoutSessionCreateInvoiceCreationParams struct { + // Set to `true` to enable invoice creation. + Enabled *bool `form:"enabled"` + // Parameters passed when creating invoices for payment-mode Checkout Sessions. + InvoiceData *CheckoutSessionCreateInvoiceCreationInvoiceDataParams `form:"invoice_data"` +} + +// When set, provides configuration for this item's quantity to be adjusted by the customer during Checkout. +type CheckoutSessionCreateLineItemAdjustableQuantityParams struct { + // Set to true if the quantity can be adjusted to any non-negative integer. + Enabled *bool `form:"enabled"` + // The maximum quantity the customer can purchase for the Checkout Session. By default this value is 99. You can specify a value up to 999999. + Maximum *int64 `form:"maximum"` + // The minimum quantity the customer must purchase for the Checkout Session. By default this value is 0. + Minimum *int64 `form:"minimum"` +} + +// Data used to generate a new [Product](https://docs.stripe.com/api/products) object inline. One of `product` or `product_data` is required. +type CheckoutSessionCreateLineItemPriceDataProductDataParams struct { + // The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + Description *string `form:"description"` + // A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + Images []*string `form:"images"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The product's name, meant to be displayable to the customer. + Name *string `form:"name"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionCreateLineItemPriceDataProductDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The recurring components of a price such as `interval` and `interval_count`. +type CheckoutSessionCreateLineItemPriceDataRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. +type CheckoutSessionCreateLineItemPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. One of `product` or `product_data` is required. + Product *string `form:"product"` + // Data used to generate a new [Product](https://docs.stripe.com/api/products) object inline. One of `product` or `product_data` is required. + ProductData *CheckoutSessionCreateLineItemPriceDataProductDataParams `form:"product_data"` + // The recurring components of a price such as `interval` and `interval_count`. + Recurring *CheckoutSessionCreateLineItemPriceDataRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A non-negative integer in cents (or local equivalent) representing how much to charge. One of `unit_amount` or `unit_amount_decimal` is required. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// A list of items the customer is purchasing. Use this parameter to pass one-time or recurring [Prices](https://stripe.com/docs/api/prices). The parameter is required for `payment` and `subscription` mode. +// +// For `payment` mode, there is a maximum of 100 line items, however it is recommended to consolidate line items if there are more than a few dozen. +// +// For `subscription` mode, there is a maximum of 20 line items with recurring Prices and 20 line items with one-time Prices. Line items with one-time Prices will be on the initial invoice only. +type CheckoutSessionCreateLineItemParams struct { + // When set, provides configuration for this item's quantity to be adjusted by the customer during Checkout. + AdjustableQuantity *CheckoutSessionCreateLineItemAdjustableQuantityParams `form:"adjustable_quantity"` + // The [tax rates](https://stripe.com/docs/api/tax_rates) that will be applied to this line item depending on the customer's billing/shipping address. We currently support the following countries: US, GB, AU, and all countries in the EU. + DynamicTaxRates []*string `form:"dynamic_tax_rates"` + // The ID of the [Price](https://stripe.com/docs/api/prices) or [Plan](https://stripe.com/docs/api/plans) object. One of `price` or `price_data` is required. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *CheckoutSessionCreateLineItemPriceDataParams `form:"price_data"` + // The quantity of the line item being purchased. Quantity should not be defined when `recurring.usage_type=metered`. + Quantity *int64 `form:"quantity"` + // The [tax rates](https://stripe.com/docs/api/tax_rates) which apply to this line item. + TaxRates []*string `form:"tax_rates"` +} + +// When set, provides configuration for the customer to adjust the quantity of the line item created when a customer chooses to add this optional item to their order. +type CheckoutSessionCreateOptionalItemAdjustableQuantityParams struct { + // Set to true if the quantity can be adjusted to any non-negative integer. + Enabled *bool `form:"enabled"` + // The maximum quantity of this item the customer can purchase. By default this value is 99. You can specify a value up to 999999. + Maximum *int64 `form:"maximum"` + // The minimum quantity of this item the customer must purchase, if they choose to purchase it. Because this item is optional, the customer will always be able to remove it from their order, even if the `minimum` configured here is greater than 0. By default this value is 0. + Minimum *int64 `form:"minimum"` +} + +// A list of optional items the customer can add to their order at checkout. Use this parameter to pass one-time or recurring [Prices](https://stripe.com/docs/api/prices). +// +// There is a maximum of 10 optional items allowed on a Checkout Session, and the existing limits on the number of line items allowed on a Checkout Session apply to the combined number of line items and optional items. +// +// For `payment` mode, there is a maximum of 100 combined line items and optional items, however it is recommended to consolidate items if there are more than a few dozen. +// +// For `subscription` mode, there is a maximum of 20 line items and optional items with recurring Prices and 20 line items and optional items with one-time Prices. +type CheckoutSessionCreateOptionalItemParams struct { + // When set, provides configuration for the customer to adjust the quantity of the line item created when a customer chooses to add this optional item to their order. + AdjustableQuantity *CheckoutSessionCreateOptionalItemAdjustableQuantityParams `form:"adjustable_quantity"` + // The ID of the [Price](https://stripe.com/docs/api/prices) or [Plan](https://stripe.com/docs/api/plans) object. + Price *string `form:"price"` + // The initial quantity of the line item created when a customer chooses to add this optional item to their order. + Quantity *int64 `form:"quantity"` +} + +// The parameters used to automatically create a Transfer when the payment succeeds. +// For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). +type CheckoutSessionCreatePaymentIntentDataTransferDataParams struct { + // The amount that will be transferred automatically when a charge succeeds. + Amount *int64 `form:"amount"` + // If specified, successful charges will be attributed to the destination + // account for tax reporting, and the funds from charges will be transferred + // to the destination account. The ID of the resulting transfer will be + // returned on the successful charge's `transfer` field. + Destination *string `form:"destination"` +} + +// A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in `payment` mode. +type CheckoutSessionCreatePaymentIntentDataParams struct { + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. The amount of the application fee collected will be capped at the total amount captured. For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The Stripe account ID for which these funds are intended. For details, + // see the PaymentIntents [use case for connected + // accounts](https://docs.stripe.com/docs/payments/connected-accounts). + OnBehalfOf *string `form:"on_behalf_of"` + // Email address that the receipt for the resulting payment will be sent to. If `receipt_email` is specified for a payment in live mode, a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). + ReceiptEmail *string `form:"receipt_email"` + // Indicates that you intend to [make future payments](https://stripe.com/docs/payments/payment-intents#future-usage) with the payment + // method collected by this Checkout Session. + // + // When setting this to `on_session`, Checkout will show a notice to the + // customer that their payment details will be saved. + // + // When setting this to `off_session`, Checkout will show a notice to the + // customer that their payment details will be saved and used for future + // payments. + // + // If a Customer has been provided or Checkout creates a new Customer, + // Checkout will attach the payment method to the Customer. + // + // If Checkout does not create a Customer, the payment method is not attached + // to a Customer. To reuse the payment method, you can retrieve it from the + // Checkout Session's PaymentIntent. + // + // When processing card payments, Checkout also uses `setup_future_usage` + // to dynamically optimize your payment flow and comply with regional + // legislation and network rules, such as SCA. + SetupFutureUsage *string `form:"setup_future_usage"` + // Shipping information for this payment. + Shipping *ShippingDetailsParams `form:"shipping"` + // Text that appears on the customer's statement as the statement descriptor for a non-card charge. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + // + // Setting this value for a card charge returns an error. For card charges, set the [statement_descriptor_suffix](https://docs.stripe.com/get-started/account/statement-descriptors#dynamic) instead. + StatementDescriptor *string `form:"statement_descriptor"` + // Provides information about a card charge. Concatenated to the account's [statement descriptor prefix](https://docs.stripe.com/get-started/account/statement-descriptors#static) to form the complete statement descriptor that appears on the customer's statement. + StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"` + // The parameters used to automatically create a Transfer when the payment succeeds. + // For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + TransferData *CheckoutSessionCreatePaymentIntentDataTransferDataParams `form:"transfer_data"` + // A string that identifies the resulting payment as part of a group. See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/connect/separate-charges-and-transfers) for details. + TransferGroup *string `form:"transfer_group"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionCreatePaymentIntentDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// This parameter allows you to set some attributes on the payment method created during a Checkout session. +type CheckoutSessionCreatePaymentMethodDataParams struct { + // Allow redisplay will be set on the payment method on confirmation and indicates whether this payment method can be shown again to the customer in a checkout flow. Only set this field if you wish to override the allow_redisplay value determined by Checkout. + AllowRedisplay *string `form:"allow_redisplay"` +} + +// Additional fields for Mandate creation +type CheckoutSessionCreatePaymentMethodOptionsACSSDebitMandateOptionsParams struct { + // A URL for custom mandate text to render during confirmation step. + // The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + // or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + CustomMandateURL *string `form:"custom_mandate_url"` + // List of Stripe products where this mandate can be selected automatically. Only usable in `setup` mode. + DefaultFor []*string `form:"default_for"` + // Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + IntervalDescription *string `form:"interval_description"` + // Payment schedule for the mandate. + PaymentSchedule *string `form:"payment_schedule"` + // Transaction type of the mandate. + TransactionType *string `form:"transaction_type"` +} + +// contains details about the ACSS Debit payment method options. +type CheckoutSessionCreatePaymentMethodOptionsACSSDebitParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). This is only accepted for Checkout Sessions in `setup` mode. + Currency *string `form:"currency"` + // Additional fields for Mandate creation + MandateOptions *CheckoutSessionCreatePaymentMethodOptionsACSSDebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// contains details about the Affirm payment method options. +type CheckoutSessionCreatePaymentMethodOptionsAffirmParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Afterpay Clearpay payment method options. +type CheckoutSessionCreatePaymentMethodOptionsAfterpayClearpayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Alipay payment method options. +type CheckoutSessionCreatePaymentMethodOptionsAlipayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the AmazonPay payment method options. +type CheckoutSessionCreatePaymentMethodOptionsAmazonPayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the AU Becs Debit payment method options. +type CheckoutSessionCreatePaymentMethodOptionsAUBECSDebitParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// Additional fields for Mandate creation +type CheckoutSessionCreatePaymentMethodOptionsBACSDebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'DDIC' or 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// contains details about the Bacs Debit payment method options. +type CheckoutSessionCreatePaymentMethodOptionsBACSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *CheckoutSessionCreatePaymentMethodOptionsBACSDebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// contains details about the Bancontact payment method options. +type CheckoutSessionCreatePaymentMethodOptionsBancontactParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Boleto payment method options. +type CheckoutSessionCreatePaymentMethodOptionsBoletoParams struct { + // The number of calendar days before a Boleto voucher expires. For example, if you create a Boleto voucher on Monday and you set expires_after_days to 2, the Boleto invoice will expire on Wednesday at 23:59 America/Sao_Paulo time. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Installment options for card payments +type CheckoutSessionCreatePaymentMethodOptionsCardInstallmentsParams struct { + // Setting to true enables installments for this Checkout Session. + // Setting to false will prevent any installment plan from applying to a payment. + Enabled *bool `form:"enabled"` +} + +// Restrictions to apply to the card payment method. For example, you can block specific card brands. +type CheckoutSessionCreatePaymentMethodOptionsCardRestrictionsParams struct { + // Specify the card brands to block in the Checkout Session. If a customer enters or selects a card belonging to a blocked brand, they can't complete the Session. + BrandsBlocked []*string `form:"brands_blocked"` +} + +// contains details about the Card payment method options. +type CheckoutSessionCreatePaymentMethodOptionsCardParams struct { + // Installment options for card payments + Installments *CheckoutSessionCreatePaymentMethodOptionsCardInstallmentsParams `form:"installments"` + // Request ability to [capture beyond the standard authorization validity window](https://docs.stripe.com/payments/extended-authorization) for this CheckoutSession. + RequestExtendedAuthorization *string `form:"request_extended_authorization"` + // Request ability to [increment the authorization](https://docs.stripe.com/payments/incremental-authorization) for this CheckoutSession. + RequestIncrementalAuthorization *string `form:"request_incremental_authorization"` + // Request ability to make [multiple captures](https://docs.stripe.com/payments/multicapture) for this CheckoutSession. + RequestMulticapture *string `form:"request_multicapture"` + // Request ability to [overcapture](https://docs.stripe.com/payments/overcapture) for this CheckoutSession. + RequestOvercapture *string `form:"request_overcapture"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure *string `form:"request_three_d_secure"` + // Restrictions to apply to the card payment method. For example, you can block specific card brands. + Restrictions *CheckoutSessionCreatePaymentMethodOptionsCardRestrictionsParams `form:"restrictions"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Provides information about a card payment that customers see on their statements. Concatenated with the Kana prefix (shortened Kana descriptor) or Kana statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 22 characters. + StatementDescriptorSuffixKana *string `form:"statement_descriptor_suffix_kana"` + // Provides information about a card payment that customers see on their statements. Concatenated with the Kanji prefix (shortened Kanji descriptor) or Kanji statement descriptor that's set on the account to form the complete statement descriptor. Maximum 17 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 17 characters. + StatementDescriptorSuffixKanji *string `form:"statement_descriptor_suffix_kanji"` +} + +// contains details about the Cashapp Pay payment method options. +type CheckoutSessionCreatePaymentMethodOptionsCashAppParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Configuration for eu_bank_transfer funding type. +type CheckoutSessionCreatePaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country *string `form:"country"` +} + +// Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. +type CheckoutSessionCreatePaymentMethodOptionsCustomerBalanceBankTransferParams struct { + // Configuration for eu_bank_transfer funding type. + EUBankTransfer *CheckoutSessionCreatePaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams `form:"eu_bank_transfer"` + // List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. + // + // Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. + RequestedAddressTypes []*string `form:"requested_address_types"` + // The list of bank transfer types that this PaymentIntent is allowed to use for funding. + Type *string `form:"type"` +} + +// contains details about the Customer Balance payment method options. +type CheckoutSessionCreatePaymentMethodOptionsCustomerBalanceParams struct { + // Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + BankTransfer *CheckoutSessionCreatePaymentMethodOptionsCustomerBalanceBankTransferParams `form:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType *string `form:"funding_type"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the EPS payment method options. +type CheckoutSessionCreatePaymentMethodOptionsEPSParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the FPX payment method options. +type CheckoutSessionCreatePaymentMethodOptionsFPXParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Giropay payment method options. +type CheckoutSessionCreatePaymentMethodOptionsGiropayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Grabpay payment method options. +type CheckoutSessionCreatePaymentMethodOptionsGrabpayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Ideal payment method options. +type CheckoutSessionCreatePaymentMethodOptionsIDEALParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Kakao Pay payment method options. +type CheckoutSessionCreatePaymentMethodOptionsKakaoPayParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Describes the upcoming charge for this subscription. +type CheckoutSessionCreatePaymentMethodOptionsKlarnaSubscriptionNextBillingParams struct { + // The amount of the next charge for the subscription. + Amount *int64 `form:"amount"` + // The date of the next charge for the subscription in YYYY-MM-DD format. + Date *string `form:"date"` +} + +// Subscription details if the Checkout Session sets up a future subscription. +type CheckoutSessionCreatePaymentMethodOptionsKlarnaSubscriptionParams struct { + // Unit of time between subscription charges. + Interval *string `form:"interval"` + // The number of intervals (specified in the `interval` attribute) between subscription charges. For example, `interval=month` and `interval_count=3` charges every 3 months. + IntervalCount *int64 `form:"interval_count"` + // Name for subscription. + Name *string `form:"name"` + // Describes the upcoming charge for this subscription. + NextBilling *CheckoutSessionCreatePaymentMethodOptionsKlarnaSubscriptionNextBillingParams `form:"next_billing"` + // A non-customer-facing reference to correlate subscription charges in the Klarna app. Use a value that persists across subscription charges. + Reference *string `form:"reference"` +} + +// contains details about the Klarna payment method options. +type CheckoutSessionCreatePaymentMethodOptionsKlarnaParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Subscription details if the Checkout Session sets up a future subscription. + Subscriptions []*CheckoutSessionCreatePaymentMethodOptionsKlarnaSubscriptionParams `form:"subscriptions"` +} + +// contains details about the Konbini payment method options. +type CheckoutSessionCreatePaymentMethodOptionsKonbiniParams struct { + // The number of calendar days (between 1 and 60) after which Konbini payment instructions will expire. For example, if a PaymentIntent is confirmed with Konbini and `expires_after_days` set to 2 on Monday JST, the instructions will expire on Wednesday 23:59:59 JST. Defaults to 3 days. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Korean card payment method options. +type CheckoutSessionCreatePaymentMethodOptionsKrCardParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Link payment method options. +type CheckoutSessionCreatePaymentMethodOptionsLinkParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Mobilepay payment method options. +type CheckoutSessionCreatePaymentMethodOptionsMobilepayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Multibanco payment method options. +type CheckoutSessionCreatePaymentMethodOptionsMultibancoParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Naver Pay payment method options. +type CheckoutSessionCreatePaymentMethodOptionsNaverPayParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the OXXO payment method options. +type CheckoutSessionCreatePaymentMethodOptionsOXXOParams struct { + // The number of calendar days before an OXXO voucher expires. For example, if you create an OXXO voucher on Monday and you set expires_after_days to 2, the OXXO invoice will expire on Wednesday at 23:59 America/Mexico_City time. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the P24 payment method options. +type CheckoutSessionCreatePaymentMethodOptionsP24Params struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Confirm that the payer has accepted the P24 terms and conditions. + TOSShownAndAccepted *bool `form:"tos_shown_and_accepted"` +} + +// contains details about the Pay By Bank payment method options. +type CheckoutSessionCreatePaymentMethodOptionsPayByBankParams struct{} + +// contains details about the PAYCO payment method options. +type CheckoutSessionCreatePaymentMethodOptionsPaycoParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` +} + +// contains details about the PayNow payment method options. +type CheckoutSessionCreatePaymentMethodOptionsPayNowParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the PayPal payment method options. +type CheckoutSessionCreatePaymentMethodOptionsPaypalParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // [Preferred locale](https://stripe.com/docs/payments/paypal/supported-locales) of the PayPal checkout page that the customer is redirected to. + PreferredLocale *string `form:"preferred_locale"` + // A reference of the PayPal transaction visible to customer which is mapped to PayPal's invoice ID. This must be a globally unique ID if you have configured in your PayPal settings to block multiple payments per invoice ID. + Reference *string `form:"reference"` + // The risk correlation ID for an on-session payment using a saved PayPal payment method. + RiskCorrelationID *string `form:"risk_correlation_id"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Pix payment method options. +type CheckoutSessionCreatePaymentMethodOptionsPixParams struct { + // The number of seconds (between 10 and 1209600) after which Pix payment will expire. Defaults to 86400 seconds. + ExpiresAfterSeconds *int64 `form:"expires_after_seconds"` +} + +// contains details about the RevolutPay payment method options. +type CheckoutSessionCreatePaymentMethodOptionsRevolutPayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Samsung Pay payment method options. +type CheckoutSessionCreatePaymentMethodOptionsSamsungPayParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` +} + +// Additional fields for Mandate creation +type CheckoutSessionCreatePaymentMethodOptionsSEPADebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// contains details about the Sepa Debit payment method options. +type CheckoutSessionCreatePaymentMethodOptionsSEPADebitParams struct { + // Additional fields for Mandate creation + MandateOptions *CheckoutSessionCreatePaymentMethodOptionsSEPADebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// contains details about the Sofort payment method options. +type CheckoutSessionCreatePaymentMethodOptionsSofortParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// contains details about the Swish payment method options. +type CheckoutSessionCreatePaymentMethodOptionsSwishParams struct { + // The order reference that will be displayed to customers in the Swish application. Defaults to the `id` of the Payment Intent. + Reference *string `form:"reference"` +} + +// Additional fields for Financial Connections Session creation +type CheckoutSessionCreatePaymentMethodOptionsUSBankAccountFinancialConnectionsParams struct { + // The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` +} + +// contains details about the Us Bank Account payment method options. +type CheckoutSessionCreatePaymentMethodOptionsUSBankAccountParams struct { + // Additional fields for Financial Connections Session creation + FinancialConnections *CheckoutSessionCreatePaymentMethodOptionsUSBankAccountFinancialConnectionsParams `form:"financial_connections"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// contains details about the WeChat Pay payment method options. +type CheckoutSessionCreatePaymentMethodOptionsWeChatPayParams struct { + // The app ID registered with WeChat Pay. Only required when client is ios or android. + AppID *string `form:"app_id"` + // The client type that the end customer will pay from + Client *string `form:"client"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Payment-method-specific configuration. +type CheckoutSessionCreatePaymentMethodOptionsParams struct { + // contains details about the ACSS Debit payment method options. + ACSSDebit *CheckoutSessionCreatePaymentMethodOptionsACSSDebitParams `form:"acss_debit"` + // contains details about the Affirm payment method options. + Affirm *CheckoutSessionCreatePaymentMethodOptionsAffirmParams `form:"affirm"` + // contains details about the Afterpay Clearpay payment method options. + AfterpayClearpay *CheckoutSessionCreatePaymentMethodOptionsAfterpayClearpayParams `form:"afterpay_clearpay"` + // contains details about the Alipay payment method options. + Alipay *CheckoutSessionCreatePaymentMethodOptionsAlipayParams `form:"alipay"` + // contains details about the AmazonPay payment method options. + AmazonPay *CheckoutSessionCreatePaymentMethodOptionsAmazonPayParams `form:"amazon_pay"` + // contains details about the AU Becs Debit payment method options. + AUBECSDebit *CheckoutSessionCreatePaymentMethodOptionsAUBECSDebitParams `form:"au_becs_debit"` + // contains details about the Bacs Debit payment method options. + BACSDebit *CheckoutSessionCreatePaymentMethodOptionsBACSDebitParams `form:"bacs_debit"` + // contains details about the Bancontact payment method options. + Bancontact *CheckoutSessionCreatePaymentMethodOptionsBancontactParams `form:"bancontact"` + // contains details about the Boleto payment method options. + Boleto *CheckoutSessionCreatePaymentMethodOptionsBoletoParams `form:"boleto"` + // contains details about the Card payment method options. + Card *CheckoutSessionCreatePaymentMethodOptionsCardParams `form:"card"` + // contains details about the Cashapp Pay payment method options. + CashApp *CheckoutSessionCreatePaymentMethodOptionsCashAppParams `form:"cashapp"` + // contains details about the Customer Balance payment method options. + CustomerBalance *CheckoutSessionCreatePaymentMethodOptionsCustomerBalanceParams `form:"customer_balance"` + // contains details about the EPS payment method options. + EPS *CheckoutSessionCreatePaymentMethodOptionsEPSParams `form:"eps"` + // contains details about the FPX payment method options. + FPX *CheckoutSessionCreatePaymentMethodOptionsFPXParams `form:"fpx"` + // contains details about the Giropay payment method options. + Giropay *CheckoutSessionCreatePaymentMethodOptionsGiropayParams `form:"giropay"` + // contains details about the Grabpay payment method options. + Grabpay *CheckoutSessionCreatePaymentMethodOptionsGrabpayParams `form:"grabpay"` + // contains details about the Ideal payment method options. + IDEAL *CheckoutSessionCreatePaymentMethodOptionsIDEALParams `form:"ideal"` + // contains details about the Kakao Pay payment method options. + KakaoPay *CheckoutSessionCreatePaymentMethodOptionsKakaoPayParams `form:"kakao_pay"` + // contains details about the Klarna payment method options. + Klarna *CheckoutSessionCreatePaymentMethodOptionsKlarnaParams `form:"klarna"` + // contains details about the Konbini payment method options. + Konbini *CheckoutSessionCreatePaymentMethodOptionsKonbiniParams `form:"konbini"` + // contains details about the Korean card payment method options. + KrCard *CheckoutSessionCreatePaymentMethodOptionsKrCardParams `form:"kr_card"` + // contains details about the Link payment method options. + Link *CheckoutSessionCreatePaymentMethodOptionsLinkParams `form:"link"` + // contains details about the Mobilepay payment method options. + Mobilepay *CheckoutSessionCreatePaymentMethodOptionsMobilepayParams `form:"mobilepay"` + // contains details about the Multibanco payment method options. + Multibanco *CheckoutSessionCreatePaymentMethodOptionsMultibancoParams `form:"multibanco"` + // contains details about the Naver Pay payment method options. + NaverPay *CheckoutSessionCreatePaymentMethodOptionsNaverPayParams `form:"naver_pay"` + // contains details about the OXXO payment method options. + OXXO *CheckoutSessionCreatePaymentMethodOptionsOXXOParams `form:"oxxo"` + // contains details about the P24 payment method options. + P24 *CheckoutSessionCreatePaymentMethodOptionsP24Params `form:"p24"` + // contains details about the Pay By Bank payment method options. + PayByBank *CheckoutSessionCreatePaymentMethodOptionsPayByBankParams `form:"pay_by_bank"` + // contains details about the PAYCO payment method options. + Payco *CheckoutSessionCreatePaymentMethodOptionsPaycoParams `form:"payco"` + // contains details about the PayNow payment method options. + PayNow *CheckoutSessionCreatePaymentMethodOptionsPayNowParams `form:"paynow"` + // contains details about the PayPal payment method options. + Paypal *CheckoutSessionCreatePaymentMethodOptionsPaypalParams `form:"paypal"` + // contains details about the Pix payment method options. + Pix *CheckoutSessionCreatePaymentMethodOptionsPixParams `form:"pix"` + // contains details about the RevolutPay payment method options. + RevolutPay *CheckoutSessionCreatePaymentMethodOptionsRevolutPayParams `form:"revolut_pay"` + // contains details about the Samsung Pay payment method options. + SamsungPay *CheckoutSessionCreatePaymentMethodOptionsSamsungPayParams `form:"samsung_pay"` + // contains details about the Sepa Debit payment method options. + SEPADebit *CheckoutSessionCreatePaymentMethodOptionsSEPADebitParams `form:"sepa_debit"` + // contains details about the Sofort payment method options. + Sofort *CheckoutSessionCreatePaymentMethodOptionsSofortParams `form:"sofort"` + // contains details about the Swish payment method options. + Swish *CheckoutSessionCreatePaymentMethodOptionsSwishParams `form:"swish"` + // contains details about the Us Bank Account payment method options. + USBankAccount *CheckoutSessionCreatePaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` + // contains details about the WeChat Pay payment method options. + WeChatPay *CheckoutSessionCreatePaymentMethodOptionsWeChatPayParams `form:"wechat_pay"` +} + +// This property is used to set up permissions for various actions (e.g., update) on the CheckoutSession object. Can only be set when creating `embedded` or `custom` sessions. +// +// For specific permissions, please refer to their dedicated subsections, such as `permissions.update_shipping_details`. +type CheckoutSessionCreatePermissionsParams struct { + // Determines which entity is allowed to update the shipping details. + // + // Default is `client_only`. Stripe Checkout client will automatically update the shipping details. If set to `server_only`, only your server is allowed to update the shipping details. + // + // When set to `server_only`, you must add the onShippingDetailsChange event handler when initializing the Stripe Checkout client and manually update the shipping details from your server using the Stripe API. + UpdateShippingDetails *string `form:"update_shipping_details"` +} + +// Controls phone number collection settings for the session. +// +// We recommend that you review your privacy policy and check with your legal contacts +// before using this feature. Learn more about [collecting phone numbers with Checkout](https://stripe.com/docs/payments/checkout/phone-numbers). +type CheckoutSessionCreatePhoneNumberCollectionParams struct { + // Set to `true` to enable phone number collection. + // + // Can only be set in `payment` and `subscription` mode. + Enabled *bool `form:"enabled"` +} + +// Controls saved payment method settings for the session. Only available in `payment` and `subscription` mode. +type CheckoutSessionCreateSavedPaymentMethodOptionsParams struct { + // Uses the `allow_redisplay` value of each saved payment method to filter the set presented to a returning customer. By default, only saved payment methods with 'allow_redisplay: ‘always' are shown in Checkout. + AllowRedisplayFilters []*string `form:"allow_redisplay_filters"` + // Enable customers to choose if they wish to remove their saved payment methods. Disabled by default. + PaymentMethodRemove *string `form:"payment_method_remove"` + // Enable customers to choose if they wish to save their payment method for future use. Disabled by default. + PaymentMethodSave *string `form:"payment_method_save"` +} + +// A subset of parameters to be passed to SetupIntent creation for Checkout Sessions in `setup` mode. +type CheckoutSessionCreateSetupIntentDataParams struct { + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The Stripe account for which the setup is intended. + OnBehalfOf *string `form:"on_behalf_of"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionCreateSetupIntentDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// When set, provides configuration for Checkout to collect a shipping address from a customer. +type CheckoutSessionCreateShippingAddressCollectionParams struct { + // An array of two-letter ISO country codes representing which countries Checkout should provide as options for + // shipping locations. + AllowedCountries []*string `form:"allowed_countries"` +} + +// The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. +type CheckoutSessionCreateShippingOptionShippingRateDataDeliveryEstimateMaximumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The lower bound of the estimated range. If empty, represents no lower bound. +type CheckoutSessionCreateShippingOptionShippingRateDataDeliveryEstimateMinimumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. +type CheckoutSessionCreateShippingOptionShippingRateDataDeliveryEstimateParams struct { + // The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. + Maximum *CheckoutSessionCreateShippingOptionShippingRateDataDeliveryEstimateMaximumParams `form:"maximum"` + // The lower bound of the estimated range. If empty, represents no lower bound. + Minimum *CheckoutSessionCreateShippingOptionShippingRateDataDeliveryEstimateMinimumParams `form:"minimum"` +} + +// Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type CheckoutSessionCreateShippingOptionShippingRateDataFixedAmountCurrencyOptionsParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` +} + +// Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. +type CheckoutSessionCreateShippingOptionShippingRateDataFixedAmountParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*CheckoutSessionCreateShippingOptionShippingRateDataFixedAmountCurrencyOptionsParams `form:"currency_options"` +} + +// Parameters to be passed to Shipping Rate creation for this shipping option. +type CheckoutSessionCreateShippingOptionShippingRateDataParams struct { + // The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. + DeliveryEstimate *CheckoutSessionCreateShippingOptionShippingRateDataDeliveryEstimateParams `form:"delivery_estimate"` + // The name of the shipping rate, meant to be displayable to the customer. This will appear on CheckoutSessions. + DisplayName *string `form:"display_name"` + // Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. + FixedAmount *CheckoutSessionCreateShippingOptionShippingRateDataFixedAmountParams `form:"fixed_amount"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. The Shipping tax code is `txcd_92010001`. + TaxCode *string `form:"tax_code"` + // The type of calculation to use on the shipping rate. + Type *string `form:"type"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionCreateShippingOptionShippingRateDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The shipping rate options to apply to this Session. Up to a maximum of 5. +type CheckoutSessionCreateShippingOptionParams struct { + // The ID of the Shipping Rate to use for this shipping option. + ShippingRate *string `form:"shipping_rate"` + // Parameters to be passed to Shipping Rate creation for this shipping option. + ShippingRateData *CheckoutSessionCreateShippingOptionShippingRateDataParams `form:"shipping_rate_data"` +} + +// Controls how prorations and invoices for subscriptions are calculated and orchestrated. +type CheckoutSessionCreateSubscriptionDataBillingModeParams struct { + Type *string `form:"type"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type CheckoutSessionCreateSubscriptionDataInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type CheckoutSessionCreateSubscriptionDataInvoiceSettingsParams struct { + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *CheckoutSessionCreateSubscriptionDataInvoiceSettingsIssuerParams `form:"issuer"` +} + +// If specified, the funds from the subscription's invoices will be transferred to the destination and the ID of the resulting transfers will be found on the resulting charges. +type CheckoutSessionCreateSubscriptionDataTransferDataParams struct { + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + AmountPercent *float64 `form:"amount_percent"` + // ID of an existing, connected Stripe account. + Destination *string `form:"destination"` +} + +// Defines how the subscription should behave when the user's free trial ends. +type CheckoutSessionCreateSubscriptionDataTrialSettingsEndBehaviorParams struct { + // Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + MissingPaymentMethod *string `form:"missing_payment_method"` +} + +// Settings related to subscription trials. +type CheckoutSessionCreateSubscriptionDataTrialSettingsParams struct { + // Defines how the subscription should behave when the user's free trial ends. + EndBehavior *CheckoutSessionCreateSubscriptionDataTrialSettingsEndBehaviorParams `form:"end_behavior"` +} + +// A subset of parameters to be passed to subscription creation for Checkout Sessions in `subscription` mode. +type CheckoutSessionCreateSubscriptionDataParams struct { + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. To use an application fee percent, the request must be made on behalf of another account, using the `Stripe-Account` header or an OAuth key. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + ApplicationFeePercent *float64 `form:"application_fee_percent"` + // A future timestamp to anchor the subscription's billing cycle for new subscriptions. + BillingCycleAnchor *int64 `form:"billing_cycle_anchor"` + // Controls how prorations and invoices for subscriptions are calculated and orchestrated. + BillingMode *CheckoutSessionCreateSubscriptionDataBillingModeParams `form:"billing_mode"` + // The tax rates that will apply to any subscription item that does not have + // `tax_rates` set. Invoices created will have their `default_tax_rates` populated + // from the subscription. + DefaultTaxRates []*string `form:"default_tax_rates"` + // The subscription's description, meant to be displayable to the customer. + // Use this field to optionally store an explanation of the subscription + // for rendering in the [customer portal](https://stripe.com/docs/customer-management). + Description *string `form:"description"` + // All invoices will be billed using the specified settings. + InvoiceSettings *CheckoutSessionCreateSubscriptionDataInvoiceSettingsParams `form:"invoice_settings"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The account on behalf of which to charge, for each of the subscription's invoices. + OnBehalfOf *string `form:"on_behalf_of"` + // Determines how to handle prorations resulting from the `billing_cycle_anchor`. If no value is passed, the default is `create_prorations`. + ProrationBehavior *string `form:"proration_behavior"` + // If specified, the funds from the subscription's invoices will be transferred to the destination and the ID of the resulting transfers will be found on the resulting charges. + TransferData *CheckoutSessionCreateSubscriptionDataTransferDataParams `form:"transfer_data"` + // Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. Has to be at least 48 hours in the future. + TrialEnd *int64 `form:"trial_end"` + // Integer representing the number of trial period days before the customer is charged for the first time. Has to be at least 1. + TrialPeriodDays *int64 `form:"trial_period_days"` + // Settings related to subscription trials. + TrialSettings *CheckoutSessionCreateSubscriptionDataTrialSettingsParams `form:"trial_settings"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionCreateSubscriptionDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Controls tax ID collection during checkout. +type CheckoutSessionCreateTaxIDCollectionParams struct { + // Enable tax ID collection during checkout. Defaults to `false`. + Enabled *bool `form:"enabled"` + // Describes whether a tax ID is required during checkout. Defaults to `never`. + Required *string `form:"required"` +} + +// contains details about the Link wallet options. +type CheckoutSessionCreateWalletOptionsLinkParams struct { + // Specifies whether Checkout should display Link as a payment option. By default, Checkout will display all the supported wallets that the Checkout Session was created with. This is the `auto` behavior, and it is the default choice. + Display *string `form:"display"` +} + +// Wallet-specific configuration. +type CheckoutSessionCreateWalletOptionsParams struct { + // contains details about the Link wallet options. + Link *CheckoutSessionCreateWalletOptionsLinkParams `form:"link"` +} + +// Creates a Checkout Session object. +type CheckoutSessionCreateParams struct { + Params `form:"*"` + // Settings for price localization with [Adaptive Pricing](https://docs.stripe.com/payments/checkout/adaptive-pricing). + AdaptivePricing *CheckoutSessionCreateAdaptivePricingParams `form:"adaptive_pricing"` + // Configure actions after a Checkout Session has expired. + AfterExpiration *CheckoutSessionCreateAfterExpirationParams `form:"after_expiration"` + // Enables user redeemable promotion codes. + AllowPromotionCodes *bool `form:"allow_promotion_codes"` + // Settings for automatic tax lookup for this session and resulting payments, invoices, and subscriptions. + AutomaticTax *CheckoutSessionCreateAutomaticTaxParams `form:"automatic_tax"` + // Specify whether Checkout should collect the customer's billing address. Defaults to `auto`. + BillingAddressCollection *string `form:"billing_address_collection"` + // If set, Checkout displays a back button and customers will be directed to this URL if they decide to cancel payment and return to your website. This parameter is not allowed if ui_mode is `embedded` or `custom`. + CancelURL *string `form:"cancel_url"` + // A unique string to reference the Checkout Session. This can be a + // customer ID, a cart ID, or similar, and can be used to reconcile the + // session with your internal systems. + ClientReferenceID *string `form:"client_reference_id"` + // Configure fields for the Checkout Session to gather active consent from customers. + ConsentCollection *CheckoutSessionCreateConsentCollectionParams `form:"consent_collection"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). Required in `setup` mode when `payment_method_types` is not set. + Currency *string `form:"currency"` + // ID of an existing Customer, if one exists. In `payment` mode, the customer's most recently saved card + // payment method will be used to prefill the email, name, card details, and billing address + // on the Checkout page. In `subscription` mode, the customer's [default payment method](https://stripe.com/docs/api/customers/update#update_customer-invoice_settings-default_payment_method) + // will be used if it's a card, otherwise the most recently saved card will be used. A valid billing address, billing name and billing email are required on the payment method for Checkout to prefill the customer's card details. + // + // If the Customer already has a valid [email](https://stripe.com/docs/api/customers/object#customer_object-email) set, the email will be prefilled and not editable in Checkout. + // If the Customer does not have a valid `email`, Checkout will set the email entered during the session on the Customer. + // + // If blank for Checkout Sessions in `subscription` mode or with `customer_creation` set as `always` in `payment` mode, Checkout will create a new Customer object based on information provided during the payment flow. + // + // You can set [`payment_intent_data.setup_future_usage`](https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-payment_intent_data-setup_future_usage) to have Checkout automatically attach the payment method to the Customer you pass in for future reuse. + Customer *string `form:"customer"` + // Configure whether a Checkout Session creates a [Customer](https://stripe.com/docs/api/customers) during Session confirmation. + // + // When a Customer is not created, you can still retrieve email, address, and other customer data entered in Checkout + // with [customer_details](https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-customer_details). + // + // Sessions that don't create Customers instead are grouped by [guest customers](https://stripe.com/docs/payments/checkout/guest-customers) + // in the Dashboard. Promotion codes limited to first time customers will return invalid for these Sessions. + // + // Can only be set in `payment` and `setup` mode. + CustomerCreation *string `form:"customer_creation"` + // If provided, this value will be used when the Customer object is created. + // If not provided, customers will be asked to enter their email address. + // Use this parameter to prefill customer data if you already have an email + // on file. To access information about the customer once a session is + // complete, use the `customer` field. + CustomerEmail *string `form:"customer_email"` + // Controls what fields on Customer can be updated by the Checkout Session. Can only be provided when `customer` is provided. + CustomerUpdate *CheckoutSessionCreateCustomerUpdateParams `form:"customer_update"` + // Collect additional information from your customer using custom fields. Up to 3 fields are supported. + CustomFields []*CheckoutSessionCreateCustomFieldParams `form:"custom_fields"` + // Display additional text for your customers using custom text. + CustomText *CheckoutSessionCreateCustomTextParams `form:"custom_text"` + // The coupon or promotion code to apply to this Session. Currently, only up to one may be specified. + Discounts []*CheckoutSessionCreateDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The Epoch time in seconds at which the Checkout Session will expire. It can be anywhere from 30 minutes to 24 hours after Checkout Session creation. By default, this value is 24 hours from creation. + ExpiresAt *int64 `form:"expires_at"` + // Generate a post-purchase Invoice for one-time payments. + InvoiceCreation *CheckoutSessionCreateInvoiceCreationParams `form:"invoice_creation"` + // A list of items the customer is purchasing. Use this parameter to pass one-time or recurring [Prices](https://stripe.com/docs/api/prices). The parameter is required for `payment` and `subscription` mode. + // + // For `payment` mode, there is a maximum of 100 line items, however it is recommended to consolidate line items if there are more than a few dozen. + // + // For `subscription` mode, there is a maximum of 20 line items with recurring Prices and 20 line items with one-time Prices. Line items with one-time Prices will be on the initial invoice only. + LineItems []*CheckoutSessionCreateLineItemParams `form:"line_items"` + // The IETF language tag of the locale Checkout is displayed in. If blank or `auto`, the browser's locale is used. + Locale *string `form:"locale"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The mode of the Checkout Session. Pass `subscription` if the Checkout Session includes at least one recurring item. + Mode *string `form:"mode"` + // A list of optional items the customer can add to their order at checkout. Use this parameter to pass one-time or recurring [Prices](https://stripe.com/docs/api/prices). + // + // There is a maximum of 10 optional items allowed on a Checkout Session, and the existing limits on the number of line items allowed on a Checkout Session apply to the combined number of line items and optional items. + // + // For `payment` mode, there is a maximum of 100 combined line items and optional items, however it is recommended to consolidate items if there are more than a few dozen. + // + // For `subscription` mode, there is a maximum of 20 line items and optional items with recurring Prices and 20 line items and optional items with one-time Prices. + OptionalItems []*CheckoutSessionCreateOptionalItemParams `form:"optional_items"` + // A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in `payment` mode. + PaymentIntentData *CheckoutSessionCreatePaymentIntentDataParams `form:"payment_intent_data"` + // Specify whether Checkout should collect a payment method. When set to `if_required`, Checkout will not collect a payment method when the total due for the session is 0. + // This may occur if the Checkout Session includes a free trial or a discount. + // + // Can only be set in `subscription` mode. Defaults to `always`. + // + // If you'd like information on how to collect a payment method outside of Checkout, read the guide on configuring [subscriptions with a free trial](https://stripe.com/docs/payments/checkout/free-trials). + PaymentMethodCollection *string `form:"payment_method_collection"` + // The ID of the payment method configuration to use with this Checkout session. + PaymentMethodConfiguration *string `form:"payment_method_configuration"` + // This parameter allows you to set some attributes on the payment method created during a Checkout session. + PaymentMethodData *CheckoutSessionCreatePaymentMethodDataParams `form:"payment_method_data"` + // Payment-method-specific configuration. + PaymentMethodOptions *CheckoutSessionCreatePaymentMethodOptionsParams `form:"payment_method_options"` + // A list of the types of payment methods (e.g., `card`) this Checkout Session can accept. + // + // You can omit this attribute to manage your payment methods from the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). + // See [Dynamic Payment Methods](https://stripe.com/docs/payments/payment-methods/integration-options#using-dynamic-payment-methods) for more details. + // + // Read more about the supported payment methods and their requirements in our [payment + // method details guide](https://docs.stripe.com/docs/payments/checkout/payment-methods). + // + // If multiple payment methods are passed, Checkout will dynamically reorder them to + // prioritize the most relevant payment methods based on the customer's location and + // other characteristics. + PaymentMethodTypes []*string `form:"payment_method_types"` + // This property is used to set up permissions for various actions (e.g., update) on the CheckoutSession object. Can only be set when creating `embedded` or `custom` sessions. + // + // For specific permissions, please refer to their dedicated subsections, such as `permissions.update_shipping_details`. + Permissions *CheckoutSessionCreatePermissionsParams `form:"permissions"` + // Controls phone number collection settings for the session. + // + // We recommend that you review your privacy policy and check with your legal contacts + // before using this feature. Learn more about [collecting phone numbers with Checkout](https://stripe.com/docs/payments/checkout/phone-numbers). + PhoneNumberCollection *CheckoutSessionCreatePhoneNumberCollectionParams `form:"phone_number_collection"` + // This parameter applies to `ui_mode: embedded`. Learn more about the [redirect behavior](https://stripe.com/docs/payments/checkout/custom-success-page?payment-ui=embedded-form) of embedded sessions. Defaults to `always`. + RedirectOnCompletion *string `form:"redirect_on_completion"` + // The URL to redirect your customer back to after they authenticate or cancel their payment on the + // payment method's app or site. This parameter is required if `ui_mode` is `embedded` or `custom` + // and redirect-based payment methods are enabled on the session. + ReturnURL *string `form:"return_url"` + // Controls saved payment method settings for the session. Only available in `payment` and `subscription` mode. + SavedPaymentMethodOptions *CheckoutSessionCreateSavedPaymentMethodOptionsParams `form:"saved_payment_method_options"` + // A subset of parameters to be passed to SetupIntent creation for Checkout Sessions in `setup` mode. + SetupIntentData *CheckoutSessionCreateSetupIntentDataParams `form:"setup_intent_data"` + // When set, provides configuration for Checkout to collect a shipping address from a customer. + ShippingAddressCollection *CheckoutSessionCreateShippingAddressCollectionParams `form:"shipping_address_collection"` + // The shipping rate options to apply to this Session. Up to a maximum of 5. + ShippingOptions []*CheckoutSessionCreateShippingOptionParams `form:"shipping_options"` + // Describes the type of transaction being performed by Checkout in order + // to customize relevant text on the page, such as the submit button. + // `submit_type` can only be specified on Checkout Sessions in + // `payment` or `subscription` mode. If blank or `auto`, `pay` is used. + SubmitType *string `form:"submit_type"` + // A subset of parameters to be passed to subscription creation for Checkout Sessions in `subscription` mode. + SubscriptionData *CheckoutSessionCreateSubscriptionDataParams `form:"subscription_data"` + // The URL to which Stripe should send customers when payment or setup + // is complete. + // This parameter is not allowed if ui_mode is `embedded` or `custom`. If you'd like to use + // information from the successful Checkout Session on your page, read the + // guide on [customizing your success page](https://stripe.com/docs/payments/checkout/custom-success-page). + SuccessURL *string `form:"success_url"` + // Controls tax ID collection during checkout. + TaxIDCollection *CheckoutSessionCreateTaxIDCollectionParams `form:"tax_id_collection"` + // The UI mode of the Session. Defaults to `hosted`. + UIMode *string `form:"ui_mode"` + // Wallet-specific configuration. + WalletOptions *CheckoutSessionCreateWalletOptionsParams `form:"wallet_options"` +} + +// AddExpand appends a new field to expand. +func (p *CheckoutSessionCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves a Checkout Session object. +type CheckoutSessionRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CheckoutSessionRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The shipping details to apply to this Session. +type CheckoutSessionUpdateCollectedInformationShippingDetailsParams struct { + // The address of the customer + Address *AddressParams `form:"address"` + // The name of customer + Name *string `form:"name"` +} + +// Information about the customer collected within the Checkout Session. Can only be set when updating `embedded` or `custom` sessions. +type CheckoutSessionUpdateCollectedInformationParams struct { + // The shipping details to apply to this Session. + ShippingDetails *CheckoutSessionUpdateCollectedInformationShippingDetailsParams `form:"shipping_details"` +} + +// The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. +type CheckoutSessionUpdateShippingOptionShippingRateDataDeliveryEstimateMaximumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The lower bound of the estimated range. If empty, represents no lower bound. +type CheckoutSessionUpdateShippingOptionShippingRateDataDeliveryEstimateMinimumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. +type CheckoutSessionUpdateShippingOptionShippingRateDataDeliveryEstimateParams struct { + // The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. + Maximum *CheckoutSessionUpdateShippingOptionShippingRateDataDeliveryEstimateMaximumParams `form:"maximum"` + // The lower bound of the estimated range. If empty, represents no lower bound. + Minimum *CheckoutSessionUpdateShippingOptionShippingRateDataDeliveryEstimateMinimumParams `form:"minimum"` +} + +// Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type CheckoutSessionUpdateShippingOptionShippingRateDataFixedAmountCurrencyOptionsParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` +} + +// Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. +type CheckoutSessionUpdateShippingOptionShippingRateDataFixedAmountParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*CheckoutSessionUpdateShippingOptionShippingRateDataFixedAmountCurrencyOptionsParams `form:"currency_options"` +} + +// Parameters to be passed to Shipping Rate creation for this shipping option. +type CheckoutSessionUpdateShippingOptionShippingRateDataParams struct { + // The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. + DeliveryEstimate *CheckoutSessionUpdateShippingOptionShippingRateDataDeliveryEstimateParams `form:"delivery_estimate"` + // The name of the shipping rate, meant to be displayable to the customer. This will appear on CheckoutSessions. + DisplayName *string `form:"display_name"` + // Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. + FixedAmount *CheckoutSessionUpdateShippingOptionShippingRateDataFixedAmountParams `form:"fixed_amount"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. The Shipping tax code is `txcd_92010001`. + TaxCode *string `form:"tax_code"` + // The type of calculation to use on the shipping rate. + Type *string `form:"type"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionUpdateShippingOptionShippingRateDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The shipping rate options to apply to this Session. Up to a maximum of 5. +type CheckoutSessionUpdateShippingOptionParams struct { + // The ID of the Shipping Rate to use for this shipping option. + ShippingRate *string `form:"shipping_rate"` + // Parameters to be passed to Shipping Rate creation for this shipping option. + ShippingRateData *CheckoutSessionUpdateShippingOptionShippingRateDataParams `form:"shipping_rate_data"` +} + +// Updates a Checkout Session object. +// +// Related guide: [Dynamically update Checkout](https://docs.stripe.com/payments/checkout/dynamic-updates) +type CheckoutSessionUpdateParams struct { + Params `form:"*"` + // Information about the customer collected within the Checkout Session. Can only be set when updating `embedded` or `custom` sessions. + CollectedInformation *CheckoutSessionUpdateCollectedInformationParams `form:"collected_information"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The shipping rate options to apply to this Session. Up to a maximum of 5. + ShippingOptions []*CheckoutSessionUpdateShippingOptionParams `form:"shipping_options"` +} + +// AddExpand appends a new field to expand. +func (p *CheckoutSessionUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CheckoutSessionUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Settings for price localization with [Adaptive Pricing](https://docs.stripe.com/payments/checkout/adaptive-pricing). +type CheckoutSessionAdaptivePricing struct { + // Whether Adaptive Pricing is enabled. + Enabled bool `json:"enabled"` +} + +// When set, configuration used to recover the Checkout Session on expiry. +type CheckoutSessionAfterExpirationRecovery struct { + // Enables user redeemable promotion codes on the recovered Checkout Sessions. Defaults to `false` + AllowPromotionCodes bool `json:"allow_promotion_codes"` + // If `true`, a recovery url will be generated to recover this Checkout Session if it + // expires before a transaction is completed. It will be attached to the + // Checkout Session object upon expiration. + Enabled bool `json:"enabled"` + // The timestamp at which the recovery URL will expire. + ExpiresAt int64 `json:"expires_at"` + // URL that creates a new Checkout Session when clicked that is a copy of this expired Checkout Session + URL string `json:"url"` +} + +// When set, provides configuration for actions to take if this Checkout Session expires. +type CheckoutSessionAfterExpiration struct { + // When set, configuration used to recover the Checkout Session on expiry. + Recovery *CheckoutSessionAfterExpirationRecovery `json:"recovery"` +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type CheckoutSessionAutomaticTaxLiability struct { + // The connected account being referenced when `type` is `account`. + Account *Account `json:"account"` + // Type of the account referenced. + Type CheckoutSessionAutomaticTaxLiabilityType `json:"type"` +} +type CheckoutSessionAutomaticTax struct { + // Indicates whether automatic tax is enabled for the session + Enabled bool `json:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *CheckoutSessionAutomaticTaxLiability `json:"liability"` + // The tax provider powering automatic tax. + Provider string `json:"provider"` + // The status of the most recent automated tax calculation for this session. + Status CheckoutSessionAutomaticTaxStatus `json:"status"` +} + +// Shipping information for this Checkout Session. +type CheckoutSessionCollectedInformationShippingDetails struct { + Address *Address `json:"address"` + // Customer name. + Name string `json:"name"` +} + +// Information about the customer collected within the Checkout Session. +type CheckoutSessionCollectedInformation struct { + // Shipping information for this Checkout Session. + ShippingDetails *CheckoutSessionCollectedInformationShippingDetails `json:"shipping_details"` +} + +// Results of `consent_collection` for this session. +type CheckoutSessionConsent struct { + // If `opt_in`, the customer consents to receiving promotional communications + // from the merchant about this Checkout Session. + Promotions CheckoutSessionConsentPromotions `json:"promotions"` + // If `accepted`, the customer in this Checkout Session has agreed to the merchant's terms of service. + TermsOfService CheckoutSessionConsentTermsOfService `json:"terms_of_service"` +} + +// If set to `hidden`, it will hide legal text related to the reuse of a payment method. +type CheckoutSessionConsentCollectionPaymentMethodReuseAgreement struct { + // Determines the position and visibility of the payment method reuse agreement in the UI. When set to `auto`, Stripe's defaults will be used. + // + // When set to `hidden`, the payment method reuse agreement text will always be hidden in the UI. + Position CheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition `json:"position"` +} + +// When set, provides configuration for the Checkout Session to gather active consent from customers. +type CheckoutSessionConsentCollection struct { + // If set to `hidden`, it will hide legal text related to the reuse of a payment method. + PaymentMethodReuseAgreement *CheckoutSessionConsentCollectionPaymentMethodReuseAgreement `json:"payment_method_reuse_agreement"` + // If set to `auto`, enables the collection of customer consent for promotional communications. The Checkout + // Session will determine whether to display an option to opt into promotional communication + // from the merchant depending on the customer's locale. Only available to US merchants. + Promotions CheckoutSessionConsentCollectionPromotions `json:"promotions"` + // If set to `required`, it requires customers to accept the terms of service before being able to pay. + TermsOfService CheckoutSessionConsentCollectionTermsOfService `json:"terms_of_service"` +} + +// Currency conversion details for [Adaptive Pricing](https://docs.stripe.com/payments/checkout/adaptive-pricing) sessions created before 2025-03-31. +type CheckoutSessionCurrencyConversion struct { + // Total of all items in source currency before discounts or taxes are applied. + AmountSubtotal int64 `json:"amount_subtotal"` + // Total of all items in source currency after discounts and taxes are applied. + AmountTotal int64 `json:"amount_total"` + // Exchange rate used to convert source currency amounts to customer currency amounts + FxRate float64 `json:"fx_rate,string"` + // Creation currency of the CheckoutSession before localization + SourceCurrency Currency `json:"source_currency"` +} + +// The options available for the customer to select. Up to 200 options allowed. +type CheckoutSessionCustomFieldDropdownOption struct { + // The label for the option, displayed to the customer. Up to 100 characters. + Label string `json:"label"` + // The value for this option, not displayed to the customer, used by your integration to reconcile the option selected by the customer. Must be unique to this option, alphanumeric, and up to 100 characters. + Value string `json:"value"` +} +type CheckoutSessionCustomFieldDropdown struct { + // The value that will pre-fill on the payment page. + DefaultValue string `json:"default_value"` + // The options available for the customer to select. Up to 200 options allowed. + Options []*CheckoutSessionCustomFieldDropdownOption `json:"options"` + // The option selected by the customer. This will be the `value` for the option. + Value string `json:"value"` +} +type CheckoutSessionCustomFieldLabel struct { + // Custom text for the label, displayed to the customer. Up to 50 characters. + Custom string `json:"custom"` + // The type of the label. + Type CheckoutSessionCustomFieldLabelType `json:"type"` +} +type CheckoutSessionCustomFieldNumeric struct { + // The value that will pre-fill the field on the payment page. + DefaultValue string `json:"default_value"` + // The maximum character length constraint for the customer's input. + MaximumLength int64 `json:"maximum_length"` + // The minimum character length requirement for the customer's input. + MinimumLength int64 `json:"minimum_length"` + // The value entered by the customer, containing only digits. + Value string `json:"value"` +} +type CheckoutSessionCustomFieldText struct { + // The value that will pre-fill the field on the payment page. + DefaultValue string `json:"default_value"` + // The maximum character length constraint for the customer's input. + MaximumLength int64 `json:"maximum_length"` + // The minimum character length requirement for the customer's input. + MinimumLength int64 `json:"minimum_length"` + // The value entered by the customer. + Value string `json:"value"` +} + +// Collect additional information from your customer using custom fields. Up to 3 fields are supported. +type CheckoutSessionCustomField struct { + Dropdown *CheckoutSessionCustomFieldDropdown `json:"dropdown"` + // String of your choice that your integration can use to reconcile this field. Must be unique to this field, alphanumeric, and up to 200 characters. + Key string `json:"key"` + Label *CheckoutSessionCustomFieldLabel `json:"label"` + Numeric *CheckoutSessionCustomFieldNumeric `json:"numeric"` + // Whether the customer is required to complete the field before completing the Checkout Session. Defaults to `false`. + Optional bool `json:"optional"` + Text *CheckoutSessionCustomFieldText `json:"text"` + // The type of the field. + Type CheckoutSessionCustomFieldType `json:"type"` +} + +// Custom text that should be displayed after the payment confirmation button. +type CheckoutSessionCustomTextAfterSubmit struct { + // Text may be up to 1200 characters in length. + Message string `json:"message"` +} + +// Custom text that should be displayed alongside shipping address collection. +type CheckoutSessionCustomTextShippingAddress struct { + // Text may be up to 1200 characters in length. + Message string `json:"message"` +} + +// Custom text that should be displayed alongside the payment confirmation button. +type CheckoutSessionCustomTextSubmit struct { + // Text may be up to 1200 characters in length. + Message string `json:"message"` +} + +// Custom text that should be displayed in place of the default terms of service agreement text. +type CheckoutSessionCustomTextTermsOfServiceAcceptance struct { + // Text may be up to 1200 characters in length. + Message string `json:"message"` +} +type CheckoutSessionCustomText struct { + // Custom text that should be displayed after the payment confirmation button. + AfterSubmit *CheckoutSessionCustomTextAfterSubmit `json:"after_submit"` + // Custom text that should be displayed alongside shipping address collection. + ShippingAddress *CheckoutSessionCustomTextShippingAddress `json:"shipping_address"` + // Custom text that should be displayed alongside the payment confirmation button. + Submit *CheckoutSessionCustomTextSubmit `json:"submit"` + // Custom text that should be displayed in place of the default terms of service agreement text. + TermsOfServiceAcceptance *CheckoutSessionCustomTextTermsOfServiceAcceptance `json:"terms_of_service_acceptance"` +} + +// The customer's tax IDs after a completed Checkout Session. +type CheckoutSessionCustomerDetailsTaxID struct { + // The type of the tax ID, one of `ad_nrt`, `ar_cuit`, `eu_vat`, `bo_tin`, `br_cnpj`, `br_cpf`, `cn_tin`, `co_nit`, `cr_tin`, `do_rcn`, `ec_ruc`, `eu_oss_vat`, `hr_oib`, `pe_ruc`, `ro_tin`, `rs_pib`, `sv_nit`, `uy_ruc`, `ve_rif`, `vn_tin`, `gb_vat`, `nz_gst`, `au_abn`, `au_arn`, `in_gst`, `no_vat`, `no_voec`, `za_vat`, `ch_vat`, `mx_rfc`, `sg_uen`, `ru_inn`, `ru_kpp`, `ca_bn`, `hk_br`, `es_cif`, `tw_vat`, `th_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `li_uid`, `li_vat`, `my_itn`, `us_ein`, `kr_brn`, `ca_qst`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `my_sst`, `sg_gst`, `ae_trn`, `cl_tin`, `sa_vat`, `id_npwp`, `my_frp`, `il_vat`, `ge_vat`, `ua_vat`, `is_vat`, `bg_uic`, `hu_tin`, `si_tin`, `ke_pin`, `tr_tin`, `eg_tin`, `ph_tin`, `al_tin`, `bh_vat`, `kz_bin`, `ng_tin`, `om_vat`, `de_stn`, `ch_uid`, `tz_vat`, `uz_vat`, `uz_tin`, `md_vat`, `ma_vat`, `by_tin`, `ao_tin`, `bs_tin`, `bb_tin`, `cd_nif`, `mr_nif`, `me_pib`, `zw_tin`, `ba_tin`, `gn_nif`, `mk_vat`, `sr_fin`, `sn_ninea`, `am_tin`, `np_pan`, `tj_tin`, `ug_tin`, `zm_tin`, `kh_tin`, `aw_tin`, `az_tin`, `bd_bin`, `bj_ifu`, `et_tin`, `kg_tin`, `la_tin`, `cm_niu`, `cv_nif`, `bf_ifu`, or `unknown` + Type CheckoutSessionCustomerDetailsTaxIDType `json:"type"` + // The value of the tax ID. + Value string `json:"value"` +} + +// The customer details including the customer's tax exempt status and the customer's tax IDs. Customer's address details are not present on Sessions in `setup` mode. +type CheckoutSessionCustomerDetails struct { + // The customer's address after a completed Checkout Session. Note: This property is populated only for sessions on or after March 30, 2022. + Address *Address `json:"address"` + // The email associated with the Customer, if one exists, on the Checkout Session after a completed Checkout Session or at time of session expiry. + // Otherwise, if the customer has consented to promotional content, this value is the most recent valid email provided by the customer on the Checkout form. + Email string `json:"email"` + // The customer's name after a completed Checkout Session. Note: This property is populated only for sessions on or after March 30, 2022. + Name string `json:"name"` + // The customer's phone number after a completed Checkout Session. + Phone string `json:"phone"` + // The customer's tax exempt status after a completed Checkout Session. + TaxExempt CheckoutSessionCustomerDetailsTaxExempt `json:"tax_exempt"` + // The customer's tax IDs after a completed Checkout Session. + TaxIDs []*CheckoutSessionCustomerDetailsTaxID `json:"tax_ids"` +} + +// List of coupons and promotion codes attached to the Checkout Session. +type CheckoutSessionDiscount struct { + // Coupon attached to the Checkout Session. + Coupon *Coupon `json:"coupon"` + // Promotion code attached to the Checkout Session. + PromotionCode *PromotionCode `json:"promotion_code"` +} + +// Custom fields displayed on the invoice. +type CheckoutSessionInvoiceCreationInvoiceDataCustomField struct { + // The name of the custom field. + Name string `json:"name"` + // The value of the custom field. + Value string `json:"value"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type CheckoutSessionInvoiceCreationInvoiceDataIssuer struct { + // The connected account being referenced when `type` is `account`. + Account *Account `json:"account"` + // Type of the account referenced. + Type CheckoutSessionInvoiceCreationInvoiceDataIssuerType `json:"type"` +} + +// Options for invoice PDF rendering. +type CheckoutSessionInvoiceCreationInvoiceDataRenderingOptions struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. + AmountTaxDisplay string `json:"amount_tax_display"` +} +type CheckoutSessionInvoiceCreationInvoiceData struct { + // The account tax IDs associated with the invoice. + AccountTaxIDs []*TaxID `json:"account_tax_ids"` + // Custom fields displayed on the invoice. + CustomFields []*CheckoutSessionInvoiceCreationInvoiceDataCustomField `json:"custom_fields"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // Footer displayed on the invoice. + Footer string `json:"footer"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *CheckoutSessionInvoiceCreationInvoiceDataIssuer `json:"issuer"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // Options for invoice PDF rendering. + RenderingOptions *CheckoutSessionInvoiceCreationInvoiceDataRenderingOptions `json:"rendering_options"` +} + +// Details on the state of invoice creation for the Checkout Session. +type CheckoutSessionInvoiceCreation struct { + // Indicates whether invoice creation is enabled for the Checkout Session. + Enabled bool `json:"enabled"` + InvoiceData *CheckoutSessionInvoiceCreationInvoiceData `json:"invoice_data"` +} +type CheckoutSessionOptionalItemAdjustableQuantity struct { + // Set to true if the quantity can be adjusted to any non-negative integer. + Enabled bool `json:"enabled"` + // The maximum quantity of this item the customer can purchase. By default this value is 99. You can specify a value up to 999999. + Maximum int64 `json:"maximum"` + // The minimum quantity of this item the customer must purchase, if they choose to purchase it. Because this item is optional, the customer will always be able to remove it from their order, even if the `minimum` configured here is greater than 0. By default this value is 0. + Minimum int64 `json:"minimum"` +} + +// The optional items presented to the customer at checkout. +type CheckoutSessionOptionalItem struct { + AdjustableQuantity *CheckoutSessionOptionalItemAdjustableQuantity `json:"adjustable_quantity"` + Price string `json:"price"` + Quantity int64 `json:"quantity"` +} + +// Information about the payment method configuration used for this Checkout session if using dynamic payment methods. +type CheckoutSessionPaymentMethodConfigurationDetails struct { + // ID of the payment method configuration used. + ID string `json:"id"` + // ID of the parent payment method configuration used. + Parent string `json:"parent"` +} +type CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptions struct { + // A URL for custom mandate text + CustomMandateURL string `json:"custom_mandate_url"` + // List of Stripe products where this mandate can be selected automatically. Returned when the Session is in `setup` mode. + DefaultFor []CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsDefaultFor `json:"default_for"` + // Description of the interval. Only required if the 'payment_schedule' parameter is 'interval' or 'combined'. + IntervalDescription string `json:"interval_description"` + // Payment schedule for the mandate. + PaymentSchedule CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule `json:"payment_schedule"` + // Transaction type of the mandate. + TransactionType CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptionsTransactionType `json:"transaction_type"` +} +type CheckoutSessionPaymentMethodOptionsACSSDebit struct { + Currency string `json:"currency"` + MandateOptions *CheckoutSessionPaymentMethodOptionsACSSDebitMandateOptions `json:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsACSSDebitSetupFutureUsage `json:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate string `json:"target_date"` + // Bank account verification method. + VerificationMethod CheckoutSessionPaymentMethodOptionsACSSDebitVerificationMethod `json:"verification_method"` +} +type CheckoutSessionPaymentMethodOptionsAffirm struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsAffirmSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsAfterpayClearpay struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsAfterpayClearpaySetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsAlipay struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsAlipaySetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsAmazonPay struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsAmazonPaySetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsAUBECSDebit struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsAUBECSDebitSetupFutureUsage `json:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate string `json:"target_date"` +} +type CheckoutSessionPaymentMethodOptionsBACSDebitMandateOptions struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'DDIC' or 'STRIPE'. + ReferencePrefix string `json:"reference_prefix"` +} +type CheckoutSessionPaymentMethodOptionsBACSDebit struct { + MandateOptions *CheckoutSessionPaymentMethodOptionsBACSDebitMandateOptions `json:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsBACSDebitSetupFutureUsage `json:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate string `json:"target_date"` +} +type CheckoutSessionPaymentMethodOptionsBancontact struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsBancontactSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsBoleto struct { + // The number of calendar days before a Boleto voucher expires. For example, if you create a Boleto voucher on Monday and you set expires_after_days to 2, the Boleto voucher will expire on Wednesday at 23:59 America/Sao_Paulo time. + ExpiresAfterDays int64 `json:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsBoletoSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsCardInstallments struct { + // Indicates if installments are enabled + Enabled bool `json:"enabled"` +} +type CheckoutSessionPaymentMethodOptionsCardRestrictions struct { + // Specify the card brands to block in the Checkout Session. If a customer enters or selects a card belonging to a blocked brand, they can't complete the Session. + BrandsBlocked []CheckoutSessionPaymentMethodOptionsCardRestrictionsBrandsBlocked `json:"brands_blocked"` +} +type CheckoutSessionPaymentMethodOptionsCard struct { + Installments *CheckoutSessionPaymentMethodOptionsCardInstallments `json:"installments"` + // Request ability to [capture beyond the standard authorization validity window](https://docs.stripe.com/payments/extended-authorization) for this CheckoutSession. + RequestExtendedAuthorization CheckoutSessionPaymentMethodOptionsCardRequestExtendedAuthorization `json:"request_extended_authorization"` + // Request ability to [increment the authorization](https://docs.stripe.com/payments/incremental-authorization) for this CheckoutSession. + RequestIncrementalAuthorization CheckoutSessionPaymentMethodOptionsCardRequestIncrementalAuthorization `json:"request_incremental_authorization"` + // Request ability to make [multiple captures](https://docs.stripe.com/payments/multicapture) for this CheckoutSession. + RequestMulticapture CheckoutSessionPaymentMethodOptionsCardRequestMulticapture `json:"request_multicapture"` + // Request ability to [overcapture](https://docs.stripe.com/payments/overcapture) for this CheckoutSession. + RequestOvercapture CheckoutSessionPaymentMethodOptionsCardRequestOvercapture `json:"request_overcapture"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure CheckoutSessionPaymentMethodOptionsCardRequestThreeDSecure `json:"request_three_d_secure"` + Restrictions *CheckoutSessionPaymentMethodOptionsCardRestrictions `json:"restrictions"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsCardSetupFutureUsage `json:"setup_future_usage"` + // Provides information about a card payment that customers see on their statements. Concatenated with the Kana prefix (shortened Kana descriptor) or Kana statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 22 characters. + StatementDescriptorSuffixKana string `json:"statement_descriptor_suffix_kana"` + // Provides information about a card payment that customers see on their statements. Concatenated with the Kanji prefix (shortened Kanji descriptor) or Kanji statement descriptor that's set on the account to form the complete statement descriptor. Maximum 17 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 17 characters. + StatementDescriptorSuffixKanji string `json:"statement_descriptor_suffix_kanji"` +} +type CheckoutSessionPaymentMethodOptionsCashApp struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsCashAppSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransfer struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country string `json:"country"` +} +type CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransfer struct { + EUBankTransfer *CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransfer `json:"eu_bank_transfer"` + // List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. + // + // Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. + RequestedAddressTypes []CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType `json:"requested_address_types"` + // The bank transfer type that this PaymentIntent is allowed to use for funding Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + Type CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferType `json:"type"` +} +type CheckoutSessionPaymentMethodOptionsCustomerBalance struct { + BankTransfer *CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransfer `json:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType CheckoutSessionPaymentMethodOptionsCustomerBalanceFundingType `json:"funding_type"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsCustomerBalanceSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsEPS struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsEPSSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsFPX struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsFPXSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsGiropay struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsGiropaySetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsGrabpay struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsGrabpaySetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsIDEAL struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsIDEALSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsKakaoPay struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod CheckoutSessionPaymentMethodOptionsKakaoPayCaptureMethod `json:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsKakaoPaySetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsKlarna struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsKlarnaSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsKonbini struct { + // The number of calendar days (between 1 and 60) after which Konbini payment instructions will expire. For example, if a PaymentIntent is confirmed with Konbini and `expires_after_days` set to 2 on Monday JST, the instructions will expire on Wednesday 23:59:59 JST. + ExpiresAfterDays int64 `json:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsKonbiniSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsKrCard struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod CheckoutSessionPaymentMethodOptionsKrCardCaptureMethod `json:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsKrCardSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsLink struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsLinkSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsMobilepay struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsMobilepaySetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsMultibanco struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsMultibancoSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsNaverPay struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod CheckoutSessionPaymentMethodOptionsNaverPayCaptureMethod `json:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsNaverPaySetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsOXXO struct { + // The number of calendar days before an OXXO invoice expires. For example, if you create an OXXO invoice on Monday and you set expires_after_days to 2, the OXXO invoice will expire on Wednesday at 23:59 America/Mexico_City time. + ExpiresAfterDays int64 `json:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsOXXOSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsP24 struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsP24SetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsPayco struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod CheckoutSessionPaymentMethodOptionsPaycoCaptureMethod `json:"capture_method"` +} +type CheckoutSessionPaymentMethodOptionsPayNow struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsPayNowSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsPaypal struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod CheckoutSessionPaymentMethodOptionsPaypalCaptureMethod `json:"capture_method"` + // Preferred locale of the PayPal checkout page that the customer is redirected to. + PreferredLocale string `json:"preferred_locale"` + // A reference of the PayPal transaction visible to customer which is mapped to PayPal's invoice ID. This must be a globally unique ID if you have configured in your PayPal settings to block multiple payments per invoice ID. + Reference string `json:"reference"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsPaypalSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsPix struct { + // The number of seconds after which Pix payment will expire. + ExpiresAfterSeconds int64 `json:"expires_after_seconds"` +} +type CheckoutSessionPaymentMethodOptionsRevolutPay struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsRevolutPaySetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsSamsungPay struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod CheckoutSessionPaymentMethodOptionsSamsungPayCaptureMethod `json:"capture_method"` +} +type CheckoutSessionPaymentMethodOptionsSEPADebitMandateOptions struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'STRIPE'. + ReferencePrefix string `json:"reference_prefix"` +} +type CheckoutSessionPaymentMethodOptionsSEPADebit struct { + MandateOptions *CheckoutSessionPaymentMethodOptionsSEPADebitMandateOptions `json:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsSEPADebitSetupFutureUsage `json:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate string `json:"target_date"` +} +type CheckoutSessionPaymentMethodOptionsSofort struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsSofortSetupFutureUsage `json:"setup_future_usage"` +} +type CheckoutSessionPaymentMethodOptionsSwish struct { + // The order reference that will be displayed to customers in the Swish application. Defaults to the `id` of the Payment Intent. + Reference string `json:"reference"` +} +type CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsFilters struct { + // The account subcategories to use to filter for possible accounts to link. Valid subcategories are `checking` and `savings`. + AccountSubcategories []CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory `json:"account_subcategories"` +} +type CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnections struct { + Filters *CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsFilters `json:"filters"` + // The list of permissions to request. The `payment_method` permission must be included. + Permissions []CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission `json:"permissions"` + // Data features requested to be retrieved upon account creation. + Prefetch []CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch `json:"prefetch"` + // For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + ReturnURL string `json:"return_url"` +} +type CheckoutSessionPaymentMethodOptionsUSBankAccount struct { + FinancialConnections *CheckoutSessionPaymentMethodOptionsUSBankAccountFinancialConnections `json:"financial_connections"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage CheckoutSessionPaymentMethodOptionsUSBankAccountSetupFutureUsage `json:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate string `json:"target_date"` + // Bank account verification method. + VerificationMethod CheckoutSessionPaymentMethodOptionsUSBankAccountVerificationMethod `json:"verification_method"` +} + +// Payment-method-specific configuration for the PaymentIntent or SetupIntent of this CheckoutSession. +type CheckoutSessionPaymentMethodOptions struct { + ACSSDebit *CheckoutSessionPaymentMethodOptionsACSSDebit `json:"acss_debit"` + Affirm *CheckoutSessionPaymentMethodOptionsAffirm `json:"affirm"` + AfterpayClearpay *CheckoutSessionPaymentMethodOptionsAfterpayClearpay `json:"afterpay_clearpay"` + Alipay *CheckoutSessionPaymentMethodOptionsAlipay `json:"alipay"` + AmazonPay *CheckoutSessionPaymentMethodOptionsAmazonPay `json:"amazon_pay"` + AUBECSDebit *CheckoutSessionPaymentMethodOptionsAUBECSDebit `json:"au_becs_debit"` + BACSDebit *CheckoutSessionPaymentMethodOptionsBACSDebit `json:"bacs_debit"` + Bancontact *CheckoutSessionPaymentMethodOptionsBancontact `json:"bancontact"` + Boleto *CheckoutSessionPaymentMethodOptionsBoleto `json:"boleto"` + Card *CheckoutSessionPaymentMethodOptionsCard `json:"card"` + CashApp *CheckoutSessionPaymentMethodOptionsCashApp `json:"cashapp"` + CustomerBalance *CheckoutSessionPaymentMethodOptionsCustomerBalance `json:"customer_balance"` + EPS *CheckoutSessionPaymentMethodOptionsEPS `json:"eps"` + FPX *CheckoutSessionPaymentMethodOptionsFPX `json:"fpx"` + Giropay *CheckoutSessionPaymentMethodOptionsGiropay `json:"giropay"` + Grabpay *CheckoutSessionPaymentMethodOptionsGrabpay `json:"grabpay"` + IDEAL *CheckoutSessionPaymentMethodOptionsIDEAL `json:"ideal"` + KakaoPay *CheckoutSessionPaymentMethodOptionsKakaoPay `json:"kakao_pay"` + Klarna *CheckoutSessionPaymentMethodOptionsKlarna `json:"klarna"` + Konbini *CheckoutSessionPaymentMethodOptionsKonbini `json:"konbini"` + KrCard *CheckoutSessionPaymentMethodOptionsKrCard `json:"kr_card"` + Link *CheckoutSessionPaymentMethodOptionsLink `json:"link"` + Mobilepay *CheckoutSessionPaymentMethodOptionsMobilepay `json:"mobilepay"` + Multibanco *CheckoutSessionPaymentMethodOptionsMultibanco `json:"multibanco"` + NaverPay *CheckoutSessionPaymentMethodOptionsNaverPay `json:"naver_pay"` + OXXO *CheckoutSessionPaymentMethodOptionsOXXO `json:"oxxo"` + P24 *CheckoutSessionPaymentMethodOptionsP24 `json:"p24"` + Payco *CheckoutSessionPaymentMethodOptionsPayco `json:"payco"` + PayNow *CheckoutSessionPaymentMethodOptionsPayNow `json:"paynow"` + Paypal *CheckoutSessionPaymentMethodOptionsPaypal `json:"paypal"` + Pix *CheckoutSessionPaymentMethodOptionsPix `json:"pix"` + RevolutPay *CheckoutSessionPaymentMethodOptionsRevolutPay `json:"revolut_pay"` + SamsungPay *CheckoutSessionPaymentMethodOptionsSamsungPay `json:"samsung_pay"` + SEPADebit *CheckoutSessionPaymentMethodOptionsSEPADebit `json:"sepa_debit"` + Sofort *CheckoutSessionPaymentMethodOptionsSofort `json:"sofort"` + Swish *CheckoutSessionPaymentMethodOptionsSwish `json:"swish"` + USBankAccount *CheckoutSessionPaymentMethodOptionsUSBankAccount `json:"us_bank_account"` +} + +// This property is used to set up permissions for various actions (e.g., update) on the CheckoutSession object. +// +// For specific permissions, please refer to their dedicated subsections, such as `permissions.update_shipping_details`. +type CheckoutSessionPermissions struct { + // Determines which entity is allowed to update the shipping details. + // + // Default is `client_only`. Stripe Checkout client will automatically update the shipping details. If set to `server_only`, only your server is allowed to update the shipping details. + // + // When set to `server_only`, you must add the onShippingDetailsChange event handler when initializing the Stripe Checkout client and manually update the shipping details from your server using the Stripe API. + UpdateShippingDetails CheckoutSessionPermissionsUpdateShippingDetails `json:"update_shipping_details"` +} +type CheckoutSessionPhoneNumberCollection struct { + // Indicates whether phone number collection is enabled for the session + Enabled bool `json:"enabled"` +} +type CheckoutSessionPresentmentDetails struct { + // Amount intended to be collected by this payment, denominated in presentment_currency. + PresentmentAmount int64 `json:"presentment_amount"` + // Currency presented to the customer during payment. + PresentmentCurrency Currency `json:"presentment_currency"` +} + +// Controls saved payment method settings for the session. Only available in `payment` and `subscription` mode. +type CheckoutSessionSavedPaymentMethodOptions struct { + // Uses the `allow_redisplay` value of each saved payment method to filter the set presented to a returning customer. By default, only saved payment methods with 'allow_redisplay: ‘always' are shown in Checkout. + AllowRedisplayFilters []CheckoutSessionSavedPaymentMethodOptionsAllowRedisplayFilter `json:"allow_redisplay_filters"` + // Enable customers to choose if they wish to remove their saved payment methods. Disabled by default. + PaymentMethodRemove CheckoutSessionSavedPaymentMethodOptionsPaymentMethodRemove `json:"payment_method_remove"` + // Enable customers to choose if they wish to save their payment method for future use. Disabled by default. + PaymentMethodSave CheckoutSessionSavedPaymentMethodOptionsPaymentMethodSave `json:"payment_method_save"` +} + +// When set, provides configuration for Checkout to collect a shipping address from a customer. +type CheckoutSessionShippingAddressCollection struct { + // An array of two-letter ISO country codes representing which countries Checkout should provide as options for + // shipping locations. Unsupported country codes: `AS, CX, CC, CU, HM, IR, KP, MH, FM, NF, MP, PW, SY, UM, VI`. + AllowedCountries []string `json:"allowed_countries"` +} + +// The taxes applied to the shipping rate. +type CheckoutSessionShippingCostTax struct { + // Amount of tax applied for this rate. + Amount int64 `json:"amount"` + // Tax rates can be applied to [invoices](https://docs.stripe.com/invoicing/taxes/tax-rates), [subscriptions](https://docs.stripe.com/billing/taxes/tax-rates) and [Checkout Sessions](https://docs.stripe.com/payments/checkout/use-manual-tax-rates) to collect tax. + // + // Related guide: [Tax rates](https://docs.stripe.com/billing/taxes/tax-rates) + Rate *TaxRate `json:"rate"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason CheckoutSessionShippingCostTaxTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount int64 `json:"taxable_amount"` +} + +// The details of the customer cost of shipping, including the customer chosen ShippingRate. +type CheckoutSessionShippingCost struct { + // Total shipping cost before any discounts or taxes are applied. + AmountSubtotal int64 `json:"amount_subtotal"` + // Total tax amount applied due to shipping costs. If no tax was applied, defaults to 0. + AmountTax int64 `json:"amount_tax"` + // Total shipping cost after discounts and taxes are applied. + AmountTotal int64 `json:"amount_total"` + // The ID of the ShippingRate for this order. + ShippingRate *ShippingRate `json:"shipping_rate"` + // The taxes applied to the shipping rate. + Taxes []*CheckoutSessionShippingCostTax `json:"taxes"` +} + +// The shipping rate options applied to this Session. +type CheckoutSessionShippingOption struct { + // A non-negative integer in cents representing how much to charge. + ShippingAmount int64 `json:"shipping_amount"` + // The shipping rate. + ShippingRate *ShippingRate `json:"shipping_rate"` +} +type CheckoutSessionTaxIDCollection struct { + // Indicates whether tax ID collection is enabled for the session + Enabled bool `json:"enabled"` + // Indicates whether a tax ID is required on the payment page + Required CheckoutSessionTaxIDCollectionRequired `json:"required"` +} + +// The aggregated discounts. +type CheckoutSessionTotalDetailsBreakdownDiscount struct { + // The amount discounted. + Amount int64 `json:"amount"` + // A discount represents the actual application of a [coupon](https://stripe.com/docs/api#coupons) or [promotion code](https://stripe.com/docs/api#promotion_codes). + // It contains information about when the discount began, when it will end, and what it is applied to. + // + // Related guide: [Applying discounts to subscriptions](https://stripe.com/docs/billing/subscriptions/discounts) + Discount *Discount `json:"discount"` +} + +// The aggregated tax amounts by rate. +type CheckoutSessionTotalDetailsBreakdownTax struct { + // Amount of tax applied for this rate. + Amount int64 `json:"amount"` + // Tax rates can be applied to [invoices](https://docs.stripe.com/invoicing/taxes/tax-rates), [subscriptions](https://docs.stripe.com/billing/taxes/tax-rates) and [Checkout Sessions](https://docs.stripe.com/payments/checkout/use-manual-tax-rates) to collect tax. + // + // Related guide: [Tax rates](https://docs.stripe.com/billing/taxes/tax-rates) + Rate *TaxRate `json:"rate"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason CheckoutSessionTotalDetailsBreakdownTaxTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount int64 `json:"taxable_amount"` +} +type CheckoutSessionTotalDetailsBreakdown struct { + // The aggregated discounts. + Discounts []*CheckoutSessionTotalDetailsBreakdownDiscount `json:"discounts"` + // The aggregated tax amounts by rate. + Taxes []*CheckoutSessionTotalDetailsBreakdownTax `json:"taxes"` +} + +// Tax and discount details for the computed total amount. +type CheckoutSessionTotalDetails struct { + // This is the sum of all the discounts. + AmountDiscount int64 `json:"amount_discount"` + // This is the sum of all the shipping amounts. + AmountShipping int64 `json:"amount_shipping"` + // This is the sum of all the tax amounts. + AmountTax int64 `json:"amount_tax"` + Breakdown *CheckoutSessionTotalDetailsBreakdown `json:"breakdown"` +} +type CheckoutSessionWalletOptionsLink struct { + // Describes whether Checkout should display Link. Defaults to `auto`. + Display CheckoutSessionWalletOptionsLinkDisplay `json:"display"` +} + +// Wallet-specific configuration for this Checkout Session. +type CheckoutSessionWalletOptions struct { + Link *CheckoutSessionWalletOptionsLink `json:"link"` +} + +// A Checkout Session represents your customer's session as they pay for +// one-time purchases or subscriptions through [Checkout](https://stripe.com/docs/payments/checkout) +// or [Payment Links](https://stripe.com/docs/payments/payment-links). We recommend creating a +// new Session each time your customer attempts to pay. +// +// Once payment is successful, the Checkout Session will contain a reference +// to the [Customer](https://stripe.com/docs/api/customers), and either the successful +// [PaymentIntent](https://stripe.com/docs/api/payment_intents) or an active +// [Subscription](https://stripe.com/docs/api/subscriptions). +// +// You can create a Checkout Session on your server and redirect to its URL +// to begin Checkout. +// +// Related guide: [Checkout quickstart](https://stripe.com/docs/checkout/quickstart) +type CheckoutSession struct { + APIResource + // Settings for price localization with [Adaptive Pricing](https://docs.stripe.com/payments/checkout/adaptive-pricing). + AdaptivePricing *CheckoutSessionAdaptivePricing `json:"adaptive_pricing"` + // When set, provides configuration for actions to take if this Checkout Session expires. + AfterExpiration *CheckoutSessionAfterExpiration `json:"after_expiration"` + // Enables user redeemable promotion codes. + AllowPromotionCodes bool `json:"allow_promotion_codes"` + // Total of all items before discounts or taxes are applied. + AmountSubtotal int64 `json:"amount_subtotal"` + // Total of all items after discounts and taxes are applied. + AmountTotal int64 `json:"amount_total"` + AutomaticTax *CheckoutSessionAutomaticTax `json:"automatic_tax"` + // Describes whether Checkout should collect the customer's billing address. Defaults to `auto`. + BillingAddressCollection CheckoutSessionBillingAddressCollection `json:"billing_address_collection"` + // If set, Checkout displays a back button and customers will be directed to this URL if they decide to cancel payment and return to your website. + CancelURL string `json:"cancel_url"` + // A unique string to reference the Checkout Session. This can be a + // customer ID, a cart ID, or similar, and can be used to reconcile the + // Session with your internal systems. + ClientReferenceID string `json:"client_reference_id"` + // The client secret of your Checkout Session. Applies to Checkout Sessions with `ui_mode: embedded` or `ui_mode: custom`. For `ui_mode: embedded`, the client secret is to be used when initializing Stripe.js embedded checkout. + // For `ui_mode: custom`, use the client secret with [initCheckout](https://stripe.com/docs/js/custom_checkout/init) on your front end. + ClientSecret string `json:"client_secret"` + // Information about the customer collected within the Checkout Session. + CollectedInformation *CheckoutSessionCollectedInformation `json:"collected_information"` + // Results of `consent_collection` for this session. + Consent *CheckoutSessionConsent `json:"consent"` + // When set, provides configuration for the Checkout Session to gather active consent from customers. + ConsentCollection *CheckoutSessionConsentCollection `json:"consent_collection"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // Currency conversion details for [Adaptive Pricing](https://docs.stripe.com/payments/checkout/adaptive-pricing) sessions created before 2025-03-31. + CurrencyConversion *CheckoutSessionCurrencyConversion `json:"currency_conversion"` + // The ID of the customer for this Session. + // For Checkout Sessions in `subscription` mode or Checkout Sessions with `customer_creation` set as `always` in `payment` mode, Checkout + // will create a new customer object based on information provided + // during the payment flow unless an existing customer was provided when + // the Session was created. + Customer *Customer `json:"customer"` + // Configure whether a Checkout Session creates a Customer when the Checkout Session completes. + CustomerCreation CheckoutSessionCustomerCreation `json:"customer_creation"` + // The customer details including the customer's tax exempt status and the customer's tax IDs. Customer's address details are not present on Sessions in `setup` mode. + CustomerDetails *CheckoutSessionCustomerDetails `json:"customer_details"` + // If provided, this value will be used when the Customer object is created. + // If not provided, customers will be asked to enter their email address. + // Use this parameter to prefill customer data if you already have an email + // on file. To access information about the customer once the payment flow is + // complete, use the `customer` attribute. + CustomerEmail string `json:"customer_email"` + // Collect additional information from your customer using custom fields. Up to 3 fields are supported. + CustomFields []*CheckoutSessionCustomField `json:"custom_fields"` + CustomText *CheckoutSessionCustomText `json:"custom_text"` + // List of coupons and promotion codes attached to the Checkout Session. + Discounts []*CheckoutSessionDiscount `json:"discounts"` + // The timestamp at which the Checkout Session will expire. + ExpiresAt int64 `json:"expires_at"` + // Unique identifier for the object. + ID string `json:"id"` + // ID of the invoice created by the Checkout Session, if it exists. + Invoice *Invoice `json:"invoice"` + // Details on the state of invoice creation for the Checkout Session. + InvoiceCreation *CheckoutSessionInvoiceCreation `json:"invoice_creation"` + // The line items purchased by the customer. + LineItems *LineItemList `json:"line_items"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // The IETF language tag of the locale Checkout is displayed in. If blank or `auto`, the browser's locale is used. + Locale string `json:"locale"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // The mode of the Checkout Session. + Mode CheckoutSessionMode `json:"mode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The optional items presented to the customer at checkout. + OptionalItems []*CheckoutSessionOptionalItem `json:"optional_items"` + // The ID of the PaymentIntent for Checkout Sessions in `payment` mode. You can't confirm or cancel the PaymentIntent for a Checkout Session. To cancel, [expire the Checkout Session](https://stripe.com/docs/api/checkout/sessions/expire) instead. + PaymentIntent *PaymentIntent `json:"payment_intent"` + // The ID of the Payment Link that created this Session. + PaymentLink *PaymentLink `json:"payment_link"` + // Configure whether a Checkout Session should collect a payment method. Defaults to `always`. + PaymentMethodCollection CheckoutSessionPaymentMethodCollection `json:"payment_method_collection"` + // Information about the payment method configuration used for this Checkout session if using dynamic payment methods. + PaymentMethodConfigurationDetails *CheckoutSessionPaymentMethodConfigurationDetails `json:"payment_method_configuration_details"` + // Payment-method-specific configuration for the PaymentIntent or SetupIntent of this CheckoutSession. + PaymentMethodOptions *CheckoutSessionPaymentMethodOptions `json:"payment_method_options"` + // A list of the types of payment methods (e.g. card) this Checkout + // Session is allowed to accept. + PaymentMethodTypes []string `json:"payment_method_types"` + // The payment status of the Checkout Session, one of `paid`, `unpaid`, or `no_payment_required`. + // You can use this value to decide when to fulfill your customer's order. + PaymentStatus CheckoutSessionPaymentStatus `json:"payment_status"` + // This property is used to set up permissions for various actions (e.g., update) on the CheckoutSession object. + // + // For specific permissions, please refer to their dedicated subsections, such as `permissions.update_shipping_details`. + Permissions *CheckoutSessionPermissions `json:"permissions"` + PhoneNumberCollection *CheckoutSessionPhoneNumberCollection `json:"phone_number_collection"` + PresentmentDetails *CheckoutSessionPresentmentDetails `json:"presentment_details"` + // The ID of the original expired Checkout Session that triggered the recovery flow. + RecoveredFrom string `json:"recovered_from"` + // This parameter applies to `ui_mode: embedded`. Learn more about the [redirect behavior](https://stripe.com/docs/payments/checkout/custom-success-page?payment-ui=embedded-form) of embedded sessions. Defaults to `always`. + RedirectOnCompletion CheckoutSessionRedirectOnCompletion `json:"redirect_on_completion"` + // Applies to Checkout Sessions with `ui_mode: embedded` or `ui_mode: custom`. The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method's app or site. + ReturnURL string `json:"return_url"` + // Controls saved payment method settings for the session. Only available in `payment` and `subscription` mode. + SavedPaymentMethodOptions *CheckoutSessionSavedPaymentMethodOptions `json:"saved_payment_method_options"` + // The ID of the SetupIntent for Checkout Sessions in `setup` mode. You can't confirm or cancel the SetupIntent for a Checkout Session. To cancel, [expire the Checkout Session](https://stripe.com/docs/api/checkout/sessions/expire) instead. + SetupIntent *SetupIntent `json:"setup_intent"` + // When set, provides configuration for Checkout to collect a shipping address from a customer. + ShippingAddressCollection *CheckoutSessionShippingAddressCollection `json:"shipping_address_collection"` + // The details of the customer cost of shipping, including the customer chosen ShippingRate. + ShippingCost *CheckoutSessionShippingCost `json:"shipping_cost"` + // The shipping rate options applied to this Session. + ShippingOptions []*CheckoutSessionShippingOption `json:"shipping_options"` + // The status of the Checkout Session, one of `open`, `complete`, or `expired`. + Status CheckoutSessionStatus `json:"status"` + // Describes the type of transaction being performed by Checkout in order to customize + // relevant text on the page, such as the submit button. `submit_type` can only be + // specified on Checkout Sessions in `payment` mode. If blank or `auto`, `pay` is used. + SubmitType CheckoutSessionSubmitType `json:"submit_type"` + // The ID of the [Subscription](https://stripe.com/docs/api/subscriptions) for Checkout Sessions in `subscription` mode. + Subscription *Subscription `json:"subscription"` + // The URL the customer will be directed to after the payment or + // subscription creation is successful. + SuccessURL string `json:"success_url"` + TaxIDCollection *CheckoutSessionTaxIDCollection `json:"tax_id_collection"` + // Tax and discount details for the computed total amount. + TotalDetails *CheckoutSessionTotalDetails `json:"total_details"` + // The UI mode of the Session. Defaults to `hosted`. + UIMode CheckoutSessionUIMode `json:"ui_mode"` + // The URL to the Checkout Session. Applies to Checkout Sessions with `ui_mode: hosted`. Redirect customers to this URL to take them to Checkout. If you're using [Custom Domains](https://stripe.com/docs/payments/checkout/custom-domains), the URL will use your subdomain. Otherwise, it'll use `checkout.stripe.com.` + // This value is only present when the session is active. + URL string `json:"url"` + // Wallet-specific configuration for this Checkout Session. + WalletOptions *CheckoutSessionWalletOptions `json:"wallet_options"` +} + +// CheckoutSessionList is a list of Sessions as retrieved from a list endpoint. +type CheckoutSessionList struct { + APIResource + ListMeta + Data []*CheckoutSession `json:"data"` +} + +// UnmarshalJSON handles deserialization of a CheckoutSession. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (c *CheckoutSession) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + c.ID = id + return nil + } + + type checkoutSession CheckoutSession + var v checkoutSession + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *c = CheckoutSession(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/checkout_session_service.go b/vendor/github.com/stripe/stripe-go/v82/checkout_session_service.go new file mode 100644 index 00000000..4af58b31 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/checkout_session_service.go @@ -0,0 +1,108 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1CheckoutSessionService is used to invoke /v1/checkout/sessions APIs. +type v1CheckoutSessionService struct { + B Backend + Key string +} + +// Creates a Checkout Session object. +func (c v1CheckoutSessionService) Create(ctx context.Context, params *CheckoutSessionCreateParams) (*CheckoutSession, error) { + if params == nil { + params = &CheckoutSessionCreateParams{} + } + params.Context = ctx + session := &CheckoutSession{} + err := c.B.Call( + http.MethodPost, "/v1/checkout/sessions", c.Key, params, session) + return session, err +} + +// Retrieves a Checkout Session object. +func (c v1CheckoutSessionService) Retrieve(ctx context.Context, id string, params *CheckoutSessionRetrieveParams) (*CheckoutSession, error) { + if params == nil { + params = &CheckoutSessionRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/checkout/sessions/%s", id) + session := &CheckoutSession{} + err := c.B.Call(http.MethodGet, path, c.Key, params, session) + return session, err +} + +// Updates a Checkout Session object. +// +// Related guide: [Dynamically update Checkout](https://docs.stripe.com/payments/checkout/dynamic-updates) +func (c v1CheckoutSessionService) Update(ctx context.Context, id string, params *CheckoutSessionUpdateParams) (*CheckoutSession, error) { + if params == nil { + params = &CheckoutSessionUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/checkout/sessions/%s", id) + session := &CheckoutSession{} + err := c.B.Call(http.MethodPost, path, c.Key, params, session) + return session, err +} + +// A Checkout Session can be expired when it is in one of these statuses: open +// +// After it expires, a customer can't complete a Checkout Session and customers loading the Checkout Session see a message saying the Checkout Session is expired. +func (c v1CheckoutSessionService) Expire(ctx context.Context, id string, params *CheckoutSessionExpireParams) (*CheckoutSession, error) { + if params == nil { + params = &CheckoutSessionExpireParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/checkout/sessions/%s/expire", id) + session := &CheckoutSession{} + err := c.B.Call(http.MethodPost, path, c.Key, params, session) + return session, err +} + +// Returns a list of Checkout Sessions. +func (c v1CheckoutSessionService) List(ctx context.Context, listParams *CheckoutSessionListParams) Seq2[*CheckoutSession, error] { + if listParams == nil { + listParams = &CheckoutSessionListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*CheckoutSession, ListContainer, error) { + list := &CheckoutSessionList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/checkout/sessions", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// When retrieving a Checkout Session, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. +func (c v1CheckoutSessionService) ListLineItems(ctx context.Context, listParams *CheckoutSessionListLineItemsParams) Seq2[*LineItem, error] { + if listParams == nil { + listParams = &CheckoutSessionListLineItemsParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/checkout/sessions/%s/line_items", StringValue(listParams.Session)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*LineItem, ListContainer, error) { + list := &LineItemList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/climate_order.go b/vendor/github.com/stripe/stripe-go/v82/climate_order.go new file mode 100644 index 00000000..5dbc0b30 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/climate_order.go @@ -0,0 +1,269 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Reason for the cancellation of this order. +type ClimateOrderCancellationReason string + +// List of values that ClimateOrderCancellationReason can take +const ( + ClimateOrderCancellationReasonExpired ClimateOrderCancellationReason = "expired" + ClimateOrderCancellationReasonProductUnavailable ClimateOrderCancellationReason = "product_unavailable" + ClimateOrderCancellationReasonRequested ClimateOrderCancellationReason = "requested" +) + +// The current status of this order. +type ClimateOrderStatus string + +// List of values that ClimateOrderStatus can take +const ( + ClimateOrderStatusAwaitingFunds ClimateOrderStatus = "awaiting_funds" + ClimateOrderStatusCanceled ClimateOrderStatus = "canceled" + ClimateOrderStatusConfirmed ClimateOrderStatus = "confirmed" + ClimateOrderStatusDelivered ClimateOrderStatus = "delivered" + ClimateOrderStatusOpen ClimateOrderStatus = "open" +) + +// Lists all Climate order objects. The orders are returned sorted by creation date, with the +// most recently created orders appearing first. +type ClimateOrderListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ClimateOrderListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Publicly sharable reference for the end beneficiary of carbon removal. Assumed to be the Stripe account if not set. +type ClimateOrderBeneficiaryParams struct { + // Publicly displayable name for the end beneficiary of carbon removal. + PublicName *string `form:"public_name"` +} + +// Creates a Climate order object for a given Climate product. The order will be processed immediately +// after creation and payment will be deducted your Stripe balance. +type ClimateOrderParams struct { + Params `form:"*"` + // Requested amount of carbon removal units. Either this or `metric_tons` must be specified. + Amount *int64 `form:"amount"` + // Publicly sharable reference for the end beneficiary of carbon removal. Assumed to be the Stripe account if not set. + Beneficiary *ClimateOrderBeneficiaryParams `form:"beneficiary"` + // Request currency for the order as a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a supported [settlement currency for your account](https://stripe.com/docs/currencies). If omitted, the account's default currency will be used. + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Requested number of tons for the order. Either this or `amount` must be specified. + MetricTons *float64 `form:"metric_tons,high_precision"` + // Unique identifier of the Climate product. + Product *string `form:"product"` +} + +// AddExpand appends a new field to expand. +func (p *ClimateOrderParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ClimateOrderParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Cancels a Climate order. You can cancel an order within 24 hours of creation. Stripe refunds the +// reservation amount_subtotal, but not the amount_fees for user-triggered cancellations. Frontier +// might cancel reservations if suppliers fail to deliver. If Frontier cancels the reservation, Stripe +// provides 90 days advance notice and refunds the amount_total. +type ClimateOrderCancelParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ClimateOrderCancelParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Publicly sharable reference for the end beneficiary of carbon removal. Assumed to be the Stripe account if not set. +type ClimateOrderCreateBeneficiaryParams struct { + // Publicly displayable name for the end beneficiary of carbon removal. + PublicName *string `form:"public_name"` +} + +// Creates a Climate order object for a given Climate product. The order will be processed immediately +// after creation and payment will be deducted your Stripe balance. +type ClimateOrderCreateParams struct { + Params `form:"*"` + // Requested amount of carbon removal units. Either this or `metric_tons` must be specified. + Amount *int64 `form:"amount"` + // Publicly sharable reference for the end beneficiary of carbon removal. Assumed to be the Stripe account if not set. + Beneficiary *ClimateOrderCreateBeneficiaryParams `form:"beneficiary"` + // Request currency for the order as a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a supported [settlement currency for your account](https://stripe.com/docs/currencies). If omitted, the account's default currency will be used. + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Requested number of tons for the order. Either this or `amount` must be specified. + MetricTons *float64 `form:"metric_tons,high_precision"` + // Unique identifier of the Climate product. + Product *string `form:"product"` +} + +// AddExpand appends a new field to expand. +func (p *ClimateOrderCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ClimateOrderCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the details of a Climate order object with the given ID. +type ClimateOrderRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ClimateOrderRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Publicly sharable reference for the end beneficiary of carbon removal. Assumed to be the Stripe account if not set. +type ClimateOrderUpdateBeneficiaryParams struct { + // Publicly displayable name for the end beneficiary of carbon removal. + PublicName *string `form:"public_name"` +} + +// Updates the specified order by setting the values of the parameters passed. +type ClimateOrderUpdateParams struct { + Params `form:"*"` + // Publicly sharable reference for the end beneficiary of carbon removal. Assumed to be the Stripe account if not set. + Beneficiary *ClimateOrderUpdateBeneficiaryParams `form:"beneficiary"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *ClimateOrderUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ClimateOrderUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +type ClimateOrderBeneficiary struct { + // Publicly displayable name for the end beneficiary of carbon removal. + PublicName string `json:"public_name"` +} + +// Specific location of this delivery. +type ClimateOrderDeliveryDetailLocation struct { + // The city where the supplier is located. + City string `json:"city"` + // Two-letter ISO code representing the country where the supplier is located. + Country string `json:"country"` + // The geographic latitude where the supplier is located. + Latitude float64 `json:"latitude"` + // The geographic longitude where the supplier is located. + Longitude float64 `json:"longitude"` + // The state/county/province/region where the supplier is located. + Region string `json:"region"` +} + +// Details about the delivery of carbon removal for this order. +type ClimateOrderDeliveryDetail struct { + // Time at which the delivery occurred. Measured in seconds since the Unix epoch. + DeliveredAt int64 `json:"delivered_at"` + // Specific location of this delivery. + Location *ClimateOrderDeliveryDetailLocation `json:"location"` + // Quantity of carbon removal supplied by this delivery. + MetricTons string `json:"metric_tons"` + // Once retired, a URL to the registry entry for the tons from this delivery. + RegistryURL string `json:"registry_url"` + // A supplier of carbon removal. + Supplier *ClimateSupplier `json:"supplier"` +} + +// Orders represent your intent to purchase a particular Climate product. When you create an order, the +// payment is deducted from your merchant balance. +type ClimateOrder struct { + APIResource + // Total amount of [Frontier](https://frontierclimate.com/)'s service fees in the currency's smallest unit. + AmountFees int64 `json:"amount_fees"` + // Total amount of the carbon removal in the currency's smallest unit. + AmountSubtotal int64 `json:"amount_subtotal"` + // Total amount of the order including fees in the currency's smallest unit. + AmountTotal int64 `json:"amount_total"` + Beneficiary *ClimateOrderBeneficiary `json:"beneficiary"` + // Time at which the order was canceled. Measured in seconds since the Unix epoch. + CanceledAt int64 `json:"canceled_at"` + // Reason for the cancellation of this order. + CancellationReason ClimateOrderCancellationReason `json:"cancellation_reason"` + // For delivered orders, a URL to a delivery certificate for the order. + Certificate string `json:"certificate"` + // Time at which the order was confirmed. Measured in seconds since the Unix epoch. + ConfirmedAt int64 `json:"confirmed_at"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase, representing the currency for this order. + Currency Currency `json:"currency"` + // Time at which the order's expected_delivery_year was delayed. Measured in seconds since the Unix epoch. + DelayedAt int64 `json:"delayed_at"` + // Time at which the order was delivered. Measured in seconds since the Unix epoch. + DeliveredAt int64 `json:"delivered_at"` + // Details about the delivery of carbon removal for this order. + DeliveryDetails []*ClimateOrderDeliveryDetail `json:"delivery_details"` + // The year this order is expected to be delivered. + ExpectedDeliveryYear int64 `json:"expected_delivery_year"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // Quantity of carbon removal that is included in this order. + MetricTons float64 `json:"metric_tons,string"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Unique ID for the Climate `Product` this order is purchasing. + Product *ClimateProduct `json:"product"` + // Time at which the order's product was substituted for a different product. Measured in seconds since the Unix epoch. + ProductSubstitutedAt int64 `json:"product_substituted_at"` + // The current status of this order. + Status ClimateOrderStatus `json:"status"` +} + +// ClimateOrderList is a list of Orders as retrieved from a list endpoint. +type ClimateOrderList struct { + APIResource + ListMeta + Data []*ClimateOrder `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/climate_order_service.go b/vendor/github.com/stripe/stripe-go/v82/climate_order_service.go new file mode 100644 index 00000000..16e8916e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/climate_order_service.go @@ -0,0 +1,89 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1ClimateOrderService is used to invoke /v1/climate/orders APIs. +type v1ClimateOrderService struct { + B Backend + Key string +} + +// Creates a Climate order object for a given Climate product. The order will be processed immediately +// after creation and payment will be deducted your Stripe balance. +func (c v1ClimateOrderService) Create(ctx context.Context, params *ClimateOrderCreateParams) (*ClimateOrder, error) { + if params == nil { + params = &ClimateOrderCreateParams{} + } + params.Context = ctx + order := &ClimateOrder{} + err := c.B.Call(http.MethodPost, "/v1/climate/orders", c.Key, params, order) + return order, err +} + +// Retrieves the details of a Climate order object with the given ID. +func (c v1ClimateOrderService) Retrieve(ctx context.Context, id string, params *ClimateOrderRetrieveParams) (*ClimateOrder, error) { + if params == nil { + params = &ClimateOrderRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/climate/orders/%s", id) + order := &ClimateOrder{} + err := c.B.Call(http.MethodGet, path, c.Key, params, order) + return order, err +} + +// Updates the specified order by setting the values of the parameters passed. +func (c v1ClimateOrderService) Update(ctx context.Context, id string, params *ClimateOrderUpdateParams) (*ClimateOrder, error) { + if params == nil { + params = &ClimateOrderUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/climate/orders/%s", id) + order := &ClimateOrder{} + err := c.B.Call(http.MethodPost, path, c.Key, params, order) + return order, err +} + +// Cancels a Climate order. You can cancel an order within 24 hours of creation. Stripe refunds the +// reservation amount_subtotal, but not the amount_fees for user-triggered cancellations. Frontier +// might cancel reservations if suppliers fail to deliver. If Frontier cancels the reservation, Stripe +// provides 90 days advance notice and refunds the amount_total. +func (c v1ClimateOrderService) Cancel(ctx context.Context, id string, params *ClimateOrderCancelParams) (*ClimateOrder, error) { + if params == nil { + params = &ClimateOrderCancelParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/climate/orders/%s/cancel", id) + order := &ClimateOrder{} + err := c.B.Call(http.MethodPost, path, c.Key, params, order) + return order, err +} + +// Lists all Climate order objects. The orders are returned sorted by creation date, with the +// most recently created orders appearing first. +func (c v1ClimateOrderService) List(ctx context.Context, listParams *ClimateOrderListParams) Seq2[*ClimateOrder, error] { + if listParams == nil { + listParams = &ClimateOrderListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*ClimateOrder, ListContainer, error) { + list := &ClimateOrderList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/climate/orders", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/climate_product.go b/vendor/github.com/stripe/stripe-go/v82/climate_product.go new file mode 100644 index 00000000..fc41d299 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/climate_product.go @@ -0,0 +1,107 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Lists all available Climate product objects. +type ClimateProductListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ClimateProductListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of a Climate product with the given ID. +type ClimateProductParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ClimateProductParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of a Climate product with the given ID. +type ClimateProductRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ClimateProductRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Current prices for a metric ton of carbon removal in a currency's smallest unit. +type ClimateProductCurrentPricesPerMetricTon struct { + // Fees for one metric ton of carbon removal in the currency's smallest unit. + AmountFees int64 `json:"amount_fees"` + // Subtotal for one metric ton of carbon removal (excluding fees) in the currency's smallest unit. + AmountSubtotal int64 `json:"amount_subtotal"` + // Total for one metric ton of carbon removal (including fees) in the currency's smallest unit. + AmountTotal int64 `json:"amount_total"` +} + +// A Climate product represents a type of carbon removal unit available for reservation. +// You can retrieve it to see the current price and availability. +type ClimateProduct struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Current prices for a metric ton of carbon removal in a currency's smallest unit. + CurrentPricesPerMetricTon map[string]*ClimateProductCurrentPricesPerMetricTon `json:"current_prices_per_metric_ton"` + // The year in which the carbon removal is expected to be delivered. + DeliveryYear int64 `json:"delivery_year"` + // Unique identifier for the object. For convenience, Climate product IDs are human-readable strings + // that start with `climsku_`. See [carbon removal inventory](https://stripe.com/docs/climate/orders/carbon-removal-inventory) + // for a list of available carbon removal products. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // The quantity of metric tons available for reservation. + MetricTonsAvailable float64 `json:"metric_tons_available,string"` + // The Climate product's name. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The carbon removal suppliers that fulfill orders for this Climate product. + Suppliers []*ClimateSupplier `json:"suppliers"` +} + +// ClimateProductList is a list of Products as retrieved from a list endpoint. +type ClimateProductList struct { + APIResource + ListMeta + Data []*ClimateProduct `json:"data"` +} + +// UnmarshalJSON handles deserialization of a ClimateProduct. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (c *ClimateProduct) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + c.ID = id + return nil + } + + type climateProduct ClimateProduct + var v climateProduct + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *c = ClimateProduct(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/climate_product_service.go b/vendor/github.com/stripe/stripe-go/v82/climate_product_service.go new file mode 100644 index 00000000..adbc504e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/climate_product_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1ClimateProductService is used to invoke /v1/climate/products APIs. +type v1ClimateProductService struct { + B Backend + Key string +} + +// Retrieves the details of a Climate product with the given ID. +func (c v1ClimateProductService) Retrieve(ctx context.Context, id string, params *ClimateProductRetrieveParams) (*ClimateProduct, error) { + if params == nil { + params = &ClimateProductRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/climate/products/%s", id) + product := &ClimateProduct{} + err := c.B.Call(http.MethodGet, path, c.Key, params, product) + return product, err +} + +// Lists all available Climate product objects. +func (c v1ClimateProductService) List(ctx context.Context, listParams *ClimateProductListParams) Seq2[*ClimateProduct, error] { + if listParams == nil { + listParams = &ClimateProductListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*ClimateProduct, ListContainer, error) { + list := &ClimateProductList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/climate/products", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/climate_supplier.go b/vendor/github.com/stripe/stripe-go/v82/climate_supplier.go new file mode 100644 index 00000000..4232db68 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/climate_supplier.go @@ -0,0 +1,93 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The scientific pathway used for carbon removal. +type ClimateSupplierRemovalPathway string + +// List of values that ClimateSupplierRemovalPathway can take +const ( + ClimateSupplierRemovalPathwayBiomassCarbonRemovalAndStorage ClimateSupplierRemovalPathway = "biomass_carbon_removal_and_storage" + ClimateSupplierRemovalPathwayDirectAirCapture ClimateSupplierRemovalPathway = "direct_air_capture" + ClimateSupplierRemovalPathwayEnhancedWeathering ClimateSupplierRemovalPathway = "enhanced_weathering" +) + +// Lists all available Climate supplier objects. +type ClimateSupplierListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ClimateSupplierListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a Climate supplier object. +type ClimateSupplierParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ClimateSupplierParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a Climate supplier object. +type ClimateSupplierRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ClimateSupplierRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The locations in which this supplier operates. +type ClimateSupplierLocation struct { + // The city where the supplier is located. + City string `json:"city"` + // Two-letter ISO code representing the country where the supplier is located. + Country string `json:"country"` + // The geographic latitude where the supplier is located. + Latitude float64 `json:"latitude"` + // The geographic longitude where the supplier is located. + Longitude float64 `json:"longitude"` + // The state/county/province/region where the supplier is located. + Region string `json:"region"` +} + +// A supplier of carbon removal. +type ClimateSupplier struct { + APIResource + // Unique identifier for the object. + ID string `json:"id"` + // Link to a webpage to learn more about the supplier. + InfoURL string `json:"info_url"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // The locations in which this supplier operates. + Locations []*ClimateSupplierLocation `json:"locations"` + // Name of this carbon removal supplier. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The scientific pathway used for carbon removal. + RemovalPathway ClimateSupplierRemovalPathway `json:"removal_pathway"` +} + +// ClimateSupplierList is a list of Suppliers as retrieved from a list endpoint. +type ClimateSupplierList struct { + APIResource + ListMeta + Data []*ClimateSupplier `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/climate_supplier_service.go b/vendor/github.com/stripe/stripe-go/v82/climate_supplier_service.go new file mode 100644 index 00000000..db581b7d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/climate_supplier_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1ClimateSupplierService is used to invoke /v1/climate/suppliers APIs. +type v1ClimateSupplierService struct { + B Backend + Key string +} + +// Retrieves a Climate supplier object. +func (c v1ClimateSupplierService) Retrieve(ctx context.Context, id string, params *ClimateSupplierRetrieveParams) (*ClimateSupplier, error) { + if params == nil { + params = &ClimateSupplierRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/climate/suppliers/%s", id) + supplier := &ClimateSupplier{} + err := c.B.Call(http.MethodGet, path, c.Key, params, supplier) + return supplier, err +} + +// Lists all available Climate supplier objects. +func (c v1ClimateSupplierService) List(ctx context.Context, listParams *ClimateSupplierListParams) Seq2[*ClimateSupplier, error] { + if listParams == nil { + listParams = &ClimateSupplierListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*ClimateSupplier, ListContainer, error) { + list := &ClimateSupplierList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/climate/suppliers", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/confirmationtoken.go b/vendor/github.com/stripe/stripe-go/v82/confirmationtoken.go new file mode 100644 index 00000000..e445cb20 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/confirmationtoken.go @@ -0,0 +1,1172 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// For `fixed_count` installment plans, this is the interval between installment payments your customer will make to their credit card. +// One of `month`. +type ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanInterval string + +// List of values that ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanInterval can take +const ( + ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanIntervalMonth ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanInterval = "month" +) + +// Type of installment plan, one of `fixed_count`, `bonus`, or `revolving`. +type ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanType string + +// List of values that ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanType can take +const ( + ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanTypeBonus ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanType = "bonus" + ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanTypeFixedCount ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanType = "fixed_count" + ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanTypeRevolving ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanType = "revolving" +) + +// This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to “unspecified”. +type ConfirmationTokenPaymentMethodPreviewAllowRedisplay string + +// List of values that ConfirmationTokenPaymentMethodPreviewAllowRedisplay can take +const ( + ConfirmationTokenPaymentMethodPreviewAllowRedisplayAlways ConfirmationTokenPaymentMethodPreviewAllowRedisplay = "always" + ConfirmationTokenPaymentMethodPreviewAllowRedisplayLimited ConfirmationTokenPaymentMethodPreviewAllowRedisplay = "limited" + ConfirmationTokenPaymentMethodPreviewAllowRedisplayUnspecified ConfirmationTokenPaymentMethodPreviewAllowRedisplay = "unspecified" +) + +// The method used to process this payment method offline. Only deferred is allowed. +type ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentOfflineType string + +// List of values that ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentOfflineType can take +const ( + ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentOfflineTypeDeferred ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentOfflineType = "deferred" +) + +// How card details were read in this transaction. +type ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod string + +// List of values that ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod can take +const ( + ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReadMethodContactEmv ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod = "contact_emv" + ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReadMethodContactlessEmv ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod = "contactless_emv" + ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReadMethodContactlessMagstripeMode ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod = "contactless_magstripe_mode" + ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReadMethodMagneticStripeFallback ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod = "magnetic_stripe_fallback" + ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReadMethodMagneticStripeTrack2 ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod = "magnetic_stripe_track2" +) + +// The type of account being debited or credited +type ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountType string + +// List of values that ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountType can take +const ( + ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountTypeChecking ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountType = "checking" + ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountTypeCredit ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountType = "credit" + ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountTypePrepaid ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountType = "prepaid" + ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountTypeUnknown ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountType = "unknown" +) + +// The type of mobile wallet, one of `apple_pay`, `google_pay`, `samsung_pay`, or `unknown`. +type ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentWalletType string + +// List of values that ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentWalletType can take +const ( + ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentWalletTypeApplePay ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentWalletType = "apple_pay" + ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentWalletTypeGooglePay ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentWalletType = "google_pay" + ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentWalletTypeSamsungPay ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentWalletType = "samsung_pay" + ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentWalletTypeUnknown ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentWalletType = "unknown" +) + +// Status of a card based on the card issuer. +type ConfirmationTokenPaymentMethodPreviewCardRegulatedStatus string + +// List of values that ConfirmationTokenPaymentMethodPreviewCardRegulatedStatus can take +const ( + ConfirmationTokenPaymentMethodPreviewCardRegulatedStatusRegulated ConfirmationTokenPaymentMethodPreviewCardRegulatedStatus = "regulated" + ConfirmationTokenPaymentMethodPreviewCardRegulatedStatusUnregulated ConfirmationTokenPaymentMethodPreviewCardRegulatedStatus = "unregulated" +) + +// The type of the card wallet, one of `amex_express_checkout`, `apple_pay`, `google_pay`, `masterpass`, `samsung_pay`, `visa_checkout`, or `link`. An additional hash is included on the Wallet subhash with a name matching this value. It contains additional information specific to the card wallet type. +type ConfirmationTokenPaymentMethodPreviewCardWalletType string + +// List of values that ConfirmationTokenPaymentMethodPreviewCardWalletType can take +const ( + ConfirmationTokenPaymentMethodPreviewCardWalletTypeAmexExpressCheckout ConfirmationTokenPaymentMethodPreviewCardWalletType = "amex_express_checkout" + ConfirmationTokenPaymentMethodPreviewCardWalletTypeApplePay ConfirmationTokenPaymentMethodPreviewCardWalletType = "apple_pay" + ConfirmationTokenPaymentMethodPreviewCardWalletTypeGooglePay ConfirmationTokenPaymentMethodPreviewCardWalletType = "google_pay" + ConfirmationTokenPaymentMethodPreviewCardWalletTypeLink ConfirmationTokenPaymentMethodPreviewCardWalletType = "link" + ConfirmationTokenPaymentMethodPreviewCardWalletTypeMasterpass ConfirmationTokenPaymentMethodPreviewCardWalletType = "masterpass" + ConfirmationTokenPaymentMethodPreviewCardWalletTypeSamsungPay ConfirmationTokenPaymentMethodPreviewCardWalletType = "samsung_pay" + ConfirmationTokenPaymentMethodPreviewCardWalletTypeVisaCheckout ConfirmationTokenPaymentMethodPreviewCardWalletType = "visa_checkout" +) + +// The method used to process this payment method offline. Only deferred is allowed. +type ConfirmationTokenPaymentMethodPreviewCardPresentOfflineType string + +// List of values that ConfirmationTokenPaymentMethodPreviewCardPresentOfflineType can take +const ( + ConfirmationTokenPaymentMethodPreviewCardPresentOfflineTypeDeferred ConfirmationTokenPaymentMethodPreviewCardPresentOfflineType = "deferred" +) + +// How card details were read in this transaction. +type ConfirmationTokenPaymentMethodPreviewCardPresentReadMethod string + +// List of values that ConfirmationTokenPaymentMethodPreviewCardPresentReadMethod can take +const ( + ConfirmationTokenPaymentMethodPreviewCardPresentReadMethodContactEmv ConfirmationTokenPaymentMethodPreviewCardPresentReadMethod = "contact_emv" + ConfirmationTokenPaymentMethodPreviewCardPresentReadMethodContactlessEmv ConfirmationTokenPaymentMethodPreviewCardPresentReadMethod = "contactless_emv" + ConfirmationTokenPaymentMethodPreviewCardPresentReadMethodContactlessMagstripeMode ConfirmationTokenPaymentMethodPreviewCardPresentReadMethod = "contactless_magstripe_mode" + ConfirmationTokenPaymentMethodPreviewCardPresentReadMethodMagneticStripeFallback ConfirmationTokenPaymentMethodPreviewCardPresentReadMethod = "magnetic_stripe_fallback" + ConfirmationTokenPaymentMethodPreviewCardPresentReadMethodMagneticStripeTrack2 ConfirmationTokenPaymentMethodPreviewCardPresentReadMethod = "magnetic_stripe_track2" +) + +// The type of mobile wallet, one of `apple_pay`, `google_pay`, `samsung_pay`, or `unknown`. +type ConfirmationTokenPaymentMethodPreviewCardPresentWalletType string + +// List of values that ConfirmationTokenPaymentMethodPreviewCardPresentWalletType can take +const ( + ConfirmationTokenPaymentMethodPreviewCardPresentWalletTypeApplePay ConfirmationTokenPaymentMethodPreviewCardPresentWalletType = "apple_pay" + ConfirmationTokenPaymentMethodPreviewCardPresentWalletTypeGooglePay ConfirmationTokenPaymentMethodPreviewCardPresentWalletType = "google_pay" + ConfirmationTokenPaymentMethodPreviewCardPresentWalletTypeSamsungPay ConfirmationTokenPaymentMethodPreviewCardPresentWalletType = "samsung_pay" + ConfirmationTokenPaymentMethodPreviewCardPresentWalletTypeUnknown ConfirmationTokenPaymentMethodPreviewCardPresentWalletType = "unknown" +) + +// The customer's bank. Should be one of `arzte_und_apotheker_bank`, `austrian_anadi_bank_ag`, `bank_austria`, `bankhaus_carl_spangler`, `bankhaus_schelhammer_und_schattera_ag`, `bawag_psk_ag`, `bks_bank_ag`, `brull_kallmus_bank_ag`, `btv_vier_lander_bank`, `capital_bank_grawe_gruppe_ag`, `deutsche_bank_ag`, `dolomitenbank`, `easybank_ag`, `erste_bank_und_sparkassen`, `hypo_alpeadriabank_international_ag`, `hypo_noe_lb_fur_niederosterreich_u_wien`, `hypo_oberosterreich_salzburg_steiermark`, `hypo_tirol_bank_ag`, `hypo_vorarlberg_bank_ag`, `hypo_bank_burgenland_aktiengesellschaft`, `marchfelder_bank`, `oberbank_ag`, `raiffeisen_bankengruppe_osterreich`, `schoellerbank_ag`, `sparda_bank_wien`, `volksbank_gruppe`, `volkskreditbank_ag`, or `vr_bank_braunau`. +type ConfirmationTokenPaymentMethodPreviewEPSBank string + +// List of values that ConfirmationTokenPaymentMethodPreviewEPSBank can take +const ( + ConfirmationTokenPaymentMethodPreviewEPSBankArzteUndApothekerBank ConfirmationTokenPaymentMethodPreviewEPSBank = "arzte_und_apotheker_bank" + ConfirmationTokenPaymentMethodPreviewEPSBankAustrianAnadiBankAg ConfirmationTokenPaymentMethodPreviewEPSBank = "austrian_anadi_bank_ag" + ConfirmationTokenPaymentMethodPreviewEPSBankBankAustria ConfirmationTokenPaymentMethodPreviewEPSBank = "bank_austria" + ConfirmationTokenPaymentMethodPreviewEPSBankBankhausCarlSpangler ConfirmationTokenPaymentMethodPreviewEPSBank = "bankhaus_carl_spangler" + ConfirmationTokenPaymentMethodPreviewEPSBankBankhausSchelhammerUndSchatteraAg ConfirmationTokenPaymentMethodPreviewEPSBank = "bankhaus_schelhammer_und_schattera_ag" + ConfirmationTokenPaymentMethodPreviewEPSBankBawagPskAg ConfirmationTokenPaymentMethodPreviewEPSBank = "bawag_psk_ag" + ConfirmationTokenPaymentMethodPreviewEPSBankBksBankAg ConfirmationTokenPaymentMethodPreviewEPSBank = "bks_bank_ag" + ConfirmationTokenPaymentMethodPreviewEPSBankBrullKallmusBankAg ConfirmationTokenPaymentMethodPreviewEPSBank = "brull_kallmus_bank_ag" + ConfirmationTokenPaymentMethodPreviewEPSBankBtvVierLanderBank ConfirmationTokenPaymentMethodPreviewEPSBank = "btv_vier_lander_bank" + ConfirmationTokenPaymentMethodPreviewEPSBankCapitalBankGraweGruppeAg ConfirmationTokenPaymentMethodPreviewEPSBank = "capital_bank_grawe_gruppe_ag" + ConfirmationTokenPaymentMethodPreviewEPSBankDeutscheBankAg ConfirmationTokenPaymentMethodPreviewEPSBank = "deutsche_bank_ag" + ConfirmationTokenPaymentMethodPreviewEPSBankDolomitenbank ConfirmationTokenPaymentMethodPreviewEPSBank = "dolomitenbank" + ConfirmationTokenPaymentMethodPreviewEPSBankEasybankAg ConfirmationTokenPaymentMethodPreviewEPSBank = "easybank_ag" + ConfirmationTokenPaymentMethodPreviewEPSBankErsteBankUndSparkassen ConfirmationTokenPaymentMethodPreviewEPSBank = "erste_bank_und_sparkassen" + ConfirmationTokenPaymentMethodPreviewEPSBankHypoAlpeadriabankInternationalAg ConfirmationTokenPaymentMethodPreviewEPSBank = "hypo_alpeadriabank_international_ag" + ConfirmationTokenPaymentMethodPreviewEPSBankHypoBankBurgenlandAktiengesellschaft ConfirmationTokenPaymentMethodPreviewEPSBank = "hypo_bank_burgenland_aktiengesellschaft" + ConfirmationTokenPaymentMethodPreviewEPSBankHypoNoeLbFurNiederosterreichUWien ConfirmationTokenPaymentMethodPreviewEPSBank = "hypo_noe_lb_fur_niederosterreich_u_wien" + ConfirmationTokenPaymentMethodPreviewEPSBankHypoOberosterreichSalzburgSteiermark ConfirmationTokenPaymentMethodPreviewEPSBank = "hypo_oberosterreich_salzburg_steiermark" + ConfirmationTokenPaymentMethodPreviewEPSBankHypoTirolBankAg ConfirmationTokenPaymentMethodPreviewEPSBank = "hypo_tirol_bank_ag" + ConfirmationTokenPaymentMethodPreviewEPSBankHypoVorarlbergBankAg ConfirmationTokenPaymentMethodPreviewEPSBank = "hypo_vorarlberg_bank_ag" + ConfirmationTokenPaymentMethodPreviewEPSBankMarchfelderBank ConfirmationTokenPaymentMethodPreviewEPSBank = "marchfelder_bank" + ConfirmationTokenPaymentMethodPreviewEPSBankOberbankAg ConfirmationTokenPaymentMethodPreviewEPSBank = "oberbank_ag" + ConfirmationTokenPaymentMethodPreviewEPSBankRaiffeisenBankengruppeOsterreich ConfirmationTokenPaymentMethodPreviewEPSBank = "raiffeisen_bankengruppe_osterreich" + ConfirmationTokenPaymentMethodPreviewEPSBankSchoellerbankAg ConfirmationTokenPaymentMethodPreviewEPSBank = "schoellerbank_ag" + ConfirmationTokenPaymentMethodPreviewEPSBankSpardaBankWien ConfirmationTokenPaymentMethodPreviewEPSBank = "sparda_bank_wien" + ConfirmationTokenPaymentMethodPreviewEPSBankVolksbankGruppe ConfirmationTokenPaymentMethodPreviewEPSBank = "volksbank_gruppe" + ConfirmationTokenPaymentMethodPreviewEPSBankVolkskreditbankAg ConfirmationTokenPaymentMethodPreviewEPSBank = "volkskreditbank_ag" + ConfirmationTokenPaymentMethodPreviewEPSBankVrBankBraunau ConfirmationTokenPaymentMethodPreviewEPSBank = "vr_bank_braunau" +) + +// Account holder type, if provided. Can be one of `individual` or `company`. +type ConfirmationTokenPaymentMethodPreviewFPXAccountHolderType string + +// List of values that ConfirmationTokenPaymentMethodPreviewFPXAccountHolderType can take +const ( + ConfirmationTokenPaymentMethodPreviewFPXAccountHolderTypeCompany ConfirmationTokenPaymentMethodPreviewFPXAccountHolderType = "company" + ConfirmationTokenPaymentMethodPreviewFPXAccountHolderTypeIndividual ConfirmationTokenPaymentMethodPreviewFPXAccountHolderType = "individual" +) + +// The customer's bank, if provided. Can be one of `affin_bank`, `agrobank`, `alliance_bank`, `ambank`, `bank_islam`, `bank_muamalat`, `bank_rakyat`, `bsn`, `cimb`, `hong_leong_bank`, `hsbc`, `kfh`, `maybank2u`, `ocbc`, `public_bank`, `rhb`, `standard_chartered`, `uob`, `deutsche_bank`, `maybank2e`, `pb_enterprise`, or `bank_of_china`. +type ConfirmationTokenPaymentMethodPreviewFPXBank string + +// List of values that ConfirmationTokenPaymentMethodPreviewFPXBank can take +const ( + ConfirmationTokenPaymentMethodPreviewFPXBankAffinBank ConfirmationTokenPaymentMethodPreviewFPXBank = "affin_bank" + ConfirmationTokenPaymentMethodPreviewFPXBankAgrobank ConfirmationTokenPaymentMethodPreviewFPXBank = "agrobank" + ConfirmationTokenPaymentMethodPreviewFPXBankAllianceBank ConfirmationTokenPaymentMethodPreviewFPXBank = "alliance_bank" + ConfirmationTokenPaymentMethodPreviewFPXBankAmbank ConfirmationTokenPaymentMethodPreviewFPXBank = "ambank" + ConfirmationTokenPaymentMethodPreviewFPXBankBankIslam ConfirmationTokenPaymentMethodPreviewFPXBank = "bank_islam" + ConfirmationTokenPaymentMethodPreviewFPXBankBankMuamalat ConfirmationTokenPaymentMethodPreviewFPXBank = "bank_muamalat" + ConfirmationTokenPaymentMethodPreviewFPXBankBankOfChina ConfirmationTokenPaymentMethodPreviewFPXBank = "bank_of_china" + ConfirmationTokenPaymentMethodPreviewFPXBankBankRakyat ConfirmationTokenPaymentMethodPreviewFPXBank = "bank_rakyat" + ConfirmationTokenPaymentMethodPreviewFPXBankBsn ConfirmationTokenPaymentMethodPreviewFPXBank = "bsn" + ConfirmationTokenPaymentMethodPreviewFPXBankCimb ConfirmationTokenPaymentMethodPreviewFPXBank = "cimb" + ConfirmationTokenPaymentMethodPreviewFPXBankDeutscheBank ConfirmationTokenPaymentMethodPreviewFPXBank = "deutsche_bank" + ConfirmationTokenPaymentMethodPreviewFPXBankHongLeongBank ConfirmationTokenPaymentMethodPreviewFPXBank = "hong_leong_bank" + ConfirmationTokenPaymentMethodPreviewFPXBankHsbc ConfirmationTokenPaymentMethodPreviewFPXBank = "hsbc" + ConfirmationTokenPaymentMethodPreviewFPXBankKfh ConfirmationTokenPaymentMethodPreviewFPXBank = "kfh" + ConfirmationTokenPaymentMethodPreviewFPXBankMaybank2e ConfirmationTokenPaymentMethodPreviewFPXBank = "maybank2e" + ConfirmationTokenPaymentMethodPreviewFPXBankMaybank2u ConfirmationTokenPaymentMethodPreviewFPXBank = "maybank2u" + ConfirmationTokenPaymentMethodPreviewFPXBankOcbc ConfirmationTokenPaymentMethodPreviewFPXBank = "ocbc" + ConfirmationTokenPaymentMethodPreviewFPXBankPbEnterprise ConfirmationTokenPaymentMethodPreviewFPXBank = "pb_enterprise" + ConfirmationTokenPaymentMethodPreviewFPXBankPublicBank ConfirmationTokenPaymentMethodPreviewFPXBank = "public_bank" + ConfirmationTokenPaymentMethodPreviewFPXBankRhb ConfirmationTokenPaymentMethodPreviewFPXBank = "rhb" + ConfirmationTokenPaymentMethodPreviewFPXBankStandardChartered ConfirmationTokenPaymentMethodPreviewFPXBank = "standard_chartered" + ConfirmationTokenPaymentMethodPreviewFPXBankUob ConfirmationTokenPaymentMethodPreviewFPXBank = "uob" +) + +// The customer's bank, if provided. Can be one of `abn_amro`, `asn_bank`, `bunq`, `buut`, `handelsbanken`, `ing`, `knab`, `moneyou`, `n26`, `nn`, `rabobank`, `regiobank`, `revolut`, `sns_bank`, `triodos_bank`, `van_lanschot`, or `yoursafe`. +type ConfirmationTokenPaymentMethodPreviewIDEALBank string + +// List of values that ConfirmationTokenPaymentMethodPreviewIDEALBank can take +const ( + ConfirmationTokenPaymentMethodPreviewIDEALBankAbnAmro ConfirmationTokenPaymentMethodPreviewIDEALBank = "abn_amro" + ConfirmationTokenPaymentMethodPreviewIDEALBankAsnBank ConfirmationTokenPaymentMethodPreviewIDEALBank = "asn_bank" + ConfirmationTokenPaymentMethodPreviewIDEALBankBunq ConfirmationTokenPaymentMethodPreviewIDEALBank = "bunq" + ConfirmationTokenPaymentMethodPreviewIDEALBankBuut ConfirmationTokenPaymentMethodPreviewIDEALBank = "buut" + ConfirmationTokenPaymentMethodPreviewIDEALBankHandelsbanken ConfirmationTokenPaymentMethodPreviewIDEALBank = "handelsbanken" + ConfirmationTokenPaymentMethodPreviewIDEALBankIng ConfirmationTokenPaymentMethodPreviewIDEALBank = "ing" + ConfirmationTokenPaymentMethodPreviewIDEALBankKnab ConfirmationTokenPaymentMethodPreviewIDEALBank = "knab" + ConfirmationTokenPaymentMethodPreviewIDEALBankMoneyou ConfirmationTokenPaymentMethodPreviewIDEALBank = "moneyou" + ConfirmationTokenPaymentMethodPreviewIDEALBankN26 ConfirmationTokenPaymentMethodPreviewIDEALBank = "n26" + ConfirmationTokenPaymentMethodPreviewIDEALBankNn ConfirmationTokenPaymentMethodPreviewIDEALBank = "nn" + ConfirmationTokenPaymentMethodPreviewIDEALBankRabobank ConfirmationTokenPaymentMethodPreviewIDEALBank = "rabobank" + ConfirmationTokenPaymentMethodPreviewIDEALBankRegiobank ConfirmationTokenPaymentMethodPreviewIDEALBank = "regiobank" + ConfirmationTokenPaymentMethodPreviewIDEALBankRevolut ConfirmationTokenPaymentMethodPreviewIDEALBank = "revolut" + ConfirmationTokenPaymentMethodPreviewIDEALBankSnsBank ConfirmationTokenPaymentMethodPreviewIDEALBank = "sns_bank" + ConfirmationTokenPaymentMethodPreviewIDEALBankTriodosBank ConfirmationTokenPaymentMethodPreviewIDEALBank = "triodos_bank" + ConfirmationTokenPaymentMethodPreviewIDEALBankVanLanschot ConfirmationTokenPaymentMethodPreviewIDEALBank = "van_lanschot" + ConfirmationTokenPaymentMethodPreviewIDEALBankYoursafe ConfirmationTokenPaymentMethodPreviewIDEALBank = "yoursafe" +) + +// The Bank Identifier Code of the customer's bank, if the bank was provided. +type ConfirmationTokenPaymentMethodPreviewIDEALBIC string + +// List of values that ConfirmationTokenPaymentMethodPreviewIDEALBIC can take +const ( + ConfirmationTokenPaymentMethodPreviewIDEALBICABNANL2A ConfirmationTokenPaymentMethodPreviewIDEALBIC = "ABNANL2A" + ConfirmationTokenPaymentMethodPreviewIDEALBICASNBNL21 ConfirmationTokenPaymentMethodPreviewIDEALBIC = "ASNBNL21" + ConfirmationTokenPaymentMethodPreviewIDEALBICBITSNL2A ConfirmationTokenPaymentMethodPreviewIDEALBIC = "BITSNL2A" + ConfirmationTokenPaymentMethodPreviewIDEALBICBUNQNL2A ConfirmationTokenPaymentMethodPreviewIDEALBIC = "BUNQNL2A" + ConfirmationTokenPaymentMethodPreviewIDEALBICBUUTNL2A ConfirmationTokenPaymentMethodPreviewIDEALBIC = "BUUTNL2A" + ConfirmationTokenPaymentMethodPreviewIDEALBICFVLBNL22 ConfirmationTokenPaymentMethodPreviewIDEALBIC = "FVLBNL22" + ConfirmationTokenPaymentMethodPreviewIDEALBICHANDNL2A ConfirmationTokenPaymentMethodPreviewIDEALBIC = "HANDNL2A" + ConfirmationTokenPaymentMethodPreviewIDEALBICINGBNL2A ConfirmationTokenPaymentMethodPreviewIDEALBIC = "INGBNL2A" + ConfirmationTokenPaymentMethodPreviewIDEALBICKNABNL2H ConfirmationTokenPaymentMethodPreviewIDEALBIC = "KNABNL2H" + ConfirmationTokenPaymentMethodPreviewIDEALBICMOYONL21 ConfirmationTokenPaymentMethodPreviewIDEALBIC = "MOYONL21" + ConfirmationTokenPaymentMethodPreviewIDEALBICNNBANL2G ConfirmationTokenPaymentMethodPreviewIDEALBIC = "NNBANL2G" + ConfirmationTokenPaymentMethodPreviewIDEALBICNTSBDEB1 ConfirmationTokenPaymentMethodPreviewIDEALBIC = "NTSBDEB1" + ConfirmationTokenPaymentMethodPreviewIDEALBICRABONL2U ConfirmationTokenPaymentMethodPreviewIDEALBIC = "RABONL2U" + ConfirmationTokenPaymentMethodPreviewIDEALBICRBRBNL21 ConfirmationTokenPaymentMethodPreviewIDEALBIC = "RBRBNL21" + ConfirmationTokenPaymentMethodPreviewIDEALBICREVOIE23 ConfirmationTokenPaymentMethodPreviewIDEALBIC = "REVOIE23" + ConfirmationTokenPaymentMethodPreviewIDEALBICREVOLT21 ConfirmationTokenPaymentMethodPreviewIDEALBIC = "REVOLT21" + ConfirmationTokenPaymentMethodPreviewIDEALBICSNSBNL2A ConfirmationTokenPaymentMethodPreviewIDEALBIC = "SNSBNL2A" + ConfirmationTokenPaymentMethodPreviewIDEALBICTRIONL2U ConfirmationTokenPaymentMethodPreviewIDEALBIC = "TRIONL2U" +) + +// How card details were read in this transaction. +type ConfirmationTokenPaymentMethodPreviewInteracPresentReadMethod string + +// List of values that ConfirmationTokenPaymentMethodPreviewInteracPresentReadMethod can take +const ( + ConfirmationTokenPaymentMethodPreviewInteracPresentReadMethodContactEmv ConfirmationTokenPaymentMethodPreviewInteracPresentReadMethod = "contact_emv" + ConfirmationTokenPaymentMethodPreviewInteracPresentReadMethodContactlessEmv ConfirmationTokenPaymentMethodPreviewInteracPresentReadMethod = "contactless_emv" + ConfirmationTokenPaymentMethodPreviewInteracPresentReadMethodContactlessMagstripeMode ConfirmationTokenPaymentMethodPreviewInteracPresentReadMethod = "contactless_magstripe_mode" + ConfirmationTokenPaymentMethodPreviewInteracPresentReadMethodMagneticStripeFallback ConfirmationTokenPaymentMethodPreviewInteracPresentReadMethod = "magnetic_stripe_fallback" + ConfirmationTokenPaymentMethodPreviewInteracPresentReadMethodMagneticStripeTrack2 ConfirmationTokenPaymentMethodPreviewInteracPresentReadMethod = "magnetic_stripe_track2" +) + +// The local credit or debit card brand. +type ConfirmationTokenPaymentMethodPreviewKrCardBrand string + +// List of values that ConfirmationTokenPaymentMethodPreviewKrCardBrand can take +const ( + ConfirmationTokenPaymentMethodPreviewKrCardBrandBc ConfirmationTokenPaymentMethodPreviewKrCardBrand = "bc" + ConfirmationTokenPaymentMethodPreviewKrCardBrandCiti ConfirmationTokenPaymentMethodPreviewKrCardBrand = "citi" + ConfirmationTokenPaymentMethodPreviewKrCardBrandHana ConfirmationTokenPaymentMethodPreviewKrCardBrand = "hana" + ConfirmationTokenPaymentMethodPreviewKrCardBrandHyundai ConfirmationTokenPaymentMethodPreviewKrCardBrand = "hyundai" + ConfirmationTokenPaymentMethodPreviewKrCardBrandJeju ConfirmationTokenPaymentMethodPreviewKrCardBrand = "jeju" + ConfirmationTokenPaymentMethodPreviewKrCardBrandJeonbuk ConfirmationTokenPaymentMethodPreviewKrCardBrand = "jeonbuk" + ConfirmationTokenPaymentMethodPreviewKrCardBrandKakaobank ConfirmationTokenPaymentMethodPreviewKrCardBrand = "kakaobank" + ConfirmationTokenPaymentMethodPreviewKrCardBrandKbank ConfirmationTokenPaymentMethodPreviewKrCardBrand = "kbank" + ConfirmationTokenPaymentMethodPreviewKrCardBrandKdbbank ConfirmationTokenPaymentMethodPreviewKrCardBrand = "kdbbank" + ConfirmationTokenPaymentMethodPreviewKrCardBrandKookmin ConfirmationTokenPaymentMethodPreviewKrCardBrand = "kookmin" + ConfirmationTokenPaymentMethodPreviewKrCardBrandKwangju ConfirmationTokenPaymentMethodPreviewKrCardBrand = "kwangju" + ConfirmationTokenPaymentMethodPreviewKrCardBrandLotte ConfirmationTokenPaymentMethodPreviewKrCardBrand = "lotte" + ConfirmationTokenPaymentMethodPreviewKrCardBrandMg ConfirmationTokenPaymentMethodPreviewKrCardBrand = "mg" + ConfirmationTokenPaymentMethodPreviewKrCardBrandNh ConfirmationTokenPaymentMethodPreviewKrCardBrand = "nh" + ConfirmationTokenPaymentMethodPreviewKrCardBrandPost ConfirmationTokenPaymentMethodPreviewKrCardBrand = "post" + ConfirmationTokenPaymentMethodPreviewKrCardBrandSamsung ConfirmationTokenPaymentMethodPreviewKrCardBrand = "samsung" + ConfirmationTokenPaymentMethodPreviewKrCardBrandSavingsbank ConfirmationTokenPaymentMethodPreviewKrCardBrand = "savingsbank" + ConfirmationTokenPaymentMethodPreviewKrCardBrandShinhan ConfirmationTokenPaymentMethodPreviewKrCardBrand = "shinhan" + ConfirmationTokenPaymentMethodPreviewKrCardBrandShinhyup ConfirmationTokenPaymentMethodPreviewKrCardBrand = "shinhyup" + ConfirmationTokenPaymentMethodPreviewKrCardBrandSuhyup ConfirmationTokenPaymentMethodPreviewKrCardBrand = "suhyup" + ConfirmationTokenPaymentMethodPreviewKrCardBrandTossbank ConfirmationTokenPaymentMethodPreviewKrCardBrand = "tossbank" + ConfirmationTokenPaymentMethodPreviewKrCardBrandWoori ConfirmationTokenPaymentMethodPreviewKrCardBrand = "woori" +) + +// Whether to fund this transaction with Naver Pay points or a card. +type ConfirmationTokenPaymentMethodPreviewNaverPayFunding string + +// List of values that ConfirmationTokenPaymentMethodPreviewNaverPayFunding can take +const ( + ConfirmationTokenPaymentMethodPreviewNaverPayFundingCard ConfirmationTokenPaymentMethodPreviewNaverPayFunding = "card" + ConfirmationTokenPaymentMethodPreviewNaverPayFundingPoints ConfirmationTokenPaymentMethodPreviewNaverPayFunding = "points" +) + +// The customer's bank, if provided. +type ConfirmationTokenPaymentMethodPreviewP24Bank string + +// List of values that ConfirmationTokenPaymentMethodPreviewP24Bank can take +const ( + ConfirmationTokenPaymentMethodPreviewP24BankAliorBank ConfirmationTokenPaymentMethodPreviewP24Bank = "alior_bank" + ConfirmationTokenPaymentMethodPreviewP24BankBankMillennium ConfirmationTokenPaymentMethodPreviewP24Bank = "bank_millennium" + ConfirmationTokenPaymentMethodPreviewP24BankBankNowyBfgSa ConfirmationTokenPaymentMethodPreviewP24Bank = "bank_nowy_bfg_sa" + ConfirmationTokenPaymentMethodPreviewP24BankBankPekaoSa ConfirmationTokenPaymentMethodPreviewP24Bank = "bank_pekao_sa" + ConfirmationTokenPaymentMethodPreviewP24BankBankiSpbdzielcze ConfirmationTokenPaymentMethodPreviewP24Bank = "banki_spbdzielcze" + ConfirmationTokenPaymentMethodPreviewP24BankBLIK ConfirmationTokenPaymentMethodPreviewP24Bank = "blik" + ConfirmationTokenPaymentMethodPreviewP24BankBnpParibas ConfirmationTokenPaymentMethodPreviewP24Bank = "bnp_paribas" + ConfirmationTokenPaymentMethodPreviewP24BankBoz ConfirmationTokenPaymentMethodPreviewP24Bank = "boz" + ConfirmationTokenPaymentMethodPreviewP24BankCitiHandlowy ConfirmationTokenPaymentMethodPreviewP24Bank = "citi_handlowy" + ConfirmationTokenPaymentMethodPreviewP24BankCreditAgricole ConfirmationTokenPaymentMethodPreviewP24Bank = "credit_agricole" + ConfirmationTokenPaymentMethodPreviewP24BankEnvelobank ConfirmationTokenPaymentMethodPreviewP24Bank = "envelobank" + ConfirmationTokenPaymentMethodPreviewP24BankEtransferPocztowy24 ConfirmationTokenPaymentMethodPreviewP24Bank = "etransfer_pocztowy24" + ConfirmationTokenPaymentMethodPreviewP24BankGetinBank ConfirmationTokenPaymentMethodPreviewP24Bank = "getin_bank" + ConfirmationTokenPaymentMethodPreviewP24BankIdeabank ConfirmationTokenPaymentMethodPreviewP24Bank = "ideabank" + ConfirmationTokenPaymentMethodPreviewP24BankIng ConfirmationTokenPaymentMethodPreviewP24Bank = "ing" + ConfirmationTokenPaymentMethodPreviewP24BankInteligo ConfirmationTokenPaymentMethodPreviewP24Bank = "inteligo" + ConfirmationTokenPaymentMethodPreviewP24BankMbankMtransfer ConfirmationTokenPaymentMethodPreviewP24Bank = "mbank_mtransfer" + ConfirmationTokenPaymentMethodPreviewP24BankNestPrzelew ConfirmationTokenPaymentMethodPreviewP24Bank = "nest_przelew" + ConfirmationTokenPaymentMethodPreviewP24BankNoblePay ConfirmationTokenPaymentMethodPreviewP24Bank = "noble_pay" + ConfirmationTokenPaymentMethodPreviewP24BankPbacZIpko ConfirmationTokenPaymentMethodPreviewP24Bank = "pbac_z_ipko" + ConfirmationTokenPaymentMethodPreviewP24BankPlusBank ConfirmationTokenPaymentMethodPreviewP24Bank = "plus_bank" + ConfirmationTokenPaymentMethodPreviewP24BankSantanderPrzelew24 ConfirmationTokenPaymentMethodPreviewP24Bank = "santander_przelew24" + ConfirmationTokenPaymentMethodPreviewP24BankTmobileUsbugiBankowe ConfirmationTokenPaymentMethodPreviewP24Bank = "tmobile_usbugi_bankowe" + ConfirmationTokenPaymentMethodPreviewP24BankToyotaBank ConfirmationTokenPaymentMethodPreviewP24Bank = "toyota_bank" + ConfirmationTokenPaymentMethodPreviewP24BankVelobank ConfirmationTokenPaymentMethodPreviewP24Bank = "velobank" + ConfirmationTokenPaymentMethodPreviewP24BankVolkswagenBank ConfirmationTokenPaymentMethodPreviewP24Bank = "volkswagen_bank" +) + +// The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. +type ConfirmationTokenPaymentMethodPreviewType string + +// List of values that ConfirmationTokenPaymentMethodPreviewType can take +const ( + ConfirmationTokenPaymentMethodPreviewTypeACSSDebit ConfirmationTokenPaymentMethodPreviewType = "acss_debit" + ConfirmationTokenPaymentMethodPreviewTypeAffirm ConfirmationTokenPaymentMethodPreviewType = "affirm" + ConfirmationTokenPaymentMethodPreviewTypeAfterpayClearpay ConfirmationTokenPaymentMethodPreviewType = "afterpay_clearpay" + ConfirmationTokenPaymentMethodPreviewTypeAlipay ConfirmationTokenPaymentMethodPreviewType = "alipay" + ConfirmationTokenPaymentMethodPreviewTypeAlma ConfirmationTokenPaymentMethodPreviewType = "alma" + ConfirmationTokenPaymentMethodPreviewTypeAmazonPay ConfirmationTokenPaymentMethodPreviewType = "amazon_pay" + ConfirmationTokenPaymentMethodPreviewTypeAUBECSDebit ConfirmationTokenPaymentMethodPreviewType = "au_becs_debit" + ConfirmationTokenPaymentMethodPreviewTypeBACSDebit ConfirmationTokenPaymentMethodPreviewType = "bacs_debit" + ConfirmationTokenPaymentMethodPreviewTypeBancontact ConfirmationTokenPaymentMethodPreviewType = "bancontact" + ConfirmationTokenPaymentMethodPreviewTypeBillie ConfirmationTokenPaymentMethodPreviewType = "billie" + ConfirmationTokenPaymentMethodPreviewTypeBLIK ConfirmationTokenPaymentMethodPreviewType = "blik" + ConfirmationTokenPaymentMethodPreviewTypeBoleto ConfirmationTokenPaymentMethodPreviewType = "boleto" + ConfirmationTokenPaymentMethodPreviewTypeCard ConfirmationTokenPaymentMethodPreviewType = "card" + ConfirmationTokenPaymentMethodPreviewTypeCardPresent ConfirmationTokenPaymentMethodPreviewType = "card_present" + ConfirmationTokenPaymentMethodPreviewTypeCashApp ConfirmationTokenPaymentMethodPreviewType = "cashapp" + ConfirmationTokenPaymentMethodPreviewTypeCrypto ConfirmationTokenPaymentMethodPreviewType = "crypto" + ConfirmationTokenPaymentMethodPreviewTypeCustomerBalance ConfirmationTokenPaymentMethodPreviewType = "customer_balance" + ConfirmationTokenPaymentMethodPreviewTypeEPS ConfirmationTokenPaymentMethodPreviewType = "eps" + ConfirmationTokenPaymentMethodPreviewTypeFPX ConfirmationTokenPaymentMethodPreviewType = "fpx" + ConfirmationTokenPaymentMethodPreviewTypeGiropay ConfirmationTokenPaymentMethodPreviewType = "giropay" + ConfirmationTokenPaymentMethodPreviewTypeGrabpay ConfirmationTokenPaymentMethodPreviewType = "grabpay" + ConfirmationTokenPaymentMethodPreviewTypeIDEAL ConfirmationTokenPaymentMethodPreviewType = "ideal" + ConfirmationTokenPaymentMethodPreviewTypeInteracPresent ConfirmationTokenPaymentMethodPreviewType = "interac_present" + ConfirmationTokenPaymentMethodPreviewTypeKakaoPay ConfirmationTokenPaymentMethodPreviewType = "kakao_pay" + ConfirmationTokenPaymentMethodPreviewTypeKlarna ConfirmationTokenPaymentMethodPreviewType = "klarna" + ConfirmationTokenPaymentMethodPreviewTypeKonbini ConfirmationTokenPaymentMethodPreviewType = "konbini" + ConfirmationTokenPaymentMethodPreviewTypeKrCard ConfirmationTokenPaymentMethodPreviewType = "kr_card" + ConfirmationTokenPaymentMethodPreviewTypeLink ConfirmationTokenPaymentMethodPreviewType = "link" + ConfirmationTokenPaymentMethodPreviewTypeMobilepay ConfirmationTokenPaymentMethodPreviewType = "mobilepay" + ConfirmationTokenPaymentMethodPreviewTypeMultibanco ConfirmationTokenPaymentMethodPreviewType = "multibanco" + ConfirmationTokenPaymentMethodPreviewTypeNaverPay ConfirmationTokenPaymentMethodPreviewType = "naver_pay" + ConfirmationTokenPaymentMethodPreviewTypeNzBankAccount ConfirmationTokenPaymentMethodPreviewType = "nz_bank_account" + ConfirmationTokenPaymentMethodPreviewTypeOXXO ConfirmationTokenPaymentMethodPreviewType = "oxxo" + ConfirmationTokenPaymentMethodPreviewTypeP24 ConfirmationTokenPaymentMethodPreviewType = "p24" + ConfirmationTokenPaymentMethodPreviewTypePayByBank ConfirmationTokenPaymentMethodPreviewType = "pay_by_bank" + ConfirmationTokenPaymentMethodPreviewTypePayco ConfirmationTokenPaymentMethodPreviewType = "payco" + ConfirmationTokenPaymentMethodPreviewTypePayNow ConfirmationTokenPaymentMethodPreviewType = "paynow" + ConfirmationTokenPaymentMethodPreviewTypePaypal ConfirmationTokenPaymentMethodPreviewType = "paypal" + ConfirmationTokenPaymentMethodPreviewTypePix ConfirmationTokenPaymentMethodPreviewType = "pix" + ConfirmationTokenPaymentMethodPreviewTypePromptPay ConfirmationTokenPaymentMethodPreviewType = "promptpay" + ConfirmationTokenPaymentMethodPreviewTypeRevolutPay ConfirmationTokenPaymentMethodPreviewType = "revolut_pay" + ConfirmationTokenPaymentMethodPreviewTypeSamsungPay ConfirmationTokenPaymentMethodPreviewType = "samsung_pay" + ConfirmationTokenPaymentMethodPreviewTypeSatispay ConfirmationTokenPaymentMethodPreviewType = "satispay" + ConfirmationTokenPaymentMethodPreviewTypeSEPADebit ConfirmationTokenPaymentMethodPreviewType = "sepa_debit" + ConfirmationTokenPaymentMethodPreviewTypeSofort ConfirmationTokenPaymentMethodPreviewType = "sofort" + ConfirmationTokenPaymentMethodPreviewTypeSwish ConfirmationTokenPaymentMethodPreviewType = "swish" + ConfirmationTokenPaymentMethodPreviewTypeTWINT ConfirmationTokenPaymentMethodPreviewType = "twint" + ConfirmationTokenPaymentMethodPreviewTypeUSBankAccount ConfirmationTokenPaymentMethodPreviewType = "us_bank_account" + ConfirmationTokenPaymentMethodPreviewTypeWeChatPay ConfirmationTokenPaymentMethodPreviewType = "wechat_pay" + ConfirmationTokenPaymentMethodPreviewTypeZip ConfirmationTokenPaymentMethodPreviewType = "zip" +) + +// Account holder type: individual or company. +type ConfirmationTokenPaymentMethodPreviewUSBankAccountAccountHolderType string + +// List of values that ConfirmationTokenPaymentMethodPreviewUSBankAccountAccountHolderType can take +const ( + ConfirmationTokenPaymentMethodPreviewUSBankAccountAccountHolderTypeCompany ConfirmationTokenPaymentMethodPreviewUSBankAccountAccountHolderType = "company" + ConfirmationTokenPaymentMethodPreviewUSBankAccountAccountHolderTypeIndividual ConfirmationTokenPaymentMethodPreviewUSBankAccountAccountHolderType = "individual" +) + +// Account type: checkings or savings. Defaults to checking if omitted. +type ConfirmationTokenPaymentMethodPreviewUSBankAccountAccountType string + +// List of values that ConfirmationTokenPaymentMethodPreviewUSBankAccountAccountType can take +const ( + ConfirmationTokenPaymentMethodPreviewUSBankAccountAccountTypeChecking ConfirmationTokenPaymentMethodPreviewUSBankAccountAccountType = "checking" + ConfirmationTokenPaymentMethodPreviewUSBankAccountAccountTypeSavings ConfirmationTokenPaymentMethodPreviewUSBankAccountAccountType = "savings" +) + +// All supported networks. +type ConfirmationTokenPaymentMethodPreviewUSBankAccountNetworksSupported string + +// List of values that ConfirmationTokenPaymentMethodPreviewUSBankAccountNetworksSupported can take +const ( + ConfirmationTokenPaymentMethodPreviewUSBankAccountNetworksSupportedACH ConfirmationTokenPaymentMethodPreviewUSBankAccountNetworksSupported = "ach" + ConfirmationTokenPaymentMethodPreviewUSBankAccountNetworksSupportedUSDomesticWire ConfirmationTokenPaymentMethodPreviewUSBankAccountNetworksSupported = "us_domestic_wire" +) + +// The ACH network code that resulted in this block. +type ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode string + +// List of values that ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode can take +const ( + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCodeR02 ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode = "R02" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCodeR03 ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode = "R03" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCodeR04 ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode = "R04" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCodeR05 ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode = "R05" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCodeR07 ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode = "R07" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCodeR08 ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode = "R08" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCodeR10 ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode = "R10" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCodeR11 ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode = "R11" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCodeR16 ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode = "R16" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCodeR20 ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode = "R20" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCodeR29 ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode = "R29" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCodeR31 ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode = "R31" +) + +// The reason why this PaymentMethod's fingerprint has been blocked +type ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReason string + +// List of values that ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReason can take +const ( + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReasonBankAccountClosed ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReason = "bank_account_closed" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReasonBankAccountFrozen ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReason = "bank_account_frozen" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReasonBankAccountInvalidDetails ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReason = "bank_account_invalid_details" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReasonBankAccountRestricted ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReason = "bank_account_restricted" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReasonBankAccountUnusable ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReason = "bank_account_unusable" + ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReasonDebitNotAuthorized ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReason = "debit_not_authorized" +) + +// Indicates that you intend to make future payments with this ConfirmationToken's payment method. +// +// The presence of this property will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. +type ConfirmationTokenSetupFutureUsage string + +// List of values that ConfirmationTokenSetupFutureUsage can take +const ( + ConfirmationTokenSetupFutureUsageOffSession ConfirmationTokenSetupFutureUsage = "off_session" + ConfirmationTokenSetupFutureUsageOnSession ConfirmationTokenSetupFutureUsage = "on_session" +) + +// Retrieves an existing ConfirmationToken object +type ConfirmationTokenParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ConfirmationTokenParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves an existing ConfirmationToken object +type ConfirmationTokenRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ConfirmationTokenRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// If this is a Mandate accepted online, this hash contains details about the online acceptance. +type ConfirmationTokenMandateDataCustomerAcceptanceOnline struct { + // The IP address from which the Mandate was accepted by the customer. + IPAddress string `json:"ip_address"` + // The user agent of the browser from which the Mandate was accepted by the customer. + UserAgent string `json:"user_agent"` +} + +// This hash contains details about the customer acceptance of the Mandate. +type ConfirmationTokenMandateDataCustomerAcceptance struct { + // If this is a Mandate accepted online, this hash contains details about the online acceptance. + Online *ConfirmationTokenMandateDataCustomerAcceptanceOnline `json:"online"` + // The type of customer acceptance information included with the Mandate. + Type string `json:"type"` +} + +// Data used for generating a Mandate. +type ConfirmationTokenMandateData struct { + // This hash contains details about the customer acceptance of the Mandate. + CustomerAcceptance *ConfirmationTokenMandateDataCustomerAcceptance `json:"customer_acceptance"` +} +type ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlan struct { + // For `fixed_count` installment plans, this is the number of installment payments your customer will make to their credit card. + Count int64 `json:"count"` + // For `fixed_count` installment plans, this is the interval between installment payments your customer will make to their credit card. + // One of `month`. + Interval ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanInterval `json:"interval"` + // Type of installment plan, one of `fixed_count`, `bonus`, or `revolving`. + Type ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanType `json:"type"` +} + +// Installment configuration for payments. +type ConfirmationTokenPaymentMethodOptionsCardInstallments struct { + Plan *ConfirmationTokenPaymentMethodOptionsCardInstallmentsPlan `json:"plan"` +} + +// This hash contains the card payment method options. +type ConfirmationTokenPaymentMethodOptionsCard struct { + // The `cvc_update` Token collected from the Payment Element. + CVCToken string `json:"cvc_token"` + // Installment configuration for payments. + Installments *ConfirmationTokenPaymentMethodOptionsCardInstallments `json:"installments"` +} + +// Payment-method-specific configuration for this ConfirmationToken. +type ConfirmationTokenPaymentMethodOptions struct { + // This hash contains the card payment method options. + Card *ConfirmationTokenPaymentMethodOptionsCard `json:"card"` +} +type ConfirmationTokenPaymentMethodPreviewACSSDebit struct { + // Name of the bank associated with the bank account. + BankName string `json:"bank_name"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Institution number of the bank account. + InstitutionNumber string `json:"institution_number"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // Transit number of the bank account. + TransitNumber string `json:"transit_number"` +} +type ConfirmationTokenPaymentMethodPreviewAffirm struct{} +type ConfirmationTokenPaymentMethodPreviewAfterpayClearpay struct{} +type ConfirmationTokenPaymentMethodPreviewAlipay struct{} +type ConfirmationTokenPaymentMethodPreviewAlma struct{} +type ConfirmationTokenPaymentMethodPreviewAmazonPay struct{} +type ConfirmationTokenPaymentMethodPreviewAUBECSDebit struct { + // Six-digit number identifying bank and branch associated with this bank account. + BSBNumber string `json:"bsb_number"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` +} +type ConfirmationTokenPaymentMethodPreviewBACSDebit struct { + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // Sort code of the bank account. (e.g., `10-20-30`) + SortCode string `json:"sort_code"` +} +type ConfirmationTokenPaymentMethodPreviewBancontact struct{} +type ConfirmationTokenPaymentMethodPreviewBillie struct{} +type ConfirmationTokenPaymentMethodPreviewBillingDetails struct { + // Billing address. + Address *Address `json:"address"` + // Email address. + Email string `json:"email"` + // Full name. + Name string `json:"name"` + // Billing phone number (including extension). + Phone string `json:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID string `json:"tax_id"` +} +type ConfirmationTokenPaymentMethodPreviewBLIK struct{} +type ConfirmationTokenPaymentMethodPreviewBoleto struct { + // Uniquely identifies the customer tax id (CNPJ or CPF) + TaxID string `json:"tax_id"` +} + +// Checks on Card address and CVC if provided. +type ConfirmationTokenPaymentMethodPreviewCardChecks struct { + // If a address line1 was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + AddressLine1Check string `json:"address_line1_check"` + // If a address postal code was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + AddressPostalCodeCheck string `json:"address_postal_code_check"` + // If a CVC was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + CVCCheck string `json:"cvc_check"` +} + +// Details about payments collected offline. +type ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentOffline struct { + // Time at which the payment was collected while offline + StoredAt int64 `json:"stored_at"` + // The method used to process this payment method offline. Only deferred is allowed. + Type ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentOfflineType `json:"type"` +} + +// A collection of fields required to be displayed on receipts. Only required for EMV transactions. +type ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReceipt struct { + // The type of account being debited or credited + AccountType ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountType `json:"account_type"` + // The Application Cryptogram, a unique value generated by the card to authenticate the transaction with issuers. + ApplicationCryptogram string `json:"application_cryptogram"` + // The Application Identifier (AID) on the card used to determine which networks are eligible to process the transaction. Referenced from EMV tag 9F12, data encoded on the card's chip. + ApplicationPreferredName string `json:"application_preferred_name"` + // Identifier for this transaction. + AuthorizationCode string `json:"authorization_code"` + // EMV tag 8A. A code returned by the card issuer. + AuthorizationResponseCode string `json:"authorization_response_code"` + // Describes the method used by the cardholder to verify ownership of the card. One of the following: `approval`, `failure`, `none`, `offline_pin`, `offline_pin_and_signature`, `online_pin`, or `signature`. + CardholderVerificationMethod string `json:"cardholder_verification_method"` + // Similar to the application_preferred_name, identifying the applications (AIDs) available on the card. Referenced from EMV tag 84. + DedicatedFileName string `json:"dedicated_file_name"` + // A 5-byte string that records the checks and validations that occur between the card and the terminal. These checks determine how the terminal processes the transaction and what risk tolerance is acceptable. Referenced from EMV Tag 95. + TerminalVerificationResults string `json:"terminal_verification_results"` + // An indication of which steps were completed during the card read process. Referenced from EMV Tag 9B. + TransactionStatusInformation string `json:"transaction_status_information"` +} +type ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentWallet struct { + // The type of mobile wallet, one of `apple_pay`, `google_pay`, `samsung_pay`, or `unknown`. + Type ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentWalletType `json:"type"` +} +type ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresent struct { + // The authorized amount + AmountAuthorized int64 `json:"amount_authorized"` + // Card brand. Can be `amex`, `diners`, `discover`, `eftpos_au`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Brand string `json:"brand"` + // The [product code](https://stripe.com/docs/card-product-codes) that identifies the specific program or product associated with a card. + BrandProduct string `json:"brand_product"` + // When using manual capture, a future timestamp after which the charge will be automatically refunded if uncaptured. + CaptureBefore int64 `json:"capture_before"` + // The cardholder name as read from the card, in [ISO 7813](https://en.wikipedia.org/wiki/ISO/IEC_7813) format. May include alphanumeric characters, special characters and first/last name separator (`/`). In some cases, the cardholder name may not be available depending on how the issuer has configured the card. Cardholder name is typically not available on swipe or contactless payments, such as those made with Apple Pay and Google Pay. + CardholderName string `json:"cardholder_name"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // A high-level description of the type of cards issued in this range. (For internal use only and not typically available in standard API requests.) + Description string `json:"description"` + // Authorization response cryptogram. + EmvAuthData string `json:"emv_auth_data"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + // Uniquely identifies this particular card number. You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + // + // *As of May 1, 2021, card fingerprint in India for Connect changed to allow two fingerprints for the same card---one for India and one for the rest of the world.* + Fingerprint string `json:"fingerprint"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding string `json:"funding"` + // ID of a card PaymentMethod generated from the card_present PaymentMethod that may be attached to a Customer for future transactions. Only present if it was possible to generate a card PaymentMethod. + GeneratedCard string `json:"generated_card"` + // Issuer identification number of the card. (For internal use only and not typically available in standard API requests.) + IIN string `json:"iin"` + // Whether this [PaymentIntent](https://stripe.com/docs/api/payment_intents) is eligible for incremental authorizations. Request support using [request_incremental_authorization_support](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-payment_method_options-card_present-request_incremental_authorization_support). + IncrementalAuthorizationSupported bool `json:"incremental_authorization_supported"` + // The name of the card's issuing bank. (For internal use only and not typically available in standard API requests.) + Issuer string `json:"issuer"` + // The last four digits of the card. + Last4 string `json:"last4"` + // Identifies which network this charge was processed on. Can be `amex`, `cartes_bancaires`, `diners`, `discover`, `eftpos_au`, `interac`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Network string `json:"network"` + // This is used by the financial networks to identify a transaction. Visa calls this the Transaction ID, Mastercard calls this the Trace ID, and American Express calls this the Acquirer Reference Data. This value will be present if it is returned by the financial network in the authorization response, and null otherwise. + NetworkTransactionID string `json:"network_transaction_id"` + // Details about payments collected offline. + Offline *ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentOffline `json:"offline"` + // Defines whether the authorized amount can be over-captured or not + OvercaptureSupported bool `json:"overcapture_supported"` + // The languages that the issuing bank recommends using for localizing any customer-facing text, as read from the card. Referenced from EMV tag 5F2D, data encoded on the card's chip. + PreferredLocales []string `json:"preferred_locales"` + // How card details were read in this transaction. + ReadMethod ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod `json:"read_method"` + // A collection of fields required to be displayed on receipts. Only required for EMV transactions. + Receipt *ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentReceipt `json:"receipt"` + Wallet *ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresentWallet `json:"wallet"` +} + +// Transaction-specific details of the payment method used in the payment. +type ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetails struct { + CardPresent *ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetailsCardPresent `json:"card_present"` + // The type of payment method transaction-specific details from the transaction that generated this `card` payment method. Always `card_present`. + Type string `json:"type"` +} + +// Details of the original PaymentMethod that created this object. +type ConfirmationTokenPaymentMethodPreviewCardGeneratedFrom struct { + // The charge that created this object. + Charge string `json:"charge"` + // Transaction-specific details of the payment method used in the payment. + PaymentMethodDetails *ConfirmationTokenPaymentMethodPreviewCardGeneratedFromPaymentMethodDetails `json:"payment_method_details"` + // The ID of the SetupAttempt that generated this PaymentMethod, if any. + SetupAttempt *SetupAttempt `json:"setup_attempt"` +} + +// Contains information about card networks that can be used to process the payment. +type ConfirmationTokenPaymentMethodPreviewCardNetworks struct { + // All networks available for selection via [payment_method_options.card.network](https://docs.stripe.com/api/payment_intents/confirm#confirm_payment_intent-payment_method_options-card-network). + Available []string `json:"available"` + // The preferred network for co-branded cards. Can be `cartes_bancaires`, `mastercard`, `visa` or `invalid_preference` if requested network is not valid for the card. + Preferred string `json:"preferred"` +} + +// Contains details on how this Card may be used for 3D Secure authentication. +type ConfirmationTokenPaymentMethodPreviewCardThreeDSecureUsage struct { + // Whether 3D Secure is supported on this card. + Supported bool `json:"supported"` +} +type ConfirmationTokenPaymentMethodPreviewCardWalletAmexExpressCheckout struct{} +type ConfirmationTokenPaymentMethodPreviewCardWalletApplePay struct{} +type ConfirmationTokenPaymentMethodPreviewCardWalletGooglePay struct{} +type ConfirmationTokenPaymentMethodPreviewCardWalletLink struct{} +type ConfirmationTokenPaymentMethodPreviewCardWalletMasterpass struct { + // Owner's verified billing address. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + BillingAddress *Address `json:"billing_address"` + // Owner's verified email. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Email string `json:"email"` + // Owner's verified full name. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Name string `json:"name"` + // Owner's verified shipping address. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + ShippingAddress *Address `json:"shipping_address"` +} +type ConfirmationTokenPaymentMethodPreviewCardWalletSamsungPay struct{} +type ConfirmationTokenPaymentMethodPreviewCardWalletVisaCheckout struct { + // Owner's verified billing address. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + BillingAddress *Address `json:"billing_address"` + // Owner's verified email. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Email string `json:"email"` + // Owner's verified full name. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Name string `json:"name"` + // Owner's verified shipping address. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + ShippingAddress *Address `json:"shipping_address"` +} + +// If this Card is part of a card wallet, this contains the details of the card wallet. +type ConfirmationTokenPaymentMethodPreviewCardWallet struct { + AmexExpressCheckout *ConfirmationTokenPaymentMethodPreviewCardWalletAmexExpressCheckout `json:"amex_express_checkout"` + ApplePay *ConfirmationTokenPaymentMethodPreviewCardWalletApplePay `json:"apple_pay"` + // (For tokenized numbers only.) The last four digits of the device account number. + DynamicLast4 string `json:"dynamic_last4"` + GooglePay *ConfirmationTokenPaymentMethodPreviewCardWalletGooglePay `json:"google_pay"` + Link *ConfirmationTokenPaymentMethodPreviewCardWalletLink `json:"link"` + Masterpass *ConfirmationTokenPaymentMethodPreviewCardWalletMasterpass `json:"masterpass"` + SamsungPay *ConfirmationTokenPaymentMethodPreviewCardWalletSamsungPay `json:"samsung_pay"` + // The type of the card wallet, one of `amex_express_checkout`, `apple_pay`, `google_pay`, `masterpass`, `samsung_pay`, `visa_checkout`, or `link`. An additional hash is included on the Wallet subhash with a name matching this value. It contains additional information specific to the card wallet type. + Type ConfirmationTokenPaymentMethodPreviewCardWalletType `json:"type"` + VisaCheckout *ConfirmationTokenPaymentMethodPreviewCardWalletVisaCheckout `json:"visa_checkout"` +} +type ConfirmationTokenPaymentMethodPreviewCard struct { + // Card brand. Can be `amex`, `diners`, `discover`, `eftpos_au`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Brand string `json:"brand"` + // Checks on Card address and CVC if provided. + Checks *ConfirmationTokenPaymentMethodPreviewCardChecks `json:"checks"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // A high-level description of the type of cards issued in this range. (For internal use only and not typically available in standard API requests.) + Description string `json:"description"` + // The brand to use when displaying the card, this accounts for customer's brand choice on dual-branded cards. Can be `american_express`, `cartes_bancaires`, `diners_club`, `discover`, `eftpos_australia`, `interac`, `jcb`, `mastercard`, `union_pay`, `visa`, or `other` and may contain more values in the future. + DisplayBrand string `json:"display_brand"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + // Uniquely identifies this particular card number. You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + // + // *As of May 1, 2021, card fingerprint in India for Connect changed to allow two fingerprints for the same card---one for India and one for the rest of the world.* + Fingerprint string `json:"fingerprint"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding string `json:"funding"` + // Details of the original PaymentMethod that created this object. + GeneratedFrom *ConfirmationTokenPaymentMethodPreviewCardGeneratedFrom `json:"generated_from"` + // Issuer identification number of the card. (For internal use only and not typically available in standard API requests.) + IIN string `json:"iin"` + // The name of the card's issuing bank. (For internal use only and not typically available in standard API requests.) + Issuer string `json:"issuer"` + // The last four digits of the card. + Last4 string `json:"last4"` + // Contains information about card networks that can be used to process the payment. + Networks *ConfirmationTokenPaymentMethodPreviewCardNetworks `json:"networks"` + // Status of a card based on the card issuer. + RegulatedStatus ConfirmationTokenPaymentMethodPreviewCardRegulatedStatus `json:"regulated_status"` + // Contains details on how this Card may be used for 3D Secure authentication. + ThreeDSecureUsage *ConfirmationTokenPaymentMethodPreviewCardThreeDSecureUsage `json:"three_d_secure_usage"` + // If this Card is part of a card wallet, this contains the details of the card wallet. + Wallet *ConfirmationTokenPaymentMethodPreviewCardWallet `json:"wallet"` +} + +// Contains information about card networks that can be used to process the payment. +type ConfirmationTokenPaymentMethodPreviewCardPresentNetworks struct { + // All networks available for selection via [payment_method_options.card.network](https://docs.stripe.com/api/payment_intents/confirm#confirm_payment_intent-payment_method_options-card-network). + Available []string `json:"available"` + // The preferred network for the card. + Preferred string `json:"preferred"` +} + +// Details about payment methods collected offline. +type ConfirmationTokenPaymentMethodPreviewCardPresentOffline struct { + // Time at which the payment was collected while offline + StoredAt int64 `json:"stored_at"` + // The method used to process this payment method offline. Only deferred is allowed. + Type ConfirmationTokenPaymentMethodPreviewCardPresentOfflineType `json:"type"` +} +type ConfirmationTokenPaymentMethodPreviewCardPresentWallet struct { + // The type of mobile wallet, one of `apple_pay`, `google_pay`, `samsung_pay`, or `unknown`. + Type ConfirmationTokenPaymentMethodPreviewCardPresentWalletType `json:"type"` +} +type ConfirmationTokenPaymentMethodPreviewCardPresent struct { + // Card brand. Can be `amex`, `diners`, `discover`, `eftpos_au`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Brand string `json:"brand"` + // The [product code](https://stripe.com/docs/card-product-codes) that identifies the specific program or product associated with a card. + BrandProduct string `json:"brand_product"` + // The cardholder name as read from the card, in [ISO 7813](https://en.wikipedia.org/wiki/ISO/IEC_7813) format. May include alphanumeric characters, special characters and first/last name separator (`/`). In some cases, the cardholder name may not be available depending on how the issuer has configured the card. Cardholder name is typically not available on swipe or contactless payments, such as those made with Apple Pay and Google Pay. + CardholderName string `json:"cardholder_name"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // A high-level description of the type of cards issued in this range. (For internal use only and not typically available in standard API requests.) + Description string `json:"description"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + // Uniquely identifies this particular card number. You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + // + // *As of May 1, 2021, card fingerprint in India for Connect changed to allow two fingerprints for the same card---one for India and one for the rest of the world.* + Fingerprint string `json:"fingerprint"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding string `json:"funding"` + // Issuer identification number of the card. (For internal use only and not typically available in standard API requests.) + IIN string `json:"iin"` + // The name of the card's issuing bank. (For internal use only and not typically available in standard API requests.) + Issuer string `json:"issuer"` + // The last four digits of the card. + Last4 string `json:"last4"` + // Contains information about card networks that can be used to process the payment. + Networks *ConfirmationTokenPaymentMethodPreviewCardPresentNetworks `json:"networks"` + // Details about payment methods collected offline. + Offline *ConfirmationTokenPaymentMethodPreviewCardPresentOffline `json:"offline"` + // The languages that the issuing bank recommends using for localizing any customer-facing text, as read from the card. Referenced from EMV tag 5F2D, data encoded on the card's chip. + PreferredLocales []string `json:"preferred_locales"` + // How card details were read in this transaction. + ReadMethod ConfirmationTokenPaymentMethodPreviewCardPresentReadMethod `json:"read_method"` + Wallet *ConfirmationTokenPaymentMethodPreviewCardPresentWallet `json:"wallet"` +} +type ConfirmationTokenPaymentMethodPreviewCashApp struct { + // A unique and immutable identifier assigned by Cash App to every buyer. + BuyerID string `json:"buyer_id"` + // A public identifier for buyers using Cash App. + Cashtag string `json:"cashtag"` +} +type ConfirmationTokenPaymentMethodPreviewCrypto struct{} +type ConfirmationTokenPaymentMethodPreviewCustomerBalance struct{} +type ConfirmationTokenPaymentMethodPreviewEPS struct { + // The customer's bank. Should be one of `arzte_und_apotheker_bank`, `austrian_anadi_bank_ag`, `bank_austria`, `bankhaus_carl_spangler`, `bankhaus_schelhammer_und_schattera_ag`, `bawag_psk_ag`, `bks_bank_ag`, `brull_kallmus_bank_ag`, `btv_vier_lander_bank`, `capital_bank_grawe_gruppe_ag`, `deutsche_bank_ag`, `dolomitenbank`, `easybank_ag`, `erste_bank_und_sparkassen`, `hypo_alpeadriabank_international_ag`, `hypo_noe_lb_fur_niederosterreich_u_wien`, `hypo_oberosterreich_salzburg_steiermark`, `hypo_tirol_bank_ag`, `hypo_vorarlberg_bank_ag`, `hypo_bank_burgenland_aktiengesellschaft`, `marchfelder_bank`, `oberbank_ag`, `raiffeisen_bankengruppe_osterreich`, `schoellerbank_ag`, `sparda_bank_wien`, `volksbank_gruppe`, `volkskreditbank_ag`, or `vr_bank_braunau`. + Bank ConfirmationTokenPaymentMethodPreviewEPSBank `json:"bank"` +} +type ConfirmationTokenPaymentMethodPreviewFPX struct { + // Account holder type, if provided. Can be one of `individual` or `company`. + AccountHolderType ConfirmationTokenPaymentMethodPreviewFPXAccountHolderType `json:"account_holder_type"` + // The customer's bank, if provided. Can be one of `affin_bank`, `agrobank`, `alliance_bank`, `ambank`, `bank_islam`, `bank_muamalat`, `bank_rakyat`, `bsn`, `cimb`, `hong_leong_bank`, `hsbc`, `kfh`, `maybank2u`, `ocbc`, `public_bank`, `rhb`, `standard_chartered`, `uob`, `deutsche_bank`, `maybank2e`, `pb_enterprise`, or `bank_of_china`. + Bank ConfirmationTokenPaymentMethodPreviewFPXBank `json:"bank"` +} +type ConfirmationTokenPaymentMethodPreviewGiropay struct{} +type ConfirmationTokenPaymentMethodPreviewGrabpay struct{} +type ConfirmationTokenPaymentMethodPreviewIDEAL struct { + // The customer's bank, if provided. Can be one of `abn_amro`, `asn_bank`, `bunq`, `buut`, `handelsbanken`, `ing`, `knab`, `moneyou`, `n26`, `nn`, `rabobank`, `regiobank`, `revolut`, `sns_bank`, `triodos_bank`, `van_lanschot`, or `yoursafe`. + Bank ConfirmationTokenPaymentMethodPreviewIDEALBank `json:"bank"` + // The Bank Identifier Code of the customer's bank, if the bank was provided. + BIC ConfirmationTokenPaymentMethodPreviewIDEALBIC `json:"bic"` +} + +// Contains information about card networks that can be used to process the payment. +type ConfirmationTokenPaymentMethodPreviewInteracPresentNetworks struct { + // All networks available for selection via [payment_method_options.card.network](https://docs.stripe.com/api/payment_intents/confirm#confirm_payment_intent-payment_method_options-card-network). + Available []string `json:"available"` + // The preferred network for the card. + Preferred string `json:"preferred"` +} +type ConfirmationTokenPaymentMethodPreviewInteracPresent struct { + // Card brand. Can be `interac`, `mastercard` or `visa`. + Brand string `json:"brand"` + // The cardholder name as read from the card, in [ISO 7813](https://en.wikipedia.org/wiki/ISO/IEC_7813) format. May include alphanumeric characters, special characters and first/last name separator (`/`). In some cases, the cardholder name may not be available depending on how the issuer has configured the card. Cardholder name is typically not available on swipe or contactless payments, such as those made with Apple Pay and Google Pay. + CardholderName string `json:"cardholder_name"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // A high-level description of the type of cards issued in this range. (For internal use only and not typically available in standard API requests.) + Description string `json:"description"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + // Uniquely identifies this particular card number. You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + // + // *As of May 1, 2021, card fingerprint in India for Connect changed to allow two fingerprints for the same card---one for India and one for the rest of the world.* + Fingerprint string `json:"fingerprint"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding string `json:"funding"` + // Issuer identification number of the card. (For internal use only and not typically available in standard API requests.) + IIN string `json:"iin"` + // The name of the card's issuing bank. (For internal use only and not typically available in standard API requests.) + Issuer string `json:"issuer"` + // The last four digits of the card. + Last4 string `json:"last4"` + // Contains information about card networks that can be used to process the payment. + Networks *ConfirmationTokenPaymentMethodPreviewInteracPresentNetworks `json:"networks"` + // The languages that the issuing bank recommends using for localizing any customer-facing text, as read from the card. Referenced from EMV tag 5F2D, data encoded on the card's chip. + PreferredLocales []string `json:"preferred_locales"` + // How card details were read in this transaction. + ReadMethod ConfirmationTokenPaymentMethodPreviewInteracPresentReadMethod `json:"read_method"` +} +type ConfirmationTokenPaymentMethodPreviewKakaoPay struct{} + +// The customer's date of birth, if provided. +type ConfirmationTokenPaymentMethodPreviewKlarnaDOB struct { + // The day of birth, between 1 and 31. + Day int64 `json:"day"` + // The month of birth, between 1 and 12. + Month int64 `json:"month"` + // The four-digit year of birth. + Year int64 `json:"year"` +} +type ConfirmationTokenPaymentMethodPreviewKlarna struct { + // The customer's date of birth, if provided. + DOB *ConfirmationTokenPaymentMethodPreviewKlarnaDOB `json:"dob"` +} +type ConfirmationTokenPaymentMethodPreviewKonbini struct{} +type ConfirmationTokenPaymentMethodPreviewKrCard struct { + // The local credit or debit card brand. + Brand ConfirmationTokenPaymentMethodPreviewKrCardBrand `json:"brand"` + // The last four digits of the card. This may not be present for American Express cards. + Last4 string `json:"last4"` +} +type ConfirmationTokenPaymentMethodPreviewLink struct { + // Account owner's email address. + Email string `json:"email"` + // [Deprecated] This is a legacy parameter that no longer has any function. + // Deprecated: + PersistentToken string `json:"persistent_token"` +} +type ConfirmationTokenPaymentMethodPreviewMobilepay struct{} +type ConfirmationTokenPaymentMethodPreviewMultibanco struct{} +type ConfirmationTokenPaymentMethodPreviewNaverPay struct { + // Uniquely identifies this particular Naver Pay account. You can use this attribute to check whether two Naver Pay accounts are the same. + BuyerID string `json:"buyer_id"` + // Whether to fund this transaction with Naver Pay points or a card. + Funding ConfirmationTokenPaymentMethodPreviewNaverPayFunding `json:"funding"` +} +type ConfirmationTokenPaymentMethodPreviewNzBankAccount struct { + // The name on the bank account. Only present if the account holder name is different from the name of the authorized signatory collected in the PaymentMethod's billing details. + AccountHolderName string `json:"account_holder_name"` + // The numeric code for the bank account's bank. + BankCode string `json:"bank_code"` + // The name of the bank. + BankName string `json:"bank_name"` + // The numeric code for the bank account's bank branch. + BranchCode string `json:"branch_code"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // The suffix of the bank account number. + Suffix string `json:"suffix"` +} +type ConfirmationTokenPaymentMethodPreviewOXXO struct{} +type ConfirmationTokenPaymentMethodPreviewP24 struct { + // The customer's bank, if provided. + Bank ConfirmationTokenPaymentMethodPreviewP24Bank `json:"bank"` +} +type ConfirmationTokenPaymentMethodPreviewPayByBank struct{} +type ConfirmationTokenPaymentMethodPreviewPayco struct{} +type ConfirmationTokenPaymentMethodPreviewPayNow struct{} +type ConfirmationTokenPaymentMethodPreviewPaypal struct { + // Two-letter ISO code representing the buyer's country. Values are provided by PayPal directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Country string `json:"country"` + // Owner's email. Values are provided by PayPal directly + // (if supported) at the time of authorization or settlement. They cannot be set or mutated. + PayerEmail string `json:"payer_email"` + // PayPal account PayerID. This identifier uniquely identifies the PayPal customer. + PayerID string `json:"payer_id"` +} +type ConfirmationTokenPaymentMethodPreviewPix struct{} +type ConfirmationTokenPaymentMethodPreviewPromptPay struct{} +type ConfirmationTokenPaymentMethodPreviewRevolutPay struct{} +type ConfirmationTokenPaymentMethodPreviewSamsungPay struct{} +type ConfirmationTokenPaymentMethodPreviewSatispay struct{} + +// Information about the object that generated this PaymentMethod. +type ConfirmationTokenPaymentMethodPreviewSEPADebitGeneratedFrom struct { + // The ID of the Charge that generated this PaymentMethod, if any. + Charge *Charge `json:"charge"` + // The ID of the SetupAttempt that generated this PaymentMethod, if any. + SetupAttempt *SetupAttempt `json:"setup_attempt"` +} +type ConfirmationTokenPaymentMethodPreviewSEPADebit struct { + // Bank code of bank associated with the bank account. + BankCode string `json:"bank_code"` + // Branch code of bank associated with the bank account. + BranchCode string `json:"branch_code"` + // Two-letter ISO code representing the country the bank account is located in. + Country string `json:"country"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Information about the object that generated this PaymentMethod. + GeneratedFrom *ConfirmationTokenPaymentMethodPreviewSEPADebitGeneratedFrom `json:"generated_from"` + // Last four characters of the IBAN. + Last4 string `json:"last4"` +} +type ConfirmationTokenPaymentMethodPreviewSofort struct { + // Two-letter ISO code representing the country the bank account is located in. + Country string `json:"country"` +} +type ConfirmationTokenPaymentMethodPreviewSwish struct{} +type ConfirmationTokenPaymentMethodPreviewTWINT struct{} + +// Contains information about US bank account networks that can be used. +type ConfirmationTokenPaymentMethodPreviewUSBankAccountNetworks struct { + // The preferred network. + Preferred string `json:"preferred"` + // All supported networks. + Supported []ConfirmationTokenPaymentMethodPreviewUSBankAccountNetworksSupported `json:"supported"` +} +type ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlocked struct { + // The ACH network code that resulted in this block. + NetworkCode ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedNetworkCode `json:"network_code"` + // The reason why this PaymentMethod's fingerprint has been blocked + Reason ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlockedReason `json:"reason"` +} + +// Contains information about the future reusability of this PaymentMethod. +type ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetails struct { + Blocked *ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetailsBlocked `json:"blocked"` +} +type ConfirmationTokenPaymentMethodPreviewUSBankAccount struct { + // Account holder type: individual or company. + AccountHolderType ConfirmationTokenPaymentMethodPreviewUSBankAccountAccountHolderType `json:"account_holder_type"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType ConfirmationTokenPaymentMethodPreviewUSBankAccountAccountType `json:"account_type"` + // The name of the bank. + BankName string `json:"bank_name"` + // The ID of the Financial Connections Account used to create the payment method. + FinancialConnectionsAccount string `json:"financial_connections_account"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // Contains information about US bank account networks that can be used. + Networks *ConfirmationTokenPaymentMethodPreviewUSBankAccountNetworks `json:"networks"` + // Routing number of the bank account. + RoutingNumber string `json:"routing_number"` + // Contains information about the future reusability of this PaymentMethod. + StatusDetails *ConfirmationTokenPaymentMethodPreviewUSBankAccountStatusDetails `json:"status_details"` +} +type ConfirmationTokenPaymentMethodPreviewWeChatPay struct{} +type ConfirmationTokenPaymentMethodPreviewZip struct{} + +// Payment details collected by the Payment Element, used to create a PaymentMethod when a PaymentIntent or SetupIntent is confirmed with this ConfirmationToken. +type ConfirmationTokenPaymentMethodPreview struct { + ACSSDebit *ConfirmationTokenPaymentMethodPreviewACSSDebit `json:"acss_debit"` + Affirm *ConfirmationTokenPaymentMethodPreviewAffirm `json:"affirm"` + AfterpayClearpay *ConfirmationTokenPaymentMethodPreviewAfterpayClearpay `json:"afterpay_clearpay"` + Alipay *ConfirmationTokenPaymentMethodPreviewAlipay `json:"alipay"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to “unspecified”. + AllowRedisplay ConfirmationTokenPaymentMethodPreviewAllowRedisplay `json:"allow_redisplay"` + Alma *ConfirmationTokenPaymentMethodPreviewAlma `json:"alma"` + AmazonPay *ConfirmationTokenPaymentMethodPreviewAmazonPay `json:"amazon_pay"` + AUBECSDebit *ConfirmationTokenPaymentMethodPreviewAUBECSDebit `json:"au_becs_debit"` + BACSDebit *ConfirmationTokenPaymentMethodPreviewBACSDebit `json:"bacs_debit"` + Bancontact *ConfirmationTokenPaymentMethodPreviewBancontact `json:"bancontact"` + Billie *ConfirmationTokenPaymentMethodPreviewBillie `json:"billie"` + BillingDetails *ConfirmationTokenPaymentMethodPreviewBillingDetails `json:"billing_details"` + BLIK *ConfirmationTokenPaymentMethodPreviewBLIK `json:"blik"` + Boleto *ConfirmationTokenPaymentMethodPreviewBoleto `json:"boleto"` + Card *ConfirmationTokenPaymentMethodPreviewCard `json:"card"` + CardPresent *ConfirmationTokenPaymentMethodPreviewCardPresent `json:"card_present"` + CashApp *ConfirmationTokenPaymentMethodPreviewCashApp `json:"cashapp"` + Crypto *ConfirmationTokenPaymentMethodPreviewCrypto `json:"crypto"` + // The ID of the Customer to which this PaymentMethod is saved. This will not be set when the PaymentMethod has not been saved to a Customer. + Customer *Customer `json:"customer"` + CustomerBalance *ConfirmationTokenPaymentMethodPreviewCustomerBalance `json:"customer_balance"` + EPS *ConfirmationTokenPaymentMethodPreviewEPS `json:"eps"` + FPX *ConfirmationTokenPaymentMethodPreviewFPX `json:"fpx"` + Giropay *ConfirmationTokenPaymentMethodPreviewGiropay `json:"giropay"` + Grabpay *ConfirmationTokenPaymentMethodPreviewGrabpay `json:"grabpay"` + IDEAL *ConfirmationTokenPaymentMethodPreviewIDEAL `json:"ideal"` + InteracPresent *ConfirmationTokenPaymentMethodPreviewInteracPresent `json:"interac_present"` + KakaoPay *ConfirmationTokenPaymentMethodPreviewKakaoPay `json:"kakao_pay"` + Klarna *ConfirmationTokenPaymentMethodPreviewKlarna `json:"klarna"` + Konbini *ConfirmationTokenPaymentMethodPreviewKonbini `json:"konbini"` + KrCard *ConfirmationTokenPaymentMethodPreviewKrCard `json:"kr_card"` + Link *ConfirmationTokenPaymentMethodPreviewLink `json:"link"` + Mobilepay *ConfirmationTokenPaymentMethodPreviewMobilepay `json:"mobilepay"` + Multibanco *ConfirmationTokenPaymentMethodPreviewMultibanco `json:"multibanco"` + NaverPay *ConfirmationTokenPaymentMethodPreviewNaverPay `json:"naver_pay"` + NzBankAccount *ConfirmationTokenPaymentMethodPreviewNzBankAccount `json:"nz_bank_account"` + OXXO *ConfirmationTokenPaymentMethodPreviewOXXO `json:"oxxo"` + P24 *ConfirmationTokenPaymentMethodPreviewP24 `json:"p24"` + PayByBank *ConfirmationTokenPaymentMethodPreviewPayByBank `json:"pay_by_bank"` + Payco *ConfirmationTokenPaymentMethodPreviewPayco `json:"payco"` + PayNow *ConfirmationTokenPaymentMethodPreviewPayNow `json:"paynow"` + Paypal *ConfirmationTokenPaymentMethodPreviewPaypal `json:"paypal"` + Pix *ConfirmationTokenPaymentMethodPreviewPix `json:"pix"` + PromptPay *ConfirmationTokenPaymentMethodPreviewPromptPay `json:"promptpay"` + RevolutPay *ConfirmationTokenPaymentMethodPreviewRevolutPay `json:"revolut_pay"` + SamsungPay *ConfirmationTokenPaymentMethodPreviewSamsungPay `json:"samsung_pay"` + Satispay *ConfirmationTokenPaymentMethodPreviewSatispay `json:"satispay"` + SEPADebit *ConfirmationTokenPaymentMethodPreviewSEPADebit `json:"sepa_debit"` + Sofort *ConfirmationTokenPaymentMethodPreviewSofort `json:"sofort"` + Swish *ConfirmationTokenPaymentMethodPreviewSwish `json:"swish"` + TWINT *ConfirmationTokenPaymentMethodPreviewTWINT `json:"twint"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type ConfirmationTokenPaymentMethodPreviewType `json:"type"` + USBankAccount *ConfirmationTokenPaymentMethodPreviewUSBankAccount `json:"us_bank_account"` + WeChatPay *ConfirmationTokenPaymentMethodPreviewWeChatPay `json:"wechat_pay"` + Zip *ConfirmationTokenPaymentMethodPreviewZip `json:"zip"` +} + +// Shipping information collected on this ConfirmationToken. +type ConfirmationTokenShipping struct { + Address *Address `json:"address"` + // Recipient name. + Name string `json:"name"` + // Recipient phone (including extension). + Phone string `json:"phone"` +} + +// ConfirmationTokens help transport client side data collected by Stripe JS over +// to your server for confirming a PaymentIntent or SetupIntent. If the confirmation +// is successful, values present on the ConfirmationToken are written onto the Intent. +// +// To learn more about how to use ConfirmationToken, visit the related guides: +// - [Finalize payments on the server](https://stripe.com/docs/payments/finalize-payments-on-the-server) +// - [Build two-step confirmation](https://stripe.com/docs/payments/build-a-two-step-confirmation). +type ConfirmationToken struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Time at which this ConfirmationToken expires and can no longer be used to confirm a PaymentIntent or SetupIntent. + ExpiresAt int64 `json:"expires_at"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Data used for generating a Mandate. + MandateData *ConfirmationTokenMandateData `json:"mandate_data"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // ID of the PaymentIntent that this ConfirmationToken was used to confirm, or null if this ConfirmationToken has not yet been used. + PaymentIntent string `json:"payment_intent"` + // Payment-method-specific configuration for this ConfirmationToken. + PaymentMethodOptions *ConfirmationTokenPaymentMethodOptions `json:"payment_method_options"` + // Payment details collected by the Payment Element, used to create a PaymentMethod when a PaymentIntent or SetupIntent is confirmed with this ConfirmationToken. + PaymentMethodPreview *ConfirmationTokenPaymentMethodPreview `json:"payment_method_preview"` + // Return URL used to confirm the Intent. + ReturnURL string `json:"return_url"` + // Indicates that you intend to make future payments with this ConfirmationToken's payment method. + // + // The presence of this property will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. + SetupFutureUsage ConfirmationTokenSetupFutureUsage `json:"setup_future_usage"` + // ID of the SetupIntent that this ConfirmationToken was used to confirm, or null if this ConfirmationToken has not yet been used. + SetupIntent string `json:"setup_intent"` + // Shipping information collected on this ConfirmationToken. + Shipping *ConfirmationTokenShipping `json:"shipping"` + // Indicates whether the Stripe SDK is used to handle confirmation flow. Defaults to `true` on ConfirmationToken. + UseStripeSDK bool `json:"use_stripe_sdk"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/confirmationtoken_service.go b/vendor/github.com/stripe/stripe-go/v82/confirmationtoken_service.go new file mode 100644 index 00000000..8f37ef4f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/confirmationtoken_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1ConfirmationTokenService is used to invoke /v1/confirmation_tokens APIs. +type v1ConfirmationTokenService struct { + B Backend + Key string +} + +// Retrieves an existing ConfirmationToken object +func (c v1ConfirmationTokenService) Retrieve(ctx context.Context, id string, params *ConfirmationTokenRetrieveParams) (*ConfirmationToken, error) { + if params == nil { + params = &ConfirmationTokenRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/confirmation_tokens/%s", id) + confirmationtoken := &ConfirmationToken{} + err := c.B.Call(http.MethodGet, path, c.Key, params, confirmationtoken) + return confirmationtoken, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/connectcollectiontransfer.go b/vendor/github.com/stripe/stripe-go/v82/connectcollectiontransfer.go new file mode 100644 index 00000000..4a550012 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/connectcollectiontransfer.go @@ -0,0 +1,43 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +type ConnectCollectionTransfer struct { + // Amount transferred, in cents (or local equivalent). + Amount int64 `json:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // ID of the account that funds are being collected for. + Destination *Account `json:"destination"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} + +// UnmarshalJSON handles deserialization of a ConnectCollectionTransfer. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (c *ConnectCollectionTransfer) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + c.ID = id + return nil + } + + type connectCollectionTransfer ConnectCollectionTransfer + var v connectCollectionTransfer + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *c = ConnectCollectionTransfer(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/countryspec.go b/vendor/github.com/stripe/stripe-go/v82/countryspec.go new file mode 100644 index 00000000..d5a6c056 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/countryspec.go @@ -0,0 +1,85 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Lists all Country Spec objects available in the API. +type CountrySpecListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CountrySpecListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Country is the list of supported countries +type Country string + +// Returns a Country Spec for a given Country code. +type CountrySpecParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CountrySpecParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Returns a Country Spec for a given Country code. +type CountrySpecRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CountrySpecRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// VerificationFieldsList lists the fields needed for an account verification. +// For more details see https://stripe.com/docs/api#country_spec_object-verification_fields. +type VerificationFieldsList struct { + AdditionalFields []string `json:"additional"` + Minimum []string `json:"minimum"` +} + +// Stripe needs to collect certain pieces of information about each account +// created. These requirements can differ depending on the account's country. The +// Country Specs API makes these rules available to your integration. +// +// You can also view the information from this API call as [an online +// guide](https://docs.stripe.com/docs/connect/required-verification-information). +type CountrySpec struct { + APIResource + // The default currency for this country. This applies to both payment methods and bank accounts. + DefaultCurrency Currency `json:"default_currency"` + // Unique identifier for the object. Represented as the ISO country code for this country. + ID string `json:"id"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Currencies that can be accepted in the specific country (for transfers). + SupportedBankAccountCurrencies map[Currency][]Country `json:"supported_bank_account_currencies"` + // Currencies that can be accepted in the specified country (for payments). + SupportedPaymentCurrencies []Currency `json:"supported_payment_currencies"` + // Payment methods available in the specified country. You may need to enable some payment methods (e.g., [ACH](https://stripe.com/docs/ach)) on your account before they appear in this list. The `stripe` payment method refers to [charging through your platform](https://stripe.com/docs/connect/destination-charges). + SupportedPaymentMethods []string `json:"supported_payment_methods"` + // Countries that can accept transfers from the specified country. + SupportedTransferCountries []string `json:"supported_transfer_countries"` + VerificationFields map[AccountBusinessType]*VerificationFieldsList `json:"verification_fields"` +} + +// CountrySpecList is a list of CountrySpecs as retrieved from a list endpoint. +type CountrySpecList struct { + APIResource + ListMeta + Data []*CountrySpec `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/countryspec_service.go b/vendor/github.com/stripe/stripe-go/v82/countryspec_service.go new file mode 100644 index 00000000..01b5e98a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/countryspec_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1CountrySpecService is used to invoke /v1/country_specs APIs. +type v1CountrySpecService struct { + B Backend + Key string +} + +// Returns a Country Spec for a given Country code. +func (c v1CountrySpecService) Retrieve(ctx context.Context, id string, params *CountrySpecRetrieveParams) (*CountrySpec, error) { + if params == nil { + params = &CountrySpecRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/country_specs/%s", id) + countryspec := &CountrySpec{} + err := c.B.Call(http.MethodGet, path, c.Key, params, countryspec) + return countryspec, err +} + +// Lists all Country Spec objects available in the API. +func (c v1CountrySpecService) List(ctx context.Context, listParams *CountrySpecListParams) Seq2[*CountrySpec, error] { + if listParams == nil { + listParams = &CountrySpecListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*CountrySpec, ListContainer, error) { + list := &CountrySpecList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/country_specs", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/coupon.go b/vendor/github.com/stripe/stripe-go/v82/coupon.go new file mode 100644 index 00000000..cab03f47 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/coupon.go @@ -0,0 +1,279 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// One of `forever`, `once`, or `repeating`. Describes how long a customer who applies this coupon will get the discount. +type CouponDuration string + +// List of values that CouponDuration can take +const ( + CouponDurationForever CouponDuration = "forever" + CouponDurationOnce CouponDuration = "once" + CouponDurationRepeating CouponDuration = "repeating" +) + +// You can delete coupons via the [coupon management](https://dashboard.stripe.com/coupons) page of the Stripe dashboard. However, deleting a coupon does not affect any customers who have already applied the coupon; it means that new customers can't redeem the coupon. You can also delete coupons via the API. +type CouponParams struct { + Params `form:"*"` + // A positive integer representing the amount to subtract from an invoice total (required if `percent_off` is not passed). + AmountOff *int64 `form:"amount_off"` + // A hash containing directions for what this Coupon will apply discounts to. + AppliesTo *CouponAppliesToParams `form:"applies_to"` + // Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) of the `amount_off` parameter (required if `amount_off` is passed). + Currency *string `form:"currency"` + // Coupons defined in each available currency option (only supported if the coupon is amount-based). Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*CouponCurrencyOptionsParams `form:"currency_options"` + // Specifies how long the discount will be in effect if used on a subscription. Defaults to `once`. + Duration *string `form:"duration"` + // Required only if `duration` is `repeating`, in which case it must be a positive integer that specifies the number of months the discount will be in effect. + DurationInMonths *int64 `form:"duration_in_months"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Unique string of your choice that will be used to identify this coupon when applying it to a customer. If you don't want to specify a particular code, you can leave the ID blank and we'll generate a random code for you. + ID *string `form:"id"` + // A positive integer specifying the number of times the coupon can be redeemed before it's no longer valid. For example, you might have a 50% off coupon that the first 20 readers of your blog can use. + MaxRedemptions *int64 `form:"max_redemptions"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Name of the coupon displayed to customers on, for instance invoices, or receipts. By default the `id` is shown if `name` is not set. + Name *string `form:"name"` + // A positive float larger than 0, and smaller or equal to 100, that represents the discount the coupon will apply (required if `amount_off` is not passed). + PercentOff *float64 `form:"percent_off"` + // Unix timestamp specifying the last time at which the coupon can be redeemed. After the redeem_by date, the coupon can no longer be applied to new customers. + RedeemBy *int64 `form:"redeem_by"` +} + +// AddExpand appends a new field to expand. +func (p *CouponParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CouponParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Coupons defined in each available currency option (only supported if the coupon is amount-based). Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type CouponCurrencyOptionsParams struct { + // A positive integer representing the amount to subtract from an invoice total. + AmountOff *int64 `form:"amount_off"` +} + +// Returns a list of your coupons. +type CouponListParams struct { + ListParams `form:"*"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + Created *int64 `form:"created"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CouponListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A hash containing directions for what this Coupon will apply discounts to. +type CouponAppliesToParams struct { + // An array of Product IDs that this Coupon will apply to. + Products []*string `form:"products"` +} + +// You can delete coupons via the [coupon management](https://dashboard.stripe.com/coupons) page of the Stripe dashboard. However, deleting a coupon does not affect any customers who have already applied the coupon; it means that new customers can't redeem the coupon. You can also delete coupons via the API. +type CouponDeleteParams struct { + Params `form:"*"` +} + +// Retrieves the coupon with the given ID. +type CouponRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CouponRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Coupons defined in each available currency option (only supported if the coupon is amount-based). Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type CouponUpdateCurrencyOptionsParams struct { + // A positive integer representing the amount to subtract from an invoice total. + AmountOff *int64 `form:"amount_off"` +} + +// Updates the metadata of a coupon. Other coupon details (currency, duration, amount_off) are, by design, not editable. +type CouponUpdateParams struct { + Params `form:"*"` + // Coupons defined in each available currency option (only supported if the coupon is amount-based). Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*CouponUpdateCurrencyOptionsParams `form:"currency_options"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Name of the coupon displayed to customers on, for instance invoices, or receipts. By default the `id` is shown if `name` is not set. + Name *string `form:"name"` +} + +// AddExpand appends a new field to expand. +func (p *CouponUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CouponUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A hash containing directions for what this Coupon will apply discounts to. +type CouponCreateAppliesToParams struct { + // An array of Product IDs that this Coupon will apply to. + Products []*string `form:"products"` +} + +// Coupons defined in each available currency option (only supported if `amount_off` is passed). Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type CouponCreateCurrencyOptionsParams struct { + // A positive integer representing the amount to subtract from an invoice total. + AmountOff *int64 `form:"amount_off"` +} + +// You can create coupons easily via the [coupon management](https://dashboard.stripe.com/coupons) page of the Stripe dashboard. Coupon creation is also accessible via the API if you need to create coupons on the fly. +// +// A coupon has either a percent_off or an amount_off and currency. If you set an amount_off, that amount will be subtracted from any invoice's subtotal. For example, an invoice with a subtotal of 100 will have a final total of 0 if a coupon with an amount_off of 200 is applied to it and an invoice with a subtotal of 300 will have a final total of 100 if a coupon with an amount_off of 200 is applied to it. +type CouponCreateParams struct { + Params `form:"*"` + // A positive integer representing the amount to subtract from an invoice total (required if `percent_off` is not passed). + AmountOff *int64 `form:"amount_off"` + // A hash containing directions for what this Coupon will apply discounts to. + AppliesTo *CouponCreateAppliesToParams `form:"applies_to"` + // Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) of the `amount_off` parameter (required if `amount_off` is passed). + Currency *string `form:"currency"` + // Coupons defined in each available currency option (only supported if `amount_off` is passed). Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*CouponCreateCurrencyOptionsParams `form:"currency_options"` + // Specifies how long the discount will be in effect if used on a subscription. Defaults to `once`. + Duration *string `form:"duration"` + // Required only if `duration` is `repeating`, in which case it must be a positive integer that specifies the number of months the discount will be in effect. + DurationInMonths *int64 `form:"duration_in_months"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Unique string of your choice that will be used to identify this coupon when applying it to a customer. If you don't want to specify a particular code, you can leave the ID blank and we'll generate a random code for you. + ID *string `form:"id"` + // A positive integer specifying the number of times the coupon can be redeemed before it's no longer valid. For example, you might have a 50% off coupon that the first 20 readers of your blog can use. + MaxRedemptions *int64 `form:"max_redemptions"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Name of the coupon displayed to customers on, for instance invoices, or receipts. By default the `id` is shown if `name` is not set. + Name *string `form:"name"` + // A positive float larger than 0, and smaller or equal to 100, that represents the discount the coupon will apply (required if `amount_off` is not passed). + PercentOff *float64 `form:"percent_off"` + // Unix timestamp specifying the last time at which the coupon can be redeemed. After the redeem_by date, the coupon can no longer be applied to new customers. + RedeemBy *int64 `form:"redeem_by"` +} + +// AddExpand appends a new field to expand. +func (p *CouponCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CouponCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +type CouponAppliesTo struct { + // A list of product IDs this coupon applies to + Products []string `json:"products"` +} + +// Coupons defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type CouponCurrencyOptions struct { + // Amount (in the `currency` specified) that will be taken off the subtotal of any invoices for this customer. + AmountOff int64 `json:"amount_off"` +} + +// A coupon contains information about a percent-off or amount-off discount you +// might want to apply to a customer. Coupons may be applied to [subscriptions](https://stripe.com/docs/api#subscriptions), [invoices](https://stripe.com/docs/api#invoices), +// [checkout sessions](https://stripe.com/docs/api/checkout/sessions), [quotes](https://stripe.com/docs/api#quotes), and more. Coupons do not work with conventional one-off [charges](https://stripe.com/docs/api#create_charge) or [payment intents](https://stripe.com/docs/api/payment_intents). +type Coupon struct { + APIResource + // Amount (in the `currency` specified) that will be taken off the subtotal of any invoices for this customer. + AmountOff int64 `json:"amount_off"` + AppliesTo *CouponAppliesTo `json:"applies_to"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // If `amount_off` has been set, the three-letter [ISO code for the currency](https://stripe.com/docs/currencies) of the amount to take off. + Currency Currency `json:"currency"` + // Coupons defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*CouponCurrencyOptions `json:"currency_options"` + Deleted bool `json:"deleted"` + // One of `forever`, `once`, or `repeating`. Describes how long a customer who applies this coupon will get the discount. + Duration CouponDuration `json:"duration"` + // If `duration` is `repeating`, the number of months the coupon applies. Null if coupon `duration` is `forever` or `once`. + DurationInMonths int64 `json:"duration_in_months"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Maximum number of times this coupon can be redeemed, in total, across all customers, before it is no longer valid. + MaxRedemptions int64 `json:"max_redemptions"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // Name of the coupon displayed to customers on for instance invoices or receipts. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Percent that will be taken off the subtotal of any invoices for this customer for the duration of the coupon. For example, a coupon with percent_off of 50 will make a $ (or local equivalent)100 invoice $ (or local equivalent)50 instead. + PercentOff float64 `json:"percent_off"` + // Date after which the coupon can no longer be redeemed. + RedeemBy int64 `json:"redeem_by"` + // Number of times this coupon has been applied to a customer. + TimesRedeemed int64 `json:"times_redeemed"` + // Taking account of the above properties, whether this coupon can still be applied to a customer. + Valid bool `json:"valid"` +} + +// CouponList is a list of Coupons as retrieved from a list endpoint. +type CouponList struct { + APIResource + ListMeta + Data []*Coupon `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Coupon. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (c *Coupon) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + c.ID = id + return nil + } + + type coupon Coupon + var v coupon + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *c = Coupon(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/coupon_service.go b/vendor/github.com/stripe/stripe-go/v82/coupon_service.go new file mode 100644 index 00000000..3767a8a6 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/coupon_service.go @@ -0,0 +1,86 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1CouponService is used to invoke /v1/coupons APIs. +type v1CouponService struct { + B Backend + Key string +} + +// You can create coupons easily via the [coupon management](https://dashboard.stripe.com/coupons) page of the Stripe dashboard. Coupon creation is also accessible via the API if you need to create coupons on the fly. +// +// A coupon has either a percent_off or an amount_off and currency. If you set an amount_off, that amount will be subtracted from any invoice's subtotal. For example, an invoice with a subtotal of 100 will have a final total of 0 if a coupon with an amount_off of 200 is applied to it and an invoice with a subtotal of 300 will have a final total of 100 if a coupon with an amount_off of 200 is applied to it. +func (c v1CouponService) Create(ctx context.Context, params *CouponCreateParams) (*Coupon, error) { + if params == nil { + params = &CouponCreateParams{} + } + params.Context = ctx + coupon := &Coupon{} + err := c.B.Call(http.MethodPost, "/v1/coupons", c.Key, params, coupon) + return coupon, err +} + +// Retrieves the coupon with the given ID. +func (c v1CouponService) Retrieve(ctx context.Context, id string, params *CouponRetrieveParams) (*Coupon, error) { + if params == nil { + params = &CouponRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/coupons/%s", id) + coupon := &Coupon{} + err := c.B.Call(http.MethodGet, path, c.Key, params, coupon) + return coupon, err +} + +// Updates the metadata of a coupon. Other coupon details (currency, duration, amount_off) are, by design, not editable. +func (c v1CouponService) Update(ctx context.Context, id string, params *CouponUpdateParams) (*Coupon, error) { + if params == nil { + params = &CouponUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/coupons/%s", id) + coupon := &Coupon{} + err := c.B.Call(http.MethodPost, path, c.Key, params, coupon) + return coupon, err +} + +// You can delete coupons via the [coupon management](https://dashboard.stripe.com/coupons) page of the Stripe dashboard. However, deleting a coupon does not affect any customers who have already applied the coupon; it means that new customers can't redeem the coupon. You can also delete coupons via the API. +func (c v1CouponService) Delete(ctx context.Context, id string, params *CouponDeleteParams) (*Coupon, error) { + if params == nil { + params = &CouponDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/coupons/%s", id) + coupon := &Coupon{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, coupon) + return coupon, err +} + +// Returns a list of your coupons. +func (c v1CouponService) List(ctx context.Context, listParams *CouponListParams) Seq2[*Coupon, error] { + if listParams == nil { + listParams = &CouponListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Coupon, ListContainer, error) { + list := &CouponList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/coupons", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/creditnote.go b/vendor/github.com/stripe/stripe-go/v82/creditnote.go new file mode 100644 index 00000000..aff9f5a4 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/creditnote.go @@ -0,0 +1,760 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Type of the pretax credit amount referenced. +type CreditNotePretaxCreditAmountType string + +// List of values that CreditNotePretaxCreditAmountType can take +const ( + CreditNotePretaxCreditAmountTypeCreditBalanceTransaction CreditNotePretaxCreditAmountType = "credit_balance_transaction" + CreditNotePretaxCreditAmountTypeDiscount CreditNotePretaxCreditAmountType = "discount" +) + +// Reason for issuing this credit note, one of `duplicate`, `fraudulent`, `order_change`, or `product_unsatisfactory` +type CreditNoteReason string + +// List of values that CreditNoteReason can take +const ( + CreditNoteReasonDuplicate CreditNoteReason = "duplicate" + CreditNoteReasonFraudulent CreditNoteReason = "fraudulent" + CreditNoteReasonOrderChange CreditNoteReason = "order_change" + CreditNoteReasonProductUnsatisfactory CreditNoteReason = "product_unsatisfactory" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type CreditNoteShippingCostTaxTaxabilityReason string + +// List of values that CreditNoteShippingCostTaxTaxabilityReason can take +const ( + CreditNoteShippingCostTaxTaxabilityReasonCustomerExempt CreditNoteShippingCostTaxTaxabilityReason = "customer_exempt" + CreditNoteShippingCostTaxTaxabilityReasonNotCollecting CreditNoteShippingCostTaxTaxabilityReason = "not_collecting" + CreditNoteShippingCostTaxTaxabilityReasonNotSubjectToTax CreditNoteShippingCostTaxTaxabilityReason = "not_subject_to_tax" + CreditNoteShippingCostTaxTaxabilityReasonNotSupported CreditNoteShippingCostTaxTaxabilityReason = "not_supported" + CreditNoteShippingCostTaxTaxabilityReasonPortionProductExempt CreditNoteShippingCostTaxTaxabilityReason = "portion_product_exempt" + CreditNoteShippingCostTaxTaxabilityReasonPortionReducedRated CreditNoteShippingCostTaxTaxabilityReason = "portion_reduced_rated" + CreditNoteShippingCostTaxTaxabilityReasonPortionStandardRated CreditNoteShippingCostTaxTaxabilityReason = "portion_standard_rated" + CreditNoteShippingCostTaxTaxabilityReasonProductExempt CreditNoteShippingCostTaxTaxabilityReason = "product_exempt" + CreditNoteShippingCostTaxTaxabilityReasonProductExemptHoliday CreditNoteShippingCostTaxTaxabilityReason = "product_exempt_holiday" + CreditNoteShippingCostTaxTaxabilityReasonProportionallyRated CreditNoteShippingCostTaxTaxabilityReason = "proportionally_rated" + CreditNoteShippingCostTaxTaxabilityReasonReducedRated CreditNoteShippingCostTaxTaxabilityReason = "reduced_rated" + CreditNoteShippingCostTaxTaxabilityReasonReverseCharge CreditNoteShippingCostTaxTaxabilityReason = "reverse_charge" + CreditNoteShippingCostTaxTaxabilityReasonStandardRated CreditNoteShippingCostTaxTaxabilityReason = "standard_rated" + CreditNoteShippingCostTaxTaxabilityReasonTaxableBasisReduced CreditNoteShippingCostTaxTaxabilityReason = "taxable_basis_reduced" + CreditNoteShippingCostTaxTaxabilityReasonZeroRated CreditNoteShippingCostTaxTaxabilityReason = "zero_rated" +) + +// Status of this credit note, one of `issued` or `void`. Learn more about [voiding credit notes](https://stripe.com/docs/billing/invoices/credit-notes#voiding). +type CreditNoteStatus string + +// List of values that CreditNoteStatus can take +const ( + CreditNoteStatusIssued CreditNoteStatus = "issued" + CreditNoteStatusVoid CreditNoteStatus = "void" +) + +// Whether this tax is inclusive or exclusive. +type CreditNoteTotalTaxTaxBehavior string + +// List of values that CreditNoteTotalTaxTaxBehavior can take +const ( + CreditNoteTotalTaxTaxBehaviorExclusive CreditNoteTotalTaxTaxBehavior = "exclusive" + CreditNoteTotalTaxTaxBehaviorInclusive CreditNoteTotalTaxTaxBehavior = "inclusive" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type CreditNoteTotalTaxTaxabilityReason string + +// List of values that CreditNoteTotalTaxTaxabilityReason can take +const ( + CreditNoteTotalTaxTaxabilityReasonCustomerExempt CreditNoteTotalTaxTaxabilityReason = "customer_exempt" + CreditNoteTotalTaxTaxabilityReasonNotAvailable CreditNoteTotalTaxTaxabilityReason = "not_available" + CreditNoteTotalTaxTaxabilityReasonNotCollecting CreditNoteTotalTaxTaxabilityReason = "not_collecting" + CreditNoteTotalTaxTaxabilityReasonNotSubjectToTax CreditNoteTotalTaxTaxabilityReason = "not_subject_to_tax" + CreditNoteTotalTaxTaxabilityReasonNotSupported CreditNoteTotalTaxTaxabilityReason = "not_supported" + CreditNoteTotalTaxTaxabilityReasonPortionProductExempt CreditNoteTotalTaxTaxabilityReason = "portion_product_exempt" + CreditNoteTotalTaxTaxabilityReasonPortionReducedRated CreditNoteTotalTaxTaxabilityReason = "portion_reduced_rated" + CreditNoteTotalTaxTaxabilityReasonPortionStandardRated CreditNoteTotalTaxTaxabilityReason = "portion_standard_rated" + CreditNoteTotalTaxTaxabilityReasonProductExempt CreditNoteTotalTaxTaxabilityReason = "product_exempt" + CreditNoteTotalTaxTaxabilityReasonProductExemptHoliday CreditNoteTotalTaxTaxabilityReason = "product_exempt_holiday" + CreditNoteTotalTaxTaxabilityReasonProportionallyRated CreditNoteTotalTaxTaxabilityReason = "proportionally_rated" + CreditNoteTotalTaxTaxabilityReasonReducedRated CreditNoteTotalTaxTaxabilityReason = "reduced_rated" + CreditNoteTotalTaxTaxabilityReasonReverseCharge CreditNoteTotalTaxTaxabilityReason = "reverse_charge" + CreditNoteTotalTaxTaxabilityReasonStandardRated CreditNoteTotalTaxTaxabilityReason = "standard_rated" + CreditNoteTotalTaxTaxabilityReasonTaxableBasisReduced CreditNoteTotalTaxTaxabilityReason = "taxable_basis_reduced" + CreditNoteTotalTaxTaxabilityReasonZeroRated CreditNoteTotalTaxTaxabilityReason = "zero_rated" +) + +// The type of tax information. +type CreditNoteTotalTaxType string + +// List of values that CreditNoteTotalTaxType can take +const ( + CreditNoteTotalTaxTypeTaxRateDetails CreditNoteTotalTaxType = "tax_rate_details" +) + +// Type of this credit note, one of `pre_payment` or `post_payment`. A `pre_payment` credit note means it was issued when the invoice was open. A `post_payment` credit note means it was issued when the invoice was paid. +type CreditNoteType string + +// List of values that CreditNoteType can take +const ( + CreditNoteTypeMixed CreditNoteType = "mixed" + CreditNoteTypePostPayment CreditNoteType = "post_payment" + CreditNoteTypePrePayment CreditNoteType = "pre_payment" +) + +// Returns a list of credit notes. +type CreditNoteListParams struct { + ListParams `form:"*"` + // Only return credit notes that were created during the given date interval. + Created *int64 `form:"created"` + // Only return credit notes that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Only return credit notes for the customer specified by this customer ID. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return credit notes for the invoice specified by this invoice ID. + Invoice *string `form:"invoice"` +} + +// AddExpand appends a new field to expand. +func (p *CreditNoteListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A list of up to 10 tax amounts for the credit note line item. Cannot be mixed with `tax_rates`. +type CreditNoteLineTaxAmountParams struct { + // The amount, in cents (or local equivalent), of the tax. + Amount *int64 `form:"amount"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount *int64 `form:"taxable_amount"` + // The id of the tax rate for this tax amount. The tax rate must have been automatically created by Stripe. + TaxRate *string `form:"tax_rate"` +} + +// Line items that make up the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. +type CreditNoteLineParams struct { + // The line item amount to credit. Only valid when `type` is `invoice_line_item`. If invoice is set up with `automatic_tax[enabled]=true`, this amount is tax exclusive + Amount *int64 `form:"amount"` + // The description of the credit note line item. Only valid when the `type` is `custom_line_item`. + Description *string `form:"description"` + // The invoice line item to credit. Only valid when the `type` is `invoice_line_item`. + InvoiceLineItem *string `form:"invoice_line_item"` + // The line item quantity to credit. + Quantity *int64 `form:"quantity"` + // A list of up to 10 tax amounts for the credit note line item. Cannot be mixed with `tax_rates`. + TaxAmounts []*CreditNoteLineTaxAmountParams `form:"tax_amounts"` + // The tax rates which apply to the credit note line item. Only valid when the `type` is `custom_line_item` and cannot be mixed with `tax_amounts`. + TaxRates []*string `form:"tax_rates"` + // Type of the credit note line item, one of `invoice_line_item` or `custom_line_item` + Type *string `form:"type"` + // The integer unit amount in cents (or local equivalent) of the credit note line item. This `unit_amount` will be multiplied by the quantity to get the full amount to credit for this line item. Only valid when `type` is `custom_line_item`. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// Refunds to link to this credit note. +type CreditNoteRefundParams struct { + // Amount of the refund that applies to this credit note, in cents (or local equivalent). Defaults to the entire refund amount. + AmountRefunded *int64 `form:"amount_refunded"` + // ID of an existing refund to link this credit note to. + Refund *string `form:"refund"` +} + +// When shipping_cost contains the shipping_rate from the invoice, the shipping_cost is included in the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. +type CreditNoteShippingCostParams struct { + // The ID of the shipping rate to use for this order. + ShippingRate *string `form:"shipping_rate"` +} + +// Issue a credit note to adjust the amount of a finalized invoice. A credit note will first reduce the invoice's amount_remaining (and amount_due), but not below zero. +// This amount is indicated by the credit note's pre_payment_amount. The excess amount is indicated by post_payment_amount, and it can result in any combination of the following: +// +// Refunds: create a new refund (using refund_amount) or link existing refunds (using refunds). +// Customer balance credit: credit the customer's balance (using credit_amount) which will be automatically applied to their next invoice when it's finalized. +// Outside of Stripe credit: record the amount that is or will be credited outside of Stripe (using out_of_band_amount). +// +// The sum of refunds, customer balance credits, and outside of Stripe credits must equal the post_payment_amount. +// +// You may issue multiple credit notes for an invoice. Each credit note may increment the invoice's pre_payment_credit_notes_amount, +// post_payment_credit_notes_amount, or both, depending on the invoice's amount_remaining at the time of credit note creation. +type CreditNoteParams struct { + Params `form:"*"` + // The integer amount in cents (or local equivalent) representing the total amount of the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. + Amount *int64 `form:"amount"` + // The integer amount in cents (or local equivalent) representing the amount to credit the customer's balance, which will be automatically applied to their next invoice. + CreditAmount *int64 `form:"credit_amount"` + // The date when this credit note is in effect. Same as `created` unless overwritten. When defined, this value replaces the system-generated 'Date of issue' printed on the credit note PDF. + EffectiveAt *int64 `form:"effective_at"` + // Type of email to send to the customer, one of `credit_note` or `none` and the default is `credit_note`. + EmailType *string `form:"email_type"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // ID of the invoice. + Invoice *string `form:"invoice"` + // Line items that make up the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. + Lines []*CreditNoteLineParams `form:"lines"` + // The credit note's memo appears on the credit note PDF. + Memo *string `form:"memo"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The integer amount in cents (or local equivalent) representing the amount that is credited outside of Stripe. + OutOfBandAmount *int64 `form:"out_of_band_amount"` + // Reason for issuing this credit note, one of `duplicate`, `fraudulent`, `order_change`, or `product_unsatisfactory` + Reason *string `form:"reason"` + // The integer amount in cents (or local equivalent) representing the amount to refund. If set, a refund will be created for the charge associated with the invoice. + RefundAmount *int64 `form:"refund_amount"` + // Refunds to link to this credit note. + Refunds []*CreditNoteRefundParams `form:"refunds"` + // When shipping_cost contains the shipping_rate from the invoice, the shipping_cost is included in the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. + ShippingCost *CreditNoteShippingCostParams `form:"shipping_cost"` +} + +// AddExpand appends a new field to expand. +func (p *CreditNoteParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CreditNoteParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A list of up to 10 tax amounts for the credit note line item. Cannot be mixed with `tax_rates`. +type CreditNotePreviewLineTaxAmountParams struct { + // The amount, in cents (or local equivalent), of the tax. + Amount *int64 `form:"amount"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount *int64 `form:"taxable_amount"` + // The id of the tax rate for this tax amount. The tax rate must have been automatically created by Stripe. + TaxRate *string `form:"tax_rate"` +} + +// Line items that make up the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. +type CreditNotePreviewLineParams struct { + // The line item amount to credit. Only valid when `type` is `invoice_line_item`. If invoice is set up with `automatic_tax[enabled]=true`, this amount is tax exclusive + Amount *int64 `form:"amount"` + // The description of the credit note line item. Only valid when the `type` is `custom_line_item`. + Description *string `form:"description"` + // The invoice line item to credit. Only valid when the `type` is `invoice_line_item`. + InvoiceLineItem *string `form:"invoice_line_item"` + // The line item quantity to credit. + Quantity *int64 `form:"quantity"` + // A list of up to 10 tax amounts for the credit note line item. Cannot be mixed with `tax_rates`. + TaxAmounts []*CreditNotePreviewLineTaxAmountParams `form:"tax_amounts"` + // The tax rates which apply to the credit note line item. Only valid when the `type` is `custom_line_item` and cannot be mixed with `tax_amounts`. + TaxRates []*string `form:"tax_rates"` + // Type of the credit note line item, one of `invoice_line_item` or `custom_line_item` + Type *string `form:"type"` + // The integer unit amount in cents (or local equivalent) of the credit note line item. This `unit_amount` will be multiplied by the quantity to get the full amount to credit for this line item. Only valid when `type` is `custom_line_item`. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// Refunds to link to this credit note. +type CreditNotePreviewRefundParams struct { + // Amount of the refund that applies to this credit note, in cents (or local equivalent). Defaults to the entire refund amount. + AmountRefunded *int64 `form:"amount_refunded"` + // ID of an existing refund to link this credit note to. + Refund *string `form:"refund"` +} + +// When shipping_cost contains the shipping_rate from the invoice, the shipping_cost is included in the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. +type CreditNotePreviewShippingCostParams struct { + // The ID of the shipping rate to use for this order. + ShippingRate *string `form:"shipping_rate"` +} + +// Get a preview of a credit note without creating it. +type CreditNotePreviewParams struct { + Params `form:"*"` + // The integer amount in cents (or local equivalent) representing the total amount of the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. + Amount *int64 `form:"amount"` + // The integer amount in cents (or local equivalent) representing the amount to credit the customer's balance, which will be automatically applied to their next invoice. + CreditAmount *int64 `form:"credit_amount"` + // The date when this credit note is in effect. Same as `created` unless overwritten. When defined, this value replaces the system-generated 'Date of issue' printed on the credit note PDF. + EffectiveAt *int64 `form:"effective_at"` + // Type of email to send to the customer, one of `credit_note` or `none` and the default is `credit_note`. + EmailType *string `form:"email_type"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // ID of the invoice. + Invoice *string `form:"invoice"` + // Line items that make up the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. + Lines []*CreditNotePreviewLineParams `form:"lines"` + // The credit note's memo appears on the credit note PDF. + Memo *string `form:"memo"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The integer amount in cents (or local equivalent) representing the amount that is credited outside of Stripe. + OutOfBandAmount *int64 `form:"out_of_band_amount"` + // Reason for issuing this credit note, one of `duplicate`, `fraudulent`, `order_change`, or `product_unsatisfactory` + Reason *string `form:"reason"` + // The integer amount in cents (or local equivalent) representing the amount to refund. If set, a refund will be created for the charge associated with the invoice. + RefundAmount *int64 `form:"refund_amount"` + // Refunds to link to this credit note. + Refunds []*CreditNotePreviewRefundParams `form:"refunds"` + // When shipping_cost contains the shipping_rate from the invoice, the shipping_cost is included in the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. + ShippingCost *CreditNotePreviewShippingCostParams `form:"shipping_cost"` +} + +// AddExpand appends a new field to expand. +func (p *CreditNotePreviewParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CreditNotePreviewParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A list of up to 10 tax amounts for the credit note line item. Cannot be mixed with `tax_rates`. +type CreditNotePreviewLinesLineTaxAmountParams struct { + // The amount, in cents (or local equivalent), of the tax. + Amount *int64 `form:"amount"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount *int64 `form:"taxable_amount"` + // The id of the tax rate for this tax amount. The tax rate must have been automatically created by Stripe. + TaxRate *string `form:"tax_rate"` +} + +// Line items that make up the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. +type CreditNotePreviewLinesLineParams struct { + // The line item amount to credit. Only valid when `type` is `invoice_line_item`. If invoice is set up with `automatic_tax[enabled]=true`, this amount is tax exclusive + Amount *int64 `form:"amount"` + // The description of the credit note line item. Only valid when the `type` is `custom_line_item`. + Description *string `form:"description"` + // The invoice line item to credit. Only valid when the `type` is `invoice_line_item`. + InvoiceLineItem *string `form:"invoice_line_item"` + // The line item quantity to credit. + Quantity *int64 `form:"quantity"` + // A list of up to 10 tax amounts for the credit note line item. Cannot be mixed with `tax_rates`. + TaxAmounts []*CreditNotePreviewLinesLineTaxAmountParams `form:"tax_amounts"` + // The tax rates which apply to the credit note line item. Only valid when the `type` is `custom_line_item` and cannot be mixed with `tax_amounts`. + TaxRates []*string `form:"tax_rates"` + // Type of the credit note line item, one of `invoice_line_item` or `custom_line_item` + Type *string `form:"type"` + // The integer unit amount in cents (or local equivalent) of the credit note line item. This `unit_amount` will be multiplied by the quantity to get the full amount to credit for this line item. Only valid when `type` is `custom_line_item`. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// Refunds to link to this credit note. +type CreditNotePreviewLinesRefundParams struct { + // Amount of the refund that applies to this credit note, in cents (or local equivalent). Defaults to the entire refund amount. + AmountRefunded *int64 `form:"amount_refunded"` + // ID of an existing refund to link this credit note to. + Refund *string `form:"refund"` +} + +// When shipping_cost contains the shipping_rate from the invoice, the shipping_cost is included in the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. +type CreditNotePreviewLinesShippingCostParams struct { + // The ID of the shipping rate to use for this order. + ShippingRate *string `form:"shipping_rate"` +} + +// Line items that make up the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. +type CreditNotePreviewLinesParams struct { + ListParams `form:"*"` + // The integer amount in cents (or local equivalent) representing the total amount of the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. + Amount *int64 `form:"amount"` + // The integer amount in cents (or local equivalent) representing the amount to credit the customer's balance, which will be automatically applied to their next invoice. + CreditAmount *int64 `form:"credit_amount"` + // The date when this credit note is in effect. Same as `created` unless overwritten. When defined, this value replaces the system-generated 'Date of issue' printed on the credit note PDF. + EffectiveAt *int64 `form:"effective_at"` + // Type of email to send to the customer, one of `credit_note` or `none` and the default is `credit_note`. + EmailType *string `form:"email_type"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // ID of the invoice. + Invoice *string `form:"invoice"` + // Line items that make up the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. + Lines []*CreditNotePreviewLinesLineParams `form:"lines"` + // The credit note's memo appears on the credit note PDF. + Memo *string `form:"memo"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The integer amount in cents (or local equivalent) representing the amount that is credited outside of Stripe. + OutOfBandAmount *int64 `form:"out_of_band_amount"` + // Reason for issuing this credit note, one of `duplicate`, `fraudulent`, `order_change`, or `product_unsatisfactory` + Reason *string `form:"reason"` + // The integer amount in cents (or local equivalent) representing the amount to refund. If set, a refund will be created for the charge associated with the invoice. + RefundAmount *int64 `form:"refund_amount"` + // Refunds to link to this credit note. + Refunds []*CreditNotePreviewLinesRefundParams `form:"refunds"` + // When shipping_cost contains the shipping_rate from the invoice, the shipping_cost is included in the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. + ShippingCost *CreditNotePreviewLinesShippingCostParams `form:"shipping_cost"` +} + +// AddExpand appends a new field to expand. +func (p *CreditNotePreviewLinesParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CreditNotePreviewLinesParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Marks a credit note as void. Learn more about [voiding credit notes](https://docs.stripe.com/docs/billing/invoices/credit-notes#voiding). +type CreditNoteVoidCreditNoteParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CreditNoteVoidCreditNoteParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When retrieving a credit note, you'll get a lines property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. +type CreditNoteListLinesParams struct { + ListParams `form:"*"` + CreditNote *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CreditNoteListLinesParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A list of up to 10 tax amounts for the credit note line item. Cannot be mixed with `tax_rates`. +type CreditNoteCreateLineTaxAmountParams struct { + // The amount, in cents (or local equivalent), of the tax. + Amount *int64 `form:"amount"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount *int64 `form:"taxable_amount"` + // The id of the tax rate for this tax amount. The tax rate must have been automatically created by Stripe. + TaxRate *string `form:"tax_rate"` +} + +// Line items that make up the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. +type CreditNoteCreateLineParams struct { + // The line item amount to credit. Only valid when `type` is `invoice_line_item`. If invoice is set up with `automatic_tax[enabled]=true`, this amount is tax exclusive + Amount *int64 `form:"amount"` + // The description of the credit note line item. Only valid when the `type` is `custom_line_item`. + Description *string `form:"description"` + // The invoice line item to credit. Only valid when the `type` is `invoice_line_item`. + InvoiceLineItem *string `form:"invoice_line_item"` + // The line item quantity to credit. + Quantity *int64 `form:"quantity"` + // A list of up to 10 tax amounts for the credit note line item. Cannot be mixed with `tax_rates`. + TaxAmounts []*CreditNoteCreateLineTaxAmountParams `form:"tax_amounts"` + // The tax rates which apply to the credit note line item. Only valid when the `type` is `custom_line_item` and cannot be mixed with `tax_amounts`. + TaxRates []*string `form:"tax_rates"` + // Type of the credit note line item, one of `invoice_line_item` or `custom_line_item` + Type *string `form:"type"` + // The integer unit amount in cents (or local equivalent) of the credit note line item. This `unit_amount` will be multiplied by the quantity to get the full amount to credit for this line item. Only valid when `type` is `custom_line_item`. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// Refunds to link to this credit note. +type CreditNoteCreateRefundParams struct { + // Amount of the refund that applies to this credit note, in cents (or local equivalent). Defaults to the entire refund amount. + AmountRefunded *int64 `form:"amount_refunded"` + // ID of an existing refund to link this credit note to. + Refund *string `form:"refund"` +} + +// When shipping_cost contains the shipping_rate from the invoice, the shipping_cost is included in the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. +type CreditNoteCreateShippingCostParams struct { + // The ID of the shipping rate to use for this order. + ShippingRate *string `form:"shipping_rate"` +} + +// Issue a credit note to adjust the amount of a finalized invoice. A credit note will first reduce the invoice's amount_remaining (and amount_due), but not below zero. +// This amount is indicated by the credit note's pre_payment_amount. The excess amount is indicated by post_payment_amount, and it can result in any combination of the following: +// +// Refunds: create a new refund (using refund_amount) or link existing refunds (using refunds). +// Customer balance credit: credit the customer's balance (using credit_amount) which will be automatically applied to their next invoice when it's finalized. +// Outside of Stripe credit: record the amount that is or will be credited outside of Stripe (using out_of_band_amount). +// +// The sum of refunds, customer balance credits, and outside of Stripe credits must equal the post_payment_amount. +// +// You may issue multiple credit notes for an invoice. Each credit note may increment the invoice's pre_payment_credit_notes_amount, +// post_payment_credit_notes_amount, or both, depending on the invoice's amount_remaining at the time of credit note creation. +type CreditNoteCreateParams struct { + Params `form:"*"` + // The integer amount in cents (or local equivalent) representing the total amount of the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. + Amount *int64 `form:"amount"` + // The integer amount in cents (or local equivalent) representing the amount to credit the customer's balance, which will be automatically applied to their next invoice. + CreditAmount *int64 `form:"credit_amount"` + // The date when this credit note is in effect. Same as `created` unless overwritten. When defined, this value replaces the system-generated 'Date of issue' printed on the credit note PDF. + EffectiveAt *int64 `form:"effective_at"` + // Type of email to send to the customer, one of `credit_note` or `none` and the default is `credit_note`. + EmailType *string `form:"email_type"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // ID of the invoice. + Invoice *string `form:"invoice"` + // Line items that make up the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. + Lines []*CreditNoteCreateLineParams `form:"lines"` + // The credit note's memo appears on the credit note PDF. + Memo *string `form:"memo"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The integer amount in cents (or local equivalent) representing the amount that is credited outside of Stripe. + OutOfBandAmount *int64 `form:"out_of_band_amount"` + // Reason for issuing this credit note, one of `duplicate`, `fraudulent`, `order_change`, or `product_unsatisfactory` + Reason *string `form:"reason"` + // The integer amount in cents (or local equivalent) representing the amount to refund. If set, a refund will be created for the charge associated with the invoice. + RefundAmount *int64 `form:"refund_amount"` + // Refunds to link to this credit note. + Refunds []*CreditNoteCreateRefundParams `form:"refunds"` + // When shipping_cost contains the shipping_rate from the invoice, the shipping_cost is included in the credit note. One of `amount`, `lines`, or `shipping_cost` must be provided. + ShippingCost *CreditNoteCreateShippingCostParams `form:"shipping_cost"` +} + +// AddExpand appends a new field to expand. +func (p *CreditNoteCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CreditNoteCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the credit note object with the given identifier. +type CreditNoteRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CreditNoteRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates an existing credit note. +type CreditNoteUpdateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Credit note memo. + Memo *string `form:"memo"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *CreditNoteUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CreditNoteUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The integer amount in cents (or local equivalent) representing the total amount of discount that was credited. +type CreditNoteDiscountAmount struct { + // The amount, in cents (or local equivalent), of the discount. + Amount int64 `json:"amount"` + // The discount that was applied to get this discount amount. + Discount *Discount `json:"discount"` +} + +// The pretax credit amounts (ex: discount, credit grants, etc) for all line items. +type CreditNotePretaxCreditAmount struct { + // The amount, in cents (or local equivalent), of the pretax credit amount. + Amount int64 `json:"amount"` + // The credit balance transaction that was applied to get this pretax credit amount. + CreditBalanceTransaction *BillingCreditBalanceTransaction `json:"credit_balance_transaction"` + // The discount that was applied to get this pretax credit amount. + Discount *Discount `json:"discount"` + // Type of the pretax credit amount referenced. + Type CreditNotePretaxCreditAmountType `json:"type"` +} + +// Refunds related to this credit note. +type CreditNoteRefund struct { + // Amount of the refund that applies to this credit note, in cents (or local equivalent). + AmountRefunded int64 `json:"amount_refunded"` + // ID of the refund. + Refund *Refund `json:"refund"` +} + +// The taxes applied to the shipping rate. +type CreditNoteShippingCostTax struct { + // Amount of tax applied for this rate. + Amount int64 `json:"amount"` + // Tax rates can be applied to [invoices](https://docs.stripe.com/invoicing/taxes/tax-rates), [subscriptions](https://docs.stripe.com/billing/taxes/tax-rates) and [Checkout Sessions](https://docs.stripe.com/payments/checkout/use-manual-tax-rates) to collect tax. + // + // Related guide: [Tax rates](https://docs.stripe.com/billing/taxes/tax-rates) + Rate *TaxRate `json:"rate"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason CreditNoteShippingCostTaxTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount int64 `json:"taxable_amount"` +} + +// The details of the cost of shipping, including the ShippingRate applied to the invoice. +type CreditNoteShippingCost struct { + // Total shipping cost before any taxes are applied. + AmountSubtotal int64 `json:"amount_subtotal"` + // Total tax amount applied due to shipping costs. If no tax was applied, defaults to 0. + AmountTax int64 `json:"amount_tax"` + // Total shipping cost after taxes are applied. + AmountTotal int64 `json:"amount_total"` + // The ID of the ShippingRate for this invoice. + ShippingRate *ShippingRate `json:"shipping_rate"` + // The taxes applied to the shipping rate. + Taxes []*CreditNoteShippingCostTax `json:"taxes"` +} + +// Additional details about the tax rate. Only present when `type` is `tax_rate_details`. +type CreditNoteTotalTaxTaxRateDetails struct { + TaxRate string `json:"tax_rate"` +} + +// The aggregate tax information for all line items. +type CreditNoteTotalTax struct { + // The amount of the tax, in cents (or local equivalent). + Amount int64 `json:"amount"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason CreditNoteTotalTaxTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount int64 `json:"taxable_amount"` + // Whether this tax is inclusive or exclusive. + TaxBehavior CreditNoteTotalTaxTaxBehavior `json:"tax_behavior"` + // Additional details about the tax rate. Only present when `type` is `tax_rate_details`. + TaxRateDetails *CreditNoteTotalTaxTaxRateDetails `json:"tax_rate_details"` + // The type of tax information. + Type CreditNoteTotalTaxType `json:"type"` +} + +// Issue a credit note to adjust an invoice's amount after the invoice is finalized. +// +// Related guide: [Credit notes](https://stripe.com/docs/billing/invoices/credit-notes) +type CreditNote struct { + APIResource + // The integer amount in cents (or local equivalent) representing the total amount of the credit note, including tax. + Amount int64 `json:"amount"` + // This is the sum of all the shipping amounts. + AmountShipping int64 `json:"amount_shipping"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // ID of the customer. + Customer *Customer `json:"customer"` + // Customer balance transaction related to this credit note. + CustomerBalanceTransaction *CustomerBalanceTransaction `json:"customer_balance_transaction"` + // The integer amount in cents (or local equivalent) representing the total amount of discount that was credited. + DiscountAmount int64 `json:"discount_amount"` + // The aggregate amounts calculated per discount for all line items. + DiscountAmounts []*CreditNoteDiscountAmount `json:"discount_amounts"` + // The date when this credit note is in effect. Same as `created` unless overwritten. When defined, this value replaces the system-generated 'Date of issue' printed on the credit note PDF. + EffectiveAt int64 `json:"effective_at"` + // Unique identifier for the object. + ID string `json:"id"` + // ID of the invoice. + Invoice *Invoice `json:"invoice"` + // Line items that make up the credit note + Lines *CreditNoteLineItemList `json:"lines"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Customer-facing text that appears on the credit note PDF. + Memo string `json:"memo"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // A unique number that identifies this particular credit note and appears on the PDF of the credit note and its associated invoice. + Number string `json:"number"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Amount that was credited outside of Stripe. + OutOfBandAmount int64 `json:"out_of_band_amount"` + // The link to download the PDF of the credit note. + PDF string `json:"pdf"` + // The amount of the credit note that was refunded to the customer, credited to the customer's balance, credited outside of Stripe, or any combination thereof. + PostPaymentAmount int64 `json:"post_payment_amount"` + // The amount of the credit note by which the invoice's `amount_remaining` and `amount_due` were reduced. + PrePaymentAmount int64 `json:"pre_payment_amount"` + // The pretax credit amounts (ex: discount, credit grants, etc) for all line items. + PretaxCreditAmounts []*CreditNotePretaxCreditAmount `json:"pretax_credit_amounts"` + // Reason for issuing this credit note, one of `duplicate`, `fraudulent`, `order_change`, or `product_unsatisfactory` + Reason CreditNoteReason `json:"reason"` + // Refunds related to this credit note. + Refunds []*CreditNoteRefund `json:"refunds"` + // The details of the cost of shipping, including the ShippingRate applied to the invoice. + ShippingCost *CreditNoteShippingCost `json:"shipping_cost"` + // Status of this credit note, one of `issued` or `void`. Learn more about [voiding credit notes](https://stripe.com/docs/billing/invoices/credit-notes#voiding). + Status CreditNoteStatus `json:"status"` + // The integer amount in cents (or local equivalent) representing the amount of the credit note, excluding exclusive tax and invoice level discounts. + Subtotal int64 `json:"subtotal"` + // The integer amount in cents (or local equivalent) representing the amount of the credit note, excluding all tax and invoice level discounts. + SubtotalExcludingTax int64 `json:"subtotal_excluding_tax"` + // The integer amount in cents (or local equivalent) representing the total amount of the credit note, including tax and all discount. + Total int64 `json:"total"` + // The integer amount in cents (or local equivalent) representing the total amount of the credit note, excluding tax, but including discounts. + TotalExcludingTax int64 `json:"total_excluding_tax"` + // The aggregate tax information for all line items. + TotalTaxes []*CreditNoteTotalTax `json:"total_taxes"` + // Type of this credit note, one of `pre_payment` or `post_payment`. A `pre_payment` credit note means it was issued when the invoice was open. A `post_payment` credit note means it was issued when the invoice was paid. + Type CreditNoteType `json:"type"` + // The time that the credit note was voided. + VoidedAt int64 `json:"voided_at"` +} + +// CreditNoteList is a list of CreditNotes as retrieved from a list endpoint. +type CreditNoteList struct { + APIResource + ListMeta + Data []*CreditNote `json:"data"` +} + +// UnmarshalJSON handles deserialization of a CreditNote. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (c *CreditNote) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + c.ID = id + return nil + } + + type creditNote CreditNote + var v creditNote + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *c = CreditNote(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/creditnote_service.go b/vendor/github.com/stripe/stripe-go/v82/creditnote_service.go new file mode 100644 index 00000000..a668bfe8 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/creditnote_service.go @@ -0,0 +1,143 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1CreditNoteService is used to invoke /v1/credit_notes APIs. +type v1CreditNoteService struct { + B Backend + Key string +} + +// Issue a credit note to adjust the amount of a finalized invoice. A credit note will first reduce the invoice's amount_remaining (and amount_due), but not below zero. +// This amount is indicated by the credit note's pre_payment_amount. The excess amount is indicated by post_payment_amount, and it can result in any combination of the following: +// +// Refunds: create a new refund (using refund_amount) or link existing refunds (using refunds). +// Customer balance credit: credit the customer's balance (using credit_amount) which will be automatically applied to their next invoice when it's finalized. +// Outside of Stripe credit: record the amount that is or will be credited outside of Stripe (using out_of_band_amount). +// +// The sum of refunds, customer balance credits, and outside of Stripe credits must equal the post_payment_amount. +// +// You may issue multiple credit notes for an invoice. Each credit note may increment the invoice's pre_payment_credit_notes_amount, +// post_payment_credit_notes_amount, or both, depending on the invoice's amount_remaining at the time of credit note creation. +func (c v1CreditNoteService) Create(ctx context.Context, params *CreditNoteCreateParams) (*CreditNote, error) { + if params == nil { + params = &CreditNoteCreateParams{} + } + params.Context = ctx + creditnote := &CreditNote{} + err := c.B.Call( + http.MethodPost, "/v1/credit_notes", c.Key, params, creditnote) + return creditnote, err +} + +// Retrieves the credit note object with the given identifier. +func (c v1CreditNoteService) Retrieve(ctx context.Context, id string, params *CreditNoteRetrieveParams) (*CreditNote, error) { + if params == nil { + params = &CreditNoteRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/credit_notes/%s", id) + creditnote := &CreditNote{} + err := c.B.Call(http.MethodGet, path, c.Key, params, creditnote) + return creditnote, err +} + +// Updates an existing credit note. +func (c v1CreditNoteService) Update(ctx context.Context, id string, params *CreditNoteUpdateParams) (*CreditNote, error) { + if params == nil { + params = &CreditNoteUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/credit_notes/%s", id) + creditnote := &CreditNote{} + err := c.B.Call(http.MethodPost, path, c.Key, params, creditnote) + return creditnote, err +} + +// Get a preview of a credit note without creating it. +func (c v1CreditNoteService) Preview(ctx context.Context, params *CreditNotePreviewParams) (*CreditNote, error) { + if params == nil { + params = &CreditNotePreviewParams{} + } + params.Context = ctx + creditnote := &CreditNote{} + err := c.B.Call( + http.MethodGet, "/v1/credit_notes/preview", c.Key, params, creditnote) + return creditnote, err +} + +// Marks a credit note as void. Learn more about [voiding credit notes](https://docs.stripe.com/docs/billing/invoices/credit-notes#voiding). +func (c v1CreditNoteService) VoidCreditNote(ctx context.Context, id string, params *CreditNoteVoidCreditNoteParams) (*CreditNote, error) { + if params == nil { + params = &CreditNoteVoidCreditNoteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/credit_notes/%s/void", id) + creditnote := &CreditNote{} + err := c.B.Call(http.MethodPost, path, c.Key, params, creditnote) + return creditnote, err +} + +// Returns a list of credit notes. +func (c v1CreditNoteService) List(ctx context.Context, listParams *CreditNoteListParams) Seq2[*CreditNote, error] { + if listParams == nil { + listParams = &CreditNoteListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*CreditNote, ListContainer, error) { + list := &CreditNoteList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/credit_notes", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// When retrieving a credit note, you'll get a lines property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. +func (c v1CreditNoteService) ListLines(ctx context.Context, listParams *CreditNoteListLinesParams) Seq2[*CreditNoteLineItem, error] { + if listParams == nil { + listParams = &CreditNoteListLinesParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/credit_notes/%s/lines", StringValue(listParams.CreditNote)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*CreditNoteLineItem, ListContainer, error) { + list := &CreditNoteLineItemList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// When retrieving a credit note preview, you'll get a lines property containing the first handful of those items. This URL you can retrieve the full (paginated) list of line items. +func (c v1CreditNoteService) PreviewLines(ctx context.Context, listParams *CreditNotePreviewLinesParams) Seq2[*CreditNoteLineItem, error] { + if listParams == nil { + listParams = &CreditNotePreviewLinesParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*CreditNoteLineItem, ListContainer, error) { + list := &CreditNoteLineItemList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/credit_notes/preview/lines", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/creditnotelineitem.go b/vendor/github.com/stripe/stripe-go/v82/creditnotelineitem.go new file mode 100644 index 00000000..fbdf48f2 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/creditnotelineitem.go @@ -0,0 +1,149 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Type of the pretax credit amount referenced. +type CreditNoteLineItemPretaxCreditAmountType string + +// List of values that CreditNoteLineItemPretaxCreditAmountType can take +const ( + CreditNoteLineItemPretaxCreditAmountTypeCreditBalanceTransaction CreditNoteLineItemPretaxCreditAmountType = "credit_balance_transaction" + CreditNoteLineItemPretaxCreditAmountTypeDiscount CreditNoteLineItemPretaxCreditAmountType = "discount" +) + +// Whether this tax is inclusive or exclusive. +type CreditNoteLineItemTaxTaxBehavior string + +// List of values that CreditNoteLineItemTaxTaxBehavior can take +const ( + CreditNoteLineItemTaxTaxBehaviorExclusive CreditNoteLineItemTaxTaxBehavior = "exclusive" + CreditNoteLineItemTaxTaxBehaviorInclusive CreditNoteLineItemTaxTaxBehavior = "inclusive" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type CreditNoteLineItemTaxTaxabilityReason string + +// List of values that CreditNoteLineItemTaxTaxabilityReason can take +const ( + CreditNoteLineItemTaxTaxabilityReasonCustomerExempt CreditNoteLineItemTaxTaxabilityReason = "customer_exempt" + CreditNoteLineItemTaxTaxabilityReasonNotAvailable CreditNoteLineItemTaxTaxabilityReason = "not_available" + CreditNoteLineItemTaxTaxabilityReasonNotCollecting CreditNoteLineItemTaxTaxabilityReason = "not_collecting" + CreditNoteLineItemTaxTaxabilityReasonNotSubjectToTax CreditNoteLineItemTaxTaxabilityReason = "not_subject_to_tax" + CreditNoteLineItemTaxTaxabilityReasonNotSupported CreditNoteLineItemTaxTaxabilityReason = "not_supported" + CreditNoteLineItemTaxTaxabilityReasonPortionProductExempt CreditNoteLineItemTaxTaxabilityReason = "portion_product_exempt" + CreditNoteLineItemTaxTaxabilityReasonPortionReducedRated CreditNoteLineItemTaxTaxabilityReason = "portion_reduced_rated" + CreditNoteLineItemTaxTaxabilityReasonPortionStandardRated CreditNoteLineItemTaxTaxabilityReason = "portion_standard_rated" + CreditNoteLineItemTaxTaxabilityReasonProductExempt CreditNoteLineItemTaxTaxabilityReason = "product_exempt" + CreditNoteLineItemTaxTaxabilityReasonProductExemptHoliday CreditNoteLineItemTaxTaxabilityReason = "product_exempt_holiday" + CreditNoteLineItemTaxTaxabilityReasonProportionallyRated CreditNoteLineItemTaxTaxabilityReason = "proportionally_rated" + CreditNoteLineItemTaxTaxabilityReasonReducedRated CreditNoteLineItemTaxTaxabilityReason = "reduced_rated" + CreditNoteLineItemTaxTaxabilityReasonReverseCharge CreditNoteLineItemTaxTaxabilityReason = "reverse_charge" + CreditNoteLineItemTaxTaxabilityReasonStandardRated CreditNoteLineItemTaxTaxabilityReason = "standard_rated" + CreditNoteLineItemTaxTaxabilityReasonTaxableBasisReduced CreditNoteLineItemTaxTaxabilityReason = "taxable_basis_reduced" + CreditNoteLineItemTaxTaxabilityReasonZeroRated CreditNoteLineItemTaxTaxabilityReason = "zero_rated" +) + +// The type of tax information. +type CreditNoteLineItemTaxType string + +// List of values that CreditNoteLineItemTaxType can take +const ( + CreditNoteLineItemTaxTypeTaxRateDetails CreditNoteLineItemTaxType = "tax_rate_details" +) + +// The type of the credit note line item, one of `invoice_line_item` or `custom_line_item`. When the type is `invoice_line_item` there is an additional `invoice_line_item` property on the resource the value of which is the id of the credited line item on the invoice. +type CreditNoteLineItemType string + +// List of values that CreditNoteLineItemType can take +const ( + CreditNoteLineItemTypeCustomLineItem CreditNoteLineItemType = "custom_line_item" + CreditNoteLineItemTypeInvoiceLineItem CreditNoteLineItemType = "invoice_line_item" +) + +// The integer amount in cents (or local equivalent) representing the discount being credited for this line item. +type CreditNoteLineItemDiscountAmount struct { + // The amount, in cents (or local equivalent), of the discount. + Amount int64 `json:"amount"` + // The discount that was applied to get this discount amount. + Discount *Discount `json:"discount"` +} + +// The pretax credit amounts (ex: discount, credit grants, etc) for this line item. +type CreditNoteLineItemPretaxCreditAmount struct { + // The amount, in cents (or local equivalent), of the pretax credit amount. + Amount int64 `json:"amount"` + // The credit balance transaction that was applied to get this pretax credit amount. + CreditBalanceTransaction *BillingCreditBalanceTransaction `json:"credit_balance_transaction"` + // The discount that was applied to get this pretax credit amount. + Discount *Discount `json:"discount"` + // Type of the pretax credit amount referenced. + Type CreditNoteLineItemPretaxCreditAmountType `json:"type"` +} + +// Additional details about the tax rate. Only present when `type` is `tax_rate_details`. +type CreditNoteLineItemTaxTaxRateDetails struct { + TaxRate string `json:"tax_rate"` +} + +// The tax information of the line item. +type CreditNoteLineItemTax struct { + // The amount of the tax, in cents (or local equivalent). + Amount int64 `json:"amount"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason CreditNoteLineItemTaxTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount int64 `json:"taxable_amount"` + // Whether this tax is inclusive or exclusive. + TaxBehavior CreditNoteLineItemTaxTaxBehavior `json:"tax_behavior"` + // Additional details about the tax rate. Only present when `type` is `tax_rate_details`. + TaxRateDetails *CreditNoteLineItemTaxTaxRateDetails `json:"tax_rate_details"` + // The type of tax information. + Type CreditNoteLineItemTaxType `json:"type"` +} + +// CreditNoteLineItem is the resource representing a Stripe credit note line item. +// For more details see https://stripe.com/docs/api/credit_notes/line_item +// The credit note line item object +type CreditNoteLineItem struct { + // The integer amount in cents (or local equivalent) representing the gross amount being credited for this line item, excluding (exclusive) tax and discounts. + Amount int64 `json:"amount"` + // Description of the item being credited. + Description string `json:"description"` + // The integer amount in cents (or local equivalent) representing the discount being credited for this line item. + DiscountAmount int64 `json:"discount_amount"` + // The amount of discount calculated per discount for this line item + DiscountAmounts []*CreditNoteLineItemDiscountAmount `json:"discount_amounts"` + // Unique identifier for the object. + ID string `json:"id"` + // ID of the invoice line item being credited + InvoiceLineItem string `json:"invoice_line_item"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The pretax credit amounts (ex: discount, credit grants, etc) for this line item. + PretaxCreditAmounts []*CreditNoteLineItemPretaxCreditAmount `json:"pretax_credit_amounts"` + // The number of units of product being credited. + Quantity int64 `json:"quantity"` + // The tax information of the line item. + Taxes []*CreditNoteLineItemTax `json:"taxes"` + // The tax rates which apply to the line item. + TaxRates []*TaxRate `json:"tax_rates"` + // The type of the credit note line item, one of `invoice_line_item` or `custom_line_item`. When the type is `invoice_line_item` there is an additional `invoice_line_item` property on the resource the value of which is the id of the credited line item on the invoice. + Type CreditNoteLineItemType `json:"type"` + // The cost of each unit of product being credited. + UnitAmount int64 `json:"unit_amount"` + // Same as `unit_amount`, but contains a decimal value with at most 12 decimal places. + UnitAmountDecimal float64 `json:"unit_amount_decimal,string"` +} + +// CreditNoteLineItemList is a list of CreditNoteLineItems as retrieved from a list endpoint. +type CreditNoteLineItemList struct { + APIResource + ListMeta + Data []*CreditNoteLineItem `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/currency.go b/vendor/github.com/stripe/stripe-go/v82/currency.go new file mode 100644 index 00000000..2de67494 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/currency.go @@ -0,0 +1,148 @@ +package stripe + +// Currency is the list of supported currencies. +// For more details see https://support.stripe.com/questions/which-currencies-does-stripe-support. +type Currency string + +// List of values that Currency can take. +const ( + CurrencyAED Currency = "aed" // United Arab Emirates Dirham + CurrencyAFN Currency = "afn" // Afghan Afghani + CurrencyALL Currency = "all" // Albanian Lek + CurrencyAMD Currency = "amd" // Armenian Dram + CurrencyANG Currency = "ang" // Netherlands Antillean Gulden + CurrencyAOA Currency = "aoa" // Angolan Kwanza + CurrencyARS Currency = "ars" // Argentine Peso + CurrencyAUD Currency = "aud" // Australian Dollar + CurrencyAWG Currency = "awg" // Aruban Florin + CurrencyAZN Currency = "azn" // Azerbaijani Manat + CurrencyBAM Currency = "bam" // Bosnia & Herzegovina Convertible Mark + CurrencyBBD Currency = "bbd" // Barbadian Dollar + CurrencyBDT Currency = "bdt" // Bangladeshi Taka + CurrencyBGN Currency = "bgn" // Bulgarian Lev + CurrencyBIF Currency = "bif" // Burundian Franc + CurrencyBMD Currency = "bmd" // Bermudian Dollar + CurrencyBND Currency = "bnd" // Brunei Dollar + CurrencyBOB Currency = "bob" // Bolivian Boliviano + CurrencyBRL Currency = "brl" // Brazilian Real + CurrencyBSD Currency = "bsd" // Bahamian Dollar + CurrencyBWP Currency = "bwp" // Botswana Pula + CurrencyBZD Currency = "bzd" // Belize Dollar + CurrencyCAD Currency = "cad" // Canadian Dollar + CurrencyCDF Currency = "cdf" // Congolese Franc + CurrencyCHF Currency = "chf" // Swiss Franc + CurrencyCLP Currency = "clp" // Chilean Peso + CurrencyCNY Currency = "cny" // Chinese Renminbi Yuan + CurrencyCOP Currency = "cop" // Colombian Peso + CurrencyCRC Currency = "crc" // Costa Rican Colón + CurrencyCVE Currency = "cve" // Cape Verdean Escudo + CurrencyCZK Currency = "czk" // Czech Koruna + CurrencyDJF Currency = "djf" // Djiboutian Franc + CurrencyDKK Currency = "dkk" // Danish Krone + CurrencyDOP Currency = "dop" // Dominican Peso + CurrencyDZD Currency = "dzd" // Algerian Dinar + CurrencyEEK Currency = "eek" // Estonian Kroon + CurrencyEGP Currency = "egp" // Egyptian Pound + CurrencyETB Currency = "etb" // Ethiopian Birr + CurrencyEUR Currency = "eur" // Euro + CurrencyFJD Currency = "fjd" // Fijian Dollar + CurrencyFKP Currency = "fkp" // Falkland Islands Pound + CurrencyGBP Currency = "gbp" // British Pound + CurrencyGEL Currency = "gel" // Georgian Lari + CurrencyGIP Currency = "gip" // Gibraltar Pound + CurrencyGMD Currency = "gmd" // Gambian Dalasi + CurrencyGNF Currency = "gnf" // Guinean Franc + CurrencyGTQ Currency = "gtq" // Guatemalan Quetzal + CurrencyGYD Currency = "gyd" // Guyanese Dollar + CurrencyHKD Currency = "hkd" // Hong Kong Dollar + CurrencyHNL Currency = "hnl" // Honduran Lempira + CurrencyHRK Currency = "hrk" // Croatian Kuna + CurrencyHTG Currency = "htg" // Haitian Gourde + CurrencyHUF Currency = "huf" // Hungarian Forint + CurrencyIDR Currency = "idr" // Indonesian Rupiah + CurrencyILS Currency = "ils" // Israeli New Sheqel + CurrencyINR Currency = "inr" // Indian Rupee + CurrencyISK Currency = "isk" // Icelandic Króna + CurrencyJMD Currency = "jmd" // Jamaican Dollar + CurrencyJPY Currency = "jpy" // Japanese Yen + CurrencyKES Currency = "kes" // Kenyan Shilling + CurrencyKGS Currency = "kgs" // Kyrgyzstani Som + CurrencyKHR Currency = "khr" // Cambodian Riel + CurrencyKMF Currency = "kmf" // Comorian Franc + CurrencyKRW Currency = "krw" // South Korean Won + CurrencyKYD Currency = "kyd" // Cayman Islands Dollar + CurrencyKZT Currency = "kzt" // Kazakhstani Tenge + CurrencyLAK Currency = "lak" // Lao Kip + CurrencyLBP Currency = "lbp" // Lebanese Pound + CurrencyLKR Currency = "lkr" // Sri Lankan Rupee + CurrencyLRD Currency = "lrd" // Liberian Dollar + CurrencyLSL Currency = "lsl" // Lesotho Loti + CurrencyLTL Currency = "ltl" // Lithuanian Litas + CurrencyLVL Currency = "lvl" // Latvian Lats + CurrencyMAD Currency = "mad" // Moroccan Dirham + CurrencyMDL Currency = "mdl" // Moldovan Leu + CurrencyMGA Currency = "mga" // Malagasy Ariary + CurrencyMKD Currency = "mkd" // Macedonian Denar + CurrencyMNT Currency = "mnt" // Mongolian Tögrög + CurrencyMOP Currency = "mop" // Macanese Pataca + CurrencyMRO Currency = "mro" // Mauritanian Ouguiya + CurrencyMUR Currency = "mur" // Mauritian Rupee + CurrencyMVR Currency = "mvr" // Maldivian Rufiyaa + CurrencyMWK Currency = "mwk" // Malawian Kwacha + CurrencyMXN Currency = "mxn" // Mexican Peso + CurrencyMYR Currency = "myr" // Malaysian Ringgit + CurrencyMZN Currency = "mzn" // Mozambican Metical + CurrencyNAD Currency = "nad" // Namibian Dollar + CurrencyNGN Currency = "ngn" // Nigerian Naira + CurrencyNIO Currency = "nio" // Nicaraguan Córdoba + CurrencyNOK Currency = "nok" // Norwegian Krone + CurrencyNPR Currency = "npr" // Nepalese Rupee + CurrencyNZD Currency = "nzd" // New Zealand Dollar + CurrencyPAB Currency = "pab" // Panamanian Balboa + CurrencyPEN Currency = "pen" // Peruvian Nuevo Sol + CurrencyPGK Currency = "pgk" // Papua New Guinean Kina + CurrencyPHP Currency = "php" // Philippine Peso + CurrencyPKR Currency = "pkr" // Pakistani Rupee + CurrencyPLN Currency = "pln" // Polish Złoty + CurrencyPYG Currency = "pyg" // Paraguayan Guaraní + CurrencyQAR Currency = "qar" // Qatari Riyal + CurrencyRON Currency = "ron" // Romanian Leu + CurrencyRSD Currency = "rsd" // Serbian Dinar + CurrencyRUB Currency = "rub" // Russian Ruble + CurrencyRWF Currency = "rwf" // Rwandan Franc + CurrencySAR Currency = "sar" // Saudi Riyal + CurrencySBD Currency = "sbd" // Solomon Islands Dollar + CurrencySCR Currency = "scr" // Seychellois Rupee + CurrencySEK Currency = "sek" // Swedish Krona + CurrencySGD Currency = "sgd" // Singapore Dollar + CurrencySHP Currency = "shp" // Saint Helenian Pound + CurrencySLL Currency = "sll" // Sierra Leonean Leone + CurrencySOS Currency = "sos" // Somali Shilling + CurrencySRD Currency = "srd" // Surinamese Dollar + CurrencySTD Currency = "std" // São Tomé and Príncipe Dobra + CurrencySVC Currency = "svc" // Salvadoran Colón + CurrencySZL Currency = "szl" // Swazi Lilangeni + CurrencyTHB Currency = "thb" // Thai Baht + CurrencyTJS Currency = "tjs" // Tajikistani Somoni + CurrencyTOP Currency = "top" // Tongan Paʻanga + CurrencyTRY Currency = "try" // Turkish Lira + CurrencyTTD Currency = "ttd" // Trinidad and Tobago Dollar + CurrencyTWD Currency = "twd" // New Taiwan Dollar + CurrencyTZS Currency = "tzs" // Tanzanian Shilling + CurrencyUAH Currency = "uah" // Ukrainian Hryvnia + CurrencyUGX Currency = "ugx" // Ugandan Shilling + CurrencyUSD Currency = "usd" // United States Dollar + CurrencyUYU Currency = "uyu" // Uruguayan Peso + CurrencyUZS Currency = "uzs" // Uzbekistani Som + CurrencyVEF Currency = "vef" // Venezuelan Bolívar + CurrencyVND Currency = "vnd" // Vietnamese Đồng + CurrencyVUV Currency = "vuv" // Vanuatu Vatu + CurrencyWST Currency = "wst" // Samoan Tala + CurrencyXAF Currency = "xaf" // Central African Cfa Franc + CurrencyXCD Currency = "xcd" // East Caribbean Dollar + CurrencyXOF Currency = "xof" // West African Cfa Franc + CurrencyXPF Currency = "xpf" // Cfp Franc + CurrencyYER Currency = "yer" // Yemeni Rial + CurrencyZAR Currency = "zar" // South African Rand + CurrencyZMW Currency = "zmw" // Zambian Kwacha +) diff --git a/vendor/github.com/stripe/stripe-go/v82/customer.go b/vendor/github.com/stripe/stripe-go/v82/customer.go new file mode 100644 index 00000000..8742ebac --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/customer.go @@ -0,0 +1,690 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Surfaces if automatic tax computation is possible given the current customer location information. +type CustomerTaxAutomaticTax string + +// List of values that CustomerTaxAutomaticTax can take +const ( + CustomerTaxAutomaticTaxFailed CustomerTaxAutomaticTax = "failed" + CustomerTaxAutomaticTaxNotCollecting CustomerTaxAutomaticTax = "not_collecting" + CustomerTaxAutomaticTaxSupported CustomerTaxAutomaticTax = "supported" + CustomerTaxAutomaticTaxUnrecognizedLocation CustomerTaxAutomaticTax = "unrecognized_location" +) + +// The data source used to infer the customer's location. +type CustomerTaxLocationSource string + +// List of values that CustomerTaxLocationSource can take +const ( + CustomerTaxLocationSourceBillingAddress CustomerTaxLocationSource = "billing_address" + CustomerTaxLocationSourceIPAddress CustomerTaxLocationSource = "ip_address" + CustomerTaxLocationSourcePaymentMethod CustomerTaxLocationSource = "payment_method" + CustomerTaxLocationSourceShippingDestination CustomerTaxLocationSource = "shipping_destination" +) + +// Describes the customer's tax exemption status, which is `none`, `exempt`, or `reverse`. When set to `reverse`, invoice and receipt PDFs include the following text: **"Reverse charge"**. +type CustomerTaxExempt string + +// List of values that CustomerTaxExempt can take +const ( + CustomerTaxExemptExempt CustomerTaxExempt = "exempt" + CustomerTaxExemptNone CustomerTaxExempt = "none" + CustomerTaxExemptReverse CustomerTaxExempt = "reverse" +) + +// Permanently deletes a customer. It cannot be undone. Also immediately cancels any active subscriptions on the customer. +type CustomerParams struct { + Params `form:"*"` + // The customer's address. + Address *AddressParams `form:"address"` + // An integer amount in cents (or local equivalent) that represents the customer's current balance, which affect the customer's future invoices. A negative amount represents a credit that decreases the amount due on an invoice; a positive amount increases the amount due on an invoice. + Balance *int64 `form:"balance"` + // Balance information and default balance settings for this customer. + CashBalance *CustomerCashBalanceParams `form:"cash_balance"` + // If you are using payment methods created via the PaymentMethods API, see the [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/update#update_customer-invoice_settings-default_payment_method) parameter. + // + // Provide the ID of a payment source already attached to this customer to make it this customer's default payment source. + // + // If you want to add a new payment source and make it the default, see the [source](https://stripe.com/docs/api/customers/update#update_customer-source) property. + DefaultSource *string `form:"default_source"` + // An arbitrary string that you can attach to a customer object. It is displayed alongside the customer in the dashboard. + Description *string `form:"description"` + // Customer's email address. It's displayed alongside the customer in your dashboard and can be useful for searching and tracking. This may be up to *512 characters*. + Email *string `form:"email"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The prefix for the customer used to generate unique invoice numbers. Must be 3–12 uppercase letters or numbers. + InvoicePrefix *string `form:"invoice_prefix"` + // Default invoice settings for this customer. + InvoiceSettings *CustomerInvoiceSettingsParams `form:"invoice_settings"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The customer's full name or business name. + Name *string `form:"name"` + // The sequence to be used on the customer's next invoice. Defaults to 1. + NextInvoiceSequence *int64 `form:"next_invoice_sequence"` + PaymentMethod *string `form:"payment_method"` + // The customer's phone number. + Phone *string `form:"phone"` + // Customer's preferred languages, ordered by preference. + PreferredLocales []*string `form:"preferred_locales"` + // The customer's shipping information. Appears on invoices emailed to this customer. + Shipping *CustomerShippingParams `form:"shipping"` + Source *string `form:"source"` + // Tax details about the customer. + Tax *CustomerTaxParams `form:"tax"` + // The customer's tax exemption. One of `none`, `exempt`, or `reverse`. + TaxExempt *string `form:"tax_exempt"` + // The customer's tax IDs. + TaxIDData []*CustomerTaxIDDataParams `form:"tax_id_data"` + // ID of the test clock to attach to the customer. + TestClock *string `form:"test_clock"` + Validate *bool `form:"validate"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CustomerParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Settings controlling the behavior of the customer's cash balance, +// such as reconciliation of funds received. +type CustomerCashBalanceSettingsParams struct { + // Controls how funds transferred by the customer are applied to payment intents and invoices. Valid options are `automatic`, `manual`, or `merchant_default`. For more information about these reconciliation modes, see [Reconciliation](https://stripe.com/docs/payments/customer-balance/reconciliation). + ReconciliationMode *string `form:"reconciliation_mode"` +} + +// Balance information and default balance settings for this customer. +type CustomerCashBalanceParams struct { + // Settings controlling the behavior of the customer's cash balance, + // such as reconciliation of funds received. + Settings *CustomerCashBalanceSettingsParams `form:"settings"` +} + +// The list of up to 4 default custom fields to be displayed on invoices for this customer. When updating, pass an empty string to remove previously-defined fields. +type CustomerInvoiceSettingsCustomFieldParams struct { + // The name of the custom field. This may be up to 40 characters. + Name *string `form:"name"` + // The value of the custom field. This may be up to 140 characters. + Value *string `form:"value"` +} + +// Default options for invoice PDF rendering for this customer. +type CustomerInvoiceSettingsRenderingOptionsParams struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + AmountTaxDisplay *string `form:"amount_tax_display"` + // ID of the invoice rendering template to use for future invoices. + Template *string `form:"template"` +} + +// Default invoice settings for this customer. +type CustomerInvoiceSettingsParams struct { + // The list of up to 4 default custom fields to be displayed on invoices for this customer. When updating, pass an empty string to remove previously-defined fields. + CustomFields []*CustomerInvoiceSettingsCustomFieldParams `form:"custom_fields"` + // ID of a payment method that's attached to the customer, to be used as the customer's default payment method for subscriptions and invoices. + DefaultPaymentMethod *string `form:"default_payment_method"` + // Default footer to be displayed on invoices for this customer. + Footer *string `form:"footer"` + // Default options for invoice PDF rendering for this customer. + RenderingOptions *CustomerInvoiceSettingsRenderingOptionsParams `form:"rendering_options"` +} + +// The customer's shipping information. Appears on invoices emailed to this customer. +type CustomerShippingParams struct { + // Customer shipping address. + Address *AddressParams `form:"address"` + // Customer name. + Name *string `form:"name"` + // Customer phone (including extension). + Phone *string `form:"phone"` +} + +// Tax details about the customer. +type CustomerTaxParams struct { + // A recent IP address of the customer used for tax reporting and tax location inference. Stripe recommends updating the IP address when a new PaymentMethod is attached or the address field on the customer is updated. We recommend against updating this field more frequently since it could result in unexpected tax location/reporting outcomes. + IPAddress *string `form:"ip_address"` + // A flag that indicates when Stripe should validate the customer tax location. Defaults to `deferred`. + ValidateLocation *string `form:"validate_location"` +} + +// Removes the currently applied discount on a customer. +type CustomerDeleteDiscountParams struct { + Params `form:"*"` +} + +// Returns a list of your customers. The customers are returned sorted by creation date, with the most recent customers appearing first. +type CustomerListParams struct { + ListParams `form:"*"` + // Only return customers that were created during the given date interval. + Created *int64 `form:"created"` + // Only return customers that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // A case-sensitive filter on the list based on the customer's `email` field. The value must be a string. + Email *string `form:"email"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Provides a list of customers that are associated with the specified test clock. The response will not include customers with test clocks if this parameter is not set. + TestClock *string `form:"test_clock"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The customer's tax IDs. +type CustomerTaxIDDataParams struct { + // Type of the tax ID, one of `ad_nrt`, `ae_trn`, `al_tin`, `am_tin`, `ao_tin`, `ar_cuit`, `au_abn`, `au_arn`, `aw_tin`, `az_tin`, `ba_tin`, `bb_tin`, `bd_bin`, `bf_ifu`, `bg_uic`, `bh_vat`, `bj_ifu`, `bo_tin`, `br_cnpj`, `br_cpf`, `bs_tin`, `by_tin`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `ca_qst`, `cd_nif`, `ch_uid`, `ch_vat`, `cl_tin`, `cm_niu`, `cn_tin`, `co_nit`, `cr_tin`, `cv_nif`, `de_stn`, `do_rcn`, `ec_ruc`, `eg_tin`, `es_cif`, `et_tin`, `eu_oss_vat`, `eu_vat`, `gb_vat`, `ge_vat`, `gn_nif`, `hk_br`, `hr_oib`, `hu_tin`, `id_npwp`, `il_vat`, `in_gst`, `is_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `ke_pin`, `kg_tin`, `kh_tin`, `kr_brn`, `kz_bin`, `la_tin`, `li_uid`, `li_vat`, `ma_vat`, `md_vat`, `me_pib`, `mk_vat`, `mr_nif`, `mx_rfc`, `my_frp`, `my_itn`, `my_sst`, `ng_tin`, `no_vat`, `no_voec`, `np_pan`, `nz_gst`, `om_vat`, `pe_ruc`, `ph_tin`, `ro_tin`, `rs_pib`, `ru_inn`, `ru_kpp`, `sa_vat`, `sg_gst`, `sg_uen`, `si_tin`, `sn_ninea`, `sr_fin`, `sv_nit`, `th_vat`, `tj_tin`, `tr_tin`, `tw_vat`, `tz_vat`, `ua_vat`, `ug_tin`, `us_ein`, `uy_ruc`, `uz_tin`, `uz_vat`, `ve_rif`, `vn_tin`, `za_vat`, `zm_tin`, or `zw_tin` + Type *string `form:"type"` + // Value of the tax ID. + Value *string `form:"value"` +} + +// Returns a list of PaymentMethods for a given Customer +type CustomerListPaymentMethodsParams struct { + ListParams `form:"*"` + Customer *string `form:"-"` // Included in URL + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. + AllowRedisplay *string `form:"allow_redisplay"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // An optional filter on the list, based on the object `type` field. Without the filter, the list includes all current and future payment method types. If your integration expects only one type of payment method in the response, make sure to provide a type value in the request. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerListPaymentMethodsParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a PaymentMethod object for a given Customer. +type CustomerRetrievePaymentMethodParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerRetrievePaymentMethodParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Search for customers you've previously created using Stripe's [Search Query Language](https://docs.stripe.com/docs/search#search-query-language). +// Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating +// conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up +// to an hour behind during outages. Search functionality is not available to merchants in India. +type CustomerSearchParams struct { + SearchParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + Page *string `form:"page"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerSearchParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Configuration for eu_bank_transfer funding type. +type CustomerCreateFundingInstructionsBankTransferEUBankTransferParams struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country *string `form:"country"` +} + +// Additional parameters for `bank_transfer` funding types +type CustomerCreateFundingInstructionsBankTransferParams struct { + // Configuration for eu_bank_transfer funding type. + EUBankTransfer *CustomerCreateFundingInstructionsBankTransferEUBankTransferParams `form:"eu_bank_transfer"` + // List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. + // + // Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. + RequestedAddressTypes []*string `form:"requested_address_types"` + // The type of the `bank_transfer` + Type *string `form:"type"` +} + +// Retrieve funding instructions for a customer cash balance. If funding instructions do not yet exist for the customer, new +// funding instructions will be created. If funding instructions have already been created for a given customer, the same +// funding instructions will be retrieved. In other words, we will return the same funding instructions each time. +type CustomerCreateFundingInstructionsParams struct { + Params `form:"*"` + // Additional parameters for `bank_transfer` funding types + BankTransfer *CustomerCreateFundingInstructionsBankTransferParams `form:"bank_transfer"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The `funding_type` to get the instructions for. + FundingType *string `form:"funding_type"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerCreateFundingInstructionsParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Permanently deletes a customer. It cannot be undone. Also immediately cancels any active subscriptions on the customer. +type CustomerDeleteParams struct { + Params `form:"*"` +} + +// Retrieves a Customer object. +type CustomerRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Settings controlling the behavior of the customer's cash balance, +// such as reconciliation of funds received. +type CustomerUpdateCashBalanceSettingsParams struct { + // Controls how funds transferred by the customer are applied to payment intents and invoices. Valid options are `automatic`, `manual`, or `merchant_default`. For more information about these reconciliation modes, see [Reconciliation](https://stripe.com/docs/payments/customer-balance/reconciliation). + ReconciliationMode *string `form:"reconciliation_mode"` +} + +// Balance information and default balance settings for this customer. +type CustomerUpdateCashBalanceParams struct { + // Settings controlling the behavior of the customer's cash balance, + // such as reconciliation of funds received. + Settings *CustomerUpdateCashBalanceSettingsParams `form:"settings"` +} + +// The list of up to 4 default custom fields to be displayed on invoices for this customer. When updating, pass an empty string to remove previously-defined fields. +type CustomerUpdateInvoiceSettingsCustomFieldParams struct { + // The name of the custom field. This may be up to 40 characters. + Name *string `form:"name"` + // The value of the custom field. This may be up to 140 characters. + Value *string `form:"value"` +} + +// Default options for invoice PDF rendering for this customer. +type CustomerUpdateInvoiceSettingsRenderingOptionsParams struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + AmountTaxDisplay *string `form:"amount_tax_display"` + // ID of the invoice rendering template to use for future invoices. + Template *string `form:"template"` +} + +// Default invoice settings for this customer. +type CustomerUpdateInvoiceSettingsParams struct { + // The list of up to 4 default custom fields to be displayed on invoices for this customer. When updating, pass an empty string to remove previously-defined fields. + CustomFields []*CustomerUpdateInvoiceSettingsCustomFieldParams `form:"custom_fields"` + // ID of a payment method that's attached to the customer, to be used as the customer's default payment method for subscriptions and invoices. + DefaultPaymentMethod *string `form:"default_payment_method"` + // Default footer to be displayed on invoices for this customer. + Footer *string `form:"footer"` + // Default options for invoice PDF rendering for this customer. + RenderingOptions *CustomerUpdateInvoiceSettingsRenderingOptionsParams `form:"rendering_options"` +} + +// The customer's shipping information. Appears on invoices emailed to this customer. +type CustomerUpdateShippingParams struct { + // Customer shipping address. + Address *AddressParams `form:"address"` + // Customer name. + Name *string `form:"name"` + // Customer phone (including extension). + Phone *string `form:"phone"` +} + +// Tax details about the customer. +type CustomerUpdateTaxParams struct { + // A recent IP address of the customer used for tax reporting and tax location inference. Stripe recommends updating the IP address when a new PaymentMethod is attached or the address field on the customer is updated. We recommend against updating this field more frequently since it could result in unexpected tax location/reporting outcomes. + IPAddress *string `form:"ip_address"` + // A flag that indicates when Stripe should validate the customer tax location. Defaults to `auto`. + ValidateLocation *string `form:"validate_location"` +} + +// Updates the specified customer by setting the values of the parameters passed. Any parameters not provided will be left unchanged. For example, if you pass the source parameter, that becomes the customer's active source (e.g., a card) to be used for all charges in the future. When you update a customer to a new valid card source by passing the source parameter: for each of the customer's current subscriptions, if the subscription bills automatically and is in the past_due state, then the latest open invoice for the subscription with automatic collection enabled will be retried. This retry will not count as an automatic retry, and will not affect the next regularly scheduled payment for the invoice. Changing the default_source for a customer will not trigger this behavior. +// +// This request accepts mostly the same arguments as the customer creation call. +type CustomerUpdateParams struct { + Params `form:"*"` + // The customer's address. + Address *AddressParams `form:"address"` + // An integer amount in cents (or local equivalent) that represents the customer's current balance, which affect the customer's future invoices. A negative amount represents a credit that decreases the amount due on an invoice; a positive amount increases the amount due on an invoice. + Balance *int64 `form:"balance"` + // Balance information and default balance settings for this customer. + CashBalance *CustomerUpdateCashBalanceParams `form:"cash_balance"` + // If you are using payment methods created via the PaymentMethods API, see the [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/update#update_customer-invoice_settings-default_payment_method) parameter. + // + // Provide the ID of a payment source already attached to this customer to make it this customer's default payment source. + // + // If you want to add a new payment source and make it the default, see the [source](https://stripe.com/docs/api/customers/update#update_customer-source) property. + DefaultSource *string `form:"default_source"` + // An arbitrary string that you can attach to a customer object. It is displayed alongside the customer in the dashboard. + Description *string `form:"description"` + // Customer's email address. It's displayed alongside the customer in your dashboard and can be useful for searching and tracking. This may be up to *512 characters*. + Email *string `form:"email"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The prefix for the customer used to generate unique invoice numbers. Must be 3–12 uppercase letters or numbers. + InvoicePrefix *string `form:"invoice_prefix"` + // Default invoice settings for this customer. + InvoiceSettings *CustomerUpdateInvoiceSettingsParams `form:"invoice_settings"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The customer's full name or business name. + Name *string `form:"name"` + // The sequence to be used on the customer's next invoice. Defaults to 1. + NextInvoiceSequence *int64 `form:"next_invoice_sequence"` + // The customer's phone number. + Phone *string `form:"phone"` + // Customer's preferred languages, ordered by preference. + PreferredLocales []*string `form:"preferred_locales"` + // The customer's shipping information. Appears on invoices emailed to this customer. + Shipping *CustomerUpdateShippingParams `form:"shipping"` + Source *string `form:"source"` + // Tax details about the customer. + Tax *CustomerUpdateTaxParams `form:"tax"` + // The customer's tax exemption. One of `none`, `exempt`, or `reverse`. + TaxExempt *string `form:"tax_exempt"` + Validate *bool `form:"validate"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CustomerUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Settings controlling the behavior of the customer's cash balance, +// such as reconciliation of funds received. +type CustomerCreateCashBalanceSettingsParams struct { + // Controls how funds transferred by the customer are applied to payment intents and invoices. Valid options are `automatic`, `manual`, or `merchant_default`. For more information about these reconciliation modes, see [Reconciliation](https://stripe.com/docs/payments/customer-balance/reconciliation). + ReconciliationMode *string `form:"reconciliation_mode"` +} + +// Balance information and default balance settings for this customer. +type CustomerCreateCashBalanceParams struct { + // Settings controlling the behavior of the customer's cash balance, + // such as reconciliation of funds received. + Settings *CustomerCreateCashBalanceSettingsParams `form:"settings"` +} + +// The list of up to 4 default custom fields to be displayed on invoices for this customer. When updating, pass an empty string to remove previously-defined fields. +type CustomerCreateInvoiceSettingsCustomFieldParams struct { + // The name of the custom field. This may be up to 40 characters. + Name *string `form:"name"` + // The value of the custom field. This may be up to 140 characters. + Value *string `form:"value"` +} + +// Default options for invoice PDF rendering for this customer. +type CustomerCreateInvoiceSettingsRenderingOptionsParams struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + AmountTaxDisplay *string `form:"amount_tax_display"` + // ID of the invoice rendering template to use for future invoices. + Template *string `form:"template"` +} + +// Default invoice settings for this customer. +type CustomerCreateInvoiceSettingsParams struct { + // The list of up to 4 default custom fields to be displayed on invoices for this customer. When updating, pass an empty string to remove previously-defined fields. + CustomFields []*CustomerCreateInvoiceSettingsCustomFieldParams `form:"custom_fields"` + // ID of a payment method that's attached to the customer, to be used as the customer's default payment method for subscriptions and invoices. + DefaultPaymentMethod *string `form:"default_payment_method"` + // Default footer to be displayed on invoices for this customer. + Footer *string `form:"footer"` + // Default options for invoice PDF rendering for this customer. + RenderingOptions *CustomerCreateInvoiceSettingsRenderingOptionsParams `form:"rendering_options"` +} + +// The customer's shipping information. Appears on invoices emailed to this customer. +type CustomerCreateShippingParams struct { + // Customer shipping address. + Address *AddressParams `form:"address"` + // Customer name. + Name *string `form:"name"` + // Customer phone (including extension). + Phone *string `form:"phone"` +} + +// Tax details about the customer. +type CustomerCreateTaxParams struct { + // A recent IP address of the customer used for tax reporting and tax location inference. Stripe recommends updating the IP address when a new PaymentMethod is attached or the address field on the customer is updated. We recommend against updating this field more frequently since it could result in unexpected tax location/reporting outcomes. + IPAddress *string `form:"ip_address"` + // A flag that indicates when Stripe should validate the customer tax location. Defaults to `deferred`. + ValidateLocation *string `form:"validate_location"` +} + +// The customer's tax IDs. +type CustomerCreateTaxIDDataParams struct { + // Type of the tax ID, one of `ad_nrt`, `ae_trn`, `al_tin`, `am_tin`, `ao_tin`, `ar_cuit`, `au_abn`, `au_arn`, `aw_tin`, `az_tin`, `ba_tin`, `bb_tin`, `bd_bin`, `bf_ifu`, `bg_uic`, `bh_vat`, `bj_ifu`, `bo_tin`, `br_cnpj`, `br_cpf`, `bs_tin`, `by_tin`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `ca_qst`, `cd_nif`, `ch_uid`, `ch_vat`, `cl_tin`, `cm_niu`, `cn_tin`, `co_nit`, `cr_tin`, `cv_nif`, `de_stn`, `do_rcn`, `ec_ruc`, `eg_tin`, `es_cif`, `et_tin`, `eu_oss_vat`, `eu_vat`, `gb_vat`, `ge_vat`, `gn_nif`, `hk_br`, `hr_oib`, `hu_tin`, `id_npwp`, `il_vat`, `in_gst`, `is_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `ke_pin`, `kg_tin`, `kh_tin`, `kr_brn`, `kz_bin`, `la_tin`, `li_uid`, `li_vat`, `ma_vat`, `md_vat`, `me_pib`, `mk_vat`, `mr_nif`, `mx_rfc`, `my_frp`, `my_itn`, `my_sst`, `ng_tin`, `no_vat`, `no_voec`, `np_pan`, `nz_gst`, `om_vat`, `pe_ruc`, `ph_tin`, `ro_tin`, `rs_pib`, `ru_inn`, `ru_kpp`, `sa_vat`, `sg_gst`, `sg_uen`, `si_tin`, `sn_ninea`, `sr_fin`, `sv_nit`, `th_vat`, `tj_tin`, `tr_tin`, `tw_vat`, `tz_vat`, `ua_vat`, `ug_tin`, `us_ein`, `uy_ruc`, `uz_tin`, `uz_vat`, `ve_rif`, `vn_tin`, `za_vat`, `zm_tin`, or `zw_tin` + Type *string `form:"type"` + // Value of the tax ID. + Value *string `form:"value"` +} + +// Creates a new customer object. +type CustomerCreateParams struct { + Params `form:"*"` + // The customer's address. + Address *AddressParams `form:"address"` + // An integer amount in cents (or local equivalent) that represents the customer's current balance, which affect the customer's future invoices. A negative amount represents a credit that decreases the amount due on an invoice; a positive amount increases the amount due on an invoice. + Balance *int64 `form:"balance"` + // Balance information and default balance settings for this customer. + CashBalance *CustomerCreateCashBalanceParams `form:"cash_balance"` + // An arbitrary string that you can attach to a customer object. It is displayed alongside the customer in the dashboard. + Description *string `form:"description"` + // Customer's email address. It's displayed alongside the customer in your dashboard and can be useful for searching and tracking. This may be up to *512 characters*. + Email *string `form:"email"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The prefix for the customer used to generate unique invoice numbers. Must be 3–12 uppercase letters or numbers. + InvoicePrefix *string `form:"invoice_prefix"` + // Default invoice settings for this customer. + InvoiceSettings *CustomerCreateInvoiceSettingsParams `form:"invoice_settings"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The customer's full name or business name. + Name *string `form:"name"` + // The sequence to be used on the customer's next invoice. Defaults to 1. + NextInvoiceSequence *int64 `form:"next_invoice_sequence"` + PaymentMethod *string `form:"payment_method"` + // The customer's phone number. + Phone *string `form:"phone"` + // Customer's preferred languages, ordered by preference. + PreferredLocales []*string `form:"preferred_locales"` + // The customer's shipping information. Appears on invoices emailed to this customer. + Shipping *CustomerCreateShippingParams `form:"shipping"` + Source *string `form:"source"` + // Tax details about the customer. + Tax *CustomerCreateTaxParams `form:"tax"` + // The customer's tax exemption. One of `none`, `exempt`, or `reverse`. + TaxExempt *string `form:"tax_exempt"` + // The customer's tax IDs. + TaxIDData []*CustomerCreateTaxIDDataParams `form:"tax_id_data"` + // ID of the test clock to attach to the customer. + TestClock *string `form:"test_clock"` + Validate *bool `form:"validate"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CustomerCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Default custom fields to be displayed on invoices for this customer. +type CustomerInvoiceSettingsCustomField struct { + // The name of the custom field. + Name string `json:"name"` + // The value of the custom field. + Value string `json:"value"` +} + +// Default options for invoice PDF rendering for this customer. +type CustomerInvoiceSettingsRenderingOptions struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. + AmountTaxDisplay string `json:"amount_tax_display"` + // ID of the invoice rendering template to be used for this customer's invoices. If set, the template will be used on all invoices for this customer unless a template is set directly on the invoice. + Template string `json:"template"` +} +type CustomerInvoiceSettings struct { + // Default custom fields to be displayed on invoices for this customer. + CustomFields []*CustomerInvoiceSettingsCustomField `json:"custom_fields"` + // ID of a payment method that's attached to the customer, to be used as the customer's default payment method for subscriptions and invoices. + DefaultPaymentMethod *PaymentMethod `json:"default_payment_method"` + // Default footer to be displayed on invoices for this customer. + Footer string `json:"footer"` + // Default options for invoice PDF rendering for this customer. + RenderingOptions *CustomerInvoiceSettingsRenderingOptions `json:"rendering_options"` +} + +// The identified tax location of the customer. +type CustomerTaxLocation struct { + // The identified tax country of the customer. + Country string `json:"country"` + // The data source used to infer the customer's location. + Source CustomerTaxLocationSource `json:"source"` + // The identified tax state, county, province, or region of the customer. + State string `json:"state"` +} +type CustomerTax struct { + // Surfaces if automatic tax computation is possible given the current customer location information. + AutomaticTax CustomerTaxAutomaticTax `json:"automatic_tax"` + // A recent IP address of the customer used for tax reporting and tax location inference. + IPAddress string `json:"ip_address"` + // The identified tax location of the customer. + Location *CustomerTaxLocation `json:"location"` +} + +// This object represents a customer of your business. Use it to [create recurring charges](https://stripe.com/docs/invoicing/customer), [save payment](https://stripe.com/docs/payments/save-during-payment) and contact information, +// and track payments that belong to the same customer. +type Customer struct { + APIResource + // The customer's address. + Address *Address `json:"address"` + // The current balance, if any, that's stored on the customer. If negative, the customer has credit to apply to their next invoice. If positive, the customer has an amount owed that's added to their next invoice. The balance only considers amounts that Stripe hasn't successfully applied to any invoice. It doesn't reflect unpaid invoices. This balance is only taken into account after invoices finalize. + Balance int64 `json:"balance"` + // The current funds being held by Stripe on behalf of the customer. You can apply these funds towards payment intents when the source is "cash_balance". The `settings[reconciliation_mode]` field describes if these funds apply to these payment intents manually or automatically. + CashBalance *CashBalance `json:"cash_balance"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) the customer can be charged in for recurring billing purposes. + Currency Currency `json:"currency"` + // ID of the default payment source for the customer. + // + // If you use payment methods created through the PaymentMethods API, see the [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) field instead. + DefaultSource *PaymentSource `json:"default_source"` + Deleted bool `json:"deleted"` + // Tracks the most recent state change on any invoice belonging to the customer. Paying an invoice or marking it uncollectible via the API will set this field to false. An automatic payment failure or passing the `invoice.due_date` will set this field to `true`. + // + // If an invoice becomes uncollectible by [dunning](https://stripe.com/docs/billing/automatic-collection), `delinquent` doesn't reset to `false`. + // + // If you care whether the customer has paid their most recent subscription invoice, use `subscription.status` instead. Paying or marking uncollectible any customer invoice regardless of whether it is the latest invoice for a subscription will always set this field to `false`. + Delinquent bool `json:"delinquent"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // Describes the current discount active on the customer, if there is one. + Discount *Discount `json:"discount"` + // The customer's email address. + Email string `json:"email"` + // Unique identifier for the object. + ID string `json:"id"` + // The current multi-currency balances, if any, that's stored on the customer. If positive in a currency, the customer has a credit to apply to their next invoice denominated in that currency. If negative, the customer has an amount owed that's added to their next invoice denominated in that currency. These balances don't apply to unpaid invoices. They solely track amounts that Stripe hasn't successfully applied to any invoice. Stripe only applies a balance in a specific currency to an invoice after that invoice (which is in the same currency) finalizes. + InvoiceCreditBalance map[string]int64 `json:"invoice_credit_balance"` + // The prefix for the customer used to generate unique invoice numbers. + InvoicePrefix string `json:"invoice_prefix"` + InvoiceSettings *CustomerInvoiceSettings `json:"invoice_settings"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // The customer's full name or business name. + Name string `json:"name"` + // The suffix of the customer's next invoice number (for example, 0001). When the account uses account level sequencing, this parameter is ignored in API requests and the field omitted in API responses. + NextInvoiceSequence int64 `json:"next_invoice_sequence"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The customer's phone number. + Phone string `json:"phone"` + // The customer's preferred locales (languages), ordered by preference. + PreferredLocales []string `json:"preferred_locales"` + // Mailing and shipping address for the customer. Appears on invoices emailed to this customer. + Shipping *ShippingDetails `json:"shipping"` + Sources *PaymentSourceList `json:"sources"` + // The customer's current subscriptions, if any. + Subscriptions *SubscriptionList `json:"subscriptions"` + Tax *CustomerTax `json:"tax"` + // Describes the customer's tax exemption status, which is `none`, `exempt`, or `reverse`. When set to `reverse`, invoice and receipt PDFs include the following text: **"Reverse charge"**. + TaxExempt CustomerTaxExempt `json:"tax_exempt"` + // The customer's tax IDs. + TaxIDs *TaxIDList `json:"tax_ids"` + // ID of the test clock that this customer belongs to. + TestClock *TestHelpersTestClock `json:"test_clock"` +} + +// CustomerList is a list of Customers as retrieved from a list endpoint. +type CustomerList struct { + APIResource + ListMeta + Data []*Customer `json:"data"` +} + +// CustomerSearchResult is a list of Customer search results as retrieved from a search endpoint. +type CustomerSearchResult struct { + APIResource + SearchMeta + Data []*Customer `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Customer. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (c *Customer) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + c.ID = id + return nil + } + + type customer Customer + var v customer + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *c = Customer(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/customer_service.go b/vendor/github.com/stripe/stripe-go/v82/customer_service.go new file mode 100644 index 00000000..813d7c14 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/customer_service.go @@ -0,0 +1,164 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1CustomerService is used to invoke /v1/customers APIs. +type v1CustomerService struct { + B Backend + Key string +} + +// Creates a new customer object. +func (c v1CustomerService) Create(ctx context.Context, params *CustomerCreateParams) (*Customer, error) { + if params == nil { + params = &CustomerCreateParams{} + } + params.Context = ctx + customer := &Customer{} + err := c.B.Call(http.MethodPost, "/v1/customers", c.Key, params, customer) + return customer, err +} + +// Retrieves a Customer object. +func (c v1CustomerService) Retrieve(ctx context.Context, id string, params *CustomerRetrieveParams) (*Customer, error) { + if params == nil { + params = &CustomerRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/customers/%s", id) + customer := &Customer{} + err := c.B.Call(http.MethodGet, path, c.Key, params, customer) + return customer, err +} + +// Updates the specified customer by setting the values of the parameters passed. Any parameters not provided will be left unchanged. For example, if you pass the source parameter, that becomes the customer's active source (e.g., a card) to be used for all charges in the future. When you update a customer to a new valid card source by passing the source parameter: for each of the customer's current subscriptions, if the subscription bills automatically and is in the past_due state, then the latest open invoice for the subscription with automatic collection enabled will be retried. This retry will not count as an automatic retry, and will not affect the next regularly scheduled payment for the invoice. Changing the default_source for a customer will not trigger this behavior. +// +// This request accepts mostly the same arguments as the customer creation call. +func (c v1CustomerService) Update(ctx context.Context, id string, params *CustomerUpdateParams) (*Customer, error) { + if params == nil { + params = &CustomerUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/customers/%s", id) + customer := &Customer{} + err := c.B.Call(http.MethodPost, path, c.Key, params, customer) + return customer, err +} + +// Permanently deletes a customer. It cannot be undone. Also immediately cancels any active subscriptions on the customer. +func (c v1CustomerService) Delete(ctx context.Context, id string, params *CustomerDeleteParams) (*Customer, error) { + if params == nil { + params = &CustomerDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/customers/%s", id) + customer := &Customer{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, customer) + return customer, err +} + +// Retrieve funding instructions for a customer cash balance. If funding instructions do not yet exist for the customer, new +// funding instructions will be created. If funding instructions have already been created for a given customer, the same +// funding instructions will be retrieved. In other words, we will return the same funding instructions each time. +func (c v1CustomerService) CreateFundingInstructions(ctx context.Context, id string, params *CustomerCreateFundingInstructionsParams) (*FundingInstructions, error) { + if params == nil { + params = &CustomerCreateFundingInstructionsParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/customers/%s/funding_instructions", id) + fundinginstructions := &FundingInstructions{} + err := c.B.Call(http.MethodPost, path, c.Key, params, fundinginstructions) + return fundinginstructions, err +} + +// Removes the currently applied discount on a customer. +func (c v1CustomerService) DeleteDiscount(ctx context.Context, id string, params *CustomerDeleteDiscountParams) (*Customer, error) { + if params == nil { + params = &CustomerDeleteDiscountParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/customers/%s/discount", id) + customer := &Customer{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, customer) + return customer, err +} + +// Retrieves a PaymentMethod object for a given Customer. +func (c v1CustomerService) RetrievePaymentMethod(ctx context.Context, id string, params *CustomerRetrievePaymentMethodParams) (*PaymentMethod, error) { + if params == nil { + params = &CustomerRetrievePaymentMethodParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/payment_methods/%s", StringValue(params.Customer), id) + paymentmethod := &PaymentMethod{} + err := c.B.Call(http.MethodGet, path, c.Key, params, paymentmethod) + return paymentmethod, err +} + +// Returns a list of your customers. The customers are returned sorted by creation date, with the most recent customers appearing first. +func (c v1CustomerService) List(ctx context.Context, listParams *CustomerListParams) Seq2[*Customer, error] { + if listParams == nil { + listParams = &CustomerListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Customer, ListContainer, error) { + list := &CustomerList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/customers", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// Returns a list of PaymentMethods for a given Customer +func (c v1CustomerService) ListPaymentMethods(ctx context.Context, listParams *CustomerListPaymentMethodsParams) Seq2[*PaymentMethod, error] { + if listParams == nil { + listParams = &CustomerListPaymentMethodsParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/payment_methods", StringValue(listParams.Customer)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*PaymentMethod, ListContainer, error) { + list := &PaymentMethodList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// Search for customers you've previously created using Stripe's [Search Query Language](https://docs.stripe.com/docs/search#search-query-language). +// Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating +// conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up +// to an hour behind during outages. Search functionality is not available to merchants in India. +func (c v1CustomerService) Search(ctx context.Context, params *CustomerSearchParams) Seq2[*Customer, error] { + if params == nil { + params = &CustomerSearchParams{} + } + params.Context = ctx + return newV1SearchList(params, func(p *Params, b *form.Values) ([]*Customer, SearchContainer, error) { + list := &CustomerSearchResult{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/customers/search", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/customerbalancetransaction.go b/vendor/github.com/stripe/stripe-go/v82/customerbalancetransaction.go new file mode 100644 index 00000000..88bf8fd1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/customerbalancetransaction.go @@ -0,0 +1,204 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Transaction type: `adjustment`, `applied_to_invoice`, `credit_note`, `initial`, `invoice_overpaid`, `invoice_too_large`, `invoice_too_small`, `unspent_receiver_credit`, `unapplied_from_invoice`, `checkout_session_subscription_payment`, or `checkout_session_subscription_payment_canceled`. See the [Customer Balance page](https://stripe.com/docs/billing/customer/balance#types) to learn more about transaction types. +type CustomerBalanceTransactionType string + +// List of values that CustomerBalanceTransactionType can take +const ( + CustomerBalanceTransactionTypeAdjustment CustomerBalanceTransactionType = "adjustment" + CustomerBalanceTransactionTypeAppliedToInvoice CustomerBalanceTransactionType = "applied_to_invoice" + CustomerBalanceTransactionTypeCheckoutSessionSubscriptionPayment CustomerBalanceTransactionType = "checkout_session_subscription_payment" + CustomerBalanceTransactionTypeCheckoutSessionSubscriptionPaymentCanceled CustomerBalanceTransactionType = "checkout_session_subscription_payment_canceled" + CustomerBalanceTransactionTypeCreditNote CustomerBalanceTransactionType = "credit_note" + CustomerBalanceTransactionTypeInitial CustomerBalanceTransactionType = "initial" + CustomerBalanceTransactionTypeInvoiceOverpaid CustomerBalanceTransactionType = "invoice_overpaid" + CustomerBalanceTransactionTypeInvoiceTooLarge CustomerBalanceTransactionType = "invoice_too_large" + CustomerBalanceTransactionTypeInvoiceTooSmall CustomerBalanceTransactionType = "invoice_too_small" + CustomerBalanceTransactionTypeMigration CustomerBalanceTransactionType = "migration" + CustomerBalanceTransactionTypeUnappliedFromInvoice CustomerBalanceTransactionType = "unapplied_from_invoice" + CustomerBalanceTransactionTypeUnspentReceiverCredit CustomerBalanceTransactionType = "unspent_receiver_credit" +) + +// Returns a list of transactions that updated the customer's [balances](https://docs.stripe.com/docs/billing/customer/balance). +type CustomerBalanceTransactionListParams struct { + ListParams `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerBalanceTransactionListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates an immutable transaction that updates the customer's credit [balance](https://docs.stripe.com/docs/billing/customer/balance). +type CustomerBalanceTransactionParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // The integer amount in **cents (or local equivalent)** to apply to the customer's credit balance. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). Specifies the [`invoice_credit_balance`](https://stripe.com/docs/api/customers/object#customer_object-invoice_credit_balance) that this transaction will apply to. If the customer's `currency` is not set, it will be updated to this value. + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerBalanceTransactionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CustomerBalanceTransactionParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Creates an immutable transaction that updates the customer's credit [balance](https://docs.stripe.com/docs/billing/customer/balance). +type CustomerBalanceTransactionCreateParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // The integer amount in **cents (or local equivalent)** to apply to the customer's credit balance. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). Specifies the [`invoice_credit_balance`](https://stripe.com/docs/api/customers/object#customer_object-invoice_credit_balance) that this transaction will apply to. If the customer's `currency` is not set, it will be updated to this value. + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerBalanceTransactionCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CustomerBalanceTransactionCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves a specific customer balance transaction that updated the customer's [balances](https://docs.stripe.com/docs/billing/customer/balance). +type CustomerBalanceTransactionRetrieveParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerBalanceTransactionRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Most credit balance transaction fields are immutable, but you may update its description and metadata. +type CustomerBalanceTransactionUpdateParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerBalanceTransactionUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *CustomerBalanceTransactionUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Each customer has a [Balance](https://stripe.com/docs/api/customers/object#customer_object-balance) value, +// which denotes a debit or credit that's automatically applied to their next invoice upon finalization. +// You may modify the value directly by using the [update customer API](https://stripe.com/docs/api/customers/update), +// or by creating a Customer Balance Transaction, which increments or decrements the customer's `balance` by the specified `amount`. +// +// Related guide: [Customer balance](https://stripe.com/docs/billing/customer/balance) +type CustomerBalanceTransaction struct { + APIResource + // The amount of the transaction. A negative value is a credit for the customer's balance, and a positive value is a debit to the customer's `balance`. + Amount int64 `json:"amount"` + // The ID of the checkout session (if any) that created the transaction. + CheckoutSession *CheckoutSession `json:"checkout_session"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The ID of the credit note (if any) related to the transaction. + CreditNote *CreditNote `json:"credit_note"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // The ID of the customer the transaction belongs to. + Customer *Customer `json:"customer"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // The customer's `balance` after the transaction was applied. A negative value decreases the amount due on the customer's next invoice. A positive value increases the amount due on the customer's next invoice. + EndingBalance int64 `json:"ending_balance"` + // Unique identifier for the object. + ID string `json:"id"` + // The ID of the invoice (if any) related to the transaction. + Invoice *Invoice `json:"invoice"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Transaction type: `adjustment`, `applied_to_invoice`, `credit_note`, `initial`, `invoice_overpaid`, `invoice_too_large`, `invoice_too_small`, `unspent_receiver_credit`, `unapplied_from_invoice`, `checkout_session_subscription_payment`, or `checkout_session_subscription_payment_canceled`. See the [Customer Balance page](https://stripe.com/docs/billing/customer/balance#types) to learn more about transaction types. + Type CustomerBalanceTransactionType `json:"type"` +} + +// CustomerBalanceTransactionList is a list of CustomerBalanceTransactions as retrieved from a list endpoint. +type CustomerBalanceTransactionList struct { + APIResource + ListMeta + Data []*CustomerBalanceTransaction `json:"data"` +} + +// UnmarshalJSON handles deserialization of a CustomerBalanceTransaction. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (c *CustomerBalanceTransaction) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + c.ID = id + return nil + } + + type customerBalanceTransaction CustomerBalanceTransaction + var v customerBalanceTransaction + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *c = CustomerBalanceTransaction(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/customerbalancetransaction_service.go b/vendor/github.com/stripe/stripe-go/v82/customerbalancetransaction_service.go new file mode 100644 index 00000000..cc9c6ee0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/customerbalancetransaction_service.go @@ -0,0 +1,83 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1CustomerBalanceTransactionService is used to invoke /v1/customers/{customer}/balance_transactions APIs. +type v1CustomerBalanceTransactionService struct { + B Backend + Key string +} + +// Creates an immutable transaction that updates the customer's credit [balance](https://docs.stripe.com/docs/billing/customer/balance). +func (c v1CustomerBalanceTransactionService) Create(ctx context.Context, params *CustomerBalanceTransactionCreateParams) (*CustomerBalanceTransaction, error) { + if params == nil { + params = &CustomerBalanceTransactionCreateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/balance_transactions", StringValue(params.Customer)) + customerbalancetransaction := &CustomerBalanceTransaction{} + err := c.B.Call( + http.MethodPost, path, c.Key, params, customerbalancetransaction) + return customerbalancetransaction, err +} + +// Retrieves a specific customer balance transaction that updated the customer's [balances](https://docs.stripe.com/docs/billing/customer/balance). +func (c v1CustomerBalanceTransactionService) Retrieve(ctx context.Context, id string, params *CustomerBalanceTransactionRetrieveParams) (*CustomerBalanceTransaction, error) { + if params == nil { + params = &CustomerBalanceTransactionRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/balance_transactions/%s", StringValue( + params.Customer), id) + customerbalancetransaction := &CustomerBalanceTransaction{} + err := c.B.Call( + http.MethodGet, path, c.Key, params, customerbalancetransaction) + return customerbalancetransaction, err +} + +// Most credit balance transaction fields are immutable, but you may update its description and metadata. +func (c v1CustomerBalanceTransactionService) Update(ctx context.Context, id string, params *CustomerBalanceTransactionUpdateParams) (*CustomerBalanceTransaction, error) { + if params == nil { + params = &CustomerBalanceTransactionUpdateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/balance_transactions/%s", StringValue( + params.Customer), id) + customerbalancetransaction := &CustomerBalanceTransaction{} + err := c.B.Call( + http.MethodPost, path, c.Key, params, customerbalancetransaction) + return customerbalancetransaction, err +} + +// Returns a list of transactions that updated the customer's [balances](https://docs.stripe.com/docs/billing/customer/balance). +func (c v1CustomerBalanceTransactionService) List(ctx context.Context, listParams *CustomerBalanceTransactionListParams) Seq2[*CustomerBalanceTransaction, error] { + if listParams == nil { + listParams = &CustomerBalanceTransactionListParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/balance_transactions", StringValue(listParams.Customer)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*CustomerBalanceTransaction, ListContainer, error) { + list := &CustomerBalanceTransactionList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/customercashbalancetransaction.go b/vendor/github.com/stripe/stripe-go/v82/customercashbalancetransaction.go new file mode 100644 index 00000000..8bda0d4c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/customercashbalancetransaction.go @@ -0,0 +1,210 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The funding method type used to fund the customer balance. Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. +type CustomerCashBalanceTransactionFundedBankTransferType string + +// List of values that CustomerCashBalanceTransactionFundedBankTransferType can take +const ( + CustomerCashBalanceTransactionFundedBankTransferTypeEUBankTransfer CustomerCashBalanceTransactionFundedBankTransferType = "eu_bank_transfer" + CustomerCashBalanceTransactionFundedBankTransferTypeGBBankTransfer CustomerCashBalanceTransactionFundedBankTransferType = "gb_bank_transfer" + CustomerCashBalanceTransactionFundedBankTransferTypeJPBankTransfer CustomerCashBalanceTransactionFundedBankTransferType = "jp_bank_transfer" + CustomerCashBalanceTransactionFundedBankTransferTypeMXBankTransfer CustomerCashBalanceTransactionFundedBankTransferType = "mx_bank_transfer" + CustomerCashBalanceTransactionFundedBankTransferTypeUSBankTransfer CustomerCashBalanceTransactionFundedBankTransferType = "us_bank_transfer" +) + +// The banking network used for this funding. +type CustomerCashBalanceTransactionFundedBankTransferUSBankTransferNetwork string + +// List of values that CustomerCashBalanceTransactionFundedBankTransferUSBankTransferNetwork can take +const ( + CustomerCashBalanceTransactionFundedBankTransferUSBankTransferNetworkACH CustomerCashBalanceTransactionFundedBankTransferUSBankTransferNetwork = "ach" + CustomerCashBalanceTransactionFundedBankTransferUSBankTransferNetworkDomesticWireUS CustomerCashBalanceTransactionFundedBankTransferUSBankTransferNetwork = "domestic_wire_us" + CustomerCashBalanceTransactionFundedBankTransferUSBankTransferNetworkSwift CustomerCashBalanceTransactionFundedBankTransferUSBankTransferNetwork = "swift" +) + +// The type of the cash balance transaction. New types may be added in future. See [Customer Balance](https://stripe.com/docs/payments/customer-balance#types) to learn more about these types. +type CustomerCashBalanceTransactionType string + +// List of values that CustomerCashBalanceTransactionType can take +const ( + CustomerCashBalanceTransactionTypeAdjustedForOverdraft CustomerCashBalanceTransactionType = "adjusted_for_overdraft" + CustomerCashBalanceTransactionTypeAppliedToPayment CustomerCashBalanceTransactionType = "applied_to_payment" + CustomerCashBalanceTransactionTypeFunded CustomerCashBalanceTransactionType = "funded" + CustomerCashBalanceTransactionTypeFundingReversed CustomerCashBalanceTransactionType = "funding_reversed" + CustomerCashBalanceTransactionTypeRefundedFromPayment CustomerCashBalanceTransactionType = "refunded_from_payment" + CustomerCashBalanceTransactionTypeReturnCanceled CustomerCashBalanceTransactionType = "return_canceled" + CustomerCashBalanceTransactionTypeReturnInitiated CustomerCashBalanceTransactionType = "return_initiated" + CustomerCashBalanceTransactionTypeTransferredToBalance CustomerCashBalanceTransactionType = "transferred_to_balance" + CustomerCashBalanceTransactionTypeUnappliedFromPayment CustomerCashBalanceTransactionType = "unapplied_from_payment" +) + +// Returns a list of transactions that modified the customer's [cash balance](https://docs.stripe.com/docs/payments/customer-balance). +type CustomerCashBalanceTransactionListParams struct { + ListParams `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerCashBalanceTransactionListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a specific cash balance transaction, which updated the customer's [cash balance](https://docs.stripe.com/docs/payments/customer-balance). +type CustomerCashBalanceTransactionParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerCashBalanceTransactionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a specific cash balance transaction, which updated the customer's [cash balance](https://docs.stripe.com/docs/payments/customer-balance). +type CustomerCashBalanceTransactionRetrieveParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerCashBalanceTransactionRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type CustomerCashBalanceTransactionAdjustedForOverdraft struct { + // The [Balance Transaction](https://stripe.com/docs/api/balance_transactions/object) that corresponds to funds taken out of your Stripe balance. + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + // The [Cash Balance Transaction](https://stripe.com/docs/api/cash_balance_transactions/object) that brought the customer balance negative, triggering the clawback of funds. + LinkedTransaction *CustomerCashBalanceTransaction `json:"linked_transaction"` +} +type CustomerCashBalanceTransactionAppliedToPayment struct { + // The [Payment Intent](https://stripe.com/docs/api/payment_intents/object) that funds were applied to. + PaymentIntent *PaymentIntent `json:"payment_intent"` +} +type CustomerCashBalanceTransactionFundedBankTransferEUBankTransfer struct { + // The BIC of the bank of the sender of the funding. + BIC string `json:"bic"` + // The last 4 digits of the IBAN of the sender of the funding. + IBANLast4 string `json:"iban_last4"` + // The full name of the sender, as supplied by the sending bank. + SenderName string `json:"sender_name"` +} +type CustomerCashBalanceTransactionFundedBankTransferGBBankTransfer struct { + // The last 4 digits of the account number of the sender of the funding. + AccountNumberLast4 string `json:"account_number_last4"` + // The full name of the sender, as supplied by the sending bank. + SenderName string `json:"sender_name"` + // The sort code of the bank of the sender of the funding + SortCode string `json:"sort_code"` +} +type CustomerCashBalanceTransactionFundedBankTransferJPBankTransfer struct { + // The name of the bank of the sender of the funding. + SenderBank string `json:"sender_bank"` + // The name of the bank branch of the sender of the funding. + SenderBranch string `json:"sender_branch"` + // The full name of the sender, as supplied by the sending bank. + SenderName string `json:"sender_name"` +} +type CustomerCashBalanceTransactionFundedBankTransferUSBankTransfer struct { + // The banking network used for this funding. + Network CustomerCashBalanceTransactionFundedBankTransferUSBankTransferNetwork `json:"network"` + // The full name of the sender, as supplied by the sending bank. + SenderName string `json:"sender_name"` +} +type CustomerCashBalanceTransactionFundedBankTransfer struct { + EUBankTransfer *CustomerCashBalanceTransactionFundedBankTransferEUBankTransfer `json:"eu_bank_transfer"` + GBBankTransfer *CustomerCashBalanceTransactionFundedBankTransferGBBankTransfer `json:"gb_bank_transfer"` + JPBankTransfer *CustomerCashBalanceTransactionFundedBankTransferJPBankTransfer `json:"jp_bank_transfer"` + // The user-supplied reference field on the bank transfer. + Reference string `json:"reference"` + // The funding method type used to fund the customer balance. Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + Type CustomerCashBalanceTransactionFundedBankTransferType `json:"type"` + USBankTransfer *CustomerCashBalanceTransactionFundedBankTransferUSBankTransfer `json:"us_bank_transfer"` +} +type CustomerCashBalanceTransactionFunded struct { + BankTransfer *CustomerCashBalanceTransactionFundedBankTransfer `json:"bank_transfer"` +} +type CustomerCashBalanceTransactionRefundedFromPayment struct { + // The [Refund](https://stripe.com/docs/api/refunds/object) that moved these funds into the customer's cash balance. + Refund *Refund `json:"refund"` +} +type CustomerCashBalanceTransactionTransferredToBalance struct { + // The [Balance Transaction](https://stripe.com/docs/api/balance_transactions/object) that corresponds to funds transferred to your Stripe balance. + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` +} +type CustomerCashBalanceTransactionUnappliedFromPayment struct { + // The [Payment Intent](https://stripe.com/docs/api/payment_intents/object) that funds were unapplied from. + PaymentIntent *PaymentIntent `json:"payment_intent"` +} + +// Customers with certain payments enabled have a cash balance, representing funds that were paid +// by the customer to a merchant, but have not yet been allocated to a payment. Cash Balance Transactions +// represent when funds are moved into or out of this balance. This includes funding by the customer, allocation +// to payments, and refunds to the customer. +type CustomerCashBalanceTransaction struct { + APIResource + AdjustedForOverdraft *CustomerCashBalanceTransactionAdjustedForOverdraft `json:"adjusted_for_overdraft"` + AppliedToPayment *CustomerCashBalanceTransactionAppliedToPayment `json:"applied_to_payment"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // The customer whose available cash balance changed as a result of this transaction. + Customer *Customer `json:"customer"` + // The total available cash balance for the specified currency after this transaction was applied. Represented in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + EndingBalance int64 `json:"ending_balance"` + Funded *CustomerCashBalanceTransactionFunded `json:"funded"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // The amount by which the cash balance changed, represented in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). A positive value represents funds being added to the cash balance, a negative value represents funds being removed from the cash balance. + NetAmount int64 `json:"net_amount"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + RefundedFromPayment *CustomerCashBalanceTransactionRefundedFromPayment `json:"refunded_from_payment"` + TransferredToBalance *CustomerCashBalanceTransactionTransferredToBalance `json:"transferred_to_balance"` + // The type of the cash balance transaction. New types may be added in future. See [Customer Balance](https://stripe.com/docs/payments/customer-balance#types) to learn more about these types. + Type CustomerCashBalanceTransactionType `json:"type"` + UnappliedFromPayment *CustomerCashBalanceTransactionUnappliedFromPayment `json:"unapplied_from_payment"` +} + +// CustomerCashBalanceTransactionList is a list of CustomerCashBalanceTransactions as retrieved from a list endpoint. +type CustomerCashBalanceTransactionList struct { + APIResource + ListMeta + Data []*CustomerCashBalanceTransaction `json:"data"` +} + +// UnmarshalJSON handles deserialization of a CustomerCashBalanceTransaction. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (c *CustomerCashBalanceTransaction) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + c.ID = id + return nil + } + + type customerCashBalanceTransaction CustomerCashBalanceTransaction + var v customerCashBalanceTransaction + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *c = CustomerCashBalanceTransaction(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/customercashbalancetransaction_service.go b/vendor/github.com/stripe/stripe-go/v82/customercashbalancetransaction_service.go new file mode 100644 index 00000000..006c784a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/customercashbalancetransaction_service.go @@ -0,0 +1,55 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1CustomerCashBalanceTransactionService is used to invoke /v1/customers/{customer}/cash_balance_transactions APIs. +type v1CustomerCashBalanceTransactionService struct { + B Backend + Key string +} + +// Retrieves a specific cash balance transaction, which updated the customer's [cash balance](https://docs.stripe.com/docs/payments/customer-balance). +func (c v1CustomerCashBalanceTransactionService) Retrieve(ctx context.Context, id string, params *CustomerCashBalanceTransactionRetrieveParams) (*CustomerCashBalanceTransaction, error) { + if params == nil { + params = &CustomerCashBalanceTransactionRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/cash_balance_transactions/%s", StringValue( + params.Customer), id) + customercashbalancetransaction := &CustomerCashBalanceTransaction{} + err := c.B.Call( + http.MethodGet, path, c.Key, params, customercashbalancetransaction) + return customercashbalancetransaction, err +} + +// Returns a list of transactions that modified the customer's [cash balance](https://docs.stripe.com/docs/payments/customer-balance). +func (c v1CustomerCashBalanceTransactionService) List(ctx context.Context, listParams *CustomerCashBalanceTransactionListParams) Seq2[*CustomerCashBalanceTransaction, error] { + if listParams == nil { + listParams = &CustomerCashBalanceTransactionListParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/cash_balance_transactions", StringValue( + listParams.Customer)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*CustomerCashBalanceTransaction, ListContainer, error) { + list := &CustomerCashBalanceTransactionList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/customersession.go b/vendor/github.com/stripe/stripe-go/v82/customersession.go new file mode 100644 index 00000000..c06c1922 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/customersession.go @@ -0,0 +1,281 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// A list of [`allow_redisplay`](https://docs.stripe.com/api/payment_methods/object#payment_method_object-allow_redisplay) values that controls which saved payment methods the Payment Element displays by filtering to only show payment methods with an `allow_redisplay` value that is present in this list. +// +// If not specified, defaults to ["always"]. In order to display all saved payment methods, specify ["always", "limited", "unspecified"]. +type CustomerSessionComponentsPaymentElementFeaturesPaymentMethodAllowRedisplayFilter string + +// List of values that CustomerSessionComponentsPaymentElementFeaturesPaymentMethodAllowRedisplayFilter can take +const ( + CustomerSessionComponentsPaymentElementFeaturesPaymentMethodAllowRedisplayFilterAlways CustomerSessionComponentsPaymentElementFeaturesPaymentMethodAllowRedisplayFilter = "always" + CustomerSessionComponentsPaymentElementFeaturesPaymentMethodAllowRedisplayFilterLimited CustomerSessionComponentsPaymentElementFeaturesPaymentMethodAllowRedisplayFilter = "limited" + CustomerSessionComponentsPaymentElementFeaturesPaymentMethodAllowRedisplayFilterUnspecified CustomerSessionComponentsPaymentElementFeaturesPaymentMethodAllowRedisplayFilter = "unspecified" +) + +// Controls whether or not the Payment Element shows saved payment methods. This parameter defaults to `disabled`. +type CustomerSessionComponentsPaymentElementFeaturesPaymentMethodRedisplay string + +// List of values that CustomerSessionComponentsPaymentElementFeaturesPaymentMethodRedisplay can take +const ( + CustomerSessionComponentsPaymentElementFeaturesPaymentMethodRedisplayDisabled CustomerSessionComponentsPaymentElementFeaturesPaymentMethodRedisplay = "disabled" + CustomerSessionComponentsPaymentElementFeaturesPaymentMethodRedisplayEnabled CustomerSessionComponentsPaymentElementFeaturesPaymentMethodRedisplay = "enabled" +) + +// Controls whether the Payment Element displays the option to remove a saved payment method. This parameter defaults to `disabled`. +// +// Allowing buyers to remove their saved payment methods impacts subscriptions that depend on that payment method. Removing the payment method detaches the [`customer` object](https://docs.stripe.com/api/payment_methods/object#payment_method_object-customer) from that [PaymentMethod](https://docs.stripe.com/api/payment_methods). +type CustomerSessionComponentsPaymentElementFeaturesPaymentMethodRemove string + +// List of values that CustomerSessionComponentsPaymentElementFeaturesPaymentMethodRemove can take +const ( + CustomerSessionComponentsPaymentElementFeaturesPaymentMethodRemoveDisabled CustomerSessionComponentsPaymentElementFeaturesPaymentMethodRemove = "disabled" + CustomerSessionComponentsPaymentElementFeaturesPaymentMethodRemoveEnabled CustomerSessionComponentsPaymentElementFeaturesPaymentMethodRemove = "enabled" +) + +// Controls whether the Payment Element displays a checkbox offering to save a new payment method. This parameter defaults to `disabled`. +// +// If a customer checks the box, the [`allow_redisplay`](https://docs.stripe.com/api/payment_methods/object#payment_method_object-allow_redisplay) value on the PaymentMethod is set to `'always'` at confirmation time. For PaymentIntents, the [`setup_future_usage`](https://docs.stripe.com/api/payment_intents/object#payment_intent_object-setup_future_usage) value is also set to the value defined in `payment_method_save_usage`. +type CustomerSessionComponentsPaymentElementFeaturesPaymentMethodSave string + +// List of values that CustomerSessionComponentsPaymentElementFeaturesPaymentMethodSave can take +const ( + CustomerSessionComponentsPaymentElementFeaturesPaymentMethodSaveDisabled CustomerSessionComponentsPaymentElementFeaturesPaymentMethodSave = "disabled" + CustomerSessionComponentsPaymentElementFeaturesPaymentMethodSaveEnabled CustomerSessionComponentsPaymentElementFeaturesPaymentMethodSave = "enabled" +) + +// When using PaymentIntents and the customer checks the save checkbox, this field determines the [`setup_future_usage`](https://docs.stripe.com/api/payment_intents/object#payment_intent_object-setup_future_usage) value used to confirm the PaymentIntent. +// +// When using SetupIntents, directly configure the [`usage`](https://docs.stripe.com/api/setup_intents/object#setup_intent_object-usage) value on SetupIntent creation. +type CustomerSessionComponentsPaymentElementFeaturesPaymentMethodSaveUsage string + +// List of values that CustomerSessionComponentsPaymentElementFeaturesPaymentMethodSaveUsage can take +const ( + CustomerSessionComponentsPaymentElementFeaturesPaymentMethodSaveUsageOffSession CustomerSessionComponentsPaymentElementFeaturesPaymentMethodSaveUsage = "off_session" + CustomerSessionComponentsPaymentElementFeaturesPaymentMethodSaveUsageOnSession CustomerSessionComponentsPaymentElementFeaturesPaymentMethodSaveUsage = "on_session" +) + +// Configuration for buy button. +type CustomerSessionComponentsBuyButtonParams struct { + // Whether the buy button is enabled. + Enabled *bool `form:"enabled"` +} + +// This hash defines whether the Payment Element supports certain features. +type CustomerSessionComponentsPaymentElementFeaturesParams struct { + // A list of [`allow_redisplay`](https://docs.stripe.com/api/payment_methods/object#payment_method_object-allow_redisplay) values that controls which saved payment methods the Payment Element displays by filtering to only show payment methods with an `allow_redisplay` value that is present in this list. + // + // If not specified, defaults to ["always"]. In order to display all saved payment methods, specify ["always", "limited", "unspecified"]. + PaymentMethodAllowRedisplayFilters []*string `form:"payment_method_allow_redisplay_filters"` + // Controls whether or not the Payment Element shows saved payment methods. This parameter defaults to `disabled`. + PaymentMethodRedisplay *string `form:"payment_method_redisplay"` + // Determines the max number of saved payment methods for the Payment Element to display. This parameter defaults to `3`. The maximum redisplay limit is `10`. + PaymentMethodRedisplayLimit *int64 `form:"payment_method_redisplay_limit"` + // Controls whether the Payment Element displays the option to remove a saved payment method. This parameter defaults to `disabled`. + // + // Allowing buyers to remove their saved payment methods impacts subscriptions that depend on that payment method. Removing the payment method detaches the [`customer` object](https://docs.stripe.com/api/payment_methods/object#payment_method_object-customer) from that [PaymentMethod](https://docs.stripe.com/api/payment_methods). + PaymentMethodRemove *string `form:"payment_method_remove"` + // Controls whether the Payment Element displays a checkbox offering to save a new payment method. This parameter defaults to `disabled`. + // + // If a customer checks the box, the [`allow_redisplay`](https://docs.stripe.com/api/payment_methods/object#payment_method_object-allow_redisplay) value on the PaymentMethod is set to `'always'` at confirmation time. For PaymentIntents, the [`setup_future_usage`](https://docs.stripe.com/api/payment_intents/object#payment_intent_object-setup_future_usage) value is also set to the value defined in `payment_method_save_usage`. + PaymentMethodSave *string `form:"payment_method_save"` + // When using PaymentIntents and the customer checks the save checkbox, this field determines the [`setup_future_usage`](https://docs.stripe.com/api/payment_intents/object#payment_intent_object-setup_future_usage) value used to confirm the PaymentIntent. + // + // When using SetupIntents, directly configure the [`usage`](https://docs.stripe.com/api/setup_intents/object#setup_intent_object-usage) value on SetupIntent creation. + PaymentMethodSaveUsage *string `form:"payment_method_save_usage"` +} + +// Configuration for the Payment Element. +type CustomerSessionComponentsPaymentElementParams struct { + // Whether the Payment Element is enabled. + Enabled *bool `form:"enabled"` + // This hash defines whether the Payment Element supports certain features. + Features *CustomerSessionComponentsPaymentElementFeaturesParams `form:"features"` +} + +// Configuration for the pricing table. +type CustomerSessionComponentsPricingTableParams struct { + // Whether the pricing table is enabled. + Enabled *bool `form:"enabled"` +} + +// Configuration for each component. Exactly 1 component must be enabled. +type CustomerSessionComponentsParams struct { + // Configuration for buy button. + BuyButton *CustomerSessionComponentsBuyButtonParams `form:"buy_button"` + // Configuration for the Payment Element. + PaymentElement *CustomerSessionComponentsPaymentElementParams `form:"payment_element"` + // Configuration for the pricing table. + PricingTable *CustomerSessionComponentsPricingTableParams `form:"pricing_table"` +} + +// Creates a Customer Session object that includes a single-use client secret that you can use on your front-end to grant client-side API access for certain customer resources. +type CustomerSessionParams struct { + Params `form:"*"` + // Configuration for each component. Exactly 1 component must be enabled. + Components *CustomerSessionComponentsParams `form:"components"` + // The ID of an existing customer for which to create the Customer Session. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerSessionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Configuration for buy button. +type CustomerSessionCreateComponentsBuyButtonParams struct { + // Whether the buy button is enabled. + Enabled *bool `form:"enabled"` +} + +// This hash defines whether the Payment Element supports certain features. +type CustomerSessionCreateComponentsPaymentElementFeaturesParams struct { + // A list of [`allow_redisplay`](https://docs.stripe.com/api/payment_methods/object#payment_method_object-allow_redisplay) values that controls which saved payment methods the Payment Element displays by filtering to only show payment methods with an `allow_redisplay` value that is present in this list. + // + // If not specified, defaults to ["always"]. In order to display all saved payment methods, specify ["always", "limited", "unspecified"]. + PaymentMethodAllowRedisplayFilters []*string `form:"payment_method_allow_redisplay_filters"` + // Controls whether or not the Payment Element shows saved payment methods. This parameter defaults to `disabled`. + PaymentMethodRedisplay *string `form:"payment_method_redisplay"` + // Determines the max number of saved payment methods for the Payment Element to display. This parameter defaults to `3`. The maximum redisplay limit is `10`. + PaymentMethodRedisplayLimit *int64 `form:"payment_method_redisplay_limit"` + // Controls whether the Payment Element displays the option to remove a saved payment method. This parameter defaults to `disabled`. + // + // Allowing buyers to remove their saved payment methods impacts subscriptions that depend on that payment method. Removing the payment method detaches the [`customer` object](https://docs.stripe.com/api/payment_methods/object#payment_method_object-customer) from that [PaymentMethod](https://docs.stripe.com/api/payment_methods). + PaymentMethodRemove *string `form:"payment_method_remove"` + // Controls whether the Payment Element displays a checkbox offering to save a new payment method. This parameter defaults to `disabled`. + // + // If a customer checks the box, the [`allow_redisplay`](https://docs.stripe.com/api/payment_methods/object#payment_method_object-allow_redisplay) value on the PaymentMethod is set to `'always'` at confirmation time. For PaymentIntents, the [`setup_future_usage`](https://docs.stripe.com/api/payment_intents/object#payment_intent_object-setup_future_usage) value is also set to the value defined in `payment_method_save_usage`. + PaymentMethodSave *string `form:"payment_method_save"` + // When using PaymentIntents and the customer checks the save checkbox, this field determines the [`setup_future_usage`](https://docs.stripe.com/api/payment_intents/object#payment_intent_object-setup_future_usage) value used to confirm the PaymentIntent. + // + // When using SetupIntents, directly configure the [`usage`](https://docs.stripe.com/api/setup_intents/object#setup_intent_object-usage) value on SetupIntent creation. + PaymentMethodSaveUsage *string `form:"payment_method_save_usage"` +} + +// Configuration for the Payment Element. +type CustomerSessionCreateComponentsPaymentElementParams struct { + // Whether the Payment Element is enabled. + Enabled *bool `form:"enabled"` + // This hash defines whether the Payment Element supports certain features. + Features *CustomerSessionCreateComponentsPaymentElementFeaturesParams `form:"features"` +} + +// Configuration for the pricing table. +type CustomerSessionCreateComponentsPricingTableParams struct { + // Whether the pricing table is enabled. + Enabled *bool `form:"enabled"` +} + +// Configuration for each component. Exactly 1 component must be enabled. +type CustomerSessionCreateComponentsParams struct { + // Configuration for buy button. + BuyButton *CustomerSessionCreateComponentsBuyButtonParams `form:"buy_button"` + // Configuration for the Payment Element. + PaymentElement *CustomerSessionCreateComponentsPaymentElementParams `form:"payment_element"` + // Configuration for the pricing table. + PricingTable *CustomerSessionCreateComponentsPricingTableParams `form:"pricing_table"` +} + +// Creates a Customer Session object that includes a single-use client secret that you can use on your front-end to grant client-side API access for certain customer resources. +type CustomerSessionCreateParams struct { + Params `form:"*"` + // Configuration for each component. Exactly 1 component must be enabled. + Components *CustomerSessionCreateComponentsParams `form:"components"` + // The ID of an existing customer for which to create the Customer Session. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *CustomerSessionCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// This hash contains whether the buy button is enabled. +type CustomerSessionComponentsBuyButton struct { + // Whether the buy button is enabled. + Enabled bool `json:"enabled"` +} + +// This hash defines whether the Payment Element supports certain features. +type CustomerSessionComponentsPaymentElementFeatures struct { + // A list of [`allow_redisplay`](https://docs.stripe.com/api/payment_methods/object#payment_method_object-allow_redisplay) values that controls which saved payment methods the Payment Element displays by filtering to only show payment methods with an `allow_redisplay` value that is present in this list. + // + // If not specified, defaults to ["always"]. In order to display all saved payment methods, specify ["always", "limited", "unspecified"]. + PaymentMethodAllowRedisplayFilters []CustomerSessionComponentsPaymentElementFeaturesPaymentMethodAllowRedisplayFilter `json:"payment_method_allow_redisplay_filters"` + // Controls whether or not the Payment Element shows saved payment methods. This parameter defaults to `disabled`. + PaymentMethodRedisplay CustomerSessionComponentsPaymentElementFeaturesPaymentMethodRedisplay `json:"payment_method_redisplay"` + // Determines the max number of saved payment methods for the Payment Element to display. This parameter defaults to `3`. The maximum redisplay limit is `10`. + PaymentMethodRedisplayLimit int64 `json:"payment_method_redisplay_limit"` + // Controls whether the Payment Element displays the option to remove a saved payment method. This parameter defaults to `disabled`. + // + // Allowing buyers to remove their saved payment methods impacts subscriptions that depend on that payment method. Removing the payment method detaches the [`customer` object](https://docs.stripe.com/api/payment_methods/object#payment_method_object-customer) from that [PaymentMethod](https://docs.stripe.com/api/payment_methods). + PaymentMethodRemove CustomerSessionComponentsPaymentElementFeaturesPaymentMethodRemove `json:"payment_method_remove"` + // Controls whether the Payment Element displays a checkbox offering to save a new payment method. This parameter defaults to `disabled`. + // + // If a customer checks the box, the [`allow_redisplay`](https://docs.stripe.com/api/payment_methods/object#payment_method_object-allow_redisplay) value on the PaymentMethod is set to `'always'` at confirmation time. For PaymentIntents, the [`setup_future_usage`](https://docs.stripe.com/api/payment_intents/object#payment_intent_object-setup_future_usage) value is also set to the value defined in `payment_method_save_usage`. + PaymentMethodSave CustomerSessionComponentsPaymentElementFeaturesPaymentMethodSave `json:"payment_method_save"` + // When using PaymentIntents and the customer checks the save checkbox, this field determines the [`setup_future_usage`](https://docs.stripe.com/api/payment_intents/object#payment_intent_object-setup_future_usage) value used to confirm the PaymentIntent. + // + // When using SetupIntents, directly configure the [`usage`](https://docs.stripe.com/api/setup_intents/object#setup_intent_object-usage) value on SetupIntent creation. + PaymentMethodSaveUsage CustomerSessionComponentsPaymentElementFeaturesPaymentMethodSaveUsage `json:"payment_method_save_usage"` +} + +// This hash contains whether the Payment Element is enabled and the features it supports. +type CustomerSessionComponentsPaymentElement struct { + // Whether the Payment Element is enabled. + Enabled bool `json:"enabled"` + // This hash defines whether the Payment Element supports certain features. + Features *CustomerSessionComponentsPaymentElementFeatures `json:"features"` +} + +// This hash contains whether the pricing table is enabled. +type CustomerSessionComponentsPricingTable struct { + // Whether the pricing table is enabled. + Enabled bool `json:"enabled"` +} + +// Configuration for the components supported by this Customer Session. +type CustomerSessionComponents struct { + // This hash contains whether the buy button is enabled. + BuyButton *CustomerSessionComponentsBuyButton `json:"buy_button"` + // This hash contains whether the Payment Element is enabled and the features it supports. + PaymentElement *CustomerSessionComponentsPaymentElement `json:"payment_element"` + // This hash contains whether the pricing table is enabled. + PricingTable *CustomerSessionComponentsPricingTable `json:"pricing_table"` +} + +// A Customer Session allows you to grant Stripe's frontend SDKs (like Stripe.js) client-side access +// control over a Customer. +// +// Related guides: [Customer Session with the Payment Element](https://docs.stripe.com/payments/accept-a-payment-deferred?platform=web&type=payment#save-payment-methods), +// [Customer Session with the Pricing Table](https://docs.stripe.com/payments/checkout/pricing-table#customer-session), +// [Customer Session with the Buy Button](https://docs.stripe.com/payment-links/buy-button#pass-an-existing-customer). +type CustomerSession struct { + APIResource + // The client secret of this Customer Session. Used on the client to set up secure access to the given `customer`. + // + // The client secret can be used to provide access to `customer` from your frontend. It should not be stored, logged, or exposed to anyone other than the relevant customer. Make sure that you have TLS enabled on any page that includes the client secret. + ClientSecret string `json:"client_secret"` + // Configuration for the components supported by this Customer Session. + Components *CustomerSessionComponents `json:"components"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The Customer the Customer Session was created for. + Customer *Customer `json:"customer"` + // The timestamp at which this Customer Session will expire. + ExpiresAt int64 `json:"expires_at"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/customersession_service.go b/vendor/github.com/stripe/stripe-go/v82/customersession_service.go new file mode 100644 index 00000000..671f1dcb --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/customersession_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1CustomerSessionService is used to invoke /v1/customer_sessions APIs. +type v1CustomerSessionService struct { + B Backend + Key string +} + +// Creates a Customer Session object that includes a single-use client secret that you can use on your front-end to grant client-side API access for certain customer resources. +func (c v1CustomerSessionService) Create(ctx context.Context, params *CustomerSessionCreateParams) (*CustomerSession, error) { + if params == nil { + params = &CustomerSessionCreateParams{} + } + params.Context = ctx + customersession := &CustomerSession{} + err := c.B.Call( + http.MethodPost, "/v1/customer_sessions", c.Key, params, customersession) + return customersession, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/discount.go b/vendor/github.com/stripe/stripe-go/v82/discount.go new file mode 100644 index 00000000..c671330f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/discount.go @@ -0,0 +1,62 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// A discount represents the actual application of a [coupon](https://stripe.com/docs/api#coupons) or [promotion code](https://stripe.com/docs/api#promotion_codes). +// It contains information about when the discount began, when it will end, and what it is applied to. +// +// Related guide: [Applying discounts to subscriptions](https://stripe.com/docs/billing/subscriptions/discounts) +type Discount struct { + // The Checkout session that this coupon is applied to, if it is applied to a particular session in payment mode. Will not be present for subscription mode. + CheckoutSession string `json:"checkout_session"` + // A coupon contains information about a percent-off or amount-off discount you + // might want to apply to a customer. Coupons may be applied to [subscriptions](https://stripe.com/docs/api#subscriptions), [invoices](https://stripe.com/docs/api#invoices), + // [checkout sessions](https://stripe.com/docs/api/checkout/sessions), [quotes](https://stripe.com/docs/api#quotes), and more. Coupons do not work with conventional one-off [charges](https://stripe.com/docs/api#create_charge) or [payment intents](https://stripe.com/docs/api/payment_intents). + Coupon *Coupon `json:"coupon"` + // The ID of the customer associated with this discount. + Customer *Customer `json:"customer"` + Deleted bool `json:"deleted"` + // If the coupon has a duration of `repeating`, the date that this discount will end. If the coupon has a duration of `once` or `forever`, this attribute will be null. + End int64 `json:"end"` + // The ID of the discount object. Discounts cannot be fetched by ID. Use `expand[]=discounts` in API calls to expand discount IDs in an array. + ID string `json:"id"` + // The invoice that the discount's coupon was applied to, if it was applied directly to a particular invoice. + Invoice string `json:"invoice"` + // The invoice item `id` (or invoice line item `id` for invoice line items of type='subscription') that the discount's coupon was applied to, if it was applied directly to a particular invoice item or invoice line item. + InvoiceItem string `json:"invoice_item"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The promotion code applied to create this discount. + PromotionCode *PromotionCode `json:"promotion_code"` + // Date that the coupon was applied. + Start int64 `json:"start"` + // The subscription that this coupon is applied to, if it is applied to a particular subscription. + Subscription string `json:"subscription"` + // The subscription item that this coupon is applied to, if it is applied to a particular subscription item. + SubscriptionItem string `json:"subscription_item"` +} + +// UnmarshalJSON handles deserialization of a Discount. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (d *Discount) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + d.ID = id + return nil + } + + type discount Discount + var v discount + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *d = Discount(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/dispute.go b/vendor/github.com/stripe/stripe-go/v82/dispute.go new file mode 100644 index 00000000..096c653a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/dispute.go @@ -0,0 +1,704 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// List of eligibility types that are included in `enhanced_evidence`. +type DisputeEnhancedEligibilityType string + +// List of values that DisputeEnhancedEligibilityType can take +const ( + DisputeEnhancedEligibilityTypeVisaCompellingEvidence3 DisputeEnhancedEligibilityType = "visa_compelling_evidence_3" + DisputeEnhancedEligibilityTypeVisaCompliance DisputeEnhancedEligibilityType = "visa_compliance" +) + +// Categorization of disputed payment. +type DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3DisputedTransactionMerchandiseOrServices string + +// List of values that DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3DisputedTransactionMerchandiseOrServices can take +const ( + DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3DisputedTransactionMerchandiseOrServicesMerchandise DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3DisputedTransactionMerchandiseOrServices = "merchandise" + DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3DisputedTransactionMerchandiseOrServicesServices DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3DisputedTransactionMerchandiseOrServices = "services" +) + +// List of actions required to qualify dispute for Visa Compelling Evidence 3.0 evidence submission. +type DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3RequiredAction string + +// List of values that DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3RequiredAction can take +const ( + DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3RequiredActionMissingCustomerIdentifiers DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3RequiredAction = "missing_customer_identifiers" + DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3RequiredActionMissingDisputedTransactionDescription DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3RequiredAction = "missing_disputed_transaction_description" + DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3RequiredActionMissingMerchandiseOrServices DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3RequiredAction = "missing_merchandise_or_services" + DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3RequiredActionMissingPriorUndisputedTransactionDescription DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3RequiredAction = "missing_prior_undisputed_transaction_description" + DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3RequiredActionMissingPriorUndisputedTransactions DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3RequiredAction = "missing_prior_undisputed_transactions" +) + +// Visa Compelling Evidence 3.0 eligibility status. +type DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3Status string + +// List of values that DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3Status can take +const ( + DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3StatusNotQualified DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3Status = "not_qualified" + DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3StatusQualified DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3Status = "qualified" + DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3StatusRequiresAction DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3Status = "requires_action" +) + +// Visa compliance eligibility status. +type DisputeEvidenceDetailsEnhancedEligibilityVisaComplianceStatus string + +// List of values that DisputeEvidenceDetailsEnhancedEligibilityVisaComplianceStatus can take +const ( + DisputeEvidenceDetailsEnhancedEligibilityVisaComplianceStatusFeeAcknowledged DisputeEvidenceDetailsEnhancedEligibilityVisaComplianceStatus = "fee_acknowledged" + DisputeEvidenceDetailsEnhancedEligibilityVisaComplianceStatusRequiresFeeAcknowledgement DisputeEvidenceDetailsEnhancedEligibilityVisaComplianceStatus = "requires_fee_acknowledgement" +) + +// The AmazonPay dispute type, chargeback or claim +type DisputePaymentMethodDetailsAmazonPayDisputeType string + +// List of values that DisputePaymentMethodDetailsAmazonPayDisputeType can take +const ( + DisputePaymentMethodDetailsAmazonPayDisputeTypeChargeback DisputePaymentMethodDetailsAmazonPayDisputeType = "chargeback" + DisputePaymentMethodDetailsAmazonPayDisputeTypeClaim DisputePaymentMethodDetailsAmazonPayDisputeType = "claim" +) + +// The type of dispute opened. Different case types may have varying fees and financial impact. +type DisputePaymentMethodDetailsCardCaseType string + +// List of values that DisputePaymentMethodDetailsCardCaseType can take +const ( + DisputePaymentMethodDetailsCardCaseTypeChargeback DisputePaymentMethodDetailsCardCaseType = "chargeback" + DisputePaymentMethodDetailsCardCaseTypeCompliance DisputePaymentMethodDetailsCardCaseType = "compliance" + DisputePaymentMethodDetailsCardCaseTypeInquiry DisputePaymentMethodDetailsCardCaseType = "inquiry" +) + +// Payment method type. +type DisputePaymentMethodDetailsType string + +// List of values that DisputePaymentMethodDetailsType can take +const ( + DisputePaymentMethodDetailsTypeAmazonPay DisputePaymentMethodDetailsType = "amazon_pay" + DisputePaymentMethodDetailsTypeCard DisputePaymentMethodDetailsType = "card" + DisputePaymentMethodDetailsTypeKlarna DisputePaymentMethodDetailsType = "klarna" + DisputePaymentMethodDetailsTypePaypal DisputePaymentMethodDetailsType = "paypal" +) + +// Reason given by cardholder for dispute. Possible values are `bank_cannot_process`, `check_returned`, `credit_not_processed`, `customer_initiated`, `debit_not_authorized`, `duplicate`, `fraudulent`, `general`, `incorrect_account_details`, `insufficient_funds`, `noncompliant`, `product_not_received`, `product_unacceptable`, `subscription_canceled`, or `unrecognized`. Learn more about [dispute reasons](https://stripe.com/docs/disputes/categories). +type DisputeReason string + +// List of values that DisputeReason can take +const ( + DisputeReasonBankCannotProcess DisputeReason = "bank_cannot_process" + DisputeReasonCheckReturned DisputeReason = "check_returned" + DisputeReasonCreditNotProcessed DisputeReason = "credit_not_processed" + DisputeReasonCustomerInitiated DisputeReason = "customer_initiated" + DisputeReasonDebitNotAuthorized DisputeReason = "debit_not_authorized" + DisputeReasonDuplicate DisputeReason = "duplicate" + DisputeReasonFraudulent DisputeReason = "fraudulent" + DisputeReasonGeneral DisputeReason = "general" + DisputeReasonIncorrectAccountDetails DisputeReason = "incorrect_account_details" + DisputeReasonInsufficientFunds DisputeReason = "insufficient_funds" + DisputeReasonNoncompliant DisputeReason = "noncompliant" + DisputeReasonProductNotReceived DisputeReason = "product_not_received" + DisputeReasonProductUnacceptable DisputeReason = "product_unacceptable" + DisputeReasonSubscriptionCanceled DisputeReason = "subscription_canceled" + DisputeReasonUnrecognized DisputeReason = "unrecognized" +) + +// Current status of dispute. Possible values are `warning_needs_response`, `warning_under_review`, `warning_closed`, `needs_response`, `under_review`, `won`, or `lost`. +type DisputeStatus string + +// List of values that DisputeStatus can take +const ( + DisputeStatusLost DisputeStatus = "lost" + DisputeStatusNeedsResponse DisputeStatus = "needs_response" + DisputeStatusUnderReview DisputeStatus = "under_review" + DisputeStatusWarningClosed DisputeStatus = "warning_closed" + DisputeStatusWarningNeedsResponse DisputeStatus = "warning_needs_response" + DisputeStatusWarningUnderReview DisputeStatus = "warning_under_review" + DisputeStatusWon DisputeStatus = "won" +) + +// Returns a list of your disputes. +type DisputeListParams struct { + ListParams `form:"*"` + // Only return disputes associated to the charge specified by this charge ID. + Charge *string `form:"charge"` + // Only return disputes that were created during the given date interval. + Created *int64 `form:"created"` + // Only return disputes that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return disputes associated to the PaymentIntent specified by this PaymentIntent ID. + PaymentIntent *string `form:"payment_intent"` +} + +// AddExpand appends a new field to expand. +func (p *DisputeListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the dispute with the given ID. +type DisputeParams struct { + Params `form:"*"` + // Evidence to upload, to respond to a dispute. Updating any field in the hash will submit all fields in the hash for review. The combined character count of all fields is limited to 150,000. + Evidence *DisputeEvidenceParams `form:"evidence"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Whether to immediately submit evidence to the bank. If `false`, evidence is staged on the dispute. Staged evidence is visible in the API and Dashboard, and can be submitted to the bank by making another request with this attribute set to `true` (the default). + Submit *bool `form:"submit"` +} + +// AddExpand appends a new field to expand. +func (p *DisputeParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *DisputeParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Disputed transaction details for Visa Compelling Evidence 3.0 evidence submission. +type DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3DisputedTransactionParams struct { + // User Account ID used to log into business platform. Must be recognizable by the user. + CustomerAccountID *string `form:"customer_account_id"` + // Unique identifier of the cardholder's device derived from a combination of at least two hardware and software attributes. Must be at least 20 characters. + CustomerDeviceFingerprint *string `form:"customer_device_fingerprint"` + // Unique identifier of the cardholder's device such as a device serial number (e.g., International Mobile Equipment Identity [IMEI]). Must be at least 15 characters. + CustomerDeviceID *string `form:"customer_device_id"` + // The email address of the customer. + CustomerEmailAddress *string `form:"customer_email_address"` + // The IP address that the customer used when making the purchase. + CustomerPurchaseIP *string `form:"customer_purchase_ip"` + // Categorization of disputed payment. + MerchandiseOrServices *string `form:"merchandise_or_services"` + // A description of the product or service that was sold. + ProductDescription *string `form:"product_description"` + // The address to which a physical product was shipped. All fields are required for Visa Compelling Evidence 3.0 evidence submission. + ShippingAddress *AddressParams `form:"shipping_address"` +} + +// List of exactly two prior undisputed transaction objects for Visa Compelling Evidence 3.0 evidence submission. +type DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3PriorUndisputedTransactionParams struct { + // Stripe charge ID for the Visa Compelling Evidence 3.0 eligible prior charge. + Charge *string `form:"charge"` + // User Account ID used to log into business platform. Must be recognizable by the user. + CustomerAccountID *string `form:"customer_account_id"` + // Unique identifier of the cardholder's device derived from a combination of at least two hardware and software attributes. Must be at least 20 characters. + CustomerDeviceFingerprint *string `form:"customer_device_fingerprint"` + // Unique identifier of the cardholder's device such as a device serial number (e.g., International Mobile Equipment Identity [IMEI]). Must be at least 15 characters. + CustomerDeviceID *string `form:"customer_device_id"` + // The email address of the customer. + CustomerEmailAddress *string `form:"customer_email_address"` + // The IP address that the customer used when making the purchase. + CustomerPurchaseIP *string `form:"customer_purchase_ip"` + // A description of the product or service that was sold. + ProductDescription *string `form:"product_description"` + // The address to which a physical product was shipped. All fields are required for Visa Compelling Evidence 3.0 evidence submission. + ShippingAddress *AddressParams `form:"shipping_address"` +} + +// Evidence provided for Visa Compelling Evidence 3.0 evidence submission. +type DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3Params struct { + // Disputed transaction details for Visa Compelling Evidence 3.0 evidence submission. + DisputedTransaction *DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3DisputedTransactionParams `form:"disputed_transaction"` + // List of exactly two prior undisputed transaction objects for Visa Compelling Evidence 3.0 evidence submission. + PriorUndisputedTransactions []*DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3PriorUndisputedTransactionParams `form:"prior_undisputed_transactions"` +} + +// Evidence provided for Visa compliance evidence submission. +type DisputeEvidenceEnhancedEvidenceVisaComplianceParams struct { + // A field acknowledging the fee incurred when countering a Visa compliance dispute. If this field is set to true, evidence can be submitted for the compliance dispute. Stripe collects a 500 USD (or local equivalent) amount to cover the network costs associated with resolving compliance disputes. Stripe refunds the 500 USD network fee if you win the dispute. + FeeAcknowledged *bool `form:"fee_acknowledged"` +} + +// Additional evidence for qualifying evidence programs. +type DisputeEvidenceEnhancedEvidenceParams struct { + // Evidence provided for Visa Compelling Evidence 3.0 evidence submission. + VisaCompellingEvidence3 *DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3Params `form:"visa_compelling_evidence_3"` + // Evidence provided for Visa compliance evidence submission. + VisaCompliance *DisputeEvidenceEnhancedEvidenceVisaComplianceParams `form:"visa_compliance"` +} + +// Evidence to upload, to respond to a dispute. Updating any field in the hash will submit all fields in the hash for review. The combined character count of all fields is limited to 150,000. +type DisputeEvidenceParams struct { + // Any server or activity logs showing proof that the customer accessed or downloaded the purchased digital product. This information should include IP addresses, corresponding timestamps, and any detailed recorded activity. Has a maximum character count of 20,000. + AccessActivityLog *string `form:"access_activity_log"` + // The billing address provided by the customer. + BillingAddress *string `form:"billing_address"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Your subscription cancellation policy, as shown to the customer. + CancellationPolicy *string `form:"cancellation_policy"` + // An explanation of how and when the customer was shown your refund policy prior to purchase. Has a maximum character count of 20,000. + CancellationPolicyDisclosure *string `form:"cancellation_policy_disclosure"` + // A justification for why the customer's subscription was not canceled. Has a maximum character count of 20,000. + CancellationRebuttal *string `form:"cancellation_rebuttal"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any communication with the customer that you feel is relevant to your case. Examples include emails proving that the customer received the product or service, or demonstrating their use of or satisfaction with the product or service. + CustomerCommunication *string `form:"customer_communication"` + // The email address of the customer. + CustomerEmailAddress *string `form:"customer_email_address"` + // The name of the customer. + CustomerName *string `form:"customer_name"` + // The IP address that the customer used when making the purchase. + CustomerPurchaseIP *string `form:"customer_purchase_ip"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) A relevant document or contract showing the customer's signature. + CustomerSignature *string `form:"customer_signature"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation for the prior charge that can uniquely identify the charge, such as a receipt, shipping label, work order, etc. This document should be paired with a similar document from the disputed payment that proves the two payments are separate. + DuplicateChargeDocumentation *string `form:"duplicate_charge_documentation"` + // An explanation of the difference between the disputed charge versus the prior charge that appears to be a duplicate. Has a maximum character count of 20,000. + DuplicateChargeExplanation *string `form:"duplicate_charge_explanation"` + // The Stripe ID for the prior charge which appears to be a duplicate of the disputed charge. + DuplicateChargeID *string `form:"duplicate_charge_id"` + // Additional evidence for qualifying evidence programs. + EnhancedEvidence *DisputeEvidenceEnhancedEvidenceParams `form:"enhanced_evidence"` + // A description of the product or service that was sold. Has a maximum character count of 20,000. + ProductDescription *string `form:"product_description"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any receipt or message sent to the customer notifying them of the charge. + Receipt *string `form:"receipt"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Your refund policy, as shown to the customer. + RefundPolicy *string `form:"refund_policy"` + // Documentation demonstrating that the customer was shown your refund policy prior to purchase. Has a maximum character count of 20,000. + RefundPolicyDisclosure *string `form:"refund_policy_disclosure"` + // A justification for why the customer is not entitled to a refund. Has a maximum character count of 20,000. + RefundRefusalExplanation *string `form:"refund_refusal_explanation"` + // The date on which the customer received or began receiving the purchased service, in a clear human-readable format. + ServiceDate *string `form:"service_date"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation showing proof that a service was provided to the customer. This could include a copy of a signed contract, work order, or other form of written agreement. + ServiceDocumentation *string `form:"service_documentation"` + // The address to which a physical product was shipped. You should try to include as complete address information as possible. + ShippingAddress *string `form:"shipping_address"` + // The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. If multiple carriers were used for this purchase, please separate them with commas. + ShippingCarrier *string `form:"shipping_carrier"` + // The date on which a physical product began its route to the shipping address, in a clear human-readable format. + ShippingDate *string `form:"shipping_date"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation showing proof that a product was shipped to the customer at the same address the customer provided to you. This could include a copy of the shipment receipt, shipping label, etc. It should show the customer's full shipping address, if possible. + ShippingDocumentation *string `form:"shipping_documentation"` + // The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas. + ShippingTrackingNumber *string `form:"shipping_tracking_number"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any additional evidence or statements. + UncategorizedFile *string `form:"uncategorized_file"` + // Any additional evidence or statements. Has a maximum character count of 20,000. + UncategorizedText *string `form:"uncategorized_text"` +} + +// Closing the dispute for a charge indicates that you do not have any evidence to submit and are essentially dismissing the dispute, acknowledging it as lost. +// +// The status of the dispute will change from needs_response to lost. Closing a dispute is irreversible. +type DisputeCloseParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *DisputeCloseParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the dispute with the given ID. +type DisputeRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *DisputeRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Disputed transaction details for Visa Compelling Evidence 3.0 evidence submission. +type DisputeUpdateEvidenceEnhancedEvidenceVisaCompellingEvidence3DisputedTransactionParams struct { + // User Account ID used to log into business platform. Must be recognizable by the user. + CustomerAccountID *string `form:"customer_account_id"` + // Unique identifier of the cardholder's device derived from a combination of at least two hardware and software attributes. Must be at least 20 characters. + CustomerDeviceFingerprint *string `form:"customer_device_fingerprint"` + // Unique identifier of the cardholder's device such as a device serial number (e.g., International Mobile Equipment Identity [IMEI]). Must be at least 15 characters. + CustomerDeviceID *string `form:"customer_device_id"` + // The email address of the customer. + CustomerEmailAddress *string `form:"customer_email_address"` + // The IP address that the customer used when making the purchase. + CustomerPurchaseIP *string `form:"customer_purchase_ip"` + // Categorization of disputed payment. + MerchandiseOrServices *string `form:"merchandise_or_services"` + // A description of the product or service that was sold. + ProductDescription *string `form:"product_description"` + // The address to which a physical product was shipped. All fields are required for Visa Compelling Evidence 3.0 evidence submission. + ShippingAddress *AddressParams `form:"shipping_address"` +} + +// List of exactly two prior undisputed transaction objects for Visa Compelling Evidence 3.0 evidence submission. +type DisputeUpdateEvidenceEnhancedEvidenceVisaCompellingEvidence3PriorUndisputedTransactionParams struct { + // Stripe charge ID for the Visa Compelling Evidence 3.0 eligible prior charge. + Charge *string `form:"charge"` + // User Account ID used to log into business platform. Must be recognizable by the user. + CustomerAccountID *string `form:"customer_account_id"` + // Unique identifier of the cardholder's device derived from a combination of at least two hardware and software attributes. Must be at least 20 characters. + CustomerDeviceFingerprint *string `form:"customer_device_fingerprint"` + // Unique identifier of the cardholder's device such as a device serial number (e.g., International Mobile Equipment Identity [IMEI]). Must be at least 15 characters. + CustomerDeviceID *string `form:"customer_device_id"` + // The email address of the customer. + CustomerEmailAddress *string `form:"customer_email_address"` + // The IP address that the customer used when making the purchase. + CustomerPurchaseIP *string `form:"customer_purchase_ip"` + // A description of the product or service that was sold. + ProductDescription *string `form:"product_description"` + // The address to which a physical product was shipped. All fields are required for Visa Compelling Evidence 3.0 evidence submission. + ShippingAddress *AddressParams `form:"shipping_address"` +} + +// Evidence provided for Visa Compelling Evidence 3.0 evidence submission. +type DisputeUpdateEvidenceEnhancedEvidenceVisaCompellingEvidence3Params struct { + // Disputed transaction details for Visa Compelling Evidence 3.0 evidence submission. + DisputedTransaction *DisputeUpdateEvidenceEnhancedEvidenceVisaCompellingEvidence3DisputedTransactionParams `form:"disputed_transaction"` + // List of exactly two prior undisputed transaction objects for Visa Compelling Evidence 3.0 evidence submission. + PriorUndisputedTransactions []*DisputeUpdateEvidenceEnhancedEvidenceVisaCompellingEvidence3PriorUndisputedTransactionParams `form:"prior_undisputed_transactions"` +} + +// Evidence provided for Visa compliance evidence submission. +type DisputeUpdateEvidenceEnhancedEvidenceVisaComplianceParams struct { + // A field acknowledging the fee incurred when countering a Visa compliance dispute. If this field is set to true, evidence can be submitted for the compliance dispute. Stripe collects a 500 USD (or local equivalent) amount to cover the network costs associated with resolving compliance disputes. Stripe refunds the 500 USD network fee if you win the dispute. + FeeAcknowledged *bool `form:"fee_acknowledged"` +} + +// Additional evidence for qualifying evidence programs. +type DisputeUpdateEvidenceEnhancedEvidenceParams struct { + // Evidence provided for Visa Compelling Evidence 3.0 evidence submission. + VisaCompellingEvidence3 *DisputeUpdateEvidenceEnhancedEvidenceVisaCompellingEvidence3Params `form:"visa_compelling_evidence_3"` + // Evidence provided for Visa compliance evidence submission. + VisaCompliance *DisputeUpdateEvidenceEnhancedEvidenceVisaComplianceParams `form:"visa_compliance"` +} + +// Evidence to upload, to respond to a dispute. Updating any field in the hash will submit all fields in the hash for review. The combined character count of all fields is limited to 150,000. +type DisputeUpdateEvidenceParams struct { + // Any server or activity logs showing proof that the customer accessed or downloaded the purchased digital product. This information should include IP addresses, corresponding timestamps, and any detailed recorded activity. Has a maximum character count of 20,000. + AccessActivityLog *string `form:"access_activity_log"` + // The billing address provided by the customer. + BillingAddress *string `form:"billing_address"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Your subscription cancellation policy, as shown to the customer. + CancellationPolicy *string `form:"cancellation_policy"` + // An explanation of how and when the customer was shown your refund policy prior to purchase. Has a maximum character count of 20,000. + CancellationPolicyDisclosure *string `form:"cancellation_policy_disclosure"` + // A justification for why the customer's subscription was not canceled. Has a maximum character count of 20,000. + CancellationRebuttal *string `form:"cancellation_rebuttal"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any communication with the customer that you feel is relevant to your case. Examples include emails proving that the customer received the product or service, or demonstrating their use of or satisfaction with the product or service. + CustomerCommunication *string `form:"customer_communication"` + // The email address of the customer. + CustomerEmailAddress *string `form:"customer_email_address"` + // The name of the customer. + CustomerName *string `form:"customer_name"` + // The IP address that the customer used when making the purchase. + CustomerPurchaseIP *string `form:"customer_purchase_ip"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) A relevant document or contract showing the customer's signature. + CustomerSignature *string `form:"customer_signature"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation for the prior charge that can uniquely identify the charge, such as a receipt, shipping label, work order, etc. This document should be paired with a similar document from the disputed payment that proves the two payments are separate. + DuplicateChargeDocumentation *string `form:"duplicate_charge_documentation"` + // An explanation of the difference between the disputed charge versus the prior charge that appears to be a duplicate. Has a maximum character count of 20,000. + DuplicateChargeExplanation *string `form:"duplicate_charge_explanation"` + // The Stripe ID for the prior charge which appears to be a duplicate of the disputed charge. + DuplicateChargeID *string `form:"duplicate_charge_id"` + // Additional evidence for qualifying evidence programs. + EnhancedEvidence *DisputeUpdateEvidenceEnhancedEvidenceParams `form:"enhanced_evidence"` + // A description of the product or service that was sold. Has a maximum character count of 20,000. + ProductDescription *string `form:"product_description"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any receipt or message sent to the customer notifying them of the charge. + Receipt *string `form:"receipt"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Your refund policy, as shown to the customer. + RefundPolicy *string `form:"refund_policy"` + // Documentation demonstrating that the customer was shown your refund policy prior to purchase. Has a maximum character count of 20,000. + RefundPolicyDisclosure *string `form:"refund_policy_disclosure"` + // A justification for why the customer is not entitled to a refund. Has a maximum character count of 20,000. + RefundRefusalExplanation *string `form:"refund_refusal_explanation"` + // The date on which the customer received or began receiving the purchased service, in a clear human-readable format. + ServiceDate *string `form:"service_date"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation showing proof that a service was provided to the customer. This could include a copy of a signed contract, work order, or other form of written agreement. + ServiceDocumentation *string `form:"service_documentation"` + // The address to which a physical product was shipped. You should try to include as complete address information as possible. + ShippingAddress *string `form:"shipping_address"` + // The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. If multiple carriers were used for this purchase, please separate them with commas. + ShippingCarrier *string `form:"shipping_carrier"` + // The date on which a physical product began its route to the shipping address, in a clear human-readable format. + ShippingDate *string `form:"shipping_date"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation showing proof that a product was shipped to the customer at the same address the customer provided to you. This could include a copy of the shipment receipt, shipping label, etc. It should show the customer's full shipping address, if possible. + ShippingDocumentation *string `form:"shipping_documentation"` + // The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas. + ShippingTrackingNumber *string `form:"shipping_tracking_number"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any additional evidence or statements. + UncategorizedFile *string `form:"uncategorized_file"` + // Any additional evidence or statements. Has a maximum character count of 20,000. + UncategorizedText *string `form:"uncategorized_text"` +} + +// When you get a dispute, contacting your customer is always the best first step. If that doesn't work, you can submit evidence to help us resolve the dispute in your favor. You can do this in your [dashboard](https://dashboard.stripe.com/disputes), but if you prefer, you can use the API to submit evidence programmatically. +// +// Depending on your dispute type, different evidence fields will give you a better chance of winning your dispute. To figure out which evidence fields to provide, see our [guide to dispute types](https://docs.stripe.com/docs/disputes/categories). +type DisputeUpdateParams struct { + Params `form:"*"` + // Evidence to upload, to respond to a dispute. Updating any field in the hash will submit all fields in the hash for review. The combined character count of all fields is limited to 150,000. + Evidence *DisputeUpdateEvidenceParams `form:"evidence"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Whether to immediately submit evidence to the bank. If `false`, evidence is staged on the dispute. Staged evidence is visible in the API and Dashboard, and can be submitted to the bank by making another request with this attribute set to `true` (the default). + Submit *bool `form:"submit"` +} + +// AddExpand appends a new field to expand. +func (p *DisputeUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *DisputeUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Disputed transaction details for Visa Compelling Evidence 3.0 evidence submission. +type DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3DisputedTransaction struct { + // User Account ID used to log into business platform. Must be recognizable by the user. + CustomerAccountID string `json:"customer_account_id"` + // Unique identifier of the cardholder's device derived from a combination of at least two hardware and software attributes. Must be at least 20 characters. + CustomerDeviceFingerprint string `json:"customer_device_fingerprint"` + // Unique identifier of the cardholder's device such as a device serial number (e.g., International Mobile Equipment Identity [IMEI]). Must be at least 15 characters. + CustomerDeviceID string `json:"customer_device_id"` + // The email address of the customer. + CustomerEmailAddress string `json:"customer_email_address"` + // The IP address that the customer used when making the purchase. + CustomerPurchaseIP string `json:"customer_purchase_ip"` + // Categorization of disputed payment. + MerchandiseOrServices DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3DisputedTransactionMerchandiseOrServices `json:"merchandise_or_services"` + // A description of the product or service that was sold. + ProductDescription string `json:"product_description"` + // The address to which a physical product was shipped. All fields are required for Visa Compelling Evidence 3.0 evidence submission. + ShippingAddress *Address `json:"shipping_address"` +} + +// List of exactly two prior undisputed transaction objects for Visa Compelling Evidence 3.0 evidence submission. +type DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3PriorUndisputedTransaction struct { + // Stripe charge ID for the Visa Compelling Evidence 3.0 eligible prior charge. + Charge string `json:"charge"` + // User Account ID used to log into business platform. Must be recognizable by the user. + CustomerAccountID string `json:"customer_account_id"` + // Unique identifier of the cardholder's device derived from a combination of at least two hardware and software attributes. Must be at least 20 characters. + CustomerDeviceFingerprint string `json:"customer_device_fingerprint"` + // Unique identifier of the cardholder's device such as a device serial number (e.g., International Mobile Equipment Identity [IMEI]). Must be at least 15 characters. + CustomerDeviceID string `json:"customer_device_id"` + // The email address of the customer. + CustomerEmailAddress string `json:"customer_email_address"` + // The IP address that the customer used when making the purchase. + CustomerPurchaseIP string `json:"customer_purchase_ip"` + // A description of the product or service that was sold. + ProductDescription string `json:"product_description"` + // The address to which a physical product was shipped. All fields are required for Visa Compelling Evidence 3.0 evidence submission. + ShippingAddress *Address `json:"shipping_address"` +} +type DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3 struct { + // Disputed transaction details for Visa Compelling Evidence 3.0 evidence submission. + DisputedTransaction *DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3DisputedTransaction `json:"disputed_transaction"` + // List of exactly two prior undisputed transaction objects for Visa Compelling Evidence 3.0 evidence submission. + PriorUndisputedTransactions []*DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3PriorUndisputedTransaction `json:"prior_undisputed_transactions"` +} +type DisputeEvidenceEnhancedEvidenceVisaCompliance struct { + // A field acknowledging the fee incurred when countering a Visa compliance dispute. If this field is set to true, evidence can be submitted for the compliance dispute. Stripe collects a 500 USD (or local equivalent) amount to cover the network costs associated with resolving compliance disputes. Stripe refunds the 500 USD network fee if you win the dispute. + FeeAcknowledged bool `json:"fee_acknowledged"` +} +type DisputeEvidenceEnhancedEvidence struct { + VisaCompellingEvidence3 *DisputeEvidenceEnhancedEvidenceVisaCompellingEvidence3 `json:"visa_compelling_evidence_3"` + VisaCompliance *DisputeEvidenceEnhancedEvidenceVisaCompliance `json:"visa_compliance"` +} +type DisputeEvidence struct { + // Any server or activity logs showing proof that the customer accessed or downloaded the purchased digital product. This information should include IP addresses, corresponding timestamps, and any detailed recorded activity. + AccessActivityLog string `json:"access_activity_log"` + // The billing address provided by the customer. + BillingAddress string `json:"billing_address"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Your subscription cancellation policy, as shown to the customer. + CancellationPolicy *File `json:"cancellation_policy"` + // An explanation of how and when the customer was shown your refund policy prior to purchase. + CancellationPolicyDisclosure string `json:"cancellation_policy_disclosure"` + // A justification for why the customer's subscription was not canceled. + CancellationRebuttal string `json:"cancellation_rebuttal"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any communication with the customer that you feel is relevant to your case. Examples include emails proving that the customer received the product or service, or demonstrating their use of or satisfaction with the product or service. + CustomerCommunication *File `json:"customer_communication"` + // The email address of the customer. + CustomerEmailAddress string `json:"customer_email_address"` + // The name of the customer. + CustomerName string `json:"customer_name"` + // The IP address that the customer used when making the purchase. + CustomerPurchaseIP string `json:"customer_purchase_ip"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) A relevant document or contract showing the customer's signature. + CustomerSignature *File `json:"customer_signature"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation for the prior charge that can uniquely identify the charge, such as a receipt, shipping label, work order, etc. This document should be paired with a similar document from the disputed payment that proves the two payments are separate. + DuplicateChargeDocumentation *File `json:"duplicate_charge_documentation"` + // An explanation of the difference between the disputed charge versus the prior charge that appears to be a duplicate. + DuplicateChargeExplanation string `json:"duplicate_charge_explanation"` + // The Stripe ID for the prior charge which appears to be a duplicate of the disputed charge. + DuplicateChargeID string `json:"duplicate_charge_id"` + EnhancedEvidence *DisputeEvidenceEnhancedEvidence `json:"enhanced_evidence"` + // A description of the product or service that was sold. + ProductDescription string `json:"product_description"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any receipt or message sent to the customer notifying them of the charge. + Receipt *File `json:"receipt"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Your refund policy, as shown to the customer. + RefundPolicy *File `json:"refund_policy"` + // Documentation demonstrating that the customer was shown your refund policy prior to purchase. + RefundPolicyDisclosure string `json:"refund_policy_disclosure"` + // A justification for why the customer is not entitled to a refund. + RefundRefusalExplanation string `json:"refund_refusal_explanation"` + // The date on which the customer received or began receiving the purchased service, in a clear human-readable format. + ServiceDate string `json:"service_date"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation showing proof that a service was provided to the customer. This could include a copy of a signed contract, work order, or other form of written agreement. + ServiceDocumentation *File `json:"service_documentation"` + // The address to which a physical product was shipped. You should try to include as complete address information as possible. + ShippingAddress string `json:"shipping_address"` + // The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. If multiple carriers were used for this purchase, please separate them with commas. + ShippingCarrier string `json:"shipping_carrier"` + // The date on which a physical product began its route to the shipping address, in a clear human-readable format. + ShippingDate string `json:"shipping_date"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation showing proof that a product was shipped to the customer at the same address the customer provided to you. This could include a copy of the shipment receipt, shipping label, etc. It should show the customer's full shipping address, if possible. + ShippingDocumentation *File `json:"shipping_documentation"` + // The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas. + ShippingTrackingNumber string `json:"shipping_tracking_number"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any additional evidence or statements. + UncategorizedFile *File `json:"uncategorized_file"` + // Any additional evidence or statements. + UncategorizedText string `json:"uncategorized_text"` +} +type DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3 struct { + // List of actions required to qualify dispute for Visa Compelling Evidence 3.0 evidence submission. + RequiredActions []DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3RequiredAction `json:"required_actions"` + // Visa Compelling Evidence 3.0 eligibility status. + Status DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3Status `json:"status"` +} +type DisputeEvidenceDetailsEnhancedEligibilityVisaCompliance struct { + // Visa compliance eligibility status. + Status DisputeEvidenceDetailsEnhancedEligibilityVisaComplianceStatus `json:"status"` +} +type DisputeEvidenceDetailsEnhancedEligibility struct { + VisaCompellingEvidence3 *DisputeEvidenceDetailsEnhancedEligibilityVisaCompellingEvidence3 `json:"visa_compelling_evidence_3"` + VisaCompliance *DisputeEvidenceDetailsEnhancedEligibilityVisaCompliance `json:"visa_compliance"` +} +type DisputeEvidenceDetails struct { + // Date by which evidence must be submitted in order to successfully challenge dispute. Will be 0 if the customer's bank or credit card company doesn't allow a response for this particular dispute. + DueBy int64 `json:"due_by"` + EnhancedEligibility *DisputeEvidenceDetailsEnhancedEligibility `json:"enhanced_eligibility"` + // Whether evidence has been staged for this dispute. + HasEvidence bool `json:"has_evidence"` + // Whether the last evidence submission was submitted past the due date. Defaults to `false` if no evidence submissions have occurred. If `true`, then delivery of the latest evidence is *not* guaranteed. + PastDue bool `json:"past_due"` + // The number of times evidence has been submitted. Typically, you may only submit evidence once. + SubmissionCount int64 `json:"submission_count"` +} +type DisputePaymentMethodDetailsAmazonPay struct { + // The AmazonPay dispute type, chargeback or claim + DisputeType DisputePaymentMethodDetailsAmazonPayDisputeType `json:"dispute_type"` +} +type DisputePaymentMethodDetailsCard struct { + // Card brand. Can be `amex`, `diners`, `discover`, `eftpos_au`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Brand string `json:"brand"` + // The type of dispute opened. Different case types may have varying fees and financial impact. + CaseType DisputePaymentMethodDetailsCardCaseType `json:"case_type"` + // The card network's specific dispute reason code, which maps to one of Stripe's primary dispute categories to simplify response guidance. The [Network code map](https://stripe.com/docs/disputes/categories#network-code-map) lists all available dispute reason codes by network. + NetworkReasonCode string `json:"network_reason_code"` +} +type DisputePaymentMethodDetailsKlarna struct { + // The reason for the dispute as defined by Klarna + ReasonCode string `json:"reason_code"` +} +type DisputePaymentMethodDetailsPaypal struct { + // The ID of the dispute in PayPal. + CaseID string `json:"case_id"` + // The reason for the dispute as defined by PayPal + ReasonCode string `json:"reason_code"` +} +type DisputePaymentMethodDetails struct { + AmazonPay *DisputePaymentMethodDetailsAmazonPay `json:"amazon_pay"` + Card *DisputePaymentMethodDetailsCard `json:"card"` + Klarna *DisputePaymentMethodDetailsKlarna `json:"klarna"` + Paypal *DisputePaymentMethodDetailsPaypal `json:"paypal"` + // Payment method type. + Type DisputePaymentMethodDetailsType `json:"type"` +} + +// A dispute occurs when a customer questions your charge with their card issuer. +// When this happens, you have the opportunity to respond to the dispute with +// evidence that shows that the charge is legitimate. +// +// Related guide: [Disputes and fraud](https://stripe.com/docs/disputes) +type Dispute struct { + APIResource + // Disputed amount. Usually the amount of the charge, but it can differ (usually because of currency fluctuation or because only part of the order is disputed). + Amount int64 `json:"amount"` + // List of zero, one, or two balance transactions that show funds withdrawn and reinstated to your Stripe account as a result of this dispute. + BalanceTransactions []*BalanceTransaction `json:"balance_transactions"` + // ID of the charge that's disputed. + Charge *Charge `json:"charge"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // List of eligibility types that are included in `enhanced_evidence`. + EnhancedEligibilityTypes []DisputeEnhancedEligibilityType `json:"enhanced_eligibility_types"` + Evidence *DisputeEvidence `json:"evidence"` + EvidenceDetails *DisputeEvidenceDetails `json:"evidence_details"` + // Unique identifier for the object. + ID string `json:"id"` + // If true, it's still possible to refund the disputed payment. After the payment has been fully refunded, no further funds are withdrawn from your Stripe account as a result of this dispute. + IsChargeRefundable bool `json:"is_charge_refundable"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // Network-dependent reason code for the dispute. + NetworkReasonCode string `json:"network_reason_code"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // ID of the PaymentIntent that's disputed. + PaymentIntent *PaymentIntent `json:"payment_intent"` + PaymentMethodDetails *DisputePaymentMethodDetails `json:"payment_method_details"` + // Reason given by cardholder for dispute. Possible values are `bank_cannot_process`, `check_returned`, `credit_not_processed`, `customer_initiated`, `debit_not_authorized`, `duplicate`, `fraudulent`, `general`, `incorrect_account_details`, `insufficient_funds`, `noncompliant`, `product_not_received`, `product_unacceptable`, `subscription_canceled`, or `unrecognized`. Learn more about [dispute reasons](https://stripe.com/docs/disputes/categories). + Reason DisputeReason `json:"reason"` + // Current status of dispute. Possible values are `warning_needs_response`, `warning_under_review`, `warning_closed`, `needs_response`, `under_review`, `won`, or `lost`. + Status DisputeStatus `json:"status"` +} + +// DisputeList is a list of Disputes as retrieved from a list endpoint. +type DisputeList struct { + APIResource + ListMeta + Data []*Dispute `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Dispute. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (d *Dispute) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + d.ID = id + return nil + } + + type dispute Dispute + var v dispute + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *d = Dispute(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/dispute_service.go b/vendor/github.com/stripe/stripe-go/v82/dispute_service.go new file mode 100644 index 00000000..779aa2c6 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/dispute_service.go @@ -0,0 +1,77 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1DisputeService is used to invoke /v1/disputes APIs. +type v1DisputeService struct { + B Backend + Key string +} + +// Retrieves the dispute with the given ID. +func (c v1DisputeService) Retrieve(ctx context.Context, id string, params *DisputeRetrieveParams) (*Dispute, error) { + if params == nil { + params = &DisputeRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/disputes/%s", id) + dispute := &Dispute{} + err := c.B.Call(http.MethodGet, path, c.Key, params, dispute) + return dispute, err +} + +// When you get a dispute, contacting your customer is always the best first step. If that doesn't work, you can submit evidence to help us resolve the dispute in your favor. You can do this in your [dashboard](https://dashboard.stripe.com/disputes), but if you prefer, you can use the API to submit evidence programmatically. +// +// Depending on your dispute type, different evidence fields will give you a better chance of winning your dispute. To figure out which evidence fields to provide, see our [guide to dispute types](https://docs.stripe.com/docs/disputes/categories). +func (c v1DisputeService) Update(ctx context.Context, id string, params *DisputeUpdateParams) (*Dispute, error) { + if params == nil { + params = &DisputeUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/disputes/%s", id) + dispute := &Dispute{} + err := c.B.Call(http.MethodPost, path, c.Key, params, dispute) + return dispute, err +} + +// Closing the dispute for a charge indicates that you do not have any evidence to submit and are essentially dismissing the dispute, acknowledging it as lost. +// +// The status of the dispute will change from needs_response to lost. Closing a dispute is irreversible. +func (c v1DisputeService) Close(ctx context.Context, id string, params *DisputeCloseParams) (*Dispute, error) { + path := FormatURLPath("/v1/disputes/%s/close", id) + dispute := &Dispute{} + if params == nil { + params = &DisputeCloseParams{} + } + params.Context = ctx + err := c.B.Call(http.MethodPost, path, c.Key, params, dispute) + return dispute, err +} + +// Returns a list of your disputes. +func (c v1DisputeService) List(ctx context.Context, listParams *DisputeListParams) Seq2[*Dispute, error] { + if listParams == nil { + listParams = &DisputeListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Dispute, ListContainer, error) { + list := &DisputeList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/disputes", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/entitlements_activeentitlement.go b/vendor/github.com/stripe/stripe-go/v82/entitlements_activeentitlement.go new file mode 100644 index 00000000..c2c981e6 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/entitlements_activeentitlement.go @@ -0,0 +1,67 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Retrieve a list of active entitlements for a customer +type EntitlementsActiveEntitlementListParams struct { + ListParams `form:"*"` + // The ID of the customer. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *EntitlementsActiveEntitlementListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieve an active entitlement +type EntitlementsActiveEntitlementParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *EntitlementsActiveEntitlementParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieve an active entitlement +type EntitlementsActiveEntitlementRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *EntitlementsActiveEntitlementRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// An active entitlement describes access to a feature for a customer. +type EntitlementsActiveEntitlement struct { + APIResource + // The [Feature](https://stripe.com/docs/api/entitlements/feature) that the customer is entitled to. + Feature *EntitlementsFeature `json:"feature"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // A unique key you provide as your own system identifier. This may be up to 80 characters. + LookupKey string `json:"lookup_key"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} + +// EntitlementsActiveEntitlementList is a list of ActiveEntitlements as retrieved from a list endpoint. +type EntitlementsActiveEntitlementList struct { + APIResource + ListMeta + Data []*EntitlementsActiveEntitlement `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/entitlements_activeentitlement_service.go b/vendor/github.com/stripe/stripe-go/v82/entitlements_activeentitlement_service.go new file mode 100644 index 00000000..eb417f56 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/entitlements_activeentitlement_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1EntitlementsActiveEntitlementService is used to invoke /v1/entitlements/active_entitlements APIs. +type v1EntitlementsActiveEntitlementService struct { + B Backend + Key string +} + +// Retrieve an active entitlement +func (c v1EntitlementsActiveEntitlementService) Retrieve(ctx context.Context, id string, params *EntitlementsActiveEntitlementRetrieveParams) (*EntitlementsActiveEntitlement, error) { + if params == nil { + params = &EntitlementsActiveEntitlementRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/entitlements/active_entitlements/%s", id) + activeentitlement := &EntitlementsActiveEntitlement{} + err := c.B.Call(http.MethodGet, path, c.Key, params, activeentitlement) + return activeentitlement, err +} + +// Retrieve a list of active entitlements for a customer +func (c v1EntitlementsActiveEntitlementService) List(ctx context.Context, listParams *EntitlementsActiveEntitlementListParams) Seq2[*EntitlementsActiveEntitlement, error] { + if listParams == nil { + listParams = &EntitlementsActiveEntitlementListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*EntitlementsActiveEntitlement, ListContainer, error) { + list := &EntitlementsActiveEntitlementList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/entitlements/active_entitlements", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/entitlements_activeentitlementsummary.go b/vendor/github.com/stripe/stripe-go/v82/entitlements_activeentitlementsummary.go new file mode 100644 index 00000000..a5fa8a82 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/entitlements_activeentitlementsummary.go @@ -0,0 +1,19 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// A summary of a customer's active entitlements. +type EntitlementsActiveEntitlementSummary struct { + // The customer that is entitled to this feature. + Customer string `json:"customer"` + // The list of entitlements this customer has. + Entitlements *EntitlementsActiveEntitlementList `json:"entitlements"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/entitlements_feature.go b/vendor/github.com/stripe/stripe-go/v82/entitlements_feature.go new file mode 100644 index 00000000..d66b4611 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/entitlements_feature.go @@ -0,0 +1,166 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Retrieve a list of features +type EntitlementsFeatureListParams struct { + ListParams `form:"*"` + // If set, filter results to only include features with the given archive status. + Archived *bool `form:"archived"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // If set, filter results to only include features with the given lookup_key. + LookupKey *string `form:"lookup_key"` +} + +// AddExpand appends a new field to expand. +func (p *EntitlementsFeatureListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates a feature +type EntitlementsFeatureParams struct { + Params `form:"*"` + // Inactive features cannot be attached to new products and will not be returned from the features list endpoint. + Active *bool `form:"active"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A unique key you provide as your own system identifier. This may be up to 80 characters. + LookupKey *string `form:"lookup_key"` + // Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `form:"metadata"` + // The feature's name, for your own purpose, not meant to be displayable to the customer. + Name *string `form:"name"` +} + +// AddExpand appends a new field to expand. +func (p *EntitlementsFeatureParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *EntitlementsFeatureParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Creates a feature +type EntitlementsFeatureCreateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A unique key you provide as your own system identifier. This may be up to 80 characters. + LookupKey *string `form:"lookup_key"` + // Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `form:"metadata"` + // The feature's name, for your own purpose, not meant to be displayable to the customer. + Name *string `form:"name"` +} + +// AddExpand appends a new field to expand. +func (p *EntitlementsFeatureCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *EntitlementsFeatureCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves a feature +type EntitlementsFeatureRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *EntitlementsFeatureRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Update a feature's metadata or permanently deactivate it. +type EntitlementsFeatureUpdateParams struct { + Params `form:"*"` + // Inactive features cannot be attached to new products and will not be returned from the features list endpoint. + Active *bool `form:"active"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `form:"metadata"` + // The feature's name, for your own purpose, not meant to be displayable to the customer. + Name *string `form:"name"` +} + +// AddExpand appends a new field to expand. +func (p *EntitlementsFeatureUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *EntitlementsFeatureUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A feature represents a monetizable ability or functionality in your system. +// Features can be assigned to products, and when those products are purchased, Stripe will create an entitlement to the feature for the purchasing customer. +type EntitlementsFeature struct { + APIResource + // Inactive features cannot be attached to new products and will not be returned from the features list endpoint. + Active bool `json:"active"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // A unique key you provide as your own system identifier. This may be up to 80 characters. + LookupKey string `json:"lookup_key"` + // Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // The feature's name, for your own purpose, not meant to be displayable to the customer. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} + +// EntitlementsFeatureList is a list of Features as retrieved from a list endpoint. +type EntitlementsFeatureList struct { + APIResource + ListMeta + Data []*EntitlementsFeature `json:"data"` +} + +// UnmarshalJSON handles deserialization of an EntitlementsFeature. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (e *EntitlementsFeature) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + e.ID = id + return nil + } + + type entitlementsFeature EntitlementsFeature + var v entitlementsFeature + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *e = EntitlementsFeature(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/entitlements_feature_service.go b/vendor/github.com/stripe/stripe-go/v82/entitlements_feature_service.go new file mode 100644 index 00000000..520d1593 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/entitlements_feature_service.go @@ -0,0 +1,73 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1EntitlementsFeatureService is used to invoke /v1/entitlements/features APIs. +type v1EntitlementsFeatureService struct { + B Backend + Key string +} + +// Creates a feature +func (c v1EntitlementsFeatureService) Create(ctx context.Context, params *EntitlementsFeatureCreateParams) (*EntitlementsFeature, error) { + if params == nil { + params = &EntitlementsFeatureCreateParams{} + } + params.Context = ctx + feature := &EntitlementsFeature{} + err := c.B.Call( + http.MethodPost, "/v1/entitlements/features", c.Key, params, feature) + return feature, err +} + +// Retrieves a feature +func (c v1EntitlementsFeatureService) Retrieve(ctx context.Context, id string, params *EntitlementsFeatureRetrieveParams) (*EntitlementsFeature, error) { + if params == nil { + params = &EntitlementsFeatureRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/entitlements/features/%s", id) + feature := &EntitlementsFeature{} + err := c.B.Call(http.MethodGet, path, c.Key, params, feature) + return feature, err +} + +// Update a feature's metadata or permanently deactivate it. +func (c v1EntitlementsFeatureService) Update(ctx context.Context, id string, params *EntitlementsFeatureUpdateParams) (*EntitlementsFeature, error) { + if params == nil { + params = &EntitlementsFeatureUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/entitlements/features/%s", id) + feature := &EntitlementsFeature{} + err := c.B.Call(http.MethodPost, path, c.Key, params, feature) + return feature, err +} + +// Retrieve a list of features +func (c v1EntitlementsFeatureService) List(ctx context.Context, listParams *EntitlementsFeatureListParams) Seq2[*EntitlementsFeature, error] { + if listParams == nil { + listParams = &EntitlementsFeatureListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*EntitlementsFeature, ListContainer, error) { + list := &EntitlementsFeatureList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/entitlements/features", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/ephemeralkey.go b/vendor/github.com/stripe/stripe-go/v82/ephemeralkey.go new file mode 100644 index 00000000..8d9bd8b5 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/ephemeralkey.go @@ -0,0 +1,106 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Invalidates a short-lived API key for a given resource. +type EphemeralKeyParams struct { + Params `form:"*"` + // The ID of the Customer you'd like to modify using the resulting ephemeral key. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The ID of the Issuing Card you'd like to access using the resulting ephemeral key. + IssuingCard *string `form:"issuing_card"` + // A single-use token, created by Stripe.js, used for creating ephemeral keys for Issuing Cards without exchanging sensitive information. + Nonce *string `form:"nonce"` + // The ID of the Identity VerificationSession you'd like to access using the resulting ephemeral key + VerificationSession *string `form:"verification_session"` + StripeVersion *string `form:"-"` // This goes in the `Stripe-Version` header +} + +// AddExpand appends a new field to expand. +func (p *EphemeralKeyParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Invalidates a short-lived API key for a given resource. +type EphemeralKeyDeleteParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *EphemeralKeyDeleteParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates a short-lived API key for a given resource. +type EphemeralKeyCreateParams struct { + Params `form:"*"` + // The ID of the Customer you'd like to modify using the resulting ephemeral key. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The ID of the Issuing Card you'd like to access using the resulting ephemeral key. + IssuingCard *string `form:"issuing_card"` + // A single-use token, created by Stripe.js, used for creating ephemeral keys for Issuing Cards without exchanging sensitive information. + Nonce *string `form:"nonce"` + // The ID of the Identity VerificationSession you'd like to access using the resulting ephemeral key + VerificationSession *string `form:"verification_session"` + StripeVersion *string `form:"-"` // This goes in the `Stripe-Version` header +} + +// AddExpand appends a new field to expand. +func (p *EphemeralKeyCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type EphemeralKey struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Time at which the key will expire. Measured in seconds since the Unix epoch. + Expires int64 `json:"expires"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The key's secret. You can use this value to make authorized requests to the Stripe API. + Secret string `json:"secret"` + // RawJSON is provided so that it may be passed back to the frontend + // unchanged. Ephemeral keys are issued on behalf of another client which + // may be running a different version of the bindings and thus expect a + // different JSON structure. This ensures that if the structure differs + // from the version of these bindings, we can still pass back a compatible + // key. + RawJSON []byte `json:"-"` +} + +// UnmarshalJSON handles deserialization of an EphemeralKey. +// This custom unmarshaling is needed because we need to store the +// raw JSON on the object so it may be passed back to the frontend. + +func (e *EphemeralKey) UnmarshalJSON(data []byte) error { + type ephemeralKey EphemeralKey + var ee ephemeralKey + err := json.Unmarshal(data, &ee) + if err == nil { + *e = EphemeralKey(ee) + } + + // Go does guarantee the longevity of `data`, so copy when assigning `RawJSON` + // See https://golang.org/pkg/encoding/json/#Unmarshaler + // and https://github.com/stripe/stripe-go/pull/1142 + e.RawJSON = append(e.RawJSON[:0], data...) + + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/ephemeralkey_service.go b/vendor/github.com/stripe/stripe-go/v82/ephemeralkey_service.go new file mode 100644 index 00000000..146387fb --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/ephemeralkey_service.go @@ -0,0 +1,42 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1EphemeralKeyService is used to invoke /v1/ephemeral_keys APIs. +type v1EphemeralKeyService struct { + B Backend + Key string +} + +// Creates a short-lived API key for a given resource. +func (c v1EphemeralKeyService) Create(ctx context.Context, params *EphemeralKeyCreateParams) (*EphemeralKey, error) { + if params == nil { + params = &EphemeralKeyCreateParams{} + } + params.Context = ctx + ephemeralkey := &EphemeralKey{} + err := c.B.Call( + http.MethodPost, "/v1/ephemeral_keys", c.Key, params, ephemeralkey) + return ephemeralkey, err +} + +// Invalidates a short-lived API key for a given resource. +func (c v1EphemeralKeyService) Delete(ctx context.Context, id string, params *EphemeralKeyDeleteParams) (*EphemeralKey, error) { + if params == nil { + params = &EphemeralKeyDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/ephemeral_keys/%s", id) + ephemeralkey := &EphemeralKey{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, ephemeralkey) + return ephemeralkey, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/error.go b/vendor/github.com/stripe/stripe-go/v82/error.go new file mode 100644 index 00000000..3df4d378 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/error.go @@ -0,0 +1,469 @@ +package stripe + +import ( + "encoding/json" + "net/http" +) + +// errorEnums: The beginning of the section generated from our OpenAPI spec +// errorEnums: The end of the section generated from our OpenAPI spec + +// ErrorType is the list of allowed values for the error's type. +type ErrorType string + +// List of values that ErrorType can take. +// errorTypes: The beginning of the section generated from our OpenAPI spec +const ( + ErrorTypeAPI ErrorType = "api_error" + ErrorTypeCard ErrorType = "card_error" + ErrorTypeIdempotency ErrorType = "idempotency_error" + ErrorTypeInvalidRequest ErrorType = "invalid_request_error" + + // V2 error types + ErrorTypeTemporarySessionExpired ErrorType = "temporary_session_expired" +) + +// errorTypes: The end of the section generated from our OpenAPI spec + +// DeclineCode is the list of reasons provided by card issuers for decline of payment. +type DeclineCode string + +// ErrorCode is the list of allowed values for the error's code. +type ErrorCode string + +// List of values that ErrorCode can take. +// For descriptions see https://stripe.com/docs/error-codes +// v1ErrorCodes: The beginning of the section generated from our OpenAPI spec +const ( + ErrorCodeACSSDebitSessionIncomplete ErrorCode = "acss_debit_session_incomplete" + ErrorCodeAPIKeyExpired ErrorCode = "api_key_expired" + ErrorCodeAccountClosed ErrorCode = "account_closed" + ErrorCodeAccountCountryInvalidAddress ErrorCode = "account_country_invalid_address" + ErrorCodeAccountErrorCountryChangeRequiresAdditionalSteps ErrorCode = "account_error_country_change_requires_additional_steps" + ErrorCodeAccountInformationMismatch ErrorCode = "account_information_mismatch" + ErrorCodeAccountInvalid ErrorCode = "account_invalid" + ErrorCodeAccountNumberInvalid ErrorCode = "account_number_invalid" + ErrorCodeAlipayUpgradeRequired ErrorCode = "alipay_upgrade_required" + ErrorCodeAmountTooLarge ErrorCode = "amount_too_large" + ErrorCodeAmountTooSmall ErrorCode = "amount_too_small" + ErrorCodeApplicationFeesNotAllowed ErrorCode = "application_fees_not_allowed" + ErrorCodeAuthenticationRequired ErrorCode = "authentication_required" + ErrorCodeBalanceInsufficient ErrorCode = "balance_insufficient" + ErrorCodeBalanceInvalidParameter ErrorCode = "balance_invalid_parameter" + ErrorCodeBankAccountBadRoutingNumbers ErrorCode = "bank_account_bad_routing_numbers" + ErrorCodeBankAccountDeclined ErrorCode = "bank_account_declined" + ErrorCodeBankAccountExists ErrorCode = "bank_account_exists" + ErrorCodeBankAccountRestricted ErrorCode = "bank_account_restricted" + ErrorCodeBankAccountUnusable ErrorCode = "bank_account_unusable" + ErrorCodeBankAccountUnverified ErrorCode = "bank_account_unverified" + ErrorCodeBankAccountVerificationFailed ErrorCode = "bank_account_verification_failed" + ErrorCodeBillingInvalidMandate ErrorCode = "billing_invalid_mandate" + ErrorCodeBitcoinUpgradeRequired ErrorCode = "bitcoin_upgrade_required" + ErrorCodeCaptureChargeAuthorizationExpired ErrorCode = "capture_charge_authorization_expired" + ErrorCodeCaptureUnauthorizedPayment ErrorCode = "capture_unauthorized_payment" + ErrorCodeCardDeclineRateLimitExceeded ErrorCode = "card_decline_rate_limit_exceeded" + ErrorCodeCardDeclined ErrorCode = "card_declined" + ErrorCodeCardholderPhoneNumberRequired ErrorCode = "cardholder_phone_number_required" + ErrorCodeChargeAlreadyCaptured ErrorCode = "charge_already_captured" + ErrorCodeChargeAlreadyRefunded ErrorCode = "charge_already_refunded" + ErrorCodeChargeDisputed ErrorCode = "charge_disputed" + ErrorCodeChargeExceedsSourceLimit ErrorCode = "charge_exceeds_source_limit" + ErrorCodeChargeExceedsTransactionLimit ErrorCode = "charge_exceeds_transaction_limit" + ErrorCodeChargeExpiredForCapture ErrorCode = "charge_expired_for_capture" + ErrorCodeChargeInvalidParameter ErrorCode = "charge_invalid_parameter" + ErrorCodeChargeNotRefundable ErrorCode = "charge_not_refundable" + ErrorCodeClearingCodeUnsupported ErrorCode = "clearing_code_unsupported" + ErrorCodeCountryCodeInvalid ErrorCode = "country_code_invalid" + ErrorCodeCountryUnsupported ErrorCode = "country_unsupported" + ErrorCodeCouponExpired ErrorCode = "coupon_expired" + ErrorCodeCustomerMaxPaymentMethods ErrorCode = "customer_max_payment_methods" + ErrorCodeCustomerMaxSubscriptions ErrorCode = "customer_max_subscriptions" + ErrorCodeCustomerTaxLocationInvalid ErrorCode = "customer_tax_location_invalid" + ErrorCodeDebitNotAuthorized ErrorCode = "debit_not_authorized" + ErrorCodeEmailInvalid ErrorCode = "email_invalid" + ErrorCodeExpiredCard ErrorCode = "expired_card" + ErrorCodeFinancialConnectionsAccountInactive ErrorCode = "financial_connections_account_inactive" + ErrorCodeFinancialConnectionsNoSuccessfulTransactionRefresh ErrorCode = "financial_connections_no_successful_transaction_refresh" + ErrorCodeForwardingAPIInactive ErrorCode = "forwarding_api_inactive" + ErrorCodeForwardingAPIInvalidParameter ErrorCode = "forwarding_api_invalid_parameter" + ErrorCodeForwardingAPIRetryableUpstreamError ErrorCode = "forwarding_api_retryable_upstream_error" + ErrorCodeForwardingAPIUpstreamConnectionError ErrorCode = "forwarding_api_upstream_connection_error" + ErrorCodeForwardingAPIUpstreamConnectionTimeout ErrorCode = "forwarding_api_upstream_connection_timeout" + ErrorCodeForwardingAPIUpstreamError ErrorCode = "forwarding_api_upstream_error" + ErrorCodeIdempotencyKeyInUse ErrorCode = "idempotency_key_in_use" + ErrorCodeIncorrectAddress ErrorCode = "incorrect_address" + ErrorCodeIncorrectCVC ErrorCode = "incorrect_cvc" + ErrorCodeIncorrectNumber ErrorCode = "incorrect_number" + ErrorCodeIncorrectZip ErrorCode = "incorrect_zip" + ErrorCodeInstantPayoutsConfigDisabled ErrorCode = "instant_payouts_config_disabled" + ErrorCodeInstantPayoutsCurrencyDisabled ErrorCode = "instant_payouts_currency_disabled" + ErrorCodeInstantPayoutsLimitExceeded ErrorCode = "instant_payouts_limit_exceeded" + ErrorCodeInstantPayoutsUnsupported ErrorCode = "instant_payouts_unsupported" + ErrorCodeInsufficientFunds ErrorCode = "insufficient_funds" + ErrorCodeIntentInvalidState ErrorCode = "intent_invalid_state" + ErrorCodeIntentVerificationMethodMissing ErrorCode = "intent_verification_method_missing" + ErrorCodeInvalidCVC ErrorCode = "invalid_cvc" + ErrorCodeInvalidCardType ErrorCode = "invalid_card_type" + ErrorCodeInvalidCharacters ErrorCode = "invalid_characters" + ErrorCodeInvalidChargeAmount ErrorCode = "invalid_charge_amount" + ErrorCodeInvalidExpiryMonth ErrorCode = "invalid_expiry_month" + ErrorCodeInvalidExpiryYear ErrorCode = "invalid_expiry_year" + ErrorCodeInvalidMandateReferencePrefixFormat ErrorCode = "invalid_mandate_reference_prefix_format" + ErrorCodeInvalidNumber ErrorCode = "invalid_number" + ErrorCodeInvalidSourceUsage ErrorCode = "invalid_source_usage" + ErrorCodeInvalidTaxLocation ErrorCode = "invalid_tax_location" + ErrorCodeInvoiceNoCustomerLineItems ErrorCode = "invoice_no_customer_line_items" + ErrorCodeInvoiceNoPaymentMethodTypes ErrorCode = "invoice_no_payment_method_types" + ErrorCodeInvoiceNoSubscriptionLineItems ErrorCode = "invoice_no_subscription_line_items" + ErrorCodeInvoiceNotEditable ErrorCode = "invoice_not_editable" + ErrorCodeInvoiceOnBehalfOfNotEditable ErrorCode = "invoice_on_behalf_of_not_editable" + ErrorCodeInvoicePaymentIntentRequiresAction ErrorCode = "invoice_payment_intent_requires_action" + ErrorCodeInvoiceUpcomingNone ErrorCode = "invoice_upcoming_none" + ErrorCodeLivemodeMismatch ErrorCode = "livemode_mismatch" + ErrorCodeLockTimeout ErrorCode = "lock_timeout" + ErrorCodeMissing ErrorCode = "missing" + ErrorCodeNoAccount ErrorCode = "no_account" + ErrorCodeNotAllowedOnStandardAccount ErrorCode = "not_allowed_on_standard_account" + ErrorCodeOutOfInventory ErrorCode = "out_of_inventory" + ErrorCodeOwnershipDeclarationNotAllowed ErrorCode = "ownership_declaration_not_allowed" + ErrorCodeParameterInvalidEmpty ErrorCode = "parameter_invalid_empty" + ErrorCodeParameterInvalidInteger ErrorCode = "parameter_invalid_integer" + ErrorCodeParameterInvalidStringBlank ErrorCode = "parameter_invalid_string_blank" + ErrorCodeParameterInvalidStringEmpty ErrorCode = "parameter_invalid_string_empty" + ErrorCodeParameterMissing ErrorCode = "parameter_missing" + ErrorCodeParameterUnknown ErrorCode = "parameter_unknown" + ErrorCodeParametersExclusive ErrorCode = "parameters_exclusive" + ErrorCodePaymentIntentActionRequired ErrorCode = "payment_intent_action_required" + ErrorCodePaymentIntentAuthenticationFailure ErrorCode = "payment_intent_authentication_failure" + ErrorCodePaymentIntentIncompatiblePaymentMethod ErrorCode = "payment_intent_incompatible_payment_method" + ErrorCodePaymentIntentInvalidParameter ErrorCode = "payment_intent_invalid_parameter" + ErrorCodePaymentIntentKonbiniRejectedConfirmationNumber ErrorCode = "payment_intent_konbini_rejected_confirmation_number" + ErrorCodePaymentIntentMandateInvalid ErrorCode = "payment_intent_mandate_invalid" + ErrorCodePaymentIntentPaymentAttemptExpired ErrorCode = "payment_intent_payment_attempt_expired" + ErrorCodePaymentIntentPaymentAttemptFailed ErrorCode = "payment_intent_payment_attempt_failed" + ErrorCodePaymentIntentUnexpectedState ErrorCode = "payment_intent_unexpected_state" + ErrorCodePaymentMethodBankAccountAlreadyVerified ErrorCode = "payment_method_bank_account_already_verified" + ErrorCodePaymentMethodBankAccountBlocked ErrorCode = "payment_method_bank_account_blocked" + ErrorCodePaymentMethodBillingDetailsAddressMissing ErrorCode = "payment_method_billing_details_address_missing" + ErrorCodePaymentMethodConfigurationFailures ErrorCode = "payment_method_configuration_failures" + ErrorCodePaymentMethodCurrencyMismatch ErrorCode = "payment_method_currency_mismatch" + ErrorCodePaymentMethodCustomerDecline ErrorCode = "payment_method_customer_decline" + ErrorCodePaymentMethodInvalidParameter ErrorCode = "payment_method_invalid_parameter" + ErrorCodePaymentMethodInvalidParameterTestmode ErrorCode = "payment_method_invalid_parameter_testmode" + ErrorCodePaymentMethodMicrodepositFailed ErrorCode = "payment_method_microdeposit_failed" + ErrorCodePaymentMethodMicrodepositVerificationAmountsInvalid ErrorCode = "payment_method_microdeposit_verification_amounts_invalid" + ErrorCodePaymentMethodMicrodepositVerificationAmountsMismatch ErrorCode = "payment_method_microdeposit_verification_amounts_mismatch" + ErrorCodePaymentMethodMicrodepositVerificationAttemptsExceeded ErrorCode = "payment_method_microdeposit_verification_attempts_exceeded" + ErrorCodePaymentMethodMicrodepositVerificationDescriptorCodeMismatch ErrorCode = "payment_method_microdeposit_verification_descriptor_code_mismatch" + ErrorCodePaymentMethodMicrodepositVerificationTimeout ErrorCode = "payment_method_microdeposit_verification_timeout" + ErrorCodePaymentMethodNotAvailable ErrorCode = "payment_method_not_available" + ErrorCodePaymentMethodProviderDecline ErrorCode = "payment_method_provider_decline" + ErrorCodePaymentMethodProviderTimeout ErrorCode = "payment_method_provider_timeout" + ErrorCodePaymentMethodUnactivated ErrorCode = "payment_method_unactivated" + ErrorCodePaymentMethodUnexpectedState ErrorCode = "payment_method_unexpected_state" + ErrorCodePaymentMethodUnsupportedType ErrorCode = "payment_method_unsupported_type" + ErrorCodePayoutReconciliationNotReady ErrorCode = "payout_reconciliation_not_ready" + ErrorCodePayoutsLimitExceeded ErrorCode = "payouts_limit_exceeded" + ErrorCodePayoutsNotAllowed ErrorCode = "payouts_not_allowed" + ErrorCodePlatformAPIKeyExpired ErrorCode = "platform_api_key_expired" + ErrorCodePlatformAccountRequired ErrorCode = "platform_account_required" + ErrorCodePostalCodeInvalid ErrorCode = "postal_code_invalid" + ErrorCodeProcessingError ErrorCode = "processing_error" + ErrorCodeProductInactive ErrorCode = "product_inactive" + ErrorCodeProgressiveOnboardingLimitExceeded ErrorCode = "progressive_onboarding_limit_exceeded" + ErrorCodeRateLimit ErrorCode = "rate_limit" + ErrorCodeReferToCustomer ErrorCode = "refer_to_customer" + ErrorCodeRefundDisputedPayment ErrorCode = "refund_disputed_payment" + ErrorCodeResourceAlreadyExists ErrorCode = "resource_already_exists" + ErrorCodeResourceMissing ErrorCode = "resource_missing" + ErrorCodeReturnIntentAlreadyProcessed ErrorCode = "return_intent_already_processed" + ErrorCodeRoutingNumberInvalid ErrorCode = "routing_number_invalid" + ErrorCodeSEPAUnsupportedAccount ErrorCode = "sepa_unsupported_account" + ErrorCodeSKUInactive ErrorCode = "sku_inactive" + ErrorCodeSecretKeyRequired ErrorCode = "secret_key_required" + ErrorCodeSetupAttemptFailed ErrorCode = "setup_attempt_failed" + ErrorCodeSetupIntentAuthenticationFailure ErrorCode = "setup_intent_authentication_failure" + ErrorCodeSetupIntentInvalidParameter ErrorCode = "setup_intent_invalid_parameter" + ErrorCodeSetupIntentMandateInvalid ErrorCode = "setup_intent_mandate_invalid" + ErrorCodeSetupIntentMobileWalletUnsupported ErrorCode = "setup_intent_mobile_wallet_unsupported" + ErrorCodeSetupIntentSetupAttemptExpired ErrorCode = "setup_intent_setup_attempt_expired" + ErrorCodeSetupIntentUnexpectedState ErrorCode = "setup_intent_unexpected_state" + ErrorCodeShippingAddressInvalid ErrorCode = "shipping_address_invalid" + ErrorCodeShippingCalculationFailed ErrorCode = "shipping_calculation_failed" + ErrorCodeStateUnsupported ErrorCode = "state_unsupported" + ErrorCodeStatusTransitionInvalid ErrorCode = "status_transition_invalid" + ErrorCodeStripeTaxInactive ErrorCode = "stripe_tax_inactive" + ErrorCodeTLSVersionUnsupported ErrorCode = "tls_version_unsupported" + ErrorCodeTaxIDInvalid ErrorCode = "tax_id_invalid" + ErrorCodeTaxIDProhibited ErrorCode = "tax_id_prohibited" + ErrorCodeTaxesCalculationFailed ErrorCode = "taxes_calculation_failed" + ErrorCodeTerminalLocationCountryUnsupported ErrorCode = "terminal_location_country_unsupported" + ErrorCodeTerminalReaderBusy ErrorCode = "terminal_reader_busy" + ErrorCodeTerminalReaderHardwareFault ErrorCode = "terminal_reader_hardware_fault" + ErrorCodeTerminalReaderInvalidLocationForActivation ErrorCode = "terminal_reader_invalid_location_for_activation" + ErrorCodeTerminalReaderInvalidLocationForPayment ErrorCode = "terminal_reader_invalid_location_for_payment" + ErrorCodeTerminalReaderOffline ErrorCode = "terminal_reader_offline" + ErrorCodeTerminalReaderTimeout ErrorCode = "terminal_reader_timeout" + ErrorCodeTestmodeChargesOnly ErrorCode = "testmode_charges_only" + ErrorCodeTokenAlreadyUsed ErrorCode = "token_already_used" + ErrorCodeTokenCardNetworkInvalid ErrorCode = "token_card_network_invalid" + ErrorCodeTokenInUse ErrorCode = "token_in_use" + ErrorCodeTransferSourceBalanceParametersMismatch ErrorCode = "transfer_source_balance_parameters_mismatch" + ErrorCodeTransfersNotAllowed ErrorCode = "transfers_not_allowed" + ErrorCodeURLInvalid ErrorCode = "url_invalid" +) + +// v1ErrorCodes: The end of the section generated from our OpenAPI spec + +// List of DeclineCode values. +// For descriptions see https://stripe.com/docs/declines/codes +const ( + DeclineCodeAuthenticationRequired DeclineCode = "authentication_required" + DeclineCodeApproveWithID DeclineCode = "approve_with_id" + DeclineCodeCallIssuer DeclineCode = "call_issuer" + DeclineCodeCardNotSupported DeclineCode = "card_not_supported" + DeclineCodeCardVelocityExceeded DeclineCode = "card_velocity_exceeded" + DeclineCodeCurrencyNotSupported DeclineCode = "currency_not_supported" + DeclineCodeDoNotHonor DeclineCode = "do_not_honor" + DeclineCodeDoNotTryAgain DeclineCode = "do_not_try_again" + DeclineCodeDuplicateTransaction DeclineCode = "duplicate_transaction" + DeclineCodeExpiredCard DeclineCode = "expired_card" + DeclineCodeFraudulent DeclineCode = "fraudulent" + DeclineCodeGenericDecline DeclineCode = "generic_decline" + DeclineCodeIncorrectNumber DeclineCode = "incorrect_number" + DeclineCodeIncorrectCVC DeclineCode = "incorrect_cvc" + DeclineCodeIncorrectPIN DeclineCode = "incorrect_pin" + DeclineCodeIncorrectZip DeclineCode = "incorrect_zip" + DeclineCodeInsufficientFunds DeclineCode = "insufficient_funds" + DeclineCodeInvalidAccount DeclineCode = "invalid_account" + DeclineCodeInvalidAmount DeclineCode = "invalid_amount" + DeclineCodeInvalidCVC DeclineCode = "invalid_cvc" + DeclineCodeInvalidExpiryMonth DeclineCode = "invalid_expiry_month" + DeclineCodeInvalidExpiryYear DeclineCode = "invalid_expiry_year" + DeclineCodeInvalidNumber DeclineCode = "invalid_number" + DeclineCodeInvalidPIN DeclineCode = "invalid_pin" + DeclineCodeIssuerNotAvailable DeclineCode = "issuer_not_available" + DeclineCodeLostCard DeclineCode = "lost_card" + DeclineCodeMerchantBlacklist DeclineCode = "merchant_blacklist" + DeclineCodeNewAccountInformationAvailable DeclineCode = "new_account_information_available" + DeclineCodeNoActionTaken DeclineCode = "no_action_taken" + DeclineCodeNotPermitted DeclineCode = "not_permitted" + DeclineCodeOfflinePINRequired DeclineCode = "offline_pin_required" + DeclineCodeOnlineOrOfflinePINRequired DeclineCode = "online_or_offline_pin_required" + DeclineCodePickupCard DeclineCode = "pickup_card" + DeclineCodePINTryExceeded DeclineCode = "pin_try_exceeded" + DeclineCodeProcessingError DeclineCode = "processing_error" + DeclineCodeReenterTransaction DeclineCode = "reenter_transaction" + DeclineCodeRestrictedCard DeclineCode = "restricted_card" + DeclineCodeRevocationOfAllAuthorizations DeclineCode = "revocation_of_all_authorizations" + DeclineCodeRevocationOfAuthorization DeclineCode = "revocation_of_authorization" + DeclineCodeSecurityViolation DeclineCode = "security_violation" + DeclineCodeServiceNotAllowed DeclineCode = "service_not_allowed" + DeclineCodeStolenCard DeclineCode = "stolen_card" + DeclineCodeStopPaymentOrder DeclineCode = "stop_payment_order" + DeclineCodeTestModeDecline DeclineCode = "testmode_decline" + DeclineCodeTransactionNotAllowed DeclineCode = "transaction_not_allowed" + DeclineCodeTryAgainLater DeclineCode = "try_again_later" + DeclineCodeWithdrawalCountLimitExceeded DeclineCode = "withdrawal_count_limit_exceeded" +) + +type retrier interface { + canRetry() bool +} + +type redacter interface { + redact() error +} + +// Error is the response returned when a call is unsuccessful. +// For more details see https://stripe.com/docs/api#errors. +type Error struct { + APIResource + + ChargeID string `json:"charge,omitempty"` + Code ErrorCode `json:"code,omitempty"` + DeclineCode DeclineCode `json:"decline_code,omitempty"` + DocURL string `json:"doc_url,omitempty"` + + // Err contains an internal error with an additional level of granularity + // that can be used in some cases to get more detailed information about + // what went wrong. For example, Err may hold a CardError that indicates + // exactly what went wrong during charging a card. + Err error `json:"-"` + + HTTPStatusCode int `json:"status,omitempty"` + Msg string `json:"message"` + DeveloperMsg string `json:"developer_message,omitempty"` + Param string `json:"param,omitempty"` + PaymentIntent *PaymentIntent `json:"payment_intent,omitempty"` + PaymentMethod *PaymentMethod `json:"payment_method,omitempty"` + PaymentMethodType PaymentMethodType `json:"payment_method_type,omitempty"` + RequestID string `json:"request_id,omitempty"` + RequestLogURL string `json:"request_log_url,omitempty"` + SetupIntent *SetupIntent `json:"setup_intent,omitempty"` + Source *PaymentSource `json:"source,omitempty"` + Type ErrorType `json:"type"` + + // OAuth specific Error properties. Named OAuthError because of name conflict. + OAuthError string `json:"error,omitempty"` + OAuthErrorDescription string `json:"error_description,omitempty"` +} + +// Error serializes the error object to JSON and returns it as a string. +func (e *Error) Error() string { + ret, _ := json.Marshal(e) + return string(ret) +} + +// Unwrap returns the wrapped typed error. +func (e *Error) Unwrap() error { + return e.Err +} + +// canRetry implements the retrier interface. +func (e *Error) canRetry() bool { + if e == nil { + return false + } + + // 429 Too Many Requests + // + // There are a few different problems that can lead to a 429. The most + // common is rate limiting, on which we *don't* want to retry because + // that'd likely contribute to more contention problems. However, some 429s + // are lock timeouts, which is when a request conflicted with another + // request or an internal process on some particular object. These 429s are + // safe to retry. + if e.HTTPStatusCode == http.StatusTooManyRequests && e.Code == ErrorCodeLockTimeout { + return true + } + + return false +} + +// redact returns a copy of the error object with sensitive fields replaced with +// a placeholder value. This implements the redacter interface. +func (e *Error) redact() error { + // Fast path, since this applies to most cases + if e.PaymentIntent == nil && e.SetupIntent == nil { + return e + } + errCopy := *e + if e.PaymentIntent != nil { + pi := *e.PaymentIntent + errCopy.PaymentIntent = &pi + errCopy.PaymentIntent.ClientSecret = "REDACTED" + } + if e.SetupIntent != nil { + si := *e.SetupIntent + errCopy.SetupIntent = &si + errCopy.SetupIntent.ClientSecret = "REDACTED" + } + return &errCopy +} + +// APIError is a catch all for any errors not covered by other types (and +// should be extremely uncommon). +type APIError struct { + stripeErr *Error +} + +// Error serializes the error object to JSON and returns it as a string. +func (e *APIError) Error() string { + return e.stripeErr.Error() +} + +// CardError are the most common type of error you should expect to handle. +// They result when the user enters a card that can't be charged for some +// reason. +type CardError struct { + stripeErr *Error + // DeclineCode is a code indicating a card issuer's reason for declining a + // card (if they provided one). + DeclineCode DeclineCode `json:"decline_code,omitempty"` +} + +// Error serializes the error object to JSON and returns it as a string. +func (e *CardError) Error() string { + return e.stripeErr.Error() +} + +// InvalidRequestError is an error that occurs when a request contains invalid +// parameters. +type InvalidRequestError struct { + stripeErr *Error +} + +// Error serializes the error object to JSON and returns it as a string. +func (e *InvalidRequestError) Error() string { + return e.stripeErr.Error() +} + +// IdempotencyError occurs when an Idempotency-Key is re-used on a request +// that does not match the first request's API endpoint and parameters. +type IdempotencyError struct { + stripeErr *Error +} + +// Error serializes the error object to JSON and returns it as a string. +func (e *IdempotencyError) Error() string { + return e.stripeErr.Error() +} + +// errorStructs: The beginning of the section generated from our OpenAPI spec + +// TemporarySessionExpiredError is the Go struct corresponding to the error type "temporary_session_expired." +// The temporary session token has expired. +type TemporarySessionExpiredError struct { + APIResource + Code string `json:"code"` + DocURL *string `json:"doc_url,omitempty"` + Message string `json:"message"` + Type ErrorType `json:"type"` + UserMessage *string `json:"user_message,omitempty"` +} + +// Error serializes the error object to JSON and returns it as a string. +func (e *TemporarySessionExpiredError) Error() string { + ret, _ := json.Marshal(e) + return string(ret) +} + +// redact implements the redacter interface. +func (e *TemporarySessionExpiredError) redact() error { + return e +} + +// canRetry implements the retrier interface. +func (e *TemporarySessionExpiredError) canRetry() bool { + return false +} + +// errorStructs: The end of the section generated from our OpenAPI spec + +// V2RawError is a catch-all for any errors not covered by other types +type V2RawError struct { + Code string `json:"code"` + Type *ErrorType `json:"type,omitempty"` + Message string `json:"message"` + UserMesage *string `json:"user_message,omitempty"` +} + +func (e *V2RawError) Error() string { + ret, _ := json.Marshal(e) + return string(ret) +} + +func (e *V2RawError) redact() error { + return e +} + +func (e *V2RawError) canRetry() bool { + return false +} + +// rawError deserializes the outer JSON object returned in an error response +// from the API. +type rawError struct { + Error *Error `json:"error,omitempty"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/event.go b/vendor/github.com/stripe/stripe-go/v82/event.go new file mode 100644 index 00000000..6cac3fa5 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/event.go @@ -0,0 +1,462 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "encoding/json" + "fmt" + "strconv" +) + +// Description of the event (for example, `invoice.created` or `charge.refunded`). +type EventType string + +// List of values that EventType can take +const ( + EventTypeAccountApplicationAuthorized EventType = "account.application.authorized" + EventTypeAccountApplicationDeauthorized EventType = "account.application.deauthorized" + EventTypeAccountExternalAccountCreated EventType = "account.external_account.created" + EventTypeAccountExternalAccountDeleted EventType = "account.external_account.deleted" + EventTypeAccountExternalAccountUpdated EventType = "account.external_account.updated" + EventTypeAccountUpdated EventType = "account.updated" + EventTypeApplicationFeeCreated EventType = "application_fee.created" + EventTypeApplicationFeeRefundUpdated EventType = "application_fee.refund.updated" + EventTypeApplicationFeeRefunded EventType = "application_fee.refunded" + EventTypeBalanceAvailable EventType = "balance.available" + EventTypeBillingAlertTriggered EventType = "billing.alert.triggered" + EventTypeBillingPortalConfigurationCreated EventType = "billing_portal.configuration.created" + EventTypeBillingPortalConfigurationUpdated EventType = "billing_portal.configuration.updated" + EventTypeBillingPortalSessionCreated EventType = "billing_portal.session.created" + EventTypeCapabilityUpdated EventType = "capability.updated" + EventTypeCashBalanceFundsAvailable EventType = "cash_balance.funds_available" + EventTypeChargeCaptured EventType = "charge.captured" + EventTypeChargeDisputeClosed EventType = "charge.dispute.closed" + EventTypeChargeDisputeCreated EventType = "charge.dispute.created" + EventTypeChargeDisputeFundsReinstated EventType = "charge.dispute.funds_reinstated" + EventTypeChargeDisputeFundsWithdrawn EventType = "charge.dispute.funds_withdrawn" + EventTypeChargeDisputeUpdated EventType = "charge.dispute.updated" + EventTypeChargeExpired EventType = "charge.expired" + EventTypeChargeFailed EventType = "charge.failed" + EventTypeChargePending EventType = "charge.pending" + EventTypeChargeRefundUpdated EventType = "charge.refund.updated" + EventTypeChargeRefunded EventType = "charge.refunded" + EventTypeChargeSucceeded EventType = "charge.succeeded" + EventTypeChargeUpdated EventType = "charge.updated" + EventTypeCheckoutSessionAsyncPaymentFailed EventType = "checkout.session.async_payment_failed" + EventTypeCheckoutSessionAsyncPaymentSucceeded EventType = "checkout.session.async_payment_succeeded" + EventTypeCheckoutSessionCompleted EventType = "checkout.session.completed" + EventTypeCheckoutSessionExpired EventType = "checkout.session.expired" + EventTypeClimateOrderCanceled EventType = "climate.order.canceled" + EventTypeClimateOrderCreated EventType = "climate.order.created" + EventTypeClimateOrderDelayed EventType = "climate.order.delayed" + EventTypeClimateOrderDelivered EventType = "climate.order.delivered" + EventTypeClimateOrderProductSubstituted EventType = "climate.order.product_substituted" + EventTypeClimateProductCreated EventType = "climate.product.created" + EventTypeClimateProductPricingUpdated EventType = "climate.product.pricing_updated" + EventTypeCouponCreated EventType = "coupon.created" + EventTypeCouponDeleted EventType = "coupon.deleted" + EventTypeCouponUpdated EventType = "coupon.updated" + EventTypeCreditNoteCreated EventType = "credit_note.created" + EventTypeCreditNoteUpdated EventType = "credit_note.updated" + EventTypeCreditNoteVoided EventType = "credit_note.voided" + EventTypeCustomerCreated EventType = "customer.created" + EventTypeCustomerDeleted EventType = "customer.deleted" + EventTypeCustomerDiscountCreated EventType = "customer.discount.created" + EventTypeCustomerDiscountDeleted EventType = "customer.discount.deleted" + EventTypeCustomerDiscountUpdated EventType = "customer.discount.updated" + EventTypeCustomerSourceCreated EventType = "customer.source.created" + EventTypeCustomerSourceDeleted EventType = "customer.source.deleted" + EventTypeCustomerSourceExpiring EventType = "customer.source.expiring" + EventTypeCustomerSourceUpdated EventType = "customer.source.updated" + EventTypeCustomerSubscriptionCreated EventType = "customer.subscription.created" + EventTypeCustomerSubscriptionDeleted EventType = "customer.subscription.deleted" + EventTypeCustomerSubscriptionPaused EventType = "customer.subscription.paused" + EventTypeCustomerSubscriptionPendingUpdateApplied EventType = "customer.subscription.pending_update_applied" + EventTypeCustomerSubscriptionPendingUpdateExpired EventType = "customer.subscription.pending_update_expired" + EventTypeCustomerSubscriptionResumed EventType = "customer.subscription.resumed" + EventTypeCustomerSubscriptionTrialWillEnd EventType = "customer.subscription.trial_will_end" + EventTypeCustomerSubscriptionUpdated EventType = "customer.subscription.updated" + EventTypeCustomerTaxIDCreated EventType = "customer.tax_id.created" + EventTypeCustomerTaxIDDeleted EventType = "customer.tax_id.deleted" + EventTypeCustomerTaxIDUpdated EventType = "customer.tax_id.updated" + EventTypeCustomerUpdated EventType = "customer.updated" + EventTypeCustomerCashBalanceTransactionCreated EventType = "customer_cash_balance_transaction.created" + EventTypeEntitlementsActiveEntitlementSummaryUpdated EventType = "entitlements.active_entitlement_summary.updated" + EventTypeFileCreated EventType = "file.created" + EventTypeFinancialConnectionsAccountCreated EventType = "financial_connections.account.created" + EventTypeFinancialConnectionsAccountDeactivated EventType = "financial_connections.account.deactivated" + EventTypeFinancialConnectionsAccountDisconnected EventType = "financial_connections.account.disconnected" + EventTypeFinancialConnectionsAccountReactivated EventType = "financial_connections.account.reactivated" + EventTypeFinancialConnectionsAccountRefreshedBalance EventType = "financial_connections.account.refreshed_balance" + EventTypeFinancialConnectionsAccountRefreshedOwnership EventType = "financial_connections.account.refreshed_ownership" + EventTypeFinancialConnectionsAccountRefreshedTransactions EventType = "financial_connections.account.refreshed_transactions" + EventTypeIdentityVerificationSessionCanceled EventType = "identity.verification_session.canceled" + EventTypeIdentityVerificationSessionCreated EventType = "identity.verification_session.created" + EventTypeIdentityVerificationSessionProcessing EventType = "identity.verification_session.processing" + EventTypeIdentityVerificationSessionRedacted EventType = "identity.verification_session.redacted" + EventTypeIdentityVerificationSessionRequiresInput EventType = "identity.verification_session.requires_input" + EventTypeIdentityVerificationSessionVerified EventType = "identity.verification_session.verified" + EventTypeInvoiceCreated EventType = "invoice.created" + EventTypeInvoiceDeleted EventType = "invoice.deleted" + EventTypeInvoiceFinalizationFailed EventType = "invoice.finalization_failed" + EventTypeInvoiceFinalized EventType = "invoice.finalized" + EventTypeInvoiceMarkedUncollectible EventType = "invoice.marked_uncollectible" + EventTypeInvoiceOverdue EventType = "invoice.overdue" + EventTypeInvoiceOverpaid EventType = "invoice.overpaid" + EventTypeInvoicePaid EventType = "invoice.paid" + EventTypeInvoicePaymentActionRequired EventType = "invoice.payment_action_required" + EventTypeInvoicePaymentFailed EventType = "invoice.payment_failed" + EventTypeInvoicePaymentSucceeded EventType = "invoice.payment_succeeded" + EventTypeInvoiceSent EventType = "invoice.sent" + EventTypeInvoiceUpcoming EventType = "invoice.upcoming" + EventTypeInvoiceUpdated EventType = "invoice.updated" + EventTypeInvoiceVoided EventType = "invoice.voided" + EventTypeInvoiceWillBeDue EventType = "invoice.will_be_due" + EventTypeInvoicePaymentPaid EventType = "invoice_payment.paid" + EventTypeInvoiceItemCreated EventType = "invoiceitem.created" + EventTypeInvoiceItemDeleted EventType = "invoiceitem.deleted" + EventTypeIssuingAuthorizationCreated EventType = "issuing_authorization.created" + EventTypeIssuingAuthorizationRequest EventType = "issuing_authorization.request" + EventTypeIssuingAuthorizationUpdated EventType = "issuing_authorization.updated" + EventTypeIssuingCardCreated EventType = "issuing_card.created" + EventTypeIssuingCardUpdated EventType = "issuing_card.updated" + EventTypeIssuingCardholderCreated EventType = "issuing_cardholder.created" + EventTypeIssuingCardholderUpdated EventType = "issuing_cardholder.updated" + EventTypeIssuingDisputeClosed EventType = "issuing_dispute.closed" + EventTypeIssuingDisputeCreated EventType = "issuing_dispute.created" + EventTypeIssuingDisputeFundsReinstated EventType = "issuing_dispute.funds_reinstated" + EventTypeIssuingDisputeFundsRescinded EventType = "issuing_dispute.funds_rescinded" + EventTypeIssuingDisputeSubmitted EventType = "issuing_dispute.submitted" + EventTypeIssuingDisputeUpdated EventType = "issuing_dispute.updated" + EventTypeIssuingPersonalizationDesignActivated EventType = "issuing_personalization_design.activated" + EventTypeIssuingPersonalizationDesignDeactivated EventType = "issuing_personalization_design.deactivated" + EventTypeIssuingPersonalizationDesignRejected EventType = "issuing_personalization_design.rejected" + EventTypeIssuingPersonalizationDesignUpdated EventType = "issuing_personalization_design.updated" + EventTypeIssuingTokenCreated EventType = "issuing_token.created" + EventTypeIssuingTokenUpdated EventType = "issuing_token.updated" + EventTypeIssuingTransactionCreated EventType = "issuing_transaction.created" + EventTypeIssuingTransactionPurchaseDetailsReceiptUpdated EventType = "issuing_transaction.purchase_details_receipt_updated" + EventTypeIssuingTransactionUpdated EventType = "issuing_transaction.updated" + EventTypeMandateUpdated EventType = "mandate.updated" + EventTypePaymentIntentAmountCapturableUpdated EventType = "payment_intent.amount_capturable_updated" + EventTypePaymentIntentCanceled EventType = "payment_intent.canceled" + EventTypePaymentIntentCreated EventType = "payment_intent.created" + EventTypePaymentIntentPartiallyFunded EventType = "payment_intent.partially_funded" + EventTypePaymentIntentPaymentFailed EventType = "payment_intent.payment_failed" + EventTypePaymentIntentProcessing EventType = "payment_intent.processing" + EventTypePaymentIntentRequiresAction EventType = "payment_intent.requires_action" + EventTypePaymentIntentSucceeded EventType = "payment_intent.succeeded" + EventTypePaymentLinkCreated EventType = "payment_link.created" + EventTypePaymentLinkUpdated EventType = "payment_link.updated" + EventTypePaymentMethodAttached EventType = "payment_method.attached" + EventTypePaymentMethodAutomaticallyUpdated EventType = "payment_method.automatically_updated" + EventTypePaymentMethodDetached EventType = "payment_method.detached" + EventTypePaymentMethodUpdated EventType = "payment_method.updated" + EventTypePayoutCanceled EventType = "payout.canceled" + EventTypePayoutCreated EventType = "payout.created" + EventTypePayoutFailed EventType = "payout.failed" + EventTypePayoutPaid EventType = "payout.paid" + EventTypePayoutReconciliationCompleted EventType = "payout.reconciliation_completed" + EventTypePayoutUpdated EventType = "payout.updated" + EventTypePersonCreated EventType = "person.created" + EventTypePersonDeleted EventType = "person.deleted" + EventTypePersonUpdated EventType = "person.updated" + EventTypePlanCreated EventType = "plan.created" + EventTypePlanDeleted EventType = "plan.deleted" + EventTypePlanUpdated EventType = "plan.updated" + EventTypePriceCreated EventType = "price.created" + EventTypePriceDeleted EventType = "price.deleted" + EventTypePriceUpdated EventType = "price.updated" + EventTypeProductCreated EventType = "product.created" + EventTypeProductDeleted EventType = "product.deleted" + EventTypeProductUpdated EventType = "product.updated" + EventTypePromotionCodeCreated EventType = "promotion_code.created" + EventTypePromotionCodeUpdated EventType = "promotion_code.updated" + EventTypeQuoteAccepted EventType = "quote.accepted" + EventTypeQuoteCanceled EventType = "quote.canceled" + EventTypeQuoteCreated EventType = "quote.created" + EventTypeQuoteFinalized EventType = "quote.finalized" + EventTypeRadarEarlyFraudWarningCreated EventType = "radar.early_fraud_warning.created" + EventTypeRadarEarlyFraudWarningUpdated EventType = "radar.early_fraud_warning.updated" + EventTypeRefundCreated EventType = "refund.created" + EventTypeRefundFailed EventType = "refund.failed" + EventTypeRefundUpdated EventType = "refund.updated" + EventTypeReportingReportRunFailed EventType = "reporting.report_run.failed" + EventTypeReportingReportRunSucceeded EventType = "reporting.report_run.succeeded" + EventTypeReportingReportTypeUpdated EventType = "reporting.report_type.updated" + EventTypeReviewClosed EventType = "review.closed" + EventTypeReviewOpened EventType = "review.opened" + EventTypeSetupIntentCanceled EventType = "setup_intent.canceled" + EventTypeSetupIntentCreated EventType = "setup_intent.created" + EventTypeSetupIntentRequiresAction EventType = "setup_intent.requires_action" + EventTypeSetupIntentSetupFailed EventType = "setup_intent.setup_failed" + EventTypeSetupIntentSucceeded EventType = "setup_intent.succeeded" + EventTypeSigmaScheduledQueryRunCreated EventType = "sigma.scheduled_query_run.created" + EventTypeSourceCanceled EventType = "source.canceled" + EventTypeSourceChargeable EventType = "source.chargeable" + EventTypeSourceFailed EventType = "source.failed" + EventTypeSourceMandateNotification EventType = "source.mandate_notification" + EventTypeSourceRefundAttributesRequired EventType = "source.refund_attributes_required" + EventTypeSourceTransactionCreated EventType = "source.transaction.created" + EventTypeSourceTransactionUpdated EventType = "source.transaction.updated" + EventTypeSubscriptionScheduleAborted EventType = "subscription_schedule.aborted" + EventTypeSubscriptionScheduleCanceled EventType = "subscription_schedule.canceled" + EventTypeSubscriptionScheduleCompleted EventType = "subscription_schedule.completed" + EventTypeSubscriptionScheduleCreated EventType = "subscription_schedule.created" + EventTypeSubscriptionScheduleExpiring EventType = "subscription_schedule.expiring" + EventTypeSubscriptionScheduleReleased EventType = "subscription_schedule.released" + EventTypeSubscriptionScheduleUpdated EventType = "subscription_schedule.updated" + EventTypeTaxSettingsUpdated EventType = "tax.settings.updated" + EventTypeTaxRateCreated EventType = "tax_rate.created" + EventTypeTaxRateUpdated EventType = "tax_rate.updated" + EventTypeTerminalReaderActionFailed EventType = "terminal.reader.action_failed" + EventTypeTerminalReaderActionSucceeded EventType = "terminal.reader.action_succeeded" + EventTypeTerminalReaderActionUpdated EventType = "terminal.reader.action_updated" + EventTypeTestHelpersTestClockAdvancing EventType = "test_helpers.test_clock.advancing" + EventTypeTestHelpersTestClockCreated EventType = "test_helpers.test_clock.created" + EventTypeTestHelpersTestClockDeleted EventType = "test_helpers.test_clock.deleted" + EventTypeTestHelpersTestClockInternalFailure EventType = "test_helpers.test_clock.internal_failure" + EventTypeTestHelpersTestClockReady EventType = "test_helpers.test_clock.ready" + EventTypeTopupCanceled EventType = "topup.canceled" + EventTypeTopupCreated EventType = "topup.created" + EventTypeTopupFailed EventType = "topup.failed" + EventTypeTopupReversed EventType = "topup.reversed" + EventTypeTopupSucceeded EventType = "topup.succeeded" + EventTypeTransferCreated EventType = "transfer.created" + EventTypeTransferReversed EventType = "transfer.reversed" + EventTypeTransferUpdated EventType = "transfer.updated" + EventTypeTreasuryCreditReversalCreated EventType = "treasury.credit_reversal.created" + EventTypeTreasuryCreditReversalPosted EventType = "treasury.credit_reversal.posted" + EventTypeTreasuryDebitReversalCompleted EventType = "treasury.debit_reversal.completed" + EventTypeTreasuryDebitReversalCreated EventType = "treasury.debit_reversal.created" + EventTypeTreasuryDebitReversalInitialCreditGranted EventType = "treasury.debit_reversal.initial_credit_granted" + EventTypeTreasuryFinancialAccountClosed EventType = "treasury.financial_account.closed" + EventTypeTreasuryFinancialAccountCreated EventType = "treasury.financial_account.created" + EventTypeTreasuryFinancialAccountFeaturesStatusUpdated EventType = "treasury.financial_account.features_status_updated" + EventTypeTreasuryInboundTransferCanceled EventType = "treasury.inbound_transfer.canceled" + EventTypeTreasuryInboundTransferCreated EventType = "treasury.inbound_transfer.created" + EventTypeTreasuryInboundTransferFailed EventType = "treasury.inbound_transfer.failed" + EventTypeTreasuryInboundTransferSucceeded EventType = "treasury.inbound_transfer.succeeded" + EventTypeTreasuryOutboundPaymentCanceled EventType = "treasury.outbound_payment.canceled" + EventTypeTreasuryOutboundPaymentCreated EventType = "treasury.outbound_payment.created" + EventTypeTreasuryOutboundPaymentExpectedArrivalDateUpdated EventType = "treasury.outbound_payment.expected_arrival_date_updated" + EventTypeTreasuryOutboundPaymentFailed EventType = "treasury.outbound_payment.failed" + EventTypeTreasuryOutboundPaymentPosted EventType = "treasury.outbound_payment.posted" + EventTypeTreasuryOutboundPaymentReturned EventType = "treasury.outbound_payment.returned" + EventTypeTreasuryOutboundPaymentTrackingDetailsUpdated EventType = "treasury.outbound_payment.tracking_details_updated" + EventTypeTreasuryOutboundTransferCanceled EventType = "treasury.outbound_transfer.canceled" + EventTypeTreasuryOutboundTransferCreated EventType = "treasury.outbound_transfer.created" + EventTypeTreasuryOutboundTransferExpectedArrivalDateUpdated EventType = "treasury.outbound_transfer.expected_arrival_date_updated" + EventTypeTreasuryOutboundTransferFailed EventType = "treasury.outbound_transfer.failed" + EventTypeTreasuryOutboundTransferPosted EventType = "treasury.outbound_transfer.posted" + EventTypeTreasuryOutboundTransferReturned EventType = "treasury.outbound_transfer.returned" + EventTypeTreasuryOutboundTransferTrackingDetailsUpdated EventType = "treasury.outbound_transfer.tracking_details_updated" + EventTypeTreasuryReceivedCreditCreated EventType = "treasury.received_credit.created" + EventTypeTreasuryReceivedCreditFailed EventType = "treasury.received_credit.failed" + EventTypeTreasuryReceivedCreditSucceeded EventType = "treasury.received_credit.succeeded" + EventTypeTreasuryReceivedDebitCreated EventType = "treasury.received_debit.created" + EventTypeBillingCreditBalanceTransactionCreated EventType = "billing.credit_balance_transaction.created" + EventTypeBillingCreditGrantCreated EventType = "billing.credit_grant.created" + EventTypeBillingCreditGrantUpdated EventType = "billing.credit_grant.updated" + EventTypeBillingMeterCreated EventType = "billing.meter.created" + EventTypeBillingMeterDeactivated EventType = "billing.meter.deactivated" + EventTypeBillingMeterReactivated EventType = "billing.meter.reactivated" + EventTypeBillingMeterUpdated EventType = "billing.meter.updated" +) + +// List events, going back up to 30 days. Each event data is rendered according to Stripe API version at its creation time, specified in [event object](https://docs.stripe.com/api/events/object) api_version attribute (not according to your current Stripe API version or Stripe-Version header). +type EventListParams struct { + ListParams `form:"*"` + // Only return events that were created during the given date interval. + Created *int64 `form:"created"` + // Only return events that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Filter events by whether all webhooks were successfully delivered. If false, events which are still pending or have failed all delivery attempts to a webhook endpoint will be returned. + DeliverySuccess *bool `form:"delivery_success"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A string containing a specific event name, or group of events using * as a wildcard. The list will be filtered to include only events with a matching event property. + Type *string `form:"type"` + // An array of up to 20 strings containing specific event names. The list will be filtered to include only events with a matching event property. You may pass either `type` or `types`, but not both. + Types []*string `form:"types"` +} + +// AddExpand appends a new field to expand. +func (p *EventListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an event if it was created in the last 30 days. Supply the unique identifier of the event, which you might have received in a webhook. +type EventParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *EventParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an event if it was created in the last 30 days. Supply the unique identifier of the event, which you might have received in a webhook. +type EventRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *EventRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type EventData struct { + // Object is a raw mapping of the API resource contained in the event. + // Although marked with json:"-", it's still populated independently by + // a custom UnmarshalJSON implementation. + // Object containing the API resource relevant to the event. For example, an `invoice.created` event will have a full [invoice object](https://stripe.com/docs/api#invoice_object) as the value of the object key. + Object map[string]interface{} `json:"-"` + // Object containing the names of the updated attributes and their values prior to the event (only included in events of type `*.updated`). If an array attribute has any updated elements, this object contains the entire array. In Stripe API versions 2017-04-06 or earlier, an updated array attribute in this object includes only the updated array elements. + PreviousAttributes map[string]interface{} `json:"previous_attributes"` + Raw json.RawMessage `json:"object"` +} + +// Information on the API request that triggers the event. +type EventRequest struct { + // ID is the request ID of the request that created an event, if the event + // was created by a request. + // ID of the API request that caused the event. If null, the event was automatic (e.g., Stripe's automatic subscription handling). Request logs are available in the [dashboard](https://dashboard.stripe.com/logs), but currently not in the API. + ID string `json:"id"` + + // IdempotencyKey is the idempotency key of the request that created an + // event, if the event was created by a request and if an idempotency key + // was specified for that request. + // The idempotency key transmitted during the request, if any. *Note: This property is populated only for events on or after May 23, 2017*. + IdempotencyKey string `json:"idempotency_key"` +} + +// Events are our way of letting you know when something interesting happens in +// your account. When an interesting event occurs, we create a new `Event` +// object. For example, when a charge succeeds, we create a `charge.succeeded` +// event, and when an invoice payment attempt fails, we create an +// `invoice.payment_failed` event. Certain API requests might create multiple +// events. For example, if you create a new subscription for a +// customer, you receive both a `customer.subscription.created` event and a +// `charge.succeeded` event. +// +// Events occur when the state of another API resource changes. The event's data +// field embeds the resource's state at the time of the change. For +// example, a `charge.succeeded` event contains a charge, and an +// `invoice.payment_failed` event contains an invoice. +// +// As with other API resources, you can use endpoints to retrieve an +// [individual event](https://stripe.com/docs/api#retrieve_event) or a [list of events](https://stripe.com/docs/api#list_events) +// from the API. We also have a separate +// [webhooks](http://en.wikipedia.org/wiki/Webhook) system for sending the +// `Event` objects directly to an endpoint on your server. You can manage +// webhooks in your +// [account settings](https://dashboard.stripe.com/account/webhooks). Learn how +// to [listen for events](https://docs.stripe.com/webhooks) +// so that your integration can automatically trigger reactions. +// +// When using [Connect](https://docs.stripe.com/connect), you can also receive event notifications +// that occur in connected accounts. For these events, there's an +// additional `account` attribute in the received `Event` object. +// +// We only guarantee access to events through the [Retrieve Event API](https://stripe.com/docs/api#retrieve_event) +// for 30 days. +type Event struct { + APIResource + // The connected account that originates the event. + Account string `json:"account"` + // The Stripe API version used to render `data` when the event was created. The contents of `data` never change, so this value remains static regardless of the API version currently in use. This property is populated only for events created on or after October 31, 2014. + APIVersion string `json:"api_version"` + // Authentication context needed to fetch the event or related object. + Context string `json:"context"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + Data *EventData `json:"data"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Number of webhooks that haven't been successfully delivered (for example, to return a 20x response) to the URLs you specify. + PendingWebhooks int64 `json:"pending_webhooks"` + // Information on the API request that triggers the event. + Request *EventRequest `json:"request"` + // Description of the event (for example, `invoice.created` or `charge.refunded`). + Type EventType `json:"type"` +} + +// EventList is a list of Events as retrieved from a list endpoint. +type EventList struct { + APIResource + ListMeta + Data []*Event `json:"data"` +} + +// GetObjectValue returns the value from the e.Data.Object bag based on the keys hierarchy. +func (e *Event) GetObjectValue(keys ...string) string { + return getValue(e.Data.Object, keys) +} + +// GetPreviousValue returns the value from the e.Data.Prev bag based on the keys hierarchy. +func (e *Event) GetPreviousValue(keys ...string) string { + return getValue(e.Data.PreviousAttributes, keys) +} + +// UnmarshalJSON handles deserialization of the EventData. +// This custom unmarshaling exists so that we can keep both the map and raw data. +func (e *EventData) UnmarshalJSON(data []byte) error { + type eventdata EventData + var ee eventdata + err := json.Unmarshal(data, &ee) + if err != nil { + return err + } + + *e = EventData(ee) + return json.Unmarshal(e.Raw, &e.Object) +} + +// getValue returns the value from the m map based on the keys. +func getValue(m map[string]interface{}, keys []string) string { + node := m[keys[0]] + + for i := 1; i < len(keys); i++ { + key := keys[i] + + sliceNode, ok := node.([]interface{}) + if ok { + intKey, err := strconv.Atoi(key) + if err != nil { + panic(fmt.Sprintf( + "Cannot access nested slice element with non-integer key: %s", + key)) + } + node = sliceNode[intKey] + continue + } + + mapNode, ok := node.(map[string]interface{}) + if ok { + node = mapNode[key] + continue + } + + panic(fmt.Sprintf( + "Cannot descend into non-map non-slice object with key: %s", key)) + } + + if node == nil { + return "" + } + + return fmt.Sprintf("%v", node) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/event_service.go b/vendor/github.com/stripe/stripe-go/v82/event_service.go new file mode 100644 index 00000000..6cdefa0e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/event_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1EventService is used to invoke /v1/events APIs. +type v1EventService struct { + B Backend + Key string +} + +// Retrieves the details of an event if it was created in the last 30 days. Supply the unique identifier of the event, which you might have received in a webhook. +func (c v1EventService) Retrieve(ctx context.Context, id string, params *EventRetrieveParams) (*Event, error) { + if params == nil { + params = &EventRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/events/%s", id) + event := &Event{} + err := c.B.Call(http.MethodGet, path, c.Key, params, event) + return event, err +} + +// List events, going back up to 30 days. Each event data is rendered according to Stripe API version at its creation time, specified in [event object](https://docs.stripe.com/api/events/object) api_version attribute (not according to your current Stripe API version or Stripe-Version header). +func (c v1EventService) List(ctx context.Context, listParams *EventListParams) Seq2[*Event, error] { + if listParams == nil { + listParams = &EventListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Event, ListContainer, error) { + list := &EventList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/events", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/feerefund.go b/vendor/github.com/stripe/stripe-go/v82/feerefund.go new file mode 100644 index 00000000..08dbdb69 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/feerefund.go @@ -0,0 +1,173 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// By default, you can see the 10 most recent refunds stored directly on the application fee object, but you can also retrieve details about a specific refund stored on the application fee. +type FeeRefundParams struct { + Params `form:"*"` + ID *string `form:"-"` // Included in URL + Fee *string `form:"-"` // Included in URL + // A positive integer, in _cents (or local equivalent)_, representing how much of this fee to refund. Can refund only up to the remaining unrefunded amount of the fee. + Amount *int64 `form:"amount"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *FeeRefundParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *FeeRefundParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// You can see a list of the refunds belonging to a specific application fee. Note that the 10 most recent refunds are always available by default on the application fee object. If you need more than those 10, you can use this API method and the limit and starting_after parameters to page through additional refunds. +type FeeRefundListParams struct { + ListParams `form:"*"` + ID *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *FeeRefundListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// By default, you can see the 10 most recent refunds stored directly on the application fee object, but you can also retrieve details about a specific refund stored on the application fee. +type FeeRefundRetrieveParams struct { + Params `form:"*"` + Fee *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *FeeRefundRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the specified application fee refund by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +// +// This request only accepts metadata as an argument. +type FeeRefundUpdateParams struct { + Params `form:"*"` + Fee *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *FeeRefundUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *FeeRefundUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Refunds an application fee that has previously been collected but not yet refunded. +// Funds will be refunded to the Stripe account from which the fee was originally collected. +// +// You can optionally refund only part of an application fee. +// You can do so multiple times, until the entire fee has been refunded. +// +// Once entirely refunded, an application fee can't be refunded again. +// This method will raise an error when called on an already-refunded application fee, +// or when trying to refund more money than is left on an application fee. +type FeeRefundCreateParams struct { + Params `form:"*"` + ID *string `form:"-"` // Included in URL + // A positive integer, in _cents (or local equivalent)_, representing how much of this fee to refund. Can refund only up to the remaining unrefunded amount of the fee. + Amount *int64 `form:"amount"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *FeeRefundCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *FeeRefundCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// `Application Fee Refund` objects allow you to refund an application fee that +// has previously been created but not yet refunded. Funds will be refunded to +// the Stripe account from which the fee was originally collected. +// +// Related guide: [Refunding application fees](https://stripe.com/docs/connect/destination-charges#refunding-app-fee) +type FeeRefund struct { + APIResource + // Amount, in cents (or local equivalent). + Amount int64 `json:"amount"` + // Balance transaction that describes the impact on your account balance. + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // ID of the application fee that was refunded. + Fee *ApplicationFee `json:"fee"` + // Unique identifier for the object. + ID string `json:"id"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} + +// FeeRefundList is a list of FeeRefunds as retrieved from a list endpoint. +type FeeRefundList struct { + APIResource + ListMeta + Data []*FeeRefund `json:"data"` +} + +// UnmarshalJSON handles deserialization of a FeeRefund. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (f *FeeRefund) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + f.ID = id + return nil + } + + type feeRefund FeeRefund + var v feeRefund + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *f = FeeRefund(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/feerefund_service.go b/vendor/github.com/stripe/stripe-go/v82/feerefund_service.go new file mode 100644 index 00000000..dcfc5d68 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/feerefund_service.go @@ -0,0 +1,95 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "fmt" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1FeeRefundService is used to invoke /v1/application_fees/{id}/refunds APIs. +type v1FeeRefundService struct { + B Backend + Key string +} + +// Refunds an application fee that has previously been collected but not yet refunded. +// Funds will be refunded to the Stripe account from which the fee was originally collected. +// +// You can optionally refund only part of an application fee. +// You can do so multiple times, until the entire fee has been refunded. +// +// Once entirely refunded, an application fee can't be refunded again. +// This method will raise an error when called on an already-refunded application fee, +// or when trying to refund more money than is left on an application fee. +func (c v1FeeRefundService) Create(ctx context.Context, params *FeeRefundCreateParams) (*FeeRefund, error) { + if params == nil { + params = &FeeRefundCreateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/application_fees/%s/refunds", StringValue(params.ID)) + feerefund := &FeeRefund{} + err := c.B.Call(http.MethodPost, path, c.Key, params, feerefund) + return feerefund, err +} + +// By default, you can see the 10 most recent refunds stored directly on the application fee object, but you can also retrieve details about a specific refund stored on the application fee. +func (c v1FeeRefundService) Retrieve(ctx context.Context, id string, params *FeeRefundRetrieveParams) (*FeeRefund, error) { + if params == nil { + params = &FeeRefundRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/application_fees/%s/refunds/%s", StringValue(params.Fee), id) + feerefund := &FeeRefund{} + err := c.B.Call(http.MethodGet, path, c.Key, params, feerefund) + return feerefund, err +} + +// Updates the specified application fee refund by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +// +// This request only accepts metadata as an argument. +func (c v1FeeRefundService) Update(ctx context.Context, id string, params *FeeRefundUpdateParams) (*FeeRefund, error) { + if params == nil { + return nil, fmt.Errorf("params cannot be nil") + } + if params.Fee == nil { + return nil, fmt.Errorf("params.Fee must be set") + } + if params == nil { + params = &FeeRefundUpdateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/application_fees/%s/refunds/%s", StringValue(params.Fee), id) + feerefund := &FeeRefund{} + err := c.B.Call(http.MethodPost, path, c.Key, params, feerefund) + return feerefund, err +} + +// You can see a list of the refunds belonging to a specific application fee. Note that the 10 most recent refunds are always available by default on the application fee object. If you need more than those 10, you can use this API method and the limit and starting_after parameters to page through additional refunds. +func (c v1FeeRefundService) List(ctx context.Context, listParams *FeeRefundListParams) Seq2[*FeeRefund, error] { + if listParams == nil { + listParams = &FeeRefundListParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/application_fees/%s/refunds", StringValue(listParams.ID)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*FeeRefund, ListContainer, error) { + list := &FeeRefundList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/file.go b/vendor/github.com/stripe/stripe-go/v82/file.go new file mode 100644 index 00000000..350c4ceb --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/file.go @@ -0,0 +1,318 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "bytes" + "encoding/json" + "github.com/stripe/stripe-go/v82/form" + "io" + "mime/multipart" + "net/url" + "path/filepath" +) + +// The [purpose](https://stripe.com/docs/file-upload#uploading-a-file) of the uploaded file. +type FilePurpose string + +// List of values that FilePurpose can take +const ( + FilePurposeAccountRequirement FilePurpose = "account_requirement" + FilePurposeAdditionalVerification FilePurpose = "additional_verification" + FilePurposeBusinessIcon FilePurpose = "business_icon" + FilePurposeBusinessLogo FilePurpose = "business_logo" + FilePurposeCustomerSignature FilePurpose = "customer_signature" + FilePurposeDisputeEvidence FilePurpose = "dispute_evidence" + FilePurposeDocumentProviderIdentityDocument FilePurpose = "document_provider_identity_document" + FilePurposeFinanceReportRun FilePurpose = "finance_report_run" + FilePurposeFinancialAccountStatement FilePurpose = "financial_account_statement" + FilePurposeIdentityDocument FilePurpose = "identity_document" + FilePurposeIdentityDocumentDownloadable FilePurpose = "identity_document_downloadable" + FilePurposeIssuingRegulatoryReporting FilePurpose = "issuing_regulatory_reporting" + FilePurposePCIDocument FilePurpose = "pci_document" + FilePurposeSelfie FilePurpose = "selfie" + FilePurposeSigmaScheduledQuery FilePurpose = "sigma_scheduled_query" + FilePurposeTaxDocumentUserUpload FilePurpose = "tax_document_user_upload" + FilePurposeTerminalReaderSplashscreen FilePurpose = "terminal_reader_splashscreen" +) + +// Returns a list of the files that your account has access to. Stripe sorts and returns the files by their creation dates, placing the most recently created files at the top. +type FileListParams struct { + ListParams `form:"*"` + // Only return files that were created during the given date interval. + Created *int64 `form:"created"` + // Only return files that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Filter queries by the file purpose. If you don't provide a purpose, the queries return unfiltered files. + Purpose *string `form:"purpose"` +} + +// AddExpand appends a new field to expand. +func (p *FileListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Optional parameters that automatically create a [file link](https://stripe.com/docs/api#file_links) for the newly created file. +type FileFileLinkDataParams struct { + Params `form:"*"` + // Set this to `true` to create a file link for the newly created file. Creating a link is only possible when the file's `purpose` is one of the following: `business_icon`, `business_logo`, `customer_signature`, `dispute_evidence`, `issuing_regulatory_reporting`, `pci_document`, `tax_document_user_upload`, or `terminal_reader_splashscreen`. + Create *bool `form:"create"` + // The link isn't available after this future timestamp. + ExpiresAt *int64 `form:"expires_at"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *FileFileLinkDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// To upload a file to Stripe, you need to send a request of type multipart/form-data. Include the file you want to upload in the request, and the parameters for creating a file. +// +// All of Stripe's officially supported Client libraries support sending multipart/form-data. +type FileParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // FileReader is a reader with the contents of the file that should be uploaded. + FileReader io.Reader + + // Filename is just the name of the file without path information. + Filename *string + // Optional parameters that automatically create a [file link](https://stripe.com/docs/api#file_links) for the newly created file. + FileLinkData *FileFileLinkDataParams `form:"file_link_data"` + // The [purpose](https://stripe.com/docs/file-upload#uploading-a-file) of the uploaded file. + Purpose *string `form:"purpose"` +} + +// GetBody gets an appropriate multipart form payload to use in a request body +// to create a new file. +func (p *FileParams) GetBody() (*bytes.Buffer, string, error) { + body := &bytes.Buffer{} + writer := multipart.NewWriter(body) + + if p.Purpose != nil { + err := writer.WriteField("purpose", StringValue(p.Purpose)) + if err != nil { + return nil, "", err + } + } + + if p.FileReader != nil && p.Filename != nil { + part, err := writer.CreateFormFile( + "file", filepath.Base(StringValue(p.Filename))) + + if err != nil { + return nil, "", err + } + + _, err = io.Copy(part, p.FileReader) + if err != nil { + return nil, "", err + } + } + + if p.FileLinkData != nil { + values := &form.Values{} + form.AppendToPrefixed(values, p.FileLinkData, []string{"file_link_data"}) + + params, err := url.ParseQuery(values.Encode()) + if err != nil { + return nil, "", err + } + for key, values := range params { + err := writer.WriteField(key, values[0]) + if err != nil { + return nil, "", err + } + } + } + + err := writer.Close() + if err != nil { + return nil, "", err + } + + return body, writer.Boundary(), nil +} + +// AddExpand appends a new field to expand. +func (p *FileParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Optional parameters that automatically create a [file link](https://stripe.com/docs/api#file_links) for the newly created file. +type FileCreateFileLinkDataParams struct { + Params `form:"*"` + // Set this to `true` to create a file link for the newly created file. Creating a link is only possible when the file's `purpose` is one of the following: `business_icon`, `business_logo`, `customer_signature`, `dispute_evidence`, `issuing_regulatory_reporting`, `pci_document`, `tax_document_user_upload`, or `terminal_reader_splashscreen`. + Create *bool `form:"create"` + // The link isn't available after this future timestamp. + ExpiresAt *int64 `form:"expires_at"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *FileCreateFileLinkDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// To upload a file to Stripe, you need to send a request of type multipart/form-data. Include the file you want to upload in the request, and the parameters for creating a file. +// +// All of Stripe's officially supported Client libraries support sending multipart/form-data. +type FileCreateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // FileReader is a reader with the contents of the file that should be uploaded. + FileReader io.Reader + + // Filename is just the name of the file without path information. + Filename *string + // Optional parameters that automatically create a [file link](https://stripe.com/docs/api#file_links) for the newly created file. + FileLinkData *FileCreateFileLinkDataParams `form:"file_link_data"` + // The [purpose](https://stripe.com/docs/file-upload#uploading-a-file) of the uploaded file. + Purpose *string `form:"purpose"` +} + +// GetBody gets an appropriate multipart form payload to use in a request body +// to create a new file. +func (p *FileCreateParams) GetBody() (*bytes.Buffer, string, error) { + body := &bytes.Buffer{} + writer := multipart.NewWriter(body) + + if p.Purpose != nil { + err := writer.WriteField("purpose", StringValue(p.Purpose)) + if err != nil { + return nil, "", err + } + } + + if p.FileReader != nil && p.Filename != nil { + part, err := writer.CreateFormFile( + "file", filepath.Base(StringValue(p.Filename))) + + if err != nil { + return nil, "", err + } + + _, err = io.Copy(part, p.FileReader) + if err != nil { + return nil, "", err + } + } + + if p.FileLinkData != nil { + values := &form.Values{} + form.AppendToPrefixed(values, p.FileLinkData, []string{"file_link_data"}) + + params, err := url.ParseQuery(values.Encode()) + if err != nil { + return nil, "", err + } + for key, values := range params { + err := writer.WriteField(key, values[0]) + if err != nil { + return nil, "", err + } + } + } + + err := writer.Close() + if err != nil { + return nil, "", err + } + + return body, writer.Boundary(), nil +} + +// AddExpand appends a new field to expand. +func (p *FileCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an existing file object. After you supply a unique file ID, Stripe returns the corresponding file object. Learn how to [access file contents](https://docs.stripe.com/docs/file-upload#download-file-contents). +type FileRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *FileRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// This object represents files hosted on Stripe's servers. You can upload +// files with the [create file](https://stripe.com/docs/api#create_file) request +// (for example, when uploading dispute evidence). Stripe also +// creates files independently (for example, the results of a [Sigma scheduled +// query](https://docs.stripe.com/api#scheduled_queries)). +// +// Related guide: [File upload guide](https://stripe.com/docs/file-upload) +type File struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The file expires and isn't available at this time in epoch seconds. + ExpiresAt int64 `json:"expires_at"` + // The suitable name for saving the file to a filesystem. + Filename string `json:"filename"` + // Unique identifier for the object. + ID string `json:"id"` + // A list of [file links](https://stripe.com/docs/api#file_links) that point at this file. + Links *FileLinkList `json:"links"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The [purpose](https://stripe.com/docs/file-upload#uploading-a-file) of the uploaded file. + Purpose FilePurpose `json:"purpose"` + // The size of the file object in bytes. + Size int64 `json:"size"` + // A suitable title for the document. + Title string `json:"title"` + // The returned file type (for example, `csv`, `pdf`, `jpg`, or `png`). + Type string `json:"type"` + // Use your live secret API key to download the file from this URL. + URL string `json:"url"` +} + +// FileList is a list of Files as retrieved from a list endpoint. +type FileList struct { + APIResource + ListMeta + Data []*File `json:"data"` +} + +// UnmarshalJSON handles deserialization of a File. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (f *File) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + f.ID = id + return nil + } + + type file File + var v file + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *f = File(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/file_service.go b/vendor/github.com/stripe/stripe-go/v82/file_service.go new file mode 100644 index 00000000..ade2f5c1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/file_service.go @@ -0,0 +1,69 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "fmt" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1FileService is used to invoke /v1/files APIs. +type v1FileService struct { + B Backend + BUploads Backend + Key string +} + +// To upload a file to Stripe, you need to send a request of type multipart/form-data. Include the file you want to upload in the request, and the parameters for creating a file. +// +// All of Stripe's officially supported Client libraries support sending multipart/form-data. +func (c v1FileService) Create(ctx context.Context, params *FileCreateParams) (*File, error) { + if params == nil { + return nil, fmt.Errorf( + "params cannot be nil, and params.Purpose and params.File must be set") + } + bodyBuffer, boundary, err := params.GetBody() + if err != nil { + return nil, err + } + params.Context = ctx + file := &File{} + err = c.BUploads.CallMultipart(http.MethodPost, "/v1/files", c.Key, boundary, bodyBuffer, ¶ms.Params, file) + return file, err +} + +// Retrieves the details of an existing file object. After you supply a unique file ID, Stripe returns the corresponding file object. Learn how to [access file contents](https://docs.stripe.com/docs/file-upload#download-file-contents). +func (c v1FileService) Retrieve(ctx context.Context, id string, params *FileRetrieveParams) (*File, error) { + if params == nil { + params = &FileRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/files/%s", id) + file := &File{} + err := c.B.Call(http.MethodGet, path, c.Key, params, file) + return file, err +} + +// Returns a list of the files that your account has access to. Stripe sorts and returns the files by their creation dates, placing the most recently created files at the top. +func (c v1FileService) List(ctx context.Context, listParams *FileListParams) Seq2[*File, error] { + if listParams == nil { + listParams = &FileListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*File, ListContainer, error) { + list := &FileList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/files", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/filelink.go b/vendor/github.com/stripe/stripe-go/v82/filelink.go new file mode 100644 index 00000000..8c46f8be --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/filelink.go @@ -0,0 +1,168 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "github.com/stripe/stripe-go/v82/form" + +// Returns a list of file links. +type FileLinkListParams struct { + ListParams `form:"*"` + // Only return links that were created during the given date interval. + Created *int64 `form:"created"` + // Only return links that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Filter links by their expiration status. By default, Stripe returns all links. + Expired *bool `form:"expired"` + // Only return links for the given file. + File *string `form:"file"` +} + +// AddExpand appends a new field to expand. +func (p *FileLinkListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates a new file link object. +type FileLinkParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A future timestamp after which the link will no longer be usable, or `now` to expire the link immediately. + ExpiresAt *int64 `form:"expires_at"` + ExpiresAtNow *bool `form:"-"` // See custom AppendTo + // The ID of the file. The file's `purpose` must be one of the following: `business_icon`, `business_logo`, `customer_signature`, `dispute_evidence`, `finance_report_run`, `financial_account_statement`, `identity_document_downloadable`, `issuing_regulatory_reporting`, `pci_document`, `selfie`, `sigma_scheduled_query`, `tax_document_user_upload`, or `terminal_reader_splashscreen`. + File *string `form:"file"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *FileLinkParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *FileLinkParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// AppendTo implements custom encoding logic for FileLinkParams. +func (p *FileLinkParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.ExpiresAtNow) { + body.Add(form.FormatKey(append(keyParts, "expires_at")), "now") + } +} + +// Creates a new file link object. +type FileLinkCreateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The link isn't usable after this future timestamp. + ExpiresAt *int64 `form:"expires_at"` + // The ID of the file. The file's `purpose` must be one of the following: `business_icon`, `business_logo`, `customer_signature`, `dispute_evidence`, `finance_report_run`, `financial_account_statement`, `identity_document_downloadable`, `issuing_regulatory_reporting`, `pci_document`, `selfie`, `sigma_scheduled_query`, `tax_document_user_upload`, or `terminal_reader_splashscreen`. + File *string `form:"file"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *FileLinkCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *FileLinkCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the file link with the given ID. +type FileLinkRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *FileLinkRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates an existing file link object. Expired links can no longer be updated. +type FileLinkUpdateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A future timestamp after which the link will no longer be usable, or `now` to expire the link immediately. + ExpiresAt *int64 `form:"expires_at"` + ExpiresAtNow *bool `form:"-"` // See custom AppendTo + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *FileLinkUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *FileLinkUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// AppendTo implements custom encoding logic for FileLinkUpdateParams. +func (p *FileLinkUpdateParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.ExpiresAtNow) { + body.Add(form.FormatKey(append(keyParts, "expires_at")), "now") + } +} + +// To share the contents of a `File` object with non-Stripe users, you can +// create a `FileLink`. `FileLink`s contain a URL that you can use to +// retrieve the contents of the file without authentication. +type FileLink struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Returns if the link is already expired. + Expired bool `json:"expired"` + // Time that the link expires. + ExpiresAt int64 `json:"expires_at"` + // The file object this link points to. + File *File `json:"file"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The publicly accessible URL to download the file. + URL string `json:"url"` +} + +// FileLinkList is a list of FileLinks as retrieved from a list endpoint. +type FileLinkList struct { + APIResource + ListMeta + Data []*FileLink `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/filelink_service.go b/vendor/github.com/stripe/stripe-go/v82/filelink_service.go new file mode 100644 index 00000000..d691f305 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/filelink_service.go @@ -0,0 +1,72 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1FileLinkService is used to invoke /v1/file_links APIs. +type v1FileLinkService struct { + B Backend + Key string +} + +// Creates a new file link object. +func (c v1FileLinkService) Create(ctx context.Context, params *FileLinkCreateParams) (*FileLink, error) { + if params == nil { + params = &FileLinkCreateParams{} + } + params.Context = ctx + filelink := &FileLink{} + err := c.B.Call(http.MethodPost, "/v1/file_links", c.Key, params, filelink) + return filelink, err +} + +// Retrieves the file link with the given ID. +func (c v1FileLinkService) Retrieve(ctx context.Context, id string, params *FileLinkRetrieveParams) (*FileLink, error) { + if params == nil { + params = &FileLinkRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/file_links/%s", id) + filelink := &FileLink{} + err := c.B.Call(http.MethodGet, path, c.Key, params, filelink) + return filelink, err +} + +// Updates an existing file link object. Expired links can no longer be updated. +func (c v1FileLinkService) Update(ctx context.Context, id string, params *FileLinkUpdateParams) (*FileLink, error) { + if params == nil { + params = &FileLinkUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/file_links/%s", id) + filelink := &FileLink{} + err := c.B.Call(http.MethodPost, path, c.Key, params, filelink) + return filelink, err +} + +// Returns a list of file links. +func (c v1FileLinkService) List(ctx context.Context, listParams *FileLinkListParams) Seq2[*FileLink, error] { + if listParams == nil { + listParams = &FileLinkListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*FileLink, ListContainer, error) { + list := &FileLinkList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/file_links", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/financialconnections_account.go b/vendor/github.com/stripe/stripe-go/v82/financialconnections_account.go new file mode 100644 index 00000000..52e363de --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/financialconnections_account.go @@ -0,0 +1,384 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Type of account holder that this account belongs to. +type FinancialConnectionsAccountAccountHolderType string + +// List of values that FinancialConnectionsAccountAccountHolderType can take +const ( + FinancialConnectionsAccountAccountHolderTypeAccount FinancialConnectionsAccountAccountHolderType = "account" + FinancialConnectionsAccountAccountHolderTypeCustomer FinancialConnectionsAccountAccountHolderType = "customer" +) + +// The `type` of the balance. An additional hash is included on the balance with a name matching this value. +type FinancialConnectionsAccountBalanceType string + +// List of values that FinancialConnectionsAccountBalanceType can take +const ( + FinancialConnectionsAccountBalanceTypeCash FinancialConnectionsAccountBalanceType = "cash" + FinancialConnectionsAccountBalanceTypeCredit FinancialConnectionsAccountBalanceType = "credit" +) + +// The status of the last refresh attempt. +type FinancialConnectionsAccountBalanceRefreshStatus string + +// List of values that FinancialConnectionsAccountBalanceRefreshStatus can take +const ( + FinancialConnectionsAccountBalanceRefreshStatusFailed FinancialConnectionsAccountBalanceRefreshStatus = "failed" + FinancialConnectionsAccountBalanceRefreshStatusPending FinancialConnectionsAccountBalanceRefreshStatus = "pending" + FinancialConnectionsAccountBalanceRefreshStatusSucceeded FinancialConnectionsAccountBalanceRefreshStatus = "succeeded" +) + +// The type of the account. Account category is further divided in `subcategory`. +type FinancialConnectionsAccountCategory string + +// List of values that FinancialConnectionsAccountCategory can take +const ( + FinancialConnectionsAccountCategoryCash FinancialConnectionsAccountCategory = "cash" + FinancialConnectionsAccountCategoryCredit FinancialConnectionsAccountCategory = "credit" + FinancialConnectionsAccountCategoryInvestment FinancialConnectionsAccountCategory = "investment" + FinancialConnectionsAccountCategoryOther FinancialConnectionsAccountCategory = "other" +) + +// The status of the last refresh attempt. +type FinancialConnectionsAccountOwnershipRefreshStatus string + +// List of values that FinancialConnectionsAccountOwnershipRefreshStatus can take +const ( + FinancialConnectionsAccountOwnershipRefreshStatusFailed FinancialConnectionsAccountOwnershipRefreshStatus = "failed" + FinancialConnectionsAccountOwnershipRefreshStatusPending FinancialConnectionsAccountOwnershipRefreshStatus = "pending" + FinancialConnectionsAccountOwnershipRefreshStatusSucceeded FinancialConnectionsAccountOwnershipRefreshStatus = "succeeded" +) + +// The list of permissions granted by this account. +type FinancialConnectionsAccountPermission string + +// List of values that FinancialConnectionsAccountPermission can take +const ( + FinancialConnectionsAccountPermissionBalances FinancialConnectionsAccountPermission = "balances" + FinancialConnectionsAccountPermissionOwnership FinancialConnectionsAccountPermission = "ownership" + FinancialConnectionsAccountPermissionPaymentMethod FinancialConnectionsAccountPermission = "payment_method" + FinancialConnectionsAccountPermissionTransactions FinancialConnectionsAccountPermission = "transactions" +) + +// The status of the link to the account. +type FinancialConnectionsAccountStatus string + +// List of values that FinancialConnectionsAccountStatus can take +const ( + FinancialConnectionsAccountStatusActive FinancialConnectionsAccountStatus = "active" + FinancialConnectionsAccountStatusDisconnected FinancialConnectionsAccountStatus = "disconnected" + FinancialConnectionsAccountStatusInactive FinancialConnectionsAccountStatus = "inactive" +) + +// If `category` is `cash`, one of: +// +// - `checking` +// - `savings` +// - `other` +// +// If `category` is `credit`, one of: +// +// - `mortgage` +// - `line_of_credit` +// - `credit_card` +// - `other` +// +// If `category` is `investment` or `other`, this will be `other`. +type FinancialConnectionsAccountSubcategory string + +// List of values that FinancialConnectionsAccountSubcategory can take +const ( + FinancialConnectionsAccountSubcategoryChecking FinancialConnectionsAccountSubcategory = "checking" + FinancialConnectionsAccountSubcategoryCreditCard FinancialConnectionsAccountSubcategory = "credit_card" + FinancialConnectionsAccountSubcategoryLineOfCredit FinancialConnectionsAccountSubcategory = "line_of_credit" + FinancialConnectionsAccountSubcategoryMortgage FinancialConnectionsAccountSubcategory = "mortgage" + FinancialConnectionsAccountSubcategoryOther FinancialConnectionsAccountSubcategory = "other" + FinancialConnectionsAccountSubcategorySavings FinancialConnectionsAccountSubcategory = "savings" +) + +// The list of data refresh subscriptions requested on this account. +type FinancialConnectionsAccountSubscription string + +// List of values that FinancialConnectionsAccountSubscription can take +const ( + FinancialConnectionsAccountSubscriptionTransactions FinancialConnectionsAccountSubscription = "transactions" +) + +// The [PaymentMethod type](https://stripe.com/docs/api/payment_methods/object#payment_method_object-type)(s) that can be created from this account. +type FinancialConnectionsAccountSupportedPaymentMethodType string + +// List of values that FinancialConnectionsAccountSupportedPaymentMethodType can take +const ( + FinancialConnectionsAccountSupportedPaymentMethodTypeLink FinancialConnectionsAccountSupportedPaymentMethodType = "link" + FinancialConnectionsAccountSupportedPaymentMethodTypeUSBankAccount FinancialConnectionsAccountSupportedPaymentMethodType = "us_bank_account" +) + +// The status of the last refresh attempt. +type FinancialConnectionsAccountTransactionRefreshStatus string + +// List of values that FinancialConnectionsAccountTransactionRefreshStatus can take +const ( + FinancialConnectionsAccountTransactionRefreshStatusFailed FinancialConnectionsAccountTransactionRefreshStatus = "failed" + FinancialConnectionsAccountTransactionRefreshStatusPending FinancialConnectionsAccountTransactionRefreshStatus = "pending" + FinancialConnectionsAccountTransactionRefreshStatusSucceeded FinancialConnectionsAccountTransactionRefreshStatus = "succeeded" +) + +// If present, only return accounts that belong to the specified account holder. `account_holder[customer]` and `account_holder[account]` are mutually exclusive. +type FinancialConnectionsAccountListAccountHolderParams struct { + // The ID of the Stripe account whose accounts will be retrieved. + Account *string `form:"account"` + // The ID of the Stripe customer whose accounts will be retrieved. + Customer *string `form:"customer"` +} + +// Returns a list of Financial Connections Account objects. +type FinancialConnectionsAccountListParams struct { + ListParams `form:"*"` + // If present, only return accounts that belong to the specified account holder. `account_holder[customer]` and `account_holder[account]` are mutually exclusive. + AccountHolder *FinancialConnectionsAccountListAccountHolderParams `form:"account_holder"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // If present, only return accounts that were collected as part of the given session. + Session *string `form:"session"` +} + +// AddExpand appends a new field to expand. +func (p *FinancialConnectionsAccountListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an Financial Connections Account. +type FinancialConnectionsAccountParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *FinancialConnectionsAccountParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Lists all owners for a given Account +type FinancialConnectionsAccountListOwnersParams struct { + ListParams `form:"*"` + Account *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The ID of the ownership object to fetch owners from. + Ownership *string `form:"ownership"` +} + +// AddExpand appends a new field to expand. +func (p *FinancialConnectionsAccountListOwnersParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Disables your access to a Financial Connections Account. You will no longer be able to access data associated with the account (e.g. balances, transactions). +type FinancialConnectionsAccountDisconnectParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *FinancialConnectionsAccountDisconnectParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Refreshes the data associated with a Financial Connections Account. +type FinancialConnectionsAccountRefreshParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The list of account features that you would like to refresh. + Features []*string `form:"features"` +} + +// AddExpand appends a new field to expand. +func (p *FinancialConnectionsAccountRefreshParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Subscribes to periodic refreshes of data associated with a Financial Connections Account. +type FinancialConnectionsAccountSubscribeParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The list of account features to which you would like to subscribe. + Features []*string `form:"features"` +} + +// AddExpand appends a new field to expand. +func (p *FinancialConnectionsAccountSubscribeParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Unsubscribes from periodic refreshes of data associated with a Financial Connections Account. +type FinancialConnectionsAccountUnsubscribeParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The list of account features from which you would like to unsubscribe. + Features []*string `form:"features"` +} + +// AddExpand appends a new field to expand. +func (p *FinancialConnectionsAccountUnsubscribeParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an Financial Connections Account. +type FinancialConnectionsAccountRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *FinancialConnectionsAccountRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The account holder that this account belongs to. +type FinancialConnectionsAccountAccountHolder struct { + // The ID of the Stripe account this account belongs to. Should only be present if `account_holder.type` is `account`. + Account *Account `json:"account"` + // ID of the Stripe customer this account belongs to. Present if and only if `account_holder.type` is `customer`. + Customer *Customer `json:"customer"` + // Type of account holder that this account belongs to. + Type FinancialConnectionsAccountAccountHolderType `json:"type"` +} +type FinancialConnectionsAccountBalanceCash struct { + // The funds available to the account holder. Typically this is the current balance after subtracting any outbound pending transactions and adding any inbound pending transactions. + // + // Each key is a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + // + // Each value is a integer amount. A positive amount indicates money owed to the account holder. A negative amount indicates money owed by the account holder. + Available map[string]int64 `json:"available"` +} +type FinancialConnectionsAccountBalanceCredit struct { + // The credit that has been used by the account holder. + // + // Each key is a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + // + // Each value is a integer amount. A positive amount indicates money owed to the account holder. A negative amount indicates money owed by the account holder. + Used map[string]int64 `json:"used"` +} + +// The most recent information about the account's balance. +type FinancialConnectionsAccountBalance struct { + // The time that the external institution calculated this balance. Measured in seconds since the Unix epoch. + AsOf int64 `json:"as_of"` + Cash *FinancialConnectionsAccountBalanceCash `json:"cash"` + Credit *FinancialConnectionsAccountBalanceCredit `json:"credit"` + // The balances owed to (or by) the account holder, before subtracting any outbound pending transactions or adding any inbound pending transactions. + // + // Each key is a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + // + // Each value is a integer amount. A positive amount indicates money owed to the account holder. A negative amount indicates money owed by the account holder. + Current map[string]int64 `json:"current"` + // The `type` of the balance. An additional hash is included on the balance with a name matching this value. + Type FinancialConnectionsAccountBalanceType `json:"type"` +} + +// The state of the most recent attempt to refresh the account balance. +type FinancialConnectionsAccountBalanceRefresh struct { + // The time at which the last refresh attempt was initiated. Measured in seconds since the Unix epoch. + LastAttemptedAt int64 `json:"last_attempted_at"` + // Time at which the next balance refresh can be initiated. This value will be `null` when `status` is `pending`. Measured in seconds since the Unix epoch. + NextRefreshAvailableAt int64 `json:"next_refresh_available_at"` + // The status of the last refresh attempt. + Status FinancialConnectionsAccountBalanceRefreshStatus `json:"status"` +} + +// The state of the most recent attempt to refresh the account owners. +type FinancialConnectionsAccountOwnershipRefresh struct { + // The time at which the last refresh attempt was initiated. Measured in seconds since the Unix epoch. + LastAttemptedAt int64 `json:"last_attempted_at"` + // Time at which the next ownership refresh can be initiated. This value will be `null` when `status` is `pending`. Measured in seconds since the Unix epoch. + NextRefreshAvailableAt int64 `json:"next_refresh_available_at"` + // The status of the last refresh attempt. + Status FinancialConnectionsAccountOwnershipRefreshStatus `json:"status"` +} + +// The state of the most recent attempt to refresh the account transactions. +type FinancialConnectionsAccountTransactionRefresh struct { + // Unique identifier for the object. + ID string `json:"id"` + // The time at which the last refresh attempt was initiated. Measured in seconds since the Unix epoch. + LastAttemptedAt int64 `json:"last_attempted_at"` + // Time at which the next transaction refresh can be initiated. This value will be `null` when `status` is `pending`. Measured in seconds since the Unix epoch. + NextRefreshAvailableAt int64 `json:"next_refresh_available_at"` + // The status of the last refresh attempt. + Status FinancialConnectionsAccountTransactionRefreshStatus `json:"status"` +} + +// A Financial Connections Account represents an account that exists outside of Stripe, to which you have been granted some degree of access. +type FinancialConnectionsAccount struct { + APIResource + // The account holder that this account belongs to. + AccountHolder *FinancialConnectionsAccountAccountHolder `json:"account_holder"` + // The most recent information about the account's balance. + Balance *FinancialConnectionsAccountBalance `json:"balance"` + // The state of the most recent attempt to refresh the account balance. + BalanceRefresh *FinancialConnectionsAccountBalanceRefresh `json:"balance_refresh"` + // The type of the account. Account category is further divided in `subcategory`. + Category FinancialConnectionsAccountCategory `json:"category"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // A human-readable name that has been assigned to this account, either by the account holder or by the institution. + DisplayName string `json:"display_name"` + // Unique identifier for the object. + ID string `json:"id"` + // The name of the institution that holds this account. + InstitutionName string `json:"institution_name"` + // The last 4 digits of the account number. If present, this will be 4 numeric characters. + Last4 string `json:"last4"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The most recent information about the account's owners. + Ownership *FinancialConnectionsAccountOwnership `json:"ownership"` + // The state of the most recent attempt to refresh the account owners. + OwnershipRefresh *FinancialConnectionsAccountOwnershipRefresh `json:"ownership_refresh"` + // The list of permissions granted by this account. + Permissions []FinancialConnectionsAccountPermission `json:"permissions"` + // The status of the link to the account. + Status FinancialConnectionsAccountStatus `json:"status"` + // If `category` is `cash`, one of: + // + // - `checking` + // - `savings` + // - `other` + // + // If `category` is `credit`, one of: + // + // - `mortgage` + // - `line_of_credit` + // - `credit_card` + // - `other` + // + // If `category` is `investment` or `other`, this will be `other`. + Subcategory FinancialConnectionsAccountSubcategory `json:"subcategory"` + // The list of data refresh subscriptions requested on this account. + Subscriptions []FinancialConnectionsAccountSubscription `json:"subscriptions"` + // The [PaymentMethod type](https://stripe.com/docs/api/payment_methods/object#payment_method_object-type)(s) that can be created from this account. + SupportedPaymentMethodTypes []FinancialConnectionsAccountSupportedPaymentMethodType `json:"supported_payment_method_types"` + // The state of the most recent attempt to refresh the account transactions. + TransactionRefresh *FinancialConnectionsAccountTransactionRefresh `json:"transaction_refresh"` +} + +// FinancialConnectionsAccountList is a list of Accounts as retrieved from a list endpoint. +type FinancialConnectionsAccountList struct { + APIResource + ListMeta + Data []*FinancialConnectionsAccount `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/financialconnections_account_service.go b/vendor/github.com/stripe/stripe-go/v82/financialconnections_account_service.go new file mode 100644 index 00000000..4fdbc9f5 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/financialconnections_account_service.go @@ -0,0 +1,117 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1FinancialConnectionsAccountService is used to invoke /v1/financial_connections/accounts APIs. +type v1FinancialConnectionsAccountService struct { + B Backend + Key string +} + +// Retrieves the details of an Financial Connections Account. +func (c v1FinancialConnectionsAccountService) GetByID(ctx context.Context, id string, params *FinancialConnectionsAccountRetrieveParams) (*FinancialConnectionsAccount, error) { + if params == nil { + params = &FinancialConnectionsAccountRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/financial_connections/accounts/%s", id) + account := &FinancialConnectionsAccount{} + err := c.B.Call(http.MethodGet, path, c.Key, params, account) + return account, err +} + +// Disables your access to a Financial Connections Account. You will no longer be able to access data associated with the account (e.g. balances, transactions). +func (c v1FinancialConnectionsAccountService) Disconnect(ctx context.Context, id string, params *FinancialConnectionsAccountDisconnectParams) (*FinancialConnectionsAccount, error) { + if params == nil { + params = &FinancialConnectionsAccountDisconnectParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/financial_connections/accounts/%s/disconnect", id) + account := &FinancialConnectionsAccount{} + err := c.B.Call(http.MethodPost, path, c.Key, params, account) + return account, err +} + +// Refreshes the data associated with a Financial Connections Account. +func (c v1FinancialConnectionsAccountService) Refresh(ctx context.Context, id string, params *FinancialConnectionsAccountRefreshParams) (*FinancialConnectionsAccount, error) { + if params == nil { + params = &FinancialConnectionsAccountRefreshParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/financial_connections/accounts/%s/refresh", id) + account := &FinancialConnectionsAccount{} + err := c.B.Call(http.MethodPost, path, c.Key, params, account) + return account, err +} + +// Subscribes to periodic refreshes of data associated with a Financial Connections Account. +func (c v1FinancialConnectionsAccountService) Subscribe(ctx context.Context, id string, params *FinancialConnectionsAccountSubscribeParams) (*FinancialConnectionsAccount, error) { + if params == nil { + params = &FinancialConnectionsAccountSubscribeParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/financial_connections/accounts/%s/subscribe", id) + account := &FinancialConnectionsAccount{} + err := c.B.Call(http.MethodPost, path, c.Key, params, account) + return account, err +} + +// Unsubscribes from periodic refreshes of data associated with a Financial Connections Account. +func (c v1FinancialConnectionsAccountService) Unsubscribe(ctx context.Context, id string, params *FinancialConnectionsAccountUnsubscribeParams) (*FinancialConnectionsAccount, error) { + if params == nil { + params = &FinancialConnectionsAccountUnsubscribeParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/financial_connections/accounts/%s/unsubscribe", id) + account := &FinancialConnectionsAccount{} + err := c.B.Call(http.MethodPost, path, c.Key, params, account) + return account, err +} + +// Returns a list of Financial Connections Account objects. +func (c v1FinancialConnectionsAccountService) List(ctx context.Context, listParams *FinancialConnectionsAccountListParams) Seq2[*FinancialConnectionsAccount, error] { + if listParams == nil { + listParams = &FinancialConnectionsAccountListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*FinancialConnectionsAccount, ListContainer, error) { + list := &FinancialConnectionsAccountList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/financial_connections/accounts", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// Lists all owners for a given Account +func (c v1FinancialConnectionsAccountService) ListOwners(ctx context.Context, listParams *FinancialConnectionsAccountListOwnersParams) Seq2[*FinancialConnectionsAccountOwner, error] { + if listParams == nil { + listParams = &FinancialConnectionsAccountListOwnersParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/financial_connections/accounts/%s/owners", StringValue( + listParams.Account)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*FinancialConnectionsAccountOwner, ListContainer, error) { + list := &FinancialConnectionsAccountOwnerList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/financialconnections_accountowner.go b/vendor/github.com/stripe/stripe-go/v82/financialconnections_accountowner.go new file mode 100644 index 00000000..49fca19a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/financialconnections_accountowner.go @@ -0,0 +1,34 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Describes an owner of an account. +type FinancialConnectionsAccountOwner struct { + // The email address of the owner. + Email string `json:"email"` + // Unique identifier for the object. + ID string `json:"id"` + // The full name of the owner. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The ownership object that this owner belongs to. + Ownership string `json:"ownership"` + // The raw phone number of the owner. + Phone string `json:"phone"` + // The raw physical address of the owner. + RawAddress string `json:"raw_address"` + // The timestamp of the refresh that updated this owner. + RefreshedAt int64 `json:"refreshed_at"` +} + +// FinancialConnectionsAccountOwnerList is a list of AccountOwners as retrieved from a list endpoint. +type FinancialConnectionsAccountOwnerList struct { + APIResource + ListMeta + Data []*FinancialConnectionsAccountOwner `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/financialconnections_accountownership.go b/vendor/github.com/stripe/stripe-go/v82/financialconnections_accountownership.go new file mode 100644 index 00000000..1b642879 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/financialconnections_accountownership.go @@ -0,0 +1,40 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Describes a snapshot of the owners of an account at a particular point in time. +type FinancialConnectionsAccountOwnership struct { + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Unique identifier for the object. + ID string `json:"id"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // A paginated list of owners for this account. + Owners *FinancialConnectionsAccountOwnerList `json:"owners"` +} + +// UnmarshalJSON handles deserialization of a FinancialConnectionsAccountOwnership. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (f *FinancialConnectionsAccountOwnership) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + f.ID = id + return nil + } + + type financialConnectionsAccountOwnership FinancialConnectionsAccountOwnership + var v financialConnectionsAccountOwnership + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *f = FinancialConnectionsAccountOwnership(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/financialconnections_session.go b/vendor/github.com/stripe/stripe-go/v82/financialconnections_session.go new file mode 100644 index 00000000..22c45823 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/financialconnections_session.go @@ -0,0 +1,185 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Type of account holder that this account belongs to. +type FinancialConnectionsSessionAccountHolderType string + +// List of values that FinancialConnectionsSessionAccountHolderType can take +const ( + FinancialConnectionsSessionAccountHolderTypeAccount FinancialConnectionsSessionAccountHolderType = "account" + FinancialConnectionsSessionAccountHolderTypeCustomer FinancialConnectionsSessionAccountHolderType = "customer" +) + +// Restricts the Session to subcategories of accounts that can be linked. Valid subcategories are: `checking`, `savings`, `mortgage`, `line_of_credit`, `credit_card`. +type FinancialConnectionsSessionFiltersAccountSubcategory string + +// List of values that FinancialConnectionsSessionFiltersAccountSubcategory can take +const ( + FinancialConnectionsSessionFiltersAccountSubcategoryChecking FinancialConnectionsSessionFiltersAccountSubcategory = "checking" + FinancialConnectionsSessionFiltersAccountSubcategoryCreditCard FinancialConnectionsSessionFiltersAccountSubcategory = "credit_card" + FinancialConnectionsSessionFiltersAccountSubcategoryLineOfCredit FinancialConnectionsSessionFiltersAccountSubcategory = "line_of_credit" + FinancialConnectionsSessionFiltersAccountSubcategoryMortgage FinancialConnectionsSessionFiltersAccountSubcategory = "mortgage" + FinancialConnectionsSessionFiltersAccountSubcategorySavings FinancialConnectionsSessionFiltersAccountSubcategory = "savings" +) + +// Permissions requested for accounts collected during this session. +type FinancialConnectionsSessionPermission string + +// List of values that FinancialConnectionsSessionPermission can take +const ( + FinancialConnectionsSessionPermissionBalances FinancialConnectionsSessionPermission = "balances" + FinancialConnectionsSessionPermissionOwnership FinancialConnectionsSessionPermission = "ownership" + FinancialConnectionsSessionPermissionPaymentMethod FinancialConnectionsSessionPermission = "payment_method" + FinancialConnectionsSessionPermissionTransactions FinancialConnectionsSessionPermission = "transactions" +) + +// Data features requested to be retrieved upon account creation. +type FinancialConnectionsSessionPrefetch string + +// List of values that FinancialConnectionsSessionPrefetch can take +const ( + FinancialConnectionsSessionPrefetchBalances FinancialConnectionsSessionPrefetch = "balances" + FinancialConnectionsSessionPrefetchOwnership FinancialConnectionsSessionPrefetch = "ownership" + FinancialConnectionsSessionPrefetchTransactions FinancialConnectionsSessionPrefetch = "transactions" +) + +// Retrieves the details of a Financial Connections Session +type FinancialConnectionsSessionParams struct { + Params `form:"*"` + // The account holder to link accounts for. + AccountHolder *FinancialConnectionsSessionAccountHolderParams `form:"account_holder"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Filters to restrict the kinds of accounts to collect. + Filters *FinancialConnectionsSessionFiltersParams `form:"filters"` + // List of data features that you would like to request access to. + // + // Possible values are `balances`, `transactions`, `ownership`, and `payment_method`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` + // For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + ReturnURL *string `form:"return_url"` +} + +// AddExpand appends a new field to expand. +func (p *FinancialConnectionsSessionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The account holder to link accounts for. +type FinancialConnectionsSessionAccountHolderParams struct { + // The ID of the Stripe account whose accounts will be retrieved. Should only be present if `type` is `account`. + Account *string `form:"account"` + // The ID of the Stripe customer whose accounts will be retrieved. Should only be present if `type` is `customer`. + Customer *string `form:"customer"` + // Type of account holder to collect accounts for. + Type *string `form:"type"` +} + +// Filters to restrict the kinds of accounts to collect. +type FinancialConnectionsSessionFiltersParams struct { + // Restricts the Session to subcategories of accounts that can be linked. Valid subcategories are: `checking`, `savings`, `mortgage`, `line_of_credit`, `credit_card`. + AccountSubcategories []*string `form:"account_subcategories"` + // List of countries from which to collect accounts. + Countries []*string `form:"countries"` +} + +// Retrieves the details of a Financial Connections Session +type FinancialConnectionsSessionRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *FinancialConnectionsSessionRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The account holder to link accounts for. +type FinancialConnectionsSessionCreateAccountHolderParams struct { + // The ID of the Stripe account whose accounts will be retrieved. Should only be present if `type` is `account`. + Account *string `form:"account"` + // The ID of the Stripe customer whose accounts will be retrieved. Should only be present if `type` is `customer`. + Customer *string `form:"customer"` + // Type of account holder to collect accounts for. + Type *string `form:"type"` +} + +// Filters to restrict the kinds of accounts to collect. +type FinancialConnectionsSessionCreateFiltersParams struct { + // Restricts the Session to subcategories of accounts that can be linked. Valid subcategories are: `checking`, `savings`, `mortgage`, `line_of_credit`, `credit_card`. + AccountSubcategories []*string `form:"account_subcategories"` + // List of countries from which to collect accounts. + Countries []*string `form:"countries"` +} + +// To launch the Financial Connections authorization flow, create a Session. The session's client_secret can be used to launch the flow using Stripe.js. +type FinancialConnectionsSessionCreateParams struct { + Params `form:"*"` + // The account holder to link accounts for. + AccountHolder *FinancialConnectionsSessionCreateAccountHolderParams `form:"account_holder"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Filters to restrict the kinds of accounts to collect. + Filters *FinancialConnectionsSessionCreateFiltersParams `form:"filters"` + // List of data features that you would like to request access to. + // + // Possible values are `balances`, `transactions`, `ownership`, and `payment_method`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` + // For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + ReturnURL *string `form:"return_url"` +} + +// AddExpand appends a new field to expand. +func (p *FinancialConnectionsSessionCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The account holder for whom accounts are collected in this session. +type FinancialConnectionsSessionAccountHolder struct { + // The ID of the Stripe account this account belongs to. Should only be present if `account_holder.type` is `account`. + Account *Account `json:"account"` + // ID of the Stripe customer this account belongs to. Present if and only if `account_holder.type` is `customer`. + Customer *Customer `json:"customer"` + // Type of account holder that this account belongs to. + Type FinancialConnectionsSessionAccountHolderType `json:"type"` +} +type FinancialConnectionsSessionFilters struct { + // Restricts the Session to subcategories of accounts that can be linked. Valid subcategories are: `checking`, `savings`, `mortgage`, `line_of_credit`, `credit_card`. + AccountSubcategories []FinancialConnectionsSessionFiltersAccountSubcategory `json:"account_subcategories"` + // List of countries from which to filter accounts. + Countries []string `json:"countries"` +} + +// A Financial Connections Session is the secure way to programmatically launch the client-side Stripe.js modal that lets your users link their accounts. +type FinancialConnectionsSession struct { + APIResource + // The account holder for whom accounts are collected in this session. + AccountHolder *FinancialConnectionsSessionAccountHolder `json:"account_holder"` + // The accounts that were collected as part of this Session. + Accounts *FinancialConnectionsAccountList `json:"accounts"` + // A value that will be passed to the client to launch the authentication flow. + ClientSecret string `json:"client_secret"` + Filters *FinancialConnectionsSessionFilters `json:"filters"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Permissions requested for accounts collected during this session. + Permissions []FinancialConnectionsSessionPermission `json:"permissions"` + // Data features requested to be retrieved upon account creation. + Prefetch []FinancialConnectionsSessionPrefetch `json:"prefetch"` + // For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + ReturnURL string `json:"return_url"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/financialconnections_session_service.go b/vendor/github.com/stripe/stripe-go/v82/financialconnections_session_service.go new file mode 100644 index 00000000..99d56651 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/financialconnections_session_service.go @@ -0,0 +1,42 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1FinancialConnectionsSessionService is used to invoke /v1/financial_connections/sessions APIs. +type v1FinancialConnectionsSessionService struct { + B Backend + Key string +} + +// To launch the Financial Connections authorization flow, create a Session. The session's client_secret can be used to launch the flow using Stripe.js. +func (c v1FinancialConnectionsSessionService) Create(ctx context.Context, params *FinancialConnectionsSessionCreateParams) (*FinancialConnectionsSession, error) { + if params == nil { + params = &FinancialConnectionsSessionCreateParams{} + } + params.Context = ctx + session := &FinancialConnectionsSession{} + err := c.B.Call( + http.MethodPost, "/v1/financial_connections/sessions", c.Key, params, session) + return session, err +} + +// Retrieves the details of a Financial Connections Session +func (c v1FinancialConnectionsSessionService) Retrieve(ctx context.Context, id string, params *FinancialConnectionsSessionRetrieveParams) (*FinancialConnectionsSession, error) { + if params == nil { + params = &FinancialConnectionsSessionRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/financial_connections/sessions/%s", id) + session := &FinancialConnectionsSession{} + err := c.B.Call(http.MethodGet, path, c.Key, params, session) + return session, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/financialconnections_transaction.go b/vendor/github.com/stripe/stripe-go/v82/financialconnections_transaction.go new file mode 100644 index 00000000..84a08c07 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/financialconnections_transaction.go @@ -0,0 +1,109 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The status of the transaction. +type FinancialConnectionsTransactionStatus string + +// List of values that FinancialConnectionsTransactionStatus can take +const ( + FinancialConnectionsTransactionStatusPending FinancialConnectionsTransactionStatus = "pending" + FinancialConnectionsTransactionStatusPosted FinancialConnectionsTransactionStatus = "posted" + FinancialConnectionsTransactionStatusVoid FinancialConnectionsTransactionStatus = "void" +) + +// A filter on the list based on the object `transaction_refresh` field. The value can be a dictionary with the following options: +type FinancialConnectionsTransactionListTransactionRefreshParams struct { + // Return results where the transactions were created or updated by a refresh that took place after this refresh (non-inclusive). + After *string `form:"after"` +} + +// Returns a list of Financial Connections Transaction objects. +type FinancialConnectionsTransactionListParams struct { + ListParams `form:"*"` + // The ID of the Financial Connections Account whose transactions will be retrieved. + Account *string `form:"account"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A filter on the list based on the object `transacted_at` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with the following options: + TransactedAt *int64 `form:"transacted_at"` + // A filter on the list based on the object `transacted_at` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with the following options: + TransactedAtRange *RangeQueryParams `form:"transacted_at"` + // A filter on the list based on the object `transaction_refresh` field. The value can be a dictionary with the following options: + TransactionRefresh *FinancialConnectionsTransactionListTransactionRefreshParams `form:"transaction_refresh"` +} + +// AddExpand appends a new field to expand. +func (p *FinancialConnectionsTransactionListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of a Financial Connections Transaction +type FinancialConnectionsTransactionParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *FinancialConnectionsTransactionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of a Financial Connections Transaction +type FinancialConnectionsTransactionRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *FinancialConnectionsTransactionRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type FinancialConnectionsTransactionStatusTransitions struct { + // Time at which this transaction posted. Measured in seconds since the Unix epoch. + PostedAt int64 `json:"posted_at"` + // Time at which this transaction was voided. Measured in seconds since the Unix epoch. + VoidAt int64 `json:"void_at"` +} + +// A Transaction represents a real transaction that affects a Financial Connections Account balance. +type FinancialConnectionsTransaction struct { + APIResource + // The ID of the Financial Connections Account this transaction belongs to. + Account string `json:"account"` + // The amount of this transaction, in cents (or local equivalent). + Amount int64 `json:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // The description of this transaction. + Description string `json:"description"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The status of the transaction. + Status FinancialConnectionsTransactionStatus `json:"status"` + StatusTransitions *FinancialConnectionsTransactionStatusTransitions `json:"status_transitions"` + // Time at which the transaction was transacted. Measured in seconds since the Unix epoch. + TransactedAt int64 `json:"transacted_at"` + // The token of the transaction refresh that last updated or created this transaction. + TransactionRefresh string `json:"transaction_refresh"` + // Time at which the object was last updated. Measured in seconds since the Unix epoch. + Updated int64 `json:"updated"` +} + +// FinancialConnectionsTransactionList is a list of Transactions as retrieved from a list endpoint. +type FinancialConnectionsTransactionList struct { + APIResource + ListMeta + Data []*FinancialConnectionsTransaction `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/financialconnections_transaction_service.go b/vendor/github.com/stripe/stripe-go/v82/financialconnections_transaction_service.go new file mode 100644 index 00000000..3fd479ff --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/financialconnections_transaction_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1FinancialConnectionsTransactionService is used to invoke /v1/financial_connections/transactions APIs. +type v1FinancialConnectionsTransactionService struct { + B Backend + Key string +} + +// Retrieves the details of a Financial Connections Transaction +func (c v1FinancialConnectionsTransactionService) Retrieve(ctx context.Context, id string, params *FinancialConnectionsTransactionRetrieveParams) (*FinancialConnectionsTransaction, error) { + if params == nil { + params = &FinancialConnectionsTransactionRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/financial_connections/transactions/%s", id) + transaction := &FinancialConnectionsTransaction{} + err := c.B.Call(http.MethodGet, path, c.Key, params, transaction) + return transaction, err +} + +// Returns a list of Financial Connections Transaction objects. +func (c v1FinancialConnectionsTransactionService) List(ctx context.Context, listParams *FinancialConnectionsTransactionListParams) Seq2[*FinancialConnectionsTransaction, error] { + if listParams == nil { + listParams = &FinancialConnectionsTransactionListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*FinancialConnectionsTransaction, ListContainer, error) { + list := &FinancialConnectionsTransactionList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/financial_connections/transactions", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/form/form.go b/vendor/github.com/stripe/stripe-go/v82/form/form.go new file mode 100644 index 00000000..a5ed4031 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/form/form.go @@ -0,0 +1,650 @@ +package form + +import ( + "bytes" + "fmt" + "net/url" + "reflect" + "sort" + "strconv" + "strings" + "sync" + "time" +) + +const tagName = "form" + +// Appender is the interface implemented by types that can append themselves to +// a collection of form values. +// +// This is usually something that shouldn't be used, but is needed in a few +// places where authors deviated from norms while implementing various +// parameters. +type Appender interface { + // AppendTo is invoked by the form package on any types found to implement + // Appender so that they have a chance to encode themselves. Note that + // AppendTo is called in addition to normal encoding, so other form tags on + // the struct are still fair game. + AppendTo(values *Values, keyParts []string) +} + +// encoderFunc is used to encode any type from a request. +// +// A note about encodeZero: Since some types in the Stripe API are defaulted to +// non-zero values, and Go defaults types to their zero values, any type that +// has a Stripe API default of a non-zero value is defined as a Go pointer, +// meaning nil defaults to the Stripe API non-zero value. To override this, a +// check is made to see if the value is the zero-value for that type. If it is +// and encodeZero is true, it's encoded. This is ignored as a parameter when +// dealing with types like structs, where the decision cannot be made +// preemptively. +type encoderFunc func(values *Values, v reflect.Value, keyParts []string, encodeZero bool, options *formOptions) + +// field represents a single field found in a struct. It caches information +// about that field so that we can make encoding faster. +type field struct { + formName string + index int + isAppender bool + isPtr bool + options *formOptions +} + +type formOptions struct { + // Empty indicates that a field's value should be emptied in that its value + // should be an empty string. It's used to workaround the fact that an + // empty string is a string's zero value and wouldn't normally be encoded. + Empty bool + + // HighPrecision indicates that this field should be treated as a high + // precision decimal, a decimal whose precision is important to the API and + // which we want to encode as accurately as possible. + // + // All parameters are encoded using form encoding, so this of course + // encodes a value to a string, but notably, these high precision fields + // are sent back as strings in JSON, even though they might be surfaced as + // floats in this library. + // + // This isn't a perfect abstraction because floats are not precise in + // nature, and we might be better-advised to use a real high-precision data + // type like `big.Float`. That said, we suspect that this will be an + // adequate solution in the vast majority of cases and has a usability + // benefit, so we've gone this route. + HighPrecision bool +} + +type structEncoder struct { + fields []*field + fieldEncs []encoderFunc +} + +func (se *structEncoder) encode(values *Values, v reflect.Value, keyParts []string, _ bool, _ *formOptions) { + for i, f := range se.fields { + var fieldKeyParts []string + fieldV := v.Field(f.index) + + // The wildcard on a form tag is a "special" value: it indicates a + // struct field that we should recurse into, but for which no part + // should be added to the key parts, meaning that its own subfields + // will be named at the same level as with the fields of the + // current structure. + if f.formName == "*" { + fieldKeyParts = keyParts + } else { + fieldKeyParts = append(keyParts, f.formName) + } + + se.fieldEncs[i](values, fieldV, fieldKeyParts, f.isPtr, f.options) + if f.isAppender && (!f.isPtr || !fieldV.IsNil()) { + fieldV.Interface().(Appender).AppendTo(values, fieldKeyParts) + } + } +} + +// --- + +// Strict enables strict mode wherein the package will panic on an AppendTo +// function if it finds that a tag string was malformed. +var Strict = false + +var encoderCache struct { + m map[reflect.Type]encoderFunc + mu sync.RWMutex // for coordinating concurrent operations on m +} + +var structCache struct { + m map[reflect.Type]*structEncoder + mu sync.RWMutex // for coordinating concurrent operations on m +} + +// AppendTo uses reflection to form encode into the given values collection +// based off the form tags that it defines. +func AppendTo(values *Values, i interface{}) { + reflectValue(values, reflect.ValueOf(i), false, nil) +} + +// AppendToPrefixed is the same as AppendTo, but it allows a slice of key parts +// to be specified to prefix the form values. +// +// I was hoping not to have to expose this function, but I ended up needing it +// for recipients. Recipients is going away, and when it does, we can probably +// remove it again. +func AppendToPrefixed(values *Values, i interface{}, keyParts []string) { + reflectValue(values, reflect.ValueOf(i), false, keyParts) +} + +// FormatKey takes a series of key parts that may be parameter keyParts, map keys, +// or array indices and unifies them into a single key suitable for Stripe's +// style of form encoding. +func FormatKey(parts []string) string { + if len(parts) < 1 { + panic("Not allowed 0-length parts slice") + } + + key := parts[0] + for i := 1; i < len(parts); i++ { + key += "[" + parts[i] + "]" + } + return key +} + +// --- + +func boolEncoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, options *formOptions) { + val := v.Bool() + if !val && !encodeZero { + return + } + + if options != nil { + switch { + case options.Empty: + values.Add(FormatKey(keyParts), "") + } + } else { + values.Add(FormatKey(keyParts), strconv.FormatBool(val)) + } +} + +func buildArrayOrSliceEncoder(t reflect.Type) encoderFunc { + // Gets an encoder for the type that the array or slice will hold + elemF := getCachedOrBuildTypeEncoder(t.Elem()) + + return func(values *Values, v reflect.Value, keyParts []string, _ bool, options *formOptions) { + // When encountering a slice that's been explicitly set (i.e. non-nil) + // and which is of 0 length, we take this as an indication that the + // user is trying to zero the API array. See the `additional_owners` + // property under `legal_entity` on account for an example of somewhere + // that this is useful. + // + // This only works for a slice (and not an array) because even a zeroed + // array always has a fixed length. + if t.Kind() == reflect.Slice && !v.IsNil() && v.Len() == 0 { + values.Add(FormatKey(keyParts), "") + return + } + + var arrNames []string + + for i := 0; i < v.Len(); i++ { + arrNames = append(keyParts, strconv.Itoa(i)) + + indexV := v.Index(i) + elemF(values, indexV, arrNames, indexV.Kind() == reflect.Ptr, nil) + + if isAppender(indexV.Type()) && !indexV.IsNil() { + indexV.Interface().(Appender).AppendTo(values, arrNames) + } + } + } +} + +func buildPtrEncoder(t reflect.Type) encoderFunc { + // Gets an encoder for the type that the pointer wraps + elemF := getCachedOrBuildTypeEncoder(t.Elem()) + + return func(values *Values, v reflect.Value, keyParts []string, _ bool, options *formOptions) { + // We take a nil to mean that the property wasn't set, so ignore it in + // the final encoding. + if v.IsNil() { + return + } + + // Handle "zeroing" an array stored as a pointer to a slice. See + // comment in `buildArrayOrSliceEncoder` above. + if t.Elem().Kind() == reflect.Slice && v.Elem().Len() == 0 { + values.Add(FormatKey(keyParts), "") + return + } + + // Otherwise, call into the appropriate encoder for the pointer's type. + elemF(values, v.Elem(), keyParts, true, options) + } +} + +func buildStructEncoder(t reflect.Type) encoderFunc { + se := getCachedOrBuildStructEncoder(t) + return se.encode +} + +func float32Encoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, options *formOptions) { + val := v.Float() + if val == 0.0 && !encodeZero { + return + } + prec := 4 + if options != nil && options.HighPrecision { + // Special value that tells Go to format the float in as few required + // digits as necessary for it to be successfully parsable from a string + // back to the same original number. + prec = -1 + } + values.Add(FormatKey(keyParts), strconv.FormatFloat(val, 'f', prec, 32)) +} + +func float64Encoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, options *formOptions) { + val := v.Float() + if val == 0.0 && !encodeZero { + return + } + prec := 4 + if options != nil && options.HighPrecision { + // Special value that tells Go to format the float in as few required + // digits as necessary for it to be successfully parsable from a string + // back to the same original number. + prec = -1 + } + values.Add(FormatKey(keyParts), strconv.FormatFloat(val, 'f', prec, 64)) +} + +func getCachedOrBuildStructEncoder(t reflect.Type) *structEncoder { + // Just acquire a read lock when extracting a value (note that in Go, a map + // cannot be read while it's also being written). + structCache.mu.RLock() + f := structCache.m[t] + structCache.mu.RUnlock() + + if f != nil { + return f + } + + // We do the work to get the encoder without holding a lock. This could + // result in duplicate work, but it will help us avoid a deadlock. Encoders + // may be built and stored recursively in the cases of something like an + // array or slice, so we need to make sure that this function is properly + // re-entrant. + f = makeStructEncoder(t) + + structCache.mu.Lock() + defer structCache.mu.Unlock() + + if structCache.m == nil { + structCache.m = make(map[reflect.Type]*structEncoder) + } + structCache.m[t] = f + + return f +} + +// getCachedOrBuildTypeEncoder tries to get an encoderFunc for the type from +// the cache, and falls back to building one if there wasn't a cached one +// available. If an encoder is built, it's stored back to the cache. +func getCachedOrBuildTypeEncoder(t reflect.Type) encoderFunc { + // Just acquire a read lock when extracting a value (note that in Go, a map + // cannot be read while it's also being written). + encoderCache.mu.RLock() + f := encoderCache.m[t] + encoderCache.mu.RUnlock() + + if f != nil { + return f + } + + // We do the work to get the encoder without holding a lock. This could + // result in duplicate work, but it will help us avoid a deadlock. Encoders + // may be built and stored recursively in the cases of something like an + // array or slice, so we need to make sure that this function is properly + // re-entrant. + f = makeTypeEncoder(t) + + encoderCache.mu.Lock() + defer encoderCache.mu.Unlock() + + if encoderCache.m == nil { + encoderCache.m = make(map[reflect.Type]encoderFunc) + } + encoderCache.m[t] = f + + return f +} + +func intEncoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, options *formOptions) { + val := v.Int() + if val == 0 && !encodeZero { + return + } + values.Add(FormatKey(keyParts), strconv.FormatInt(val, 10)) +} + +func timeEncoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, _ *formOptions) { + val := v.Interface().(time.Time) + if val.IsZero() && !encodeZero { + return + } + values.Add(FormatKey(keyParts), val.String()) +} + +func interfaceEncoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, _ *formOptions) { + // interfaceEncoder never encodes a `nil`, but it will pass through an + // `encodeZero` value into its chained encoder + if v.IsNil() { + return + } + reflectValue(values, v.Elem(), encodeZero, keyParts) +} + +func isAppender(t reflect.Type) bool { + return t.Implements(reflect.TypeOf((*Appender)(nil)).Elem()) +} + +func mapEncoder(values *Values, v reflect.Value, keyParts []string, _ bool, _ *formOptions) { + keys := make([]string, 0, v.Len()) + for _, keyVal := range v.MapKeys() { + if keyVal.Kind() != reflect.String { + if Strict { + panic("Don't support serializing maps with non-string keys") + } + // otherwise keyVal.String() will panic later + continue + } + keys = append(keys, keyVal.String()) + } + sort.Strings(keys) + for _, key := range keys { + // Unlike a property on a struct which will contain a zero value even + // if never set, any value found in a map has been explicitly set, so + // we always make an effort to encode them, even if a zero value + // (that's why we pass through `true` here). + reflectValue(values, v.MapIndex(reflect.ValueOf(key)), true, append(keyParts, key)) + } +} + +func stringEncoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, options *formOptions) { + val := v.String() + if val == "" && !encodeZero { + return + } + values.Add(FormatKey(keyParts), val) +} + +func uintEncoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, options *formOptions) { + val := v.Uint() + if val == 0 && !encodeZero { + return + } + values.Add(FormatKey(keyParts), strconv.FormatUint(val, 10)) +} + +// reflectValue is roughly the shared entry point of any AppendTo functions. +// It's also called recursively in cases where a precise type isn't yet known +// and its encoding needs to be deferred down the chain; for example, when +// encoding interface{} or the values in an array or map containing +// interface{}. +func reflectValue(values *Values, v reflect.Value, encodeZero bool, keyParts []string) { + t := v.Type() + + f := getCachedOrBuildTypeEncoder(t) + if f != nil { + f(values, v, keyParts, encodeZero || v.Kind() == reflect.Ptr, nil) + } + + if isAppender(t) { + v.Interface().(Appender).AppendTo(values, keyParts) + } +} + +func makeStructEncoder(t reflect.Type) *structEncoder { + // Don't specify capacity because we don't know how many fields are tagged with + // `form` + se := &structEncoder{} + + for i := 0; i < t.NumField(); i++ { + reflectField := t.Field(i) + tag := reflectField.Tag.Get(tagName) + if Strict && tag == "" { + panic(fmt.Sprintf( + "All fields in structs to be form-encoded must have `form` tag; on: %s/%s "+ + "(hint: use an explicit `form:\"-\"` if the field should not be encoded", + t.Name(), reflectField.Name, + )) + } + + formName, options := parseTag(tag) + + // Like with encoding/json, a hyphen is an explicit way of saying + // that this field should not be encoded + if formName == "-" { + continue + } + + fldTyp := reflectField.Type + fldKind := fldTyp.Kind() + + if Strict && options != nil { + if options.Empty && fldKind != reflect.Bool { + panic(fmt.Sprintf( + "Cannot specify `empty` for non-boolean field; on: %s/%s", + t.Name(), reflectField.Name, + )) + } + + var k reflect.Kind + if fldKind == reflect.Ptr { + k = fldTyp.Elem().Kind() + } else { + k = fldKind + } + + fldIsFloat := k == reflect.Float32 || k == reflect.Float64 + + if options.HighPrecision && !fldIsFloat { + panic(fmt.Sprintf( + "Cannot specify `high_precision` for non-float field; on: %s/%s (%s)", + t.Name(), reflectField.Name, fldTyp, + )) + } + } + + se.fields = append(se.fields, &field{ + formName: formName, + index: i, + isAppender: isAppender(fldTyp), + isPtr: fldKind == reflect.Ptr, + options: options, + }) + se.fieldEncs = append(se.fieldEncs, + getCachedOrBuildTypeEncoder(fldTyp)) + } + + return se +} + +func makeTypeEncoder(t reflect.Type) encoderFunc { + // For time.Time, we want to encode imediately it as a Unix timestamp, + // and don't want to inspect into it and encode it as a struct. + if t == reflect.TypeOf(time.Time{}) { + return timeEncoder + } + + switch t.Kind() { + case reflect.Array, reflect.Slice: + return buildArrayOrSliceEncoder(t) + + case reflect.Bool: + return boolEncoder + + case reflect.Float32: + return float32Encoder + + case reflect.Float64: + return float64Encoder + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return intEncoder + + case reflect.Interface: + return interfaceEncoder + + case reflect.Map: + return mapEncoder + + case reflect.Ptr: + return buildPtrEncoder(t) + + case reflect.String: + return stringEncoder + + case reflect.Struct: + return buildStructEncoder(t) + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return uintEncoder + } + + return nil +} + +func parseTag(tag string) (string, *formOptions) { + var options *formOptions + parts := strings.Split(tag, ",") + name := parts[0] + + for i := 1; i < len(parts); i++ { + switch parts[i] { + case "empty": + if options == nil { + options = &formOptions{} + } + options.Empty = true + + case "high_precision": + if options == nil { + options = &formOptions{} + } + options.HighPrecision = true + + default: + if Strict { + part := parts[i] + if part == "" { + part = "(empty)" + } + panic(fmt.Sprintf("Don't know how to handle form tag part: %s (tag: %s)", + part, tag)) + } + } + } + + return name, options +} + +// --- + +// Values is a collection of values that can be submitted along with a +// request that specifically allows for duplicate keys and encodes its entries +// in the same order that they were added. +type Values struct { + values []formValue +} + +// Add adds a key/value tuple to the form. +func (f *Values) Add(key, val string) { + f.values = append(f.values, formValue{key, val}) +} + +// Encode encodes the keys and values into “URL encoded” form +// ("bar=baz&foo=quux"). +func (f *Values) Encode() string { + if f == nil { + return "" + } + var buf bytes.Buffer + for _, v := range f.values { + if buf.Len() > 0 { + buf.WriteByte('&') + } + key := url.QueryEscape(v.Key) + key = strings.Replace(key, "%5B", "[", -1) + key = strings.Replace(key, "%5D", "]", -1) + buf.WriteString(key) + buf.WriteString("=") + buf.WriteString(url.QueryEscape(v.Value)) + } + return buf.String() +} + +// Empty returns true if no parameters have been set. +func (f *Values) Empty() bool { + return len(f.values) == 0 +} + +// Set sets the first instance of a parameter for the given key to the given +// value. If no parameters exist with the key, a new one is added. +// +// Note that Set is O(n) and may be quite slow for a very large parameter list. +func (f *Values) Set(key, val string) { + for i, v := range f.values { + if v.Key == key { + f.values[i].Value = val + return + } + } + + f.Add(key, val) +} + +// Get retrieves the list of values for the given key. If no values exist +// for the key, nil will be returned. +// +// Note that Get is O(n) and may be quite slow for a very large parameter list. +func (f *Values) Get(key string) []string { + var results []string + for i, v := range f.values { + if v.Key == key { + results = append(results, f.values[i].Value) + } + } + return results +} + +// ToValues converts an instance of Values into an instance of +// url.Values. This can be useful in cases where it's useful to make an +// unordered comparison of two sets of request values. +// +// Note that url.Values is incapable of representing certain Rack form types in +// a cohesive way. For example, an array of maps in Rack is encoded with a +// string like: +// +// arr[][foo]=foo0&arr[][bar]=bar0&arr[][foo]=foo1&arr[][bar]=bar1 +// +// Because url.Values is a map, values will be handled in a way that's grouped +// by their key instead of in the order they were added. Therefore the above +// may by encoded to something like (maps are unordered so the actual result is +// somewhat non-deterministic): +// +// arr[][foo]=foo0&arr[][foo]=foo1&arr[][bar]=bar0&arr[][bar]=bar1 +// +// And thus result in an incorrect request to Stripe. +func (f *Values) ToValues() url.Values { + values := url.Values{} + for _, v := range f.values { + values.Add(v.Key, v.Value) + } + return values +} + +// A key/value tuple for use in the Values type. +type formValue struct { + Key string + Value string +} diff --git a/vendor/github.com/stripe/stripe-go/v82/forwarding_request.go b/vendor/github.com/stripe/stripe-go/v82/forwarding_request.go new file mode 100644 index 00000000..e5952aa5 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/forwarding_request.go @@ -0,0 +1,240 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The field kinds to be replaced in the forwarded request. +type ForwardingRequestReplacement string + +// List of values that ForwardingRequestReplacement can take +const ( + ForwardingRequestReplacementCardCVC ForwardingRequestReplacement = "card_cvc" + ForwardingRequestReplacementCardExpiry ForwardingRequestReplacement = "card_expiry" + ForwardingRequestReplacementCardNumber ForwardingRequestReplacement = "card_number" + ForwardingRequestReplacementCardholderName ForwardingRequestReplacement = "cardholder_name" + ForwardingRequestReplacementRequestSignature ForwardingRequestReplacement = "request_signature" +) + +// The HTTP method used to call the destination endpoint. +type ForwardingRequestRequestDetailsHTTPMethod string + +// List of values that ForwardingRequestRequestDetailsHTTPMethod can take +const ( + ForwardingRequestRequestDetailsHTTPMethodPOST ForwardingRequestRequestDetailsHTTPMethod = "POST" +) + +// Lists all ForwardingRequest objects. +type ForwardingRequestListParams struct { + ListParams `form:"*"` + // Similar to other List endpoints, filters results based on created timestamp. You can pass gt, gte, lt, and lte timestamp values. + Created *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ForwardingRequestListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The headers to include in the forwarded request. Can be omitted if no additional headers (excluding Stripe-generated ones such as the Content-Type header) should be included. +type ForwardingRequestRequestHeaderParams struct { + // The header name. + Name *string `form:"name"` + // The header value. + Value *string `form:"value"` +} + +// The request body and headers to be sent to the destination endpoint. +type ForwardingRequestRequestParams struct { + // The body payload to send to the destination endpoint. + Body *string `form:"body"` + // The headers to include in the forwarded request. Can be omitted if no additional headers (excluding Stripe-generated ones such as the Content-Type header) should be included. + Headers []*ForwardingRequestRequestHeaderParams `form:"headers"` +} + +// Creates a ForwardingRequest object. +type ForwardingRequestParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The PaymentMethod to insert into the forwarded request. Forwarding previously consumed PaymentMethods is allowed. + PaymentMethod *string `form:"payment_method"` + // The field kinds to be replaced in the forwarded request. + Replacements []*string `form:"replacements"` + // The request body and headers to be sent to the destination endpoint. + Request *ForwardingRequestRequestParams `form:"request"` + // The destination URL for the forwarded request. Must be supported by the config. + URL *string `form:"url"` +} + +// AddExpand appends a new field to expand. +func (p *ForwardingRequestParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ForwardingRequestParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The headers to include in the forwarded request. Can be omitted if no additional headers (excluding Stripe-generated ones such as the Content-Type header) should be included. +type ForwardingRequestCreateRequestHeaderParams struct { + // The header name. + Name *string `form:"name"` + // The header value. + Value *string `form:"value"` +} + +// The request body and headers to be sent to the destination endpoint. +type ForwardingRequestCreateRequestParams struct { + // The body payload to send to the destination endpoint. + Body *string `form:"body"` + // The headers to include in the forwarded request. Can be omitted if no additional headers (excluding Stripe-generated ones such as the Content-Type header) should be included. + Headers []*ForwardingRequestCreateRequestHeaderParams `form:"headers"` +} + +// Creates a ForwardingRequest object. +type ForwardingRequestCreateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The PaymentMethod to insert into the forwarded request. Forwarding previously consumed PaymentMethods is allowed. + PaymentMethod *string `form:"payment_method"` + // The field kinds to be replaced in the forwarded request. + Replacements []*string `form:"replacements"` + // The request body and headers to be sent to the destination endpoint. + Request *ForwardingRequestCreateRequestParams `form:"request"` + // The destination URL for the forwarded request. Must be supported by the config. + URL *string `form:"url"` +} + +// AddExpand appends a new field to expand. +func (p *ForwardingRequestCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ForwardingRequestCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves a ForwardingRequest object. +type ForwardingRequestRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ForwardingRequestRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Context about the request from Stripe's servers to the destination endpoint. +type ForwardingRequestRequestContext struct { + // The time it took in milliseconds for the destination endpoint to respond. + DestinationDuration int64 `json:"destination_duration"` + // The IP address of the destination. + DestinationIPAddress string `json:"destination_ip_address"` +} + +// The headers to include in the forwarded request. Can be omitted if no additional headers (excluding Stripe-generated ones such as the Content-Type header) should be included. +type ForwardingRequestRequestDetailsHeader struct { + // The header name. + Name string `json:"name"` + // The header value. + Value string `json:"value"` +} + +// The request that was sent to the destination endpoint. We redact any sensitive fields. +type ForwardingRequestRequestDetails struct { + // The body payload to send to the destination endpoint. + Body string `json:"body"` + // The headers to include in the forwarded request. Can be omitted if no additional headers (excluding Stripe-generated ones such as the Content-Type header) should be included. + Headers []*ForwardingRequestRequestDetailsHeader `json:"headers"` + // The HTTP method used to call the destination endpoint. + HTTPMethod ForwardingRequestRequestDetailsHTTPMethod `json:"http_method"` +} + +// HTTP headers that the destination endpoint returned. +type ForwardingRequestResponseDetailsHeader struct { + // The header name. + Name string `json:"name"` + // The header value. + Value string `json:"value"` +} + +// The response that the destination endpoint returned to us. We redact any sensitive fields. +type ForwardingRequestResponseDetails struct { + // The response body from the destination endpoint to Stripe. + Body string `json:"body"` + // HTTP headers that the destination endpoint returned. + Headers []*ForwardingRequestResponseDetailsHeader `json:"headers"` + // The HTTP status code that the destination endpoint returned. + Status int64 `json:"status"` +} + +// Instructs Stripe to make a request on your behalf using the destination URL. The destination URL +// is activated by Stripe at the time of onboarding. Stripe verifies requests with your credentials +// provided during onboarding, and injects card details from the payment_method into the request. +// +// Stripe redacts all sensitive fields and headers, including authentication credentials and card numbers, +// before storing the request and response data in the forwarding Request object, which are subject to a +// 30-day retention period. +// +// You can provide a Stripe idempotency key to make sure that requests with the same key result in only one +// outbound request. The Stripe idempotency key provided should be unique and different from any idempotency +// keys provided on the underlying third-party request. +// +// Forwarding Requests are synchronous requests that return a response or time out according to +// Stripe's limits. +// +// Related guide: [Forward card details to third-party API endpoints](https://docs.stripe.com/payments/forwarding). +type ForwardingRequest struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The PaymentMethod to insert into the forwarded request. Forwarding previously consumed PaymentMethods is allowed. + PaymentMethod string `json:"payment_method"` + // The field kinds to be replaced in the forwarded request. + Replacements []ForwardingRequestReplacement `json:"replacements"` + // Context about the request from Stripe's servers to the destination endpoint. + RequestContext *ForwardingRequestRequestContext `json:"request_context"` + // The request that was sent to the destination endpoint. We redact any sensitive fields. + RequestDetails *ForwardingRequestRequestDetails `json:"request_details"` + // The response that the destination endpoint returned to us. We redact any sensitive fields. + ResponseDetails *ForwardingRequestResponseDetails `json:"response_details"` + // The destination URL for the forwarded request. Must be supported by the config. + URL string `json:"url"` +} + +// ForwardingRequestList is a list of Requests as retrieved from a list endpoint. +type ForwardingRequestList struct { + APIResource + ListMeta + Data []*ForwardingRequest `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/forwarding_request_service.go b/vendor/github.com/stripe/stripe-go/v82/forwarding_request_service.go new file mode 100644 index 00000000..1eedba7d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/forwarding_request_service.go @@ -0,0 +1,61 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1ForwardingRequestService is used to invoke /v1/forwarding/requests APIs. +type v1ForwardingRequestService struct { + B Backend + Key string +} + +// Creates a ForwardingRequest object. +func (c v1ForwardingRequestService) Create(ctx context.Context, params *ForwardingRequestCreateParams) (*ForwardingRequest, error) { + if params == nil { + params = &ForwardingRequestCreateParams{} + } + params.Context = ctx + request := &ForwardingRequest{} + err := c.B.Call( + http.MethodPost, "/v1/forwarding/requests", c.Key, params, request) + return request, err +} + +// Retrieves a ForwardingRequest object. +func (c v1ForwardingRequestService) Retrieve(ctx context.Context, id string, params *ForwardingRequestRetrieveParams) (*ForwardingRequest, error) { + if params == nil { + params = &ForwardingRequestRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/forwarding/requests/%s", id) + request := &ForwardingRequest{} + err := c.B.Call(http.MethodGet, path, c.Key, params, request) + return request, err +} + +// Lists all ForwardingRequest objects. +func (c v1ForwardingRequestService) List(ctx context.Context, listParams *ForwardingRequestListParams) Seq2[*ForwardingRequest, error] { + if listParams == nil { + listParams = &ForwardingRequestListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*ForwardingRequest, ListContainer, error) { + list := &ForwardingRequestList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/forwarding/requests", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/fundinginstructions.go b/vendor/github.com/stripe/stripe-go/v82/fundinginstructions.go new file mode 100644 index 00000000..5db67669 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/fundinginstructions.go @@ -0,0 +1,190 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The payment networks supported by this FinancialAddress +type FundingInstructionsBankTransferFinancialAddressSupportedNetwork string + +// List of values that FundingInstructionsBankTransferFinancialAddressSupportedNetwork can take +const ( + FundingInstructionsBankTransferFinancialAddressSupportedNetworkACH FundingInstructionsBankTransferFinancialAddressSupportedNetwork = "ach" + FundingInstructionsBankTransferFinancialAddressSupportedNetworkBACS FundingInstructionsBankTransferFinancialAddressSupportedNetwork = "bacs" + FundingInstructionsBankTransferFinancialAddressSupportedNetworkDomesticWireUS FundingInstructionsBankTransferFinancialAddressSupportedNetwork = "domestic_wire_us" + FundingInstructionsBankTransferFinancialAddressSupportedNetworkFPS FundingInstructionsBankTransferFinancialAddressSupportedNetwork = "fps" + FundingInstructionsBankTransferFinancialAddressSupportedNetworkSEPA FundingInstructionsBankTransferFinancialAddressSupportedNetwork = "sepa" + FundingInstructionsBankTransferFinancialAddressSupportedNetworkSpei FundingInstructionsBankTransferFinancialAddressSupportedNetwork = "spei" + FundingInstructionsBankTransferFinancialAddressSupportedNetworkSwift FundingInstructionsBankTransferFinancialAddressSupportedNetwork = "swift" + FundingInstructionsBankTransferFinancialAddressSupportedNetworkZengin FundingInstructionsBankTransferFinancialAddressSupportedNetwork = "zengin" +) + +// The type of financial address +type FundingInstructionsBankTransferFinancialAddressType string + +// List of values that FundingInstructionsBankTransferFinancialAddressType can take +const ( + FundingInstructionsBankTransferFinancialAddressTypeABA FundingInstructionsBankTransferFinancialAddressType = "aba" + FundingInstructionsBankTransferFinancialAddressTypeIBAN FundingInstructionsBankTransferFinancialAddressType = "iban" + FundingInstructionsBankTransferFinancialAddressTypeSortCode FundingInstructionsBankTransferFinancialAddressType = "sort_code" + FundingInstructionsBankTransferFinancialAddressTypeSpei FundingInstructionsBankTransferFinancialAddressType = "spei" + FundingInstructionsBankTransferFinancialAddressTypeSwift FundingInstructionsBankTransferFinancialAddressType = "swift" + FundingInstructionsBankTransferFinancialAddressTypeZengin FundingInstructionsBankTransferFinancialAddressType = "zengin" +) + +// The bank_transfer type +type FundingInstructionsBankTransferType string + +// List of values that FundingInstructionsBankTransferType can take +const ( + FundingInstructionsBankTransferTypeEUBankTransfer FundingInstructionsBankTransferType = "eu_bank_transfer" + FundingInstructionsBankTransferTypeJPBankTransfer FundingInstructionsBankTransferType = "jp_bank_transfer" +) + +// The `funding_type` of the returned instructions +type FundingInstructionsFundingType string + +// List of values that FundingInstructionsFundingType can take +const ( + FundingInstructionsFundingTypeBankTransfer FundingInstructionsFundingType = "bank_transfer" +) + +// ABA Records contain U.S. bank account details per the ABA format. +type FundingInstructionsBankTransferFinancialAddressABA struct { + AccountHolderAddress *Address `json:"account_holder_address"` + // The account holder name + AccountHolderName string `json:"account_holder_name"` + // The ABA account number + AccountNumber string `json:"account_number"` + // The account type + AccountType string `json:"account_type"` + BankAddress *Address `json:"bank_address"` + // The bank name + BankName string `json:"bank_name"` + // The ABA routing number + RoutingNumber string `json:"routing_number"` +} + +// Iban Records contain E.U. bank account details per the SEPA format. +type FundingInstructionsBankTransferFinancialAddressIBAN struct { + AccountHolderAddress *Address `json:"account_holder_address"` + // The name of the person or business that owns the bank account + AccountHolderName string `json:"account_holder_name"` + BankAddress *Address `json:"bank_address"` + // The BIC/SWIFT code of the account. + BIC string `json:"bic"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country string `json:"country"` + // The IBAN of the account. + IBAN string `json:"iban"` +} + +// Sort Code Records contain U.K. bank account details per the sort code format. +type FundingInstructionsBankTransferFinancialAddressSortCode struct { + AccountHolderAddress *Address `json:"account_holder_address"` + // The name of the person or business that owns the bank account + AccountHolderName string `json:"account_holder_name"` + // The account number + AccountNumber string `json:"account_number"` + BankAddress *Address `json:"bank_address"` + // The six-digit sort code + SortCode string `json:"sort_code"` +} + +// SPEI Records contain Mexico bank account details per the SPEI format. +type FundingInstructionsBankTransferFinancialAddressSpei struct { + AccountHolderAddress *Address `json:"account_holder_address"` + // The account holder name + AccountHolderName string `json:"account_holder_name"` + BankAddress *Address `json:"bank_address"` + // The three-digit bank code + BankCode string `json:"bank_code"` + // The short banking institution name + BankName string `json:"bank_name"` + // The CLABE number + Clabe string `json:"clabe"` +} + +// SWIFT Records contain U.S. bank account details per the SWIFT format. +type FundingInstructionsBankTransferFinancialAddressSwift struct { + AccountHolderAddress *Address `json:"account_holder_address"` + // The account holder name + AccountHolderName string `json:"account_holder_name"` + // The account number + AccountNumber string `json:"account_number"` + // The account type + AccountType string `json:"account_type"` + BankAddress *Address `json:"bank_address"` + // The bank name + BankName string `json:"bank_name"` + // The SWIFT code + SwiftCode string `json:"swift_code"` +} + +// Zengin Records contain Japan bank account details per the Zengin format. +type FundingInstructionsBankTransferFinancialAddressZengin struct { + AccountHolderAddress *Address `json:"account_holder_address"` + // The account holder name + AccountHolderName string `json:"account_holder_name"` + // The account number + AccountNumber string `json:"account_number"` + // The bank account type. In Japan, this can only be `futsu` or `toza`. + AccountType string `json:"account_type"` + BankAddress *Address `json:"bank_address"` + // The bank code of the account + BankCode string `json:"bank_code"` + // The bank name of the account + BankName string `json:"bank_name"` + // The branch code of the account + BranchCode string `json:"branch_code"` + // The branch name of the account + BranchName string `json:"branch_name"` +} + +// A list of financial addresses that can be used to fund a particular balance +type FundingInstructionsBankTransferFinancialAddress struct { + // ABA Records contain U.S. bank account details per the ABA format. + ABA *FundingInstructionsBankTransferFinancialAddressABA `json:"aba"` + // Iban Records contain E.U. bank account details per the SEPA format. + IBAN *FundingInstructionsBankTransferFinancialAddressIBAN `json:"iban"` + // Sort Code Records contain U.K. bank account details per the sort code format. + SortCode *FundingInstructionsBankTransferFinancialAddressSortCode `json:"sort_code"` + // SPEI Records contain Mexico bank account details per the SPEI format. + Spei *FundingInstructionsBankTransferFinancialAddressSpei `json:"spei"` + // The payment networks supported by this FinancialAddress + SupportedNetworks []FundingInstructionsBankTransferFinancialAddressSupportedNetwork `json:"supported_networks"` + // SWIFT Records contain U.S. bank account details per the SWIFT format. + Swift *FundingInstructionsBankTransferFinancialAddressSwift `json:"swift"` + // The type of financial address + Type FundingInstructionsBankTransferFinancialAddressType `json:"type"` + // Zengin Records contain Japan bank account details per the Zengin format. + Zengin *FundingInstructionsBankTransferFinancialAddressZengin `json:"zengin"` +} +type FundingInstructionsBankTransfer struct { + // The country of the bank account to fund + Country string `json:"country"` + // A list of financial addresses that can be used to fund a particular balance + FinancialAddresses []*FundingInstructionsBankTransferFinancialAddress `json:"financial_addresses"` + // The bank_transfer type + Type FundingInstructionsBankTransferType `json:"type"` +} + +// Each customer has a [`balance`](https://stripe.com/docs/api/customers/object#customer_object-balance) that is +// automatically applied to future invoices and payments using the `customer_balance` payment method. +// Customers can fund this balance by initiating a bank transfer to any account in the +// `financial_addresses` field. +// Related guide: [Customer balance funding instructions](https://stripe.com/docs/payments/customer-balance/funding-instructions) +type FundingInstructions struct { + APIResource + BankTransfer *FundingInstructionsBankTransfer `json:"bank_transfer"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // The `funding_type` of the returned instructions + FundingType FundingInstructionsFundingType `json:"funding_type"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/identity_verificationreport.go b/vendor/github.com/stripe/stripe-go/v82/identity_verificationreport.go new file mode 100644 index 00000000..2147e3ab --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/identity_verificationreport.go @@ -0,0 +1,447 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// A short machine-readable string giving the reason for the verification failure. +type IdentityVerificationReportDocumentErrorCode string + +// List of values that IdentityVerificationReportDocumentErrorCode can take +const ( + IdentityVerificationReportDocumentErrorCodeDocumentExpired IdentityVerificationReportDocumentErrorCode = "document_expired" + IdentityVerificationReportDocumentErrorCodeDocumentTypeNotSupported IdentityVerificationReportDocumentErrorCode = "document_type_not_supported" + IdentityVerificationReportDocumentErrorCodeDocumentUnverifiedOther IdentityVerificationReportDocumentErrorCode = "document_unverified_other" +) + +// Sex of the person in the document. +type IdentityVerificationReportDocumentSex string + +// List of values that IdentityVerificationReportDocumentSex can take +const ( + IdentityVerificationReportDocumentSexRedacted IdentityVerificationReportDocumentSex = "[redacted]" + IdentityVerificationReportDocumentSexFemale IdentityVerificationReportDocumentSex = "female" + IdentityVerificationReportDocumentSexMale IdentityVerificationReportDocumentSex = "male" + IdentityVerificationReportDocumentSexUnknown IdentityVerificationReportDocumentSex = "unknown" +) + +// Status of this `document` check. +type IdentityVerificationReportDocumentStatus string + +// List of values that IdentityVerificationReportDocumentStatus can take +const ( + IdentityVerificationReportDocumentStatusUnverified IdentityVerificationReportDocumentStatus = "unverified" + IdentityVerificationReportDocumentStatusVerified IdentityVerificationReportDocumentStatus = "verified" +) + +// Type of the document. +type IdentityVerificationReportDocumentType string + +// List of values that IdentityVerificationReportDocumentType can take +const ( + IdentityVerificationReportDocumentTypeDrivingLicense IdentityVerificationReportDocumentType = "driving_license" + IdentityVerificationReportDocumentTypeIDCard IdentityVerificationReportDocumentType = "id_card" + IdentityVerificationReportDocumentTypePassport IdentityVerificationReportDocumentType = "passport" +) + +// A short machine-readable string giving the reason for the verification failure. +type IdentityVerificationReportEmailErrorCode string + +// List of values that IdentityVerificationReportEmailErrorCode can take +const ( + IdentityVerificationReportEmailErrorCodeEmailUnverifiedOther IdentityVerificationReportEmailErrorCode = "email_unverified_other" + IdentityVerificationReportEmailErrorCodeEmailVerificationDeclined IdentityVerificationReportEmailErrorCode = "email_verification_declined" +) + +// Status of this `email` check. +type IdentityVerificationReportEmailStatus string + +// List of values that IdentityVerificationReportEmailStatus can take +const ( + IdentityVerificationReportEmailStatusUnverified IdentityVerificationReportEmailStatus = "unverified" + IdentityVerificationReportEmailStatusVerified IdentityVerificationReportEmailStatus = "verified" +) + +// A short machine-readable string giving the reason for the verification failure. +type IdentityVerificationReportIDNumberErrorCode string + +// List of values that IdentityVerificationReportIDNumberErrorCode can take +const ( + IdentityVerificationReportIDNumberErrorCodeIDNumberInsufficientDocumentData IdentityVerificationReportIDNumberErrorCode = "id_number_insufficient_document_data" + IdentityVerificationReportIDNumberErrorCodeIDNumberMismatch IdentityVerificationReportIDNumberErrorCode = "id_number_mismatch" + IdentityVerificationReportIDNumberErrorCodeIDNumberUnverifiedOther IdentityVerificationReportIDNumberErrorCode = "id_number_unverified_other" +) + +// Type of ID number. +type IdentityVerificationReportIDNumberIDNumberType string + +// List of values that IdentityVerificationReportIDNumberIDNumberType can take +const ( + IdentityVerificationReportIDNumberIDNumberTypeBRCPF IdentityVerificationReportIDNumberIDNumberType = "br_cpf" + IdentityVerificationReportIDNumberIDNumberTypeSGNRIC IdentityVerificationReportIDNumberIDNumberType = "sg_nric" + IdentityVerificationReportIDNumberIDNumberTypeUSSSN IdentityVerificationReportIDNumberIDNumberType = "us_ssn" +) + +// Status of this `id_number` check. +type IdentityVerificationReportIDNumberStatus string + +// List of values that IdentityVerificationReportIDNumberStatus can take +const ( + IdentityVerificationReportIDNumberStatusUnverified IdentityVerificationReportIDNumberStatus = "unverified" + IdentityVerificationReportIDNumberStatusVerified IdentityVerificationReportIDNumberStatus = "verified" +) + +// Array of strings of allowed identity document types. If the provided identity document isn't one of the allowed types, the verification check will fail with a document_type_not_allowed error code. +type IdentityVerificationReportOptionsDocumentAllowedType string + +// List of values that IdentityVerificationReportOptionsDocumentAllowedType can take +const ( + IdentityVerificationReportOptionsDocumentAllowedTypeDrivingLicense IdentityVerificationReportOptionsDocumentAllowedType = "driving_license" + IdentityVerificationReportOptionsDocumentAllowedTypeIDCard IdentityVerificationReportOptionsDocumentAllowedType = "id_card" + IdentityVerificationReportOptionsDocumentAllowedTypePassport IdentityVerificationReportOptionsDocumentAllowedType = "passport" +) + +// A short machine-readable string giving the reason for the verification failure. +type IdentityVerificationReportPhoneErrorCode string + +// List of values that IdentityVerificationReportPhoneErrorCode can take +const ( + IdentityVerificationReportPhoneErrorCodePhoneUnverifiedOther IdentityVerificationReportPhoneErrorCode = "phone_unverified_other" + IdentityVerificationReportPhoneErrorCodePhoneVerificationDeclined IdentityVerificationReportPhoneErrorCode = "phone_verification_declined" +) + +// Status of this `phone` check. +type IdentityVerificationReportPhoneStatus string + +// List of values that IdentityVerificationReportPhoneStatus can take +const ( + IdentityVerificationReportPhoneStatusUnverified IdentityVerificationReportPhoneStatus = "unverified" + IdentityVerificationReportPhoneStatusVerified IdentityVerificationReportPhoneStatus = "verified" +) + +// A short machine-readable string giving the reason for the verification failure. +type IdentityVerificationReportSelfieErrorCode string + +// List of values that IdentityVerificationReportSelfieErrorCode can take +const ( + IdentityVerificationReportSelfieErrorCodeSelfieDocumentMissingPhoto IdentityVerificationReportSelfieErrorCode = "selfie_document_missing_photo" + IdentityVerificationReportSelfieErrorCodeSelfieFaceMismatch IdentityVerificationReportSelfieErrorCode = "selfie_face_mismatch" + IdentityVerificationReportSelfieErrorCodeSelfieManipulated IdentityVerificationReportSelfieErrorCode = "selfie_manipulated" + IdentityVerificationReportSelfieErrorCodeSelfieUnverifiedOther IdentityVerificationReportSelfieErrorCode = "selfie_unverified_other" +) + +// Status of this `selfie` check. +type IdentityVerificationReportSelfieStatus string + +// List of values that IdentityVerificationReportSelfieStatus can take +const ( + IdentityVerificationReportSelfieStatusUnverified IdentityVerificationReportSelfieStatus = "unverified" + IdentityVerificationReportSelfieStatusVerified IdentityVerificationReportSelfieStatus = "verified" +) + +// Type of report. +type IdentityVerificationReportType string + +// List of values that IdentityVerificationReportType can take +const ( + IdentityVerificationReportTypeDocument IdentityVerificationReportType = "document" + IdentityVerificationReportTypeIDNumber IdentityVerificationReportType = "id_number" + IdentityVerificationReportTypeVerificationFlow IdentityVerificationReportType = "verification_flow" +) + +// List all verification reports. +type IdentityVerificationReportListParams struct { + ListParams `form:"*"` + // A string to reference this user. This can be a customer ID, a session ID, or similar, and can be used to reconcile this verification with your internal systems. + ClientReferenceID *string `form:"client_reference_id"` + // Only return VerificationReports that were created during the given date interval. + Created *int64 `form:"created"` + // Only return VerificationReports that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return VerificationReports of this type + Type *string `form:"type"` + // Only return VerificationReports created by this VerificationSession ID. It is allowed to provide a VerificationIntent ID. + VerificationSession *string `form:"verification_session"` +} + +// AddExpand appends a new field to expand. +func (p *IdentityVerificationReportListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves an existing VerificationReport +type IdentityVerificationReportParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *IdentityVerificationReportParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves an existing VerificationReport +type IdentityVerificationReportRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *IdentityVerificationReportRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Date of birth as it appears in the document. +type IdentityVerificationReportDocumentDOB struct { + // Numerical day between 1 and 31. + Day int64 `json:"day"` + // Numerical month between 1 and 12. + Month int64 `json:"month"` + // The four-digit year. + Year int64 `json:"year"` +} + +// Details on the verification error. Present when status is `unverified`. +type IdentityVerificationReportDocumentError struct { + // A short machine-readable string giving the reason for the verification failure. + Code IdentityVerificationReportDocumentErrorCode `json:"code"` + // A human-readable message giving the reason for the failure. These messages can be shown to your users. + Reason string `json:"reason"` +} + +// Expiration date of the document. +type IdentityVerificationReportDocumentExpirationDate struct { + // Numerical day between 1 and 31. + Day int64 `json:"day"` + // Numerical month between 1 and 12. + Month int64 `json:"month"` + // The four-digit year. + Year int64 `json:"year"` +} + +// Issued date of the document. +type IdentityVerificationReportDocumentIssuedDate struct { + // Numerical day between 1 and 31. + Day int64 `json:"day"` + // Numerical month between 1 and 12. + Month int64 `json:"month"` + // The four-digit year. + Year int64 `json:"year"` +} + +// Result from a document check +type IdentityVerificationReportDocument struct { + // Address as it appears in the document. + Address *Address `json:"address"` + // Date of birth as it appears in the document. + DOB *IdentityVerificationReportDocumentDOB `json:"dob"` + // Details on the verification error. Present when status is `unverified`. + Error *IdentityVerificationReportDocumentError `json:"error"` + // Expiration date of the document. + ExpirationDate *IdentityVerificationReportDocumentExpirationDate `json:"expiration_date"` + // Array of [File](https://stripe.com/docs/api/files) ids containing images for this document. + Files []string `json:"files"` + // First name as it appears in the document. + FirstName string `json:"first_name"` + // Issued date of the document. + IssuedDate *IdentityVerificationReportDocumentIssuedDate `json:"issued_date"` + // Issuing country of the document. + IssuingCountry string `json:"issuing_country"` + // Last name as it appears in the document. + LastName string `json:"last_name"` + // Document ID number. + Number string `json:"number"` + // Sex of the person in the document. + Sex IdentityVerificationReportDocumentSex `json:"sex"` + // Status of this `document` check. + Status IdentityVerificationReportDocumentStatus `json:"status"` + // Type of the document. + Type IdentityVerificationReportDocumentType `json:"type"` + // Place of birth as it appears in the document. + UnparsedPlaceOfBirth string `json:"unparsed_place_of_birth"` + // Sex as it appears in the document. + UnparsedSex string `json:"unparsed_sex"` +} + +// Details on the verification error. Present when status is `unverified`. +type IdentityVerificationReportEmailError struct { + // A short machine-readable string giving the reason for the verification failure. + Code IdentityVerificationReportEmailErrorCode `json:"code"` + // A human-readable message giving the reason for the failure. These messages can be shown to your users. + Reason string `json:"reason"` +} + +// Result from a email check +type IdentityVerificationReportEmail struct { + // Email to be verified. + Email string `json:"email"` + // Details on the verification error. Present when status is `unverified`. + Error *IdentityVerificationReportEmailError `json:"error"` + // Status of this `email` check. + Status IdentityVerificationReportEmailStatus `json:"status"` +} + +// Date of birth. +type IdentityVerificationReportIDNumberDOB struct { + // Numerical day between 1 and 31. + Day int64 `json:"day"` + // Numerical month between 1 and 12. + Month int64 `json:"month"` + // The four-digit year. + Year int64 `json:"year"` +} + +// Details on the verification error. Present when status is `unverified`. +type IdentityVerificationReportIDNumberError struct { + // A short machine-readable string giving the reason for the verification failure. + Code IdentityVerificationReportIDNumberErrorCode `json:"code"` + // A human-readable message giving the reason for the failure. These messages can be shown to your users. + Reason string `json:"reason"` +} + +// Result from an id_number check +type IdentityVerificationReportIDNumber struct { + // Date of birth. + DOB *IdentityVerificationReportIDNumberDOB `json:"dob"` + // Details on the verification error. Present when status is `unverified`. + Error *IdentityVerificationReportIDNumberError `json:"error"` + // First name. + FirstName string `json:"first_name"` + // ID number. When `id_number_type` is `us_ssn`, only the last 4 digits are present. + IDNumber string `json:"id_number"` + // Type of ID number. + IDNumberType IdentityVerificationReportIDNumberIDNumberType `json:"id_number_type"` + // Last name. + LastName string `json:"last_name"` + // Status of this `id_number` check. + Status IdentityVerificationReportIDNumberStatus `json:"status"` +} +type IdentityVerificationReportOptionsDocument struct { + // Array of strings of allowed identity document types. If the provided identity document isn't one of the allowed types, the verification check will fail with a document_type_not_allowed error code. + AllowedTypes []IdentityVerificationReportOptionsDocumentAllowedType `json:"allowed_types"` + // Collect an ID number and perform an [ID number check](https://stripe.com/docs/identity/verification-checks?type=id-number) with the document's extracted name and date of birth. + RequireIDNumber bool `json:"require_id_number"` + // Disable image uploads, identity document images have to be captured using the device's camera. + RequireLiveCapture bool `json:"require_live_capture"` + // Capture a face image and perform a [selfie check](https://stripe.com/docs/identity/verification-checks?type=selfie) comparing a photo ID and a picture of your user's face. [Learn more](https://stripe.com/docs/identity/selfie). + RequireMatchingSelfie bool `json:"require_matching_selfie"` +} +type IdentityVerificationReportOptionsIDNumber struct{} +type IdentityVerificationReportOptions struct { + Document *IdentityVerificationReportOptionsDocument `json:"document"` + IDNumber *IdentityVerificationReportOptionsIDNumber `json:"id_number"` +} + +// Details on the verification error. Present when status is `unverified`. +type IdentityVerificationReportPhoneError struct { + // A short machine-readable string giving the reason for the verification failure. + Code IdentityVerificationReportPhoneErrorCode `json:"code"` + // A human-readable message giving the reason for the failure. These messages can be shown to your users. + Reason string `json:"reason"` +} + +// Result from a phone check +type IdentityVerificationReportPhone struct { + // Details on the verification error. Present when status is `unverified`. + Error *IdentityVerificationReportPhoneError `json:"error"` + // Phone to be verified. + Phone string `json:"phone"` + // Status of this `phone` check. + Status IdentityVerificationReportPhoneStatus `json:"status"` +} + +// Details on the verification error. Present when status is `unverified`. +type IdentityVerificationReportSelfieError struct { + // A short machine-readable string giving the reason for the verification failure. + Code IdentityVerificationReportSelfieErrorCode `json:"code"` + // A human-readable message giving the reason for the failure. These messages can be shown to your users. + Reason string `json:"reason"` +} + +// Result from a selfie check +type IdentityVerificationReportSelfie struct { + // ID of the [File](https://stripe.com/docs/api/files) holding the image of the identity document used in this check. + Document string `json:"document"` + // Details on the verification error. Present when status is `unverified`. + Error *IdentityVerificationReportSelfieError `json:"error"` + // ID of the [File](https://stripe.com/docs/api/files) holding the image of the selfie used in this check. + Selfie string `json:"selfie"` + // Status of this `selfie` check. + Status IdentityVerificationReportSelfieStatus `json:"status"` +} + +// A VerificationReport is the result of an attempt to collect and verify data from a user. +// The collection of verification checks performed is determined from the `type` and `options` +// parameters used. You can find the result of each verification check performed in the +// appropriate sub-resource: `document`, `id_number`, `selfie`. +// +// Each VerificationReport contains a copy of any data collected by the user as well as +// reference IDs which can be used to access collected images through the [FileUpload](https://stripe.com/docs/api/files) +// API. To configure and create VerificationReports, use the +// [VerificationSession](https://stripe.com/docs/api/identity/verification_sessions) API. +// +// Related guide: [Accessing verification results](https://stripe.com/docs/identity/verification-sessions#results). +type IdentityVerificationReport struct { + APIResource + // A string to reference this user. This can be a customer ID, a session ID, or similar, and can be used to reconcile this verification with your internal systems. + ClientReferenceID string `json:"client_reference_id"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Result from a document check + Document *IdentityVerificationReportDocument `json:"document"` + // Result from a email check + Email *IdentityVerificationReportEmail `json:"email"` + // Unique identifier for the object. + ID string `json:"id"` + // Result from an id_number check + IDNumber *IdentityVerificationReportIDNumber `json:"id_number"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + Options *IdentityVerificationReportOptions `json:"options"` + // Result from a phone check + Phone *IdentityVerificationReportPhone `json:"phone"` + // Result from a selfie check + Selfie *IdentityVerificationReportSelfie `json:"selfie"` + // Type of report. + Type IdentityVerificationReportType `json:"type"` + // The configuration token of a verification flow from the dashboard. + VerificationFlow string `json:"verification_flow"` + // ID of the VerificationSession that created this report. + VerificationSession string `json:"verification_session"` +} + +// IdentityVerificationReportList is a list of VerificationReports as retrieved from a list endpoint. +type IdentityVerificationReportList struct { + APIResource + ListMeta + Data []*IdentityVerificationReport `json:"data"` +} + +// UnmarshalJSON handles deserialization of an IdentityVerificationReport. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (i *IdentityVerificationReport) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + i.ID = id + return nil + } + + type identityVerificationReport IdentityVerificationReport + var v identityVerificationReport + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *i = IdentityVerificationReport(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/identity_verificationreport_service.go b/vendor/github.com/stripe/stripe-go/v82/identity_verificationreport_service.go new file mode 100644 index 00000000..2a470495 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/identity_verificationreport_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1IdentityVerificationReportService is used to invoke /v1/identity/verification_reports APIs. +type v1IdentityVerificationReportService struct { + B Backend + Key string +} + +// Retrieves an existing VerificationReport +func (c v1IdentityVerificationReportService) Retrieve(ctx context.Context, id string, params *IdentityVerificationReportRetrieveParams) (*IdentityVerificationReport, error) { + if params == nil { + params = &IdentityVerificationReportRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/identity/verification_reports/%s", id) + verificationreport := &IdentityVerificationReport{} + err := c.B.Call(http.MethodGet, path, c.Key, params, verificationreport) + return verificationreport, err +} + +// List all verification reports. +func (c v1IdentityVerificationReportService) List(ctx context.Context, listParams *IdentityVerificationReportListParams) Seq2[*IdentityVerificationReport, error] { + if listParams == nil { + listParams = &IdentityVerificationReportListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*IdentityVerificationReport, ListContainer, error) { + list := &IdentityVerificationReportList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/identity/verification_reports", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/identity_verificationsession.go b/vendor/github.com/stripe/stripe-go/v82/identity_verificationsession.go new file mode 100644 index 00000000..c7ec67c0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/identity_verificationsession.go @@ -0,0 +1,565 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// A short machine-readable string giving the reason for the verification or user-session failure. +type IdentityVerificationSessionLastErrorCode string + +// List of values that IdentityVerificationSessionLastErrorCode can take +const ( + IdentityVerificationSessionLastErrorCodeAbandoned IdentityVerificationSessionLastErrorCode = "abandoned" + IdentityVerificationSessionLastErrorCodeConsentDeclined IdentityVerificationSessionLastErrorCode = "consent_declined" + IdentityVerificationSessionLastErrorCodeCountryNotSupported IdentityVerificationSessionLastErrorCode = "country_not_supported" + IdentityVerificationSessionLastErrorCodeDeviceNotSupported IdentityVerificationSessionLastErrorCode = "device_not_supported" + IdentityVerificationSessionLastErrorCodeDocumentExpired IdentityVerificationSessionLastErrorCode = "document_expired" + IdentityVerificationSessionLastErrorCodeDocumentTypeNotSupported IdentityVerificationSessionLastErrorCode = "document_type_not_supported" + IdentityVerificationSessionLastErrorCodeDocumentUnverifiedOther IdentityVerificationSessionLastErrorCode = "document_unverified_other" + IdentityVerificationSessionLastErrorCodeEmailUnverifiedOther IdentityVerificationSessionLastErrorCode = "email_unverified_other" + IdentityVerificationSessionLastErrorCodeEmailVerificationDeclined IdentityVerificationSessionLastErrorCode = "email_verification_declined" + IdentityVerificationSessionLastErrorCodeIDNumberInsufficientDocumentData IdentityVerificationSessionLastErrorCode = "id_number_insufficient_document_data" + IdentityVerificationSessionLastErrorCodeIDNumberMismatch IdentityVerificationSessionLastErrorCode = "id_number_mismatch" + IdentityVerificationSessionLastErrorCodeIDNumberUnverifiedOther IdentityVerificationSessionLastErrorCode = "id_number_unverified_other" + IdentityVerificationSessionLastErrorCodePhoneUnverifiedOther IdentityVerificationSessionLastErrorCode = "phone_unverified_other" + IdentityVerificationSessionLastErrorCodePhoneVerificationDeclined IdentityVerificationSessionLastErrorCode = "phone_verification_declined" + IdentityVerificationSessionLastErrorCodeSelfieDocumentMissingPhoto IdentityVerificationSessionLastErrorCode = "selfie_document_missing_photo" + IdentityVerificationSessionLastErrorCodeSelfieFaceMismatch IdentityVerificationSessionLastErrorCode = "selfie_face_mismatch" + IdentityVerificationSessionLastErrorCodeSelfieManipulated IdentityVerificationSessionLastErrorCode = "selfie_manipulated" + IdentityVerificationSessionLastErrorCodeSelfieUnverifiedOther IdentityVerificationSessionLastErrorCode = "selfie_unverified_other" + IdentityVerificationSessionLastErrorCodeUnderSupportedAge IdentityVerificationSessionLastErrorCode = "under_supported_age" +) + +// Array of strings of allowed identity document types. If the provided identity document isn't one of the allowed types, the verification check will fail with a document_type_not_allowed error code. +type IdentityVerificationSessionOptionsDocumentAllowedType string + +// List of values that IdentityVerificationSessionOptionsDocumentAllowedType can take +const ( + IdentityVerificationSessionOptionsDocumentAllowedTypeDrivingLicense IdentityVerificationSessionOptionsDocumentAllowedType = "driving_license" + IdentityVerificationSessionOptionsDocumentAllowedTypeIDCard IdentityVerificationSessionOptionsDocumentAllowedType = "id_card" + IdentityVerificationSessionOptionsDocumentAllowedTypePassport IdentityVerificationSessionOptionsDocumentAllowedType = "passport" +) + +// Strictness of the DOB matching policy to apply. +type IdentityVerificationSessionOptionsMatchingDOB string + +// List of values that IdentityVerificationSessionOptionsMatchingDOB can take +const ( + IdentityVerificationSessionOptionsMatchingDOBNone IdentityVerificationSessionOptionsMatchingDOB = "none" + IdentityVerificationSessionOptionsMatchingDOBSimilar IdentityVerificationSessionOptionsMatchingDOB = "similar" +) + +// Strictness of the name matching policy to apply. +type IdentityVerificationSessionOptionsMatchingName string + +// List of values that IdentityVerificationSessionOptionsMatchingName can take +const ( + IdentityVerificationSessionOptionsMatchingNameNone IdentityVerificationSessionOptionsMatchingName = "none" + IdentityVerificationSessionOptionsMatchingNameSimilar IdentityVerificationSessionOptionsMatchingName = "similar" +) + +// Indicates whether this object and its related objects have been redacted or not. +type IdentityVerificationSessionRedactionStatus string + +// List of values that IdentityVerificationSessionRedactionStatus can take +const ( + IdentityVerificationSessionRedactionStatusProcessing IdentityVerificationSessionRedactionStatus = "processing" + IdentityVerificationSessionRedactionStatusRedacted IdentityVerificationSessionRedactionStatus = "redacted" +) + +// Status of this VerificationSession. [Learn more about the lifecycle of sessions](https://stripe.com/docs/identity/how-sessions-work). +type IdentityVerificationSessionStatus string + +// List of values that IdentityVerificationSessionStatus can take +const ( + IdentityVerificationSessionStatusCanceled IdentityVerificationSessionStatus = "canceled" + IdentityVerificationSessionStatusProcessing IdentityVerificationSessionStatus = "processing" + IdentityVerificationSessionStatusRequiresInput IdentityVerificationSessionStatus = "requires_input" + IdentityVerificationSessionStatusVerified IdentityVerificationSessionStatus = "verified" +) + +// The type of [verification check](https://stripe.com/docs/identity/verification-checks) to be performed. +type IdentityVerificationSessionType string + +// List of values that IdentityVerificationSessionType can take +const ( + IdentityVerificationSessionTypeDocument IdentityVerificationSessionType = "document" + IdentityVerificationSessionTypeIDNumber IdentityVerificationSessionType = "id_number" + IdentityVerificationSessionTypeVerificationFlow IdentityVerificationSessionType = "verification_flow" +) + +// The user's verified id number type. +type IdentityVerificationSessionVerifiedOutputsIDNumberType string + +// List of values that IdentityVerificationSessionVerifiedOutputsIDNumberType can take +const ( + IdentityVerificationSessionVerifiedOutputsIDNumberTypeBRCPF IdentityVerificationSessionVerifiedOutputsIDNumberType = "br_cpf" + IdentityVerificationSessionVerifiedOutputsIDNumberTypeSGNRIC IdentityVerificationSessionVerifiedOutputsIDNumberType = "sg_nric" + IdentityVerificationSessionVerifiedOutputsIDNumberTypeUSSSN IdentityVerificationSessionVerifiedOutputsIDNumberType = "us_ssn" +) + +// The user's verified sex. +type IdentityVerificationSessionVerifiedOutputsSex string + +// List of values that IdentityVerificationSessionVerifiedOutputsSex can take +const ( + IdentityVerificationSessionVerifiedOutputsSexRedacted IdentityVerificationSessionVerifiedOutputsSex = "[redacted]" + IdentityVerificationSessionVerifiedOutputsSexFemale IdentityVerificationSessionVerifiedOutputsSex = "female" + IdentityVerificationSessionVerifiedOutputsSexMale IdentityVerificationSessionVerifiedOutputsSex = "male" + IdentityVerificationSessionVerifiedOutputsSexUnknown IdentityVerificationSessionVerifiedOutputsSex = "unknown" +) + +// Returns a list of VerificationSessions +type IdentityVerificationSessionListParams struct { + ListParams `form:"*"` + // A string to reference this user. This can be a customer ID, a session ID, or similar, and can be used to reconcile this verification with your internal systems. + ClientReferenceID *string `form:"client_reference_id"` + // Only return VerificationSessions that were created during the given date interval. + Created *int64 `form:"created"` + // Only return VerificationSessions that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + RelatedCustomer *string `form:"related_customer"` + // Only return VerificationSessions with this status. [Learn more about the lifecycle of sessions](https://stripe.com/docs/identity/how-sessions-work). + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *IdentityVerificationSessionListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Options that apply to the [document check](https://stripe.com/docs/identity/verification-checks?type=document). +type IdentityVerificationSessionOptionsDocumentParams struct { + // Array of strings of allowed identity document types. If the provided identity document isn't one of the allowed types, the verification check will fail with a document_type_not_allowed error code. + AllowedTypes []*string `form:"allowed_types"` + // Collect an ID number and perform an [ID number check](https://stripe.com/docs/identity/verification-checks?type=id-number) with the document's extracted name and date of birth. + RequireIDNumber *bool `form:"require_id_number"` + // Disable image uploads, identity document images have to be captured using the device's camera. + RequireLiveCapture *bool `form:"require_live_capture"` + // Capture a face image and perform a [selfie check](https://stripe.com/docs/identity/verification-checks?type=selfie) comparing a photo ID and a picture of your user's face. [Learn more](https://stripe.com/docs/identity/selfie). + RequireMatchingSelfie *bool `form:"require_matching_selfie"` +} + +// A set of options for the session's verification checks. +type IdentityVerificationSessionOptionsParams struct { + // Options that apply to the [document check](https://stripe.com/docs/identity/verification-checks?type=document). + Document *IdentityVerificationSessionOptionsDocumentParams `form:"document"` +} + +// Details provided about the user being verified. These details may be shown to the user. +type IdentityVerificationSessionProvidedDetailsParams struct { + // Email of user being verified + Email *string `form:"email"` + // Phone number of user being verified + Phone *string `form:"phone"` +} + +// Tokens referencing a Person resource and it's associated account. +type IdentityVerificationSessionRelatedPersonParams struct { + // A token representing a connected account. If provided, the person parameter is also required and must be associated with the account. + Account *string `form:"account"` + // A token referencing a Person resource that this verification is being used to verify. + Person *string `form:"person"` +} + +// Creates a VerificationSession object. +// +// After the VerificationSession is created, display a verification modal using the session client_secret or send your users to the session's url. +// +// If your API key is in test mode, verification checks won't actually process, though everything else will occur as if in live mode. +// +// Related guide: [Verify your users' identity documents](https://docs.stripe.com/docs/identity/verify-identity-documents) +type IdentityVerificationSessionParams struct { + Params `form:"*"` + // A string to reference this user. This can be a customer ID, a session ID, or similar, and can be used to reconcile this verification with your internal systems. + ClientReferenceID *string `form:"client_reference_id"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // A set of options for the session's verification checks. + Options *IdentityVerificationSessionOptionsParams `form:"options"` + // Details provided about the user being verified. These details may be shown to the user. + ProvidedDetails *IdentityVerificationSessionProvidedDetailsParams `form:"provided_details"` + // Customer ID + RelatedCustomer *string `form:"related_customer"` + // Tokens referencing a Person resource and it's associated account. + RelatedPerson *IdentityVerificationSessionRelatedPersonParams `form:"related_person"` + // The URL that the user will be redirected to upon completing the verification flow. + ReturnURL *string `form:"return_url"` + // The type of [verification check](https://stripe.com/docs/identity/verification-checks) to be performed. You must provide a `type` if not passing `verification_flow`. + Type *string `form:"type"` + // The ID of a verification flow from the Dashboard. See https://docs.stripe.com/identity/verification-flows. + VerificationFlow *string `form:"verification_flow"` +} + +// AddExpand appends a new field to expand. +func (p *IdentityVerificationSessionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IdentityVerificationSessionParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A VerificationSession object can be canceled when it is in requires_input [status](https://docs.stripe.com/docs/identity/how-sessions-work). +// +// Once canceled, future submission attempts are disabled. This cannot be undone. [Learn more](https://docs.stripe.com/docs/identity/verification-sessions#cancel). +type IdentityVerificationSessionCancelParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *IdentityVerificationSessionCancelParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Redact a VerificationSession to remove all collected information from Stripe. This will redact +// the VerificationSession and all objects related to it, including VerificationReports, Events, +// request logs, etc. +// +// A VerificationSession object can be redacted when it is in requires_input or verified +// [status](https://docs.stripe.com/docs/identity/how-sessions-work). Redacting a VerificationSession in requires_action +// state will automatically cancel it. +// +// The redaction process may take up to four days. When the redaction process is in progress, the +// VerificationSession's redaction.status field will be set to processing; when the process is +// finished, it will change to redacted and an identity.verification_session.redacted event +// will be emitted. +// +// Redaction is irreversible. Redacted objects are still accessible in the Stripe API, but all the +// fields that contain personal data will be replaced by the string [redacted] or a similar +// placeholder. The metadata field will also be erased. Redacted objects cannot be updated or +// used for any purpose. +// +// [Learn more](https://docs.stripe.com/docs/identity/verification-sessions#redact). +type IdentityVerificationSessionRedactParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *IdentityVerificationSessionRedactParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Options that apply to the [document check](https://stripe.com/docs/identity/verification-checks?type=document). +type IdentityVerificationSessionCreateOptionsDocumentParams struct { + // Array of strings of allowed identity document types. If the provided identity document isn't one of the allowed types, the verification check will fail with a document_type_not_allowed error code. + AllowedTypes []*string `form:"allowed_types"` + // Collect an ID number and perform an [ID number check](https://stripe.com/docs/identity/verification-checks?type=id-number) with the document's extracted name and date of birth. + RequireIDNumber *bool `form:"require_id_number"` + // Disable image uploads, identity document images have to be captured using the device's camera. + RequireLiveCapture *bool `form:"require_live_capture"` + // Capture a face image and perform a [selfie check](https://stripe.com/docs/identity/verification-checks?type=selfie) comparing a photo ID and a picture of your user's face. [Learn more](https://stripe.com/docs/identity/selfie). + RequireMatchingSelfie *bool `form:"require_matching_selfie"` +} + +// A set of options for the session's verification checks. +type IdentityVerificationSessionCreateOptionsParams struct { + // Options that apply to the [document check](https://stripe.com/docs/identity/verification-checks?type=document). + Document *IdentityVerificationSessionCreateOptionsDocumentParams `form:"document"` +} + +// Details provided about the user being verified. These details may be shown to the user. +type IdentityVerificationSessionCreateProvidedDetailsParams struct { + // Email of user being verified + Email *string `form:"email"` + // Phone number of user being verified + Phone *string `form:"phone"` +} + +// Tokens referencing a Person resource and it's associated account. +type IdentityVerificationSessionCreateRelatedPersonParams struct { + // A token representing a connected account. If provided, the person parameter is also required and must be associated with the account. + Account *string `form:"account"` + // A token referencing a Person resource that this verification is being used to verify. + Person *string `form:"person"` +} + +// Creates a VerificationSession object. +// +// After the VerificationSession is created, display a verification modal using the session client_secret or send your users to the session's url. +// +// If your API key is in test mode, verification checks won't actually process, though everything else will occur as if in live mode. +// +// Related guide: [Verify your users' identity documents](https://docs.stripe.com/docs/identity/verify-identity-documents) +type IdentityVerificationSessionCreateParams struct { + Params `form:"*"` + // A string to reference this user. This can be a customer ID, a session ID, or similar, and can be used to reconcile this verification with your internal systems. + ClientReferenceID *string `form:"client_reference_id"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // A set of options for the session's verification checks. + Options *IdentityVerificationSessionCreateOptionsParams `form:"options"` + // Details provided about the user being verified. These details may be shown to the user. + ProvidedDetails *IdentityVerificationSessionCreateProvidedDetailsParams `form:"provided_details"` + // Customer ID + RelatedCustomer *string `form:"related_customer"` + // Tokens referencing a Person resource and it's associated account. + RelatedPerson *IdentityVerificationSessionCreateRelatedPersonParams `form:"related_person"` + // The URL that the user will be redirected to upon completing the verification flow. + ReturnURL *string `form:"return_url"` + // The type of [verification check](https://stripe.com/docs/identity/verification-checks) to be performed. You must provide a `type` if not passing `verification_flow`. + Type *string `form:"type"` + // The ID of a verification flow from the Dashboard. See https://docs.stripe.com/identity/verification-flows. + VerificationFlow *string `form:"verification_flow"` +} + +// AddExpand appends a new field to expand. +func (p *IdentityVerificationSessionCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IdentityVerificationSessionCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the details of a VerificationSession that was previously created. +// +// When the session status is requires_input, you can use this method to retrieve a valid +// client_secret or url to allow re-submission. +type IdentityVerificationSessionRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *IdentityVerificationSessionRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Options that apply to the [document check](https://stripe.com/docs/identity/verification-checks?type=document). +type IdentityVerificationSessionUpdateOptionsDocumentParams struct { + // Array of strings of allowed identity document types. If the provided identity document isn't one of the allowed types, the verification check will fail with a document_type_not_allowed error code. + AllowedTypes []*string `form:"allowed_types"` + // Collect an ID number and perform an [ID number check](https://stripe.com/docs/identity/verification-checks?type=id-number) with the document's extracted name and date of birth. + RequireIDNumber *bool `form:"require_id_number"` + // Disable image uploads, identity document images have to be captured using the device's camera. + RequireLiveCapture *bool `form:"require_live_capture"` + // Capture a face image and perform a [selfie check](https://stripe.com/docs/identity/verification-checks?type=selfie) comparing a photo ID and a picture of your user's face. [Learn more](https://stripe.com/docs/identity/selfie). + RequireMatchingSelfie *bool `form:"require_matching_selfie"` +} + +// A set of options for the session's verification checks. +type IdentityVerificationSessionUpdateOptionsParams struct { + // Options that apply to the [document check](https://stripe.com/docs/identity/verification-checks?type=document). + Document *IdentityVerificationSessionUpdateOptionsDocumentParams `form:"document"` +} + +// Details provided about the user being verified. These details may be shown to the user. +type IdentityVerificationSessionUpdateProvidedDetailsParams struct { + // Email of user being verified + Email *string `form:"email"` + // Phone number of user being verified + Phone *string `form:"phone"` +} + +// Updates a VerificationSession object. +// +// When the session status is requires_input, you can use this method to update the +// verification check and options. +type IdentityVerificationSessionUpdateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // A set of options for the session's verification checks. + Options *IdentityVerificationSessionUpdateOptionsParams `form:"options"` + // Details provided about the user being verified. These details may be shown to the user. + ProvidedDetails *IdentityVerificationSessionUpdateProvidedDetailsParams `form:"provided_details"` + // The type of [verification check](https://stripe.com/docs/identity/verification-checks) to be performed. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *IdentityVerificationSessionUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IdentityVerificationSessionUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// If present, this property tells you the last error encountered when processing the verification. +type IdentityVerificationSessionLastError struct { + // A short machine-readable string giving the reason for the verification or user-session failure. + Code IdentityVerificationSessionLastErrorCode `json:"code"` + // A message that explains the reason for verification or user-session failure. + Reason string `json:"reason"` +} +type IdentityVerificationSessionOptionsDocument struct { + // Array of strings of allowed identity document types. If the provided identity document isn't one of the allowed types, the verification check will fail with a document_type_not_allowed error code. + AllowedTypes []IdentityVerificationSessionOptionsDocumentAllowedType `json:"allowed_types"` + // Collect an ID number and perform an [ID number check](https://stripe.com/docs/identity/verification-checks?type=id-number) with the document's extracted name and date of birth. + RequireIDNumber bool `json:"require_id_number"` + // Disable image uploads, identity document images have to be captured using the device's camera. + RequireLiveCapture bool `json:"require_live_capture"` + // Capture a face image and perform a [selfie check](https://stripe.com/docs/identity/verification-checks?type=selfie) comparing a photo ID and a picture of your user's face. [Learn more](https://stripe.com/docs/identity/selfie). + RequireMatchingSelfie bool `json:"require_matching_selfie"` +} +type IdentityVerificationSessionOptionsEmail struct { + // Request one time password verification of `provided_details.email`. + RequireVerification bool `json:"require_verification"` +} +type IdentityVerificationSessionOptionsIDNumber struct{} +type IdentityVerificationSessionOptionsMatching struct { + // Strictness of the DOB matching policy to apply. + DOB IdentityVerificationSessionOptionsMatchingDOB `json:"dob"` + // Strictness of the name matching policy to apply. + Name IdentityVerificationSessionOptionsMatchingName `json:"name"` +} +type IdentityVerificationSessionOptionsPhone struct { + // Request one time password verification of `provided_details.phone`. + RequireVerification bool `json:"require_verification"` +} + +// A set of options for the session's verification checks. +type IdentityVerificationSessionOptions struct { + Document *IdentityVerificationSessionOptionsDocument `json:"document"` + Email *IdentityVerificationSessionOptionsEmail `json:"email"` + IDNumber *IdentityVerificationSessionOptionsIDNumber `json:"id_number"` + Matching *IdentityVerificationSessionOptionsMatching `json:"matching"` + Phone *IdentityVerificationSessionOptionsPhone `json:"phone"` +} + +// Details provided about the user being verified. These details may be shown to the user. +type IdentityVerificationSessionProvidedDetails struct { + // Email of user being verified + Email string `json:"email"` + // Phone number of user being verified + Phone string `json:"phone"` +} + +// Redaction status of this VerificationSession. If the VerificationSession is not redacted, this field will be null. +type IdentityVerificationSessionRedaction struct { + // Indicates whether this object and its related objects have been redacted or not. + Status IdentityVerificationSessionRedactionStatus `json:"status"` +} +type IdentityVerificationSessionRelatedPerson struct { + // Token referencing the associated Account of the related Person resource. + Account string `json:"account"` + // Token referencing the related Person resource. + Person string `json:"person"` +} + +// The user's verified date of birth. +type IdentityVerificationSessionVerifiedOutputsDOB struct { + // Numerical day between 1 and 31. + Day int64 `json:"day"` + // Numerical month between 1 and 12. + Month int64 `json:"month"` + // The four-digit year. + Year int64 `json:"year"` +} + +// The user's verified data. +type IdentityVerificationSessionVerifiedOutputs struct { + // The user's verified address. + Address *Address `json:"address"` + // The user's verified date of birth. + DOB *IdentityVerificationSessionVerifiedOutputsDOB `json:"dob"` + // The user's verified email address + Email string `json:"email"` + // The user's verified first name. + FirstName string `json:"first_name"` + // The user's verified id number. + IDNumber string `json:"id_number"` + // The user's verified id number type. + IDNumberType IdentityVerificationSessionVerifiedOutputsIDNumberType `json:"id_number_type"` + // The user's verified last name. + LastName string `json:"last_name"` + // The user's verified phone number + Phone string `json:"phone"` + // The user's verified sex. + Sex IdentityVerificationSessionVerifiedOutputsSex `json:"sex"` + // The user's verified place of birth as it appears in the document. + UnparsedPlaceOfBirth string `json:"unparsed_place_of_birth"` + // The user's verified sex as it appears in the document. + UnparsedSex string `json:"unparsed_sex"` +} + +// A VerificationSession guides you through the process of collecting and verifying the identities +// of your users. It contains details about the type of verification, such as what [verification +// check](https://docs.stripe.com/docs/identity/verification-checks) to perform. Only create one VerificationSession for +// each verification in your system. +// +// A VerificationSession transitions through [multiple +// statuses](https://docs.stripe.com/docs/identity/how-sessions-work) throughout its lifetime as it progresses through +// the verification flow. The VerificationSession contains the user's verified data after +// verification checks are complete. +// +// Related guide: [The Verification Sessions API](https://stripe.com/docs/identity/verification-sessions) +type IdentityVerificationSession struct { + APIResource + // A string to reference this user. This can be a customer ID, a session ID, or similar, and can be used to reconcile this verification with your internal systems. + ClientReferenceID string `json:"client_reference_id"` + // The short-lived client secret used by Stripe.js to [show a verification modal](https://stripe.com/docs/js/identity/modal) inside your app. This client secret expires after 24 hours and can only be used once. Don't store it, log it, embed it in a URL, or expose it to anyone other than the user. Make sure that you have TLS enabled on any page that includes the client secret. Refer to our docs on [passing the client secret to the frontend](https://stripe.com/docs/identity/verification-sessions#client-secret) to learn more. + ClientSecret string `json:"client_secret"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Unique identifier for the object. + ID string `json:"id"` + // If present, this property tells you the last error encountered when processing the verification. + LastError *IdentityVerificationSessionLastError `json:"last_error"` + // ID of the most recent VerificationReport. [Learn more about accessing detailed verification results.](https://stripe.com/docs/identity/verification-sessions#results) + LastVerificationReport *IdentityVerificationReport `json:"last_verification_report"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // A set of options for the session's verification checks. + Options *IdentityVerificationSessionOptions `json:"options"` + // Details provided about the user being verified. These details may be shown to the user. + ProvidedDetails *IdentityVerificationSessionProvidedDetails `json:"provided_details"` + // Redaction status of this VerificationSession. If the VerificationSession is not redacted, this field will be null. + Redaction *IdentityVerificationSessionRedaction `json:"redaction"` + // Customer ID + RelatedCustomer string `json:"related_customer"` + RelatedPerson *IdentityVerificationSessionRelatedPerson `json:"related_person"` + // Status of this VerificationSession. [Learn more about the lifecycle of sessions](https://stripe.com/docs/identity/how-sessions-work). + Status IdentityVerificationSessionStatus `json:"status"` + // The type of [verification check](https://stripe.com/docs/identity/verification-checks) to be performed. + Type IdentityVerificationSessionType `json:"type"` + // The short-lived URL that you use to redirect a user to Stripe to submit their identity information. This URL expires after 48 hours and can only be used once. Don't store it, log it, send it in emails or expose it to anyone other than the user. Refer to our docs on [verifying identity documents](https://stripe.com/docs/identity/verify-identity-documents?platform=web&type=redirect) to learn how to redirect users to Stripe. + URL string `json:"url"` + // The configuration token of a verification flow from the dashboard. + VerificationFlow string `json:"verification_flow"` + // The user's verified data. + VerifiedOutputs *IdentityVerificationSessionVerifiedOutputs `json:"verified_outputs"` +} + +// IdentityVerificationSessionList is a list of VerificationSessions as retrieved from a list endpoint. +type IdentityVerificationSessionList struct { + APIResource + ListMeta + Data []*IdentityVerificationSession `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/identity_verificationsession_service.go b/vendor/github.com/stripe/stripe-go/v82/identity_verificationsession_service.go new file mode 100644 index 00000000..a1fb7efe --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/identity_verificationsession_service.go @@ -0,0 +1,129 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1IdentityVerificationSessionService is used to invoke /v1/identity/verification_sessions APIs. +type v1IdentityVerificationSessionService struct { + B Backend + Key string +} + +// Creates a VerificationSession object. +// +// After the VerificationSession is created, display a verification modal using the session client_secret or send your users to the session's url. +// +// If your API key is in test mode, verification checks won't actually process, though everything else will occur as if in live mode. +// +// Related guide: [Verify your users' identity documents](https://docs.stripe.com/docs/identity/verify-identity-documents) +func (c v1IdentityVerificationSessionService) Create(ctx context.Context, params *IdentityVerificationSessionCreateParams) (*IdentityVerificationSession, error) { + if params == nil { + params = &IdentityVerificationSessionCreateParams{} + } + params.Context = ctx + verificationsession := &IdentityVerificationSession{} + err := c.B.Call( + http.MethodPost, "/v1/identity/verification_sessions", c.Key, params, verificationsession) + return verificationsession, err +} + +// Retrieves the details of a VerificationSession that was previously created. +// +// When the session status is requires_input, you can use this method to retrieve a valid +// client_secret or url to allow re-submission. +func (c v1IdentityVerificationSessionService) Retrieve(ctx context.Context, id string, params *IdentityVerificationSessionRetrieveParams) (*IdentityVerificationSession, error) { + if params == nil { + params = &IdentityVerificationSessionRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/identity/verification_sessions/%s", id) + verificationsession := &IdentityVerificationSession{} + err := c.B.Call(http.MethodGet, path, c.Key, params, verificationsession) + return verificationsession, err +} + +// Updates a VerificationSession object. +// +// When the session status is requires_input, you can use this method to update the +// verification check and options. +func (c v1IdentityVerificationSessionService) Update(ctx context.Context, id string, params *IdentityVerificationSessionUpdateParams) (*IdentityVerificationSession, error) { + if params == nil { + params = &IdentityVerificationSessionUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/identity/verification_sessions/%s", id) + verificationsession := &IdentityVerificationSession{} + err := c.B.Call(http.MethodPost, path, c.Key, params, verificationsession) + return verificationsession, err +} + +// A VerificationSession object can be canceled when it is in requires_input [status](https://docs.stripe.com/docs/identity/how-sessions-work). +// +// Once canceled, future submission attempts are disabled. This cannot be undone. [Learn more](https://docs.stripe.com/docs/identity/verification-sessions#cancel). +func (c v1IdentityVerificationSessionService) Cancel(ctx context.Context, id string, params *IdentityVerificationSessionCancelParams) (*IdentityVerificationSession, error) { + if params == nil { + params = &IdentityVerificationSessionCancelParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/identity/verification_sessions/%s/cancel", id) + verificationsession := &IdentityVerificationSession{} + err := c.B.Call(http.MethodPost, path, c.Key, params, verificationsession) + return verificationsession, err +} + +// Redact a VerificationSession to remove all collected information from Stripe. This will redact +// the VerificationSession and all objects related to it, including VerificationReports, Events, +// request logs, etc. +// +// A VerificationSession object can be redacted when it is in requires_input or verified +// [status](https://docs.stripe.com/docs/identity/how-sessions-work). Redacting a VerificationSession in requires_action +// state will automatically cancel it. +// +// The redaction process may take up to four days. When the redaction process is in progress, the +// VerificationSession's redaction.status field will be set to processing; when the process is +// finished, it will change to redacted and an identity.verification_session.redacted event +// will be emitted. +// +// Redaction is irreversible. Redacted objects are still accessible in the Stripe API, but all the +// fields that contain personal data will be replaced by the string [redacted] or a similar +// placeholder. The metadata field will also be erased. Redacted objects cannot be updated or +// used for any purpose. +// +// [Learn more](https://docs.stripe.com/docs/identity/verification-sessions#redact). +func (c v1IdentityVerificationSessionService) Redact(ctx context.Context, id string, params *IdentityVerificationSessionRedactParams) (*IdentityVerificationSession, error) { + if params == nil { + params = &IdentityVerificationSessionRedactParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/identity/verification_sessions/%s/redact", id) + verificationsession := &IdentityVerificationSession{} + err := c.B.Call(http.MethodPost, path, c.Key, params, verificationsession) + return verificationsession, err +} + +// Returns a list of VerificationSessions +func (c v1IdentityVerificationSessionService) List(ctx context.Context, listParams *IdentityVerificationSessionListParams) Seq2[*IdentityVerificationSession, error] { + if listParams == nil { + listParams = &IdentityVerificationSessionListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*IdentityVerificationSession, ListContainer, error) { + list := &IdentityVerificationSessionList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/identity/verification_sessions", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/invoice.go b/vendor/github.com/stripe/stripe-go/v82/invoice.go new file mode 100644 index 00000000..f43be76c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/invoice.go @@ -0,0 +1,3033 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "encoding/json" + "github.com/stripe/stripe-go/v82/form" +) + +// If Stripe disabled automatic tax, this enum describes why. +type InvoiceAutomaticTaxDisabledReason string + +// List of values that InvoiceAutomaticTaxDisabledReason can take +const ( + InvoiceAutomaticTaxDisabledReasonFinalizationRequiresLocationInputs InvoiceAutomaticTaxDisabledReason = "finalization_requires_location_inputs" + InvoiceAutomaticTaxDisabledReasonFinalizationSystemError InvoiceAutomaticTaxDisabledReason = "finalization_system_error" +) + +// Type of the account referenced. +type InvoiceAutomaticTaxLiabilityType string + +// List of values that InvoiceAutomaticTaxLiabilityType can take +const ( + InvoiceAutomaticTaxLiabilityTypeAccount InvoiceAutomaticTaxLiabilityType = "account" + InvoiceAutomaticTaxLiabilityTypeSelf InvoiceAutomaticTaxLiabilityType = "self" +) + +// The status of the most recent automated tax calculation for this invoice. +type InvoiceAutomaticTaxStatus string + +// List of values that InvoiceAutomaticTaxStatus can take +const ( + InvoiceAutomaticTaxStatusComplete InvoiceAutomaticTaxStatus = "complete" + InvoiceAutomaticTaxStatusFailed InvoiceAutomaticTaxStatus = "failed" + InvoiceAutomaticTaxStatusRequiresLocationInputs InvoiceAutomaticTaxStatus = "requires_location_inputs" +) + +// Indicates the reason why the invoice was created. +// +// * `manual`: Unrelated to a subscription, for example, created via the invoice editor. +// * `subscription`: No longer in use. Applies to subscriptions from before May 2018 where no distinction was made between updates, cycles, and thresholds. +// * `subscription_create`: A new subscription was created. +// * `subscription_cycle`: A subscription advanced into a new period. +// * `subscription_threshold`: A subscription reached a billing threshold. +// * `subscription_update`: A subscription was updated. +// * `upcoming`: Reserved for simulated invoices, per the upcoming invoice endpoint. +type InvoiceBillingReason string + +// List of values that InvoiceBillingReason can take +const ( + InvoiceBillingReasonAutomaticPendingInvoiceItemInvoice InvoiceBillingReason = "automatic_pending_invoice_item_invoice" + InvoiceBillingReasonManual InvoiceBillingReason = "manual" + InvoiceBillingReasonQuoteAccept InvoiceBillingReason = "quote_accept" + InvoiceBillingReasonSubscription InvoiceBillingReason = "subscription" + InvoiceBillingReasonSubscriptionCreate InvoiceBillingReason = "subscription_create" + InvoiceBillingReasonSubscriptionCycle InvoiceBillingReason = "subscription_cycle" + InvoiceBillingReasonSubscriptionThreshold InvoiceBillingReason = "subscription_threshold" + InvoiceBillingReasonSubscriptionUpdate InvoiceBillingReason = "subscription_update" + InvoiceBillingReasonUpcoming InvoiceBillingReason = "upcoming" +) + +// Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay this invoice using the default source attached to the customer. When sending an invoice, Stripe will email this invoice to the customer with payment instructions. +type InvoiceCollectionMethod string + +// List of values that InvoiceCollectionMethod can take +const ( + InvoiceCollectionMethodChargeAutomatically InvoiceCollectionMethod = "charge_automatically" + InvoiceCollectionMethodSendInvoice InvoiceCollectionMethod = "send_invoice" +) + +// Type of the account referenced. +type InvoiceIssuerType string + +// List of values that InvoiceIssuerType can take +const ( + InvoiceIssuerTypeAccount InvoiceIssuerType = "account" + InvoiceIssuerTypeSelf InvoiceIssuerType = "self" +) + +// The type of parent that generated this invoice +type InvoiceParentType string + +// List of values that InvoiceParentType can take +const ( + InvoiceParentTypeQuoteDetails InvoiceParentType = "quote_details" + InvoiceParentTypeSubscriptionDetails InvoiceParentType = "subscription_details" +) + +// Transaction type of the mandate. +type InvoicePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsTransactionType string + +// List of values that InvoicePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsTransactionType can take +const ( + InvoicePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsTransactionTypeBusiness InvoicePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsTransactionType = "business" + InvoicePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsTransactionTypePersonal InvoicePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsTransactionType = "personal" +) + +// Bank account verification method. +type InvoicePaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethod string + +// List of values that InvoicePaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethod can take +const ( + InvoicePaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethodAutomatic InvoicePaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethod = "automatic" + InvoicePaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethodInstant InvoicePaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethod = "instant" + InvoicePaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethodMicrodeposits InvoicePaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethod = "microdeposits" +) + +// We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. +type InvoicePaymentSettingsPaymentMethodOptionsCardRequestThreeDSecure string + +// List of values that InvoicePaymentSettingsPaymentMethodOptionsCardRequestThreeDSecure can take +const ( + InvoicePaymentSettingsPaymentMethodOptionsCardRequestThreeDSecureAny InvoicePaymentSettingsPaymentMethodOptionsCardRequestThreeDSecure = "any" + InvoicePaymentSettingsPaymentMethodOptionsCardRequestThreeDSecureAutomatic InvoicePaymentSettingsPaymentMethodOptionsCardRequestThreeDSecure = "automatic" + InvoicePaymentSettingsPaymentMethodOptionsCardRequestThreeDSecureChallenge InvoicePaymentSettingsPaymentMethodOptionsCardRequestThreeDSecure = "challenge" +) + +// The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. +type InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceFundingType string + +// List of values that InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceFundingType can take +const ( + InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceFundingTypeBankTransfer InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceFundingType = "bank_transfer" +) + +// The account subcategories to use to filter for possible accounts to link. Valid subcategories are `checking` and `savings`. +type InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory string + +// List of values that InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory can take +const ( + InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategoryChecking InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory = "checking" + InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategorySavings InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory = "savings" +) + +// The list of permissions to request. The `payment_method` permission must be included. +type InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission string + +// List of values that InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission can take +const ( + InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionBalances InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "balances" + InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionOwnership InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "ownership" + InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionPaymentMethod InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "payment_method" + InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionTransactions InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "transactions" +) + +// Data features requested to be retrieved upon account creation. +type InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch string + +// List of values that InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch can take +const ( + InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchBalances InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "balances" + InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchOwnership InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "ownership" + InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchTransactions InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "transactions" +) + +// Bank account verification method. +type InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethod string + +// List of values that InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethod can take +const ( + InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethodAutomatic InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethod = "automatic" + InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethodInstant InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethod = "instant" + InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethodMicrodeposits InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethod = "microdeposits" +) + +// The list of payment method types (e.g. card) to provide to the invoice's PaymentIntent. If not set, Stripe attempts to automatically determine the types to use by looking at the invoice's default payment method, the subscription's default payment method, the customer's default payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). +type InvoicePaymentSettingsPaymentMethodType string + +// List of values that InvoicePaymentSettingsPaymentMethodType can take +const ( + InvoicePaymentSettingsPaymentMethodTypeACHCreditTransfer InvoicePaymentSettingsPaymentMethodType = "ach_credit_transfer" + InvoicePaymentSettingsPaymentMethodTypeACHDebit InvoicePaymentSettingsPaymentMethodType = "ach_debit" + InvoicePaymentSettingsPaymentMethodTypeACSSDebit InvoicePaymentSettingsPaymentMethodType = "acss_debit" + InvoicePaymentSettingsPaymentMethodTypeAffirm InvoicePaymentSettingsPaymentMethodType = "affirm" + InvoicePaymentSettingsPaymentMethodTypeAmazonPay InvoicePaymentSettingsPaymentMethodType = "amazon_pay" + InvoicePaymentSettingsPaymentMethodTypeAUBECSDebit InvoicePaymentSettingsPaymentMethodType = "au_becs_debit" + InvoicePaymentSettingsPaymentMethodTypeBACSDebit InvoicePaymentSettingsPaymentMethodType = "bacs_debit" + InvoicePaymentSettingsPaymentMethodTypeBancontact InvoicePaymentSettingsPaymentMethodType = "bancontact" + InvoicePaymentSettingsPaymentMethodTypeBoleto InvoicePaymentSettingsPaymentMethodType = "boleto" + InvoicePaymentSettingsPaymentMethodTypeCard InvoicePaymentSettingsPaymentMethodType = "card" + InvoicePaymentSettingsPaymentMethodTypeCashApp InvoicePaymentSettingsPaymentMethodType = "cashapp" + InvoicePaymentSettingsPaymentMethodTypeCrypto InvoicePaymentSettingsPaymentMethodType = "crypto" + InvoicePaymentSettingsPaymentMethodTypeCustomerBalance InvoicePaymentSettingsPaymentMethodType = "customer_balance" + InvoicePaymentSettingsPaymentMethodTypeEPS InvoicePaymentSettingsPaymentMethodType = "eps" + InvoicePaymentSettingsPaymentMethodTypeFPX InvoicePaymentSettingsPaymentMethodType = "fpx" + InvoicePaymentSettingsPaymentMethodTypeGiropay InvoicePaymentSettingsPaymentMethodType = "giropay" + InvoicePaymentSettingsPaymentMethodTypeGrabpay InvoicePaymentSettingsPaymentMethodType = "grabpay" + InvoicePaymentSettingsPaymentMethodTypeIDEAL InvoicePaymentSettingsPaymentMethodType = "ideal" + InvoicePaymentSettingsPaymentMethodTypeJPCreditTransfer InvoicePaymentSettingsPaymentMethodType = "jp_credit_transfer" + InvoicePaymentSettingsPaymentMethodTypeKakaoPay InvoicePaymentSettingsPaymentMethodType = "kakao_pay" + InvoicePaymentSettingsPaymentMethodTypeKlarna InvoicePaymentSettingsPaymentMethodType = "klarna" + InvoicePaymentSettingsPaymentMethodTypeKonbini InvoicePaymentSettingsPaymentMethodType = "konbini" + InvoicePaymentSettingsPaymentMethodTypeKrCard InvoicePaymentSettingsPaymentMethodType = "kr_card" + InvoicePaymentSettingsPaymentMethodTypeLink InvoicePaymentSettingsPaymentMethodType = "link" + InvoicePaymentSettingsPaymentMethodTypeMultibanco InvoicePaymentSettingsPaymentMethodType = "multibanco" + InvoicePaymentSettingsPaymentMethodTypeNaverPay InvoicePaymentSettingsPaymentMethodType = "naver_pay" + InvoicePaymentSettingsPaymentMethodTypeNzBankAccount InvoicePaymentSettingsPaymentMethodType = "nz_bank_account" + InvoicePaymentSettingsPaymentMethodTypeP24 InvoicePaymentSettingsPaymentMethodType = "p24" + InvoicePaymentSettingsPaymentMethodTypePayco InvoicePaymentSettingsPaymentMethodType = "payco" + InvoicePaymentSettingsPaymentMethodTypePayNow InvoicePaymentSettingsPaymentMethodType = "paynow" + InvoicePaymentSettingsPaymentMethodTypePaypal InvoicePaymentSettingsPaymentMethodType = "paypal" + InvoicePaymentSettingsPaymentMethodTypePromptPay InvoicePaymentSettingsPaymentMethodType = "promptpay" + InvoicePaymentSettingsPaymentMethodTypeRevolutPay InvoicePaymentSettingsPaymentMethodType = "revolut_pay" + InvoicePaymentSettingsPaymentMethodTypeSEPACreditTransfer InvoicePaymentSettingsPaymentMethodType = "sepa_credit_transfer" + InvoicePaymentSettingsPaymentMethodTypeSEPADebit InvoicePaymentSettingsPaymentMethodType = "sepa_debit" + InvoicePaymentSettingsPaymentMethodTypeSofort InvoicePaymentSettingsPaymentMethodType = "sofort" + InvoicePaymentSettingsPaymentMethodTypeSwish InvoicePaymentSettingsPaymentMethodType = "swish" + InvoicePaymentSettingsPaymentMethodTypeUSBankAccount InvoicePaymentSettingsPaymentMethodType = "us_bank_account" + InvoicePaymentSettingsPaymentMethodTypeWeChatPay InvoicePaymentSettingsPaymentMethodType = "wechat_pay" +) + +// Page size of invoice pdf. Options include a4, letter, and auto. If set to auto, page size will be switched to a4 or letter based on customer locale. +type InvoiceRenderingPDFPageSize string + +// List of values that InvoiceRenderingPDFPageSize can take +const ( + InvoiceRenderingPDFPageSizeA4 InvoiceRenderingPDFPageSize = "a4" + InvoiceRenderingPDFPageSizeAuto InvoiceRenderingPDFPageSize = "auto" + InvoiceRenderingPDFPageSizeLetter InvoiceRenderingPDFPageSize = "letter" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type InvoiceShippingCostTaxTaxabilityReason string + +// List of values that InvoiceShippingCostTaxTaxabilityReason can take +const ( + InvoiceShippingCostTaxTaxabilityReasonCustomerExempt InvoiceShippingCostTaxTaxabilityReason = "customer_exempt" + InvoiceShippingCostTaxTaxabilityReasonNotCollecting InvoiceShippingCostTaxTaxabilityReason = "not_collecting" + InvoiceShippingCostTaxTaxabilityReasonNotSubjectToTax InvoiceShippingCostTaxTaxabilityReason = "not_subject_to_tax" + InvoiceShippingCostTaxTaxabilityReasonNotSupported InvoiceShippingCostTaxTaxabilityReason = "not_supported" + InvoiceShippingCostTaxTaxabilityReasonPortionProductExempt InvoiceShippingCostTaxTaxabilityReason = "portion_product_exempt" + InvoiceShippingCostTaxTaxabilityReasonPortionReducedRated InvoiceShippingCostTaxTaxabilityReason = "portion_reduced_rated" + InvoiceShippingCostTaxTaxabilityReasonPortionStandardRated InvoiceShippingCostTaxTaxabilityReason = "portion_standard_rated" + InvoiceShippingCostTaxTaxabilityReasonProductExempt InvoiceShippingCostTaxTaxabilityReason = "product_exempt" + InvoiceShippingCostTaxTaxabilityReasonProductExemptHoliday InvoiceShippingCostTaxTaxabilityReason = "product_exempt_holiday" + InvoiceShippingCostTaxTaxabilityReasonProportionallyRated InvoiceShippingCostTaxTaxabilityReason = "proportionally_rated" + InvoiceShippingCostTaxTaxabilityReasonReducedRated InvoiceShippingCostTaxTaxabilityReason = "reduced_rated" + InvoiceShippingCostTaxTaxabilityReasonReverseCharge InvoiceShippingCostTaxTaxabilityReason = "reverse_charge" + InvoiceShippingCostTaxTaxabilityReasonStandardRated InvoiceShippingCostTaxTaxabilityReason = "standard_rated" + InvoiceShippingCostTaxTaxabilityReasonTaxableBasisReduced InvoiceShippingCostTaxTaxabilityReason = "taxable_basis_reduced" + InvoiceShippingCostTaxTaxabilityReasonZeroRated InvoiceShippingCostTaxTaxabilityReason = "zero_rated" +) + +// The status of the invoice, one of `draft`, `open`, `paid`, `uncollectible`, or `void`. [Learn more](https://stripe.com/docs/billing/invoices/workflow#workflow-overview) +type InvoiceStatus string + +// List of values that InvoiceStatus can take +const ( + InvoiceStatusDraft InvoiceStatus = "draft" + InvoiceStatusOpen InvoiceStatus = "open" + InvoiceStatusPaid InvoiceStatus = "paid" + InvoiceStatusUncollectible InvoiceStatus = "uncollectible" + InvoiceStatusVoid InvoiceStatus = "void" +) + +// Type of the pretax credit amount referenced. +type InvoiceTotalPretaxCreditAmountType string + +// List of values that InvoiceTotalPretaxCreditAmountType can take +const ( + InvoiceTotalPretaxCreditAmountTypeCreditBalanceTransaction InvoiceTotalPretaxCreditAmountType = "credit_balance_transaction" + InvoiceTotalPretaxCreditAmountTypeDiscount InvoiceTotalPretaxCreditAmountType = "discount" +) + +// Whether this tax is inclusive or exclusive. +type InvoiceTotalTaxTaxBehavior string + +// List of values that InvoiceTotalTaxTaxBehavior can take +const ( + InvoiceTotalTaxTaxBehaviorExclusive InvoiceTotalTaxTaxBehavior = "exclusive" + InvoiceTotalTaxTaxBehaviorInclusive InvoiceTotalTaxTaxBehavior = "inclusive" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type InvoiceTotalTaxTaxabilityReason string + +// List of values that InvoiceTotalTaxTaxabilityReason can take +const ( + InvoiceTotalTaxTaxabilityReasonCustomerExempt InvoiceTotalTaxTaxabilityReason = "customer_exempt" + InvoiceTotalTaxTaxabilityReasonNotAvailable InvoiceTotalTaxTaxabilityReason = "not_available" + InvoiceTotalTaxTaxabilityReasonNotCollecting InvoiceTotalTaxTaxabilityReason = "not_collecting" + InvoiceTotalTaxTaxabilityReasonNotSubjectToTax InvoiceTotalTaxTaxabilityReason = "not_subject_to_tax" + InvoiceTotalTaxTaxabilityReasonNotSupported InvoiceTotalTaxTaxabilityReason = "not_supported" + InvoiceTotalTaxTaxabilityReasonPortionProductExempt InvoiceTotalTaxTaxabilityReason = "portion_product_exempt" + InvoiceTotalTaxTaxabilityReasonPortionReducedRated InvoiceTotalTaxTaxabilityReason = "portion_reduced_rated" + InvoiceTotalTaxTaxabilityReasonPortionStandardRated InvoiceTotalTaxTaxabilityReason = "portion_standard_rated" + InvoiceTotalTaxTaxabilityReasonProductExempt InvoiceTotalTaxTaxabilityReason = "product_exempt" + InvoiceTotalTaxTaxabilityReasonProductExemptHoliday InvoiceTotalTaxTaxabilityReason = "product_exempt_holiday" + InvoiceTotalTaxTaxabilityReasonProportionallyRated InvoiceTotalTaxTaxabilityReason = "proportionally_rated" + InvoiceTotalTaxTaxabilityReasonReducedRated InvoiceTotalTaxTaxabilityReason = "reduced_rated" + InvoiceTotalTaxTaxabilityReasonReverseCharge InvoiceTotalTaxTaxabilityReason = "reverse_charge" + InvoiceTotalTaxTaxabilityReasonStandardRated InvoiceTotalTaxTaxabilityReason = "standard_rated" + InvoiceTotalTaxTaxabilityReasonTaxableBasisReduced InvoiceTotalTaxTaxabilityReason = "taxable_basis_reduced" + InvoiceTotalTaxTaxabilityReasonZeroRated InvoiceTotalTaxTaxabilityReason = "zero_rated" +) + +// The type of tax information. +type InvoiceTotalTaxType string + +// List of values that InvoiceTotalTaxType can take +const ( + InvoiceTotalTaxTypeTaxRateDetails InvoiceTotalTaxType = "tax_rate_details" +) + +// Permanently deletes a one-off invoice draft. This cannot be undone. Attempts to delete invoices that are no longer in a draft state will fail; once an invoice has been finalized or if an invoice is for a subscription, it must be [voided](https://docs.stripe.com/api#void_invoice). +type InvoiceParams struct { + Params `form:"*"` + // The account tax IDs associated with the invoice. Only editable when the invoice is a draft. + AccountTaxIDs []*string `form:"account_tax_ids"` + // A fee in cents (or local equivalent) that will be applied to the invoice and transferred to the application owner's Stripe account. The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. For more information, see the application fees [documentation](https://stripe.com/docs/billing/invoices/connect#collecting-fees). + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // Controls whether Stripe performs [automatic collection](https://stripe.com/docs/invoicing/integration/automatic-advancement-collection) of the invoice. If `false`, the invoice's state doesn't automatically advance without an explicit action. + AutoAdvance *bool `form:"auto_advance"` + // The time when this invoice should be scheduled to finalize. The invoice will be finalized at this time if it is still in draft state. To turn off automatic finalization, set `auto_advance` to false. + AutomaticallyFinalizesAt *int64 `form:"automatically_finalizes_at"` + // Settings for automatic tax lookup for this invoice. + AutomaticTax *InvoiceAutomaticTaxParams `form:"automatic_tax"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay this invoice using the default source attached to the customer. When sending an invoice, Stripe will email this invoice to the customer with payment instructions. Defaults to `charge_automatically`. + CollectionMethod *string `form:"collection_method"` + // The currency to create this invoice in. Defaults to that of `customer` if not specified. + Currency *string `form:"currency"` + // The ID of the customer who will be billed. + Customer *string `form:"customer"` + // A list of up to 4 custom fields to be displayed on the invoice. If a value for `custom_fields` is specified, the list specified will replace the existing custom field list on this invoice. Pass an empty string to remove previously-defined fields. + CustomFields []*InvoiceCustomFieldParams `form:"custom_fields"` + // The number of days from which the invoice is created until it is due. Only valid for invoices where `collection_method=send_invoice`. This field can only be updated on `draft` invoices. + DaysUntilDue *int64 `form:"days_until_due"` + // ID of the default payment method for the invoice. It must belong to the customer associated with the invoice. If not set, defaults to the subscription's default payment method, if any, or to the default payment method in the customer's invoice settings. + DefaultPaymentMethod *string `form:"default_payment_method"` + // ID of the default payment source for the invoice. It must belong to the customer associated with the invoice and be in a chargeable state. If not set, defaults to the subscription's default source, if any, or to the customer's default source. + DefaultSource *string `form:"default_source"` + // The tax rates that will apply to any line item that does not have `tax_rates` set. Pass an empty string to remove previously-defined tax rates. + DefaultTaxRates []*string `form:"default_tax_rates"` + // An arbitrary string attached to the object. Often useful for displaying to users. Referenced as 'memo' in the Dashboard. + Description *string `form:"description"` + // The coupons and promotion codes to redeem into discounts for the invoice. If not specified, inherits the discount from the invoice's customer. Pass an empty string to avoid inheriting any discounts. + Discounts []*InvoiceDiscountParams `form:"discounts"` + // The date on which payment for this invoice is due. Only valid for invoices where `collection_method=send_invoice`. This field can only be updated on `draft` invoices. + DueDate *int64 `form:"due_date"` + // The date when this invoice is in effect. Same as `finalized_at` unless overwritten. When defined, this value replaces the system-generated 'Date of issue' printed on the invoice PDF and receipt. + EffectiveAt *int64 `form:"effective_at"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Footer to be displayed on the invoice. + Footer *string `form:"footer"` + // Revise an existing invoice. The new invoice will be created in `status=draft`. See the [revision documentation](https://stripe.com/docs/invoicing/invoice-revisions) for more details. + FromInvoice *InvoiceFromInvoiceParams `form:"from_invoice"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *InvoiceIssuerParams `form:"issuer"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Set the number for this invoice. If no number is present then a number will be assigned automatically when the invoice is finalized. In many markets, regulations require invoices to be unique, sequential and / or gapless. You are responsible for ensuring this is true across all your different invoicing systems in the event that you edit the invoice number using our API. If you use only Stripe for your invoices and do not change invoice numbers, Stripe handles this aspect of compliance for you automatically. + Number *string `form:"number"` + // The account (if any) for which the funds of the invoice payment are intended. If set, the invoice will be presented with the branding and support information of the specified account. See the [Invoices with Connect](https://stripe.com/docs/billing/invoices/connect) documentation for details. + OnBehalfOf *string `form:"on_behalf_of"` + // Configuration settings for the PaymentIntent that is generated when the invoice is finalized. + PaymentSettings *InvoicePaymentSettingsParams `form:"payment_settings"` + // How to handle pending invoice items on invoice creation. Defaults to `exclude` if the parameter is omitted. + PendingInvoiceItemsBehavior *string `form:"pending_invoice_items_behavior"` + // The rendering-related settings that control how the invoice is displayed on customer-facing surfaces such as PDF and Hosted Invoice Page. + Rendering *InvoiceRenderingParams `form:"rendering"` + // Settings for the cost of shipping for this invoice. + ShippingCost *InvoiceShippingCostParams `form:"shipping_cost"` + // Shipping details for the invoice. The Invoice PDF will use the `shipping_details` value if it is set, otherwise the PDF will render the shipping address from the customer. + ShippingDetails *InvoiceShippingDetailsParams `form:"shipping_details"` + // Extra information about a charge for the customer's credit card statement. It must contain at least one letter. If not specified and this invoice is part of a subscription, the default `statement_descriptor` will be set to the first subscription item's product's `statement_descriptor`. + StatementDescriptor *string `form:"statement_descriptor"` + // The ID of the subscription to invoice, if any. If set, the created invoice will only include pending invoice items for that subscription. The subscription's billing cycle and regular subscription events won't be affected. + Subscription *string `form:"subscription"` + // If specified, the funds from the invoice will be transferred to the destination and the ID of the resulting transfer will be found on the invoice's charge. This will be unset if you POST an empty value. + TransferData *InvoiceTransferDataParams `form:"transfer_data"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type InvoiceAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Settings for automatic tax lookup for this invoice. +type InvoiceAutomaticTaxParams struct { + // Whether Stripe automatically computes tax on this invoice. Note that incompatible invoice items (invoice items with manually specified [tax rates](https://stripe.com/docs/api/tax_rates), negative amounts, or `tax_behavior=unspecified`) cannot be added to automatic tax invoices. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *InvoiceAutomaticTaxLiabilityParams `form:"liability"` +} + +// A list of up to 4 custom fields to be displayed on the invoice. If a value for `custom_fields` is specified, the list specified will replace the existing custom field list on this invoice. Pass an empty string to remove previously-defined fields. +type InvoiceCustomFieldParams struct { + // The name of the custom field. This may be up to 40 characters. + Name *string `form:"name"` + // The value of the custom field. This may be up to 140 characters. + Value *string `form:"value"` +} + +// The discounts that will apply to the invoice. Pass an empty string to remove previously-defined discounts. +type InvoiceDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type InvoiceIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Additional fields for Mandate creation +type InvoicePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsParams struct { + // Transaction type of the mandate. + TransactionType *string `form:"transaction_type"` +} + +// If paying by `acss_debit`, this sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsACSSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *InvoicePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsParams `form:"mandate_options"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// If paying by `bancontact`, this sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsBancontactParams struct { + // Preferred language of the Bancontact authorization page that the customer is redirected to. + PreferredLanguage *string `form:"preferred_language"` +} + +// The selected installment plan to use for this invoice. +type InvoicePaymentSettingsPaymentMethodOptionsCardInstallmentsPlanParams struct { + // For `fixed_count` installment plans, this is required. It represents the number of installment payments your customer will make to their credit card. + Count *int64 `form:"count"` + // For `fixed_count` installment plans, this is required. It represents the interval between installment payments your customer will make to their credit card. + // One of `month`. + Interval *string `form:"interval"` + // Type of installment plan, one of `fixed_count`, `bonus`, or `revolving`. + Type *string `form:"type"` +} + +// Installment configuration for payments attempted on this invoice (Mexico Only). +// +// For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). +type InvoicePaymentSettingsPaymentMethodOptionsCardInstallmentsParams struct { + // Setting to true enables installments for this invoice. + // Setting to false will prevent any selected plan from applying to a payment. + Enabled *bool `form:"enabled"` + // The selected installment plan to use for this invoice. + Plan *InvoicePaymentSettingsPaymentMethodOptionsCardInstallmentsPlanParams `form:"plan"` +} + +// If paying by `card`, this sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsCardParams struct { + // Installment configuration for payments attempted on this invoice (Mexico Only). + // + // For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + Installments *InvoicePaymentSettingsPaymentMethodOptionsCardInstallmentsParams `form:"installments"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure *string `form:"request_three_d_secure"` +} + +// Configuration for eu_bank_transfer funding type. +type InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country *string `form:"country"` +} + +// Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. +type InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams struct { + // Configuration for eu_bank_transfer funding type. + EUBankTransfer *InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams `form:"eu_bank_transfer"` + // The bank transfer type that can be used for funding. Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + Type *string `form:"type"` +} + +// If paying by `customer_balance`, this sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceParams struct { + // Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + BankTransfer *InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams `form:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType *string `form:"funding_type"` +} + +// If paying by `konbini`, this sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsKonbiniParams struct{} + +// If paying by `sepa_debit`, this sub-hash contains details about the SEPA Direct Debit payment method options to pass to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsSEPADebitParams struct{} + +// Provide filters for the linked accounts that the customer can select for the payment method. +type InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams struct { + // The account subcategories to use to filter for selectable accounts. Valid subcategories are `checking` and `savings`. + AccountSubcategories []*string `form:"account_subcategories"` +} + +// Additional fields for Financial Connections Session creation +type InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsParams struct { + // Provide filters for the linked accounts that the customer can select for the payment method. + Filters *InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams `form:"filters"` + // The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` +} + +// If paying by `us_bank_account`, this sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountParams struct { + // Additional fields for Financial Connections Session creation + FinancialConnections *InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsParams `form:"financial_connections"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// Payment-method-specific configuration to provide to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsParams struct { + // If paying by `acss_debit`, this sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. + ACSSDebit *InvoicePaymentSettingsPaymentMethodOptionsACSSDebitParams `form:"acss_debit"` + // If paying by `bancontact`, this sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. + Bancontact *InvoicePaymentSettingsPaymentMethodOptionsBancontactParams `form:"bancontact"` + // If paying by `card`, this sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. + Card *InvoicePaymentSettingsPaymentMethodOptionsCardParams `form:"card"` + // If paying by `customer_balance`, this sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. + CustomerBalance *InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceParams `form:"customer_balance"` + // If paying by `konbini`, this sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. + Konbini *InvoicePaymentSettingsPaymentMethodOptionsKonbiniParams `form:"konbini"` + // If paying by `sepa_debit`, this sub-hash contains details about the SEPA Direct Debit payment method options to pass to the invoice's PaymentIntent. + SEPADebit *InvoicePaymentSettingsPaymentMethodOptionsSEPADebitParams `form:"sepa_debit"` + // If paying by `us_bank_account`, this sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. + USBankAccount *InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` +} + +// Configuration settings for the PaymentIntent that is generated when the invoice is finalized. +type InvoicePaymentSettingsParams struct { + // ID of the mandate to be used for this invoice. It must correspond to the payment method used to pay the invoice, including the invoice's default_payment_method or default_source, if set. + DefaultMandate *string `form:"default_mandate"` + // Payment-method-specific configuration to provide to the invoice's PaymentIntent. + PaymentMethodOptions *InvoicePaymentSettingsPaymentMethodOptionsParams `form:"payment_method_options"` + // The list of payment method types (e.g. card) to provide to the invoice's PaymentIntent. If not set, Stripe attempts to automatically determine the types to use by looking at the invoice's default payment method, the subscription's default payment method, the customer's default payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). Should not be specified with payment_method_configuration + PaymentMethodTypes []*string `form:"payment_method_types"` +} + +// Invoice pdf rendering options +type InvoiceRenderingPDFParams struct { + // Page size for invoice PDF. Can be set to `a4`, `letter`, or `auto`. + // If set to `auto`, invoice PDF page size defaults to `a4` for customers with + // Japanese locale and `letter` for customers with other locales. + PageSize *string `form:"page_size"` +} + +// The rendering-related settings that control how the invoice is displayed on customer-facing surfaces such as PDF and Hosted Invoice Page. +type InvoiceRenderingParams struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + AmountTaxDisplay *string `form:"amount_tax_display"` + // Invoice pdf rendering options + PDF *InvoiceRenderingPDFParams `form:"pdf"` + // ID of the invoice rendering template to use for this invoice. + Template *string `form:"template"` + // The specific version of invoice rendering template to use for this invoice. + TemplateVersion *int64 `form:"template_version"` +} + +// The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. +type InvoiceShippingCostShippingRateDataDeliveryEstimateMaximumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The lower bound of the estimated range. If empty, represents no lower bound. +type InvoiceShippingCostShippingRateDataDeliveryEstimateMinimumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. +type InvoiceShippingCostShippingRateDataDeliveryEstimateParams struct { + // The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. + Maximum *InvoiceShippingCostShippingRateDataDeliveryEstimateMaximumParams `form:"maximum"` + // The lower bound of the estimated range. If empty, represents no lower bound. + Minimum *InvoiceShippingCostShippingRateDataDeliveryEstimateMinimumParams `form:"minimum"` +} + +// Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type InvoiceShippingCostShippingRateDataFixedAmountCurrencyOptionsParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` +} + +// Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. +type InvoiceShippingCostShippingRateDataFixedAmountParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*InvoiceShippingCostShippingRateDataFixedAmountCurrencyOptionsParams `form:"currency_options"` +} + +// Parameters to create a new ad-hoc shipping rate for this order. +type InvoiceShippingCostShippingRateDataParams struct { + // The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. + DeliveryEstimate *InvoiceShippingCostShippingRateDataDeliveryEstimateParams `form:"delivery_estimate"` + // The name of the shipping rate, meant to be displayable to the customer. This will appear on CheckoutSessions. + DisplayName *string `form:"display_name"` + // Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. + FixedAmount *InvoiceShippingCostShippingRateDataFixedAmountParams `form:"fixed_amount"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. The Shipping tax code is `txcd_92010001`. + TaxCode *string `form:"tax_code"` + // The type of calculation to use on the shipping rate. + Type *string `form:"type"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceShippingCostShippingRateDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Settings for the cost of shipping for this invoice. +type InvoiceShippingCostParams struct { + // The ID of the shipping rate to use for this order. + ShippingRate *string `form:"shipping_rate"` + // Parameters to create a new ad-hoc shipping rate for this order. + ShippingRateData *InvoiceShippingCostShippingRateDataParams `form:"shipping_rate_data"` +} + +// Shipping details for the invoice. The Invoice PDF will use the `shipping_details` value if it is set, otherwise the PDF will render the shipping address from the customer. +type InvoiceShippingDetailsParams struct { + // Shipping address + Address *AddressParams `form:"address"` + // Recipient name. + Name *string `form:"name"` + // Recipient phone (including extension) + Phone *string `form:"phone"` +} + +// If specified, the funds from the invoice will be transferred to the destination and the ID of the resulting transfer will be found on the invoice's charge. This will be unset if you POST an empty value. +type InvoiceTransferDataParams struct { + // The amount that will be transferred automatically when the invoice is paid. If no amount is set, the full amount is transferred. + Amount *int64 `form:"amount"` + // ID of an existing, connected Stripe account. + Destination *string `form:"destination"` +} + +// You can list all invoices, or list the invoices for a specific customer. The invoices are returned sorted by creation date, with the most recently created invoices appearing first. +type InvoiceListParams struct { + ListParams `form:"*"` + // The collection method of the invoice to retrieve. Either `charge_automatically` or `send_invoice`. + CollectionMethod *string `form:"collection_method"` + // Only return invoices that were created during the given date interval. + Created *int64 `form:"created"` + // Only return invoices that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Only return invoices for the customer specified by this customer ID. + Customer *string `form:"customer"` + DueDate *int64 `form:"due_date"` + DueDateRange *RangeQueryParams `form:"due_date"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The status of the invoice, one of `draft`, `open`, `paid`, `uncollectible`, or `void`. [Learn more](https://stripe.com/docs/billing/invoices/workflow#workflow-overview) + Status *string `form:"status"` + // Only return invoices for the subscription specified by this subscription ID. + Subscription *string `form:"subscription"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Revise an existing invoice. The new invoice will be created in `status=draft`. See the [revision documentation](https://stripe.com/docs/invoicing/invoice-revisions) for more details. +type InvoiceFromInvoiceParams struct { + // The relation between the new invoice and the original invoice. Currently, only 'revision' is permitted + Action *string `form:"action"` + // The `id` of the invoice that will be cloned. + Invoice *string `form:"invoice"` +} + +// Search for invoices you've previously created using Stripe's [Search Query Language](https://docs.stripe.com/docs/search#search-query-language). +// Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating +// conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up +// to an hour behind during outages. Search functionality is not available to merchants in India. +type InvoiceSearchParams struct { + SearchParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + Page *string `form:"page"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceSearchParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The coupons, promotion codes & existing discounts which apply to the line item. Item discounts are applied before invoice discounts. Pass an empty string to remove previously-defined discounts. +type InvoiceAddLinesLineDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. +type InvoiceAddLinesLinePeriodParams struct { + // The end of the period, which must be greater than or equal to the start. This value is inclusive. + End *int64 `form:"end"` + // The start of the period. This value is inclusive. + Start *int64 `form:"start"` +} + +// Data used to generate a new [Product](https://docs.stripe.com/api/products) object inline. One of `product` or `product_data` is required. +type InvoiceAddLinesLinePriceDataProductDataParams struct { + // The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + Description *string `form:"description"` + // A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + Images []*string `form:"images"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The product's name, meant to be displayable to the customer. + Name *string `form:"name"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceAddLinesLinePriceDataProductDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. +type InvoiceAddLinesLinePriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. One of `product` or `product_data` is required. + Product *string `form:"product"` + // Data used to generate a new [Product](https://docs.stripe.com/api/products) object inline. One of `product` or `product_data` is required. + ProductData *InvoiceAddLinesLinePriceDataProductDataParams `form:"product_data"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A non-negative integer in cents (or local equivalent) representing how much to charge. One of `unit_amount` or `unit_amount_decimal` is required. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// The pricing information for the invoice item. +type InvoiceAddLinesLinePricingParams struct { + // The ID of the price object. + Price *string `form:"price"` +} + +// Data to find or create a TaxRate object. +// +// Stripe automatically creates or reuses a TaxRate object for each tax amount. If the `tax_rate_data` exactly matches a previous value, Stripe will reuse the TaxRate object. TaxRate objects created automatically by Stripe are immediately archived, do not appear in the line item's `tax_rates`, and cannot be directly added to invoices, payments, or line items. +type InvoiceAddLinesLineTaxAmountTaxRateDataParams struct { + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // An arbitrary string attached to the tax rate for your internal use only. It will not be visible to your customers. + Description *string `form:"description"` + // The display name of the tax rate, which will be shown to users. + DisplayName *string `form:"display_name"` + // This specifies if the tax rate is inclusive or exclusive. + Inclusive *bool `form:"inclusive"` + // The jurisdiction for the tax rate. You can use this label field for tax reporting purposes. It also appears on your customer's invoice. + Jurisdiction *string `form:"jurisdiction"` + // The level of the jurisdiction that imposes this tax rate. + JurisdictionLevel *string `form:"jurisdiction_level"` + // The statutory tax rate percent. This field accepts decimal values between 0 and 100 inclusive with at most 4 decimal places. To accommodate fixed-amount taxes, set the percentage to zero. Stripe will not display zero percentages on the invoice unless the `amount` of the tax is also zero. + Percentage *float64 `form:"percentage"` + // [ISO 3166-2 subdivision code](https://en.wikipedia.org/wiki/ISO_3166-2:US), without country prefix. For example, "NY" for New York, United States. + State *string `form:"state"` + // The high-level tax type, such as `vat` or `sales_tax`. + TaxType *string `form:"tax_type"` +} + +// A list of up to 10 tax amounts for this line item. This can be useful if you calculate taxes on your own or use a third-party to calculate them. You cannot set tax amounts if any line item has [tax_rates](https://stripe.com/docs/api/invoices/line_item#invoice_line_item_object-tax_rates) or if the invoice has [default_tax_rates](https://stripe.com/docs/api/invoices/object#invoice_object-default_tax_rates) or uses [automatic tax](https://stripe.com/docs/tax/invoicing). Pass an empty string to remove previously defined tax amounts. +type InvoiceAddLinesLineTaxAmountParams struct { + // The amount, in cents (or local equivalent), of the tax. + Amount *int64 `form:"amount"` + // The reasoning behind this tax, for example, if the product is tax exempt. + TaxabilityReason *string `form:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount *int64 `form:"taxable_amount"` + // Data to find or create a TaxRate object. + // + // Stripe automatically creates or reuses a TaxRate object for each tax amount. If the `tax_rate_data` exactly matches a previous value, Stripe will reuse the TaxRate object. TaxRate objects created automatically by Stripe are immediately archived, do not appear in the line item's `tax_rates`, and cannot be directly added to invoices, payments, or line items. + TaxRateData *InvoiceAddLinesLineTaxAmountTaxRateDataParams `form:"tax_rate_data"` +} + +// The line items to add. +type InvoiceAddLinesLineParams struct { + // The integer amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. If you want to apply a credit to the customer's account, pass a negative amount. + Amount *int64 `form:"amount"` + // An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. + Description *string `form:"description"` + // Controls whether discounts apply to this line item. Defaults to false for prorations or negative line items, and true for all other line items. Cannot be set to true for prorations. + Discountable *bool `form:"discountable"` + // The coupons, promotion codes & existing discounts which apply to the line item. Item discounts are applied before invoice discounts. Pass an empty string to remove previously-defined discounts. + Discounts []*InvoiceAddLinesLineDiscountParams `form:"discounts"` + // ID of an unassigned invoice item to assign to this invoice. If not provided, a new item will be created. + InvoiceItem *string `form:"invoice_item"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. + Period *InvoiceAddLinesLinePeriodParams `form:"period"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + PriceData *InvoiceAddLinesLinePriceDataParams `form:"price_data"` + // The pricing information for the invoice item. + Pricing *InvoiceAddLinesLinePricingParams `form:"pricing"` + // Non-negative integer. The quantity of units for the line item. + Quantity *int64 `form:"quantity"` + // A list of up to 10 tax amounts for this line item. This can be useful if you calculate taxes on your own or use a third-party to calculate them. You cannot set tax amounts if any line item has [tax_rates](https://stripe.com/docs/api/invoices/line_item#invoice_line_item_object-tax_rates) or if the invoice has [default_tax_rates](https://stripe.com/docs/api/invoices/object#invoice_object-default_tax_rates) or uses [automatic tax](https://stripe.com/docs/tax/invoicing). Pass an empty string to remove previously defined tax amounts. + TaxAmounts []*InvoiceAddLinesLineTaxAmountParams `form:"tax_amounts"` + // The tax rates which apply to the line item. When set, the `default_tax_rates` on the invoice do not apply to this line item. Pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceAddLinesLineParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Adds multiple line items to an invoice. This is only possible when an invoice is still a draft. +type InvoiceAddLinesParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + InvoiceMetadata map[string]string `form:"invoice_metadata"` + // The line items to add. + Lines []*InvoiceAddLinesLineParams `form:"lines"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceAddLinesParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Attaches a PaymentIntent or an Out of Band Payment to the invoice, adding it to the list of payments. +// +// For the PaymentIntent, when the PaymentIntent's status changes to succeeded, the payment is credited +// to the invoice, increasing its amount_paid. When the invoice is fully paid, the +// invoice's status becomes paid. +// +// If the PaymentIntent's status is already succeeded when it's attached, it's +// credited to the invoice immediately. +// +// See: [Partial payments](https://docs.stripe.com/docs/invoicing/partial-payments) to learn more. +type InvoiceAttachPaymentParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The ID of the PaymentIntent to attach to the invoice. + PaymentIntent *string `form:"payment_intent"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceAttachPaymentParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Stripe automatically finalizes drafts before sending and attempting payment on invoices. However, if you'd like to finalize a draft invoice manually, you can do so using this method. +type InvoiceFinalizeInvoiceParams struct { + Params `form:"*"` + // Controls whether Stripe performs [automatic collection](https://stripe.com/docs/invoicing/integration/automatic-advancement-collection) of the invoice. If `false`, the invoice's state doesn't automatically advance without an explicit action. + AutoAdvance *bool `form:"auto_advance"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceFinalizeInvoiceParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Marking an invoice as uncollectible is useful for keeping track of bad debts that can be written off for accounting purposes. +type InvoiceMarkUncollectibleParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceMarkUncollectibleParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Stripe automatically creates and then attempts to collect payment on invoices for customers on subscriptions according to your [subscriptions settings](https://dashboard.stripe.com/account/billing/automatic). However, if you'd like to attempt payment on an invoice out of the normal collection schedule or for some other reason, you can do so. +type InvoicePayParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // In cases where the source used to pay the invoice has insufficient funds, passing `forgive=true` controls whether a charge should be attempted for the full amount available on the source, up to the amount to fully pay the invoice. This effectively forgives the difference between the amount available on the source and the amount due. + // + // Passing `forgive=false` will fail the charge if the source hasn't been pre-funded with the right amount. An example for this case is with ACH Credit Transfers and wires: if the amount wired is less than the amount due by a small amount, you might want to forgive the difference. Defaults to `false`. + Forgive *bool `form:"forgive"` + // ID of the mandate to be used for this invoice. It must correspond to the payment method used to pay the invoice, including the payment_method param or the invoice's default_payment_method or default_source, if set. + Mandate *string `form:"mandate"` + // Indicates if a customer is on or off-session while an invoice payment is attempted. Defaults to `true` (off-session). + OffSession *bool `form:"off_session"` + // Boolean representing whether an invoice is paid outside of Stripe. This will result in no charge being made. Defaults to `false`. + PaidOutOfBand *bool `form:"paid_out_of_band"` + // A PaymentMethod to be charged. The PaymentMethod must be the ID of a PaymentMethod belonging to the customer associated with the invoice being paid. + PaymentMethod *string `form:"payment_method"` + // A payment source to be charged. The source must be the ID of a source belonging to the customer associated with the invoice being paid. + Source *string `form:"source"` +} + +// AddExpand appends a new field to expand. +func (p *InvoicePayParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The line items to remove. +type InvoiceRemoveLinesLineParams struct { + // Either `delete` or `unassign`. Deleted line items are permanently deleted. Unassigned line items can be reassigned to an invoice. + Behavior *string `form:"behavior"` + // ID of an existing line item to remove from this invoice. + ID *string `form:"id"` +} + +// Removes multiple line items from an invoice. This is only possible when an invoice is still a draft. +type InvoiceRemoveLinesParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + InvoiceMetadata map[string]string `form:"invoice_metadata"` + // The line items to remove. + Lines []*InvoiceRemoveLinesLineParams `form:"lines"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceRemoveLinesParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Stripe will automatically send invoices to customers according to your [subscriptions settings](https://dashboard.stripe.com/account/billing/automatic). However, if you'd like to manually send an invoice to your customer out of the normal schedule, you can do so. When sending invoices that have already been paid, there will be no reference to the payment in the email. +// +// Requests made in test-mode result in no emails being sent, despite sending an invoice.sent event. +type InvoiceSendInvoiceParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceSendInvoiceParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The coupons, promotion codes & existing discounts which apply to the line item. Item discounts are applied before invoice discounts. Pass an empty string to remove previously-defined discounts. +type InvoiceUpdateLinesLineDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. +type InvoiceUpdateLinesLinePeriodParams struct { + // The end of the period, which must be greater than or equal to the start. This value is inclusive. + End *int64 `form:"end"` + // The start of the period. This value is inclusive. + Start *int64 `form:"start"` +} + +// Data used to generate a new [Product](https://docs.stripe.com/api/products) object inline. One of `product` or `product_data` is required. +type InvoiceUpdateLinesLinePriceDataProductDataParams struct { + // The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + Description *string `form:"description"` + // A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + Images []*string `form:"images"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The product's name, meant to be displayable to the customer. + Name *string `form:"name"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceUpdateLinesLinePriceDataProductDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. +type InvoiceUpdateLinesLinePriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. One of `product` or `product_data` is required. + Product *string `form:"product"` + // Data used to generate a new [Product](https://docs.stripe.com/api/products) object inline. One of `product` or `product_data` is required. + ProductData *InvoiceUpdateLinesLinePriceDataProductDataParams `form:"product_data"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A non-negative integer in cents (or local equivalent) representing how much to charge. One of `unit_amount` or `unit_amount_decimal` is required. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// The pricing information for the invoice item. +type InvoiceUpdateLinesLinePricingParams struct { + // The ID of the price object. + Price *string `form:"price"` +} + +// Data to find or create a TaxRate object. +// +// Stripe automatically creates or reuses a TaxRate object for each tax amount. If the `tax_rate_data` exactly matches a previous value, Stripe will reuse the TaxRate object. TaxRate objects created automatically by Stripe are immediately archived, do not appear in the line item's `tax_rates`, and cannot be directly added to invoices, payments, or line items. +type InvoiceUpdateLinesLineTaxAmountTaxRateDataParams struct { + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // An arbitrary string attached to the tax rate for your internal use only. It will not be visible to your customers. + Description *string `form:"description"` + // The display name of the tax rate, which will be shown to users. + DisplayName *string `form:"display_name"` + // This specifies if the tax rate is inclusive or exclusive. + Inclusive *bool `form:"inclusive"` + // The jurisdiction for the tax rate. You can use this label field for tax reporting purposes. It also appears on your customer's invoice. + Jurisdiction *string `form:"jurisdiction"` + // The level of the jurisdiction that imposes this tax rate. + JurisdictionLevel *string `form:"jurisdiction_level"` + // The statutory tax rate percent. This field accepts decimal values between 0 and 100 inclusive with at most 4 decimal places. To accommodate fixed-amount taxes, set the percentage to zero. Stripe will not display zero percentages on the invoice unless the `amount` of the tax is also zero. + Percentage *float64 `form:"percentage"` + // [ISO 3166-2 subdivision code](https://en.wikipedia.org/wiki/ISO_3166-2:US), without country prefix. For example, "NY" for New York, United States. + State *string `form:"state"` + // The high-level tax type, such as `vat` or `sales_tax`. + TaxType *string `form:"tax_type"` +} + +// A list of up to 10 tax amounts for this line item. This can be useful if you calculate taxes on your own or use a third-party to calculate them. You cannot set tax amounts if any line item has [tax_rates](https://stripe.com/docs/api/invoices/line_item#invoice_line_item_object-tax_rates) or if the invoice has [default_tax_rates](https://stripe.com/docs/api/invoices/object#invoice_object-default_tax_rates) or uses [automatic tax](https://stripe.com/docs/tax/invoicing). Pass an empty string to remove previously defined tax amounts. +type InvoiceUpdateLinesLineTaxAmountParams struct { + // The amount, in cents (or local equivalent), of the tax. + Amount *int64 `form:"amount"` + // The reasoning behind this tax, for example, if the product is tax exempt. + TaxabilityReason *string `form:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount *int64 `form:"taxable_amount"` + // Data to find or create a TaxRate object. + // + // Stripe automatically creates or reuses a TaxRate object for each tax amount. If the `tax_rate_data` exactly matches a previous value, Stripe will reuse the TaxRate object. TaxRate objects created automatically by Stripe are immediately archived, do not appear in the line item's `tax_rates`, and cannot be directly added to invoices, payments, or line items. + TaxRateData *InvoiceUpdateLinesLineTaxAmountTaxRateDataParams `form:"tax_rate_data"` +} + +// The line items to update. +type InvoiceUpdateLinesLineParams struct { + // The integer amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. If you want to apply a credit to the customer's account, pass a negative amount. + Amount *int64 `form:"amount"` + // An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. + Description *string `form:"description"` + // Controls whether discounts apply to this line item. Defaults to false for prorations or negative line items, and true for all other line items. Cannot be set to true for prorations. + Discountable *bool `form:"discountable"` + // The coupons, promotion codes & existing discounts which apply to the line item. Item discounts are applied before invoice discounts. Pass an empty string to remove previously-defined discounts. + Discounts []*InvoiceUpdateLinesLineDiscountParams `form:"discounts"` + // ID of an existing line item on the invoice. + ID *string `form:"id"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. For [type=subscription](https://stripe.com/docs/api/invoices/line_item#invoice_line_item_object-type) line items, the incoming metadata specified on the request is directly used to set this value, in contrast to [type=invoiceitem](api/invoices/line_item#invoice_line_item_object-type) line items, where any existing metadata on the invoice line is merged with the incoming data. + Metadata map[string]string `form:"metadata"` + // The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. + Period *InvoiceUpdateLinesLinePeriodParams `form:"period"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + PriceData *InvoiceUpdateLinesLinePriceDataParams `form:"price_data"` + // The pricing information for the invoice item. + Pricing *InvoiceUpdateLinesLinePricingParams `form:"pricing"` + // Non-negative integer. The quantity of units for the line item. + Quantity *int64 `form:"quantity"` + // A list of up to 10 tax amounts for this line item. This can be useful if you calculate taxes on your own or use a third-party to calculate them. You cannot set tax amounts if any line item has [tax_rates](https://stripe.com/docs/api/invoices/line_item#invoice_line_item_object-tax_rates) or if the invoice has [default_tax_rates](https://stripe.com/docs/api/invoices/object#invoice_object-default_tax_rates) or uses [automatic tax](https://stripe.com/docs/tax/invoicing). Pass an empty string to remove previously defined tax amounts. + TaxAmounts []*InvoiceUpdateLinesLineTaxAmountParams `form:"tax_amounts"` + // The tax rates which apply to the line item. When set, the `default_tax_rates` on the invoice do not apply to this line item. Pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceUpdateLinesLineParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Updates multiple line items on an invoice. This is only possible when an invoice is still a draft. +type InvoiceUpdateLinesParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. For [type=subscription](https://stripe.com/docs/api/invoices/line_item#invoice_line_item_object-type) line items, the incoming metadata specified on the request is directly used to set this value, in contrast to [type=invoiceitem](api/invoices/line_item#invoice_line_item_object-type) line items, where any existing metadata on the invoice line is merged with the incoming data. + InvoiceMetadata map[string]string `form:"invoice_metadata"` + // The line items to update. + Lines []*InvoiceUpdateLinesLineParams `form:"lines"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceUpdateLinesParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Mark a finalized invoice as void. This cannot be undone. Voiding an invoice is similar to [deletion](https://docs.stripe.com/api#delete_invoice), however it only applies to finalized invoices and maintains a papertrail where the invoice can still be found. +// +// Consult with local regulations to determine whether and how an invoice might be amended, canceled, or voided in the jurisdiction you're doing business in. You might need to [issue another invoice or credit note](https://docs.stripe.com/api#create_invoice) instead. Stripe recommends that you consult with your legal counsel for advice specific to your business. +type InvoiceVoidInvoiceParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceVoidInvoiceParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type InvoiceCreatePreviewAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Settings for automatic tax lookup for this invoice preview. +type InvoiceCreatePreviewAutomaticTaxParams struct { + // Whether Stripe automatically computes tax on this invoice. Note that incompatible invoice items (invoice items with manually specified [tax rates](https://stripe.com/docs/api/tax_rates), negative amounts, or `tax_behavior=unspecified`) cannot be added to automatic tax invoices. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *InvoiceCreatePreviewAutomaticTaxLiabilityParams `form:"liability"` +} + +// The customer's shipping information. Appears on invoices emailed to this customer. +type InvoiceCreatePreviewCustomerDetailsShippingParams struct { + // Customer shipping address. + Address *AddressParams `form:"address"` + // Customer name. + Name *string `form:"name"` + // Customer phone (including extension). + Phone *string `form:"phone"` +} + +// Tax details about the customer. +type InvoiceCreatePreviewCustomerDetailsTaxParams struct { + // A recent IP address of the customer used for tax reporting and tax location inference. Stripe recommends updating the IP address when a new PaymentMethod is attached or the address field on the customer is updated. We recommend against updating this field more frequently since it could result in unexpected tax location/reporting outcomes. + IPAddress *string `form:"ip_address"` +} + +// The customer's tax IDs. +type InvoiceCreatePreviewCustomerDetailsTaxIDParams struct { + // Type of the tax ID, one of `ad_nrt`, `ae_trn`, `al_tin`, `am_tin`, `ao_tin`, `ar_cuit`, `au_abn`, `au_arn`, `aw_tin`, `az_tin`, `ba_tin`, `bb_tin`, `bd_bin`, `bf_ifu`, `bg_uic`, `bh_vat`, `bj_ifu`, `bo_tin`, `br_cnpj`, `br_cpf`, `bs_tin`, `by_tin`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `ca_qst`, `cd_nif`, `ch_uid`, `ch_vat`, `cl_tin`, `cm_niu`, `cn_tin`, `co_nit`, `cr_tin`, `cv_nif`, `de_stn`, `do_rcn`, `ec_ruc`, `eg_tin`, `es_cif`, `et_tin`, `eu_oss_vat`, `eu_vat`, `gb_vat`, `ge_vat`, `gn_nif`, `hk_br`, `hr_oib`, `hu_tin`, `id_npwp`, `il_vat`, `in_gst`, `is_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `ke_pin`, `kg_tin`, `kh_tin`, `kr_brn`, `kz_bin`, `la_tin`, `li_uid`, `li_vat`, `ma_vat`, `md_vat`, `me_pib`, `mk_vat`, `mr_nif`, `mx_rfc`, `my_frp`, `my_itn`, `my_sst`, `ng_tin`, `no_vat`, `no_voec`, `np_pan`, `nz_gst`, `om_vat`, `pe_ruc`, `ph_tin`, `ro_tin`, `rs_pib`, `ru_inn`, `ru_kpp`, `sa_vat`, `sg_gst`, `sg_uen`, `si_tin`, `sn_ninea`, `sr_fin`, `sv_nit`, `th_vat`, `tj_tin`, `tr_tin`, `tw_vat`, `tz_vat`, `ua_vat`, `ug_tin`, `us_ein`, `uy_ruc`, `uz_tin`, `uz_vat`, `ve_rif`, `vn_tin`, `za_vat`, `zm_tin`, or `zw_tin` + Type *string `form:"type"` + // Value of the tax ID. + Value *string `form:"value"` +} + +// Details about the customer you want to invoice or overrides for an existing customer. If `automatic_tax` is enabled then one of `customer`, `customer_details`, `subscription`, or `schedule` must be set. +type InvoiceCreatePreviewCustomerDetailsParams struct { + // The customer's address. + Address *AddressParams `form:"address"` + // The customer's shipping information. Appears on invoices emailed to this customer. + Shipping *InvoiceCreatePreviewCustomerDetailsShippingParams `form:"shipping"` + // Tax details about the customer. + Tax *InvoiceCreatePreviewCustomerDetailsTaxParams `form:"tax"` + // The customer's tax exemption. One of `none`, `exempt`, or `reverse`. + TaxExempt *string `form:"tax_exempt"` + // The customer's tax IDs. + TaxIDs []*InvoiceCreatePreviewCustomerDetailsTaxIDParams `form:"tax_ids"` +} + +// The coupons to redeem into discounts for the invoice preview. If not specified, inherits the discount from the subscription or customer. This works for both coupons directly applied to an invoice and coupons applied to a subscription. Pass an empty string to avoid inheriting any discounts. +type InvoiceCreatePreviewDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The coupons to redeem into discounts for the invoice item in the preview. +type InvoiceCreatePreviewInvoiceItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. +type InvoiceCreatePreviewInvoiceItemPeriodParams struct { + // The end of the period, which must be greater than or equal to the start. This value is inclusive. + End *int64 `form:"end"` + // The start of the period. This value is inclusive. + Start *int64 `form:"start"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. +type InvoiceCreatePreviewInvoiceItemPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// List of invoice items to add or update in the upcoming invoice preview (up to 250). +type InvoiceCreatePreviewInvoiceItemParams struct { + // The integer amount in cents (or local equivalent) of previewed invoice item. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). Only applicable to new invoice items. + Currency *string `form:"currency"` + // An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. + Description *string `form:"description"` + // Explicitly controls whether discounts apply to this invoice item. Defaults to true, except for negative invoice items. + Discountable *bool `form:"discountable"` + // The coupons to redeem into discounts for the invoice item in the preview. + Discounts []*InvoiceCreatePreviewInvoiceItemDiscountParams `form:"discounts"` + // The ID of the invoice item to update in preview. If not specified, a new invoice item will be added to the preview of the upcoming invoice. + InvoiceItem *string `form:"invoiceitem"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. + Period *InvoiceCreatePreviewInvoiceItemPeriodParams `form:"period"` + // The ID of the price object. One of `price` or `price_data` is required. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *InvoiceCreatePreviewInvoiceItemPriceDataParams `form:"price_data"` + // Non-negative integer. The quantity of units for the invoice item. + Quantity *int64 `form:"quantity"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` + // The tax rates that apply to the item. When set, any `default_tax_rates` do not apply to this item. + TaxRates []*string `form:"tax_rates"` + // The integer unit amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. This unit_amount will be multiplied by the quantity to get the full amount. If you want to apply a credit to the customer's account, pass a negative unit_amount. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceCreatePreviewInvoiceItemParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type InvoiceCreatePreviewIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Controls how prorations and invoices for subscriptions are calculated and orchestrated. +type InvoiceCreatePreviewScheduleDetailsBillingModeParams struct { + Type *string `form:"type"` +} + +// The coupons to redeem into discounts for the item. +type InvoiceCreatePreviewScheduleDetailsPhaseAddInvoiceItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. +type InvoiceCreatePreviewScheduleDetailsPhaseAddInvoiceItemPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge or a negative integer representing the amount to credit to the customer. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// A list of prices and quantities that will generate invoice items appended to the next invoice for this phase. You may pass up to 20 items. +type InvoiceCreatePreviewScheduleDetailsPhaseAddInvoiceItemParams struct { + // The coupons to redeem into discounts for the item. + Discounts []*InvoiceCreatePreviewScheduleDetailsPhaseAddInvoiceItemDiscountParams `form:"discounts"` + // The ID of the price object. One of `price` or `price_data` is required. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *InvoiceCreatePreviewScheduleDetailsPhaseAddInvoiceItemPriceDataParams `form:"price_data"` + // Quantity for this item. Defaults to 1. + Quantity *int64 `form:"quantity"` + // The tax rates which apply to the item. When set, the `default_tax_rates` do not apply to this item. + TaxRates []*string `form:"tax_rates"` +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type InvoiceCreatePreviewScheduleDetailsPhaseAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Automatic tax settings for this phase. +type InvoiceCreatePreviewScheduleDetailsPhaseAutomaticTaxParams struct { + // Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *InvoiceCreatePreviewScheduleDetailsPhaseAutomaticTaxLiabilityParams `form:"liability"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type InvoiceCreatePreviewScheduleDetailsPhaseBillingThresholdsParams struct { + // Monetary threshold that triggers the subscription to advance to a new billing period + AmountGTE *int64 `form:"amount_gte"` + // Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + ResetBillingCycleAnchor *bool `form:"reset_billing_cycle_anchor"` +} + +// The coupons to redeem into discounts for the schedule phase. If not specified, inherits the discount from the subscription's customer. Pass an empty string to avoid inheriting any discounts. +type InvoiceCreatePreviewScheduleDetailsPhaseDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type InvoiceCreatePreviewScheduleDetailsPhaseInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type InvoiceCreatePreviewScheduleDetailsPhaseInvoiceSettingsParams struct { + // The account tax IDs associated with this phase of the subscription schedule. Will be set on invoices generated by this phase of the subscription schedule. + AccountTaxIDs []*string `form:"account_tax_ids"` + // Number of days within which a customer must pay invoices generated by this subscription schedule. This value will be `null` for subscription schedules where `billing=charge_automatically`. + DaysUntilDue *int64 `form:"days_until_due"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *InvoiceCreatePreviewScheduleDetailsPhaseInvoiceSettingsIssuerParams `form:"issuer"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type InvoiceCreatePreviewScheduleDetailsPhaseItemBillingThresholdsParams struct { + // Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + UsageGTE *int64 `form:"usage_gte"` +} + +// The coupons to redeem into discounts for the subscription item. +type InvoiceCreatePreviewScheduleDetailsPhaseItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The recurring components of a price such as `interval` and `interval_count`. +type InvoiceCreatePreviewScheduleDetailsPhaseItemPriceDataRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. +type InvoiceCreatePreviewScheduleDetailsPhaseItemPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // The recurring components of a price such as `interval` and `interval_count`. + Recurring *InvoiceCreatePreviewScheduleDetailsPhaseItemPriceDataRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// List of configuration items, each with an attached price, to apply during this phase of the subscription schedule. +type InvoiceCreatePreviewScheduleDetailsPhaseItemParams struct { + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *InvoiceCreatePreviewScheduleDetailsPhaseItemBillingThresholdsParams `form:"billing_thresholds"` + // The coupons to redeem into discounts for the subscription item. + Discounts []*InvoiceCreatePreviewScheduleDetailsPhaseItemDiscountParams `form:"discounts"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to a configuration item. Metadata on a configuration item will update the underlying subscription item's `metadata` when the phase is entered, adding new keys and replacing existing keys. Individual keys in the subscription item's `metadata` can be unset by posting an empty value to them in the configuration item's `metadata`. To unset all keys in the subscription item's `metadata`, update the subscription item directly or unset every key individually from the configuration item's `metadata`. + Metadata map[string]string `form:"metadata"` + // The plan ID to subscribe to. You may specify the same ID in `plan` and `price`. + Plan *string `form:"plan"` + // The ID of the price object. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + PriceData *InvoiceCreatePreviewScheduleDetailsPhaseItemPriceDataParams `form:"price_data"` + // Quantity for the given price. Can be set only if the price's `usage_type` is `licensed` and not `metered`. + Quantity *int64 `form:"quantity"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceCreatePreviewScheduleDetailsPhaseItemParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The data with which to automatically create a Transfer for each of the associated subscription's invoices. +type InvoiceCreatePreviewScheduleDetailsPhaseTransferDataParams struct { + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + AmountPercent *float64 `form:"amount_percent"` + // ID of an existing, connected Stripe account. + Destination *string `form:"destination"` +} + +// List representing phases of the subscription schedule. Each phase can be customized to have different durations, plans, and coupons. If there are multiple phases, the `end_date` of one phase will always equal the `start_date` of the next phase. +type InvoiceCreatePreviewScheduleDetailsPhaseParams struct { + // A list of prices and quantities that will generate invoice items appended to the next invoice for this phase. You may pass up to 20 items. + AddInvoiceItems []*InvoiceCreatePreviewScheduleDetailsPhaseAddInvoiceItemParams `form:"add_invoice_items"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + ApplicationFeePercent *float64 `form:"application_fee_percent"` + // Automatic tax settings for this phase. + AutomaticTax *InvoiceCreatePreviewScheduleDetailsPhaseAutomaticTaxParams `form:"automatic_tax"` + // Can be set to `phase_start` to set the anchor to the start of the phase or `automatic` to automatically change it if needed. Cannot be set to `phase_start` if this phase specifies a trial. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + BillingCycleAnchor *string `form:"billing_cycle_anchor"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *InvoiceCreatePreviewScheduleDetailsPhaseBillingThresholdsParams `form:"billing_thresholds"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically` on creation. + CollectionMethod *string `form:"collection_method"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // ID of the default payment method for the subscription schedule. It must belong to the customer associated with the subscription schedule. If not set, invoices will use the default payment method in the customer's invoice settings. + DefaultPaymentMethod *string `form:"default_payment_method"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will set the Subscription's [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates), which means they will be the Invoice's [`default_tax_rates`](https://stripe.com/docs/api/invoices/create#create_invoice-default_tax_rates) for any Invoices issued by the Subscription during this Phase. + DefaultTaxRates []*string `form:"default_tax_rates"` + // Subscription description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // The coupons to redeem into discounts for the schedule phase. If not specified, inherits the discount from the subscription's customer. Pass an empty string to avoid inheriting any discounts. + Discounts []*InvoiceCreatePreviewScheduleDetailsPhaseDiscountParams `form:"discounts"` + // The date at which this phase of the subscription schedule ends. If set, `iterations` must not be set. + EndDate *int64 `form:"end_date"` + EndDateNow *bool `form:"-"` // See custom AppendTo + // All invoices will be billed using the specified settings. + InvoiceSettings *InvoiceCreatePreviewScheduleDetailsPhaseInvoiceSettingsParams `form:"invoice_settings"` + // List of configuration items, each with an attached price, to apply during this phase of the subscription schedule. + Items []*InvoiceCreatePreviewScheduleDetailsPhaseItemParams `form:"items"` + // Integer representing the multiplier applied to the price interval. For example, `iterations=2` applied to a price with `interval=month` and `interval_count=3` results in a phase of duration `2 * 3 months = 6 months`. If set, `end_date` must not be set. + Iterations *int64 `form:"iterations"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to a phase. Metadata on a schedule's phase will update the underlying subscription's `metadata` when the phase is entered, adding new keys and replacing existing keys in the subscription's `metadata`. Individual keys in the subscription's `metadata` can be unset by posting an empty value to them in the phase's `metadata`. To unset all keys in the subscription's `metadata`, update the subscription directly or unset every key individually from the phase's `metadata`. + Metadata map[string]string `form:"metadata"` + // The account on behalf of which to charge, for each of the associated subscription's invoices. + OnBehalfOf *string `form:"on_behalf_of"` + // Controls whether the subscription schedule should create [prorations](https://stripe.com/docs/billing/subscriptions/prorations) when transitioning to this phase if there is a difference in billing configuration. It's different from the request-level [proration_behavior](https://stripe.com/docs/api/subscription_schedules/update#update_subscription_schedule-proration_behavior) parameter which controls what happens if the update request affects the billing configuration (item price, quantity, etc.) of the current phase. + ProrationBehavior *string `form:"proration_behavior"` + // The date at which this phase of the subscription schedule starts or `now`. Must be set on the first phase. + StartDate *int64 `form:"start_date"` + StartDateNow *bool `form:"-"` // See custom AppendTo + // The data with which to automatically create a Transfer for each of the associated subscription's invoices. + TransferData *InvoiceCreatePreviewScheduleDetailsPhaseTransferDataParams `form:"transfer_data"` + // If set to true the entire phase is counted as a trial and the customer will not be charged for any fees. + Trial *bool `form:"trial"` + // Sets the phase to trialing from the start date to this date. Must be before the phase end date, can not be combined with `trial` + TrialEnd *int64 `form:"trial_end"` + TrialEndNow *bool `form:"-"` // See custom AppendTo +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceCreatePreviewScheduleDetailsPhaseParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// AppendTo implements custom encoding logic for InvoiceCreatePreviewScheduleDetailsPhaseParams. +func (p *InvoiceCreatePreviewScheduleDetailsPhaseParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.EndDateNow) { + body.Add(form.FormatKey(append(keyParts, "end_date")), "now") + } + if BoolValue(p.StartDateNow) { + body.Add(form.FormatKey(append(keyParts, "start_date")), "now") + } + if BoolValue(p.TrialEndNow) { + body.Add(form.FormatKey(append(keyParts, "trial_end")), "now") + } +} + +// The schedule creation or modification params to apply as a preview. Cannot be used with `subscription` or `subscription_` prefixed fields. +type InvoiceCreatePreviewScheduleDetailsParams struct { + // Controls how prorations and invoices for subscriptions are calculated and orchestrated. + BillingMode *InvoiceCreatePreviewScheduleDetailsBillingModeParams `form:"billing_mode"` + // Behavior of the subscription schedule and underlying subscription when it ends. Possible values are `release` or `cancel` with the default being `release`. `release` will end the subscription schedule and keep the underlying subscription running. `cancel` will end the subscription schedule and cancel the underlying subscription. + EndBehavior *string `form:"end_behavior"` + // List representing phases of the subscription schedule. Each phase can be customized to have different durations, plans, and coupons. If there are multiple phases, the `end_date` of one phase will always equal the `start_date` of the next phase. + Phases []*InvoiceCreatePreviewScheduleDetailsPhaseParams `form:"phases"` + // In cases where the `schedule_details` params update the currently active phase, specifies if and how to prorate at the time of the request. + ProrationBehavior *string `form:"proration_behavior"` +} + +// Controls how prorations and invoices for subscriptions are calculated and orchestrated. +type InvoiceCreatePreviewSubscriptionDetailsBillingModeParams struct { + Type *string `form:"type"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type InvoiceCreatePreviewSubscriptionDetailsItemBillingThresholdsParams struct { + // Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + UsageGTE *int64 `form:"usage_gte"` +} + +// The coupons to redeem into discounts for the subscription item. +type InvoiceCreatePreviewSubscriptionDetailsItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The recurring components of a price such as `interval` and `interval_count`. +type InvoiceCreatePreviewSubscriptionDetailsItemPriceDataRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. +type InvoiceCreatePreviewSubscriptionDetailsItemPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // The recurring components of a price such as `interval` and `interval_count`. + Recurring *InvoiceCreatePreviewSubscriptionDetailsItemPriceDataRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// A list of up to 20 subscription items, each with an attached price. +type InvoiceCreatePreviewSubscriptionDetailsItemParams struct { + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *InvoiceCreatePreviewSubscriptionDetailsItemBillingThresholdsParams `form:"billing_thresholds"` + // Delete all usage for a given subscription item. You must pass this when deleting a usage records subscription item. `clear_usage` has no effect if the plan has a billing meter attached. + ClearUsage *bool `form:"clear_usage"` + // A flag that, if set to `true`, will delete the specified item. + Deleted *bool `form:"deleted"` + // The coupons to redeem into discounts for the subscription item. + Discounts []*InvoiceCreatePreviewSubscriptionDetailsItemDiscountParams `form:"discounts"` + // Subscription item to update. + ID *string `form:"id"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Plan ID for this item, as a string. + Plan *string `form:"plan"` + // The ID of the price object. One of `price` or `price_data` is required. When changing a subscription item's price, `quantity` is set to 1 unless a `quantity` parameter is provided. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *InvoiceCreatePreviewSubscriptionDetailsItemPriceDataParams `form:"price_data"` + // Quantity for this item. + Quantity *int64 `form:"quantity"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceCreatePreviewSubscriptionDetailsItemParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The subscription creation or modification params to apply as a preview. Cannot be used with `schedule` or `schedule_details` fields. +type InvoiceCreatePreviewSubscriptionDetailsParams struct { + // For new subscriptions, a future timestamp to anchor the subscription's [billing cycle](https://stripe.com/docs/subscriptions/billing-cycle). This is used to determine the date of the first full invoice, and, for plans with `month` or `year` intervals, the day of the month for subsequent invoices. For existing subscriptions, the value can only be set to `now` or `unchanged`. + BillingCycleAnchor *int64 `form:"billing_cycle_anchor"` + BillingCycleAnchorNow *bool `form:"-"` // See custom AppendTo + BillingCycleAnchorUnchanged *bool `form:"-"` // See custom AppendTo + // Controls how prorations and invoices for subscriptions are calculated and orchestrated. + BillingMode *InvoiceCreatePreviewSubscriptionDetailsBillingModeParams `form:"billing_mode"` + // A timestamp at which the subscription should cancel. If set to a date before the current period ends, this will cause a proration if prorations have been enabled using `proration_behavior`. If set during a future period, this will always cause a proration for that period. + CancelAt *int64 `form:"cancel_at"` + // Indicate whether this subscription should cancel at the end of the current period (`current_period_end`). Defaults to `false`. + CancelAtPeriodEnd *bool `form:"cancel_at_period_end"` + // This simulates the subscription being canceled or expired immediately. + CancelNow *bool `form:"cancel_now"` + // If provided, the invoice returned will preview updating or creating a subscription with these default tax rates. The default tax rates will apply to any line item that does not have `tax_rates` set. + DefaultTaxRates []*string `form:"default_tax_rates"` + // A list of up to 20 subscription items, each with an attached price. + Items []*InvoiceCreatePreviewSubscriptionDetailsItemParams `form:"items"` + // Determines how to handle [prorations](https://stripe.com/docs/billing/subscriptions/prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. The default value is `create_prorations`. + ProrationBehavior *string `form:"proration_behavior"` + // If previewing an update to a subscription, and doing proration, `subscription_details.proration_date` forces the proration to be calculated as though the update was done at the specified time. The time given must be within the current subscription period and within the current phase of the schedule backing this subscription, if the schedule exists. If set, `subscription`, and one of `subscription_details.items`, or `subscription_details.trial_end` are required. Also, `subscription_details.proration_behavior` cannot be set to 'none'. + ProrationDate *int64 `form:"proration_date"` + // For paused subscriptions, setting `subscription_details.resume_at` to `now` will preview the invoice that will be generated if the subscription is resumed. + ResumeAt *string `form:"resume_at"` + // Date a subscription is intended to start (can be future or past). + StartDate *int64 `form:"start_date"` + // If provided, the invoice returned will preview updating or creating a subscription with that trial end. If set, one of `subscription_details.items` or `subscription` is required. + TrialEnd *int64 `form:"trial_end"` + TrialEndNow *bool `form:"-"` // See custom AppendTo +} + +// AppendTo implements custom encoding logic for InvoiceCreatePreviewSubscriptionDetailsParams. +func (p *InvoiceCreatePreviewSubscriptionDetailsParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.BillingCycleAnchorNow) { + body.Add(form.FormatKey(append(keyParts, "billing_cycle_anchor")), "now") + } + if BoolValue(p.BillingCycleAnchorUnchanged) { + body.Add(form.FormatKey(append(keyParts, "billing_cycle_anchor")), "unchanged") + } + if BoolValue(p.TrialEndNow) { + body.Add(form.FormatKey(append(keyParts, "trial_end")), "now") + } +} + +// At any time, you can preview the upcoming invoice for a subscription or subscription schedule. This will show you all the charges that are pending, including subscription renewal charges, invoice item charges, etc. It will also show you any discounts that are applicable to the invoice. +// +// You can also preview the effects of creating or updating a subscription or subscription schedule, including a preview of any prorations that will take place. To ensure that the actual proration is calculated exactly the same as the previewed proration, you should pass the subscription_details.proration_date parameter when doing the actual subscription update. +// +// The recommended way to get only the prorations being previewed on the invoice is to consider line items where parent.subscription_item_details.proration is true. +// +// Note that when you are viewing an upcoming invoice, you are simply viewing a preview – the invoice has not yet been created. As such, the upcoming invoice will not show up in invoice listing calls, and you cannot use the API to pay or edit the invoice. If you want to change the amount that your customer will be billed, you can add, remove, or update pending invoice items, or update the customer's discount. +// +// Note: Currency conversion calculations use the latest exchange rates. Exchange rates may vary between the time of the preview and the time of the actual invoice creation. [Learn more](https://docs.stripe.com/currencies/conversions) +type InvoiceCreatePreviewParams struct { + Params `form:"*"` + // Settings for automatic tax lookup for this invoice preview. + AutomaticTax *InvoiceCreatePreviewAutomaticTaxParams `form:"automatic_tax"` + // The currency to preview this invoice in. Defaults to that of `customer` if not specified. + Currency *string `form:"currency"` + // The identifier of the customer whose upcoming invoice you'd like to retrieve. If `automatic_tax` is enabled then one of `customer`, `customer_details`, `subscription`, or `schedule` must be set. + Customer *string `form:"customer"` + // Details about the customer you want to invoice or overrides for an existing customer. If `automatic_tax` is enabled then one of `customer`, `customer_details`, `subscription`, or `schedule` must be set. + CustomerDetails *InvoiceCreatePreviewCustomerDetailsParams `form:"customer_details"` + // The coupons to redeem into discounts for the invoice preview. If not specified, inherits the discount from the subscription or customer. This works for both coupons directly applied to an invoice and coupons applied to a subscription. Pass an empty string to avoid inheriting any discounts. + Discounts []*InvoiceCreatePreviewDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // List of invoice items to add or update in the upcoming invoice preview (up to 250). + InvoiceItems []*InvoiceCreatePreviewInvoiceItemParams `form:"invoice_items"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *InvoiceCreatePreviewIssuerParams `form:"issuer"` + // The account (if any) for which the funds of the invoice payment are intended. If set, the invoice will be presented with the branding and support information of the specified account. See the [Invoices with Connect](https://stripe.com/docs/billing/invoices/connect) documentation for details. + OnBehalfOf *string `form:"on_behalf_of"` + // Customizes the types of values to include when calculating the invoice. Defaults to `next` if unspecified. + PreviewMode *string `form:"preview_mode"` + // The identifier of the schedule whose upcoming invoice you'd like to retrieve. Cannot be used with subscription or subscription fields. + Schedule *string `form:"schedule"` + // The schedule creation or modification params to apply as a preview. Cannot be used with `subscription` or `subscription_` prefixed fields. + ScheduleDetails *InvoiceCreatePreviewScheduleDetailsParams `form:"schedule_details"` + // The identifier of the subscription for which you'd like to retrieve the upcoming invoice. If not provided, but a `subscription_details.items` is provided, you will preview creating a subscription with those items. If neither `subscription` nor `subscription_details.items` is provided, you will retrieve the next upcoming invoice from among the customer's subscriptions. + Subscription *string `form:"subscription"` + // The subscription creation or modification params to apply as a preview. Cannot be used with `schedule` or `schedule_details` fields. + SubscriptionDetails *InvoiceCreatePreviewSubscriptionDetailsParams `form:"subscription_details"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceCreatePreviewParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When retrieving an invoice, you'll get a lines property containing the total count of line items and the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. +type InvoiceListLinesParams struct { + ListParams `form:"*"` + Invoice *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceListLinesParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Permanently deletes a one-off invoice draft. This cannot be undone. Attempts to delete invoices that are no longer in a draft state will fail; once an invoice has been finalized or if an invoice is for a subscription, it must be [voided](https://docs.stripe.com/api#void_invoice). +type InvoiceDeleteParams struct { + Params `form:"*"` +} + +// Retrieves the invoice with the given ID. +type InvoiceRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type InvoiceUpdateAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Settings for automatic tax lookup for this invoice. +type InvoiceUpdateAutomaticTaxParams struct { + // Whether Stripe automatically computes tax on this invoice. Note that incompatible invoice items (invoice items with manually specified [tax rates](https://stripe.com/docs/api/tax_rates), negative amounts, or `tax_behavior=unspecified`) cannot be added to automatic tax invoices. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *InvoiceUpdateAutomaticTaxLiabilityParams `form:"liability"` +} + +// A list of up to 4 custom fields to be displayed on the invoice. If a value for `custom_fields` is specified, the list specified will replace the existing custom field list on this invoice. Pass an empty string to remove previously-defined fields. +type InvoiceUpdateCustomFieldParams struct { + // The name of the custom field. This may be up to 40 characters. + Name *string `form:"name"` + // The value of the custom field. This may be up to 140 characters. + Value *string `form:"value"` +} + +// The discounts that will apply to the invoice. Pass an empty string to remove previously-defined discounts. +type InvoiceUpdateDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type InvoiceUpdateIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Additional fields for Mandate creation +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsParams struct { + // Transaction type of the mandate. + TransactionType *string `form:"transaction_type"` +} + +// If paying by `acss_debit`, this sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsACSSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *InvoiceUpdatePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsParams `form:"mandate_options"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// If paying by `bancontact`, this sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsBancontactParams struct { + // Preferred language of the Bancontact authorization page that the customer is redirected to. + PreferredLanguage *string `form:"preferred_language"` +} + +// The selected installment plan to use for this invoice. +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsCardInstallmentsPlanParams struct { + // For `fixed_count` installment plans, this is required. It represents the number of installment payments your customer will make to their credit card. + Count *int64 `form:"count"` + // For `fixed_count` installment plans, this is required. It represents the interval between installment payments your customer will make to their credit card. + // One of `month`. + Interval *string `form:"interval"` + // Type of installment plan, one of `fixed_count`, `bonus`, or `revolving`. + Type *string `form:"type"` +} + +// Installment configuration for payments attempted on this invoice (Mexico Only). +// +// For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsCardInstallmentsParams struct { + // Setting to true enables installments for this invoice. + // Setting to false will prevent any selected plan from applying to a payment. + Enabled *bool `form:"enabled"` + // The selected installment plan to use for this invoice. + Plan *InvoiceUpdatePaymentSettingsPaymentMethodOptionsCardInstallmentsPlanParams `form:"plan"` +} + +// If paying by `card`, this sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsCardParams struct { + // Installment configuration for payments attempted on this invoice (Mexico Only). + // + // For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + Installments *InvoiceUpdatePaymentSettingsPaymentMethodOptionsCardInstallmentsParams `form:"installments"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure *string `form:"request_three_d_secure"` +} + +// Configuration for eu_bank_transfer funding type. +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country *string `form:"country"` +} + +// Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams struct { + // Configuration for eu_bank_transfer funding type. + EUBankTransfer *InvoiceUpdatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams `form:"eu_bank_transfer"` + // The bank transfer type that can be used for funding. Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + Type *string `form:"type"` +} + +// If paying by `customer_balance`, this sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsCustomerBalanceParams struct { + // Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + BankTransfer *InvoiceUpdatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams `form:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType *string `form:"funding_type"` +} + +// If paying by `konbini`, this sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsKonbiniParams struct{} + +// If paying by `sepa_debit`, this sub-hash contains details about the SEPA Direct Debit payment method options to pass to the invoice's PaymentIntent. +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsSEPADebitParams struct{} + +// Provide filters for the linked accounts that the customer can select for the payment method. +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams struct { + // The account subcategories to use to filter for selectable accounts. Valid subcategories are `checking` and `savings`. + AccountSubcategories []*string `form:"account_subcategories"` +} + +// Additional fields for Financial Connections Session creation +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsParams struct { + // Provide filters for the linked accounts that the customer can select for the payment method. + Filters *InvoiceUpdatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams `form:"filters"` + // The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` +} + +// If paying by `us_bank_account`, this sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsUSBankAccountParams struct { + // Additional fields for Financial Connections Session creation + FinancialConnections *InvoiceUpdatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsParams `form:"financial_connections"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// Payment-method-specific configuration to provide to the invoice's PaymentIntent. +type InvoiceUpdatePaymentSettingsPaymentMethodOptionsParams struct { + // If paying by `acss_debit`, this sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. + ACSSDebit *InvoiceUpdatePaymentSettingsPaymentMethodOptionsACSSDebitParams `form:"acss_debit"` + // If paying by `bancontact`, this sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. + Bancontact *InvoiceUpdatePaymentSettingsPaymentMethodOptionsBancontactParams `form:"bancontact"` + // If paying by `card`, this sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. + Card *InvoiceUpdatePaymentSettingsPaymentMethodOptionsCardParams `form:"card"` + // If paying by `customer_balance`, this sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. + CustomerBalance *InvoiceUpdatePaymentSettingsPaymentMethodOptionsCustomerBalanceParams `form:"customer_balance"` + // If paying by `konbini`, this sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. + Konbini *InvoiceUpdatePaymentSettingsPaymentMethodOptionsKonbiniParams `form:"konbini"` + // If paying by `sepa_debit`, this sub-hash contains details about the SEPA Direct Debit payment method options to pass to the invoice's PaymentIntent. + SEPADebit *InvoiceUpdatePaymentSettingsPaymentMethodOptionsSEPADebitParams `form:"sepa_debit"` + // If paying by `us_bank_account`, this sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. + USBankAccount *InvoiceUpdatePaymentSettingsPaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` +} + +// Configuration settings for the PaymentIntent that is generated when the invoice is finalized. +type InvoiceUpdatePaymentSettingsParams struct { + // ID of the mandate to be used for this invoice. It must correspond to the payment method used to pay the invoice, including the invoice's default_payment_method or default_source, if set. + DefaultMandate *string `form:"default_mandate"` + // Payment-method-specific configuration to provide to the invoice's PaymentIntent. + PaymentMethodOptions *InvoiceUpdatePaymentSettingsPaymentMethodOptionsParams `form:"payment_method_options"` + // The list of payment method types (e.g. card) to provide to the invoice's PaymentIntent. If not set, Stripe attempts to automatically determine the types to use by looking at the invoice's default payment method, the subscription's default payment method, the customer's default payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). Should not be specified with payment_method_configuration + PaymentMethodTypes []*string `form:"payment_method_types"` +} + +// Invoice pdf rendering options +type InvoiceUpdateRenderingPDFParams struct { + // Page size for invoice PDF. Can be set to `a4`, `letter`, or `auto`. + // If set to `auto`, invoice PDF page size defaults to `a4` for customers with + // Japanese locale and `letter` for customers with other locales. + PageSize *string `form:"page_size"` +} + +// The rendering-related settings that control how the invoice is displayed on customer-facing surfaces such as PDF and Hosted Invoice Page. +type InvoiceUpdateRenderingParams struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + AmountTaxDisplay *string `form:"amount_tax_display"` + // Invoice pdf rendering options + PDF *InvoiceUpdateRenderingPDFParams `form:"pdf"` + // ID of the invoice rendering template to use for this invoice. + Template *string `form:"template"` + // The specific version of invoice rendering template to use for this invoice. + TemplateVersion *int64 `form:"template_version"` +} + +// The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. +type InvoiceUpdateShippingCostShippingRateDataDeliveryEstimateMaximumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The lower bound of the estimated range. If empty, represents no lower bound. +type InvoiceUpdateShippingCostShippingRateDataDeliveryEstimateMinimumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. +type InvoiceUpdateShippingCostShippingRateDataDeliveryEstimateParams struct { + // The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. + Maximum *InvoiceUpdateShippingCostShippingRateDataDeliveryEstimateMaximumParams `form:"maximum"` + // The lower bound of the estimated range. If empty, represents no lower bound. + Minimum *InvoiceUpdateShippingCostShippingRateDataDeliveryEstimateMinimumParams `form:"minimum"` +} + +// Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type InvoiceUpdateShippingCostShippingRateDataFixedAmountCurrencyOptionsParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` +} + +// Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. +type InvoiceUpdateShippingCostShippingRateDataFixedAmountParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*InvoiceUpdateShippingCostShippingRateDataFixedAmountCurrencyOptionsParams `form:"currency_options"` +} + +// Parameters to create a new ad-hoc shipping rate for this order. +type InvoiceUpdateShippingCostShippingRateDataParams struct { + // The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. + DeliveryEstimate *InvoiceUpdateShippingCostShippingRateDataDeliveryEstimateParams `form:"delivery_estimate"` + // The name of the shipping rate, meant to be displayable to the customer. This will appear on CheckoutSessions. + DisplayName *string `form:"display_name"` + // Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. + FixedAmount *InvoiceUpdateShippingCostShippingRateDataFixedAmountParams `form:"fixed_amount"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. The Shipping tax code is `txcd_92010001`. + TaxCode *string `form:"tax_code"` + // The type of calculation to use on the shipping rate. + Type *string `form:"type"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceUpdateShippingCostShippingRateDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Settings for the cost of shipping for this invoice. +type InvoiceUpdateShippingCostParams struct { + // The ID of the shipping rate to use for this order. + ShippingRate *string `form:"shipping_rate"` + // Parameters to create a new ad-hoc shipping rate for this order. + ShippingRateData *InvoiceUpdateShippingCostShippingRateDataParams `form:"shipping_rate_data"` +} + +// Shipping details for the invoice. The Invoice PDF will use the `shipping_details` value if it is set, otherwise the PDF will render the shipping address from the customer. +type InvoiceUpdateShippingDetailsParams struct { + // Shipping address + Address *AddressParams `form:"address"` + // Recipient name. + Name *string `form:"name"` + // Recipient phone (including extension) + Phone *string `form:"phone"` +} + +// If specified, the funds from the invoice will be transferred to the destination and the ID of the resulting transfer will be found on the invoice's charge. This will be unset if you POST an empty value. +type InvoiceUpdateTransferDataParams struct { + // The amount that will be transferred automatically when the invoice is paid. If no amount is set, the full amount is transferred. + Amount *int64 `form:"amount"` + // ID of an existing, connected Stripe account. + Destination *string `form:"destination"` +} + +// Draft invoices are fully editable. Once an invoice is [finalized](https://docs.stripe.com/docs/billing/invoices/workflow#finalized), +// monetary values, as well as collection_method, become uneditable. +// +// If you would like to stop the Stripe Billing engine from automatically finalizing, reattempting payments on, +// sending reminders for, or [automatically reconciling](https://docs.stripe.com/docs/billing/invoices/reconciliation) invoices, pass +// auto_advance=false. +type InvoiceUpdateParams struct { + Params `form:"*"` + // The account tax IDs associated with the invoice. Only editable when the invoice is a draft. + AccountTaxIDs []*string `form:"account_tax_ids"` + // A fee in cents (or local equivalent) that will be applied to the invoice and transferred to the application owner's Stripe account. The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. For more information, see the application fees [documentation](https://stripe.com/docs/billing/invoices/connect#collecting-fees). + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // Controls whether Stripe performs [automatic collection](https://stripe.com/docs/invoicing/integration/automatic-advancement-collection) of the invoice. + AutoAdvance *bool `form:"auto_advance"` + // The time when this invoice should be scheduled to finalize. The invoice will be finalized at this time if it is still in draft state. To turn off automatic finalization, set `auto_advance` to false. + AutomaticallyFinalizesAt *int64 `form:"automatically_finalizes_at"` + // Settings for automatic tax lookup for this invoice. + AutomaticTax *InvoiceUpdateAutomaticTaxParams `form:"automatic_tax"` + // Either `charge_automatically` or `send_invoice`. This field can be updated only on `draft` invoices. + CollectionMethod *string `form:"collection_method"` + // A list of up to 4 custom fields to be displayed on the invoice. If a value for `custom_fields` is specified, the list specified will replace the existing custom field list on this invoice. Pass an empty string to remove previously-defined fields. + CustomFields []*InvoiceUpdateCustomFieldParams `form:"custom_fields"` + // The number of days from which the invoice is created until it is due. Only valid for invoices where `collection_method=send_invoice`. This field can only be updated on `draft` invoices. + DaysUntilDue *int64 `form:"days_until_due"` + // ID of the default payment method for the invoice. It must belong to the customer associated with the invoice. If not set, defaults to the subscription's default payment method, if any, or to the default payment method in the customer's invoice settings. + DefaultPaymentMethod *string `form:"default_payment_method"` + // ID of the default payment source for the invoice. It must belong to the customer associated with the invoice and be in a chargeable state. If not set, defaults to the subscription's default source, if any, or to the customer's default source. + DefaultSource *string `form:"default_source"` + // The tax rates that will apply to any line item that does not have `tax_rates` set. Pass an empty string to remove previously-defined tax rates. + DefaultTaxRates []*string `form:"default_tax_rates"` + // An arbitrary string attached to the object. Often useful for displaying to users. Referenced as 'memo' in the Dashboard. + Description *string `form:"description"` + // The discounts that will apply to the invoice. Pass an empty string to remove previously-defined discounts. + Discounts []*InvoiceUpdateDiscountParams `form:"discounts"` + // The date on which payment for this invoice is due. Only valid for invoices where `collection_method=send_invoice`. This field can only be updated on `draft` invoices. + DueDate *int64 `form:"due_date"` + // The date when this invoice is in effect. Same as `finalized_at` unless overwritten. When defined, this value replaces the system-generated 'Date of issue' printed on the invoice PDF and receipt. + EffectiveAt *int64 `form:"effective_at"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Footer to be displayed on the invoice. + Footer *string `form:"footer"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *InvoiceUpdateIssuerParams `form:"issuer"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Set the number for this invoice. If no number is present then a number will be assigned automatically when the invoice is finalized. In many markets, regulations require invoices to be unique, sequential and / or gapless. You are responsible for ensuring this is true across all your different invoicing systems in the event that you edit the invoice number using our API. If you use only Stripe for your invoices and do not change invoice numbers, Stripe handles this aspect of compliance for you automatically. + Number *string `form:"number"` + // The account (if any) for which the funds of the invoice payment are intended. If set, the invoice will be presented with the branding and support information of the specified account. See the [Invoices with Connect](https://stripe.com/docs/billing/invoices/connect) documentation for details. + OnBehalfOf *string `form:"on_behalf_of"` + // Configuration settings for the PaymentIntent that is generated when the invoice is finalized. + PaymentSettings *InvoiceUpdatePaymentSettingsParams `form:"payment_settings"` + // The rendering-related settings that control how the invoice is displayed on customer-facing surfaces such as PDF and Hosted Invoice Page. + Rendering *InvoiceUpdateRenderingParams `form:"rendering"` + // Settings for the cost of shipping for this invoice. + ShippingCost *InvoiceUpdateShippingCostParams `form:"shipping_cost"` + // Shipping details for the invoice. The Invoice PDF will use the `shipping_details` value if it is set, otherwise the PDF will render the shipping address from the customer. + ShippingDetails *InvoiceUpdateShippingDetailsParams `form:"shipping_details"` + // Extra information about a charge for the customer's credit card statement. It must contain at least one letter. If not specified and this invoice is part of a subscription, the default `statement_descriptor` will be set to the first subscription item's product's `statement_descriptor`. + StatementDescriptor *string `form:"statement_descriptor"` + // If specified, the funds from the invoice will be transferred to the destination and the ID of the resulting transfer will be found on the invoice's charge. This will be unset if you POST an empty value. + TransferData *InvoiceUpdateTransferDataParams `form:"transfer_data"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type InvoiceCreateAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Settings for automatic tax lookup for this invoice. +type InvoiceCreateAutomaticTaxParams struct { + // Whether Stripe automatically computes tax on this invoice. Note that incompatible invoice items (invoice items with manually specified [tax rates](https://stripe.com/docs/api/tax_rates), negative amounts, or `tax_behavior=unspecified`) cannot be added to automatic tax invoices. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *InvoiceCreateAutomaticTaxLiabilityParams `form:"liability"` +} + +// A list of up to 4 custom fields to be displayed on the invoice. +type InvoiceCreateCustomFieldParams struct { + // The name of the custom field. This may be up to 40 characters. + Name *string `form:"name"` + // The value of the custom field. This may be up to 140 characters. + Value *string `form:"value"` +} + +// The coupons and promotion codes to redeem into discounts for the invoice. If not specified, inherits the discount from the invoice's customer. Pass an empty string to avoid inheriting any discounts. +type InvoiceCreateDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// Revise an existing invoice. The new invoice will be created in `status=draft`. See the [revision documentation](https://stripe.com/docs/invoicing/invoice-revisions) for more details. +type InvoiceCreateFromInvoiceParams struct { + // The relation between the new invoice and the original invoice. Currently, only 'revision' is permitted + Action *string `form:"action"` + // The `id` of the invoice that will be cloned. + Invoice *string `form:"invoice"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type InvoiceCreateIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Additional fields for Mandate creation +type InvoiceCreatePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsParams struct { + // Transaction type of the mandate. + TransactionType *string `form:"transaction_type"` +} + +// If paying by `acss_debit`, this sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. +type InvoiceCreatePaymentSettingsPaymentMethodOptionsACSSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *InvoiceCreatePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsParams `form:"mandate_options"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// If paying by `bancontact`, this sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. +type InvoiceCreatePaymentSettingsPaymentMethodOptionsBancontactParams struct { + // Preferred language of the Bancontact authorization page that the customer is redirected to. + PreferredLanguage *string `form:"preferred_language"` +} + +// The selected installment plan to use for this invoice. +type InvoiceCreatePaymentSettingsPaymentMethodOptionsCardInstallmentsPlanParams struct { + // For `fixed_count` installment plans, this is required. It represents the number of installment payments your customer will make to their credit card. + Count *int64 `form:"count"` + // For `fixed_count` installment plans, this is required. It represents the interval between installment payments your customer will make to their credit card. + // One of `month`. + Interval *string `form:"interval"` + // Type of installment plan, one of `fixed_count`, `bonus`, or `revolving`. + Type *string `form:"type"` +} + +// Installment configuration for payments attempted on this invoice (Mexico Only). +// +// For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). +type InvoiceCreatePaymentSettingsPaymentMethodOptionsCardInstallmentsParams struct { + // Setting to true enables installments for this invoice. + // Setting to false will prevent any selected plan from applying to a payment. + Enabled *bool `form:"enabled"` + // The selected installment plan to use for this invoice. + Plan *InvoiceCreatePaymentSettingsPaymentMethodOptionsCardInstallmentsPlanParams `form:"plan"` +} + +// If paying by `card`, this sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. +type InvoiceCreatePaymentSettingsPaymentMethodOptionsCardParams struct { + // Installment configuration for payments attempted on this invoice (Mexico Only). + // + // For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + Installments *InvoiceCreatePaymentSettingsPaymentMethodOptionsCardInstallmentsParams `form:"installments"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure *string `form:"request_three_d_secure"` +} + +// Configuration for eu_bank_transfer funding type. +type InvoiceCreatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country *string `form:"country"` +} + +// Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. +type InvoiceCreatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams struct { + // Configuration for eu_bank_transfer funding type. + EUBankTransfer *InvoiceCreatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams `form:"eu_bank_transfer"` + // The bank transfer type that can be used for funding. Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + Type *string `form:"type"` +} + +// If paying by `customer_balance`, this sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. +type InvoiceCreatePaymentSettingsPaymentMethodOptionsCustomerBalanceParams struct { + // Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + BankTransfer *InvoiceCreatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams `form:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType *string `form:"funding_type"` +} + +// If paying by `konbini`, this sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. +type InvoiceCreatePaymentSettingsPaymentMethodOptionsKonbiniParams struct{} + +// If paying by `sepa_debit`, this sub-hash contains details about the SEPA Direct Debit payment method options to pass to the invoice's PaymentIntent. +type InvoiceCreatePaymentSettingsPaymentMethodOptionsSEPADebitParams struct{} + +// Provide filters for the linked accounts that the customer can select for the payment method. +type InvoiceCreatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams struct { + // The account subcategories to use to filter for selectable accounts. Valid subcategories are `checking` and `savings`. + AccountSubcategories []*string `form:"account_subcategories"` +} + +// Additional fields for Financial Connections Session creation +type InvoiceCreatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsParams struct { + // Provide filters for the linked accounts that the customer can select for the payment method. + Filters *InvoiceCreatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams `form:"filters"` + // The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` +} + +// If paying by `us_bank_account`, this sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. +type InvoiceCreatePaymentSettingsPaymentMethodOptionsUSBankAccountParams struct { + // Additional fields for Financial Connections Session creation + FinancialConnections *InvoiceCreatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsParams `form:"financial_connections"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// Payment-method-specific configuration to provide to the invoice's PaymentIntent. +type InvoiceCreatePaymentSettingsPaymentMethodOptionsParams struct { + // If paying by `acss_debit`, this sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. + ACSSDebit *InvoiceCreatePaymentSettingsPaymentMethodOptionsACSSDebitParams `form:"acss_debit"` + // If paying by `bancontact`, this sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. + Bancontact *InvoiceCreatePaymentSettingsPaymentMethodOptionsBancontactParams `form:"bancontact"` + // If paying by `card`, this sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. + Card *InvoiceCreatePaymentSettingsPaymentMethodOptionsCardParams `form:"card"` + // If paying by `customer_balance`, this sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. + CustomerBalance *InvoiceCreatePaymentSettingsPaymentMethodOptionsCustomerBalanceParams `form:"customer_balance"` + // If paying by `konbini`, this sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. + Konbini *InvoiceCreatePaymentSettingsPaymentMethodOptionsKonbiniParams `form:"konbini"` + // If paying by `sepa_debit`, this sub-hash contains details about the SEPA Direct Debit payment method options to pass to the invoice's PaymentIntent. + SEPADebit *InvoiceCreatePaymentSettingsPaymentMethodOptionsSEPADebitParams `form:"sepa_debit"` + // If paying by `us_bank_account`, this sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. + USBankAccount *InvoiceCreatePaymentSettingsPaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` +} + +// Configuration settings for the PaymentIntent that is generated when the invoice is finalized. +type InvoiceCreatePaymentSettingsParams struct { + // ID of the mandate to be used for this invoice. It must correspond to the payment method used to pay the invoice, including the invoice's default_payment_method or default_source, if set. + DefaultMandate *string `form:"default_mandate"` + // Payment-method-specific configuration to provide to the invoice's PaymentIntent. + PaymentMethodOptions *InvoiceCreatePaymentSettingsPaymentMethodOptionsParams `form:"payment_method_options"` + // The list of payment method types (e.g. card) to provide to the invoice's PaymentIntent. If not set, Stripe attempts to automatically determine the types to use by looking at the invoice's default payment method, the subscription's default payment method, the customer's default payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). Should not be specified with payment_method_configuration + PaymentMethodTypes []*string `form:"payment_method_types"` +} + +// Invoice pdf rendering options +type InvoiceCreateRenderingPDFParams struct { + // Page size for invoice PDF. Can be set to `a4`, `letter`, or `auto`. + // If set to `auto`, invoice PDF page size defaults to `a4` for customers with + // Japanese locale and `letter` for customers with other locales. + PageSize *string `form:"page_size"` +} + +// The rendering-related settings that control how the invoice is displayed on customer-facing surfaces such as PDF and Hosted Invoice Page. +type InvoiceCreateRenderingParams struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + AmountTaxDisplay *string `form:"amount_tax_display"` + // Invoice pdf rendering options + PDF *InvoiceCreateRenderingPDFParams `form:"pdf"` + // ID of the invoice rendering template to use for this invoice. + Template *string `form:"template"` + // The specific version of invoice rendering template to use for this invoice. + TemplateVersion *int64 `form:"template_version"` +} + +// The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. +type InvoiceCreateShippingCostShippingRateDataDeliveryEstimateMaximumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The lower bound of the estimated range. If empty, represents no lower bound. +type InvoiceCreateShippingCostShippingRateDataDeliveryEstimateMinimumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. +type InvoiceCreateShippingCostShippingRateDataDeliveryEstimateParams struct { + // The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. + Maximum *InvoiceCreateShippingCostShippingRateDataDeliveryEstimateMaximumParams `form:"maximum"` + // The lower bound of the estimated range. If empty, represents no lower bound. + Minimum *InvoiceCreateShippingCostShippingRateDataDeliveryEstimateMinimumParams `form:"minimum"` +} + +// Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type InvoiceCreateShippingCostShippingRateDataFixedAmountCurrencyOptionsParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` +} + +// Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. +type InvoiceCreateShippingCostShippingRateDataFixedAmountParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*InvoiceCreateShippingCostShippingRateDataFixedAmountCurrencyOptionsParams `form:"currency_options"` +} + +// Parameters to create a new ad-hoc shipping rate for this order. +type InvoiceCreateShippingCostShippingRateDataParams struct { + // The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. + DeliveryEstimate *InvoiceCreateShippingCostShippingRateDataDeliveryEstimateParams `form:"delivery_estimate"` + // The name of the shipping rate, meant to be displayable to the customer. This will appear on CheckoutSessions. + DisplayName *string `form:"display_name"` + // Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. + FixedAmount *InvoiceCreateShippingCostShippingRateDataFixedAmountParams `form:"fixed_amount"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. The Shipping tax code is `txcd_92010001`. + TaxCode *string `form:"tax_code"` + // The type of calculation to use on the shipping rate. + Type *string `form:"type"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceCreateShippingCostShippingRateDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Settings for the cost of shipping for this invoice. +type InvoiceCreateShippingCostParams struct { + // The ID of the shipping rate to use for this order. + ShippingRate *string `form:"shipping_rate"` + // Parameters to create a new ad-hoc shipping rate for this order. + ShippingRateData *InvoiceCreateShippingCostShippingRateDataParams `form:"shipping_rate_data"` +} + +// Shipping details for the invoice. The Invoice PDF will use the `shipping_details` value if it is set, otherwise the PDF will render the shipping address from the customer. +type InvoiceCreateShippingDetailsParams struct { + // Shipping address + Address *AddressParams `form:"address"` + // Recipient name. + Name *string `form:"name"` + // Recipient phone (including extension) + Phone *string `form:"phone"` +} + +// If specified, the funds from the invoice will be transferred to the destination and the ID of the resulting transfer will be found on the invoice's charge. +type InvoiceCreateTransferDataParams struct { + // The amount that will be transferred automatically when the invoice is paid. If no amount is set, the full amount is transferred. + Amount *int64 `form:"amount"` + // ID of an existing, connected Stripe account. + Destination *string `form:"destination"` +} + +// This endpoint creates a draft invoice for a given customer. The invoice remains a draft until you [finalize the invoice, which allows you to [pay](#pay_invoice) or send](https://docs.stripe.com/api#finalize_invoice) the invoice to your customers. +type InvoiceCreateParams struct { + Params `form:"*"` + // The account tax IDs associated with the invoice. Only editable when the invoice is a draft. + AccountTaxIDs []*string `form:"account_tax_ids"` + // A fee in cents (or local equivalent) that will be applied to the invoice and transferred to the application owner's Stripe account. The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. For more information, see the application fees [documentation](https://stripe.com/docs/billing/invoices/connect#collecting-fees). + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // Controls whether Stripe performs [automatic collection](https://stripe.com/docs/invoicing/integration/automatic-advancement-collection) of the invoice. If `false`, the invoice's state doesn't automatically advance without an explicit action. + AutoAdvance *bool `form:"auto_advance"` + // The time when this invoice should be scheduled to finalize. The invoice will be finalized at this time if it is still in draft state. + AutomaticallyFinalizesAt *int64 `form:"automatically_finalizes_at"` + // Settings for automatic tax lookup for this invoice. + AutomaticTax *InvoiceCreateAutomaticTaxParams `form:"automatic_tax"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay this invoice using the default source attached to the customer. When sending an invoice, Stripe will email this invoice to the customer with payment instructions. Defaults to `charge_automatically`. + CollectionMethod *string `form:"collection_method"` + // The currency to create this invoice in. Defaults to that of `customer` if not specified. + Currency *string `form:"currency"` + // The ID of the customer who will be billed. + Customer *string `form:"customer"` + // A list of up to 4 custom fields to be displayed on the invoice. + CustomFields []*InvoiceCreateCustomFieldParams `form:"custom_fields"` + // The number of days from when the invoice is created until it is due. Valid only for invoices where `collection_method=send_invoice`. + DaysUntilDue *int64 `form:"days_until_due"` + // ID of the default payment method for the invoice. It must belong to the customer associated with the invoice. If not set, defaults to the subscription's default payment method, if any, or to the default payment method in the customer's invoice settings. + DefaultPaymentMethod *string `form:"default_payment_method"` + // ID of the default payment source for the invoice. It must belong to the customer associated with the invoice and be in a chargeable state. If not set, defaults to the subscription's default source, if any, or to the customer's default source. + DefaultSource *string `form:"default_source"` + // The tax rates that will apply to any line item that does not have `tax_rates` set. + DefaultTaxRates []*string `form:"default_tax_rates"` + // An arbitrary string attached to the object. Often useful for displaying to users. Referenced as 'memo' in the Dashboard. + Description *string `form:"description"` + // The coupons and promotion codes to redeem into discounts for the invoice. If not specified, inherits the discount from the invoice's customer. Pass an empty string to avoid inheriting any discounts. + Discounts []*InvoiceCreateDiscountParams `form:"discounts"` + // The date on which payment for this invoice is due. Valid only for invoices where `collection_method=send_invoice`. + DueDate *int64 `form:"due_date"` + // The date when this invoice is in effect. Same as `finalized_at` unless overwritten. When defined, this value replaces the system-generated 'Date of issue' printed on the invoice PDF and receipt. + EffectiveAt *int64 `form:"effective_at"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Footer to be displayed on the invoice. + Footer *string `form:"footer"` + // Revise an existing invoice. The new invoice will be created in `status=draft`. See the [revision documentation](https://stripe.com/docs/invoicing/invoice-revisions) for more details. + FromInvoice *InvoiceCreateFromInvoiceParams `form:"from_invoice"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *InvoiceCreateIssuerParams `form:"issuer"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Set the number for this invoice. If no number is present then a number will be assigned automatically when the invoice is finalized. In many markets, regulations require invoices to be unique, sequential and / or gapless. You are responsible for ensuring this is true across all your different invoicing systems in the event that you edit the invoice number using our API. If you use only Stripe for your invoices and do not change invoice numbers, Stripe handles this aspect of compliance for you automatically. + Number *string `form:"number"` + // The account (if any) for which the funds of the invoice payment are intended. If set, the invoice will be presented with the branding and support information of the specified account. See the [Invoices with Connect](https://stripe.com/docs/billing/invoices/connect) documentation for details. + OnBehalfOf *string `form:"on_behalf_of"` + // Configuration settings for the PaymentIntent that is generated when the invoice is finalized. + PaymentSettings *InvoiceCreatePaymentSettingsParams `form:"payment_settings"` + // How to handle pending invoice items on invoice creation. Defaults to `exclude` if the parameter is omitted. + PendingInvoiceItemsBehavior *string `form:"pending_invoice_items_behavior"` + // The rendering-related settings that control how the invoice is displayed on customer-facing surfaces such as PDF and Hosted Invoice Page. + Rendering *InvoiceCreateRenderingParams `form:"rendering"` + // Settings for the cost of shipping for this invoice. + ShippingCost *InvoiceCreateShippingCostParams `form:"shipping_cost"` + // Shipping details for the invoice. The Invoice PDF will use the `shipping_details` value if it is set, otherwise the PDF will render the shipping address from the customer. + ShippingDetails *InvoiceCreateShippingDetailsParams `form:"shipping_details"` + // Extra information about a charge for the customer's credit card statement. It must contain at least one letter. If not specified and this invoice is part of a subscription, the default `statement_descriptor` will be set to the first subscription item's product's `statement_descriptor`. + StatementDescriptor *string `form:"statement_descriptor"` + // The ID of the subscription to invoice, if any. If set, the created invoice will only include pending invoice items for that subscription. The subscription's billing cycle and regular subscription events won't be affected. + Subscription *string `form:"subscription"` + // If specified, the funds from the invoice will be transferred to the destination and the ID of the resulting transfer will be found on the invoice's charge. + TransferData *InvoiceCreateTransferDataParams `form:"transfer_data"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type InvoiceAutomaticTaxLiability struct { + // The connected account being referenced when `type` is `account`. + Account *Account `json:"account"` + // Type of the account referenced. + Type InvoiceAutomaticTaxLiabilityType `json:"type"` +} +type InvoiceAutomaticTax struct { + // If Stripe disabled automatic tax, this enum describes why. + DisabledReason InvoiceAutomaticTaxDisabledReason `json:"disabled_reason"` + // Whether Stripe automatically computes tax on this invoice. Note that incompatible invoice items (invoice items with manually specified [tax rates](https://stripe.com/docs/api/tax_rates), negative amounts, or `tax_behavior=unspecified`) cannot be added to automatic tax invoices. + Enabled bool `json:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *InvoiceAutomaticTaxLiability `json:"liability"` + // The tax provider powering automatic tax. + Provider string `json:"provider"` + // The status of the most recent automated tax calculation for this invoice. + Status InvoiceAutomaticTaxStatus `json:"status"` +} + +// The confirmation secret associated with this invoice. Currently, this contains the client_secret of the PaymentIntent that Stripe creates during invoice finalization. +type InvoiceConfirmationSecret struct { + // The client_secret of the payment that Stripe creates for the invoice after finalization. + ClientSecret string `json:"client_secret"` + // The type of client_secret. Currently this is always payment_intent, referencing the default payment_intent that Stripe creates during invoice finalization + Type string `json:"type"` +} + +// Custom fields displayed on the invoice. +type InvoiceCustomField struct { + // The name of the custom field. + Name string `json:"name"` + // The value of the custom field. + Value string `json:"value"` +} + +// The customer's tax IDs. Until the invoice is finalized, this field will contain the same tax IDs as `customer.tax_ids`. Once the invoice is finalized, this field will no longer be updated. +type InvoiceCustomerTaxID struct { + // The type of the tax ID, one of `ad_nrt`, `ar_cuit`, `eu_vat`, `bo_tin`, `br_cnpj`, `br_cpf`, `cn_tin`, `co_nit`, `cr_tin`, `do_rcn`, `ec_ruc`, `eu_oss_vat`, `hr_oib`, `pe_ruc`, `ro_tin`, `rs_pib`, `sv_nit`, `uy_ruc`, `ve_rif`, `vn_tin`, `gb_vat`, `nz_gst`, `au_abn`, `au_arn`, `in_gst`, `no_vat`, `no_voec`, `za_vat`, `ch_vat`, `mx_rfc`, `sg_uen`, `ru_inn`, `ru_kpp`, `ca_bn`, `hk_br`, `es_cif`, `tw_vat`, `th_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `li_uid`, `li_vat`, `my_itn`, `us_ein`, `kr_brn`, `ca_qst`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `my_sst`, `sg_gst`, `ae_trn`, `cl_tin`, `sa_vat`, `id_npwp`, `my_frp`, `il_vat`, `ge_vat`, `ua_vat`, `is_vat`, `bg_uic`, `hu_tin`, `si_tin`, `ke_pin`, `tr_tin`, `eg_tin`, `ph_tin`, `al_tin`, `bh_vat`, `kz_bin`, `ng_tin`, `om_vat`, `de_stn`, `ch_uid`, `tz_vat`, `uz_vat`, `uz_tin`, `md_vat`, `ma_vat`, `by_tin`, `ao_tin`, `bs_tin`, `bb_tin`, `cd_nif`, `mr_nif`, `me_pib`, `zw_tin`, `ba_tin`, `gn_nif`, `mk_vat`, `sr_fin`, `sn_ninea`, `am_tin`, `np_pan`, `tj_tin`, `ug_tin`, `zm_tin`, `kh_tin`, `aw_tin`, `az_tin`, `bd_bin`, `bj_ifu`, `et_tin`, `kg_tin`, `la_tin`, `cm_niu`, `cv_nif`, `bf_ifu`, or `unknown` + Type *TaxIDType `json:"type"` + // The value of the tax ID. + Value string `json:"value"` +} + +// Details of the invoice that was cloned. See the [revision documentation](https://stripe.com/docs/invoicing/invoice-revisions) for more details. +type InvoiceFromInvoice struct { + // The relation between this invoice and the cloned invoice + Action string `json:"action"` + // The invoice that was cloned. + Invoice *Invoice `json:"invoice"` +} +type InvoiceIssuer struct { + // The connected account being referenced when `type` is `account`. + Account *Account `json:"account"` + // Type of the account referenced. + Type InvoiceIssuerType `json:"type"` +} + +// Details about the quote that generated this invoice +type InvoiceParentQuoteDetails struct { + // The quote that generated this invoice + Quote string `json:"quote"` +} + +// Details about the subscription that generated this invoice +type InvoiceParentSubscriptionDetails struct { + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) defined as subscription metadata when an invoice is created. Becomes an immutable snapshot of the subscription metadata at the time of invoice finalization. + // *Note: This attribute is populated only for invoices created on or after June 29, 2023.* + Metadata map[string]string `json:"metadata"` + // The subscription that generated this invoice + Subscription *Subscription `json:"subscription"` + // Only set for upcoming invoices that preview prorations. The time used to calculate prorations. + SubscriptionProrationDate int64 `json:"subscription_proration_date"` +} + +// The parent that generated this invoice +type InvoiceParent struct { + // Details about the quote that generated this invoice + QuoteDetails *InvoiceParentQuoteDetails `json:"quote_details"` + // Details about the subscription that generated this invoice + SubscriptionDetails *InvoiceParentSubscriptionDetails `json:"subscription_details"` + // The type of parent that generated this invoice + Type InvoiceParentType `json:"type"` +} +type InvoicePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptions struct { + // Transaction type of the mandate. + TransactionType InvoicePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsTransactionType `json:"transaction_type"` +} + +// If paying by `acss_debit`, this sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsACSSDebit struct { + MandateOptions *InvoicePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptions `json:"mandate_options"` + // Bank account verification method. + VerificationMethod InvoicePaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethod `json:"verification_method"` +} + +// If paying by `bancontact`, this sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsBancontact struct { + // Preferred language of the Bancontact authorization page that the customer is redirected to. + PreferredLanguage string `json:"preferred_language"` +} +type InvoicePaymentSettingsPaymentMethodOptionsCardInstallments struct { + // Whether Installments are enabled for this Invoice. + Enabled bool `json:"enabled"` +} + +// If paying by `card`, this sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsCard struct { + Installments *InvoicePaymentSettingsPaymentMethodOptionsCardInstallments `json:"installments"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure InvoicePaymentSettingsPaymentMethodOptionsCardRequestThreeDSecure `json:"request_three_d_secure"` +} +type InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransfer struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country string `json:"country"` +} +type InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer struct { + EUBankTransfer *InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransfer `json:"eu_bank_transfer"` + // The bank transfer type that can be used for funding. Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + Type string `json:"type"` +} + +// If paying by `customer_balance`, this sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsCustomerBalance struct { + BankTransfer *InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer `json:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType InvoicePaymentSettingsPaymentMethodOptionsCustomerBalanceFundingType `json:"funding_type"` +} + +// If paying by `konbini`, this sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsKonbini struct{} + +// If paying by `sepa_debit`, this sub-hash contains details about the SEPA Direct Debit payment method options to pass to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsSEPADebit struct{} +type InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFilters struct { + // The account subcategories to use to filter for possible accounts to link. Valid subcategories are `checking` and `savings`. + AccountSubcategories []InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory `json:"account_subcategories"` +} +type InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnections struct { + Filters *InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFilters `json:"filters"` + // The list of permissions to request. The `payment_method` permission must be included. + Permissions []InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission `json:"permissions"` + // Data features requested to be retrieved upon account creation. + Prefetch []InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch `json:"prefetch"` +} + +// If paying by `us_bank_account`, this sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptionsUSBankAccount struct { + FinancialConnections *InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnections `json:"financial_connections"` + // Bank account verification method. + VerificationMethod InvoicePaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethod `json:"verification_method"` +} + +// Payment-method-specific configuration to provide to the invoice's PaymentIntent. +type InvoicePaymentSettingsPaymentMethodOptions struct { + // If paying by `acss_debit`, this sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. + ACSSDebit *InvoicePaymentSettingsPaymentMethodOptionsACSSDebit `json:"acss_debit"` + // If paying by `bancontact`, this sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. + Bancontact *InvoicePaymentSettingsPaymentMethodOptionsBancontact `json:"bancontact"` + // If paying by `card`, this sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. + Card *InvoicePaymentSettingsPaymentMethodOptionsCard `json:"card"` + // If paying by `customer_balance`, this sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. + CustomerBalance *InvoicePaymentSettingsPaymentMethodOptionsCustomerBalance `json:"customer_balance"` + // If paying by `konbini`, this sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. + Konbini *InvoicePaymentSettingsPaymentMethodOptionsKonbini `json:"konbini"` + // If paying by `sepa_debit`, this sub-hash contains details about the SEPA Direct Debit payment method options to pass to the invoice's PaymentIntent. + SEPADebit *InvoicePaymentSettingsPaymentMethodOptionsSEPADebit `json:"sepa_debit"` + // If paying by `us_bank_account`, this sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. + USBankAccount *InvoicePaymentSettingsPaymentMethodOptionsUSBankAccount `json:"us_bank_account"` +} +type InvoicePaymentSettings struct { + // ID of the mandate to be used for this invoice. It must correspond to the payment method used to pay the invoice, including the invoice's default_payment_method or default_source, if set. + DefaultMandate string `json:"default_mandate"` + // Payment-method-specific configuration to provide to the invoice's PaymentIntent. + PaymentMethodOptions *InvoicePaymentSettingsPaymentMethodOptions `json:"payment_method_options"` + // The list of payment method types (e.g. card) to provide to the invoice's PaymentIntent. If not set, Stripe attempts to automatically determine the types to use by looking at the invoice's default payment method, the subscription's default payment method, the customer's default payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). + PaymentMethodTypes []InvoicePaymentSettingsPaymentMethodType `json:"payment_method_types"` +} + +// Invoice pdf rendering options +type InvoiceRenderingPDF struct { + // Page size of invoice pdf. Options include a4, letter, and auto. If set to auto, page size will be switched to a4 or letter based on customer locale. + PageSize InvoiceRenderingPDFPageSize `json:"page_size"` +} + +// The rendering-related settings that control how the invoice is displayed on customer-facing surfaces such as PDF and Hosted Invoice Page. +type InvoiceRendering struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. + AmountTaxDisplay string `json:"amount_tax_display"` + // Invoice pdf rendering options + PDF *InvoiceRenderingPDF `json:"pdf"` + // ID of the rendering template that the invoice is formatted by. + Template string `json:"template"` + // Version of the rendering template that the invoice is using. + TemplateVersion int64 `json:"template_version"` +} + +// The taxes applied to the shipping rate. +type InvoiceShippingCostTax struct { + // Amount of tax applied for this rate. + Amount int64 `json:"amount"` + // Tax rates can be applied to [invoices](https://docs.stripe.com/invoicing/taxes/tax-rates), [subscriptions](https://docs.stripe.com/billing/taxes/tax-rates) and [Checkout Sessions](https://docs.stripe.com/payments/checkout/use-manual-tax-rates) to collect tax. + // + // Related guide: [Tax rates](https://docs.stripe.com/billing/taxes/tax-rates) + Rate *TaxRate `json:"rate"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason InvoiceShippingCostTaxTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount int64 `json:"taxable_amount"` +} + +// The details of the cost of shipping, including the ShippingRate applied on the invoice. +type InvoiceShippingCost struct { + // Total shipping cost before any taxes are applied. + AmountSubtotal int64 `json:"amount_subtotal"` + // Total tax amount applied due to shipping costs. If no tax was applied, defaults to 0. + AmountTax int64 `json:"amount_tax"` + // Total shipping cost after taxes are applied. + AmountTotal int64 `json:"amount_total"` + // The ID of the ShippingRate for this invoice. + ShippingRate *ShippingRate `json:"shipping_rate"` + // The taxes applied to the shipping rate. + Taxes []*InvoiceShippingCostTax `json:"taxes"` +} +type InvoiceStatusTransitions struct { + // The time that the invoice draft was finalized. + FinalizedAt int64 `json:"finalized_at"` + // The time that the invoice was marked uncollectible. + MarkedUncollectibleAt int64 `json:"marked_uncollectible_at"` + // The time that the invoice was paid. + PaidAt int64 `json:"paid_at"` + // The time that the invoice was voided. + VoidedAt int64 `json:"voided_at"` +} + +// Indicates which line items triggered a threshold invoice. +type InvoiceThresholdReasonItemReason struct { + // The IDs of the line items that triggered the threshold invoice. + LineItemIDs []string `json:"line_item_ids"` + // The quantity threshold boundary that applied to the given line item. + UsageGTE int64 `json:"usage_gte"` +} +type InvoiceThresholdReason struct { + // The total invoice amount threshold boundary if it triggered the threshold invoice. + AmountGTE int64 `json:"amount_gte"` + // Indicates which line items triggered a threshold invoice. + ItemReasons []*InvoiceThresholdReasonItemReason `json:"item_reasons"` +} + +// The aggregate amounts calculated per discount across all line items. +type InvoiceTotalDiscountAmount struct { + // The amount, in cents (or local equivalent), of the discount. + Amount int64 `json:"amount"` + // The discount that was applied to get this discount amount. + Discount *Discount `json:"discount"` +} + +// Contains pretax credit amounts (ex: discount, credit grants, etc) that apply to this invoice. This is a combined list of total_pretax_credit_amounts across all invoice line items. +type InvoiceTotalPretaxCreditAmount struct { + // The amount, in cents (or local equivalent), of the pretax credit amount. + Amount int64 `json:"amount"` + // The credit balance transaction that was applied to get this pretax credit amount. + CreditBalanceTransaction *BillingCreditBalanceTransaction `json:"credit_balance_transaction"` + // The discount that was applied to get this pretax credit amount. + Discount *Discount `json:"discount"` + // Type of the pretax credit amount referenced. + Type InvoiceTotalPretaxCreditAmountType `json:"type"` +} + +// Additional details about the tax rate. Only present when `type` is `tax_rate_details`. +type InvoiceTotalTaxTaxRateDetails struct { + TaxRate string `json:"tax_rate"` +} + +// The aggregate tax information of all line items. +type InvoiceTotalTax struct { + // The amount of the tax, in cents (or local equivalent). + Amount int64 `json:"amount"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason InvoiceTotalTaxTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount int64 `json:"taxable_amount"` + // Whether this tax is inclusive or exclusive. + TaxBehavior InvoiceTotalTaxTaxBehavior `json:"tax_behavior"` + // Additional details about the tax rate. Only present when `type` is `tax_rate_details`. + TaxRateDetails *InvoiceTotalTaxTaxRateDetails `json:"tax_rate_details"` + // The type of tax information. + Type InvoiceTotalTaxType `json:"type"` +} + +// Invoices are statements of amounts owed by a customer, and are either +// generated one-off, or generated periodically from a subscription. +// +// They contain [invoice items](https://stripe.com/docs/api#invoiceitems), and proration adjustments +// that may be caused by subscription upgrades/downgrades (if necessary). +// +// If your invoice is configured to be billed through automatic charges, +// Stripe automatically finalizes your invoice and attempts payment. Note +// that finalizing the invoice, +// [when automatic](https://stripe.com/docs/invoicing/integration/automatic-advancement-collection), does +// not happen immediately as the invoice is created. Stripe waits +// until one hour after the last webhook was successfully sent (or the last +// webhook timed out after failing). If you (and the platforms you may have +// connected to) have no webhooks configured, Stripe waits one hour after +// creation to finalize the invoice. +// +// If your invoice is configured to be billed by sending an email, then based on your +// [email settings](https://dashboard.stripe.com/account/billing/automatic), +// Stripe will email the invoice to your customer and await payment. These +// emails can contain a link to a hosted page to pay the invoice. +// +// Stripe applies any customer credit on the account before determining the +// amount due for the invoice (i.e., the amount that will be actually +// charged). If the amount due for the invoice is less than Stripe's [minimum allowed charge +// per currency](https://docs.stripe.com/docs/currencies#minimum-and-maximum-charge-amounts), the +// invoice is automatically marked paid, and we add the amount due to the +// customer's credit balance which is applied to the next invoice. +// +// More details on the customer's credit balance are +// [here](https://stripe.com/docs/billing/customer/balance). +// +// Related guide: [Send invoices to customers](https://stripe.com/docs/billing/invoices/sending) +type Invoice struct { + APIResource + // The country of the business associated with this invoice, most often the business creating the invoice. + AccountCountry string `json:"account_country"` + // The public name of the business associated with this invoice, most often the business creating the invoice. + AccountName string `json:"account_name"` + // The account tax IDs associated with the invoice. Only editable when the invoice is a draft. + AccountTaxIDs []*TaxID `json:"account_tax_ids"` + // Final amount due at this time for this invoice. If the invoice's total is smaller than the minimum charge amount, for example, or if there is account credit that can be applied to the invoice, the `amount_due` may be 0. If there is a positive `starting_balance` for the invoice (the customer owes money), the `amount_due` will also take that into account. The charge that gets generated for the invoice will be for the amount specified in `amount_due`. + AmountDue int64 `json:"amount_due"` + // Amount that was overpaid on the invoice. The amount overpaid is credited to the customer's credit balance. + AmountOverpaid int64 `json:"amount_overpaid"` + // The amount, in cents (or local equivalent), that was paid. + AmountPaid int64 `json:"amount_paid"` + // The difference between amount_due and amount_paid, in cents (or local equivalent). + AmountRemaining int64 `json:"amount_remaining"` + // This is the sum of all the shipping amounts. + AmountShipping int64 `json:"amount_shipping"` + // ID of the Connect Application that created the invoice. + Application *Application `json:"application"` + // Number of payment attempts made for this invoice, from the perspective of the payment retry schedule. Any payment attempt counts as the first attempt, and subsequently only automatic retries increment the attempt count. In other words, manual payment attempts after the first attempt do not affect the retry schedule. If a failure is returned with a non-retryable return code, the invoice can no longer be retried unless a new payment method is obtained. Retries will continue to be scheduled, and attempt_count will continue to increment, but retries will only be executed if a new payment method is obtained. + AttemptCount int64 `json:"attempt_count"` + // Whether an attempt has been made to pay the invoice. An invoice is not attempted until 1 hour after the `invoice.created` webhook, for example, so you might not want to display that invoice as unpaid to your users. + Attempted bool `json:"attempted"` + // Controls whether Stripe performs [automatic collection](https://stripe.com/docs/invoicing/integration/automatic-advancement-collection) of the invoice. If `false`, the invoice's state doesn't automatically advance without an explicit action. + AutoAdvance bool `json:"auto_advance"` + // The time when this invoice is currently scheduled to be automatically finalized. The field will be `null` if the invoice is not scheduled to finalize in the future. If the invoice is not in the draft state, this field will always be `null` - see `finalized_at` for the time when an already-finalized invoice was finalized. + AutomaticallyFinalizesAt int64 `json:"automatically_finalizes_at"` + AutomaticTax *InvoiceAutomaticTax `json:"automatic_tax"` + // Indicates the reason why the invoice was created. + // + // * `manual`: Unrelated to a subscription, for example, created via the invoice editor. + // * `subscription`: No longer in use. Applies to subscriptions from before May 2018 where no distinction was made between updates, cycles, and thresholds. + // * `subscription_create`: A new subscription was created. + // * `subscription_cycle`: A subscription advanced into a new period. + // * `subscription_threshold`: A subscription reached a billing threshold. + // * `subscription_update`: A subscription was updated. + // * `upcoming`: Reserved for simulated invoices, per the upcoming invoice endpoint. + BillingReason InvoiceBillingReason `json:"billing_reason"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay this invoice using the default source attached to the customer. When sending an invoice, Stripe will email this invoice to the customer with payment instructions. + CollectionMethod InvoiceCollectionMethod `json:"collection_method"` + // The confirmation secret associated with this invoice. Currently, this contains the client_secret of the PaymentIntent that Stripe creates during invoice finalization. + ConfirmationSecret *InvoiceConfirmationSecret `json:"confirmation_secret"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // The ID of the customer who will be billed. + Customer *Customer `json:"customer"` + // The customer's address. Until the invoice is finalized, this field will equal `customer.address`. Once the invoice is finalized, this field will no longer be updated. + CustomerAddress *Address `json:"customer_address"` + // The customer's email. Until the invoice is finalized, this field will equal `customer.email`. Once the invoice is finalized, this field will no longer be updated. + CustomerEmail string `json:"customer_email"` + // The customer's name. Until the invoice is finalized, this field will equal `customer.name`. Once the invoice is finalized, this field will no longer be updated. + CustomerName string `json:"customer_name"` + // The customer's phone number. Until the invoice is finalized, this field will equal `customer.phone`. Once the invoice is finalized, this field will no longer be updated. + CustomerPhone string `json:"customer_phone"` + // The customer's shipping information. Until the invoice is finalized, this field will equal `customer.shipping`. Once the invoice is finalized, this field will no longer be updated. + CustomerShipping *ShippingDetails `json:"customer_shipping"` + // The customer's tax exempt status. Until the invoice is finalized, this field will equal `customer.tax_exempt`. Once the invoice is finalized, this field will no longer be updated. + CustomerTaxExempt *CustomerTaxExempt `json:"customer_tax_exempt"` + // The customer's tax IDs. Until the invoice is finalized, this field will contain the same tax IDs as `customer.tax_ids`. Once the invoice is finalized, this field will no longer be updated. + CustomerTaxIDs []*InvoiceCustomerTaxID `json:"customer_tax_ids"` + // Custom fields displayed on the invoice. + CustomFields []*InvoiceCustomField `json:"custom_fields"` + // ID of the default payment method for the invoice. It must belong to the customer associated with the invoice. If not set, defaults to the subscription's default payment method, if any, or to the default payment method in the customer's invoice settings. + DefaultPaymentMethod *PaymentMethod `json:"default_payment_method"` + // ID of the default payment source for the invoice. It must belong to the customer associated with the invoice and be in a chargeable state. If not set, defaults to the subscription's default source, if any, or to the customer's default source. + DefaultSource *PaymentSource `json:"default_source"` + // The tax rates applied to this invoice, if any. + DefaultTaxRates []*TaxRate `json:"default_tax_rates"` + Deleted bool `json:"deleted"` + // An arbitrary string attached to the object. Often useful for displaying to users. Referenced as 'memo' in the Dashboard. + Description string `json:"description"` + // The discounts applied to the invoice. Line item discounts are applied before invoice discounts. Use `expand[]=discounts` to expand each discount. + Discounts []*Discount `json:"discounts"` + // The date on which payment for this invoice is due. This value will be `null` for invoices where `collection_method=charge_automatically`. + DueDate int64 `json:"due_date"` + // The date when this invoice is in effect. Same as `finalized_at` unless overwritten. When defined, this value replaces the system-generated 'Date of issue' printed on the invoice PDF and receipt. + EffectiveAt int64 `json:"effective_at"` + // Ending customer balance after the invoice is finalized. Invoices are finalized approximately an hour after successful webhook delivery or when payment collection is attempted for the invoice. If the invoice has not been finalized yet, this will be null. + EndingBalance int64 `json:"ending_balance"` + // Footer displayed on the invoice. + Footer string `json:"footer"` + // Details of the invoice that was cloned. See the [revision documentation](https://stripe.com/docs/invoicing/invoice-revisions) for more details. + FromInvoice *InvoiceFromInvoice `json:"from_invoice"` + // The URL for the hosted invoice page, which allows customers to view and pay an invoice. If the invoice has not been finalized yet, this will be null. + HostedInvoiceURL string `json:"hosted_invoice_url"` + // Unique identifier for the object. For preview invoices created using the [create preview](https://stripe.com/docs/api/invoices/create_preview) endpoint, this id will be prefixed with `upcoming_in`. + ID string `json:"id"` + // The link to download the PDF for the invoice. If the invoice has not been finalized yet, this will be null. + InvoicePDF string `json:"invoice_pdf"` + Issuer *InvoiceIssuer `json:"issuer"` + // The error encountered during the previous attempt to finalize the invoice. This field is cleared when the invoice is successfully finalized. + LastFinalizationError *Error `json:"last_finalization_error"` + // The ID of the most recent non-draft revision of this invoice + LatestRevision *Invoice `json:"latest_revision"` + // The individual line items that make up the invoice. `lines` is sorted as follows: (1) pending invoice items (including prorations) in reverse chronological order, (2) subscription items in reverse chronological order, and (3) invoice items added after invoice creation in chronological order. + Lines *InvoiceLineItemList `json:"lines"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // The time at which payment will next be attempted. This value will be `null` for invoices where `collection_method=send_invoice`. + NextPaymentAttempt int64 `json:"next_payment_attempt"` + // A unique, identifying string that appears on emails sent to the customer for this invoice. This starts with the customer's unique invoice_prefix if it is specified. + Number string `json:"number"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The account (if any) for which the funds of the invoice payment are intended. If set, the invoice will be presented with the branding and support information of the specified account. See the [Invoices with Connect](https://stripe.com/docs/billing/invoices/connect) documentation for details. + OnBehalfOf *Account `json:"on_behalf_of"` + // The parent that generated this invoice + Parent *InvoiceParent `json:"parent"` + // Payments for this invoice + Payments *InvoicePaymentList `json:"payments"` + PaymentSettings *InvoicePaymentSettings `json:"payment_settings"` + // End of the usage period during which invoice items were added to this invoice. This looks back one period for a subscription invoice. Use the [line item period](https://docs.stripe.com/api/invoices/line_item#invoice_line_item_object-period) to get the service period for each price. + PeriodEnd int64 `json:"period_end"` + // Start of the usage period during which invoice items were added to this invoice. This looks back one period for a subscription invoice. Use the [line item period](https://docs.stripe.com/api/invoices/line_item#invoice_line_item_object-period) to get the service period for each price. + PeriodStart int64 `json:"period_start"` + // Total amount of all post-payment credit notes issued for this invoice. + PostPaymentCreditNotesAmount int64 `json:"post_payment_credit_notes_amount"` + // Total amount of all pre-payment credit notes issued for this invoice. + PrePaymentCreditNotesAmount int64 `json:"pre_payment_credit_notes_amount"` + // This is the transaction number that appears on email receipts sent for this invoice. + ReceiptNumber string `json:"receipt_number"` + // The rendering-related settings that control how the invoice is displayed on customer-facing surfaces such as PDF and Hosted Invoice Page. + Rendering *InvoiceRendering `json:"rendering"` + // The details of the cost of shipping, including the ShippingRate applied on the invoice. + ShippingCost *InvoiceShippingCost `json:"shipping_cost"` + // Shipping details for the invoice. The Invoice PDF will use the `shipping_details` value if it is set, otherwise the PDF will render the shipping address from the customer. + ShippingDetails *ShippingDetails `json:"shipping_details"` + // Starting customer balance before the invoice is finalized. If the invoice has not been finalized yet, this will be the current customer balance. For revision invoices, this also includes any customer balance that was applied to the original invoice. + StartingBalance int64 `json:"starting_balance"` + // Extra information about an invoice for the customer's credit card statement. + StatementDescriptor string `json:"statement_descriptor"` + // The status of the invoice, one of `draft`, `open`, `paid`, `uncollectible`, or `void`. [Learn more](https://stripe.com/docs/billing/invoices/workflow#workflow-overview) + Status InvoiceStatus `json:"status"` + StatusTransitions *InvoiceStatusTransitions `json:"status_transitions"` + // Total of all subscriptions, invoice items, and prorations on the invoice before any invoice level discount or exclusive tax is applied. Item discounts are already incorporated + Subtotal int64 `json:"subtotal"` + // The integer amount in cents (or local equivalent) representing the subtotal of the invoice before any invoice level discount or tax is applied. Item discounts are already incorporated + SubtotalExcludingTax int64 `json:"subtotal_excluding_tax"` + // ID of the test clock this invoice belongs to. + TestClock *TestHelpersTestClock `json:"test_clock"` + ThresholdReason *InvoiceThresholdReason `json:"threshold_reason"` + // Total after discounts and taxes. + Total int64 `json:"total"` + // The aggregate amounts calculated per discount across all line items. + TotalDiscountAmounts []*InvoiceTotalDiscountAmount `json:"total_discount_amounts"` + // The integer amount in cents (or local equivalent) representing the total amount of the invoice including all discounts but excluding all tax. + TotalExcludingTax int64 `json:"total_excluding_tax"` + // Contains pretax credit amounts (ex: discount, credit grants, etc) that apply to this invoice. This is a combined list of total_pretax_credit_amounts across all invoice line items. + TotalPretaxCreditAmounts []*InvoiceTotalPretaxCreditAmount `json:"total_pretax_credit_amounts"` + // The aggregate tax information of all line items. + TotalTaxes []*InvoiceTotalTax `json:"total_taxes"` + // Invoices are automatically paid or sent 1 hour after webhooks are delivered, or until all webhook delivery attempts have [been exhausted](https://stripe.com/docs/billing/webhooks#understand). This field tracks the time when webhooks for this invoice were successfully delivered. If the invoice had no webhooks to deliver, this will be set while the invoice is being created. + WebhooksDeliveredAt int64 `json:"webhooks_delivered_at"` +} + +// InvoiceList is a list of Invoices as retrieved from a list endpoint. +type InvoiceList struct { + APIResource + ListMeta + Data []*Invoice `json:"data"` +} + +// InvoiceSearchResult is a list of Invoice search results as retrieved from a search endpoint. +type InvoiceSearchResult struct { + APIResource + SearchMeta + Data []*Invoice `json:"data"` +} + +// UnmarshalJSON handles deserialization of an Invoice. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (i *Invoice) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + i.ID = id + return nil + } + + type invoice Invoice + var v invoice + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *i = Invoice(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/invoice_service.go b/vendor/github.com/stripe/stripe-go/v82/invoice_service.go new file mode 100644 index 00000000..d69361fb --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/invoice_service.go @@ -0,0 +1,269 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1InvoiceService is used to invoke /v1/invoices APIs. +type v1InvoiceService struct { + B Backend + Key string +} + +// This endpoint creates a draft invoice for a given customer. The invoice remains a draft until you [finalize the invoice, which allows you to [pay](#pay_invoice) or send](https://docs.stripe.com/api#finalize_invoice) the invoice to your customers. +func (c v1InvoiceService) Create(ctx context.Context, params *InvoiceCreateParams) (*Invoice, error) { + if params == nil { + params = &InvoiceCreateParams{} + } + params.Context = ctx + invoice := &Invoice{} + err := c.B.Call(http.MethodPost, "/v1/invoices", c.Key, params, invoice) + return invoice, err +} + +// Retrieves the invoice with the given ID. +func (c v1InvoiceService) Retrieve(ctx context.Context, id string, params *InvoiceRetrieveParams) (*Invoice, error) { + if params == nil { + params = &InvoiceRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoices/%s", id) + invoice := &Invoice{} + err := c.B.Call(http.MethodGet, path, c.Key, params, invoice) + return invoice, err +} + +// Draft invoices are fully editable. Once an invoice is [finalized](https://docs.stripe.com/docs/billing/invoices/workflow#finalized), +// monetary values, as well as collection_method, become uneditable. +// +// If you would like to stop the Stripe Billing engine from automatically finalizing, reattempting payments on, +// sending reminders for, or [automatically reconciling](https://docs.stripe.com/docs/billing/invoices/reconciliation) invoices, pass +// auto_advance=false. +func (c v1InvoiceService) Update(ctx context.Context, id string, params *InvoiceUpdateParams) (*Invoice, error) { + if params == nil { + params = &InvoiceUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoices/%s", id) + invoice := &Invoice{} + err := c.B.Call(http.MethodPost, path, c.Key, params, invoice) + return invoice, err +} + +// Permanently deletes a one-off invoice draft. This cannot be undone. Attempts to delete invoices that are no longer in a draft state will fail; once an invoice has been finalized or if an invoice is for a subscription, it must be [voided](https://docs.stripe.com/api#void_invoice). +func (c v1InvoiceService) Delete(ctx context.Context, id string, params *InvoiceDeleteParams) (*Invoice, error) { + if params == nil { + params = &InvoiceDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoices/%s", id) + invoice := &Invoice{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, invoice) + return invoice, err +} + +// Adds multiple line items to an invoice. This is only possible when an invoice is still a draft. +func (c v1InvoiceService) AddLines(ctx context.Context, id string, params *InvoiceAddLinesParams) (*Invoice, error) { + if params == nil { + params = &InvoiceAddLinesParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoices/%s/add_lines", id) + invoice := &Invoice{} + err := c.B.Call(http.MethodPost, path, c.Key, params, invoice) + return invoice, err +} + +// Attaches a PaymentIntent or an Out of Band Payment to the invoice, adding it to the list of payments. +// +// For the PaymentIntent, when the PaymentIntent's status changes to succeeded, the payment is credited +// to the invoice, increasing its amount_paid. When the invoice is fully paid, the +// invoice's status becomes paid. +// +// If the PaymentIntent's status is already succeeded when it's attached, it's +// credited to the invoice immediately. +// +// See: [Partial payments](https://docs.stripe.com/docs/invoicing/partial-payments) to learn more. +func (c v1InvoiceService) AttachPayment(ctx context.Context, id string, params *InvoiceAttachPaymentParams) (*Invoice, error) { + if params == nil { + params = &InvoiceAttachPaymentParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoices/%s/attach_payment", id) + invoice := &Invoice{} + err := c.B.Call(http.MethodPost, path, c.Key, params, invoice) + return invoice, err +} + +// At any time, you can preview the upcoming invoice for a subscription or subscription schedule. This will show you all the charges that are pending, including subscription renewal charges, invoice item charges, etc. It will also show you any discounts that are applicable to the invoice. +// +// You can also preview the effects of creating or updating a subscription or subscription schedule, including a preview of any prorations that will take place. To ensure that the actual proration is calculated exactly the same as the previewed proration, you should pass the subscription_details.proration_date parameter when doing the actual subscription update. +// +// The recommended way to get only the prorations being previewed on the invoice is to consider line items where parent.subscription_item_details.proration is true. +// +// Note that when you are viewing an upcoming invoice, you are simply viewing a preview – the invoice has not yet been created. As such, the upcoming invoice will not show up in invoice listing calls, and you cannot use the API to pay or edit the invoice. If you want to change the amount that your customer will be billed, you can add, remove, or update pending invoice items, or update the customer's discount. +// +// Note: Currency conversion calculations use the latest exchange rates. Exchange rates may vary between the time of the preview and the time of the actual invoice creation. [Learn more](https://docs.stripe.com/currencies/conversions) +func (c v1InvoiceService) CreatePreview(ctx context.Context, params *InvoiceCreatePreviewParams) (*Invoice, error) { + if params == nil { + params = &InvoiceCreatePreviewParams{} + } + params.Context = ctx + invoice := &Invoice{} + err := c.B.Call( + http.MethodPost, "/v1/invoices/create_preview", c.Key, params, invoice) + return invoice, err +} + +// Stripe automatically finalizes drafts before sending and attempting payment on invoices. However, if you'd like to finalize a draft invoice manually, you can do so using this method. +func (c v1InvoiceService) FinalizeInvoice(ctx context.Context, id string, params *InvoiceFinalizeInvoiceParams) (*Invoice, error) { + if params == nil { + params = &InvoiceFinalizeInvoiceParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoices/%s/finalize", id) + invoice := &Invoice{} + err := c.B.Call(http.MethodPost, path, c.Key, params, invoice) + return invoice, err +} + +// Marking an invoice as uncollectible is useful for keeping track of bad debts that can be written off for accounting purposes. +func (c v1InvoiceService) MarkUncollectible(ctx context.Context, id string, params *InvoiceMarkUncollectibleParams) (*Invoice, error) { + if params == nil { + params = &InvoiceMarkUncollectibleParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoices/%s/mark_uncollectible", id) + invoice := &Invoice{} + err := c.B.Call(http.MethodPost, path, c.Key, params, invoice) + return invoice, err +} + +// Stripe automatically creates and then attempts to collect payment on invoices for customers on subscriptions according to your [subscriptions settings](https://dashboard.stripe.com/account/billing/automatic). However, if you'd like to attempt payment on an invoice out of the normal collection schedule or for some other reason, you can do so. +func (c v1InvoiceService) Pay(ctx context.Context, id string, params *InvoicePayParams) (*Invoice, error) { + if params == nil { + params = &InvoicePayParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoices/%s/pay", id) + invoice := &Invoice{} + err := c.B.Call(http.MethodPost, path, c.Key, params, invoice) + return invoice, err +} + +// Removes multiple line items from an invoice. This is only possible when an invoice is still a draft. +func (c v1InvoiceService) RemoveLines(ctx context.Context, id string, params *InvoiceRemoveLinesParams) (*Invoice, error) { + if params == nil { + params = &InvoiceRemoveLinesParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoices/%s/remove_lines", id) + invoice := &Invoice{} + err := c.B.Call(http.MethodPost, path, c.Key, params, invoice) + return invoice, err +} + +// Stripe will automatically send invoices to customers according to your [subscriptions settings](https://dashboard.stripe.com/account/billing/automatic). However, if you'd like to manually send an invoice to your customer out of the normal schedule, you can do so. When sending invoices that have already been paid, there will be no reference to the payment in the email. +// +// Requests made in test-mode result in no emails being sent, despite sending an invoice.sent event. +func (c v1InvoiceService) SendInvoice(ctx context.Context, id string, params *InvoiceSendInvoiceParams) (*Invoice, error) { + if params == nil { + params = &InvoiceSendInvoiceParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoices/%s/send", id) + invoice := &Invoice{} + err := c.B.Call(http.MethodPost, path, c.Key, params, invoice) + return invoice, err +} + +// Updates multiple line items on an invoice. This is only possible when an invoice is still a draft. +func (c v1InvoiceService) UpdateLines(ctx context.Context, id string, params *InvoiceUpdateLinesParams) (*Invoice, error) { + if params == nil { + params = &InvoiceUpdateLinesParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoices/%s/update_lines", id) + invoice := &Invoice{} + err := c.B.Call(http.MethodPost, path, c.Key, params, invoice) + return invoice, err +} + +// Mark a finalized invoice as void. This cannot be undone. Voiding an invoice is similar to [deletion](https://docs.stripe.com/api#delete_invoice), however it only applies to finalized invoices and maintains a papertrail where the invoice can still be found. +// +// Consult with local regulations to determine whether and how an invoice might be amended, canceled, or voided in the jurisdiction you're doing business in. You might need to [issue another invoice or credit note](https://docs.stripe.com/api#create_invoice) instead. Stripe recommends that you consult with your legal counsel for advice specific to your business. +func (c v1InvoiceService) VoidInvoice(ctx context.Context, id string, params *InvoiceVoidInvoiceParams) (*Invoice, error) { + if params == nil { + params = &InvoiceVoidInvoiceParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoices/%s/void", id) + invoice := &Invoice{} + err := c.B.Call(http.MethodPost, path, c.Key, params, invoice) + return invoice, err +} + +// You can list all invoices, or list the invoices for a specific customer. The invoices are returned sorted by creation date, with the most recently created invoices appearing first. +func (c v1InvoiceService) List(ctx context.Context, listParams *InvoiceListParams) Seq2[*Invoice, error] { + if listParams == nil { + listParams = &InvoiceListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Invoice, ListContainer, error) { + list := &InvoiceList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/invoices", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// When retrieving an invoice, you'll get a lines property containing the total count of line items and the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. +func (c v1InvoiceService) ListLines(ctx context.Context, listParams *InvoiceListLinesParams) Seq2[*InvoiceLineItem, error] { + if listParams == nil { + listParams = &InvoiceListLinesParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/invoices/%s/lines", StringValue(listParams.Invoice)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*InvoiceLineItem, ListContainer, error) { + list := &InvoiceLineItemList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// Search for invoices you've previously created using Stripe's [Search Query Language](https://docs.stripe.com/docs/search#search-query-language). +// Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating +// conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up +// to an hour behind during outages. Search functionality is not available to merchants in India. +func (c v1InvoiceService) Search(ctx context.Context, params *InvoiceSearchParams) Seq2[*Invoice, error] { + if params == nil { + params = &InvoiceSearchParams{} + } + params.Context = ctx + return newV1SearchList(params, func(p *Params, b *form.Values) ([]*Invoice, SearchContainer, error) { + list := &InvoiceSearchResult{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/invoices/search", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/invoiceitem.go b/vendor/github.com/stripe/stripe-go/v82/invoiceitem.go new file mode 100644 index 00000000..eacb9fa7 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/invoiceitem.go @@ -0,0 +1,421 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The type of parent that generated this invoice item +type InvoiceItemParentType string + +// List of values that InvoiceItemParentType can take +const ( + InvoiceItemParentTypeSubscriptionDetails InvoiceItemParentType = "subscription_details" +) + +// The type of the pricing details. +type InvoiceItemPricingType string + +// List of values that InvoiceItemPricingType can take +const ( + InvoiceItemPricingTypePriceDetails InvoiceItemPricingType = "price_details" +) + +// Deletes an invoice item, removing it from an invoice. Deleting invoice items is only possible when they're not attached to invoices, or if it's attached to a draft invoice. +type InvoiceItemParams struct { + Params `form:"*"` + // The integer amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. If you want to apply a credit to the customer's account, pass a negative amount. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the customer who will be billed when this invoice item is billed. + Customer *string `form:"customer"` + // An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. + Description *string `form:"description"` + // Controls whether discounts apply to this invoice item. Defaults to false for prorations or negative invoice items, and true for all other invoice items. Cannot be set to true for prorations. + Discountable *bool `form:"discountable"` + // The coupons, promotion codes & existing discounts which apply to the invoice item or invoice line item. Item discounts are applied before invoice discounts. Pass an empty string to remove previously-defined discounts. + Discounts []*InvoiceItemDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The ID of an existing invoice to add this invoice item to. When left blank, the invoice item will be added to the next upcoming scheduled invoice. This is useful when adding invoice items in response to an invoice.created webhook. You can only add invoice items to draft invoices and there is a maximum of 250 items per invoice. + Invoice *string `form:"invoice"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. + Period *InvoiceItemPeriodParams `form:"period"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + PriceData *InvoiceItemPriceDataParams `form:"price_data"` + // The pricing information for the invoice item. + Pricing *InvoiceItemPricingParams `form:"pricing"` + // Non-negative integer. The quantity of units for the invoice item. + Quantity *int64 `form:"quantity"` + // The ID of a subscription to add this invoice item to. When left blank, the invoice item is added to the next upcoming scheduled invoice. When set, scheduled invoices for subscriptions other than the specified subscription will ignore the invoice item. Use this when you want to express that an invoice item has been accrued within the context of a particular subscription. + Subscription *string `form:"subscription"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` + // The tax rates which apply to the invoice item. When set, the `default_tax_rates` on the invoice do not apply to this invoice item. Pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` + // The decimal unit amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. This `unit_amount_decimal` will be multiplied by the quantity to get the full amount. Passing in a negative `unit_amount_decimal` will reduce the `amount_due` on the invoice. Accepts at most 12 decimal places. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceItemParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceItemParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The coupons, promotion codes & existing discounts which apply to the invoice item or invoice line item. Item discounts are applied before invoice discounts. Pass an empty string to remove previously-defined discounts. +type InvoiceItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. +type InvoiceItemPeriodParams struct { + // The end of the period, which must be greater than or equal to the start. This value is inclusive. + End *int64 `form:"end"` + // The start of the period. This value is inclusive. + Start *int64 `form:"start"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. +type InvoiceItemPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// The pricing information for the invoice item. +type InvoiceItemPricingParams struct { + // The ID of the price object. + Price *string `form:"price"` +} + +// Returns a list of your invoice items. Invoice items are returned sorted by creation date, with the most recently created invoice items appearing first. +type InvoiceItemListParams struct { + ListParams `form:"*"` + // Only return invoice items that were created during the given date interval. + Created *int64 `form:"created"` + // Only return invoice items that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // The identifier of the customer whose invoice items to return. If none is provided, all invoice items will be returned. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return invoice items belonging to this invoice. If none is provided, all invoice items will be returned. If specifying an invoice, no customer identifier is needed. + Invoice *string `form:"invoice"` + // Set to `true` to only show pending invoice items, which are not yet attached to any invoices. Set to `false` to only show invoice items already attached to invoices. If unspecified, no filter is applied. + Pending *bool `form:"pending"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceItemListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Deletes an invoice item, removing it from an invoice. Deleting invoice items is only possible when they're not attached to invoices, or if it's attached to a draft invoice. +type InvoiceItemDeleteParams struct { + Params `form:"*"` +} + +// Retrieves the invoice item with the given ID. +type InvoiceItemRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceItemRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The coupons, promotion codes & existing discounts which apply to the invoice item or invoice line item. Item discounts are applied before invoice discounts. Pass an empty string to remove previously-defined discounts. +type InvoiceItemUpdateDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. +type InvoiceItemUpdatePeriodParams struct { + // The end of the period, which must be greater than or equal to the start. This value is inclusive. + End *int64 `form:"end"` + // The start of the period. This value is inclusive. + Start *int64 `form:"start"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. +type InvoiceItemUpdatePriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// The pricing information for the invoice item. +type InvoiceItemUpdatePricingParams struct { + // The ID of the price object. + Price *string `form:"price"` +} + +// Updates the amount or description of an invoice item on an upcoming invoice. Updating an invoice item is only possible before the invoice it's attached to is closed. +type InvoiceItemUpdateParams struct { + Params `form:"*"` + // The integer amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. If you want to apply a credit to the customer's account, pass a negative amount. + Amount *int64 `form:"amount"` + // An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. + Description *string `form:"description"` + // Controls whether discounts apply to this invoice item. Defaults to false for prorations or negative invoice items, and true for all other invoice items. Cannot be set to true for prorations. + Discountable *bool `form:"discountable"` + // The coupons, promotion codes & existing discounts which apply to the invoice item or invoice line item. Item discounts are applied before invoice discounts. Pass an empty string to remove previously-defined discounts. + Discounts []*InvoiceItemUpdateDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. + Period *InvoiceItemUpdatePeriodParams `form:"period"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + PriceData *InvoiceItemUpdatePriceDataParams `form:"price_data"` + // The pricing information for the invoice item. + Pricing *InvoiceItemUpdatePricingParams `form:"pricing"` + // Non-negative integer. The quantity of units for the invoice item. + Quantity *int64 `form:"quantity"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` + // The tax rates which apply to the invoice item. When set, the `default_tax_rates` on the invoice do not apply to this invoice item. Pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` + // The decimal unit amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. This `unit_amount_decimal` will be multiplied by the quantity to get the full amount. Passing in a negative `unit_amount_decimal` will reduce the `amount_due` on the invoice. Accepts at most 12 decimal places. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceItemUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceItemUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The coupons and promotion codes to redeem into discounts for the invoice item or invoice line item. +type InvoiceItemCreateDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. +type InvoiceItemCreatePeriodParams struct { + // The end of the period, which must be greater than or equal to the start. This value is inclusive. + End *int64 `form:"end"` + // The start of the period. This value is inclusive. + Start *int64 `form:"start"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. +type InvoiceItemCreatePriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// The pricing information for the invoice item. +type InvoiceItemCreatePricingParams struct { + // The ID of the price object. + Price *string `form:"price"` +} + +// Creates an item to be added to a draft invoice (up to 250 items per invoice). If no invoice is specified, the item will be on the next invoice created for the customer specified. +type InvoiceItemCreateParams struct { + Params `form:"*"` + // The integer amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. Passing in a negative `amount` will reduce the `amount_due` on the invoice. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the customer who will be billed when this invoice item is billed. + Customer *string `form:"customer"` + // An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. + Description *string `form:"description"` + // Controls whether discounts apply to this invoice item. Defaults to false for prorations or negative invoice items, and true for all other invoice items. + Discountable *bool `form:"discountable"` + // The coupons and promotion codes to redeem into discounts for the invoice item or invoice line item. + Discounts []*InvoiceItemCreateDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The ID of an existing invoice to add this invoice item to. When left blank, the invoice item will be added to the next upcoming scheduled invoice. This is useful when adding invoice items in response to an invoice.created webhook. You can only add invoice items to draft invoices and there is a maximum of 250 items per invoice. + Invoice *string `form:"invoice"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. + Period *InvoiceItemCreatePeriodParams `form:"period"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + PriceData *InvoiceItemCreatePriceDataParams `form:"price_data"` + // The pricing information for the invoice item. + Pricing *InvoiceItemCreatePricingParams `form:"pricing"` + // Non-negative integer. The quantity of units for the invoice item. + Quantity *int64 `form:"quantity"` + // The ID of a subscription to add this invoice item to. When left blank, the invoice item is added to the next upcoming scheduled invoice. When set, scheduled invoices for subscriptions other than the specified subscription will ignore the invoice item. Use this when you want to express that an invoice item has been accrued within the context of a particular subscription. + Subscription *string `form:"subscription"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` + // The tax rates which apply to the invoice item. When set, the `default_tax_rates` on the invoice do not apply to this invoice item. + TaxRates []*string `form:"tax_rates"` + // The decimal unit amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. This `unit_amount_decimal` will be multiplied by the quantity to get the full amount. Passing in a negative `unit_amount_decimal` will reduce the `amount_due` on the invoice. Accepts at most 12 decimal places. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceItemCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceItemCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Details about the subscription that generated this invoice item +type InvoiceItemParentSubscriptionDetails struct { + // The subscription that generated this invoice item + Subscription string `json:"subscription"` + // The subscription item that generated this invoice item + SubscriptionItem string `json:"subscription_item"` +} + +// The parent that generated this invoice item. +type InvoiceItemParent struct { + // Details about the subscription that generated this invoice item + SubscriptionDetails *InvoiceItemParentSubscriptionDetails `json:"subscription_details"` + // The type of parent that generated this invoice item + Type InvoiceItemParentType `json:"type"` +} +type InvoiceItemPricingPriceDetails struct { + // The ID of the price this item is associated with. + Price string `json:"price"` + // The ID of the product this item is associated with. + Product string `json:"product"` +} + +// The pricing information of the invoice item. +type InvoiceItemPricing struct { + PriceDetails *InvoiceItemPricingPriceDetails `json:"price_details"` + // The type of the pricing details. + Type InvoiceItemPricingType `json:"type"` + // The unit amount (in the `currency` specified) of the item which contains a decimal value with at most 12 decimal places. + UnitAmountDecimal float64 `json:"unit_amount_decimal,string"` +} + +// Invoice Items represent the component lines of an [invoice](https://stripe.com/docs/api/invoices). When you create an invoice item with an `invoice` field, it is attached to the specified invoice and included as [an invoice line item](https://stripe.com/docs/api/invoices/line_item) within [invoice.lines](https://stripe.com/docs/api/invoices/object#invoice_object-lines). +// +// Invoice Items can be created before you are ready to actually send the invoice. This can be particularly useful when combined +// with a [subscription](https://stripe.com/docs/api/subscriptions). Sometimes you want to add a charge or credit to a customer, but actually charge +// or credit the customer's card only at the end of a regular billing cycle. This is useful for combining several charges +// (to minimize per-transaction fees), or for having Stripe tabulate your usage-based billing totals. +// +// Related guides: [Integrate with the Invoicing API](https://stripe.com/docs/invoicing/integration), [Subscription Invoices](https://stripe.com/docs/billing/invoices/subscription#adding-upcoming-invoice-items). +type InvoiceItem struct { + APIResource + // Amount (in the `currency` specified) of the invoice item. This should always be equal to `unit_amount * quantity`. + Amount int64 `json:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // The ID of the customer who will be billed when this invoice item is billed. + Customer *Customer `json:"customer"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Date int64 `json:"date"` + Deleted bool `json:"deleted"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // If true, discounts will apply to this invoice item. Always false for prorations. + Discountable bool `json:"discountable"` + // The discounts which apply to the invoice item. Item discounts are applied before invoice discounts. Use `expand[]=discounts` to expand each discount. + Discounts []*Discount `json:"discounts"` + // Unique identifier for the object. + ID string `json:"id"` + // The ID of the invoice this invoice item belongs to. + Invoice *Invoice `json:"invoice"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The parent that generated this invoice item. + Parent *InvoiceItemParent `json:"parent"` + Period *Period `json:"period"` + // The pricing information of the invoice item. + Pricing *InvoiceItemPricing `json:"pricing"` + // Whether the invoice item was created automatically as a proration adjustment when the customer switched plans. + Proration bool `json:"proration"` + // Quantity of units for the invoice item. If the invoice item is a proration, the quantity of the subscription that the proration was computed for. + Quantity int64 `json:"quantity"` + // The tax rates which apply to the invoice item. When set, the `default_tax_rates` on the invoice do not apply to this invoice item. + TaxRates []*TaxRate `json:"tax_rates"` + // ID of the test clock this invoice item belongs to. + TestClock *TestHelpersTestClock `json:"test_clock"` +} + +// InvoiceItemList is a list of InvoiceItems as retrieved from a list endpoint. +type InvoiceItemList struct { + APIResource + ListMeta + Data []*InvoiceItem `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/invoiceitem_service.go b/vendor/github.com/stripe/stripe-go/v82/invoiceitem_service.go new file mode 100644 index 00000000..a795a0f5 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/invoiceitem_service.go @@ -0,0 +1,85 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1InvoiceItemService is used to invoke /v1/invoiceitems APIs. +type v1InvoiceItemService struct { + B Backend + Key string +} + +// Creates an item to be added to a draft invoice (up to 250 items per invoice). If no invoice is specified, the item will be on the next invoice created for the customer specified. +func (c v1InvoiceItemService) Create(ctx context.Context, params *InvoiceItemCreateParams) (*InvoiceItem, error) { + if params == nil { + params = &InvoiceItemCreateParams{} + } + params.Context = ctx + invoiceitem := &InvoiceItem{} + err := c.B.Call( + http.MethodPost, "/v1/invoiceitems", c.Key, params, invoiceitem) + return invoiceitem, err +} + +// Retrieves the invoice item with the given ID. +func (c v1InvoiceItemService) Retrieve(ctx context.Context, id string, params *InvoiceItemRetrieveParams) (*InvoiceItem, error) { + if params == nil { + params = &InvoiceItemRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoiceitems/%s", id) + invoiceitem := &InvoiceItem{} + err := c.B.Call(http.MethodGet, path, c.Key, params, invoiceitem) + return invoiceitem, err +} + +// Updates the amount or description of an invoice item on an upcoming invoice. Updating an invoice item is only possible before the invoice it's attached to is closed. +func (c v1InvoiceItemService) Update(ctx context.Context, id string, params *InvoiceItemUpdateParams) (*InvoiceItem, error) { + if params == nil { + params = &InvoiceItemUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoiceitems/%s", id) + invoiceitem := &InvoiceItem{} + err := c.B.Call(http.MethodPost, path, c.Key, params, invoiceitem) + return invoiceitem, err +} + +// Deletes an invoice item, removing it from an invoice. Deleting invoice items is only possible when they're not attached to invoices, or if it's attached to a draft invoice. +func (c v1InvoiceItemService) Delete(ctx context.Context, id string, params *InvoiceItemDeleteParams) (*InvoiceItem, error) { + if params == nil { + params = &InvoiceItemDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoiceitems/%s", id) + invoiceitem := &InvoiceItem{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, invoiceitem) + return invoiceitem, err +} + +// Returns a list of your invoice items. Invoice items are returned sorted by creation date, with the most recently created invoice items appearing first. +func (c v1InvoiceItemService) List(ctx context.Context, listParams *InvoiceItemListParams) Seq2[*InvoiceItem, error] { + if listParams == nil { + listParams = &InvoiceItemListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*InvoiceItem, ListContainer, error) { + list := &InvoiceItemList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/invoiceitems", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/invoicelineitem.go b/vendor/github.com/stripe/stripe-go/v82/invoicelineitem.go new file mode 100644 index 00000000..560fad4e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/invoicelineitem.go @@ -0,0 +1,543 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The type of parent that generated this line item +type InvoiceLineItemParentType string + +// List of values that InvoiceLineItemParentType can take +const ( + InvoiceLineItemParentTypeInvoiceItemDetails InvoiceLineItemParentType = "invoice_item_details" + InvoiceLineItemParentTypeSubscriptionItemDetails InvoiceLineItemParentType = "subscription_item_details" +) + +// Type of the pretax credit amount referenced. +type InvoiceLineItemPretaxCreditAmountType string + +// List of values that InvoiceLineItemPretaxCreditAmountType can take +const ( + InvoiceLineItemPretaxCreditAmountTypeCreditBalanceTransaction InvoiceLineItemPretaxCreditAmountType = "credit_balance_transaction" + InvoiceLineItemPretaxCreditAmountTypeDiscount InvoiceLineItemPretaxCreditAmountType = "discount" +) + +// The type of the pricing details. +type InvoiceLineItemPricingType string + +// List of values that InvoiceLineItemPricingType can take +const ( + InvoiceLineItemPricingTypePriceDetails InvoiceLineItemPricingType = "price_details" +) + +// Whether this tax is inclusive or exclusive. +type InvoiceLineItemTaxTaxBehavior string + +// List of values that InvoiceLineItemTaxTaxBehavior can take +const ( + InvoiceLineItemTaxTaxBehaviorExclusive InvoiceLineItemTaxTaxBehavior = "exclusive" + InvoiceLineItemTaxTaxBehaviorInclusive InvoiceLineItemTaxTaxBehavior = "inclusive" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type InvoiceLineItemTaxTaxabilityReason string + +// List of values that InvoiceLineItemTaxTaxabilityReason can take +const ( + InvoiceLineItemTaxTaxabilityReasonCustomerExempt InvoiceLineItemTaxTaxabilityReason = "customer_exempt" + InvoiceLineItemTaxTaxabilityReasonNotAvailable InvoiceLineItemTaxTaxabilityReason = "not_available" + InvoiceLineItemTaxTaxabilityReasonNotCollecting InvoiceLineItemTaxTaxabilityReason = "not_collecting" + InvoiceLineItemTaxTaxabilityReasonNotSubjectToTax InvoiceLineItemTaxTaxabilityReason = "not_subject_to_tax" + InvoiceLineItemTaxTaxabilityReasonNotSupported InvoiceLineItemTaxTaxabilityReason = "not_supported" + InvoiceLineItemTaxTaxabilityReasonPortionProductExempt InvoiceLineItemTaxTaxabilityReason = "portion_product_exempt" + InvoiceLineItemTaxTaxabilityReasonPortionReducedRated InvoiceLineItemTaxTaxabilityReason = "portion_reduced_rated" + InvoiceLineItemTaxTaxabilityReasonPortionStandardRated InvoiceLineItemTaxTaxabilityReason = "portion_standard_rated" + InvoiceLineItemTaxTaxabilityReasonProductExempt InvoiceLineItemTaxTaxabilityReason = "product_exempt" + InvoiceLineItemTaxTaxabilityReasonProductExemptHoliday InvoiceLineItemTaxTaxabilityReason = "product_exempt_holiday" + InvoiceLineItemTaxTaxabilityReasonProportionallyRated InvoiceLineItemTaxTaxabilityReason = "proportionally_rated" + InvoiceLineItemTaxTaxabilityReasonReducedRated InvoiceLineItemTaxTaxabilityReason = "reduced_rated" + InvoiceLineItemTaxTaxabilityReasonReverseCharge InvoiceLineItemTaxTaxabilityReason = "reverse_charge" + InvoiceLineItemTaxTaxabilityReasonStandardRated InvoiceLineItemTaxTaxabilityReason = "standard_rated" + InvoiceLineItemTaxTaxabilityReasonTaxableBasisReduced InvoiceLineItemTaxTaxabilityReason = "taxable_basis_reduced" + InvoiceLineItemTaxTaxabilityReasonZeroRated InvoiceLineItemTaxTaxabilityReason = "zero_rated" +) + +// The type of tax information. +type InvoiceLineItemTaxType string + +// List of values that InvoiceLineItemTaxType can take +const ( + InvoiceLineItemTaxTypeTaxRateDetails InvoiceLineItemTaxType = "tax_rate_details" +) + +// The coupons, promotion codes & existing discounts which apply to the line item. Item discounts are applied before invoice discounts. Pass an empty string to remove previously-defined discounts. +type InvoiceLineItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. +type InvoiceLineItemPeriodParams struct { + // The end of the period, which must be greater than or equal to the start. This value is inclusive. + End *int64 `form:"end"` + // The start of the period. This value is inclusive. + Start *int64 `form:"start"` +} + +// Data used to generate a new [Product](https://docs.stripe.com/api/products) object inline. One of `product` or `product_data` is required. +type InvoiceLineItemPriceDataProductDataParams struct { + // The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + Description *string `form:"description"` + // A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + Images []*string `form:"images"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The product's name, meant to be displayable to the customer. + Name *string `form:"name"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceLineItemPriceDataProductDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. +type InvoiceLineItemPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. One of `product` or `product_data` is required. + Product *string `form:"product"` + // Data used to generate a new [Product](https://docs.stripe.com/api/products) object inline. One of `product` or `product_data` is required. + ProductData *InvoiceLineItemPriceDataProductDataParams `form:"product_data"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A non-negative integer in cents (or local equivalent) representing how much to charge. One of `unit_amount` or `unit_amount_decimal` is required. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// The pricing information for the invoice item. +type InvoiceLineItemPricingParams struct { + // The ID of the price object. + Price *string `form:"price"` +} + +// Data to find or create a TaxRate object. +// +// Stripe automatically creates or reuses a TaxRate object for each tax amount. If the `tax_rate_data` exactly matches a previous value, Stripe will reuse the TaxRate object. TaxRate objects created automatically by Stripe are immediately archived, do not appear in the line item's `tax_rates`, and cannot be directly added to invoices, payments, or line items. +type InvoiceLineItemTaxAmountTaxRateDataParams struct { + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // An arbitrary string attached to the tax rate for your internal use only. It will not be visible to your customers. + Description *string `form:"description"` + // The display name of the tax rate, which will be shown to users. + DisplayName *string `form:"display_name"` + // This specifies if the tax rate is inclusive or exclusive. + Inclusive *bool `form:"inclusive"` + // The jurisdiction for the tax rate. You can use this label field for tax reporting purposes. It also appears on your customer's invoice. + Jurisdiction *string `form:"jurisdiction"` + // The level of the jurisdiction that imposes this tax rate. + JurisdictionLevel *string `form:"jurisdiction_level"` + // The statutory tax rate percent. This field accepts decimal values between 0 and 100 inclusive with at most 4 decimal places. To accommodate fixed-amount taxes, set the percentage to zero. Stripe will not display zero percentages on the invoice unless the `amount` of the tax is also zero. + Percentage *float64 `form:"percentage"` + // [ISO 3166-2 subdivision code](https://en.wikipedia.org/wiki/ISO_3166-2:US), without country prefix. For example, "NY" for New York, United States. + State *string `form:"state"` + // The high-level tax type, such as `vat` or `sales_tax`. + TaxType *string `form:"tax_type"` +} + +// A list of up to 10 tax amounts for this line item. This can be useful if you calculate taxes on your own or use a third-party to calculate them. You cannot set tax amounts if any line item has [tax_rates](https://stripe.com/docs/api/invoices/line_item#invoice_line_item_object-tax_rates) or if the invoice has [default_tax_rates](https://stripe.com/docs/api/invoices/object#invoice_object-default_tax_rates) or uses [automatic tax](https://stripe.com/docs/tax/invoicing). Pass an empty string to remove previously defined tax amounts. +type InvoiceLineItemTaxAmountParams struct { + // The amount, in cents (or local equivalent), of the tax. + Amount *int64 `form:"amount"` + // The reasoning behind this tax, for example, if the product is tax exempt. + TaxabilityReason *string `form:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount *int64 `form:"taxable_amount"` + // Data to find or create a TaxRate object. + // + // Stripe automatically creates or reuses a TaxRate object for each tax amount. If the `tax_rate_data` exactly matches a previous value, Stripe will reuse the TaxRate object. TaxRate objects created automatically by Stripe are immediately archived, do not appear in the line item's `tax_rates`, and cannot be directly added to invoices, payments, or line items. + TaxRateData *InvoiceLineItemTaxAmountTaxRateDataParams `form:"tax_rate_data"` +} + +// Updates an invoice's line item. Some fields, such as tax_amounts, only live on the invoice line item, +// so they can only be updated through this endpoint. Other fields, such as amount, live on both the invoice +// item and the invoice line item, so updates on this endpoint will propagate to the invoice item as well. +// Updating an invoice's line item is only possible before the invoice is finalized. +type InvoiceLineItemParams struct { + Params `form:"*"` + Invoice *string `form:"-"` // Included in URL + // The integer amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. If you want to apply a credit to the customer's account, pass a negative amount. + Amount *int64 `form:"amount"` + // An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. + Description *string `form:"description"` + // Controls whether discounts apply to this line item. Defaults to false for prorations or negative line items, and true for all other line items. Cannot be set to true for prorations. + Discountable *bool `form:"discountable"` + // The coupons, promotion codes & existing discounts which apply to the line item. Item discounts are applied before invoice discounts. Pass an empty string to remove previously-defined discounts. + Discounts []*InvoiceLineItemDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. For [type=subscription](https://stripe.com/docs/api/invoices/line_item#invoice_line_item_object-type) line items, the incoming metadata specified on the request is directly used to set this value, in contrast to [type=invoiceitem](api/invoices/line_item#invoice_line_item_object-type) line items, where any existing metadata on the invoice line is merged with the incoming data. + Metadata map[string]string `form:"metadata"` + // The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. + Period *InvoiceLineItemPeriodParams `form:"period"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + PriceData *InvoiceLineItemPriceDataParams `form:"price_data"` + // The pricing information for the invoice item. + Pricing *InvoiceLineItemPricingParams `form:"pricing"` + // Non-negative integer. The quantity of units for the line item. + Quantity *int64 `form:"quantity"` + // A list of up to 10 tax amounts for this line item. This can be useful if you calculate taxes on your own or use a third-party to calculate them. You cannot set tax amounts if any line item has [tax_rates](https://stripe.com/docs/api/invoices/line_item#invoice_line_item_object-tax_rates) or if the invoice has [default_tax_rates](https://stripe.com/docs/api/invoices/object#invoice_object-default_tax_rates) or uses [automatic tax](https://stripe.com/docs/tax/invoicing). Pass an empty string to remove previously defined tax amounts. + TaxAmounts []*InvoiceLineItemTaxAmountParams `form:"tax_amounts"` + // The tax rates which apply to the line item. When set, the `default_tax_rates` on the invoice do not apply to this line item. Pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceLineItemParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceLineItemParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The coupons, promotion codes & existing discounts which apply to the line item. Item discounts are applied before invoice discounts. Pass an empty string to remove previously-defined discounts. +type InvoiceLineItemUpdateDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. +type InvoiceLineItemUpdatePeriodParams struct { + // The end of the period, which must be greater than or equal to the start. This value is inclusive. + End *int64 `form:"end"` + // The start of the period. This value is inclusive. + Start *int64 `form:"start"` +} + +// Data used to generate a new [Product](https://docs.stripe.com/api/products) object inline. One of `product` or `product_data` is required. +type InvoiceLineItemUpdatePriceDataProductDataParams struct { + // The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + Description *string `form:"description"` + // A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + Images []*string `form:"images"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The product's name, meant to be displayable to the customer. + Name *string `form:"name"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceLineItemUpdatePriceDataProductDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. +type InvoiceLineItemUpdatePriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. One of `product` or `product_data` is required. + Product *string `form:"product"` + // Data used to generate a new [Product](https://docs.stripe.com/api/products) object inline. One of `product` or `product_data` is required. + ProductData *InvoiceLineItemUpdatePriceDataProductDataParams `form:"product_data"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A non-negative integer in cents (or local equivalent) representing how much to charge. One of `unit_amount` or `unit_amount_decimal` is required. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// The pricing information for the invoice item. +type InvoiceLineItemUpdatePricingParams struct { + // The ID of the price object. + Price *string `form:"price"` +} + +// Data to find or create a TaxRate object. +// +// Stripe automatically creates or reuses a TaxRate object for each tax amount. If the `tax_rate_data` exactly matches a previous value, Stripe will reuse the TaxRate object. TaxRate objects created automatically by Stripe are immediately archived, do not appear in the line item's `tax_rates`, and cannot be directly added to invoices, payments, or line items. +type InvoiceLineItemUpdateTaxAmountTaxRateDataParams struct { + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // An arbitrary string attached to the tax rate for your internal use only. It will not be visible to your customers. + Description *string `form:"description"` + // The display name of the tax rate, which will be shown to users. + DisplayName *string `form:"display_name"` + // This specifies if the tax rate is inclusive or exclusive. + Inclusive *bool `form:"inclusive"` + // The jurisdiction for the tax rate. You can use this label field for tax reporting purposes. It also appears on your customer's invoice. + Jurisdiction *string `form:"jurisdiction"` + // The level of the jurisdiction that imposes this tax rate. + JurisdictionLevel *string `form:"jurisdiction_level"` + // The statutory tax rate percent. This field accepts decimal values between 0 and 100 inclusive with at most 4 decimal places. To accommodate fixed-amount taxes, set the percentage to zero. Stripe will not display zero percentages on the invoice unless the `amount` of the tax is also zero. + Percentage *float64 `form:"percentage"` + // [ISO 3166-2 subdivision code](https://en.wikipedia.org/wiki/ISO_3166-2:US), without country prefix. For example, "NY" for New York, United States. + State *string `form:"state"` + // The high-level tax type, such as `vat` or `sales_tax`. + TaxType *string `form:"tax_type"` +} + +// A list of up to 10 tax amounts for this line item. This can be useful if you calculate taxes on your own or use a third-party to calculate them. You cannot set tax amounts if any line item has [tax_rates](https://stripe.com/docs/api/invoices/line_item#invoice_line_item_object-tax_rates) or if the invoice has [default_tax_rates](https://stripe.com/docs/api/invoices/object#invoice_object-default_tax_rates) or uses [automatic tax](https://stripe.com/docs/tax/invoicing). Pass an empty string to remove previously defined tax amounts. +type InvoiceLineItemUpdateTaxAmountParams struct { + // The amount, in cents (or local equivalent), of the tax. + Amount *int64 `form:"amount"` + // The reasoning behind this tax, for example, if the product is tax exempt. + TaxabilityReason *string `form:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount *int64 `form:"taxable_amount"` + // Data to find or create a TaxRate object. + // + // Stripe automatically creates or reuses a TaxRate object for each tax amount. If the `tax_rate_data` exactly matches a previous value, Stripe will reuse the TaxRate object. TaxRate objects created automatically by Stripe are immediately archived, do not appear in the line item's `tax_rates`, and cannot be directly added to invoices, payments, or line items. + TaxRateData *InvoiceLineItemUpdateTaxAmountTaxRateDataParams `form:"tax_rate_data"` +} + +// Updates an invoice's line item. Some fields, such as tax_amounts, only live on the invoice line item, +// so they can only be updated through this endpoint. Other fields, such as amount, live on both the invoice +// item and the invoice line item, so updates on this endpoint will propagate to the invoice item as well. +// Updating an invoice's line item is only possible before the invoice is finalized. +type InvoiceLineItemUpdateParams struct { + Params `form:"*"` + Invoice *string `form:"-"` // Included in URL + // The integer amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. If you want to apply a credit to the customer's account, pass a negative amount. + Amount *int64 `form:"amount"` + // An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. + Description *string `form:"description"` + // Controls whether discounts apply to this line item. Defaults to false for prorations or negative line items, and true for all other line items. Cannot be set to true for prorations. + Discountable *bool `form:"discountable"` + // The coupons, promotion codes & existing discounts which apply to the line item. Item discounts are applied before invoice discounts. Pass an empty string to remove previously-defined discounts. + Discounts []*InvoiceLineItemUpdateDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. For [type=subscription](https://stripe.com/docs/api/invoices/line_item#invoice_line_item_object-type) line items, the incoming metadata specified on the request is directly used to set this value, in contrast to [type=invoiceitem](api/invoices/line_item#invoice_line_item_object-type) line items, where any existing metadata on the invoice line is merged with the incoming data. + Metadata map[string]string `form:"metadata"` + // The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. + Period *InvoiceLineItemUpdatePeriodParams `form:"period"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + PriceData *InvoiceLineItemUpdatePriceDataParams `form:"price_data"` + // The pricing information for the invoice item. + Pricing *InvoiceLineItemUpdatePricingParams `form:"pricing"` + // Non-negative integer. The quantity of units for the line item. + Quantity *int64 `form:"quantity"` + // A list of up to 10 tax amounts for this line item. This can be useful if you calculate taxes on your own or use a third-party to calculate them. You cannot set tax amounts if any line item has [tax_rates](https://stripe.com/docs/api/invoices/line_item#invoice_line_item_object-tax_rates) or if the invoice has [default_tax_rates](https://stripe.com/docs/api/invoices/object#invoice_object-default_tax_rates) or uses [automatic tax](https://stripe.com/docs/tax/invoicing). Pass an empty string to remove previously defined tax amounts. + TaxAmounts []*InvoiceLineItemUpdateTaxAmountParams `form:"tax_amounts"` + // The tax rates which apply to the line item. When set, the `default_tax_rates` on the invoice do not apply to this line item. Pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceLineItemUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *InvoiceLineItemUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The amount of discount calculated per discount for this line item. +type InvoiceLineItemDiscountAmount struct { + // The amount, in cents (or local equivalent), of the discount. + Amount int64 `json:"amount"` + // The discount that was applied to get this discount amount. + Discount *Discount `json:"discount"` +} + +// For a credit proration `line_item`, the original debit line_items to which the credit proration applies. +type InvoiceLineItemParentInvoiceItemDetailsProrationDetailsCreditedItems struct { + // Invoice containing the credited invoice line items + Invoice string `json:"invoice"` + // Credited invoice line items + InvoiceLineItems []string `json:"invoice_line_items"` +} + +// Additional details for proration line items +type InvoiceLineItemParentInvoiceItemDetailsProrationDetails struct { + // For a credit proration `line_item`, the original debit line_items to which the credit proration applies. + CreditedItems *InvoiceLineItemParentInvoiceItemDetailsProrationDetailsCreditedItems `json:"credited_items"` +} + +// Details about the invoice item that generated this line item +type InvoiceLineItemParentInvoiceItemDetails struct { + // The invoice item that generated this line item + InvoiceItem string `json:"invoice_item"` + // Whether this is a proration + Proration bool `json:"proration"` + // Additional details for proration line items + ProrationDetails *InvoiceLineItemParentInvoiceItemDetailsProrationDetails `json:"proration_details"` + // The subscription that the invoice item belongs to + Subscription string `json:"subscription"` +} + +// For a credit proration `line_item`, the original debit line_items to which the credit proration applies. +type InvoiceLineItemParentSubscriptionItemDetailsProrationDetailsCreditedItems struct { + // Invoice containing the credited invoice line items + Invoice string `json:"invoice"` + // Credited invoice line items + InvoiceLineItems []string `json:"invoice_line_items"` +} + +// Additional details for proration line items +type InvoiceLineItemParentSubscriptionItemDetailsProrationDetails struct { + // For a credit proration `line_item`, the original debit line_items to which the credit proration applies. + CreditedItems *InvoiceLineItemParentSubscriptionItemDetailsProrationDetailsCreditedItems `json:"credited_items"` +} + +// Details about the subscription item that generated this line item +type InvoiceLineItemParentSubscriptionItemDetails struct { + // The invoice item that generated this line item + InvoiceItem string `json:"invoice_item"` + // Whether this is a proration + Proration bool `json:"proration"` + // Additional details for proration line items + ProrationDetails *InvoiceLineItemParentSubscriptionItemDetailsProrationDetails `json:"proration_details"` + // The subscription that the subscription item belongs to + Subscription string `json:"subscription"` + // The subscription item that generated this line item + SubscriptionItem string `json:"subscription_item"` +} + +// The parent that generated this line item. +type InvoiceLineItemParent struct { + // Details about the invoice item that generated this line item + InvoiceItemDetails *InvoiceLineItemParentInvoiceItemDetails `json:"invoice_item_details"` + // Details about the subscription item that generated this line item + SubscriptionItemDetails *InvoiceLineItemParentSubscriptionItemDetails `json:"subscription_item_details"` + // The type of parent that generated this line item + Type InvoiceLineItemParentType `json:"type"` +} + +// Contains pretax credit amounts (ex: discount, credit grants, etc) that apply to this line item. +type InvoiceLineItemPretaxCreditAmount struct { + // The amount, in cents (or local equivalent), of the pretax credit amount. + Amount int64 `json:"amount"` + // The credit balance transaction that was applied to get this pretax credit amount. + CreditBalanceTransaction *BillingCreditBalanceTransaction `json:"credit_balance_transaction"` + // The discount that was applied to get this pretax credit amount. + Discount *Discount `json:"discount"` + // Type of the pretax credit amount referenced. + Type InvoiceLineItemPretaxCreditAmountType `json:"type"` +} +type InvoiceLineItemPricingPriceDetails struct { + // The ID of the price this item is associated with. + Price string `json:"price"` + // The ID of the product this item is associated with. + Product string `json:"product"` +} + +// The pricing information of the line item. +type InvoiceLineItemPricing struct { + PriceDetails *InvoiceLineItemPricingPriceDetails `json:"price_details"` + // The type of the pricing details. + Type InvoiceLineItemPricingType `json:"type"` + // The unit amount (in the `currency` specified) of the item which contains a decimal value with at most 12 decimal places. + UnitAmountDecimal float64 `json:"unit_amount_decimal,string"` +} + +// Additional details about the tax rate. Only present when `type` is `tax_rate_details`. +type InvoiceLineItemTaxTaxRateDetails struct { + TaxRate string `json:"tax_rate"` +} + +// The tax information of the line item. +type InvoiceLineItemTax struct { + // The amount of the tax, in cents (or local equivalent). + Amount int64 `json:"amount"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason InvoiceLineItemTaxTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount int64 `json:"taxable_amount"` + // Whether this tax is inclusive or exclusive. + TaxBehavior InvoiceLineItemTaxTaxBehavior `json:"tax_behavior"` + // Additional details about the tax rate. Only present when `type` is `tax_rate_details`. + TaxRateDetails *InvoiceLineItemTaxTaxRateDetails `json:"tax_rate_details"` + // The type of tax information. + Type InvoiceLineItemTaxType `json:"type"` +} + +// Invoice Line Items represent the individual lines within an [invoice](https://stripe.com/docs/api/invoices) and only exist within the context of an invoice. +// +// Each line item is backed by either an [invoice item](https://stripe.com/docs/api/invoiceitems) or a [subscription item](https://stripe.com/docs/api/subscription_items). +type InvoiceLineItem struct { + APIResource + // The amount, in cents (or local equivalent). + Amount int64 `json:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // If true, discounts will apply to this line item. Always false for prorations. + Discountable bool `json:"discountable"` + // The amount of discount calculated per discount for this line item. + DiscountAmounts []*InvoiceLineItemDiscountAmount `json:"discount_amounts"` + // The discounts applied to the invoice line item. Line item discounts are applied before invoice discounts. Use `expand[]=discounts` to expand each discount. + Discounts []*Discount `json:"discounts"` + // Unique identifier for the object. + ID string `json:"id"` + // The ID of the invoice that contains this line item. + Invoice string `json:"invoice"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Note that for line items with `type=subscription`, `metadata` reflects the current metadata from the subscription associated with the line item, unless the invoice line was directly updated with different metadata after creation. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The parent that generated this line item. + Parent *InvoiceLineItemParent `json:"parent"` + Period *Period `json:"period"` + // Contains pretax credit amounts (ex: discount, credit grants, etc) that apply to this line item. + PretaxCreditAmounts []*InvoiceLineItemPretaxCreditAmount `json:"pretax_credit_amounts"` + // The pricing information of the line item. + Pricing *InvoiceLineItemPricing `json:"pricing"` + // The quantity of the subscription, if the line item is a subscription or a proration. + Quantity int64 `json:"quantity"` + Subscription *Subscription `json:"subscription"` + // The tax information of the line item. + Taxes []*InvoiceLineItemTax `json:"taxes"` +} + +// Period is a structure representing a start and end dates. +type Period struct { + End int64 `json:"end"` + Start int64 `json:"start"` +} + +// InvoiceLineItemList is a list of InvoiceLineItems as retrieved from a list endpoint. +type InvoiceLineItemList struct { + APIResource + ListMeta + Data []*InvoiceLineItem `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/invoicelineitem_service.go b/vendor/github.com/stripe/stripe-go/v82/invoicelineitem_service.go new file mode 100644 index 00000000..2b537dde --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/invoicelineitem_service.go @@ -0,0 +1,34 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1InvoiceLineItemService is used to invoke /v1/invoices/{invoice}/lines APIs. +type v1InvoiceLineItemService struct { + B Backend + Key string +} + +// Updates an invoice's line item. Some fields, such as tax_amounts, only live on the invoice line item, +// so they can only be updated through this endpoint. Other fields, such as amount, live on both the invoice +// item and the invoice line item, so updates on this endpoint will propagate to the invoice item as well. +// Updating an invoice's line item is only possible before the invoice is finalized. +func (c v1InvoiceLineItemService) Update(ctx context.Context, id string, params *InvoiceLineItemUpdateParams) (*InvoiceLineItem, error) { + if params == nil { + params = &InvoiceLineItemUpdateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/invoices/%s/lines/%s", StringValue(params.Invoice), id) + invoicelineitem := &InvoiceLineItem{} + err := c.B.Call(http.MethodPost, path, c.Key, params, invoicelineitem) + return invoicelineitem, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/invoicepayment.go b/vendor/github.com/stripe/stripe-go/v82/invoicepayment.go new file mode 100644 index 00000000..a4407189 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/invoicepayment.go @@ -0,0 +1,122 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Type of payment object associated with this invoice payment. +type InvoicePaymentPaymentType string + +// List of values that InvoicePaymentPaymentType can take +const ( + InvoicePaymentPaymentTypeCharge InvoicePaymentPaymentType = "charge" + InvoicePaymentPaymentTypePaymentIntent InvoicePaymentPaymentType = "payment_intent" +) + +// The payment details of the invoice payments to return. +type InvoicePaymentListPaymentParams struct { + // Only return invoice payments associated by this payment intent ID. + PaymentIntent *string `form:"payment_intent"` + // Only return invoice payments associated by this payment type. + Type *string `form:"type"` +} + +// When retrieving an invoice, there is an includable payments property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of payments. +type InvoicePaymentListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The identifier of the invoice whose payments to return. + Invoice *string `form:"invoice"` + // The payment details of the invoice payments to return. + Payment *InvoicePaymentListPaymentParams `form:"payment"` + // The status of the invoice payments to return. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *InvoicePaymentListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the invoice payment with the given ID. +type InvoicePaymentParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *InvoicePaymentParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the invoice payment with the given ID. +type InvoicePaymentRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *InvoicePaymentRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type InvoicePaymentPayment struct { + // ID of the successful charge for this payment when `type` is `charge`.Note: charge is only surfaced if the charge object is not associated with a payment intent. If the charge object does have a payment intent, the Invoice Payment surfaces the payment intent instead. + Charge *Charge `json:"charge"` + // ID of the PaymentIntent associated with this payment when `type` is `payment_intent`. Note: This property is only populated for invoices finalized on or after March 15th, 2019. + PaymentIntent *PaymentIntent `json:"payment_intent"` + // Type of payment object associated with this invoice payment. + Type InvoicePaymentPaymentType `json:"type"` +} +type InvoicePaymentStatusTransitions struct { + // The time that the payment was canceled. + CanceledAt int64 `json:"canceled_at"` + // The time that the payment succeeded. + PaidAt int64 `json:"paid_at"` +} + +// Invoice Payments represent payments made against invoices. Invoice Payments can +// be accessed in two ways: +// 1. By expanding the `payments` field on the [Invoice](https://stripe.com/docs/api#invoice) resource. +// 2. By using the Invoice Payment retrieve and list endpoints. +// +// Invoice Payments include the mapping between payment objects, such as Payment Intent, and Invoices. +// This resource and its endpoints allows you to easily track if a payment is associated with a specific invoice and +// monitor the allocation details of the payments. +type InvoicePayment struct { + APIResource + // Amount that was actually paid for this invoice, in cents (or local equivalent). This field is null until the payment is `paid`. This amount can be less than the `amount_requested` if the PaymentIntent's `amount_received` is not sufficient to pay all of the invoices that it is attached to. + AmountPaid int64 `json:"amount_paid"` + // Amount intended to be paid toward this invoice, in cents (or local equivalent) + AmountRequested int64 `json:"amount_requested"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // Unique identifier for the object. + ID string `json:"id"` + // The invoice that was paid. + Invoice *Invoice `json:"invoice"` + // Stripe automatically creates a default InvoicePayment when the invoice is finalized, and keeps it synchronized with the invoice's `amount_remaining`. The PaymentIntent associated with the default payment can't be edited or canceled directly. + IsDefault bool `json:"is_default"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + Payment *InvoicePaymentPayment `json:"payment"` + // The status of the payment, one of `open`, `paid`, or `canceled`. + Status string `json:"status"` + StatusTransitions *InvoicePaymentStatusTransitions `json:"status_transitions"` +} + +// InvoicePaymentList is a list of InvoicePayments as retrieved from a list endpoint. +type InvoicePaymentList struct { + APIResource + ListMeta + Data []*InvoicePayment `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/invoicepayment_service.go b/vendor/github.com/stripe/stripe-go/v82/invoicepayment_service.go new file mode 100644 index 00000000..c3d7b720 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/invoicepayment_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1InvoicePaymentService is used to invoke /v1/invoice_payments APIs. +type v1InvoicePaymentService struct { + B Backend + Key string +} + +// Retrieves the invoice payment with the given ID. +func (c v1InvoicePaymentService) Retrieve(ctx context.Context, id string, params *InvoicePaymentRetrieveParams) (*InvoicePayment, error) { + if params == nil { + params = &InvoicePaymentRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoice_payments/%s", id) + invoicepayment := &InvoicePayment{} + err := c.B.Call(http.MethodGet, path, c.Key, params, invoicepayment) + return invoicepayment, err +} + +// When retrieving an invoice, there is an includable payments property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of payments. +func (c v1InvoicePaymentService) List(ctx context.Context, listParams *InvoicePaymentListParams) Seq2[*InvoicePayment, error] { + if listParams == nil { + listParams = &InvoicePaymentListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*InvoicePayment, ListContainer, error) { + list := &InvoicePaymentList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/invoice_payments", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/invoicerenderingtemplate.go b/vendor/github.com/stripe/stripe-go/v82/invoicerenderingtemplate.go new file mode 100644 index 00000000..82a5d0bb --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/invoicerenderingtemplate.go @@ -0,0 +1,108 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The status of the template, one of `active` or `archived`. +type InvoiceRenderingTemplateStatus string + +// List of values that InvoiceRenderingTemplateStatus can take +const ( + InvoiceRenderingTemplateStatusActive InvoiceRenderingTemplateStatus = "active" + InvoiceRenderingTemplateStatusArchived InvoiceRenderingTemplateStatus = "archived" +) + +// List all templates, ordered by creation date, with the most recently created template appearing first. +type InvoiceRenderingTemplateListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceRenderingTemplateListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves an invoice rendering template with the given ID. It by default returns the latest version of the template. Optionally, specify a version to see previous versions. +type InvoiceRenderingTemplateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + Version *int64 `form:"version"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceRenderingTemplateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the status of an invoice rendering template to ‘archived' so no new Stripe objects (customers, invoices, etc.) can reference it. The template can also no longer be updated. However, if the template is already set on a Stripe object, it will continue to be applied on invoices generated by it. +type InvoiceRenderingTemplateArchiveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceRenderingTemplateArchiveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Unarchive an invoice rendering template so it can be used on new Stripe objects again. +type InvoiceRenderingTemplateUnarchiveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceRenderingTemplateUnarchiveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves an invoice rendering template with the given ID. It by default returns the latest version of the template. Optionally, specify a version to see previous versions. +type InvoiceRenderingTemplateRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + Version *int64 `form:"version"` +} + +// AddExpand appends a new field to expand. +func (p *InvoiceRenderingTemplateRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Invoice Rendering Templates are used to configure how invoices are rendered on surfaces like the PDF. Invoice Rendering Templates +// can be created from within the Dashboard, and they can be used over the API when creating invoices. +type InvoiceRenderingTemplate struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // A brief description of the template, hidden from customers + Nickname string `json:"nickname"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The status of the template, one of `active` or `archived`. + Status InvoiceRenderingTemplateStatus `json:"status"` + // Version of this template; version increases by one when an update on the template changes any field that controls invoice rendering + Version int64 `json:"version"` +} + +// InvoiceRenderingTemplateList is a list of InvoiceRenderingTemplates as retrieved from a list endpoint. +type InvoiceRenderingTemplateList struct { + APIResource + ListMeta + Data []*InvoiceRenderingTemplate `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/invoicerenderingtemplate_service.go b/vendor/github.com/stripe/stripe-go/v82/invoicerenderingtemplate_service.go new file mode 100644 index 00000000..f0723909 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/invoicerenderingtemplate_service.go @@ -0,0 +1,75 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1InvoiceRenderingTemplateService is used to invoke /v1/invoice_rendering_templates APIs. +type v1InvoiceRenderingTemplateService struct { + B Backend + Key string +} + +// Retrieves an invoice rendering template with the given ID. It by default returns the latest version of the template. Optionally, specify a version to see previous versions. +func (c v1InvoiceRenderingTemplateService) Retrieve(ctx context.Context, id string, params *InvoiceRenderingTemplateRetrieveParams) (*InvoiceRenderingTemplate, error) { + if params == nil { + params = &InvoiceRenderingTemplateRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoice_rendering_templates/%s", id) + invoicerenderingtemplate := &InvoiceRenderingTemplate{} + err := c.B.Call(http.MethodGet, path, c.Key, params, invoicerenderingtemplate) + return invoicerenderingtemplate, err +} + +// Updates the status of an invoice rendering template to ‘archived' so no new Stripe objects (customers, invoices, etc.) can reference it. The template can also no longer be updated. However, if the template is already set on a Stripe object, it will continue to be applied on invoices generated by it. +func (c v1InvoiceRenderingTemplateService) Archive(ctx context.Context, id string, params *InvoiceRenderingTemplateArchiveParams) (*InvoiceRenderingTemplate, error) { + if params == nil { + params = &InvoiceRenderingTemplateArchiveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoice_rendering_templates/%s/archive", id) + invoicerenderingtemplate := &InvoiceRenderingTemplate{} + err := c.B.Call( + http.MethodPost, path, c.Key, params, invoicerenderingtemplate) + return invoicerenderingtemplate, err +} + +// Unarchive an invoice rendering template so it can be used on new Stripe objects again. +func (c v1InvoiceRenderingTemplateService) Unarchive(ctx context.Context, id string, params *InvoiceRenderingTemplateUnarchiveParams) (*InvoiceRenderingTemplate, error) { + if params == nil { + params = &InvoiceRenderingTemplateUnarchiveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/invoice_rendering_templates/%s/unarchive", id) + invoicerenderingtemplate := &InvoiceRenderingTemplate{} + err := c.B.Call( + http.MethodPost, path, c.Key, params, invoicerenderingtemplate) + return invoicerenderingtemplate, err +} + +// List all templates, ordered by creation date, with the most recently created template appearing first. +func (c v1InvoiceRenderingTemplateService) List(ctx context.Context, listParams *InvoiceRenderingTemplateListParams) Seq2[*InvoiceRenderingTemplate, error] { + if listParams == nil { + listParams = &InvoiceRenderingTemplateListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*InvoiceRenderingTemplate, ListContainer, error) { + list := &InvoiceRenderingTemplateList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/invoice_rendering_templates", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_authorization.go b/vendor/github.com/stripe/stripe-go/v82/issuing_authorization.go new file mode 100644 index 00000000..279c7344 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_authorization.go @@ -0,0 +1,617 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// How the card details were provided. +type IssuingAuthorizationAuthorizationMethod string + +// List of values that IssuingAuthorizationAuthorizationMethod can take +const ( + IssuingAuthorizationAuthorizationMethodChip IssuingAuthorizationAuthorizationMethod = "chip" + IssuingAuthorizationAuthorizationMethodContactless IssuingAuthorizationAuthorizationMethod = "contactless" + IssuingAuthorizationAuthorizationMethodKeyedIn IssuingAuthorizationAuthorizationMethod = "keyed_in" + IssuingAuthorizationAuthorizationMethodOnline IssuingAuthorizationAuthorizationMethod = "online" + IssuingAuthorizationAuthorizationMethodSwipe IssuingAuthorizationAuthorizationMethod = "swipe" +) + +// The type of purchase. +type IssuingAuthorizationFleetPurchaseType string + +// List of values that IssuingAuthorizationFleetPurchaseType can take +const ( + IssuingAuthorizationFleetPurchaseTypeFuelAndNonFuelPurchase IssuingAuthorizationFleetPurchaseType = "fuel_and_non_fuel_purchase" + IssuingAuthorizationFleetPurchaseTypeFuelPurchase IssuingAuthorizationFleetPurchaseType = "fuel_purchase" + IssuingAuthorizationFleetPurchaseTypeNonFuelPurchase IssuingAuthorizationFleetPurchaseType = "non_fuel_purchase" +) + +// The type of fuel service. +type IssuingAuthorizationFleetServiceType string + +// List of values that IssuingAuthorizationFleetServiceType can take +const ( + IssuingAuthorizationFleetServiceTypeFullService IssuingAuthorizationFleetServiceType = "full_service" + IssuingAuthorizationFleetServiceTypeNonFuelTransaction IssuingAuthorizationFleetServiceType = "non_fuel_transaction" + IssuingAuthorizationFleetServiceTypeSelfService IssuingAuthorizationFleetServiceType = "self_service" +) + +// The method by which the fraud challenge was delivered to the cardholder. +type IssuingAuthorizationFraudChallengeChannel string + +// List of values that IssuingAuthorizationFraudChallengeChannel can take +const ( + IssuingAuthorizationFraudChallengeChannelSms IssuingAuthorizationFraudChallengeChannel = "sms" +) + +// The status of the fraud challenge. +type IssuingAuthorizationFraudChallengeStatus string + +// List of values that IssuingAuthorizationFraudChallengeStatus can take +const ( + IssuingAuthorizationFraudChallengeStatusExpired IssuingAuthorizationFraudChallengeStatus = "expired" + IssuingAuthorizationFraudChallengeStatusPending IssuingAuthorizationFraudChallengeStatus = "pending" + IssuingAuthorizationFraudChallengeStatusRejected IssuingAuthorizationFraudChallengeStatus = "rejected" + IssuingAuthorizationFraudChallengeStatusUndeliverable IssuingAuthorizationFraudChallengeStatus = "undeliverable" + IssuingAuthorizationFraudChallengeStatusVerified IssuingAuthorizationFraudChallengeStatus = "verified" +) + +// If the challenge is not deliverable, the reason why. +type IssuingAuthorizationFraudChallengeUndeliverableReason string + +// List of values that IssuingAuthorizationFraudChallengeUndeliverableReason can take +const ( + IssuingAuthorizationFraudChallengeUndeliverableReasonNoPhoneNumber IssuingAuthorizationFraudChallengeUndeliverableReason = "no_phone_number" + IssuingAuthorizationFraudChallengeUndeliverableReasonUnsupportedPhoneNumber IssuingAuthorizationFraudChallengeUndeliverableReason = "unsupported_phone_number" +) + +// The type of fuel that was purchased. +type IssuingAuthorizationFuelType string + +// List of values that IssuingAuthorizationFuelType can take +const ( + IssuingAuthorizationFuelTypeDiesel IssuingAuthorizationFuelType = "diesel" + IssuingAuthorizationFuelTypeOther IssuingAuthorizationFuelType = "other" + IssuingAuthorizationFuelTypeUnleadedPlus IssuingAuthorizationFuelType = "unleaded_plus" + IssuingAuthorizationFuelTypeUnleadedRegular IssuingAuthorizationFuelType = "unleaded_regular" + IssuingAuthorizationFuelTypeUnleadedSuper IssuingAuthorizationFuelType = "unleaded_super" +) + +// The units for `quantity_decimal`. +type IssuingAuthorizationFuelUnit string + +// List of values that IssuingAuthorizationFuelUnit can take +const ( + IssuingAuthorizationFuelUnitChargingMinute IssuingAuthorizationFuelUnit = "charging_minute" + IssuingAuthorizationFuelUnitImperialGallon IssuingAuthorizationFuelUnit = "imperial_gallon" + IssuingAuthorizationFuelUnitKilogram IssuingAuthorizationFuelUnit = "kilogram" + IssuingAuthorizationFuelUnitKilowattHour IssuingAuthorizationFuelUnit = "kilowatt_hour" + IssuingAuthorizationFuelUnitLiter IssuingAuthorizationFuelUnit = "liter" + IssuingAuthorizationFuelUnitOther IssuingAuthorizationFuelUnit = "other" + IssuingAuthorizationFuelUnitPound IssuingAuthorizationFuelUnit = "pound" + IssuingAuthorizationFuelUnitUSGallon IssuingAuthorizationFuelUnit = "us_gallon" +) + +// When an authorization is approved or declined by you or by Stripe, this field provides additional detail on the reason for the outcome. +type IssuingAuthorizationRequestHistoryReason string + +// List of values that IssuingAuthorizationRequestHistoryReason can take +const ( + IssuingAuthorizationRequestHistoryReasonAccountDisabled IssuingAuthorizationRequestHistoryReason = "account_disabled" + IssuingAuthorizationRequestHistoryReasonCardActive IssuingAuthorizationRequestHistoryReason = "card_active" + IssuingAuthorizationRequestHistoryReasonCardCanceled IssuingAuthorizationRequestHistoryReason = "card_canceled" + IssuingAuthorizationRequestHistoryReasonCardExpired IssuingAuthorizationRequestHistoryReason = "card_expired" + IssuingAuthorizationRequestHistoryReasonCardInactive IssuingAuthorizationRequestHistoryReason = "card_inactive" + IssuingAuthorizationRequestHistoryReasonCardholderBlocked IssuingAuthorizationRequestHistoryReason = "cardholder_blocked" + IssuingAuthorizationRequestHistoryReasonCardholderInactive IssuingAuthorizationRequestHistoryReason = "cardholder_inactive" + IssuingAuthorizationRequestHistoryReasonCardholderVerificationRequired IssuingAuthorizationRequestHistoryReason = "cardholder_verification_required" + IssuingAuthorizationRequestHistoryReasonInsecureAuthorizationMethod IssuingAuthorizationRequestHistoryReason = "insecure_authorization_method" + IssuingAuthorizationRequestHistoryReasonInsufficientFunds IssuingAuthorizationRequestHistoryReason = "insufficient_funds" + IssuingAuthorizationRequestHistoryReasonNetworkFallback IssuingAuthorizationRequestHistoryReason = "network_fallback" + IssuingAuthorizationRequestHistoryReasonNotAllowed IssuingAuthorizationRequestHistoryReason = "not_allowed" + IssuingAuthorizationRequestHistoryReasonPINBlocked IssuingAuthorizationRequestHistoryReason = "pin_blocked" + IssuingAuthorizationRequestHistoryReasonSpendingControls IssuingAuthorizationRequestHistoryReason = "spending_controls" + IssuingAuthorizationRequestHistoryReasonSuspectedFraud IssuingAuthorizationRequestHistoryReason = "suspected_fraud" + IssuingAuthorizationRequestHistoryReasonVerificationFailed IssuingAuthorizationRequestHistoryReason = "verification_failed" + IssuingAuthorizationRequestHistoryReasonWebhookApproved IssuingAuthorizationRequestHistoryReason = "webhook_approved" + IssuingAuthorizationRequestHistoryReasonWebhookDeclined IssuingAuthorizationRequestHistoryReason = "webhook_declined" + IssuingAuthorizationRequestHistoryReasonWebhookError IssuingAuthorizationRequestHistoryReason = "webhook_error" + IssuingAuthorizationRequestHistoryReasonWebhookTimeout IssuingAuthorizationRequestHistoryReason = "webhook_timeout" +) + +// The current status of the authorization in its lifecycle. +type IssuingAuthorizationStatus string + +// List of values that IssuingAuthorizationStatus can take +const ( + IssuingAuthorizationStatusClosed IssuingAuthorizationStatus = "closed" + IssuingAuthorizationStatusExpired IssuingAuthorizationStatus = "expired" + IssuingAuthorizationStatusPending IssuingAuthorizationStatus = "pending" + IssuingAuthorizationStatusReversed IssuingAuthorizationStatus = "reversed" +) + +// Whether the cardholder provided an address first line and if it matched the cardholder's `billing.address.line1`. +type IssuingAuthorizationVerificationDataCheck string + +// List of values that IssuingAuthorizationVerificationDataCheck can take +const ( + IssuingAuthorizationVerificationDataCheckMatch IssuingAuthorizationVerificationDataCheck = "match" + IssuingAuthorizationVerificationDataCheckMismatch IssuingAuthorizationVerificationDataCheck = "mismatch" + IssuingAuthorizationVerificationDataCheckNotProvided IssuingAuthorizationVerificationDataCheck = "not_provided" +) + +// The entity that requested the exemption, either the acquiring merchant or the Issuing user. +type IssuingAuthorizationVerificationDataAuthenticationExemptionClaimedBy string + +// List of values that IssuingAuthorizationVerificationDataAuthenticationExemptionClaimedBy can take +const ( + IssuingAuthorizationVerificationDataAuthenticationExemptionClaimedByAcquirer IssuingAuthorizationVerificationDataAuthenticationExemptionClaimedBy = "acquirer" + IssuingAuthorizationVerificationDataAuthenticationExemptionClaimedByIssuer IssuingAuthorizationVerificationDataAuthenticationExemptionClaimedBy = "issuer" +) + +// The specific exemption claimed for this authorization. +type IssuingAuthorizationVerificationDataAuthenticationExemptionType string + +// List of values that IssuingAuthorizationVerificationDataAuthenticationExemptionType can take +const ( + IssuingAuthorizationVerificationDataAuthenticationExemptionTypeLowValueTransaction IssuingAuthorizationVerificationDataAuthenticationExemptionType = "low_value_transaction" + IssuingAuthorizationVerificationDataAuthenticationExemptionTypeTransactionRiskAnalysis IssuingAuthorizationVerificationDataAuthenticationExemptionType = "transaction_risk_analysis" + IssuingAuthorizationVerificationDataAuthenticationExemptionTypeUnknown IssuingAuthorizationVerificationDataAuthenticationExemptionType = "unknown" +) + +// The outcome of the 3D Secure authentication request. +type IssuingAuthorizationVerificationDataThreeDSecureResult string + +// List of values that IssuingAuthorizationVerificationDataThreeDSecureResult can take +const ( + IssuingAuthorizationVerificationDataThreeDSecureResultAttemptAcknowledged IssuingAuthorizationVerificationDataThreeDSecureResult = "attempt_acknowledged" + IssuingAuthorizationVerificationDataThreeDSecureResultAuthenticated IssuingAuthorizationVerificationDataThreeDSecureResult = "authenticated" + IssuingAuthorizationVerificationDataThreeDSecureResultFailed IssuingAuthorizationVerificationDataThreeDSecureResult = "failed" + IssuingAuthorizationVerificationDataThreeDSecureResultRequired IssuingAuthorizationVerificationDataThreeDSecureResult = "required" +) + +// The digital wallet used for this transaction. One of `apple_pay`, `google_pay`, or `samsung_pay`. Will populate as `null` when no digital wallet was utilized. +type IssuingAuthorizationWallet string + +// List of values that IssuingAuthorizationWallet can take +const ( + IssuingAuthorizationWalletApplePay IssuingAuthorizationWallet = "apple_pay" + IssuingAuthorizationWalletGooglePay IssuingAuthorizationWallet = "google_pay" + IssuingAuthorizationWalletSamsungPay IssuingAuthorizationWallet = "samsung_pay" +) + +// Returns a list of Issuing Authorization objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +type IssuingAuthorizationListParams struct { + ListParams `form:"*"` + // Only return authorizations that belong to the given card. + Card *string `form:"card"` + // Only return authorizations that belong to the given cardholder. + Cardholder *string `form:"cardholder"` + // Only return authorizations that were created during the given date interval. + Created *int64 `form:"created"` + // Only return authorizations that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return authorizations with the given status. One of `pending`, `closed`, or `reversed`. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingAuthorizationListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves an Issuing Authorization object. +type IssuingAuthorizationParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingAuthorizationParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingAuthorizationParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// [Deprecated] Approves a pending Issuing Authorization object. This request should be made within the timeout window of the [real-time authorization](https://docs.stripe.com/docs/issuing/controls/real-time-authorizations) flow. +// This method is deprecated. Instead, [respond directly to the webhook request to approve an authorization](https://docs.stripe.com/docs/issuing/controls/real-time-authorizations#authorization-handling). +type IssuingAuthorizationApproveParams struct { + Params `form:"*"` + // If the authorization's `pending_request.is_amount_controllable` property is `true`, you may provide this value to control how much to hold for the authorization. Must be positive (use [`decline`](https://stripe.com/docs/api/issuing/authorizations/decline) to decline an authorization request). + Amount *int64 `form:"amount"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingAuthorizationApproveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingAuthorizationApproveParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// [Deprecated] Declines a pending Issuing Authorization object. This request should be made within the timeout window of the [real time authorization](https://docs.stripe.com/docs/issuing/controls/real-time-authorizations) flow. +// This method is deprecated. Instead, [respond directly to the webhook request to decline an authorization](https://docs.stripe.com/docs/issuing/controls/real-time-authorizations#authorization-handling). +type IssuingAuthorizationDeclineParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingAuthorizationDeclineParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingAuthorizationDeclineParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves an Issuing Authorization object. +type IssuingAuthorizationRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingAuthorizationRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the specified Issuing Authorization object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +type IssuingAuthorizationUpdateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingAuthorizationUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingAuthorizationUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Detailed breakdown of amount components. These amounts are denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). +type IssuingAuthorizationAmountDetails struct { + // The fee charged by the ATM for the cash withdrawal. + ATMFee int64 `json:"atm_fee"` + // The amount of cash requested by the cardholder. + CashbackAmount int64 `json:"cashback_amount"` +} + +// Answers to prompts presented to the cardholder at the point of sale. Prompted fields vary depending on the configuration of your physical fleet cards. Typical points of sale support only numeric entry. +type IssuingAuthorizationFleetCardholderPromptData struct { + // [Deprecated] An alphanumeric ID, though typical point of sales only support numeric entry. The card program can be configured to prompt for a vehicle ID, driver ID, or generic ID. + // Deprecated: + AlphanumericID string `json:"alphanumeric_id"` + // Driver ID. + DriverID string `json:"driver_id"` + // Odometer reading. + Odometer int64 `json:"odometer"` + // An alphanumeric ID. This field is used when a vehicle ID, driver ID, or generic ID is entered by the cardholder, but the merchant or card network did not specify the prompt type. + UnspecifiedID string `json:"unspecified_id"` + // User ID. + UserID string `json:"user_id"` + // Vehicle number. + VehicleNumber string `json:"vehicle_number"` +} + +// Breakdown of fuel portion of the purchase. +type IssuingAuthorizationFleetReportedBreakdownFuel struct { + // Gross fuel amount that should equal Fuel Quantity multiplied by Fuel Unit Cost, inclusive of taxes. + GrossAmountDecimal float64 `json:"gross_amount_decimal,string"` +} + +// Breakdown of non-fuel portion of the purchase. +type IssuingAuthorizationFleetReportedBreakdownNonFuel struct { + // Gross non-fuel amount that should equal the sum of the line items, inclusive of taxes. + GrossAmountDecimal float64 `json:"gross_amount_decimal,string"` +} + +// Information about tax included in this transaction. +type IssuingAuthorizationFleetReportedBreakdownTax struct { + // Amount of state or provincial Sales Tax included in the transaction amount. `null` if not reported by merchant or not subject to tax. + LocalAmountDecimal float64 `json:"local_amount_decimal,string"` + // Amount of national Sales Tax or VAT included in the transaction amount. `null` if not reported by merchant or not subject to tax. + NationalAmountDecimal float64 `json:"national_amount_decimal,string"` +} + +// More information about the total amount. Typically this information is received from the merchant after the authorization has been approved and the fuel dispensed. This information is not guaranteed to be accurate as some merchants may provide unreliable data. +type IssuingAuthorizationFleetReportedBreakdown struct { + // Breakdown of fuel portion of the purchase. + Fuel *IssuingAuthorizationFleetReportedBreakdownFuel `json:"fuel"` + // Breakdown of non-fuel portion of the purchase. + NonFuel *IssuingAuthorizationFleetReportedBreakdownNonFuel `json:"non_fuel"` + // Information about tax included in this transaction. + Tax *IssuingAuthorizationFleetReportedBreakdownTax `json:"tax"` +} + +// Fleet-specific information for authorizations using Fleet cards. +type IssuingAuthorizationFleet struct { + // Answers to prompts presented to the cardholder at the point of sale. Prompted fields vary depending on the configuration of your physical fleet cards. Typical points of sale support only numeric entry. + CardholderPromptData *IssuingAuthorizationFleetCardholderPromptData `json:"cardholder_prompt_data"` + // The type of purchase. + PurchaseType IssuingAuthorizationFleetPurchaseType `json:"purchase_type"` + // More information about the total amount. Typically this information is received from the merchant after the authorization has been approved and the fuel dispensed. This information is not guaranteed to be accurate as some merchants may provide unreliable data. + ReportedBreakdown *IssuingAuthorizationFleetReportedBreakdown `json:"reported_breakdown"` + // The type of fuel service. + ServiceType IssuingAuthorizationFleetServiceType `json:"service_type"` +} + +// Fraud challenges sent to the cardholder, if this authorization was declined for fraud risk reasons. +type IssuingAuthorizationFraudChallenge struct { + // The method by which the fraud challenge was delivered to the cardholder. + Channel IssuingAuthorizationFraudChallengeChannel `json:"channel"` + // The status of the fraud challenge. + Status IssuingAuthorizationFraudChallengeStatus `json:"status"` + // If the challenge is not deliverable, the reason why. + UndeliverableReason IssuingAuthorizationFraudChallengeUndeliverableReason `json:"undeliverable_reason"` +} + +// Information about fuel that was purchased with this transaction. Typically this information is received from the merchant after the authorization has been approved and the fuel dispensed. +type IssuingAuthorizationFuel struct { + // [Conexxus Payment System Product Code](https://www.conexxus.org/conexxus-payment-system-product-codes) identifying the primary fuel product purchased. + IndustryProductCode string `json:"industry_product_code"` + // The quantity of `unit`s of fuel that was dispensed, represented as a decimal string with at most 12 decimal places. + QuantityDecimal float64 `json:"quantity_decimal,string"` + // The type of fuel that was purchased. + Type IssuingAuthorizationFuelType `json:"type"` + // The units for `quantity_decimal`. + Unit IssuingAuthorizationFuelUnit `json:"unit"` + // The cost in cents per each unit of fuel, represented as a decimal string with at most 12 decimal places. + UnitCostDecimal float64 `json:"unit_cost_decimal,string"` +} +type IssuingAuthorizationMerchantData struct { + // A categorization of the seller's type of business. See our [merchant categories guide](https://stripe.com/docs/issuing/merchant-categories) for a list of possible values. + Category string `json:"category"` + // The merchant category code for the seller's business + CategoryCode string `json:"category_code"` + // City where the seller is located + City string `json:"city"` + // Country where the seller is located + Country string `json:"country"` + // Name of the seller + Name string `json:"name"` + // Identifier assigned to the seller by the card network. Different card networks may assign different network_id fields to the same merchant. + NetworkID string `json:"network_id"` + // Postal code where the seller is located + PostalCode string `json:"postal_code"` + // State where the seller is located + State string `json:"state"` + // The seller's tax identification number. Currently populated for French merchants only. + TaxID string `json:"tax_id"` + // An ID assigned by the seller to the location of the sale. + TerminalID string `json:"terminal_id"` + // URL provided by the merchant on a 3DS request + URL string `json:"url"` +} + +// Details about the authorization, such as identifiers, set by the card network. +type IssuingAuthorizationNetworkData struct { + // Identifier assigned to the acquirer by the card network. Sometimes this value is not provided by the network; in this case, the value will be `null`. + AcquiringInstitutionID string `json:"acquiring_institution_id"` + // The System Trace Audit Number (STAN) is a 6-digit identifier assigned by the acquirer. Prefer `network_data.transaction_id` if present, unless you have special requirements. + SystemTraceAuditNumber string `json:"system_trace_audit_number"` + // Unique identifier for the authorization assigned by the card network used to match subsequent messages, disputes, and transactions. + TransactionID string `json:"transaction_id"` +} + +// The pending authorization request. This field will only be non-null during an `issuing_authorization.request` webhook. +type IssuingAuthorizationPendingRequest struct { + // The additional amount Stripe will hold if the authorization is approved, in the card's [currency](https://stripe.com/docs/api#issuing_authorization_object-pending-request-currency) and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Amount int64 `json:"amount"` + // Detailed breakdown of amount components. These amounts are denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + AmountDetails *IssuingAuthorizationAmountDetails `json:"amount_details"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // If set `true`, you may provide [amount](https://stripe.com/docs/api/issuing/authorizations/approve#approve_issuing_authorization-amount) to control how much to hold for the authorization. + IsAmountControllable bool `json:"is_amount_controllable"` + // The amount the merchant is requesting to be authorized in the `merchant_currency`. The amount is in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + MerchantAmount int64 `json:"merchant_amount"` + // The local currency the merchant is requesting to authorize. + MerchantCurrency Currency `json:"merchant_currency"` + // The card network's estimate of the likelihood that an authorization is fraudulent. Takes on values between 1 and 99. + NetworkRiskScore int64 `json:"network_risk_score"` +} + +// History of every time a `pending_request` authorization was approved/declined, either by you directly or by Stripe (e.g. based on your spending_controls). If the merchant changes the authorization by performing an incremental authorization, you can look at this field to see the previous requests for the authorization. This field can be helpful in determining why a given authorization was approved/declined. +type IssuingAuthorizationRequestHistory struct { + // The `pending_request.amount` at the time of the request, presented in your card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). Stripe held this amount from your account to fund the authorization if the request was approved. + Amount int64 `json:"amount"` + // Detailed breakdown of amount components. These amounts are denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + AmountDetails *IssuingAuthorizationAmountDetails `json:"amount_details"` + // Whether this request was approved. + Approved bool `json:"approved"` + // A code created by Stripe which is shared with the merchant to validate the authorization. This field will be populated if the authorization message was approved. The code typically starts with the letter "S", followed by a six-digit number. For example, "S498162". Please note that the code is not guaranteed to be unique across authorizations. + AuthorizationCode string `json:"authorization_code"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // The `pending_request.merchant_amount` at the time of the request, presented in the `merchant_currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + MerchantAmount int64 `json:"merchant_amount"` + // The currency that was collected by the merchant and presented to the cardholder for the authorization. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + MerchantCurrency Currency `json:"merchant_currency"` + // The card network's estimate of the likelihood that an authorization is fraudulent. Takes on values between 1 and 99. + NetworkRiskScore int64 `json:"network_risk_score"` + // When an authorization is approved or declined by you or by Stripe, this field provides additional detail on the reason for the outcome. + Reason IssuingAuthorizationRequestHistoryReason `json:"reason"` + // If the `request_history.reason` is `webhook_error` because the direct webhook response is invalid (for example, parsing errors or missing parameters), we surface a more detailed error message via this field. + ReasonMessage string `json:"reason_message"` + // Time when the card network received an authorization request from the acquirer in UTC. Referred to by networks as transmission time. + RequestedAt int64 `json:"requested_at"` +} + +// [Treasury](https://stripe.com/docs/api/treasury) details related to this authorization if it was created on a [FinancialAccount](https://stripe.com/docs/api/treasury/financial_accounts). +type IssuingAuthorizationTreasury struct { + // The array of [ReceivedCredits](https://stripe.com/docs/api/treasury/received_credits) associated with this authorization + ReceivedCredits []string `json:"received_credits"` + // The array of [ReceivedDebits](https://stripe.com/docs/api/treasury/received_debits) associated with this authorization + ReceivedDebits []string `json:"received_debits"` + // The Treasury [Transaction](https://stripe.com/docs/api/treasury/transactions) associated with this authorization + Transaction string `json:"transaction"` +} + +// The exemption applied to this authorization. +type IssuingAuthorizationVerificationDataAuthenticationExemption struct { + // The entity that requested the exemption, either the acquiring merchant or the Issuing user. + ClaimedBy IssuingAuthorizationVerificationDataAuthenticationExemptionClaimedBy `json:"claimed_by"` + // The specific exemption claimed for this authorization. + Type IssuingAuthorizationVerificationDataAuthenticationExemptionType `json:"type"` +} + +// 3D Secure details. +type IssuingAuthorizationVerificationDataThreeDSecure struct { + // The outcome of the 3D Secure authentication request. + Result IssuingAuthorizationVerificationDataThreeDSecureResult `json:"result"` +} +type IssuingAuthorizationVerificationData struct { + // Whether the cardholder provided an address first line and if it matched the cardholder's `billing.address.line1`. + AddressLine1Check IssuingAuthorizationVerificationDataCheck `json:"address_line1_check"` + // Whether the cardholder provided a postal code and if it matched the cardholder's `billing.address.postal_code`. + AddressPostalCodeCheck IssuingAuthorizationVerificationDataCheck `json:"address_postal_code_check"` + // The exemption applied to this authorization. + AuthenticationExemption *IssuingAuthorizationVerificationDataAuthenticationExemption `json:"authentication_exemption"` + // Whether the cardholder provided a CVC and if it matched Stripe's record. + CVCCheck IssuingAuthorizationVerificationDataCheck `json:"cvc_check"` + // Whether the cardholder provided an expiry date and if it matched Stripe's record. + ExpiryCheck IssuingAuthorizationVerificationDataCheck `json:"expiry_check"` + // The postal code submitted as part of the authorization used for postal code verification. + PostalCode string `json:"postal_code"` + // 3D Secure details. + ThreeDSecure *IssuingAuthorizationVerificationDataThreeDSecure `json:"three_d_secure"` +} + +// When an [issued card](https://stripe.com/docs/issuing) is used to make a purchase, an Issuing `Authorization` +// object is created. [Authorizations](https://stripe.com/docs/issuing/purchases/authorizations) must be approved for the +// purchase to be completed successfully. +// +// Related guide: [Issued card authorizations](https://stripe.com/docs/issuing/purchases/authorizations) +type IssuingAuthorization struct { + APIResource + // The total amount that was authorized or rejected. This amount is in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). `amount` should be the same as `merchant_amount`, unless `currency` and `merchant_currency` are different. + Amount int64 `json:"amount"` + // Detailed breakdown of amount components. These amounts are denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + AmountDetails *IssuingAuthorizationAmountDetails `json:"amount_details"` + // Whether the authorization has been approved. + Approved bool `json:"approved"` + // How the card details were provided. + AuthorizationMethod IssuingAuthorizationAuthorizationMethod `json:"authorization_method"` + // List of balance transactions associated with this authorization. + BalanceTransactions []*BalanceTransaction `json:"balance_transactions"` + // You can [create physical or virtual cards](https://stripe.com/docs/issuing) that are issued to cardholders. + Card *IssuingCard `json:"card"` + // The cardholder to whom this authorization belongs. + Cardholder *IssuingCardholder `json:"cardholder"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The currency of the cardholder. This currency can be different from the currency presented at authorization and the `merchant_currency` field on this authorization. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // Fleet-specific information for authorizations using Fleet cards. + Fleet *IssuingAuthorizationFleet `json:"fleet"` + // Fraud challenges sent to the cardholder, if this authorization was declined for fraud risk reasons. + FraudChallenges []*IssuingAuthorizationFraudChallenge `json:"fraud_challenges"` + // Information about fuel that was purchased with this transaction. Typically this information is received from the merchant after the authorization has been approved and the fuel dispensed. + Fuel *IssuingAuthorizationFuel `json:"fuel"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // The total amount that was authorized or rejected. This amount is in the `merchant_currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). `merchant_amount` should be the same as `amount`, unless `merchant_currency` and `currency` are different. + MerchantAmount int64 `json:"merchant_amount"` + // The local currency that was presented to the cardholder for the authorization. This currency can be different from the cardholder currency and the `currency` field on this authorization. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + MerchantCurrency Currency `json:"merchant_currency"` + MerchantData *IssuingAuthorizationMerchantData `json:"merchant_data"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // Details about the authorization, such as identifiers, set by the card network. + NetworkData *IssuingAuthorizationNetworkData `json:"network_data"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The pending authorization request. This field will only be non-null during an `issuing_authorization.request` webhook. + PendingRequest *IssuingAuthorizationPendingRequest `json:"pending_request"` + // History of every time a `pending_request` authorization was approved/declined, either by you directly or by Stripe (e.g. based on your spending_controls). If the merchant changes the authorization by performing an incremental authorization, you can look at this field to see the previous requests for the authorization. This field can be helpful in determining why a given authorization was approved/declined. + RequestHistory []*IssuingAuthorizationRequestHistory `json:"request_history"` + // The current status of the authorization in its lifecycle. + Status IssuingAuthorizationStatus `json:"status"` + // [Token](https://stripe.com/docs/api/issuing/tokens/object) object used for this authorization. If a network token was not used for this authorization, this field will be null. + Token *IssuingToken `json:"token"` + // List of [transactions](https://stripe.com/docs/api/issuing/transactions) associated with this authorization. + Transactions []*IssuingTransaction `json:"transactions"` + // [Treasury](https://stripe.com/docs/api/treasury) details related to this authorization if it was created on a [FinancialAccount](https://stripe.com/docs/api/treasury/financial_accounts). + Treasury *IssuingAuthorizationTreasury `json:"treasury"` + VerificationData *IssuingAuthorizationVerificationData `json:"verification_data"` + // Whether the authorization bypassed fraud risk checks because the cardholder has previously completed a fraud challenge on a similar high-risk authorization from the same merchant. + VerifiedByFraudChallenge bool `json:"verified_by_fraud_challenge"` + // The digital wallet used for this transaction. One of `apple_pay`, `google_pay`, or `samsung_pay`. Will populate as `null` when no digital wallet was utilized. + Wallet IssuingAuthorizationWallet `json:"wallet"` +} + +// IssuingAuthorizationList is a list of Authorizations as retrieved from a list endpoint. +type IssuingAuthorizationList struct { + APIResource + ListMeta + Data []*IssuingAuthorization `json:"data"` +} + +// UnmarshalJSON handles deserialization of an IssuingAuthorization. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (i *IssuingAuthorization) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + i.ID = id + return nil + } + + type issuingAuthorization IssuingAuthorization + var v issuingAuthorization + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *i = IssuingAuthorization(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_authorization_service.go b/vendor/github.com/stripe/stripe-go/v82/issuing_authorization_service.go new file mode 100644 index 00000000..13cdfa31 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_authorization_service.go @@ -0,0 +1,87 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1IssuingAuthorizationService is used to invoke /v1/issuing/authorizations APIs. +type v1IssuingAuthorizationService struct { + B Backend + Key string +} + +// Retrieves an Issuing Authorization object. +func (c v1IssuingAuthorizationService) Retrieve(ctx context.Context, id string, params *IssuingAuthorizationRetrieveParams) (*IssuingAuthorization, error) { + if params == nil { + params = &IssuingAuthorizationRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/authorizations/%s", id) + authorization := &IssuingAuthorization{} + err := c.B.Call(http.MethodGet, path, c.Key, params, authorization) + return authorization, err +} + +// Updates the specified Issuing Authorization object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +func (c v1IssuingAuthorizationService) Update(ctx context.Context, id string, params *IssuingAuthorizationUpdateParams) (*IssuingAuthorization, error) { + if params == nil { + params = &IssuingAuthorizationUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/authorizations/%s", id) + authorization := &IssuingAuthorization{} + err := c.B.Call(http.MethodPost, path, c.Key, params, authorization) + return authorization, err +} + +// Deprecated: [Deprecated] Approves a pending Issuing Authorization object. This request should be made within the timeout window of the [real-time authorization](https://docs.stripe.com/docs/issuing/controls/real-time-authorizations) flow. +// This method is deprecated. Instead, [respond directly to the webhook request to approve an authorization](https://docs.stripe.com/docs/issuing/controls/real-time-authorizations#authorization-handling). +func (c v1IssuingAuthorizationService) Approve(ctx context.Context, id string, params *IssuingAuthorizationApproveParams) (*IssuingAuthorization, error) { + if params == nil { + params = &IssuingAuthorizationApproveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/authorizations/%s/approve", id) + authorization := &IssuingAuthorization{} + err := c.B.Call(http.MethodPost, path, c.Key, params, authorization) + return authorization, err +} + +// Deprecated: [Deprecated] Declines a pending Issuing Authorization object. This request should be made within the timeout window of the [real time authorization](https://docs.stripe.com/docs/issuing/controls/real-time-authorizations) flow. +// This method is deprecated. Instead, [respond directly to the webhook request to decline an authorization](https://docs.stripe.com/docs/issuing/controls/real-time-authorizations#authorization-handling). +func (c v1IssuingAuthorizationService) Decline(ctx context.Context, id string, params *IssuingAuthorizationDeclineParams) (*IssuingAuthorization, error) { + if params == nil { + params = &IssuingAuthorizationDeclineParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/authorizations/%s/decline", id) + authorization := &IssuingAuthorization{} + err := c.B.Call(http.MethodPost, path, c.Key, params, authorization) + return authorization, err +} + +// Returns a list of Issuing Authorization objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +func (c v1IssuingAuthorizationService) List(ctx context.Context, listParams *IssuingAuthorizationListParams) Seq2[*IssuingAuthorization, error] { + if listParams == nil { + listParams = &IssuingAuthorizationListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*IssuingAuthorization, ListContainer, error) { + list := &IssuingAuthorizationList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/issuing/authorizations", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_card.go b/vendor/github.com/stripe/stripe-go/v82/issuing_card.go new file mode 100644 index 00000000..848fabfd --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_card.go @@ -0,0 +1,673 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The reason why the card was canceled. +type IssuingCardCancellationReason string + +// List of values that IssuingCardCancellationReason can take +const ( + IssuingCardCancellationReasonDesignRejected IssuingCardCancellationReason = "design_rejected" + IssuingCardCancellationReasonLost IssuingCardCancellationReason = "lost" + IssuingCardCancellationReasonStolen IssuingCardCancellationReason = "stolen" +) + +// The reason why the previous card needed to be replaced. +type IssuingCardReplacementReason string + +// List of values that IssuingCardReplacementReason can take +const ( + IssuingCardReplacementReasonDamaged IssuingCardReplacementReason = "damaged" + IssuingCardReplacementReasonExpired IssuingCardReplacementReason = "expired" + IssuingCardReplacementReasonLost IssuingCardReplacementReason = "lost" + IssuingCardReplacementReasonStolen IssuingCardReplacementReason = "stolen" +) + +// The address validation capabilities to use. +type IssuingCardShippingAddressValidationMode string + +// List of values that IssuingCardShippingAddressValidationMode can take +const ( + IssuingCardShippingAddressValidationModeDisabled IssuingCardShippingAddressValidationMode = "disabled" + IssuingCardShippingAddressValidationModeNormalizationOnly IssuingCardShippingAddressValidationMode = "normalization_only" + IssuingCardShippingAddressValidationModeValidationAndNormalization IssuingCardShippingAddressValidationMode = "validation_and_normalization" +) + +// The validation result for the shipping address. +type IssuingCardShippingAddressValidationResult string + +// List of values that IssuingCardShippingAddressValidationResult can take +const ( + IssuingCardShippingAddressValidationResultIndeterminate IssuingCardShippingAddressValidationResult = "indeterminate" + IssuingCardShippingAddressValidationResultLikelyDeliverable IssuingCardShippingAddressValidationResult = "likely_deliverable" + IssuingCardShippingAddressValidationResultLikelyUndeliverable IssuingCardShippingAddressValidationResult = "likely_undeliverable" +) + +// The delivery company that shipped a card. +type IssuingCardShippingCarrier string + +// List of values that IssuingCardShippingCarrier can take +const ( + IssuingCardShippingCarrierDHL IssuingCardShippingCarrier = "dhl" + IssuingCardShippingCarrierFedEx IssuingCardShippingCarrier = "fedex" + IssuingCardShippingCarrierRoyalMail IssuingCardShippingCarrier = "royal_mail" + IssuingCardShippingCarrierUSPS IssuingCardShippingCarrier = "usps" +) + +// Shipment service, such as `standard` or `express`. +type IssuingCardShippingService string + +// List of values that IssuingCardShippingService can take +const ( + IssuingCardShippingServiceExpress IssuingCardShippingService = "express" + IssuingCardShippingServicePriority IssuingCardShippingService = "priority" + IssuingCardShippingServiceStandard IssuingCardShippingService = "standard" +) + +// The delivery status of the card. +type IssuingCardShippingStatus string + +// List of values that IssuingCardShippingStatus can take +const ( + IssuingCardShippingStatusCanceled IssuingCardShippingStatus = "canceled" + IssuingCardShippingStatusDelivered IssuingCardShippingStatus = "delivered" + IssuingCardShippingStatusFailure IssuingCardShippingStatus = "failure" + IssuingCardShippingStatusPending IssuingCardShippingStatus = "pending" + IssuingCardShippingStatusReturned IssuingCardShippingStatus = "returned" + IssuingCardShippingStatusShipped IssuingCardShippingStatus = "shipped" + IssuingCardShippingStatusSubmitted IssuingCardShippingStatus = "submitted" +) + +// Packaging options. +type IssuingCardShippingType string + +// List of values that IssuingCardShippingType can take +const ( + IssuingCardShippingTypeBulk IssuingCardShippingType = "bulk" + IssuingCardShippingTypeIndividual IssuingCardShippingType = "individual" +) + +// Interval (or event) to which the amount applies. +type IssuingCardSpendingControlsSpendingLimitInterval string + +// List of values that IssuingCardSpendingControlsSpendingLimitInterval can take +const ( + IssuingCardSpendingControlsSpendingLimitIntervalAllTime IssuingCardSpendingControlsSpendingLimitInterval = "all_time" + IssuingCardSpendingControlsSpendingLimitIntervalDaily IssuingCardSpendingControlsSpendingLimitInterval = "daily" + IssuingCardSpendingControlsSpendingLimitIntervalMonthly IssuingCardSpendingControlsSpendingLimitInterval = "monthly" + IssuingCardSpendingControlsSpendingLimitIntervalPerAuthorization IssuingCardSpendingControlsSpendingLimitInterval = "per_authorization" + IssuingCardSpendingControlsSpendingLimitIntervalWeekly IssuingCardSpendingControlsSpendingLimitInterval = "weekly" + IssuingCardSpendingControlsSpendingLimitIntervalYearly IssuingCardSpendingControlsSpendingLimitInterval = "yearly" +) + +// Whether authorizations can be approved on this card. May be blocked from activating cards depending on past-due Cardholder requirements. Defaults to `inactive`. +type IssuingCardStatus string + +// List of values that IssuingCardStatus can take +const ( + IssuingCardStatusActive IssuingCardStatus = "active" + IssuingCardStatusCanceled IssuingCardStatus = "canceled" + IssuingCardStatusInactive IssuingCardStatus = "inactive" +) + +// The type of the card. +type IssuingCardType string + +// List of values that IssuingCardType can take +const ( + IssuingCardTypePhysical IssuingCardType = "physical" + IssuingCardTypeVirtual IssuingCardType = "virtual" +) + +// Reason the card is ineligible for Apple Pay +type IssuingCardWalletsApplePayIneligibleReason string + +// List of values that IssuingCardWalletsApplePayIneligibleReason can take +const ( + IssuingCardWalletsApplePayIneligibleReasonMissingAgreement IssuingCardWalletsApplePayIneligibleReason = "missing_agreement" + IssuingCardWalletsApplePayIneligibleReasonMissingCardholderContact IssuingCardWalletsApplePayIneligibleReason = "missing_cardholder_contact" + IssuingCardWalletsApplePayIneligibleReasonUnsupportedRegion IssuingCardWalletsApplePayIneligibleReason = "unsupported_region" +) + +// Reason the card is ineligible for Google Pay +type IssuingCardWalletsGooglePayIneligibleReason string + +// List of values that IssuingCardWalletsGooglePayIneligibleReason can take +const ( + IssuingCardWalletsGooglePayIneligibleReasonMissingAgreement IssuingCardWalletsGooglePayIneligibleReason = "missing_agreement" + IssuingCardWalletsGooglePayIneligibleReasonMissingCardholderContact IssuingCardWalletsGooglePayIneligibleReason = "missing_cardholder_contact" + IssuingCardWalletsGooglePayIneligibleReasonUnsupportedRegion IssuingCardWalletsGooglePayIneligibleReason = "unsupported_region" +) + +// Returns a list of Issuing Card objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +type IssuingCardListParams struct { + ListParams `form:"*"` + // Only return cards belonging to the Cardholder with the provided ID. + Cardholder *string `form:"cardholder"` + // Only return cards that were issued during the given date interval. + Created *int64 `form:"created"` + // Only return cards that were issued during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return cards that have the given expiration month. + ExpMonth *int64 `form:"exp_month"` + // Only return cards that have the given expiration year. + ExpYear *int64 `form:"exp_year"` + // Only return cards that have the given last four digits. + Last4 *string `form:"last4"` + PersonalizationDesign *string `form:"personalization_design"` + // Only return cards that have the given status. One of `active`, `inactive`, or `canceled`. + Status *string `form:"status"` + // Only return cards that have the given type. One of `virtual` or `physical`. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingCardListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The desired PIN for this card. +type IssuingCardPINParams struct { + // The card's desired new PIN, encrypted under Stripe's public key. + EncryptedNumber *string `form:"encrypted_number"` +} + +// Address validation settings. +type IssuingCardShippingAddressValidationParams struct { + // The address validation capabilities to use. + Mode *string `form:"mode"` +} + +// Customs information for the shipment. +type IssuingCardShippingCustomsParams struct { + // The Economic Operators Registration and Identification (EORI) number to use for Customs. Required for bulk shipments to Europe. + EORINumber *string `form:"eori_number"` +} + +// The address where the card will be shipped. +type IssuingCardShippingParams struct { + // The address that the card is shipped to. + Address *AddressParams `form:"address"` + // Address validation settings. + AddressValidation *IssuingCardShippingAddressValidationParams `form:"address_validation"` + // Customs information for the shipment. + Customs *IssuingCardShippingCustomsParams `form:"customs"` + // The name printed on the shipping label when shipping the card. + Name *string `form:"name"` + // Phone number of the recipient of the shipment. + PhoneNumber *string `form:"phone_number"` + // Whether a signature is required for card delivery. + RequireSignature *bool `form:"require_signature"` + // Shipment service. + Service *string `form:"service"` + // Packaging options. + Type *string `form:"type"` +} + +// Limit spending with amount-based rules that apply across any cards this card replaced (i.e., its `replacement_for` card and _that_ card's `replacement_for` card, up the chain). +type IssuingCardSpendingControlsSpendingLimitParams struct { + // Maximum amount allowed to spend per interval. + Amount *int64 `form:"amount"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories. + Categories []*string `form:"categories"` + // Interval (or event) to which the amount applies. + Interval *string `form:"interval"` +} + +// Rules that control spending for this card. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. +type IssuingCardSpendingControlsParams struct { + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`. + AllowedCategories []*string `form:"allowed_categories"` + // Array of strings containing representing countries from which authorizations will be allowed. Authorizations from merchants in all other countries will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `blocked_merchant_countries`. Provide an empty value to unset this control. + AllowedMerchantCountries []*string `form:"allowed_merchant_countries"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`. + BlockedCategories []*string `form:"blocked_categories"` + // Array of strings containing representing countries from which authorizations will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `allowed_merchant_countries`. Provide an empty value to unset this control. + BlockedMerchantCountries []*string `form:"blocked_merchant_countries"` + // Limit spending with amount-based rules that apply across any cards this card replaced (i.e., its `replacement_for` card and _that_ card's `replacement_for` card, up the chain). + SpendingLimits []*IssuingCardSpendingControlsSpendingLimitParams `form:"spending_limits"` +} + +// Creates an Issuing Card object. +type IssuingCardParams struct { + Params `form:"*"` + // The [Cardholder](https://stripe.com/docs/api#issuing_cardholder_object) object with which the card will be associated. + Cardholder *string `form:"cardholder"` + // The currency for the card. + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The new financial account ID the card will be associated with. This field allows a card to be reassigned to a different financial account. + FinancialAccount *string `form:"financial_account"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The personalization design object belonging to this card. + PersonalizationDesign *string `form:"personalization_design"` + // The desired new PIN for this card. + PIN *IssuingCardPINParams `form:"pin"` + // The card this is meant to be a replacement for (if any). + ReplacementFor *string `form:"replacement_for"` + // If `replacement_for` is specified, this should indicate why that card is being replaced. + ReplacementReason *string `form:"replacement_reason"` + // The second line to print on the card. Max length: 24 characters. + SecondLine *string `form:"second_line"` + // The address where the card will be shipped. + Shipping *IssuingCardShippingParams `form:"shipping"` + // Rules that control spending for this card. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. + SpendingControls *IssuingCardSpendingControlsParams `form:"spending_controls"` + // Dictates whether authorizations can be approved on this card. May be blocked from activating cards depending on past-due Cardholder requirements. Defaults to `inactive`. If this card is being canceled because it was lost or stolen, this information should be provided as `cancellation_reason`. + Status *string `form:"status"` + // The type of card to issue. Possible values are `physical` or `virtual`. + Type *string `form:"type"` + // The following parameter is only supported when updating a card + // Reason why the `status` of this card is `canceled`. + CancellationReason *string `form:"cancellation_reason"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingCardParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingCardParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The desired PIN for this card. +type IssuingCardCreatePINParams struct { + // The card's desired new PIN, encrypted under Stripe's public key. + EncryptedNumber *string `form:"encrypted_number"` +} + +// Address validation settings. +type IssuingCardCreateShippingAddressValidationParams struct { + // The address validation capabilities to use. + Mode *string `form:"mode"` +} + +// Customs information for the shipment. +type IssuingCardCreateShippingCustomsParams struct { + // The Economic Operators Registration and Identification (EORI) number to use for Customs. Required for bulk shipments to Europe. + EORINumber *string `form:"eori_number"` +} + +// The address where the card will be shipped. +type IssuingCardCreateShippingParams struct { + // The address that the card is shipped to. + Address *AddressParams `form:"address"` + // Address validation settings. + AddressValidation *IssuingCardCreateShippingAddressValidationParams `form:"address_validation"` + // Customs information for the shipment. + Customs *IssuingCardCreateShippingCustomsParams `form:"customs"` + // The name printed on the shipping label when shipping the card. + Name *string `form:"name"` + // Phone number of the recipient of the shipment. + PhoneNumber *string `form:"phone_number"` + // Whether a signature is required for card delivery. + RequireSignature *bool `form:"require_signature"` + // Shipment service. + Service *string `form:"service"` + // Packaging options. + Type *string `form:"type"` +} + +// Limit spending with amount-based rules that apply across any cards this card replaced (i.e., its `replacement_for` card and _that_ card's `replacement_for` card, up the chain). +type IssuingCardCreateSpendingControlsSpendingLimitParams struct { + // Maximum amount allowed to spend per interval. + Amount *int64 `form:"amount"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories. + Categories []*string `form:"categories"` + // Interval (or event) to which the amount applies. + Interval *string `form:"interval"` +} + +// Rules that control spending for this card. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. +type IssuingCardCreateSpendingControlsParams struct { + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`. + AllowedCategories []*string `form:"allowed_categories"` + // Array of strings containing representing countries from which authorizations will be allowed. Authorizations from merchants in all other countries will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `blocked_merchant_countries`. Provide an empty value to unset this control. + AllowedMerchantCountries []*string `form:"allowed_merchant_countries"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`. + BlockedCategories []*string `form:"blocked_categories"` + // Array of strings containing representing countries from which authorizations will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `allowed_merchant_countries`. Provide an empty value to unset this control. + BlockedMerchantCountries []*string `form:"blocked_merchant_countries"` + // Limit spending with amount-based rules that apply across any cards this card replaced (i.e., its `replacement_for` card and _that_ card's `replacement_for` card, up the chain). + SpendingLimits []*IssuingCardCreateSpendingControlsSpendingLimitParams `form:"spending_limits"` +} + +// Creates an Issuing Card object. +type IssuingCardCreateParams struct { + Params `form:"*"` + // The [Cardholder](https://stripe.com/docs/api#issuing_cardholder_object) object with which the card will be associated. + Cardholder *string `form:"cardholder"` + // The currency for the card. + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The new financial account ID the card will be associated with. This field allows a card to be reassigned to a different financial account. + FinancialAccount *string `form:"financial_account"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The personalization design object belonging to this card. + PersonalizationDesign *string `form:"personalization_design"` + // The desired PIN for this card. + PIN *IssuingCardCreatePINParams `form:"pin"` + // The card this is meant to be a replacement for (if any). + ReplacementFor *string `form:"replacement_for"` + // If `replacement_for` is specified, this should indicate why that card is being replaced. + ReplacementReason *string `form:"replacement_reason"` + // The second line to print on the card. Max length: 24 characters. + SecondLine *string `form:"second_line"` + // The address where the card will be shipped. + Shipping *IssuingCardCreateShippingParams `form:"shipping"` + // Rules that control spending for this card. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. + SpendingControls *IssuingCardCreateSpendingControlsParams `form:"spending_controls"` + // Whether authorizations can be approved on this card. May be blocked from activating cards depending on past-due Cardholder requirements. Defaults to `inactive`. + Status *string `form:"status"` + // The type of card to issue. Possible values are `physical` or `virtual`. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingCardCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingCardCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves an Issuing Card object. +type IssuingCardRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingCardRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The desired new PIN for this card. +type IssuingCardUpdatePINParams struct { + // The card's desired new PIN, encrypted under Stripe's public key. + EncryptedNumber *string `form:"encrypted_number"` +} + +// Address validation settings. +type IssuingCardUpdateShippingAddressValidationParams struct { + // The address validation capabilities to use. + Mode *string `form:"mode"` +} + +// Customs information for the shipment. +type IssuingCardUpdateShippingCustomsParams struct { + // The Economic Operators Registration and Identification (EORI) number to use for Customs. Required for bulk shipments to Europe. + EORINumber *string `form:"eori_number"` +} + +// Updated shipping information for the card. +type IssuingCardUpdateShippingParams struct { + // The address that the card is shipped to. + Address *AddressParams `form:"address"` + // Address validation settings. + AddressValidation *IssuingCardUpdateShippingAddressValidationParams `form:"address_validation"` + // Customs information for the shipment. + Customs *IssuingCardUpdateShippingCustomsParams `form:"customs"` + // The name printed on the shipping label when shipping the card. + Name *string `form:"name"` + // Phone number of the recipient of the shipment. + PhoneNumber *string `form:"phone_number"` + // Whether a signature is required for card delivery. + RequireSignature *bool `form:"require_signature"` + // Shipment service. + Service *string `form:"service"` + // Packaging options. + Type *string `form:"type"` +} + +// Limit spending with amount-based rules that apply across any cards this card replaced (i.e., its `replacement_for` card and _that_ card's `replacement_for` card, up the chain). +type IssuingCardUpdateSpendingControlsSpendingLimitParams struct { + // Maximum amount allowed to spend per interval. + Amount *int64 `form:"amount"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories. + Categories []*string `form:"categories"` + // Interval (or event) to which the amount applies. + Interval *string `form:"interval"` +} + +// Rules that control spending for this card. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. +type IssuingCardUpdateSpendingControlsParams struct { + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`. + AllowedCategories []*string `form:"allowed_categories"` + // Array of strings containing representing countries from which authorizations will be allowed. Authorizations from merchants in all other countries will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `blocked_merchant_countries`. Provide an empty value to unset this control. + AllowedMerchantCountries []*string `form:"allowed_merchant_countries"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`. + BlockedCategories []*string `form:"blocked_categories"` + // Array of strings containing representing countries from which authorizations will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `allowed_merchant_countries`. Provide an empty value to unset this control. + BlockedMerchantCountries []*string `form:"blocked_merchant_countries"` + // Limit spending with amount-based rules that apply across any cards this card replaced (i.e., its `replacement_for` card and _that_ card's `replacement_for` card, up the chain). + SpendingLimits []*IssuingCardUpdateSpendingControlsSpendingLimitParams `form:"spending_limits"` +} + +// Updates the specified Issuing Card object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +type IssuingCardUpdateParams struct { + Params `form:"*"` + // Reason why the `status` of this card is `canceled`. + CancellationReason *string `form:"cancellation_reason"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + PersonalizationDesign *string `form:"personalization_design"` + // The desired new PIN for this card. + PIN *IssuingCardUpdatePINParams `form:"pin"` + // Updated shipping information for the card. + Shipping *IssuingCardUpdateShippingParams `form:"shipping"` + // Rules that control spending for this card. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. + SpendingControls *IssuingCardUpdateSpendingControlsParams `form:"spending_controls"` + // Dictates whether authorizations can be approved on this card. May be blocked from activating cards depending on past-due Cardholder requirements. Defaults to `inactive`. If this card is being canceled because it was lost or stolen, this information should be provided as `cancellation_reason`. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingCardUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingCardUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Address validation details for the shipment. +type IssuingCardShippingAddressValidation struct { + // The address validation capabilities to use. + Mode IssuingCardShippingAddressValidationMode `json:"mode"` + // The normalized shipping address. + NormalizedAddress *Address `json:"normalized_address"` + // The validation result for the shipping address. + Result IssuingCardShippingAddressValidationResult `json:"result"` +} + +// Additional information that may be required for clearing customs. +type IssuingCardShippingCustoms struct { + // A registration number used for customs in Europe. See [https://www.gov.uk/eori](https://www.gov.uk/eori) for the UK and [https://ec.europa.eu/taxation_customs/business/customs-procedures-import-and-export/customs-procedures/economic-operators-registration-and-identification-number-eori_en](https://ec.europa.eu/taxation_customs/business/customs-procedures-import-and-export/customs-procedures/economic-operators-registration-and-identification-number-eori_en) for the EU. + EORINumber string `json:"eori_number"` +} + +// Where and how the card will be shipped. +type IssuingCardShipping struct { + Address *Address `json:"address"` + // Address validation details for the shipment. + AddressValidation *IssuingCardShippingAddressValidation `json:"address_validation"` + // The delivery company that shipped a card. + Carrier IssuingCardShippingCarrier `json:"carrier"` + // Additional information that may be required for clearing customs. + Customs *IssuingCardShippingCustoms `json:"customs"` + // A unix timestamp representing a best estimate of when the card will be delivered. + ETA int64 `json:"eta"` + // Recipient name. + Name string `json:"name"` + // The phone number of the receiver of the shipment. Our courier partners will use this number to contact you in the event of card delivery issues. For individual shipments to the EU/UK, if this field is empty, we will provide them with the phone number provided when the cardholder was initially created. + PhoneNumber string `json:"phone_number"` + // Whether a signature is required for card delivery. This feature is only supported for US users. Standard shipping service does not support signature on delivery. The default value for standard shipping service is false and for express and priority services is true. + RequireSignature bool `json:"require_signature"` + // Shipment service, such as `standard` or `express`. + Service IssuingCardShippingService `json:"service"` + // The delivery status of the card. + Status IssuingCardShippingStatus `json:"status"` + // A tracking number for a card shipment. + TrackingNumber string `json:"tracking_number"` + // A link to the shipping carrier's site where you can view detailed information about a card shipment. + TrackingURL string `json:"tracking_url"` + // Packaging options. + Type IssuingCardShippingType `json:"type"` +} + +// Limit spending with amount-based rules that apply across any cards this card replaced (i.e., its `replacement_for` card and _that_ card's `replacement_for` card, up the chain). +type IssuingCardSpendingControlsSpendingLimit struct { + // Maximum amount allowed to spend per interval. This amount is in the card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Amount int64 `json:"amount"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories. + Categories []string `json:"categories"` + // Interval (or event) to which the amount applies. + Interval IssuingCardSpendingControlsSpendingLimitInterval `json:"interval"` +} +type IssuingCardSpendingControls struct { + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`. + AllowedCategories []string `json:"allowed_categories"` + // Array of strings containing representing countries from which authorizations will be allowed. Authorizations from merchants in all other countries will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `blocked_merchant_countries`. Provide an empty value to unset this control. + AllowedMerchantCountries []string `json:"allowed_merchant_countries"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`. + BlockedCategories []string `json:"blocked_categories"` + // Array of strings containing representing countries from which authorizations will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `allowed_merchant_countries`. Provide an empty value to unset this control. + BlockedMerchantCountries []string `json:"blocked_merchant_countries"` + // Limit spending with amount-based rules that apply across any cards this card replaced (i.e., its `replacement_for` card and _that_ card's `replacement_for` card, up the chain). + SpendingLimits []*IssuingCardSpendingControlsSpendingLimit `json:"spending_limits"` + // Currency of the amounts within `spending_limits`. Always the same as the currency of the card. + SpendingLimitsCurrency Currency `json:"spending_limits_currency"` +} +type IssuingCardWalletsApplePay struct { + // Apple Pay Eligibility + Eligible bool `json:"eligible"` + // Reason the card is ineligible for Apple Pay + IneligibleReason IssuingCardWalletsApplePayIneligibleReason `json:"ineligible_reason"` +} +type IssuingCardWalletsGooglePay struct { + // Google Pay Eligibility + Eligible bool `json:"eligible"` + // Reason the card is ineligible for Google Pay + IneligibleReason IssuingCardWalletsGooglePayIneligibleReason `json:"ineligible_reason"` +} + +// Information relating to digital wallets (like Apple Pay and Google Pay). +type IssuingCardWallets struct { + ApplePay *IssuingCardWalletsApplePay `json:"apple_pay"` + GooglePay *IssuingCardWalletsGooglePay `json:"google_pay"` + // Unique identifier for a card used with digital wallets + PrimaryAccountIdentifier string `json:"primary_account_identifier"` +} + +// You can [create physical or virtual cards](https://stripe.com/docs/issuing) that are issued to cardholders. +type IssuingCard struct { + APIResource + // The brand of the card. + Brand string `json:"brand"` + // The reason why the card was canceled. + CancellationReason IssuingCardCancellationReason `json:"cancellation_reason"` + // An Issuing `Cardholder` object represents an individual or business entity who is [issued](https://stripe.com/docs/issuing) cards. + // + // Related guide: [How to create a cardholder](https://stripe.com/docs/issuing/cards/virtual/issue-cards#create-cardholder) + Cardholder *IssuingCardholder `json:"cardholder"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Supported currencies are `usd` in the US, `eur` in the EU, and `gbp` in the UK. + Currency Currency `json:"currency"` + // The card's CVC. For security reasons, this is only available for virtual cards, and will be omitted unless you explicitly request it with [the `expand` parameter](https://stripe.com/docs/api/expanding_objects). Additionally, it's only available via the ["Retrieve a card" endpoint](https://stripe.com/docs/api/issuing/cards/retrieve), not via "List all cards" or any other endpoint. + CVC string `json:"cvc"` + // The expiration month of the card. + ExpMonth int64 `json:"exp_month"` + // The expiration year of the card. + ExpYear int64 `json:"exp_year"` + // The financial account this card is attached to. + FinancialAccount string `json:"financial_account"` + // Unique identifier for the object. + ID string `json:"id"` + // The last 4 digits of the card number. + Last4 string `json:"last4"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // The full unredacted card number. For security reasons, this is only available for virtual cards, and will be omitted unless you explicitly request it with [the `expand` parameter](https://stripe.com/docs/api/expanding_objects). Additionally, it's only available via the ["Retrieve a card" endpoint](https://stripe.com/docs/api/issuing/cards/retrieve), not via "List all cards" or any other endpoint. + Number string `json:"number"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The personalization design object belonging to this card. + PersonalizationDesign *IssuingPersonalizationDesign `json:"personalization_design"` + // The latest card that replaces this card, if any. + ReplacedBy *IssuingCard `json:"replaced_by"` + // The card this card replaces, if any. + ReplacementFor *IssuingCard `json:"replacement_for"` + // The reason why the previous card needed to be replaced. + ReplacementReason IssuingCardReplacementReason `json:"replacement_reason"` + // Where and how the card will be shipped. + Shipping *IssuingCardShipping `json:"shipping"` + SpendingControls *IssuingCardSpendingControls `json:"spending_controls"` + // Whether authorizations can be approved on this card. May be blocked from activating cards depending on past-due Cardholder requirements. Defaults to `inactive`. + Status IssuingCardStatus `json:"status"` + // The type of the card. + Type IssuingCardType `json:"type"` + // Information relating to digital wallets (like Apple Pay and Google Pay). + Wallets *IssuingCardWallets `json:"wallets"` +} + +// IssuingCardList is a list of Cards as retrieved from a list endpoint. +type IssuingCardList struct { + APIResource + ListMeta + Data []*IssuingCard `json:"data"` +} + +// UnmarshalJSON handles deserialization of an IssuingCard. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (i *IssuingCard) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + i.ID = id + return nil + } + + type issuingCard IssuingCard + var v issuingCard + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *i = IssuingCard(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_card_service.go b/vendor/github.com/stripe/stripe-go/v82/issuing_card_service.go new file mode 100644 index 00000000..4f4affc4 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_card_service.go @@ -0,0 +1,72 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1IssuingCardService is used to invoke /v1/issuing/cards APIs. +type v1IssuingCardService struct { + B Backend + Key string +} + +// Creates an Issuing Card object. +func (c v1IssuingCardService) Create(ctx context.Context, params *IssuingCardCreateParams) (*IssuingCard, error) { + if params == nil { + params = &IssuingCardCreateParams{} + } + params.Context = ctx + card := &IssuingCard{} + err := c.B.Call(http.MethodPost, "/v1/issuing/cards", c.Key, params, card) + return card, err +} + +// Retrieves an Issuing Card object. +func (c v1IssuingCardService) Retrieve(ctx context.Context, id string, params *IssuingCardRetrieveParams) (*IssuingCard, error) { + if params == nil { + params = &IssuingCardRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/cards/%s", id) + card := &IssuingCard{} + err := c.B.Call(http.MethodGet, path, c.Key, params, card) + return card, err +} + +// Updates the specified Issuing Card object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +func (c v1IssuingCardService) Update(ctx context.Context, id string, params *IssuingCardUpdateParams) (*IssuingCard, error) { + if params == nil { + params = &IssuingCardUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/cards/%s", id) + card := &IssuingCard{} + err := c.B.Call(http.MethodPost, path, c.Key, params, card) + return card, err +} + +// Returns a list of Issuing Card objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +func (c v1IssuingCardService) List(ctx context.Context, listParams *IssuingCardListParams) Seq2[*IssuingCard, error] { + if listParams == nil { + listParams = &IssuingCardListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*IssuingCard, ListContainer, error) { + list := &IssuingCardList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/issuing/cards", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_cardholder.go b/vendor/github.com/stripe/stripe-go/v82/issuing_cardholder.go new file mode 100644 index 00000000..26dd9033 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_cardholder.go @@ -0,0 +1,666 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The cardholder's preferred locales (languages), ordered by preference. Locales can be `de`, `en`, `es`, `fr`, or `it`. +// +// This changes the language of the [3D Secure flow](https://stripe.com/docs/issuing/3d-secure) and one-time password messages sent to the cardholder. +type IssuingCardholderPreferredLocale string + +// List of values that IssuingCardholderPreferredLocale can take +const ( + IssuingCardholderPreferredLocaleDE IssuingCardholderPreferredLocale = "de" + IssuingCardholderPreferredLocaleEN IssuingCardholderPreferredLocale = "en" + IssuingCardholderPreferredLocaleES IssuingCardholderPreferredLocale = "es" + IssuingCardholderPreferredLocaleFR IssuingCardholderPreferredLocale = "fr" + IssuingCardholderPreferredLocaleIT IssuingCardholderPreferredLocale = "it" +) + +// If `disabled_reason` is present, all cards will decline authorizations with `cardholder_verification_required` reason. +type IssuingCardholderRequirementsDisabledReason string + +// List of values that IssuingCardholderRequirementsDisabledReason can take +const ( + IssuingCardholderRequirementsDisabledReasonListed IssuingCardholderRequirementsDisabledReason = "listed" + IssuingCardholderRequirementsDisabledReasonRejectedListed IssuingCardholderRequirementsDisabledReason = "rejected.listed" + IssuingCardholderRequirementsDisabledReasonRequirementsPastDue IssuingCardholderRequirementsDisabledReason = "requirements.past_due" + IssuingCardholderRequirementsDisabledReasonUnderReview IssuingCardholderRequirementsDisabledReason = "under_review" +) + +// Interval (or event) to which the amount applies. +type IssuingCardholderSpendingControlsSpendingLimitInterval string + +// List of values that IssuingCardholderSpendingControlsSpendingLimitInterval can take +const ( + IssuingCardholderSpendingControlsSpendingLimitIntervalAllTime IssuingCardholderSpendingControlsSpendingLimitInterval = "all_time" + IssuingCardholderSpendingControlsSpendingLimitIntervalDaily IssuingCardholderSpendingControlsSpendingLimitInterval = "daily" + IssuingCardholderSpendingControlsSpendingLimitIntervalMonthly IssuingCardholderSpendingControlsSpendingLimitInterval = "monthly" + IssuingCardholderSpendingControlsSpendingLimitIntervalPerAuthorization IssuingCardholderSpendingControlsSpendingLimitInterval = "per_authorization" + IssuingCardholderSpendingControlsSpendingLimitIntervalWeekly IssuingCardholderSpendingControlsSpendingLimitInterval = "weekly" + IssuingCardholderSpendingControlsSpendingLimitIntervalYearly IssuingCardholderSpendingControlsSpendingLimitInterval = "yearly" +) + +// Specifies whether to permit authorizations on this cardholder's cards. +type IssuingCardholderStatus string + +// List of values that IssuingCardholderStatus can take +const ( + IssuingCardholderStatusActive IssuingCardholderStatus = "active" + IssuingCardholderStatusBlocked IssuingCardholderStatus = "blocked" + IssuingCardholderStatusInactive IssuingCardholderStatus = "inactive" +) + +// One of `individual` or `company`. See [Choose a cardholder type](https://stripe.com/docs/issuing/other/choose-cardholder) for more details. +type IssuingCardholderType string + +// List of values that IssuingCardholderType can take +const ( + IssuingCardholderTypeCompany IssuingCardholderType = "company" + IssuingCardholderTypeIndividual IssuingCardholderType = "individual" +) + +// Returns a list of Issuing Cardholder objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +type IssuingCardholderListParams struct { + ListParams `form:"*"` + // Only return cardholders that were created during the given date interval. + Created *int64 `form:"created"` + // Only return cardholders that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Only return cardholders that have the given email address. + Email *string `form:"email"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return cardholders that have the given phone number. + PhoneNumber *string `form:"phone_number"` + // Only return cardholders that have the given status. One of `active`, `inactive`, or `blocked`. + Status *string `form:"status"` + // Only return cardholders that have the given type. One of `individual` or `company`. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingCardholderListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The cardholder's billing address. +type IssuingCardholderBillingParams struct { + // The cardholder's billing address. + Address *AddressParams `form:"address"` +} + +// Additional information about a `company` cardholder. +type IssuingCardholderCompanyParams struct { + // The entity's business ID number. + TaxID *string `form:"tax_id"` +} + +// Information about cardholder acceptance of Celtic [Authorized User Terms](https://stripe.com/docs/issuing/cards#accept-authorized-user-terms). Required for cards backed by a Celtic program. +type IssuingCardholderIndividualCardIssuingUserTermsAcceptanceParams struct { + // The Unix timestamp marking when the cardholder accepted the Authorized User Terms. Required for Celtic Spend Card users. + Date *int64 `form:"date"` + // The IP address from which the cardholder accepted the Authorized User Terms. Required for Celtic Spend Card users. + IP *string `form:"ip"` + // The user agent of the browser from which the cardholder accepted the Authorized User Terms. + UserAgent *string `form:"user_agent"` +} + +// Information related to the card_issuing program for this cardholder. +type IssuingCardholderIndividualCardIssuingParams struct { + // Information about cardholder acceptance of Celtic [Authorized User Terms](https://stripe.com/docs/issuing/cards#accept-authorized-user-terms). Required for cards backed by a Celtic program. + UserTermsAcceptance *IssuingCardholderIndividualCardIssuingUserTermsAcceptanceParams `form:"user_terms_acceptance"` +} + +// The date of birth of this cardholder. Cardholders must be older than 13 years old. +type IssuingCardholderIndividualDOBParams struct { + // The day of birth, between 1 and 31. + Day *int64 `form:"day"` + // The month of birth, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of birth. + Year *int64 `form:"year"` +} + +// An identifying document, either a passport or local ID card. +type IssuingCardholderIndividualVerificationDocumentParams struct { + // The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + Back *string `form:"back"` + // The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + Front *string `form:"front"` +} + +// Government-issued ID document for this cardholder. +type IssuingCardholderIndividualVerificationParams struct { + // An identifying document, either a passport or local ID card. + Document *IssuingCardholderIndividualVerificationDocumentParams `form:"document"` +} + +// Additional information about an `individual` cardholder. +type IssuingCardholderIndividualParams struct { + // Information related to the card_issuing program for this cardholder. + CardIssuing *IssuingCardholderIndividualCardIssuingParams `form:"card_issuing"` + // The date of birth of this cardholder. Cardholders must be older than 13 years old. + DOB *IssuingCardholderIndividualDOBParams `form:"dob"` + // The first name of this cardholder. Required before activating Cards. This field cannot contain any numbers, special characters (except periods, commas, hyphens, spaces and apostrophes) or non-latin letters. + FirstName *string `form:"first_name"` + // The last name of this cardholder. Required before activating Cards. This field cannot contain any numbers, special characters (except periods, commas, hyphens, spaces and apostrophes) or non-latin letters. + LastName *string `form:"last_name"` + // Government-issued ID document for this cardholder. + Verification *IssuingCardholderIndividualVerificationParams `form:"verification"` +} + +// Limit spending with amount-based rules that apply across this cardholder's cards. +type IssuingCardholderSpendingControlsSpendingLimitParams struct { + // Maximum amount allowed to spend per interval. + Amount *int64 `form:"amount"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories. + Categories []*string `form:"categories"` + // Interval (or event) to which the amount applies. + Interval *string `form:"interval"` +} + +// Rules that control spending across this cardholder's cards. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. +type IssuingCardholderSpendingControlsParams struct { + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`. + AllowedCategories []*string `form:"allowed_categories"` + // Array of strings containing representing countries from which authorizations will be allowed. Authorizations from merchants in all other countries will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `blocked_merchant_countries`. Provide an empty value to unset this control. + AllowedMerchantCountries []*string `form:"allowed_merchant_countries"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`. + BlockedCategories []*string `form:"blocked_categories"` + // Array of strings containing representing countries from which authorizations will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `allowed_merchant_countries`. Provide an empty value to unset this control. + BlockedMerchantCountries []*string `form:"blocked_merchant_countries"` + // Limit spending with amount-based rules that apply across this cardholder's cards. + SpendingLimits []*IssuingCardholderSpendingControlsSpendingLimitParams `form:"spending_limits"` + // Currency of amounts within `spending_limits`. Defaults to your merchant country's currency. + SpendingLimitsCurrency *string `form:"spending_limits_currency"` +} + +// Creates a new Issuing Cardholder object that can be issued cards. +type IssuingCardholderParams struct { + Params `form:"*"` + // The cardholder's billing address. + Billing *IssuingCardholderBillingParams `form:"billing"` + // Additional information about a `company` cardholder. + Company *IssuingCardholderCompanyParams `form:"company"` + // The cardholder's email address. + Email *string `form:"email"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Additional information about an `individual` cardholder. + Individual *IssuingCardholderIndividualParams `form:"individual"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The cardholder's name. This will be printed on cards issued to them. The maximum length of this field is 24 characters. This field cannot contain any special characters or numbers. + Name *string `form:"name"` + // The cardholder's phone number. This will be transformed to [E.164](https://en.wikipedia.org/wiki/E.164) if it is not provided in that format already. This is required for all cardholders who will be creating EU cards. See the [3D Secure documentation](https://stripe.com/docs/issuing/3d-secure#when-is-3d-secure-applied) for more details. + PhoneNumber *string `form:"phone_number"` + // The cardholder's preferred locales (languages), ordered by preference. Locales can be `de`, `en`, `es`, `fr`, or `it`. + // This changes the language of the [3D Secure flow](https://stripe.com/docs/issuing/3d-secure) and one-time password messages sent to the cardholder. + PreferredLocales []*string `form:"preferred_locales"` + // Rules that control spending across this cardholder's cards. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. + SpendingControls *IssuingCardholderSpendingControlsParams `form:"spending_controls"` + // Specifies whether to permit authorizations on this cardholder's cards. Defaults to `active`. + Status *string `form:"status"` + // One of `individual` or `company`. See [Choose a cardholder type](https://stripe.com/docs/issuing/other/choose-cardholder) for more details. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingCardholderParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingCardholderParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The cardholder's billing address. +type IssuingCardholderCreateBillingParams struct { + // The cardholder's billing address. + Address *AddressParams `form:"address"` +} + +// Additional information about a `company` cardholder. +type IssuingCardholderCreateCompanyParams struct { + // The entity's business ID number. + TaxID *string `form:"tax_id"` +} + +// Information about cardholder acceptance of Celtic [Authorized User Terms](https://stripe.com/docs/issuing/cards#accept-authorized-user-terms). Required for cards backed by a Celtic program. +type IssuingCardholderCreateIndividualCardIssuingUserTermsAcceptanceParams struct { + // The Unix timestamp marking when the cardholder accepted the Authorized User Terms. Required for Celtic Spend Card users. + Date *int64 `form:"date"` + // The IP address from which the cardholder accepted the Authorized User Terms. Required for Celtic Spend Card users. + IP *string `form:"ip"` + // The user agent of the browser from which the cardholder accepted the Authorized User Terms. + UserAgent *string `form:"user_agent"` +} + +// Information related to the card_issuing program for this cardholder. +type IssuingCardholderCreateIndividualCardIssuingParams struct { + // Information about cardholder acceptance of Celtic [Authorized User Terms](https://stripe.com/docs/issuing/cards#accept-authorized-user-terms). Required for cards backed by a Celtic program. + UserTermsAcceptance *IssuingCardholderCreateIndividualCardIssuingUserTermsAcceptanceParams `form:"user_terms_acceptance"` +} + +// The date of birth of this cardholder. Cardholders must be older than 13 years old. +type IssuingCardholderCreateIndividualDOBParams struct { + // The day of birth, between 1 and 31. + Day *int64 `form:"day"` + // The month of birth, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of birth. + Year *int64 `form:"year"` +} + +// An identifying document, either a passport or local ID card. +type IssuingCardholderCreateIndividualVerificationDocumentParams struct { + // The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + Back *string `form:"back"` + // The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + Front *string `form:"front"` +} + +// Government-issued ID document for this cardholder. +type IssuingCardholderCreateIndividualVerificationParams struct { + // An identifying document, either a passport or local ID card. + Document *IssuingCardholderCreateIndividualVerificationDocumentParams `form:"document"` +} + +// Additional information about an `individual` cardholder. +type IssuingCardholderCreateIndividualParams struct { + // Information related to the card_issuing program for this cardholder. + CardIssuing *IssuingCardholderCreateIndividualCardIssuingParams `form:"card_issuing"` + // The date of birth of this cardholder. Cardholders must be older than 13 years old. + DOB *IssuingCardholderCreateIndividualDOBParams `form:"dob"` + // The first name of this cardholder. Required before activating Cards. This field cannot contain any numbers, special characters (except periods, commas, hyphens, spaces and apostrophes) or non-latin letters. + FirstName *string `form:"first_name"` + // The last name of this cardholder. Required before activating Cards. This field cannot contain any numbers, special characters (except periods, commas, hyphens, spaces and apostrophes) or non-latin letters. + LastName *string `form:"last_name"` + // Government-issued ID document for this cardholder. + Verification *IssuingCardholderCreateIndividualVerificationParams `form:"verification"` +} + +// Limit spending with amount-based rules that apply across this cardholder's cards. +type IssuingCardholderCreateSpendingControlsSpendingLimitParams struct { + // Maximum amount allowed to spend per interval. + Amount *int64 `form:"amount"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories. + Categories []*string `form:"categories"` + // Interval (or event) to which the amount applies. + Interval *string `form:"interval"` +} + +// Rules that control spending across this cardholder's cards. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. +type IssuingCardholderCreateSpendingControlsParams struct { + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`. + AllowedCategories []*string `form:"allowed_categories"` + // Array of strings containing representing countries from which authorizations will be allowed. Authorizations from merchants in all other countries will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `blocked_merchant_countries`. Provide an empty value to unset this control. + AllowedMerchantCountries []*string `form:"allowed_merchant_countries"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`. + BlockedCategories []*string `form:"blocked_categories"` + // Array of strings containing representing countries from which authorizations will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `allowed_merchant_countries`. Provide an empty value to unset this control. + BlockedMerchantCountries []*string `form:"blocked_merchant_countries"` + // Limit spending with amount-based rules that apply across this cardholder's cards. + SpendingLimits []*IssuingCardholderCreateSpendingControlsSpendingLimitParams `form:"spending_limits"` + // Currency of amounts within `spending_limits`. Defaults to your merchant country's currency. + SpendingLimitsCurrency *string `form:"spending_limits_currency"` +} + +// Creates a new Issuing Cardholder object that can be issued cards. +type IssuingCardholderCreateParams struct { + Params `form:"*"` + // The cardholder's billing address. + Billing *IssuingCardholderCreateBillingParams `form:"billing"` + // Additional information about a `company` cardholder. + Company *IssuingCardholderCreateCompanyParams `form:"company"` + // The cardholder's email address. + Email *string `form:"email"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Additional information about an `individual` cardholder. + Individual *IssuingCardholderCreateIndividualParams `form:"individual"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The cardholder's name. This will be printed on cards issued to them. The maximum length of this field is 24 characters. This field cannot contain any special characters or numbers. + Name *string `form:"name"` + // The cardholder's phone number. This will be transformed to [E.164](https://en.wikipedia.org/wiki/E.164) if it is not provided in that format already. This is required for all cardholders who will be creating EU cards. See the [3D Secure documentation](https://stripe.com/docs/issuing/3d-secure#when-is-3d-secure-applied) for more details. + PhoneNumber *string `form:"phone_number"` + // The cardholder's preferred locales (languages), ordered by preference. Locales can be `de`, `en`, `es`, `fr`, or `it`. + // This changes the language of the [3D Secure flow](https://stripe.com/docs/issuing/3d-secure) and one-time password messages sent to the cardholder. + PreferredLocales []*string `form:"preferred_locales"` + // Rules that control spending across this cardholder's cards. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. + SpendingControls *IssuingCardholderCreateSpendingControlsParams `form:"spending_controls"` + // Specifies whether to permit authorizations on this cardholder's cards. Defaults to `active`. + Status *string `form:"status"` + // One of `individual` or `company`. See [Choose a cardholder type](https://stripe.com/docs/issuing/other/choose-cardholder) for more details. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingCardholderCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingCardholderCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves an Issuing Cardholder object. +type IssuingCardholderRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingCardholderRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The cardholder's billing address. +type IssuingCardholderUpdateBillingParams struct { + // The cardholder's billing address. + Address *AddressParams `form:"address"` +} + +// Additional information about a `company` cardholder. +type IssuingCardholderUpdateCompanyParams struct { + // The entity's business ID number. + TaxID *string `form:"tax_id"` +} + +// Information about cardholder acceptance of Celtic [Authorized User Terms](https://stripe.com/docs/issuing/cards#accept-authorized-user-terms). Required for cards backed by a Celtic program. +type IssuingCardholderUpdateIndividualCardIssuingUserTermsAcceptanceParams struct { + // The Unix timestamp marking when the cardholder accepted the Authorized User Terms. Required for Celtic Spend Card users. + Date *int64 `form:"date"` + // The IP address from which the cardholder accepted the Authorized User Terms. Required for Celtic Spend Card users. + IP *string `form:"ip"` + // The user agent of the browser from which the cardholder accepted the Authorized User Terms. + UserAgent *string `form:"user_agent"` +} + +// Information related to the card_issuing program for this cardholder. +type IssuingCardholderUpdateIndividualCardIssuingParams struct { + // Information about cardholder acceptance of Celtic [Authorized User Terms](https://stripe.com/docs/issuing/cards#accept-authorized-user-terms). Required for cards backed by a Celtic program. + UserTermsAcceptance *IssuingCardholderUpdateIndividualCardIssuingUserTermsAcceptanceParams `form:"user_terms_acceptance"` +} + +// The date of birth of this cardholder. Cardholders must be older than 13 years old. +type IssuingCardholderUpdateIndividualDOBParams struct { + // The day of birth, between 1 and 31. + Day *int64 `form:"day"` + // The month of birth, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of birth. + Year *int64 `form:"year"` +} + +// An identifying document, either a passport or local ID card. +type IssuingCardholderUpdateIndividualVerificationDocumentParams struct { + // The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + Back *string `form:"back"` + // The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + Front *string `form:"front"` +} + +// Government-issued ID document for this cardholder. +type IssuingCardholderUpdateIndividualVerificationParams struct { + // An identifying document, either a passport or local ID card. + Document *IssuingCardholderUpdateIndividualVerificationDocumentParams `form:"document"` +} + +// Additional information about an `individual` cardholder. +type IssuingCardholderUpdateIndividualParams struct { + // Information related to the card_issuing program for this cardholder. + CardIssuing *IssuingCardholderUpdateIndividualCardIssuingParams `form:"card_issuing"` + // The date of birth of this cardholder. Cardholders must be older than 13 years old. + DOB *IssuingCardholderUpdateIndividualDOBParams `form:"dob"` + // The first name of this cardholder. Required before activating Cards. This field cannot contain any numbers, special characters (except periods, commas, hyphens, spaces and apostrophes) or non-latin letters. + FirstName *string `form:"first_name"` + // The last name of this cardholder. Required before activating Cards. This field cannot contain any numbers, special characters (except periods, commas, hyphens, spaces and apostrophes) or non-latin letters. + LastName *string `form:"last_name"` + // Government-issued ID document for this cardholder. + Verification *IssuingCardholderUpdateIndividualVerificationParams `form:"verification"` +} + +// Limit spending with amount-based rules that apply across this cardholder's cards. +type IssuingCardholderUpdateSpendingControlsSpendingLimitParams struct { + // Maximum amount allowed to spend per interval. + Amount *int64 `form:"amount"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories. + Categories []*string `form:"categories"` + // Interval (or event) to which the amount applies. + Interval *string `form:"interval"` +} + +// Rules that control spending across this cardholder's cards. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. +type IssuingCardholderUpdateSpendingControlsParams struct { + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`. + AllowedCategories []*string `form:"allowed_categories"` + // Array of strings containing representing countries from which authorizations will be allowed. Authorizations from merchants in all other countries will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `blocked_merchant_countries`. Provide an empty value to unset this control. + AllowedMerchantCountries []*string `form:"allowed_merchant_countries"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`. + BlockedCategories []*string `form:"blocked_categories"` + // Array of strings containing representing countries from which authorizations will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `allowed_merchant_countries`. Provide an empty value to unset this control. + BlockedMerchantCountries []*string `form:"blocked_merchant_countries"` + // Limit spending with amount-based rules that apply across this cardholder's cards. + SpendingLimits []*IssuingCardholderUpdateSpendingControlsSpendingLimitParams `form:"spending_limits"` + // Currency of amounts within `spending_limits`. Defaults to your merchant country's currency. + SpendingLimitsCurrency *string `form:"spending_limits_currency"` +} + +// Updates the specified Issuing Cardholder object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +type IssuingCardholderUpdateParams struct { + Params `form:"*"` + // The cardholder's billing address. + Billing *IssuingCardholderUpdateBillingParams `form:"billing"` + // Additional information about a `company` cardholder. + Company *IssuingCardholderUpdateCompanyParams `form:"company"` + // The cardholder's email address. + Email *string `form:"email"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Additional information about an `individual` cardholder. + Individual *IssuingCardholderUpdateIndividualParams `form:"individual"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The cardholder's phone number. This is required for all cardholders who will be creating EU cards. See the [3D Secure documentation](https://stripe.com/docs/issuing/3d-secure) for more details. + PhoneNumber *string `form:"phone_number"` + // The cardholder's preferred locales (languages), ordered by preference. Locales can be `de`, `en`, `es`, `fr`, or `it`. + // This changes the language of the [3D Secure flow](https://stripe.com/docs/issuing/3d-secure) and one-time password messages sent to the cardholder. + PreferredLocales []*string `form:"preferred_locales"` + // Rules that control spending across this cardholder's cards. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. + SpendingControls *IssuingCardholderUpdateSpendingControlsParams `form:"spending_controls"` + // Specifies whether to permit authorizations on this cardholder's cards. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingCardholderUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingCardholderUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +type IssuingCardholderBilling struct { + Address *Address `json:"address"` +} + +// Additional information about a `company` cardholder. +type IssuingCardholderCompany struct { + // Whether the company's business ID number was provided. + TaxIDProvided bool `json:"tax_id_provided"` +} + +// Information about cardholder acceptance of Celtic [Authorized User Terms](https://stripe.com/docs/issuing/cards#accept-authorized-user-terms). Required for cards backed by a Celtic program. +type IssuingCardholderIndividualCardIssuingUserTermsAcceptance struct { + // The Unix timestamp marking when the cardholder accepted the Authorized User Terms. + Date int64 `json:"date"` + // The IP address from which the cardholder accepted the Authorized User Terms. + IP string `json:"ip"` + // The user agent of the browser from which the cardholder accepted the Authorized User Terms. + UserAgent string `json:"user_agent"` +} + +// Information related to the card_issuing program for this cardholder. +type IssuingCardholderIndividualCardIssuing struct { + // Information about cardholder acceptance of Celtic [Authorized User Terms](https://stripe.com/docs/issuing/cards#accept-authorized-user-terms). Required for cards backed by a Celtic program. + UserTermsAcceptance *IssuingCardholderIndividualCardIssuingUserTermsAcceptance `json:"user_terms_acceptance"` +} + +// The date of birth of this cardholder. +type IssuingCardholderIndividualDOB struct { + // The day of birth, between 1 and 31. + Day int64 `json:"day"` + // The month of birth, between 1 and 12. + Month int64 `json:"month"` + // The four-digit year of birth. + Year int64 `json:"year"` +} + +// An identifying document, either a passport or local ID card. +type IssuingCardholderIndividualVerificationDocument struct { + // The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + Back *File `json:"back"` + // The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + Front *File `json:"front"` +} + +// Government-issued ID document for this cardholder. +type IssuingCardholderIndividualVerification struct { + // An identifying document, either a passport or local ID card. + Document *IssuingCardholderIndividualVerificationDocument `json:"document"` +} + +// Additional information about an `individual` cardholder. +type IssuingCardholderIndividual struct { + // Information related to the card_issuing program for this cardholder. + CardIssuing *IssuingCardholderIndividualCardIssuing `json:"card_issuing"` + // The date of birth of this cardholder. + DOB *IssuingCardholderIndividualDOB `json:"dob"` + // The first name of this cardholder. Required before activating Cards. This field cannot contain any numbers, special characters (except periods, commas, hyphens, spaces and apostrophes) or non-latin letters. + FirstName string `json:"first_name"` + // The last name of this cardholder. Required before activating Cards. This field cannot contain any numbers, special characters (except periods, commas, hyphens, spaces and apostrophes) or non-latin letters. + LastName string `json:"last_name"` + // Government-issued ID document for this cardholder. + Verification *IssuingCardholderIndividualVerification `json:"verification"` +} +type IssuingCardholderRequirements struct { + // If `disabled_reason` is present, all cards will decline authorizations with `cardholder_verification_required` reason. + DisabledReason IssuingCardholderRequirementsDisabledReason `json:"disabled_reason"` + // Array of fields that need to be collected in order to verify and re-enable the cardholder. + PastDue []string `json:"past_due"` +} + +// Limit spending with amount-based rules that apply across this cardholder's cards. +type IssuingCardholderSpendingControlsSpendingLimit struct { + // Maximum amount allowed to spend per interval. This amount is in the card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Amount int64 `json:"amount"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories. + Categories []string `json:"categories"` + // Interval (or event) to which the amount applies. + Interval IssuingCardholderSpendingControlsSpendingLimitInterval `json:"interval"` +} + +// Rules that control spending across this cardholder's cards. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. +type IssuingCardholderSpendingControls struct { + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`. + AllowedCategories []string `json:"allowed_categories"` + // Array of strings containing representing countries from which authorizations will be allowed. Authorizations from merchants in all other countries will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `blocked_merchant_countries`. Provide an empty value to unset this control. + AllowedMerchantCountries []string `json:"allowed_merchant_countries"` + // Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`. + BlockedCategories []string `json:"blocked_categories"` + // Array of strings containing representing countries from which authorizations will be declined. Country codes should be ISO 3166 alpha-2 country codes (e.g. `US`). Cannot be set with `allowed_merchant_countries`. Provide an empty value to unset this control. + BlockedMerchantCountries []string `json:"blocked_merchant_countries"` + // Limit spending with amount-based rules that apply across this cardholder's cards. + SpendingLimits []*IssuingCardholderSpendingControlsSpendingLimit `json:"spending_limits"` + // Currency of the amounts within `spending_limits`. + SpendingLimitsCurrency Currency `json:"spending_limits_currency"` +} + +// An Issuing `Cardholder` object represents an individual or business entity who is [issued](https://stripe.com/docs/issuing) cards. +// +// Related guide: [How to create a cardholder](https://stripe.com/docs/issuing/cards/virtual/issue-cards#create-cardholder) +type IssuingCardholder struct { + APIResource + Billing *IssuingCardholderBilling `json:"billing"` + // Additional information about a `company` cardholder. + Company *IssuingCardholderCompany `json:"company"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The cardholder's email address. + Email string `json:"email"` + // Unique identifier for the object. + ID string `json:"id"` + // Additional information about an `individual` cardholder. + Individual *IssuingCardholderIndividual `json:"individual"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // The cardholder's name. This will be printed on cards issued to them. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The cardholder's phone number. This is required for all cardholders who will be creating EU cards. See the [3D Secure documentation](https://stripe.com/docs/issuing/3d-secure#when-is-3d-secure-applied) for more details. + PhoneNumber string `json:"phone_number"` + // The cardholder's preferred locales (languages), ordered by preference. Locales can be `de`, `en`, `es`, `fr`, or `it`. + // This changes the language of the [3D Secure flow](https://stripe.com/docs/issuing/3d-secure) and one-time password messages sent to the cardholder. + PreferredLocales []IssuingCardholderPreferredLocale `json:"preferred_locales"` + Requirements *IssuingCardholderRequirements `json:"requirements"` + // Rules that control spending across this cardholder's cards. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. + SpendingControls *IssuingCardholderSpendingControls `json:"spending_controls"` + // Specifies whether to permit authorizations on this cardholder's cards. + Status IssuingCardholderStatus `json:"status"` + // One of `individual` or `company`. See [Choose a cardholder type](https://stripe.com/docs/issuing/other/choose-cardholder) for more details. + Type IssuingCardholderType `json:"type"` +} + +// IssuingCardholderList is a list of Cardholders as retrieved from a list endpoint. +type IssuingCardholderList struct { + APIResource + ListMeta + Data []*IssuingCardholder `json:"data"` +} + +// UnmarshalJSON handles deserialization of an IssuingCardholder. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (i *IssuingCardholder) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + i.ID = id + return nil + } + + type issuingCardholder IssuingCardholder + var v issuingCardholder + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *i = IssuingCardholder(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_cardholder_service.go b/vendor/github.com/stripe/stripe-go/v82/issuing_cardholder_service.go new file mode 100644 index 00000000..e1f311b5 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_cardholder_service.go @@ -0,0 +1,73 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1IssuingCardholderService is used to invoke /v1/issuing/cardholders APIs. +type v1IssuingCardholderService struct { + B Backend + Key string +} + +// Creates a new Issuing Cardholder object that can be issued cards. +func (c v1IssuingCardholderService) Create(ctx context.Context, params *IssuingCardholderCreateParams) (*IssuingCardholder, error) { + if params == nil { + params = &IssuingCardholderCreateParams{} + } + params.Context = ctx + cardholder := &IssuingCardholder{} + err := c.B.Call( + http.MethodPost, "/v1/issuing/cardholders", c.Key, params, cardholder) + return cardholder, err +} + +// Retrieves an Issuing Cardholder object. +func (c v1IssuingCardholderService) Retrieve(ctx context.Context, id string, params *IssuingCardholderRetrieveParams) (*IssuingCardholder, error) { + if params == nil { + params = &IssuingCardholderRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/cardholders/%s", id) + cardholder := &IssuingCardholder{} + err := c.B.Call(http.MethodGet, path, c.Key, params, cardholder) + return cardholder, err +} + +// Updates the specified Issuing Cardholder object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +func (c v1IssuingCardholderService) Update(ctx context.Context, id string, params *IssuingCardholderUpdateParams) (*IssuingCardholder, error) { + if params == nil { + params = &IssuingCardholderUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/cardholders/%s", id) + cardholder := &IssuingCardholder{} + err := c.B.Call(http.MethodPost, path, c.Key, params, cardholder) + return cardholder, err +} + +// Returns a list of Issuing Cardholder objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +func (c v1IssuingCardholderService) List(ctx context.Context, listParams *IssuingCardholderListParams) Seq2[*IssuingCardholder, error] { + if listParams == nil { + listParams = &IssuingCardholderListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*IssuingCardholder, ListContainer, error) { + list := &IssuingCardholderList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/issuing/cardholders", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_dispute.go b/vendor/github.com/stripe/stripe-go/v82/issuing_dispute.go new file mode 100644 index 00000000..3a21760b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_dispute.go @@ -0,0 +1,841 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Whether the product was a merchandise or service. +type IssuingDisputeEvidenceCanceledProductType string + +// List of values that IssuingDisputeEvidenceCanceledProductType can take +const ( + IssuingDisputeEvidenceCanceledProductTypeMerchandise IssuingDisputeEvidenceCanceledProductType = "merchandise" + IssuingDisputeEvidenceCanceledProductTypeService IssuingDisputeEvidenceCanceledProductType = "service" +) + +// Result of cardholder's attempt to return the product. +type IssuingDisputeEvidenceCanceledReturnStatus string + +// List of values that IssuingDisputeEvidenceCanceledReturnStatus can take +const ( + IssuingDisputeEvidenceCanceledReturnStatusMerchantRejected IssuingDisputeEvidenceCanceledReturnStatus = "merchant_rejected" + IssuingDisputeEvidenceCanceledReturnStatusSuccessful IssuingDisputeEvidenceCanceledReturnStatus = "successful" +) + +// Result of cardholder's attempt to return the product. +type IssuingDisputeEvidenceMerchandiseNotAsDescribedReturnStatus string + +// List of values that IssuingDisputeEvidenceMerchandiseNotAsDescribedReturnStatus can take +const ( + IssuingDisputeEvidenceMerchandiseNotAsDescribedReturnStatusMerchantRejected IssuingDisputeEvidenceMerchandiseNotAsDescribedReturnStatus = "merchant_rejected" + IssuingDisputeEvidenceMerchandiseNotAsDescribedReturnStatusSuccessful IssuingDisputeEvidenceMerchandiseNotAsDescribedReturnStatus = "successful" +) + +// Whether the product was a merchandise or service. +type IssuingDisputeEvidenceNotReceivedProductType string + +// List of values that IssuingDisputeEvidenceNotReceivedProductType can take +const ( + IssuingDisputeEvidenceNotReceivedProductTypeMerchandise IssuingDisputeEvidenceNotReceivedProductType = "merchandise" + IssuingDisputeEvidenceNotReceivedProductTypeService IssuingDisputeEvidenceNotReceivedProductType = "service" +) + +// Whether the product was a merchandise or service. +type IssuingDisputeEvidenceOtherProductType string + +// List of values that IssuingDisputeEvidenceOtherProductType can take +const ( + IssuingDisputeEvidenceOtherProductTypeMerchandise IssuingDisputeEvidenceOtherProductType = "merchandise" + IssuingDisputeEvidenceOtherProductTypeService IssuingDisputeEvidenceOtherProductType = "service" +) + +// The reason for filing the dispute. Its value will match the field containing the evidence. +type IssuingDisputeEvidenceReason string + +// List of values that IssuingDisputeEvidenceReason can take +const ( + IssuingDisputeEvidenceReasonCanceled IssuingDisputeEvidenceReason = "canceled" + IssuingDisputeEvidenceReasonDuplicate IssuingDisputeEvidenceReason = "duplicate" + IssuingDisputeEvidenceReasonFraudulent IssuingDisputeEvidenceReason = "fraudulent" + IssuingDisputeEvidenceReasonMerchandiseNotAsDescribed IssuingDisputeEvidenceReason = "merchandise_not_as_described" + IssuingDisputeEvidenceReasonNoValidAuthorization IssuingDisputeEvidenceReason = "no_valid_authorization" + IssuingDisputeEvidenceReasonNotReceived IssuingDisputeEvidenceReason = "not_received" + IssuingDisputeEvidenceReasonOther IssuingDisputeEvidenceReason = "other" + IssuingDisputeEvidenceReasonServiceNotAsDescribed IssuingDisputeEvidenceReason = "service_not_as_described" +) + +// The enum that describes the dispute loss outcome. If the dispute is not lost, this field will be absent. New enum values may be added in the future, so be sure to handle unknown values. +type IssuingDisputeLossReason string + +// List of values that IssuingDisputeLossReason can take +const ( + IssuingDisputeLossReasonCardholderAuthenticationIssuerLiability IssuingDisputeLossReason = "cardholder_authentication_issuer_liability" + IssuingDisputeLossReasonEci5TokenTransactionWithTavv IssuingDisputeLossReason = "eci5_token_transaction_with_tavv" + IssuingDisputeLossReasonExcessDisputesInTimeframe IssuingDisputeLossReason = "excess_disputes_in_timeframe" + IssuingDisputeLossReasonHasNotMetTheMinimumDisputeAmountRequirements IssuingDisputeLossReason = "has_not_met_the_minimum_dispute_amount_requirements" + IssuingDisputeLossReasonInvalidDuplicateDispute IssuingDisputeLossReason = "invalid_duplicate_dispute" + IssuingDisputeLossReasonInvalidIncorrectAmountDispute IssuingDisputeLossReason = "invalid_incorrect_amount_dispute" + IssuingDisputeLossReasonInvalidNoAuthorization IssuingDisputeLossReason = "invalid_no_authorization" + IssuingDisputeLossReasonInvalidUseOfDisputes IssuingDisputeLossReason = "invalid_use_of_disputes" + IssuingDisputeLossReasonMerchandiseDeliveredOrShipped IssuingDisputeLossReason = "merchandise_delivered_or_shipped" + IssuingDisputeLossReasonMerchandiseOrServiceAsDescribed IssuingDisputeLossReason = "merchandise_or_service_as_described" + IssuingDisputeLossReasonNotCancelled IssuingDisputeLossReason = "not_cancelled" + IssuingDisputeLossReasonOther IssuingDisputeLossReason = "other" + IssuingDisputeLossReasonRefundIssued IssuingDisputeLossReason = "refund_issued" + IssuingDisputeLossReasonSubmittedBeyondAllowableTimeLimit IssuingDisputeLossReason = "submitted_beyond_allowable_time_limit" + IssuingDisputeLossReasonTransaction3dsRequired IssuingDisputeLossReason = "transaction_3ds_required" + IssuingDisputeLossReasonTransactionApprovedAfterPriorFraudDispute IssuingDisputeLossReason = "transaction_approved_after_prior_fraud_dispute" + IssuingDisputeLossReasonTransactionAuthorized IssuingDisputeLossReason = "transaction_authorized" + IssuingDisputeLossReasonTransactionElectronicallyRead IssuingDisputeLossReason = "transaction_electronically_read" + IssuingDisputeLossReasonTransactionQualifiesForVisaEasyPaymentService IssuingDisputeLossReason = "transaction_qualifies_for_visa_easy_payment_service" + IssuingDisputeLossReasonTransactionUnattended IssuingDisputeLossReason = "transaction_unattended" +) + +// Current status of the dispute. +type IssuingDisputeStatus string + +// List of values that IssuingDisputeStatus can take +const ( + IssuingDisputeStatusExpired IssuingDisputeStatus = "expired" + IssuingDisputeStatusLost IssuingDisputeStatus = "lost" + IssuingDisputeStatusSubmitted IssuingDisputeStatus = "submitted" + IssuingDisputeStatusUnsubmitted IssuingDisputeStatus = "unsubmitted" + IssuingDisputeStatusWon IssuingDisputeStatus = "won" +) + +// Returns a list of Issuing Dispute objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +type IssuingDisputeListParams struct { + ListParams `form:"*"` + // Only return Issuing disputes that were created during the given date interval. + Created *int64 `form:"created"` + // Only return Issuing disputes that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Select Issuing disputes with the given status. + Status *string `form:"status"` + // Select the Issuing dispute for the given transaction. + Transaction *string `form:"transaction"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingDisputeListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Evidence provided when `reason` is 'canceled'. +type IssuingDisputeEvidenceCanceledParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Date when order was canceled. + CanceledAt *int64 `form:"canceled_at"` + // Whether the cardholder was provided with a cancellation policy. + CancellationPolicyProvided *bool `form:"cancellation_policy_provided"` + // Reason for canceling the order. + CancellationReason *string `form:"cancellation_reason"` + // Date when the cardholder expected to receive the product. + ExpectedAt *int64 `form:"expected_at"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Description of the merchandise or service that was purchased. + ProductDescription *string `form:"product_description"` + // Whether the product was a merchandise or service. + ProductType *string `form:"product_type"` + // Date when the product was returned or attempted to be returned. + ReturnedAt *int64 `form:"returned_at"` + // Result of cardholder's attempt to return the product. + ReturnStatus *string `form:"return_status"` +} + +// Evidence provided when `reason` is 'duplicate'. +type IssuingDisputeEvidenceDuplicateParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Copy of the card statement showing that the product had already been paid for. + CardStatement *string `form:"card_statement"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Copy of the receipt showing that the product had been paid for in cash. + CashReceipt *string `form:"cash_receipt"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Image of the front and back of the check that was used to pay for the product. + CheckImage *string `form:"check_image"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Transaction (e.g., ipi_...) that the disputed transaction is a duplicate of. Of the two or more transactions that are copies of each other, this is original undisputed one. + OriginalTransaction *string `form:"original_transaction"` +} + +// Evidence provided when `reason` is 'fraudulent'. +type IssuingDisputeEvidenceFraudulentParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` +} + +// Evidence provided when `reason` is 'merchandise_not_as_described'. +type IssuingDisputeEvidenceMerchandiseNotAsDescribedParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Date when the product was received. + ReceivedAt *int64 `form:"received_at"` + // Description of the cardholder's attempt to return the product. + ReturnDescription *string `form:"return_description"` + // Date when the product was returned or attempted to be returned. + ReturnedAt *int64 `form:"returned_at"` + // Result of cardholder's attempt to return the product. + ReturnStatus *string `form:"return_status"` +} + +// Evidence provided when `reason` is 'no_valid_authorization'. +type IssuingDisputeEvidenceNoValidAuthorizationParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` +} + +// Evidence provided when `reason` is 'not_received'. +type IssuingDisputeEvidenceNotReceivedParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Date when the cardholder expected to receive the product. + ExpectedAt *int64 `form:"expected_at"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Description of the merchandise or service that was purchased. + ProductDescription *string `form:"product_description"` + // Whether the product was a merchandise or service. + ProductType *string `form:"product_type"` +} + +// Evidence provided when `reason` is 'other'. +type IssuingDisputeEvidenceOtherParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Description of the merchandise or service that was purchased. + ProductDescription *string `form:"product_description"` + // Whether the product was a merchandise or service. + ProductType *string `form:"product_type"` +} + +// Evidence provided when `reason` is 'service_not_as_described'. +type IssuingDisputeEvidenceServiceNotAsDescribedParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Date when order was canceled. + CanceledAt *int64 `form:"canceled_at"` + // Reason for canceling the order. + CancellationReason *string `form:"cancellation_reason"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Date when the product was received. + ReceivedAt *int64 `form:"received_at"` +} + +// Evidence provided for the dispute. +type IssuingDisputeEvidenceParams struct { + // Evidence provided when `reason` is 'canceled'. + Canceled *IssuingDisputeEvidenceCanceledParams `form:"canceled"` + // Evidence provided when `reason` is 'duplicate'. + Duplicate *IssuingDisputeEvidenceDuplicateParams `form:"duplicate"` + // Evidence provided when `reason` is 'fraudulent'. + Fraudulent *IssuingDisputeEvidenceFraudulentParams `form:"fraudulent"` + // Evidence provided when `reason` is 'merchandise_not_as_described'. + MerchandiseNotAsDescribed *IssuingDisputeEvidenceMerchandiseNotAsDescribedParams `form:"merchandise_not_as_described"` + // Evidence provided when `reason` is 'not_received'. + NotReceived *IssuingDisputeEvidenceNotReceivedParams `form:"not_received"` + // Evidence provided when `reason` is 'no_valid_authorization'. + NoValidAuthorization *IssuingDisputeEvidenceNoValidAuthorizationParams `form:"no_valid_authorization"` + // Evidence provided when `reason` is 'other'. + Other *IssuingDisputeEvidenceOtherParams `form:"other"` + // The reason for filing the dispute. The evidence should be submitted in the field of the same name. + Reason *string `form:"reason"` + // Evidence provided when `reason` is 'service_not_as_described'. + ServiceNotAsDescribed *IssuingDisputeEvidenceServiceNotAsDescribedParams `form:"service_not_as_described"` +} + +// Params for disputes related to Treasury FinancialAccounts +type IssuingDisputeTreasuryParams struct { + // The ID of the ReceivedDebit to initiate an Issuings dispute for. + ReceivedDebit *string `form:"received_debit"` +} + +// Creates an Issuing Dispute object. Individual pieces of evidence within the evidence object are optional at this point. Stripe only validates that required evidence is present during submission. Refer to [Dispute reasons and evidence](https://docs.stripe.com/docs/issuing/purchases/disputes#dispute-reasons-and-evidence) for more details about evidence requirements. +type IssuingDisputeParams struct { + Params `form:"*"` + // The dispute amount in the card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). If not set, defaults to the full transaction amount. + Amount *int64 `form:"amount"` + // Evidence provided for the dispute. + Evidence *IssuingDisputeEvidenceParams `form:"evidence"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The ID of the issuing transaction to create a dispute for. For transaction on Treasury FinancialAccounts, use `treasury.received_debit`. + Transaction *string `form:"transaction"` + // Params for disputes related to Treasury FinancialAccounts + Treasury *IssuingDisputeTreasuryParams `form:"treasury"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingDisputeParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingDisputeParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Submits an Issuing Dispute to the card network. Stripe validates that all evidence fields required for the dispute's reason are present. For more details, see [Dispute reasons and evidence](https://docs.stripe.com/docs/issuing/purchases/disputes#dispute-reasons-and-evidence). +type IssuingDisputeSubmitParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingDisputeSubmitParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingDisputeSubmitParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Evidence provided when `reason` is 'canceled'. +type IssuingDisputeCreateEvidenceCanceledParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Date when order was canceled. + CanceledAt *int64 `form:"canceled_at"` + // Whether the cardholder was provided with a cancellation policy. + CancellationPolicyProvided *bool `form:"cancellation_policy_provided"` + // Reason for canceling the order. + CancellationReason *string `form:"cancellation_reason"` + // Date when the cardholder expected to receive the product. + ExpectedAt *int64 `form:"expected_at"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Description of the merchandise or service that was purchased. + ProductDescription *string `form:"product_description"` + // Whether the product was a merchandise or service. + ProductType *string `form:"product_type"` + // Date when the product was returned or attempted to be returned. + ReturnedAt *int64 `form:"returned_at"` + // Result of cardholder's attempt to return the product. + ReturnStatus *string `form:"return_status"` +} + +// Evidence provided when `reason` is 'duplicate'. +type IssuingDisputeCreateEvidenceDuplicateParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Copy of the card statement showing that the product had already been paid for. + CardStatement *string `form:"card_statement"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Copy of the receipt showing that the product had been paid for in cash. + CashReceipt *string `form:"cash_receipt"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Image of the front and back of the check that was used to pay for the product. + CheckImage *string `form:"check_image"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Transaction (e.g., ipi_...) that the disputed transaction is a duplicate of. Of the two or more transactions that are copies of each other, this is original undisputed one. + OriginalTransaction *string `form:"original_transaction"` +} + +// Evidence provided when `reason` is 'fraudulent'. +type IssuingDisputeCreateEvidenceFraudulentParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` +} + +// Evidence provided when `reason` is 'merchandise_not_as_described'. +type IssuingDisputeCreateEvidenceMerchandiseNotAsDescribedParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Date when the product was received. + ReceivedAt *int64 `form:"received_at"` + // Description of the cardholder's attempt to return the product. + ReturnDescription *string `form:"return_description"` + // Date when the product was returned or attempted to be returned. + ReturnedAt *int64 `form:"returned_at"` + // Result of cardholder's attempt to return the product. + ReturnStatus *string `form:"return_status"` +} + +// Evidence provided when `reason` is 'no_valid_authorization'. +type IssuingDisputeCreateEvidenceNoValidAuthorizationParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` +} + +// Evidence provided when `reason` is 'not_received'. +type IssuingDisputeCreateEvidenceNotReceivedParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Date when the cardholder expected to receive the product. + ExpectedAt *int64 `form:"expected_at"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Description of the merchandise or service that was purchased. + ProductDescription *string `form:"product_description"` + // Whether the product was a merchandise or service. + ProductType *string `form:"product_type"` +} + +// Evidence provided when `reason` is 'other'. +type IssuingDisputeCreateEvidenceOtherParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Description of the merchandise or service that was purchased. + ProductDescription *string `form:"product_description"` + // Whether the product was a merchandise or service. + ProductType *string `form:"product_type"` +} + +// Evidence provided when `reason` is 'service_not_as_described'. +type IssuingDisputeCreateEvidenceServiceNotAsDescribedParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Date when order was canceled. + CanceledAt *int64 `form:"canceled_at"` + // Reason for canceling the order. + CancellationReason *string `form:"cancellation_reason"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Date when the product was received. + ReceivedAt *int64 `form:"received_at"` +} + +// Evidence provided for the dispute. +type IssuingDisputeCreateEvidenceParams struct { + // Evidence provided when `reason` is 'canceled'. + Canceled *IssuingDisputeCreateEvidenceCanceledParams `form:"canceled"` + // Evidence provided when `reason` is 'duplicate'. + Duplicate *IssuingDisputeCreateEvidenceDuplicateParams `form:"duplicate"` + // Evidence provided when `reason` is 'fraudulent'. + Fraudulent *IssuingDisputeCreateEvidenceFraudulentParams `form:"fraudulent"` + // Evidence provided when `reason` is 'merchandise_not_as_described'. + MerchandiseNotAsDescribed *IssuingDisputeCreateEvidenceMerchandiseNotAsDescribedParams `form:"merchandise_not_as_described"` + // Evidence provided when `reason` is 'not_received'. + NotReceived *IssuingDisputeCreateEvidenceNotReceivedParams `form:"not_received"` + // Evidence provided when `reason` is 'no_valid_authorization'. + NoValidAuthorization *IssuingDisputeCreateEvidenceNoValidAuthorizationParams `form:"no_valid_authorization"` + // Evidence provided when `reason` is 'other'. + Other *IssuingDisputeCreateEvidenceOtherParams `form:"other"` + // The reason for filing the dispute. The evidence should be submitted in the field of the same name. + Reason *string `form:"reason"` + // Evidence provided when `reason` is 'service_not_as_described'. + ServiceNotAsDescribed *IssuingDisputeCreateEvidenceServiceNotAsDescribedParams `form:"service_not_as_described"` +} + +// Params for disputes related to Treasury FinancialAccounts +type IssuingDisputeCreateTreasuryParams struct { + // The ID of the ReceivedDebit to initiate an Issuings dispute for. + ReceivedDebit *string `form:"received_debit"` +} + +// Creates an Issuing Dispute object. Individual pieces of evidence within the evidence object are optional at this point. Stripe only validates that required evidence is present during submission. Refer to [Dispute reasons and evidence](https://docs.stripe.com/docs/issuing/purchases/disputes#dispute-reasons-and-evidence) for more details about evidence requirements. +type IssuingDisputeCreateParams struct { + Params `form:"*"` + // The dispute amount in the card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). If not set, defaults to the full transaction amount. + Amount *int64 `form:"amount"` + // Evidence provided for the dispute. + Evidence *IssuingDisputeCreateEvidenceParams `form:"evidence"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The ID of the issuing transaction to create a dispute for. For transaction on Treasury FinancialAccounts, use `treasury.received_debit`. + Transaction *string `form:"transaction"` + // Params for disputes related to Treasury FinancialAccounts + Treasury *IssuingDisputeCreateTreasuryParams `form:"treasury"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingDisputeCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingDisputeCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves an Issuing Dispute object. +type IssuingDisputeRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingDisputeRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Evidence provided when `reason` is 'canceled'. +type IssuingDisputeUpdateEvidenceCanceledParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Date when order was canceled. + CanceledAt *int64 `form:"canceled_at"` + // Whether the cardholder was provided with a cancellation policy. + CancellationPolicyProvided *bool `form:"cancellation_policy_provided"` + // Reason for canceling the order. + CancellationReason *string `form:"cancellation_reason"` + // Date when the cardholder expected to receive the product. + ExpectedAt *int64 `form:"expected_at"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Description of the merchandise or service that was purchased. + ProductDescription *string `form:"product_description"` + // Whether the product was a merchandise or service. + ProductType *string `form:"product_type"` + // Date when the product was returned or attempted to be returned. + ReturnedAt *int64 `form:"returned_at"` + // Result of cardholder's attempt to return the product. + ReturnStatus *string `form:"return_status"` +} + +// Evidence provided when `reason` is 'duplicate'. +type IssuingDisputeUpdateEvidenceDuplicateParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Copy of the card statement showing that the product had already been paid for. + CardStatement *string `form:"card_statement"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Copy of the receipt showing that the product had been paid for in cash. + CashReceipt *string `form:"cash_receipt"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Image of the front and back of the check that was used to pay for the product. + CheckImage *string `form:"check_image"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Transaction (e.g., ipi_...) that the disputed transaction is a duplicate of. Of the two or more transactions that are copies of each other, this is original undisputed one. + OriginalTransaction *string `form:"original_transaction"` +} + +// Evidence provided when `reason` is 'fraudulent'. +type IssuingDisputeUpdateEvidenceFraudulentParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` +} + +// Evidence provided when `reason` is 'merchandise_not_as_described'. +type IssuingDisputeUpdateEvidenceMerchandiseNotAsDescribedParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Date when the product was received. + ReceivedAt *int64 `form:"received_at"` + // Description of the cardholder's attempt to return the product. + ReturnDescription *string `form:"return_description"` + // Date when the product was returned or attempted to be returned. + ReturnedAt *int64 `form:"returned_at"` + // Result of cardholder's attempt to return the product. + ReturnStatus *string `form:"return_status"` +} + +// Evidence provided when `reason` is 'no_valid_authorization'. +type IssuingDisputeUpdateEvidenceNoValidAuthorizationParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` +} + +// Evidence provided when `reason` is 'not_received'. +type IssuingDisputeUpdateEvidenceNotReceivedParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Date when the cardholder expected to receive the product. + ExpectedAt *int64 `form:"expected_at"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Description of the merchandise or service that was purchased. + ProductDescription *string `form:"product_description"` + // Whether the product was a merchandise or service. + ProductType *string `form:"product_type"` +} + +// Evidence provided when `reason` is 'other'. +type IssuingDisputeUpdateEvidenceOtherParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Description of the merchandise or service that was purchased. + ProductDescription *string `form:"product_description"` + // Whether the product was a merchandise or service. + ProductType *string `form:"product_type"` +} + +// Evidence provided when `reason` is 'service_not_as_described'. +type IssuingDisputeUpdateEvidenceServiceNotAsDescribedParams struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *string `form:"additional_documentation"` + // Date when order was canceled. + CanceledAt *int64 `form:"canceled_at"` + // Reason for canceling the order. + CancellationReason *string `form:"cancellation_reason"` + // Explanation of why the cardholder is disputing this transaction. + Explanation *string `form:"explanation"` + // Date when the product was received. + ReceivedAt *int64 `form:"received_at"` +} + +// Evidence provided for the dispute. +type IssuingDisputeUpdateEvidenceParams struct { + // Evidence provided when `reason` is 'canceled'. + Canceled *IssuingDisputeUpdateEvidenceCanceledParams `form:"canceled"` + // Evidence provided when `reason` is 'duplicate'. + Duplicate *IssuingDisputeUpdateEvidenceDuplicateParams `form:"duplicate"` + // Evidence provided when `reason` is 'fraudulent'. + Fraudulent *IssuingDisputeUpdateEvidenceFraudulentParams `form:"fraudulent"` + // Evidence provided when `reason` is 'merchandise_not_as_described'. + MerchandiseNotAsDescribed *IssuingDisputeUpdateEvidenceMerchandiseNotAsDescribedParams `form:"merchandise_not_as_described"` + // Evidence provided when `reason` is 'not_received'. + NotReceived *IssuingDisputeUpdateEvidenceNotReceivedParams `form:"not_received"` + // Evidence provided when `reason` is 'no_valid_authorization'. + NoValidAuthorization *IssuingDisputeUpdateEvidenceNoValidAuthorizationParams `form:"no_valid_authorization"` + // Evidence provided when `reason` is 'other'. + Other *IssuingDisputeUpdateEvidenceOtherParams `form:"other"` + // The reason for filing the dispute. The evidence should be submitted in the field of the same name. + Reason *string `form:"reason"` + // Evidence provided when `reason` is 'service_not_as_described'. + ServiceNotAsDescribed *IssuingDisputeUpdateEvidenceServiceNotAsDescribedParams `form:"service_not_as_described"` +} + +// Updates the specified Issuing Dispute object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. Properties on the evidence object can be unset by passing in an empty string. +type IssuingDisputeUpdateParams struct { + Params `form:"*"` + // The dispute amount in the card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Amount *int64 `form:"amount"` + // Evidence provided for the dispute. + Evidence *IssuingDisputeUpdateEvidenceParams `form:"evidence"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingDisputeUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingDisputeUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +type IssuingDisputeEvidenceCanceled struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *File `json:"additional_documentation"` + // Date when order was canceled. + CanceledAt int64 `json:"canceled_at"` + // Whether the cardholder was provided with a cancellation policy. + CancellationPolicyProvided bool `json:"cancellation_policy_provided"` + // Reason for canceling the order. + CancellationReason string `json:"cancellation_reason"` + // Date when the cardholder expected to receive the product. + ExpectedAt int64 `json:"expected_at"` + // Explanation of why the cardholder is disputing this transaction. + Explanation string `json:"explanation"` + // Description of the merchandise or service that was purchased. + ProductDescription string `json:"product_description"` + // Whether the product was a merchandise or service. + ProductType IssuingDisputeEvidenceCanceledProductType `json:"product_type"` + // Date when the product was returned or attempted to be returned. + ReturnedAt int64 `json:"returned_at"` + // Result of cardholder's attempt to return the product. + ReturnStatus IssuingDisputeEvidenceCanceledReturnStatus `json:"return_status"` +} +type IssuingDisputeEvidenceDuplicate struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *File `json:"additional_documentation"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Copy of the card statement showing that the product had already been paid for. + CardStatement *File `json:"card_statement"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Copy of the receipt showing that the product had been paid for in cash. + CashReceipt *File `json:"cash_receipt"` + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Image of the front and back of the check that was used to pay for the product. + CheckImage *File `json:"check_image"` + // Explanation of why the cardholder is disputing this transaction. + Explanation string `json:"explanation"` + // Transaction (e.g., ipi_...) that the disputed transaction is a duplicate of. Of the two or more transactions that are copies of each other, this is original undisputed one. + OriginalTransaction string `json:"original_transaction"` +} +type IssuingDisputeEvidenceFraudulent struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *File `json:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation string `json:"explanation"` +} +type IssuingDisputeEvidenceMerchandiseNotAsDescribed struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *File `json:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation string `json:"explanation"` + // Date when the product was received. + ReceivedAt int64 `json:"received_at"` + // Description of the cardholder's attempt to return the product. + ReturnDescription string `json:"return_description"` + // Date when the product was returned or attempted to be returned. + ReturnedAt int64 `json:"returned_at"` + // Result of cardholder's attempt to return the product. + ReturnStatus IssuingDisputeEvidenceMerchandiseNotAsDescribedReturnStatus `json:"return_status"` +} +type IssuingDisputeEvidenceNoValidAuthorization struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *File `json:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation string `json:"explanation"` +} +type IssuingDisputeEvidenceNotReceived struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *File `json:"additional_documentation"` + // Date when the cardholder expected to receive the product. + ExpectedAt int64 `json:"expected_at"` + // Explanation of why the cardholder is disputing this transaction. + Explanation string `json:"explanation"` + // Description of the merchandise or service that was purchased. + ProductDescription string `json:"product_description"` + // Whether the product was a merchandise or service. + ProductType IssuingDisputeEvidenceNotReceivedProductType `json:"product_type"` +} +type IssuingDisputeEvidenceOther struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *File `json:"additional_documentation"` + // Explanation of why the cardholder is disputing this transaction. + Explanation string `json:"explanation"` + // Description of the merchandise or service that was purchased. + ProductDescription string `json:"product_description"` + // Whether the product was a merchandise or service. + ProductType IssuingDisputeEvidenceOtherProductType `json:"product_type"` +} +type IssuingDisputeEvidenceServiceNotAsDescribed struct { + // (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + AdditionalDocumentation *File `json:"additional_documentation"` + // Date when order was canceled. + CanceledAt int64 `json:"canceled_at"` + // Reason for canceling the order. + CancellationReason string `json:"cancellation_reason"` + // Explanation of why the cardholder is disputing this transaction. + Explanation string `json:"explanation"` + // Date when the product was received. + ReceivedAt int64 `json:"received_at"` +} +type IssuingDisputeEvidence struct { + Canceled *IssuingDisputeEvidenceCanceled `json:"canceled"` + Duplicate *IssuingDisputeEvidenceDuplicate `json:"duplicate"` + Fraudulent *IssuingDisputeEvidenceFraudulent `json:"fraudulent"` + MerchandiseNotAsDescribed *IssuingDisputeEvidenceMerchandiseNotAsDescribed `json:"merchandise_not_as_described"` + NotReceived *IssuingDisputeEvidenceNotReceived `json:"not_received"` + NoValidAuthorization *IssuingDisputeEvidenceNoValidAuthorization `json:"no_valid_authorization"` + Other *IssuingDisputeEvidenceOther `json:"other"` + // The reason for filing the dispute. Its value will match the field containing the evidence. + Reason IssuingDisputeEvidenceReason `json:"reason"` + ServiceNotAsDescribed *IssuingDisputeEvidenceServiceNotAsDescribed `json:"service_not_as_described"` +} + +// [Treasury](https://stripe.com/docs/api/treasury) details related to this dispute if it was created on a [FinancialAccount](/docs/api/treasury/financial_accounts +type IssuingDisputeTreasury struct { + // The Treasury [DebitReversal](https://stripe.com/docs/api/treasury/debit_reversals) representing this Issuing dispute + DebitReversal string `json:"debit_reversal"` + // The Treasury [ReceivedDebit](https://stripe.com/docs/api/treasury/received_debits) that is being disputed. + ReceivedDebit string `json:"received_debit"` +} + +// As a [card issuer](https://stripe.com/docs/issuing), you can dispute transactions that the cardholder does not recognize, suspects to be fraudulent, or has other issues with. +// +// Related guide: [Issuing disputes](https://stripe.com/docs/issuing/purchases/disputes) +type IssuingDispute struct { + APIResource + // Disputed amount in the card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). Usually the amount of the `transaction`, but can differ (usually because of currency fluctuation). + Amount int64 `json:"amount"` + // List of balance transactions associated with the dispute. + BalanceTransactions []*BalanceTransaction `json:"balance_transactions"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The currency the `transaction` was made in. + Currency Currency `json:"currency"` + Evidence *IssuingDisputeEvidence `json:"evidence"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // The enum that describes the dispute loss outcome. If the dispute is not lost, this field will be absent. New enum values may be added in the future, so be sure to handle unknown values. + LossReason IssuingDisputeLossReason `json:"loss_reason"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Current status of the dispute. + Status IssuingDisputeStatus `json:"status"` + // The transaction being disputed. + Transaction *IssuingTransaction `json:"transaction"` + // [Treasury](https://stripe.com/docs/api/treasury) details related to this dispute if it was created on a [FinancialAccount](/docs/api/treasury/financial_accounts + Treasury *IssuingDisputeTreasury `json:"treasury"` +} + +// IssuingDisputeList is a list of Disputes as retrieved from a list endpoint. +type IssuingDisputeList struct { + APIResource + ListMeta + Data []*IssuingDispute `json:"data"` +} + +// UnmarshalJSON handles deserialization of an IssuingDispute. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (i *IssuingDispute) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + i.ID = id + return nil + } + + type issuingDispute IssuingDispute + var v issuingDispute + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *i = IssuingDispute(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_dispute_service.go b/vendor/github.com/stripe/stripe-go/v82/issuing_dispute_service.go new file mode 100644 index 00000000..e7e49cc2 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_dispute_service.go @@ -0,0 +1,85 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1IssuingDisputeService is used to invoke /v1/issuing/disputes APIs. +type v1IssuingDisputeService struct { + B Backend + Key string +} + +// Creates an Issuing Dispute object. Individual pieces of evidence within the evidence object are optional at this point. Stripe only validates that required evidence is present during submission. Refer to [Dispute reasons and evidence](https://docs.stripe.com/docs/issuing/purchases/disputes#dispute-reasons-and-evidence) for more details about evidence requirements. +func (c v1IssuingDisputeService) Create(ctx context.Context, params *IssuingDisputeCreateParams) (*IssuingDispute, error) { + if params == nil { + params = &IssuingDisputeCreateParams{} + } + params.Context = ctx + dispute := &IssuingDispute{} + err := c.B.Call( + http.MethodPost, "/v1/issuing/disputes", c.Key, params, dispute) + return dispute, err +} + +// Retrieves an Issuing Dispute object. +func (c v1IssuingDisputeService) Retrieve(ctx context.Context, id string, params *IssuingDisputeRetrieveParams) (*IssuingDispute, error) { + if params == nil { + params = &IssuingDisputeRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/disputes/%s", id) + dispute := &IssuingDispute{} + err := c.B.Call(http.MethodGet, path, c.Key, params, dispute) + return dispute, err +} + +// Updates the specified Issuing Dispute object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. Properties on the evidence object can be unset by passing in an empty string. +func (c v1IssuingDisputeService) Update(ctx context.Context, id string, params *IssuingDisputeUpdateParams) (*IssuingDispute, error) { + if params == nil { + params = &IssuingDisputeUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/disputes/%s", id) + dispute := &IssuingDispute{} + err := c.B.Call(http.MethodPost, path, c.Key, params, dispute) + return dispute, err +} + +// Submits an Issuing Dispute to the card network. Stripe validates that all evidence fields required for the dispute's reason are present. For more details, see [Dispute reasons and evidence](https://docs.stripe.com/docs/issuing/purchases/disputes#dispute-reasons-and-evidence). +func (c v1IssuingDisputeService) Submit(ctx context.Context, id string, params *IssuingDisputeSubmitParams) (*IssuingDispute, error) { + if params == nil { + params = &IssuingDisputeSubmitParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/disputes/%s/submit", id) + dispute := &IssuingDispute{} + err := c.B.Call(http.MethodPost, path, c.Key, params, dispute) + return dispute, err +} + +// Returns a list of Issuing Dispute objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +func (c v1IssuingDisputeService) List(ctx context.Context, listParams *IssuingDisputeListParams) Seq2[*IssuingDispute, error] { + if listParams == nil { + listParams = &IssuingDisputeListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*IssuingDispute, ListContainer, error) { + list := &IssuingDisputeList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/issuing/disputes", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_personalizationdesign.go b/vendor/github.com/stripe/stripe-go/v82/issuing_personalizationdesign.go new file mode 100644 index 00000000..c01e5e29 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_personalizationdesign.go @@ -0,0 +1,331 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The reason(s) the card logo was rejected. +type IssuingPersonalizationDesignRejectionReasonsCardLogo string + +// List of values that IssuingPersonalizationDesignRejectionReasonsCardLogo can take +const ( + IssuingPersonalizationDesignRejectionReasonsCardLogoGeographicLocation IssuingPersonalizationDesignRejectionReasonsCardLogo = "geographic_location" + IssuingPersonalizationDesignRejectionReasonsCardLogoInappropriate IssuingPersonalizationDesignRejectionReasonsCardLogo = "inappropriate" + IssuingPersonalizationDesignRejectionReasonsCardLogoNetworkName IssuingPersonalizationDesignRejectionReasonsCardLogo = "network_name" + IssuingPersonalizationDesignRejectionReasonsCardLogoNonBinaryImage IssuingPersonalizationDesignRejectionReasonsCardLogo = "non_binary_image" + IssuingPersonalizationDesignRejectionReasonsCardLogoNonFiatCurrency IssuingPersonalizationDesignRejectionReasonsCardLogo = "non_fiat_currency" + IssuingPersonalizationDesignRejectionReasonsCardLogoOther IssuingPersonalizationDesignRejectionReasonsCardLogo = "other" + IssuingPersonalizationDesignRejectionReasonsCardLogoOtherEntity IssuingPersonalizationDesignRejectionReasonsCardLogo = "other_entity" + IssuingPersonalizationDesignRejectionReasonsCardLogoPromotionalMaterial IssuingPersonalizationDesignRejectionReasonsCardLogo = "promotional_material" +) + +// The reason(s) the carrier text was rejected. +type IssuingPersonalizationDesignRejectionReasonsCarrierText string + +// List of values that IssuingPersonalizationDesignRejectionReasonsCarrierText can take +const ( + IssuingPersonalizationDesignRejectionReasonsCarrierTextGeographicLocation IssuingPersonalizationDesignRejectionReasonsCarrierText = "geographic_location" + IssuingPersonalizationDesignRejectionReasonsCarrierTextInappropriate IssuingPersonalizationDesignRejectionReasonsCarrierText = "inappropriate" + IssuingPersonalizationDesignRejectionReasonsCarrierTextNetworkName IssuingPersonalizationDesignRejectionReasonsCarrierText = "network_name" + IssuingPersonalizationDesignRejectionReasonsCarrierTextNonFiatCurrency IssuingPersonalizationDesignRejectionReasonsCarrierText = "non_fiat_currency" + IssuingPersonalizationDesignRejectionReasonsCarrierTextOther IssuingPersonalizationDesignRejectionReasonsCarrierText = "other" + IssuingPersonalizationDesignRejectionReasonsCarrierTextOtherEntity IssuingPersonalizationDesignRejectionReasonsCarrierText = "other_entity" + IssuingPersonalizationDesignRejectionReasonsCarrierTextPromotionalMaterial IssuingPersonalizationDesignRejectionReasonsCarrierText = "promotional_material" +) + +// Whether this personalization design can be used to create cards. +type IssuingPersonalizationDesignStatus string + +// List of values that IssuingPersonalizationDesignStatus can take +const ( + IssuingPersonalizationDesignStatusActive IssuingPersonalizationDesignStatus = "active" + IssuingPersonalizationDesignStatusInactive IssuingPersonalizationDesignStatus = "inactive" + IssuingPersonalizationDesignStatusRejected IssuingPersonalizationDesignStatus = "rejected" + IssuingPersonalizationDesignStatusReview IssuingPersonalizationDesignStatus = "review" +) + +// Only return personalization designs with the given preferences. +type IssuingPersonalizationDesignListPreferencesParams struct { + // Only return the personalization design that's set as the default. A connected account uses the Connect platform's default design if no personalization design is set as the default. + IsDefault *bool `form:"is_default"` + // Only return the personalization design that is set as the Connect platform's default. This parameter is only applicable to connected accounts. + IsPlatformDefault *bool `form:"is_platform_default"` +} + +// Returns a list of personalization design objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +type IssuingPersonalizationDesignListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return personalization designs with the given lookup keys. + LookupKeys []*string `form:"lookup_keys"` + // Only return personalization designs with the given preferences. + Preferences *IssuingPersonalizationDesignListPreferencesParams `form:"preferences"` + // Only return personalization designs with the given status. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingPersonalizationDesignListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Hash containing carrier text, for use with physical bundles that support carrier text. +type IssuingPersonalizationDesignCarrierTextParams struct { + // The footer body text of the carrier letter. + FooterBody *string `form:"footer_body"` + // The footer title text of the carrier letter. + FooterTitle *string `form:"footer_title"` + // The header body text of the carrier letter. + HeaderBody *string `form:"header_body"` + // The header title text of the carrier letter. + HeaderTitle *string `form:"header_title"` +} + +// Information on whether this personalization design is used to create cards when one is not specified. +type IssuingPersonalizationDesignPreferencesParams struct { + // Whether we use this personalization design to create cards when one isn't specified. A connected account uses the Connect platform's default design if no personalization design is set as the default design. + IsDefault *bool `form:"is_default"` +} + +// Creates a personalization design object. +type IssuingPersonalizationDesignParams struct { + Params `form:"*"` + // The file for the card logo, for use with physical bundles that support card logos. Must have a `purpose` value of `issuing_logo`. + CardLogo *string `form:"card_logo"` + // Hash containing carrier text, for use with physical bundles that support carrier text. + CarrierText *IssuingPersonalizationDesignCarrierTextParams `form:"carrier_text"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A lookup key used to retrieve personalization designs dynamically from a static string. This may be up to 200 characters. + LookupKey *string `form:"lookup_key"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Friendly display name. Providing an empty string will set the field to null. + Name *string `form:"name"` + // The physical bundle object belonging to this personalization design. + PhysicalBundle *string `form:"physical_bundle"` + // Information on whether this personalization design is used to create cards when one is not specified. + Preferences *IssuingPersonalizationDesignPreferencesParams `form:"preferences"` + // If set to true, will atomically remove the lookup key from the existing personalization design, and assign it to this personalization design. + TransferLookupKey *bool `form:"transfer_lookup_key"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingPersonalizationDesignParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingPersonalizationDesignParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Hash containing carrier text, for use with physical bundles that support carrier text. +type IssuingPersonalizationDesignCreateCarrierTextParams struct { + // The footer body text of the carrier letter. + FooterBody *string `form:"footer_body"` + // The footer title text of the carrier letter. + FooterTitle *string `form:"footer_title"` + // The header body text of the carrier letter. + HeaderBody *string `form:"header_body"` + // The header title text of the carrier letter. + HeaderTitle *string `form:"header_title"` +} + +// Information on whether this personalization design is used to create cards when one is not specified. +type IssuingPersonalizationDesignCreatePreferencesParams struct { + // Whether we use this personalization design to create cards when one isn't specified. A connected account uses the Connect platform's default design if no personalization design is set as the default design. + IsDefault *bool `form:"is_default"` +} + +// Creates a personalization design object. +type IssuingPersonalizationDesignCreateParams struct { + Params `form:"*"` + // The file for the card logo, for use with physical bundles that support card logos. Must have a `purpose` value of `issuing_logo`. + CardLogo *string `form:"card_logo"` + // Hash containing carrier text, for use with physical bundles that support carrier text. + CarrierText *IssuingPersonalizationDesignCreateCarrierTextParams `form:"carrier_text"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A lookup key used to retrieve personalization designs dynamically from a static string. This may be up to 200 characters. + LookupKey *string `form:"lookup_key"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Friendly display name. + Name *string `form:"name"` + // The physical bundle object belonging to this personalization design. + PhysicalBundle *string `form:"physical_bundle"` + // Information on whether this personalization design is used to create cards when one is not specified. + Preferences *IssuingPersonalizationDesignCreatePreferencesParams `form:"preferences"` + // If set to true, will atomically remove the lookup key from the existing personalization design, and assign it to this personalization design. + TransferLookupKey *bool `form:"transfer_lookup_key"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingPersonalizationDesignCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingPersonalizationDesignCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves a personalization design object. +type IssuingPersonalizationDesignRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingPersonalizationDesignRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Hash containing carrier text, for use with physical bundles that support carrier text. +type IssuingPersonalizationDesignUpdateCarrierTextParams struct { + // The footer body text of the carrier letter. + FooterBody *string `form:"footer_body"` + // The footer title text of the carrier letter. + FooterTitle *string `form:"footer_title"` + // The header body text of the carrier letter. + HeaderBody *string `form:"header_body"` + // The header title text of the carrier letter. + HeaderTitle *string `form:"header_title"` +} + +// Information on whether this personalization design is used to create cards when one is not specified. +type IssuingPersonalizationDesignUpdatePreferencesParams struct { + // Whether we use this personalization design to create cards when one isn't specified. A connected account uses the Connect platform's default design if no personalization design is set as the default design. + IsDefault *bool `form:"is_default"` +} + +// Updates a card personalization object. +type IssuingPersonalizationDesignUpdateParams struct { + Params `form:"*"` + // The file for the card logo, for use with physical bundles that support card logos. Must have a `purpose` value of `issuing_logo`. + CardLogo *string `form:"card_logo"` + // Hash containing carrier text, for use with physical bundles that support carrier text. + CarrierText *IssuingPersonalizationDesignUpdateCarrierTextParams `form:"carrier_text"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A lookup key used to retrieve personalization designs dynamically from a static string. This may be up to 200 characters. + LookupKey *string `form:"lookup_key"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Friendly display name. Providing an empty string will set the field to null. + Name *string `form:"name"` + // The physical bundle object belonging to this personalization design. + PhysicalBundle *string `form:"physical_bundle"` + // Information on whether this personalization design is used to create cards when one is not specified. + Preferences *IssuingPersonalizationDesignUpdatePreferencesParams `form:"preferences"` + // If set to true, will atomically remove the lookup key from the existing personalization design, and assign it to this personalization design. + TransferLookupKey *bool `form:"transfer_lookup_key"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingPersonalizationDesignUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingPersonalizationDesignUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Hash containing carrier text, for use with physical bundles that support carrier text. +type IssuingPersonalizationDesignCarrierText struct { + // The footer body text of the carrier letter. + FooterBody string `json:"footer_body"` + // The footer title text of the carrier letter. + FooterTitle string `json:"footer_title"` + // The header body text of the carrier letter. + HeaderBody string `json:"header_body"` + // The header title text of the carrier letter. + HeaderTitle string `json:"header_title"` +} +type IssuingPersonalizationDesignPreferences struct { + // Whether we use this personalization design to create cards when one isn't specified. A connected account uses the Connect platform's default design if no personalization design is set as the default design. + IsDefault bool `json:"is_default"` + // Whether this personalization design is used to create cards when one is not specified and a default for this connected account does not exist. + IsPlatformDefault bool `json:"is_platform_default"` +} +type IssuingPersonalizationDesignRejectionReasons struct { + // The reason(s) the card logo was rejected. + CardLogo []IssuingPersonalizationDesignRejectionReasonsCardLogo `json:"card_logo"` + // The reason(s) the carrier text was rejected. + CarrierText []IssuingPersonalizationDesignRejectionReasonsCarrierText `json:"carrier_text"` +} + +// A Personalization Design is a logical grouping of a Physical Bundle, card logo, and carrier text that represents a product line. +type IssuingPersonalizationDesign struct { + APIResource + // The file for the card logo to use with physical bundles that support card logos. Must have a `purpose` value of `issuing_logo`. + CardLogo *File `json:"card_logo"` + // Hash containing carrier text, for use with physical bundles that support carrier text. + CarrierText *IssuingPersonalizationDesignCarrierText `json:"carrier_text"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // A lookup key used to retrieve personalization designs dynamically from a static string. This may be up to 200 characters. + LookupKey string `json:"lookup_key"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // Friendly display name. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The physical bundle object belonging to this personalization design. + PhysicalBundle *IssuingPhysicalBundle `json:"physical_bundle"` + Preferences *IssuingPersonalizationDesignPreferences `json:"preferences"` + RejectionReasons *IssuingPersonalizationDesignRejectionReasons `json:"rejection_reasons"` + // Whether this personalization design can be used to create cards. + Status IssuingPersonalizationDesignStatus `json:"status"` +} + +// IssuingPersonalizationDesignList is a list of PersonalizationDesigns as retrieved from a list endpoint. +type IssuingPersonalizationDesignList struct { + APIResource + ListMeta + Data []*IssuingPersonalizationDesign `json:"data"` +} + +// UnmarshalJSON handles deserialization of an IssuingPersonalizationDesign. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (i *IssuingPersonalizationDesign) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + i.ID = id + return nil + } + + type issuingPersonalizationDesign IssuingPersonalizationDesign + var v issuingPersonalizationDesign + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *i = IssuingPersonalizationDesign(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_personalizationdesign_service.go b/vendor/github.com/stripe/stripe-go/v82/issuing_personalizationdesign_service.go new file mode 100644 index 00000000..764276b7 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_personalizationdesign_service.go @@ -0,0 +1,73 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1IssuingPersonalizationDesignService is used to invoke /v1/issuing/personalization_designs APIs. +type v1IssuingPersonalizationDesignService struct { + B Backend + Key string +} + +// Creates a personalization design object. +func (c v1IssuingPersonalizationDesignService) Create(ctx context.Context, params *IssuingPersonalizationDesignCreateParams) (*IssuingPersonalizationDesign, error) { + if params == nil { + params = &IssuingPersonalizationDesignCreateParams{} + } + params.Context = ctx + personalizationdesign := &IssuingPersonalizationDesign{} + err := c.B.Call( + http.MethodPost, "/v1/issuing/personalization_designs", c.Key, params, personalizationdesign) + return personalizationdesign, err +} + +// Retrieves a personalization design object. +func (c v1IssuingPersonalizationDesignService) Retrieve(ctx context.Context, id string, params *IssuingPersonalizationDesignRetrieveParams) (*IssuingPersonalizationDesign, error) { + if params == nil { + params = &IssuingPersonalizationDesignRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/personalization_designs/%s", id) + personalizationdesign := &IssuingPersonalizationDesign{} + err := c.B.Call(http.MethodGet, path, c.Key, params, personalizationdesign) + return personalizationdesign, err +} + +// Updates a card personalization object. +func (c v1IssuingPersonalizationDesignService) Update(ctx context.Context, id string, params *IssuingPersonalizationDesignUpdateParams) (*IssuingPersonalizationDesign, error) { + if params == nil { + params = &IssuingPersonalizationDesignUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/personalization_designs/%s", id) + personalizationdesign := &IssuingPersonalizationDesign{} + err := c.B.Call(http.MethodPost, path, c.Key, params, personalizationdesign) + return personalizationdesign, err +} + +// Returns a list of personalization design objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +func (c v1IssuingPersonalizationDesignService) List(ctx context.Context, listParams *IssuingPersonalizationDesignListParams) Seq2[*IssuingPersonalizationDesign, error] { + if listParams == nil { + listParams = &IssuingPersonalizationDesignListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*IssuingPersonalizationDesign, ListContainer, error) { + list := &IssuingPersonalizationDesignList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/issuing/personalization_designs", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_physicalbundle.go b/vendor/github.com/stripe/stripe-go/v82/issuing_physicalbundle.go new file mode 100644 index 00000000..bb077870 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_physicalbundle.go @@ -0,0 +1,151 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The policy for how to use card logo images in a card design with this physical bundle. +type IssuingPhysicalBundleFeaturesCardLogo string + +// List of values that IssuingPhysicalBundleFeaturesCardLogo can take +const ( + IssuingPhysicalBundleFeaturesCardLogoOptional IssuingPhysicalBundleFeaturesCardLogo = "optional" + IssuingPhysicalBundleFeaturesCardLogoRequired IssuingPhysicalBundleFeaturesCardLogo = "required" + IssuingPhysicalBundleFeaturesCardLogoUnsupported IssuingPhysicalBundleFeaturesCardLogo = "unsupported" +) + +// The policy for how to use carrier letter text in a card design with this physical bundle. +type IssuingPhysicalBundleFeaturesCarrierText string + +// List of values that IssuingPhysicalBundleFeaturesCarrierText can take +const ( + IssuingPhysicalBundleFeaturesCarrierTextOptional IssuingPhysicalBundleFeaturesCarrierText = "optional" + IssuingPhysicalBundleFeaturesCarrierTextRequired IssuingPhysicalBundleFeaturesCarrierText = "required" + IssuingPhysicalBundleFeaturesCarrierTextUnsupported IssuingPhysicalBundleFeaturesCarrierText = "unsupported" +) + +// The policy for how to use a second line on a card with this physical bundle. +type IssuingPhysicalBundleFeaturesSecondLine string + +// List of values that IssuingPhysicalBundleFeaturesSecondLine can take +const ( + IssuingPhysicalBundleFeaturesSecondLineOptional IssuingPhysicalBundleFeaturesSecondLine = "optional" + IssuingPhysicalBundleFeaturesSecondLineRequired IssuingPhysicalBundleFeaturesSecondLine = "required" + IssuingPhysicalBundleFeaturesSecondLineUnsupported IssuingPhysicalBundleFeaturesSecondLine = "unsupported" +) + +// Whether this physical bundle can be used to create cards. +type IssuingPhysicalBundleStatus string + +// List of values that IssuingPhysicalBundleStatus can take +const ( + IssuingPhysicalBundleStatusActive IssuingPhysicalBundleStatus = "active" + IssuingPhysicalBundleStatusInactive IssuingPhysicalBundleStatus = "inactive" + IssuingPhysicalBundleStatusReview IssuingPhysicalBundleStatus = "review" +) + +// Whether this physical bundle is a standard Stripe offering or custom-made for you. +type IssuingPhysicalBundleType string + +// List of values that IssuingPhysicalBundleType can take +const ( + IssuingPhysicalBundleTypeCustom IssuingPhysicalBundleType = "custom" + IssuingPhysicalBundleTypeStandard IssuingPhysicalBundleType = "standard" +) + +// Returns a list of physical bundle objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +type IssuingPhysicalBundleListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return physical bundles with the given status. + Status *string `form:"status"` + // Only return physical bundles with the given type. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingPhysicalBundleListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a physical bundle object. +type IssuingPhysicalBundleParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingPhysicalBundleParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a physical bundle object. +type IssuingPhysicalBundleRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingPhysicalBundleRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type IssuingPhysicalBundleFeatures struct { + // The policy for how to use card logo images in a card design with this physical bundle. + CardLogo IssuingPhysicalBundleFeaturesCardLogo `json:"card_logo"` + // The policy for how to use carrier letter text in a card design with this physical bundle. + CarrierText IssuingPhysicalBundleFeaturesCarrierText `json:"carrier_text"` + // The policy for how to use a second line on a card with this physical bundle. + SecondLine IssuingPhysicalBundleFeaturesSecondLine `json:"second_line"` +} + +// A Physical Bundle represents the bundle of physical items - card stock, carrier letter, and envelope - that is shipped to a cardholder when you create a physical card. +type IssuingPhysicalBundle struct { + APIResource + Features *IssuingPhysicalBundleFeatures `json:"features"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Friendly display name. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Whether this physical bundle can be used to create cards. + Status IssuingPhysicalBundleStatus `json:"status"` + // Whether this physical bundle is a standard Stripe offering or custom-made for you. + Type IssuingPhysicalBundleType `json:"type"` +} + +// IssuingPhysicalBundleList is a list of PhysicalBundles as retrieved from a list endpoint. +type IssuingPhysicalBundleList struct { + APIResource + ListMeta + Data []*IssuingPhysicalBundle `json:"data"` +} + +// UnmarshalJSON handles deserialization of an IssuingPhysicalBundle. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (i *IssuingPhysicalBundle) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + i.ID = id + return nil + } + + type issuingPhysicalBundle IssuingPhysicalBundle + var v issuingPhysicalBundle + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *i = IssuingPhysicalBundle(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_physicalbundle_service.go b/vendor/github.com/stripe/stripe-go/v82/issuing_physicalbundle_service.go new file mode 100644 index 00000000..64bfb4f3 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_physicalbundle_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1IssuingPhysicalBundleService is used to invoke /v1/issuing/physical_bundles APIs. +type v1IssuingPhysicalBundleService struct { + B Backend + Key string +} + +// Retrieves a physical bundle object. +func (c v1IssuingPhysicalBundleService) Retrieve(ctx context.Context, id string, params *IssuingPhysicalBundleRetrieveParams) (*IssuingPhysicalBundle, error) { + if params == nil { + params = &IssuingPhysicalBundleRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/physical_bundles/%s", id) + physicalbundle := &IssuingPhysicalBundle{} + err := c.B.Call(http.MethodGet, path, c.Key, params, physicalbundle) + return physicalbundle, err +} + +// Returns a list of physical bundle objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +func (c v1IssuingPhysicalBundleService) List(ctx context.Context, listParams *IssuingPhysicalBundleListParams) Seq2[*IssuingPhysicalBundle, error] { + if listParams == nil { + listParams = &IssuingPhysicalBundleListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*IssuingPhysicalBundle, ListContainer, error) { + list := &IssuingPhysicalBundleList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/issuing/physical_bundles", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_token.go b/vendor/github.com/stripe/stripe-go/v82/issuing_token.go new file mode 100644 index 00000000..0c013a00 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_token.go @@ -0,0 +1,298 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The token service provider / card network associated with the token. +type IssuingTokenNetwork string + +// List of values that IssuingTokenNetwork can take +const ( + IssuingTokenNetworkMastercard IssuingTokenNetwork = "mastercard" + IssuingTokenNetworkVisa IssuingTokenNetwork = "visa" +) + +// The type of device used for tokenization. +type IssuingTokenNetworkDataDeviceType string + +// List of values that IssuingTokenNetworkDataDeviceType can take +const ( + IssuingTokenNetworkDataDeviceTypeOther IssuingTokenNetworkDataDeviceType = "other" + IssuingTokenNetworkDataDeviceTypePhone IssuingTokenNetworkDataDeviceType = "phone" + IssuingTokenNetworkDataDeviceTypeWatch IssuingTokenNetworkDataDeviceType = "watch" +) + +// The network that the token is associated with. An additional hash is included with a name matching this value, containing tokenization data specific to the card network. +type IssuingTokenNetworkDataType string + +// List of values that IssuingTokenNetworkDataType can take +const ( + IssuingTokenNetworkDataTypeMastercard IssuingTokenNetworkDataType = "mastercard" + IssuingTokenNetworkDataTypeVisa IssuingTokenNetworkDataType = "visa" +) + +// The method used for tokenizing a card. +type IssuingTokenNetworkDataWalletProviderCardNumberSource string + +// List of values that IssuingTokenNetworkDataWalletProviderCardNumberSource can take +const ( + IssuingTokenNetworkDataWalletProviderCardNumberSourceApp IssuingTokenNetworkDataWalletProviderCardNumberSource = "app" + IssuingTokenNetworkDataWalletProviderCardNumberSourceManual IssuingTokenNetworkDataWalletProviderCardNumberSource = "manual" + IssuingTokenNetworkDataWalletProviderCardNumberSourceOnFile IssuingTokenNetworkDataWalletProviderCardNumberSource = "on_file" + IssuingTokenNetworkDataWalletProviderCardNumberSourceOther IssuingTokenNetworkDataWalletProviderCardNumberSource = "other" +) + +// The reasons for suggested tokenization given by the card network. +type IssuingTokenNetworkDataWalletProviderReasonCode string + +// List of values that IssuingTokenNetworkDataWalletProviderReasonCode can take +const ( + IssuingTokenNetworkDataWalletProviderReasonCodeAccountCardTooNew IssuingTokenNetworkDataWalletProviderReasonCode = "account_card_too_new" + IssuingTokenNetworkDataWalletProviderReasonCodeAccountRecentlyChanged IssuingTokenNetworkDataWalletProviderReasonCode = "account_recently_changed" + IssuingTokenNetworkDataWalletProviderReasonCodeAccountTooNew IssuingTokenNetworkDataWalletProviderReasonCode = "account_too_new" + IssuingTokenNetworkDataWalletProviderReasonCodeAccountTooNewSinceLaunch IssuingTokenNetworkDataWalletProviderReasonCode = "account_too_new_since_launch" + IssuingTokenNetworkDataWalletProviderReasonCodeAdditionalDevice IssuingTokenNetworkDataWalletProviderReasonCode = "additional_device" + IssuingTokenNetworkDataWalletProviderReasonCodeDataExpired IssuingTokenNetworkDataWalletProviderReasonCode = "data_expired" + IssuingTokenNetworkDataWalletProviderReasonCodeDeferIDVDecision IssuingTokenNetworkDataWalletProviderReasonCode = "defer_id_v_decision" + IssuingTokenNetworkDataWalletProviderReasonCodeDeviceRecentlyLost IssuingTokenNetworkDataWalletProviderReasonCode = "device_recently_lost" + IssuingTokenNetworkDataWalletProviderReasonCodeGoodActivityHistory IssuingTokenNetworkDataWalletProviderReasonCode = "good_activity_history" + IssuingTokenNetworkDataWalletProviderReasonCodeHasSuspendedTokens IssuingTokenNetworkDataWalletProviderReasonCode = "has_suspended_tokens" + IssuingTokenNetworkDataWalletProviderReasonCodeHighRisk IssuingTokenNetworkDataWalletProviderReasonCode = "high_risk" + IssuingTokenNetworkDataWalletProviderReasonCodeInactiveAccount IssuingTokenNetworkDataWalletProviderReasonCode = "inactive_account" + IssuingTokenNetworkDataWalletProviderReasonCodeLongAccountTenure IssuingTokenNetworkDataWalletProviderReasonCode = "long_account_tenure" + IssuingTokenNetworkDataWalletProviderReasonCodeLowAccountScore IssuingTokenNetworkDataWalletProviderReasonCode = "low_account_score" + IssuingTokenNetworkDataWalletProviderReasonCodeLowDeviceScore IssuingTokenNetworkDataWalletProviderReasonCode = "low_device_score" + IssuingTokenNetworkDataWalletProviderReasonCodeLowPhoneNumberScore IssuingTokenNetworkDataWalletProviderReasonCode = "low_phone_number_score" + IssuingTokenNetworkDataWalletProviderReasonCodeNetworkServiceError IssuingTokenNetworkDataWalletProviderReasonCode = "network_service_error" + IssuingTokenNetworkDataWalletProviderReasonCodeOutsideHomeTerritory IssuingTokenNetworkDataWalletProviderReasonCode = "outside_home_territory" + IssuingTokenNetworkDataWalletProviderReasonCodeProvisioningCardholderMismatch IssuingTokenNetworkDataWalletProviderReasonCode = "provisioning_cardholder_mismatch" + IssuingTokenNetworkDataWalletProviderReasonCodeProvisioningDeviceAndCardholderMismatch IssuingTokenNetworkDataWalletProviderReasonCode = "provisioning_device_and_cardholder_mismatch" + IssuingTokenNetworkDataWalletProviderReasonCodeProvisioningDeviceMismatch IssuingTokenNetworkDataWalletProviderReasonCode = "provisioning_device_mismatch" + IssuingTokenNetworkDataWalletProviderReasonCodeSameDeviceNoPriorAuthentication IssuingTokenNetworkDataWalletProviderReasonCode = "same_device_no_prior_authentication" + IssuingTokenNetworkDataWalletProviderReasonCodeSameDeviceSuccessfulPriorAuthentication IssuingTokenNetworkDataWalletProviderReasonCode = "same_device_successful_prior_authentication" + IssuingTokenNetworkDataWalletProviderReasonCodeSoftwareUpdate IssuingTokenNetworkDataWalletProviderReasonCode = "software_update" + IssuingTokenNetworkDataWalletProviderReasonCodeSuspiciousActivity IssuingTokenNetworkDataWalletProviderReasonCode = "suspicious_activity" + IssuingTokenNetworkDataWalletProviderReasonCodeTooManyDifferentCardholders IssuingTokenNetworkDataWalletProviderReasonCode = "too_many_different_cardholders" + IssuingTokenNetworkDataWalletProviderReasonCodeTooManyRecentAttempts IssuingTokenNetworkDataWalletProviderReasonCode = "too_many_recent_attempts" + IssuingTokenNetworkDataWalletProviderReasonCodeTooManyRecentTokens IssuingTokenNetworkDataWalletProviderReasonCode = "too_many_recent_tokens" +) + +// The recommendation on responding to the tokenization request. +type IssuingTokenNetworkDataWalletProviderSuggestedDecision string + +// List of values that IssuingTokenNetworkDataWalletProviderSuggestedDecision can take +const ( + IssuingTokenNetworkDataWalletProviderSuggestedDecisionApprove IssuingTokenNetworkDataWalletProviderSuggestedDecision = "approve" + IssuingTokenNetworkDataWalletProviderSuggestedDecisionDecline IssuingTokenNetworkDataWalletProviderSuggestedDecision = "decline" + IssuingTokenNetworkDataWalletProviderSuggestedDecisionRequireAuth IssuingTokenNetworkDataWalletProviderSuggestedDecision = "require_auth" +) + +// The usage state of the token. +type IssuingTokenStatus string + +// List of values that IssuingTokenStatus can take +const ( + IssuingTokenStatusActive IssuingTokenStatus = "active" + IssuingTokenStatusDeleted IssuingTokenStatus = "deleted" + IssuingTokenStatusRequested IssuingTokenStatus = "requested" + IssuingTokenStatusSuspended IssuingTokenStatus = "suspended" +) + +// The digital wallet for this token, if one was used. +type IssuingTokenWalletProvider string + +// List of values that IssuingTokenWalletProvider can take +const ( + IssuingTokenWalletProviderApplePay IssuingTokenWalletProvider = "apple_pay" + IssuingTokenWalletProviderGooglePay IssuingTokenWalletProvider = "google_pay" + IssuingTokenWalletProviderSamsungPay IssuingTokenWalletProvider = "samsung_pay" +) + +// Lists all Issuing Token objects for a given card. +type IssuingTokenListParams struct { + ListParams `form:"*"` + // The Issuing card identifier to list tokens for. + Card *string `form:"card"` + // Only return Issuing tokens that were created during the given date interval. + Created *int64 `form:"created"` + // Only return Issuing tokens that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Select Issuing tokens with the given status. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingTokenListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves an Issuing Token object. +type IssuingTokenParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Specifies which status the token should be updated to. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingTokenParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves an Issuing Token object. +type IssuingTokenRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingTokenRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Attempts to update the specified Issuing Token object to the status specified. +type IssuingTokenUpdateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Specifies which status the token should be updated to. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingTokenUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type IssuingTokenNetworkDataDevice struct { + // An obfuscated ID derived from the device ID. + DeviceFingerprint string `json:"device_fingerprint"` + // The IP address of the device at provisioning time. + IPAddress string `json:"ip_address"` + // The geographic latitude/longitude coordinates of the device at provisioning time. The format is [+-]decimal/[+-]decimal. + Location string `json:"location"` + // The name of the device used for tokenization. + Name string `json:"name"` + // The phone number of the device used for tokenization. + PhoneNumber string `json:"phone_number"` + // The type of device used for tokenization. + Type IssuingTokenNetworkDataDeviceType `json:"type"` +} +type IssuingTokenNetworkDataMastercard struct { + // A unique reference ID from MasterCard to represent the card account number. + CardReferenceID string `json:"card_reference_id"` + // The network-unique identifier for the token. + TokenReferenceID string `json:"token_reference_id"` + // The ID of the entity requesting tokenization, specific to MasterCard. + TokenRequestorID string `json:"token_requestor_id"` + // The name of the entity requesting tokenization, if known. This is directly provided from MasterCard. + TokenRequestorName string `json:"token_requestor_name"` +} +type IssuingTokenNetworkDataVisa struct { + // A unique reference ID from Visa to represent the card account number. + CardReferenceID string `json:"card_reference_id"` + // The network-unique identifier for the token. + TokenReferenceID string `json:"token_reference_id"` + // The ID of the entity requesting tokenization, specific to Visa. + TokenRequestorID string `json:"token_requestor_id"` + // Degree of risk associated with the token between `01` and `99`, with higher number indicating higher risk. A `00` value indicates the token was not scored by Visa. + TokenRiskScore string `json:"token_risk_score"` +} +type IssuingTokenNetworkDataWalletProviderCardholderAddress struct { + // The street address of the cardholder tokenizing the card. + Line1 string `json:"line1"` + // The postal code of the cardholder tokenizing the card. + PostalCode string `json:"postal_code"` +} +type IssuingTokenNetworkDataWalletProvider struct { + // The wallet provider-given account ID of the digital wallet the token belongs to. + AccountID string `json:"account_id"` + // An evaluation on the trustworthiness of the wallet account between 1 and 5. A higher score indicates more trustworthy. + AccountTrustScore int64 `json:"account_trust_score"` + CardholderAddress *IssuingTokenNetworkDataWalletProviderCardholderAddress `json:"cardholder_address"` + // The name of the cardholder tokenizing the card. + CardholderName string `json:"cardholder_name"` + // The method used for tokenizing a card. + CardNumberSource IssuingTokenNetworkDataWalletProviderCardNumberSource `json:"card_number_source"` + // An evaluation on the trustworthiness of the device. A higher score indicates more trustworthy. + DeviceTrustScore int64 `json:"device_trust_score"` + // The hashed email address of the cardholder's account with the wallet provider. + HashedAccountEmailAddress string `json:"hashed_account_email_address"` + // The reasons for suggested tokenization given by the card network. + ReasonCodes []IssuingTokenNetworkDataWalletProviderReasonCode `json:"reason_codes"` + // The recommendation on responding to the tokenization request. + SuggestedDecision IssuingTokenNetworkDataWalletProviderSuggestedDecision `json:"suggested_decision"` + // The version of the standard for mapping reason codes followed by the wallet provider. + SuggestedDecisionVersion string `json:"suggested_decision_version"` +} +type IssuingTokenNetworkData struct { + Device *IssuingTokenNetworkDataDevice `json:"device"` + Mastercard *IssuingTokenNetworkDataMastercard `json:"mastercard"` + // The network that the token is associated with. An additional hash is included with a name matching this value, containing tokenization data specific to the card network. + Type IssuingTokenNetworkDataType `json:"type"` + Visa *IssuingTokenNetworkDataVisa `json:"visa"` + WalletProvider *IssuingTokenNetworkDataWalletProvider `json:"wallet_provider"` +} + +// An issuing token object is created when an issued card is added to a digital wallet. As a [card issuer](https://stripe.com/docs/issuing), you can [view and manage these tokens](https://stripe.com/docs/issuing/controls/token-management) through Stripe. +type IssuingToken struct { + APIResource + // Card associated with this token. + Card *IssuingCard `json:"card"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The hashed ID derived from the device ID from the card network associated with the token. + DeviceFingerprint string `json:"device_fingerprint"` + // Unique identifier for the object. + ID string `json:"id"` + // The last four digits of the token. + Last4 string `json:"last4"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // The token service provider / card network associated with the token. + Network IssuingTokenNetwork `json:"network"` + NetworkData *IssuingTokenNetworkData `json:"network_data"` + // Time at which the token was last updated by the card network. Measured in seconds since the Unix epoch. + NetworkUpdatedAt int64 `json:"network_updated_at"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The usage state of the token. + Status IssuingTokenStatus `json:"status"` + // The digital wallet for this token, if one was used. + WalletProvider IssuingTokenWalletProvider `json:"wallet_provider"` +} + +// IssuingTokenList is a list of Tokens as retrieved from a list endpoint. +type IssuingTokenList struct { + APIResource + ListMeta + Data []*IssuingToken `json:"data"` +} + +// UnmarshalJSON handles deserialization of an IssuingToken. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (i *IssuingToken) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + i.ID = id + return nil + } + + type issuingToken IssuingToken + var v issuingToken + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *i = IssuingToken(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_token_service.go b/vendor/github.com/stripe/stripe-go/v82/issuing_token_service.go new file mode 100644 index 00000000..2474b6b8 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_token_service.go @@ -0,0 +1,61 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1IssuingTokenService is used to invoke /v1/issuing/tokens APIs. +type v1IssuingTokenService struct { + B Backend + Key string +} + +// Retrieves an Issuing Token object. +func (c v1IssuingTokenService) Retrieve(ctx context.Context, id string, params *IssuingTokenRetrieveParams) (*IssuingToken, error) { + if params == nil { + params = &IssuingTokenRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/tokens/%s", id) + token := &IssuingToken{} + err := c.B.Call(http.MethodGet, path, c.Key, params, token) + return token, err +} + +// Attempts to update the specified Issuing Token object to the status specified. +func (c v1IssuingTokenService) Update(ctx context.Context, id string, params *IssuingTokenUpdateParams) (*IssuingToken, error) { + if params == nil { + params = &IssuingTokenUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/tokens/%s", id) + token := &IssuingToken{} + err := c.B.Call(http.MethodPost, path, c.Key, params, token) + return token, err +} + +// Lists all Issuing Token objects for a given card. +func (c v1IssuingTokenService) List(ctx context.Context, listParams *IssuingTokenListParams) Seq2[*IssuingToken, error] { + if listParams == nil { + listParams = &IssuingTokenListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*IssuingToken, ListContainer, error) { + list := &IssuingTokenList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/issuing/tokens", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_transaction.go b/vendor/github.com/stripe/stripe-go/v82/issuing_transaction.go new file mode 100644 index 00000000..3042895d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_transaction.go @@ -0,0 +1,375 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The type of fuel that was purchased. One of `diesel`, `unleaded_plus`, `unleaded_regular`, `unleaded_super`, or `other`. +type IssuingTransactionPurchaseDetailsFuelType string + +// List of values that IssuingTransactionPurchaseDetailsFuelType can take +const ( + IssuingTransactionPurchaseDetailsFuelTypeDiesel IssuingTransactionPurchaseDetailsFuelType = "diesel" + IssuingTransactionPurchaseDetailsFuelTypeOther IssuingTransactionPurchaseDetailsFuelType = "other" + IssuingTransactionPurchaseDetailsFuelTypeUnleadedPlus IssuingTransactionPurchaseDetailsFuelType = "unleaded_plus" + IssuingTransactionPurchaseDetailsFuelTypeUnleadedRegular IssuingTransactionPurchaseDetailsFuelType = "unleaded_regular" + IssuingTransactionPurchaseDetailsFuelTypeUnleadedSuper IssuingTransactionPurchaseDetailsFuelType = "unleaded_super" +) + +// The units for `quantity_decimal`. One of `charging_minute`, `imperial_gallon`, `kilogram`, `kilowatt_hour`, `liter`, `pound`, `us_gallon`, or `other`. +type IssuingTransactionPurchaseDetailsFuelUnit string + +// List of values that IssuingTransactionPurchaseDetailsFuelUnit can take +const ( + IssuingTransactionPurchaseDetailsFuelUnitChargingMinute IssuingTransactionPurchaseDetailsFuelUnit = "charging_minute" + IssuingTransactionPurchaseDetailsFuelUnitImperialGallon IssuingTransactionPurchaseDetailsFuelUnit = "imperial_gallon" + IssuingTransactionPurchaseDetailsFuelUnitKilogram IssuingTransactionPurchaseDetailsFuelUnit = "kilogram" + IssuingTransactionPurchaseDetailsFuelUnitKilowattHour IssuingTransactionPurchaseDetailsFuelUnit = "kilowatt_hour" + IssuingTransactionPurchaseDetailsFuelUnitLiter IssuingTransactionPurchaseDetailsFuelUnit = "liter" + IssuingTransactionPurchaseDetailsFuelUnitPound IssuingTransactionPurchaseDetailsFuelUnit = "pound" + IssuingTransactionPurchaseDetailsFuelUnitUSGallon IssuingTransactionPurchaseDetailsFuelUnit = "us_gallon" + IssuingTransactionPurchaseDetailsFuelUnitOther IssuingTransactionPurchaseDetailsFuelUnit = "other" +) + +// The nature of the transaction. +type IssuingTransactionType string + +// List of values that IssuingTransactionType can take +const ( + IssuingTransactionTypeCapture IssuingTransactionType = "capture" + IssuingTransactionTypeRefund IssuingTransactionType = "refund" +) + +// The digital wallet used for this transaction. One of `apple_pay`, `google_pay`, or `samsung_pay`. +type IssuingTransactionWallet string + +// List of values that IssuingTransactionWallet can take +const ( + IssuingTransactionWalletApplePay IssuingTransactionWallet = "apple_pay" + IssuingTransactionWalletGooglePay IssuingTransactionWallet = "google_pay" + IssuingTransactionWalletSamsungPay IssuingTransactionWallet = "samsung_pay" +) + +// Returns a list of Issuing Transaction objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +type IssuingTransactionListParams struct { + ListParams `form:"*"` + // Only return transactions that belong to the given card. + Card *string `form:"card"` + // Only return transactions that belong to the given cardholder. + Cardholder *string `form:"cardholder"` + // Only return transactions that were created during the given date interval. + Created *int64 `form:"created"` + // Only return transactions that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return transactions that have the given type. One of `capture` or `refund`. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingTransactionListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves an Issuing Transaction object. +type IssuingTransactionParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingTransactionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingTransactionParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves an Issuing Transaction object. +type IssuingTransactionRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingTransactionRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the specified Issuing Transaction object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +type IssuingTransactionUpdateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *IssuingTransactionUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *IssuingTransactionUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Detailed breakdown of amount components. These amounts are denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). +type IssuingTransactionAmountDetails struct { + // The fee charged by the ATM for the cash withdrawal. + ATMFee int64 `json:"atm_fee"` + // The amount of cash requested by the cardholder. + CashbackAmount int64 `json:"cashback_amount"` +} + +// Details about the transaction, such as processing dates, set by the card network. +type IssuingTransactionNetworkData struct { + // A code created by Stripe which is shared with the merchant to validate the authorization. This field will be populated if the authorization message was approved. The code typically starts with the letter "S", followed by a six-digit number. For example, "S498162". Please note that the code is not guaranteed to be unique across authorizations. + AuthorizationCode string `json:"authorization_code"` + // The date the transaction was processed by the card network. This can be different from the date the seller recorded the transaction depending on when the acquirer submits the transaction to the network. + ProcessingDate string `json:"processing_date"` + // Unique identifier for the authorization assigned by the card network used to match subsequent messages, disputes, and transactions. + TransactionID string `json:"transaction_id"` +} + +// Answers to prompts presented to cardholder at point of sale. +type IssuingTransactionPurchaseDetailsFleetCardholderPromptData struct { + // Driver ID. + DriverID string `json:"driver_id"` + // Odometer reading. + Odometer int64 `json:"odometer"` + // An alphanumeric ID. This field is used when a vehicle ID, driver ID, or generic ID is entered by the cardholder, but the merchant or card network did not specify the prompt type. + UnspecifiedID string `json:"unspecified_id"` + // User ID. + UserID string `json:"user_id"` + // Vehicle number. + VehicleNumber string `json:"vehicle_number"` +} + +// Breakdown of fuel portion of the purchase. +type IssuingTransactionPurchaseDetailsFleetReportedBreakdownFuel struct { + // Gross fuel amount that should equal Fuel Volume multipled by Fuel Unit Cost, inclusive of taxes. + GrossAmountDecimal float64 `json:"gross_amount_decimal,string"` +} + +// Breakdown of non-fuel portion of the purchase. +type IssuingTransactionPurchaseDetailsFleetReportedBreakdownNonFuel struct { + // Gross non-fuel amount that should equal the sum of the line items, inclusive of taxes. + GrossAmountDecimal float64 `json:"gross_amount_decimal,string"` +} + +// Information about tax included in this transaction. +type IssuingTransactionPurchaseDetailsFleetReportedBreakdownTax struct { + // Amount of state or provincial Sales Tax included in the transaction amount. Null if not reported by merchant or not subject to tax. + LocalAmountDecimal float64 `json:"local_amount_decimal,string"` + // Amount of national Sales Tax or VAT included in the transaction amount. Null if not reported by merchant or not subject to tax. + NationalAmountDecimal float64 `json:"national_amount_decimal,string"` +} + +// More information about the total amount. This information is not guaranteed to be accurate as some merchants may provide unreliable data. +type IssuingTransactionPurchaseDetailsFleetReportedBreakdown struct { + // Breakdown of fuel portion of the purchase. + Fuel *IssuingTransactionPurchaseDetailsFleetReportedBreakdownFuel `json:"fuel"` + // Breakdown of non-fuel portion of the purchase. + NonFuel *IssuingTransactionPurchaseDetailsFleetReportedBreakdownNonFuel `json:"non_fuel"` + // Information about tax included in this transaction. + Tax *IssuingTransactionPurchaseDetailsFleetReportedBreakdownTax `json:"tax"` +} + +// Fleet-specific information for transactions using Fleet cards. +type IssuingTransactionPurchaseDetailsFleet struct { + // Answers to prompts presented to cardholder at point of sale. + CardholderPromptData *IssuingTransactionPurchaseDetailsFleetCardholderPromptData `json:"cardholder_prompt_data"` + // The type of purchase. One of `fuel_purchase`, `non_fuel_purchase`, or `fuel_and_non_fuel_purchase`. + PurchaseType string `json:"purchase_type"` + // More information about the total amount. This information is not guaranteed to be accurate as some merchants may provide unreliable data. + ReportedBreakdown *IssuingTransactionPurchaseDetailsFleetReportedBreakdown `json:"reported_breakdown"` + // The type of fuel service. One of `non_fuel_transaction`, `full_service`, or `self_service`. + ServiceType string `json:"service_type"` +} + +// The legs of the trip. +type IssuingTransactionPurchaseDetailsFlightSegment struct { + // The three-letter IATA airport code of the flight's destination. + ArrivalAirportCode string `json:"arrival_airport_code"` + // The airline carrier code. + Carrier string `json:"carrier"` + // The three-letter IATA airport code that the flight departed from. + DepartureAirportCode string `json:"departure_airport_code"` + // The flight number. + FlightNumber string `json:"flight_number"` + // The flight's service class. + ServiceClass string `json:"service_class"` + // Whether a stopover is allowed on this flight. + StopoverAllowed bool `json:"stopover_allowed"` +} + +// Information about the flight that was purchased with this transaction. +type IssuingTransactionPurchaseDetailsFlight struct { + // The time that the flight departed. + DepartureAt int64 `json:"departure_at"` + // The name of the passenger. + PassengerName string `json:"passenger_name"` + // Whether the ticket is refundable. + Refundable bool `json:"refundable"` + // The legs of the trip. + Segments []*IssuingTransactionPurchaseDetailsFlightSegment `json:"segments"` + // The travel agency that issued the ticket. + TravelAgency string `json:"travel_agency"` +} + +// Information about fuel that was purchased with this transaction. +type IssuingTransactionPurchaseDetailsFuel struct { + // [Conexxus Payment System Product Code](https://www.conexxus.org/conexxus-payment-system-product-codes) identifying the primary fuel product purchased. + IndustryProductCode string `json:"industry_product_code"` + // The quantity of `unit`s of fuel that was dispensed, represented as a decimal string with at most 12 decimal places. + QuantityDecimal float64 `json:"quantity_decimal,string"` + // The type of fuel that was purchased. One of `diesel`, `unleaded_plus`, `unleaded_regular`, `unleaded_super`, or `other`. + Type IssuingTransactionPurchaseDetailsFuelType `json:"type"` + // The units for `quantity_decimal`. One of `charging_minute`, `imperial_gallon`, `kilogram`, `kilowatt_hour`, `liter`, `pound`, `us_gallon`, or `other`. + Unit IssuingTransactionPurchaseDetailsFuelUnit `json:"unit"` + // The cost in cents per each unit of fuel, represented as a decimal string with at most 12 decimal places. + UnitCostDecimal float64 `json:"unit_cost_decimal,string"` +} + +// Information about lodging that was purchased with this transaction. +type IssuingTransactionPurchaseDetailsLodging struct { + // The time of checking into the lodging. + CheckInAt int64 `json:"check_in_at"` + // The number of nights stayed at the lodging. + Nights int64 `json:"nights"` +} + +// The line items in the purchase. +type IssuingTransactionPurchaseDetailsReceipt struct { + // The description of the item. The maximum length of this field is 26 characters. + Description string `json:"description"` + // The quantity of the item. + Quantity float64 `json:"quantity"` + // The total for this line item in cents. + Total int64 `json:"total"` + // The unit cost of the item in cents. + UnitCost int64 `json:"unit_cost"` +} + +// Additional purchase information that is optionally provided by the merchant. +type IssuingTransactionPurchaseDetails struct { + // Fleet-specific information for transactions using Fleet cards. + Fleet *IssuingTransactionPurchaseDetailsFleet `json:"fleet"` + // Information about the flight that was purchased with this transaction. + Flight *IssuingTransactionPurchaseDetailsFlight `json:"flight"` + // Information about fuel that was purchased with this transaction. + Fuel *IssuingTransactionPurchaseDetailsFuel `json:"fuel"` + // Information about lodging that was purchased with this transaction. + Lodging *IssuingTransactionPurchaseDetailsLodging `json:"lodging"` + // The line items in the purchase. + Receipt []*IssuingTransactionPurchaseDetailsReceipt `json:"receipt"` + // A merchant-specific order number. + Reference string `json:"reference"` +} + +// [Treasury](https://stripe.com/docs/api/treasury) details related to this transaction if it was created on a [FinancialAccount](/docs/api/treasury/financial_accounts +type IssuingTransactionTreasury struct { + // The Treasury [ReceivedCredit](https://stripe.com/docs/api/treasury/received_credits) representing this Issuing transaction if it is a refund + ReceivedCredit string `json:"received_credit"` + // The Treasury [ReceivedDebit](https://stripe.com/docs/api/treasury/received_debits) representing this Issuing transaction if it is a capture + ReceivedDebit string `json:"received_debit"` +} + +// Any use of an [issued card](https://stripe.com/docs/issuing) that results in funds entering or leaving +// your Stripe account, such as a completed purchase or refund, is represented by an Issuing +// `Transaction` object. +// +// Related guide: [Issued card transactions](https://stripe.com/docs/issuing/purchases/transactions) +type IssuingTransaction struct { + APIResource + // The transaction amount, which will be reflected in your balance. This amount is in your currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Amount int64 `json:"amount"` + // Detailed breakdown of amount components. These amounts are denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + AmountDetails *IssuingTransactionAmountDetails `json:"amount_details"` + // The `Authorization` object that led to this transaction. + Authorization *IssuingAuthorization `json:"authorization"` + // ID of the [balance transaction](https://stripe.com/docs/api/balance_transactions) associated with this transaction. + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + // The card used to make this transaction. + Card *IssuingCard `json:"card"` + // The cardholder to whom this transaction belongs. + Cardholder *IssuingCardholder `json:"cardholder"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // If you've disputed the transaction, the ID of the dispute. + Dispute *IssuingDispute `json:"dispute"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // The amount that the merchant will receive, denominated in `merchant_currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). It will be different from `amount` if the merchant is taking payment in a different currency. + MerchantAmount int64 `json:"merchant_amount"` + // The currency with which the merchant is taking payment. + MerchantCurrency Currency `json:"merchant_currency"` + MerchantData *IssuingAuthorizationMerchantData `json:"merchant_data"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // Details about the transaction, such as processing dates, set by the card network. + NetworkData *IssuingTransactionNetworkData `json:"network_data"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Additional purchase information that is optionally provided by the merchant. + PurchaseDetails *IssuingTransactionPurchaseDetails `json:"purchase_details"` + // [Token](https://stripe.com/docs/api/issuing/tokens/object) object used for this transaction. If a network token was not used for this transaction, this field will be null. + Token *IssuingToken `json:"token"` + // [Treasury](https://stripe.com/docs/api/treasury) details related to this transaction if it was created on a [FinancialAccount](/docs/api/treasury/financial_accounts + Treasury *IssuingTransactionTreasury `json:"treasury"` + // The nature of the transaction. + Type IssuingTransactionType `json:"type"` + // The digital wallet used for this transaction. One of `apple_pay`, `google_pay`, or `samsung_pay`. + Wallet IssuingTransactionWallet `json:"wallet"` +} + +// IssuingTransactionList is a list of Transactions as retrieved from a list endpoint. +type IssuingTransactionList struct { + APIResource + ListMeta + Data []*IssuingTransaction `json:"data"` +} + +// UnmarshalJSON handles deserialization of an IssuingTransaction. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (i *IssuingTransaction) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + i.ID = id + return nil + } + + type issuingTransaction IssuingTransaction + var v issuingTransaction + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *i = IssuingTransaction(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/issuing_transaction_service.go b/vendor/github.com/stripe/stripe-go/v82/issuing_transaction_service.go new file mode 100644 index 00000000..8bc0d8df --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/issuing_transaction_service.go @@ -0,0 +1,61 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1IssuingTransactionService is used to invoke /v1/issuing/transactions APIs. +type v1IssuingTransactionService struct { + B Backend + Key string +} + +// Retrieves an Issuing Transaction object. +func (c v1IssuingTransactionService) Retrieve(ctx context.Context, id string, params *IssuingTransactionRetrieveParams) (*IssuingTransaction, error) { + if params == nil { + params = &IssuingTransactionRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/transactions/%s", id) + transaction := &IssuingTransaction{} + err := c.B.Call(http.MethodGet, path, c.Key, params, transaction) + return transaction, err +} + +// Updates the specified Issuing Transaction object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +func (c v1IssuingTransactionService) Update(ctx context.Context, id string, params *IssuingTransactionUpdateParams) (*IssuingTransaction, error) { + if params == nil { + params = &IssuingTransactionUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/issuing/transactions/%s", id) + transaction := &IssuingTransaction{} + err := c.B.Call(http.MethodPost, path, c.Key, params, transaction) + return transaction, err +} + +// Returns a list of Issuing Transaction objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +func (c v1IssuingTransactionService) List(ctx context.Context, listParams *IssuingTransactionListParams) Seq2[*IssuingTransaction, error] { + if listParams == nil { + listParams = &IssuingTransactionListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*IssuingTransaction, ListContainer, error) { + list := &IssuingTransactionList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/issuing/transactions", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/iter.go b/vendor/github.com/stripe/stripe-go/v82/iter.go new file mode 100644 index 00000000..cc3ef873 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/iter.go @@ -0,0 +1,328 @@ +package stripe + +import ( + "reflect" + + "github.com/stripe/stripe-go/v82/form" +) + +// Iter provides a convenient interface +// for iterating over the elements +// returned from paginated list API calls. +// Successive calls to the Next method +// will step through each item in the list, +// fetching pages of items as needed. +// Iterators are not thread-safe, so they should not be consumed +// across multiple goroutines. +type Iter struct { + cur interface{} + err error + formValues *form.Values + list ListContainer + listParams ListParams + meta *ListMeta + query Query + values []interface{} +} + +// Current returns the most recent item +// visited by a call to Next. +func (it *Iter) Current() interface{} { + return it.cur +} + +// Err returns the error, if any, +// that caused the Iter to stop. +// It must be inspected +// after Next returns false. +func (it *Iter) Err() error { + return it.err +} + +// List returns the current list object which the iterator is currently using. +// List objects will change as new API calls are made to continue pagination. +func (it *Iter) List() ListContainer { + return it.list +} + +// Meta returns the list metadata. +func (it *Iter) Meta() *ListMeta { + return it.meta +} + +// Next advances the Iter to the next item in the list, +// which will then be available +// through the Current method. +// It returns false when the iterator stops +// at the end of the list. +func (it *Iter) Next() bool { + if len(it.values) == 0 && it.meta.HasMore && !it.listParams.Single { + // determine if we're moving forward or backwards in paging + if it.listParams.EndingBefore != nil { + it.listParams.EndingBefore = String(listItemID(it.cur)) + it.formValues.Set(EndingBefore, *it.listParams.EndingBefore) + } else { + it.listParams.StartingAfter = String(listItemID(it.cur)) + it.formValues.Set(StartingAfter, *it.listParams.StartingAfter) + } + it.getPage() + } + if len(it.values) == 0 { + return false + } + it.cur = it.values[0] + it.values = it.values[1:] + return true +} + +func (it *Iter) getPage() { + it.values, it.list, it.err = it.query(it.listParams.GetParams(), it.formValues) + it.meta = it.list.GetListMeta() + + if it.listParams.EndingBefore != nil { + // We are moving backward, + // but items arrive in forward order. + reverse(it.values) + } +} + +// Query is the function used to get a page listing. +type Query func(*Params, *form.Values) ([]interface{}, ListContainer, error) + +// GetIter returns a new Iter for a given query and its options. +func GetIter(container ListParamsContainer, query Query) *Iter { + var listParams *ListParams + formValues := &form.Values{} + + if container != nil { + reflectValue := reflect.ValueOf(container) + + // See the comment on Call in stripe.go. + if reflectValue.Kind() == reflect.Ptr && !reflectValue.IsNil() { + listParams = container.GetListParams() + form.AppendTo(formValues, container) + } + } + + if listParams == nil { + listParams = &ListParams{} + } + iter := &Iter{ + formValues: formValues, + listParams: *listParams, + query: query, + } + + iter.getPage() + + return iter +} + +// v1List provides a convenient interface for iterating over the elements +// returned from paginated list API calls. It is meant to be an improvement +// over the Iter type, which was written before Go introduced generics and iter.Seq2. +// Calling the `All` allows you to iterate over all items in the list, +// with automatic pagination. +type v1List[T any] struct { + cur *T + err error + formValues *form.Values + listContainer ListContainer + listParams ListParams + listMeta *ListMeta + query v1Query[T] + values []*T +} + +// All returns a Seq2 that will be evaluated on each item in a v1List. +// The All function will continue to fetch pages of items as needed. +func (it *v1List[T]) All() Seq2[*T, error] { + return func(yield func(*T, error) bool) { + for it.next() { + if !yield(it.cur, nil) { + return + } + } + if it.err != nil { + if !yield(nil, it.err) { + return + } + } + } +} + +// next advances the V1List to the next item in the list, +// which will then be available +// through the current method. +// It returns false when the iterator stops +// at the end of the list. +func (it *v1List[T]) next() bool { + if len(it.values) == 0 && it.listMeta.HasMore && !it.listParams.Single { + // determine if we're moving forward or backwards in paging + if it.listParams.EndingBefore != nil { + it.listParams.EndingBefore = String(listItemID(it.cur)) + it.formValues.Set(EndingBefore, *it.listParams.EndingBefore) + } else { + it.listParams.StartingAfter = String(listItemID(it.cur)) + it.formValues.Set(StartingAfter, *it.listParams.StartingAfter) + } + it.getPage() + } + if len(it.values) == 0 { + return false + } + it.cur = it.values[0] + it.values = it.values[1:] + return true +} + +func (it *v1List[T]) getPage() { + it.values, it.listContainer, it.err = it.query(it.listParams.GetParams(), it.formValues) + it.listMeta = it.listContainer.GetListMeta() + + if it.listParams.EndingBefore != nil { + // We are moving backward, + // but items arrive in forward order. + reverse(it.values) + } +} + +// Query is the function used to get a page listing. +type v1Query[T any] func(*Params, *form.Values) ([]*T, ListContainer, error) + +// newV1List returns a new v1List for a given query and its options, and initializes +// it by fetching the first page of items. +func newV1List[T any](container ListParamsContainer, query v1Query[T]) *v1List[T] { + var listParams *ListParams + formValues := &form.Values{} + + if container != nil { + reflectValue := reflect.ValueOf(container) + + // See the comment on Call in stripe.go. + if reflectValue.Kind() == reflect.Ptr && !reflectValue.IsNil() { + listParams = container.GetListParams() + form.AppendTo(formValues, container) + } + } + + if listParams == nil { + listParams = &ListParams{} + } + iter := &v1List[T]{ + formValues: formValues, + listParams: *listParams, + query: query, + } + + iter.getPage() + + return iter +} + +func listItemID[T any](x T) string { + return reflect.ValueOf(x).Elem().FieldByName("ID").String() +} + +func reverse[T any](a []T) { + for i := 0; i < len(a)/2; i++ { + a[i], a[len(a)-i-1] = a[len(a)-i-1], a[i] + } +} + +// Seq2 is the same as the iter.Seq2 type in Go 1.23+. It is used as the return type +// of All methods. If you are using Go 1.23+, you can just range over the an All +// method directly, e.g., +// +// for event, err := range sc.V2Events.All() { +// // check err and do something with event +// } +// +// For older versions of Go, the yield function should return false +// to stop iteration or true to continue. +type Seq2[K, V any] func(yield func(K, V) bool) + +// V2List contains a page of data received from a List API call, +// and the means to paginate to the next page of data via the fetch function. +type V2List[T any] struct { + fetch Fetch[T] + params ParamsContainer + initialized bool + // Page contains the items returned from the last API call. + V2Page[T] +} + +// V2Page is represents a single page returned from a List API call. +// Users will not ordinaily interact with this type directly. +type V2Page[T any] struct { + APIResource + Data []T `json:"data"` + NextPageURL string `json:"next_page_url"` + PreviousPageURL string `json:"previous_page_url"` +} + +// NewV2List creates a new V2List with the given path and fetch function. +func NewV2List[T any](path string, p ParamsContainer, fetch Fetch[T]) *V2List[T] { + return &V2List[T]{ + fetch: fetch, + params: p, + V2Page: V2Page[T]{NextPageURL: path}, + } +} + +// Fetch is a function that fetches a page of items. +type Fetch[T any] func(path string, p ParamsContainer) (*V2Page[T], error) + +// All returns a Seq2 that will be evaluated on each item in a V2List. +// The All function will continue to fetch pages of items as needed. +func (s *V2List[T]) All() Seq2[T, error] { + return func(yield func(T, error) bool) { + var fetchMore bool + // fetch inital page + err := s.page() + if err != nil && !yield(*new(T), err) { + return + } + s.initialized = true + fetchMore = (s.NextPageURL != "") + + for len(s.Data) > 0 { + for _, item := range s.Data { + if !yield(item, nil) { + return + } + } + + if !fetchMore { + return + } + err := s.page() + if err != nil && !yield(*new(T), err) { + return + } + fetchMore = (s.NextPageURL != "") + } + } +} + +// page fetches the next page of items and updates the Seq's state. +// It returns true if there exist more pages to fetch, and false if +// that was the last page. +func (s *V2List[T]) page() error { + // if we've already fetched a page, the next page URL + // already contains all of the query parameters + var params ParamsContainer + if s.initialized { + params = &Params{} + } else { + params = s.params + } + + next, err := s.fetch(s.NextPageURL, params) + if err != nil { + return err + } + + s.V2Page = *next + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/justfile b/vendor/github.com/stripe/stripe-go/v82/justfile new file mode 100644 index 00000000..a8341ef7 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/justfile @@ -0,0 +1,62 @@ +set quiet + +import? '../sdk-codegen/utils.just' + +# ensure tools installed with `go install` are available to call +export PATH := home_directory() + "/go/bin:" + env('PATH') + +_default: + just --list --unsorted + +# ⭐ run all unit tests, or pass a package name (./invoice) to only run those tests +test *args="./...": + go run scripts/test_with_stripe_mock/main.go -race {{ args }} + +# check for potential mistakes (slow) +lint: install + go vet ./... + staticcheck + +# don't depend on `install` in this step! Before formatting, our `go` code isn't syntactically valid +# ⭐ format all files +format: _normalize-imports install + scripts/gofmt.sh + goimports -w example/generated_examples_test.go + +# verify, but don't modify, the formatting of the files +format-check: + scripts/gofmt.sh check + +ci-test: test bench + +# compile the project +build: + go build ./... + +# install dependencies (including those needed for development). Mostly called by other recipes +install: + go get -t + go install honnef.co/go/tools/cmd/staticcheck@v0.4.7 + go install golang.org/x/tools/cmd/goimports@v0.24.0 + +# run benchmarking to check for performance regressions +bench: + go test -race -bench . -run "Benchmark" ./form + +# called by tooling. It updates the package version in the `VERSION` file and `stripe.go` +[private] +update-version version: && _normalize-imports + echo "{{ version }}" > VERSION + perl -pi -e 's|const clientversion = "[.\d\-\w]+"|const clientversion = "{{ version }}"|' stripe.go + +# go imports use the package's major version in the path, so we need to update them +# we also generate files with a placeholder `[MAJOR_VERSION]` that we need to replace +# we can pull the major version out of the `VERSION` file +# NOTE: because we run this _after_ other recipes that modify `VERSION`, it's important that we only read the file in the argument evaluation +# (if it's a top-level variable, it's read when the file is parsed, which is too early) +# arguments are only evaluated when the recipe starts +# so, setting it as the default means we get both the variable and the lazy evaluation we need +_normalize-imports major_version=replace_regex(`cat VERSION`, '\..*', ""): + perl -pi -e 's|github.com/stripe/stripe-go/v\d+|github.com/stripe/stripe-go/v{{ major_version }}|' README.md + perl -pi -e 's|github.com/stripe/stripe-go/v\d+|github.com/stripe/stripe-go/v{{ major_version }}|' go.mod + find . -name '*.go' -exec perl -pi -e 's|github.com/stripe/stripe-go/(v\d+\|\[MAJOR_VERSION\])|github.com/stripe/stripe-go/v{{ major_version }}|' {} + diff --git a/vendor/github.com/stripe/stripe-go/v82/lineitem.go b/vendor/github.com/stripe/stripe-go/v82/lineitem.go new file mode 100644 index 00000000..3a6c42ea --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/lineitem.go @@ -0,0 +1,89 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type LineItemTaxTaxabilityReason string + +// List of values that LineItemTaxTaxabilityReason can take +const ( + LineItemTaxTaxabilityReasonCustomerExempt LineItemTaxTaxabilityReason = "customer_exempt" + LineItemTaxTaxabilityReasonNotCollecting LineItemTaxTaxabilityReason = "not_collecting" + LineItemTaxTaxabilityReasonNotSubjectToTax LineItemTaxTaxabilityReason = "not_subject_to_tax" + LineItemTaxTaxabilityReasonNotSupported LineItemTaxTaxabilityReason = "not_supported" + LineItemTaxTaxabilityReasonPortionProductExempt LineItemTaxTaxabilityReason = "portion_product_exempt" + LineItemTaxTaxabilityReasonPortionReducedRated LineItemTaxTaxabilityReason = "portion_reduced_rated" + LineItemTaxTaxabilityReasonPortionStandardRated LineItemTaxTaxabilityReason = "portion_standard_rated" + LineItemTaxTaxabilityReasonProductExempt LineItemTaxTaxabilityReason = "product_exempt" + LineItemTaxTaxabilityReasonProductExemptHoliday LineItemTaxTaxabilityReason = "product_exempt_holiday" + LineItemTaxTaxabilityReasonProportionallyRated LineItemTaxTaxabilityReason = "proportionally_rated" + LineItemTaxTaxabilityReasonReducedRated LineItemTaxTaxabilityReason = "reduced_rated" + LineItemTaxTaxabilityReasonReverseCharge LineItemTaxTaxabilityReason = "reverse_charge" + LineItemTaxTaxabilityReasonStandardRated LineItemTaxTaxabilityReason = "standard_rated" + LineItemTaxTaxabilityReasonTaxableBasisReduced LineItemTaxTaxabilityReason = "taxable_basis_reduced" + LineItemTaxTaxabilityReasonZeroRated LineItemTaxTaxabilityReason = "zero_rated" +) + +// The discounts applied to the line item. +type LineItemDiscount struct { + // The amount discounted. + Amount int64 `json:"amount"` + // A discount represents the actual application of a [coupon](https://stripe.com/docs/api#coupons) or [promotion code](https://stripe.com/docs/api#promotion_codes). + // It contains information about when the discount began, when it will end, and what it is applied to. + // + // Related guide: [Applying discounts to subscriptions](https://stripe.com/docs/billing/subscriptions/discounts) + Discount *Discount `json:"discount"` +} + +// The taxes applied to the line item. +type LineItemTax struct { + // Amount of tax applied for this rate. + Amount int64 `json:"amount"` + // Tax rates can be applied to [invoices](https://docs.stripe.com/invoicing/taxes/tax-rates), [subscriptions](https://docs.stripe.com/billing/taxes/tax-rates) and [Checkout Sessions](https://docs.stripe.com/payments/checkout/use-manual-tax-rates) to collect tax. + // + // Related guide: [Tax rates](https://docs.stripe.com/billing/taxes/tax-rates) + Rate *TaxRate `json:"rate"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason LineItemTaxTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount int64 `json:"taxable_amount"` +} + +// A line item. +type LineItem struct { + // Total discount amount applied. If no discounts were applied, defaults to 0. + AmountDiscount int64 `json:"amount_discount"` + // Total before any discounts or taxes are applied. + AmountSubtotal int64 `json:"amount_subtotal"` + // Total tax amount applied. If no tax was applied, defaults to 0. + AmountTax int64 `json:"amount_tax"` + // Total after discounts and taxes. + AmountTotal int64 `json:"amount_total"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. Defaults to product name. + Description string `json:"description"` + // The discounts applied to the line item. + Discounts []*LineItemDiscount `json:"discounts"` + // Unique identifier for the object. + ID string `json:"id"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The price used to generate the line item. + Price *Price `json:"price"` + // The quantity of products being purchased. + Quantity int64 `json:"quantity"` + // The taxes applied to the line item. + Taxes []*LineItemTax `json:"taxes"` +} + +// LineItemList is a list of LineItems as retrieved from a list endpoint. +type LineItemList struct { + APIResource + ListMeta + Data []*LineItem `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/log.go b/vendor/github.com/stripe/stripe-go/v82/log.go new file mode 100644 index 00000000..b52d7ac5 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/log.go @@ -0,0 +1,142 @@ +package stripe + +import ( + "fmt" + "io" + "os" +) + +// +// Public constants +// + +const ( + // LevelNull sets a logger to show no messages at all. + LevelNull Level = 0 + + // LevelError sets a logger to show error messages only. + LevelError Level = 1 + + // LevelWarn sets a logger to show warning messages or anything more + // severe. + LevelWarn Level = 2 + + // LevelInfo sets a logger to show informational messages or anything more + // severe. + LevelInfo Level = 3 + + // LevelDebug sets a logger to show informational messages or anything more + // severe. + LevelDebug Level = 4 +) + +// +// Public variables +// + +// DefaultLeveledLogger is the default logger that the library will use to log +// errors, warnings, and informational messages. +// +// LeveledLoggerInterface is implemented by LeveledLogger, and one can be +// initialized at the desired level of logging. LeveledLoggerInterface also +// provides out-of-the-box compatibility with a Logrus Logger, but may require +// a thin shim for use with other logging libraries that use less standard +// conventions like Zap. +// +// This Logger will be inherited by any backends created by default, but will +// be overridden if a backend is created with GetBackendWithConfig with a +// custom LeveledLogger set. +var DefaultLeveledLogger LeveledLoggerInterface = &LeveledLogger{ + Level: LevelError, +} + +// +// Public types +// + +// Level represents a logging level. +type Level uint32 + +// LeveledLogger is a leveled logger implementation. +// +// It prints warnings and errors to `os.Stderr` and other messages to +// `os.Stdout`. +type LeveledLogger struct { + // Level is the minimum logging level that will be emitted by this logger. + // + // For example, a Level set to LevelWarn will emit warnings and errors, but + // not informational or debug messages. + // + // Always set this with a constant like LevelWarn because the individual + // values are not guaranteed to be stable. + Level Level + + // Internal testing use only. + stderrOverride io.Writer + stdoutOverride io.Writer +} + +// Debugf logs a debug message using Printf conventions. +func (l *LeveledLogger) Debugf(format string, v ...interface{}) { + if l.Level >= LevelDebug { + fmt.Fprintf(l.stdout(), "[DEBUG] "+format+"\n", v...) + } +} + +// Errorf logs a warning message using Printf conventions. +func (l *LeveledLogger) Errorf(format string, v ...interface{}) { + // Infof logs a debug message using Printf conventions. + if l.Level >= LevelError { + fmt.Fprintf(l.stderr(), "[ERROR] "+format+"\n", v...) + } +} + +// Infof logs an informational message using Printf conventions. +func (l *LeveledLogger) Infof(format string, v ...interface{}) { + if l.Level >= LevelInfo { + fmt.Fprintf(l.stdout(), "[INFO] "+format+"\n", v...) + } +} + +// Warnf logs a warning message using Printf conventions. +func (l *LeveledLogger) Warnf(format string, v ...interface{}) { + if l.Level >= LevelWarn { + fmt.Fprintf(l.stderr(), "[WARN] "+format+"\n", v...) + } +} + +func (l *LeveledLogger) stderr() io.Writer { + if l.stderrOverride != nil { + return l.stderrOverride + } + + return os.Stderr +} + +func (l *LeveledLogger) stdout() io.Writer { + if l.stdoutOverride != nil { + return l.stdoutOverride + } + + return os.Stdout +} + +// LeveledLoggerInterface provides a basic leveled logging interface for +// printing debug, informational, warning, and error messages. +// +// It's implemented by LeveledLogger and also provides out-of-the-box +// compatibility with a Logrus Logger, but may require a thin shim for use with +// other logging libraries that you use less standard conventions like Zap. +type LeveledLoggerInterface interface { + // Debugf logs a debug message using Printf conventions. + Debugf(format string, v ...interface{}) + + // Errorf logs a warning message using Printf conventions. + Errorf(format string, v ...interface{}) + + // Infof logs an informational message using Printf conventions. + Infof(format string, v ...interface{}) + + // Warnf logs a warning message using Printf conventions. + Warnf(format string, v ...interface{}) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/loginlink.go b/vendor/github.com/stripe/stripe-go/v82/loginlink.go new file mode 100644 index 00000000..f13740ef --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/loginlink.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Creates a login link for a connected account to access the Express Dashboard. +// +// You can only create login links for accounts that use the [Express Dashboard](https://docs.stripe.com/connect/express-dashboard) and are connected to your platform. +type LoginLinkParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *LoginLinkParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates a login link for a connected account to access the Express Dashboard. +// +// You can only create login links for accounts that use the [Express Dashboard](https://docs.stripe.com/connect/express-dashboard) and are connected to your platform. +type LoginLinkCreateParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *LoginLinkCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Login Links are single-use URLs that takes an Express account to the login page for their Stripe dashboard. +// A Login Link differs from an [Account Link](https://stripe.com/docs/api/account_links) in that it takes the user directly to their [Express dashboard for the specified account](https://stripe.com/docs/connect/integrate-express-dashboard#create-login-link) +type LoginLink struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The URL for the login link. + URL string `json:"url"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/loginlink_service.go b/vendor/github.com/stripe/stripe-go/v82/loginlink_service.go new file mode 100644 index 00000000..e1a35f1d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/loginlink_service.go @@ -0,0 +1,33 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1LoginLinkService is used to invoke /v1/accounts/{account}/login_links APIs. +type v1LoginLinkService struct { + B Backend + Key string +} + +// Creates a login link for a connected account to access the Express Dashboard. +// +// You can only create login links for accounts that use the [Express Dashboard](https://docs.stripe.com/connect/express-dashboard) and are connected to your platform. +func (c v1LoginLinkService) Create(ctx context.Context, params *LoginLinkCreateParams) (*LoginLink, error) { + if params == nil { + params = &LoginLinkCreateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/login_links", StringValue(params.Account)) + loginlink := &LoginLink{} + err := c.B.Call(http.MethodPost, path, c.Key, params, loginlink) + return loginlink, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/mandate.go b/vendor/github.com/stripe/stripe-go/v82/mandate.go new file mode 100644 index 00000000..ce223534 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/mandate.go @@ -0,0 +1,270 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The mandate includes the type of customer acceptance information, such as: `online` or `offline`. +type MandateCustomerAcceptanceType string + +// List of values that MandateCustomerAcceptanceType can take +const ( + MandateCustomerAcceptanceTypeOffline MandateCustomerAcceptanceType = "offline" + MandateCustomerAcceptanceTypeOnline MandateCustomerAcceptanceType = "online" +) + +// List of Stripe products where this mandate can be selected automatically. +type MandatePaymentMethodDetailsACSSDebitDefaultFor string + +// List of values that MandatePaymentMethodDetailsACSSDebitDefaultFor can take +const ( + MandatePaymentMethodDetailsACSSDebitDefaultForInvoice MandatePaymentMethodDetailsACSSDebitDefaultFor = "invoice" + MandatePaymentMethodDetailsACSSDebitDefaultForSubscription MandatePaymentMethodDetailsACSSDebitDefaultFor = "subscription" +) + +// Payment schedule for the mandate. +type MandatePaymentMethodDetailsACSSDebitPaymentSchedule string + +// List of values that MandatePaymentMethodDetailsACSSDebitPaymentSchedule can take +const ( + MandatePaymentMethodDetailsACSSDebitPaymentScheduleCombined MandatePaymentMethodDetailsACSSDebitPaymentSchedule = "combined" + MandatePaymentMethodDetailsACSSDebitPaymentScheduleInterval MandatePaymentMethodDetailsACSSDebitPaymentSchedule = "interval" + MandatePaymentMethodDetailsACSSDebitPaymentScheduleSporadic MandatePaymentMethodDetailsACSSDebitPaymentSchedule = "sporadic" +) + +// Transaction type of the mandate. +type MandatePaymentMethodDetailsACSSDebitTransactionType string + +// List of values that MandatePaymentMethodDetailsACSSDebitTransactionType can take +const ( + MandatePaymentMethodDetailsACSSDebitTransactionTypeBusiness MandatePaymentMethodDetailsACSSDebitTransactionType = "business" + MandatePaymentMethodDetailsACSSDebitTransactionTypePersonal MandatePaymentMethodDetailsACSSDebitTransactionType = "personal" +) + +// The status of the mandate on the Bacs network. Can be one of `pending`, `revoked`, `refused`, or `accepted`. +type MandatePaymentMethodDetailsBACSDebitNetworkStatus string + +// List of values that MandatePaymentMethodDetailsBACSDebitNetworkStatus can take +const ( + MandatePaymentMethodDetailsBACSDebitNetworkStatusAccepted MandatePaymentMethodDetailsBACSDebitNetworkStatus = "accepted" + MandatePaymentMethodDetailsBACSDebitNetworkStatusPending MandatePaymentMethodDetailsBACSDebitNetworkStatus = "pending" + MandatePaymentMethodDetailsBACSDebitNetworkStatusRefused MandatePaymentMethodDetailsBACSDebitNetworkStatus = "refused" + MandatePaymentMethodDetailsBACSDebitNetworkStatusRevoked MandatePaymentMethodDetailsBACSDebitNetworkStatus = "revoked" +) + +// When the mandate is revoked on the Bacs network this field displays the reason for the revocation. +type MandatePaymentMethodDetailsBACSDebitRevocationReason string + +// List of values that MandatePaymentMethodDetailsBACSDebitRevocationReason can take +const ( + MandatePaymentMethodDetailsBACSDebitRevocationReasonAccountClosed MandatePaymentMethodDetailsBACSDebitRevocationReason = "account_closed" + MandatePaymentMethodDetailsBACSDebitRevocationReasonBankAccountRestricted MandatePaymentMethodDetailsBACSDebitRevocationReason = "bank_account_restricted" + MandatePaymentMethodDetailsBACSDebitRevocationReasonBankOwnershipChanged MandatePaymentMethodDetailsBACSDebitRevocationReason = "bank_ownership_changed" + MandatePaymentMethodDetailsBACSDebitRevocationReasonCouldNotProcess MandatePaymentMethodDetailsBACSDebitRevocationReason = "could_not_process" + MandatePaymentMethodDetailsBACSDebitRevocationReasonDebitNotAuthorized MandatePaymentMethodDetailsBACSDebitRevocationReason = "debit_not_authorized" +) + +// This mandate corresponds with a specific payment method type. The `payment_method_details` includes an additional hash with the same name and contains mandate information that's specific to that payment method. +type MandatePaymentMethodDetailsType string + +// List of values that MandatePaymentMethodDetailsType can take +const ( + MandatePaymentMethodDetailsTypeACSSDebit MandatePaymentMethodDetailsType = "acss_debit" + MandatePaymentMethodDetailsTypeAUBECSDebit MandatePaymentMethodDetailsType = "au_becs_debit" + MandatePaymentMethodDetailsTypeBACSDebit MandatePaymentMethodDetailsType = "bacs_debit" + MandatePaymentMethodDetailsTypeBLIK MandatePaymentMethodDetailsType = "blik" + MandatePaymentMethodDetailsTypeCard MandatePaymentMethodDetailsType = "card" + MandatePaymentMethodDetailsTypeLink MandatePaymentMethodDetailsType = "link" + MandatePaymentMethodDetailsTypeSEPADebit MandatePaymentMethodDetailsType = "sepa_debit" + MandatePaymentMethodDetailsTypeUSBankAccount MandatePaymentMethodDetailsType = "us_bank_account" +) + +// Mandate collection method +type MandatePaymentMethodDetailsUSBankAccountCollectionMethod string + +// List of values that MandatePaymentMethodDetailsUSBankAccountCollectionMethod can take +const ( + MandatePaymentMethodDetailsUSBankAccountCollectionMethodPaper MandatePaymentMethodDetailsUSBankAccountCollectionMethod = "paper" +) + +// The mandate status indicates whether or not you can use it to initiate a payment. +type MandateStatus string + +// List of values that MandateStatus can take +const ( + MandateStatusActive MandateStatus = "active" + MandateStatusInactive MandateStatus = "inactive" + MandateStatusPending MandateStatus = "pending" +) + +// The type of the mandate. +type MandateType string + +// List of values that MandateType can take +const ( + MandateTypeMultiUse MandateType = "multi_use" + MandateTypeSingleUse MandateType = "single_use" +) + +// Retrieves a Mandate object. +type MandateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *MandateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a Mandate object. +type MandateRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *MandateRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type MandateCustomerAcceptanceOffline struct{} +type MandateCustomerAcceptanceOnline struct { + // The customer accepts the mandate from this IP address. + IPAddress string `json:"ip_address"` + // The customer accepts the mandate using the user agent of the browser. + UserAgent string `json:"user_agent"` +} +type MandateCustomerAcceptance struct { + // The time that the customer accepts the mandate. + AcceptedAt int64 `json:"accepted_at"` + Offline *MandateCustomerAcceptanceOffline `json:"offline"` + Online *MandateCustomerAcceptanceOnline `json:"online"` + // The mandate includes the type of customer acceptance information, such as: `online` or `offline`. + Type MandateCustomerAcceptanceType `json:"type"` +} +type MandateMultiUse struct{} +type MandatePaymentMethodDetailsACSSDebit struct { + // List of Stripe products where this mandate can be selected automatically. + DefaultFor []MandatePaymentMethodDetailsACSSDebitDefaultFor `json:"default_for"` + // Description of the interval. Only required if the 'payment_schedule' parameter is 'interval' or 'combined'. + IntervalDescription string `json:"interval_description"` + // Payment schedule for the mandate. + PaymentSchedule MandatePaymentMethodDetailsACSSDebitPaymentSchedule `json:"payment_schedule"` + // Transaction type of the mandate. + TransactionType MandatePaymentMethodDetailsACSSDebitTransactionType `json:"transaction_type"` +} +type MandatePaymentMethodDetailsAmazonPay struct{} +type MandatePaymentMethodDetailsAUBECSDebit struct { + // The URL of the mandate. This URL generally contains sensitive information about the customer and should be shared with them exclusively. + URL string `json:"url"` +} +type MandatePaymentMethodDetailsBACSDebit struct { + // The status of the mandate on the Bacs network. Can be one of `pending`, `revoked`, `refused`, or `accepted`. + NetworkStatus MandatePaymentMethodDetailsBACSDebitNetworkStatus `json:"network_status"` + // The unique reference identifying the mandate on the Bacs network. + Reference string `json:"reference"` + // When the mandate is revoked on the Bacs network this field displays the reason for the revocation. + RevocationReason MandatePaymentMethodDetailsBACSDebitRevocationReason `json:"revocation_reason"` + // The URL that will contain the mandate that the customer has signed. + URL string `json:"url"` +} +type MandatePaymentMethodDetailsCard struct{} +type MandatePaymentMethodDetailsCashApp struct{} +type MandatePaymentMethodDetailsKakaoPay struct{} +type MandatePaymentMethodDetailsKlarna struct{} +type MandatePaymentMethodDetailsKrCard struct{} +type MandatePaymentMethodDetailsLink struct{} +type MandatePaymentMethodDetailsNaverPay struct{} +type MandatePaymentMethodDetailsNzBankAccount struct{} +type MandatePaymentMethodDetailsPaypal struct { + // The PayPal Billing Agreement ID (BAID). This is an ID generated by PayPal which represents the mandate between the merchant and the customer. + BillingAgreementID string `json:"billing_agreement_id"` + // PayPal account PayerID. This identifier uniquely identifies the PayPal customer. + PayerID string `json:"payer_id"` +} +type MandatePaymentMethodDetailsRevolutPay struct{} +type MandatePaymentMethodDetailsSEPADebit struct { + // The unique reference of the mandate. + Reference string `json:"reference"` + // The URL of the mandate. This URL generally contains sensitive information about the customer and should be shared with them exclusively. + URL string `json:"url"` +} +type MandatePaymentMethodDetailsUSBankAccount struct { + // Mandate collection method + CollectionMethod MandatePaymentMethodDetailsUSBankAccountCollectionMethod `json:"collection_method"` +} +type MandatePaymentMethodDetails struct { + ACSSDebit *MandatePaymentMethodDetailsACSSDebit `json:"acss_debit"` + AmazonPay *MandatePaymentMethodDetailsAmazonPay `json:"amazon_pay"` + AUBECSDebit *MandatePaymentMethodDetailsAUBECSDebit `json:"au_becs_debit"` + BACSDebit *MandatePaymentMethodDetailsBACSDebit `json:"bacs_debit"` + Card *MandatePaymentMethodDetailsCard `json:"card"` + CashApp *MandatePaymentMethodDetailsCashApp `json:"cashapp"` + KakaoPay *MandatePaymentMethodDetailsKakaoPay `json:"kakao_pay"` + Klarna *MandatePaymentMethodDetailsKlarna `json:"klarna"` + KrCard *MandatePaymentMethodDetailsKrCard `json:"kr_card"` + Link *MandatePaymentMethodDetailsLink `json:"link"` + NaverPay *MandatePaymentMethodDetailsNaverPay `json:"naver_pay"` + NzBankAccount *MandatePaymentMethodDetailsNzBankAccount `json:"nz_bank_account"` + Paypal *MandatePaymentMethodDetailsPaypal `json:"paypal"` + RevolutPay *MandatePaymentMethodDetailsRevolutPay `json:"revolut_pay"` + SEPADebit *MandatePaymentMethodDetailsSEPADebit `json:"sepa_debit"` + // This mandate corresponds with a specific payment method type. The `payment_method_details` includes an additional hash with the same name and contains mandate information that's specific to that payment method. + Type MandatePaymentMethodDetailsType `json:"type"` + USBankAccount *MandatePaymentMethodDetailsUSBankAccount `json:"us_bank_account"` +} +type MandateSingleUse struct { + // The amount of the payment on a single use mandate. + Amount int64 `json:"amount"` + // The currency of the payment on a single use mandate. + Currency Currency `json:"currency"` +} + +// A Mandate is a record of the permission that your customer gives you to debit their payment method. +type Mandate struct { + APIResource + CustomerAcceptance *MandateCustomerAcceptance `json:"customer_acceptance"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + MultiUse *MandateMultiUse `json:"multi_use"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The account (if any) that the mandate is intended for. + OnBehalfOf string `json:"on_behalf_of"` + // ID of the payment method associated with this mandate. + PaymentMethod *PaymentMethod `json:"payment_method"` + PaymentMethodDetails *MandatePaymentMethodDetails `json:"payment_method_details"` + SingleUse *MandateSingleUse `json:"single_use"` + // The mandate status indicates whether or not you can use it to initiate a payment. + Status MandateStatus `json:"status"` + // The type of the mandate. + Type MandateType `json:"type"` +} + +// UnmarshalJSON handles deserialization of a Mandate. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (m *Mandate) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + m.ID = id + return nil + } + + type mandate Mandate + var v mandate + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *m = Mandate(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/mandate_service.go b/vendor/github.com/stripe/stripe-go/v82/mandate_service.go new file mode 100644 index 00000000..75b57bd0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/mandate_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1MandateService is used to invoke /v1/mandates APIs. +type v1MandateService struct { + B Backend + Key string +} + +// Retrieves a Mandate object. +func (c v1MandateService) Retrieve(ctx context.Context, id string, params *MandateRetrieveParams) (*Mandate, error) { + if params == nil { + params = &MandateRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/mandates/%s", id) + mandate := &Mandate{} + err := c.B.Call(http.MethodGet, path, c.Key, params, mandate) + return mandate, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/oauth.go b/vendor/github.com/stripe/stripe-go/v82/oauth.go new file mode 100644 index 00000000..32f11f18 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/oauth.go @@ -0,0 +1,132 @@ +package stripe + +// OAuthScopeType is the type of OAuth scope. +type OAuthScopeType string + +// List of possible values for OAuth scopes. +const ( + OAuthScopeTypeReadOnly OAuthScopeType = "read_only" + OAuthScopeTypeReadWrite OAuthScopeType = "read_write" +) + +// OAuthTokenType is the type of token. This will always be "bearer." +type OAuthTokenType string + +// List of possible OAuthTokenType values. +const ( + OAuthTokenTypeBearer OAuthTokenType = "bearer" +) + +// OAuthStripeUserBusinessType is the business type for the Stripe oauth user. +type OAuthStripeUserBusinessType string + +// List of supported values for business type. +const ( + OAuthStripeUserBusinessTypeCorporation OAuthStripeUserBusinessType = "corporation" + OAuthStripeUserBusinessTypeLLC OAuthStripeUserBusinessType = "llc" + OAuthStripeUserBusinessTypeNonProfit OAuthStripeUserBusinessType = "non_profit" + OAuthStripeUserBusinessTypePartnership OAuthStripeUserBusinessType = "partnership" + OAuthStripeUserBusinessTypeSoleProp OAuthStripeUserBusinessType = "sole_prop" +) + +// OAuthStripeUserGender of the person who will be filling out a Stripe +// application. (International regulations require either male or female.) +type OAuthStripeUserGender string + +// The gender of the person who will be filling out a Stripe application. +// (International regulations require either male or female.) +const ( + OAuthStripeUserGenderFemale OAuthStripeUserGender = "female" + OAuthStripeUserGenderMale OAuthStripeUserGender = "male" +) + +// OAuthStripeUserParams for the stripe_user OAuth Authorize params. +type OAuthStripeUserParams struct { + BlockKana *string `form:"block_kana"` + BlockKanji *string `form:"block_kanji"` + BuildingKana *string `form:"building_kana"` + BuildingKanji *string `form:"building_kanji"` + BusinessName *string `form:"business_name"` + BusinessType *string `form:"business_type"` + City *string `form:"city"` + Country *string `form:"country"` + Currency *string `form:"currency"` + DOBDay *int64 `form:"dob_day"` + DOBMonth *int64 `form:"dob_month"` + DOBYear *int64 `form:"dob_year"` + Email *string `form:"email"` + FirstName *string `form:"first_name"` + FirstNameKana *string `form:"first_name_kana"` + FirstNameKanji *string `form:"first_name_kanji"` + Gender *string `form:"gender"` + LastName *string `form:"last_name"` + LastNameKana *string `form:"last_name_kana"` + LastNameKanji *string `form:"last_name_kanji"` + PhoneNumber *string `form:"phone_number"` + PhysicalProduct *bool `form:"physical_product"` + ProductDescription *string `form:"product_description"` + State *string `form:"state"` + StreetAddress *string `form:"street_address"` + URL *string `form:"url"` + Zip *string `form:"zip"` +} + +// AuthorizeURLParams for creating OAuth AuthorizeURLs. +type AuthorizeURLParams struct { + Params `form:"*"` + AlwaysPrompt *bool `form:"always_prompt"` + ClientID *string `form:"client_id"` + RedirectURI *string `form:"redirect_uri"` + ResponseType *string `form:"response_type"` + Scope *string `form:"scope"` + State *string `form:"state"` + StripeLanding *string `form:"stripe_landing"` + StripeUser *OAuthStripeUserParams `form:"stripe_user"` + SuggestedCapabilities []*string `form:"suggested_capabilities"` + + // Express is not sent as a parameter, but is used to modify the authorize URL + // path to use the express OAuth path. + Express *bool `form:"-"` +} + +// DeauthorizeParams for deauthorizing an account. +type DeauthorizeParams struct { + Params `form:"*"` + ClientID *string `form:"client_id"` + StripeUserID *string `form:"stripe_user_id"` +} + +// OAuthTokenParams is the set of paramaters that can be used to request +// OAuthTokens. +type OAuthTokenParams struct { + Params `form:"*"` + AssertCapabilities []*string `form:"assert_capabilities"` + ClientSecret *string `form:"client_secret"` + Code *string `form:"code"` + GrantType *string `form:"grant_type"` + RefreshToken *string `form:"refresh_token"` + Scope *string `form:"scope"` +} + +// OAuthToken is the value of the OAuthToken from OAuth flow. +// https://stripe.com/docs/connect/oauth-reference#post-token +type OAuthToken struct { + APIResource + + Livemode bool `json:"livemode"` + Scope OAuthScopeType `json:"scope"` + StripeUserID string `json:"stripe_user_id"` + TokenType OAuthTokenType `json:"token_type"` + + // Deprecated, please use StripeUserID + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + StripePublishableKey string `json:"stripe_publishable_key"` +} + +// Deauthorize is the value of the return from deauthorizing. +// https://stripe.com/docs/connect/oauth-reference#post-deauthorize +type Deauthorize struct { + APIResource + StripeUserID string `json:"stripe_user_id"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/oauth_service.go b/vendor/github.com/stripe/stripe-go/v82/oauth_service.go new file mode 100644 index 00000000..6886a007 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/oauth_service.go @@ -0,0 +1,51 @@ +package stripe + +import ( + "context" + "fmt" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// oauthService is used to invoke /oauth and related APIs. +type oauthService struct { + B Backend + Key string +} + +// AuthorizeURL builds an OAuth authorize URL. +func (c oauthService) AuthorizeURL(params *AuthorizeURLParams) string { + express := "" + if BoolValue(params.Express) { + express = "/express" + } + qs := &form.Values{} + form.AppendTo(qs, params) + return fmt.Sprintf("%s%s/oauth/authorize?%s", ConnectURL, express, qs.Encode()) +} + +// Create creates an OAuth token using a code after successful redirection back. +func (c oauthService) Create(ctx context.Context, params *OAuthTokenParams) (*OAuthToken, error) { + if params == nil { + params = &OAuthTokenParams{} + } + params.Context = ctx + if params.ClientSecret == nil { + params.ClientSecret = String(c.Key) + } + oauthToken := &OAuthToken{} + err := c.B.Call(http.MethodPost, "/oauth/token", c.Key, params, oauthToken) + return oauthToken, err +} + +// Delete deauthorizes a connected account. +func (c oauthService) Delete(ctx context.Context, params *DeauthorizeParams) (*Deauthorize, error) { + if params == nil { + params = &DeauthorizeParams{} + } + params.Context = ctx + deauthorization := &Deauthorize{} + err := c.B.Call(http.MethodPost, "/oauth/deauthorize", c.Key, params, deauthorization) + return deauthorization, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/params.go b/vendor/github.com/stripe/stripe-go/v82/params.go new file mode 100644 index 00000000..f1e33b62 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/params.go @@ -0,0 +1,355 @@ +package stripe + +import ( + "context" + "crypto/rand" + "encoding/base64" + "fmt" + "net/http" + "net/url" + "time" + + "github.com/stripe/stripe-go/v82/form" +) + +// +// Public constants +// + +// Contains constants for the names of parameters used for pagination in list APIs. +const ( + EndingBefore = "ending_before" + StartingAfter = "starting_after" +) + +// +// Public types +// + +// ExtraValues are extra parameters that are attached to an API request. +// They're implemented as a custom type so that they can have their own +// AppendTo implementation. +type ExtraValues struct { + url.Values `form:"-" json:"-"` // See custom AppendTo implementation +} + +// AppendTo implements custom form encoding for extra parameter values. +func (v ExtraValues) AppendTo(body *form.Values, keyParts []string) { + for k, vs := range v.Values { + for _, v := range vs { + body.Add(form.FormatKey(append(keyParts, k)), v) + } + } +} + +// Filters is a structure that contains a collection of filters for list-related APIs. +type Filters struct { + f []*filter `form:"-" json:"-"` // See custom AppendTo implementation +} + +// AddFilter adds a new filter with a given key, op and value. +func (f *Filters) AddFilter(key, op, value string) { + filter := &filter{Key: key, Op: op, Val: value} + f.f = append(f.f, filter) +} + +// AppendTo implements custom form encoding for filters. +func (f Filters) AppendTo(body *form.Values, keyParts []string) { + if len(f.f) > 0 { + for _, v := range f.f { + if len(v.Op) > 0 { + body.Add(form.FormatKey(append(keyParts, v.Key, v.Op)), v.Val) + } else { + body.Add(form.FormatKey(append(keyParts, v.Key)), v.Val) + } + } + } +} + +// ListContainer is a general interface for which all list object structs +// should comply. They achieve this by embedding a ListMeta struct and +// inheriting its implementation of this interface. +type ListContainer interface { + GetListMeta() *ListMeta +} + +// ListMeta is the structure that contains the common properties +// of List iterators. The Count property is only populated if the +// total_count include option is passed in (see tests for example). +type ListMeta struct { + HasMore bool `json:"has_more"` + URL string `json:"url"` + + // TotalCount is the total number of objects in the collection (beyond just + // on the current page). This is not returned in most list calls. + // + // Deprecated: TotalCount is only included in some legacy situations and + // not generally available anymore. + TotalCount uint32 `json:"total_count"` +} + +// GetListMeta returns a ListMeta struct (itself). It exists because any +// structs that embed ListMeta will inherit it, and thus implement the +// ListContainer interface. +func (l *ListMeta) GetListMeta() *ListMeta { + return l +} + +// ListParams is the structure that contains the common properties +// of any *ListParams structure. +type ListParams struct { + // Context used for request. It may carry deadlines, cancelation signals, + // and other request-scoped values across API boundaries and between + // processes. + // + // Note that a cancelled or timed out context does not provide any + // guarantee whether the operation was or was not completed on Stripe's API + // servers. For certainty, you must either retry with the same idempotency + // key or query the state of the API. + Context context.Context `form:"-"` + + EndingBefore *string `form:"ending_before"` + // Deprecated: Please use Expand in the surrounding struct instead. + Expand []*string `form:"expand"` + Filters Filters `form:"*"` + Limit *int64 `form:"limit"` + + // Single specifies whether this is a single page iterator. By default, + // listing through an iterator will automatically grab additional pages as + // the query progresses. To change this behavior and just load a single + // page, set this to true. + Single bool `form:"-"` // Not an API parameter + + StartingAfter *string `form:"starting_after"` + + // StripeAccount may contain the ID of a connected account. By including + // this field, the request is made as if it originated from the connected + // account instead of under the account of the owner of the configured + // Stripe key. + StripeAccount *string `form:"-"` // Passed as header +} + +// AddExpand on the embedded ListParams struct is deprecated. +// Deprecated: please use AddExpand on the surrounding struct instead. +func (p *ListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// GetListParams returns a ListParams struct (itself). It exists because any +// structs that embed ListParams will inherit it, and thus implement the +// ListParamsContainer interface. +func (p *ListParams) GetListParams() *ListParams { + return p +} + +// GetParams returns ListParams as a Params struct. It exists because any +// structs that embed Params will inherit it, and thus implement the +// ParamsContainer interface. +func (p *ListParams) GetParams() *Params { + return p.ToParams() +} + +// SetStripeAccount sets a value for the Stripe-Account header. +func (p *ListParams) SetStripeAccount(val string) { + p.StripeAccount = &val +} + +// ToParams converts a ListParams to a Params by moving over any fields that +// have valid targets in the new type. This is useful because fields in +// Params can be injected directly into an http.Request while generally +// ListParams is only used to build a set of parameters. +func (p *ListParams) ToParams() *Params { + return &Params{ + Context: p.Context, + StripeAccount: p.StripeAccount, + } +} + +// ListParamsContainer is a general interface for which all list parameter +// structs should comply. They achieve this by embedding a ListParams struct +// and inheriting its implementation of this interface. +type ListParamsContainer interface { + GetListParams() *ListParams +} + +type APIMode string + +var V1APIMode APIMode = "v1" +var V2APIMode APIMode = "v2" + +func (m APIMode) contentType() string { + switch m { + case V1APIMode: + return "application/x-www-form-urlencoded" + case V2APIMode: + return "application/json" + default: + // The only way we can get here is if someone has mutated the APIMode + // variables, which would lead to unexpected behavior. + panic("unknown API mode") + } +} + +// Params is the structure that contains the common properties +// of any *Params structure. +type Params struct { + // Context used for request. It may carry deadlines, cancelation signals, + // and other request-scoped values across API boundaries and between + // processes. + // + // Note that a cancelled or timed out context does not provide any + // guarantee whether the operation was or was not completed on Stripe's API + // servers. For certainty, you must either retry with the same idempotency + // key or query the state of the API. + Context context.Context `form:"-" json:"-"` + + // Deprecated: please use Expand in the surrounding struct instead. + Expand []*string `form:"expand" json:"-"` + Extra *ExtraValues `form:"*" json:"-"` + + // Headers may be used to provide extra header lines on the HTTP request. + Headers http.Header `form:"-" json:"-"` + + IdempotencyKey *string `form:"-" json:"-"` // Passed as header + + // Deprecated: Please use Metadata in the surrounding struct instead. + Metadata map[string]string `form:"metadata" json:"-"` + + // StripeAccount may contain the ID of a connected account. By including + // this field, the request is made as if it originated from the connected + // account instead of under the account of the owner of the configured + // Stripe key. + StripeAccount *string `form:"-" json:"-"` // Passed as header + + // StripeContext is used to set the Stripe-Context header on a request. + // The Stripe-Context header can be used to set the account with which + // the request is made. + StripeContext *string `form:"-" json:"-"` // Passed as header + + usage []string `form:"-" json:"-"` // Tracked behaviors +} + +// AddExpand on the Params embedded struct is deprecated. +// Deprecated: please use Expand in the surrounding struct instead. +func (p *Params) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// InternalSetUsage sets the usage field on the Params struct, removing duplicates. +// Unstable: for internal stripe-go usage only. +func (p *Params) InternalSetUsage(usage []string) { + // Optimization for nil or empty usage + if len(usage) == 0 { + return + } + + // Use a map to track unique usage values + usageMap := make(map[string]struct{}) + for _, u := range p.usage { + usageMap[u] = struct{}{} + } + for _, u := range usage { + usageMap[u] = struct{}{} + } + p.usage = p.usage[:0] // Reset the slice to avoid retaining old values + for u := range usageMap { + p.usage = append(p.usage, u) + } +} + +// AddExtra adds a new arbitrary key-value pair to the request data +func (p *Params) AddExtra(key, value string) { + if p.Extra == nil { + p.Extra = &ExtraValues{Values: make(url.Values)} + } + + p.Extra.Add(key, value) +} + +// AddMetadata on the Params embedded struct is deprecated. +// Deprecated: please use .AddMetadata of the surrounding struct. +func (p *Params) AddMetadata(key, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// GetParams returns a Params struct (itself). It exists because any structs +// that embed Params will inherit it, and thus implement the ParamsContainer +// interface. +func (p *Params) GetParams() *Params { + return p +} + +// SetIdempotencyKey sets a value for the Idempotency-Key header. +func (p *Params) SetIdempotencyKey(val string) { + p.IdempotencyKey = &val +} + +// SetStripeAccount sets a value for the Stripe-Account header. +func (p *Params) SetStripeAccount(val string) { + p.StripeAccount = &val +} + +// SetStripeContext sets a value for the Stripe-Context header. +func (p *Params) SetStripeContext(val string) { + p.StripeContext = &val +} + +// ParamsContainer is a general interface for which all parameter structs +// should comply. They achieve this by embedding a Params struct and inheriting +// its implementation of this interface. +type ParamsContainer interface { + GetParams() *Params +} + +type RawParams struct { + Params `form:"*"` + StripeContext string `form:"-"` +} + +// RangeQueryParams are a set of generic request parameters that are used on +// list endpoints to filter their results by some timestamp. +type RangeQueryParams struct { + // GreaterThan specifies that values should be a greater than this + // timestamp. + GreaterThan int64 `form:"gt"` + + // GreaterThanOrEqual specifies that values should be greater than or equal + // to this timestamp. + GreaterThanOrEqual int64 `form:"gte"` + + // LesserThan specifies that values should be lesser than this timetamp. + LesserThan int64 `form:"lt"` + + // LesserThanOrEqual specifies that values should be lesser than or + // equalthis timetamp. + LesserThanOrEqual int64 `form:"lte"` +} + +// +// Public functions +// + +// NewIdempotencyKey generates a new idempotency key that +// can be used on a request. +func NewIdempotencyKey() string { + now := time.Now().UnixNano() + buf := make([]byte, 4) + if _, err := rand.Read(buf); err != nil { + panic(err) + } + return fmt.Sprintf("%v_%v", now, base64.URLEncoding.EncodeToString(buf)[:6]) +} + +// +// Private types +// + +// filter is the structure that contains a filter for list-related APIs. +// It ends up passing query string parameters in the format key[op]=value. +type filter struct { + Key, Op, Val string +} diff --git a/vendor/github.com/stripe/stripe-go/v82/paymentintent.go b/vendor/github.com/stripe/stripe-go/v82/paymentintent.go new file mode 100644 index 00000000..22dd1216 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/paymentintent.go @@ -0,0 +1,7073 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Controls whether this PaymentIntent will accept redirect-based payment methods. +// +// Redirect-based payment methods may require your customer to be redirected to a payment method's app or site for authentication or additional steps. To [confirm](https://stripe.com/docs/api/payment_intents/confirm) this PaymentIntent, you may be required to provide a `return_url` to redirect customers back to your site after they authenticate or complete the payment. +type PaymentIntentAutomaticPaymentMethodsAllowRedirects string + +// List of values that PaymentIntentAutomaticPaymentMethodsAllowRedirects can take +const ( + PaymentIntentAutomaticPaymentMethodsAllowRedirectsAlways PaymentIntentAutomaticPaymentMethodsAllowRedirects = "always" + PaymentIntentAutomaticPaymentMethodsAllowRedirectsNever PaymentIntentAutomaticPaymentMethodsAllowRedirects = "never" +) + +// Reason for cancellation of this PaymentIntent, either user-provided (`duplicate`, `fraudulent`, `requested_by_customer`, or `abandoned`) or generated by Stripe internally (`failed_invoice`, `void_invoice`, `automatic`, or `expired`). +type PaymentIntentCancellationReason string + +// List of values that PaymentIntentCancellationReason can take +const ( + PaymentIntentCancellationReasonAbandoned PaymentIntentCancellationReason = "abandoned" + PaymentIntentCancellationReasonAutomatic PaymentIntentCancellationReason = "automatic" + PaymentIntentCancellationReasonDuplicate PaymentIntentCancellationReason = "duplicate" + PaymentIntentCancellationReasonExpired PaymentIntentCancellationReason = "expired" + PaymentIntentCancellationReasonFailedInvoice PaymentIntentCancellationReason = "failed_invoice" + PaymentIntentCancellationReasonFraudulent PaymentIntentCancellationReason = "fraudulent" + PaymentIntentCancellationReasonRequestedByCustomer PaymentIntentCancellationReason = "requested_by_customer" + PaymentIntentCancellationReasonVoidInvoice PaymentIntentCancellationReason = "void_invoice" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentCaptureMethod string + +// List of values that PaymentIntentCaptureMethod can take +const ( + PaymentIntentCaptureMethodAutomatic PaymentIntentCaptureMethod = "automatic" + PaymentIntentCaptureMethodAutomaticAsync PaymentIntentCaptureMethod = "automatic_async" + PaymentIntentCaptureMethodManual PaymentIntentCaptureMethod = "manual" +) + +// Describes whether we can confirm this PaymentIntent automatically, or if it requires customer action to confirm the payment. +type PaymentIntentConfirmationMethod string + +// List of values that PaymentIntentConfirmationMethod can take +const ( + PaymentIntentConfirmationMethodAutomatic PaymentIntentConfirmationMethod = "automatic" + PaymentIntentConfirmationMethodManual PaymentIntentConfirmationMethod = "manual" +) + +// The payment networks supported by this FinancialAddress +type PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetwork string + +// List of values that PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetwork can take +const ( + PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetworkACH PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetwork = "ach" + PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetworkBACS PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetwork = "bacs" + PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetworkDomesticWireUS PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetwork = "domestic_wire_us" + PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetworkFPS PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetwork = "fps" + PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetworkSEPA PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetwork = "sepa" + PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetworkSpei PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetwork = "spei" + PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetworkSwift PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetwork = "swift" + PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetworkZengin PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetwork = "zengin" +) + +// The type of financial address +type PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressType string + +// List of values that PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressType can take +const ( + PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressTypeABA PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressType = "aba" + PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressTypeIBAN PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressType = "iban" + PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressTypeSortCode PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressType = "sort_code" + PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressTypeSpei PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressType = "spei" + PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressTypeSwift PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressType = "swift" + PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressTypeZengin PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressType = "zengin" +) + +// Type of bank transfer +type PaymentIntentNextActionDisplayBankTransferInstructionsType string + +// List of values that PaymentIntentNextActionDisplayBankTransferInstructionsType can take +const ( + PaymentIntentNextActionDisplayBankTransferInstructionsTypeEUBankTransfer PaymentIntentNextActionDisplayBankTransferInstructionsType = "eu_bank_transfer" + PaymentIntentNextActionDisplayBankTransferInstructionsTypeGBBankTransfer PaymentIntentNextActionDisplayBankTransferInstructionsType = "gb_bank_transfer" + PaymentIntentNextActionDisplayBankTransferInstructionsTypeJPBankTransfer PaymentIntentNextActionDisplayBankTransferInstructionsType = "jp_bank_transfer" + PaymentIntentNextActionDisplayBankTransferInstructionsTypeMXBankTransfer PaymentIntentNextActionDisplayBankTransferInstructionsType = "mx_bank_transfer" + PaymentIntentNextActionDisplayBankTransferInstructionsTypeUSBankTransfer PaymentIntentNextActionDisplayBankTransferInstructionsType = "us_bank_transfer" +) + +// Type of the next action to perform. Refer to the other child attributes under `next_action` for available values. Examples include: `redirect_to_url`, `use_stripe_sdk`, `alipay_handle_redirect`, `oxxo_display_details`, or `verify_with_microdeposits`. +type PaymentIntentNextActionType string + +// List of values that PaymentIntentNextActionType can take +const ( + PaymentIntentNextActionTypeAlipayHandleRedirect PaymentIntentNextActionType = "alipay_handle_redirect" + PaymentIntentNextActionTypeOXXODisplayDetails PaymentIntentNextActionType = "oxxo_display_details" + PaymentIntentNextActionTypeRedirectToURL PaymentIntentNextActionType = "redirect_to_url" + PaymentIntentNextActionTypeUseStripeSDK PaymentIntentNextActionType = "use_stripe_sdk" + PaymentIntentNextActionTypeVerifyWithMicrodeposits PaymentIntentNextActionType = "verify_with_microdeposits" +) + +// The type of the microdeposit sent to the customer. Used to distinguish between different verification methods. +type PaymentIntentNextActionVerifyWithMicrodepositsMicrodepositType string + +// List of values that PaymentIntentNextActionVerifyWithMicrodepositsMicrodepositType can take +const ( + PaymentIntentNextActionVerifyWithMicrodepositsMicrodepositTypeAmounts PaymentIntentNextActionVerifyWithMicrodepositsMicrodepositType = "amounts" + PaymentIntentNextActionVerifyWithMicrodepositsMicrodepositTypeDescriptorCode PaymentIntentNextActionVerifyWithMicrodepositsMicrodepositType = "descriptor_code" +) + +// Payment schedule for the mandate. +type PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule string + +// List of values that PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule can take +const ( + PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentScheduleCombined PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule = "combined" + PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentScheduleInterval PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule = "interval" + PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentScheduleSporadic PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule = "sporadic" +) + +// Transaction type of the mandate. +type PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsTransactionType string + +// List of values that PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsTransactionType can take +const ( + PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsTransactionTypeBusiness PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsTransactionType = "business" + PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsTransactionTypePersonal PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsTransactionType = "personal" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsACSSDebitSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsACSSDebitSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsACSSDebitSetupFutureUsageNone PaymentIntentPaymentMethodOptionsACSSDebitSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsACSSDebitSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsACSSDebitSetupFutureUsage = "off_session" + PaymentIntentPaymentMethodOptionsACSSDebitSetupFutureUsageOnSession PaymentIntentPaymentMethodOptionsACSSDebitSetupFutureUsage = "on_session" +) + +// Bank account verification method. +type PaymentIntentPaymentMethodOptionsACSSDebitVerificationMethod string + +// List of values that PaymentIntentPaymentMethodOptionsACSSDebitVerificationMethod can take +const ( + PaymentIntentPaymentMethodOptionsACSSDebitVerificationMethodAutomatic PaymentIntentPaymentMethodOptionsACSSDebitVerificationMethod = "automatic" + PaymentIntentPaymentMethodOptionsACSSDebitVerificationMethodInstant PaymentIntentPaymentMethodOptionsACSSDebitVerificationMethod = "instant" + PaymentIntentPaymentMethodOptionsACSSDebitVerificationMethodMicrodeposits PaymentIntentPaymentMethodOptionsACSSDebitVerificationMethod = "microdeposits" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsAffirmCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsAffirmCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsAffirmCaptureMethodManual PaymentIntentPaymentMethodOptionsAffirmCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsAffirmSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsAffirmSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsAffirmSetupFutureUsageNone PaymentIntentPaymentMethodOptionsAffirmSetupFutureUsage = "none" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsAfterpayClearpayCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsAfterpayClearpayCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsAfterpayClearpayCaptureMethodManual PaymentIntentPaymentMethodOptionsAfterpayClearpayCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsAfterpayClearpaySetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsAfterpayClearpaySetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsAfterpayClearpaySetupFutureUsageNone PaymentIntentPaymentMethodOptionsAfterpayClearpaySetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsAlipaySetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsAlipaySetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsAlipaySetupFutureUsageNone PaymentIntentPaymentMethodOptionsAlipaySetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsAlipaySetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsAlipaySetupFutureUsage = "off_session" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsAlmaCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsAlmaCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsAlmaCaptureMethodManual PaymentIntentPaymentMethodOptionsAlmaCaptureMethod = "manual" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsAmazonPayCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsAmazonPayCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsAmazonPayCaptureMethodManual PaymentIntentPaymentMethodOptionsAmazonPayCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsAmazonPaySetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsAmazonPaySetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsAmazonPaySetupFutureUsageNone PaymentIntentPaymentMethodOptionsAmazonPaySetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsAmazonPaySetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsAmazonPaySetupFutureUsage = "off_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsAUBECSDebitSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsAUBECSDebitSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsAUBECSDebitSetupFutureUsageNone PaymentIntentPaymentMethodOptionsAUBECSDebitSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsAUBECSDebitSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsAUBECSDebitSetupFutureUsage = "off_session" + PaymentIntentPaymentMethodOptionsAUBECSDebitSetupFutureUsageOnSession PaymentIntentPaymentMethodOptionsAUBECSDebitSetupFutureUsage = "on_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsBACSDebitSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsBACSDebitSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsBACSDebitSetupFutureUsageNone PaymentIntentPaymentMethodOptionsBACSDebitSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsBACSDebitSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsBACSDebitSetupFutureUsage = "off_session" + PaymentIntentPaymentMethodOptionsBACSDebitSetupFutureUsageOnSession PaymentIntentPaymentMethodOptionsBACSDebitSetupFutureUsage = "on_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsBancontactSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsBancontactSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsBancontactSetupFutureUsageNone PaymentIntentPaymentMethodOptionsBancontactSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsBancontactSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsBancontactSetupFutureUsage = "off_session" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsBillieCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsBillieCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsBillieCaptureMethodManual PaymentIntentPaymentMethodOptionsBillieCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsBLIKSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsBLIKSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsBLIKSetupFutureUsageNone PaymentIntentPaymentMethodOptionsBLIKSetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsBoletoSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsBoletoSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsBoletoSetupFutureUsageNone PaymentIntentPaymentMethodOptionsBoletoSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsBoletoSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsBoletoSetupFutureUsage = "off_session" + PaymentIntentPaymentMethodOptionsBoletoSetupFutureUsageOnSession PaymentIntentPaymentMethodOptionsBoletoSetupFutureUsage = "on_session" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsCardCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsCardCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsCardCaptureMethodManual PaymentIntentPaymentMethodOptionsCardCaptureMethod = "manual" +) + +// For `fixed_count` installment plans, this is the interval between installment payments your customer will make to their credit card. +// One of `month`. +type PaymentIntentPaymentMethodOptionsCardInstallmentsPlanInterval string + +// List of values that PaymentIntentPaymentMethodOptionsCardInstallmentsPlanInterval can take +const ( + PaymentIntentPaymentMethodOptionsCardInstallmentsPlanIntervalMonth PaymentIntentPaymentMethodOptionsCardInstallmentsPlanInterval = "month" +) + +// Type of installment plan, one of `fixed_count`, `bonus`, or `revolving`. +type PaymentIntentPaymentMethodOptionsCardInstallmentsPlanType string + +// List of values that PaymentIntentPaymentMethodOptionsCardInstallmentsPlanType can take +const ( + PaymentIntentPaymentMethodOptionsCardInstallmentsPlanTypeBonus PaymentIntentPaymentMethodOptionsCardInstallmentsPlanType = "bonus" + PaymentIntentPaymentMethodOptionsCardInstallmentsPlanTypeFixedCount PaymentIntentPaymentMethodOptionsCardInstallmentsPlanType = "fixed_count" + PaymentIntentPaymentMethodOptionsCardInstallmentsPlanTypeRevolving PaymentIntentPaymentMethodOptionsCardInstallmentsPlanType = "revolving" +) + +// One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. +type PaymentIntentPaymentMethodOptionsCardMandateOptionsAmountType string + +// List of values that PaymentIntentPaymentMethodOptionsCardMandateOptionsAmountType can take +const ( + PaymentIntentPaymentMethodOptionsCardMandateOptionsAmountTypeFixed PaymentIntentPaymentMethodOptionsCardMandateOptionsAmountType = "fixed" + PaymentIntentPaymentMethodOptionsCardMandateOptionsAmountTypeMaximum PaymentIntentPaymentMethodOptionsCardMandateOptionsAmountType = "maximum" +) + +// Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. +type PaymentIntentPaymentMethodOptionsCardMandateOptionsInterval string + +// List of values that PaymentIntentPaymentMethodOptionsCardMandateOptionsInterval can take +const ( + PaymentIntentPaymentMethodOptionsCardMandateOptionsIntervalDay PaymentIntentPaymentMethodOptionsCardMandateOptionsInterval = "day" + PaymentIntentPaymentMethodOptionsCardMandateOptionsIntervalMonth PaymentIntentPaymentMethodOptionsCardMandateOptionsInterval = "month" + PaymentIntentPaymentMethodOptionsCardMandateOptionsIntervalSporadic PaymentIntentPaymentMethodOptionsCardMandateOptionsInterval = "sporadic" + PaymentIntentPaymentMethodOptionsCardMandateOptionsIntervalWeek PaymentIntentPaymentMethodOptionsCardMandateOptionsInterval = "week" + PaymentIntentPaymentMethodOptionsCardMandateOptionsIntervalYear PaymentIntentPaymentMethodOptionsCardMandateOptionsInterval = "year" +) + +// Specifies the type of mandates supported. Possible values are `india`. +type PaymentIntentPaymentMethodOptionsCardMandateOptionsSupportedType string + +// List of values that PaymentIntentPaymentMethodOptionsCardMandateOptionsSupportedType can take +const ( + PaymentIntentPaymentMethodOptionsCardMandateOptionsSupportedTypeIndia PaymentIntentPaymentMethodOptionsCardMandateOptionsSupportedType = "india" +) + +// Selected network to process this payment intent on. Depends on the available networks of the card attached to the payment intent. Can be only set confirm-time. +type PaymentIntentPaymentMethodOptionsCardNetwork string + +// List of values that PaymentIntentPaymentMethodOptionsCardNetwork can take +const ( + PaymentIntentPaymentMethodOptionsCardNetworkAmex PaymentIntentPaymentMethodOptionsCardNetwork = "amex" + PaymentIntentPaymentMethodOptionsCardNetworkCartesBancaires PaymentIntentPaymentMethodOptionsCardNetwork = "cartes_bancaires" + PaymentIntentPaymentMethodOptionsCardNetworkDiners PaymentIntentPaymentMethodOptionsCardNetwork = "diners" + PaymentIntentPaymentMethodOptionsCardNetworkDiscover PaymentIntentPaymentMethodOptionsCardNetwork = "discover" + PaymentIntentPaymentMethodOptionsCardNetworkEFTPOSAU PaymentIntentPaymentMethodOptionsCardNetwork = "eftpos_au" + PaymentIntentPaymentMethodOptionsCardNetworkGirocard PaymentIntentPaymentMethodOptionsCardNetwork = "girocard" + PaymentIntentPaymentMethodOptionsCardNetworkInterac PaymentIntentPaymentMethodOptionsCardNetwork = "interac" + PaymentIntentPaymentMethodOptionsCardNetworkJCB PaymentIntentPaymentMethodOptionsCardNetwork = "jcb" + PaymentIntentPaymentMethodOptionsCardNetworkLink PaymentIntentPaymentMethodOptionsCardNetwork = "link" + PaymentIntentPaymentMethodOptionsCardNetworkMastercard PaymentIntentPaymentMethodOptionsCardNetwork = "mastercard" + PaymentIntentPaymentMethodOptionsCardNetworkUnionpay PaymentIntentPaymentMethodOptionsCardNetwork = "unionpay" + PaymentIntentPaymentMethodOptionsCardNetworkUnknown PaymentIntentPaymentMethodOptionsCardNetwork = "unknown" + PaymentIntentPaymentMethodOptionsCardNetworkVisa PaymentIntentPaymentMethodOptionsCardNetwork = "visa" +) + +// Request ability to [capture beyond the standard authorization validity window](https://stripe.com/docs/payments/extended-authorization) for this PaymentIntent. +type PaymentIntentPaymentMethodOptionsCardRequestExtendedAuthorization string + +// List of values that PaymentIntentPaymentMethodOptionsCardRequestExtendedAuthorization can take +const ( + PaymentIntentPaymentMethodOptionsCardRequestExtendedAuthorizationIfAvailable PaymentIntentPaymentMethodOptionsCardRequestExtendedAuthorization = "if_available" + PaymentIntentPaymentMethodOptionsCardRequestExtendedAuthorizationNever PaymentIntentPaymentMethodOptionsCardRequestExtendedAuthorization = "never" +) + +// Request ability to [increment the authorization](https://stripe.com/docs/payments/incremental-authorization) for this PaymentIntent. +type PaymentIntentPaymentMethodOptionsCardRequestIncrementalAuthorization string + +// List of values that PaymentIntentPaymentMethodOptionsCardRequestIncrementalAuthorization can take +const ( + PaymentIntentPaymentMethodOptionsCardRequestIncrementalAuthorizationIfAvailable PaymentIntentPaymentMethodOptionsCardRequestIncrementalAuthorization = "if_available" + PaymentIntentPaymentMethodOptionsCardRequestIncrementalAuthorizationNever PaymentIntentPaymentMethodOptionsCardRequestIncrementalAuthorization = "never" +) + +// Request ability to make [multiple captures](https://stripe.com/docs/payments/multicapture) for this PaymentIntent. +type PaymentIntentPaymentMethodOptionsCardRequestMulticapture string + +// List of values that PaymentIntentPaymentMethodOptionsCardRequestMulticapture can take +const ( + PaymentIntentPaymentMethodOptionsCardRequestMulticaptureIfAvailable PaymentIntentPaymentMethodOptionsCardRequestMulticapture = "if_available" + PaymentIntentPaymentMethodOptionsCardRequestMulticaptureNever PaymentIntentPaymentMethodOptionsCardRequestMulticapture = "never" +) + +// Request ability to [overcapture](https://stripe.com/docs/payments/overcapture) for this PaymentIntent. +type PaymentIntentPaymentMethodOptionsCardRequestOvercapture string + +// List of values that PaymentIntentPaymentMethodOptionsCardRequestOvercapture can take +const ( + PaymentIntentPaymentMethodOptionsCardRequestOvercaptureIfAvailable PaymentIntentPaymentMethodOptionsCardRequestOvercapture = "if_available" + PaymentIntentPaymentMethodOptionsCardRequestOvercaptureNever PaymentIntentPaymentMethodOptionsCardRequestOvercapture = "never" +) + +// We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. +type PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure string + +// List of values that PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure can take +const ( + PaymentIntentPaymentMethodOptionsCardRequestThreeDSecureAny PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure = "any" + PaymentIntentPaymentMethodOptionsCardRequestThreeDSecureAutomatic PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure = "automatic" + PaymentIntentPaymentMethodOptionsCardRequestThreeDSecureChallenge PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure = "challenge" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsCardSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsCardSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsCardSetupFutureUsageNone PaymentIntentPaymentMethodOptionsCardSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsCardSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsCardSetupFutureUsage = "off_session" + PaymentIntentPaymentMethodOptionsCardSetupFutureUsageOnSession PaymentIntentPaymentMethodOptionsCardSetupFutureUsage = "on_session" +) + +// Requested routing priority +type PaymentIntentPaymentMethodOptionsCardPresentRoutingRequestedPriority string + +// List of values that PaymentIntentPaymentMethodOptionsCardPresentRoutingRequestedPriority can take +const ( + PaymentIntentPaymentMethodOptionsCardPresentRoutingRequestedPriorityDomestic PaymentIntentPaymentMethodOptionsCardPresentRoutingRequestedPriority = "domestic" + PaymentIntentPaymentMethodOptionsCardPresentRoutingRequestedPriorityInternational PaymentIntentPaymentMethodOptionsCardPresentRoutingRequestedPriority = "international" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsCashAppCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsCashAppCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsCashAppCaptureMethodManual PaymentIntentPaymentMethodOptionsCashAppCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsCashAppSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsCashAppSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsCashAppSetupFutureUsageNone PaymentIntentPaymentMethodOptionsCashAppSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsCashAppSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsCashAppSetupFutureUsage = "off_session" + PaymentIntentPaymentMethodOptionsCashAppSetupFutureUsageOnSession PaymentIntentPaymentMethodOptionsCashAppSetupFutureUsage = "on_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsCryptoSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsCryptoSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsCryptoSetupFutureUsageNone PaymentIntentPaymentMethodOptionsCryptoSetupFutureUsage = "none" +) + +// List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. +// +// Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. +type PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType string + +// List of values that PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType can take +const ( + PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypeABA PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType = "aba" + PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypeIBAN PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType = "iban" + PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypeSEPA PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType = "sepa" + PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypeSortCode PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType = "sort_code" + PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypeSpei PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType = "spei" + PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypeSwift PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType = "swift" + PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressTypeZengin PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType = "zengin" +) + +// The bank transfer type that this PaymentIntent is allowed to use for funding Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. +type PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferType string + +// List of values that PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferType can take +const ( + PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferTypeEUBankTransfer PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferType = "eu_bank_transfer" + PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferTypeGBBankTransfer PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferType = "gb_bank_transfer" + PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferTypeJPBankTransfer PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferType = "jp_bank_transfer" + PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferTypeMXBankTransfer PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferType = "mx_bank_transfer" + PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferTypeUSBankTransfer PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferType = "us_bank_transfer" +) + +// The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. +type PaymentIntentPaymentMethodOptionsCustomerBalanceFundingType string + +// List of values that PaymentIntentPaymentMethodOptionsCustomerBalanceFundingType can take +const ( + PaymentIntentPaymentMethodOptionsCustomerBalanceFundingTypeBankTransfer PaymentIntentPaymentMethodOptionsCustomerBalanceFundingType = "bank_transfer" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsCustomerBalanceSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsCustomerBalanceSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsCustomerBalanceSetupFutureUsageNone PaymentIntentPaymentMethodOptionsCustomerBalanceSetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsEPSSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsEPSSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsEPSSetupFutureUsageNone PaymentIntentPaymentMethodOptionsEPSSetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsFPXSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsFPXSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsFPXSetupFutureUsageNone PaymentIntentPaymentMethodOptionsFPXSetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsGiropaySetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsGiropaySetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsGiropaySetupFutureUsageNone PaymentIntentPaymentMethodOptionsGiropaySetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsGrabpaySetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsGrabpaySetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsGrabpaySetupFutureUsageNone PaymentIntentPaymentMethodOptionsGrabpaySetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsIDEALSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsIDEALSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsIDEALSetupFutureUsageNone PaymentIntentPaymentMethodOptionsIDEALSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsIDEALSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsIDEALSetupFutureUsage = "off_session" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsKakaoPayCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsKakaoPayCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsKakaoPayCaptureMethodManual PaymentIntentPaymentMethodOptionsKakaoPayCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsKakaoPaySetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsKakaoPaySetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsKakaoPaySetupFutureUsageNone PaymentIntentPaymentMethodOptionsKakaoPaySetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsKakaoPaySetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsKakaoPaySetupFutureUsage = "off_session" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsKlarnaCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsKlarnaCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsKlarnaCaptureMethodManual PaymentIntentPaymentMethodOptionsKlarnaCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsKlarnaSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsKlarnaSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsKlarnaSetupFutureUsageNone PaymentIntentPaymentMethodOptionsKlarnaSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsKlarnaSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsKlarnaSetupFutureUsage = "off_session" + PaymentIntentPaymentMethodOptionsKlarnaSetupFutureUsageOnSession PaymentIntentPaymentMethodOptionsKlarnaSetupFutureUsage = "on_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsKonbiniSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsKonbiniSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsKonbiniSetupFutureUsageNone PaymentIntentPaymentMethodOptionsKonbiniSetupFutureUsage = "none" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsKrCardCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsKrCardCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsKrCardCaptureMethodManual PaymentIntentPaymentMethodOptionsKrCardCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsKrCardSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsKrCardSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsKrCardSetupFutureUsageNone PaymentIntentPaymentMethodOptionsKrCardSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsKrCardSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsKrCardSetupFutureUsage = "off_session" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsLinkCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsLinkCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsLinkCaptureMethodManual PaymentIntentPaymentMethodOptionsLinkCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsLinkSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsLinkSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsLinkSetupFutureUsageNone PaymentIntentPaymentMethodOptionsLinkSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsLinkSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsLinkSetupFutureUsage = "off_session" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsMobilepayCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsMobilepayCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsMobilepayCaptureMethodManual PaymentIntentPaymentMethodOptionsMobilepayCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsMobilepaySetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsMobilepaySetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsMobilepaySetupFutureUsageNone PaymentIntentPaymentMethodOptionsMobilepaySetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsMultibancoSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsMultibancoSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsMultibancoSetupFutureUsageNone PaymentIntentPaymentMethodOptionsMultibancoSetupFutureUsage = "none" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsNaverPayCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsNaverPayCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsNaverPayCaptureMethodManual PaymentIntentPaymentMethodOptionsNaverPayCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsNaverPaySetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsNaverPaySetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsNaverPaySetupFutureUsageNone PaymentIntentPaymentMethodOptionsNaverPaySetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsNaverPaySetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsNaverPaySetupFutureUsage = "off_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsNzBankAccountSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsNzBankAccountSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsNzBankAccountSetupFutureUsageNone PaymentIntentPaymentMethodOptionsNzBankAccountSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsNzBankAccountSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsNzBankAccountSetupFutureUsage = "off_session" + PaymentIntentPaymentMethodOptionsNzBankAccountSetupFutureUsageOnSession PaymentIntentPaymentMethodOptionsNzBankAccountSetupFutureUsage = "on_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsOXXOSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsOXXOSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsOXXOSetupFutureUsageNone PaymentIntentPaymentMethodOptionsOXXOSetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsP24SetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsP24SetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsP24SetupFutureUsageNone PaymentIntentPaymentMethodOptionsP24SetupFutureUsage = "none" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsPaycoCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsPaycoCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsPaycoCaptureMethodManual PaymentIntentPaymentMethodOptionsPaycoCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsPayNowSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsPayNowSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsPayNowSetupFutureUsageNone PaymentIntentPaymentMethodOptionsPayNowSetupFutureUsage = "none" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsPaypalCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsPaypalCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsPaypalCaptureMethodManual PaymentIntentPaymentMethodOptionsPaypalCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsPaypalSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsPaypalSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsPaypalSetupFutureUsageNone PaymentIntentPaymentMethodOptionsPaypalSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsPaypalSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsPaypalSetupFutureUsage = "off_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsPixSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsPixSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsPixSetupFutureUsageNone PaymentIntentPaymentMethodOptionsPixSetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsPromptPaySetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsPromptPaySetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsPromptPaySetupFutureUsageNone PaymentIntentPaymentMethodOptionsPromptPaySetupFutureUsage = "none" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsRevolutPayCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsRevolutPayCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsRevolutPayCaptureMethodManual PaymentIntentPaymentMethodOptionsRevolutPayCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsRevolutPaySetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsRevolutPaySetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsRevolutPaySetupFutureUsageNone PaymentIntentPaymentMethodOptionsRevolutPaySetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsRevolutPaySetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsRevolutPaySetupFutureUsage = "off_session" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsSamsungPayCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsSamsungPayCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsSamsungPayCaptureMethodManual PaymentIntentPaymentMethodOptionsSamsungPayCaptureMethod = "manual" +) + +// Controls when the funds will be captured from the customer's account. +type PaymentIntentPaymentMethodOptionsSatispayCaptureMethod string + +// List of values that PaymentIntentPaymentMethodOptionsSatispayCaptureMethod can take +const ( + PaymentIntentPaymentMethodOptionsSatispayCaptureMethodManual PaymentIntentPaymentMethodOptionsSatispayCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsSEPADebitSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsSEPADebitSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsSEPADebitSetupFutureUsageNone PaymentIntentPaymentMethodOptionsSEPADebitSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsSEPADebitSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsSEPADebitSetupFutureUsage = "off_session" + PaymentIntentPaymentMethodOptionsSEPADebitSetupFutureUsageOnSession PaymentIntentPaymentMethodOptionsSEPADebitSetupFutureUsage = "on_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsSofortSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsSofortSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsSofortSetupFutureUsageNone PaymentIntentPaymentMethodOptionsSofortSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsSofortSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsSofortSetupFutureUsage = "off_session" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsSwishSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsSwishSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsSwishSetupFutureUsageNone PaymentIntentPaymentMethodOptionsSwishSetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsTWINTSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsTWINTSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsTWINTSetupFutureUsageNone PaymentIntentPaymentMethodOptionsTWINTSetupFutureUsage = "none" +) + +// The account subcategories to use to filter for possible accounts to link. Valid subcategories are `checking` and `savings`. +type PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory string + +// List of values that PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory can take +const ( + PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategoryChecking PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory = "checking" + PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategorySavings PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory = "savings" +) + +// The list of permissions to request. The `payment_method` permission must be included. +type PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission string + +// List of values that PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission can take +const ( + PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionBalances PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "balances" + PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionOwnership PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "ownership" + PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionPaymentMethod PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "payment_method" + PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionTransactions PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "transactions" +) + +// Data features requested to be retrieved upon account creation. +type PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch string + +// List of values that PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch can take +const ( + PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchBalances PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "balances" + PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchOwnership PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "ownership" + PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchTransactions PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "transactions" +) + +// Mandate collection method +type PaymentIntentPaymentMethodOptionsUSBankAccountMandateOptionsCollectionMethod string + +// List of values that PaymentIntentPaymentMethodOptionsUSBankAccountMandateOptionsCollectionMethod can take +const ( + PaymentIntentPaymentMethodOptionsUSBankAccountMandateOptionsCollectionMethodPaper PaymentIntentPaymentMethodOptionsUSBankAccountMandateOptionsCollectionMethod = "paper" +) + +// Preferred transaction settlement speed +type PaymentIntentPaymentMethodOptionsUSBankAccountPreferredSettlementSpeed string + +// List of values that PaymentIntentPaymentMethodOptionsUSBankAccountPreferredSettlementSpeed can take +const ( + PaymentIntentPaymentMethodOptionsUSBankAccountPreferredSettlementSpeedFastest PaymentIntentPaymentMethodOptionsUSBankAccountPreferredSettlementSpeed = "fastest" + PaymentIntentPaymentMethodOptionsUSBankAccountPreferredSettlementSpeedStandard PaymentIntentPaymentMethodOptionsUSBankAccountPreferredSettlementSpeed = "standard" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsUSBankAccountSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsUSBankAccountSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsUSBankAccountSetupFutureUsageNone PaymentIntentPaymentMethodOptionsUSBankAccountSetupFutureUsage = "none" + PaymentIntentPaymentMethodOptionsUSBankAccountSetupFutureUsageOffSession PaymentIntentPaymentMethodOptionsUSBankAccountSetupFutureUsage = "off_session" + PaymentIntentPaymentMethodOptionsUSBankAccountSetupFutureUsageOnSession PaymentIntentPaymentMethodOptionsUSBankAccountSetupFutureUsage = "on_session" +) + +// Bank account verification method. +type PaymentIntentPaymentMethodOptionsUSBankAccountVerificationMethod string + +// List of values that PaymentIntentPaymentMethodOptionsUSBankAccountVerificationMethod can take +const ( + PaymentIntentPaymentMethodOptionsUSBankAccountVerificationMethodAutomatic PaymentIntentPaymentMethodOptionsUSBankAccountVerificationMethod = "automatic" + PaymentIntentPaymentMethodOptionsUSBankAccountVerificationMethodInstant PaymentIntentPaymentMethodOptionsUSBankAccountVerificationMethod = "instant" + PaymentIntentPaymentMethodOptionsUSBankAccountVerificationMethodMicrodeposits PaymentIntentPaymentMethodOptionsUSBankAccountVerificationMethod = "microdeposits" +) + +// The client type that the end customer will pay from +type PaymentIntentPaymentMethodOptionsWeChatPayClient string + +// List of values that PaymentIntentPaymentMethodOptionsWeChatPayClient can take +const ( + PaymentIntentPaymentMethodOptionsWeChatPayClientAndroid PaymentIntentPaymentMethodOptionsWeChatPayClient = "android" + PaymentIntentPaymentMethodOptionsWeChatPayClientIOS PaymentIntentPaymentMethodOptionsWeChatPayClient = "ios" + PaymentIntentPaymentMethodOptionsWeChatPayClientWeb PaymentIntentPaymentMethodOptionsWeChatPayClient = "web" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsWeChatPaySetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsWeChatPaySetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsWeChatPaySetupFutureUsageNone PaymentIntentPaymentMethodOptionsWeChatPaySetupFutureUsage = "none" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentPaymentMethodOptionsZipSetupFutureUsage string + +// List of values that PaymentIntentPaymentMethodOptionsZipSetupFutureUsage can take +const ( + PaymentIntentPaymentMethodOptionsZipSetupFutureUsageNone PaymentIntentPaymentMethodOptionsZipSetupFutureUsage = "none" +) + +// Type of the payment method for which payment is in `processing` state, one of `card`. +type PaymentIntentProcessingType string + +// List of values that PaymentIntentProcessingType can take +const ( + PaymentIntentProcessingTypeCard PaymentIntentProcessingType = "card" +) + +// Indicates that you intend to make future payments with this PaymentIntent's payment method. +// +// If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. +// +// If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. +// +// When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). +type PaymentIntentSetupFutureUsage string + +// List of values that PaymentIntentSetupFutureUsage can take +const ( + PaymentIntentSetupFutureUsageOffSession PaymentIntentSetupFutureUsage = "off_session" + PaymentIntentSetupFutureUsageOnSession PaymentIntentSetupFutureUsage = "on_session" +) + +// Status of this PaymentIntent, one of `requires_payment_method`, `requires_confirmation`, `requires_action`, `processing`, `requires_capture`, `canceled`, or `succeeded`. Read more about each PaymentIntent [status](https://stripe.com/docs/payments/intents#intent-statuses). +type PaymentIntentStatus string + +// List of values that PaymentIntentStatus can take +const ( + PaymentIntentStatusCanceled PaymentIntentStatus = "canceled" + PaymentIntentStatusProcessing PaymentIntentStatus = "processing" + PaymentIntentStatusRequiresAction PaymentIntentStatus = "requires_action" + PaymentIntentStatusRequiresCapture PaymentIntentStatus = "requires_capture" + PaymentIntentStatusRequiresConfirmation PaymentIntentStatus = "requires_confirmation" + PaymentIntentStatusRequiresPaymentMethod PaymentIntentStatus = "requires_payment_method" + PaymentIntentStatusSucceeded PaymentIntentStatus = "succeeded" +) + +// Returns a list of PaymentIntents. +type PaymentIntentListParams struct { + ListParams `form:"*"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp or a dictionary with a number of different query options. + Created *int64 `form:"created"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp or a dictionary with a number of different query options. + CreatedRange *RangeQueryParams `form:"created"` + // Only return PaymentIntents for the customer that this customer ID specifies. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentIntentListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When you enable this parameter, this PaymentIntent accepts payment methods that you enable in the Dashboard and that are compatible with this PaymentIntent's other parameters. +type PaymentIntentAutomaticPaymentMethodsParams struct { + // Controls whether this PaymentIntent will accept redirect-based payment methods. + // + // Redirect-based payment methods may require your customer to be redirected to a payment method's app or site for authentication or additional steps. To [confirm](https://stripe.com/docs/api/payment_intents/confirm) this PaymentIntent, you may be required to provide a `return_url` to redirect customers back to your site after they authenticate or complete the payment. + AllowRedirects *string `form:"allow_redirects"` + // Whether this feature is enabled. + Enabled *bool `form:"enabled"` +} + +// If this is a Mandate accepted offline, this hash contains details about the offline acceptance. +type PaymentIntentMandateDataCustomerAcceptanceOfflineParams struct{} + +// If this is a Mandate accepted online, this hash contains details about the online acceptance. +type PaymentIntentMandateDataCustomerAcceptanceOnlineParams struct { + // The IP address from which the Mandate was accepted by the customer. + IPAddress *string `form:"ip_address"` + // The user agent of the browser from which the Mandate was accepted by the customer. + UserAgent *string `form:"user_agent"` +} + +// This hash contains details about the customer acceptance of the Mandate. +type PaymentIntentMandateDataCustomerAcceptanceParams struct { + // The time at which the customer accepted the Mandate. + AcceptedAt *int64 `form:"accepted_at"` + // If this is a Mandate accepted offline, this hash contains details about the offline acceptance. + Offline *PaymentIntentMandateDataCustomerAcceptanceOfflineParams `form:"offline"` + // If this is a Mandate accepted online, this hash contains details about the online acceptance. + Online *PaymentIntentMandateDataCustomerAcceptanceOnlineParams `form:"online"` + // The type of customer acceptance information included with the Mandate. One of `online` or `offline`. + Type *string `form:"type"` +} + +// This hash contains details about the Mandate to create. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). +type PaymentIntentMandateDataParams struct { + // This hash contains details about the customer acceptance of the Mandate. + CustomerAcceptance *PaymentIntentMandateDataCustomerAcceptanceParams `form:"customer_acceptance"` +} + +// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. +type PaymentIntentPaymentMethodDataBillingDetailsParams struct { + // Billing address. + Address *AddressParams `form:"address"` + // Email address. + Email *string `form:"email"` + // Full name. + Name *string `form:"name"` + // Billing phone number (including extension). + Phone *string `form:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID *string `form:"tax_id"` +} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type PaymentIntentPaymentMethodDataRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// If provided, this hash will be used to create a PaymentMethod. The new PaymentMethod will appear +// in the [payment_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-payment_method) +// property on the PaymentIntent. +type PaymentIntentPaymentMethodDataParams struct { + // If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + ACSSDebit *PaymentMethodACSSDebitParams `form:"acss_debit"` + // If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + Affirm *PaymentMethodAffirmParams `form:"affirm"` + // If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + AfterpayClearpay *PaymentMethodAfterpayClearpayParams `form:"afterpay_clearpay"` + // If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + Alipay *PaymentMethodAlipayParams `form:"alipay"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to `unspecified`. + AllowRedisplay *string `form:"allow_redisplay"` + // If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. + Alma *PaymentMethodAlmaParams `form:"alma"` + // If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. + AmazonPay *PaymentMethodAmazonPayParams `form:"amazon_pay"` + // If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + AUBECSDebit *PaymentMethodAUBECSDebitParams `form:"au_becs_debit"` + // If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + BACSDebit *PaymentMethodBACSDebitParams `form:"bacs_debit"` + // If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + Bancontact *PaymentMethodBancontactParams `form:"bancontact"` + // If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. + Billie *PaymentMethodBillieParams `form:"billie"` + // Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + BillingDetails *PaymentIntentPaymentMethodDataBillingDetailsParams `form:"billing_details"` + // If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + BLIK *PaymentMethodBLIKParams `form:"blik"` + // If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + Boleto *PaymentMethodBoletoParams `form:"boleto"` + // If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + CashApp *PaymentMethodCashAppParams `form:"cashapp"` + // If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. + Crypto *PaymentMethodCryptoParams `form:"crypto"` + // If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + CustomerBalance *PaymentMethodCustomerBalanceParams `form:"customer_balance"` + // If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + EPS *PaymentMethodEPSParams `form:"eps"` + // If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + FPX *PaymentMethodFPXParams `form:"fpx"` + // If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + Giropay *PaymentMethodGiropayParams `form:"giropay"` + // If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + Grabpay *PaymentMethodGrabpayParams `form:"grabpay"` + // If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + IDEAL *PaymentMethodIDEALParams `form:"ideal"` + // If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + InteracPresent *PaymentMethodInteracPresentParams `form:"interac_present"` + // If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. + KakaoPay *PaymentMethodKakaoPayParams `form:"kakao_pay"` + // If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + Klarna *PaymentMethodKlarnaParams `form:"klarna"` + // If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + Konbini *PaymentMethodKonbiniParams `form:"konbini"` + // If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. + KrCard *PaymentMethodKrCardParams `form:"kr_card"` + // If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + Link *PaymentMethodLinkParams `form:"link"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. + Mobilepay *PaymentMethodMobilepayParams `form:"mobilepay"` + // If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. + Multibanco *PaymentMethodMultibancoParams `form:"multibanco"` + // If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. + NaverPay *PaymentMethodNaverPayParams `form:"naver_pay"` + // If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. + NzBankAccount *PaymentMethodNzBankAccountParams `form:"nz_bank_account"` + // If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + OXXO *PaymentMethodOXXOParams `form:"oxxo"` + // If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + P24 *PaymentMethodP24Params `form:"p24"` + // If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. + PayByBank *PaymentMethodPayByBankParams `form:"pay_by_bank"` + // If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. + Payco *PaymentMethodPaycoParams `form:"payco"` + // If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + PayNow *PaymentMethodPayNowParams `form:"paynow"` + // If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + Paypal *PaymentMethodPaypalParams `form:"paypal"` + // If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + Pix *PaymentMethodPixParams `form:"pix"` + // If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + PromptPay *PaymentMethodPromptPayParams `form:"promptpay"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *PaymentIntentPaymentMethodDataRadarOptionsParams `form:"radar_options"` + // If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + RevolutPay *PaymentMethodRevolutPayParams `form:"revolut_pay"` + // If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. + SamsungPay *PaymentMethodSamsungPayParams `form:"samsung_pay"` + // If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. + Satispay *PaymentMethodSatispayParams `form:"satispay"` + // If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + SEPADebit *PaymentMethodSEPADebitParams `form:"sepa_debit"` + // If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + Sofort *PaymentMethodSofortParams `form:"sofort"` + // If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. + Swish *PaymentMethodSwishParams `form:"swish"` + // If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. + TWINT *PaymentMethodTWINTParams `form:"twint"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type *string `form:"type"` + // If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + USBankAccount *PaymentMethodUSBankAccountParams `form:"us_bank_account"` + // If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + WeChatPay *PaymentMethodWeChatPayParams `form:"wechat_pay"` + // If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + Zip *PaymentMethodZipParams `form:"zip"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentIntentPaymentMethodDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Additional fields for Mandate creation +type PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsParams struct { + // A URL for custom mandate text to render during confirmation step. + // The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + // or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + CustomMandateURL *string `form:"custom_mandate_url"` + // Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + IntervalDescription *string `form:"interval_description"` + // Payment schedule for the mandate. + PaymentSchedule *string `form:"payment_schedule"` + // Transaction type of the mandate. + TransactionType *string `form:"transaction_type"` +} + +// If this is a `acss_debit` PaymentMethod, this sub-hash contains details about the ACSS Debit payment method options. +type PaymentIntentPaymentMethodOptionsACSSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` + // Bank account verification method. + VerificationMethod *string `form:"verification_method"` +} + +// If this is an `affirm` PaymentMethod, this sub-hash contains details about the Affirm payment method options. +type PaymentIntentPaymentMethodOptionsAffirmParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Preferred language of the Affirm authorization page that the customer is redirected to. + PreferredLocale *string `form:"preferred_locale"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `afterpay_clearpay` PaymentMethod, this sub-hash contains details about the Afterpay Clearpay payment method options. +type PaymentIntentPaymentMethodOptionsAfterpayClearpayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // An internal identifier or reference that this payment corresponds to. You must limit the identifier to 128 characters, and it can only contain letters, numbers, underscores, backslashes, and dashes. + // This field differs from the statement descriptor and item name. + Reference *string `form:"reference"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `alipay` PaymentMethod, this sub-hash contains details about the Alipay payment method options. +type PaymentIntentPaymentMethodOptionsAlipayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `alma` PaymentMethod, this sub-hash contains details about the Alma payment method options. +type PaymentIntentPaymentMethodOptionsAlmaParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// If this is a `amazon_pay` PaymentMethod, this sub-hash contains details about the Amazon Pay payment method options. +type PaymentIntentPaymentMethodOptionsAmazonPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `au_becs_debit` PaymentMethod, this sub-hash contains details about the AU BECS Direct Debit payment method options. +type PaymentIntentPaymentMethodOptionsAUBECSDebitParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// Additional fields for Mandate creation +type PaymentIntentPaymentMethodOptionsBACSDebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'DDIC' or 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// If this is a `bacs_debit` PaymentMethod, this sub-hash contains details about the BACS Debit payment method options. +type PaymentIntentPaymentMethodOptionsBACSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *PaymentIntentPaymentMethodOptionsBACSDebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// If this is a `bancontact` PaymentMethod, this sub-hash contains details about the Bancontact payment method options. +type PaymentIntentPaymentMethodOptionsBancontactParams struct { + // Preferred language of the Bancontact authorization page that the customer is redirected to. + PreferredLanguage *string `form:"preferred_language"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `billie` PaymentMethod, this sub-hash contains details about the Billie payment method options. +type PaymentIntentPaymentMethodOptionsBillieParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// If this is a `blik` PaymentMethod, this sub-hash contains details about the BLIK payment method options. +type PaymentIntentPaymentMethodOptionsBLIKParams struct { + // The 6-digit BLIK code that a customer has generated using their banking application. Can only be set on confirmation. + Code *string `form:"code"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `boleto` PaymentMethod, this sub-hash contains details about the Boleto payment method options. +type PaymentIntentPaymentMethodOptionsBoletoParams struct { + // The number of calendar days before a Boleto voucher expires. For example, if you create a Boleto voucher on Monday and you set expires_after_days to 2, the Boleto invoice will expire on Wednesday at 23:59 America/Sao_Paulo time. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// The selected installment plan to use for this payment attempt. +// This parameter can only be provided during confirmation. +type PaymentIntentPaymentMethodOptionsCardInstallmentsPlanParams struct { + // For `fixed_count` installment plans, this is required. It represents the number of installment payments your customer will make to their credit card. + Count *int64 `form:"count"` + // For `fixed_count` installment plans, this is required. It represents the interval between installment payments your customer will make to their credit card. + // One of `month`. + Interval *string `form:"interval"` + // Type of installment plan, one of `fixed_count`, `bonus`, or `revolving`. + Type *string `form:"type"` +} + +// Installment configuration for payments attempted on this PaymentIntent (Mexico Only). +// +// For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). +type PaymentIntentPaymentMethodOptionsCardInstallmentsParams struct { + // Setting to true enables installments for this PaymentIntent. + // This will cause the response to contain a list of available installment plans. + // Setting to false will prevent any selected plan from applying to a charge. + Enabled *bool `form:"enabled"` + // The selected installment plan to use for this payment attempt. + // This parameter can only be provided during confirmation. + Plan *PaymentIntentPaymentMethodOptionsCardInstallmentsPlanParams `form:"plan"` +} + +// Configuration options for setting up an eMandate for cards issued in India. +type PaymentIntentPaymentMethodOptionsCardMandateOptionsParams struct { + // Amount to be charged for future payments. + Amount *int64 `form:"amount"` + // One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + AmountType *string `form:"amount_type"` + // A description of the mandate or subscription that is meant to be displayed to the customer. + Description *string `form:"description"` + // End date of the mandate or subscription. If not provided, the mandate will be active until canceled. If provided, end date should be after start date. + EndDate *int64 `form:"end_date"` + // Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. + Interval *string `form:"interval"` + // The number of intervals between payments. For example, `interval=month` and `interval_count=3` indicates one payment every three months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). This parameter is optional when `interval=sporadic`. + IntervalCount *int64 `form:"interval_count"` + // Unique identifier for the mandate or subscription. + Reference *string `form:"reference"` + // Start date of the mandate or subscription. Start date should not be lesser than yesterday. + StartDate *int64 `form:"start_date"` + // Specifies the type of mandates supported. Possible values are `india`. + SupportedTypes []*string `form:"supported_types"` +} + +// Cartes Bancaires-specific 3DS fields. +type PaymentIntentPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancairesParams struct { + // The cryptogram calculation algorithm used by the card Issuer's ACS + // to calculate the Authentication cryptogram. Also known as `cavvAlgorithm`. + // messageExtension: CB-AVALGO + CbAvalgo *string `form:"cb_avalgo"` + // The exemption indicator returned from Cartes Bancaires in the ARes. + // message extension: CB-EXEMPTION; string (4 characters) + // This is a 3 byte bitmap (low significant byte first and most significant + // bit first) that has been Base64 encoded + CbExemption *string `form:"cb_exemption"` + // The risk score returned from Cartes Bancaires in the ARes. + // message extension: CB-SCORE; numeric value 0-99 + CbScore *int64 `form:"cb_score"` +} + +// Network specific 3DS fields. Network specific arguments require an +// explicit card brand choice. The parameter `payment_method_options.card.network“ +// must be populated accordingly +type PaymentIntentPaymentMethodOptionsCardThreeDSecureNetworkOptionsParams struct { + // Cartes Bancaires-specific 3DS fields. + CartesBancaires *PaymentIntentPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancairesParams `form:"cartes_bancaires"` +} + +// If 3D Secure authentication was performed with a third-party provider, +// the authentication details to use for this payment. +type PaymentIntentPaymentMethodOptionsCardThreeDSecureParams struct { + // The `transStatus` returned from the card Issuer's ACS in the ARes. + AresTransStatus *string `form:"ares_trans_status"` + // The cryptogram, also known as the "authentication value" (AAV, CAVV or + // AEVV). This value is 20 bytes, base64-encoded into a 28-character string. + // (Most 3D Secure providers will return the base64-encoded version, which + // is what you should specify here.) + Cryptogram *string `form:"cryptogram"` + // The Electronic Commerce Indicator (ECI) is returned by your 3D Secure + // provider and indicates what degree of authentication was performed. + ElectronicCommerceIndicator *string `form:"electronic_commerce_indicator"` + // The exemption requested via 3DS and accepted by the issuer at authentication time. + ExemptionIndicator *string `form:"exemption_indicator"` + // Network specific 3DS fields. Network specific arguments require an + // explicit card brand choice. The parameter `payment_method_options.card.network`` + // must be populated accordingly + NetworkOptions *PaymentIntentPaymentMethodOptionsCardThreeDSecureNetworkOptionsParams `form:"network_options"` + // The challenge indicator (`threeDSRequestorChallengeInd`) which was requested in the + // AReq sent to the card Issuer's ACS. A string containing 2 digits from 01-99. + RequestorChallengeIndicator *string `form:"requestor_challenge_indicator"` + // For 3D Secure 1, the XID. For 3D Secure 2, the Directory Server + // Transaction ID (dsTransID). + TransactionID *string `form:"transaction_id"` + // The version of 3D Secure that was performed. + Version *string `form:"version"` +} + +// Configuration for any card payments attempted on this PaymentIntent. +type PaymentIntentPaymentMethodOptionsCardParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // A single-use `cvc_update` Token that represents a card CVC value. When provided, the CVC value will be verified during the card payment attempt. This parameter can only be provided during confirmation. + CVCToken *string `form:"cvc_token"` + // Installment configuration for payments attempted on this PaymentIntent (Mexico Only). + // + // For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + Installments *PaymentIntentPaymentMethodOptionsCardInstallmentsParams `form:"installments"` + // Configuration options for setting up an eMandate for cards issued in India. + MandateOptions *PaymentIntentPaymentMethodOptionsCardMandateOptionsParams `form:"mandate_options"` + // When specified, this parameter indicates that a transaction will be marked + // as MOTO (Mail Order Telephone Order) and thus out of scope for SCA. This + // parameter can only be provided during confirmation. + MOTO *bool `form:"moto"` + // Selected network to process this PaymentIntent on. Depends on the available networks of the card attached to the PaymentIntent. Can be only set confirm-time. + Network *string `form:"network"` + // Request ability to [capture beyond the standard authorization validity window](https://stripe.com/docs/payments/extended-authorization) for this PaymentIntent. + RequestExtendedAuthorization *string `form:"request_extended_authorization"` + // Request ability to [increment the authorization](https://stripe.com/docs/payments/incremental-authorization) for this PaymentIntent. + RequestIncrementalAuthorization *string `form:"request_incremental_authorization"` + // Request ability to make [multiple captures](https://stripe.com/docs/payments/multicapture) for this PaymentIntent. + RequestMulticapture *string `form:"request_multicapture"` + // Request ability to [overcapture](https://stripe.com/docs/payments/overcapture) for this PaymentIntent. + RequestOvercapture *string `form:"request_overcapture"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure *string `form:"request_three_d_secure"` + // When enabled, using a card that is attached to a customer will require the CVC to be provided again (i.e. using the cvc_token parameter). + RequireCVCRecollection *bool `form:"require_cvc_recollection"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Provides information about a card payment that customers see on their statements. Concatenated with the Kana prefix (shortened Kana descriptor) or Kana statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 22 characters. + StatementDescriptorSuffixKana *string `form:"statement_descriptor_suffix_kana"` + // Provides information about a card payment that customers see on their statements. Concatenated with the Kanji prefix (shortened Kanji descriptor) or Kanji statement descriptor that's set on the account to form the complete statement descriptor. Maximum 17 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 17 characters. + StatementDescriptorSuffixKanji *string `form:"statement_descriptor_suffix_kanji"` + // If 3D Secure authentication was performed with a third-party provider, + // the authentication details to use for this payment. + ThreeDSecure *PaymentIntentPaymentMethodOptionsCardThreeDSecureParams `form:"three_d_secure"` +} + +// Network routing priority on co-branded EMV cards supporting domestic debit and international card schemes. +type PaymentIntentPaymentMethodOptionsCardPresentRoutingParams struct { + // Routing requested priority + RequestedPriority *string `form:"requested_priority"` +} + +// If this is a `card_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. +type PaymentIntentPaymentMethodOptionsCardPresentParams struct { + // Request ability to capture this payment beyond the standard [authorization validity window](https://stripe.com/docs/terminal/features/extended-authorizations#authorization-validity) + RequestExtendedAuthorization *bool `form:"request_extended_authorization"` + // Request ability to [increment](https://stripe.com/docs/terminal/features/incremental-authorizations) this PaymentIntent if the combination of MCC and card brand is eligible. Check [incremental_authorization_supported](https://stripe.com/docs/api/charges/object#charge_object-payment_method_details-card_present-incremental_authorization_supported) in the [Confirm](https://stripe.com/docs/api/payment_intents/confirm) response to verify support. + RequestIncrementalAuthorizationSupport *bool `form:"request_incremental_authorization_support"` + // Network routing priority on co-branded EMV cards supporting domestic debit and international card schemes. + Routing *PaymentIntentPaymentMethodOptionsCardPresentRoutingParams `form:"routing"` +} + +// If this is a `cashapp` PaymentMethod, this sub-hash contains details about the Cash App Pay payment method options. +type PaymentIntentPaymentMethodOptionsCashAppParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `crypto` PaymentMethod, this sub-hash contains details about the Crypto payment method options. +type PaymentIntentPaymentMethodOptionsCryptoParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Configuration for the eu_bank_transfer funding type. +type PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country *string `form:"country"` +} + +// Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. +type PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferParams struct { + // Configuration for the eu_bank_transfer funding type. + EUBankTransfer *PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams `form:"eu_bank_transfer"` + // List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. + // + // Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. + RequestedAddressTypes []*string `form:"requested_address_types"` + // The list of bank transfer types that this PaymentIntent is allowed to use for funding Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + Type *string `form:"type"` +} + +// If this is a `customer balance` PaymentMethod, this sub-hash contains details about the customer balance payment method options. +type PaymentIntentPaymentMethodOptionsCustomerBalanceParams struct { + // Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + BankTransfer *PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferParams `form:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType *string `form:"funding_type"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `eps` PaymentMethod, this sub-hash contains details about the EPS payment method options. +type PaymentIntentPaymentMethodOptionsEPSParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `fpx` PaymentMethod, this sub-hash contains details about the FPX payment method options. +type PaymentIntentPaymentMethodOptionsFPXParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `giropay` PaymentMethod, this sub-hash contains details about the Giropay payment method options. +type PaymentIntentPaymentMethodOptionsGiropayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `grabpay` PaymentMethod, this sub-hash contains details about the Grabpay payment method options. +type PaymentIntentPaymentMethodOptionsGrabpayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `ideal` PaymentMethod, this sub-hash contains details about the Ideal payment method options. +type PaymentIntentPaymentMethodOptionsIDEALParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `interac_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. +type PaymentIntentPaymentMethodOptionsInteracPresentParams struct{} + +// If this is a `kakao_pay` PaymentMethod, this sub-hash contains details about the Kakao Pay payment method options. +type PaymentIntentPaymentMethodOptionsKakaoPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// On-demand details if setting up or charging an on-demand payment. +type PaymentIntentPaymentMethodOptionsKlarnaOnDemandParams struct { + // Your average amount value. You can use a value across your customer base, or segment based on customer type, country, etc. + AverageAmount *int64 `form:"average_amount"` + // The maximum value you may charge a customer per purchase. You can use a value across your customer base, or segment based on customer type, country, etc. + MaximumAmount *int64 `form:"maximum_amount"` + // The lowest or minimum value you may charge a customer per purchase. You can use a value across your customer base, or segment based on customer type, country, etc. + MinimumAmount *int64 `form:"minimum_amount"` + // Interval at which the customer is making purchases + PurchaseInterval *string `form:"purchase_interval"` + // The number of `purchase_interval` between charges + PurchaseIntervalCount *int64 `form:"purchase_interval_count"` +} + +// Describes the upcoming charge for this subscription. +type PaymentIntentPaymentMethodOptionsKlarnaSubscriptionNextBillingParams struct { + // The amount of the next charge for the subscription. + Amount *int64 `form:"amount"` + // The date of the next charge for the subscription in YYYY-MM-DD format. + Date *string `form:"date"` +} + +// Subscription details if setting up or charging a subscription. +type PaymentIntentPaymentMethodOptionsKlarnaSubscriptionParams struct { + // Unit of time between subscription charges. + Interval *string `form:"interval"` + // The number of intervals (specified in the `interval` attribute) between subscription charges. For example, `interval=month` and `interval_count=3` charges every 3 months. + IntervalCount *int64 `form:"interval_count"` + // Name for subscription. + Name *string `form:"name"` + // Describes the upcoming charge for this subscription. + NextBilling *PaymentIntentPaymentMethodOptionsKlarnaSubscriptionNextBillingParams `form:"next_billing"` + // A non-customer-facing reference to correlate subscription charges in the Klarna app. Use a value that persists across subscription charges. + Reference *string `form:"reference"` +} + +// If this is a `klarna` PaymentMethod, this sub-hash contains details about the Klarna payment method options. +type PaymentIntentPaymentMethodOptionsKlarnaParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // On-demand details if setting up or charging an on-demand payment. + OnDemand *PaymentIntentPaymentMethodOptionsKlarnaOnDemandParams `form:"on_demand"` + // Preferred language of the Klarna authorization page that the customer is redirected to + PreferredLocale *string `form:"preferred_locale"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Subscription details if setting up or charging a subscription. + Subscriptions []*PaymentIntentPaymentMethodOptionsKlarnaSubscriptionParams `form:"subscriptions"` +} + +// If this is a `konbini` PaymentMethod, this sub-hash contains details about the Konbini payment method options. +type PaymentIntentPaymentMethodOptionsKonbiniParams struct { + // An optional 10 to 11 digit numeric-only string determining the confirmation code at applicable convenience stores. Must not consist of only zeroes and could be rejected in case of insufficient uniqueness. We recommend to use the customer's phone number. + ConfirmationNumber *string `form:"confirmation_number"` + // The number of calendar days (between 1 and 60) after which Konbini payment instructions will expire. For example, if a PaymentIntent is confirmed with Konbini and `expires_after_days` set to 2 on Monday JST, the instructions will expire on Wednesday 23:59:59 JST. Defaults to 3 days. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // The timestamp at which the Konbini payment instructions will expire. Only one of `expires_after_days` or `expires_at` may be set. + ExpiresAt *int64 `form:"expires_at"` + // A product descriptor of up to 22 characters, which will appear to customers at the convenience store. + ProductDescription *string `form:"product_description"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `kr_card` PaymentMethod, this sub-hash contains details about the KR Card payment method options. +type PaymentIntentPaymentMethodOptionsKrCardParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. +type PaymentIntentPaymentMethodOptionsLinkParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // [Deprecated] This is a legacy parameter that no longer has any function. + // Deprecated: + PersistentToken *string `form:"persistent_token"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `MobilePay` PaymentMethod, this sub-hash contains details about the MobilePay payment method options. +type PaymentIntentPaymentMethodOptionsMobilepayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `multibanco` PaymentMethod, this sub-hash contains details about the Multibanco payment method options. +type PaymentIntentPaymentMethodOptionsMultibancoParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `naver_pay` PaymentMethod, this sub-hash contains details about the Naver Pay payment method options. +type PaymentIntentPaymentMethodOptionsNaverPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `nz_bank_account` PaymentMethod, this sub-hash contains details about the NZ BECS Direct Debit payment method options. +type PaymentIntentPaymentMethodOptionsNzBankAccountParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// If this is a `oxxo` PaymentMethod, this sub-hash contains details about the OXXO payment method options. +type PaymentIntentPaymentMethodOptionsOXXOParams struct { + // The number of calendar days before an OXXO voucher expires. For example, if you create an OXXO voucher on Monday and you set expires_after_days to 2, the OXXO invoice will expire on Wednesday at 23:59 America/Mexico_City time. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `p24` PaymentMethod, this sub-hash contains details about the Przelewy24 payment method options. +type PaymentIntentPaymentMethodOptionsP24Params struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Confirm that the payer has accepted the P24 terms and conditions. + TOSShownAndAccepted *bool `form:"tos_shown_and_accepted"` +} + +// If this is a `pay_by_bank` PaymentMethod, this sub-hash contains details about the PayByBank payment method options. +type PaymentIntentPaymentMethodOptionsPayByBankParams struct{} + +// If this is a `payco` PaymentMethod, this sub-hash contains details about the PAYCO payment method options. +type PaymentIntentPaymentMethodOptionsPaycoParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// If this is a `paynow` PaymentMethod, this sub-hash contains details about the PayNow payment method options. +type PaymentIntentPaymentMethodOptionsPayNowParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. +type PaymentIntentPaymentMethodOptionsPaypalParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // [Preferred locale](https://stripe.com/docs/payments/paypal/supported-locales) of the PayPal checkout page that the customer is redirected to. + PreferredLocale *string `form:"preferred_locale"` + // A reference of the PayPal transaction visible to customer which is mapped to PayPal's invoice ID. This must be a globally unique ID if you have configured in your PayPal settings to block multiple payments per invoice ID. + Reference *string `form:"reference"` + // The risk correlation ID for an on-session payment using a saved PayPal payment method. + RiskCorrelationID *string `form:"risk_correlation_id"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `pix` PaymentMethod, this sub-hash contains details about the Pix payment method options. +type PaymentIntentPaymentMethodOptionsPixParams struct { + // The number of seconds (between 10 and 1209600) after which Pix payment will expire. Defaults to 86400 seconds. + ExpiresAfterSeconds *int64 `form:"expires_after_seconds"` + // The timestamp at which the Pix expires (between 10 and 1209600 seconds in the future). Defaults to 1 day in the future. + ExpiresAt *int64 `form:"expires_at"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `promptpay` PaymentMethod, this sub-hash contains details about the PromptPay payment method options. +type PaymentIntentPaymentMethodOptionsPromptPayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `revolut_pay` PaymentMethod, this sub-hash contains details about the Revolut Pay payment method options. +type PaymentIntentPaymentMethodOptionsRevolutPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `samsung_pay` PaymentMethod, this sub-hash contains details about the Samsung Pay payment method options. +type PaymentIntentPaymentMethodOptionsSamsungPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// If this is a `satispay` PaymentMethod, this sub-hash contains details about the Satispay payment method options. +type PaymentIntentPaymentMethodOptionsSatispayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// Additional fields for Mandate creation +type PaymentIntentPaymentMethodOptionsSEPADebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// If this is a `sepa_debit` PaymentIntent, this sub-hash contains details about the SEPA Debit payment method options. +type PaymentIntentPaymentMethodOptionsSEPADebitParams struct { + // Additional fields for Mandate creation + MandateOptions *PaymentIntentPaymentMethodOptionsSEPADebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// If this is a `sofort` PaymentMethod, this sub-hash contains details about the SOFORT payment method options. +type PaymentIntentPaymentMethodOptionsSofortParams struct { + // Language shown to the payer on redirect. + PreferredLanguage *string `form:"preferred_language"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `Swish` PaymentMethod, this sub-hash contains details about the Swish payment method options. +type PaymentIntentPaymentMethodOptionsSwishParams struct { + // A reference for this payment to be displayed in the Swish app. + Reference *string `form:"reference"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `twint` PaymentMethod, this sub-hash contains details about the TWINT payment method options. +type PaymentIntentPaymentMethodOptionsTWINTParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Provide filters for the linked accounts that the customer can select for the payment method. +type PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams struct { + // The account subcategories to use to filter for selectable accounts. Valid subcategories are `checking` and `savings`. + AccountSubcategories []*string `form:"account_subcategories"` +} + +// Additional fields for Financial Connections Session creation +type PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsParams struct { + // Provide filters for the linked accounts that the customer can select for the payment method. + Filters *PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams `form:"filters"` + // The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` + // For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + ReturnURL *string `form:"return_url"` +} + +// Additional fields for Mandate creation +type PaymentIntentPaymentMethodOptionsUSBankAccountMandateOptionsParams struct { + // The method used to collect offline mandate customer acceptance. + CollectionMethod *string `form:"collection_method"` +} + +// Additional fields for network related functions +type PaymentIntentPaymentMethodOptionsUSBankAccountNetworksParams struct { + // Triggers validations to run across the selected networks + Requested []*string `form:"requested"` +} + +// If this is a `us_bank_account` PaymentMethod, this sub-hash contains details about the US bank account payment method options. +type PaymentIntentPaymentMethodOptionsUSBankAccountParams struct { + // Additional fields for Financial Connections Session creation + FinancialConnections *PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsParams `form:"financial_connections"` + // Additional fields for Mandate creation + MandateOptions *PaymentIntentPaymentMethodOptionsUSBankAccountMandateOptionsParams `form:"mandate_options"` + // Additional fields for network related functions + Networks *PaymentIntentPaymentMethodOptionsUSBankAccountNetworksParams `form:"networks"` + // Preferred transaction settlement speed + PreferredSettlementSpeed *string `form:"preferred_settlement_speed"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` + // Bank account verification method. + VerificationMethod *string `form:"verification_method"` +} + +// If this is a `wechat_pay` PaymentMethod, this sub-hash contains details about the WeChat Pay payment method options. +type PaymentIntentPaymentMethodOptionsWeChatPayParams struct { + // The app ID registered with WeChat Pay. Only required when client is ios or android. + AppID *string `form:"app_id"` + // The client type that the end customer will pay from + Client *string `form:"client"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `zip` PaymentMethod, this sub-hash contains details about the Zip payment method options. +type PaymentIntentPaymentMethodOptionsZipParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Payment method-specific configuration for this PaymentIntent. +type PaymentIntentPaymentMethodOptionsParams struct { + // If this is a `acss_debit` PaymentMethod, this sub-hash contains details about the ACSS Debit payment method options. + ACSSDebit *PaymentIntentPaymentMethodOptionsACSSDebitParams `form:"acss_debit"` + // If this is an `affirm` PaymentMethod, this sub-hash contains details about the Affirm payment method options. + Affirm *PaymentIntentPaymentMethodOptionsAffirmParams `form:"affirm"` + // If this is a `afterpay_clearpay` PaymentMethod, this sub-hash contains details about the Afterpay Clearpay payment method options. + AfterpayClearpay *PaymentIntentPaymentMethodOptionsAfterpayClearpayParams `form:"afterpay_clearpay"` + // If this is a `alipay` PaymentMethod, this sub-hash contains details about the Alipay payment method options. + Alipay *PaymentIntentPaymentMethodOptionsAlipayParams `form:"alipay"` + // If this is a `alma` PaymentMethod, this sub-hash contains details about the Alma payment method options. + Alma *PaymentIntentPaymentMethodOptionsAlmaParams `form:"alma"` + // If this is a `amazon_pay` PaymentMethod, this sub-hash contains details about the Amazon Pay payment method options. + AmazonPay *PaymentIntentPaymentMethodOptionsAmazonPayParams `form:"amazon_pay"` + // If this is a `au_becs_debit` PaymentMethod, this sub-hash contains details about the AU BECS Direct Debit payment method options. + AUBECSDebit *PaymentIntentPaymentMethodOptionsAUBECSDebitParams `form:"au_becs_debit"` + // If this is a `bacs_debit` PaymentMethod, this sub-hash contains details about the BACS Debit payment method options. + BACSDebit *PaymentIntentPaymentMethodOptionsBACSDebitParams `form:"bacs_debit"` + // If this is a `bancontact` PaymentMethod, this sub-hash contains details about the Bancontact payment method options. + Bancontact *PaymentIntentPaymentMethodOptionsBancontactParams `form:"bancontact"` + // If this is a `billie` PaymentMethod, this sub-hash contains details about the Billie payment method options. + Billie *PaymentIntentPaymentMethodOptionsBillieParams `form:"billie"` + // If this is a `blik` PaymentMethod, this sub-hash contains details about the BLIK payment method options. + BLIK *PaymentIntentPaymentMethodOptionsBLIKParams `form:"blik"` + // If this is a `boleto` PaymentMethod, this sub-hash contains details about the Boleto payment method options. + Boleto *PaymentIntentPaymentMethodOptionsBoletoParams `form:"boleto"` + // Configuration for any card payments attempted on this PaymentIntent. + Card *PaymentIntentPaymentMethodOptionsCardParams `form:"card"` + // If this is a `card_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. + CardPresent *PaymentIntentPaymentMethodOptionsCardPresentParams `form:"card_present"` + // If this is a `cashapp` PaymentMethod, this sub-hash contains details about the Cash App Pay payment method options. + CashApp *PaymentIntentPaymentMethodOptionsCashAppParams `form:"cashapp"` + // If this is a `crypto` PaymentMethod, this sub-hash contains details about the Crypto payment method options. + Crypto *PaymentIntentPaymentMethodOptionsCryptoParams `form:"crypto"` + // If this is a `customer balance` PaymentMethod, this sub-hash contains details about the customer balance payment method options. + CustomerBalance *PaymentIntentPaymentMethodOptionsCustomerBalanceParams `form:"customer_balance"` + // If this is a `eps` PaymentMethod, this sub-hash contains details about the EPS payment method options. + EPS *PaymentIntentPaymentMethodOptionsEPSParams `form:"eps"` + // If this is a `fpx` PaymentMethod, this sub-hash contains details about the FPX payment method options. + FPX *PaymentIntentPaymentMethodOptionsFPXParams `form:"fpx"` + // If this is a `giropay` PaymentMethod, this sub-hash contains details about the Giropay payment method options. + Giropay *PaymentIntentPaymentMethodOptionsGiropayParams `form:"giropay"` + // If this is a `grabpay` PaymentMethod, this sub-hash contains details about the Grabpay payment method options. + Grabpay *PaymentIntentPaymentMethodOptionsGrabpayParams `form:"grabpay"` + // If this is a `ideal` PaymentMethod, this sub-hash contains details about the Ideal payment method options. + IDEAL *PaymentIntentPaymentMethodOptionsIDEALParams `form:"ideal"` + // If this is a `interac_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. + InteracPresent *PaymentIntentPaymentMethodOptionsInteracPresentParams `form:"interac_present"` + // If this is a `kakao_pay` PaymentMethod, this sub-hash contains details about the Kakao Pay payment method options. + KakaoPay *PaymentIntentPaymentMethodOptionsKakaoPayParams `form:"kakao_pay"` + // If this is a `klarna` PaymentMethod, this sub-hash contains details about the Klarna payment method options. + Klarna *PaymentIntentPaymentMethodOptionsKlarnaParams `form:"klarna"` + // If this is a `konbini` PaymentMethod, this sub-hash contains details about the Konbini payment method options. + Konbini *PaymentIntentPaymentMethodOptionsKonbiniParams `form:"konbini"` + // If this is a `kr_card` PaymentMethod, this sub-hash contains details about the KR Card payment method options. + KrCard *PaymentIntentPaymentMethodOptionsKrCardParams `form:"kr_card"` + // If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. + Link *PaymentIntentPaymentMethodOptionsLinkParams `form:"link"` + // If this is a `MobilePay` PaymentMethod, this sub-hash contains details about the MobilePay payment method options. + Mobilepay *PaymentIntentPaymentMethodOptionsMobilepayParams `form:"mobilepay"` + // If this is a `multibanco` PaymentMethod, this sub-hash contains details about the Multibanco payment method options. + Multibanco *PaymentIntentPaymentMethodOptionsMultibancoParams `form:"multibanco"` + // If this is a `naver_pay` PaymentMethod, this sub-hash contains details about the Naver Pay payment method options. + NaverPay *PaymentIntentPaymentMethodOptionsNaverPayParams `form:"naver_pay"` + // If this is a `nz_bank_account` PaymentMethod, this sub-hash contains details about the NZ BECS Direct Debit payment method options. + NzBankAccount *PaymentIntentPaymentMethodOptionsNzBankAccountParams `form:"nz_bank_account"` + // If this is a `oxxo` PaymentMethod, this sub-hash contains details about the OXXO payment method options. + OXXO *PaymentIntentPaymentMethodOptionsOXXOParams `form:"oxxo"` + // If this is a `p24` PaymentMethod, this sub-hash contains details about the Przelewy24 payment method options. + P24 *PaymentIntentPaymentMethodOptionsP24Params `form:"p24"` + // If this is a `pay_by_bank` PaymentMethod, this sub-hash contains details about the PayByBank payment method options. + PayByBank *PaymentIntentPaymentMethodOptionsPayByBankParams `form:"pay_by_bank"` + // If this is a `payco` PaymentMethod, this sub-hash contains details about the PAYCO payment method options. + Payco *PaymentIntentPaymentMethodOptionsPaycoParams `form:"payco"` + // If this is a `paynow` PaymentMethod, this sub-hash contains details about the PayNow payment method options. + PayNow *PaymentIntentPaymentMethodOptionsPayNowParams `form:"paynow"` + // If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. + Paypal *PaymentIntentPaymentMethodOptionsPaypalParams `form:"paypal"` + // If this is a `pix` PaymentMethod, this sub-hash contains details about the Pix payment method options. + Pix *PaymentIntentPaymentMethodOptionsPixParams `form:"pix"` + // If this is a `promptpay` PaymentMethod, this sub-hash contains details about the PromptPay payment method options. + PromptPay *PaymentIntentPaymentMethodOptionsPromptPayParams `form:"promptpay"` + // If this is a `revolut_pay` PaymentMethod, this sub-hash contains details about the Revolut Pay payment method options. + RevolutPay *PaymentIntentPaymentMethodOptionsRevolutPayParams `form:"revolut_pay"` + // If this is a `samsung_pay` PaymentMethod, this sub-hash contains details about the Samsung Pay payment method options. + SamsungPay *PaymentIntentPaymentMethodOptionsSamsungPayParams `form:"samsung_pay"` + // If this is a `satispay` PaymentMethod, this sub-hash contains details about the Satispay payment method options. + Satispay *PaymentIntentPaymentMethodOptionsSatispayParams `form:"satispay"` + // If this is a `sepa_debit` PaymentIntent, this sub-hash contains details about the SEPA Debit payment method options. + SEPADebit *PaymentIntentPaymentMethodOptionsSEPADebitParams `form:"sepa_debit"` + // If this is a `sofort` PaymentMethod, this sub-hash contains details about the SOFORT payment method options. + Sofort *PaymentIntentPaymentMethodOptionsSofortParams `form:"sofort"` + // If this is a `Swish` PaymentMethod, this sub-hash contains details about the Swish payment method options. + Swish *PaymentIntentPaymentMethodOptionsSwishParams `form:"swish"` + // If this is a `twint` PaymentMethod, this sub-hash contains details about the TWINT payment method options. + TWINT *PaymentIntentPaymentMethodOptionsTWINTParams `form:"twint"` + // If this is a `us_bank_account` PaymentMethod, this sub-hash contains details about the US bank account payment method options. + USBankAccount *PaymentIntentPaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` + // If this is a `wechat_pay` PaymentMethod, this sub-hash contains details about the WeChat Pay payment method options. + WeChatPay *PaymentIntentPaymentMethodOptionsWeChatPayParams `form:"wechat_pay"` + // If this is a `zip` PaymentMethod, this sub-hash contains details about the Zip payment method options. + Zip *PaymentIntentPaymentMethodOptionsZipParams `form:"zip"` +} + +// Options to configure Radar. Learn more about [Radar Sessions](https://stripe.com/docs/radar/radar-session). +type PaymentIntentRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// The parameters that you can use to automatically create a Transfer. +// Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). +type PaymentIntentTransferDataParams struct { + // The amount that will be transferred automatically when a charge succeeds. + // The amount is capped at the total transaction amount and if no amount is set, + // the full amount is transferred. + // + // If you intend to collect a fee and you need a more robust reporting experience, using + // [application_fee_amount](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-application_fee_amount) + // might be a better fit for your integration. + Amount *int64 `form:"amount"` + // If specified, successful charges will be attributed to the destination + // account for tax reporting, and the funds from charges will be transferred + // to the destination account. The ID of the resulting transfer will be + // returned on the successful charge's `transfer` field. + Destination *string `form:"destination"` +} + +// Creates a PaymentIntent object. +// +// After the PaymentIntent is created, attach a payment method and [confirm](https://docs.stripe.com/docs/api/payment_intents/confirm) +// to continue the payment. Learn more about the available payment flows +// with the Payment Intents API. +// +// When you use confirm=true during creation, it's equivalent to creating +// and confirming the PaymentIntent in the same call. You can use any parameters +// available in the [confirm API](https://docs.stripe.com/docs/api/payment_intents/confirm) when you supply +// confirm=true. +type PaymentIntentParams struct { + Params `form:"*"` + // Amount intended to be collected by this PaymentIntent. A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + Amount *int64 `form:"amount"` + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. The amount of the application fee collected will be capped at the total amount captured. For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // When you enable this parameter, this PaymentIntent accepts payment methods that you enable in the Dashboard and that are compatible with this PaymentIntent's other parameters. + AutomaticPaymentMethods *PaymentIntentAutomaticPaymentMethodsParams `form:"automatic_payment_methods"` + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // The client secret of the PaymentIntent. We require it if you use a publishable key to retrieve the source. + ClientSecret *string `form:"client_secret"` + // Set to `true` to attempt to [confirm this PaymentIntent](https://stripe.com/docs/api/payment_intents/confirm) immediately. This parameter defaults to `false`. When creating and confirming a PaymentIntent at the same time, you can also provide the parameters available in the [Confirm API](https://stripe.com/docs/api/payment_intents/confirm). + Confirm *bool `form:"confirm"` + // Describes whether we can confirm this PaymentIntent automatically, or if it requires customer action to confirm the payment. + ConfirmationMethod *string `form:"confirmation_method"` + // ID of the ConfirmationToken used to confirm this PaymentIntent. + // + // If the provided ConfirmationToken contains properties that are also being provided in this request, such as `payment_method`, then the values in this request will take precedence. + ConfirmationToken *string `form:"confirmation_token"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // ID of the Customer this PaymentIntent belongs to, if one exists. + // + // Payment methods attached to other Customers cannot be used with this PaymentIntent. + // + // If [setup_future_usage](https://stripe.com/docs/api#payment_intent_object-setup_future_usage) is set and this PaymentIntent's payment method is not `card_present`, then the payment method attaches to the Customer after the PaymentIntent has been confirmed and any required actions from the user are complete. If the payment method is `card_present` and isn't a digital wallet, then a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card is created and attached to the Customer instead. + Customer *string `form:"customer"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // ID of the mandate that's used for this payment. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + Mandate *string `form:"mandate"` + // This hash contains details about the Mandate to create. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + MandateData *PaymentIntentMandateDataParams `form:"mandate_data"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The Stripe account ID that these funds are intended for. Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + OnBehalfOf *string `form:"on_behalf_of"` + // ID of the payment method (a PaymentMethod, Card, or [compatible Source](https://stripe.com/docs/payments/payment-methods#compatibility) object) to attach to this PaymentIntent. + // + // If you don't provide the `payment_method` parameter or the `source` parameter with `confirm=true`, `source` automatically populates with `customer.default_source` to improve migration for users of the Charges API. We recommend that you explicitly provide the `payment_method` moving forward. + // If the payment method is attached to a Customer, you must also provide the ID of that Customer as the [customer](https://stripe.com/docs/api#create_payment_intent-customer) parameter of this PaymentIntent. + // end + PaymentMethod *string `form:"payment_method"` + // The ID of the [payment method configuration](https://stripe.com/docs/api/payment_method_configurations) to use with this PaymentIntent. + PaymentMethodConfiguration *string `form:"payment_method_configuration"` + // If provided, this hash will be used to create a PaymentMethod. The new PaymentMethod will appear + // in the [payment_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-payment_method) + // property on the PaymentIntent. + PaymentMethodData *PaymentIntentPaymentMethodDataParams `form:"payment_method_data"` + // Payment-method-specific configuration for this PaymentIntent. + PaymentMethodOptions *PaymentIntentPaymentMethodOptionsParams `form:"payment_method_options"` + // The list of payment method types (for example, a card) that this PaymentIntent can use. If you don't provide this, Stripe will dynamically show relevant payment methods from your [payment method settings](https://dashboard.stripe.com/settings/payment_methods). A list of valid payment method types can be found [here](https://docs.stripe.com/api/payment_methods/object#payment_method_object-type). + PaymentMethodTypes []*string `form:"payment_method_types"` + // Options to configure Radar. Learn more about [Radar Sessions](https://stripe.com/docs/radar/radar-session). + RadarOptions *PaymentIntentRadarOptionsParams `form:"radar_options"` + // Email address that the receipt for the resulting payment will be sent to. If `receipt_email` is specified for a payment in live mode, a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). + ReceiptEmail *string `form:"receipt_email"` + // The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method's app or site. If you'd prefer to redirect to a mobile application, you can alternatively supply an application URI scheme. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + ReturnURL *string `form:"return_url"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Shipping information for this PaymentIntent. + Shipping *ShippingDetailsParams `form:"shipping"` + // Text that appears on the customer's statement as the statement descriptor for a non-card charge. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + // + // Setting this value for a card charge returns an error. For card charges, set the [statement_descriptor_suffix](https://docs.stripe.com/get-started/account/statement-descriptors#dynamic) instead. + StatementDescriptor *string `form:"statement_descriptor"` + // Provides information about a card charge. Concatenated to the account's [statement descriptor prefix](https://docs.stripe.com/get-started/account/statement-descriptors#static) to form the complete statement descriptor that appears on the customer's statement. + StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"` + // Use this parameter to automatically create a Transfer when the payment succeeds. Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + TransferData *PaymentIntentTransferDataParams `form:"transfer_data"` + // A string that identifies the resulting payment as part of a group. You can only provide `transfer_group` if it hasn't been set. Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + TransferGroup *string `form:"transfer_group"` + // These parameters apply only for paymentIntent.New with `confirm=true` + // Set to `true` to fail the payment attempt if the PaymentIntent transitions into `requires_action`. Use this parameter for simpler integrations that don't handle customer actions, such as [saving cards without authentication](https://stripe.com/docs/payments/save-card-without-authentication). This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + ErrorOnRequiresAction *bool `form:"error_on_requires_action"` + // Set to `true` to indicate that the customer isn't in your checkout flow during this payment attempt and can't authenticate. Use this parameter in scenarios where you collect card details and [charge them later](https://stripe.com/docs/payments/cards/charging-saved-cards). This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + OffSession *bool `form:"off_session"` + // Set to `true` when confirming server-side and using Stripe.js, iOS, or Android client-side SDKs to handle the next actions. + UseStripeSDK *bool `form:"use_stripe_sdk"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentIntentParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentIntentParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Search for PaymentIntents you've previously created using Stripe's [Search Query Language](https://docs.stripe.com/docs/search#search-query-language). +// Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating +// conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up +// to an hour behind during outages. Search functionality is not available to merchants in India. +type PaymentIntentSearchParams struct { + SearchParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + Page *string `form:"page"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentIntentSearchParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Manually reconcile the remaining amount for a customer_balance PaymentIntent. +type PaymentIntentApplyCustomerBalanceParams struct { + Params `form:"*"` + // Amount that you intend to apply to this PaymentIntent from the customer's cash balance. If the PaymentIntent was created by an Invoice, the full amount of the PaymentIntent is applied regardless of this parameter. + // + // A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (for example, 100 cents to charge 1 USD or 100 to charge 100 JPY, a zero-decimal currency). The maximum amount is the amount of the PaymentIntent. + // + // When you omit the amount, it defaults to the remaining amount requested on the PaymentIntent. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentIntentApplyCustomerBalanceParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// You can cancel a PaymentIntent object when it's in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_action or, [in rare cases](https://docs.stripe.com/docs/payments/intents), processing. +// +// After it's canceled, no additional charges are made by the PaymentIntent and any operations on the PaymentIntent fail with an error. For PaymentIntents with a status of requires_capture, the remaining amount_capturable is automatically refunded. +// +// You can't cancel the PaymentIntent for a Checkout Session. [Expire the Checkout Session](https://docs.stripe.com/docs/api/checkout/sessions/expire) instead. +type PaymentIntentCancelParams struct { + Params `form:"*"` + // Reason for canceling this PaymentIntent. Possible values are: `duplicate`, `fraudulent`, `requested_by_customer`, or `abandoned` + CancellationReason *string `form:"cancellation_reason"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentIntentCancelParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Capture the funds of an existing uncaptured PaymentIntent when its status is requires_capture. +// +// Uncaptured PaymentIntents are cancelled a set number of days (7 by default) after their creation. +// +// Learn more about [separate authorization and capture](https://docs.stripe.com/docs/payments/capture-later). +type PaymentIntentCaptureParams struct { + Params `form:"*"` + // The amount to capture from the PaymentIntent, which must be less than or equal to the original amount. Defaults to the full `amount_capturable` if it's not provided. + AmountToCapture *int64 `form:"amount_to_capture"` + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. The amount of the application fee collected will be capped at the total amount captured. For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Defaults to `true`. When capturing a PaymentIntent, setting `final_capture` to `false` notifies Stripe to not release the remaining uncaptured funds to make sure that they're captured in future requests. You can only use this setting when [multicapture](https://stripe.com/docs/payments/multicapture) is available for PaymentIntents. + FinalCapture *bool `form:"final_capture"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Text that appears on the customer's statement as the statement descriptor for a non-card charge. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + // + // Setting this value for a card charge returns an error. For card charges, set the [statement_descriptor_suffix](https://docs.stripe.com/get-started/account/statement-descriptors#dynamic) instead. + StatementDescriptor *string `form:"statement_descriptor"` + // Provides information about a card charge. Concatenated to the account's [statement descriptor prefix](https://docs.stripe.com/get-started/account/statement-descriptors#static) to form the complete statement descriptor that appears on the customer's statement. + StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"` + // The parameters that you can use to automatically create a transfer after the payment + // is captured. Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + TransferData *PaymentIntentTransferDataParams `form:"transfer_data"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentIntentCaptureParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentIntentCaptureParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Options to configure Radar. Learn more about [Radar Sessions](https://stripe.com/docs/radar/radar-session). +type PaymentIntentConfirmRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// Confirm that your customer intends to pay with current or provided +// payment method. Upon confirmation, the PaymentIntent will attempt to initiate +// a payment. +// If the selected payment method requires additional authentication steps, the +// PaymentIntent will transition to the requires_action status and +// suggest additional actions via next_action. If payment fails, +// the PaymentIntent transitions to the requires_payment_method status or the +// canceled status if the confirmation limit is reached. If +// payment succeeds, the PaymentIntent will transition to the succeeded +// status (or requires_capture, if capture_method is set to manual). +// If the confirmation_method is automatic, payment may be attempted +// using our [client SDKs](https://docs.stripe.com/docs/stripe-js/reference#stripe-handle-card-payment) +// and the PaymentIntent's [client_secret](https://docs.stripe.com/api#payment_intent_object-client_secret). +// After next_actions are handled by the client, no additional +// confirmation is required to complete the payment. +// If the confirmation_method is manual, all payment attempts must be +// initiated using a secret key. +// If any actions are required for the payment, the PaymentIntent will +// return to the requires_confirmation state +// after those actions are completed. Your server needs to then +// explicitly re-confirm the PaymentIntent to initiate the next payment +// attempt. +// There is a variable upper limit on how many times a PaymentIntent can be confirmed. +// After this limit is reached, any further calls to this endpoint will +// transition the PaymentIntent to the canceled state. +type PaymentIntentConfirmParams struct { + Params `form:"*"` + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // ID of the ConfirmationToken used to confirm this PaymentIntent. + // + // If the provided ConfirmationToken contains properties that are also being provided in this request, such as `payment_method`, then the values in this request will take precedence. + ConfirmationToken *string `form:"confirmation_token"` + // Set to `true` to fail the payment attempt if the PaymentIntent transitions into `requires_action`. This parameter is intended for simpler integrations that do not handle customer actions, like [saving cards without authentication](https://stripe.com/docs/payments/save-card-without-authentication). + ErrorOnRequiresAction *bool `form:"error_on_requires_action"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // ID of the mandate that's used for this payment. + Mandate *string `form:"mandate"` + MandateData *PaymentIntentMandateDataParams `form:"mandate_data"` + // Set to `true` to indicate that the customer isn't in your checkout flow during this payment attempt and can't authenticate. Use this parameter in scenarios where you collect card details and [charge them later](https://stripe.com/docs/payments/cards/charging-saved-cards). + OffSession *bool `form:"off_session"` + // ID of the payment method (a PaymentMethod, Card, or [compatible Source](https://stripe.com/docs/payments/payment-methods/transitioning#compatibility) object) to attach to this PaymentIntent. + // If the payment method is attached to a Customer, it must match the [customer](https://stripe.com/docs/api#create_payment_intent-customer) that is set on this PaymentIntent. + PaymentMethod *string `form:"payment_method"` + // If provided, this hash will be used to create a PaymentMethod. The new PaymentMethod will appear + // in the [payment_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-payment_method) + // property on the PaymentIntent. + PaymentMethodData *PaymentIntentPaymentMethodDataParams `form:"payment_method_data"` + // Payment method-specific configuration for this PaymentIntent. + PaymentMethodOptions *PaymentIntentPaymentMethodOptionsParams `form:"payment_method_options"` + // The list of payment method types (for example, a card) that this PaymentIntent can use. Use `automatic_payment_methods` to manage payment methods from the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). A list of valid payment method types can be found [here](https://docs.stripe.com/api/payment_methods/object#payment_method_object-type). + PaymentMethodTypes []*string `form:"payment_method_types"` + // Options to configure Radar. Learn more about [Radar Sessions](https://stripe.com/docs/radar/radar-session). + RadarOptions *PaymentIntentConfirmRadarOptionsParams `form:"radar_options"` + // Email address that the receipt for the resulting payment will be sent to. If `receipt_email` is specified for a payment in live mode, a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). + ReceiptEmail *string `form:"receipt_email"` + // The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method's app or site. + // If you'd prefer to redirect to a mobile application, you can alternatively supply an application URI scheme. + // This parameter is only used for cards and other redirect-based payment methods. + ReturnURL *string `form:"return_url"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Shipping information for this PaymentIntent. + Shipping *ShippingDetailsParams `form:"shipping"` + // Set to `true` when confirming server-side and using Stripe.js, iOS, or Android client-side SDKs to handle the next actions. + UseStripeSDK *bool `form:"use_stripe_sdk"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentIntentConfirmParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The parameters used to automatically create a transfer after the payment is captured. +// Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). +type PaymentIntentIncrementAuthorizationTransferDataParams struct { + // The amount that will be transferred automatically when a charge succeeds. + Amount *int64 `form:"amount"` +} + +// Perform an incremental authorization on an eligible +// [PaymentIntent](https://docs.stripe.com/docs/api/payment_intents/object). To be eligible, the +// PaymentIntent's status must be requires_capture and +// [incremental_authorization_supported](https://docs.stripe.com/docs/api/charges/object#charge_object-payment_method_details-card_present-incremental_authorization_supported) +// must be true. +// +// Incremental authorizations attempt to increase the authorized amount on +// your customer's card to the new, higher amount provided. Similar to the +// initial authorization, incremental authorizations can be declined. A +// single PaymentIntent can call this endpoint multiple times to further +// increase the authorized amount. +// +// If the incremental authorization succeeds, the PaymentIntent object +// returns with the updated +// [amount](https://docs.stripe.com/docs/api/payment_intents/object#payment_intent_object-amount). +// If the incremental authorization fails, a +// [card_declined](https://docs.stripe.com/docs/error-codes#card-declined) error returns, and no other +// fields on the PaymentIntent or Charge update. The PaymentIntent +// object remains capturable for the previously authorized amount. +// +// Each PaymentIntent can have a maximum of 10 incremental authorization attempts, including declines. +// After it's captured, a PaymentIntent can no longer be incremented. +// +// Learn more about [incremental authorizations](https://docs.stripe.com/docs/terminal/features/incremental-authorizations). +type PaymentIntentIncrementAuthorizationParams struct { + Params `form:"*"` + // The updated total amount that you intend to collect from the cardholder. This amount must be greater than the currently authorized amount. + Amount *int64 `form:"amount"` + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. The amount of the application fee collected will be capped at the total amount captured. For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Text that appears on the customer's statement as the statement descriptor for a non-card or card charge. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + StatementDescriptor *string `form:"statement_descriptor"` + // The parameters used to automatically create a transfer after the payment is captured. + // Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + TransferData *PaymentIntentIncrementAuthorizationTransferDataParams `form:"transfer_data"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentIntentIncrementAuthorizationParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentIntentIncrementAuthorizationParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Verifies microdeposits on a PaymentIntent object. +type PaymentIntentVerifyMicrodepositsParams struct { + Params `form:"*"` + // Two positive integers, in *cents*, equal to the values of the microdeposits sent to the bank account. + Amounts []*int64 `form:"amounts"` + // A six-character code starting with SM present in the microdeposit sent to the bank account. + DescriptorCode *string `form:"descriptor_code"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentIntentVerifyMicrodepositsParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When you enable this parameter, this PaymentIntent accepts payment methods that you enable in the Dashboard and that are compatible with this PaymentIntent's other parameters. +type PaymentIntentCreateAutomaticPaymentMethodsParams struct { + // Controls whether this PaymentIntent will accept redirect-based payment methods. + // + // Redirect-based payment methods may require your customer to be redirected to a payment method's app or site for authentication or additional steps. To [confirm](https://stripe.com/docs/api/payment_intents/confirm) this PaymentIntent, you may be required to provide a `return_url` to redirect customers back to your site after they authenticate or complete the payment. + AllowRedirects *string `form:"allow_redirects"` + // Whether this feature is enabled. + Enabled *bool `form:"enabled"` +} + +// If this is a Mandate accepted offline, this hash contains details about the offline acceptance. +type PaymentIntentCreateMandateDataCustomerAcceptanceOfflineParams struct{} + +// If this is a Mandate accepted online, this hash contains details about the online acceptance. +type PaymentIntentCreateMandateDataCustomerAcceptanceOnlineParams struct { + // The IP address from which the Mandate was accepted by the customer. + IPAddress *string `form:"ip_address"` + // The user agent of the browser from which the Mandate was accepted by the customer. + UserAgent *string `form:"user_agent"` +} + +// This hash contains details about the customer acceptance of the Mandate. +type PaymentIntentCreateMandateDataCustomerAcceptanceParams struct { + // The time at which the customer accepted the Mandate. + AcceptedAt *int64 `form:"accepted_at"` + // If this is a Mandate accepted offline, this hash contains details about the offline acceptance. + Offline *PaymentIntentCreateMandateDataCustomerAcceptanceOfflineParams `form:"offline"` + // If this is a Mandate accepted online, this hash contains details about the online acceptance. + Online *PaymentIntentCreateMandateDataCustomerAcceptanceOnlineParams `form:"online"` + // The type of customer acceptance information included with the Mandate. One of `online` or `offline`. + Type *string `form:"type"` +} + +// This hash contains details about the Mandate to create. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). +type PaymentIntentCreateMandateDataParams struct { + // This hash contains details about the customer acceptance of the Mandate. + CustomerAcceptance *PaymentIntentCreateMandateDataCustomerAcceptanceParams `form:"customer_acceptance"` +} + +// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. +type PaymentIntentCreatePaymentMethodDataBillingDetailsParams struct { + // Billing address. + Address *AddressParams `form:"address"` + // Email address. + Email *string `form:"email"` + // Full name. + Name *string `form:"name"` + // Billing phone number (including extension). + Phone *string `form:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID *string `form:"tax_id"` +} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type PaymentIntentCreatePaymentMethodDataRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// If provided, this hash will be used to create a PaymentMethod. The new PaymentMethod will appear +// in the [payment_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-payment_method) +// property on the PaymentIntent. +type PaymentIntentCreatePaymentMethodDataParams struct { + // If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + ACSSDebit *PaymentMethodACSSDebitParams `form:"acss_debit"` + // If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + Affirm *PaymentMethodAffirmParams `form:"affirm"` + // If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + AfterpayClearpay *PaymentMethodAfterpayClearpayParams `form:"afterpay_clearpay"` + // If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + Alipay *PaymentMethodAlipayParams `form:"alipay"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to `unspecified`. + AllowRedisplay *string `form:"allow_redisplay"` + // If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. + Alma *PaymentMethodAlmaParams `form:"alma"` + // If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. + AmazonPay *PaymentMethodAmazonPayParams `form:"amazon_pay"` + // If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + AUBECSDebit *PaymentMethodAUBECSDebitParams `form:"au_becs_debit"` + // If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + BACSDebit *PaymentMethodBACSDebitParams `form:"bacs_debit"` + // If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + Bancontact *PaymentMethodBancontactParams `form:"bancontact"` + // If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. + Billie *PaymentMethodBillieParams `form:"billie"` + // Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + BillingDetails *PaymentIntentCreatePaymentMethodDataBillingDetailsParams `form:"billing_details"` + // If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + BLIK *PaymentMethodBLIKParams `form:"blik"` + // If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + Boleto *PaymentMethodBoletoParams `form:"boleto"` + // If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + CashApp *PaymentMethodCashAppParams `form:"cashapp"` + // If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. + Crypto *PaymentMethodCryptoParams `form:"crypto"` + // If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + CustomerBalance *PaymentMethodCustomerBalanceParams `form:"customer_balance"` + // If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + EPS *PaymentMethodEPSParams `form:"eps"` + // If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + FPX *PaymentMethodFPXParams `form:"fpx"` + // If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + Giropay *PaymentMethodGiropayParams `form:"giropay"` + // If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + Grabpay *PaymentMethodGrabpayParams `form:"grabpay"` + // If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + IDEAL *PaymentMethodIDEALParams `form:"ideal"` + // If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + InteracPresent *PaymentMethodInteracPresentParams `form:"interac_present"` + // If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. + KakaoPay *PaymentMethodKakaoPayParams `form:"kakao_pay"` + // If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + Klarna *PaymentMethodKlarnaParams `form:"klarna"` + // If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + Konbini *PaymentMethodKonbiniParams `form:"konbini"` + // If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. + KrCard *PaymentMethodKrCardParams `form:"kr_card"` + // If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + Link *PaymentMethodLinkParams `form:"link"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. + Mobilepay *PaymentMethodMobilepayParams `form:"mobilepay"` + // If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. + Multibanco *PaymentMethodMultibancoParams `form:"multibanco"` + // If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. + NaverPay *PaymentMethodNaverPayParams `form:"naver_pay"` + // If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. + NzBankAccount *PaymentMethodNzBankAccountParams `form:"nz_bank_account"` + // If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + OXXO *PaymentMethodOXXOParams `form:"oxxo"` + // If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + P24 *PaymentMethodP24Params `form:"p24"` + // If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. + PayByBank *PaymentMethodPayByBankParams `form:"pay_by_bank"` + // If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. + Payco *PaymentMethodPaycoParams `form:"payco"` + // If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + PayNow *PaymentMethodPayNowParams `form:"paynow"` + // If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + Paypal *PaymentMethodPaypalParams `form:"paypal"` + // If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + Pix *PaymentMethodPixParams `form:"pix"` + // If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + PromptPay *PaymentMethodPromptPayParams `form:"promptpay"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *PaymentIntentCreatePaymentMethodDataRadarOptionsParams `form:"radar_options"` + // If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + RevolutPay *PaymentMethodRevolutPayParams `form:"revolut_pay"` + // If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. + SamsungPay *PaymentMethodSamsungPayParams `form:"samsung_pay"` + // If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. + Satispay *PaymentMethodSatispayParams `form:"satispay"` + // If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + SEPADebit *PaymentMethodSEPADebitParams `form:"sepa_debit"` + // If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + Sofort *PaymentMethodSofortParams `form:"sofort"` + // If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. + Swish *PaymentMethodSwishParams `form:"swish"` + // If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. + TWINT *PaymentMethodTWINTParams `form:"twint"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type *string `form:"type"` + // If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + USBankAccount *PaymentMethodUSBankAccountParams `form:"us_bank_account"` + // If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + WeChatPay *PaymentMethodWeChatPayParams `form:"wechat_pay"` + // If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + Zip *PaymentMethodZipParams `form:"zip"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentIntentCreatePaymentMethodDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Additional fields for Mandate creation +type PaymentIntentCreatePaymentMethodOptionsACSSDebitMandateOptionsParams struct { + // A URL for custom mandate text to render during confirmation step. + // The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + // or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + CustomMandateURL *string `form:"custom_mandate_url"` + // Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + IntervalDescription *string `form:"interval_description"` + // Payment schedule for the mandate. + PaymentSchedule *string `form:"payment_schedule"` + // Transaction type of the mandate. + TransactionType *string `form:"transaction_type"` +} + +// If this is a `acss_debit` PaymentMethod, this sub-hash contains details about the ACSS Debit payment method options. +type PaymentIntentCreatePaymentMethodOptionsACSSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *PaymentIntentCreatePaymentMethodOptionsACSSDebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` + // Bank account verification method. + VerificationMethod *string `form:"verification_method"` +} + +// If this is an `affirm` PaymentMethod, this sub-hash contains details about the Affirm payment method options. +type PaymentIntentCreatePaymentMethodOptionsAffirmParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Preferred language of the Affirm authorization page that the customer is redirected to. + PreferredLocale *string `form:"preferred_locale"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `afterpay_clearpay` PaymentMethod, this sub-hash contains details about the Afterpay Clearpay payment method options. +type PaymentIntentCreatePaymentMethodOptionsAfterpayClearpayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // An internal identifier or reference that this payment corresponds to. You must limit the identifier to 128 characters, and it can only contain letters, numbers, underscores, backslashes, and dashes. + // This field differs from the statement descriptor and item name. + Reference *string `form:"reference"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `alipay` PaymentMethod, this sub-hash contains details about the Alipay payment method options. +type PaymentIntentCreatePaymentMethodOptionsAlipayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `alma` PaymentMethod, this sub-hash contains details about the Alma payment method options. +type PaymentIntentCreatePaymentMethodOptionsAlmaParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// If this is a `amazon_pay` PaymentMethod, this sub-hash contains details about the Amazon Pay payment method options. +type PaymentIntentCreatePaymentMethodOptionsAmazonPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `au_becs_debit` PaymentMethod, this sub-hash contains details about the AU BECS Direct Debit payment method options. +type PaymentIntentCreatePaymentMethodOptionsAUBECSDebitParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// Additional fields for Mandate creation +type PaymentIntentCreatePaymentMethodOptionsBACSDebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'DDIC' or 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// If this is a `bacs_debit` PaymentMethod, this sub-hash contains details about the BACS Debit payment method options. +type PaymentIntentCreatePaymentMethodOptionsBACSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *PaymentIntentCreatePaymentMethodOptionsBACSDebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// If this is a `bancontact` PaymentMethod, this sub-hash contains details about the Bancontact payment method options. +type PaymentIntentCreatePaymentMethodOptionsBancontactParams struct { + // Preferred language of the Bancontact authorization page that the customer is redirected to. + PreferredLanguage *string `form:"preferred_language"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `billie` PaymentMethod, this sub-hash contains details about the Billie payment method options. +type PaymentIntentCreatePaymentMethodOptionsBillieParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// If this is a `blik` PaymentMethod, this sub-hash contains details about the BLIK payment method options. +type PaymentIntentCreatePaymentMethodOptionsBLIKParams struct { + // The 6-digit BLIK code that a customer has generated using their banking application. Can only be set on confirmation. + Code *string `form:"code"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `boleto` PaymentMethod, this sub-hash contains details about the Boleto payment method options. +type PaymentIntentCreatePaymentMethodOptionsBoletoParams struct { + // The number of calendar days before a Boleto voucher expires. For example, if you create a Boleto voucher on Monday and you set expires_after_days to 2, the Boleto invoice will expire on Wednesday at 23:59 America/Sao_Paulo time. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// The selected installment plan to use for this payment attempt. +// This parameter can only be provided during confirmation. +type PaymentIntentCreatePaymentMethodOptionsCardInstallmentsPlanParams struct { + // For `fixed_count` installment plans, this is required. It represents the number of installment payments your customer will make to their credit card. + Count *int64 `form:"count"` + // For `fixed_count` installment plans, this is required. It represents the interval between installment payments your customer will make to their credit card. + // One of `month`. + Interval *string `form:"interval"` + // Type of installment plan, one of `fixed_count`, `bonus`, or `revolving`. + Type *string `form:"type"` +} + +// Installment configuration for payments attempted on this PaymentIntent (Mexico Only). +// +// For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). +type PaymentIntentCreatePaymentMethodOptionsCardInstallmentsParams struct { + // Setting to true enables installments for this PaymentIntent. + // This will cause the response to contain a list of available installment plans. + // Setting to false will prevent any selected plan from applying to a charge. + Enabled *bool `form:"enabled"` + // The selected installment plan to use for this payment attempt. + // This parameter can only be provided during confirmation. + Plan *PaymentIntentCreatePaymentMethodOptionsCardInstallmentsPlanParams `form:"plan"` +} + +// Configuration options for setting up an eMandate for cards issued in India. +type PaymentIntentCreatePaymentMethodOptionsCardMandateOptionsParams struct { + // Amount to be charged for future payments. + Amount *int64 `form:"amount"` + // One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + AmountType *string `form:"amount_type"` + // A description of the mandate or subscription that is meant to be displayed to the customer. + Description *string `form:"description"` + // End date of the mandate or subscription. If not provided, the mandate will be active until canceled. If provided, end date should be after start date. + EndDate *int64 `form:"end_date"` + // Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. + Interval *string `form:"interval"` + // The number of intervals between payments. For example, `interval=month` and `interval_count=3` indicates one payment every three months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). This parameter is optional when `interval=sporadic`. + IntervalCount *int64 `form:"interval_count"` + // Unique identifier for the mandate or subscription. + Reference *string `form:"reference"` + // Start date of the mandate or subscription. Start date should not be lesser than yesterday. + StartDate *int64 `form:"start_date"` + // Specifies the type of mandates supported. Possible values are `india`. + SupportedTypes []*string `form:"supported_types"` +} + +// Cartes Bancaires-specific 3DS fields. +type PaymentIntentCreatePaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancairesParams struct { + // The cryptogram calculation algorithm used by the card Issuer's ACS + // to calculate the Authentication cryptogram. Also known as `cavvAlgorithm`. + // messageExtension: CB-AVALGO + CbAvalgo *string `form:"cb_avalgo"` + // The exemption indicator returned from Cartes Bancaires in the ARes. + // message extension: CB-EXEMPTION; string (4 characters) + // This is a 3 byte bitmap (low significant byte first and most significant + // bit first) that has been Base64 encoded + CbExemption *string `form:"cb_exemption"` + // The risk score returned from Cartes Bancaires in the ARes. + // message extension: CB-SCORE; numeric value 0-99 + CbScore *int64 `form:"cb_score"` +} + +// Network specific 3DS fields. Network specific arguments require an +// explicit card brand choice. The parameter `payment_method_options.card.network“ +// must be populated accordingly +type PaymentIntentCreatePaymentMethodOptionsCardThreeDSecureNetworkOptionsParams struct { + // Cartes Bancaires-specific 3DS fields. + CartesBancaires *PaymentIntentCreatePaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancairesParams `form:"cartes_bancaires"` +} + +// If 3D Secure authentication was performed with a third-party provider, +// the authentication details to use for this payment. +type PaymentIntentCreatePaymentMethodOptionsCardThreeDSecureParams struct { + // The `transStatus` returned from the card Issuer's ACS in the ARes. + AresTransStatus *string `form:"ares_trans_status"` + // The cryptogram, also known as the "authentication value" (AAV, CAVV or + // AEVV). This value is 20 bytes, base64-encoded into a 28-character string. + // (Most 3D Secure providers will return the base64-encoded version, which + // is what you should specify here.) + Cryptogram *string `form:"cryptogram"` + // The Electronic Commerce Indicator (ECI) is returned by your 3D Secure + // provider and indicates what degree of authentication was performed. + ElectronicCommerceIndicator *string `form:"electronic_commerce_indicator"` + // The exemption requested via 3DS and accepted by the issuer at authentication time. + ExemptionIndicator *string `form:"exemption_indicator"` + // Network specific 3DS fields. Network specific arguments require an + // explicit card brand choice. The parameter `payment_method_options.card.network`` + // must be populated accordingly + NetworkOptions *PaymentIntentCreatePaymentMethodOptionsCardThreeDSecureNetworkOptionsParams `form:"network_options"` + // The challenge indicator (`threeDSRequestorChallengeInd`) which was requested in the + // AReq sent to the card Issuer's ACS. A string containing 2 digits from 01-99. + RequestorChallengeIndicator *string `form:"requestor_challenge_indicator"` + // For 3D Secure 1, the XID. For 3D Secure 2, the Directory Server + // Transaction ID (dsTransID). + TransactionID *string `form:"transaction_id"` + // The version of 3D Secure that was performed. + Version *string `form:"version"` +} + +// Configuration for any card payments attempted on this PaymentIntent. +type PaymentIntentCreatePaymentMethodOptionsCardParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // A single-use `cvc_update` Token that represents a card CVC value. When provided, the CVC value will be verified during the card payment attempt. This parameter can only be provided during confirmation. + CVCToken *string `form:"cvc_token"` + // Installment configuration for payments attempted on this PaymentIntent (Mexico Only). + // + // For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + Installments *PaymentIntentCreatePaymentMethodOptionsCardInstallmentsParams `form:"installments"` + // Configuration options for setting up an eMandate for cards issued in India. + MandateOptions *PaymentIntentCreatePaymentMethodOptionsCardMandateOptionsParams `form:"mandate_options"` + // When specified, this parameter indicates that a transaction will be marked + // as MOTO (Mail Order Telephone Order) and thus out of scope for SCA. This + // parameter can only be provided during confirmation. + MOTO *bool `form:"moto"` + // Selected network to process this PaymentIntent on. Depends on the available networks of the card attached to the PaymentIntent. Can be only set confirm-time. + Network *string `form:"network"` + // Request ability to [capture beyond the standard authorization validity window](https://stripe.com/docs/payments/extended-authorization) for this PaymentIntent. + RequestExtendedAuthorization *string `form:"request_extended_authorization"` + // Request ability to [increment the authorization](https://stripe.com/docs/payments/incremental-authorization) for this PaymentIntent. + RequestIncrementalAuthorization *string `form:"request_incremental_authorization"` + // Request ability to make [multiple captures](https://stripe.com/docs/payments/multicapture) for this PaymentIntent. + RequestMulticapture *string `form:"request_multicapture"` + // Request ability to [overcapture](https://stripe.com/docs/payments/overcapture) for this PaymentIntent. + RequestOvercapture *string `form:"request_overcapture"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure *string `form:"request_three_d_secure"` + // When enabled, using a card that is attached to a customer will require the CVC to be provided again (i.e. using the cvc_token parameter). + RequireCVCRecollection *bool `form:"require_cvc_recollection"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Provides information about a card payment that customers see on their statements. Concatenated with the Kana prefix (shortened Kana descriptor) or Kana statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 22 characters. + StatementDescriptorSuffixKana *string `form:"statement_descriptor_suffix_kana"` + // Provides information about a card payment that customers see on their statements. Concatenated with the Kanji prefix (shortened Kanji descriptor) or Kanji statement descriptor that's set on the account to form the complete statement descriptor. Maximum 17 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 17 characters. + StatementDescriptorSuffixKanji *string `form:"statement_descriptor_suffix_kanji"` + // If 3D Secure authentication was performed with a third-party provider, + // the authentication details to use for this payment. + ThreeDSecure *PaymentIntentCreatePaymentMethodOptionsCardThreeDSecureParams `form:"three_d_secure"` +} + +// Network routing priority on co-branded EMV cards supporting domestic debit and international card schemes. +type PaymentIntentCreatePaymentMethodOptionsCardPresentRoutingParams struct { + // Routing requested priority + RequestedPriority *string `form:"requested_priority"` +} + +// If this is a `card_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. +type PaymentIntentCreatePaymentMethodOptionsCardPresentParams struct { + // Request ability to capture this payment beyond the standard [authorization validity window](https://stripe.com/docs/terminal/features/extended-authorizations#authorization-validity) + RequestExtendedAuthorization *bool `form:"request_extended_authorization"` + // Request ability to [increment](https://stripe.com/docs/terminal/features/incremental-authorizations) this PaymentIntent if the combination of MCC and card brand is eligible. Check [incremental_authorization_supported](https://stripe.com/docs/api/charges/object#charge_object-payment_method_details-card_present-incremental_authorization_supported) in the [Confirm](https://stripe.com/docs/api/payment_intents/confirm) response to verify support. + RequestIncrementalAuthorizationSupport *bool `form:"request_incremental_authorization_support"` + // Network routing priority on co-branded EMV cards supporting domestic debit and international card schemes. + Routing *PaymentIntentCreatePaymentMethodOptionsCardPresentRoutingParams `form:"routing"` +} + +// If this is a `cashapp` PaymentMethod, this sub-hash contains details about the Cash App Pay payment method options. +type PaymentIntentCreatePaymentMethodOptionsCashAppParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `crypto` PaymentMethod, this sub-hash contains details about the Crypto payment method options. +type PaymentIntentCreatePaymentMethodOptionsCryptoParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Configuration for the eu_bank_transfer funding type. +type PaymentIntentCreatePaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country *string `form:"country"` +} + +// Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. +type PaymentIntentCreatePaymentMethodOptionsCustomerBalanceBankTransferParams struct { + // Configuration for the eu_bank_transfer funding type. + EUBankTransfer *PaymentIntentCreatePaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams `form:"eu_bank_transfer"` + // List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. + // + // Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. + RequestedAddressTypes []*string `form:"requested_address_types"` + // The list of bank transfer types that this PaymentIntent is allowed to use for funding Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + Type *string `form:"type"` +} + +// If this is a `customer balance` PaymentMethod, this sub-hash contains details about the customer balance payment method options. +type PaymentIntentCreatePaymentMethodOptionsCustomerBalanceParams struct { + // Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + BankTransfer *PaymentIntentCreatePaymentMethodOptionsCustomerBalanceBankTransferParams `form:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType *string `form:"funding_type"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `eps` PaymentMethod, this sub-hash contains details about the EPS payment method options. +type PaymentIntentCreatePaymentMethodOptionsEPSParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `fpx` PaymentMethod, this sub-hash contains details about the FPX payment method options. +type PaymentIntentCreatePaymentMethodOptionsFPXParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `giropay` PaymentMethod, this sub-hash contains details about the Giropay payment method options. +type PaymentIntentCreatePaymentMethodOptionsGiropayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `grabpay` PaymentMethod, this sub-hash contains details about the Grabpay payment method options. +type PaymentIntentCreatePaymentMethodOptionsGrabpayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `ideal` PaymentMethod, this sub-hash contains details about the Ideal payment method options. +type PaymentIntentCreatePaymentMethodOptionsIDEALParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `interac_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. +type PaymentIntentCreatePaymentMethodOptionsInteracPresentParams struct{} + +// If this is a `kakao_pay` PaymentMethod, this sub-hash contains details about the Kakao Pay payment method options. +type PaymentIntentCreatePaymentMethodOptionsKakaoPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// On-demand details if setting up or charging an on-demand payment. +type PaymentIntentCreatePaymentMethodOptionsKlarnaOnDemandParams struct { + // Your average amount value. You can use a value across your customer base, or segment based on customer type, country, etc. + AverageAmount *int64 `form:"average_amount"` + // The maximum value you may charge a customer per purchase. You can use a value across your customer base, or segment based on customer type, country, etc. + MaximumAmount *int64 `form:"maximum_amount"` + // The lowest or minimum value you may charge a customer per purchase. You can use a value across your customer base, or segment based on customer type, country, etc. + MinimumAmount *int64 `form:"minimum_amount"` + // Interval at which the customer is making purchases + PurchaseInterval *string `form:"purchase_interval"` + // The number of `purchase_interval` between charges + PurchaseIntervalCount *int64 `form:"purchase_interval_count"` +} + +// Describes the upcoming charge for this subscription. +type PaymentIntentCreatePaymentMethodOptionsKlarnaSubscriptionNextBillingParams struct { + // The amount of the next charge for the subscription. + Amount *int64 `form:"amount"` + // The date of the next charge for the subscription in YYYY-MM-DD format. + Date *string `form:"date"` +} + +// Subscription details if setting up or charging a subscription. +type PaymentIntentCreatePaymentMethodOptionsKlarnaSubscriptionParams struct { + // Unit of time between subscription charges. + Interval *string `form:"interval"` + // The number of intervals (specified in the `interval` attribute) between subscription charges. For example, `interval=month` and `interval_count=3` charges every 3 months. + IntervalCount *int64 `form:"interval_count"` + // Name for subscription. + Name *string `form:"name"` + // Describes the upcoming charge for this subscription. + NextBilling *PaymentIntentCreatePaymentMethodOptionsKlarnaSubscriptionNextBillingParams `form:"next_billing"` + // A non-customer-facing reference to correlate subscription charges in the Klarna app. Use a value that persists across subscription charges. + Reference *string `form:"reference"` +} + +// If this is a `klarna` PaymentMethod, this sub-hash contains details about the Klarna payment method options. +type PaymentIntentCreatePaymentMethodOptionsKlarnaParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // On-demand details if setting up or charging an on-demand payment. + OnDemand *PaymentIntentCreatePaymentMethodOptionsKlarnaOnDemandParams `form:"on_demand"` + // Preferred language of the Klarna authorization page that the customer is redirected to + PreferredLocale *string `form:"preferred_locale"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Subscription details if setting up or charging a subscription. + Subscriptions []*PaymentIntentCreatePaymentMethodOptionsKlarnaSubscriptionParams `form:"subscriptions"` +} + +// If this is a `konbini` PaymentMethod, this sub-hash contains details about the Konbini payment method options. +type PaymentIntentCreatePaymentMethodOptionsKonbiniParams struct { + // An optional 10 to 11 digit numeric-only string determining the confirmation code at applicable convenience stores. Must not consist of only zeroes and could be rejected in case of insufficient uniqueness. We recommend to use the customer's phone number. + ConfirmationNumber *string `form:"confirmation_number"` + // The number of calendar days (between 1 and 60) after which Konbini payment instructions will expire. For example, if a PaymentIntent is confirmed with Konbini and `expires_after_days` set to 2 on Monday JST, the instructions will expire on Wednesday 23:59:59 JST. Defaults to 3 days. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // The timestamp at which the Konbini payment instructions will expire. Only one of `expires_after_days` or `expires_at` may be set. + ExpiresAt *int64 `form:"expires_at"` + // A product descriptor of up to 22 characters, which will appear to customers at the convenience store. + ProductDescription *string `form:"product_description"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `kr_card` PaymentMethod, this sub-hash contains details about the KR Card payment method options. +type PaymentIntentCreatePaymentMethodOptionsKrCardParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. +type PaymentIntentCreatePaymentMethodOptionsLinkParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // [Deprecated] This is a legacy parameter that no longer has any function. + // Deprecated: + PersistentToken *string `form:"persistent_token"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `MobilePay` PaymentMethod, this sub-hash contains details about the MobilePay payment method options. +type PaymentIntentCreatePaymentMethodOptionsMobilepayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `multibanco` PaymentMethod, this sub-hash contains details about the Multibanco payment method options. +type PaymentIntentCreatePaymentMethodOptionsMultibancoParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `naver_pay` PaymentMethod, this sub-hash contains details about the Naver Pay payment method options. +type PaymentIntentCreatePaymentMethodOptionsNaverPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `nz_bank_account` PaymentMethod, this sub-hash contains details about the NZ BECS Direct Debit payment method options. +type PaymentIntentCreatePaymentMethodOptionsNzBankAccountParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// If this is a `oxxo` PaymentMethod, this sub-hash contains details about the OXXO payment method options. +type PaymentIntentCreatePaymentMethodOptionsOXXOParams struct { + // The number of calendar days before an OXXO voucher expires. For example, if you create an OXXO voucher on Monday and you set expires_after_days to 2, the OXXO invoice will expire on Wednesday at 23:59 America/Mexico_City time. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `p24` PaymentMethod, this sub-hash contains details about the Przelewy24 payment method options. +type PaymentIntentCreatePaymentMethodOptionsP24Params struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Confirm that the payer has accepted the P24 terms and conditions. + TOSShownAndAccepted *bool `form:"tos_shown_and_accepted"` +} + +// If this is a `pay_by_bank` PaymentMethod, this sub-hash contains details about the PayByBank payment method options. +type PaymentIntentCreatePaymentMethodOptionsPayByBankParams struct{} + +// If this is a `payco` PaymentMethod, this sub-hash contains details about the PAYCO payment method options. +type PaymentIntentCreatePaymentMethodOptionsPaycoParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// If this is a `paynow` PaymentMethod, this sub-hash contains details about the PayNow payment method options. +type PaymentIntentCreatePaymentMethodOptionsPayNowParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. +type PaymentIntentCreatePaymentMethodOptionsPaypalParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // [Preferred locale](https://stripe.com/docs/payments/paypal/supported-locales) of the PayPal checkout page that the customer is redirected to. + PreferredLocale *string `form:"preferred_locale"` + // A reference of the PayPal transaction visible to customer which is mapped to PayPal's invoice ID. This must be a globally unique ID if you have configured in your PayPal settings to block multiple payments per invoice ID. + Reference *string `form:"reference"` + // The risk correlation ID for an on-session payment using a saved PayPal payment method. + RiskCorrelationID *string `form:"risk_correlation_id"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `pix` PaymentMethod, this sub-hash contains details about the Pix payment method options. +type PaymentIntentCreatePaymentMethodOptionsPixParams struct { + // The number of seconds (between 10 and 1209600) after which Pix payment will expire. Defaults to 86400 seconds. + ExpiresAfterSeconds *int64 `form:"expires_after_seconds"` + // The timestamp at which the Pix expires (between 10 and 1209600 seconds in the future). Defaults to 1 day in the future. + ExpiresAt *int64 `form:"expires_at"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `promptpay` PaymentMethod, this sub-hash contains details about the PromptPay payment method options. +type PaymentIntentCreatePaymentMethodOptionsPromptPayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `revolut_pay` PaymentMethod, this sub-hash contains details about the Revolut Pay payment method options. +type PaymentIntentCreatePaymentMethodOptionsRevolutPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `samsung_pay` PaymentMethod, this sub-hash contains details about the Samsung Pay payment method options. +type PaymentIntentCreatePaymentMethodOptionsSamsungPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// If this is a `satispay` PaymentMethod, this sub-hash contains details about the Satispay payment method options. +type PaymentIntentCreatePaymentMethodOptionsSatispayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// Additional fields for Mandate creation +type PaymentIntentCreatePaymentMethodOptionsSEPADebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// If this is a `sepa_debit` PaymentIntent, this sub-hash contains details about the SEPA Debit payment method options. +type PaymentIntentCreatePaymentMethodOptionsSEPADebitParams struct { + // Additional fields for Mandate creation + MandateOptions *PaymentIntentCreatePaymentMethodOptionsSEPADebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// If this is a `sofort` PaymentMethod, this sub-hash contains details about the SOFORT payment method options. +type PaymentIntentCreatePaymentMethodOptionsSofortParams struct { + // Language shown to the payer on redirect. + PreferredLanguage *string `form:"preferred_language"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `Swish` PaymentMethod, this sub-hash contains details about the Swish payment method options. +type PaymentIntentCreatePaymentMethodOptionsSwishParams struct { + // A reference for this payment to be displayed in the Swish app. + Reference *string `form:"reference"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `twint` PaymentMethod, this sub-hash contains details about the TWINT payment method options. +type PaymentIntentCreatePaymentMethodOptionsTWINTParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Provide filters for the linked accounts that the customer can select for the payment method. +type PaymentIntentCreatePaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams struct { + // The account subcategories to use to filter for selectable accounts. Valid subcategories are `checking` and `savings`. + AccountSubcategories []*string `form:"account_subcategories"` +} + +// Additional fields for Financial Connections Session creation +type PaymentIntentCreatePaymentMethodOptionsUSBankAccountFinancialConnectionsParams struct { + // Provide filters for the linked accounts that the customer can select for the payment method. + Filters *PaymentIntentCreatePaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams `form:"filters"` + // The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` + // For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + ReturnURL *string `form:"return_url"` +} + +// Additional fields for Mandate creation +type PaymentIntentCreatePaymentMethodOptionsUSBankAccountMandateOptionsParams struct { + // The method used to collect offline mandate customer acceptance. + CollectionMethod *string `form:"collection_method"` +} + +// Additional fields for network related functions +type PaymentIntentCreatePaymentMethodOptionsUSBankAccountNetworksParams struct { + // Triggers validations to run across the selected networks + Requested []*string `form:"requested"` +} + +// If this is a `us_bank_account` PaymentMethod, this sub-hash contains details about the US bank account payment method options. +type PaymentIntentCreatePaymentMethodOptionsUSBankAccountParams struct { + // Additional fields for Financial Connections Session creation + FinancialConnections *PaymentIntentCreatePaymentMethodOptionsUSBankAccountFinancialConnectionsParams `form:"financial_connections"` + // Additional fields for Mandate creation + MandateOptions *PaymentIntentCreatePaymentMethodOptionsUSBankAccountMandateOptionsParams `form:"mandate_options"` + // Additional fields for network related functions + Networks *PaymentIntentCreatePaymentMethodOptionsUSBankAccountNetworksParams `form:"networks"` + // Preferred transaction settlement speed + PreferredSettlementSpeed *string `form:"preferred_settlement_speed"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` + // Bank account verification method. + VerificationMethod *string `form:"verification_method"` +} + +// If this is a `wechat_pay` PaymentMethod, this sub-hash contains details about the WeChat Pay payment method options. +type PaymentIntentCreatePaymentMethodOptionsWeChatPayParams struct { + // The app ID registered with WeChat Pay. Only required when client is ios or android. + AppID *string `form:"app_id"` + // The client type that the end customer will pay from + Client *string `form:"client"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `zip` PaymentMethod, this sub-hash contains details about the Zip payment method options. +type PaymentIntentCreatePaymentMethodOptionsZipParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Payment method-specific configuration for this PaymentIntent. +type PaymentIntentCreatePaymentMethodOptionsParams struct { + // If this is a `acss_debit` PaymentMethod, this sub-hash contains details about the ACSS Debit payment method options. + ACSSDebit *PaymentIntentCreatePaymentMethodOptionsACSSDebitParams `form:"acss_debit"` + // If this is an `affirm` PaymentMethod, this sub-hash contains details about the Affirm payment method options. + Affirm *PaymentIntentCreatePaymentMethodOptionsAffirmParams `form:"affirm"` + // If this is a `afterpay_clearpay` PaymentMethod, this sub-hash contains details about the Afterpay Clearpay payment method options. + AfterpayClearpay *PaymentIntentCreatePaymentMethodOptionsAfterpayClearpayParams `form:"afterpay_clearpay"` + // If this is a `alipay` PaymentMethod, this sub-hash contains details about the Alipay payment method options. + Alipay *PaymentIntentCreatePaymentMethodOptionsAlipayParams `form:"alipay"` + // If this is a `alma` PaymentMethod, this sub-hash contains details about the Alma payment method options. + Alma *PaymentIntentCreatePaymentMethodOptionsAlmaParams `form:"alma"` + // If this is a `amazon_pay` PaymentMethod, this sub-hash contains details about the Amazon Pay payment method options. + AmazonPay *PaymentIntentCreatePaymentMethodOptionsAmazonPayParams `form:"amazon_pay"` + // If this is a `au_becs_debit` PaymentMethod, this sub-hash contains details about the AU BECS Direct Debit payment method options. + AUBECSDebit *PaymentIntentCreatePaymentMethodOptionsAUBECSDebitParams `form:"au_becs_debit"` + // If this is a `bacs_debit` PaymentMethod, this sub-hash contains details about the BACS Debit payment method options. + BACSDebit *PaymentIntentCreatePaymentMethodOptionsBACSDebitParams `form:"bacs_debit"` + // If this is a `bancontact` PaymentMethod, this sub-hash contains details about the Bancontact payment method options. + Bancontact *PaymentIntentCreatePaymentMethodOptionsBancontactParams `form:"bancontact"` + // If this is a `billie` PaymentMethod, this sub-hash contains details about the Billie payment method options. + Billie *PaymentIntentCreatePaymentMethodOptionsBillieParams `form:"billie"` + // If this is a `blik` PaymentMethod, this sub-hash contains details about the BLIK payment method options. + BLIK *PaymentIntentCreatePaymentMethodOptionsBLIKParams `form:"blik"` + // If this is a `boleto` PaymentMethod, this sub-hash contains details about the Boleto payment method options. + Boleto *PaymentIntentCreatePaymentMethodOptionsBoletoParams `form:"boleto"` + // Configuration for any card payments attempted on this PaymentIntent. + Card *PaymentIntentCreatePaymentMethodOptionsCardParams `form:"card"` + // If this is a `card_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. + CardPresent *PaymentIntentCreatePaymentMethodOptionsCardPresentParams `form:"card_present"` + // If this is a `cashapp` PaymentMethod, this sub-hash contains details about the Cash App Pay payment method options. + CashApp *PaymentIntentCreatePaymentMethodOptionsCashAppParams `form:"cashapp"` + // If this is a `crypto` PaymentMethod, this sub-hash contains details about the Crypto payment method options. + Crypto *PaymentIntentCreatePaymentMethodOptionsCryptoParams `form:"crypto"` + // If this is a `customer balance` PaymentMethod, this sub-hash contains details about the customer balance payment method options. + CustomerBalance *PaymentIntentCreatePaymentMethodOptionsCustomerBalanceParams `form:"customer_balance"` + // If this is a `eps` PaymentMethod, this sub-hash contains details about the EPS payment method options. + EPS *PaymentIntentCreatePaymentMethodOptionsEPSParams `form:"eps"` + // If this is a `fpx` PaymentMethod, this sub-hash contains details about the FPX payment method options. + FPX *PaymentIntentCreatePaymentMethodOptionsFPXParams `form:"fpx"` + // If this is a `giropay` PaymentMethod, this sub-hash contains details about the Giropay payment method options. + Giropay *PaymentIntentCreatePaymentMethodOptionsGiropayParams `form:"giropay"` + // If this is a `grabpay` PaymentMethod, this sub-hash contains details about the Grabpay payment method options. + Grabpay *PaymentIntentCreatePaymentMethodOptionsGrabpayParams `form:"grabpay"` + // If this is a `ideal` PaymentMethod, this sub-hash contains details about the Ideal payment method options. + IDEAL *PaymentIntentCreatePaymentMethodOptionsIDEALParams `form:"ideal"` + // If this is a `interac_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. + InteracPresent *PaymentIntentCreatePaymentMethodOptionsInteracPresentParams `form:"interac_present"` + // If this is a `kakao_pay` PaymentMethod, this sub-hash contains details about the Kakao Pay payment method options. + KakaoPay *PaymentIntentCreatePaymentMethodOptionsKakaoPayParams `form:"kakao_pay"` + // If this is a `klarna` PaymentMethod, this sub-hash contains details about the Klarna payment method options. + Klarna *PaymentIntentCreatePaymentMethodOptionsKlarnaParams `form:"klarna"` + // If this is a `konbini` PaymentMethod, this sub-hash contains details about the Konbini payment method options. + Konbini *PaymentIntentCreatePaymentMethodOptionsKonbiniParams `form:"konbini"` + // If this is a `kr_card` PaymentMethod, this sub-hash contains details about the KR Card payment method options. + KrCard *PaymentIntentCreatePaymentMethodOptionsKrCardParams `form:"kr_card"` + // If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. + Link *PaymentIntentCreatePaymentMethodOptionsLinkParams `form:"link"` + // If this is a `MobilePay` PaymentMethod, this sub-hash contains details about the MobilePay payment method options. + Mobilepay *PaymentIntentCreatePaymentMethodOptionsMobilepayParams `form:"mobilepay"` + // If this is a `multibanco` PaymentMethod, this sub-hash contains details about the Multibanco payment method options. + Multibanco *PaymentIntentCreatePaymentMethodOptionsMultibancoParams `form:"multibanco"` + // If this is a `naver_pay` PaymentMethod, this sub-hash contains details about the Naver Pay payment method options. + NaverPay *PaymentIntentCreatePaymentMethodOptionsNaverPayParams `form:"naver_pay"` + // If this is a `nz_bank_account` PaymentMethod, this sub-hash contains details about the NZ BECS Direct Debit payment method options. + NzBankAccount *PaymentIntentCreatePaymentMethodOptionsNzBankAccountParams `form:"nz_bank_account"` + // If this is a `oxxo` PaymentMethod, this sub-hash contains details about the OXXO payment method options. + OXXO *PaymentIntentCreatePaymentMethodOptionsOXXOParams `form:"oxxo"` + // If this is a `p24` PaymentMethod, this sub-hash contains details about the Przelewy24 payment method options. + P24 *PaymentIntentCreatePaymentMethodOptionsP24Params `form:"p24"` + // If this is a `pay_by_bank` PaymentMethod, this sub-hash contains details about the PayByBank payment method options. + PayByBank *PaymentIntentCreatePaymentMethodOptionsPayByBankParams `form:"pay_by_bank"` + // If this is a `payco` PaymentMethod, this sub-hash contains details about the PAYCO payment method options. + Payco *PaymentIntentCreatePaymentMethodOptionsPaycoParams `form:"payco"` + // If this is a `paynow` PaymentMethod, this sub-hash contains details about the PayNow payment method options. + PayNow *PaymentIntentCreatePaymentMethodOptionsPayNowParams `form:"paynow"` + // If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. + Paypal *PaymentIntentCreatePaymentMethodOptionsPaypalParams `form:"paypal"` + // If this is a `pix` PaymentMethod, this sub-hash contains details about the Pix payment method options. + Pix *PaymentIntentCreatePaymentMethodOptionsPixParams `form:"pix"` + // If this is a `promptpay` PaymentMethod, this sub-hash contains details about the PromptPay payment method options. + PromptPay *PaymentIntentCreatePaymentMethodOptionsPromptPayParams `form:"promptpay"` + // If this is a `revolut_pay` PaymentMethod, this sub-hash contains details about the Revolut Pay payment method options. + RevolutPay *PaymentIntentCreatePaymentMethodOptionsRevolutPayParams `form:"revolut_pay"` + // If this is a `samsung_pay` PaymentMethod, this sub-hash contains details about the Samsung Pay payment method options. + SamsungPay *PaymentIntentCreatePaymentMethodOptionsSamsungPayParams `form:"samsung_pay"` + // If this is a `satispay` PaymentMethod, this sub-hash contains details about the Satispay payment method options. + Satispay *PaymentIntentCreatePaymentMethodOptionsSatispayParams `form:"satispay"` + // If this is a `sepa_debit` PaymentIntent, this sub-hash contains details about the SEPA Debit payment method options. + SEPADebit *PaymentIntentCreatePaymentMethodOptionsSEPADebitParams `form:"sepa_debit"` + // If this is a `sofort` PaymentMethod, this sub-hash contains details about the SOFORT payment method options. + Sofort *PaymentIntentCreatePaymentMethodOptionsSofortParams `form:"sofort"` + // If this is a `Swish` PaymentMethod, this sub-hash contains details about the Swish payment method options. + Swish *PaymentIntentCreatePaymentMethodOptionsSwishParams `form:"swish"` + // If this is a `twint` PaymentMethod, this sub-hash contains details about the TWINT payment method options. + TWINT *PaymentIntentCreatePaymentMethodOptionsTWINTParams `form:"twint"` + // If this is a `us_bank_account` PaymentMethod, this sub-hash contains details about the US bank account payment method options. + USBankAccount *PaymentIntentCreatePaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` + // If this is a `wechat_pay` PaymentMethod, this sub-hash contains details about the WeChat Pay payment method options. + WeChatPay *PaymentIntentCreatePaymentMethodOptionsWeChatPayParams `form:"wechat_pay"` + // If this is a `zip` PaymentMethod, this sub-hash contains details about the Zip payment method options. + Zip *PaymentIntentCreatePaymentMethodOptionsZipParams `form:"zip"` +} + +// Options to configure Radar. Learn more about [Radar Sessions](https://stripe.com/docs/radar/radar-session). +type PaymentIntentCreateRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// The parameters that you can use to automatically create a Transfer. +// Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). +type PaymentIntentCreateTransferDataParams struct { + // The amount that will be transferred automatically when a charge succeeds. + // The amount is capped at the total transaction amount and if no amount is set, + // the full amount is transferred. + // + // If you intend to collect a fee and you need a more robust reporting experience, using + // [application_fee_amount](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-application_fee_amount) + // might be a better fit for your integration. + Amount *int64 `form:"amount"` + // If specified, successful charges will be attributed to the destination + // account for tax reporting, and the funds from charges will be transferred + // to the destination account. The ID of the resulting transfer will be + // returned on the successful charge's `transfer` field. + Destination *string `form:"destination"` +} + +// Creates a PaymentIntent object. +// +// After the PaymentIntent is created, attach a payment method and [confirm](https://docs.stripe.com/docs/api/payment_intents/confirm) +// to continue the payment. Learn more about the available payment flows +// with the Payment Intents API. +// +// When you use confirm=true during creation, it's equivalent to creating +// and confirming the PaymentIntent in the same call. You can use any parameters +// available in the [confirm API](https://docs.stripe.com/docs/api/payment_intents/confirm) when you supply +// confirm=true. +type PaymentIntentCreateParams struct { + Params `form:"*"` + // Amount intended to be collected by this PaymentIntent. A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + Amount *int64 `form:"amount"` + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. The amount of the application fee collected will be capped at the total amount captured. For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // When you enable this parameter, this PaymentIntent accepts payment methods that you enable in the Dashboard and that are compatible with this PaymentIntent's other parameters. + AutomaticPaymentMethods *PaymentIntentCreateAutomaticPaymentMethodsParams `form:"automatic_payment_methods"` + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // Set to `true` to attempt to [confirm this PaymentIntent](https://stripe.com/docs/api/payment_intents/confirm) immediately. This parameter defaults to `false`. When creating and confirming a PaymentIntent at the same time, you can also provide the parameters available in the [Confirm API](https://stripe.com/docs/api/payment_intents/confirm). + Confirm *bool `form:"confirm"` + // Describes whether we can confirm this PaymentIntent automatically, or if it requires customer action to confirm the payment. + ConfirmationMethod *string `form:"confirmation_method"` + // ID of the ConfirmationToken used to confirm this PaymentIntent. + // + // If the provided ConfirmationToken contains properties that are also being provided in this request, such as `payment_method`, then the values in this request will take precedence. + ConfirmationToken *string `form:"confirmation_token"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // ID of the Customer this PaymentIntent belongs to, if one exists. + // + // Payment methods attached to other Customers cannot be used with this PaymentIntent. + // + // If [setup_future_usage](https://stripe.com/docs/api#payment_intent_object-setup_future_usage) is set and this PaymentIntent's payment method is not `card_present`, then the payment method attaches to the Customer after the PaymentIntent has been confirmed and any required actions from the user are complete. If the payment method is `card_present` and isn't a digital wallet, then a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card is created and attached to the Customer instead. + Customer *string `form:"customer"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Set to `true` to fail the payment attempt if the PaymentIntent transitions into `requires_action`. Use this parameter for simpler integrations that don't handle customer actions, such as [saving cards without authentication](https://stripe.com/docs/payments/save-card-without-authentication). This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + ErrorOnRequiresAction *bool `form:"error_on_requires_action"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // ID of the mandate that's used for this payment. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + Mandate *string `form:"mandate"` + // This hash contains details about the Mandate to create. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + MandateData *PaymentIntentCreateMandateDataParams `form:"mandate_data"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Set to `true` to indicate that the customer isn't in your checkout flow during this payment attempt and can't authenticate. Use this parameter in scenarios where you collect card details and [charge them later](https://stripe.com/docs/payments/cards/charging-saved-cards). This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + OffSession *bool `form:"off_session"` + // The Stripe account ID that these funds are intended for. Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + OnBehalfOf *string `form:"on_behalf_of"` + // ID of the payment method (a PaymentMethod, Card, or [compatible Source](https://stripe.com/docs/payments/payment-methods#compatibility) object) to attach to this PaymentIntent. + // + // If you don't provide the `payment_method` parameter or the `source` parameter with `confirm=true`, `source` automatically populates with `customer.default_source` to improve migration for users of the Charges API. We recommend that you explicitly provide the `payment_method` moving forward. + // If the payment method is attached to a Customer, you must also provide the ID of that Customer as the [customer](https://stripe.com/docs/api#create_payment_intent-customer) parameter of this PaymentIntent. + // end + PaymentMethod *string `form:"payment_method"` + // The ID of the [payment method configuration](https://stripe.com/docs/api/payment_method_configurations) to use with this PaymentIntent. + PaymentMethodConfiguration *string `form:"payment_method_configuration"` + // If provided, this hash will be used to create a PaymentMethod. The new PaymentMethod will appear + // in the [payment_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-payment_method) + // property on the PaymentIntent. + PaymentMethodData *PaymentIntentCreatePaymentMethodDataParams `form:"payment_method_data"` + // Payment method-specific configuration for this PaymentIntent. + PaymentMethodOptions *PaymentIntentCreatePaymentMethodOptionsParams `form:"payment_method_options"` + // The list of payment method types (for example, a card) that this PaymentIntent can use. If you don't provide this, Stripe will dynamically show relevant payment methods from your [payment method settings](https://dashboard.stripe.com/settings/payment_methods). A list of valid payment method types can be found [here](https://docs.stripe.com/api/payment_methods/object#payment_method_object-type). + PaymentMethodTypes []*string `form:"payment_method_types"` + // Options to configure Radar. Learn more about [Radar Sessions](https://stripe.com/docs/radar/radar-session). + RadarOptions *PaymentIntentCreateRadarOptionsParams `form:"radar_options"` + // Email address to send the receipt to. If you specify `receipt_email` for a payment in live mode, you send a receipt regardless of your [email settings](https://dashboard.stripe.com/account/emails). + ReceiptEmail *string `form:"receipt_email"` + // The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method's app or site. If you'd prefer to redirect to a mobile application, you can alternatively supply an application URI scheme. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + ReturnURL *string `form:"return_url"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` + // Shipping information for this PaymentIntent. + Shipping *ShippingDetailsParams `form:"shipping"` + // Text that appears on the customer's statement as the statement descriptor for a non-card charge. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + // + // Setting this value for a card charge returns an error. For card charges, set the [statement_descriptor_suffix](https://docs.stripe.com/get-started/account/statement-descriptors#dynamic) instead. + StatementDescriptor *string `form:"statement_descriptor"` + // Provides information about a card charge. Concatenated to the account's [statement descriptor prefix](https://docs.stripe.com/get-started/account/statement-descriptors#static) to form the complete statement descriptor that appears on the customer's statement. + StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"` + // The parameters that you can use to automatically create a Transfer. + // Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + TransferData *PaymentIntentCreateTransferDataParams `form:"transfer_data"` + // A string that identifies the resulting payment as part of a group. Learn more about the [use case for connected accounts](https://stripe.com/docs/connect/separate-charges-and-transfers). + TransferGroup *string `form:"transfer_group"` + // Set to `true` when confirming server-side and using Stripe.js, iOS, or Android client-side SDKs to handle the next actions. + UseStripeSDK *bool `form:"use_stripe_sdk"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentIntentCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentIntentCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the details of a PaymentIntent that has previously been created. +// +// You can retrieve a PaymentIntent client-side using a publishable key when the client_secret is in the query string. +// +// If you retrieve a PaymentIntent with a publishable key, it only returns a subset of properties. Refer to the [payment intent](https://docs.stripe.com/api#payment_intent_object) object reference for more details. +type PaymentIntentRetrieveParams struct { + Params `form:"*"` + // The client secret of the PaymentIntent. We require it if you use a publishable key to retrieve the source. + ClientSecret *string `form:"client_secret"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentIntentRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. +type PaymentIntentUpdatePaymentMethodDataBillingDetailsParams struct { + // Billing address. + Address *AddressParams `form:"address"` + // Email address. + Email *string `form:"email"` + // Full name. + Name *string `form:"name"` + // Billing phone number (including extension). + Phone *string `form:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID *string `form:"tax_id"` +} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type PaymentIntentUpdatePaymentMethodDataRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// If provided, this hash will be used to create a PaymentMethod. The new PaymentMethod will appear +// in the [payment_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-payment_method) +// property on the PaymentIntent. +type PaymentIntentUpdatePaymentMethodDataParams struct { + // If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + ACSSDebit *PaymentMethodACSSDebitParams `form:"acss_debit"` + // If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + Affirm *PaymentMethodAffirmParams `form:"affirm"` + // If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + AfterpayClearpay *PaymentMethodAfterpayClearpayParams `form:"afterpay_clearpay"` + // If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + Alipay *PaymentMethodAlipayParams `form:"alipay"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to `unspecified`. + AllowRedisplay *string `form:"allow_redisplay"` + // If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. + Alma *PaymentMethodAlmaParams `form:"alma"` + // If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. + AmazonPay *PaymentMethodAmazonPayParams `form:"amazon_pay"` + // If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + AUBECSDebit *PaymentMethodAUBECSDebitParams `form:"au_becs_debit"` + // If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + BACSDebit *PaymentMethodBACSDebitParams `form:"bacs_debit"` + // If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + Bancontact *PaymentMethodBancontactParams `form:"bancontact"` + // If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. + Billie *PaymentMethodBillieParams `form:"billie"` + // Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + BillingDetails *PaymentIntentUpdatePaymentMethodDataBillingDetailsParams `form:"billing_details"` + // If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + BLIK *PaymentMethodBLIKParams `form:"blik"` + // If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + Boleto *PaymentMethodBoletoParams `form:"boleto"` + // If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + CashApp *PaymentMethodCashAppParams `form:"cashapp"` + // If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. + Crypto *PaymentMethodCryptoParams `form:"crypto"` + // If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + CustomerBalance *PaymentMethodCustomerBalanceParams `form:"customer_balance"` + // If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + EPS *PaymentMethodEPSParams `form:"eps"` + // If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + FPX *PaymentMethodFPXParams `form:"fpx"` + // If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + Giropay *PaymentMethodGiropayParams `form:"giropay"` + // If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + Grabpay *PaymentMethodGrabpayParams `form:"grabpay"` + // If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + IDEAL *PaymentMethodIDEALParams `form:"ideal"` + // If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + InteracPresent *PaymentMethodInteracPresentParams `form:"interac_present"` + // If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. + KakaoPay *PaymentMethodKakaoPayParams `form:"kakao_pay"` + // If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + Klarna *PaymentMethodKlarnaParams `form:"klarna"` + // If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + Konbini *PaymentMethodKonbiniParams `form:"konbini"` + // If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. + KrCard *PaymentMethodKrCardParams `form:"kr_card"` + // If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + Link *PaymentMethodLinkParams `form:"link"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. + Mobilepay *PaymentMethodMobilepayParams `form:"mobilepay"` + // If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. + Multibanco *PaymentMethodMultibancoParams `form:"multibanco"` + // If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. + NaverPay *PaymentMethodNaverPayParams `form:"naver_pay"` + // If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. + NzBankAccount *PaymentMethodNzBankAccountParams `form:"nz_bank_account"` + // If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + OXXO *PaymentMethodOXXOParams `form:"oxxo"` + // If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + P24 *PaymentMethodP24Params `form:"p24"` + // If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. + PayByBank *PaymentMethodPayByBankParams `form:"pay_by_bank"` + // If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. + Payco *PaymentMethodPaycoParams `form:"payco"` + // If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + PayNow *PaymentMethodPayNowParams `form:"paynow"` + // If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + Paypal *PaymentMethodPaypalParams `form:"paypal"` + // If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + Pix *PaymentMethodPixParams `form:"pix"` + // If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + PromptPay *PaymentMethodPromptPayParams `form:"promptpay"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *PaymentIntentUpdatePaymentMethodDataRadarOptionsParams `form:"radar_options"` + // If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + RevolutPay *PaymentMethodRevolutPayParams `form:"revolut_pay"` + // If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. + SamsungPay *PaymentMethodSamsungPayParams `form:"samsung_pay"` + // If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. + Satispay *PaymentMethodSatispayParams `form:"satispay"` + // If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + SEPADebit *PaymentMethodSEPADebitParams `form:"sepa_debit"` + // If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + Sofort *PaymentMethodSofortParams `form:"sofort"` + // If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. + Swish *PaymentMethodSwishParams `form:"swish"` + // If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. + TWINT *PaymentMethodTWINTParams `form:"twint"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type *string `form:"type"` + // If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + USBankAccount *PaymentMethodUSBankAccountParams `form:"us_bank_account"` + // If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + WeChatPay *PaymentMethodWeChatPayParams `form:"wechat_pay"` + // If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + Zip *PaymentMethodZipParams `form:"zip"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentIntentUpdatePaymentMethodDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Additional fields for Mandate creation +type PaymentIntentUpdatePaymentMethodOptionsACSSDebitMandateOptionsParams struct { + // A URL for custom mandate text to render during confirmation step. + // The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + // or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + CustomMandateURL *string `form:"custom_mandate_url"` + // Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + IntervalDescription *string `form:"interval_description"` + // Payment schedule for the mandate. + PaymentSchedule *string `form:"payment_schedule"` + // Transaction type of the mandate. + TransactionType *string `form:"transaction_type"` +} + +// If this is a `acss_debit` PaymentMethod, this sub-hash contains details about the ACSS Debit payment method options. +type PaymentIntentUpdatePaymentMethodOptionsACSSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *PaymentIntentUpdatePaymentMethodOptionsACSSDebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` + // Bank account verification method. + VerificationMethod *string `form:"verification_method"` +} + +// If this is an `affirm` PaymentMethod, this sub-hash contains details about the Affirm payment method options. +type PaymentIntentUpdatePaymentMethodOptionsAffirmParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Preferred language of the Affirm authorization page that the customer is redirected to. + PreferredLocale *string `form:"preferred_locale"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `afterpay_clearpay` PaymentMethod, this sub-hash contains details about the Afterpay Clearpay payment method options. +type PaymentIntentUpdatePaymentMethodOptionsAfterpayClearpayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // An internal identifier or reference that this payment corresponds to. You must limit the identifier to 128 characters, and it can only contain letters, numbers, underscores, backslashes, and dashes. + // This field differs from the statement descriptor and item name. + Reference *string `form:"reference"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `alipay` PaymentMethod, this sub-hash contains details about the Alipay payment method options. +type PaymentIntentUpdatePaymentMethodOptionsAlipayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `alma` PaymentMethod, this sub-hash contains details about the Alma payment method options. +type PaymentIntentUpdatePaymentMethodOptionsAlmaParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// If this is a `amazon_pay` PaymentMethod, this sub-hash contains details about the Amazon Pay payment method options. +type PaymentIntentUpdatePaymentMethodOptionsAmazonPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `au_becs_debit` PaymentMethod, this sub-hash contains details about the AU BECS Direct Debit payment method options. +type PaymentIntentUpdatePaymentMethodOptionsAUBECSDebitParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// Additional fields for Mandate creation +type PaymentIntentUpdatePaymentMethodOptionsBACSDebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'DDIC' or 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// If this is a `bacs_debit` PaymentMethod, this sub-hash contains details about the BACS Debit payment method options. +type PaymentIntentUpdatePaymentMethodOptionsBACSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *PaymentIntentUpdatePaymentMethodOptionsBACSDebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// If this is a `bancontact` PaymentMethod, this sub-hash contains details about the Bancontact payment method options. +type PaymentIntentUpdatePaymentMethodOptionsBancontactParams struct { + // Preferred language of the Bancontact authorization page that the customer is redirected to. + PreferredLanguage *string `form:"preferred_language"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `billie` PaymentMethod, this sub-hash contains details about the Billie payment method options. +type PaymentIntentUpdatePaymentMethodOptionsBillieParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// If this is a `blik` PaymentMethod, this sub-hash contains details about the BLIK payment method options. +type PaymentIntentUpdatePaymentMethodOptionsBLIKParams struct { + // The 6-digit BLIK code that a customer has generated using their banking application. Can only be set on confirmation. + Code *string `form:"code"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `boleto` PaymentMethod, this sub-hash contains details about the Boleto payment method options. +type PaymentIntentUpdatePaymentMethodOptionsBoletoParams struct { + // The number of calendar days before a Boleto voucher expires. For example, if you create a Boleto voucher on Monday and you set expires_after_days to 2, the Boleto invoice will expire on Wednesday at 23:59 America/Sao_Paulo time. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// The selected installment plan to use for this payment attempt. +// This parameter can only be provided during confirmation. +type PaymentIntentUpdatePaymentMethodOptionsCardInstallmentsPlanParams struct { + // For `fixed_count` installment plans, this is required. It represents the number of installment payments your customer will make to their credit card. + Count *int64 `form:"count"` + // For `fixed_count` installment plans, this is required. It represents the interval between installment payments your customer will make to their credit card. + // One of `month`. + Interval *string `form:"interval"` + // Type of installment plan, one of `fixed_count`, `bonus`, or `revolving`. + Type *string `form:"type"` +} + +// Installment configuration for payments attempted on this PaymentIntent (Mexico Only). +// +// For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). +type PaymentIntentUpdatePaymentMethodOptionsCardInstallmentsParams struct { + // Setting to true enables installments for this PaymentIntent. + // This will cause the response to contain a list of available installment plans. + // Setting to false will prevent any selected plan from applying to a charge. + Enabled *bool `form:"enabled"` + // The selected installment plan to use for this payment attempt. + // This parameter can only be provided during confirmation. + Plan *PaymentIntentUpdatePaymentMethodOptionsCardInstallmentsPlanParams `form:"plan"` +} + +// Configuration options for setting up an eMandate for cards issued in India. +type PaymentIntentUpdatePaymentMethodOptionsCardMandateOptionsParams struct { + // Amount to be charged for future payments. + Amount *int64 `form:"amount"` + // One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + AmountType *string `form:"amount_type"` + // A description of the mandate or subscription that is meant to be displayed to the customer. + Description *string `form:"description"` + // End date of the mandate or subscription. If not provided, the mandate will be active until canceled. If provided, end date should be after start date. + EndDate *int64 `form:"end_date"` + // Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. + Interval *string `form:"interval"` + // The number of intervals between payments. For example, `interval=month` and `interval_count=3` indicates one payment every three months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). This parameter is optional when `interval=sporadic`. + IntervalCount *int64 `form:"interval_count"` + // Unique identifier for the mandate or subscription. + Reference *string `form:"reference"` + // Start date of the mandate or subscription. Start date should not be lesser than yesterday. + StartDate *int64 `form:"start_date"` + // Specifies the type of mandates supported. Possible values are `india`. + SupportedTypes []*string `form:"supported_types"` +} + +// Cartes Bancaires-specific 3DS fields. +type PaymentIntentUpdatePaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancairesParams struct { + // The cryptogram calculation algorithm used by the card Issuer's ACS + // to calculate the Authentication cryptogram. Also known as `cavvAlgorithm`. + // messageExtension: CB-AVALGO + CbAvalgo *string `form:"cb_avalgo"` + // The exemption indicator returned from Cartes Bancaires in the ARes. + // message extension: CB-EXEMPTION; string (4 characters) + // This is a 3 byte bitmap (low significant byte first and most significant + // bit first) that has been Base64 encoded + CbExemption *string `form:"cb_exemption"` + // The risk score returned from Cartes Bancaires in the ARes. + // message extension: CB-SCORE; numeric value 0-99 + CbScore *int64 `form:"cb_score"` +} + +// Network specific 3DS fields. Network specific arguments require an +// explicit card brand choice. The parameter `payment_method_options.card.network“ +// must be populated accordingly +type PaymentIntentUpdatePaymentMethodOptionsCardThreeDSecureNetworkOptionsParams struct { + // Cartes Bancaires-specific 3DS fields. + CartesBancaires *PaymentIntentUpdatePaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancairesParams `form:"cartes_bancaires"` +} + +// If 3D Secure authentication was performed with a third-party provider, +// the authentication details to use for this payment. +type PaymentIntentUpdatePaymentMethodOptionsCardThreeDSecureParams struct { + // The `transStatus` returned from the card Issuer's ACS in the ARes. + AresTransStatus *string `form:"ares_trans_status"` + // The cryptogram, also known as the "authentication value" (AAV, CAVV or + // AEVV). This value is 20 bytes, base64-encoded into a 28-character string. + // (Most 3D Secure providers will return the base64-encoded version, which + // is what you should specify here.) + Cryptogram *string `form:"cryptogram"` + // The Electronic Commerce Indicator (ECI) is returned by your 3D Secure + // provider and indicates what degree of authentication was performed. + ElectronicCommerceIndicator *string `form:"electronic_commerce_indicator"` + // The exemption requested via 3DS and accepted by the issuer at authentication time. + ExemptionIndicator *string `form:"exemption_indicator"` + // Network specific 3DS fields. Network specific arguments require an + // explicit card brand choice. The parameter `payment_method_options.card.network`` + // must be populated accordingly + NetworkOptions *PaymentIntentUpdatePaymentMethodOptionsCardThreeDSecureNetworkOptionsParams `form:"network_options"` + // The challenge indicator (`threeDSRequestorChallengeInd`) which was requested in the + // AReq sent to the card Issuer's ACS. A string containing 2 digits from 01-99. + RequestorChallengeIndicator *string `form:"requestor_challenge_indicator"` + // For 3D Secure 1, the XID. For 3D Secure 2, the Directory Server + // Transaction ID (dsTransID). + TransactionID *string `form:"transaction_id"` + // The version of 3D Secure that was performed. + Version *string `form:"version"` +} + +// Configuration for any card payments attempted on this PaymentIntent. +type PaymentIntentUpdatePaymentMethodOptionsCardParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // A single-use `cvc_update` Token that represents a card CVC value. When provided, the CVC value will be verified during the card payment attempt. This parameter can only be provided during confirmation. + CVCToken *string `form:"cvc_token"` + // Installment configuration for payments attempted on this PaymentIntent (Mexico Only). + // + // For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + Installments *PaymentIntentUpdatePaymentMethodOptionsCardInstallmentsParams `form:"installments"` + // Configuration options for setting up an eMandate for cards issued in India. + MandateOptions *PaymentIntentUpdatePaymentMethodOptionsCardMandateOptionsParams `form:"mandate_options"` + // When specified, this parameter indicates that a transaction will be marked + // as MOTO (Mail Order Telephone Order) and thus out of scope for SCA. This + // parameter can only be provided during confirmation. + MOTO *bool `form:"moto"` + // Selected network to process this PaymentIntent on. Depends on the available networks of the card attached to the PaymentIntent. Can be only set confirm-time. + Network *string `form:"network"` + // Request ability to [capture beyond the standard authorization validity window](https://stripe.com/docs/payments/extended-authorization) for this PaymentIntent. + RequestExtendedAuthorization *string `form:"request_extended_authorization"` + // Request ability to [increment the authorization](https://stripe.com/docs/payments/incremental-authorization) for this PaymentIntent. + RequestIncrementalAuthorization *string `form:"request_incremental_authorization"` + // Request ability to make [multiple captures](https://stripe.com/docs/payments/multicapture) for this PaymentIntent. + RequestMulticapture *string `form:"request_multicapture"` + // Request ability to [overcapture](https://stripe.com/docs/payments/overcapture) for this PaymentIntent. + RequestOvercapture *string `form:"request_overcapture"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure *string `form:"request_three_d_secure"` + // When enabled, using a card that is attached to a customer will require the CVC to be provided again (i.e. using the cvc_token parameter). + RequireCVCRecollection *bool `form:"require_cvc_recollection"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Provides information about a card payment that customers see on their statements. Concatenated with the Kana prefix (shortened Kana descriptor) or Kana statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 22 characters. + StatementDescriptorSuffixKana *string `form:"statement_descriptor_suffix_kana"` + // Provides information about a card payment that customers see on their statements. Concatenated with the Kanji prefix (shortened Kanji descriptor) or Kanji statement descriptor that's set on the account to form the complete statement descriptor. Maximum 17 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 17 characters. + StatementDescriptorSuffixKanji *string `form:"statement_descriptor_suffix_kanji"` + // If 3D Secure authentication was performed with a third-party provider, + // the authentication details to use for this payment. + ThreeDSecure *PaymentIntentUpdatePaymentMethodOptionsCardThreeDSecureParams `form:"three_d_secure"` +} + +// Network routing priority on co-branded EMV cards supporting domestic debit and international card schemes. +type PaymentIntentUpdatePaymentMethodOptionsCardPresentRoutingParams struct { + // Routing requested priority + RequestedPriority *string `form:"requested_priority"` +} + +// If this is a `card_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. +type PaymentIntentUpdatePaymentMethodOptionsCardPresentParams struct { + // Request ability to capture this payment beyond the standard [authorization validity window](https://stripe.com/docs/terminal/features/extended-authorizations#authorization-validity) + RequestExtendedAuthorization *bool `form:"request_extended_authorization"` + // Request ability to [increment](https://stripe.com/docs/terminal/features/incremental-authorizations) this PaymentIntent if the combination of MCC and card brand is eligible. Check [incremental_authorization_supported](https://stripe.com/docs/api/charges/object#charge_object-payment_method_details-card_present-incremental_authorization_supported) in the [Confirm](https://stripe.com/docs/api/payment_intents/confirm) response to verify support. + RequestIncrementalAuthorizationSupport *bool `form:"request_incremental_authorization_support"` + // Network routing priority on co-branded EMV cards supporting domestic debit and international card schemes. + Routing *PaymentIntentUpdatePaymentMethodOptionsCardPresentRoutingParams `form:"routing"` +} + +// If this is a `cashapp` PaymentMethod, this sub-hash contains details about the Cash App Pay payment method options. +type PaymentIntentUpdatePaymentMethodOptionsCashAppParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `crypto` PaymentMethod, this sub-hash contains details about the Crypto payment method options. +type PaymentIntentUpdatePaymentMethodOptionsCryptoParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Configuration for the eu_bank_transfer funding type. +type PaymentIntentUpdatePaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country *string `form:"country"` +} + +// Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. +type PaymentIntentUpdatePaymentMethodOptionsCustomerBalanceBankTransferParams struct { + // Configuration for the eu_bank_transfer funding type. + EUBankTransfer *PaymentIntentUpdatePaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams `form:"eu_bank_transfer"` + // List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. + // + // Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. + RequestedAddressTypes []*string `form:"requested_address_types"` + // The list of bank transfer types that this PaymentIntent is allowed to use for funding Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + Type *string `form:"type"` +} + +// If this is a `customer balance` PaymentMethod, this sub-hash contains details about the customer balance payment method options. +type PaymentIntentUpdatePaymentMethodOptionsCustomerBalanceParams struct { + // Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + BankTransfer *PaymentIntentUpdatePaymentMethodOptionsCustomerBalanceBankTransferParams `form:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType *string `form:"funding_type"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `eps` PaymentMethod, this sub-hash contains details about the EPS payment method options. +type PaymentIntentUpdatePaymentMethodOptionsEPSParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `fpx` PaymentMethod, this sub-hash contains details about the FPX payment method options. +type PaymentIntentUpdatePaymentMethodOptionsFPXParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `giropay` PaymentMethod, this sub-hash contains details about the Giropay payment method options. +type PaymentIntentUpdatePaymentMethodOptionsGiropayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `grabpay` PaymentMethod, this sub-hash contains details about the Grabpay payment method options. +type PaymentIntentUpdatePaymentMethodOptionsGrabpayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `ideal` PaymentMethod, this sub-hash contains details about the Ideal payment method options. +type PaymentIntentUpdatePaymentMethodOptionsIDEALParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `interac_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. +type PaymentIntentUpdatePaymentMethodOptionsInteracPresentParams struct{} + +// If this is a `kakao_pay` PaymentMethod, this sub-hash contains details about the Kakao Pay payment method options. +type PaymentIntentUpdatePaymentMethodOptionsKakaoPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// On-demand details if setting up or charging an on-demand payment. +type PaymentIntentUpdatePaymentMethodOptionsKlarnaOnDemandParams struct { + // Your average amount value. You can use a value across your customer base, or segment based on customer type, country, etc. + AverageAmount *int64 `form:"average_amount"` + // The maximum value you may charge a customer per purchase. You can use a value across your customer base, or segment based on customer type, country, etc. + MaximumAmount *int64 `form:"maximum_amount"` + // The lowest or minimum value you may charge a customer per purchase. You can use a value across your customer base, or segment based on customer type, country, etc. + MinimumAmount *int64 `form:"minimum_amount"` + // Interval at which the customer is making purchases + PurchaseInterval *string `form:"purchase_interval"` + // The number of `purchase_interval` between charges + PurchaseIntervalCount *int64 `form:"purchase_interval_count"` +} + +// Describes the upcoming charge for this subscription. +type PaymentIntentUpdatePaymentMethodOptionsKlarnaSubscriptionNextBillingParams struct { + // The amount of the next charge for the subscription. + Amount *int64 `form:"amount"` + // The date of the next charge for the subscription in YYYY-MM-DD format. + Date *string `form:"date"` +} + +// Subscription details if setting up or charging a subscription. +type PaymentIntentUpdatePaymentMethodOptionsKlarnaSubscriptionParams struct { + // Unit of time between subscription charges. + Interval *string `form:"interval"` + // The number of intervals (specified in the `interval` attribute) between subscription charges. For example, `interval=month` and `interval_count=3` charges every 3 months. + IntervalCount *int64 `form:"interval_count"` + // Name for subscription. + Name *string `form:"name"` + // Describes the upcoming charge for this subscription. + NextBilling *PaymentIntentUpdatePaymentMethodOptionsKlarnaSubscriptionNextBillingParams `form:"next_billing"` + // A non-customer-facing reference to correlate subscription charges in the Klarna app. Use a value that persists across subscription charges. + Reference *string `form:"reference"` +} + +// If this is a `klarna` PaymentMethod, this sub-hash contains details about the Klarna payment method options. +type PaymentIntentUpdatePaymentMethodOptionsKlarnaParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // On-demand details if setting up or charging an on-demand payment. + OnDemand *PaymentIntentUpdatePaymentMethodOptionsKlarnaOnDemandParams `form:"on_demand"` + // Preferred language of the Klarna authorization page that the customer is redirected to + PreferredLocale *string `form:"preferred_locale"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Subscription details if setting up or charging a subscription. + Subscriptions []*PaymentIntentUpdatePaymentMethodOptionsKlarnaSubscriptionParams `form:"subscriptions"` +} + +// If this is a `konbini` PaymentMethod, this sub-hash contains details about the Konbini payment method options. +type PaymentIntentUpdatePaymentMethodOptionsKonbiniParams struct { + // An optional 10 to 11 digit numeric-only string determining the confirmation code at applicable convenience stores. Must not consist of only zeroes and could be rejected in case of insufficient uniqueness. We recommend to use the customer's phone number. + ConfirmationNumber *string `form:"confirmation_number"` + // The number of calendar days (between 1 and 60) after which Konbini payment instructions will expire. For example, if a PaymentIntent is confirmed with Konbini and `expires_after_days` set to 2 on Monday JST, the instructions will expire on Wednesday 23:59:59 JST. Defaults to 3 days. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // The timestamp at which the Konbini payment instructions will expire. Only one of `expires_after_days` or `expires_at` may be set. + ExpiresAt *int64 `form:"expires_at"` + // A product descriptor of up to 22 characters, which will appear to customers at the convenience store. + ProductDescription *string `form:"product_description"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `kr_card` PaymentMethod, this sub-hash contains details about the KR Card payment method options. +type PaymentIntentUpdatePaymentMethodOptionsKrCardParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. +type PaymentIntentUpdatePaymentMethodOptionsLinkParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // [Deprecated] This is a legacy parameter that no longer has any function. + // Deprecated: + PersistentToken *string `form:"persistent_token"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `MobilePay` PaymentMethod, this sub-hash contains details about the MobilePay payment method options. +type PaymentIntentUpdatePaymentMethodOptionsMobilepayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `multibanco` PaymentMethod, this sub-hash contains details about the Multibanco payment method options. +type PaymentIntentUpdatePaymentMethodOptionsMultibancoParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `naver_pay` PaymentMethod, this sub-hash contains details about the Naver Pay payment method options. +type PaymentIntentUpdatePaymentMethodOptionsNaverPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `nz_bank_account` PaymentMethod, this sub-hash contains details about the NZ BECS Direct Debit payment method options. +type PaymentIntentUpdatePaymentMethodOptionsNzBankAccountParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// If this is a `oxxo` PaymentMethod, this sub-hash contains details about the OXXO payment method options. +type PaymentIntentUpdatePaymentMethodOptionsOXXOParams struct { + // The number of calendar days before an OXXO voucher expires. For example, if you create an OXXO voucher on Monday and you set expires_after_days to 2, the OXXO invoice will expire on Wednesday at 23:59 America/Mexico_City time. + ExpiresAfterDays *int64 `form:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `p24` PaymentMethod, this sub-hash contains details about the Przelewy24 payment method options. +type PaymentIntentUpdatePaymentMethodOptionsP24Params struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Confirm that the payer has accepted the P24 terms and conditions. + TOSShownAndAccepted *bool `form:"tos_shown_and_accepted"` +} + +// If this is a `pay_by_bank` PaymentMethod, this sub-hash contains details about the PayByBank payment method options. +type PaymentIntentUpdatePaymentMethodOptionsPayByBankParams struct{} + +// If this is a `payco` PaymentMethod, this sub-hash contains details about the PAYCO payment method options. +type PaymentIntentUpdatePaymentMethodOptionsPaycoParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// If this is a `paynow` PaymentMethod, this sub-hash contains details about the PayNow payment method options. +type PaymentIntentUpdatePaymentMethodOptionsPayNowParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. +type PaymentIntentUpdatePaymentMethodOptionsPaypalParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // [Preferred locale](https://stripe.com/docs/payments/paypal/supported-locales) of the PayPal checkout page that the customer is redirected to. + PreferredLocale *string `form:"preferred_locale"` + // A reference of the PayPal transaction visible to customer which is mapped to PayPal's invoice ID. This must be a globally unique ID if you have configured in your PayPal settings to block multiple payments per invoice ID. + Reference *string `form:"reference"` + // The risk correlation ID for an on-session payment using a saved PayPal payment method. + RiskCorrelationID *string `form:"risk_correlation_id"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `pix` PaymentMethod, this sub-hash contains details about the Pix payment method options. +type PaymentIntentUpdatePaymentMethodOptionsPixParams struct { + // The number of seconds (between 10 and 1209600) after which Pix payment will expire. Defaults to 86400 seconds. + ExpiresAfterSeconds *int64 `form:"expires_after_seconds"` + // The timestamp at which the Pix expires (between 10 and 1209600 seconds in the future). Defaults to 1 day in the future. + ExpiresAt *int64 `form:"expires_at"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `promptpay` PaymentMethod, this sub-hash contains details about the PromptPay payment method options. +type PaymentIntentUpdatePaymentMethodOptionsPromptPayParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `revolut_pay` PaymentMethod, this sub-hash contains details about the Revolut Pay payment method options. +type PaymentIntentUpdatePaymentMethodOptionsRevolutPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `samsung_pay` PaymentMethod, this sub-hash contains details about the Samsung Pay payment method options. +type PaymentIntentUpdatePaymentMethodOptionsSamsungPayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// If this is a `satispay` PaymentMethod, this sub-hash contains details about the Satispay payment method options. +type PaymentIntentUpdatePaymentMethodOptionsSatispayParams struct { + // Controls when the funds are captured from the customer's account. + // + // If provided, this parameter overrides the behavior of the top-level [capture_method](https://docs.stripe.com/api/payment_intents/update#update_payment_intent-capture_method) for this payment method type when finalizing the payment with this payment method type. + // + // If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter unsets the stored value for this payment method type. + CaptureMethod *string `form:"capture_method"` +} + +// Additional fields for Mandate creation +type PaymentIntentUpdatePaymentMethodOptionsSEPADebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// If this is a `sepa_debit` PaymentIntent, this sub-hash contains details about the SEPA Debit payment method options. +type PaymentIntentUpdatePaymentMethodOptionsSEPADebitParams struct { + // Additional fields for Mandate creation + MandateOptions *PaymentIntentUpdatePaymentMethodOptionsSEPADebitMandateOptionsParams `form:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` +} + +// If this is a `sofort` PaymentMethod, this sub-hash contains details about the SOFORT payment method options. +type PaymentIntentUpdatePaymentMethodOptionsSofortParams struct { + // Language shown to the payer on redirect. + PreferredLanguage *string `form:"preferred_language"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `Swish` PaymentMethod, this sub-hash contains details about the Swish payment method options. +type PaymentIntentUpdatePaymentMethodOptionsSwishParams struct { + // A reference for this payment to be displayed in the Swish app. + Reference *string `form:"reference"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `twint` PaymentMethod, this sub-hash contains details about the TWINT payment method options. +type PaymentIntentUpdatePaymentMethodOptionsTWINTParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Provide filters for the linked accounts that the customer can select for the payment method. +type PaymentIntentUpdatePaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams struct { + // The account subcategories to use to filter for selectable accounts. Valid subcategories are `checking` and `savings`. + AccountSubcategories []*string `form:"account_subcategories"` +} + +// Additional fields for Financial Connections Session creation +type PaymentIntentUpdatePaymentMethodOptionsUSBankAccountFinancialConnectionsParams struct { + // Provide filters for the linked accounts that the customer can select for the payment method. + Filters *PaymentIntentUpdatePaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams `form:"filters"` + // The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` + // For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + ReturnURL *string `form:"return_url"` +} + +// Additional fields for Mandate creation +type PaymentIntentUpdatePaymentMethodOptionsUSBankAccountMandateOptionsParams struct { + // The method used to collect offline mandate customer acceptance. + CollectionMethod *string `form:"collection_method"` +} + +// Additional fields for network related functions +type PaymentIntentUpdatePaymentMethodOptionsUSBankAccountNetworksParams struct { + // Triggers validations to run across the selected networks + Requested []*string `form:"requested"` +} + +// If this is a `us_bank_account` PaymentMethod, this sub-hash contains details about the US bank account payment method options. +type PaymentIntentUpdatePaymentMethodOptionsUSBankAccountParams struct { + // Additional fields for Financial Connections Session creation + FinancialConnections *PaymentIntentUpdatePaymentMethodOptionsUSBankAccountFinancialConnectionsParams `form:"financial_connections"` + // Additional fields for Mandate creation + MandateOptions *PaymentIntentUpdatePaymentMethodOptionsUSBankAccountMandateOptionsParams `form:"mandate_options"` + // Additional fields for network related functions + Networks *PaymentIntentUpdatePaymentMethodOptionsUSBankAccountNetworksParams `form:"networks"` + // Preferred transaction settlement speed + PreferredSettlementSpeed *string `form:"preferred_settlement_speed"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate *string `form:"target_date"` + // Bank account verification method. + VerificationMethod *string `form:"verification_method"` +} + +// If this is a `wechat_pay` PaymentMethod, this sub-hash contains details about the WeChat Pay payment method options. +type PaymentIntentUpdatePaymentMethodOptionsWeChatPayParams struct { + // The app ID registered with WeChat Pay. Only required when client is ios or android. + AppID *string `form:"app_id"` + // The client type that the end customer will pay from + Client *string `form:"client"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// If this is a `zip` PaymentMethod, this sub-hash contains details about the Zip payment method options. +type PaymentIntentUpdatePaymentMethodOptionsZipParams struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` +} + +// Payment-method-specific configuration for this PaymentIntent. +type PaymentIntentUpdatePaymentMethodOptionsParams struct { + // If this is a `acss_debit` PaymentMethod, this sub-hash contains details about the ACSS Debit payment method options. + ACSSDebit *PaymentIntentUpdatePaymentMethodOptionsACSSDebitParams `form:"acss_debit"` + // If this is an `affirm` PaymentMethod, this sub-hash contains details about the Affirm payment method options. + Affirm *PaymentIntentUpdatePaymentMethodOptionsAffirmParams `form:"affirm"` + // If this is a `afterpay_clearpay` PaymentMethod, this sub-hash contains details about the Afterpay Clearpay payment method options. + AfterpayClearpay *PaymentIntentUpdatePaymentMethodOptionsAfterpayClearpayParams `form:"afterpay_clearpay"` + // If this is a `alipay` PaymentMethod, this sub-hash contains details about the Alipay payment method options. + Alipay *PaymentIntentUpdatePaymentMethodOptionsAlipayParams `form:"alipay"` + // If this is a `alma` PaymentMethod, this sub-hash contains details about the Alma payment method options. + Alma *PaymentIntentUpdatePaymentMethodOptionsAlmaParams `form:"alma"` + // If this is a `amazon_pay` PaymentMethod, this sub-hash contains details about the Amazon Pay payment method options. + AmazonPay *PaymentIntentUpdatePaymentMethodOptionsAmazonPayParams `form:"amazon_pay"` + // If this is a `au_becs_debit` PaymentMethod, this sub-hash contains details about the AU BECS Direct Debit payment method options. + AUBECSDebit *PaymentIntentUpdatePaymentMethodOptionsAUBECSDebitParams `form:"au_becs_debit"` + // If this is a `bacs_debit` PaymentMethod, this sub-hash contains details about the BACS Debit payment method options. + BACSDebit *PaymentIntentUpdatePaymentMethodOptionsBACSDebitParams `form:"bacs_debit"` + // If this is a `bancontact` PaymentMethod, this sub-hash contains details about the Bancontact payment method options. + Bancontact *PaymentIntentUpdatePaymentMethodOptionsBancontactParams `form:"bancontact"` + // If this is a `billie` PaymentMethod, this sub-hash contains details about the Billie payment method options. + Billie *PaymentIntentUpdatePaymentMethodOptionsBillieParams `form:"billie"` + // If this is a `blik` PaymentMethod, this sub-hash contains details about the BLIK payment method options. + BLIK *PaymentIntentUpdatePaymentMethodOptionsBLIKParams `form:"blik"` + // If this is a `boleto` PaymentMethod, this sub-hash contains details about the Boleto payment method options. + Boleto *PaymentIntentUpdatePaymentMethodOptionsBoletoParams `form:"boleto"` + // Configuration for any card payments attempted on this PaymentIntent. + Card *PaymentIntentUpdatePaymentMethodOptionsCardParams `form:"card"` + // If this is a `card_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. + CardPresent *PaymentIntentUpdatePaymentMethodOptionsCardPresentParams `form:"card_present"` + // If this is a `cashapp` PaymentMethod, this sub-hash contains details about the Cash App Pay payment method options. + CashApp *PaymentIntentUpdatePaymentMethodOptionsCashAppParams `form:"cashapp"` + // If this is a `crypto` PaymentMethod, this sub-hash contains details about the Crypto payment method options. + Crypto *PaymentIntentUpdatePaymentMethodOptionsCryptoParams `form:"crypto"` + // If this is a `customer balance` PaymentMethod, this sub-hash contains details about the customer balance payment method options. + CustomerBalance *PaymentIntentUpdatePaymentMethodOptionsCustomerBalanceParams `form:"customer_balance"` + // If this is a `eps` PaymentMethod, this sub-hash contains details about the EPS payment method options. + EPS *PaymentIntentUpdatePaymentMethodOptionsEPSParams `form:"eps"` + // If this is a `fpx` PaymentMethod, this sub-hash contains details about the FPX payment method options. + FPX *PaymentIntentUpdatePaymentMethodOptionsFPXParams `form:"fpx"` + // If this is a `giropay` PaymentMethod, this sub-hash contains details about the Giropay payment method options. + Giropay *PaymentIntentUpdatePaymentMethodOptionsGiropayParams `form:"giropay"` + // If this is a `grabpay` PaymentMethod, this sub-hash contains details about the Grabpay payment method options. + Grabpay *PaymentIntentUpdatePaymentMethodOptionsGrabpayParams `form:"grabpay"` + // If this is a `ideal` PaymentMethod, this sub-hash contains details about the Ideal payment method options. + IDEAL *PaymentIntentUpdatePaymentMethodOptionsIDEALParams `form:"ideal"` + // If this is a `interac_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. + InteracPresent *PaymentIntentUpdatePaymentMethodOptionsInteracPresentParams `form:"interac_present"` + // If this is a `kakao_pay` PaymentMethod, this sub-hash contains details about the Kakao Pay payment method options. + KakaoPay *PaymentIntentUpdatePaymentMethodOptionsKakaoPayParams `form:"kakao_pay"` + // If this is a `klarna` PaymentMethod, this sub-hash contains details about the Klarna payment method options. + Klarna *PaymentIntentUpdatePaymentMethodOptionsKlarnaParams `form:"klarna"` + // If this is a `konbini` PaymentMethod, this sub-hash contains details about the Konbini payment method options. + Konbini *PaymentIntentUpdatePaymentMethodOptionsKonbiniParams `form:"konbini"` + // If this is a `kr_card` PaymentMethod, this sub-hash contains details about the KR Card payment method options. + KrCard *PaymentIntentUpdatePaymentMethodOptionsKrCardParams `form:"kr_card"` + // If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. + Link *PaymentIntentUpdatePaymentMethodOptionsLinkParams `form:"link"` + // If this is a `MobilePay` PaymentMethod, this sub-hash contains details about the MobilePay payment method options. + Mobilepay *PaymentIntentUpdatePaymentMethodOptionsMobilepayParams `form:"mobilepay"` + // If this is a `multibanco` PaymentMethod, this sub-hash contains details about the Multibanco payment method options. + Multibanco *PaymentIntentUpdatePaymentMethodOptionsMultibancoParams `form:"multibanco"` + // If this is a `naver_pay` PaymentMethod, this sub-hash contains details about the Naver Pay payment method options. + NaverPay *PaymentIntentUpdatePaymentMethodOptionsNaverPayParams `form:"naver_pay"` + // If this is a `nz_bank_account` PaymentMethod, this sub-hash contains details about the NZ BECS Direct Debit payment method options. + NzBankAccount *PaymentIntentUpdatePaymentMethodOptionsNzBankAccountParams `form:"nz_bank_account"` + // If this is a `oxxo` PaymentMethod, this sub-hash contains details about the OXXO payment method options. + OXXO *PaymentIntentUpdatePaymentMethodOptionsOXXOParams `form:"oxxo"` + // If this is a `p24` PaymentMethod, this sub-hash contains details about the Przelewy24 payment method options. + P24 *PaymentIntentUpdatePaymentMethodOptionsP24Params `form:"p24"` + // If this is a `pay_by_bank` PaymentMethod, this sub-hash contains details about the PayByBank payment method options. + PayByBank *PaymentIntentUpdatePaymentMethodOptionsPayByBankParams `form:"pay_by_bank"` + // If this is a `payco` PaymentMethod, this sub-hash contains details about the PAYCO payment method options. + Payco *PaymentIntentUpdatePaymentMethodOptionsPaycoParams `form:"payco"` + // If this is a `paynow` PaymentMethod, this sub-hash contains details about the PayNow payment method options. + PayNow *PaymentIntentUpdatePaymentMethodOptionsPayNowParams `form:"paynow"` + // If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. + Paypal *PaymentIntentUpdatePaymentMethodOptionsPaypalParams `form:"paypal"` + // If this is a `pix` PaymentMethod, this sub-hash contains details about the Pix payment method options. + Pix *PaymentIntentUpdatePaymentMethodOptionsPixParams `form:"pix"` + // If this is a `promptpay` PaymentMethod, this sub-hash contains details about the PromptPay payment method options. + PromptPay *PaymentIntentUpdatePaymentMethodOptionsPromptPayParams `form:"promptpay"` + // If this is a `revolut_pay` PaymentMethod, this sub-hash contains details about the Revolut Pay payment method options. + RevolutPay *PaymentIntentUpdatePaymentMethodOptionsRevolutPayParams `form:"revolut_pay"` + // If this is a `samsung_pay` PaymentMethod, this sub-hash contains details about the Samsung Pay payment method options. + SamsungPay *PaymentIntentUpdatePaymentMethodOptionsSamsungPayParams `form:"samsung_pay"` + // If this is a `satispay` PaymentMethod, this sub-hash contains details about the Satispay payment method options. + Satispay *PaymentIntentUpdatePaymentMethodOptionsSatispayParams `form:"satispay"` + // If this is a `sepa_debit` PaymentIntent, this sub-hash contains details about the SEPA Debit payment method options. + SEPADebit *PaymentIntentUpdatePaymentMethodOptionsSEPADebitParams `form:"sepa_debit"` + // If this is a `sofort` PaymentMethod, this sub-hash contains details about the SOFORT payment method options. + Sofort *PaymentIntentUpdatePaymentMethodOptionsSofortParams `form:"sofort"` + // If this is a `Swish` PaymentMethod, this sub-hash contains details about the Swish payment method options. + Swish *PaymentIntentUpdatePaymentMethodOptionsSwishParams `form:"swish"` + // If this is a `twint` PaymentMethod, this sub-hash contains details about the TWINT payment method options. + TWINT *PaymentIntentUpdatePaymentMethodOptionsTWINTParams `form:"twint"` + // If this is a `us_bank_account` PaymentMethod, this sub-hash contains details about the US bank account payment method options. + USBankAccount *PaymentIntentUpdatePaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` + // If this is a `wechat_pay` PaymentMethod, this sub-hash contains details about the WeChat Pay payment method options. + WeChatPay *PaymentIntentUpdatePaymentMethodOptionsWeChatPayParams `form:"wechat_pay"` + // If this is a `zip` PaymentMethod, this sub-hash contains details about the Zip payment method options. + Zip *PaymentIntentUpdatePaymentMethodOptionsZipParams `form:"zip"` +} + +// Use this parameter to automatically create a Transfer when the payment succeeds. Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). +type PaymentIntentUpdateTransferDataParams struct { + // The amount that will be transferred automatically when a charge succeeds. + Amount *int64 `form:"amount"` +} + +// Updates properties on a PaymentIntent object without confirming. +// +// Depending on which properties you update, you might need to confirm the +// PaymentIntent again. For example, updating the payment_method +// always requires you to confirm the PaymentIntent again. If you prefer to +// update and confirm at the same time, we recommend updating properties through +// the [confirm API](https://docs.stripe.com/docs/api/payment_intents/confirm) instead. +type PaymentIntentUpdateParams struct { + Params `form:"*"` + // Amount intended to be collected by this PaymentIntent. A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + Amount *int64 `form:"amount"` + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. The amount of the application fee collected will be capped at the total amount captured. For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // ID of the Customer this PaymentIntent belongs to, if one exists. + // + // Payment methods attached to other Customers cannot be used with this PaymentIntent. + // + // If [setup_future_usage](https://stripe.com/docs/api#payment_intent_object-setup_future_usage) is set and this PaymentIntent's payment method is not `card_present`, then the payment method attaches to the Customer after the PaymentIntent has been confirmed and any required actions from the user are complete. If the payment method is `card_present` and isn't a digital wallet, then a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card is created and attached to the Customer instead. + Customer *string `form:"customer"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // ID of the payment method (a PaymentMethod, Card, or [compatible Source](https://stripe.com/docs/payments/payment-methods/transitioning#compatibility) object) to attach to this PaymentIntent. To unset this field to null, pass in an empty string. + PaymentMethod *string `form:"payment_method"` + // The ID of the [payment method configuration](https://stripe.com/docs/api/payment_method_configurations) to use with this PaymentIntent. + PaymentMethodConfiguration *string `form:"payment_method_configuration"` + // If provided, this hash will be used to create a PaymentMethod. The new PaymentMethod will appear + // in the [payment_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-payment_method) + // property on the PaymentIntent. + PaymentMethodData *PaymentIntentUpdatePaymentMethodDataParams `form:"payment_method_data"` + // Payment-method-specific configuration for this PaymentIntent. + PaymentMethodOptions *PaymentIntentUpdatePaymentMethodOptionsParams `form:"payment_method_options"` + // The list of payment method types (for example, card) that this PaymentIntent can use. Use `automatic_payment_methods` to manage payment methods from the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). A list of valid payment method types can be found [here](https://docs.stripe.com/api/payment_methods/object#payment_method_object-type). + PaymentMethodTypes []*string `form:"payment_method_types"` + // Email address that the receipt for the resulting payment will be sent to. If `receipt_email` is specified for a payment in live mode, a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). + ReceiptEmail *string `form:"receipt_email"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + // + // If you've already set `setup_future_usage` and you're performing a request using a publishable key, you can only update the value from `on_session` to `off_session`. + SetupFutureUsage *string `form:"setup_future_usage"` + // Shipping information for this PaymentIntent. + Shipping *ShippingDetailsParams `form:"shipping"` + // Text that appears on the customer's statement as the statement descriptor for a non-card charge. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + // + // Setting this value for a card charge returns an error. For card charges, set the [statement_descriptor_suffix](https://docs.stripe.com/get-started/account/statement-descriptors#dynamic) instead. + StatementDescriptor *string `form:"statement_descriptor"` + // Provides information about a card charge. Concatenated to the account's [statement descriptor prefix](https://docs.stripe.com/get-started/account/statement-descriptors#static) to form the complete statement descriptor that appears on the customer's statement. + StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"` + // Use this parameter to automatically create a Transfer when the payment succeeds. Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + TransferData *PaymentIntentUpdateTransferDataParams `form:"transfer_data"` + // A string that identifies the resulting payment as part of a group. You can only provide `transfer_group` if it hasn't been set. Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + TransferGroup *string `form:"transfer_group"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentIntentUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentIntentUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +type PaymentIntentAmountDetailsTip struct { + // Portion of the amount that corresponds to a tip. + Amount int64 `json:"amount"` +} +type PaymentIntentAmountDetails struct { + Tip *PaymentIntentAmountDetailsTip `json:"tip"` +} + +// Settings to configure compatible payment methods from the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods) +type PaymentIntentAutomaticPaymentMethods struct { + // Controls whether this PaymentIntent will accept redirect-based payment methods. + // + // Redirect-based payment methods may require your customer to be redirected to a payment method's app or site for authentication or additional steps. To [confirm](https://stripe.com/docs/api/payment_intents/confirm) this PaymentIntent, you may be required to provide a `return_url` to redirect customers back to your site after they authenticate or complete the payment. + AllowRedirects PaymentIntentAutomaticPaymentMethodsAllowRedirects `json:"allow_redirects"` + // Automatically calculates compatible payment methods + Enabled bool `json:"enabled"` +} +type PaymentIntentNextActionAlipayHandleRedirect struct { + // The native data to be used with Alipay SDK you must redirect your customer to in order to authenticate the payment in an Android App. + NativeData string `json:"native_data"` + // The native URL you must redirect your customer to in order to authenticate the payment in an iOS App. + NativeURL string `json:"native_url"` + // If the customer does not exit their browser while authenticating, they will be redirected to this specified URL after completion. + ReturnURL string `json:"return_url"` + // The URL you must redirect your customer to in order to authenticate the payment. + URL string `json:"url"` +} +type PaymentIntentNextActionBoletoDisplayDetails struct { + // The timestamp after which the boleto expires. + ExpiresAt int64 `json:"expires_at"` + // The URL to the hosted boleto voucher page, which allows customers to view the boleto voucher. + HostedVoucherURL string `json:"hosted_voucher_url"` + // The boleto number. + Number string `json:"number"` + // The URL to the downloadable boleto voucher PDF. + PDF string `json:"pdf"` +} +type PaymentIntentNextActionCardAwaitNotification struct { + // The time that payment will be attempted. If customer approval is required, they need to provide approval before this time. + ChargeAttemptAt int64 `json:"charge_attempt_at"` + // For payments greater than INR 15000, the customer must provide explicit approval of the payment with their bank. For payments of lower amount, no customer action is required. + CustomerApprovalRequired bool `json:"customer_approval_required"` +} +type PaymentIntentNextActionCashAppHandleRedirectOrDisplayQRCodeQRCode struct { + // The date (unix timestamp) when the QR code expires. + ExpiresAt int64 `json:"expires_at"` + // The image_url_png string used to render QR code + ImageURLPNG string `json:"image_url_png"` + // The image_url_svg string used to render QR code + ImageURLSVG string `json:"image_url_svg"` +} +type PaymentIntentNextActionCashAppHandleRedirectOrDisplayQRCode struct { + // The URL to the hosted Cash App Pay instructions page, which allows customers to view the QR code, and supports QR code refreshing on expiration. + HostedInstructionsURL string `json:"hosted_instructions_url"` + // The url for mobile redirect based auth + MobileAuthURL string `json:"mobile_auth_url"` + QRCode *PaymentIntentNextActionCashAppHandleRedirectOrDisplayQRCodeQRCode `json:"qr_code"` +} + +// ABA Records contain U.S. bank account details per the ABA format. +type PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressABA struct { + AccountHolderAddress *Address `json:"account_holder_address"` + // The account holder name + AccountHolderName string `json:"account_holder_name"` + // The ABA account number + AccountNumber string `json:"account_number"` + // The account type + AccountType string `json:"account_type"` + BankAddress *Address `json:"bank_address"` + // The bank name + BankName string `json:"bank_name"` + // The ABA routing number + RoutingNumber string `json:"routing_number"` +} + +// Iban Records contain E.U. bank account details per the SEPA format. +type PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressIBAN struct { + AccountHolderAddress *Address `json:"account_holder_address"` + // The name of the person or business that owns the bank account + AccountHolderName string `json:"account_holder_name"` + BankAddress *Address `json:"bank_address"` + // The BIC/SWIFT code of the account. + BIC string `json:"bic"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country string `json:"country"` + // The IBAN of the account. + IBAN string `json:"iban"` +} + +// Sort Code Records contain U.K. bank account details per the sort code format. +type PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSortCode struct { + AccountHolderAddress *Address `json:"account_holder_address"` + // The name of the person or business that owns the bank account + AccountHolderName string `json:"account_holder_name"` + // The account number + AccountNumber string `json:"account_number"` + BankAddress *Address `json:"bank_address"` + // The six-digit sort code + SortCode string `json:"sort_code"` +} + +// SPEI Records contain Mexico bank account details per the SPEI format. +type PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSpei struct { + AccountHolderAddress *Address `json:"account_holder_address"` + // The account holder name + AccountHolderName string `json:"account_holder_name"` + BankAddress *Address `json:"bank_address"` + // The three-digit bank code + BankCode string `json:"bank_code"` + // The short banking institution name + BankName string `json:"bank_name"` + // The CLABE number + Clabe string `json:"clabe"` +} + +// SWIFT Records contain U.S. bank account details per the SWIFT format. +type PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSwift struct { + AccountHolderAddress *Address `json:"account_holder_address"` + // The account holder name + AccountHolderName string `json:"account_holder_name"` + // The account number + AccountNumber string `json:"account_number"` + // The account type + AccountType string `json:"account_type"` + BankAddress *Address `json:"bank_address"` + // The bank name + BankName string `json:"bank_name"` + // The SWIFT code + SwiftCode string `json:"swift_code"` +} + +// Zengin Records contain Japan bank account details per the Zengin format. +type PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressZengin struct { + AccountHolderAddress *Address `json:"account_holder_address"` + // The account holder name + AccountHolderName string `json:"account_holder_name"` + // The account number + AccountNumber string `json:"account_number"` + // The bank account type. In Japan, this can only be `futsu` or `toza`. + AccountType string `json:"account_type"` + BankAddress *Address `json:"bank_address"` + // The bank code of the account + BankCode string `json:"bank_code"` + // The bank name of the account + BankName string `json:"bank_name"` + // The branch code of the account + BranchCode string `json:"branch_code"` + // The branch name of the account + BranchName string `json:"branch_name"` +} + +// A list of financial addresses that can be used to fund the customer balance +type PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddress struct { + // ABA Records contain U.S. bank account details per the ABA format. + ABA *PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressABA `json:"aba"` + // Iban Records contain E.U. bank account details per the SEPA format. + IBAN *PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressIBAN `json:"iban"` + // Sort Code Records contain U.K. bank account details per the sort code format. + SortCode *PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSortCode `json:"sort_code"` + // SPEI Records contain Mexico bank account details per the SPEI format. + Spei *PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSpei `json:"spei"` + // The payment networks supported by this FinancialAddress + SupportedNetworks []PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSupportedNetwork `json:"supported_networks"` + // SWIFT Records contain U.S. bank account details per the SWIFT format. + Swift *PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressSwift `json:"swift"` + // The type of financial address + Type PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressType `json:"type"` + // Zengin Records contain Japan bank account details per the Zengin format. + Zengin *PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressZengin `json:"zengin"` +} +type PaymentIntentNextActionDisplayBankTransferInstructions struct { + // The remaining amount that needs to be transferred to complete the payment. + AmountRemaining int64 `json:"amount_remaining"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // A list of financial addresses that can be used to fund the customer balance + FinancialAddresses []*PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddress `json:"financial_addresses"` + // A link to a hosted page that guides your customer through completing the transfer. + HostedInstructionsURL string `json:"hosted_instructions_url"` + // A string identifying this payment. Instruct your customer to include this code in the reference or memo field of their bank transfer. + Reference string `json:"reference"` + // Type of bank transfer + Type PaymentIntentNextActionDisplayBankTransferInstructionsType `json:"type"` +} + +// FamilyMart instruction details. +type PaymentIntentNextActionKonbiniDisplayDetailsStoresFamilyMart struct { + // The confirmation number. + ConfirmationNumber string `json:"confirmation_number"` + // The payment code. + PaymentCode string `json:"payment_code"` +} + +// Lawson instruction details. +type PaymentIntentNextActionKonbiniDisplayDetailsStoresLawson struct { + // The confirmation number. + ConfirmationNumber string `json:"confirmation_number"` + // The payment code. + PaymentCode string `json:"payment_code"` +} + +// Ministop instruction details. +type PaymentIntentNextActionKonbiniDisplayDetailsStoresMinistop struct { + // The confirmation number. + ConfirmationNumber string `json:"confirmation_number"` + // The payment code. + PaymentCode string `json:"payment_code"` +} + +// Seicomart instruction details. +type PaymentIntentNextActionKonbiniDisplayDetailsStoresSeicomart struct { + // The confirmation number. + ConfirmationNumber string `json:"confirmation_number"` + // The payment code. + PaymentCode string `json:"payment_code"` +} +type PaymentIntentNextActionKonbiniDisplayDetailsStores struct { + // FamilyMart instruction details. + FamilyMart *PaymentIntentNextActionKonbiniDisplayDetailsStoresFamilyMart `json:"familymart"` + // Lawson instruction details. + Lawson *PaymentIntentNextActionKonbiniDisplayDetailsStoresLawson `json:"lawson"` + // Ministop instruction details. + Ministop *PaymentIntentNextActionKonbiniDisplayDetailsStoresMinistop `json:"ministop"` + // Seicomart instruction details. + Seicomart *PaymentIntentNextActionKonbiniDisplayDetailsStoresSeicomart `json:"seicomart"` +} +type PaymentIntentNextActionKonbiniDisplayDetails struct { + // The timestamp at which the pending Konbini payment expires. + ExpiresAt int64 `json:"expires_at"` + // The URL for the Konbini payment instructions page, which allows customers to view and print a Konbini voucher. + HostedVoucherURL string `json:"hosted_voucher_url"` + Stores *PaymentIntentNextActionKonbiniDisplayDetailsStores `json:"stores"` +} +type PaymentIntentNextActionMultibancoDisplayDetails struct { + // Entity number associated with this Multibanco payment. + Entity string `json:"entity"` + // The timestamp at which the Multibanco voucher expires. + ExpiresAt int64 `json:"expires_at"` + // The URL for the hosted Multibanco voucher page, which allows customers to view a Multibanco voucher. + HostedVoucherURL string `json:"hosted_voucher_url"` + // Reference number associated with this Multibanco payment. + Reference string `json:"reference"` +} +type PaymentIntentNextActionOXXODisplayDetails struct { + // The timestamp after which the OXXO voucher expires. + ExpiresAfter int64 `json:"expires_after"` + // The URL for the hosted OXXO voucher page, which allows customers to view and print an OXXO voucher. + HostedVoucherURL string `json:"hosted_voucher_url"` + // OXXO reference number. + Number string `json:"number"` +} +type PaymentIntentNextActionPayNowDisplayQRCode struct { + // The raw data string used to generate QR code, it should be used together with QR code library. + Data string `json:"data"` + // The URL to the hosted PayNow instructions page, which allows customers to view the PayNow QR code. + HostedInstructionsURL string `json:"hosted_instructions_url"` + // The image_url_png string used to render QR code + ImageURLPNG string `json:"image_url_png"` + // The image_url_svg string used to render QR code + ImageURLSVG string `json:"image_url_svg"` +} +type PaymentIntentNextActionPixDisplayQRCode struct { + // The raw data string used to generate QR code, it should be used together with QR code library. + Data string `json:"data"` + // The date (unix timestamp) when the PIX expires. + ExpiresAt int64 `json:"expires_at"` + // The URL to the hosted pix instructions page, which allows customers to view the pix QR code. + HostedInstructionsURL string `json:"hosted_instructions_url"` + // The image_url_png string used to render png QR code + ImageURLPNG string `json:"image_url_png"` + // The image_url_svg string used to render svg QR code + ImageURLSVG string `json:"image_url_svg"` +} +type PaymentIntentNextActionPromptPayDisplayQRCode struct { + // The raw data string used to generate QR code, it should be used together with QR code library. + Data string `json:"data"` + // The URL to the hosted PromptPay instructions page, which allows customers to view the PromptPay QR code. + HostedInstructionsURL string `json:"hosted_instructions_url"` + // The PNG path used to render the QR code, can be used as the source in an HTML img tag + ImageURLPNG string `json:"image_url_png"` + // The SVG path used to render the QR code, can be used as the source in an HTML img tag + ImageURLSVG string `json:"image_url_svg"` +} +type PaymentIntentNextActionRedirectToURL struct { + // If the customer does not exit their browser while authenticating, they will be redirected to this specified URL after completion. + ReturnURL string `json:"return_url"` + // The URL you must redirect your customer to in order to authenticate the payment. + URL string `json:"url"` +} +type PaymentIntentNextActionSwishHandleRedirectOrDisplayQRCodeQRCode struct { + // The raw data string used to generate QR code, it should be used together with QR code library. + Data string `json:"data"` + // The image_url_png string used to render QR code + ImageURLPNG string `json:"image_url_png"` + // The image_url_svg string used to render QR code + ImageURLSVG string `json:"image_url_svg"` +} +type PaymentIntentNextActionSwishHandleRedirectOrDisplayQRCode struct { + // The URL to the hosted Swish instructions page, which allows customers to view the QR code. + HostedInstructionsURL string `json:"hosted_instructions_url"` + // The url for mobile redirect based auth (for internal use only and not typically available in standard API requests). + MobileAuthURL string `json:"mobile_auth_url"` + QRCode *PaymentIntentNextActionSwishHandleRedirectOrDisplayQRCodeQRCode `json:"qr_code"` +} + +// When confirming a PaymentIntent with Stripe.js, Stripe.js depends on the contents of this dictionary to invoke authentication flows. The shape of the contents is subject to change and is only intended to be used by Stripe.js. +type PaymentIntentNextActionUseStripeSDK struct{} +type PaymentIntentNextActionVerifyWithMicrodeposits struct { + // The timestamp when the microdeposits are expected to land. + ArrivalDate int64 `json:"arrival_date"` + // The URL for the hosted verification page, which allows customers to verify their bank account. + HostedVerificationURL string `json:"hosted_verification_url"` + // The type of the microdeposit sent to the customer. Used to distinguish between different verification methods. + MicrodepositType PaymentIntentNextActionVerifyWithMicrodepositsMicrodepositType `json:"microdeposit_type"` +} +type PaymentIntentNextActionWeChatPayDisplayQRCode struct { + // The data being used to generate QR code + Data string `json:"data"` + // The URL to the hosted WeChat Pay instructions page, which allows customers to view the WeChat Pay QR code. + HostedInstructionsURL string `json:"hosted_instructions_url"` + // The base64 image data for a pre-generated QR code + ImageDataURL string `json:"image_data_url"` + // The image_url_png string used to render QR code + ImageURLPNG string `json:"image_url_png"` + // The image_url_svg string used to render QR code + ImageURLSVG string `json:"image_url_svg"` +} +type PaymentIntentNextActionWeChatPayRedirectToAndroidApp struct { + // app_id is the APP ID registered on WeChat open platform + AppID string `json:"app_id"` + // nonce_str is a random string + NonceStr string `json:"nonce_str"` + // package is static value + Package string `json:"package"` + // an unique merchant ID assigned by WeChat Pay + PartnerID string `json:"partner_id"` + // an unique trading ID assigned by WeChat Pay + PrepayID string `json:"prepay_id"` + // A signature + Sign string `json:"sign"` + // Specifies the current time in epoch format + Timestamp string `json:"timestamp"` +} +type PaymentIntentNextActionWeChatPayRedirectToIOSApp struct { + // An universal link that redirect to WeChat Pay app + NativeURL string `json:"native_url"` +} + +// If present, this property tells you what actions you need to take in order for your customer to fulfill a payment using the provided source. +type PaymentIntentNextAction struct { + AlipayHandleRedirect *PaymentIntentNextActionAlipayHandleRedirect `json:"alipay_handle_redirect"` + BoletoDisplayDetails *PaymentIntentNextActionBoletoDisplayDetails `json:"boleto_display_details"` + CardAwaitNotification *PaymentIntentNextActionCardAwaitNotification `json:"card_await_notification"` + CashAppHandleRedirectOrDisplayQRCode *PaymentIntentNextActionCashAppHandleRedirectOrDisplayQRCode `json:"cashapp_handle_redirect_or_display_qr_code"` + DisplayBankTransferInstructions *PaymentIntentNextActionDisplayBankTransferInstructions `json:"display_bank_transfer_instructions"` + KonbiniDisplayDetails *PaymentIntentNextActionKonbiniDisplayDetails `json:"konbini_display_details"` + MultibancoDisplayDetails *PaymentIntentNextActionMultibancoDisplayDetails `json:"multibanco_display_details"` + OXXODisplayDetails *PaymentIntentNextActionOXXODisplayDetails `json:"oxxo_display_details"` + PayNowDisplayQRCode *PaymentIntentNextActionPayNowDisplayQRCode `json:"paynow_display_qr_code"` + PixDisplayQRCode *PaymentIntentNextActionPixDisplayQRCode `json:"pix_display_qr_code"` + PromptPayDisplayQRCode *PaymentIntentNextActionPromptPayDisplayQRCode `json:"promptpay_display_qr_code"` + RedirectToURL *PaymentIntentNextActionRedirectToURL `json:"redirect_to_url"` + SwishHandleRedirectOrDisplayQRCode *PaymentIntentNextActionSwishHandleRedirectOrDisplayQRCode `json:"swish_handle_redirect_or_display_qr_code"` + // Type of the next action to perform. Refer to the other child attributes under `next_action` for available values. Examples include: `redirect_to_url`, `use_stripe_sdk`, `alipay_handle_redirect`, `oxxo_display_details`, or `verify_with_microdeposits`. + Type PaymentIntentNextActionType `json:"type"` + // When confirming a PaymentIntent with Stripe.js, Stripe.js depends on the contents of this dictionary to invoke authentication flows. The shape of the contents is subject to change and is only intended to be used by Stripe.js. + UseStripeSDK *PaymentIntentNextActionUseStripeSDK `json:"use_stripe_sdk"` + VerifyWithMicrodeposits *PaymentIntentNextActionVerifyWithMicrodeposits `json:"verify_with_microdeposits"` + WeChatPayDisplayQRCode *PaymentIntentNextActionWeChatPayDisplayQRCode `json:"wechat_pay_display_qr_code"` + WeChatPayRedirectToAndroidApp *PaymentIntentNextActionWeChatPayRedirectToAndroidApp `json:"wechat_pay_redirect_to_android_app"` + WeChatPayRedirectToIOSApp *PaymentIntentNextActionWeChatPayRedirectToIOSApp `json:"wechat_pay_redirect_to_ios_app"` +} + +// Information about the [payment method configuration](https://stripe.com/docs/api/payment_method_configurations) used for this PaymentIntent. +type PaymentIntentPaymentMethodConfigurationDetails struct { + // ID of the payment method configuration used. + ID string `json:"id"` + // ID of the parent payment method configuration used. + Parent string `json:"parent"` +} +type PaymentIntentPaymentMethodOptionsACSSDebitMandateOptions struct { + // A URL for custom mandate text + CustomMandateURL string `json:"custom_mandate_url"` + // Description of the interval. Only required if the 'payment_schedule' parameter is 'interval' or 'combined'. + IntervalDescription string `json:"interval_description"` + // Payment schedule for the mandate. + PaymentSchedule PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule `json:"payment_schedule"` + // Transaction type of the mandate. + TransactionType PaymentIntentPaymentMethodOptionsACSSDebitMandateOptionsTransactionType `json:"transaction_type"` +} +type PaymentIntentPaymentMethodOptionsACSSDebit struct { + MandateOptions *PaymentIntentPaymentMethodOptionsACSSDebitMandateOptions `json:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsACSSDebitSetupFutureUsage `json:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate string `json:"target_date"` + // Bank account verification method. + VerificationMethod PaymentIntentPaymentMethodOptionsACSSDebitVerificationMethod `json:"verification_method"` +} +type PaymentIntentPaymentMethodOptionsAffirm struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsAffirmCaptureMethod `json:"capture_method"` + // Preferred language of the Affirm authorization page that the customer is redirected to. + PreferredLocale string `json:"preferred_locale"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsAffirmSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsAfterpayClearpay struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsAfterpayClearpayCaptureMethod `json:"capture_method"` + // An internal identifier or reference that this payment corresponds to. You must limit the identifier to 128 characters, and it can only contain letters, numbers, underscores, backslashes, and dashes. + // This field differs from the statement descriptor and item name. + Reference string `json:"reference"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsAfterpayClearpaySetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsAlipay struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsAlipaySetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsAlma struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsAlmaCaptureMethod `json:"capture_method"` +} +type PaymentIntentPaymentMethodOptionsAmazonPay struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsAmazonPayCaptureMethod `json:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsAmazonPaySetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsAUBECSDebit struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsAUBECSDebitSetupFutureUsage `json:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate string `json:"target_date"` +} +type PaymentIntentPaymentMethodOptionsBACSDebitMandateOptions struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'DDIC' or 'STRIPE'. + ReferencePrefix string `json:"reference_prefix"` +} +type PaymentIntentPaymentMethodOptionsBACSDebit struct { + MandateOptions *PaymentIntentPaymentMethodOptionsBACSDebitMandateOptions `json:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsBACSDebitSetupFutureUsage `json:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate string `json:"target_date"` +} +type PaymentIntentPaymentMethodOptionsBancontact struct { + // Preferred language of the Bancontact authorization page that the customer is redirected to. + PreferredLanguage string `json:"preferred_language"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsBancontactSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsBillie struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsBillieCaptureMethod `json:"capture_method"` +} +type PaymentIntentPaymentMethodOptionsBLIK struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsBLIKSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsBoleto struct { + // The number of calendar days before a Boleto voucher expires. For example, if you create a Boleto voucher on Monday and you set expires_after_days to 2, the Boleto voucher will expire on Wednesday at 23:59 America/Sao_Paulo time. + ExpiresAfterDays int64 `json:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsBoletoSetupFutureUsage `json:"setup_future_usage"` +} + +// Installment plan selected for this PaymentIntent. +type PaymentIntentPaymentMethodOptionsCardInstallmentsPlan struct { + // For `fixed_count` installment plans, this is the number of installment payments your customer will make to their credit card. + Count int64 `json:"count"` + // For `fixed_count` installment plans, this is the interval between installment payments your customer will make to their credit card. + // One of `month`. + Interval PaymentIntentPaymentMethodOptionsCardInstallmentsPlanInterval `json:"interval"` + // Type of installment plan, one of `fixed_count`, `bonus`, or `revolving`. + Type PaymentIntentPaymentMethodOptionsCardInstallmentsPlanType `json:"type"` +} + +// Installment details for this payment. +// +// For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). +type PaymentIntentPaymentMethodOptionsCardInstallments struct { + // Installment plans that may be selected for this PaymentIntent. + AvailablePlans []*PaymentIntentPaymentMethodOptionsCardInstallmentsPlan `json:"available_plans"` + // Whether Installments are enabled for this PaymentIntent. + Enabled bool `json:"enabled"` + // Installment plan selected for this PaymentIntent. + Plan *PaymentIntentPaymentMethodOptionsCardInstallmentsPlan `json:"plan"` +} + +// Configuration options for setting up an eMandate for cards issued in India. +type PaymentIntentPaymentMethodOptionsCardMandateOptions struct { + // Amount to be charged for future payments. + Amount int64 `json:"amount"` + // One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + AmountType PaymentIntentPaymentMethodOptionsCardMandateOptionsAmountType `json:"amount_type"` + // A description of the mandate or subscription that is meant to be displayed to the customer. + Description string `json:"description"` + // End date of the mandate or subscription. If not provided, the mandate will be active until canceled. If provided, end date should be after start date. + EndDate int64 `json:"end_date"` + // Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. + Interval PaymentIntentPaymentMethodOptionsCardMandateOptionsInterval `json:"interval"` + // The number of intervals between payments. For example, `interval=month` and `interval_count=3` indicates one payment every three months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). This parameter is optional when `interval=sporadic`. + IntervalCount int64 `json:"interval_count"` + // Unique identifier for the mandate or subscription. + Reference string `json:"reference"` + // Start date of the mandate or subscription. Start date should not be lesser than yesterday. + StartDate int64 `json:"start_date"` + // Specifies the type of mandates supported. Possible values are `india`. + SupportedTypes []PaymentIntentPaymentMethodOptionsCardMandateOptionsSupportedType `json:"supported_types"` +} +type PaymentIntentPaymentMethodOptionsCard struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsCardCaptureMethod `json:"capture_method"` + // Installment details for this payment. + // + // For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + Installments *PaymentIntentPaymentMethodOptionsCardInstallments `json:"installments"` + // Configuration options for setting up an eMandate for cards issued in India. + MandateOptions *PaymentIntentPaymentMethodOptionsCardMandateOptions `json:"mandate_options"` + // Selected network to process this payment intent on. Depends on the available networks of the card attached to the payment intent. Can be only set confirm-time. + Network PaymentIntentPaymentMethodOptionsCardNetwork `json:"network"` + // Request ability to [capture beyond the standard authorization validity window](https://stripe.com/docs/payments/extended-authorization) for this PaymentIntent. + RequestExtendedAuthorization PaymentIntentPaymentMethodOptionsCardRequestExtendedAuthorization `json:"request_extended_authorization"` + // Request ability to [increment the authorization](https://stripe.com/docs/payments/incremental-authorization) for this PaymentIntent. + RequestIncrementalAuthorization PaymentIntentPaymentMethodOptionsCardRequestIncrementalAuthorization `json:"request_incremental_authorization"` + // Request ability to make [multiple captures](https://stripe.com/docs/payments/multicapture) for this PaymentIntent. + RequestMulticapture PaymentIntentPaymentMethodOptionsCardRequestMulticapture `json:"request_multicapture"` + // Request ability to [overcapture](https://stripe.com/docs/payments/overcapture) for this PaymentIntent. + RequestOvercapture PaymentIntentPaymentMethodOptionsCardRequestOvercapture `json:"request_overcapture"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure `json:"request_three_d_secure"` + // When enabled, using a card that is attached to a customer will require the CVC to be provided again (i.e. using the cvc_token parameter). + RequireCVCRecollection bool `json:"require_cvc_recollection"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsCardSetupFutureUsage `json:"setup_future_usage"` + // Provides information about a card payment that customers see on their statements. Concatenated with the Kana prefix (shortened Kana descriptor) or Kana statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 22 characters. + StatementDescriptorSuffixKana string `json:"statement_descriptor_suffix_kana"` + // Provides information about a card payment that customers see on their statements. Concatenated with the Kanji prefix (shortened Kanji descriptor) or Kanji statement descriptor that's set on the account to form the complete statement descriptor. Maximum 17 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 17 characters. + StatementDescriptorSuffixKanji string `json:"statement_descriptor_suffix_kanji"` +} +type PaymentIntentPaymentMethodOptionsCardPresentRouting struct { + // Requested routing priority + RequestedPriority PaymentIntentPaymentMethodOptionsCardPresentRoutingRequestedPriority `json:"requested_priority"` +} +type PaymentIntentPaymentMethodOptionsCardPresent struct { + // Request ability to capture this payment beyond the standard [authorization validity window](https://stripe.com/docs/terminal/features/extended-authorizations#authorization-validity) + RequestExtendedAuthorization bool `json:"request_extended_authorization"` + // Request ability to [increment](https://stripe.com/docs/terminal/features/incremental-authorizations) this PaymentIntent if the combination of MCC and card brand is eligible. Check [incremental_authorization_supported](https://stripe.com/docs/api/charges/object#charge_object-payment_method_details-card_present-incremental_authorization_supported) in the [Confirm](https://stripe.com/docs/api/payment_intents/confirm) response to verify support. + RequestIncrementalAuthorizationSupport bool `json:"request_incremental_authorization_support"` + Routing *PaymentIntentPaymentMethodOptionsCardPresentRouting `json:"routing"` +} +type PaymentIntentPaymentMethodOptionsCashApp struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsCashAppCaptureMethod `json:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsCashAppSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsCrypto struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsCryptoSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransfer struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country string `json:"country"` +} +type PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransfer struct { + EUBankTransfer *PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransfer `json:"eu_bank_transfer"` + // List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. + // + // Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. + RequestedAddressTypes []PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferRequestedAddressType `json:"requested_address_types"` + // The bank transfer type that this PaymentIntent is allowed to use for funding Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + Type PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransferType `json:"type"` +} +type PaymentIntentPaymentMethodOptionsCustomerBalance struct { + BankTransfer *PaymentIntentPaymentMethodOptionsCustomerBalanceBankTransfer `json:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType PaymentIntentPaymentMethodOptionsCustomerBalanceFundingType `json:"funding_type"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsCustomerBalanceSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsEPS struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsEPSSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsFPX struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsFPXSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsGiropay struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsGiropaySetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsGrabpay struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsGrabpaySetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsIDEAL struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsIDEALSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsInteracPresent struct{} +type PaymentIntentPaymentMethodOptionsKakaoPay struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsKakaoPayCaptureMethod `json:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsKakaoPaySetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsKlarna struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsKlarnaCaptureMethod `json:"capture_method"` + // Preferred locale of the Klarna checkout page that the customer is redirected to. + PreferredLocale string `json:"preferred_locale"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsKlarnaSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsKonbini struct { + // An optional 10 to 11 digit numeric-only string determining the confirmation code at applicable convenience stores. + ConfirmationNumber string `json:"confirmation_number"` + // The number of calendar days (between 1 and 60) after which Konbini payment instructions will expire. For example, if a PaymentIntent is confirmed with Konbini and `expires_after_days` set to 2 on Monday JST, the instructions will expire on Wednesday 23:59:59 JST. + ExpiresAfterDays int64 `json:"expires_after_days"` + // The timestamp at which the Konbini payment instructions will expire. Only one of `expires_after_days` or `expires_at` may be set. + ExpiresAt int64 `json:"expires_at"` + // A product descriptor of up to 22 characters, which will appear to customers at the convenience store. + ProductDescription string `json:"product_description"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsKonbiniSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsKrCard struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsKrCardCaptureMethod `json:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsKrCardSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsLink struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsLinkCaptureMethod `json:"capture_method"` + // [Deprecated] This is a legacy parameter that no longer has any function. + // Deprecated: + PersistentToken string `json:"persistent_token"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsLinkSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsMobilepay struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsMobilepayCaptureMethod `json:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsMobilepaySetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsMultibanco struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsMultibancoSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsNaverPay struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsNaverPayCaptureMethod `json:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsNaverPaySetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsNzBankAccount struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsNzBankAccountSetupFutureUsage `json:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate string `json:"target_date"` +} +type PaymentIntentPaymentMethodOptionsOXXO struct { + // The number of calendar days before an OXXO invoice expires. For example, if you create an OXXO invoice on Monday and you set expires_after_days to 2, the OXXO invoice will expire on Wednesday at 23:59 America/Mexico_City time. + ExpiresAfterDays int64 `json:"expires_after_days"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsOXXOSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsP24 struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsP24SetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsPayByBank struct{} +type PaymentIntentPaymentMethodOptionsPayco struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsPaycoCaptureMethod `json:"capture_method"` +} +type PaymentIntentPaymentMethodOptionsPayNow struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsPayNowSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsPaypal struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsPaypalCaptureMethod `json:"capture_method"` + // Preferred locale of the PayPal checkout page that the customer is redirected to. + PreferredLocale string `json:"preferred_locale"` + // A reference of the PayPal transaction visible to customer which is mapped to PayPal's invoice ID. This must be a globally unique ID if you have configured in your PayPal settings to block multiple payments per invoice ID. + Reference string `json:"reference"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsPaypalSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsPix struct { + // The number of seconds (between 10 and 1209600) after which Pix payment will expire. + ExpiresAfterSeconds int64 `json:"expires_after_seconds"` + // The timestamp at which the Pix expires. + ExpiresAt int64 `json:"expires_at"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsPixSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsPromptPay struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsPromptPaySetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsRevolutPay struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsRevolutPayCaptureMethod `json:"capture_method"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsRevolutPaySetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsSamsungPay struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsSamsungPayCaptureMethod `json:"capture_method"` +} +type PaymentIntentPaymentMethodOptionsSatispay struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentPaymentMethodOptionsSatispayCaptureMethod `json:"capture_method"` +} +type PaymentIntentPaymentMethodOptionsSEPADebitMandateOptions struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'STRIPE'. + ReferencePrefix string `json:"reference_prefix"` +} +type PaymentIntentPaymentMethodOptionsSEPADebit struct { + MandateOptions *PaymentIntentPaymentMethodOptionsSEPADebitMandateOptions `json:"mandate_options"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsSEPADebitSetupFutureUsage `json:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate string `json:"target_date"` +} +type PaymentIntentPaymentMethodOptionsSofort struct { + // Preferred language of the SOFORT authorization page that the customer is redirected to. + PreferredLanguage string `json:"preferred_language"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsSofortSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsSwish struct { + // A reference for this payment to be displayed in the Swish app. + Reference string `json:"reference"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsSwishSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsTWINT struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsTWINTSetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFilters struct { + // The account subcategories to use to filter for possible accounts to link. Valid subcategories are `checking` and `savings`. + AccountSubcategories []PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory `json:"account_subcategories"` +} +type PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnections struct { + Filters *PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFilters `json:"filters"` + // The list of permissions to request. The `payment_method` permission must be included. + Permissions []PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission `json:"permissions"` + // Data features requested to be retrieved upon account creation. + Prefetch []PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch `json:"prefetch"` + // For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + ReturnURL string `json:"return_url"` +} +type PaymentIntentPaymentMethodOptionsUSBankAccountMandateOptions struct { + // Mandate collection method + CollectionMethod PaymentIntentPaymentMethodOptionsUSBankAccountMandateOptionsCollectionMethod `json:"collection_method"` +} +type PaymentIntentPaymentMethodOptionsUSBankAccount struct { + FinancialConnections *PaymentIntentPaymentMethodOptionsUSBankAccountFinancialConnections `json:"financial_connections"` + MandateOptions *PaymentIntentPaymentMethodOptionsUSBankAccountMandateOptions `json:"mandate_options"` + // Preferred transaction settlement speed + PreferredSettlementSpeed PaymentIntentPaymentMethodOptionsUSBankAccountPreferredSettlementSpeed `json:"preferred_settlement_speed"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsUSBankAccountSetupFutureUsage `json:"setup_future_usage"` + // Controls when Stripe will attempt to debit the funds from the customer's account. The date must be a string in YYYY-MM-DD format. The date must be in the future and between 3 and 15 calendar days from now. + TargetDate string `json:"target_date"` + // Bank account verification method. + VerificationMethod PaymentIntentPaymentMethodOptionsUSBankAccountVerificationMethod `json:"verification_method"` +} +type PaymentIntentPaymentMethodOptionsWeChatPay struct { + // The app ID registered with WeChat Pay. Only required when client is ios or android. + AppID string `json:"app_id"` + // The client type that the end customer will pay from + Client PaymentIntentPaymentMethodOptionsWeChatPayClient `json:"client"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsWeChatPaySetupFutureUsage `json:"setup_future_usage"` +} +type PaymentIntentPaymentMethodOptionsZip struct { + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentPaymentMethodOptionsZipSetupFutureUsage `json:"setup_future_usage"` +} + +// Payment-method-specific configuration for this PaymentIntent. +type PaymentIntentPaymentMethodOptions struct { + ACSSDebit *PaymentIntentPaymentMethodOptionsACSSDebit `json:"acss_debit"` + Affirm *PaymentIntentPaymentMethodOptionsAffirm `json:"affirm"` + AfterpayClearpay *PaymentIntentPaymentMethodOptionsAfterpayClearpay `json:"afterpay_clearpay"` + Alipay *PaymentIntentPaymentMethodOptionsAlipay `json:"alipay"` + Alma *PaymentIntentPaymentMethodOptionsAlma `json:"alma"` + AmazonPay *PaymentIntentPaymentMethodOptionsAmazonPay `json:"amazon_pay"` + AUBECSDebit *PaymentIntentPaymentMethodOptionsAUBECSDebit `json:"au_becs_debit"` + BACSDebit *PaymentIntentPaymentMethodOptionsBACSDebit `json:"bacs_debit"` + Bancontact *PaymentIntentPaymentMethodOptionsBancontact `json:"bancontact"` + Billie *PaymentIntentPaymentMethodOptionsBillie `json:"billie"` + BLIK *PaymentIntentPaymentMethodOptionsBLIK `json:"blik"` + Boleto *PaymentIntentPaymentMethodOptionsBoleto `json:"boleto"` + Card *PaymentIntentPaymentMethodOptionsCard `json:"card"` + CardPresent *PaymentIntentPaymentMethodOptionsCardPresent `json:"card_present"` + CashApp *PaymentIntentPaymentMethodOptionsCashApp `json:"cashapp"` + Crypto *PaymentIntentPaymentMethodOptionsCrypto `json:"crypto"` + CustomerBalance *PaymentIntentPaymentMethodOptionsCustomerBalance `json:"customer_balance"` + EPS *PaymentIntentPaymentMethodOptionsEPS `json:"eps"` + FPX *PaymentIntentPaymentMethodOptionsFPX `json:"fpx"` + Giropay *PaymentIntentPaymentMethodOptionsGiropay `json:"giropay"` + Grabpay *PaymentIntentPaymentMethodOptionsGrabpay `json:"grabpay"` + IDEAL *PaymentIntentPaymentMethodOptionsIDEAL `json:"ideal"` + InteracPresent *PaymentIntentPaymentMethodOptionsInteracPresent `json:"interac_present"` + KakaoPay *PaymentIntentPaymentMethodOptionsKakaoPay `json:"kakao_pay"` + Klarna *PaymentIntentPaymentMethodOptionsKlarna `json:"klarna"` + Konbini *PaymentIntentPaymentMethodOptionsKonbini `json:"konbini"` + KrCard *PaymentIntentPaymentMethodOptionsKrCard `json:"kr_card"` + Link *PaymentIntentPaymentMethodOptionsLink `json:"link"` + Mobilepay *PaymentIntentPaymentMethodOptionsMobilepay `json:"mobilepay"` + Multibanco *PaymentIntentPaymentMethodOptionsMultibanco `json:"multibanco"` + NaverPay *PaymentIntentPaymentMethodOptionsNaverPay `json:"naver_pay"` + NzBankAccount *PaymentIntentPaymentMethodOptionsNzBankAccount `json:"nz_bank_account"` + OXXO *PaymentIntentPaymentMethodOptionsOXXO `json:"oxxo"` + P24 *PaymentIntentPaymentMethodOptionsP24 `json:"p24"` + PayByBank *PaymentIntentPaymentMethodOptionsPayByBank `json:"pay_by_bank"` + Payco *PaymentIntentPaymentMethodOptionsPayco `json:"payco"` + PayNow *PaymentIntentPaymentMethodOptionsPayNow `json:"paynow"` + Paypal *PaymentIntentPaymentMethodOptionsPaypal `json:"paypal"` + Pix *PaymentIntentPaymentMethodOptionsPix `json:"pix"` + PromptPay *PaymentIntentPaymentMethodOptionsPromptPay `json:"promptpay"` + RevolutPay *PaymentIntentPaymentMethodOptionsRevolutPay `json:"revolut_pay"` + SamsungPay *PaymentIntentPaymentMethodOptionsSamsungPay `json:"samsung_pay"` + Satispay *PaymentIntentPaymentMethodOptionsSatispay `json:"satispay"` + SEPADebit *PaymentIntentPaymentMethodOptionsSEPADebit `json:"sepa_debit"` + Sofort *PaymentIntentPaymentMethodOptionsSofort `json:"sofort"` + Swish *PaymentIntentPaymentMethodOptionsSwish `json:"swish"` + TWINT *PaymentIntentPaymentMethodOptionsTWINT `json:"twint"` + USBankAccount *PaymentIntentPaymentMethodOptionsUSBankAccount `json:"us_bank_account"` + WeChatPay *PaymentIntentPaymentMethodOptionsWeChatPay `json:"wechat_pay"` + Zip *PaymentIntentPaymentMethodOptionsZip `json:"zip"` +} +type PaymentIntentPresentmentDetails struct { + // Amount intended to be collected by this payment, denominated in presentment_currency. + PresentmentAmount int64 `json:"presentment_amount"` + // Currency presented to the customer during payment. + PresentmentCurrency Currency `json:"presentment_currency"` +} +type PaymentIntentProcessingCardCustomerNotification struct { + // Whether customer approval has been requested for this payment. For payments greater than INR 15000 or mandate amount, the customer must provide explicit approval of the payment with their bank. + ApprovalRequested bool `json:"approval_requested"` + // If customer approval is required, they need to provide approval before this time. + CompletesAt int64 `json:"completes_at"` +} +type PaymentIntentProcessingCard struct { + CustomerNotification *PaymentIntentProcessingCardCustomerNotification `json:"customer_notification"` +} + +// If present, this property tells you about the processing state of the payment. +type PaymentIntentProcessing struct { + Card *PaymentIntentProcessingCard `json:"card"` + // Type of the payment method for which payment is in `processing` state, one of `card`. + Type PaymentIntentProcessingType `json:"type"` +} + +// The data that automatically creates a Transfer after the payment finalizes. Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). +type PaymentIntentTransferData struct { + // The amount transferred to the destination account. This transfer will occur automatically after the payment succeeds. If no amount is specified, by default the entire payment amount is transferred to the destination account. + // The amount must be less than or equal to the [amount](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-amount), and must be a positive integer + // representing how much to transfer in the smallest currency unit (e.g., 100 cents to charge $1.00). + Amount int64 `json:"amount"` + // The account (if any) that the payment is attributed to for tax reporting, and where funds from the payment are transferred to after payment success. + Destination *Account `json:"destination"` +} + +// A PaymentIntent guides you through the process of collecting a payment from your customer. +// We recommend that you create exactly one PaymentIntent for each order or +// customer session in your system. You can reference the PaymentIntent later to +// see the history of payment attempts for a particular session. +// +// A PaymentIntent transitions through +// [multiple statuses](https://stripe.com/docs/payments/intents#intent-statuses) +// throughout its lifetime as it interfaces with Stripe.js to perform +// authentication flows and ultimately creates at most one successful charge. +// +// Related guide: [Payment Intents API](https://stripe.com/docs/payments/payment-intents) +type PaymentIntent struct { + APIResource + // Amount intended to be collected by this PaymentIntent. A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + Amount int64 `json:"amount"` + // Amount that can be captured from this PaymentIntent. + AmountCapturable int64 `json:"amount_capturable"` + AmountDetails *PaymentIntentAmountDetails `json:"amount_details"` + // Amount that this PaymentIntent collects. + AmountReceived int64 `json:"amount_received"` + // ID of the Connect application that created the PaymentIntent. + Application *Application `json:"application"` + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. The amount of the application fee collected will be capped at the total amount captured. For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + ApplicationFeeAmount int64 `json:"application_fee_amount"` + // Settings to configure compatible payment methods from the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods) + AutomaticPaymentMethods *PaymentIntentAutomaticPaymentMethods `json:"automatic_payment_methods"` + // Populated when `status` is `canceled`, this is the time at which the PaymentIntent was canceled. Measured in seconds since the Unix epoch. + CanceledAt int64 `json:"canceled_at"` + // Reason for cancellation of this PaymentIntent, either user-provided (`duplicate`, `fraudulent`, `requested_by_customer`, or `abandoned`) or generated by Stripe internally (`failed_invoice`, `void_invoice`, `automatic`, or `expired`). + CancellationReason PaymentIntentCancellationReason `json:"cancellation_reason"` + // Controls when the funds will be captured from the customer's account. + CaptureMethod PaymentIntentCaptureMethod `json:"capture_method"` + // The client secret of this PaymentIntent. Used for client-side retrieval using a publishable key. + // + // The client secret can be used to complete a payment from your frontend. It should not be stored, logged, or exposed to anyone other than the customer. Make sure that you have TLS enabled on any page that includes the client secret. + // + // Refer to our docs to [accept a payment](https://stripe.com/docs/payments/accept-a-payment?ui=elements) and learn about how `client_secret` should be handled. + ClientSecret string `json:"client_secret"` + // Describes whether we can confirm this PaymentIntent automatically, or if it requires customer action to confirm the payment. + ConfirmationMethod PaymentIntentConfirmationMethod `json:"confirmation_method"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // ID of the Customer this PaymentIntent belongs to, if one exists. + // + // Payment methods attached to other Customers cannot be used with this PaymentIntent. + // + // If [setup_future_usage](https://stripe.com/docs/api#payment_intent_object-setup_future_usage) is set and this PaymentIntent's payment method is not `card_present`, then the payment method attaches to the Customer after the PaymentIntent has been confirmed and any required actions from the user are complete. If the payment method is `card_present` and isn't a digital wallet, then a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card is created and attached to the Customer instead. + Customer *Customer `json:"customer"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // Unique identifier for the object. + ID string `json:"id"` + // The payment error encountered in the previous PaymentIntent confirmation. It will be cleared if the PaymentIntent is later updated for any reason. + LastPaymentError *Error `json:"last_payment_error"` + // ID of the latest [Charge object](https://stripe.com/docs/api/charges) created by this PaymentIntent. This property is `null` until PaymentIntent confirmation is attempted. + LatestCharge *Charge `json:"latest_charge"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Learn more about [storing information in metadata](https://stripe.com/docs/payments/payment-intents/creating-payment-intents#storing-information-in-metadata). + Metadata map[string]string `json:"metadata"` + // If present, this property tells you what actions you need to take in order for your customer to fulfill a payment using the provided source. + NextAction *PaymentIntentNextAction `json:"next_action"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The account (if any) for which the funds of the PaymentIntent are intended. See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts) for details. + OnBehalfOf *Account `json:"on_behalf_of"` + // ID of the payment method used in this PaymentIntent. + PaymentMethod *PaymentMethod `json:"payment_method"` + // Information about the [payment method configuration](https://stripe.com/docs/api/payment_method_configurations) used for this PaymentIntent. + PaymentMethodConfigurationDetails *PaymentIntentPaymentMethodConfigurationDetails `json:"payment_method_configuration_details"` + // Payment-method-specific configuration for this PaymentIntent. + PaymentMethodOptions *PaymentIntentPaymentMethodOptions `json:"payment_method_options"` + // The list of payment method types (e.g. card) that this PaymentIntent is allowed to use. A comprehensive list of valid payment method types can be found [here](https://docs.stripe.com/api/payment_methods/object#payment_method_object-type). + PaymentMethodTypes []string `json:"payment_method_types"` + PresentmentDetails *PaymentIntentPresentmentDetails `json:"presentment_details"` + // If present, this property tells you about the processing state of the payment. + Processing *PaymentIntentProcessing `json:"processing"` + // Email address that the receipt for the resulting payment will be sent to. If `receipt_email` is specified for a payment in live mode, a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). + ReceiptEmail string `json:"receipt_email"` + // ID of the review associated with this PaymentIntent, if any. + Review *Review `json:"review"` + // Indicates that you intend to make future payments with this PaymentIntent's payment method. + // + // If you provide a Customer with the PaymentIntent, you can use this parameter to [attach the payment method](https://docs.stripe.com/payments/save-during-payment) to the Customer after the PaymentIntent is confirmed and the customer completes any required actions. If you don't provide a Customer, you can still [attach](https://docs.stripe.com/api/payment_methods/attach) the payment method to a Customer after the transaction completes. + // + // If the payment method is `card_present` and isn't a digital wallet, Stripe creates and attaches a [generated_card](https://docs.stripe.com/api/charges/object#charge_object-payment_method_details-card_present-generated_card) payment method representing the card to the Customer instead. + // + // When processing card payments, Stripe uses `setup_future_usage` to help you comply with regional legislation and network rules, such as [SCA](https://docs.stripe.com/strong-customer-authentication). + SetupFutureUsage PaymentIntentSetupFutureUsage `json:"setup_future_usage"` + // Shipping information for this PaymentIntent. + Shipping *ShippingDetails `json:"shipping"` + // This is a legacy field that will be removed in the future. It is the ID of the Source object that is associated with this PaymentIntent, if one was supplied. + Source *PaymentSource `json:"source"` + // Text that appears on the customer's statement as the statement descriptor for a non-card charge. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + // + // Setting this value for a card charge returns an error. For card charges, set the [statement_descriptor_suffix](https://docs.stripe.com/get-started/account/statement-descriptors#dynamic) instead. + StatementDescriptor string `json:"statement_descriptor"` + // Provides information about a card charge. Concatenated to the account's [statement descriptor prefix](https://docs.stripe.com/get-started/account/statement-descriptors#static) to form the complete statement descriptor that appears on the customer's statement. + StatementDescriptorSuffix string `json:"statement_descriptor_suffix"` + // Status of this PaymentIntent, one of `requires_payment_method`, `requires_confirmation`, `requires_action`, `processing`, `requires_capture`, `canceled`, or `succeeded`. Read more about each PaymentIntent [status](https://stripe.com/docs/payments/intents#intent-statuses). + Status PaymentIntentStatus `json:"status"` + // The data that automatically creates a Transfer after the payment finalizes. Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + TransferData *PaymentIntentTransferData `json:"transfer_data"` + // A string that identifies the resulting payment as part of a group. Learn more about the [use case for connected accounts](https://stripe.com/docs/connect/separate-charges-and-transfers). + TransferGroup string `json:"transfer_group"` +} + +// PaymentIntentList is a list of PaymentIntents as retrieved from a list endpoint. +type PaymentIntentList struct { + APIResource + ListMeta + Data []*PaymentIntent `json:"data"` +} + +// PaymentIntentSearchResult is a list of PaymentIntent search results as retrieved from a search endpoint. +type PaymentIntentSearchResult struct { + APIResource + SearchMeta + Data []*PaymentIntent `json:"data"` +} + +// UnmarshalJSON handles deserialization of a PaymentIntent. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (p *PaymentIntent) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + p.ID = id + return nil + } + + type paymentIntent PaymentIntent + var v paymentIntent + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *p = PaymentIntent(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/paymentintent_service.go b/vendor/github.com/stripe/stripe-go/v82/paymentintent_service.go new file mode 100644 index 00000000..139455a8 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/paymentintent_service.go @@ -0,0 +1,239 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1PaymentIntentService is used to invoke /v1/payment_intents APIs. +type v1PaymentIntentService struct { + B Backend + Key string +} + +// Creates a PaymentIntent object. +// +// After the PaymentIntent is created, attach a payment method and [confirm](https://docs.stripe.com/docs/api/payment_intents/confirm) +// to continue the payment. Learn more about the available payment flows +// with the Payment Intents API. +// +// When you use confirm=true during creation, it's equivalent to creating +// and confirming the PaymentIntent in the same call. You can use any parameters +// available in the [confirm API](https://docs.stripe.com/docs/api/payment_intents/confirm) when you supply +// confirm=true. +func (c v1PaymentIntentService) Create(ctx context.Context, params *PaymentIntentCreateParams) (*PaymentIntent, error) { + if params == nil { + params = &PaymentIntentCreateParams{} + } + params.Context = ctx + paymentintent := &PaymentIntent{} + err := c.B.Call( + http.MethodPost, "/v1/payment_intents", c.Key, params, paymentintent) + return paymentintent, err +} + +// Retrieves the details of a PaymentIntent that has previously been created. +// +// You can retrieve a PaymentIntent client-side using a publishable key when the client_secret is in the query string. +// +// If you retrieve a PaymentIntent with a publishable key, it only returns a subset of properties. Refer to the [payment intent](https://docs.stripe.com/api#payment_intent_object) object reference for more details. +func (c v1PaymentIntentService) Retrieve(ctx context.Context, id string, params *PaymentIntentRetrieveParams) (*PaymentIntent, error) { + if params == nil { + params = &PaymentIntentRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_intents/%s", id) + paymentintent := &PaymentIntent{} + err := c.B.Call(http.MethodGet, path, c.Key, params, paymentintent) + return paymentintent, err +} + +// Updates properties on a PaymentIntent object without confirming. +// +// Depending on which properties you update, you might need to confirm the +// PaymentIntent again. For example, updating the payment_method +// always requires you to confirm the PaymentIntent again. If you prefer to +// update and confirm at the same time, we recommend updating properties through +// the [confirm API](https://docs.stripe.com/docs/api/payment_intents/confirm) instead. +func (c v1PaymentIntentService) Update(ctx context.Context, id string, params *PaymentIntentUpdateParams) (*PaymentIntent, error) { + if params == nil { + params = &PaymentIntentUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_intents/%s", id) + paymentintent := &PaymentIntent{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentintent) + return paymentintent, err +} + +// Manually reconcile the remaining amount for a customer_balance PaymentIntent. +func (c v1PaymentIntentService) ApplyCustomerBalance(ctx context.Context, id string, params *PaymentIntentApplyCustomerBalanceParams) (*PaymentIntent, error) { + if params == nil { + params = &PaymentIntentApplyCustomerBalanceParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_intents/%s/apply_customer_balance", id) + paymentintent := &PaymentIntent{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentintent) + return paymentintent, err +} + +// You can cancel a PaymentIntent object when it's in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_action or, [in rare cases](https://docs.stripe.com/docs/payments/intents), processing. +// +// After it's canceled, no additional charges are made by the PaymentIntent and any operations on the PaymentIntent fail with an error. For PaymentIntents with a status of requires_capture, the remaining amount_capturable is automatically refunded. +// +// You can't cancel the PaymentIntent for a Checkout Session. [Expire the Checkout Session](https://docs.stripe.com/docs/api/checkout/sessions/expire) instead. +func (c v1PaymentIntentService) Cancel(ctx context.Context, id string, params *PaymentIntentCancelParams) (*PaymentIntent, error) { + if params == nil { + params = &PaymentIntentCancelParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_intents/%s/cancel", id) + paymentintent := &PaymentIntent{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentintent) + return paymentintent, err +} + +// Capture the funds of an existing uncaptured PaymentIntent when its status is requires_capture. +// +// Uncaptured PaymentIntents are cancelled a set number of days (7 by default) after their creation. +// +// Learn more about [separate authorization and capture](https://docs.stripe.com/docs/payments/capture-later). +func (c v1PaymentIntentService) Capture(ctx context.Context, id string, params *PaymentIntentCaptureParams) (*PaymentIntent, error) { + if params == nil { + params = &PaymentIntentCaptureParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_intents/%s/capture", id) + paymentintent := &PaymentIntent{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentintent) + return paymentintent, err +} + +// Confirm that your customer intends to pay with current or provided +// payment method. Upon confirmation, the PaymentIntent will attempt to initiate +// a payment. +// If the selected payment method requires additional authentication steps, the +// PaymentIntent will transition to the requires_action status and +// suggest additional actions via next_action. If payment fails, +// the PaymentIntent transitions to the requires_payment_method status or the +// canceled status if the confirmation limit is reached. If +// payment succeeds, the PaymentIntent will transition to the succeeded +// status (or requires_capture, if capture_method is set to manual). +// If the confirmation_method is automatic, payment may be attempted +// using our [client SDKs](https://docs.stripe.com/docs/stripe-js/reference#stripe-handle-card-payment) +// and the PaymentIntent's [client_secret](https://docs.stripe.com/api#payment_intent_object-client_secret). +// After next_actions are handled by the client, no additional +// confirmation is required to complete the payment. +// If the confirmation_method is manual, all payment attempts must be +// initiated using a secret key. +// If any actions are required for the payment, the PaymentIntent will +// return to the requires_confirmation state +// after those actions are completed. Your server needs to then +// explicitly re-confirm the PaymentIntent to initiate the next payment +// attempt. +// There is a variable upper limit on how many times a PaymentIntent can be confirmed. +// After this limit is reached, any further calls to this endpoint will +// transition the PaymentIntent to the canceled state. +func (c v1PaymentIntentService) Confirm(ctx context.Context, id string, params *PaymentIntentConfirmParams) (*PaymentIntent, error) { + if params == nil { + params = &PaymentIntentConfirmParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_intents/%s/confirm", id) + paymentintent := &PaymentIntent{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentintent) + return paymentintent, err +} + +// Perform an incremental authorization on an eligible +// [PaymentIntent](https://docs.stripe.com/docs/api/payment_intents/object). To be eligible, the +// PaymentIntent's status must be requires_capture and +// [incremental_authorization_supported](https://docs.stripe.com/docs/api/charges/object#charge_object-payment_method_details-card_present-incremental_authorization_supported) +// must be true. +// +// Incremental authorizations attempt to increase the authorized amount on +// your customer's card to the new, higher amount provided. Similar to the +// initial authorization, incremental authorizations can be declined. A +// single PaymentIntent can call this endpoint multiple times to further +// increase the authorized amount. +// +// If the incremental authorization succeeds, the PaymentIntent object +// returns with the updated +// [amount](https://docs.stripe.com/docs/api/payment_intents/object#payment_intent_object-amount). +// If the incremental authorization fails, a +// [card_declined](https://docs.stripe.com/docs/error-codes#card-declined) error returns, and no other +// fields on the PaymentIntent or Charge update. The PaymentIntent +// object remains capturable for the previously authorized amount. +// +// Each PaymentIntent can have a maximum of 10 incremental authorization attempts, including declines. +// After it's captured, a PaymentIntent can no longer be incremented. +// +// Learn more about [incremental authorizations](https://docs.stripe.com/docs/terminal/features/incremental-authorizations). +func (c v1PaymentIntentService) IncrementAuthorization(ctx context.Context, id string, params *PaymentIntentIncrementAuthorizationParams) (*PaymentIntent, error) { + if params == nil { + params = &PaymentIntentIncrementAuthorizationParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_intents/%s/increment_authorization", id) + paymentintent := &PaymentIntent{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentintent) + return paymentintent, err +} + +// Verifies microdeposits on a PaymentIntent object. +func (c v1PaymentIntentService) VerifyMicrodeposits(ctx context.Context, id string, params *PaymentIntentVerifyMicrodepositsParams) (*PaymentIntent, error) { + if params == nil { + params = &PaymentIntentVerifyMicrodepositsParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_intents/%s/verify_microdeposits", id) + paymentintent := &PaymentIntent{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentintent) + return paymentintent, err +} + +// Returns a list of PaymentIntents. +func (c v1PaymentIntentService) List(ctx context.Context, listParams *PaymentIntentListParams) Seq2[*PaymentIntent, error] { + if listParams == nil { + listParams = &PaymentIntentListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*PaymentIntent, ListContainer, error) { + list := &PaymentIntentList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/payment_intents", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// Search for PaymentIntents you've previously created using Stripe's [Search Query Language](https://docs.stripe.com/docs/search#search-query-language). +// Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating +// conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up +// to an hour behind during outages. Search functionality is not available to merchants in India. +func (c v1PaymentIntentService) Search(ctx context.Context, params *PaymentIntentSearchParams) Seq2[*PaymentIntent, error] { + if params == nil { + params = &PaymentIntentSearchParams{} + } + params.Context = ctx + return newV1SearchList(params, func(p *Params, b *form.Values) ([]*PaymentIntent, SearchContainer, error) { + list := &PaymentIntentSearchResult{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/payment_intents/search", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/paymentlink.go b/vendor/github.com/stripe/stripe-go/v82/paymentlink.go new file mode 100644 index 00000000..fa72ab34 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/paymentlink.go @@ -0,0 +1,1996 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The specified behavior after the purchase is complete. +type PaymentLinkAfterCompletionType string + +// List of values that PaymentLinkAfterCompletionType can take +const ( + PaymentLinkAfterCompletionTypeHostedConfirmation PaymentLinkAfterCompletionType = "hosted_confirmation" + PaymentLinkAfterCompletionTypeRedirect PaymentLinkAfterCompletionType = "redirect" +) + +// Type of the account referenced. +type PaymentLinkAutomaticTaxLiabilityType string + +// List of values that PaymentLinkAutomaticTaxLiabilityType can take +const ( + PaymentLinkAutomaticTaxLiabilityTypeAccount PaymentLinkAutomaticTaxLiabilityType = "account" + PaymentLinkAutomaticTaxLiabilityTypeSelf PaymentLinkAutomaticTaxLiabilityType = "self" +) + +// Configuration for collecting the customer's billing address. Defaults to `auto`. +type PaymentLinkBillingAddressCollection string + +// List of values that PaymentLinkBillingAddressCollection can take +const ( + PaymentLinkBillingAddressCollectionAuto PaymentLinkBillingAddressCollection = "auto" + PaymentLinkBillingAddressCollectionRequired PaymentLinkBillingAddressCollection = "required" +) + +// Determines the position and visibility of the payment method reuse agreement in the UI. When set to `auto`, Stripe's defaults will be used. +// +// When set to `hidden`, the payment method reuse agreement text will always be hidden in the UI. +type PaymentLinkConsentCollectionPaymentMethodReuseAgreementPosition string + +// List of values that PaymentLinkConsentCollectionPaymentMethodReuseAgreementPosition can take +const ( + PaymentLinkConsentCollectionPaymentMethodReuseAgreementPositionAuto PaymentLinkConsentCollectionPaymentMethodReuseAgreementPosition = "auto" + PaymentLinkConsentCollectionPaymentMethodReuseAgreementPositionHidden PaymentLinkConsentCollectionPaymentMethodReuseAgreementPosition = "hidden" +) + +// If set to `auto`, enables the collection of customer consent for promotional communications. +type PaymentLinkConsentCollectionPromotions string + +// List of values that PaymentLinkConsentCollectionPromotions can take +const ( + PaymentLinkConsentCollectionPromotionsAuto PaymentLinkConsentCollectionPromotions = "auto" + PaymentLinkConsentCollectionPromotionsNone PaymentLinkConsentCollectionPromotions = "none" +) + +// If set to `required`, it requires cutomers to accept the terms of service before being able to pay. If set to `none`, customers won't be shown a checkbox to accept the terms of service. +type PaymentLinkConsentCollectionTermsOfService string + +// List of values that PaymentLinkConsentCollectionTermsOfService can take +const ( + PaymentLinkConsentCollectionTermsOfServiceNone PaymentLinkConsentCollectionTermsOfService = "none" + PaymentLinkConsentCollectionTermsOfServiceRequired PaymentLinkConsentCollectionTermsOfService = "required" +) + +// The type of the label. +type PaymentLinkCustomFieldLabelType string + +// List of values that PaymentLinkCustomFieldLabelType can take +const ( + PaymentLinkCustomFieldLabelTypeCustom PaymentLinkCustomFieldLabelType = "custom" +) + +// The type of the field. +type PaymentLinkCustomFieldType string + +// List of values that PaymentLinkCustomFieldType can take +const ( + PaymentLinkCustomFieldTypeDropdown PaymentLinkCustomFieldType = "dropdown" + PaymentLinkCustomFieldTypeNumeric PaymentLinkCustomFieldType = "numeric" + PaymentLinkCustomFieldTypeText PaymentLinkCustomFieldType = "text" +) + +// Configuration for Customer creation during checkout. +type PaymentLinkCustomerCreation string + +// List of values that PaymentLinkCustomerCreation can take +const ( + PaymentLinkCustomerCreationAlways PaymentLinkCustomerCreation = "always" + PaymentLinkCustomerCreationIfRequired PaymentLinkCustomerCreation = "if_required" +) + +// Type of the account referenced. +type PaymentLinkInvoiceCreationInvoiceDataIssuerType string + +// List of values that PaymentLinkInvoiceCreationInvoiceDataIssuerType can take +const ( + PaymentLinkInvoiceCreationInvoiceDataIssuerTypeAccount PaymentLinkInvoiceCreationInvoiceDataIssuerType = "account" + PaymentLinkInvoiceCreationInvoiceDataIssuerTypeSelf PaymentLinkInvoiceCreationInvoiceDataIssuerType = "self" +) + +// Indicates when the funds will be captured from the customer's account. +type PaymentLinkPaymentIntentDataCaptureMethod string + +// List of values that PaymentLinkPaymentIntentDataCaptureMethod can take +const ( + PaymentLinkPaymentIntentDataCaptureMethodAutomatic PaymentLinkPaymentIntentDataCaptureMethod = "automatic" + PaymentLinkPaymentIntentDataCaptureMethodAutomaticAsync PaymentLinkPaymentIntentDataCaptureMethod = "automatic_async" + PaymentLinkPaymentIntentDataCaptureMethodManual PaymentLinkPaymentIntentDataCaptureMethod = "manual" +) + +// Indicates that you intend to make future payments with the payment method collected during checkout. +type PaymentLinkPaymentIntentDataSetupFutureUsage string + +// List of values that PaymentLinkPaymentIntentDataSetupFutureUsage can take +const ( + PaymentLinkPaymentIntentDataSetupFutureUsageOffSession PaymentLinkPaymentIntentDataSetupFutureUsage = "off_session" + PaymentLinkPaymentIntentDataSetupFutureUsageOnSession PaymentLinkPaymentIntentDataSetupFutureUsage = "on_session" +) + +// Configuration for collecting a payment method during checkout. Defaults to `always`. +type PaymentLinkPaymentMethodCollection string + +// List of values that PaymentLinkPaymentMethodCollection can take +const ( + PaymentLinkPaymentMethodCollectionAlways PaymentLinkPaymentMethodCollection = "always" + PaymentLinkPaymentMethodCollectionIfRequired PaymentLinkPaymentMethodCollection = "if_required" +) + +// The list of payment method types that customers can use. When `null`, Stripe will dynamically show relevant payment methods you've enabled in your [payment method settings](https://dashboard.stripe.com/settings/payment_methods). +type PaymentLinkPaymentMethodType string + +// List of values that PaymentLinkPaymentMethodType can take +const ( + PaymentLinkPaymentMethodTypeAffirm PaymentLinkPaymentMethodType = "affirm" + PaymentLinkPaymentMethodTypeAfterpayClearpay PaymentLinkPaymentMethodType = "afterpay_clearpay" + PaymentLinkPaymentMethodTypeAlipay PaymentLinkPaymentMethodType = "alipay" + PaymentLinkPaymentMethodTypeAlma PaymentLinkPaymentMethodType = "alma" + PaymentLinkPaymentMethodTypeAUBECSDebit PaymentLinkPaymentMethodType = "au_becs_debit" + PaymentLinkPaymentMethodTypeBACSDebit PaymentLinkPaymentMethodType = "bacs_debit" + PaymentLinkPaymentMethodTypeBancontact PaymentLinkPaymentMethodType = "bancontact" + PaymentLinkPaymentMethodTypeBillie PaymentLinkPaymentMethodType = "billie" + PaymentLinkPaymentMethodTypeBLIK PaymentLinkPaymentMethodType = "blik" + PaymentLinkPaymentMethodTypeBoleto PaymentLinkPaymentMethodType = "boleto" + PaymentLinkPaymentMethodTypeCard PaymentLinkPaymentMethodType = "card" + PaymentLinkPaymentMethodTypeCashApp PaymentLinkPaymentMethodType = "cashapp" + PaymentLinkPaymentMethodTypeEPS PaymentLinkPaymentMethodType = "eps" + PaymentLinkPaymentMethodTypeFPX PaymentLinkPaymentMethodType = "fpx" + PaymentLinkPaymentMethodTypeGiropay PaymentLinkPaymentMethodType = "giropay" + PaymentLinkPaymentMethodTypeGrabpay PaymentLinkPaymentMethodType = "grabpay" + PaymentLinkPaymentMethodTypeIDEAL PaymentLinkPaymentMethodType = "ideal" + PaymentLinkPaymentMethodTypeKlarna PaymentLinkPaymentMethodType = "klarna" + PaymentLinkPaymentMethodTypeKonbini PaymentLinkPaymentMethodType = "konbini" + PaymentLinkPaymentMethodTypeLink PaymentLinkPaymentMethodType = "link" + PaymentLinkPaymentMethodTypeMobilepay PaymentLinkPaymentMethodType = "mobilepay" + PaymentLinkPaymentMethodTypeMultibanco PaymentLinkPaymentMethodType = "multibanco" + PaymentLinkPaymentMethodTypeOXXO PaymentLinkPaymentMethodType = "oxxo" + PaymentLinkPaymentMethodTypeP24 PaymentLinkPaymentMethodType = "p24" + PaymentLinkPaymentMethodTypePayByBank PaymentLinkPaymentMethodType = "pay_by_bank" + PaymentLinkPaymentMethodTypePayNow PaymentLinkPaymentMethodType = "paynow" + PaymentLinkPaymentMethodTypePaypal PaymentLinkPaymentMethodType = "paypal" + PaymentLinkPaymentMethodTypePix PaymentLinkPaymentMethodType = "pix" + PaymentLinkPaymentMethodTypePromptPay PaymentLinkPaymentMethodType = "promptpay" + PaymentLinkPaymentMethodTypeSatispay PaymentLinkPaymentMethodType = "satispay" + PaymentLinkPaymentMethodTypeSEPADebit PaymentLinkPaymentMethodType = "sepa_debit" + PaymentLinkPaymentMethodTypeSofort PaymentLinkPaymentMethodType = "sofort" + PaymentLinkPaymentMethodTypeSwish PaymentLinkPaymentMethodType = "swish" + PaymentLinkPaymentMethodTypeTWINT PaymentLinkPaymentMethodType = "twint" + PaymentLinkPaymentMethodTypeUSBankAccount PaymentLinkPaymentMethodType = "us_bank_account" + PaymentLinkPaymentMethodTypeWeChatPay PaymentLinkPaymentMethodType = "wechat_pay" + PaymentLinkPaymentMethodTypeZip PaymentLinkPaymentMethodType = "zip" +) + +// Indicates the type of transaction being performed which customizes relevant text on the page, such as the submit button. +type PaymentLinkSubmitType string + +// List of values that PaymentLinkSubmitType can take +const ( + PaymentLinkSubmitTypeAuto PaymentLinkSubmitType = "auto" + PaymentLinkSubmitTypeBook PaymentLinkSubmitType = "book" + PaymentLinkSubmitTypeDonate PaymentLinkSubmitType = "donate" + PaymentLinkSubmitTypePay PaymentLinkSubmitType = "pay" + PaymentLinkSubmitTypeSubscribe PaymentLinkSubmitType = "subscribe" +) + +// Type of the account referenced. +type PaymentLinkSubscriptionDataInvoiceSettingsIssuerType string + +// List of values that PaymentLinkSubscriptionDataInvoiceSettingsIssuerType can take +const ( + PaymentLinkSubscriptionDataInvoiceSettingsIssuerTypeAccount PaymentLinkSubscriptionDataInvoiceSettingsIssuerType = "account" + PaymentLinkSubscriptionDataInvoiceSettingsIssuerTypeSelf PaymentLinkSubscriptionDataInvoiceSettingsIssuerType = "self" +) + +// Indicates how the subscription should change when the trial ends if the user did not provide a payment method. +type PaymentLinkSubscriptionDataTrialSettingsEndBehaviorMissingPaymentMethod string + +// List of values that PaymentLinkSubscriptionDataTrialSettingsEndBehaviorMissingPaymentMethod can take +const ( + PaymentLinkSubscriptionDataTrialSettingsEndBehaviorMissingPaymentMethodCancel PaymentLinkSubscriptionDataTrialSettingsEndBehaviorMissingPaymentMethod = "cancel" + PaymentLinkSubscriptionDataTrialSettingsEndBehaviorMissingPaymentMethodCreateInvoice PaymentLinkSubscriptionDataTrialSettingsEndBehaviorMissingPaymentMethod = "create_invoice" + PaymentLinkSubscriptionDataTrialSettingsEndBehaviorMissingPaymentMethodPause PaymentLinkSubscriptionDataTrialSettingsEndBehaviorMissingPaymentMethod = "pause" +) + +type PaymentLinkTaxIDCollectionRequired string + +// List of values that PaymentLinkTaxIDCollectionRequired can take +const ( + PaymentLinkTaxIDCollectionRequiredIfSupported PaymentLinkTaxIDCollectionRequired = "if_supported" + PaymentLinkTaxIDCollectionRequiredNever PaymentLinkTaxIDCollectionRequired = "never" +) + +// Returns a list of your payment links. +type PaymentLinkListParams struct { + ListParams `form:"*"` + // Only return payment links that are active or inactive (e.g., pass `false` to list all inactive payment links). + Active *bool `form:"active"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentLinkListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Configuration when `type=hosted_confirmation`. +type PaymentLinkAfterCompletionHostedConfirmationParams struct { + // A custom message to display to the customer after the purchase is complete. + CustomMessage *string `form:"custom_message"` +} + +// Configuration when `type=redirect`. +type PaymentLinkAfterCompletionRedirectParams struct { + // The URL the customer will be redirected to after the purchase is complete. You can embed `{CHECKOUT_SESSION_ID}` into the URL to have the `id` of the completed [checkout session](https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-id) included. + URL *string `form:"url"` +} + +// Behavior after the purchase is complete. +type PaymentLinkAfterCompletionParams struct { + // Configuration when `type=hosted_confirmation`. + HostedConfirmation *PaymentLinkAfterCompletionHostedConfirmationParams `form:"hosted_confirmation"` + // Configuration when `type=redirect`. + Redirect *PaymentLinkAfterCompletionRedirectParams `form:"redirect"` + // The specified behavior after the purchase is complete. Either `redirect` or `hosted_confirmation`. + Type *string `form:"type"` +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type PaymentLinkAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Configuration for automatic tax collection. +type PaymentLinkAutomaticTaxParams struct { + // Set to `true` to [calculate tax automatically](https://docs.stripe.com/tax) using the customer's location. + // + // Enabling this parameter causes the payment link to collect any billing address information necessary for tax calculation. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *PaymentLinkAutomaticTaxLiabilityParams `form:"liability"` +} + +// Determines the display of payment method reuse agreement text in the UI. If set to `hidden`, it will hide legal text related to the reuse of a payment method. +type PaymentLinkConsentCollectionPaymentMethodReuseAgreementParams struct { + // Determines the position and visibility of the payment method reuse agreement in the UI. When set to `auto`, Stripe's + // defaults will be used. When set to `hidden`, the payment method reuse agreement text will always be hidden in the UI. + Position *string `form:"position"` +} + +// Configure fields to gather active consent from customers. +type PaymentLinkConsentCollectionParams struct { + // Determines the display of payment method reuse agreement text in the UI. If set to `hidden`, it will hide legal text related to the reuse of a payment method. + PaymentMethodReuseAgreement *PaymentLinkConsentCollectionPaymentMethodReuseAgreementParams `form:"payment_method_reuse_agreement"` + // If set to `auto`, enables the collection of customer consent for promotional communications. The Checkout + // Session will determine whether to display an option to opt into promotional communication + // from the merchant depending on the customer's locale. Only available to US merchants. + Promotions *string `form:"promotions"` + // If set to `required`, it requires customers to check a terms of service checkbox before being able to pay. + // There must be a valid terms of service URL set in your [Dashboard settings](https://dashboard.stripe.com/settings/public). + TermsOfService *string `form:"terms_of_service"` +} + +// The options available for the customer to select. Up to 200 options allowed. +type PaymentLinkCustomFieldDropdownOptionParams struct { + // The label for the option, displayed to the customer. Up to 100 characters. + Label *string `form:"label"` + // The value for this option, not displayed to the customer, used by your integration to reconcile the option selected by the customer. Must be unique to this option, alphanumeric, and up to 100 characters. + Value *string `form:"value"` +} + +// Configuration for `type=dropdown` fields. +type PaymentLinkCustomFieldDropdownParams struct { + // The value that will pre-fill the field on the payment page.Must match a `value` in the `options` array. + DefaultValue *string `form:"default_value"` + // The options available for the customer to select. Up to 200 options allowed. + Options []*PaymentLinkCustomFieldDropdownOptionParams `form:"options"` +} + +// The label for the field, displayed to the customer. +type PaymentLinkCustomFieldLabelParams struct { + // Custom text for the label, displayed to the customer. Up to 50 characters. + Custom *string `form:"custom"` + // The type of the label. + Type *string `form:"type"` +} + +// Configuration for `type=numeric` fields. +type PaymentLinkCustomFieldNumericParams struct { + // The value that will pre-fill the field on the payment page. + DefaultValue *string `form:"default_value"` + // The maximum character length constraint for the customer's input. + MaximumLength *int64 `form:"maximum_length"` + // The minimum character length requirement for the customer's input. + MinimumLength *int64 `form:"minimum_length"` +} + +// Configuration for `type=text` fields. +type PaymentLinkCustomFieldTextParams struct { + // The value that will pre-fill the field on the payment page. + DefaultValue *string `form:"default_value"` + // The maximum character length constraint for the customer's input. + MaximumLength *int64 `form:"maximum_length"` + // The minimum character length requirement for the customer's input. + MinimumLength *int64 `form:"minimum_length"` +} + +// Collect additional information from your customer using custom fields. Up to 3 fields are supported. +type PaymentLinkCustomFieldParams struct { + // Configuration for `type=dropdown` fields. + Dropdown *PaymentLinkCustomFieldDropdownParams `form:"dropdown"` + // String of your choice that your integration can use to reconcile this field. Must be unique to this field, alphanumeric, and up to 200 characters. + Key *string `form:"key"` + // The label for the field, displayed to the customer. + Label *PaymentLinkCustomFieldLabelParams `form:"label"` + // Configuration for `type=numeric` fields. + Numeric *PaymentLinkCustomFieldNumericParams `form:"numeric"` + // Whether the customer is required to complete the field before completing the Checkout Session. Defaults to `false`. + Optional *bool `form:"optional"` + // Configuration for `type=text` fields. + Text *PaymentLinkCustomFieldTextParams `form:"text"` + // The type of the field. + Type *string `form:"type"` +} + +// Custom text that should be displayed after the payment confirmation button. +type PaymentLinkCustomTextAfterSubmitParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed alongside shipping address collection. +type PaymentLinkCustomTextShippingAddressParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed alongside the payment confirmation button. +type PaymentLinkCustomTextSubmitParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed in place of the default terms of service agreement text. +type PaymentLinkCustomTextTermsOfServiceAcceptanceParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Display additional text for your customers using custom text. +type PaymentLinkCustomTextParams struct { + // Custom text that should be displayed after the payment confirmation button. + AfterSubmit *PaymentLinkCustomTextAfterSubmitParams `form:"after_submit"` + // Custom text that should be displayed alongside shipping address collection. + ShippingAddress *PaymentLinkCustomTextShippingAddressParams `form:"shipping_address"` + // Custom text that should be displayed alongside the payment confirmation button. + Submit *PaymentLinkCustomTextSubmitParams `form:"submit"` + // Custom text that should be displayed in place of the default terms of service agreement text. + TermsOfServiceAcceptance *PaymentLinkCustomTextTermsOfServiceAcceptanceParams `form:"terms_of_service_acceptance"` +} + +// Default custom fields to be displayed on invoices for this customer. +type PaymentLinkInvoiceCreationInvoiceDataCustomFieldParams struct { + // The name of the custom field. This may be up to 40 characters. + Name *string `form:"name"` + // The value of the custom field. This may be up to 140 characters. + Value *string `form:"value"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type PaymentLinkInvoiceCreationInvoiceDataIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Default options for invoice PDF rendering for this customer. +type PaymentLinkInvoiceCreationInvoiceDataRenderingOptionsParams struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + AmountTaxDisplay *string `form:"amount_tax_display"` +} + +// Invoice PDF configuration. +type PaymentLinkInvoiceCreationInvoiceDataParams struct { + // The account tax IDs associated with the invoice. + AccountTaxIDs []*string `form:"account_tax_ids"` + // Default custom fields to be displayed on invoices for this customer. + CustomFields []*PaymentLinkInvoiceCreationInvoiceDataCustomFieldParams `form:"custom_fields"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Default footer to be displayed on invoices for this customer. + Footer *string `form:"footer"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *PaymentLinkInvoiceCreationInvoiceDataIssuerParams `form:"issuer"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Default options for invoice PDF rendering for this customer. + RenderingOptions *PaymentLinkInvoiceCreationInvoiceDataRenderingOptionsParams `form:"rendering_options"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentLinkInvoiceCreationInvoiceDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Generate a post-purchase Invoice for one-time payments. +type PaymentLinkInvoiceCreationParams struct { + // Whether the feature is enabled + Enabled *bool `form:"enabled"` + // Invoice PDF configuration. + InvoiceData *PaymentLinkInvoiceCreationInvoiceDataParams `form:"invoice_data"` +} + +// When set, provides configuration for this item's quantity to be adjusted by the customer during checkout. +type PaymentLinkLineItemAdjustableQuantityParams struct { + // Set to true if the quantity can be adjusted to any non-negative Integer. + Enabled *bool `form:"enabled"` + // The maximum quantity the customer can purchase. By default this value is 99. You can specify a value up to 999. + Maximum *int64 `form:"maximum"` + // The minimum quantity the customer can purchase. By default this value is 0. If there is only one item in the cart then that item's quantity cannot go down to 0. + Minimum *int64 `form:"minimum"` +} + +// The line items representing what is being sold. Each line item represents an item being sold. Up to 20 line items are supported. +type PaymentLinkLineItemParams struct { + // When set, provides configuration for this item's quantity to be adjusted by the customer during checkout. + AdjustableQuantity *PaymentLinkLineItemAdjustableQuantityParams `form:"adjustable_quantity"` + // The ID of an existing line item on the payment link. + ID *string `form:"id"` + // The ID of the [Price](https://stripe.com/docs/api/prices) or [Plan](https://stripe.com/docs/api/plans) object. + Price *string `form:"price"` + // The quantity of the line item being purchased. + Quantity *int64 `form:"quantity"` +} + +// When set, provides configuration for the customer to adjust the quantity of the line item created when a customer chooses to add this optional item to their order. +type PaymentLinkOptionalItemAdjustableQuantityParams struct { + // Set to true if the quantity can be adjusted to any non-negative integer. + Enabled *bool `form:"enabled"` + // The maximum quantity of this item the customer can purchase. By default this value is 99. + Maximum *int64 `form:"maximum"` + // The minimum quantity of this item the customer must purchase, if they choose to purchase it. Because this item is optional, the customer will always be able to remove it from their order, even if the `minimum` configured here is greater than 0. By default this value is 0. + Minimum *int64 `form:"minimum"` +} + +// A list of optional items the customer can add to their order at checkout. Use this parameter to pass one-time or recurring [Prices](https://stripe.com/docs/api/prices). +// There is a maximum of 10 optional items allowed on a payment link, and the existing limits on the number of line items allowed on a payment link apply to the combined number of line items and optional items. +// There is a maximum of 20 combined line items and optional items. +type PaymentLinkOptionalItemParams struct { + // When set, provides configuration for the customer to adjust the quantity of the line item created when a customer chooses to add this optional item to their order. + AdjustableQuantity *PaymentLinkOptionalItemAdjustableQuantityParams `form:"adjustable_quantity"` + // The ID of the [Price](https://stripe.com/docs/api/prices) or [Plan](https://stripe.com/docs/api/plans) object. + Price *string `form:"price"` + // The initial quantity of the line item created when a customer chooses to add this optional item to their order. + Quantity *int64 `form:"quantity"` +} + +// A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in `payment` mode. +type PaymentLinkPaymentIntentDataParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will declaratively set metadata on [Payment Intents](https://stripe.com/docs/api/payment_intents) generated from this payment link. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + Metadata map[string]string `form:"metadata"` + // Indicates that you intend to [make future payments](https://stripe.com/docs/payments/payment-intents#future-usage) with the payment method collected by this Checkout Session. + // + // When setting this to `on_session`, Checkout will show a notice to the customer that their payment details will be saved. + // + // When setting this to `off_session`, Checkout will show a notice to the customer that their payment details will be saved and used for future payments. + // + // If a Customer has been provided or Checkout creates a new Customer,Checkout will attach the payment method to the Customer. + // + // If Checkout does not create a Customer, the payment method is not attached to a Customer. To reuse the payment method, you can retrieve it from the Checkout Session's PaymentIntent. + // + // When processing card payments, Checkout also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as SCA. + SetupFutureUsage *string `form:"setup_future_usage"` + // Text that appears on the customer's statement as the statement descriptor for a non-card charge. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + // + // Setting this value for a card charge returns an error. For card charges, set the [statement_descriptor_suffix](https://docs.stripe.com/get-started/account/statement-descriptors#dynamic) instead. + StatementDescriptor *string `form:"statement_descriptor"` + // Provides information about a card charge. Concatenated to the account's [statement descriptor prefix](https://docs.stripe.com/get-started/account/statement-descriptors#static) to form the complete statement descriptor that appears on the customer's statement. + StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"` + // A string that identifies the resulting payment as part of a group. See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/connect/separate-charges-and-transfers) for details. + TransferGroup *string `form:"transfer_group"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentLinkPaymentIntentDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Controls phone number collection settings during checkout. +// +// We recommend that you review your privacy policy and check with your legal contacts. +type PaymentLinkPhoneNumberCollectionParams struct { + // Set to `true` to enable phone number collection. + Enabled *bool `form:"enabled"` +} + +// Configuration for the `completed_sessions` restriction type. +type PaymentLinkRestrictionsCompletedSessionsParams struct { + // The maximum number of checkout sessions that can be completed for the `completed_sessions` restriction to be met. + Limit *int64 `form:"limit"` +} + +// Settings that restrict the usage of a payment link. +type PaymentLinkRestrictionsParams struct { + // Configuration for the `completed_sessions` restriction type. + CompletedSessions *PaymentLinkRestrictionsCompletedSessionsParams `form:"completed_sessions"` +} + +// Configuration for collecting the customer's shipping address. +type PaymentLinkShippingAddressCollectionParams struct { + // An array of two-letter ISO country codes representing which countries Checkout should provide as options for + // shipping locations. + AllowedCountries []*string `form:"allowed_countries"` +} + +// The shipping rate options to apply to [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link. +type PaymentLinkShippingOptionParams struct { + // The ID of the Shipping Rate to use for this shipping option. + ShippingRate *string `form:"shipping_rate"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type PaymentLinkSubscriptionDataInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type PaymentLinkSubscriptionDataInvoiceSettingsParams struct { + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *PaymentLinkSubscriptionDataInvoiceSettingsIssuerParams `form:"issuer"` +} + +// Defines how the subscription should behave when the user's free trial ends. +type PaymentLinkSubscriptionDataTrialSettingsEndBehaviorParams struct { + // Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + MissingPaymentMethod *string `form:"missing_payment_method"` +} + +// Settings related to subscription trials. +type PaymentLinkSubscriptionDataTrialSettingsParams struct { + // Defines how the subscription should behave when the user's free trial ends. + EndBehavior *PaymentLinkSubscriptionDataTrialSettingsEndBehaviorParams `form:"end_behavior"` +} + +// When creating a subscription, the specified configuration data will be used. There must be at least one line item with a recurring price to use `subscription_data`. +type PaymentLinkSubscriptionDataParams struct { + // The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // All invoices will be billed using the specified settings. + InvoiceSettings *PaymentLinkSubscriptionDataInvoiceSettingsParams `form:"invoice_settings"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will declaratively set metadata on [Subscriptions](https://stripe.com/docs/api/subscriptions) generated from this payment link. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + Metadata map[string]string `form:"metadata"` + // Integer representing the number of trial period days before the customer is charged for the first time. Has to be at least 1. + TrialPeriodDays *int64 `form:"trial_period_days"` + // Settings related to subscription trials. + TrialSettings *PaymentLinkSubscriptionDataTrialSettingsParams `form:"trial_settings"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentLinkSubscriptionDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Controls tax ID collection during checkout. +type PaymentLinkTaxIDCollectionParams struct { + // Enable tax ID collection during checkout. Defaults to `false`. + Enabled *bool `form:"enabled"` + // Describes whether a tax ID is required during checkout. Defaults to `never`. + Required *string `form:"required"` +} + +// The account (if any) the payments will be attributed to for tax reporting, and where funds from each payment will be transferred to. +type PaymentLinkTransferDataParams struct { + // The amount that will be transferred automatically when a charge succeeds. + Amount *int64 `form:"amount"` + // If specified, successful charges will be attributed to the destination + // account for tax reporting, and the funds from charges will be transferred + // to the destination account. The ID of the resulting transfer will be + // returned on the successful charge's `transfer` field. + Destination *string `form:"destination"` +} + +// Creates a payment link. +type PaymentLinkParams struct { + Params `form:"*"` + // Whether the payment link's `url` is active. If `false`, customers visiting the URL will be shown a page saying that the link has been deactivated. + Active *bool `form:"active"` + // Behavior after the purchase is complete. + AfterCompletion *PaymentLinkAfterCompletionParams `form:"after_completion"` + // Enables user redeemable promotion codes. + AllowPromotionCodes *bool `form:"allow_promotion_codes"` + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. Can only be applied when there are no line items with recurring prices. + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. There must be at least 1 line item with a recurring price to use this field. + ApplicationFeePercent *float64 `form:"application_fee_percent"` + // Configuration for automatic tax collection. + AutomaticTax *PaymentLinkAutomaticTaxParams `form:"automatic_tax"` + // Configuration for collecting the customer's billing address. Defaults to `auto`. + BillingAddressCollection *string `form:"billing_address_collection"` + // Configure fields to gather active consent from customers. + ConsentCollection *PaymentLinkConsentCollectionParams `form:"consent_collection"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies) and supported by each line item's price. + Currency *string `form:"currency"` + // Configures whether [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link create a [Customer](https://stripe.com/docs/api/customers). + CustomerCreation *string `form:"customer_creation"` + // Collect additional information from your customer using custom fields. Up to 3 fields are supported. + CustomFields []*PaymentLinkCustomFieldParams `form:"custom_fields"` + // Display additional text for your customers using custom text. + CustomText *PaymentLinkCustomTextParams `form:"custom_text"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The custom message to be displayed to a customer when a payment link is no longer active. + InactiveMessage *string `form:"inactive_message"` + // Generate a post-purchase Invoice for one-time payments. + InvoiceCreation *PaymentLinkInvoiceCreationParams `form:"invoice_creation"` + // The line items representing what is being sold. Each line item represents an item being sold. Up to 20 line items are supported. + LineItems []*PaymentLinkLineItemParams `form:"line_items"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. Metadata associated with this Payment Link will automatically be copied to [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link. + Metadata map[string]string `form:"metadata"` + // The account on behalf of which to charge. + OnBehalfOf *string `form:"on_behalf_of"` + // A list of optional items the customer can add to their order at checkout. Use this parameter to pass one-time or recurring [Prices](https://stripe.com/docs/api/prices). + // There is a maximum of 10 optional items allowed on a payment link, and the existing limits on the number of line items allowed on a payment link apply to the combined number of line items and optional items. + // There is a maximum of 20 combined line items and optional items. + OptionalItems []*PaymentLinkOptionalItemParams `form:"optional_items"` + // A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in `payment` mode. + PaymentIntentData *PaymentLinkPaymentIntentDataParams `form:"payment_intent_data"` + // Specify whether Checkout should collect a payment method. When set to `if_required`, Checkout will not collect a payment method when the total due for the session is 0.This may occur if the Checkout Session includes a free trial or a discount. + // + // Can only be set in `subscription` mode. Defaults to `always`. + // + // If you'd like information on how to collect a payment method outside of Checkout, read the guide on [configuring subscriptions with a free trial](https://stripe.com/docs/payments/checkout/free-trials). + PaymentMethodCollection *string `form:"payment_method_collection"` + // The list of payment method types that customers can use. If no value is passed, Stripe will dynamically show relevant payment methods from your [payment method settings](https://dashboard.stripe.com/settings/payment_methods) (20+ payment methods [supported](https://stripe.com/docs/payments/payment-methods/integration-options#payment-method-product-support)). + PaymentMethodTypes []*string `form:"payment_method_types"` + // Controls phone number collection settings during checkout. + // + // We recommend that you review your privacy policy and check with your legal contacts. + PhoneNumberCollection *PaymentLinkPhoneNumberCollectionParams `form:"phone_number_collection"` + // Settings that restrict the usage of a payment link. + Restrictions *PaymentLinkRestrictionsParams `form:"restrictions"` + // Configuration for collecting the customer's shipping address. + ShippingAddressCollection *PaymentLinkShippingAddressCollectionParams `form:"shipping_address_collection"` + // The shipping rate options to apply to [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link. + ShippingOptions []*PaymentLinkShippingOptionParams `form:"shipping_options"` + // Describes the type of transaction being performed in order to customize relevant text on the page, such as the submit button. Changing this value will also affect the hostname in the [url](https://stripe.com/docs/api/payment_links/payment_links/object#url) property (example: `donate.stripe.com`). + SubmitType *string `form:"submit_type"` + // When creating a subscription, the specified configuration data will be used. There must be at least one line item with a recurring price to use `subscription_data`. + SubscriptionData *PaymentLinkSubscriptionDataParams `form:"subscription_data"` + // Controls tax ID collection during checkout. + TaxIDCollection *PaymentLinkTaxIDCollectionParams `form:"tax_id_collection"` + // The account (if any) the payments will be attributed to for tax reporting, and where funds from each payment will be transferred to. + TransferData *PaymentLinkTransferDataParams `form:"transfer_data"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentLinkParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentLinkParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// When retrieving a payment link, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. +type PaymentLinkListLineItemsParams struct { + ListParams `form:"*"` + PaymentLink *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentLinkListLineItemsParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Configuration when `type=hosted_confirmation`. +type PaymentLinkCreateAfterCompletionHostedConfirmationParams struct { + // A custom message to display to the customer after the purchase is complete. + CustomMessage *string `form:"custom_message"` +} + +// Configuration when `type=redirect`. +type PaymentLinkCreateAfterCompletionRedirectParams struct { + // The URL the customer will be redirected to after the purchase is complete. You can embed `{CHECKOUT_SESSION_ID}` into the URL to have the `id` of the completed [checkout session](https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-id) included. + URL *string `form:"url"` +} + +// Behavior after the purchase is complete. +type PaymentLinkCreateAfterCompletionParams struct { + // Configuration when `type=hosted_confirmation`. + HostedConfirmation *PaymentLinkCreateAfterCompletionHostedConfirmationParams `form:"hosted_confirmation"` + // Configuration when `type=redirect`. + Redirect *PaymentLinkCreateAfterCompletionRedirectParams `form:"redirect"` + // The specified behavior after the purchase is complete. Either `redirect` or `hosted_confirmation`. + Type *string `form:"type"` +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type PaymentLinkCreateAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Configuration for automatic tax collection. +type PaymentLinkCreateAutomaticTaxParams struct { + // Set to `true` to [calculate tax automatically](https://docs.stripe.com/tax) using the customer's location. + // + // Enabling this parameter causes the payment link to collect any billing address information necessary for tax calculation. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *PaymentLinkCreateAutomaticTaxLiabilityParams `form:"liability"` +} + +// Determines the display of payment method reuse agreement text in the UI. If set to `hidden`, it will hide legal text related to the reuse of a payment method. +type PaymentLinkCreateConsentCollectionPaymentMethodReuseAgreementParams struct { + // Determines the position and visibility of the payment method reuse agreement in the UI. When set to `auto`, Stripe's + // defaults will be used. When set to `hidden`, the payment method reuse agreement text will always be hidden in the UI. + Position *string `form:"position"` +} + +// Configure fields to gather active consent from customers. +type PaymentLinkCreateConsentCollectionParams struct { + // Determines the display of payment method reuse agreement text in the UI. If set to `hidden`, it will hide legal text related to the reuse of a payment method. + PaymentMethodReuseAgreement *PaymentLinkCreateConsentCollectionPaymentMethodReuseAgreementParams `form:"payment_method_reuse_agreement"` + // If set to `auto`, enables the collection of customer consent for promotional communications. The Checkout + // Session will determine whether to display an option to opt into promotional communication + // from the merchant depending on the customer's locale. Only available to US merchants. + Promotions *string `form:"promotions"` + // If set to `required`, it requires customers to check a terms of service checkbox before being able to pay. + // There must be a valid terms of service URL set in your [Dashboard settings](https://dashboard.stripe.com/settings/public). + TermsOfService *string `form:"terms_of_service"` +} + +// The options available for the customer to select. Up to 200 options allowed. +type PaymentLinkCreateCustomFieldDropdownOptionParams struct { + // The label for the option, displayed to the customer. Up to 100 characters. + Label *string `form:"label"` + // The value for this option, not displayed to the customer, used by your integration to reconcile the option selected by the customer. Must be unique to this option, alphanumeric, and up to 100 characters. + Value *string `form:"value"` +} + +// Configuration for `type=dropdown` fields. +type PaymentLinkCreateCustomFieldDropdownParams struct { + // The value that will pre-fill the field on the payment page.Must match a `value` in the `options` array. + DefaultValue *string `form:"default_value"` + // The options available for the customer to select. Up to 200 options allowed. + Options []*PaymentLinkCreateCustomFieldDropdownOptionParams `form:"options"` +} + +// The label for the field, displayed to the customer. +type PaymentLinkCreateCustomFieldLabelParams struct { + // Custom text for the label, displayed to the customer. Up to 50 characters. + Custom *string `form:"custom"` + // The type of the label. + Type *string `form:"type"` +} + +// Configuration for `type=numeric` fields. +type PaymentLinkCreateCustomFieldNumericParams struct { + // The value that will pre-fill the field on the payment page. + DefaultValue *string `form:"default_value"` + // The maximum character length constraint for the customer's input. + MaximumLength *int64 `form:"maximum_length"` + // The minimum character length requirement for the customer's input. + MinimumLength *int64 `form:"minimum_length"` +} + +// Configuration for `type=text` fields. +type PaymentLinkCreateCustomFieldTextParams struct { + // The value that will pre-fill the field on the payment page. + DefaultValue *string `form:"default_value"` + // The maximum character length constraint for the customer's input. + MaximumLength *int64 `form:"maximum_length"` + // The minimum character length requirement for the customer's input. + MinimumLength *int64 `form:"minimum_length"` +} + +// Collect additional information from your customer using custom fields. Up to 3 fields are supported. +type PaymentLinkCreateCustomFieldParams struct { + // Configuration for `type=dropdown` fields. + Dropdown *PaymentLinkCreateCustomFieldDropdownParams `form:"dropdown"` + // String of your choice that your integration can use to reconcile this field. Must be unique to this field, alphanumeric, and up to 200 characters. + Key *string `form:"key"` + // The label for the field, displayed to the customer. + Label *PaymentLinkCreateCustomFieldLabelParams `form:"label"` + // Configuration for `type=numeric` fields. + Numeric *PaymentLinkCreateCustomFieldNumericParams `form:"numeric"` + // Whether the customer is required to complete the field before completing the Checkout Session. Defaults to `false`. + Optional *bool `form:"optional"` + // Configuration for `type=text` fields. + Text *PaymentLinkCreateCustomFieldTextParams `form:"text"` + // The type of the field. + Type *string `form:"type"` +} + +// Custom text that should be displayed after the payment confirmation button. +type PaymentLinkCreateCustomTextAfterSubmitParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed alongside shipping address collection. +type PaymentLinkCreateCustomTextShippingAddressParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed alongside the payment confirmation button. +type PaymentLinkCreateCustomTextSubmitParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed in place of the default terms of service agreement text. +type PaymentLinkCreateCustomTextTermsOfServiceAcceptanceParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Display additional text for your customers using custom text. +type PaymentLinkCreateCustomTextParams struct { + // Custom text that should be displayed after the payment confirmation button. + AfterSubmit *PaymentLinkCreateCustomTextAfterSubmitParams `form:"after_submit"` + // Custom text that should be displayed alongside shipping address collection. + ShippingAddress *PaymentLinkCreateCustomTextShippingAddressParams `form:"shipping_address"` + // Custom text that should be displayed alongside the payment confirmation button. + Submit *PaymentLinkCreateCustomTextSubmitParams `form:"submit"` + // Custom text that should be displayed in place of the default terms of service agreement text. + TermsOfServiceAcceptance *PaymentLinkCreateCustomTextTermsOfServiceAcceptanceParams `form:"terms_of_service_acceptance"` +} + +// Default custom fields to be displayed on invoices for this customer. +type PaymentLinkCreateInvoiceCreationInvoiceDataCustomFieldParams struct { + // The name of the custom field. This may be up to 40 characters. + Name *string `form:"name"` + // The value of the custom field. This may be up to 140 characters. + Value *string `form:"value"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type PaymentLinkCreateInvoiceCreationInvoiceDataIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Default options for invoice PDF rendering for this customer. +type PaymentLinkCreateInvoiceCreationInvoiceDataRenderingOptionsParams struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + AmountTaxDisplay *string `form:"amount_tax_display"` +} + +// Invoice PDF configuration. +type PaymentLinkCreateInvoiceCreationInvoiceDataParams struct { + // The account tax IDs associated with the invoice. + AccountTaxIDs []*string `form:"account_tax_ids"` + // Default custom fields to be displayed on invoices for this customer. + CustomFields []*PaymentLinkCreateInvoiceCreationInvoiceDataCustomFieldParams `form:"custom_fields"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Default footer to be displayed on invoices for this customer. + Footer *string `form:"footer"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *PaymentLinkCreateInvoiceCreationInvoiceDataIssuerParams `form:"issuer"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Default options for invoice PDF rendering for this customer. + RenderingOptions *PaymentLinkCreateInvoiceCreationInvoiceDataRenderingOptionsParams `form:"rendering_options"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentLinkCreateInvoiceCreationInvoiceDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Generate a post-purchase Invoice for one-time payments. +type PaymentLinkCreateInvoiceCreationParams struct { + // Whether the feature is enabled + Enabled *bool `form:"enabled"` + // Invoice PDF configuration. + InvoiceData *PaymentLinkCreateInvoiceCreationInvoiceDataParams `form:"invoice_data"` +} + +// When set, provides configuration for this item's quantity to be adjusted by the customer during checkout. +type PaymentLinkCreateLineItemAdjustableQuantityParams struct { + // Set to true if the quantity can be adjusted to any non-negative Integer. + Enabled *bool `form:"enabled"` + // The maximum quantity the customer can purchase. By default this value is 99. You can specify a value up to 999. + Maximum *int64 `form:"maximum"` + // The minimum quantity the customer can purchase. By default this value is 0. If there is only one item in the cart then that item's quantity cannot go down to 0. + Minimum *int64 `form:"minimum"` +} + +// The line items representing what is being sold. Each line item represents an item being sold. Up to 20 line items are supported. +type PaymentLinkCreateLineItemParams struct { + // When set, provides configuration for this item's quantity to be adjusted by the customer during checkout. + AdjustableQuantity *PaymentLinkCreateLineItemAdjustableQuantityParams `form:"adjustable_quantity"` + // The ID of the [Price](https://stripe.com/docs/api/prices) or [Plan](https://stripe.com/docs/api/plans) object. + Price *string `form:"price"` + // The quantity of the line item being purchased. + Quantity *int64 `form:"quantity"` +} + +// When set, provides configuration for the customer to adjust the quantity of the line item created when a customer chooses to add this optional item to their order. +type PaymentLinkCreateOptionalItemAdjustableQuantityParams struct { + // Set to true if the quantity can be adjusted to any non-negative integer. + Enabled *bool `form:"enabled"` + // The maximum quantity of this item the customer can purchase. By default this value is 99. + Maximum *int64 `form:"maximum"` + // The minimum quantity of this item the customer must purchase, if they choose to purchase it. Because this item is optional, the customer will always be able to remove it from their order, even if the `minimum` configured here is greater than 0. By default this value is 0. + Minimum *int64 `form:"minimum"` +} + +// A list of optional items the customer can add to their order at checkout. Use this parameter to pass one-time or recurring [Prices](https://stripe.com/docs/api/prices). +// There is a maximum of 10 optional items allowed on a payment link, and the existing limits on the number of line items allowed on a payment link apply to the combined number of line items and optional items. +// There is a maximum of 20 combined line items and optional items. +type PaymentLinkCreateOptionalItemParams struct { + // When set, provides configuration for the customer to adjust the quantity of the line item created when a customer chooses to add this optional item to their order. + AdjustableQuantity *PaymentLinkCreateOptionalItemAdjustableQuantityParams `form:"adjustable_quantity"` + // The ID of the [Price](https://stripe.com/docs/api/prices) or [Plan](https://stripe.com/docs/api/plans) object. + Price *string `form:"price"` + // The initial quantity of the line item created when a customer chooses to add this optional item to their order. + Quantity *int64 `form:"quantity"` +} + +// A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in `payment` mode. +type PaymentLinkCreatePaymentIntentDataParams struct { + // Controls when the funds will be captured from the customer's account. + CaptureMethod *string `form:"capture_method"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will declaratively set metadata on [Payment Intents](https://stripe.com/docs/api/payment_intents) generated from this payment link. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + Metadata map[string]string `form:"metadata"` + // Indicates that you intend to [make future payments](https://stripe.com/docs/payments/payment-intents#future-usage) with the payment method collected by this Checkout Session. + // + // When setting this to `on_session`, Checkout will show a notice to the customer that their payment details will be saved. + // + // When setting this to `off_session`, Checkout will show a notice to the customer that their payment details will be saved and used for future payments. + // + // If a Customer has been provided or Checkout creates a new Customer,Checkout will attach the payment method to the Customer. + // + // If Checkout does not create a Customer, the payment method is not attached to a Customer. To reuse the payment method, you can retrieve it from the Checkout Session's PaymentIntent. + // + // When processing card payments, Checkout also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as SCA. + SetupFutureUsage *string `form:"setup_future_usage"` + // Text that appears on the customer's statement as the statement descriptor for a non-card charge. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + // + // Setting this value for a card charge returns an error. For card charges, set the [statement_descriptor_suffix](https://docs.stripe.com/get-started/account/statement-descriptors#dynamic) instead. + StatementDescriptor *string `form:"statement_descriptor"` + // Provides information about a card charge. Concatenated to the account's [statement descriptor prefix](https://docs.stripe.com/get-started/account/statement-descriptors#static) to form the complete statement descriptor that appears on the customer's statement. + StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"` + // A string that identifies the resulting payment as part of a group. See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/connect/separate-charges-and-transfers) for details. + TransferGroup *string `form:"transfer_group"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentLinkCreatePaymentIntentDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Controls phone number collection settings during checkout. +// +// We recommend that you review your privacy policy and check with your legal contacts. +type PaymentLinkCreatePhoneNumberCollectionParams struct { + // Set to `true` to enable phone number collection. + Enabled *bool `form:"enabled"` +} + +// Configuration for the `completed_sessions` restriction type. +type PaymentLinkCreateRestrictionsCompletedSessionsParams struct { + // The maximum number of checkout sessions that can be completed for the `completed_sessions` restriction to be met. + Limit *int64 `form:"limit"` +} + +// Settings that restrict the usage of a payment link. +type PaymentLinkCreateRestrictionsParams struct { + // Configuration for the `completed_sessions` restriction type. + CompletedSessions *PaymentLinkCreateRestrictionsCompletedSessionsParams `form:"completed_sessions"` +} + +// Configuration for collecting the customer's shipping address. +type PaymentLinkCreateShippingAddressCollectionParams struct { + // An array of two-letter ISO country codes representing which countries Checkout should provide as options for + // shipping locations. + AllowedCountries []*string `form:"allowed_countries"` +} + +// The shipping rate options to apply to [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link. +type PaymentLinkCreateShippingOptionParams struct { + // The ID of the Shipping Rate to use for this shipping option. + ShippingRate *string `form:"shipping_rate"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type PaymentLinkCreateSubscriptionDataInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type PaymentLinkCreateSubscriptionDataInvoiceSettingsParams struct { + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *PaymentLinkCreateSubscriptionDataInvoiceSettingsIssuerParams `form:"issuer"` +} + +// Defines how the subscription should behave when the user's free trial ends. +type PaymentLinkCreateSubscriptionDataTrialSettingsEndBehaviorParams struct { + // Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + MissingPaymentMethod *string `form:"missing_payment_method"` +} + +// Settings related to subscription trials. +type PaymentLinkCreateSubscriptionDataTrialSettingsParams struct { + // Defines how the subscription should behave when the user's free trial ends. + EndBehavior *PaymentLinkCreateSubscriptionDataTrialSettingsEndBehaviorParams `form:"end_behavior"` +} + +// When creating a subscription, the specified configuration data will be used. There must be at least one line item with a recurring price to use `subscription_data`. +type PaymentLinkCreateSubscriptionDataParams struct { + // The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // All invoices will be billed using the specified settings. + InvoiceSettings *PaymentLinkCreateSubscriptionDataInvoiceSettingsParams `form:"invoice_settings"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will declaratively set metadata on [Subscriptions](https://stripe.com/docs/api/subscriptions) generated from this payment link. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + Metadata map[string]string `form:"metadata"` + // Integer representing the number of trial period days before the customer is charged for the first time. Has to be at least 1. + TrialPeriodDays *int64 `form:"trial_period_days"` + // Settings related to subscription trials. + TrialSettings *PaymentLinkCreateSubscriptionDataTrialSettingsParams `form:"trial_settings"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentLinkCreateSubscriptionDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Controls tax ID collection during checkout. +type PaymentLinkCreateTaxIDCollectionParams struct { + // Enable tax ID collection during checkout. Defaults to `false`. + Enabled *bool `form:"enabled"` + // Describes whether a tax ID is required during checkout. Defaults to `never`. + Required *string `form:"required"` +} + +// The account (if any) the payments will be attributed to for tax reporting, and where funds from each payment will be transferred to. +type PaymentLinkCreateTransferDataParams struct { + // The amount that will be transferred automatically when a charge succeeds. + Amount *int64 `form:"amount"` + // If specified, successful charges will be attributed to the destination + // account for tax reporting, and the funds from charges will be transferred + // to the destination account. The ID of the resulting transfer will be + // returned on the successful charge's `transfer` field. + Destination *string `form:"destination"` +} + +// Creates a payment link. +type PaymentLinkCreateParams struct { + Params `form:"*"` + // Behavior after the purchase is complete. + AfterCompletion *PaymentLinkCreateAfterCompletionParams `form:"after_completion"` + // Enables user redeemable promotion codes. + AllowPromotionCodes *bool `form:"allow_promotion_codes"` + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. Can only be applied when there are no line items with recurring prices. + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. There must be at least 1 line item with a recurring price to use this field. + ApplicationFeePercent *float64 `form:"application_fee_percent"` + // Configuration for automatic tax collection. + AutomaticTax *PaymentLinkCreateAutomaticTaxParams `form:"automatic_tax"` + // Configuration for collecting the customer's billing address. Defaults to `auto`. + BillingAddressCollection *string `form:"billing_address_collection"` + // Configure fields to gather active consent from customers. + ConsentCollection *PaymentLinkCreateConsentCollectionParams `form:"consent_collection"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies) and supported by each line item's price. + Currency *string `form:"currency"` + // Configures whether [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link create a [Customer](https://stripe.com/docs/api/customers). + CustomerCreation *string `form:"customer_creation"` + // Collect additional information from your customer using custom fields. Up to 3 fields are supported. + CustomFields []*PaymentLinkCreateCustomFieldParams `form:"custom_fields"` + // Display additional text for your customers using custom text. + CustomText *PaymentLinkCreateCustomTextParams `form:"custom_text"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The custom message to be displayed to a customer when a payment link is no longer active. + InactiveMessage *string `form:"inactive_message"` + // Generate a post-purchase Invoice for one-time payments. + InvoiceCreation *PaymentLinkCreateInvoiceCreationParams `form:"invoice_creation"` + // The line items representing what is being sold. Each line item represents an item being sold. Up to 20 line items are supported. + LineItems []*PaymentLinkCreateLineItemParams `form:"line_items"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. Metadata associated with this Payment Link will automatically be copied to [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link. + Metadata map[string]string `form:"metadata"` + // The account on behalf of which to charge. + OnBehalfOf *string `form:"on_behalf_of"` + // A list of optional items the customer can add to their order at checkout. Use this parameter to pass one-time or recurring [Prices](https://stripe.com/docs/api/prices). + // There is a maximum of 10 optional items allowed on a payment link, and the existing limits on the number of line items allowed on a payment link apply to the combined number of line items and optional items. + // There is a maximum of 20 combined line items and optional items. + OptionalItems []*PaymentLinkCreateOptionalItemParams `form:"optional_items"` + // A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in `payment` mode. + PaymentIntentData *PaymentLinkCreatePaymentIntentDataParams `form:"payment_intent_data"` + // Specify whether Checkout should collect a payment method. When set to `if_required`, Checkout will not collect a payment method when the total due for the session is 0.This may occur if the Checkout Session includes a free trial or a discount. + // + // Can only be set in `subscription` mode. Defaults to `always`. + // + // If you'd like information on how to collect a payment method outside of Checkout, read the guide on [configuring subscriptions with a free trial](https://stripe.com/docs/payments/checkout/free-trials). + PaymentMethodCollection *string `form:"payment_method_collection"` + // The list of payment method types that customers can use. If no value is passed, Stripe will dynamically show relevant payment methods from your [payment method settings](https://dashboard.stripe.com/settings/payment_methods) (20+ payment methods [supported](https://stripe.com/docs/payments/payment-methods/integration-options#payment-method-product-support)). + PaymentMethodTypes []*string `form:"payment_method_types"` + // Controls phone number collection settings during checkout. + // + // We recommend that you review your privacy policy and check with your legal contacts. + PhoneNumberCollection *PaymentLinkCreatePhoneNumberCollectionParams `form:"phone_number_collection"` + // Settings that restrict the usage of a payment link. + Restrictions *PaymentLinkCreateRestrictionsParams `form:"restrictions"` + // Configuration for collecting the customer's shipping address. + ShippingAddressCollection *PaymentLinkCreateShippingAddressCollectionParams `form:"shipping_address_collection"` + // The shipping rate options to apply to [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link. + ShippingOptions []*PaymentLinkCreateShippingOptionParams `form:"shipping_options"` + // Describes the type of transaction being performed in order to customize relevant text on the page, such as the submit button. Changing this value will also affect the hostname in the [url](https://stripe.com/docs/api/payment_links/payment_links/object#url) property (example: `donate.stripe.com`). + SubmitType *string `form:"submit_type"` + // When creating a subscription, the specified configuration data will be used. There must be at least one line item with a recurring price to use `subscription_data`. + SubscriptionData *PaymentLinkCreateSubscriptionDataParams `form:"subscription_data"` + // Controls tax ID collection during checkout. + TaxIDCollection *PaymentLinkCreateTaxIDCollectionParams `form:"tax_id_collection"` + // The account (if any) the payments will be attributed to for tax reporting, and where funds from each payment will be transferred to. + TransferData *PaymentLinkCreateTransferDataParams `form:"transfer_data"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentLinkCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentLinkCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieve a payment link. +type PaymentLinkRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentLinkRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Configuration when `type=hosted_confirmation`. +type PaymentLinkUpdateAfterCompletionHostedConfirmationParams struct { + // A custom message to display to the customer after the purchase is complete. + CustomMessage *string `form:"custom_message"` +} + +// Configuration when `type=redirect`. +type PaymentLinkUpdateAfterCompletionRedirectParams struct { + // The URL the customer will be redirected to after the purchase is complete. You can embed `{CHECKOUT_SESSION_ID}` into the URL to have the `id` of the completed [checkout session](https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-id) included. + URL *string `form:"url"` +} + +// Behavior after the purchase is complete. +type PaymentLinkUpdateAfterCompletionParams struct { + // Configuration when `type=hosted_confirmation`. + HostedConfirmation *PaymentLinkUpdateAfterCompletionHostedConfirmationParams `form:"hosted_confirmation"` + // Configuration when `type=redirect`. + Redirect *PaymentLinkUpdateAfterCompletionRedirectParams `form:"redirect"` + // The specified behavior after the purchase is complete. Either `redirect` or `hosted_confirmation`. + Type *string `form:"type"` +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type PaymentLinkUpdateAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Configuration for automatic tax collection. +type PaymentLinkUpdateAutomaticTaxParams struct { + // Set to `true` to [calculate tax automatically](https://docs.stripe.com/tax) using the customer's location. + // + // Enabling this parameter causes the payment link to collect any billing address information necessary for tax calculation. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *PaymentLinkUpdateAutomaticTaxLiabilityParams `form:"liability"` +} + +// The options available for the customer to select. Up to 200 options allowed. +type PaymentLinkUpdateCustomFieldDropdownOptionParams struct { + // The label for the option, displayed to the customer. Up to 100 characters. + Label *string `form:"label"` + // The value for this option, not displayed to the customer, used by your integration to reconcile the option selected by the customer. Must be unique to this option, alphanumeric, and up to 100 characters. + Value *string `form:"value"` +} + +// Configuration for `type=dropdown` fields. +type PaymentLinkUpdateCustomFieldDropdownParams struct { + // The value that will pre-fill the field on the payment page.Must match a `value` in the `options` array. + DefaultValue *string `form:"default_value"` + // The options available for the customer to select. Up to 200 options allowed. + Options []*PaymentLinkUpdateCustomFieldDropdownOptionParams `form:"options"` +} + +// The label for the field, displayed to the customer. +type PaymentLinkUpdateCustomFieldLabelParams struct { + // Custom text for the label, displayed to the customer. Up to 50 characters. + Custom *string `form:"custom"` + // The type of the label. + Type *string `form:"type"` +} + +// Configuration for `type=numeric` fields. +type PaymentLinkUpdateCustomFieldNumericParams struct { + // The value that will pre-fill the field on the payment page. + DefaultValue *string `form:"default_value"` + // The maximum character length constraint for the customer's input. + MaximumLength *int64 `form:"maximum_length"` + // The minimum character length requirement for the customer's input. + MinimumLength *int64 `form:"minimum_length"` +} + +// Configuration for `type=text` fields. +type PaymentLinkUpdateCustomFieldTextParams struct { + // The value that will pre-fill the field on the payment page. + DefaultValue *string `form:"default_value"` + // The maximum character length constraint for the customer's input. + MaximumLength *int64 `form:"maximum_length"` + // The minimum character length requirement for the customer's input. + MinimumLength *int64 `form:"minimum_length"` +} + +// Collect additional information from your customer using custom fields. Up to 3 fields are supported. +type PaymentLinkUpdateCustomFieldParams struct { + // Configuration for `type=dropdown` fields. + Dropdown *PaymentLinkUpdateCustomFieldDropdownParams `form:"dropdown"` + // String of your choice that your integration can use to reconcile this field. Must be unique to this field, alphanumeric, and up to 200 characters. + Key *string `form:"key"` + // The label for the field, displayed to the customer. + Label *PaymentLinkUpdateCustomFieldLabelParams `form:"label"` + // Configuration for `type=numeric` fields. + Numeric *PaymentLinkUpdateCustomFieldNumericParams `form:"numeric"` + // Whether the customer is required to complete the field before completing the Checkout Session. Defaults to `false`. + Optional *bool `form:"optional"` + // Configuration for `type=text` fields. + Text *PaymentLinkUpdateCustomFieldTextParams `form:"text"` + // The type of the field. + Type *string `form:"type"` +} + +// Custom text that should be displayed after the payment confirmation button. +type PaymentLinkUpdateCustomTextAfterSubmitParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed alongside shipping address collection. +type PaymentLinkUpdateCustomTextShippingAddressParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed alongside the payment confirmation button. +type PaymentLinkUpdateCustomTextSubmitParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Custom text that should be displayed in place of the default terms of service agreement text. +type PaymentLinkUpdateCustomTextTermsOfServiceAcceptanceParams struct { + // Text may be up to 1200 characters in length. + Message *string `form:"message"` +} + +// Display additional text for your customers using custom text. +type PaymentLinkUpdateCustomTextParams struct { + // Custom text that should be displayed after the payment confirmation button. + AfterSubmit *PaymentLinkUpdateCustomTextAfterSubmitParams `form:"after_submit"` + // Custom text that should be displayed alongside shipping address collection. + ShippingAddress *PaymentLinkUpdateCustomTextShippingAddressParams `form:"shipping_address"` + // Custom text that should be displayed alongside the payment confirmation button. + Submit *PaymentLinkUpdateCustomTextSubmitParams `form:"submit"` + // Custom text that should be displayed in place of the default terms of service agreement text. + TermsOfServiceAcceptance *PaymentLinkUpdateCustomTextTermsOfServiceAcceptanceParams `form:"terms_of_service_acceptance"` +} + +// Default custom fields to be displayed on invoices for this customer. +type PaymentLinkUpdateInvoiceCreationInvoiceDataCustomFieldParams struct { + // The name of the custom field. This may be up to 40 characters. + Name *string `form:"name"` + // The value of the custom field. This may be up to 140 characters. + Value *string `form:"value"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type PaymentLinkUpdateInvoiceCreationInvoiceDataIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Default options for invoice PDF rendering for this customer. +type PaymentLinkUpdateInvoiceCreationInvoiceDataRenderingOptionsParams struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + AmountTaxDisplay *string `form:"amount_tax_display"` +} + +// Invoice PDF configuration. +type PaymentLinkUpdateInvoiceCreationInvoiceDataParams struct { + // The account tax IDs associated with the invoice. + AccountTaxIDs []*string `form:"account_tax_ids"` + // Default custom fields to be displayed on invoices for this customer. + CustomFields []*PaymentLinkUpdateInvoiceCreationInvoiceDataCustomFieldParams `form:"custom_fields"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Default footer to be displayed on invoices for this customer. + Footer *string `form:"footer"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *PaymentLinkUpdateInvoiceCreationInvoiceDataIssuerParams `form:"issuer"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Default options for invoice PDF rendering for this customer. + RenderingOptions *PaymentLinkUpdateInvoiceCreationInvoiceDataRenderingOptionsParams `form:"rendering_options"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentLinkUpdateInvoiceCreationInvoiceDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Generate a post-purchase Invoice for one-time payments. +type PaymentLinkUpdateInvoiceCreationParams struct { + // Whether the feature is enabled + Enabled *bool `form:"enabled"` + // Invoice PDF configuration. + InvoiceData *PaymentLinkUpdateInvoiceCreationInvoiceDataParams `form:"invoice_data"` +} + +// When set, provides configuration for this item's quantity to be adjusted by the customer during checkout. +type PaymentLinkUpdateLineItemAdjustableQuantityParams struct { + // Set to true if the quantity can be adjusted to any non-negative Integer. + Enabled *bool `form:"enabled"` + // The maximum quantity the customer can purchase. By default this value is 99. You can specify a value up to 999. + Maximum *int64 `form:"maximum"` + // The minimum quantity the customer can purchase. By default this value is 0. If there is only one item in the cart then that item's quantity cannot go down to 0. + Minimum *int64 `form:"minimum"` +} + +// The line items representing what is being sold. Each line item represents an item being sold. Up to 20 line items are supported. +type PaymentLinkUpdateLineItemParams struct { + // When set, provides configuration for this item's quantity to be adjusted by the customer during checkout. + AdjustableQuantity *PaymentLinkUpdateLineItemAdjustableQuantityParams `form:"adjustable_quantity"` + // The ID of an existing line item on the payment link. + ID *string `form:"id"` + // The quantity of the line item being purchased. + Quantity *int64 `form:"quantity"` +} + +// A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in `payment` mode. +type PaymentLinkUpdatePaymentIntentDataParams struct { + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will declaratively set metadata on [Payment Intents](https://stripe.com/docs/api/payment_intents) generated from this payment link. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + Metadata map[string]string `form:"metadata"` + // Text that appears on the customer's statement as the statement descriptor for a non-card charge. This value overrides the account's default statement descriptor. For information about requirements, including the 22-character limit, see [the Statement Descriptor docs](https://docs.stripe.com/get-started/account/statement-descriptors). + // + // Setting this value for a card charge returns an error. For card charges, set the [statement_descriptor_suffix](https://docs.stripe.com/get-started/account/statement-descriptors#dynamic) instead. + StatementDescriptor *string `form:"statement_descriptor"` + // Provides information about a card charge. Concatenated to the account's [statement descriptor prefix](https://docs.stripe.com/get-started/account/statement-descriptors#static) to form the complete statement descriptor that appears on the customer's statement. + StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"` + // A string that identifies the resulting payment as part of a group. See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/connect/separate-charges-and-transfers) for details. + TransferGroup *string `form:"transfer_group"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentLinkUpdatePaymentIntentDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Controls phone number collection settings during checkout. +// +// We recommend that you review your privacy policy and check with your legal contacts. +type PaymentLinkUpdatePhoneNumberCollectionParams struct { + // Set to `true` to enable phone number collection. + Enabled *bool `form:"enabled"` +} + +// Configuration for the `completed_sessions` restriction type. +type PaymentLinkUpdateRestrictionsCompletedSessionsParams struct { + // The maximum number of checkout sessions that can be completed for the `completed_sessions` restriction to be met. + Limit *int64 `form:"limit"` +} + +// Settings that restrict the usage of a payment link. +type PaymentLinkUpdateRestrictionsParams struct { + // Configuration for the `completed_sessions` restriction type. + CompletedSessions *PaymentLinkUpdateRestrictionsCompletedSessionsParams `form:"completed_sessions"` +} + +// Configuration for collecting the customer's shipping address. +type PaymentLinkUpdateShippingAddressCollectionParams struct { + // An array of two-letter ISO country codes representing which countries Checkout should provide as options for + // shipping locations. + AllowedCountries []*string `form:"allowed_countries"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type PaymentLinkUpdateSubscriptionDataInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type PaymentLinkUpdateSubscriptionDataInvoiceSettingsParams struct { + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *PaymentLinkUpdateSubscriptionDataInvoiceSettingsIssuerParams `form:"issuer"` +} + +// Defines how the subscription should behave when the user's free trial ends. +type PaymentLinkUpdateSubscriptionDataTrialSettingsEndBehaviorParams struct { + // Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + MissingPaymentMethod *string `form:"missing_payment_method"` +} + +// Settings related to subscription trials. +type PaymentLinkUpdateSubscriptionDataTrialSettingsParams struct { + // Defines how the subscription should behave when the user's free trial ends. + EndBehavior *PaymentLinkUpdateSubscriptionDataTrialSettingsEndBehaviorParams `form:"end_behavior"` +} + +// When creating a subscription, the specified configuration data will be used. There must be at least one line item with a recurring price to use `subscription_data`. +type PaymentLinkUpdateSubscriptionDataParams struct { + // All invoices will be billed using the specified settings. + InvoiceSettings *PaymentLinkUpdateSubscriptionDataInvoiceSettingsParams `form:"invoice_settings"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will declaratively set metadata on [Subscriptions](https://stripe.com/docs/api/subscriptions) generated from this payment link. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + Metadata map[string]string `form:"metadata"` + // Integer representing the number of trial period days before the customer is charged for the first time. Has to be at least 1. + TrialPeriodDays *int64 `form:"trial_period_days"` + // Settings related to subscription trials. + TrialSettings *PaymentLinkUpdateSubscriptionDataTrialSettingsParams `form:"trial_settings"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentLinkUpdateSubscriptionDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Controls tax ID collection during checkout. +type PaymentLinkUpdateTaxIDCollectionParams struct { + // Enable tax ID collection during checkout. Defaults to `false`. + Enabled *bool `form:"enabled"` + // Describes whether a tax ID is required during checkout. Defaults to `never`. + Required *string `form:"required"` +} + +// Updates a payment link. +type PaymentLinkUpdateParams struct { + Params `form:"*"` + // Whether the payment link's `url` is active. If `false`, customers visiting the URL will be shown a page saying that the link has been deactivated. + Active *bool `form:"active"` + // Behavior after the purchase is complete. + AfterCompletion *PaymentLinkUpdateAfterCompletionParams `form:"after_completion"` + // Enables user redeemable promotion codes. + AllowPromotionCodes *bool `form:"allow_promotion_codes"` + // Configuration for automatic tax collection. + AutomaticTax *PaymentLinkUpdateAutomaticTaxParams `form:"automatic_tax"` + // Configuration for collecting the customer's billing address. Defaults to `auto`. + BillingAddressCollection *string `form:"billing_address_collection"` + // Configures whether [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link create a [Customer](https://stripe.com/docs/api/customers). + CustomerCreation *string `form:"customer_creation"` + // Collect additional information from your customer using custom fields. Up to 3 fields are supported. + CustomFields []*PaymentLinkUpdateCustomFieldParams `form:"custom_fields"` + // Display additional text for your customers using custom text. + CustomText *PaymentLinkUpdateCustomTextParams `form:"custom_text"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The custom message to be displayed to a customer when a payment link is no longer active. + InactiveMessage *string `form:"inactive_message"` + // Generate a post-purchase Invoice for one-time payments. + InvoiceCreation *PaymentLinkUpdateInvoiceCreationParams `form:"invoice_creation"` + // The line items representing what is being sold. Each line item represents an item being sold. Up to 20 line items are supported. + LineItems []*PaymentLinkUpdateLineItemParams `form:"line_items"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. Metadata associated with this Payment Link will automatically be copied to [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link. + Metadata map[string]string `form:"metadata"` + // A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in `payment` mode. + PaymentIntentData *PaymentLinkUpdatePaymentIntentDataParams `form:"payment_intent_data"` + // Specify whether Checkout should collect a payment method. When set to `if_required`, Checkout will not collect a payment method when the total due for the session is 0.This may occur if the Checkout Session includes a free trial or a discount. + // + // Can only be set in `subscription` mode. Defaults to `always`. + // + // If you'd like information on how to collect a payment method outside of Checkout, read the guide on [configuring subscriptions with a free trial](https://stripe.com/docs/payments/checkout/free-trials). + PaymentMethodCollection *string `form:"payment_method_collection"` + // The list of payment method types that customers can use. Pass an empty string to enable dynamic payment methods that use your [payment method settings](https://dashboard.stripe.com/settings/payment_methods). + PaymentMethodTypes []*string `form:"payment_method_types"` + // Controls phone number collection settings during checkout. + // + // We recommend that you review your privacy policy and check with your legal contacts. + PhoneNumberCollection *PaymentLinkUpdatePhoneNumberCollectionParams `form:"phone_number_collection"` + // Settings that restrict the usage of a payment link. + Restrictions *PaymentLinkUpdateRestrictionsParams `form:"restrictions"` + // Configuration for collecting the customer's shipping address. + ShippingAddressCollection *PaymentLinkUpdateShippingAddressCollectionParams `form:"shipping_address_collection"` + // Describes the type of transaction being performed in order to customize relevant text on the page, such as the submit button. Changing this value will also affect the hostname in the [url](https://stripe.com/docs/api/payment_links/payment_links/object#url) property (example: `donate.stripe.com`). + SubmitType *string `form:"submit_type"` + // When creating a subscription, the specified configuration data will be used. There must be at least one line item with a recurring price to use `subscription_data`. + SubscriptionData *PaymentLinkUpdateSubscriptionDataParams `form:"subscription_data"` + // Controls tax ID collection during checkout. + TaxIDCollection *PaymentLinkUpdateTaxIDCollectionParams `form:"tax_id_collection"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentLinkUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentLinkUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +type PaymentLinkAfterCompletionHostedConfirmation struct { + // The custom message that is displayed to the customer after the purchase is complete. + CustomMessage string `json:"custom_message"` +} +type PaymentLinkAfterCompletionRedirect struct { + // The URL the customer will be redirected to after the purchase is complete. + URL string `json:"url"` +} +type PaymentLinkAfterCompletion struct { + HostedConfirmation *PaymentLinkAfterCompletionHostedConfirmation `json:"hosted_confirmation"` + Redirect *PaymentLinkAfterCompletionRedirect `json:"redirect"` + // The specified behavior after the purchase is complete. + Type PaymentLinkAfterCompletionType `json:"type"` +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type PaymentLinkAutomaticTaxLiability struct { + // The connected account being referenced when `type` is `account`. + Account *Account `json:"account"` + // Type of the account referenced. + Type PaymentLinkAutomaticTaxLiabilityType `json:"type"` +} +type PaymentLinkAutomaticTax struct { + // If `true`, tax will be calculated automatically using the customer's location. + Enabled bool `json:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *PaymentLinkAutomaticTaxLiability `json:"liability"` +} + +// Settings related to the payment method reuse text shown in the Checkout UI. +type PaymentLinkConsentCollectionPaymentMethodReuseAgreement struct { + // Determines the position and visibility of the payment method reuse agreement in the UI. When set to `auto`, Stripe's defaults will be used. + // + // When set to `hidden`, the payment method reuse agreement text will always be hidden in the UI. + Position PaymentLinkConsentCollectionPaymentMethodReuseAgreementPosition `json:"position"` +} + +// When set, provides configuration to gather active consent from customers. +type PaymentLinkConsentCollection struct { + // Settings related to the payment method reuse text shown in the Checkout UI. + PaymentMethodReuseAgreement *PaymentLinkConsentCollectionPaymentMethodReuseAgreement `json:"payment_method_reuse_agreement"` + // If set to `auto`, enables the collection of customer consent for promotional communications. + Promotions PaymentLinkConsentCollectionPromotions `json:"promotions"` + // If set to `required`, it requires cutomers to accept the terms of service before being able to pay. If set to `none`, customers won't be shown a checkbox to accept the terms of service. + TermsOfService PaymentLinkConsentCollectionTermsOfService `json:"terms_of_service"` +} + +// The options available for the customer to select. Up to 200 options allowed. +type PaymentLinkCustomFieldDropdownOption struct { + // The label for the option, displayed to the customer. Up to 100 characters. + Label string `json:"label"` + // The value for this option, not displayed to the customer, used by your integration to reconcile the option selected by the customer. Must be unique to this option, alphanumeric, and up to 100 characters. + Value string `json:"value"` +} +type PaymentLinkCustomFieldDropdown struct { + // The value that will pre-fill on the payment page. + DefaultValue string `json:"default_value"` + // The options available for the customer to select. Up to 200 options allowed. + Options []*PaymentLinkCustomFieldDropdownOption `json:"options"` +} +type PaymentLinkCustomFieldLabel struct { + // Custom text for the label, displayed to the customer. Up to 50 characters. + Custom string `json:"custom"` + // The type of the label. + Type PaymentLinkCustomFieldLabelType `json:"type"` +} +type PaymentLinkCustomFieldNumeric struct { + // The value that will pre-fill the field on the payment page. + DefaultValue string `json:"default_value"` + // The maximum character length constraint for the customer's input. + MaximumLength int64 `json:"maximum_length"` + // The minimum character length requirement for the customer's input. + MinimumLength int64 `json:"minimum_length"` +} +type PaymentLinkCustomFieldText struct { + // The value that will pre-fill the field on the payment page. + DefaultValue string `json:"default_value"` + // The maximum character length constraint for the customer's input. + MaximumLength int64 `json:"maximum_length"` + // The minimum character length requirement for the customer's input. + MinimumLength int64 `json:"minimum_length"` +} + +// Collect additional information from your customer using custom fields. Up to 3 fields are supported. +type PaymentLinkCustomField struct { + Dropdown *PaymentLinkCustomFieldDropdown `json:"dropdown"` + // String of your choice that your integration can use to reconcile this field. Must be unique to this field, alphanumeric, and up to 200 characters. + Key string `json:"key"` + Label *PaymentLinkCustomFieldLabel `json:"label"` + Numeric *PaymentLinkCustomFieldNumeric `json:"numeric"` + // Whether the customer is required to complete the field before completing the Checkout Session. Defaults to `false`. + Optional bool `json:"optional"` + Text *PaymentLinkCustomFieldText `json:"text"` + // The type of the field. + Type PaymentLinkCustomFieldType `json:"type"` +} + +// Custom text that should be displayed after the payment confirmation button. +type PaymentLinkCustomTextAfterSubmit struct { + // Text may be up to 1200 characters in length. + Message string `json:"message"` +} + +// Custom text that should be displayed alongside shipping address collection. +type PaymentLinkCustomTextShippingAddress struct { + // Text may be up to 1200 characters in length. + Message string `json:"message"` +} + +// Custom text that should be displayed alongside the payment confirmation button. +type PaymentLinkCustomTextSubmit struct { + // Text may be up to 1200 characters in length. + Message string `json:"message"` +} + +// Custom text that should be displayed in place of the default terms of service agreement text. +type PaymentLinkCustomTextTermsOfServiceAcceptance struct { + // Text may be up to 1200 characters in length. + Message string `json:"message"` +} +type PaymentLinkCustomText struct { + // Custom text that should be displayed after the payment confirmation button. + AfterSubmit *PaymentLinkCustomTextAfterSubmit `json:"after_submit"` + // Custom text that should be displayed alongside shipping address collection. + ShippingAddress *PaymentLinkCustomTextShippingAddress `json:"shipping_address"` + // Custom text that should be displayed alongside the payment confirmation button. + Submit *PaymentLinkCustomTextSubmit `json:"submit"` + // Custom text that should be displayed in place of the default terms of service agreement text. + TermsOfServiceAcceptance *PaymentLinkCustomTextTermsOfServiceAcceptance `json:"terms_of_service_acceptance"` +} + +// A list of up to 4 custom fields to be displayed on the invoice. +type PaymentLinkInvoiceCreationInvoiceDataCustomField struct { + // The name of the custom field. + Name string `json:"name"` + // The value of the custom field. + Value string `json:"value"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type PaymentLinkInvoiceCreationInvoiceDataIssuer struct { + // The connected account being referenced when `type` is `account`. + Account *Account `json:"account"` + // Type of the account referenced. + Type PaymentLinkInvoiceCreationInvoiceDataIssuerType `json:"type"` +} + +// Options for invoice PDF rendering. +type PaymentLinkInvoiceCreationInvoiceDataRenderingOptions struct { + // How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. + AmountTaxDisplay string `json:"amount_tax_display"` +} + +// Configuration for the invoice. Default invoice values will be used if unspecified. +type PaymentLinkInvoiceCreationInvoiceData struct { + // The account tax IDs associated with the invoice. + AccountTaxIDs []*TaxID `json:"account_tax_ids"` + // A list of up to 4 custom fields to be displayed on the invoice. + CustomFields []*PaymentLinkInvoiceCreationInvoiceDataCustomField `json:"custom_fields"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // Footer to be displayed on the invoice. + Footer string `json:"footer"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *PaymentLinkInvoiceCreationInvoiceDataIssuer `json:"issuer"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // Options for invoice PDF rendering. + RenderingOptions *PaymentLinkInvoiceCreationInvoiceDataRenderingOptions `json:"rendering_options"` +} + +// Configuration for creating invoice for payment mode payment links. +type PaymentLinkInvoiceCreation struct { + // Enable creating an invoice on successful payment. + Enabled bool `json:"enabled"` + // Configuration for the invoice. Default invoice values will be used if unspecified. + InvoiceData *PaymentLinkInvoiceCreationInvoiceData `json:"invoice_data"` +} +type PaymentLinkOptionalItemAdjustableQuantity struct { + // Set to true if the quantity can be adjusted to any non-negative integer. + Enabled bool `json:"enabled"` + // The maximum quantity of this item the customer can purchase. By default this value is 99. + Maximum int64 `json:"maximum"` + // The minimum quantity of this item the customer must purchase, if they choose to purchase it. Because this item is optional, the customer will always be able to remove it from their order, even if the `minimum` configured here is greater than 0. By default this value is 0. + Minimum int64 `json:"minimum"` +} + +// The optional items presented to the customer at checkout. +type PaymentLinkOptionalItem struct { + AdjustableQuantity *PaymentLinkOptionalItemAdjustableQuantity `json:"adjustable_quantity"` + Price string `json:"price"` + Quantity int64 `json:"quantity"` +} + +// Indicates the parameters to be passed to PaymentIntent creation during checkout. +type PaymentLinkPaymentIntentData struct { + // Indicates when the funds will be captured from the customer's account. + CaptureMethod PaymentLinkPaymentIntentDataCaptureMethod `json:"capture_method"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will set metadata on [Payment Intents](https://stripe.com/docs/api/payment_intents) generated from this payment link. + Metadata map[string]string `json:"metadata"` + // Indicates that you intend to make future payments with the payment method collected during checkout. + SetupFutureUsage PaymentLinkPaymentIntentDataSetupFutureUsage `json:"setup_future_usage"` + // For a non-card payment, information about the charge that appears on the customer's statement when this payment succeeds in creating a charge. + StatementDescriptor string `json:"statement_descriptor"` + // For a card payment, information about the charge that appears on the customer's statement when this payment succeeds in creating a charge. Concatenated with the account's statement descriptor prefix to form the complete statement descriptor. + StatementDescriptorSuffix string `json:"statement_descriptor_suffix"` + // A string that identifies the resulting payment as part of a group. See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/connect/separate-charges-and-transfers) for details. + TransferGroup string `json:"transfer_group"` +} +type PaymentLinkPhoneNumberCollection struct { + // If `true`, a phone number will be collected during checkout. + Enabled bool `json:"enabled"` +} +type PaymentLinkRestrictionsCompletedSessions struct { + // The current number of checkout sessions that have been completed on the payment link which count towards the `completed_sessions` restriction to be met. + Count int64 `json:"count"` + // The maximum number of checkout sessions that can be completed for the `completed_sessions` restriction to be met. + Limit int64 `json:"limit"` +} + +// Settings that restrict the usage of a payment link. +type PaymentLinkRestrictions struct { + CompletedSessions *PaymentLinkRestrictionsCompletedSessions `json:"completed_sessions"` +} + +// Configuration for collecting the customer's shipping address. +type PaymentLinkShippingAddressCollection struct { + // An array of two-letter ISO country codes representing which countries Checkout should provide as options for shipping locations. Unsupported country codes: `AS, CX, CC, CU, HM, IR, KP, MH, FM, NF, MP, PW, SD, SY, UM, VI`. + AllowedCountries []string `json:"allowed_countries"` +} + +// The shipping rate options applied to the session. +type PaymentLinkShippingOption struct { + // A non-negative integer in cents representing how much to charge. + ShippingAmount int64 `json:"shipping_amount"` + // The ID of the Shipping Rate to use for this shipping option. + ShippingRate *ShippingRate `json:"shipping_rate"` +} +type PaymentLinkSubscriptionDataInvoiceSettingsIssuer struct { + // The connected account being referenced when `type` is `account`. + Account *Account `json:"account"` + // Type of the account referenced. + Type PaymentLinkSubscriptionDataInvoiceSettingsIssuerType `json:"type"` +} +type PaymentLinkSubscriptionDataInvoiceSettings struct { + Issuer *PaymentLinkSubscriptionDataInvoiceSettingsIssuer `json:"issuer"` +} + +// Defines how a subscription behaves when a free trial ends. +type PaymentLinkSubscriptionDataTrialSettingsEndBehavior struct { + // Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + MissingPaymentMethod PaymentLinkSubscriptionDataTrialSettingsEndBehaviorMissingPaymentMethod `json:"missing_payment_method"` +} + +// Settings related to subscription trials. +type PaymentLinkSubscriptionDataTrialSettings struct { + // Defines how a subscription behaves when a free trial ends. + EndBehavior *PaymentLinkSubscriptionDataTrialSettingsEndBehavior `json:"end_behavior"` +} + +// When creating a subscription, the specified configuration data will be used. There must be at least one line item with a recurring price to use `subscription_data`. +type PaymentLinkSubscriptionData struct { + // The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description string `json:"description"` + InvoiceSettings *PaymentLinkSubscriptionDataInvoiceSettings `json:"invoice_settings"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will set metadata on [Subscriptions](https://stripe.com/docs/api/subscriptions) generated from this payment link. + Metadata map[string]string `json:"metadata"` + // Integer representing the number of trial period days before the customer is charged for the first time. + TrialPeriodDays int64 `json:"trial_period_days"` + // Settings related to subscription trials. + TrialSettings *PaymentLinkSubscriptionDataTrialSettings `json:"trial_settings"` +} +type PaymentLinkTaxIDCollection struct { + // Indicates whether tax ID collection is enabled for the session. + Enabled bool `json:"enabled"` + Required PaymentLinkTaxIDCollectionRequired `json:"required"` +} + +// The account (if any) the payments will be attributed to for tax reporting, and where funds from each payment will be transferred to. +type PaymentLinkTransferData struct { + // The amount in cents (or local equivalent) that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + Amount int64 `json:"amount"` + // The connected account receiving the transfer. + Destination *Account `json:"destination"` +} + +// A payment link is a shareable URL that will take your customers to a hosted payment page. A payment link can be shared and used multiple times. +// +// When a customer opens a payment link it will open a new [checkout session](https://stripe.com/docs/api/checkout/sessions) to render the payment page. You can use [checkout session events](https://stripe.com/docs/api/events/types#event_types-checkout.session.completed) to track payments through payment links. +// +// Related guide: [Payment Links API](https://stripe.com/docs/payment-links) +type PaymentLink struct { + APIResource + // Whether the payment link's `url` is active. If `false`, customers visiting the URL will be shown a page saying that the link has been deactivated. + Active bool `json:"active"` + AfterCompletion *PaymentLinkAfterCompletion `json:"after_completion"` + // Whether user redeemable promotion codes are enabled. + AllowPromotionCodes bool `json:"allow_promotion_codes"` + // The ID of the Connect application that created the Payment Link. + Application *Application `json:"application"` + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. + ApplicationFeeAmount int64 `json:"application_fee_amount"` + // This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. + ApplicationFeePercent float64 `json:"application_fee_percent"` + AutomaticTax *PaymentLinkAutomaticTax `json:"automatic_tax"` + // Configuration for collecting the customer's billing address. Defaults to `auto`. + BillingAddressCollection PaymentLinkBillingAddressCollection `json:"billing_address_collection"` + // When set, provides configuration to gather active consent from customers. + ConsentCollection *PaymentLinkConsentCollection `json:"consent_collection"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // Configuration for Customer creation during checkout. + CustomerCreation PaymentLinkCustomerCreation `json:"customer_creation"` + // Collect additional information from your customer using custom fields. Up to 3 fields are supported. + CustomFields []*PaymentLinkCustomField `json:"custom_fields"` + CustomText *PaymentLinkCustomText `json:"custom_text"` + // Unique identifier for the object. + ID string `json:"id"` + // The custom message to be displayed to a customer when a payment link is no longer active. + InactiveMessage string `json:"inactive_message"` + // Configuration for creating invoice for payment mode payment links. + InvoiceCreation *PaymentLinkInvoiceCreation `json:"invoice_creation"` + // The line items representing what is being sold. + LineItems *LineItemList `json:"line_items"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The account on behalf of which to charge. See the [Connect documentation](https://support.stripe.com/questions/sending-invoices-on-behalf-of-connected-accounts) for details. + OnBehalfOf *Account `json:"on_behalf_of"` + // The optional items presented to the customer at checkout. + OptionalItems []*PaymentLinkOptionalItem `json:"optional_items"` + // Indicates the parameters to be passed to PaymentIntent creation during checkout. + PaymentIntentData *PaymentLinkPaymentIntentData `json:"payment_intent_data"` + // Configuration for collecting a payment method during checkout. Defaults to `always`. + PaymentMethodCollection PaymentLinkPaymentMethodCollection `json:"payment_method_collection"` + // The list of payment method types that customers can use. When `null`, Stripe will dynamically show relevant payment methods you've enabled in your [payment method settings](https://dashboard.stripe.com/settings/payment_methods). + PaymentMethodTypes []PaymentLinkPaymentMethodType `json:"payment_method_types"` + PhoneNumberCollection *PaymentLinkPhoneNumberCollection `json:"phone_number_collection"` + // Settings that restrict the usage of a payment link. + Restrictions *PaymentLinkRestrictions `json:"restrictions"` + // Configuration for collecting the customer's shipping address. + ShippingAddressCollection *PaymentLinkShippingAddressCollection `json:"shipping_address_collection"` + // The shipping rate options applied to the session. + ShippingOptions []*PaymentLinkShippingOption `json:"shipping_options"` + // Indicates the type of transaction being performed which customizes relevant text on the page, such as the submit button. + SubmitType PaymentLinkSubmitType `json:"submit_type"` + // When creating a subscription, the specified configuration data will be used. There must be at least one line item with a recurring price to use `subscription_data`. + SubscriptionData *PaymentLinkSubscriptionData `json:"subscription_data"` + TaxIDCollection *PaymentLinkTaxIDCollection `json:"tax_id_collection"` + // The account (if any) the payments will be attributed to for tax reporting, and where funds from each payment will be transferred to. + TransferData *PaymentLinkTransferData `json:"transfer_data"` + // The public URL that can be shared with customers. + URL string `json:"url"` +} + +// PaymentLinkList is a list of PaymentLinks as retrieved from a list endpoint. +type PaymentLinkList struct { + APIResource + ListMeta + Data []*PaymentLink `json:"data"` +} + +// UnmarshalJSON handles deserialization of a PaymentLink. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (p *PaymentLink) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + p.ID = id + return nil + } + + type paymentLink PaymentLink + var v paymentLink + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *p = PaymentLink(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/paymentlink_service.go b/vendor/github.com/stripe/stripe-go/v82/paymentlink_service.go new file mode 100644 index 00000000..ccb1e11b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/paymentlink_service.go @@ -0,0 +1,92 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1PaymentLinkService is used to invoke /v1/payment_links APIs. +type v1PaymentLinkService struct { + B Backend + Key string +} + +// Creates a payment link. +func (c v1PaymentLinkService) Create(ctx context.Context, params *PaymentLinkCreateParams) (*PaymentLink, error) { + if params == nil { + params = &PaymentLinkCreateParams{} + } + params.Context = ctx + paymentlink := &PaymentLink{} + err := c.B.Call( + http.MethodPost, "/v1/payment_links", c.Key, params, paymentlink) + return paymentlink, err +} + +// Retrieve a payment link. +func (c v1PaymentLinkService) Retrieve(ctx context.Context, id string, params *PaymentLinkRetrieveParams) (*PaymentLink, error) { + if params == nil { + params = &PaymentLinkRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_links/%s", id) + paymentlink := &PaymentLink{} + err := c.B.Call(http.MethodGet, path, c.Key, params, paymentlink) + return paymentlink, err +} + +// Updates a payment link. +func (c v1PaymentLinkService) Update(ctx context.Context, id string, params *PaymentLinkUpdateParams) (*PaymentLink, error) { + if params == nil { + params = &PaymentLinkUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_links/%s", id) + paymentlink := &PaymentLink{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentlink) + return paymentlink, err +} + +// Returns a list of your payment links. +func (c v1PaymentLinkService) List(ctx context.Context, listParams *PaymentLinkListParams) Seq2[*PaymentLink, error] { + if listParams == nil { + listParams = &PaymentLinkListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*PaymentLink, ListContainer, error) { + list := &PaymentLinkList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/payment_links", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// When retrieving a payment link, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. +func (c v1PaymentLinkService) ListLineItems(ctx context.Context, listParams *PaymentLinkListLineItemsParams) Seq2[*LineItem, error] { + if listParams == nil { + listParams = &PaymentLinkListLineItemsParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/payment_links/%s/line_items", StringValue(listParams.PaymentLink)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*LineItem, ListContainer, error) { + list := &LineItemList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/paymentmethod.go b/vendor/github.com/stripe/stripe-go/v82/paymentmethod.go new file mode 100644 index 00000000..aec0813c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/paymentmethod.go @@ -0,0 +1,1954 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to “unspecified”. +type PaymentMethodAllowRedisplay string + +// List of values that PaymentMethodAllowRedisplay can take +const ( + PaymentMethodAllowRedisplayAlways PaymentMethodAllowRedisplay = "always" + PaymentMethodAllowRedisplayLimited PaymentMethodAllowRedisplay = "limited" + PaymentMethodAllowRedisplayUnspecified PaymentMethodAllowRedisplay = "unspecified" +) + +// Card brand. Can be `amex`, `diners`, `discover`, `eftpos_au`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. +type PaymentMethodCardBrand string + +// List of values that PaymentMethodCardBrand can take +const ( + PaymentMethodCardBrandAmex PaymentMethodCardBrand = "amex" + PaymentMethodCardBrandDiners PaymentMethodCardBrand = "diners" + PaymentMethodCardBrandDiscover PaymentMethodCardBrand = "discover" + PaymentMethodCardBrandJCB PaymentMethodCardBrand = "jcb" + PaymentMethodCardBrandMastercard PaymentMethodCardBrand = "mastercard" + PaymentMethodCardBrandUnionpay PaymentMethodCardBrand = "unionpay" + PaymentMethodCardBrandUnknown PaymentMethodCardBrand = "unknown" + PaymentMethodCardBrandVisa PaymentMethodCardBrand = "visa" +) + +// If a address line1 was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. +type PaymentMethodCardChecksAddressLine1Check string + +// List of values that PaymentMethodCardChecksAddressLine1Check can take +const ( + PaymentMethodCardChecksAddressLine1CheckFail PaymentMethodCardChecksAddressLine1Check = "fail" + PaymentMethodCardChecksAddressLine1CheckPass PaymentMethodCardChecksAddressLine1Check = "pass" + PaymentMethodCardChecksAddressLine1CheckUnavailable PaymentMethodCardChecksAddressLine1Check = "unavailable" + PaymentMethodCardChecksAddressLine1CheckUnchecked PaymentMethodCardChecksAddressLine1Check = "unchecked" +) + +// If a address postal code was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. +type PaymentMethodCardChecksAddressPostalCodeCheck string + +// List of values that PaymentMethodCardChecksAddressPostalCodeCheck can take +const ( + PaymentMethodCardChecksAddressPostalCodeCheckFail PaymentMethodCardChecksAddressPostalCodeCheck = "fail" + PaymentMethodCardChecksAddressPostalCodeCheckPass PaymentMethodCardChecksAddressPostalCodeCheck = "pass" + PaymentMethodCardChecksAddressPostalCodeCheckUnavailable PaymentMethodCardChecksAddressPostalCodeCheck = "unavailable" + PaymentMethodCardChecksAddressPostalCodeCheckUnchecked PaymentMethodCardChecksAddressPostalCodeCheck = "unchecked" +) + +// If a CVC was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. +type PaymentMethodCardChecksCVCCheck string + +// List of values that PaymentMethodCardChecksCVCCheck can take +const ( + PaymentMethodCardChecksCVCCheckFail PaymentMethodCardChecksCVCCheck = "fail" + PaymentMethodCardChecksCVCCheckPass PaymentMethodCardChecksCVCCheck = "pass" + PaymentMethodCardChecksCVCCheckUnavailable PaymentMethodCardChecksCVCCheck = "unavailable" + PaymentMethodCardChecksCVCCheckUnchecked PaymentMethodCardChecksCVCCheck = "unchecked" +) + +// The method used to process this payment method offline. Only deferred is allowed. +type PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentOfflineType string + +// List of values that PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentOfflineType can take +const ( + PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentOfflineTypeDeferred PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentOfflineType = "deferred" +) + +// How card details were read in this transaction. +type PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod string + +// List of values that PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod can take +const ( + PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReadMethodContactEmv PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod = "contact_emv" + PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReadMethodContactlessEmv PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod = "contactless_emv" + PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReadMethodContactlessMagstripeMode PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod = "contactless_magstripe_mode" + PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReadMethodMagneticStripeFallback PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod = "magnetic_stripe_fallback" + PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReadMethodMagneticStripeTrack2 PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod = "magnetic_stripe_track2" +) + +// The type of account being debited or credited +type PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountType string + +// List of values that PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountType can take +const ( + PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountTypeChecking PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountType = "checking" + PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountTypeCredit PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountType = "credit" + PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountTypePrepaid PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountType = "prepaid" + PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountTypeUnknown PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountType = "unknown" +) + +// The type of mobile wallet, one of `apple_pay`, `google_pay`, `samsung_pay`, or `unknown`. +type PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentWalletType string + +// List of values that PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentWalletType can take +const ( + PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentWalletTypeApplePay PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentWalletType = "apple_pay" + PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentWalletTypeGooglePay PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentWalletType = "google_pay" + PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentWalletTypeSamsungPay PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentWalletType = "samsung_pay" + PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentWalletTypeUnknown PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentWalletType = "unknown" +) + +// All networks available for selection via [payment_method_options.card.network](https://docs.stripe.com/api/payment_intents/confirm#confirm_payment_intent-payment_method_options-card-network). +type PaymentMethodCardNetworksAvailable string + +// List of values that PaymentMethodCardNetworksAvailable can take +const ( + PaymentMethodCardNetworksAvailableAmex PaymentMethodCardNetworksAvailable = "amex" + PaymentMethodCardNetworksAvailableCartesBancaires PaymentMethodCardNetworksAvailable = "cartes_bancaires" + PaymentMethodCardNetworksAvailableDiners PaymentMethodCardNetworksAvailable = "diners" + PaymentMethodCardNetworksAvailableDiscover PaymentMethodCardNetworksAvailable = "discover" + PaymentMethodCardNetworksAvailableInterac PaymentMethodCardNetworksAvailable = "interac" + PaymentMethodCardNetworksAvailableJCB PaymentMethodCardNetworksAvailable = "jcb" + PaymentMethodCardNetworksAvailableMastercard PaymentMethodCardNetworksAvailable = "mastercard" + PaymentMethodCardNetworksAvailableUnionpay PaymentMethodCardNetworksAvailable = "unionpay" + PaymentMethodCardNetworksAvailableVisa PaymentMethodCardNetworksAvailable = "visa" + PaymentMethodCardNetworksAvailableUnknown PaymentMethodCardNetworksAvailable = "unknown" +) + +// The preferred network for co-branded cards. Can be `cartes_bancaires`, `mastercard`, `visa` or `invalid_preference` if requested network is not valid for the card. +type PaymentMethodCardNetworksPreferred string + +// List of values that PaymentMethodCardNetworksPreferred can take +const ( + PaymentMethodCardNetworksPreferredAmex PaymentMethodCardNetworksPreferred = "amex" + PaymentMethodCardNetworksPreferredCartesBancaires PaymentMethodCardNetworksPreferred = "cartes_bancaires" + PaymentMethodCardNetworksPreferredDiners PaymentMethodCardNetworksPreferred = "diners" + PaymentMethodCardNetworksPreferredDiscover PaymentMethodCardNetworksPreferred = "discover" + PaymentMethodCardNetworksPreferredInterac PaymentMethodCardNetworksPreferred = "interac" + PaymentMethodCardNetworksPreferredJCB PaymentMethodCardNetworksPreferred = "jcb" + PaymentMethodCardNetworksPreferredMastercard PaymentMethodCardNetworksPreferred = "mastercard" + PaymentMethodCardNetworksPreferredUnionpay PaymentMethodCardNetworksPreferred = "unionpay" + PaymentMethodCardNetworksPreferredVisa PaymentMethodCardNetworksPreferred = "visa" + PaymentMethodCardNetworksPreferredUnknown PaymentMethodCardNetworksPreferred = "unknown" +) + +// Status of a card based on the card issuer. +type PaymentMethodCardRegulatedStatus string + +// List of values that PaymentMethodCardRegulatedStatus can take +const ( + PaymentMethodCardRegulatedStatusRegulated PaymentMethodCardRegulatedStatus = "regulated" + PaymentMethodCardRegulatedStatusUnregulated PaymentMethodCardRegulatedStatus = "unregulated" +) + +// The type of the card wallet, one of `amex_express_checkout`, `apple_pay`, `google_pay`, `masterpass`, `samsung_pay`, `visa_checkout`, or `link`. An additional hash is included on the Wallet subhash with a name matching this value. It contains additional information specific to the card wallet type. +type PaymentMethodCardWalletType string + +// List of values that PaymentMethodCardWalletType can take +const ( + PaymentMethodCardWalletTypeAmexExpressCheckout PaymentMethodCardWalletType = "amex_express_checkout" + PaymentMethodCardWalletTypeApplePay PaymentMethodCardWalletType = "apple_pay" + PaymentMethodCardWalletTypeGooglePay PaymentMethodCardWalletType = "google_pay" + PaymentMethodCardWalletTypeLink PaymentMethodCardWalletType = "link" + PaymentMethodCardWalletTypeMasterpass PaymentMethodCardWalletType = "masterpass" + PaymentMethodCardWalletTypeSamsungPay PaymentMethodCardWalletType = "samsung_pay" + PaymentMethodCardWalletTypeVisaCheckout PaymentMethodCardWalletType = "visa_checkout" +) + +// The method used to process this payment method offline. Only deferred is allowed. +type PaymentMethodCardPresentOfflineType string + +// List of values that PaymentMethodCardPresentOfflineType can take +const ( + PaymentMethodCardPresentOfflineTypeDeferred PaymentMethodCardPresentOfflineType = "deferred" +) + +// How card details were read in this transaction. +type PaymentMethodCardPresentReadMethod string + +// List of values that PaymentMethodCardPresentReadMethod can take +const ( + PaymentMethodCardPresentReadMethodContactEmv PaymentMethodCardPresentReadMethod = "contact_emv" + PaymentMethodCardPresentReadMethodContactlessEmv PaymentMethodCardPresentReadMethod = "contactless_emv" + PaymentMethodCardPresentReadMethodContactlessMagstripeMode PaymentMethodCardPresentReadMethod = "contactless_magstripe_mode" + PaymentMethodCardPresentReadMethodMagneticStripeFallback PaymentMethodCardPresentReadMethod = "magnetic_stripe_fallback" + PaymentMethodCardPresentReadMethodMagneticStripeTrack2 PaymentMethodCardPresentReadMethod = "magnetic_stripe_track2" +) + +// The type of mobile wallet, one of `apple_pay`, `google_pay`, `samsung_pay`, or `unknown`. +type PaymentMethodCardPresentWalletType string + +// List of values that PaymentMethodCardPresentWalletType can take +const ( + PaymentMethodCardPresentWalletTypeApplePay PaymentMethodCardPresentWalletType = "apple_pay" + PaymentMethodCardPresentWalletTypeGooglePay PaymentMethodCardPresentWalletType = "google_pay" + PaymentMethodCardPresentWalletTypeSamsungPay PaymentMethodCardPresentWalletType = "samsung_pay" + PaymentMethodCardPresentWalletTypeUnknown PaymentMethodCardPresentWalletType = "unknown" +) + +// Account holder type, if provided. Can be one of `individual` or `company`. +type PaymentMethodFPXAccountHolderType string + +// List of values that PaymentMethodFPXAccountHolderType can take +const ( + PaymentMethodFPXAccountHolderTypeCompany PaymentMethodFPXAccountHolderType = "company" + PaymentMethodFPXAccountHolderTypeIndividual PaymentMethodFPXAccountHolderType = "individual" +) + +// How card details were read in this transaction. +type PaymentMethodInteracPresentReadMethod string + +// List of values that PaymentMethodInteracPresentReadMethod can take +const ( + PaymentMethodInteracPresentReadMethodContactEmv PaymentMethodInteracPresentReadMethod = "contact_emv" + PaymentMethodInteracPresentReadMethodContactlessEmv PaymentMethodInteracPresentReadMethod = "contactless_emv" + PaymentMethodInteracPresentReadMethodContactlessMagstripeMode PaymentMethodInteracPresentReadMethod = "contactless_magstripe_mode" + PaymentMethodInteracPresentReadMethodMagneticStripeFallback PaymentMethodInteracPresentReadMethod = "magnetic_stripe_fallback" + PaymentMethodInteracPresentReadMethodMagneticStripeTrack2 PaymentMethodInteracPresentReadMethod = "magnetic_stripe_track2" +) + +// The local credit or debit card brand. +type PaymentMethodKrCardBrand string + +// List of values that PaymentMethodKrCardBrand can take +const ( + PaymentMethodKrCardBrandBc PaymentMethodKrCardBrand = "bc" + PaymentMethodKrCardBrandCiti PaymentMethodKrCardBrand = "citi" + PaymentMethodKrCardBrandHana PaymentMethodKrCardBrand = "hana" + PaymentMethodKrCardBrandHyundai PaymentMethodKrCardBrand = "hyundai" + PaymentMethodKrCardBrandJeju PaymentMethodKrCardBrand = "jeju" + PaymentMethodKrCardBrandJeonbuk PaymentMethodKrCardBrand = "jeonbuk" + PaymentMethodKrCardBrandKakaobank PaymentMethodKrCardBrand = "kakaobank" + PaymentMethodKrCardBrandKbank PaymentMethodKrCardBrand = "kbank" + PaymentMethodKrCardBrandKdbbank PaymentMethodKrCardBrand = "kdbbank" + PaymentMethodKrCardBrandKookmin PaymentMethodKrCardBrand = "kookmin" + PaymentMethodKrCardBrandKwangju PaymentMethodKrCardBrand = "kwangju" + PaymentMethodKrCardBrandLotte PaymentMethodKrCardBrand = "lotte" + PaymentMethodKrCardBrandMg PaymentMethodKrCardBrand = "mg" + PaymentMethodKrCardBrandNh PaymentMethodKrCardBrand = "nh" + PaymentMethodKrCardBrandPost PaymentMethodKrCardBrand = "post" + PaymentMethodKrCardBrandSamsung PaymentMethodKrCardBrand = "samsung" + PaymentMethodKrCardBrandSavingsbank PaymentMethodKrCardBrand = "savingsbank" + PaymentMethodKrCardBrandShinhan PaymentMethodKrCardBrand = "shinhan" + PaymentMethodKrCardBrandShinhyup PaymentMethodKrCardBrand = "shinhyup" + PaymentMethodKrCardBrandSuhyup PaymentMethodKrCardBrand = "suhyup" + PaymentMethodKrCardBrandTossbank PaymentMethodKrCardBrand = "tossbank" + PaymentMethodKrCardBrandWoori PaymentMethodKrCardBrand = "woori" +) + +// Whether to fund this transaction with Naver Pay points or a card. +type PaymentMethodNaverPayFunding string + +// List of values that PaymentMethodNaverPayFunding can take +const ( + PaymentMethodNaverPayFundingCard PaymentMethodNaverPayFunding = "card" + PaymentMethodNaverPayFundingPoints PaymentMethodNaverPayFunding = "points" +) + +// The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. +type PaymentMethodType string + +// List of values that PaymentMethodType can take +const ( + PaymentMethodTypeACSSDebit PaymentMethodType = "acss_debit" + PaymentMethodTypeAffirm PaymentMethodType = "affirm" + PaymentMethodTypeAfterpayClearpay PaymentMethodType = "afterpay_clearpay" + PaymentMethodTypeAlipay PaymentMethodType = "alipay" + PaymentMethodTypeAlma PaymentMethodType = "alma" + PaymentMethodTypeAmazonPay PaymentMethodType = "amazon_pay" + PaymentMethodTypeAUBECSDebit PaymentMethodType = "au_becs_debit" + PaymentMethodTypeBACSDebit PaymentMethodType = "bacs_debit" + PaymentMethodTypeBancontact PaymentMethodType = "bancontact" + PaymentMethodTypeBillie PaymentMethodType = "billie" + PaymentMethodTypeBLIK PaymentMethodType = "blik" + PaymentMethodTypeBoleto PaymentMethodType = "boleto" + PaymentMethodTypeCard PaymentMethodType = "card" + PaymentMethodTypeCardPresent PaymentMethodType = "card_present" + PaymentMethodTypeCashApp PaymentMethodType = "cashapp" + PaymentMethodTypeCrypto PaymentMethodType = "crypto" + PaymentMethodTypeCustomerBalance PaymentMethodType = "customer_balance" + PaymentMethodTypeEPS PaymentMethodType = "eps" + PaymentMethodTypeFPX PaymentMethodType = "fpx" + PaymentMethodTypeGiropay PaymentMethodType = "giropay" + PaymentMethodTypeGrabpay PaymentMethodType = "grabpay" + PaymentMethodTypeIDEAL PaymentMethodType = "ideal" + PaymentMethodTypeInteracPresent PaymentMethodType = "interac_present" + PaymentMethodTypeKakaoPay PaymentMethodType = "kakao_pay" + PaymentMethodTypeKlarna PaymentMethodType = "klarna" + PaymentMethodTypeKonbini PaymentMethodType = "konbini" + PaymentMethodTypeKrCard PaymentMethodType = "kr_card" + PaymentMethodTypeLink PaymentMethodType = "link" + PaymentMethodTypeMobilepay PaymentMethodType = "mobilepay" + PaymentMethodTypeMultibanco PaymentMethodType = "multibanco" + PaymentMethodTypeNaverPay PaymentMethodType = "naver_pay" + PaymentMethodTypeNzBankAccount PaymentMethodType = "nz_bank_account" + PaymentMethodTypeOXXO PaymentMethodType = "oxxo" + PaymentMethodTypeP24 PaymentMethodType = "p24" + PaymentMethodTypePayByBank PaymentMethodType = "pay_by_bank" + PaymentMethodTypePayco PaymentMethodType = "payco" + PaymentMethodTypePayNow PaymentMethodType = "paynow" + PaymentMethodTypePaypal PaymentMethodType = "paypal" + PaymentMethodTypePix PaymentMethodType = "pix" + PaymentMethodTypePromptPay PaymentMethodType = "promptpay" + PaymentMethodTypeRevolutPay PaymentMethodType = "revolut_pay" + PaymentMethodTypeSamsungPay PaymentMethodType = "samsung_pay" + PaymentMethodTypeSatispay PaymentMethodType = "satispay" + PaymentMethodTypeSEPADebit PaymentMethodType = "sepa_debit" + PaymentMethodTypeSofort PaymentMethodType = "sofort" + PaymentMethodTypeSwish PaymentMethodType = "swish" + PaymentMethodTypeTWINT PaymentMethodType = "twint" + PaymentMethodTypeUSBankAccount PaymentMethodType = "us_bank_account" + PaymentMethodTypeWeChatPay PaymentMethodType = "wechat_pay" + PaymentMethodTypeZip PaymentMethodType = "zip" +) + +// Account holder type: individual or company. +type PaymentMethodUSBankAccountAccountHolderType string + +// List of values that PaymentMethodUSBankAccountAccountHolderType can take +const ( + PaymentMethodUSBankAccountAccountHolderTypeCompany PaymentMethodUSBankAccountAccountHolderType = "company" + PaymentMethodUSBankAccountAccountHolderTypeIndividual PaymentMethodUSBankAccountAccountHolderType = "individual" +) + +// Account type: checkings or savings. Defaults to checking if omitted. +type PaymentMethodUSBankAccountAccountType string + +// List of values that PaymentMethodUSBankAccountAccountType can take +const ( + PaymentMethodUSBankAccountAccountTypeChecking PaymentMethodUSBankAccountAccountType = "checking" + PaymentMethodUSBankAccountAccountTypeSavings PaymentMethodUSBankAccountAccountType = "savings" +) + +// All supported networks. +type PaymentMethodUSBankAccountNetworksSupported string + +// List of values that PaymentMethodUSBankAccountNetworksSupported can take +const ( + PaymentMethodUSBankAccountNetworksSupportedACH PaymentMethodUSBankAccountNetworksSupported = "ach" + PaymentMethodUSBankAccountNetworksSupportedUSDomesticWire PaymentMethodUSBankAccountNetworksSupported = "us_domestic_wire" +) + +// The ACH network code that resulted in this block. +type PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode string + +// List of values that PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode can take +const ( + PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCodeR02 PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode = "R02" + PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCodeR03 PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode = "R03" + PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCodeR04 PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode = "R04" + PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCodeR05 PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode = "R05" + PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCodeR07 PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode = "R07" + PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCodeR08 PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode = "R08" + PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCodeR10 PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode = "R10" + PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCodeR11 PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode = "R11" + PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCodeR16 PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode = "R16" + PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCodeR20 PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode = "R20" + PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCodeR29 PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode = "R29" + PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCodeR31 PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode = "R31" +) + +// The reason why this PaymentMethod's fingerprint has been blocked +type PaymentMethodUSBankAccountStatusDetailsBlockedReason string + +// List of values that PaymentMethodUSBankAccountStatusDetailsBlockedReason can take +const ( + PaymentMethodUSBankAccountStatusDetailsBlockedReasonBankAccountClosed PaymentMethodUSBankAccountStatusDetailsBlockedReason = "bank_account_closed" + PaymentMethodUSBankAccountStatusDetailsBlockedReasonBankAccountFrozen PaymentMethodUSBankAccountStatusDetailsBlockedReason = "bank_account_frozen" + PaymentMethodUSBankAccountStatusDetailsBlockedReasonBankAccountInvalidDetails PaymentMethodUSBankAccountStatusDetailsBlockedReason = "bank_account_invalid_details" + PaymentMethodUSBankAccountStatusDetailsBlockedReasonBankAccountRestricted PaymentMethodUSBankAccountStatusDetailsBlockedReason = "bank_account_restricted" + PaymentMethodUSBankAccountStatusDetailsBlockedReasonBankAccountUnusable PaymentMethodUSBankAccountStatusDetailsBlockedReason = "bank_account_unusable" + PaymentMethodUSBankAccountStatusDetailsBlockedReasonDebitNotAuthorized PaymentMethodUSBankAccountStatusDetailsBlockedReason = "debit_not_authorized" +) + +// Returns a list of PaymentMethods for Treasury flows. If you want to list the PaymentMethods attached to a Customer for payments, you should use the [List a Customer's PaymentMethods](https://docs.stripe.com/docs/api/payment_methods/customer_list) API instead. +type PaymentMethodListParams struct { + ListParams `form:"*"` + // The ID of the customer whose PaymentMethods will be retrieved. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // An optional filter on the list, based on the object `type` field. Without the filter, the list includes all current and future payment method types. If your integration expects only one type of payment method in the response, make sure to provide a type value in the request. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. +type PaymentMethodACSSDebitParams struct { + // Customer's bank account number. + AccountNumber *string `form:"account_number"` + // Institution number of the customer's bank. + InstitutionNumber *string `form:"institution_number"` + // Transit number of the customer's bank. + TransitNumber *string `form:"transit_number"` +} + +// If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. +type PaymentMethodAffirmParams struct{} + +// If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. +type PaymentMethodAfterpayClearpayParams struct{} + +// If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. +type PaymentMethodAlipayParams struct{} + +// If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. +type PaymentMethodAlmaParams struct{} + +// If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. +type PaymentMethodAmazonPayParams struct{} + +// If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. +type PaymentMethodAUBECSDebitParams struct { + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // Bank-State-Branch number of the bank account. + BSBNumber *string `form:"bsb_number"` +} + +// If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. +type PaymentMethodBACSDebitParams struct { + // Account number of the bank account that the funds will be debited from. + AccountNumber *string `form:"account_number"` + // Sort code of the bank account. (e.g., `10-20-30`) + SortCode *string `form:"sort_code"` +} + +// If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. +type PaymentMethodBancontactParams struct{} + +// If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. +type PaymentMethodBillieParams struct{} + +// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. +type PaymentMethodBillingDetailsParams struct { + // Billing address. + Address *AddressParams `form:"address"` + // Email address. + Email *string `form:"email"` + // Full name. + Name *string `form:"name"` + // Billing phone number (including extension). + Phone *string `form:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID *string `form:"tax_id"` +} + +// If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. +type PaymentMethodBLIKParams struct{} + +// If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. +type PaymentMethodBoletoParams struct { + // The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + TaxID *string `form:"tax_id"` +} + +// Contains information about card networks used to process the payment. +type PaymentMethodCardNetworksParams struct { + // The customer's preferred card network for co-branded cards. Supports `cartes_bancaires`, `mastercard`, or `visa`. Selection of a network that does not apply to the card will be stored as `invalid_preference` on the card. + Preferred *string `form:"preferred"` +} + +// If this is a `card` PaymentMethod, this hash contains the user's card details. For backwards compatibility, you can alternatively provide a Stripe token (e.g., for Apple Pay, Amex Express Checkout, or legacy Checkout) into the card hash with format `card: {token: "tok_visa"}`. When providing a card number, you must meet the requirements for [PCI compliance](https://stripe.com/docs/security#validating-pci-compliance). We strongly recommend using Stripe.js instead of interacting with this API directly. +type PaymentMethodCardParams struct { + // The card's CVC. It is highly recommended to always include this value. + CVC *string `form:"cvc"` + // Two-digit number representing the card's expiration month. + ExpMonth *int64 `form:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear *int64 `form:"exp_year"` + // Contains information about card networks used to process the payment. + Networks *PaymentMethodCardNetworksParams `form:"networks"` + // The card number, as a string without any separators. + Number *string `form:"number"` + // For backwards compatibility, you can alternatively provide a Stripe token (e.g., for Apple Pay, Amex Express Checkout, or legacy Checkout) into the card hash with format card: {token: "tok_visa"}. + Token *string `form:"token"` +} + +// If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. +type PaymentMethodCashAppParams struct{} + +// If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. +type PaymentMethodCryptoParams struct{} + +// If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. +type PaymentMethodCustomerBalanceParams struct{} + +// If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. +type PaymentMethodEPSParams struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. +type PaymentMethodFPXParams struct { + // Account holder type for FPX transaction + AccountHolderType *string `form:"account_holder_type"` + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. +type PaymentMethodGiropayParams struct{} + +// If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. +type PaymentMethodGrabpayParams struct{} + +// If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. +type PaymentMethodIDEALParams struct { + // The customer's bank. Only use this parameter for existing customers. Don't use it for new customers. + Bank *string `form:"bank"` +} + +// If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. +type PaymentMethodInteracPresentParams struct{} + +// If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. +type PaymentMethodKakaoPayParams struct{} + +// Customer's date of birth +type PaymentMethodKlarnaDOBParams struct { + // The day of birth, between 1 and 31. + Day *int64 `form:"day"` + // The month of birth, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of birth. + Year *int64 `form:"year"` +} + +// If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. +type PaymentMethodKlarnaParams struct { + // Customer's date of birth + DOB *PaymentMethodKlarnaDOBParams `form:"dob"` +} + +// If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. +type PaymentMethodKonbiniParams struct{} + +// If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. +type PaymentMethodKrCardParams struct{} + +// If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. +type PaymentMethodLinkParams struct{} + +// If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. +type PaymentMethodMobilepayParams struct{} + +// If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. +type PaymentMethodMultibancoParams struct{} + +// If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. +type PaymentMethodNaverPayParams struct { + // Whether to use Naver Pay points or a card to fund this transaction. If not provided, this defaults to `card`. + Funding *string `form:"funding"` +} + +// If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. +type PaymentMethodNzBankAccountParams struct { + // The name on the bank account. Only required if the account holder name is different from the name of the authorized signatory collected in the PaymentMethod's billing details. + AccountHolderName *string `form:"account_holder_name"` + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // The numeric code for the bank account's bank. + BankCode *string `form:"bank_code"` + // The numeric code for the bank account's bank branch. + BranchCode *string `form:"branch_code"` + Reference *string `form:"reference"` + // The suffix of the bank account number. + Suffix *string `form:"suffix"` +} + +// If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. +type PaymentMethodOXXOParams struct{} + +// If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. +type PaymentMethodP24Params struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. +type PaymentMethodPayByBankParams struct{} + +// If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. +type PaymentMethodPaycoParams struct{} + +// If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. +type PaymentMethodPayNowParams struct{} + +// If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. +type PaymentMethodPaypalParams struct{} + +// If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. +type PaymentMethodPixParams struct{} + +// If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. +type PaymentMethodPromptPayParams struct{} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type PaymentMethodRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. +type PaymentMethodRevolutPayParams struct{} + +// If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. +type PaymentMethodSamsungPayParams struct{} + +// If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. +type PaymentMethodSatispayParams struct{} + +// If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. +type PaymentMethodSEPADebitParams struct { + // IBAN of the bank account. + IBAN *string `form:"iban"` +} + +// If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. +type PaymentMethodSofortParams struct { + // Two-letter ISO code representing the country the bank account is located in. + Country *string `form:"country"` +} + +// If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. +type PaymentMethodSwishParams struct{} + +// If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. +type PaymentMethodTWINTParams struct{} + +// If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. +type PaymentMethodUSBankAccountParams struct { + // Account holder type: individual or company. + AccountHolderType *string `form:"account_holder_type"` + // Account number of the bank account. + AccountNumber *string `form:"account_number"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType *string `form:"account_type"` + // The ID of a Financial Connections Account to use as a payment method. + FinancialConnectionsAccount *string `form:"financial_connections_account"` + // Routing number of the bank account. + RoutingNumber *string `form:"routing_number"` +} + +// If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. +type PaymentMethodWeChatPayParams struct{} + +// If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. +type PaymentMethodZipParams struct{} + +// Creates a PaymentMethod object. Read the [Stripe.js reference](https://docs.stripe.com/docs/stripe-js/reference#stripe-create-payment-method) to learn how to create PaymentMethods via Stripe.js. +// +// Instead of creating a PaymentMethod directly, we recommend using the [PaymentIntents API to accept a payment immediately or the SetupIntent](https://docs.stripe.com/docs/payments/accept-a-payment) API to collect payment method details ahead of a future payment. +type PaymentMethodParams struct { + Params `form:"*"` + // If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + ACSSDebit *PaymentMethodACSSDebitParams `form:"acss_debit"` + // If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + Affirm *PaymentMethodAffirmParams `form:"affirm"` + // If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + AfterpayClearpay *PaymentMethodAfterpayClearpayParams `form:"afterpay_clearpay"` + // If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + Alipay *PaymentMethodAlipayParams `form:"alipay"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to `unspecified`. + AllowRedisplay *string `form:"allow_redisplay"` + // If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. + Alma *PaymentMethodAlmaParams `form:"alma"` + // If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. + AmazonPay *PaymentMethodAmazonPayParams `form:"amazon_pay"` + // If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + AUBECSDebit *PaymentMethodAUBECSDebitParams `form:"au_becs_debit"` + // If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + BACSDebit *PaymentMethodBACSDebitParams `form:"bacs_debit"` + // If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + Bancontact *PaymentMethodBancontactParams `form:"bancontact"` + // If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. + Billie *PaymentMethodBillieParams `form:"billie"` + // Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + BillingDetails *PaymentMethodBillingDetailsParams `form:"billing_details"` + // If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + BLIK *PaymentMethodBLIKParams `form:"blik"` + // If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + Boleto *PaymentMethodBoletoParams `form:"boleto"` + // If this is a `card` PaymentMethod, this hash contains the user's card details. For backwards compatibility, you can alternatively provide a Stripe token (e.g., for Apple Pay, Amex Express Checkout, or legacy Checkout) into the card hash with format `card: {token: "tok_visa"}`. When providing a card number, you must meet the requirements for [PCI compliance](https://stripe.com/docs/security#validating-pci-compliance). We strongly recommend using Stripe.js instead of interacting with this API directly. + Card *PaymentMethodCardParams `form:"card"` + // If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + CashApp *PaymentMethodCashAppParams `form:"cashapp"` + // If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. + Crypto *PaymentMethodCryptoParams `form:"crypto"` + // If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + CustomerBalance *PaymentMethodCustomerBalanceParams `form:"customer_balance"` + // If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + EPS *PaymentMethodEPSParams `form:"eps"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + FPX *PaymentMethodFPXParams `form:"fpx"` + // If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + Giropay *PaymentMethodGiropayParams `form:"giropay"` + // If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + Grabpay *PaymentMethodGrabpayParams `form:"grabpay"` + // If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + IDEAL *PaymentMethodIDEALParams `form:"ideal"` + // If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + InteracPresent *PaymentMethodInteracPresentParams `form:"interac_present"` + // If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. + KakaoPay *PaymentMethodKakaoPayParams `form:"kakao_pay"` + // If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + Klarna *PaymentMethodKlarnaParams `form:"klarna"` + // If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + Konbini *PaymentMethodKonbiniParams `form:"konbini"` + // If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. + KrCard *PaymentMethodKrCardParams `form:"kr_card"` + // If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + Link *PaymentMethodLinkParams `form:"link"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. + Mobilepay *PaymentMethodMobilepayParams `form:"mobilepay"` + // If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. + Multibanco *PaymentMethodMultibancoParams `form:"multibanco"` + // If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. + NaverPay *PaymentMethodNaverPayParams `form:"naver_pay"` + // If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. + NzBankAccount *PaymentMethodNzBankAccountParams `form:"nz_bank_account"` + // If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + OXXO *PaymentMethodOXXOParams `form:"oxxo"` + // If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + P24 *PaymentMethodP24Params `form:"p24"` + // If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. + PayByBank *PaymentMethodPayByBankParams `form:"pay_by_bank"` + // If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. + Payco *PaymentMethodPaycoParams `form:"payco"` + // If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + PayNow *PaymentMethodPayNowParams `form:"paynow"` + // If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + Paypal *PaymentMethodPaypalParams `form:"paypal"` + // If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + Pix *PaymentMethodPixParams `form:"pix"` + // If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + PromptPay *PaymentMethodPromptPayParams `form:"promptpay"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *PaymentMethodRadarOptionsParams `form:"radar_options"` + // If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + RevolutPay *PaymentMethodRevolutPayParams `form:"revolut_pay"` + // If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. + SamsungPay *PaymentMethodSamsungPayParams `form:"samsung_pay"` + // If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. + Satispay *PaymentMethodSatispayParams `form:"satispay"` + // If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + SEPADebit *PaymentMethodSEPADebitParams `form:"sepa_debit"` + // If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + Sofort *PaymentMethodSofortParams `form:"sofort"` + // If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. + Swish *PaymentMethodSwishParams `form:"swish"` + // If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. + TWINT *PaymentMethodTWINTParams `form:"twint"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type *string `form:"type"` + // If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + USBankAccount *PaymentMethodUSBankAccountParams `form:"us_bank_account"` + // If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + WeChatPay *PaymentMethodWeChatPayParams `form:"wechat_pay"` + // If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + Zip *PaymentMethodZipParams `form:"zip"` + // The following parameters are used when cloning a PaymentMethod to the connected account + // The `Customer` to whom the original PaymentMethod is attached. + Customer *string `form:"customer"` + // The PaymentMethod to share. + PaymentMethod *string `form:"payment_method"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentMethodParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Attaches a PaymentMethod object to a Customer. +// +// To attach a new PaymentMethod to a customer for future payments, we recommend you use a [SetupIntent](https://docs.stripe.com/docs/api/setup_intents) +// or a PaymentIntent with [setup_future_usage](https://docs.stripe.com/docs/api/payment_intents/create#create_payment_intent-setup_future_usage). +// These approaches will perform any necessary steps to set up the PaymentMethod for future payments. Using the /v1/payment_methods/:id/attach +// endpoint without first using a SetupIntent or PaymentIntent with setup_future_usage does not optimize the PaymentMethod for +// future use, which makes later declines and payment friction more likely. +// See [Optimizing cards for future payments](https://docs.stripe.com/docs/payments/payment-intents#future-usage) for more information about setting up +// future payments. +// +// To use this PaymentMethod as the default for invoice or subscription payments, +// set [invoice_settings.default_payment_method](https://docs.stripe.com/docs/api/customers/update#update_customer-invoice_settings-default_payment_method), +// on the Customer to the PaymentMethod's ID. +type PaymentMethodAttachParams struct { + Params `form:"*"` + // The ID of the customer to which to attach the PaymentMethod. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodAttachParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Detaches a PaymentMethod object from a Customer. After a PaymentMethod is detached, it can no longer be used for a payment or re-attached to a Customer. +type PaymentMethodDetachParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodDetachParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. +type PaymentMethodCreateACSSDebitParams struct { + // Customer's bank account number. + AccountNumber *string `form:"account_number"` + // Institution number of the customer's bank. + InstitutionNumber *string `form:"institution_number"` + // Transit number of the customer's bank. + TransitNumber *string `form:"transit_number"` +} + +// If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. +type PaymentMethodCreateAffirmParams struct{} + +// If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. +type PaymentMethodCreateAfterpayClearpayParams struct{} + +// If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. +type PaymentMethodCreateAlipayParams struct{} + +// If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. +type PaymentMethodCreateAlmaParams struct{} + +// If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. +type PaymentMethodCreateAmazonPayParams struct{} + +// If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. +type PaymentMethodCreateAUBECSDebitParams struct { + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // Bank-State-Branch number of the bank account. + BSBNumber *string `form:"bsb_number"` +} + +// If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. +type PaymentMethodCreateBACSDebitParams struct { + // Account number of the bank account that the funds will be debited from. + AccountNumber *string `form:"account_number"` + // Sort code of the bank account. (e.g., `10-20-30`) + SortCode *string `form:"sort_code"` +} + +// If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. +type PaymentMethodCreateBancontactParams struct{} + +// If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. +type PaymentMethodCreateBillieParams struct{} + +// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. +type PaymentMethodCreateBillingDetailsParams struct { + // Billing address. + Address *AddressParams `form:"address"` + // Email address. + Email *string `form:"email"` + // Full name. + Name *string `form:"name"` + // Billing phone number (including extension). + Phone *string `form:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID *string `form:"tax_id"` +} + +// If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. +type PaymentMethodCreateBLIKParams struct{} + +// If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. +type PaymentMethodCreateBoletoParams struct { + // The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + TaxID *string `form:"tax_id"` +} + +// Contains information about card networks used to process the payment. +type PaymentMethodCreateCardNetworksParams struct { + // The customer's preferred card network for co-branded cards. Supports `cartes_bancaires`, `mastercard`, or `visa`. Selection of a network that does not apply to the card will be stored as `invalid_preference` on the card. + Preferred *string `form:"preferred"` +} + +// If this is a `card` PaymentMethod, this hash contains the user's card details. For backwards compatibility, you can alternatively provide a Stripe token (e.g., for Apple Pay, Amex Express Checkout, or legacy Checkout) into the card hash with format `card: {token: "tok_visa"}`. When providing a card number, you must meet the requirements for [PCI compliance](https://stripe.com/docs/security#validating-pci-compliance). We strongly recommend using Stripe.js instead of interacting with this API directly. +type PaymentMethodCreateCardParams struct { + // The card's CVC. It is highly recommended to always include this value. + CVC *string `form:"cvc"` + // Two-digit number representing the card's expiration month. + ExpMonth *int64 `form:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear *int64 `form:"exp_year"` + // Contains information about card networks used to process the payment. + Networks *PaymentMethodCreateCardNetworksParams `form:"networks"` + // The card number, as a string without any separators. + Number *string `form:"number"` + // For backwards compatibility, you can alternatively provide a Stripe token (e.g., for Apple Pay, Amex Express Checkout, or legacy Checkout) into the card hash with format card: {token: "tok_visa"}. + Token *string `form:"token"` +} + +// If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. +type PaymentMethodCreateCashAppParams struct{} + +// If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. +type PaymentMethodCreateCryptoParams struct{} + +// If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. +type PaymentMethodCreateCustomerBalanceParams struct{} + +// If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. +type PaymentMethodCreateEPSParams struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. +type PaymentMethodCreateFPXParams struct { + // Account holder type for FPX transaction + AccountHolderType *string `form:"account_holder_type"` + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. +type PaymentMethodCreateGiropayParams struct{} + +// If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. +type PaymentMethodCreateGrabpayParams struct{} + +// If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. +type PaymentMethodCreateIDEALParams struct { + // The customer's bank. Only use this parameter for existing customers. Don't use it for new customers. + Bank *string `form:"bank"` +} + +// If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. +type PaymentMethodCreateInteracPresentParams struct{} + +// If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. +type PaymentMethodCreateKakaoPayParams struct{} + +// Customer's date of birth +type PaymentMethodCreateKlarnaDOBParams struct { + // The day of birth, between 1 and 31. + Day *int64 `form:"day"` + // The month of birth, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of birth. + Year *int64 `form:"year"` +} + +// If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. +type PaymentMethodCreateKlarnaParams struct { + // Customer's date of birth + DOB *PaymentMethodCreateKlarnaDOBParams `form:"dob"` +} + +// If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. +type PaymentMethodCreateKonbiniParams struct{} + +// If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. +type PaymentMethodCreateKrCardParams struct{} + +// If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. +type PaymentMethodCreateLinkParams struct{} + +// If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. +type PaymentMethodCreateMobilepayParams struct{} + +// If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. +type PaymentMethodCreateMultibancoParams struct{} + +// If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. +type PaymentMethodCreateNaverPayParams struct { + // Whether to use Naver Pay points or a card to fund this transaction. If not provided, this defaults to `card`. + Funding *string `form:"funding"` +} + +// If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. +type PaymentMethodCreateNzBankAccountParams struct { + // The name on the bank account. Only required if the account holder name is different from the name of the authorized signatory collected in the PaymentMethod's billing details. + AccountHolderName *string `form:"account_holder_name"` + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // The numeric code for the bank account's bank. + BankCode *string `form:"bank_code"` + // The numeric code for the bank account's bank branch. + BranchCode *string `form:"branch_code"` + Reference *string `form:"reference"` + // The suffix of the bank account number. + Suffix *string `form:"suffix"` +} + +// If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. +type PaymentMethodCreateOXXOParams struct{} + +// If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. +type PaymentMethodCreateP24Params struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. +type PaymentMethodCreatePayByBankParams struct{} + +// If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. +type PaymentMethodCreatePaycoParams struct{} + +// If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. +type PaymentMethodCreatePayNowParams struct{} + +// If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. +type PaymentMethodCreatePaypalParams struct{} + +// If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. +type PaymentMethodCreatePixParams struct{} + +// If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. +type PaymentMethodCreatePromptPayParams struct{} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type PaymentMethodCreateRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. +type PaymentMethodCreateRevolutPayParams struct{} + +// If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. +type PaymentMethodCreateSamsungPayParams struct{} + +// If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. +type PaymentMethodCreateSatispayParams struct{} + +// If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. +type PaymentMethodCreateSEPADebitParams struct { + // IBAN of the bank account. + IBAN *string `form:"iban"` +} + +// If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. +type PaymentMethodCreateSofortParams struct { + // Two-letter ISO code representing the country the bank account is located in. + Country *string `form:"country"` +} + +// If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. +type PaymentMethodCreateSwishParams struct{} + +// If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. +type PaymentMethodCreateTWINTParams struct{} + +// If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. +type PaymentMethodCreateUSBankAccountParams struct { + // Account holder type: individual or company. + AccountHolderType *string `form:"account_holder_type"` + // Account number of the bank account. + AccountNumber *string `form:"account_number"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType *string `form:"account_type"` + // The ID of a Financial Connections Account to use as a payment method. + FinancialConnectionsAccount *string `form:"financial_connections_account"` + // Routing number of the bank account. + RoutingNumber *string `form:"routing_number"` +} + +// If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. +type PaymentMethodCreateWeChatPayParams struct{} + +// If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. +type PaymentMethodCreateZipParams struct{} + +// Creates a PaymentMethod object. Read the [Stripe.js reference](https://docs.stripe.com/docs/stripe-js/reference#stripe-create-payment-method) to learn how to create PaymentMethods via Stripe.js. +// +// Instead of creating a PaymentMethod directly, we recommend using the [PaymentIntents API to accept a payment immediately or the SetupIntent](https://docs.stripe.com/docs/payments/accept-a-payment) API to collect payment method details ahead of a future payment. +type PaymentMethodCreateParams struct { + Params `form:"*"` + // If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + ACSSDebit *PaymentMethodCreateACSSDebitParams `form:"acss_debit"` + // If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + Affirm *PaymentMethodCreateAffirmParams `form:"affirm"` + // If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + AfterpayClearpay *PaymentMethodCreateAfterpayClearpayParams `form:"afterpay_clearpay"` + // If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + Alipay *PaymentMethodCreateAlipayParams `form:"alipay"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to `unspecified`. + AllowRedisplay *string `form:"allow_redisplay"` + // If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. + Alma *PaymentMethodCreateAlmaParams `form:"alma"` + // If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. + AmazonPay *PaymentMethodCreateAmazonPayParams `form:"amazon_pay"` + // If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + AUBECSDebit *PaymentMethodCreateAUBECSDebitParams `form:"au_becs_debit"` + // If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + BACSDebit *PaymentMethodCreateBACSDebitParams `form:"bacs_debit"` + // If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + Bancontact *PaymentMethodCreateBancontactParams `form:"bancontact"` + // If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. + Billie *PaymentMethodCreateBillieParams `form:"billie"` + // Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + BillingDetails *PaymentMethodCreateBillingDetailsParams `form:"billing_details"` + // If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + BLIK *PaymentMethodCreateBLIKParams `form:"blik"` + // If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + Boleto *PaymentMethodCreateBoletoParams `form:"boleto"` + // If this is a `card` PaymentMethod, this hash contains the user's card details. For backwards compatibility, you can alternatively provide a Stripe token (e.g., for Apple Pay, Amex Express Checkout, or legacy Checkout) into the card hash with format `card: {token: "tok_visa"}`. When providing a card number, you must meet the requirements for [PCI compliance](https://stripe.com/docs/security#validating-pci-compliance). We strongly recommend using Stripe.js instead of interacting with this API directly. + Card *PaymentMethodCreateCardParams `form:"card"` + // If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + CashApp *PaymentMethodCreateCashAppParams `form:"cashapp"` + // If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. + Crypto *PaymentMethodCreateCryptoParams `form:"crypto"` + // The `Customer` to whom the original PaymentMethod is attached. + Customer *string `form:"customer"` + // If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + CustomerBalance *PaymentMethodCreateCustomerBalanceParams `form:"customer_balance"` + // If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + EPS *PaymentMethodCreateEPSParams `form:"eps"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + FPX *PaymentMethodCreateFPXParams `form:"fpx"` + // If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + Giropay *PaymentMethodCreateGiropayParams `form:"giropay"` + // If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + Grabpay *PaymentMethodCreateGrabpayParams `form:"grabpay"` + // If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + IDEAL *PaymentMethodCreateIDEALParams `form:"ideal"` + // If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + InteracPresent *PaymentMethodCreateInteracPresentParams `form:"interac_present"` + // If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. + KakaoPay *PaymentMethodCreateKakaoPayParams `form:"kakao_pay"` + // If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + Klarna *PaymentMethodCreateKlarnaParams `form:"klarna"` + // If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + Konbini *PaymentMethodCreateKonbiniParams `form:"konbini"` + // If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. + KrCard *PaymentMethodCreateKrCardParams `form:"kr_card"` + // If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + Link *PaymentMethodCreateLinkParams `form:"link"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. + Mobilepay *PaymentMethodCreateMobilepayParams `form:"mobilepay"` + // If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. + Multibanco *PaymentMethodCreateMultibancoParams `form:"multibanco"` + // If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. + NaverPay *PaymentMethodCreateNaverPayParams `form:"naver_pay"` + // If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. + NzBankAccount *PaymentMethodCreateNzBankAccountParams `form:"nz_bank_account"` + // If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + OXXO *PaymentMethodCreateOXXOParams `form:"oxxo"` + // If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + P24 *PaymentMethodCreateP24Params `form:"p24"` + // If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. + PayByBank *PaymentMethodCreatePayByBankParams `form:"pay_by_bank"` + // If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. + Payco *PaymentMethodCreatePaycoParams `form:"payco"` + // The PaymentMethod to share. + PaymentMethod *string `form:"payment_method"` + // If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + PayNow *PaymentMethodCreatePayNowParams `form:"paynow"` + // If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + Paypal *PaymentMethodCreatePaypalParams `form:"paypal"` + // If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + Pix *PaymentMethodCreatePixParams `form:"pix"` + // If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + PromptPay *PaymentMethodCreatePromptPayParams `form:"promptpay"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *PaymentMethodCreateRadarOptionsParams `form:"radar_options"` + // If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + RevolutPay *PaymentMethodCreateRevolutPayParams `form:"revolut_pay"` + // If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. + SamsungPay *PaymentMethodCreateSamsungPayParams `form:"samsung_pay"` + // If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. + Satispay *PaymentMethodCreateSatispayParams `form:"satispay"` + // If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + SEPADebit *PaymentMethodCreateSEPADebitParams `form:"sepa_debit"` + // If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + Sofort *PaymentMethodCreateSofortParams `form:"sofort"` + // If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. + Swish *PaymentMethodCreateSwishParams `form:"swish"` + // If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. + TWINT *PaymentMethodCreateTWINTParams `form:"twint"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type *string `form:"type"` + // If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + USBankAccount *PaymentMethodCreateUSBankAccountParams `form:"us_bank_account"` + // If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + WeChatPay *PaymentMethodCreateWeChatPayParams `form:"wechat_pay"` + // If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + Zip *PaymentMethodCreateZipParams `form:"zip"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentMethodCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves a PaymentMethod object attached to the StripeAccount. To retrieve a payment method attached to a Customer, you should use [Retrieve a Customer's PaymentMethods](https://docs.stripe.com/docs/api/payment_methods/customer) +type PaymentMethodRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. +type PaymentMethodUpdateBillingDetailsParams struct { + // Billing address. + Address *AddressParams `form:"address"` + // Email address. + Email *string `form:"email"` + // Full name. + Name *string `form:"name"` + // Billing phone number (including extension). + Phone *string `form:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID *string `form:"tax_id"` +} + +// Contains information about card networks used to process the payment. +type PaymentMethodUpdateCardNetworksParams struct { + // The customer's preferred card network for co-branded cards. Supports `cartes_bancaires`, `mastercard`, or `visa`. Selection of a network that does not apply to the card will be stored as `invalid_preference` on the card. + Preferred *string `form:"preferred"` +} + +// If this is a `card` PaymentMethod, this hash contains the user's card details. +type PaymentMethodUpdateCardParams struct { + // Two-digit number representing the card's expiration month. + ExpMonth *int64 `form:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear *int64 `form:"exp_year"` + // Contains information about card networks used to process the payment. + Networks *PaymentMethodUpdateCardNetworksParams `form:"networks"` +} + +// If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. +type PaymentMethodUpdateLinkParams struct{} + +// If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. +type PaymentMethodUpdatePayByBankParams struct{} + +// If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. +type PaymentMethodUpdateUSBankAccountParams struct { + // Bank account holder type. + AccountHolderType *string `form:"account_holder_type"` + // Bank account type. + AccountType *string `form:"account_type"` +} + +// Updates a PaymentMethod object. A PaymentMethod must be attached a customer to be updated. +type PaymentMethodUpdateParams struct { + Params `form:"*"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to `unspecified`. + AllowRedisplay *string `form:"allow_redisplay"` + // Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + BillingDetails *PaymentMethodUpdateBillingDetailsParams `form:"billing_details"` + // If this is a `card` PaymentMethod, this hash contains the user's card details. + Card *PaymentMethodUpdateCardParams `form:"card"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + Link *PaymentMethodUpdateLinkParams `form:"link"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. + PayByBank *PaymentMethodUpdatePayByBankParams `form:"pay_by_bank"` + // If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + USBankAccount *PaymentMethodUpdateUSBankAccountParams `form:"us_bank_account"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentMethodUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +type PaymentMethodACSSDebit struct { + // Name of the bank associated with the bank account. + BankName string `json:"bank_name"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Institution number of the bank account. + InstitutionNumber string `json:"institution_number"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // Transit number of the bank account. + TransitNumber string `json:"transit_number"` +} +type PaymentMethodAffirm struct{} +type PaymentMethodAfterpayClearpay struct{} +type PaymentMethodAlipay struct{} +type PaymentMethodAlma struct{} +type PaymentMethodAmazonPay struct{} +type PaymentMethodAUBECSDebit struct { + // Six-digit number identifying bank and branch associated with this bank account. + BSBNumber string `json:"bsb_number"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` +} +type PaymentMethodBACSDebit struct { + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // Sort code of the bank account. (e.g., `10-20-30`) + SortCode string `json:"sort_code"` +} +type PaymentMethodBancontact struct{} +type PaymentMethodBillie struct{} +type PaymentMethodBillingDetails struct { + // Billing address. + Address *Address `json:"address"` + // Email address. + Email string `json:"email"` + // Full name. + Name string `json:"name"` + // Billing phone number (including extension). + Phone string `json:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID string `json:"tax_id"` +} +type PaymentMethodBLIK struct{} +type PaymentMethodBoleto struct { + // Uniquely identifies the customer tax id (CNPJ or CPF) + TaxID string `json:"tax_id"` +} + +// Checks on Card address and CVC if provided. +type PaymentMethodCardChecks struct { + // If a address line1 was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + AddressLine1Check PaymentMethodCardChecksAddressLine1Check `json:"address_line1_check"` + // If a address postal code was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + AddressPostalCodeCheck PaymentMethodCardChecksAddressPostalCodeCheck `json:"address_postal_code_check"` + // If a CVC was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + CVCCheck PaymentMethodCardChecksCVCCheck `json:"cvc_check"` +} + +// Details about payments collected offline. +type PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentOffline struct { + // Time at which the payment was collected while offline + StoredAt int64 `json:"stored_at"` + // The method used to process this payment method offline. Only deferred is allowed. + Type PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentOfflineType `json:"type"` +} + +// A collection of fields required to be displayed on receipts. Only required for EMV transactions. +type PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReceipt struct { + // The type of account being debited or credited + AccountType PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReceiptAccountType `json:"account_type"` + // The Application Cryptogram, a unique value generated by the card to authenticate the transaction with issuers. + ApplicationCryptogram string `json:"application_cryptogram"` + // The Application Identifier (AID) on the card used to determine which networks are eligible to process the transaction. Referenced from EMV tag 9F12, data encoded on the card's chip. + ApplicationPreferredName string `json:"application_preferred_name"` + // Identifier for this transaction. + AuthorizationCode string `json:"authorization_code"` + // EMV tag 8A. A code returned by the card issuer. + AuthorizationResponseCode string `json:"authorization_response_code"` + // Describes the method used by the cardholder to verify ownership of the card. One of the following: `approval`, `failure`, `none`, `offline_pin`, `offline_pin_and_signature`, `online_pin`, or `signature`. + CardholderVerificationMethod string `json:"cardholder_verification_method"` + // Similar to the application_preferred_name, identifying the applications (AIDs) available on the card. Referenced from EMV tag 84. + DedicatedFileName string `json:"dedicated_file_name"` + // A 5-byte string that records the checks and validations that occur between the card and the terminal. These checks determine how the terminal processes the transaction and what risk tolerance is acceptable. Referenced from EMV Tag 95. + TerminalVerificationResults string `json:"terminal_verification_results"` + // An indication of which steps were completed during the card read process. Referenced from EMV Tag 9B. + TransactionStatusInformation string `json:"transaction_status_information"` +} +type PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentWallet struct { + // The type of mobile wallet, one of `apple_pay`, `google_pay`, `samsung_pay`, or `unknown`. + Type PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentWalletType `json:"type"` +} +type PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresent struct { + // The authorized amount + AmountAuthorized int64 `json:"amount_authorized"` + // Card brand. Can be `amex`, `diners`, `discover`, `eftpos_au`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Brand string `json:"brand"` + // The [product code](https://stripe.com/docs/card-product-codes) that identifies the specific program or product associated with a card. + BrandProduct string `json:"brand_product"` + // When using manual capture, a future timestamp after which the charge will be automatically refunded if uncaptured. + CaptureBefore int64 `json:"capture_before"` + // The cardholder name as read from the card, in [ISO 7813](https://en.wikipedia.org/wiki/ISO/IEC_7813) format. May include alphanumeric characters, special characters and first/last name separator (`/`). In some cases, the cardholder name may not be available depending on how the issuer has configured the card. Cardholder name is typically not available on swipe or contactless payments, such as those made with Apple Pay and Google Pay. + CardholderName string `json:"cardholder_name"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // A high-level description of the type of cards issued in this range. (For internal use only and not typically available in standard API requests.) + Description string `json:"description"` + // Authorization response cryptogram. + EmvAuthData string `json:"emv_auth_data"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + // Uniquely identifies this particular card number. You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + // + // *As of May 1, 2021, card fingerprint in India for Connect changed to allow two fingerprints for the same card---one for India and one for the rest of the world.* + Fingerprint string `json:"fingerprint"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding string `json:"funding"` + // ID of a card PaymentMethod generated from the card_present PaymentMethod that may be attached to a Customer for future transactions. Only present if it was possible to generate a card PaymentMethod. + GeneratedCard string `json:"generated_card"` + // Issuer identification number of the card. (For internal use only and not typically available in standard API requests.) + IIN string `json:"iin"` + // Whether this [PaymentIntent](https://stripe.com/docs/api/payment_intents) is eligible for incremental authorizations. Request support using [request_incremental_authorization_support](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-payment_method_options-card_present-request_incremental_authorization_support). + IncrementalAuthorizationSupported bool `json:"incremental_authorization_supported"` + // The name of the card's issuing bank. (For internal use only and not typically available in standard API requests.) + Issuer string `json:"issuer"` + // The last four digits of the card. + Last4 string `json:"last4"` + // Identifies which network this charge was processed on. Can be `amex`, `cartes_bancaires`, `diners`, `discover`, `eftpos_au`, `interac`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Network string `json:"network"` + // This is used by the financial networks to identify a transaction. Visa calls this the Transaction ID, Mastercard calls this the Trace ID, and American Express calls this the Acquirer Reference Data. This value will be present if it is returned by the financial network in the authorization response, and null otherwise. + NetworkTransactionID string `json:"network_transaction_id"` + // Details about payments collected offline. + Offline *PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentOffline `json:"offline"` + // Defines whether the authorized amount can be over-captured or not + OvercaptureSupported bool `json:"overcapture_supported"` + // The languages that the issuing bank recommends using for localizing any customer-facing text, as read from the card. Referenced from EMV tag 5F2D, data encoded on the card's chip. + PreferredLocales []string `json:"preferred_locales"` + // How card details were read in this transaction. + ReadMethod PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReadMethod `json:"read_method"` + // A collection of fields required to be displayed on receipts. Only required for EMV transactions. + Receipt *PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentReceipt `json:"receipt"` + Wallet *PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresentWallet `json:"wallet"` +} + +// Transaction-specific details of the payment method used in the payment. +type PaymentMethodCardGeneratedFromPaymentMethodDetails struct { + CardPresent *PaymentMethodCardGeneratedFromPaymentMethodDetailsCardPresent `json:"card_present"` + // The type of payment method transaction-specific details from the transaction that generated this `card` payment method. Always `card_present`. + Type string `json:"type"` +} + +// Details of the original PaymentMethod that created this object. +type PaymentMethodCardGeneratedFrom struct { + // The charge that created this object. + Charge string `json:"charge"` + // Transaction-specific details of the payment method used in the payment. + PaymentMethodDetails *PaymentMethodCardGeneratedFromPaymentMethodDetails `json:"payment_method_details"` + // The ID of the SetupAttempt that generated this PaymentMethod, if any. + SetupAttempt *SetupAttempt `json:"setup_attempt"` +} + +// Contains information about card networks that can be used to process the payment. +type PaymentMethodCardNetworks struct { + // All networks available for selection via [payment_method_options.card.network](https://docs.stripe.com/api/payment_intents/confirm#confirm_payment_intent-payment_method_options-card-network). + Available []PaymentMethodCardNetworksAvailable `json:"available"` + // The preferred network for co-branded cards. Can be `cartes_bancaires`, `mastercard`, `visa` or `invalid_preference` if requested network is not valid for the card. + Preferred PaymentMethodCardNetworksPreferred `json:"preferred"` +} + +// Contains details on how this Card may be used for 3D Secure authentication. +type PaymentMethodCardThreeDSecureUsage struct { + // Whether 3D Secure is supported on this card. + Supported bool `json:"supported"` +} +type PaymentMethodCardWalletAmexExpressCheckout struct{} +type PaymentMethodCardWalletApplePay struct{} +type PaymentMethodCardWalletGooglePay struct{} +type PaymentMethodCardWalletLink struct{} +type PaymentMethodCardWalletMasterpass struct { + // Owner's verified billing address. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + BillingAddress *Address `json:"billing_address"` + // Owner's verified email. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Email string `json:"email"` + // Owner's verified full name. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Name string `json:"name"` + // Owner's verified shipping address. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + ShippingAddress *Address `json:"shipping_address"` +} +type PaymentMethodCardWalletSamsungPay struct{} +type PaymentMethodCardWalletVisaCheckout struct { + // Owner's verified billing address. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + BillingAddress *Address `json:"billing_address"` + // Owner's verified email. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Email string `json:"email"` + // Owner's verified full name. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Name string `json:"name"` + // Owner's verified shipping address. Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + ShippingAddress *Address `json:"shipping_address"` +} + +// If this Card is part of a card wallet, this contains the details of the card wallet. +type PaymentMethodCardWallet struct { + AmexExpressCheckout *PaymentMethodCardWalletAmexExpressCheckout `json:"amex_express_checkout"` + ApplePay *PaymentMethodCardWalletApplePay `json:"apple_pay"` + // (For tokenized numbers only.) The last four digits of the device account number. + DynamicLast4 string `json:"dynamic_last4"` + GooglePay *PaymentMethodCardWalletGooglePay `json:"google_pay"` + Link *PaymentMethodCardWalletLink `json:"link"` + Masterpass *PaymentMethodCardWalletMasterpass `json:"masterpass"` + SamsungPay *PaymentMethodCardWalletSamsungPay `json:"samsung_pay"` + // The type of the card wallet, one of `amex_express_checkout`, `apple_pay`, `google_pay`, `masterpass`, `samsung_pay`, `visa_checkout`, or `link`. An additional hash is included on the Wallet subhash with a name matching this value. It contains additional information specific to the card wallet type. + Type PaymentMethodCardWalletType `json:"type"` + VisaCheckout *PaymentMethodCardWalletVisaCheckout `json:"visa_checkout"` +} +type PaymentMethodCard struct { + // Card brand. Can be `amex`, `diners`, `discover`, `eftpos_au`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Brand PaymentMethodCardBrand `json:"brand"` + // Checks on Card address and CVC if provided. + Checks *PaymentMethodCardChecks `json:"checks"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // The brand to use when displaying the card, this accounts for customer's brand choice on dual-branded cards. Can be `american_express`, `cartes_bancaires`, `diners_club`, `discover`, `eftpos_australia`, `interac`, `jcb`, `mastercard`, `union_pay`, `visa`, or `other` and may contain more values in the future. + DisplayBrand string `json:"display_brand"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + // Uniquely identifies this particular card number. You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + // + // *As of May 1, 2021, card fingerprint in India for Connect changed to allow two fingerprints for the same card---one for India and one for the rest of the world.* + Fingerprint string `json:"fingerprint"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding CardFunding `json:"funding"` + // Details of the original PaymentMethod that created this object. + GeneratedFrom *PaymentMethodCardGeneratedFrom `json:"generated_from"` + // The last four digits of the card. + Last4 string `json:"last4"` + // Contains information about card networks that can be used to process the payment. + Networks *PaymentMethodCardNetworks `json:"networks"` + // Status of a card based on the card issuer. + RegulatedStatus PaymentMethodCardRegulatedStatus `json:"regulated_status"` + // Contains details on how this Card may be used for 3D Secure authentication. + ThreeDSecureUsage *PaymentMethodCardThreeDSecureUsage `json:"three_d_secure_usage"` + // If this Card is part of a card wallet, this contains the details of the card wallet. + Wallet *PaymentMethodCardWallet `json:"wallet"` + // Please note that the fields below are for internal use only and are not returned + // as part of standard API requests. + // A high-level description of the type of cards issued in this range. (For internal use only and not typically available in standard API requests.) + Description string `json:"description"` + // Issuer identification number of the card. (For internal use only and not typically available in standard API requests.) + IIN string `json:"iin"` + // The name of the card's issuing bank. (For internal use only and not typically available in standard API requests.) + Issuer string `json:"issuer"` +} + +// Contains information about card networks that can be used to process the payment. +type PaymentMethodCardPresentNetworks struct { + // All networks available for selection via [payment_method_options.card.network](https://docs.stripe.com/api/payment_intents/confirm#confirm_payment_intent-payment_method_options-card-network). + Available []string `json:"available"` + // The preferred network for the card. + Preferred string `json:"preferred"` +} + +// Details about payment methods collected offline. +type PaymentMethodCardPresentOffline struct { + // Time at which the payment was collected while offline + StoredAt int64 `json:"stored_at"` + // The method used to process this payment method offline. Only deferred is allowed. + Type PaymentMethodCardPresentOfflineType `json:"type"` +} +type PaymentMethodCardPresentWallet struct { + // The type of mobile wallet, one of `apple_pay`, `google_pay`, `samsung_pay`, or `unknown`. + Type PaymentMethodCardPresentWalletType `json:"type"` +} +type PaymentMethodCardPresent struct { + // Card brand. Can be `amex`, `diners`, `discover`, `eftpos_au`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Brand string `json:"brand"` + // The [product code](https://stripe.com/docs/card-product-codes) that identifies the specific program or product associated with a card. + BrandProduct string `json:"brand_product"` + // The cardholder name as read from the card, in [ISO 7813](https://en.wikipedia.org/wiki/ISO/IEC_7813) format. May include alphanumeric characters, special characters and first/last name separator (`/`). In some cases, the cardholder name may not be available depending on how the issuer has configured the card. Cardholder name is typically not available on swipe or contactless payments, such as those made with Apple Pay and Google Pay. + CardholderName string `json:"cardholder_name"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // A high-level description of the type of cards issued in this range. (For internal use only and not typically available in standard API requests.) + Description string `json:"description"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + // Uniquely identifies this particular card number. You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + // + // *As of May 1, 2021, card fingerprint in India for Connect changed to allow two fingerprints for the same card---one for India and one for the rest of the world.* + Fingerprint string `json:"fingerprint"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding string `json:"funding"` + // Issuer identification number of the card. (For internal use only and not typically available in standard API requests.) + IIN string `json:"iin"` + // The name of the card's issuing bank. (For internal use only and not typically available in standard API requests.) + Issuer string `json:"issuer"` + // The last four digits of the card. + Last4 string `json:"last4"` + // Contains information about card networks that can be used to process the payment. + Networks *PaymentMethodCardPresentNetworks `json:"networks"` + // Details about payment methods collected offline. + Offline *PaymentMethodCardPresentOffline `json:"offline"` + // The languages that the issuing bank recommends using for localizing any customer-facing text, as read from the card. Referenced from EMV tag 5F2D, data encoded on the card's chip. + PreferredLocales []string `json:"preferred_locales"` + // How card details were read in this transaction. + ReadMethod PaymentMethodCardPresentReadMethod `json:"read_method"` + Wallet *PaymentMethodCardPresentWallet `json:"wallet"` +} +type PaymentMethodCashApp struct { + // A unique and immutable identifier assigned by Cash App to every buyer. + BuyerID string `json:"buyer_id"` + // A public identifier for buyers using Cash App. + Cashtag string `json:"cashtag"` +} +type PaymentMethodCrypto struct{} +type PaymentMethodCustomerBalance struct{} +type PaymentMethodEPS struct { + // The customer's bank. Should be one of `arzte_und_apotheker_bank`, `austrian_anadi_bank_ag`, `bank_austria`, `bankhaus_carl_spangler`, `bankhaus_schelhammer_und_schattera_ag`, `bawag_psk_ag`, `bks_bank_ag`, `brull_kallmus_bank_ag`, `btv_vier_lander_bank`, `capital_bank_grawe_gruppe_ag`, `deutsche_bank_ag`, `dolomitenbank`, `easybank_ag`, `erste_bank_und_sparkassen`, `hypo_alpeadriabank_international_ag`, `hypo_noe_lb_fur_niederosterreich_u_wien`, `hypo_oberosterreich_salzburg_steiermark`, `hypo_tirol_bank_ag`, `hypo_vorarlberg_bank_ag`, `hypo_bank_burgenland_aktiengesellschaft`, `marchfelder_bank`, `oberbank_ag`, `raiffeisen_bankengruppe_osterreich`, `schoellerbank_ag`, `sparda_bank_wien`, `volksbank_gruppe`, `volkskreditbank_ag`, or `vr_bank_braunau`. + Bank string `json:"bank"` +} +type PaymentMethodFPX struct { + // Account holder type, if provided. Can be one of `individual` or `company`. + AccountHolderType PaymentMethodFPXAccountHolderType `json:"account_holder_type"` + // The customer's bank, if provided. Can be one of `affin_bank`, `agrobank`, `alliance_bank`, `ambank`, `bank_islam`, `bank_muamalat`, `bank_rakyat`, `bsn`, `cimb`, `hong_leong_bank`, `hsbc`, `kfh`, `maybank2u`, `ocbc`, `public_bank`, `rhb`, `standard_chartered`, `uob`, `deutsche_bank`, `maybank2e`, `pb_enterprise`, or `bank_of_china`. + Bank string `json:"bank"` +} +type PaymentMethodGiropay struct{} +type PaymentMethodGrabpay struct{} +type PaymentMethodIDEAL struct { + // The customer's bank, if provided. Can be one of `abn_amro`, `asn_bank`, `bunq`, `buut`, `handelsbanken`, `ing`, `knab`, `moneyou`, `n26`, `nn`, `rabobank`, `regiobank`, `revolut`, `sns_bank`, `triodos_bank`, `van_lanschot`, or `yoursafe`. + Bank string `json:"bank"` + // The Bank Identifier Code of the customer's bank, if the bank was provided. + BIC string `json:"bic"` +} + +// Contains information about card networks that can be used to process the payment. +type PaymentMethodInteracPresentNetworks struct { + // All networks available for selection via [payment_method_options.card.network](https://docs.stripe.com/api/payment_intents/confirm#confirm_payment_intent-payment_method_options-card-network). + Available []string `json:"available"` + // The preferred network for the card. + Preferred string `json:"preferred"` +} +type PaymentMethodInteracPresent struct { + // Card brand. Can be `interac`, `mastercard` or `visa`. + Brand string `json:"brand"` + // The cardholder name as read from the card, in [ISO 7813](https://en.wikipedia.org/wiki/ISO/IEC_7813) format. May include alphanumeric characters, special characters and first/last name separator (`/`). In some cases, the cardholder name may not be available depending on how the issuer has configured the card. Cardholder name is typically not available on swipe or contactless payments, such as those made with Apple Pay and Google Pay. + CardholderName string `json:"cardholder_name"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // A high-level description of the type of cards issued in this range. (For internal use only and not typically available in standard API requests.) + Description string `json:"description"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + // Uniquely identifies this particular card number. You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + // + // *As of May 1, 2021, card fingerprint in India for Connect changed to allow two fingerprints for the same card---one for India and one for the rest of the world.* + Fingerprint string `json:"fingerprint"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding string `json:"funding"` + // Issuer identification number of the card. (For internal use only and not typically available in standard API requests.) + IIN string `json:"iin"` + // The name of the card's issuing bank. (For internal use only and not typically available in standard API requests.) + Issuer string `json:"issuer"` + // The last four digits of the card. + Last4 string `json:"last4"` + // Contains information about card networks that can be used to process the payment. + Networks *PaymentMethodInteracPresentNetworks `json:"networks"` + // The languages that the issuing bank recommends using for localizing any customer-facing text, as read from the card. Referenced from EMV tag 5F2D, data encoded on the card's chip. + PreferredLocales []string `json:"preferred_locales"` + // How card details were read in this transaction. + ReadMethod PaymentMethodInteracPresentReadMethod `json:"read_method"` +} +type PaymentMethodKakaoPay struct{} + +// The customer's date of birth, if provided. +type PaymentMethodKlarnaDOB struct { + // The day of birth, between 1 and 31. + Day int64 `json:"day"` + // The month of birth, between 1 and 12. + Month int64 `json:"month"` + // The four-digit year of birth. + Year int64 `json:"year"` +} +type PaymentMethodKlarna struct { + // The customer's date of birth, if provided. + DOB *PaymentMethodKlarnaDOB `json:"dob"` +} +type PaymentMethodKonbini struct{} +type PaymentMethodKrCard struct { + // The local credit or debit card brand. + Brand PaymentMethodKrCardBrand `json:"brand"` + // The last four digits of the card. This may not be present for American Express cards. + Last4 string `json:"last4"` +} +type PaymentMethodLink struct { + // Account owner's email address. + Email string `json:"email"` + // [Deprecated] This is a legacy parameter that no longer has any function. + // Deprecated: + PersistentToken string `json:"persistent_token"` +} +type PaymentMethodMobilepay struct{} +type PaymentMethodMultibanco struct{} +type PaymentMethodNaverPay struct { + // Uniquely identifies this particular Naver Pay account. You can use this attribute to check whether two Naver Pay accounts are the same. + BuyerID string `json:"buyer_id"` + // Whether to fund this transaction with Naver Pay points or a card. + Funding PaymentMethodNaverPayFunding `json:"funding"` +} +type PaymentMethodNzBankAccount struct { + // The name on the bank account. Only present if the account holder name is different from the name of the authorized signatory collected in the PaymentMethod's billing details. + AccountHolderName string `json:"account_holder_name"` + // The numeric code for the bank account's bank. + BankCode string `json:"bank_code"` + // The name of the bank. + BankName string `json:"bank_name"` + // The numeric code for the bank account's bank branch. + BranchCode string `json:"branch_code"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // The suffix of the bank account number. + Suffix string `json:"suffix"` +} +type PaymentMethodOXXO struct{} +type PaymentMethodP24 struct { + // The customer's bank, if provided. + Bank string `json:"bank"` +} +type PaymentMethodPayByBank struct{} +type PaymentMethodPayco struct{} +type PaymentMethodPayNow struct{} +type PaymentMethodPaypal struct { + // Two-letter ISO code representing the buyer's country. Values are provided by PayPal directly (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Country string `json:"country"` + // Owner's email. Values are provided by PayPal directly + // (if supported) at the time of authorization or settlement. They cannot be set or mutated. + PayerEmail string `json:"payer_email"` + // PayPal account PayerID. This identifier uniquely identifies the PayPal customer. + PayerID string `json:"payer_id"` +} +type PaymentMethodPix struct{} +type PaymentMethodPromptPay struct{} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type PaymentMethodRadarOptions struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session string `json:"session"` +} +type PaymentMethodRevolutPay struct{} +type PaymentMethodSamsungPay struct{} +type PaymentMethodSatispay struct{} + +// Information about the object that generated this PaymentMethod. +type PaymentMethodSEPADebitGeneratedFrom struct { + // The ID of the Charge that generated this PaymentMethod, if any. + Charge *Charge `json:"charge"` + // The ID of the SetupAttempt that generated this PaymentMethod, if any. + SetupAttempt *SetupAttempt `json:"setup_attempt"` +} +type PaymentMethodSEPADebit struct { + // Bank code of bank associated with the bank account. + BankCode string `json:"bank_code"` + // Branch code of bank associated with the bank account. + BranchCode string `json:"branch_code"` + // Two-letter ISO code representing the country the bank account is located in. + Country string `json:"country"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Information about the object that generated this PaymentMethod. + GeneratedFrom *PaymentMethodSEPADebitGeneratedFrom `json:"generated_from"` + // Last four characters of the IBAN. + Last4 string `json:"last4"` +} +type PaymentMethodSofort struct { + // Two-letter ISO code representing the country the bank account is located in. + Country string `json:"country"` +} +type PaymentMethodSwish struct{} +type PaymentMethodTWINT struct{} + +// Contains information about US bank account networks that can be used. +type PaymentMethodUSBankAccountNetworks struct { + // The preferred network. + Preferred string `json:"preferred"` + // All supported networks. + Supported []PaymentMethodUSBankAccountNetworksSupported `json:"supported"` +} +type PaymentMethodUSBankAccountStatusDetailsBlocked struct { + // The ACH network code that resulted in this block. + NetworkCode PaymentMethodUSBankAccountStatusDetailsBlockedNetworkCode `json:"network_code"` + // The reason why this PaymentMethod's fingerprint has been blocked + Reason PaymentMethodUSBankAccountStatusDetailsBlockedReason `json:"reason"` +} + +// Contains information about the future reusability of this PaymentMethod. +type PaymentMethodUSBankAccountStatusDetails struct { + Blocked *PaymentMethodUSBankAccountStatusDetailsBlocked `json:"blocked"` +} +type PaymentMethodUSBankAccount struct { + // Account holder type: individual or company. + AccountHolderType PaymentMethodUSBankAccountAccountHolderType `json:"account_holder_type"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType PaymentMethodUSBankAccountAccountType `json:"account_type"` + // The name of the bank. + BankName string `json:"bank_name"` + // The ID of the Financial Connections Account used to create the payment method. + FinancialConnectionsAccount string `json:"financial_connections_account"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // Contains information about US bank account networks that can be used. + Networks *PaymentMethodUSBankAccountNetworks `json:"networks"` + // Routing number of the bank account. + RoutingNumber string `json:"routing_number"` + // Contains information about the future reusability of this PaymentMethod. + StatusDetails *PaymentMethodUSBankAccountStatusDetails `json:"status_details"` +} +type PaymentMethodWeChatPay struct{} +type PaymentMethodZip struct{} + +// PaymentMethod objects represent your customer's payment instruments. +// You can use them with [PaymentIntents](https://stripe.com/docs/payments/payment-intents) to collect payments or save them to +// Customer objects to store instrument details for future payments. +// +// Related guides: [Payment Methods](https://stripe.com/docs/payments/payment-methods) and [More Payment Scenarios](https://stripe.com/docs/payments/more-payment-scenarios). +type PaymentMethod struct { + APIResource + ACSSDebit *PaymentMethodACSSDebit `json:"acss_debit"` + Affirm *PaymentMethodAffirm `json:"affirm"` + AfterpayClearpay *PaymentMethodAfterpayClearpay `json:"afterpay_clearpay"` + Alipay *PaymentMethodAlipay `json:"alipay"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to “unspecified”. + AllowRedisplay PaymentMethodAllowRedisplay `json:"allow_redisplay"` + Alma *PaymentMethodAlma `json:"alma"` + AmazonPay *PaymentMethodAmazonPay `json:"amazon_pay"` + AUBECSDebit *PaymentMethodAUBECSDebit `json:"au_becs_debit"` + BACSDebit *PaymentMethodBACSDebit `json:"bacs_debit"` + Bancontact *PaymentMethodBancontact `json:"bancontact"` + Billie *PaymentMethodBillie `json:"billie"` + BillingDetails *PaymentMethodBillingDetails `json:"billing_details"` + BLIK *PaymentMethodBLIK `json:"blik"` + Boleto *PaymentMethodBoleto `json:"boleto"` + Card *PaymentMethodCard `json:"card"` + CardPresent *PaymentMethodCardPresent `json:"card_present"` + CashApp *PaymentMethodCashApp `json:"cashapp"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + Crypto *PaymentMethodCrypto `json:"crypto"` + // The ID of the Customer to which this PaymentMethod is saved. This will not be set when the PaymentMethod has not been saved to a Customer. + Customer *Customer `json:"customer"` + CustomerBalance *PaymentMethodCustomerBalance `json:"customer_balance"` + EPS *PaymentMethodEPS `json:"eps"` + FPX *PaymentMethodFPX `json:"fpx"` + Giropay *PaymentMethodGiropay `json:"giropay"` + Grabpay *PaymentMethodGrabpay `json:"grabpay"` + // Unique identifier for the object. + ID string `json:"id"` + IDEAL *PaymentMethodIDEAL `json:"ideal"` + InteracPresent *PaymentMethodInteracPresent `json:"interac_present"` + KakaoPay *PaymentMethodKakaoPay `json:"kakao_pay"` + Klarna *PaymentMethodKlarna `json:"klarna"` + Konbini *PaymentMethodKonbini `json:"konbini"` + KrCard *PaymentMethodKrCard `json:"kr_card"` + Link *PaymentMethodLink `json:"link"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + Mobilepay *PaymentMethodMobilepay `json:"mobilepay"` + Multibanco *PaymentMethodMultibanco `json:"multibanco"` + NaverPay *PaymentMethodNaverPay `json:"naver_pay"` + NzBankAccount *PaymentMethodNzBankAccount `json:"nz_bank_account"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + OXXO *PaymentMethodOXXO `json:"oxxo"` + P24 *PaymentMethodP24 `json:"p24"` + PayByBank *PaymentMethodPayByBank `json:"pay_by_bank"` + Payco *PaymentMethodPayco `json:"payco"` + PayNow *PaymentMethodPayNow `json:"paynow"` + Paypal *PaymentMethodPaypal `json:"paypal"` + Pix *PaymentMethodPix `json:"pix"` + PromptPay *PaymentMethodPromptPay `json:"promptpay"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *PaymentMethodRadarOptions `json:"radar_options"` + RevolutPay *PaymentMethodRevolutPay `json:"revolut_pay"` + SamsungPay *PaymentMethodSamsungPay `json:"samsung_pay"` + Satispay *PaymentMethodSatispay `json:"satispay"` + SEPADebit *PaymentMethodSEPADebit `json:"sepa_debit"` + Sofort *PaymentMethodSofort `json:"sofort"` + Swish *PaymentMethodSwish `json:"swish"` + TWINT *PaymentMethodTWINT `json:"twint"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type PaymentMethodType `json:"type"` + USBankAccount *PaymentMethodUSBankAccount `json:"us_bank_account"` + WeChatPay *PaymentMethodWeChatPay `json:"wechat_pay"` + Zip *PaymentMethodZip `json:"zip"` +} + +// PaymentMethodList is a list of PaymentMethods as retrieved from a list endpoint. +type PaymentMethodList struct { + APIResource + ListMeta + Data []*PaymentMethod `json:"data"` +} + +// UnmarshalJSON handles deserialization of a PaymentMethod. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (p *PaymentMethod) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + p.ID = id + return nil + } + + type paymentMethod PaymentMethod + var v paymentMethod + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *p = PaymentMethod(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/paymentmethod_service.go b/vendor/github.com/stripe/stripe-go/v82/paymentmethod_service.go new file mode 100644 index 00000000..b850b65b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/paymentmethod_service.go @@ -0,0 +1,111 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1PaymentMethodService is used to invoke /v1/payment_methods APIs. +type v1PaymentMethodService struct { + B Backend + Key string +} + +// Creates a PaymentMethod object. Read the [Stripe.js reference](https://docs.stripe.com/docs/stripe-js/reference#stripe-create-payment-method) to learn how to create PaymentMethods via Stripe.js. +// +// Instead of creating a PaymentMethod directly, we recommend using the [PaymentIntents API to accept a payment immediately or the SetupIntent](https://docs.stripe.com/docs/payments/accept-a-payment) API to collect payment method details ahead of a future payment. +func (c v1PaymentMethodService) Create(ctx context.Context, params *PaymentMethodCreateParams) (*PaymentMethod, error) { + if params == nil { + params = &PaymentMethodCreateParams{} + } + params.Context = ctx + paymentmethod := &PaymentMethod{} + err := c.B.Call( + http.MethodPost, "/v1/payment_methods", c.Key, params, paymentmethod) + return paymentmethod, err +} + +// Retrieves a PaymentMethod object attached to the StripeAccount. To retrieve a payment method attached to a Customer, you should use [Retrieve a Customer's PaymentMethods](https://docs.stripe.com/docs/api/payment_methods/customer) +func (c v1PaymentMethodService) Retrieve(ctx context.Context, id string, params *PaymentMethodRetrieveParams) (*PaymentMethod, error) { + if params == nil { + params = &PaymentMethodRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_methods/%s", id) + paymentmethod := &PaymentMethod{} + err := c.B.Call(http.MethodGet, path, c.Key, params, paymentmethod) + return paymentmethod, err +} + +// Updates a PaymentMethod object. A PaymentMethod must be attached a customer to be updated. +func (c v1PaymentMethodService) Update(ctx context.Context, id string, params *PaymentMethodUpdateParams) (*PaymentMethod, error) { + if params == nil { + params = &PaymentMethodUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_methods/%s", id) + paymentmethod := &PaymentMethod{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentmethod) + return paymentmethod, err +} + +// Attaches a PaymentMethod object to a Customer. +// +// To attach a new PaymentMethod to a customer for future payments, we recommend you use a [SetupIntent](https://docs.stripe.com/docs/api/setup_intents) +// or a PaymentIntent with [setup_future_usage](https://docs.stripe.com/docs/api/payment_intents/create#create_payment_intent-setup_future_usage). +// These approaches will perform any necessary steps to set up the PaymentMethod for future payments. Using the /v1/payment_methods/:id/attach +// endpoint without first using a SetupIntent or PaymentIntent with setup_future_usage does not optimize the PaymentMethod for +// future use, which makes later declines and payment friction more likely. +// See [Optimizing cards for future payments](https://docs.stripe.com/docs/payments/payment-intents#future-usage) for more information about setting up +// future payments. +// +// To use this PaymentMethod as the default for invoice or subscription payments, +// set [invoice_settings.default_payment_method](https://docs.stripe.com/docs/api/customers/update#update_customer-invoice_settings-default_payment_method), +// on the Customer to the PaymentMethod's ID. +func (c v1PaymentMethodService) Attach(ctx context.Context, id string, params *PaymentMethodAttachParams) (*PaymentMethod, error) { + if params == nil { + params = &PaymentMethodAttachParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_methods/%s/attach", id) + paymentmethod := &PaymentMethod{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentmethod) + return paymentmethod, err +} + +// Detaches a PaymentMethod object from a Customer. After a PaymentMethod is detached, it can no longer be used for a payment or re-attached to a Customer. +func (c v1PaymentMethodService) Detach(ctx context.Context, id string, params *PaymentMethodDetachParams) (*PaymentMethod, error) { + if params == nil { + params = &PaymentMethodDetachParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_methods/%s/detach", id) + paymentmethod := &PaymentMethod{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentmethod) + return paymentmethod, err +} + +// Returns a list of PaymentMethods for Treasury flows. If you want to list the PaymentMethods attached to a Customer for payments, you should use the [List a Customer's PaymentMethods](https://docs.stripe.com/docs/api/payment_methods/customer_list) API instead. +func (c v1PaymentMethodService) List(ctx context.Context, listParams *PaymentMethodListParams) Seq2[*PaymentMethod, error] { + if listParams == nil { + listParams = &PaymentMethodListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*PaymentMethod, ListContainer, error) { + list := &PaymentMethodList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/payment_methods", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/paymentmethodconfiguration.go b/vendor/github.com/stripe/stripe-go/v82/paymentmethodconfiguration.go new file mode 100644 index 00000000..b7a636ed --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/paymentmethodconfiguration.go @@ -0,0 +1,3992 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The account's display preference. +type PaymentMethodConfigurationACSSDebitDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationACSSDebitDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationACSSDebitDisplayPreferencePreferenceNone PaymentMethodConfigurationACSSDebitDisplayPreferencePreference = "none" + PaymentMethodConfigurationACSSDebitDisplayPreferencePreferenceOff PaymentMethodConfigurationACSSDebitDisplayPreferencePreference = "off" + PaymentMethodConfigurationACSSDebitDisplayPreferencePreferenceOn PaymentMethodConfigurationACSSDebitDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationACSSDebitDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationACSSDebitDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationACSSDebitDisplayPreferenceValueOff PaymentMethodConfigurationACSSDebitDisplayPreferenceValue = "off" + PaymentMethodConfigurationACSSDebitDisplayPreferenceValueOn PaymentMethodConfigurationACSSDebitDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationAffirmDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationAffirmDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationAffirmDisplayPreferencePreferenceNone PaymentMethodConfigurationAffirmDisplayPreferencePreference = "none" + PaymentMethodConfigurationAffirmDisplayPreferencePreferenceOff PaymentMethodConfigurationAffirmDisplayPreferencePreference = "off" + PaymentMethodConfigurationAffirmDisplayPreferencePreferenceOn PaymentMethodConfigurationAffirmDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationAffirmDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationAffirmDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationAffirmDisplayPreferenceValueOff PaymentMethodConfigurationAffirmDisplayPreferenceValue = "off" + PaymentMethodConfigurationAffirmDisplayPreferenceValueOn PaymentMethodConfigurationAffirmDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationAfterpayClearpayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationAfterpayClearpayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationAfterpayClearpayDisplayPreferencePreferenceNone PaymentMethodConfigurationAfterpayClearpayDisplayPreferencePreference = "none" + PaymentMethodConfigurationAfterpayClearpayDisplayPreferencePreferenceOff PaymentMethodConfigurationAfterpayClearpayDisplayPreferencePreference = "off" + PaymentMethodConfigurationAfterpayClearpayDisplayPreferencePreferenceOn PaymentMethodConfigurationAfterpayClearpayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationAfterpayClearpayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationAfterpayClearpayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationAfterpayClearpayDisplayPreferenceValueOff PaymentMethodConfigurationAfterpayClearpayDisplayPreferenceValue = "off" + PaymentMethodConfigurationAfterpayClearpayDisplayPreferenceValueOn PaymentMethodConfigurationAfterpayClearpayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationAlipayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationAlipayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationAlipayDisplayPreferencePreferenceNone PaymentMethodConfigurationAlipayDisplayPreferencePreference = "none" + PaymentMethodConfigurationAlipayDisplayPreferencePreferenceOff PaymentMethodConfigurationAlipayDisplayPreferencePreference = "off" + PaymentMethodConfigurationAlipayDisplayPreferencePreferenceOn PaymentMethodConfigurationAlipayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationAlipayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationAlipayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationAlipayDisplayPreferenceValueOff PaymentMethodConfigurationAlipayDisplayPreferenceValue = "off" + PaymentMethodConfigurationAlipayDisplayPreferenceValueOn PaymentMethodConfigurationAlipayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationAlmaDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationAlmaDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationAlmaDisplayPreferencePreferenceNone PaymentMethodConfigurationAlmaDisplayPreferencePreference = "none" + PaymentMethodConfigurationAlmaDisplayPreferencePreferenceOff PaymentMethodConfigurationAlmaDisplayPreferencePreference = "off" + PaymentMethodConfigurationAlmaDisplayPreferencePreferenceOn PaymentMethodConfigurationAlmaDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationAlmaDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationAlmaDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationAlmaDisplayPreferenceValueOff PaymentMethodConfigurationAlmaDisplayPreferenceValue = "off" + PaymentMethodConfigurationAlmaDisplayPreferenceValueOn PaymentMethodConfigurationAlmaDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationAmazonPayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationAmazonPayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationAmazonPayDisplayPreferencePreferenceNone PaymentMethodConfigurationAmazonPayDisplayPreferencePreference = "none" + PaymentMethodConfigurationAmazonPayDisplayPreferencePreferenceOff PaymentMethodConfigurationAmazonPayDisplayPreferencePreference = "off" + PaymentMethodConfigurationAmazonPayDisplayPreferencePreferenceOn PaymentMethodConfigurationAmazonPayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationAmazonPayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationAmazonPayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationAmazonPayDisplayPreferenceValueOff PaymentMethodConfigurationAmazonPayDisplayPreferenceValue = "off" + PaymentMethodConfigurationAmazonPayDisplayPreferenceValueOn PaymentMethodConfigurationAmazonPayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationApplePayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationApplePayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationApplePayDisplayPreferencePreferenceNone PaymentMethodConfigurationApplePayDisplayPreferencePreference = "none" + PaymentMethodConfigurationApplePayDisplayPreferencePreferenceOff PaymentMethodConfigurationApplePayDisplayPreferencePreference = "off" + PaymentMethodConfigurationApplePayDisplayPreferencePreferenceOn PaymentMethodConfigurationApplePayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationApplePayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationApplePayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationApplePayDisplayPreferenceValueOff PaymentMethodConfigurationApplePayDisplayPreferenceValue = "off" + PaymentMethodConfigurationApplePayDisplayPreferenceValueOn PaymentMethodConfigurationApplePayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationAUBECSDebitDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationAUBECSDebitDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationAUBECSDebitDisplayPreferencePreferenceNone PaymentMethodConfigurationAUBECSDebitDisplayPreferencePreference = "none" + PaymentMethodConfigurationAUBECSDebitDisplayPreferencePreferenceOff PaymentMethodConfigurationAUBECSDebitDisplayPreferencePreference = "off" + PaymentMethodConfigurationAUBECSDebitDisplayPreferencePreferenceOn PaymentMethodConfigurationAUBECSDebitDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationAUBECSDebitDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationAUBECSDebitDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationAUBECSDebitDisplayPreferenceValueOff PaymentMethodConfigurationAUBECSDebitDisplayPreferenceValue = "off" + PaymentMethodConfigurationAUBECSDebitDisplayPreferenceValueOn PaymentMethodConfigurationAUBECSDebitDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationBACSDebitDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationBACSDebitDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationBACSDebitDisplayPreferencePreferenceNone PaymentMethodConfigurationBACSDebitDisplayPreferencePreference = "none" + PaymentMethodConfigurationBACSDebitDisplayPreferencePreferenceOff PaymentMethodConfigurationBACSDebitDisplayPreferencePreference = "off" + PaymentMethodConfigurationBACSDebitDisplayPreferencePreferenceOn PaymentMethodConfigurationBACSDebitDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationBACSDebitDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationBACSDebitDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationBACSDebitDisplayPreferenceValueOff PaymentMethodConfigurationBACSDebitDisplayPreferenceValue = "off" + PaymentMethodConfigurationBACSDebitDisplayPreferenceValueOn PaymentMethodConfigurationBACSDebitDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationBancontactDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationBancontactDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationBancontactDisplayPreferencePreferenceNone PaymentMethodConfigurationBancontactDisplayPreferencePreference = "none" + PaymentMethodConfigurationBancontactDisplayPreferencePreferenceOff PaymentMethodConfigurationBancontactDisplayPreferencePreference = "off" + PaymentMethodConfigurationBancontactDisplayPreferencePreferenceOn PaymentMethodConfigurationBancontactDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationBancontactDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationBancontactDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationBancontactDisplayPreferenceValueOff PaymentMethodConfigurationBancontactDisplayPreferenceValue = "off" + PaymentMethodConfigurationBancontactDisplayPreferenceValueOn PaymentMethodConfigurationBancontactDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationBillieDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationBillieDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationBillieDisplayPreferencePreferenceNone PaymentMethodConfigurationBillieDisplayPreferencePreference = "none" + PaymentMethodConfigurationBillieDisplayPreferencePreferenceOff PaymentMethodConfigurationBillieDisplayPreferencePreference = "off" + PaymentMethodConfigurationBillieDisplayPreferencePreferenceOn PaymentMethodConfigurationBillieDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationBillieDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationBillieDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationBillieDisplayPreferenceValueOff PaymentMethodConfigurationBillieDisplayPreferenceValue = "off" + PaymentMethodConfigurationBillieDisplayPreferenceValueOn PaymentMethodConfigurationBillieDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationBLIKDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationBLIKDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationBLIKDisplayPreferencePreferenceNone PaymentMethodConfigurationBLIKDisplayPreferencePreference = "none" + PaymentMethodConfigurationBLIKDisplayPreferencePreferenceOff PaymentMethodConfigurationBLIKDisplayPreferencePreference = "off" + PaymentMethodConfigurationBLIKDisplayPreferencePreferenceOn PaymentMethodConfigurationBLIKDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationBLIKDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationBLIKDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationBLIKDisplayPreferenceValueOff PaymentMethodConfigurationBLIKDisplayPreferenceValue = "off" + PaymentMethodConfigurationBLIKDisplayPreferenceValueOn PaymentMethodConfigurationBLIKDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationBoletoDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationBoletoDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationBoletoDisplayPreferencePreferenceNone PaymentMethodConfigurationBoletoDisplayPreferencePreference = "none" + PaymentMethodConfigurationBoletoDisplayPreferencePreferenceOff PaymentMethodConfigurationBoletoDisplayPreferencePreference = "off" + PaymentMethodConfigurationBoletoDisplayPreferencePreferenceOn PaymentMethodConfigurationBoletoDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationBoletoDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationBoletoDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationBoletoDisplayPreferenceValueOff PaymentMethodConfigurationBoletoDisplayPreferenceValue = "off" + PaymentMethodConfigurationBoletoDisplayPreferenceValueOn PaymentMethodConfigurationBoletoDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationCardDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationCardDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationCardDisplayPreferencePreferenceNone PaymentMethodConfigurationCardDisplayPreferencePreference = "none" + PaymentMethodConfigurationCardDisplayPreferencePreferenceOff PaymentMethodConfigurationCardDisplayPreferencePreference = "off" + PaymentMethodConfigurationCardDisplayPreferencePreferenceOn PaymentMethodConfigurationCardDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationCardDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationCardDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationCardDisplayPreferenceValueOff PaymentMethodConfigurationCardDisplayPreferenceValue = "off" + PaymentMethodConfigurationCardDisplayPreferenceValueOn PaymentMethodConfigurationCardDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationCartesBancairesDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationCartesBancairesDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationCartesBancairesDisplayPreferencePreferenceNone PaymentMethodConfigurationCartesBancairesDisplayPreferencePreference = "none" + PaymentMethodConfigurationCartesBancairesDisplayPreferencePreferenceOff PaymentMethodConfigurationCartesBancairesDisplayPreferencePreference = "off" + PaymentMethodConfigurationCartesBancairesDisplayPreferencePreferenceOn PaymentMethodConfigurationCartesBancairesDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationCartesBancairesDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationCartesBancairesDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationCartesBancairesDisplayPreferenceValueOff PaymentMethodConfigurationCartesBancairesDisplayPreferenceValue = "off" + PaymentMethodConfigurationCartesBancairesDisplayPreferenceValueOn PaymentMethodConfigurationCartesBancairesDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationCashAppDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationCashAppDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationCashAppDisplayPreferencePreferenceNone PaymentMethodConfigurationCashAppDisplayPreferencePreference = "none" + PaymentMethodConfigurationCashAppDisplayPreferencePreferenceOff PaymentMethodConfigurationCashAppDisplayPreferencePreference = "off" + PaymentMethodConfigurationCashAppDisplayPreferencePreferenceOn PaymentMethodConfigurationCashAppDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationCashAppDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationCashAppDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationCashAppDisplayPreferenceValueOff PaymentMethodConfigurationCashAppDisplayPreferenceValue = "off" + PaymentMethodConfigurationCashAppDisplayPreferenceValueOn PaymentMethodConfigurationCashAppDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationCustomerBalanceDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationCustomerBalanceDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationCustomerBalanceDisplayPreferencePreferenceNone PaymentMethodConfigurationCustomerBalanceDisplayPreferencePreference = "none" + PaymentMethodConfigurationCustomerBalanceDisplayPreferencePreferenceOff PaymentMethodConfigurationCustomerBalanceDisplayPreferencePreference = "off" + PaymentMethodConfigurationCustomerBalanceDisplayPreferencePreferenceOn PaymentMethodConfigurationCustomerBalanceDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationCustomerBalanceDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationCustomerBalanceDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationCustomerBalanceDisplayPreferenceValueOff PaymentMethodConfigurationCustomerBalanceDisplayPreferenceValue = "off" + PaymentMethodConfigurationCustomerBalanceDisplayPreferenceValueOn PaymentMethodConfigurationCustomerBalanceDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationEPSDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationEPSDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationEPSDisplayPreferencePreferenceNone PaymentMethodConfigurationEPSDisplayPreferencePreference = "none" + PaymentMethodConfigurationEPSDisplayPreferencePreferenceOff PaymentMethodConfigurationEPSDisplayPreferencePreference = "off" + PaymentMethodConfigurationEPSDisplayPreferencePreferenceOn PaymentMethodConfigurationEPSDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationEPSDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationEPSDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationEPSDisplayPreferenceValueOff PaymentMethodConfigurationEPSDisplayPreferenceValue = "off" + PaymentMethodConfigurationEPSDisplayPreferenceValueOn PaymentMethodConfigurationEPSDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationFPXDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationFPXDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationFPXDisplayPreferencePreferenceNone PaymentMethodConfigurationFPXDisplayPreferencePreference = "none" + PaymentMethodConfigurationFPXDisplayPreferencePreferenceOff PaymentMethodConfigurationFPXDisplayPreferencePreference = "off" + PaymentMethodConfigurationFPXDisplayPreferencePreferenceOn PaymentMethodConfigurationFPXDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationFPXDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationFPXDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationFPXDisplayPreferenceValueOff PaymentMethodConfigurationFPXDisplayPreferenceValue = "off" + PaymentMethodConfigurationFPXDisplayPreferenceValueOn PaymentMethodConfigurationFPXDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationGiropayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationGiropayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationGiropayDisplayPreferencePreferenceNone PaymentMethodConfigurationGiropayDisplayPreferencePreference = "none" + PaymentMethodConfigurationGiropayDisplayPreferencePreferenceOff PaymentMethodConfigurationGiropayDisplayPreferencePreference = "off" + PaymentMethodConfigurationGiropayDisplayPreferencePreferenceOn PaymentMethodConfigurationGiropayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationGiropayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationGiropayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationGiropayDisplayPreferenceValueOff PaymentMethodConfigurationGiropayDisplayPreferenceValue = "off" + PaymentMethodConfigurationGiropayDisplayPreferenceValueOn PaymentMethodConfigurationGiropayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationGooglePayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationGooglePayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationGooglePayDisplayPreferencePreferenceNone PaymentMethodConfigurationGooglePayDisplayPreferencePreference = "none" + PaymentMethodConfigurationGooglePayDisplayPreferencePreferenceOff PaymentMethodConfigurationGooglePayDisplayPreferencePreference = "off" + PaymentMethodConfigurationGooglePayDisplayPreferencePreferenceOn PaymentMethodConfigurationGooglePayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationGooglePayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationGooglePayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationGooglePayDisplayPreferenceValueOff PaymentMethodConfigurationGooglePayDisplayPreferenceValue = "off" + PaymentMethodConfigurationGooglePayDisplayPreferenceValueOn PaymentMethodConfigurationGooglePayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationGrabpayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationGrabpayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationGrabpayDisplayPreferencePreferenceNone PaymentMethodConfigurationGrabpayDisplayPreferencePreference = "none" + PaymentMethodConfigurationGrabpayDisplayPreferencePreferenceOff PaymentMethodConfigurationGrabpayDisplayPreferencePreference = "off" + PaymentMethodConfigurationGrabpayDisplayPreferencePreferenceOn PaymentMethodConfigurationGrabpayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationGrabpayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationGrabpayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationGrabpayDisplayPreferenceValueOff PaymentMethodConfigurationGrabpayDisplayPreferenceValue = "off" + PaymentMethodConfigurationGrabpayDisplayPreferenceValueOn PaymentMethodConfigurationGrabpayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationIDEALDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationIDEALDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationIDEALDisplayPreferencePreferenceNone PaymentMethodConfigurationIDEALDisplayPreferencePreference = "none" + PaymentMethodConfigurationIDEALDisplayPreferencePreferenceOff PaymentMethodConfigurationIDEALDisplayPreferencePreference = "off" + PaymentMethodConfigurationIDEALDisplayPreferencePreferenceOn PaymentMethodConfigurationIDEALDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationIDEALDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationIDEALDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationIDEALDisplayPreferenceValueOff PaymentMethodConfigurationIDEALDisplayPreferenceValue = "off" + PaymentMethodConfigurationIDEALDisplayPreferenceValueOn PaymentMethodConfigurationIDEALDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationJCBDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationJCBDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationJCBDisplayPreferencePreferenceNone PaymentMethodConfigurationJCBDisplayPreferencePreference = "none" + PaymentMethodConfigurationJCBDisplayPreferencePreferenceOff PaymentMethodConfigurationJCBDisplayPreferencePreference = "off" + PaymentMethodConfigurationJCBDisplayPreferencePreferenceOn PaymentMethodConfigurationJCBDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationJCBDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationJCBDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationJCBDisplayPreferenceValueOff PaymentMethodConfigurationJCBDisplayPreferenceValue = "off" + PaymentMethodConfigurationJCBDisplayPreferenceValueOn PaymentMethodConfigurationJCBDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationKakaoPayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationKakaoPayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationKakaoPayDisplayPreferencePreferenceNone PaymentMethodConfigurationKakaoPayDisplayPreferencePreference = "none" + PaymentMethodConfigurationKakaoPayDisplayPreferencePreferenceOff PaymentMethodConfigurationKakaoPayDisplayPreferencePreference = "off" + PaymentMethodConfigurationKakaoPayDisplayPreferencePreferenceOn PaymentMethodConfigurationKakaoPayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationKakaoPayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationKakaoPayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationKakaoPayDisplayPreferenceValueOff PaymentMethodConfigurationKakaoPayDisplayPreferenceValue = "off" + PaymentMethodConfigurationKakaoPayDisplayPreferenceValueOn PaymentMethodConfigurationKakaoPayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationKlarnaDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationKlarnaDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationKlarnaDisplayPreferencePreferenceNone PaymentMethodConfigurationKlarnaDisplayPreferencePreference = "none" + PaymentMethodConfigurationKlarnaDisplayPreferencePreferenceOff PaymentMethodConfigurationKlarnaDisplayPreferencePreference = "off" + PaymentMethodConfigurationKlarnaDisplayPreferencePreferenceOn PaymentMethodConfigurationKlarnaDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationKlarnaDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationKlarnaDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationKlarnaDisplayPreferenceValueOff PaymentMethodConfigurationKlarnaDisplayPreferenceValue = "off" + PaymentMethodConfigurationKlarnaDisplayPreferenceValueOn PaymentMethodConfigurationKlarnaDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationKonbiniDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationKonbiniDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationKonbiniDisplayPreferencePreferenceNone PaymentMethodConfigurationKonbiniDisplayPreferencePreference = "none" + PaymentMethodConfigurationKonbiniDisplayPreferencePreferenceOff PaymentMethodConfigurationKonbiniDisplayPreferencePreference = "off" + PaymentMethodConfigurationKonbiniDisplayPreferencePreferenceOn PaymentMethodConfigurationKonbiniDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationKonbiniDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationKonbiniDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationKonbiniDisplayPreferenceValueOff PaymentMethodConfigurationKonbiniDisplayPreferenceValue = "off" + PaymentMethodConfigurationKonbiniDisplayPreferenceValueOn PaymentMethodConfigurationKonbiniDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationKrCardDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationKrCardDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationKrCardDisplayPreferencePreferenceNone PaymentMethodConfigurationKrCardDisplayPreferencePreference = "none" + PaymentMethodConfigurationKrCardDisplayPreferencePreferenceOff PaymentMethodConfigurationKrCardDisplayPreferencePreference = "off" + PaymentMethodConfigurationKrCardDisplayPreferencePreferenceOn PaymentMethodConfigurationKrCardDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationKrCardDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationKrCardDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationKrCardDisplayPreferenceValueOff PaymentMethodConfigurationKrCardDisplayPreferenceValue = "off" + PaymentMethodConfigurationKrCardDisplayPreferenceValueOn PaymentMethodConfigurationKrCardDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationLinkDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationLinkDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationLinkDisplayPreferencePreferenceNone PaymentMethodConfigurationLinkDisplayPreferencePreference = "none" + PaymentMethodConfigurationLinkDisplayPreferencePreferenceOff PaymentMethodConfigurationLinkDisplayPreferencePreference = "off" + PaymentMethodConfigurationLinkDisplayPreferencePreferenceOn PaymentMethodConfigurationLinkDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationLinkDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationLinkDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationLinkDisplayPreferenceValueOff PaymentMethodConfigurationLinkDisplayPreferenceValue = "off" + PaymentMethodConfigurationLinkDisplayPreferenceValueOn PaymentMethodConfigurationLinkDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationMobilepayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationMobilepayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationMobilepayDisplayPreferencePreferenceNone PaymentMethodConfigurationMobilepayDisplayPreferencePreference = "none" + PaymentMethodConfigurationMobilepayDisplayPreferencePreferenceOff PaymentMethodConfigurationMobilepayDisplayPreferencePreference = "off" + PaymentMethodConfigurationMobilepayDisplayPreferencePreferenceOn PaymentMethodConfigurationMobilepayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationMobilepayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationMobilepayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationMobilepayDisplayPreferenceValueOff PaymentMethodConfigurationMobilepayDisplayPreferenceValue = "off" + PaymentMethodConfigurationMobilepayDisplayPreferenceValueOn PaymentMethodConfigurationMobilepayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationMultibancoDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationMultibancoDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationMultibancoDisplayPreferencePreferenceNone PaymentMethodConfigurationMultibancoDisplayPreferencePreference = "none" + PaymentMethodConfigurationMultibancoDisplayPreferencePreferenceOff PaymentMethodConfigurationMultibancoDisplayPreferencePreference = "off" + PaymentMethodConfigurationMultibancoDisplayPreferencePreferenceOn PaymentMethodConfigurationMultibancoDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationMultibancoDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationMultibancoDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationMultibancoDisplayPreferenceValueOff PaymentMethodConfigurationMultibancoDisplayPreferenceValue = "off" + PaymentMethodConfigurationMultibancoDisplayPreferenceValueOn PaymentMethodConfigurationMultibancoDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationNaverPayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationNaverPayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationNaverPayDisplayPreferencePreferenceNone PaymentMethodConfigurationNaverPayDisplayPreferencePreference = "none" + PaymentMethodConfigurationNaverPayDisplayPreferencePreferenceOff PaymentMethodConfigurationNaverPayDisplayPreferencePreference = "off" + PaymentMethodConfigurationNaverPayDisplayPreferencePreferenceOn PaymentMethodConfigurationNaverPayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationNaverPayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationNaverPayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationNaverPayDisplayPreferenceValueOff PaymentMethodConfigurationNaverPayDisplayPreferenceValue = "off" + PaymentMethodConfigurationNaverPayDisplayPreferenceValueOn PaymentMethodConfigurationNaverPayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationNzBankAccountDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationNzBankAccountDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationNzBankAccountDisplayPreferencePreferenceNone PaymentMethodConfigurationNzBankAccountDisplayPreferencePreference = "none" + PaymentMethodConfigurationNzBankAccountDisplayPreferencePreferenceOff PaymentMethodConfigurationNzBankAccountDisplayPreferencePreference = "off" + PaymentMethodConfigurationNzBankAccountDisplayPreferencePreferenceOn PaymentMethodConfigurationNzBankAccountDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationNzBankAccountDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationNzBankAccountDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationNzBankAccountDisplayPreferenceValueOff PaymentMethodConfigurationNzBankAccountDisplayPreferenceValue = "off" + PaymentMethodConfigurationNzBankAccountDisplayPreferenceValueOn PaymentMethodConfigurationNzBankAccountDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationOXXODisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationOXXODisplayPreferencePreference can take +const ( + PaymentMethodConfigurationOXXODisplayPreferencePreferenceNone PaymentMethodConfigurationOXXODisplayPreferencePreference = "none" + PaymentMethodConfigurationOXXODisplayPreferencePreferenceOff PaymentMethodConfigurationOXXODisplayPreferencePreference = "off" + PaymentMethodConfigurationOXXODisplayPreferencePreferenceOn PaymentMethodConfigurationOXXODisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationOXXODisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationOXXODisplayPreferenceValue can take +const ( + PaymentMethodConfigurationOXXODisplayPreferenceValueOff PaymentMethodConfigurationOXXODisplayPreferenceValue = "off" + PaymentMethodConfigurationOXXODisplayPreferenceValueOn PaymentMethodConfigurationOXXODisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationP24DisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationP24DisplayPreferencePreference can take +const ( + PaymentMethodConfigurationP24DisplayPreferencePreferenceNone PaymentMethodConfigurationP24DisplayPreferencePreference = "none" + PaymentMethodConfigurationP24DisplayPreferencePreferenceOff PaymentMethodConfigurationP24DisplayPreferencePreference = "off" + PaymentMethodConfigurationP24DisplayPreferencePreferenceOn PaymentMethodConfigurationP24DisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationP24DisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationP24DisplayPreferenceValue can take +const ( + PaymentMethodConfigurationP24DisplayPreferenceValueOff PaymentMethodConfigurationP24DisplayPreferenceValue = "off" + PaymentMethodConfigurationP24DisplayPreferenceValueOn PaymentMethodConfigurationP24DisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationPayByBankDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationPayByBankDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationPayByBankDisplayPreferencePreferenceNone PaymentMethodConfigurationPayByBankDisplayPreferencePreference = "none" + PaymentMethodConfigurationPayByBankDisplayPreferencePreferenceOff PaymentMethodConfigurationPayByBankDisplayPreferencePreference = "off" + PaymentMethodConfigurationPayByBankDisplayPreferencePreferenceOn PaymentMethodConfigurationPayByBankDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationPayByBankDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationPayByBankDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationPayByBankDisplayPreferenceValueOff PaymentMethodConfigurationPayByBankDisplayPreferenceValue = "off" + PaymentMethodConfigurationPayByBankDisplayPreferenceValueOn PaymentMethodConfigurationPayByBankDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationPaycoDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationPaycoDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationPaycoDisplayPreferencePreferenceNone PaymentMethodConfigurationPaycoDisplayPreferencePreference = "none" + PaymentMethodConfigurationPaycoDisplayPreferencePreferenceOff PaymentMethodConfigurationPaycoDisplayPreferencePreference = "off" + PaymentMethodConfigurationPaycoDisplayPreferencePreferenceOn PaymentMethodConfigurationPaycoDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationPaycoDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationPaycoDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationPaycoDisplayPreferenceValueOff PaymentMethodConfigurationPaycoDisplayPreferenceValue = "off" + PaymentMethodConfigurationPaycoDisplayPreferenceValueOn PaymentMethodConfigurationPaycoDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationPayNowDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationPayNowDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationPayNowDisplayPreferencePreferenceNone PaymentMethodConfigurationPayNowDisplayPreferencePreference = "none" + PaymentMethodConfigurationPayNowDisplayPreferencePreferenceOff PaymentMethodConfigurationPayNowDisplayPreferencePreference = "off" + PaymentMethodConfigurationPayNowDisplayPreferencePreferenceOn PaymentMethodConfigurationPayNowDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationPayNowDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationPayNowDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationPayNowDisplayPreferenceValueOff PaymentMethodConfigurationPayNowDisplayPreferenceValue = "off" + PaymentMethodConfigurationPayNowDisplayPreferenceValueOn PaymentMethodConfigurationPayNowDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationPaypalDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationPaypalDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationPaypalDisplayPreferencePreferenceNone PaymentMethodConfigurationPaypalDisplayPreferencePreference = "none" + PaymentMethodConfigurationPaypalDisplayPreferencePreferenceOff PaymentMethodConfigurationPaypalDisplayPreferencePreference = "off" + PaymentMethodConfigurationPaypalDisplayPreferencePreferenceOn PaymentMethodConfigurationPaypalDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationPaypalDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationPaypalDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationPaypalDisplayPreferenceValueOff PaymentMethodConfigurationPaypalDisplayPreferenceValue = "off" + PaymentMethodConfigurationPaypalDisplayPreferenceValueOn PaymentMethodConfigurationPaypalDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationPixDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationPixDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationPixDisplayPreferencePreferenceNone PaymentMethodConfigurationPixDisplayPreferencePreference = "none" + PaymentMethodConfigurationPixDisplayPreferencePreferenceOff PaymentMethodConfigurationPixDisplayPreferencePreference = "off" + PaymentMethodConfigurationPixDisplayPreferencePreferenceOn PaymentMethodConfigurationPixDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationPixDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationPixDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationPixDisplayPreferenceValueOff PaymentMethodConfigurationPixDisplayPreferenceValue = "off" + PaymentMethodConfigurationPixDisplayPreferenceValueOn PaymentMethodConfigurationPixDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationPromptPayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationPromptPayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationPromptPayDisplayPreferencePreferenceNone PaymentMethodConfigurationPromptPayDisplayPreferencePreference = "none" + PaymentMethodConfigurationPromptPayDisplayPreferencePreferenceOff PaymentMethodConfigurationPromptPayDisplayPreferencePreference = "off" + PaymentMethodConfigurationPromptPayDisplayPreferencePreferenceOn PaymentMethodConfigurationPromptPayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationPromptPayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationPromptPayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationPromptPayDisplayPreferenceValueOff PaymentMethodConfigurationPromptPayDisplayPreferenceValue = "off" + PaymentMethodConfigurationPromptPayDisplayPreferenceValueOn PaymentMethodConfigurationPromptPayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationRevolutPayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationRevolutPayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationRevolutPayDisplayPreferencePreferenceNone PaymentMethodConfigurationRevolutPayDisplayPreferencePreference = "none" + PaymentMethodConfigurationRevolutPayDisplayPreferencePreferenceOff PaymentMethodConfigurationRevolutPayDisplayPreferencePreference = "off" + PaymentMethodConfigurationRevolutPayDisplayPreferencePreferenceOn PaymentMethodConfigurationRevolutPayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationRevolutPayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationRevolutPayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationRevolutPayDisplayPreferenceValueOff PaymentMethodConfigurationRevolutPayDisplayPreferenceValue = "off" + PaymentMethodConfigurationRevolutPayDisplayPreferenceValueOn PaymentMethodConfigurationRevolutPayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationSamsungPayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationSamsungPayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationSamsungPayDisplayPreferencePreferenceNone PaymentMethodConfigurationSamsungPayDisplayPreferencePreference = "none" + PaymentMethodConfigurationSamsungPayDisplayPreferencePreferenceOff PaymentMethodConfigurationSamsungPayDisplayPreferencePreference = "off" + PaymentMethodConfigurationSamsungPayDisplayPreferencePreferenceOn PaymentMethodConfigurationSamsungPayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationSamsungPayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationSamsungPayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationSamsungPayDisplayPreferenceValueOff PaymentMethodConfigurationSamsungPayDisplayPreferenceValue = "off" + PaymentMethodConfigurationSamsungPayDisplayPreferenceValueOn PaymentMethodConfigurationSamsungPayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationSatispayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationSatispayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationSatispayDisplayPreferencePreferenceNone PaymentMethodConfigurationSatispayDisplayPreferencePreference = "none" + PaymentMethodConfigurationSatispayDisplayPreferencePreferenceOff PaymentMethodConfigurationSatispayDisplayPreferencePreference = "off" + PaymentMethodConfigurationSatispayDisplayPreferencePreferenceOn PaymentMethodConfigurationSatispayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationSatispayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationSatispayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationSatispayDisplayPreferenceValueOff PaymentMethodConfigurationSatispayDisplayPreferenceValue = "off" + PaymentMethodConfigurationSatispayDisplayPreferenceValueOn PaymentMethodConfigurationSatispayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationSEPADebitDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationSEPADebitDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationSEPADebitDisplayPreferencePreferenceNone PaymentMethodConfigurationSEPADebitDisplayPreferencePreference = "none" + PaymentMethodConfigurationSEPADebitDisplayPreferencePreferenceOff PaymentMethodConfigurationSEPADebitDisplayPreferencePreference = "off" + PaymentMethodConfigurationSEPADebitDisplayPreferencePreferenceOn PaymentMethodConfigurationSEPADebitDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationSEPADebitDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationSEPADebitDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationSEPADebitDisplayPreferenceValueOff PaymentMethodConfigurationSEPADebitDisplayPreferenceValue = "off" + PaymentMethodConfigurationSEPADebitDisplayPreferenceValueOn PaymentMethodConfigurationSEPADebitDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationSofortDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationSofortDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationSofortDisplayPreferencePreferenceNone PaymentMethodConfigurationSofortDisplayPreferencePreference = "none" + PaymentMethodConfigurationSofortDisplayPreferencePreferenceOff PaymentMethodConfigurationSofortDisplayPreferencePreference = "off" + PaymentMethodConfigurationSofortDisplayPreferencePreferenceOn PaymentMethodConfigurationSofortDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationSofortDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationSofortDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationSofortDisplayPreferenceValueOff PaymentMethodConfigurationSofortDisplayPreferenceValue = "off" + PaymentMethodConfigurationSofortDisplayPreferenceValueOn PaymentMethodConfigurationSofortDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationSwishDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationSwishDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationSwishDisplayPreferencePreferenceNone PaymentMethodConfigurationSwishDisplayPreferencePreference = "none" + PaymentMethodConfigurationSwishDisplayPreferencePreferenceOff PaymentMethodConfigurationSwishDisplayPreferencePreference = "off" + PaymentMethodConfigurationSwishDisplayPreferencePreferenceOn PaymentMethodConfigurationSwishDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationSwishDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationSwishDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationSwishDisplayPreferenceValueOff PaymentMethodConfigurationSwishDisplayPreferenceValue = "off" + PaymentMethodConfigurationSwishDisplayPreferenceValueOn PaymentMethodConfigurationSwishDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationTWINTDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationTWINTDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationTWINTDisplayPreferencePreferenceNone PaymentMethodConfigurationTWINTDisplayPreferencePreference = "none" + PaymentMethodConfigurationTWINTDisplayPreferencePreferenceOff PaymentMethodConfigurationTWINTDisplayPreferencePreference = "off" + PaymentMethodConfigurationTWINTDisplayPreferencePreferenceOn PaymentMethodConfigurationTWINTDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationTWINTDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationTWINTDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationTWINTDisplayPreferenceValueOff PaymentMethodConfigurationTWINTDisplayPreferenceValue = "off" + PaymentMethodConfigurationTWINTDisplayPreferenceValueOn PaymentMethodConfigurationTWINTDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationUSBankAccountDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationUSBankAccountDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationUSBankAccountDisplayPreferencePreferenceNone PaymentMethodConfigurationUSBankAccountDisplayPreferencePreference = "none" + PaymentMethodConfigurationUSBankAccountDisplayPreferencePreferenceOff PaymentMethodConfigurationUSBankAccountDisplayPreferencePreference = "off" + PaymentMethodConfigurationUSBankAccountDisplayPreferencePreferenceOn PaymentMethodConfigurationUSBankAccountDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationUSBankAccountDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationUSBankAccountDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationUSBankAccountDisplayPreferenceValueOff PaymentMethodConfigurationUSBankAccountDisplayPreferenceValue = "off" + PaymentMethodConfigurationUSBankAccountDisplayPreferenceValueOn PaymentMethodConfigurationUSBankAccountDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationWeChatPayDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationWeChatPayDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationWeChatPayDisplayPreferencePreferenceNone PaymentMethodConfigurationWeChatPayDisplayPreferencePreference = "none" + PaymentMethodConfigurationWeChatPayDisplayPreferencePreferenceOff PaymentMethodConfigurationWeChatPayDisplayPreferencePreference = "off" + PaymentMethodConfigurationWeChatPayDisplayPreferencePreferenceOn PaymentMethodConfigurationWeChatPayDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationWeChatPayDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationWeChatPayDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationWeChatPayDisplayPreferenceValueOff PaymentMethodConfigurationWeChatPayDisplayPreferenceValue = "off" + PaymentMethodConfigurationWeChatPayDisplayPreferenceValueOn PaymentMethodConfigurationWeChatPayDisplayPreferenceValue = "on" +) + +// The account's display preference. +type PaymentMethodConfigurationZipDisplayPreferencePreference string + +// List of values that PaymentMethodConfigurationZipDisplayPreferencePreference can take +const ( + PaymentMethodConfigurationZipDisplayPreferencePreferenceNone PaymentMethodConfigurationZipDisplayPreferencePreference = "none" + PaymentMethodConfigurationZipDisplayPreferencePreferenceOff PaymentMethodConfigurationZipDisplayPreferencePreference = "off" + PaymentMethodConfigurationZipDisplayPreferencePreferenceOn PaymentMethodConfigurationZipDisplayPreferencePreference = "on" +) + +// The effective display preference value. +type PaymentMethodConfigurationZipDisplayPreferenceValue string + +// List of values that PaymentMethodConfigurationZipDisplayPreferenceValue can take +const ( + PaymentMethodConfigurationZipDisplayPreferenceValueOff PaymentMethodConfigurationZipDisplayPreferenceValue = "off" + PaymentMethodConfigurationZipDisplayPreferenceValueOn PaymentMethodConfigurationZipDisplayPreferenceValue = "on" +) + +// List payment method configurations +type PaymentMethodConfigurationListParams struct { + ListParams `form:"*"` + // The Connect application to filter by. + Application *string `form:"application"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodConfigurationListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationACSSDebitDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Canadian pre-authorized debit payments, check this [page](https://stripe.com/docs/payments/acss-debit) for more details like country availability. +type PaymentMethodConfigurationACSSDebitParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationACSSDebitDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationAffirmDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// [Affirm](https://www.affirm.com/) gives your customers a way to split purchases over a series of payments. Depending on the purchase, they can pay with four interest-free payments (Split Pay) or pay over a longer term (Installments), which might include interest. Check this [page](https://stripe.com/docs/payments/affirm) for more details like country availability. +type PaymentMethodConfigurationAffirmParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationAffirmDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationAfterpayClearpayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Afterpay gives your customers a way to pay for purchases in installments, check this [page](https://stripe.com/docs/payments/afterpay-clearpay) for more details like country availability. Afterpay is particularly popular among businesses selling fashion, beauty, and sports products. +type PaymentMethodConfigurationAfterpayClearpayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationAfterpayClearpayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationAlipayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Alipay is a digital wallet in China that has more than a billion active users worldwide. Alipay users can pay on the web or on a mobile device using login credentials or their Alipay app. Alipay has a low dispute rate and reduces fraud by authenticating payments using the customer's login credentials. Check this [page](https://stripe.com/docs/payments/alipay) for more details. +type PaymentMethodConfigurationAlipayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationAlipayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationAlmaDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Alma is a Buy Now, Pay Later payment method that offers customers the ability to pay in 2, 3, or 4 installments. +type PaymentMethodConfigurationAlmaParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationAlmaDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationAmazonPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Amazon Pay is a wallet payment method that lets your customers check out the same way as on Amazon. +type PaymentMethodConfigurationAmazonPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationAmazonPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationApplePayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users can accept [Apple Pay](https://stripe.com/payments/apple-pay) in iOS applications in iOS 9 and later, and on the web in Safari starting with iOS 10 or macOS Sierra. There are no additional fees to process Apple Pay payments, and the [pricing](https://stripe.com/pricing) is the same as other card transactions. Check this [page](https://stripe.com/docs/apple-pay) for more details. +type PaymentMethodConfigurationApplePayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationApplePayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationApplePayLaterDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Apple Pay Later, a payment method for customers to buy now and pay later, gives your customers a way to split purchases into four installments across six weeks. +type PaymentMethodConfigurationApplePayLaterParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationApplePayLaterDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationAUBECSDebitDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in Australia can accept Bulk Electronic Clearing System (BECS) direct debit payments from customers with an Australian bank account. Check this [page](https://stripe.com/docs/payments/au-becs-debit) for more details. +type PaymentMethodConfigurationAUBECSDebitParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationAUBECSDebitDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationBACSDebitDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in the UK can accept Bacs Direct Debit payments from customers with a UK bank account, check this [page](https://stripe.com/docs/payments/payment-methods/bacs-debit) for more details. +type PaymentMethodConfigurationBACSDebitParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationBACSDebitDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationBancontactDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Bancontact is the most popular online payment method in Belgium, with over 15 million cards in circulation. [Customers](https://stripe.com/docs/api/customers) use a Bancontact card or mobile app linked to a Belgian bank account to make online payments that are secure, guaranteed, and confirmed immediately. Check this [page](https://stripe.com/docs/payments/bancontact) for more details. +type PaymentMethodConfigurationBancontactParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationBancontactDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationBillieDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Billie is a [single-use](https://docs.stripe.com/payments/payment-methods#usage) payment method that offers businesses Pay by Invoice where they offer payment terms ranging from 7-120 days. Customers are redirected from your website or app, authorize the payment with Billie, then return to your website or app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods#payment-notification) of whether the payment succeeded or failed. +type PaymentMethodConfigurationBillieParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationBillieDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationBLIKDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// BLIK is a [single use](https://stripe.com/docs/payments/payment-methods#usage) payment method that requires customers to authenticate their payments. When customers want to pay online using BLIK, they request a six-digit code from their banking application and enter it into the payment collection form. Check this [page](https://stripe.com/docs/payments/blik) for more details. +type PaymentMethodConfigurationBLIKParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationBLIKDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationBoletoDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Boleto is an official (regulated by the Central Bank of Brazil) payment method in Brazil. Check this [page](https://stripe.com/docs/payments/boleto) for more details. +type PaymentMethodConfigurationBoletoParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationBoletoDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCardDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Cards are a popular way for consumers and businesses to pay online or in person. Stripe supports global and local card networks. +type PaymentMethodConfigurationCardParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCardDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCartesBancairesDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Cartes Bancaires is France's local card network. More than 95% of these cards are co-branded with either Visa or Mastercard, meaning you can process these cards over either Cartes Bancaires or the Visa or Mastercard networks. Check this [page](https://stripe.com/docs/payments/cartes-bancaires) for more details. +type PaymentMethodConfigurationCartesBancairesParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCartesBancairesDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCashAppDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Cash App is a popular consumer app in the US that allows customers to bank, invest, send, and receive money using their digital wallet. Check this [page](https://stripe.com/docs/payments/cash-app-pay) for more details. +type PaymentMethodConfigurationCashAppParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCashAppDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCustomerBalanceDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Uses a customer's [cash balance](https://stripe.com/docs/payments/customer-balance) for the payment. The cash balance can be funded via a bank transfer. Check this [page](https://stripe.com/docs/payments/bank-transfers) for more details. +type PaymentMethodConfigurationCustomerBalanceParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCustomerBalanceDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationEPSDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// EPS is an Austria-based payment method that allows customers to complete transactions online using their bank credentials. EPS is supported by all Austrian banks and is accepted by over 80% of Austrian online retailers. Check this [page](https://stripe.com/docs/payments/eps) for more details. +type PaymentMethodConfigurationEPSParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationEPSDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationFPXDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Financial Process Exchange (FPX) is a Malaysia-based payment method that allows customers to complete transactions online using their bank credentials. Bank Negara Malaysia (BNM), the Central Bank of Malaysia, and eleven other major Malaysian financial institutions are members of the PayNet Group, which owns and operates FPX. It is one of the most popular online payment methods in Malaysia, with nearly 90 million transactions in 2018 according to BNM. Check this [page](https://stripe.com/docs/payments/fpx) for more details. +type PaymentMethodConfigurationFPXParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationFPXDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationGiropayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// giropay is a German payment method based on online banking, introduced in 2006. It allows customers to complete transactions online using their online banking environment, with funds debited from their bank account. Depending on their bank, customers confirm payments on giropay using a second factor of authentication or a PIN. giropay accounts for 10% of online checkouts in Germany. Check this [page](https://stripe.com/docs/payments/giropay) for more details. +type PaymentMethodConfigurationGiropayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationGiropayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationGooglePayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Google Pay allows customers to make payments in your app or website using any credit or debit card saved to their Google Account, including those from Google Play, YouTube, Chrome, or an Android device. Use the Google Pay API to request any credit or debit card stored in your customer's Google account. Check this [page](https://stripe.com/docs/google-pay) for more details. +type PaymentMethodConfigurationGooglePayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationGooglePayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationGrabpayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// GrabPay is a payment method developed by [Grab](https://www.grab.com/sg/consumer/finance/pay/). GrabPay is a digital wallet - customers maintain a balance in their wallets that they pay out with. Check this [page](https://stripe.com/docs/payments/grabpay) for more details. +type PaymentMethodConfigurationGrabpayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationGrabpayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationIDEALDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// iDEAL is a Netherlands-based payment method that allows customers to complete transactions online using their bank credentials. All major Dutch banks are members of Currence, the scheme that operates iDEAL, making it the most popular online payment method in the Netherlands with a share of online transactions close to 55%. Check this [page](https://stripe.com/docs/payments/ideal) for more details. +type PaymentMethodConfigurationIDEALParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationIDEALDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationJCBDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// JCB is a credit card company based in Japan. JCB is currently available in Japan to businesses approved by JCB, and available to all businesses in Australia, Canada, Hong Kong, Japan, New Zealand, Singapore, Switzerland, United Kingdom, United States, and all countries in the European Economic Area except Iceland. Check this [page](https://support.stripe.com/questions/accepting-japan-credit-bureau-%28jcb%29-payments) for more details. +type PaymentMethodConfigurationJCBParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationJCBDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationKakaoPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Kakao Pay is a popular local wallet available in South Korea. +type PaymentMethodConfigurationKakaoPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationKakaoPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationKlarnaDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Klarna gives customers a range of [payment options](https://stripe.com/docs/payments/klarna#payment-options) during checkout. Available payment options vary depending on the customer's billing address and the transaction amount. These payment options make it convenient for customers to purchase items in all price ranges. Check this [page](https://stripe.com/docs/payments/klarna) for more details. +type PaymentMethodConfigurationKlarnaParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationKlarnaDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationKonbiniDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Konbini allows customers in Japan to pay for bills and online purchases at convenience stores with cash. Check this [page](https://stripe.com/docs/payments/konbini) for more details. +type PaymentMethodConfigurationKonbiniParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationKonbiniDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationKrCardDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Korean cards let users pay using locally issued cards from South Korea. +type PaymentMethodConfigurationKrCardParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationKrCardDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationLinkDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// [Link](https://stripe.com/docs/payments/link) is a payment method network. With Link, users save their payment details once, then reuse that information to pay with one click for any business on the network. +type PaymentMethodConfigurationLinkParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationLinkDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationMobilepayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// MobilePay is a [single-use](https://stripe.com/docs/payments/payment-methods#usage) card wallet payment method used in Denmark and Finland. It allows customers to [authenticate and approve](https://stripe.com/docs/payments/payment-methods#customer-actions) payments using the MobilePay app. Check this [page](https://stripe.com/docs/payments/mobilepay) for more details. +type PaymentMethodConfigurationMobilepayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationMobilepayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationMultibancoDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in Europe and the United States can accept Multibanco payments from customers in Portugal using [Sources](https://stripe.com/docs/sources)—a single integration path for creating payments using any supported method. +type PaymentMethodConfigurationMultibancoParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationMultibancoDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationNaverPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Naver Pay is a popular local wallet available in South Korea. +type PaymentMethodConfigurationNaverPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationNaverPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationNzBankAccountDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in New Zealand can accept Bulk Electronic Clearing System (BECS) direct debit payments from customers with a New Zeland bank account. Check this [page](https://stripe.com/docs/payments/nz-bank-account) for more details. +type PaymentMethodConfigurationNzBankAccountParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationNzBankAccountDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationOXXODisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// OXXO is a Mexican chain of convenience stores with thousands of locations across Latin America and represents nearly 20% of online transactions in Mexico. OXXO allows customers to pay bills and online purchases in-store with cash. Check this [page](https://stripe.com/docs/payments/oxxo) for more details. +type PaymentMethodConfigurationOXXOParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationOXXODisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationP24DisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Przelewy24 is a Poland-based payment method aggregator that allows customers to complete transactions online using bank transfers and other methods. Bank transfers account for 30% of online payments in Poland and Przelewy24 provides a way for customers to pay with over 165 banks. Check this [page](https://stripe.com/docs/payments/p24) for more details. +type PaymentMethodConfigurationP24Params struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationP24DisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationPayByBankDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Pay by bank is a redirect payment method backed by bank transfers. A customer is redirected to their bank to authorize a bank transfer for a given amount. This removes a lot of the error risks inherent in waiting for the customer to initiate a transfer themselves, and is less expensive than card payments. +type PaymentMethodConfigurationPayByBankParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationPayByBankDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationPaycoDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// PAYCO is a [single-use](https://docs.stripe.com/payments/payment-methods#usage local wallet available in South Korea. +type PaymentMethodConfigurationPaycoParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationPaycoDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationPayNowDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// PayNow is a Singapore-based payment method that allows customers to make a payment using their preferred app from participating banks and participating non-bank financial institutions. Check this [page](https://stripe.com/docs/payments/paynow) for more details. +type PaymentMethodConfigurationPayNowParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationPayNowDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationPaypalDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// PayPal, a digital wallet popular with customers in Europe, allows your customers worldwide to pay using their PayPal account. Check this [page](https://stripe.com/docs/payments/paypal) for more details. +type PaymentMethodConfigurationPaypalParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationPaypalDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationPixDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Pix is a payment method popular in Brazil. When paying with Pix, customers authenticate and approve payments by scanning a QR code in their preferred banking app. Check this [page](https://docs.stripe.com/payments/pix) for more details. +type PaymentMethodConfigurationPixParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationPixDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationPromptPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// PromptPay is a Thailand-based payment method that allows customers to make a payment using their preferred app from participating banks. Check this [page](https://stripe.com/docs/payments/promptpay) for more details. +type PaymentMethodConfigurationPromptPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationPromptPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationRevolutPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Revolut Pay, developed by Revolut, a global finance app, is a digital wallet payment method. Revolut Pay uses the customer's stored balance or cards to fund the payment, and offers the option for non-Revolut customers to save their details after their first purchase. +type PaymentMethodConfigurationRevolutPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationRevolutPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationSamsungPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Samsung Pay is a [single-use](https://docs.stripe.com/payments/payment-methods#usage local wallet available in South Korea. +type PaymentMethodConfigurationSamsungPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationSamsungPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationSatispayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Satispay is a [single-use](https://docs.stripe.com/payments/payment-methods#usage) payment method where customers are required to [authenticate](https://docs.stripe.com/payments/payment-methods#customer-actions) their payment. Customers pay by being redirected from your website or app, authorizing the payment with Satispay, then returning to your website or app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods#payment-notification) of whether the payment succeeded or failed. +type PaymentMethodConfigurationSatispayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationSatispayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationSEPADebitDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// The [Single Euro Payments Area (SEPA)](https://en.wikipedia.org/wiki/Single_Euro_Payments_Area) is an initiative of the European Union to simplify payments within and across member countries. SEPA established and enforced banking standards to allow for the direct debiting of every EUR-denominated bank account within the SEPA region, check this [page](https://stripe.com/docs/payments/sepa-debit) for more details. +type PaymentMethodConfigurationSEPADebitParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationSEPADebitDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationSofortDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in Europe and the United States can use the [Payment Intents API](https://stripe.com/docs/payments/payment-intents)—a single integration path for creating payments using any supported method—to accept [Sofort](https://www.sofort.com/) payments from customers. Check this [page](https://stripe.com/docs/payments/sofort) for more details. +type PaymentMethodConfigurationSofortParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationSofortDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationSwishDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Swish is a [real-time](https://stripe.com/docs/payments/real-time) payment method popular in Sweden. It allows customers to [authenticate and approve](https://stripe.com/docs/payments/payment-methods#customer-actions) payments using the Swish mobile app and the Swedish BankID mobile app. Check this [page](https://stripe.com/docs/payments/swish) for more details. +type PaymentMethodConfigurationSwishParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationSwishDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationTWINTDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Twint is a payment method popular in Switzerland. It allows customers to pay using their mobile phone. Check this [page](https://docs.stripe.com/payments/twint) for more details. +type PaymentMethodConfigurationTWINTParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationTWINTDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUSBankAccountDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in the United States can accept ACH direct debit payments from customers with a US bank account using the Automated Clearing House (ACH) payments system operated by Nacha. Check this [page](https://stripe.com/docs/payments/ach-direct-debit) for more details. +type PaymentMethodConfigurationUSBankAccountParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUSBankAccountDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationWeChatPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// WeChat, owned by Tencent, is China's leading mobile app with over 1 billion monthly active users. Chinese consumers can use WeChat Pay to pay for goods and services inside of businesses' apps and websites. WeChat Pay users buy most frequently in gaming, e-commerce, travel, online education, and food/nutrition. Check this [page](https://stripe.com/docs/payments/wechat-pay) for more details. +type PaymentMethodConfigurationWeChatPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationWeChatPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationZipDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Zip gives your customers a way to split purchases over a series of payments. Check this [page](https://stripe.com/docs/payments/zip) for more details like country availability. +type PaymentMethodConfigurationZipParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationZipDisplayPreferenceParams `form:"display_preference"` +} + +// Creates a payment method configuration +type PaymentMethodConfigurationParams struct { + Params `form:"*"` + // Canadian pre-authorized debit payments, check this [page](https://stripe.com/docs/payments/acss-debit) for more details like country availability. + ACSSDebit *PaymentMethodConfigurationACSSDebitParams `form:"acss_debit"` + // Whether the configuration can be used for new payments. + Active *bool `form:"active"` + // [Affirm](https://www.affirm.com/) gives your customers a way to split purchases over a series of payments. Depending on the purchase, they can pay with four interest-free payments (Split Pay) or pay over a longer term (Installments), which might include interest. Check this [page](https://stripe.com/docs/payments/affirm) for more details like country availability. + Affirm *PaymentMethodConfigurationAffirmParams `form:"affirm"` + // Afterpay gives your customers a way to pay for purchases in installments, check this [page](https://stripe.com/docs/payments/afterpay-clearpay) for more details like country availability. Afterpay is particularly popular among businesses selling fashion, beauty, and sports products. + AfterpayClearpay *PaymentMethodConfigurationAfterpayClearpayParams `form:"afterpay_clearpay"` + // Alipay is a digital wallet in China that has more than a billion active users worldwide. Alipay users can pay on the web or on a mobile device using login credentials or their Alipay app. Alipay has a low dispute rate and reduces fraud by authenticating payments using the customer's login credentials. Check this [page](https://stripe.com/docs/payments/alipay) for more details. + Alipay *PaymentMethodConfigurationAlipayParams `form:"alipay"` + // Alma is a Buy Now, Pay Later payment method that offers customers the ability to pay in 2, 3, or 4 installments. + Alma *PaymentMethodConfigurationAlmaParams `form:"alma"` + // Amazon Pay is a wallet payment method that lets your customers check out the same way as on Amazon. + AmazonPay *PaymentMethodConfigurationAmazonPayParams `form:"amazon_pay"` + // Stripe users can accept [Apple Pay](https://stripe.com/payments/apple-pay) in iOS applications in iOS 9 and later, and on the web in Safari starting with iOS 10 or macOS Sierra. There are no additional fees to process Apple Pay payments, and the [pricing](https://stripe.com/pricing) is the same as other card transactions. Check this [page](https://stripe.com/docs/apple-pay) for more details. + ApplePay *PaymentMethodConfigurationApplePayParams `form:"apple_pay"` + // Apple Pay Later, a payment method for customers to buy now and pay later, gives your customers a way to split purchases into four installments across six weeks. + ApplePayLater *PaymentMethodConfigurationApplePayLaterParams `form:"apple_pay_later"` + // Stripe users in Australia can accept Bulk Electronic Clearing System (BECS) direct debit payments from customers with an Australian bank account. Check this [page](https://stripe.com/docs/payments/au-becs-debit) for more details. + AUBECSDebit *PaymentMethodConfigurationAUBECSDebitParams `form:"au_becs_debit"` + // Stripe users in the UK can accept Bacs Direct Debit payments from customers with a UK bank account, check this [page](https://stripe.com/docs/payments/payment-methods/bacs-debit) for more details. + BACSDebit *PaymentMethodConfigurationBACSDebitParams `form:"bacs_debit"` + // Bancontact is the most popular online payment method in Belgium, with over 15 million cards in circulation. [Customers](https://stripe.com/docs/api/customers) use a Bancontact card or mobile app linked to a Belgian bank account to make online payments that are secure, guaranteed, and confirmed immediately. Check this [page](https://stripe.com/docs/payments/bancontact) for more details. + Bancontact *PaymentMethodConfigurationBancontactParams `form:"bancontact"` + // Billie is a [single-use](https://docs.stripe.com/payments/payment-methods#usage) payment method that offers businesses Pay by Invoice where they offer payment terms ranging from 7-120 days. Customers are redirected from your website or app, authorize the payment with Billie, then return to your website or app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods#payment-notification) of whether the payment succeeded or failed. + Billie *PaymentMethodConfigurationBillieParams `form:"billie"` + // BLIK is a [single use](https://stripe.com/docs/payments/payment-methods#usage) payment method that requires customers to authenticate their payments. When customers want to pay online using BLIK, they request a six-digit code from their banking application and enter it into the payment collection form. Check this [page](https://stripe.com/docs/payments/blik) for more details. + BLIK *PaymentMethodConfigurationBLIKParams `form:"blik"` + // Boleto is an official (regulated by the Central Bank of Brazil) payment method in Brazil. Check this [page](https://stripe.com/docs/payments/boleto) for more details. + Boleto *PaymentMethodConfigurationBoletoParams `form:"boleto"` + // Cards are a popular way for consumers and businesses to pay online or in person. Stripe supports global and local card networks. + Card *PaymentMethodConfigurationCardParams `form:"card"` + // Cartes Bancaires is France's local card network. More than 95% of these cards are co-branded with either Visa or Mastercard, meaning you can process these cards over either Cartes Bancaires or the Visa or Mastercard networks. Check this [page](https://stripe.com/docs/payments/cartes-bancaires) for more details. + CartesBancaires *PaymentMethodConfigurationCartesBancairesParams `form:"cartes_bancaires"` + // Cash App is a popular consumer app in the US that allows customers to bank, invest, send, and receive money using their digital wallet. Check this [page](https://stripe.com/docs/payments/cash-app-pay) for more details. + CashApp *PaymentMethodConfigurationCashAppParams `form:"cashapp"` + // Uses a customer's [cash balance](https://stripe.com/docs/payments/customer-balance) for the payment. The cash balance can be funded via a bank transfer. Check this [page](https://stripe.com/docs/payments/bank-transfers) for more details. + CustomerBalance *PaymentMethodConfigurationCustomerBalanceParams `form:"customer_balance"` + // EPS is an Austria-based payment method that allows customers to complete transactions online using their bank credentials. EPS is supported by all Austrian banks and is accepted by over 80% of Austrian online retailers. Check this [page](https://stripe.com/docs/payments/eps) for more details. + EPS *PaymentMethodConfigurationEPSParams `form:"eps"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Financial Process Exchange (FPX) is a Malaysia-based payment method that allows customers to complete transactions online using their bank credentials. Bank Negara Malaysia (BNM), the Central Bank of Malaysia, and eleven other major Malaysian financial institutions are members of the PayNet Group, which owns and operates FPX. It is one of the most popular online payment methods in Malaysia, with nearly 90 million transactions in 2018 according to BNM. Check this [page](https://stripe.com/docs/payments/fpx) for more details. + FPX *PaymentMethodConfigurationFPXParams `form:"fpx"` + // giropay is a German payment method based on online banking, introduced in 2006. It allows customers to complete transactions online using their online banking environment, with funds debited from their bank account. Depending on their bank, customers confirm payments on giropay using a second factor of authentication or a PIN. giropay accounts for 10% of online checkouts in Germany. Check this [page](https://stripe.com/docs/payments/giropay) for more details. + Giropay *PaymentMethodConfigurationGiropayParams `form:"giropay"` + // Google Pay allows customers to make payments in your app or website using any credit or debit card saved to their Google Account, including those from Google Play, YouTube, Chrome, or an Android device. Use the Google Pay API to request any credit or debit card stored in your customer's Google account. Check this [page](https://stripe.com/docs/google-pay) for more details. + GooglePay *PaymentMethodConfigurationGooglePayParams `form:"google_pay"` + // GrabPay is a payment method developed by [Grab](https://www.grab.com/sg/consumer/finance/pay/). GrabPay is a digital wallet - customers maintain a balance in their wallets that they pay out with. Check this [page](https://stripe.com/docs/payments/grabpay) for more details. + Grabpay *PaymentMethodConfigurationGrabpayParams `form:"grabpay"` + // iDEAL is a Netherlands-based payment method that allows customers to complete transactions online using their bank credentials. All major Dutch banks are members of Currence, the scheme that operates iDEAL, making it the most popular online payment method in the Netherlands with a share of online transactions close to 55%. Check this [page](https://stripe.com/docs/payments/ideal) for more details. + IDEAL *PaymentMethodConfigurationIDEALParams `form:"ideal"` + // JCB is a credit card company based in Japan. JCB is currently available in Japan to businesses approved by JCB, and available to all businesses in Australia, Canada, Hong Kong, Japan, New Zealand, Singapore, Switzerland, United Kingdom, United States, and all countries in the European Economic Area except Iceland. Check this [page](https://support.stripe.com/questions/accepting-japan-credit-bureau-%28jcb%29-payments) for more details. + JCB *PaymentMethodConfigurationJCBParams `form:"jcb"` + // Kakao Pay is a popular local wallet available in South Korea. + KakaoPay *PaymentMethodConfigurationKakaoPayParams `form:"kakao_pay"` + // Klarna gives customers a range of [payment options](https://stripe.com/docs/payments/klarna#payment-options) during checkout. Available payment options vary depending on the customer's billing address and the transaction amount. These payment options make it convenient for customers to purchase items in all price ranges. Check this [page](https://stripe.com/docs/payments/klarna) for more details. + Klarna *PaymentMethodConfigurationKlarnaParams `form:"klarna"` + // Konbini allows customers in Japan to pay for bills and online purchases at convenience stores with cash. Check this [page](https://stripe.com/docs/payments/konbini) for more details. + Konbini *PaymentMethodConfigurationKonbiniParams `form:"konbini"` + // Korean cards let users pay using locally issued cards from South Korea. + KrCard *PaymentMethodConfigurationKrCardParams `form:"kr_card"` + // [Link](https://stripe.com/docs/payments/link) is a payment method network. With Link, users save their payment details once, then reuse that information to pay with one click for any business on the network. + Link *PaymentMethodConfigurationLinkParams `form:"link"` + // MobilePay is a [single-use](https://stripe.com/docs/payments/payment-methods#usage) card wallet payment method used in Denmark and Finland. It allows customers to [authenticate and approve](https://stripe.com/docs/payments/payment-methods#customer-actions) payments using the MobilePay app. Check this [page](https://stripe.com/docs/payments/mobilepay) for more details. + Mobilepay *PaymentMethodConfigurationMobilepayParams `form:"mobilepay"` + // Stripe users in Europe and the United States can accept Multibanco payments from customers in Portugal using [Sources](https://stripe.com/docs/sources)—a single integration path for creating payments using any supported method. + Multibanco *PaymentMethodConfigurationMultibancoParams `form:"multibanco"` + // Configuration name. + Name *string `form:"name"` + // Naver Pay is a popular local wallet available in South Korea. + NaverPay *PaymentMethodConfigurationNaverPayParams `form:"naver_pay"` + // Stripe users in New Zealand can accept Bulk Electronic Clearing System (BECS) direct debit payments from customers with a New Zeland bank account. Check this [page](https://stripe.com/docs/payments/nz-bank-account) for more details. + NzBankAccount *PaymentMethodConfigurationNzBankAccountParams `form:"nz_bank_account"` + // OXXO is a Mexican chain of convenience stores with thousands of locations across Latin America and represents nearly 20% of online transactions in Mexico. OXXO allows customers to pay bills and online purchases in-store with cash. Check this [page](https://stripe.com/docs/payments/oxxo) for more details. + OXXO *PaymentMethodConfigurationOXXOParams `form:"oxxo"` + // Przelewy24 is a Poland-based payment method aggregator that allows customers to complete transactions online using bank transfers and other methods. Bank transfers account for 30% of online payments in Poland and Przelewy24 provides a way for customers to pay with over 165 banks. Check this [page](https://stripe.com/docs/payments/p24) for more details. + P24 *PaymentMethodConfigurationP24Params `form:"p24"` + // Configuration's parent configuration. Specify to create a child configuration. + Parent *string `form:"parent"` + // Pay by bank is a redirect payment method backed by bank transfers. A customer is redirected to their bank to authorize a bank transfer for a given amount. This removes a lot of the error risks inherent in waiting for the customer to initiate a transfer themselves, and is less expensive than card payments. + PayByBank *PaymentMethodConfigurationPayByBankParams `form:"pay_by_bank"` + // PAYCO is a [single-use](https://docs.stripe.com/payments/payment-methods#usage local wallet available in South Korea. + Payco *PaymentMethodConfigurationPaycoParams `form:"payco"` + // PayNow is a Singapore-based payment method that allows customers to make a payment using their preferred app from participating banks and participating non-bank financial institutions. Check this [page](https://stripe.com/docs/payments/paynow) for more details. + PayNow *PaymentMethodConfigurationPayNowParams `form:"paynow"` + // PayPal, a digital wallet popular with customers in Europe, allows your customers worldwide to pay using their PayPal account. Check this [page](https://stripe.com/docs/payments/paypal) for more details. + Paypal *PaymentMethodConfigurationPaypalParams `form:"paypal"` + // Pix is a payment method popular in Brazil. When paying with Pix, customers authenticate and approve payments by scanning a QR code in their preferred banking app. Check this [page](https://docs.stripe.com/payments/pix) for more details. + Pix *PaymentMethodConfigurationPixParams `form:"pix"` + // PromptPay is a Thailand-based payment method that allows customers to make a payment using their preferred app from participating banks. Check this [page](https://stripe.com/docs/payments/promptpay) for more details. + PromptPay *PaymentMethodConfigurationPromptPayParams `form:"promptpay"` + // Revolut Pay, developed by Revolut, a global finance app, is a digital wallet payment method. Revolut Pay uses the customer's stored balance or cards to fund the payment, and offers the option for non-Revolut customers to save their details after their first purchase. + RevolutPay *PaymentMethodConfigurationRevolutPayParams `form:"revolut_pay"` + // Samsung Pay is a [single-use](https://docs.stripe.com/payments/payment-methods#usage local wallet available in South Korea. + SamsungPay *PaymentMethodConfigurationSamsungPayParams `form:"samsung_pay"` + // Satispay is a [single-use](https://docs.stripe.com/payments/payment-methods#usage) payment method where customers are required to [authenticate](https://docs.stripe.com/payments/payment-methods#customer-actions) their payment. Customers pay by being redirected from your website or app, authorizing the payment with Satispay, then returning to your website or app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods#payment-notification) of whether the payment succeeded or failed. + Satispay *PaymentMethodConfigurationSatispayParams `form:"satispay"` + // The [Single Euro Payments Area (SEPA)](https://en.wikipedia.org/wiki/Single_Euro_Payments_Area) is an initiative of the European Union to simplify payments within and across member countries. SEPA established and enforced banking standards to allow for the direct debiting of every EUR-denominated bank account within the SEPA region, check this [page](https://stripe.com/docs/payments/sepa-debit) for more details. + SEPADebit *PaymentMethodConfigurationSEPADebitParams `form:"sepa_debit"` + // Stripe users in Europe and the United States can use the [Payment Intents API](https://stripe.com/docs/payments/payment-intents)—a single integration path for creating payments using any supported method—to accept [Sofort](https://www.sofort.com/) payments from customers. Check this [page](https://stripe.com/docs/payments/sofort) for more details. + Sofort *PaymentMethodConfigurationSofortParams `form:"sofort"` + // Swish is a [real-time](https://stripe.com/docs/payments/real-time) payment method popular in Sweden. It allows customers to [authenticate and approve](https://stripe.com/docs/payments/payment-methods#customer-actions) payments using the Swish mobile app and the Swedish BankID mobile app. Check this [page](https://stripe.com/docs/payments/swish) for more details. + Swish *PaymentMethodConfigurationSwishParams `form:"swish"` + // Twint is a payment method popular in Switzerland. It allows customers to pay using their mobile phone. Check this [page](https://docs.stripe.com/payments/twint) for more details. + TWINT *PaymentMethodConfigurationTWINTParams `form:"twint"` + // Stripe users in the United States can accept ACH direct debit payments from customers with a US bank account using the Automated Clearing House (ACH) payments system operated by Nacha. Check this [page](https://stripe.com/docs/payments/ach-direct-debit) for more details. + USBankAccount *PaymentMethodConfigurationUSBankAccountParams `form:"us_bank_account"` + // WeChat, owned by Tencent, is China's leading mobile app with over 1 billion monthly active users. Chinese consumers can use WeChat Pay to pay for goods and services inside of businesses' apps and websites. WeChat Pay users buy most frequently in gaming, e-commerce, travel, online education, and food/nutrition. Check this [page](https://stripe.com/docs/payments/wechat-pay) for more details. + WeChatPay *PaymentMethodConfigurationWeChatPayParams `form:"wechat_pay"` + // Zip gives your customers a way to split purchases over a series of payments. Check this [page](https://stripe.com/docs/payments/zip) for more details like country availability. + Zip *PaymentMethodConfigurationZipParams `form:"zip"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodConfigurationParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateACSSDebitDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Canadian pre-authorized debit payments, check this [page](https://stripe.com/docs/payments/acss-debit) for more details like country availability. +type PaymentMethodConfigurationCreateACSSDebitParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateACSSDebitDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateAffirmDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// [Affirm](https://www.affirm.com/) gives your customers a way to split purchases over a series of payments. Depending on the purchase, they can pay with four interest-free payments (Split Pay) or pay over a longer term (Installments), which might include interest. Check this [page](https://stripe.com/docs/payments/affirm) for more details like country availability. +type PaymentMethodConfigurationCreateAffirmParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateAffirmDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateAfterpayClearpayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Afterpay gives your customers a way to pay for purchases in installments, check this [page](https://stripe.com/docs/payments/afterpay-clearpay) for more details like country availability. Afterpay is particularly popular among businesses selling fashion, beauty, and sports products. +type PaymentMethodConfigurationCreateAfterpayClearpayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateAfterpayClearpayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateAlipayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Alipay is a digital wallet in China that has more than a billion active users worldwide. Alipay users can pay on the web or on a mobile device using login credentials or their Alipay app. Alipay has a low dispute rate and reduces fraud by authenticating payments using the customer's login credentials. Check this [page](https://stripe.com/docs/payments/alipay) for more details. +type PaymentMethodConfigurationCreateAlipayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateAlipayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateAlmaDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Alma is a Buy Now, Pay Later payment method that offers customers the ability to pay in 2, 3, or 4 installments. +type PaymentMethodConfigurationCreateAlmaParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateAlmaDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateAmazonPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Amazon Pay is a wallet payment method that lets your customers check out the same way as on Amazon. +type PaymentMethodConfigurationCreateAmazonPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateAmazonPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateApplePayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users can accept [Apple Pay](https://stripe.com/payments/apple-pay) in iOS applications in iOS 9 and later, and on the web in Safari starting with iOS 10 or macOS Sierra. There are no additional fees to process Apple Pay payments, and the [pricing](https://stripe.com/pricing) is the same as other card transactions. Check this [page](https://stripe.com/docs/apple-pay) for more details. +type PaymentMethodConfigurationCreateApplePayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateApplePayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateApplePayLaterDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Apple Pay Later, a payment method for customers to buy now and pay later, gives your customers a way to split purchases into four installments across six weeks. +type PaymentMethodConfigurationCreateApplePayLaterParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateApplePayLaterDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateAUBECSDebitDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in Australia can accept Bulk Electronic Clearing System (BECS) direct debit payments from customers with an Australian bank account. Check this [page](https://stripe.com/docs/payments/au-becs-debit) for more details. +type PaymentMethodConfigurationCreateAUBECSDebitParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateAUBECSDebitDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateBACSDebitDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in the UK can accept Bacs Direct Debit payments from customers with a UK bank account, check this [page](https://stripe.com/docs/payments/payment-methods/bacs-debit) for more details. +type PaymentMethodConfigurationCreateBACSDebitParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateBACSDebitDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateBancontactDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Bancontact is the most popular online payment method in Belgium, with over 15 million cards in circulation. [Customers](https://stripe.com/docs/api/customers) use a Bancontact card or mobile app linked to a Belgian bank account to make online payments that are secure, guaranteed, and confirmed immediately. Check this [page](https://stripe.com/docs/payments/bancontact) for more details. +type PaymentMethodConfigurationCreateBancontactParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateBancontactDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateBillieDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Billie is a [single-use](https://docs.stripe.com/payments/payment-methods#usage) payment method that offers businesses Pay by Invoice where they offer payment terms ranging from 7-120 days. Customers are redirected from your website or app, authorize the payment with Billie, then return to your website or app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods#payment-notification) of whether the payment succeeded or failed. +type PaymentMethodConfigurationCreateBillieParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateBillieDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateBLIKDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// BLIK is a [single use](https://stripe.com/docs/payments/payment-methods#usage) payment method that requires customers to authenticate their payments. When customers want to pay online using BLIK, they request a six-digit code from their banking application and enter it into the payment collection form. Check this [page](https://stripe.com/docs/payments/blik) for more details. +type PaymentMethodConfigurationCreateBLIKParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateBLIKDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateBoletoDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Boleto is an official (regulated by the Central Bank of Brazil) payment method in Brazil. Check this [page](https://stripe.com/docs/payments/boleto) for more details. +type PaymentMethodConfigurationCreateBoletoParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateBoletoDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateCardDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Cards are a popular way for consumers and businesses to pay online or in person. Stripe supports global and local card networks. +type PaymentMethodConfigurationCreateCardParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateCardDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateCartesBancairesDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Cartes Bancaires is France's local card network. More than 95% of these cards are co-branded with either Visa or Mastercard, meaning you can process these cards over either Cartes Bancaires or the Visa or Mastercard networks. Check this [page](https://stripe.com/docs/payments/cartes-bancaires) for more details. +type PaymentMethodConfigurationCreateCartesBancairesParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateCartesBancairesDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateCashAppDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Cash App is a popular consumer app in the US that allows customers to bank, invest, send, and receive money using their digital wallet. Check this [page](https://stripe.com/docs/payments/cash-app-pay) for more details. +type PaymentMethodConfigurationCreateCashAppParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateCashAppDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateCustomerBalanceDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Uses a customer's [cash balance](https://stripe.com/docs/payments/customer-balance) for the payment. The cash balance can be funded via a bank transfer. Check this [page](https://stripe.com/docs/payments/bank-transfers) for more details. +type PaymentMethodConfigurationCreateCustomerBalanceParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateCustomerBalanceDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateEPSDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// EPS is an Austria-based payment method that allows customers to complete transactions online using their bank credentials. EPS is supported by all Austrian banks and is accepted by over 80% of Austrian online retailers. Check this [page](https://stripe.com/docs/payments/eps) for more details. +type PaymentMethodConfigurationCreateEPSParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateEPSDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateFPXDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Financial Process Exchange (FPX) is a Malaysia-based payment method that allows customers to complete transactions online using their bank credentials. Bank Negara Malaysia (BNM), the Central Bank of Malaysia, and eleven other major Malaysian financial institutions are members of the PayNet Group, which owns and operates FPX. It is one of the most popular online payment methods in Malaysia, with nearly 90 million transactions in 2018 according to BNM. Check this [page](https://stripe.com/docs/payments/fpx) for more details. +type PaymentMethodConfigurationCreateFPXParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateFPXDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateGiropayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// giropay is a German payment method based on online banking, introduced in 2006. It allows customers to complete transactions online using their online banking environment, with funds debited from their bank account. Depending on their bank, customers confirm payments on giropay using a second factor of authentication or a PIN. giropay accounts for 10% of online checkouts in Germany. Check this [page](https://stripe.com/docs/payments/giropay) for more details. +type PaymentMethodConfigurationCreateGiropayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateGiropayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateGooglePayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Google Pay allows customers to make payments in your app or website using any credit or debit card saved to their Google Account, including those from Google Play, YouTube, Chrome, or an Android device. Use the Google Pay API to request any credit or debit card stored in your customer's Google account. Check this [page](https://stripe.com/docs/google-pay) for more details. +type PaymentMethodConfigurationCreateGooglePayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateGooglePayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateGrabpayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// GrabPay is a payment method developed by [Grab](https://www.grab.com/sg/consumer/finance/pay/). GrabPay is a digital wallet - customers maintain a balance in their wallets that they pay out with. Check this [page](https://stripe.com/docs/payments/grabpay) for more details. +type PaymentMethodConfigurationCreateGrabpayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateGrabpayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateIDEALDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// iDEAL is a Netherlands-based payment method that allows customers to complete transactions online using their bank credentials. All major Dutch banks are members of Currence, the scheme that operates iDEAL, making it the most popular online payment method in the Netherlands with a share of online transactions close to 55%. Check this [page](https://stripe.com/docs/payments/ideal) for more details. +type PaymentMethodConfigurationCreateIDEALParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateIDEALDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateJCBDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// JCB is a credit card company based in Japan. JCB is currently available in Japan to businesses approved by JCB, and available to all businesses in Australia, Canada, Hong Kong, Japan, New Zealand, Singapore, Switzerland, United Kingdom, United States, and all countries in the European Economic Area except Iceland. Check this [page](https://support.stripe.com/questions/accepting-japan-credit-bureau-%28jcb%29-payments) for more details. +type PaymentMethodConfigurationCreateJCBParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateJCBDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateKakaoPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Kakao Pay is a popular local wallet available in South Korea. +type PaymentMethodConfigurationCreateKakaoPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateKakaoPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateKlarnaDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Klarna gives customers a range of [payment options](https://stripe.com/docs/payments/klarna#payment-options) during checkout. Available payment options vary depending on the customer's billing address and the transaction amount. These payment options make it convenient for customers to purchase items in all price ranges. Check this [page](https://stripe.com/docs/payments/klarna) for more details. +type PaymentMethodConfigurationCreateKlarnaParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateKlarnaDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateKonbiniDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Konbini allows customers in Japan to pay for bills and online purchases at convenience stores with cash. Check this [page](https://stripe.com/docs/payments/konbini) for more details. +type PaymentMethodConfigurationCreateKonbiniParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateKonbiniDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateKrCardDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Korean cards let users pay using locally issued cards from South Korea. +type PaymentMethodConfigurationCreateKrCardParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateKrCardDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateLinkDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// [Link](https://stripe.com/docs/payments/link) is a payment method network. With Link, users save their payment details once, then reuse that information to pay with one click for any business on the network. +type PaymentMethodConfigurationCreateLinkParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateLinkDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateMobilepayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// MobilePay is a [single-use](https://stripe.com/docs/payments/payment-methods#usage) card wallet payment method used in Denmark and Finland. It allows customers to [authenticate and approve](https://stripe.com/docs/payments/payment-methods#customer-actions) payments using the MobilePay app. Check this [page](https://stripe.com/docs/payments/mobilepay) for more details. +type PaymentMethodConfigurationCreateMobilepayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateMobilepayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateMultibancoDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in Europe and the United States can accept Multibanco payments from customers in Portugal using [Sources](https://stripe.com/docs/sources)—a single integration path for creating payments using any supported method. +type PaymentMethodConfigurationCreateMultibancoParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateMultibancoDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateNaverPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Naver Pay is a popular local wallet available in South Korea. +type PaymentMethodConfigurationCreateNaverPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateNaverPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateNzBankAccountDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in New Zealand can accept Bulk Electronic Clearing System (BECS) direct debit payments from customers with a New Zeland bank account. Check this [page](https://stripe.com/docs/payments/nz-bank-account) for more details. +type PaymentMethodConfigurationCreateNzBankAccountParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateNzBankAccountDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateOXXODisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// OXXO is a Mexican chain of convenience stores with thousands of locations across Latin America and represents nearly 20% of online transactions in Mexico. OXXO allows customers to pay bills and online purchases in-store with cash. Check this [page](https://stripe.com/docs/payments/oxxo) for more details. +type PaymentMethodConfigurationCreateOXXOParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateOXXODisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateP24DisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Przelewy24 is a Poland-based payment method aggregator that allows customers to complete transactions online using bank transfers and other methods. Bank transfers account for 30% of online payments in Poland and Przelewy24 provides a way for customers to pay with over 165 banks. Check this [page](https://stripe.com/docs/payments/p24) for more details. +type PaymentMethodConfigurationCreateP24Params struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateP24DisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreatePayByBankDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Pay by bank is a redirect payment method backed by bank transfers. A customer is redirected to their bank to authorize a bank transfer for a given amount. This removes a lot of the error risks inherent in waiting for the customer to initiate a transfer themselves, and is less expensive than card payments. +type PaymentMethodConfigurationCreatePayByBankParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreatePayByBankDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreatePaycoDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// PAYCO is a [single-use](https://docs.stripe.com/payments/payment-methods#usage local wallet available in South Korea. +type PaymentMethodConfigurationCreatePaycoParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreatePaycoDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreatePayNowDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// PayNow is a Singapore-based payment method that allows customers to make a payment using their preferred app from participating banks and participating non-bank financial institutions. Check this [page](https://stripe.com/docs/payments/paynow) for more details. +type PaymentMethodConfigurationCreatePayNowParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreatePayNowDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreatePaypalDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// PayPal, a digital wallet popular with customers in Europe, allows your customers worldwide to pay using their PayPal account. Check this [page](https://stripe.com/docs/payments/paypal) for more details. +type PaymentMethodConfigurationCreatePaypalParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreatePaypalDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreatePixDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Pix is a payment method popular in Brazil. When paying with Pix, customers authenticate and approve payments by scanning a QR code in their preferred banking app. Check this [page](https://docs.stripe.com/payments/pix) for more details. +type PaymentMethodConfigurationCreatePixParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreatePixDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreatePromptPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// PromptPay is a Thailand-based payment method that allows customers to make a payment using their preferred app from participating banks. Check this [page](https://stripe.com/docs/payments/promptpay) for more details. +type PaymentMethodConfigurationCreatePromptPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreatePromptPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateRevolutPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Revolut Pay, developed by Revolut, a global finance app, is a digital wallet payment method. Revolut Pay uses the customer's stored balance or cards to fund the payment, and offers the option for non-Revolut customers to save their details after their first purchase. +type PaymentMethodConfigurationCreateRevolutPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateRevolutPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateSamsungPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Samsung Pay is a [single-use](https://docs.stripe.com/payments/payment-methods#usage local wallet available in South Korea. +type PaymentMethodConfigurationCreateSamsungPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateSamsungPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateSatispayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Satispay is a [single-use](https://docs.stripe.com/payments/payment-methods#usage) payment method where customers are required to [authenticate](https://docs.stripe.com/payments/payment-methods#customer-actions) their payment. Customers pay by being redirected from your website or app, authorizing the payment with Satispay, then returning to your website or app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods#payment-notification) of whether the payment succeeded or failed. +type PaymentMethodConfigurationCreateSatispayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateSatispayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateSEPADebitDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// The [Single Euro Payments Area (SEPA)](https://en.wikipedia.org/wiki/Single_Euro_Payments_Area) is an initiative of the European Union to simplify payments within and across member countries. SEPA established and enforced banking standards to allow for the direct debiting of every EUR-denominated bank account within the SEPA region, check this [page](https://stripe.com/docs/payments/sepa-debit) for more details. +type PaymentMethodConfigurationCreateSEPADebitParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateSEPADebitDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateSofortDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in Europe and the United States can use the [Payment Intents API](https://stripe.com/docs/payments/payment-intents)—a single integration path for creating payments using any supported method—to accept [Sofort](https://www.sofort.com/) payments from customers. Check this [page](https://stripe.com/docs/payments/sofort) for more details. +type PaymentMethodConfigurationCreateSofortParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateSofortDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateSwishDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Swish is a [real-time](https://stripe.com/docs/payments/real-time) payment method popular in Sweden. It allows customers to [authenticate and approve](https://stripe.com/docs/payments/payment-methods#customer-actions) payments using the Swish mobile app and the Swedish BankID mobile app. Check this [page](https://stripe.com/docs/payments/swish) for more details. +type PaymentMethodConfigurationCreateSwishParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateSwishDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateTWINTDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Twint is a payment method popular in Switzerland. It allows customers to pay using their mobile phone. Check this [page](https://docs.stripe.com/payments/twint) for more details. +type PaymentMethodConfigurationCreateTWINTParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateTWINTDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateUSBankAccountDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in the United States can accept ACH direct debit payments from customers with a US bank account using the Automated Clearing House (ACH) payments system operated by Nacha. Check this [page](https://stripe.com/docs/payments/ach-direct-debit) for more details. +type PaymentMethodConfigurationCreateUSBankAccountParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateUSBankAccountDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateWeChatPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// WeChat, owned by Tencent, is China's leading mobile app with over 1 billion monthly active users. Chinese consumers can use WeChat Pay to pay for goods and services inside of businesses' apps and websites. WeChat Pay users buy most frequently in gaming, e-commerce, travel, online education, and food/nutrition. Check this [page](https://stripe.com/docs/payments/wechat-pay) for more details. +type PaymentMethodConfigurationCreateWeChatPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateWeChatPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationCreateZipDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Zip gives your customers a way to split purchases over a series of payments. Check this [page](https://stripe.com/docs/payments/zip) for more details like country availability. +type PaymentMethodConfigurationCreateZipParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationCreateZipDisplayPreferenceParams `form:"display_preference"` +} + +// Creates a payment method configuration +type PaymentMethodConfigurationCreateParams struct { + Params `form:"*"` + // Canadian pre-authorized debit payments, check this [page](https://stripe.com/docs/payments/acss-debit) for more details like country availability. + ACSSDebit *PaymentMethodConfigurationCreateACSSDebitParams `form:"acss_debit"` + // [Affirm](https://www.affirm.com/) gives your customers a way to split purchases over a series of payments. Depending on the purchase, they can pay with four interest-free payments (Split Pay) or pay over a longer term (Installments), which might include interest. Check this [page](https://stripe.com/docs/payments/affirm) for more details like country availability. + Affirm *PaymentMethodConfigurationCreateAffirmParams `form:"affirm"` + // Afterpay gives your customers a way to pay for purchases in installments, check this [page](https://stripe.com/docs/payments/afterpay-clearpay) for more details like country availability. Afterpay is particularly popular among businesses selling fashion, beauty, and sports products. + AfterpayClearpay *PaymentMethodConfigurationCreateAfterpayClearpayParams `form:"afterpay_clearpay"` + // Alipay is a digital wallet in China that has more than a billion active users worldwide. Alipay users can pay on the web or on a mobile device using login credentials or their Alipay app. Alipay has a low dispute rate and reduces fraud by authenticating payments using the customer's login credentials. Check this [page](https://stripe.com/docs/payments/alipay) for more details. + Alipay *PaymentMethodConfigurationCreateAlipayParams `form:"alipay"` + // Alma is a Buy Now, Pay Later payment method that offers customers the ability to pay in 2, 3, or 4 installments. + Alma *PaymentMethodConfigurationCreateAlmaParams `form:"alma"` + // Amazon Pay is a wallet payment method that lets your customers check out the same way as on Amazon. + AmazonPay *PaymentMethodConfigurationCreateAmazonPayParams `form:"amazon_pay"` + // Stripe users can accept [Apple Pay](https://stripe.com/payments/apple-pay) in iOS applications in iOS 9 and later, and on the web in Safari starting with iOS 10 or macOS Sierra. There are no additional fees to process Apple Pay payments, and the [pricing](https://stripe.com/pricing) is the same as other card transactions. Check this [page](https://stripe.com/docs/apple-pay) for more details. + ApplePay *PaymentMethodConfigurationCreateApplePayParams `form:"apple_pay"` + // Apple Pay Later, a payment method for customers to buy now and pay later, gives your customers a way to split purchases into four installments across six weeks. + ApplePayLater *PaymentMethodConfigurationCreateApplePayLaterParams `form:"apple_pay_later"` + // Stripe users in Australia can accept Bulk Electronic Clearing System (BECS) direct debit payments from customers with an Australian bank account. Check this [page](https://stripe.com/docs/payments/au-becs-debit) for more details. + AUBECSDebit *PaymentMethodConfigurationCreateAUBECSDebitParams `form:"au_becs_debit"` + // Stripe users in the UK can accept Bacs Direct Debit payments from customers with a UK bank account, check this [page](https://stripe.com/docs/payments/payment-methods/bacs-debit) for more details. + BACSDebit *PaymentMethodConfigurationCreateBACSDebitParams `form:"bacs_debit"` + // Bancontact is the most popular online payment method in Belgium, with over 15 million cards in circulation. [Customers](https://stripe.com/docs/api/customers) use a Bancontact card or mobile app linked to a Belgian bank account to make online payments that are secure, guaranteed, and confirmed immediately. Check this [page](https://stripe.com/docs/payments/bancontact) for more details. + Bancontact *PaymentMethodConfigurationCreateBancontactParams `form:"bancontact"` + // Billie is a [single-use](https://docs.stripe.com/payments/payment-methods#usage) payment method that offers businesses Pay by Invoice where they offer payment terms ranging from 7-120 days. Customers are redirected from your website or app, authorize the payment with Billie, then return to your website or app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods#payment-notification) of whether the payment succeeded or failed. + Billie *PaymentMethodConfigurationCreateBillieParams `form:"billie"` + // BLIK is a [single use](https://stripe.com/docs/payments/payment-methods#usage) payment method that requires customers to authenticate their payments. When customers want to pay online using BLIK, they request a six-digit code from their banking application and enter it into the payment collection form. Check this [page](https://stripe.com/docs/payments/blik) for more details. + BLIK *PaymentMethodConfigurationCreateBLIKParams `form:"blik"` + // Boleto is an official (regulated by the Central Bank of Brazil) payment method in Brazil. Check this [page](https://stripe.com/docs/payments/boleto) for more details. + Boleto *PaymentMethodConfigurationCreateBoletoParams `form:"boleto"` + // Cards are a popular way for consumers and businesses to pay online or in person. Stripe supports global and local card networks. + Card *PaymentMethodConfigurationCreateCardParams `form:"card"` + // Cartes Bancaires is France's local card network. More than 95% of these cards are co-branded with either Visa or Mastercard, meaning you can process these cards over either Cartes Bancaires or the Visa or Mastercard networks. Check this [page](https://stripe.com/docs/payments/cartes-bancaires) for more details. + CartesBancaires *PaymentMethodConfigurationCreateCartesBancairesParams `form:"cartes_bancaires"` + // Cash App is a popular consumer app in the US that allows customers to bank, invest, send, and receive money using their digital wallet. Check this [page](https://stripe.com/docs/payments/cash-app-pay) for more details. + CashApp *PaymentMethodConfigurationCreateCashAppParams `form:"cashapp"` + // Uses a customer's [cash balance](https://stripe.com/docs/payments/customer-balance) for the payment. The cash balance can be funded via a bank transfer. Check this [page](https://stripe.com/docs/payments/bank-transfers) for more details. + CustomerBalance *PaymentMethodConfigurationCreateCustomerBalanceParams `form:"customer_balance"` + // EPS is an Austria-based payment method that allows customers to complete transactions online using their bank credentials. EPS is supported by all Austrian banks and is accepted by over 80% of Austrian online retailers. Check this [page](https://stripe.com/docs/payments/eps) for more details. + EPS *PaymentMethodConfigurationCreateEPSParams `form:"eps"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Financial Process Exchange (FPX) is a Malaysia-based payment method that allows customers to complete transactions online using their bank credentials. Bank Negara Malaysia (BNM), the Central Bank of Malaysia, and eleven other major Malaysian financial institutions are members of the PayNet Group, which owns and operates FPX. It is one of the most popular online payment methods in Malaysia, with nearly 90 million transactions in 2018 according to BNM. Check this [page](https://stripe.com/docs/payments/fpx) for more details. + FPX *PaymentMethodConfigurationCreateFPXParams `form:"fpx"` + // giropay is a German payment method based on online banking, introduced in 2006. It allows customers to complete transactions online using their online banking environment, with funds debited from their bank account. Depending on their bank, customers confirm payments on giropay using a second factor of authentication or a PIN. giropay accounts for 10% of online checkouts in Germany. Check this [page](https://stripe.com/docs/payments/giropay) for more details. + Giropay *PaymentMethodConfigurationCreateGiropayParams `form:"giropay"` + // Google Pay allows customers to make payments in your app or website using any credit or debit card saved to their Google Account, including those from Google Play, YouTube, Chrome, or an Android device. Use the Google Pay API to request any credit or debit card stored in your customer's Google account. Check this [page](https://stripe.com/docs/google-pay) for more details. + GooglePay *PaymentMethodConfigurationCreateGooglePayParams `form:"google_pay"` + // GrabPay is a payment method developed by [Grab](https://www.grab.com/sg/consumer/finance/pay/). GrabPay is a digital wallet - customers maintain a balance in their wallets that they pay out with. Check this [page](https://stripe.com/docs/payments/grabpay) for more details. + Grabpay *PaymentMethodConfigurationCreateGrabpayParams `form:"grabpay"` + // iDEAL is a Netherlands-based payment method that allows customers to complete transactions online using their bank credentials. All major Dutch banks are members of Currence, the scheme that operates iDEAL, making it the most popular online payment method in the Netherlands with a share of online transactions close to 55%. Check this [page](https://stripe.com/docs/payments/ideal) for more details. + IDEAL *PaymentMethodConfigurationCreateIDEALParams `form:"ideal"` + // JCB is a credit card company based in Japan. JCB is currently available in Japan to businesses approved by JCB, and available to all businesses in Australia, Canada, Hong Kong, Japan, New Zealand, Singapore, Switzerland, United Kingdom, United States, and all countries in the European Economic Area except Iceland. Check this [page](https://support.stripe.com/questions/accepting-japan-credit-bureau-%28jcb%29-payments) for more details. + JCB *PaymentMethodConfigurationCreateJCBParams `form:"jcb"` + // Kakao Pay is a popular local wallet available in South Korea. + KakaoPay *PaymentMethodConfigurationCreateKakaoPayParams `form:"kakao_pay"` + // Klarna gives customers a range of [payment options](https://stripe.com/docs/payments/klarna#payment-options) during checkout. Available payment options vary depending on the customer's billing address and the transaction amount. These payment options make it convenient for customers to purchase items in all price ranges. Check this [page](https://stripe.com/docs/payments/klarna) for more details. + Klarna *PaymentMethodConfigurationCreateKlarnaParams `form:"klarna"` + // Konbini allows customers in Japan to pay for bills and online purchases at convenience stores with cash. Check this [page](https://stripe.com/docs/payments/konbini) for more details. + Konbini *PaymentMethodConfigurationCreateKonbiniParams `form:"konbini"` + // Korean cards let users pay using locally issued cards from South Korea. + KrCard *PaymentMethodConfigurationCreateKrCardParams `form:"kr_card"` + // [Link](https://stripe.com/docs/payments/link) is a payment method network. With Link, users save their payment details once, then reuse that information to pay with one click for any business on the network. + Link *PaymentMethodConfigurationCreateLinkParams `form:"link"` + // MobilePay is a [single-use](https://stripe.com/docs/payments/payment-methods#usage) card wallet payment method used in Denmark and Finland. It allows customers to [authenticate and approve](https://stripe.com/docs/payments/payment-methods#customer-actions) payments using the MobilePay app. Check this [page](https://stripe.com/docs/payments/mobilepay) for more details. + Mobilepay *PaymentMethodConfigurationCreateMobilepayParams `form:"mobilepay"` + // Stripe users in Europe and the United States can accept Multibanco payments from customers in Portugal using [Sources](https://stripe.com/docs/sources)—a single integration path for creating payments using any supported method. + Multibanco *PaymentMethodConfigurationCreateMultibancoParams `form:"multibanco"` + // Configuration name. + Name *string `form:"name"` + // Naver Pay is a popular local wallet available in South Korea. + NaverPay *PaymentMethodConfigurationCreateNaverPayParams `form:"naver_pay"` + // Stripe users in New Zealand can accept Bulk Electronic Clearing System (BECS) direct debit payments from customers with a New Zeland bank account. Check this [page](https://stripe.com/docs/payments/nz-bank-account) for more details. + NzBankAccount *PaymentMethodConfigurationCreateNzBankAccountParams `form:"nz_bank_account"` + // OXXO is a Mexican chain of convenience stores with thousands of locations across Latin America and represents nearly 20% of online transactions in Mexico. OXXO allows customers to pay bills and online purchases in-store with cash. Check this [page](https://stripe.com/docs/payments/oxxo) for more details. + OXXO *PaymentMethodConfigurationCreateOXXOParams `form:"oxxo"` + // Przelewy24 is a Poland-based payment method aggregator that allows customers to complete transactions online using bank transfers and other methods. Bank transfers account for 30% of online payments in Poland and Przelewy24 provides a way for customers to pay with over 165 banks. Check this [page](https://stripe.com/docs/payments/p24) for more details. + P24 *PaymentMethodConfigurationCreateP24Params `form:"p24"` + // Configuration's parent configuration. Specify to create a child configuration. + Parent *string `form:"parent"` + // Pay by bank is a redirect payment method backed by bank transfers. A customer is redirected to their bank to authorize a bank transfer for a given amount. This removes a lot of the error risks inherent in waiting for the customer to initiate a transfer themselves, and is less expensive than card payments. + PayByBank *PaymentMethodConfigurationCreatePayByBankParams `form:"pay_by_bank"` + // PAYCO is a [single-use](https://docs.stripe.com/payments/payment-methods#usage local wallet available in South Korea. + Payco *PaymentMethodConfigurationCreatePaycoParams `form:"payco"` + // PayNow is a Singapore-based payment method that allows customers to make a payment using their preferred app from participating banks and participating non-bank financial institutions. Check this [page](https://stripe.com/docs/payments/paynow) for more details. + PayNow *PaymentMethodConfigurationCreatePayNowParams `form:"paynow"` + // PayPal, a digital wallet popular with customers in Europe, allows your customers worldwide to pay using their PayPal account. Check this [page](https://stripe.com/docs/payments/paypal) for more details. + Paypal *PaymentMethodConfigurationCreatePaypalParams `form:"paypal"` + // Pix is a payment method popular in Brazil. When paying with Pix, customers authenticate and approve payments by scanning a QR code in their preferred banking app. Check this [page](https://docs.stripe.com/payments/pix) for more details. + Pix *PaymentMethodConfigurationCreatePixParams `form:"pix"` + // PromptPay is a Thailand-based payment method that allows customers to make a payment using their preferred app from participating banks. Check this [page](https://stripe.com/docs/payments/promptpay) for more details. + PromptPay *PaymentMethodConfigurationCreatePromptPayParams `form:"promptpay"` + // Revolut Pay, developed by Revolut, a global finance app, is a digital wallet payment method. Revolut Pay uses the customer's stored balance or cards to fund the payment, and offers the option for non-Revolut customers to save their details after their first purchase. + RevolutPay *PaymentMethodConfigurationCreateRevolutPayParams `form:"revolut_pay"` + // Samsung Pay is a [single-use](https://docs.stripe.com/payments/payment-methods#usage local wallet available in South Korea. + SamsungPay *PaymentMethodConfigurationCreateSamsungPayParams `form:"samsung_pay"` + // Satispay is a [single-use](https://docs.stripe.com/payments/payment-methods#usage) payment method where customers are required to [authenticate](https://docs.stripe.com/payments/payment-methods#customer-actions) their payment. Customers pay by being redirected from your website or app, authorizing the payment with Satispay, then returning to your website or app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods#payment-notification) of whether the payment succeeded or failed. + Satispay *PaymentMethodConfigurationCreateSatispayParams `form:"satispay"` + // The [Single Euro Payments Area (SEPA)](https://en.wikipedia.org/wiki/Single_Euro_Payments_Area) is an initiative of the European Union to simplify payments within and across member countries. SEPA established and enforced banking standards to allow for the direct debiting of every EUR-denominated bank account within the SEPA region, check this [page](https://stripe.com/docs/payments/sepa-debit) for more details. + SEPADebit *PaymentMethodConfigurationCreateSEPADebitParams `form:"sepa_debit"` + // Stripe users in Europe and the United States can use the [Payment Intents API](https://stripe.com/docs/payments/payment-intents)—a single integration path for creating payments using any supported method—to accept [Sofort](https://www.sofort.com/) payments from customers. Check this [page](https://stripe.com/docs/payments/sofort) for more details. + Sofort *PaymentMethodConfigurationCreateSofortParams `form:"sofort"` + // Swish is a [real-time](https://stripe.com/docs/payments/real-time) payment method popular in Sweden. It allows customers to [authenticate and approve](https://stripe.com/docs/payments/payment-methods#customer-actions) payments using the Swish mobile app and the Swedish BankID mobile app. Check this [page](https://stripe.com/docs/payments/swish) for more details. + Swish *PaymentMethodConfigurationCreateSwishParams `form:"swish"` + // Twint is a payment method popular in Switzerland. It allows customers to pay using their mobile phone. Check this [page](https://docs.stripe.com/payments/twint) for more details. + TWINT *PaymentMethodConfigurationCreateTWINTParams `form:"twint"` + // Stripe users in the United States can accept ACH direct debit payments from customers with a US bank account using the Automated Clearing House (ACH) payments system operated by Nacha. Check this [page](https://stripe.com/docs/payments/ach-direct-debit) for more details. + USBankAccount *PaymentMethodConfigurationCreateUSBankAccountParams `form:"us_bank_account"` + // WeChat, owned by Tencent, is China's leading mobile app with over 1 billion monthly active users. Chinese consumers can use WeChat Pay to pay for goods and services inside of businesses' apps and websites. WeChat Pay users buy most frequently in gaming, e-commerce, travel, online education, and food/nutrition. Check this [page](https://stripe.com/docs/payments/wechat-pay) for more details. + WeChatPay *PaymentMethodConfigurationCreateWeChatPayParams `form:"wechat_pay"` + // Zip gives your customers a way to split purchases over a series of payments. Check this [page](https://stripe.com/docs/payments/zip) for more details like country availability. + Zip *PaymentMethodConfigurationCreateZipParams `form:"zip"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodConfigurationCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieve payment method configuration +type PaymentMethodConfigurationRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodConfigurationRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateACSSDebitDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Canadian pre-authorized debit payments, check this [page](https://stripe.com/docs/payments/acss-debit) for more details like country availability. +type PaymentMethodConfigurationUpdateACSSDebitParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateACSSDebitDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateAffirmDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// [Affirm](https://www.affirm.com/) gives your customers a way to split purchases over a series of payments. Depending on the purchase, they can pay with four interest-free payments (Split Pay) or pay over a longer term (Installments), which might include interest. Check this [page](https://stripe.com/docs/payments/affirm) for more details like country availability. +type PaymentMethodConfigurationUpdateAffirmParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateAffirmDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateAfterpayClearpayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Afterpay gives your customers a way to pay for purchases in installments, check this [page](https://stripe.com/docs/payments/afterpay-clearpay) for more details like country availability. Afterpay is particularly popular among businesses selling fashion, beauty, and sports products. +type PaymentMethodConfigurationUpdateAfterpayClearpayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateAfterpayClearpayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateAlipayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Alipay is a digital wallet in China that has more than a billion active users worldwide. Alipay users can pay on the web or on a mobile device using login credentials or their Alipay app. Alipay has a low dispute rate and reduces fraud by authenticating payments using the customer's login credentials. Check this [page](https://stripe.com/docs/payments/alipay) for more details. +type PaymentMethodConfigurationUpdateAlipayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateAlipayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateAlmaDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Alma is a Buy Now, Pay Later payment method that offers customers the ability to pay in 2, 3, or 4 installments. +type PaymentMethodConfigurationUpdateAlmaParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateAlmaDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateAmazonPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Amazon Pay is a wallet payment method that lets your customers check out the same way as on Amazon. +type PaymentMethodConfigurationUpdateAmazonPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateAmazonPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateApplePayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users can accept [Apple Pay](https://stripe.com/payments/apple-pay) in iOS applications in iOS 9 and later, and on the web in Safari starting with iOS 10 or macOS Sierra. There are no additional fees to process Apple Pay payments, and the [pricing](https://stripe.com/pricing) is the same as other card transactions. Check this [page](https://stripe.com/docs/apple-pay) for more details. +type PaymentMethodConfigurationUpdateApplePayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateApplePayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateApplePayLaterDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Apple Pay Later, a payment method for customers to buy now and pay later, gives your customers a way to split purchases into four installments across six weeks. +type PaymentMethodConfigurationUpdateApplePayLaterParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateApplePayLaterDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateAUBECSDebitDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in Australia can accept Bulk Electronic Clearing System (BECS) direct debit payments from customers with an Australian bank account. Check this [page](https://stripe.com/docs/payments/au-becs-debit) for more details. +type PaymentMethodConfigurationUpdateAUBECSDebitParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateAUBECSDebitDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateBACSDebitDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in the UK can accept Bacs Direct Debit payments from customers with a UK bank account, check this [page](https://stripe.com/docs/payments/payment-methods/bacs-debit) for more details. +type PaymentMethodConfigurationUpdateBACSDebitParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateBACSDebitDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateBancontactDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Bancontact is the most popular online payment method in Belgium, with over 15 million cards in circulation. [Customers](https://stripe.com/docs/api/customers) use a Bancontact card or mobile app linked to a Belgian bank account to make online payments that are secure, guaranteed, and confirmed immediately. Check this [page](https://stripe.com/docs/payments/bancontact) for more details. +type PaymentMethodConfigurationUpdateBancontactParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateBancontactDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateBillieDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Billie is a [single-use](https://docs.stripe.com/payments/payment-methods#usage) payment method that offers businesses Pay by Invoice where they offer payment terms ranging from 7-120 days. Customers are redirected from your website or app, authorize the payment with Billie, then return to your website or app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods#payment-notification) of whether the payment succeeded or failed. +type PaymentMethodConfigurationUpdateBillieParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateBillieDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateBLIKDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// BLIK is a [single use](https://stripe.com/docs/payments/payment-methods#usage) payment method that requires customers to authenticate their payments. When customers want to pay online using BLIK, they request a six-digit code from their banking application and enter it into the payment collection form. Check this [page](https://stripe.com/docs/payments/blik) for more details. +type PaymentMethodConfigurationUpdateBLIKParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateBLIKDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateBoletoDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Boleto is an official (regulated by the Central Bank of Brazil) payment method in Brazil. Check this [page](https://stripe.com/docs/payments/boleto) for more details. +type PaymentMethodConfigurationUpdateBoletoParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateBoletoDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateCardDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Cards are a popular way for consumers and businesses to pay online or in person. Stripe supports global and local card networks. +type PaymentMethodConfigurationUpdateCardParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateCardDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateCartesBancairesDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Cartes Bancaires is France's local card network. More than 95% of these cards are co-branded with either Visa or Mastercard, meaning you can process these cards over either Cartes Bancaires or the Visa or Mastercard networks. Check this [page](https://stripe.com/docs/payments/cartes-bancaires) for more details. +type PaymentMethodConfigurationUpdateCartesBancairesParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateCartesBancairesDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateCashAppDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Cash App is a popular consumer app in the US that allows customers to bank, invest, send, and receive money using their digital wallet. Check this [page](https://stripe.com/docs/payments/cash-app-pay) for more details. +type PaymentMethodConfigurationUpdateCashAppParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateCashAppDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateCustomerBalanceDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Uses a customer's [cash balance](https://stripe.com/docs/payments/customer-balance) for the payment. The cash balance can be funded via a bank transfer. Check this [page](https://stripe.com/docs/payments/bank-transfers) for more details. +type PaymentMethodConfigurationUpdateCustomerBalanceParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateCustomerBalanceDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateEPSDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// EPS is an Austria-based payment method that allows customers to complete transactions online using their bank credentials. EPS is supported by all Austrian banks and is accepted by over 80% of Austrian online retailers. Check this [page](https://stripe.com/docs/payments/eps) for more details. +type PaymentMethodConfigurationUpdateEPSParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateEPSDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateFPXDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Financial Process Exchange (FPX) is a Malaysia-based payment method that allows customers to complete transactions online using their bank credentials. Bank Negara Malaysia (BNM), the Central Bank of Malaysia, and eleven other major Malaysian financial institutions are members of the PayNet Group, which owns and operates FPX. It is one of the most popular online payment methods in Malaysia, with nearly 90 million transactions in 2018 according to BNM. Check this [page](https://stripe.com/docs/payments/fpx) for more details. +type PaymentMethodConfigurationUpdateFPXParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateFPXDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateGiropayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// giropay is a German payment method based on online banking, introduced in 2006. It allows customers to complete transactions online using their online banking environment, with funds debited from their bank account. Depending on their bank, customers confirm payments on giropay using a second factor of authentication or a PIN. giropay accounts for 10% of online checkouts in Germany. Check this [page](https://stripe.com/docs/payments/giropay) for more details. +type PaymentMethodConfigurationUpdateGiropayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateGiropayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateGooglePayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Google Pay allows customers to make payments in your app or website using any credit or debit card saved to their Google Account, including those from Google Play, YouTube, Chrome, or an Android device. Use the Google Pay API to request any credit or debit card stored in your customer's Google account. Check this [page](https://stripe.com/docs/google-pay) for more details. +type PaymentMethodConfigurationUpdateGooglePayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateGooglePayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateGrabpayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// GrabPay is a payment method developed by [Grab](https://www.grab.com/sg/consumer/finance/pay/). GrabPay is a digital wallet - customers maintain a balance in their wallets that they pay out with. Check this [page](https://stripe.com/docs/payments/grabpay) for more details. +type PaymentMethodConfigurationUpdateGrabpayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateGrabpayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateIDEALDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// iDEAL is a Netherlands-based payment method that allows customers to complete transactions online using their bank credentials. All major Dutch banks are members of Currence, the scheme that operates iDEAL, making it the most popular online payment method in the Netherlands with a share of online transactions close to 55%. Check this [page](https://stripe.com/docs/payments/ideal) for more details. +type PaymentMethodConfigurationUpdateIDEALParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateIDEALDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateJCBDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// JCB is a credit card company based in Japan. JCB is currently available in Japan to businesses approved by JCB, and available to all businesses in Australia, Canada, Hong Kong, Japan, New Zealand, Singapore, Switzerland, United Kingdom, United States, and all countries in the European Economic Area except Iceland. Check this [page](https://support.stripe.com/questions/accepting-japan-credit-bureau-%28jcb%29-payments) for more details. +type PaymentMethodConfigurationUpdateJCBParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateJCBDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateKakaoPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Kakao Pay is a popular local wallet available in South Korea. +type PaymentMethodConfigurationUpdateKakaoPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateKakaoPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateKlarnaDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Klarna gives customers a range of [payment options](https://stripe.com/docs/payments/klarna#payment-options) during checkout. Available payment options vary depending on the customer's billing address and the transaction amount. These payment options make it convenient for customers to purchase items in all price ranges. Check this [page](https://stripe.com/docs/payments/klarna) for more details. +type PaymentMethodConfigurationUpdateKlarnaParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateKlarnaDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateKonbiniDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Konbini allows customers in Japan to pay for bills and online purchases at convenience stores with cash. Check this [page](https://stripe.com/docs/payments/konbini) for more details. +type PaymentMethodConfigurationUpdateKonbiniParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateKonbiniDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateKrCardDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Korean cards let users pay using locally issued cards from South Korea. +type PaymentMethodConfigurationUpdateKrCardParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateKrCardDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateLinkDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// [Link](https://stripe.com/docs/payments/link) is a payment method network. With Link, users save their payment details once, then reuse that information to pay with one click for any business on the network. +type PaymentMethodConfigurationUpdateLinkParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateLinkDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateMobilepayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// MobilePay is a [single-use](https://stripe.com/docs/payments/payment-methods#usage) card wallet payment method used in Denmark and Finland. It allows customers to [authenticate and approve](https://stripe.com/docs/payments/payment-methods#customer-actions) payments using the MobilePay app. Check this [page](https://stripe.com/docs/payments/mobilepay) for more details. +type PaymentMethodConfigurationUpdateMobilepayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateMobilepayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateMultibancoDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in Europe and the United States can accept Multibanco payments from customers in Portugal using [Sources](https://stripe.com/docs/sources)—a single integration path for creating payments using any supported method. +type PaymentMethodConfigurationUpdateMultibancoParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateMultibancoDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateNaverPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Naver Pay is a popular local wallet available in South Korea. +type PaymentMethodConfigurationUpdateNaverPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateNaverPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateNzBankAccountDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in New Zealand can accept Bulk Electronic Clearing System (BECS) direct debit payments from customers with a New Zeland bank account. Check this [page](https://stripe.com/docs/payments/nz-bank-account) for more details. +type PaymentMethodConfigurationUpdateNzBankAccountParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateNzBankAccountDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateOXXODisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// OXXO is a Mexican chain of convenience stores with thousands of locations across Latin America and represents nearly 20% of online transactions in Mexico. OXXO allows customers to pay bills and online purchases in-store with cash. Check this [page](https://stripe.com/docs/payments/oxxo) for more details. +type PaymentMethodConfigurationUpdateOXXOParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateOXXODisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateP24DisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Przelewy24 is a Poland-based payment method aggregator that allows customers to complete transactions online using bank transfers and other methods. Bank transfers account for 30% of online payments in Poland and Przelewy24 provides a way for customers to pay with over 165 banks. Check this [page](https://stripe.com/docs/payments/p24) for more details. +type PaymentMethodConfigurationUpdateP24Params struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateP24DisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdatePayByBankDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Pay by bank is a redirect payment method backed by bank transfers. A customer is redirected to their bank to authorize a bank transfer for a given amount. This removes a lot of the error risks inherent in waiting for the customer to initiate a transfer themselves, and is less expensive than card payments. +type PaymentMethodConfigurationUpdatePayByBankParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdatePayByBankDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdatePaycoDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// PAYCO is a [single-use](https://docs.stripe.com/payments/payment-methods#usage local wallet available in South Korea. +type PaymentMethodConfigurationUpdatePaycoParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdatePaycoDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdatePayNowDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// PayNow is a Singapore-based payment method that allows customers to make a payment using their preferred app from participating banks and participating non-bank financial institutions. Check this [page](https://stripe.com/docs/payments/paynow) for more details. +type PaymentMethodConfigurationUpdatePayNowParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdatePayNowDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdatePaypalDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// PayPal, a digital wallet popular with customers in Europe, allows your customers worldwide to pay using their PayPal account. Check this [page](https://stripe.com/docs/payments/paypal) for more details. +type PaymentMethodConfigurationUpdatePaypalParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdatePaypalDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdatePixDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Pix is a payment method popular in Brazil. When paying with Pix, customers authenticate and approve payments by scanning a QR code in their preferred banking app. Check this [page](https://docs.stripe.com/payments/pix) for more details. +type PaymentMethodConfigurationUpdatePixParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdatePixDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdatePromptPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// PromptPay is a Thailand-based payment method that allows customers to make a payment using their preferred app from participating banks. Check this [page](https://stripe.com/docs/payments/promptpay) for more details. +type PaymentMethodConfigurationUpdatePromptPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdatePromptPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateRevolutPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Revolut Pay, developed by Revolut, a global finance app, is a digital wallet payment method. Revolut Pay uses the customer's stored balance or cards to fund the payment, and offers the option for non-Revolut customers to save their details after their first purchase. +type PaymentMethodConfigurationUpdateRevolutPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateRevolutPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateSamsungPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Samsung Pay is a [single-use](https://docs.stripe.com/payments/payment-methods#usage local wallet available in South Korea. +type PaymentMethodConfigurationUpdateSamsungPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateSamsungPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateSatispayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Satispay is a [single-use](https://docs.stripe.com/payments/payment-methods#usage) payment method where customers are required to [authenticate](https://docs.stripe.com/payments/payment-methods#customer-actions) their payment. Customers pay by being redirected from your website or app, authorizing the payment with Satispay, then returning to your website or app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods#payment-notification) of whether the payment succeeded or failed. +type PaymentMethodConfigurationUpdateSatispayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateSatispayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateSEPADebitDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// The [Single Euro Payments Area (SEPA)](https://en.wikipedia.org/wiki/Single_Euro_Payments_Area) is an initiative of the European Union to simplify payments within and across member countries. SEPA established and enforced banking standards to allow for the direct debiting of every EUR-denominated bank account within the SEPA region, check this [page](https://stripe.com/docs/payments/sepa-debit) for more details. +type PaymentMethodConfigurationUpdateSEPADebitParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateSEPADebitDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateSofortDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in Europe and the United States can use the [Payment Intents API](https://stripe.com/docs/payments/payment-intents)—a single integration path for creating payments using any supported method—to accept [Sofort](https://www.sofort.com/) payments from customers. Check this [page](https://stripe.com/docs/payments/sofort) for more details. +type PaymentMethodConfigurationUpdateSofortParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateSofortDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateSwishDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Swish is a [real-time](https://stripe.com/docs/payments/real-time) payment method popular in Sweden. It allows customers to [authenticate and approve](https://stripe.com/docs/payments/payment-methods#customer-actions) payments using the Swish mobile app and the Swedish BankID mobile app. Check this [page](https://stripe.com/docs/payments/swish) for more details. +type PaymentMethodConfigurationUpdateSwishParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateSwishDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateTWINTDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Twint is a payment method popular in Switzerland. It allows customers to pay using their mobile phone. Check this [page](https://docs.stripe.com/payments/twint) for more details. +type PaymentMethodConfigurationUpdateTWINTParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateTWINTDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateUSBankAccountDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Stripe users in the United States can accept ACH direct debit payments from customers with a US bank account using the Automated Clearing House (ACH) payments system operated by Nacha. Check this [page](https://stripe.com/docs/payments/ach-direct-debit) for more details. +type PaymentMethodConfigurationUpdateUSBankAccountParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateUSBankAccountDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateWeChatPayDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// WeChat, owned by Tencent, is China's leading mobile app with over 1 billion monthly active users. Chinese consumers can use WeChat Pay to pay for goods and services inside of businesses' apps and websites. WeChat Pay users buy most frequently in gaming, e-commerce, travel, online education, and food/nutrition. Check this [page](https://stripe.com/docs/payments/wechat-pay) for more details. +type PaymentMethodConfigurationUpdateWeChatPayParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateWeChatPayDisplayPreferenceParams `form:"display_preference"` +} + +// Whether or not the payment method should be displayed. +type PaymentMethodConfigurationUpdateZipDisplayPreferenceParams struct { + // The account's preference for whether or not to display this payment method. + Preference *string `form:"preference"` +} + +// Zip gives your customers a way to split purchases over a series of payments. Check this [page](https://stripe.com/docs/payments/zip) for more details like country availability. +type PaymentMethodConfigurationUpdateZipParams struct { + // Whether or not the payment method should be displayed. + DisplayPreference *PaymentMethodConfigurationUpdateZipDisplayPreferenceParams `form:"display_preference"` +} + +// Update payment method configuration +type PaymentMethodConfigurationUpdateParams struct { + Params `form:"*"` + // Canadian pre-authorized debit payments, check this [page](https://stripe.com/docs/payments/acss-debit) for more details like country availability. + ACSSDebit *PaymentMethodConfigurationUpdateACSSDebitParams `form:"acss_debit"` + // Whether the configuration can be used for new payments. + Active *bool `form:"active"` + // [Affirm](https://www.affirm.com/) gives your customers a way to split purchases over a series of payments. Depending on the purchase, they can pay with four interest-free payments (Split Pay) or pay over a longer term (Installments), which might include interest. Check this [page](https://stripe.com/docs/payments/affirm) for more details like country availability. + Affirm *PaymentMethodConfigurationUpdateAffirmParams `form:"affirm"` + // Afterpay gives your customers a way to pay for purchases in installments, check this [page](https://stripe.com/docs/payments/afterpay-clearpay) for more details like country availability. Afterpay is particularly popular among businesses selling fashion, beauty, and sports products. + AfterpayClearpay *PaymentMethodConfigurationUpdateAfterpayClearpayParams `form:"afterpay_clearpay"` + // Alipay is a digital wallet in China that has more than a billion active users worldwide. Alipay users can pay on the web or on a mobile device using login credentials or their Alipay app. Alipay has a low dispute rate and reduces fraud by authenticating payments using the customer's login credentials. Check this [page](https://stripe.com/docs/payments/alipay) for more details. + Alipay *PaymentMethodConfigurationUpdateAlipayParams `form:"alipay"` + // Alma is a Buy Now, Pay Later payment method that offers customers the ability to pay in 2, 3, or 4 installments. + Alma *PaymentMethodConfigurationUpdateAlmaParams `form:"alma"` + // Amazon Pay is a wallet payment method that lets your customers check out the same way as on Amazon. + AmazonPay *PaymentMethodConfigurationUpdateAmazonPayParams `form:"amazon_pay"` + // Stripe users can accept [Apple Pay](https://stripe.com/payments/apple-pay) in iOS applications in iOS 9 and later, and on the web in Safari starting with iOS 10 or macOS Sierra. There are no additional fees to process Apple Pay payments, and the [pricing](https://stripe.com/pricing) is the same as other card transactions. Check this [page](https://stripe.com/docs/apple-pay) for more details. + ApplePay *PaymentMethodConfigurationUpdateApplePayParams `form:"apple_pay"` + // Apple Pay Later, a payment method for customers to buy now and pay later, gives your customers a way to split purchases into four installments across six weeks. + ApplePayLater *PaymentMethodConfigurationUpdateApplePayLaterParams `form:"apple_pay_later"` + // Stripe users in Australia can accept Bulk Electronic Clearing System (BECS) direct debit payments from customers with an Australian bank account. Check this [page](https://stripe.com/docs/payments/au-becs-debit) for more details. + AUBECSDebit *PaymentMethodConfigurationUpdateAUBECSDebitParams `form:"au_becs_debit"` + // Stripe users in the UK can accept Bacs Direct Debit payments from customers with a UK bank account, check this [page](https://stripe.com/docs/payments/payment-methods/bacs-debit) for more details. + BACSDebit *PaymentMethodConfigurationUpdateBACSDebitParams `form:"bacs_debit"` + // Bancontact is the most popular online payment method in Belgium, with over 15 million cards in circulation. [Customers](https://stripe.com/docs/api/customers) use a Bancontact card or mobile app linked to a Belgian bank account to make online payments that are secure, guaranteed, and confirmed immediately. Check this [page](https://stripe.com/docs/payments/bancontact) for more details. + Bancontact *PaymentMethodConfigurationUpdateBancontactParams `form:"bancontact"` + // Billie is a [single-use](https://docs.stripe.com/payments/payment-methods#usage) payment method that offers businesses Pay by Invoice where they offer payment terms ranging from 7-120 days. Customers are redirected from your website or app, authorize the payment with Billie, then return to your website or app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods#payment-notification) of whether the payment succeeded or failed. + Billie *PaymentMethodConfigurationUpdateBillieParams `form:"billie"` + // BLIK is a [single use](https://stripe.com/docs/payments/payment-methods#usage) payment method that requires customers to authenticate their payments. When customers want to pay online using BLIK, they request a six-digit code from their banking application and enter it into the payment collection form. Check this [page](https://stripe.com/docs/payments/blik) for more details. + BLIK *PaymentMethodConfigurationUpdateBLIKParams `form:"blik"` + // Boleto is an official (regulated by the Central Bank of Brazil) payment method in Brazil. Check this [page](https://stripe.com/docs/payments/boleto) for more details. + Boleto *PaymentMethodConfigurationUpdateBoletoParams `form:"boleto"` + // Cards are a popular way for consumers and businesses to pay online or in person. Stripe supports global and local card networks. + Card *PaymentMethodConfigurationUpdateCardParams `form:"card"` + // Cartes Bancaires is France's local card network. More than 95% of these cards are co-branded with either Visa or Mastercard, meaning you can process these cards over either Cartes Bancaires or the Visa or Mastercard networks. Check this [page](https://stripe.com/docs/payments/cartes-bancaires) for more details. + CartesBancaires *PaymentMethodConfigurationUpdateCartesBancairesParams `form:"cartes_bancaires"` + // Cash App is a popular consumer app in the US that allows customers to bank, invest, send, and receive money using their digital wallet. Check this [page](https://stripe.com/docs/payments/cash-app-pay) for more details. + CashApp *PaymentMethodConfigurationUpdateCashAppParams `form:"cashapp"` + // Uses a customer's [cash balance](https://stripe.com/docs/payments/customer-balance) for the payment. The cash balance can be funded via a bank transfer. Check this [page](https://stripe.com/docs/payments/bank-transfers) for more details. + CustomerBalance *PaymentMethodConfigurationUpdateCustomerBalanceParams `form:"customer_balance"` + // EPS is an Austria-based payment method that allows customers to complete transactions online using their bank credentials. EPS is supported by all Austrian banks and is accepted by over 80% of Austrian online retailers. Check this [page](https://stripe.com/docs/payments/eps) for more details. + EPS *PaymentMethodConfigurationUpdateEPSParams `form:"eps"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Financial Process Exchange (FPX) is a Malaysia-based payment method that allows customers to complete transactions online using their bank credentials. Bank Negara Malaysia (BNM), the Central Bank of Malaysia, and eleven other major Malaysian financial institutions are members of the PayNet Group, which owns and operates FPX. It is one of the most popular online payment methods in Malaysia, with nearly 90 million transactions in 2018 according to BNM. Check this [page](https://stripe.com/docs/payments/fpx) for more details. + FPX *PaymentMethodConfigurationUpdateFPXParams `form:"fpx"` + // giropay is a German payment method based on online banking, introduced in 2006. It allows customers to complete transactions online using their online banking environment, with funds debited from their bank account. Depending on their bank, customers confirm payments on giropay using a second factor of authentication or a PIN. giropay accounts for 10% of online checkouts in Germany. Check this [page](https://stripe.com/docs/payments/giropay) for more details. + Giropay *PaymentMethodConfigurationUpdateGiropayParams `form:"giropay"` + // Google Pay allows customers to make payments in your app or website using any credit or debit card saved to their Google Account, including those from Google Play, YouTube, Chrome, or an Android device. Use the Google Pay API to request any credit or debit card stored in your customer's Google account. Check this [page](https://stripe.com/docs/google-pay) for more details. + GooglePay *PaymentMethodConfigurationUpdateGooglePayParams `form:"google_pay"` + // GrabPay is a payment method developed by [Grab](https://www.grab.com/sg/consumer/finance/pay/). GrabPay is a digital wallet - customers maintain a balance in their wallets that they pay out with. Check this [page](https://stripe.com/docs/payments/grabpay) for more details. + Grabpay *PaymentMethodConfigurationUpdateGrabpayParams `form:"grabpay"` + // iDEAL is a Netherlands-based payment method that allows customers to complete transactions online using their bank credentials. All major Dutch banks are members of Currence, the scheme that operates iDEAL, making it the most popular online payment method in the Netherlands with a share of online transactions close to 55%. Check this [page](https://stripe.com/docs/payments/ideal) for more details. + IDEAL *PaymentMethodConfigurationUpdateIDEALParams `form:"ideal"` + // JCB is a credit card company based in Japan. JCB is currently available in Japan to businesses approved by JCB, and available to all businesses in Australia, Canada, Hong Kong, Japan, New Zealand, Singapore, Switzerland, United Kingdom, United States, and all countries in the European Economic Area except Iceland. Check this [page](https://support.stripe.com/questions/accepting-japan-credit-bureau-%28jcb%29-payments) for more details. + JCB *PaymentMethodConfigurationUpdateJCBParams `form:"jcb"` + // Kakao Pay is a popular local wallet available in South Korea. + KakaoPay *PaymentMethodConfigurationUpdateKakaoPayParams `form:"kakao_pay"` + // Klarna gives customers a range of [payment options](https://stripe.com/docs/payments/klarna#payment-options) during checkout. Available payment options vary depending on the customer's billing address and the transaction amount. These payment options make it convenient for customers to purchase items in all price ranges. Check this [page](https://stripe.com/docs/payments/klarna) for more details. + Klarna *PaymentMethodConfigurationUpdateKlarnaParams `form:"klarna"` + // Konbini allows customers in Japan to pay for bills and online purchases at convenience stores with cash. Check this [page](https://stripe.com/docs/payments/konbini) for more details. + Konbini *PaymentMethodConfigurationUpdateKonbiniParams `form:"konbini"` + // Korean cards let users pay using locally issued cards from South Korea. + KrCard *PaymentMethodConfigurationUpdateKrCardParams `form:"kr_card"` + // [Link](https://stripe.com/docs/payments/link) is a payment method network. With Link, users save their payment details once, then reuse that information to pay with one click for any business on the network. + Link *PaymentMethodConfigurationUpdateLinkParams `form:"link"` + // MobilePay is a [single-use](https://stripe.com/docs/payments/payment-methods#usage) card wallet payment method used in Denmark and Finland. It allows customers to [authenticate and approve](https://stripe.com/docs/payments/payment-methods#customer-actions) payments using the MobilePay app. Check this [page](https://stripe.com/docs/payments/mobilepay) for more details. + Mobilepay *PaymentMethodConfigurationUpdateMobilepayParams `form:"mobilepay"` + // Stripe users in Europe and the United States can accept Multibanco payments from customers in Portugal using [Sources](https://stripe.com/docs/sources)—a single integration path for creating payments using any supported method. + Multibanco *PaymentMethodConfigurationUpdateMultibancoParams `form:"multibanco"` + // Configuration name. + Name *string `form:"name"` + // Naver Pay is a popular local wallet available in South Korea. + NaverPay *PaymentMethodConfigurationUpdateNaverPayParams `form:"naver_pay"` + // Stripe users in New Zealand can accept Bulk Electronic Clearing System (BECS) direct debit payments from customers with a New Zeland bank account. Check this [page](https://stripe.com/docs/payments/nz-bank-account) for more details. + NzBankAccount *PaymentMethodConfigurationUpdateNzBankAccountParams `form:"nz_bank_account"` + // OXXO is a Mexican chain of convenience stores with thousands of locations across Latin America and represents nearly 20% of online transactions in Mexico. OXXO allows customers to pay bills and online purchases in-store with cash. Check this [page](https://stripe.com/docs/payments/oxxo) for more details. + OXXO *PaymentMethodConfigurationUpdateOXXOParams `form:"oxxo"` + // Przelewy24 is a Poland-based payment method aggregator that allows customers to complete transactions online using bank transfers and other methods. Bank transfers account for 30% of online payments in Poland and Przelewy24 provides a way for customers to pay with over 165 banks. Check this [page](https://stripe.com/docs/payments/p24) for more details. + P24 *PaymentMethodConfigurationUpdateP24Params `form:"p24"` + // Pay by bank is a redirect payment method backed by bank transfers. A customer is redirected to their bank to authorize a bank transfer for a given amount. This removes a lot of the error risks inherent in waiting for the customer to initiate a transfer themselves, and is less expensive than card payments. + PayByBank *PaymentMethodConfigurationUpdatePayByBankParams `form:"pay_by_bank"` + // PAYCO is a [single-use](https://docs.stripe.com/payments/payment-methods#usage local wallet available in South Korea. + Payco *PaymentMethodConfigurationUpdatePaycoParams `form:"payco"` + // PayNow is a Singapore-based payment method that allows customers to make a payment using their preferred app from participating banks and participating non-bank financial institutions. Check this [page](https://stripe.com/docs/payments/paynow) for more details. + PayNow *PaymentMethodConfigurationUpdatePayNowParams `form:"paynow"` + // PayPal, a digital wallet popular with customers in Europe, allows your customers worldwide to pay using their PayPal account. Check this [page](https://stripe.com/docs/payments/paypal) for more details. + Paypal *PaymentMethodConfigurationUpdatePaypalParams `form:"paypal"` + // Pix is a payment method popular in Brazil. When paying with Pix, customers authenticate and approve payments by scanning a QR code in their preferred banking app. Check this [page](https://docs.stripe.com/payments/pix) for more details. + Pix *PaymentMethodConfigurationUpdatePixParams `form:"pix"` + // PromptPay is a Thailand-based payment method that allows customers to make a payment using their preferred app from participating banks. Check this [page](https://stripe.com/docs/payments/promptpay) for more details. + PromptPay *PaymentMethodConfigurationUpdatePromptPayParams `form:"promptpay"` + // Revolut Pay, developed by Revolut, a global finance app, is a digital wallet payment method. Revolut Pay uses the customer's stored balance or cards to fund the payment, and offers the option for non-Revolut customers to save their details after their first purchase. + RevolutPay *PaymentMethodConfigurationUpdateRevolutPayParams `form:"revolut_pay"` + // Samsung Pay is a [single-use](https://docs.stripe.com/payments/payment-methods#usage local wallet available in South Korea. + SamsungPay *PaymentMethodConfigurationUpdateSamsungPayParams `form:"samsung_pay"` + // Satispay is a [single-use](https://docs.stripe.com/payments/payment-methods#usage) payment method where customers are required to [authenticate](https://docs.stripe.com/payments/payment-methods#customer-actions) their payment. Customers pay by being redirected from your website or app, authorizing the payment with Satispay, then returning to your website or app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods#payment-notification) of whether the payment succeeded or failed. + Satispay *PaymentMethodConfigurationUpdateSatispayParams `form:"satispay"` + // The [Single Euro Payments Area (SEPA)](https://en.wikipedia.org/wiki/Single_Euro_Payments_Area) is an initiative of the European Union to simplify payments within and across member countries. SEPA established and enforced banking standards to allow for the direct debiting of every EUR-denominated bank account within the SEPA region, check this [page](https://stripe.com/docs/payments/sepa-debit) for more details. + SEPADebit *PaymentMethodConfigurationUpdateSEPADebitParams `form:"sepa_debit"` + // Stripe users in Europe and the United States can use the [Payment Intents API](https://stripe.com/docs/payments/payment-intents)—a single integration path for creating payments using any supported method—to accept [Sofort](https://www.sofort.com/) payments from customers. Check this [page](https://stripe.com/docs/payments/sofort) for more details. + Sofort *PaymentMethodConfigurationUpdateSofortParams `form:"sofort"` + // Swish is a [real-time](https://stripe.com/docs/payments/real-time) payment method popular in Sweden. It allows customers to [authenticate and approve](https://stripe.com/docs/payments/payment-methods#customer-actions) payments using the Swish mobile app and the Swedish BankID mobile app. Check this [page](https://stripe.com/docs/payments/swish) for more details. + Swish *PaymentMethodConfigurationUpdateSwishParams `form:"swish"` + // Twint is a payment method popular in Switzerland. It allows customers to pay using their mobile phone. Check this [page](https://docs.stripe.com/payments/twint) for more details. + TWINT *PaymentMethodConfigurationUpdateTWINTParams `form:"twint"` + // Stripe users in the United States can accept ACH direct debit payments from customers with a US bank account using the Automated Clearing House (ACH) payments system operated by Nacha. Check this [page](https://stripe.com/docs/payments/ach-direct-debit) for more details. + USBankAccount *PaymentMethodConfigurationUpdateUSBankAccountParams `form:"us_bank_account"` + // WeChat, owned by Tencent, is China's leading mobile app with over 1 billion monthly active users. Chinese consumers can use WeChat Pay to pay for goods and services inside of businesses' apps and websites. WeChat Pay users buy most frequently in gaming, e-commerce, travel, online education, and food/nutrition. Check this [page](https://stripe.com/docs/payments/wechat-pay) for more details. + WeChatPay *PaymentMethodConfigurationUpdateWeChatPayParams `form:"wechat_pay"` + // Zip gives your customers a way to split purchases over a series of payments. Check this [page](https://stripe.com/docs/payments/zip) for more details like country availability. + Zip *PaymentMethodConfigurationUpdateZipParams `form:"zip"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodConfigurationUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type PaymentMethodConfigurationACSSDebitDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationACSSDebitDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationACSSDebitDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationACSSDebit struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationACSSDebitDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationAffirmDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationAffirmDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationAffirmDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationAffirm struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationAffirmDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationAfterpayClearpayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationAfterpayClearpayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationAfterpayClearpayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationAfterpayClearpay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationAfterpayClearpayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationAlipayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationAlipayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationAlipayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationAlipay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationAlipayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationAlmaDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationAlmaDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationAlmaDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationAlma struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationAlmaDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationAmazonPayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationAmazonPayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationAmazonPayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationAmazonPay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationAmazonPayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationApplePayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationApplePayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationApplePayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationApplePay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationApplePayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationAUBECSDebitDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationAUBECSDebitDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationAUBECSDebitDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationAUBECSDebit struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationAUBECSDebitDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationBACSDebitDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationBACSDebitDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationBACSDebitDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationBACSDebit struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationBACSDebitDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationBancontactDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationBancontactDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationBancontactDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationBancontact struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationBancontactDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationBillieDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationBillieDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationBillieDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationBillie struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationBillieDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationBLIKDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationBLIKDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationBLIKDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationBLIK struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationBLIKDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationBoletoDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationBoletoDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationBoletoDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationBoleto struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationBoletoDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationCardDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationCardDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationCardDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationCard struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationCardDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationCartesBancairesDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationCartesBancairesDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationCartesBancairesDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationCartesBancaires struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationCartesBancairesDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationCashAppDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationCashAppDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationCashAppDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationCashApp struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationCashAppDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationCustomerBalanceDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationCustomerBalanceDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationCustomerBalanceDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationCustomerBalance struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationCustomerBalanceDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationEPSDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationEPSDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationEPSDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationEPS struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationEPSDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationFPXDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationFPXDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationFPXDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationFPX struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationFPXDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationGiropayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationGiropayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationGiropayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationGiropay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationGiropayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationGooglePayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationGooglePayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationGooglePayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationGooglePay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationGooglePayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationGrabpayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationGrabpayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationGrabpayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationGrabpay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationGrabpayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationIDEALDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationIDEALDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationIDEALDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationIDEAL struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationIDEALDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationJCBDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationJCBDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationJCBDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationJCB struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationJCBDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationKakaoPayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationKakaoPayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationKakaoPayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationKakaoPay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationKakaoPayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationKlarnaDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationKlarnaDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationKlarnaDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationKlarna struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationKlarnaDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationKonbiniDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationKonbiniDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationKonbiniDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationKonbini struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationKonbiniDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationKrCardDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationKrCardDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationKrCardDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationKrCard struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationKrCardDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationLinkDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationLinkDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationLinkDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationLink struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationLinkDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationMobilepayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationMobilepayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationMobilepayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationMobilepay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationMobilepayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationMultibancoDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationMultibancoDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationMultibancoDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationMultibanco struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationMultibancoDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationNaverPayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationNaverPayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationNaverPayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationNaverPay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationNaverPayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationNzBankAccountDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationNzBankAccountDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationNzBankAccountDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationNzBankAccount struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationNzBankAccountDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationOXXODisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationOXXODisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationOXXODisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationOXXO struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationOXXODisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationP24DisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationP24DisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationP24DisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationP24 struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationP24DisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationPayByBankDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationPayByBankDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationPayByBankDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationPayByBank struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationPayByBankDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationPaycoDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationPaycoDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationPaycoDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationPayco struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationPaycoDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationPayNowDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationPayNowDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationPayNowDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationPayNow struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationPayNowDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationPaypalDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationPaypalDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationPaypalDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationPaypal struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationPaypalDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationPixDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationPixDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationPixDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationPix struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationPixDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationPromptPayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationPromptPayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationPromptPayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationPromptPay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationPromptPayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationRevolutPayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationRevolutPayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationRevolutPayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationRevolutPay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationRevolutPayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationSamsungPayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationSamsungPayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationSamsungPayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationSamsungPay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationSamsungPayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationSatispayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationSatispayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationSatispayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationSatispay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationSatispayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationSEPADebitDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationSEPADebitDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationSEPADebitDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationSEPADebit struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationSEPADebitDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationSofortDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationSofortDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationSofortDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationSofort struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationSofortDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationSwishDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationSwishDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationSwishDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationSwish struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationSwishDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationTWINTDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationTWINTDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationTWINTDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationTWINT struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationTWINTDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationUSBankAccountDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationUSBankAccountDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationUSBankAccountDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationUSBankAccount struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationUSBankAccountDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationWeChatPayDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationWeChatPayDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationWeChatPayDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationWeChatPay struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationWeChatPayDisplayPreference `json:"display_preference"` +} +type PaymentMethodConfigurationZipDisplayPreference struct { + // For child configs, whether or not the account's preference will be observed. If `false`, the parent configuration's default is used. + Overridable bool `json:"overridable"` + // The account's display preference. + Preference PaymentMethodConfigurationZipDisplayPreferencePreference `json:"preference"` + // The effective display preference value. + Value PaymentMethodConfigurationZipDisplayPreferenceValue `json:"value"` +} +type PaymentMethodConfigurationZip struct { + // Whether this payment method may be offered at checkout. True if `display_preference` is `on` and the payment method's capability is active. + Available bool `json:"available"` + DisplayPreference *PaymentMethodConfigurationZipDisplayPreference `json:"display_preference"` +} + +// PaymentMethodConfigurations control which payment methods are displayed to your customers when you don't explicitly specify payment method types. You can have multiple configurations with different sets of payment methods for different scenarios. +// +// There are two types of PaymentMethodConfigurations. Which is used depends on the [charge type](https://stripe.com/docs/connect/charges): +// +// **Direct** configurations apply to payments created on your account, including Connect destination charges, Connect separate charges and transfers, and payments not involving Connect. +// +// **Child** configurations apply to payments created on your connected accounts using direct charges, and charges with the on_behalf_of parameter. +// +// Child configurations have a `parent` that sets default values and controls which settings connected accounts may override. You can specify a parent ID at payment time, and Stripe will automatically resolve the connected account's associated child configuration. Parent configurations are [managed in the dashboard](https://dashboard.stripe.com/settings/payment_methods/connected_accounts) and are not available in this API. +// +// Related guides: +// - [Payment Method Configurations API](https://stripe.com/docs/connect/payment-method-configurations) +// - [Multiple configurations on dynamic payment methods](https://stripe.com/docs/payments/multiple-payment-method-configs) +// - [Multiple configurations for your Connect accounts](https://stripe.com/docs/connect/multiple-payment-method-configurations) +type PaymentMethodConfiguration struct { + APIResource + ACSSDebit *PaymentMethodConfigurationACSSDebit `json:"acss_debit"` + // Whether the configuration can be used for new payments. + Active bool `json:"active"` + Affirm *PaymentMethodConfigurationAffirm `json:"affirm"` + AfterpayClearpay *PaymentMethodConfigurationAfterpayClearpay `json:"afterpay_clearpay"` + Alipay *PaymentMethodConfigurationAlipay `json:"alipay"` + Alma *PaymentMethodConfigurationAlma `json:"alma"` + AmazonPay *PaymentMethodConfigurationAmazonPay `json:"amazon_pay"` + ApplePay *PaymentMethodConfigurationApplePay `json:"apple_pay"` + // For child configs, the Connect application associated with the configuration. + Application string `json:"application"` + AUBECSDebit *PaymentMethodConfigurationAUBECSDebit `json:"au_becs_debit"` + BACSDebit *PaymentMethodConfigurationBACSDebit `json:"bacs_debit"` + Bancontact *PaymentMethodConfigurationBancontact `json:"bancontact"` + Billie *PaymentMethodConfigurationBillie `json:"billie"` + BLIK *PaymentMethodConfigurationBLIK `json:"blik"` + Boleto *PaymentMethodConfigurationBoleto `json:"boleto"` + Card *PaymentMethodConfigurationCard `json:"card"` + CartesBancaires *PaymentMethodConfigurationCartesBancaires `json:"cartes_bancaires"` + CashApp *PaymentMethodConfigurationCashApp `json:"cashapp"` + CustomerBalance *PaymentMethodConfigurationCustomerBalance `json:"customer_balance"` + EPS *PaymentMethodConfigurationEPS `json:"eps"` + FPX *PaymentMethodConfigurationFPX `json:"fpx"` + Giropay *PaymentMethodConfigurationGiropay `json:"giropay"` + GooglePay *PaymentMethodConfigurationGooglePay `json:"google_pay"` + Grabpay *PaymentMethodConfigurationGrabpay `json:"grabpay"` + // Unique identifier for the object. + ID string `json:"id"` + IDEAL *PaymentMethodConfigurationIDEAL `json:"ideal"` + // The default configuration is used whenever a payment method configuration is not specified. + IsDefault bool `json:"is_default"` + JCB *PaymentMethodConfigurationJCB `json:"jcb"` + KakaoPay *PaymentMethodConfigurationKakaoPay `json:"kakao_pay"` + Klarna *PaymentMethodConfigurationKlarna `json:"klarna"` + Konbini *PaymentMethodConfigurationKonbini `json:"konbini"` + KrCard *PaymentMethodConfigurationKrCard `json:"kr_card"` + Link *PaymentMethodConfigurationLink `json:"link"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + Mobilepay *PaymentMethodConfigurationMobilepay `json:"mobilepay"` + Multibanco *PaymentMethodConfigurationMultibanco `json:"multibanco"` + // The configuration's name. + Name string `json:"name"` + NaverPay *PaymentMethodConfigurationNaverPay `json:"naver_pay"` + NzBankAccount *PaymentMethodConfigurationNzBankAccount `json:"nz_bank_account"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + OXXO *PaymentMethodConfigurationOXXO `json:"oxxo"` + P24 *PaymentMethodConfigurationP24 `json:"p24"` + // For child configs, the configuration's parent configuration. + Parent string `json:"parent"` + PayByBank *PaymentMethodConfigurationPayByBank `json:"pay_by_bank"` + Payco *PaymentMethodConfigurationPayco `json:"payco"` + PayNow *PaymentMethodConfigurationPayNow `json:"paynow"` + Paypal *PaymentMethodConfigurationPaypal `json:"paypal"` + Pix *PaymentMethodConfigurationPix `json:"pix"` + PromptPay *PaymentMethodConfigurationPromptPay `json:"promptpay"` + RevolutPay *PaymentMethodConfigurationRevolutPay `json:"revolut_pay"` + SamsungPay *PaymentMethodConfigurationSamsungPay `json:"samsung_pay"` + Satispay *PaymentMethodConfigurationSatispay `json:"satispay"` + SEPADebit *PaymentMethodConfigurationSEPADebit `json:"sepa_debit"` + Sofort *PaymentMethodConfigurationSofort `json:"sofort"` + Swish *PaymentMethodConfigurationSwish `json:"swish"` + TWINT *PaymentMethodConfigurationTWINT `json:"twint"` + USBankAccount *PaymentMethodConfigurationUSBankAccount `json:"us_bank_account"` + WeChatPay *PaymentMethodConfigurationWeChatPay `json:"wechat_pay"` + Zip *PaymentMethodConfigurationZip `json:"zip"` +} + +// PaymentMethodConfigurationList is a list of PaymentMethodConfigurations as retrieved from a list endpoint. +type PaymentMethodConfigurationList struct { + APIResource + ListMeta + Data []*PaymentMethodConfiguration `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/paymentmethodconfiguration_service.go b/vendor/github.com/stripe/stripe-go/v82/paymentmethodconfiguration_service.go new file mode 100644 index 00000000..831ce131 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/paymentmethodconfiguration_service.go @@ -0,0 +1,75 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1PaymentMethodConfigurationService is used to invoke /v1/payment_method_configurations APIs. +type v1PaymentMethodConfigurationService struct { + B Backend + Key string +} + +// Creates a payment method configuration +func (c v1PaymentMethodConfigurationService) Create(ctx context.Context, params *PaymentMethodConfigurationCreateParams) (*PaymentMethodConfiguration, error) { + if params == nil { + params = &PaymentMethodConfigurationCreateParams{} + } + params.Context = ctx + paymentmethodconfiguration := &PaymentMethodConfiguration{} + err := c.B.Call( + http.MethodPost, "/v1/payment_method_configurations", c.Key, params, paymentmethodconfiguration) + return paymentmethodconfiguration, err +} + +// Retrieve payment method configuration +func (c v1PaymentMethodConfigurationService) Retrieve(ctx context.Context, id string, params *PaymentMethodConfigurationRetrieveParams) (*PaymentMethodConfiguration, error) { + if params == nil { + params = &PaymentMethodConfigurationRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_method_configurations/%s", id) + paymentmethodconfiguration := &PaymentMethodConfiguration{} + err := c.B.Call( + http.MethodGet, path, c.Key, params, paymentmethodconfiguration) + return paymentmethodconfiguration, err +} + +// Update payment method configuration +func (c v1PaymentMethodConfigurationService) Update(ctx context.Context, id string, params *PaymentMethodConfigurationUpdateParams) (*PaymentMethodConfiguration, error) { + if params == nil { + params = &PaymentMethodConfigurationUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_method_configurations/%s", id) + paymentmethodconfiguration := &PaymentMethodConfiguration{} + err := c.B.Call( + http.MethodPost, path, c.Key, params, paymentmethodconfiguration) + return paymentmethodconfiguration, err +} + +// List payment method configurations +func (c v1PaymentMethodConfigurationService) List(ctx context.Context, listParams *PaymentMethodConfigurationListParams) Seq2[*PaymentMethodConfiguration, error] { + if listParams == nil { + listParams = &PaymentMethodConfigurationListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*PaymentMethodConfiguration, ListContainer, error) { + list := &PaymentMethodConfigurationList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/payment_method_configurations", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/paymentmethoddomain.go b/vendor/github.com/stripe/stripe-go/v82/paymentmethoddomain.go new file mode 100644 index 00000000..4f17bddb --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/paymentmethoddomain.go @@ -0,0 +1,275 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The status of the payment method on the domain. +type PaymentMethodDomainAmazonPayStatus string + +// List of values that PaymentMethodDomainAmazonPayStatus can take +const ( + PaymentMethodDomainAmazonPayStatusActive PaymentMethodDomainAmazonPayStatus = "active" + PaymentMethodDomainAmazonPayStatusInactive PaymentMethodDomainAmazonPayStatus = "inactive" +) + +// The status of the payment method on the domain. +type PaymentMethodDomainApplePayStatus string + +// List of values that PaymentMethodDomainApplePayStatus can take +const ( + PaymentMethodDomainApplePayStatusActive PaymentMethodDomainApplePayStatus = "active" + PaymentMethodDomainApplePayStatusInactive PaymentMethodDomainApplePayStatus = "inactive" +) + +// The status of the payment method on the domain. +type PaymentMethodDomainGooglePayStatus string + +// List of values that PaymentMethodDomainGooglePayStatus can take +const ( + PaymentMethodDomainGooglePayStatusActive PaymentMethodDomainGooglePayStatus = "active" + PaymentMethodDomainGooglePayStatusInactive PaymentMethodDomainGooglePayStatus = "inactive" +) + +// The status of the payment method on the domain. +type PaymentMethodDomainKlarnaStatus string + +// List of values that PaymentMethodDomainKlarnaStatus can take +const ( + PaymentMethodDomainKlarnaStatusActive PaymentMethodDomainKlarnaStatus = "active" + PaymentMethodDomainKlarnaStatusInactive PaymentMethodDomainKlarnaStatus = "inactive" +) + +// The status of the payment method on the domain. +type PaymentMethodDomainLinkStatus string + +// List of values that PaymentMethodDomainLinkStatus can take +const ( + PaymentMethodDomainLinkStatusActive PaymentMethodDomainLinkStatus = "active" + PaymentMethodDomainLinkStatusInactive PaymentMethodDomainLinkStatus = "inactive" +) + +// The status of the payment method on the domain. +type PaymentMethodDomainPaypalStatus string + +// List of values that PaymentMethodDomainPaypalStatus can take +const ( + PaymentMethodDomainPaypalStatusActive PaymentMethodDomainPaypalStatus = "active" + PaymentMethodDomainPaypalStatusInactive PaymentMethodDomainPaypalStatus = "inactive" +) + +// Lists the details of existing payment method domains. +type PaymentMethodDomainListParams struct { + ListParams `form:"*"` + // The domain name that this payment method domain object represents. + DomainName *string `form:"domain_name"` + // Whether this payment method domain is enabled. If the domain is not enabled, payment methods will not appear in Elements or Embedded Checkout + Enabled *bool `form:"enabled"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodDomainListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates a payment method domain. +type PaymentMethodDomainParams struct { + Params `form:"*"` + // The domain name that this payment method domain object represents. + DomainName *string `form:"domain_name"` + // Whether this payment method domain is enabled. If the domain is not enabled, payment methods that require a payment method domain will not appear in Elements or Embedded Checkout. + Enabled *bool `form:"enabled"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodDomainParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Some payment methods might require additional steps to register a domain. If the requirements weren't satisfied when the domain was created, the payment method will be inactive on the domain. +// The payment method doesn't appear in Elements or Embedded Checkout for this domain until it is active. +// +// To activate a payment method on an existing payment method domain, complete the required registration steps specific to the payment method, and then validate the payment method domain with this endpoint. +// +// Related guides: [Payment method domains](https://docs.stripe.com/docs/payments/payment-methods/pmd-registration). +type PaymentMethodDomainValidateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodDomainValidateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates a payment method domain. +type PaymentMethodDomainCreateParams struct { + Params `form:"*"` + // The domain name that this payment method domain object represents. + DomainName *string `form:"domain_name"` + // Whether this payment method domain is enabled. If the domain is not enabled, payment methods that require a payment method domain will not appear in Elements or Embedded Checkout. + Enabled *bool `form:"enabled"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodDomainCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an existing payment method domain. +type PaymentMethodDomainRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodDomainRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates an existing payment method domain. +type PaymentMethodDomainUpdateParams struct { + Params `form:"*"` + // Whether this payment method domain is enabled. If the domain is not enabled, payment methods that require a payment method domain will not appear in Elements or Embedded Checkout. + Enabled *bool `form:"enabled"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentMethodDomainUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Contains additional details about the status of a payment method for a specific payment method domain. +type PaymentMethodDomainAmazonPayStatusDetails struct { + // The error message associated with the status of the payment method on the domain. + ErrorMessage string `json:"error_message"` +} + +// Indicates the status of a specific payment method on a payment method domain. +type PaymentMethodDomainAmazonPay struct { + // The status of the payment method on the domain. + Status PaymentMethodDomainAmazonPayStatus `json:"status"` + // Contains additional details about the status of a payment method for a specific payment method domain. + StatusDetails *PaymentMethodDomainAmazonPayStatusDetails `json:"status_details"` +} + +// Contains additional details about the status of a payment method for a specific payment method domain. +type PaymentMethodDomainApplePayStatusDetails struct { + // The error message associated with the status of the payment method on the domain. + ErrorMessage string `json:"error_message"` +} + +// Indicates the status of a specific payment method on a payment method domain. +type PaymentMethodDomainApplePay struct { + // The status of the payment method on the domain. + Status PaymentMethodDomainApplePayStatus `json:"status"` + // Contains additional details about the status of a payment method for a specific payment method domain. + StatusDetails *PaymentMethodDomainApplePayStatusDetails `json:"status_details"` +} + +// Contains additional details about the status of a payment method for a specific payment method domain. +type PaymentMethodDomainGooglePayStatusDetails struct { + // The error message associated with the status of the payment method on the domain. + ErrorMessage string `json:"error_message"` +} + +// Indicates the status of a specific payment method on a payment method domain. +type PaymentMethodDomainGooglePay struct { + // The status of the payment method on the domain. + Status PaymentMethodDomainGooglePayStatus `json:"status"` + // Contains additional details about the status of a payment method for a specific payment method domain. + StatusDetails *PaymentMethodDomainGooglePayStatusDetails `json:"status_details"` +} + +// Contains additional details about the status of a payment method for a specific payment method domain. +type PaymentMethodDomainKlarnaStatusDetails struct { + // The error message associated with the status of the payment method on the domain. + ErrorMessage string `json:"error_message"` +} + +// Indicates the status of a specific payment method on a payment method domain. +type PaymentMethodDomainKlarna struct { + // The status of the payment method on the domain. + Status PaymentMethodDomainKlarnaStatus `json:"status"` + // Contains additional details about the status of a payment method for a specific payment method domain. + StatusDetails *PaymentMethodDomainKlarnaStatusDetails `json:"status_details"` +} + +// Contains additional details about the status of a payment method for a specific payment method domain. +type PaymentMethodDomainLinkStatusDetails struct { + // The error message associated with the status of the payment method on the domain. + ErrorMessage string `json:"error_message"` +} + +// Indicates the status of a specific payment method on a payment method domain. +type PaymentMethodDomainLink struct { + // The status of the payment method on the domain. + Status PaymentMethodDomainLinkStatus `json:"status"` + // Contains additional details about the status of a payment method for a specific payment method domain. + StatusDetails *PaymentMethodDomainLinkStatusDetails `json:"status_details"` +} + +// Contains additional details about the status of a payment method for a specific payment method domain. +type PaymentMethodDomainPaypalStatusDetails struct { + // The error message associated with the status of the payment method on the domain. + ErrorMessage string `json:"error_message"` +} + +// Indicates the status of a specific payment method on a payment method domain. +type PaymentMethodDomainPaypal struct { + // The status of the payment method on the domain. + Status PaymentMethodDomainPaypalStatus `json:"status"` + // Contains additional details about the status of a payment method for a specific payment method domain. + StatusDetails *PaymentMethodDomainPaypalStatusDetails `json:"status_details"` +} + +// A payment method domain represents a web domain that you have registered with Stripe. +// Stripe Elements use registered payment method domains to control where certain payment methods are shown. +// +// Related guide: [Payment method domains](https://stripe.com/docs/payments/payment-methods/pmd-registration). +type PaymentMethodDomain struct { + APIResource + // Indicates the status of a specific payment method on a payment method domain. + AmazonPay *PaymentMethodDomainAmazonPay `json:"amazon_pay"` + // Indicates the status of a specific payment method on a payment method domain. + ApplePay *PaymentMethodDomainApplePay `json:"apple_pay"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The domain name that this payment method domain object represents. + DomainName string `json:"domain_name"` + // Whether this payment method domain is enabled. If the domain is not enabled, payment methods that require a payment method domain will not appear in Elements. + Enabled bool `json:"enabled"` + // Indicates the status of a specific payment method on a payment method domain. + GooglePay *PaymentMethodDomainGooglePay `json:"google_pay"` + // Unique identifier for the object. + ID string `json:"id"` + // Indicates the status of a specific payment method on a payment method domain. + Klarna *PaymentMethodDomainKlarna `json:"klarna"` + // Indicates the status of a specific payment method on a payment method domain. + Link *PaymentMethodDomainLink `json:"link"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Indicates the status of a specific payment method on a payment method domain. + Paypal *PaymentMethodDomainPaypal `json:"paypal"` +} + +// PaymentMethodDomainList is a list of PaymentMethodDomains as retrieved from a list endpoint. +type PaymentMethodDomainList struct { + APIResource + ListMeta + Data []*PaymentMethodDomain `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/paymentmethoddomain_service.go b/vendor/github.com/stripe/stripe-go/v82/paymentmethoddomain_service.go new file mode 100644 index 00000000..05dbbd12 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/paymentmethoddomain_service.go @@ -0,0 +1,90 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1PaymentMethodDomainService is used to invoke /v1/payment_method_domains APIs. +type v1PaymentMethodDomainService struct { + B Backend + Key string +} + +// Creates a payment method domain. +func (c v1PaymentMethodDomainService) Create(ctx context.Context, params *PaymentMethodDomainCreateParams) (*PaymentMethodDomain, error) { + if params == nil { + params = &PaymentMethodDomainCreateParams{} + } + params.Context = ctx + paymentmethoddomain := &PaymentMethodDomain{} + err := c.B.Call( + http.MethodPost, "/v1/payment_method_domains", c.Key, params, paymentmethoddomain) + return paymentmethoddomain, err +} + +// Retrieves the details of an existing payment method domain. +func (c v1PaymentMethodDomainService) Retrieve(ctx context.Context, id string, params *PaymentMethodDomainRetrieveParams) (*PaymentMethodDomain, error) { + if params == nil { + params = &PaymentMethodDomainRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_method_domains/%s", id) + paymentmethoddomain := &PaymentMethodDomain{} + err := c.B.Call(http.MethodGet, path, c.Key, params, paymentmethoddomain) + return paymentmethoddomain, err +} + +// Updates an existing payment method domain. +func (c v1PaymentMethodDomainService) Update(ctx context.Context, id string, params *PaymentMethodDomainUpdateParams) (*PaymentMethodDomain, error) { + if params == nil { + params = &PaymentMethodDomainUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_method_domains/%s", id) + paymentmethoddomain := &PaymentMethodDomain{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentmethoddomain) + return paymentmethoddomain, err +} + +// Some payment methods might require additional steps to register a domain. If the requirements weren't satisfied when the domain was created, the payment method will be inactive on the domain. +// The payment method doesn't appear in Elements or Embedded Checkout for this domain until it is active. +// +// To activate a payment method on an existing payment method domain, complete the required registration steps specific to the payment method, and then validate the payment method domain with this endpoint. +// +// Related guides: [Payment method domains](https://docs.stripe.com/docs/payments/payment-methods/pmd-registration). +func (c v1PaymentMethodDomainService) Validate(ctx context.Context, id string, params *PaymentMethodDomainValidateParams) (*PaymentMethodDomain, error) { + if params == nil { + params = &PaymentMethodDomainValidateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payment_method_domains/%s/validate", id) + paymentmethoddomain := &PaymentMethodDomain{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentmethoddomain) + return paymentmethoddomain, err +} + +// Lists the details of existing payment method domains. +func (c v1PaymentMethodDomainService) List(ctx context.Context, listParams *PaymentMethodDomainListParams) Seq2[*PaymentMethodDomain, error] { + if listParams == nil { + listParams = &PaymentMethodDomainListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*PaymentMethodDomain, ListContainer, error) { + list := &PaymentMethodDomainList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/payment_method_domains", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/paymentsource.go b/vendor/github.com/stripe/stripe-go/v82/paymentsource.go new file mode 100644 index 00000000..d575c253 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/paymentsource.go @@ -0,0 +1,371 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "encoding/json" + "fmt" + "github.com/stripe/stripe-go/v82/form" +) + +type PaymentSourceType string + +// List of values that PaymentSourceType can take +const ( + PaymentSourceTypeAccount PaymentSourceType = "account" + PaymentSourceTypeBankAccount PaymentSourceType = "bank_account" + PaymentSourceTypeCard PaymentSourceType = "card" + PaymentSourceTypeSource PaymentSourceType = "source" +) + +// List sources for a specified customer. +type PaymentSourceListParams struct { + ListParams `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Filter sources according to a particular object type. + Object *string `form:"object"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentSourceListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// PaymentSourceSourceParams is a union struct used to describe an +// arbitrary payment source. +type PaymentSourceSourceParams struct { + Card *CardParams `form:"-"` + Token *string `form:"source"` +} + +// AppendTo implements custom encoding logic for PaymentSourceSourceParams. +func (p *PaymentSourceSourceParams) AppendTo(body *form.Values, keyParts []string) { + if p.Card != nil { + p.Card.AppendToAsCardSourceOrExternalAccount(body, keyParts) + } +} + +// SourceParamsFor creates PaymentSourceSourceParams objects around supported +// payment sources, returning errors if not. +// +// Currently supported payment source types are Card (CardParams) and +// Tokens/IDs (string), where Tokens could be single use card +// tokens +func SourceParamsFor(obj interface{}) (*PaymentSourceSourceParams, error) { + var sp *PaymentSourceSourceParams + var err error + switch p := obj.(type) { + case *CardParams: + sp = &PaymentSourceSourceParams{ + Card: p, + } + case string: + sp = &PaymentSourceSourceParams{ + Token: &p, + } + default: + err = fmt.Errorf("Unsupported source type %s", p) + } + return sp, err +} + +// When you create a new credit card, you must specify a customer or recipient on which to create it. +// +// If the card's owner has no default card, then the new card will become the default. +// However, if the owner already has a default, then it will not change. +// To change the default, you should [update the customer](https://docs.stripe.com/docs/api#update_customer) to have a new default_source. +type PaymentSourceParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // The name of the person or business that owns the bank account. + AccountHolderName *string `form:"account_holder_name"` + // The type of entity that holds the account. This can be either `individual` or `company`. + AccountHolderType *string `form:"account_holder_type"` + // City/District/Suburb/Town/Village. + AddressCity *string `form:"address_city"` + // Billing address country, if provided when creating card. + AddressCountry *string `form:"address_country"` + // Address line 1 (Street address/PO Box/Company name). + AddressLine1 *string `form:"address_line1"` + // Address line 2 (Apartment/Suite/Unit/Building). + AddressLine2 *string `form:"address_line2"` + // State/County/Province/Region. + AddressState *string `form:"address_state"` + // ZIP or postal code. + AddressZip *string `form:"address_zip"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Two digit number representing the card's expiration month. + ExpMonth *string `form:"exp_month"` + // Four digit number representing the card's expiration year. + ExpYear *string `form:"exp_year"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Cardholder name. + Name *string `form:"name"` + Owner *PaymentSourceOwnerParams `form:"owner"` + // Please refer to full [documentation](https://stripe.com/docs/api) instead. + Source *PaymentSourceSourceParams `form:"*"` // PaymentSourceSourceParams has custom encoding so brought to top level with "*" + Validate *bool `form:"validate"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentSourceParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentSourceParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +type PaymentSourceOwnerParams struct { + // Owner's address. + Address *AddressParams `form:"address"` + // Owner's email address. + Email *string `form:"email"` + // Owner's full name. + Name *string `form:"name"` + // Owner's phone number. + Phone *string `form:"phone"` +} + +// Verify a specified bank account for a given customer. +type PaymentSourceVerifyParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // Two positive integers, in *cents*, equal to the values of the microdeposits sent to the bank account. + Amounts [2]int64 `form:"amounts"` // Amounts is used when verifying bank accounts + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + Values []*string `form:"values"` // Values is used when verifying sources +} + +// AddExpand appends a new field to expand. +func (p *PaymentSourceVerifyParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When you create a new credit card, you must specify a customer or recipient on which to create it. +// +// If the card's owner has no default card, then the new card will become the default. +// However, if the owner already has a default, then it will not change. +// To change the default, you should [update the customer](https://docs.stripe.com/docs/api#update_customer) to have a new default_source. +type PaymentSourceCreateParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Please refer to full [documentation](https://stripe.com/docs/api) instead. + Source *PaymentSourceSourceParams `form:"*"` // PaymentSourceSourceParams has custom encoding so brought to top level with "*" + Validate *bool `form:"validate"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentSourceCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentSourceCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieve a specified source for a given customer. +type PaymentSourceRetrieveParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentSourceRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type PaymentSourceUpdateOwnerParams struct { + // Owner's address. + Address *AddressParams `form:"address"` + // Owner's email address. + Email *string `form:"email"` + // Owner's full name. + Name *string `form:"name"` + // Owner's phone number. + Phone *string `form:"phone"` +} + +// Update a specified source for a given customer. +type PaymentSourceUpdateParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // The name of the person or business that owns the bank account. + AccountHolderName *string `form:"account_holder_name"` + // The type of entity that holds the account. This can be either `individual` or `company`. + AccountHolderType *string `form:"account_holder_type"` + // City/District/Suburb/Town/Village. + AddressCity *string `form:"address_city"` + // Billing address country, if provided when creating card. + AddressCountry *string `form:"address_country"` + // Address line 1 (Street address/PO Box/Company name). + AddressLine1 *string `form:"address_line1"` + // Address line 2 (Apartment/Suite/Unit/Building). + AddressLine2 *string `form:"address_line2"` + // State/County/Province/Region. + AddressState *string `form:"address_state"` + // ZIP or postal code. + AddressZip *string `form:"address_zip"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Two digit number representing the card's expiration month. + ExpMonth *string `form:"exp_month"` + // Four digit number representing the card's expiration year. + ExpYear *string `form:"exp_year"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Cardholder name. + Name *string `form:"name"` + Owner *PaymentSourceUpdateOwnerParams `form:"owner"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentSourceUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PaymentSourceUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Delete a specified source for a given customer. +type PaymentSourceDeleteParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PaymentSourceDeleteParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type PaymentSource struct { + APIResource + BankAccount *BankAccount `json:"-"` + Card *Card `json:"-"` + Deleted bool `json:"deleted"` + ID string `json:"id"` + Source *Source `json:"-"` + Type PaymentSourceType `json:"object"` +} + +// PaymentSourceList is a list of PaymentSources as retrieved from a list endpoint. +type PaymentSourceList struct { + APIResource + ListMeta + Data []*PaymentSource `json:"data"` +} + +// UnmarshalJSON handles deserialization of a PaymentSource. +// This custom unmarshaling is needed because the specific +// type of payment instrument it refers to is specified in the JSON +func (s *PaymentSource) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + s.ID = id + return nil + } + + type paymentSource PaymentSource + var v paymentSource + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + var err error + *s = PaymentSource(v) + + switch s.Type { + case PaymentSourceTypeBankAccount: + err = json.Unmarshal(data, &s.BankAccount) + case PaymentSourceTypeCard: + err = json.Unmarshal(data, &s.Card) + case PaymentSourceTypeSource: + err = json.Unmarshal(data, &s.Source) + } + + return err +} + +// MarshalJSON handles serialization of a PaymentSource. +// This custom marshaling is needed because the specific type +// of payment instrument it represents is specified by the Type +func (s *PaymentSource) MarshalJSON() ([]byte, error) { + var target interface{} + + switch s.Type { + case PaymentSourceTypeCard: + var customerID *string + if s.Card.Customer != nil { + customerID = &s.Card.Customer.ID + } + + target = struct { + *Card + Customer *string `json:"customer"` + Type PaymentSourceType `json:"object"` + }{ + Card: s.Card, + Customer: customerID, + Type: s.Type, + } + case PaymentSourceTypeAccount: + target = struct { + ID string `json:"id"` + Type PaymentSourceType `json:"object"` + }{ + ID: s.ID, + Type: s.Type, + } + case PaymentSourceTypeBankAccount: + var customerID *string + if s.BankAccount.Customer != nil { + customerID = &s.BankAccount.Customer.ID + } + + target = struct { + *BankAccount + Customer *string `json:"customer"` + Type PaymentSourceType `json:"object"` + }{ + BankAccount: s.BankAccount, + Customer: customerID, + Type: s.Type, + } + case "": + target = s.ID + } + + return json.Marshal(target) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/paymentsource_service.go b/vendor/github.com/stripe/stripe-go/v82/paymentsource_service.go new file mode 100644 index 00000000..b9dfa2c7 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/paymentsource_service.go @@ -0,0 +1,116 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "fmt" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1PaymentSourceService is used to invoke /v1/customers/{customer}/sources APIs. +type v1PaymentSourceService struct { + B Backend + Key string +} + +// When you create a new credit card, you must specify a customer or recipient on which to create it. +// +// If the card's owner has no default card, then the new card will become the default. +// However, if the owner already has a default, then it will not change. +// To change the default, you should [update the customer](https://docs.stripe.com/docs/api#update_customer) to have a new default_source. +func (c v1PaymentSourceService) Create(ctx context.Context, params *PaymentSourceCreateParams) (*PaymentSource, error) { + if params == nil { + params = &PaymentSourceCreateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/sources", StringValue(params.Customer)) + paymentsource := &PaymentSource{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentsource) + return paymentsource, err +} + +// Retrieve a specified source for a given customer. +func (c v1PaymentSourceService) Retrieve(ctx context.Context, id string, params *PaymentSourceRetrieveParams) (*PaymentSource, error) { + if params == nil { + params = &PaymentSourceRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/sources/%s", StringValue(params.Customer), id) + paymentsource := &PaymentSource{} + err := c.B.Call(http.MethodGet, path, c.Key, params, paymentsource) + return paymentsource, err +} + +// Update a specified source for a given customer. +func (c v1PaymentSourceService) Update(ctx context.Context, id string, params *PaymentSourceUpdateParams) (*PaymentSource, error) { + if params == nil { + return nil, fmt.Errorf("params should not be nil") + } + if params.Customer == nil { + return nil, fmt.Errorf("Invalid source params: customer needs to be set") + } + if params == nil { + params = &PaymentSourceUpdateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/sources/%s", StringValue(params.Customer), id) + paymentsource := &PaymentSource{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentsource) + return paymentsource, err +} + +// Delete a specified source for a given customer. +func (c v1PaymentSourceService) Delete(ctx context.Context, id string, params *PaymentSourceDeleteParams) (*PaymentSource, error) { + if params == nil { + params = &PaymentSourceDeleteParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/sources/%s", StringValue(params.Customer), id) + paymentsource := &PaymentSource{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, paymentsource) + return paymentsource, err +} + +// Verify verifies a source which is used for bank accounts. +// Verify a specified bank account for a given customer. +func (c v1PaymentSourceService) Verify(ctx context.Context, id string, params *PaymentSourceVerifyParams) (*PaymentSource, error) { + if params == nil { + params = &PaymentSourceVerifyParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/sources/%s/verify", StringValue(params.Customer), id) + paymentsource := &PaymentSource{} + err := c.B.Call(http.MethodPost, path, c.Key, params, paymentsource) + return paymentsource, err +} + +// List sources for a specified customer. +func (c v1PaymentSourceService) List(ctx context.Context, listParams *PaymentSourceListParams) Seq2[*PaymentSource, error] { + if listParams == nil { + listParams = &PaymentSourceListParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/sources", StringValue(listParams.Customer)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*PaymentSource, ListContainer, error) { + list := &PaymentSourceList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/payout.go b/vendor/github.com/stripe/stripe-go/v82/payout.go new file mode 100644 index 00000000..a576b791 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/payout.go @@ -0,0 +1,399 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +type PayoutDestinationType string + +// List of values that PayoutDestinationType can take +const ( + PayoutDestinationTypeBankAccount PayoutDestinationType = "bank_account" + PayoutDestinationTypeCard PayoutDestinationType = "card" +) + +// Error code that provides a reason for a payout failure, if available. View our [list of failure codes](https://stripe.com/docs/api#payout_failures). +type PayoutFailureCode string + +// List of values that PayoutFailureCode can take +const ( + PayoutFailureCodeAccountClosed PayoutFailureCode = "account_closed" + PayoutFailureCodeAccountFrozen PayoutFailureCode = "account_frozen" + PayoutFailureCodeBankAccountRestricted PayoutFailureCode = "bank_account_restricted" + PayoutFailureCodeBankOwnershipChanged PayoutFailureCode = "bank_ownership_changed" + PayoutFailureCodeCouldNotProcess PayoutFailureCode = "could_not_process" + PayoutFailureCodeDebitNotAuthorized PayoutFailureCode = "debit_not_authorized" + PayoutFailureCodeDeclined PayoutFailureCode = "declined" + PayoutFailureCodeInsufficientFunds PayoutFailureCode = "insufficient_funds" + PayoutFailureCodeInvalidAccountNumber PayoutFailureCode = "invalid_account_number" + PayoutFailureCodeIncorrectAccountHolderName PayoutFailureCode = "incorrect_account_holder_name" + PayoutFailureCodeIncorrectAccountHolderAddress PayoutFailureCode = "incorrect_account_holder_address" + PayoutFailureCodeIncorrectAccountHolderTaxID PayoutFailureCode = "incorrect_account_holder_tax_id" + PayoutFailureCodeInvalidCurrency PayoutFailureCode = "invalid_currency" + PayoutFailureCodeNoAccount PayoutFailureCode = "no_account" + PayoutFailureCodeUnsupportedCard PayoutFailureCode = "unsupported_card" +) + +// The method used to send this payout, which can be `standard` or `instant`. `instant` is supported for payouts to debit cards and bank accounts in certain countries. Learn more about [bank support for Instant Payouts](https://stripe.com/docs/payouts/instant-payouts-banks). +type PayoutMethodType string + +// List of values that PayoutMethodType can take +const ( + PayoutMethodInstant PayoutMethodType = "instant" + PayoutMethodStandard PayoutMethodType = "standard" +) + +// If `completed`, you can use the [Balance Transactions API](https://stripe.com/docs/api/balance_transactions/list#balance_transaction_list-payout) to list all balance transactions that are paid out in this payout. +type PayoutReconciliationStatus string + +// List of values that PayoutReconciliationStatus can take +const ( + PayoutReconciliationStatusCompleted PayoutReconciliationStatus = "completed" + PayoutReconciliationStatusInProgress PayoutReconciliationStatus = "in_progress" + PayoutReconciliationStatusNotApplicable PayoutReconciliationStatus = "not_applicable" +) + +// The source balance this payout came from, which can be one of the following: `card`, `fpx`, or `bank_account`. +type PayoutSourceType string + +// List of values that PayoutSourceType can take +const ( + PayoutSourceTypeBankAccount PayoutSourceType = "bank_account" + PayoutSourceTypeCard PayoutSourceType = "card" + PayoutSourceTypeFPX PayoutSourceType = "fpx" +) + +// Current status of the payout: `paid`, `pending`, `in_transit`, `canceled` or `failed`. A payout is `pending` until it's submitted to the bank, when it becomes `in_transit`. The status changes to `paid` if the transaction succeeds, or to `failed` or `canceled` (within 5 business days). Some payouts that fail might initially show as `paid`, then change to `failed`. +type PayoutStatus string + +// List of values that PayoutStatus can take +const ( + PayoutStatusCanceled PayoutStatus = "canceled" + PayoutStatusFailed PayoutStatus = "failed" + PayoutStatusInTransit PayoutStatus = "in_transit" + PayoutStatusPaid PayoutStatus = "paid" + PayoutStatusPending PayoutStatus = "pending" +) + +// Can be `bank_account` or `card`. +type PayoutType string + +// List of values that PayoutType can take +const ( + PayoutTypeBank PayoutType = "bank_account" + PayoutTypeCard PayoutType = "card" +) + +// Returns a list of existing payouts sent to third-party bank accounts or payouts that Stripe sent to you. The payouts return in sorted order, with the most recently created payouts appearing first. +type PayoutListParams struct { + ListParams `form:"*"` + // Only return payouts that are expected to arrive during the given date interval. + ArrivalDate *int64 `form:"arrival_date"` + // Only return payouts that are expected to arrive during the given date interval. + ArrivalDateRange *RangeQueryParams `form:"arrival_date"` + // Only return payouts that were created during the given date interval. + Created *int64 `form:"created"` + // Only return payouts that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // The ID of an external account - only return payouts sent to this external account. + Destination *string `form:"destination"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return payouts that have the given status: `pending`, `paid`, `failed`, or `canceled`. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *PayoutListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// To send funds to your own bank account, create a new payout object. Your [Stripe balance](https://docs.stripe.com/api#balance) must cover the payout amount. If it doesn't, you receive an “Insufficient Funds” error. +// +// If your API key is in test mode, money won't actually be sent, though every other action occurs as if you're in live mode. +// +// If you create a manual payout on a Stripe account that uses multiple payment source types, you need to specify the source type balance that the payout draws from. The [balance object](https://docs.stripe.com/api#balance_object) details available and pending amounts by source type. +type PayoutParams struct { + Params `form:"*"` + // A positive integer in cents representing how much to payout. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // The ID of a bank account or a card to send the payout to. If you don't provide a destination, we use the default external account for the specified currency. + Destination *string `form:"destination"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The method used to send this payout, which is `standard` or `instant`. We support `instant` for payouts to debit cards and bank accounts in certain countries. Learn more about [bank support for Instant Payouts](https://stripe.com/docs/payouts/instant-payouts-banks). + Method *string `form:"method"` + // The balance type of your Stripe balance to draw this payout from. Balances for different payment sources are kept separately. You can find the amounts with the Balances API. One of `bank_account`, `card`, or `fpx`. + SourceType *string `form:"source_type"` + // A string that displays on the recipient's bank or card statement (up to 22 characters). A `statement_descriptor` that's longer than 22 characters return an error. Most banks truncate this information and display it inconsistently. Some banks might not display it at all. + StatementDescriptor *string `form:"statement_descriptor"` +} + +// AddExpand appends a new field to expand. +func (p *PayoutParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PayoutParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Reverses a payout by debiting the destination bank account. At this time, you can only reverse payouts for connected accounts to US bank accounts. If the payout is manual and in the pending status, use /v1/payouts/:id/cancel instead. +// +// By requesting a reversal through /v1/payouts/:id/reverse, you confirm that the authorized signatory of the selected bank account authorizes the debit on the bank account and that no other authorization is required. +type PayoutReverseParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *PayoutReverseParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PayoutReverseParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// To send funds to your own bank account, create a new payout object. Your [Stripe balance](https://docs.stripe.com/api#balance) must cover the payout amount. If it doesn't, you receive an “Insufficient Funds” error. +// +// If your API key is in test mode, money won't actually be sent, though every other action occurs as if you're in live mode. +// +// If you create a manual payout on a Stripe account that uses multiple payment source types, you need to specify the source type balance that the payout draws from. The [balance object](https://docs.stripe.com/api#balance_object) details available and pending amounts by source type. +type PayoutCreateParams struct { + Params `form:"*"` + // A positive integer in cents representing how much to payout. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // The ID of a bank account or a card to send the payout to. If you don't provide a destination, we use the default external account for the specified currency. + Destination *string `form:"destination"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The method used to send this payout, which is `standard` or `instant`. We support `instant` for payouts to debit cards and bank accounts in certain countries. Learn more about [bank support for Instant Payouts](https://stripe.com/docs/payouts/instant-payouts-banks). + Method *string `form:"method"` + // The balance type of your Stripe balance to draw this payout from. Balances for different payment sources are kept separately. You can find the amounts with the Balances API. One of `bank_account`, `card`, or `fpx`. + SourceType *string `form:"source_type"` + // A string that displays on the recipient's bank or card statement (up to 22 characters). A `statement_descriptor` that's longer than 22 characters return an error. Most banks truncate this information and display it inconsistently. Some banks might not display it at all. + StatementDescriptor *string `form:"statement_descriptor"` +} + +// AddExpand appends a new field to expand. +func (p *PayoutCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PayoutCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Cancels a top-up. Only pending top-ups can be canceled. +type PayoutCancelParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PayoutCancelParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an existing payout. Supply the unique payout ID from either a payout creation request or the payout list. Stripe returns the corresponding payout information. +type PayoutRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PayoutRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the specified payout by setting the values of the parameters you pass. We don't change parameters that you don't provide. This request only accepts the metadata as arguments. +type PayoutUpdateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *PayoutUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PayoutUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A value that generates from the beneficiary's bank that allows users to track payouts with their bank. Banks might call this a "reference number" or something similar. +type PayoutTraceID struct { + // Possible values are `pending`, `supported`, and `unsupported`. When `payout.status` is `pending` or `in_transit`, this will be `pending`. When the payout transitions to `paid`, `failed`, or `canceled`, this status will become `supported` or `unsupported` shortly after in most cases. In some cases, this may appear as `pending` for up to 10 days after `arrival_date` until transitioning to `supported` or `unsupported`. + Status string `json:"status"` + // The trace ID value if `trace_id.status` is `supported`, otherwise `nil`. + Value string `json:"value"` +} + +// A `Payout` object is created when you receive funds from Stripe, or when you +// initiate a payout to either a bank account or debit card of a [connected +// Stripe account](https://docs.stripe.com/docs/connect/bank-debit-card-payouts). You can retrieve individual payouts, +// and list all payouts. Payouts are made on [varying +// schedules](https://docs.stripe.com/docs/connect/manage-payout-schedule), depending on your country and +// industry. +// +// Related guide: [Receiving payouts](https://stripe.com/docs/payouts) +type Payout struct { + APIResource + // The amount (in cents (or local equivalent)) that transfers to your bank account or debit card. + Amount int64 `json:"amount"` + // The application fee (if any) for the payout. [See the Connect documentation](https://stripe.com/docs/connect/instant-payouts#monetization-and-fees) for details. + ApplicationFee *ApplicationFee `json:"application_fee"` + // The amount of the application fee (if any) requested for the payout. [See the Connect documentation](https://stripe.com/docs/connect/instant-payouts#monetization-and-fees) for details. + ApplicationFeeAmount int64 `json:"application_fee_amount"` + // Date that you can expect the payout to arrive in the bank. This factors in delays to account for weekends or bank holidays. + ArrivalDate int64 `json:"arrival_date"` + // Returns `true` if the payout is created by an [automated payout schedule](https://stripe.com/docs/payouts#payout-schedule) and `false` if it's [requested manually](https://stripe.com/docs/payouts#manual-payouts). + Automatic bool `json:"automatic"` + // ID of the balance transaction that describes the impact of this payout on your account balance. + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // ID of the bank account or card the payout is sent to. + Destination *PayoutDestination `json:"destination"` + // If the payout fails or cancels, this is the ID of the balance transaction that reverses the initial balance transaction and returns the funds from the failed payout back in your balance. + FailureBalanceTransaction *BalanceTransaction `json:"failure_balance_transaction"` + // Error code that provides a reason for a payout failure, if available. View our [list of failure codes](https://stripe.com/docs/api#payout_failures). + FailureCode PayoutFailureCode `json:"failure_code"` + // Message that provides the reason for a payout failure, if available. + FailureMessage string `json:"failure_message"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // The method used to send this payout, which can be `standard` or `instant`. `instant` is supported for payouts to debit cards and bank accounts in certain countries. Learn more about [bank support for Instant Payouts](https://stripe.com/docs/payouts/instant-payouts-banks). + Method PayoutMethodType `json:"method"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // If the payout reverses another, this is the ID of the original payout. + OriginalPayout *Payout `json:"original_payout"` + // If `completed`, you can use the [Balance Transactions API](https://stripe.com/docs/api/balance_transactions/list#balance_transaction_list-payout) to list all balance transactions that are paid out in this payout. + ReconciliationStatus PayoutReconciliationStatus `json:"reconciliation_status"` + // If the payout reverses, this is the ID of the payout that reverses this payout. + ReversedBy *Payout `json:"reversed_by"` + // The source balance this payout came from, which can be one of the following: `card`, `fpx`, or `bank_account`. + SourceType PayoutSourceType `json:"source_type"` + // Extra information about a payout that displays on the user's bank statement. + StatementDescriptor string `json:"statement_descriptor"` + // Current status of the payout: `paid`, `pending`, `in_transit`, `canceled` or `failed`. A payout is `pending` until it's submitted to the bank, when it becomes `in_transit`. The status changes to `paid` if the transaction succeeds, or to `failed` or `canceled` (within 5 business days). Some payouts that fail might initially show as `paid`, then change to `failed`. + Status PayoutStatus `json:"status"` + // A value that generates from the beneficiary's bank that allows users to track payouts with their bank. Banks might call this a "reference number" or something similar. + TraceID *PayoutTraceID `json:"trace_id"` + // Can be `bank_account` or `card`. + Type PayoutType `json:"type"` +} +type PayoutDestination struct { + ID string `json:"id"` + Type PayoutDestinationType `json:"object"` + + BankAccount *BankAccount `json:"-"` + Card *Card `json:"-"` +} + +// PayoutList is a list of Payouts as retrieved from a list endpoint. +type PayoutList struct { + APIResource + ListMeta + Data []*Payout `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Payout. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (p *Payout) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + p.ID = id + return nil + } + + type payout Payout + var v payout + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *p = Payout(v) + return nil +} + +// UnmarshalJSON handles deserialization of a PayoutDestination. +// This custom unmarshaling is needed because the specific type of +// PayoutDestination it refers to is specified in the JSON +func (p *PayoutDestination) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + p.ID = id + return nil + } + + type payoutDestination PayoutDestination + var v payoutDestination + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *p = PayoutDestination(v) + var err error + + switch p.Type { + case PayoutDestinationTypeBankAccount: + err = json.Unmarshal(data, &p.BankAccount) + case PayoutDestinationTypeCard: + err = json.Unmarshal(data, &p.Card) + } + return err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/payout_service.go b/vendor/github.com/stripe/stripe-go/v82/payout_service.go new file mode 100644 index 00000000..dc1fc3b9 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/payout_service.go @@ -0,0 +1,102 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1PayoutService is used to invoke /v1/payouts APIs. +type v1PayoutService struct { + B Backend + Key string +} + +// To send funds to your own bank account, create a new payout object. Your [Stripe balance](https://docs.stripe.com/api#balance) must cover the payout amount. If it doesn't, you receive an “Insufficient Funds” error. +// +// If your API key is in test mode, money won't actually be sent, though every other action occurs as if you're in live mode. +// +// If you create a manual payout on a Stripe account that uses multiple payment source types, you need to specify the source type balance that the payout draws from. The [balance object](https://docs.stripe.com/api#balance_object) details available and pending amounts by source type. +func (c v1PayoutService) Create(ctx context.Context, params *PayoutCreateParams) (*Payout, error) { + if params == nil { + params = &PayoutCreateParams{} + } + params.Context = ctx + payout := &Payout{} + err := c.B.Call(http.MethodPost, "/v1/payouts", c.Key, params, payout) + return payout, err +} + +// Retrieves the details of an existing payout. Supply the unique payout ID from either a payout creation request or the payout list. Stripe returns the corresponding payout information. +func (c v1PayoutService) Retrieve(ctx context.Context, id string, params *PayoutRetrieveParams) (*Payout, error) { + if params == nil { + params = &PayoutRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payouts/%s", id) + payout := &Payout{} + err := c.B.Call(http.MethodGet, path, c.Key, params, payout) + return payout, err +} + +// Updates the specified payout by setting the values of the parameters you pass. We don't change parameters that you don't provide. This request only accepts the metadata as arguments. +func (c v1PayoutService) Update(ctx context.Context, id string, params *PayoutUpdateParams) (*Payout, error) { + if params == nil { + params = &PayoutUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payouts/%s", id) + payout := &Payout{} + err := c.B.Call(http.MethodPost, path, c.Key, params, payout) + return payout, err +} + +// Cancels a top-up. Only pending top-ups can be canceled. +func (c v1PayoutService) Cancel(ctx context.Context, id string, params *PayoutCancelParams) (*Payout, error) { + path := FormatURLPath("/v1/topups/%s/cancel", id) + topup := &Payout{} + if params == nil { + params = &PayoutCancelParams{} + } + params.Context = ctx + err := c.B.Call(http.MethodPost, path, c.Key, params, topup) + return topup, err +} + +// Reverses a payout by debiting the destination bank account. At this time, you can only reverse payouts for connected accounts to US bank accounts. If the payout is manual and in the pending status, use /v1/payouts/:id/cancel instead. +// +// By requesting a reversal through /v1/payouts/:id/reverse, you confirm that the authorized signatory of the selected bank account authorizes the debit on the bank account and that no other authorization is required. +func (c v1PayoutService) Reverse(ctx context.Context, id string, params *PayoutReverseParams) (*Payout, error) { + if params == nil { + params = &PayoutReverseParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/payouts/%s/reverse", id) + payout := &Payout{} + err := c.B.Call(http.MethodPost, path, c.Key, params, payout) + return payout, err +} + +// Returns a list of existing payouts sent to third-party bank accounts or payouts that Stripe sent to you. The payouts return in sorted order, with the most recently created payouts appearing first. +func (c v1PayoutService) List(ctx context.Context, listParams *PayoutListParams) Seq2[*Payout, error] { + if listParams == nil { + listParams = &PayoutListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Payout, ListContainer, error) { + list := &PayoutList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/payouts", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/person.go b/vendor/github.com/stripe/stripe-go/v82/person.go new file mode 100644 index 00000000..8425edc9 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/person.go @@ -0,0 +1,1128 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Indicates if the person or any of their representatives, family members, or other closely related persons, declares that they hold or have held an important public job or function, in any jurisdiction. +type PersonPoliticalExposure string + +// List of values that PersonPoliticalExposure can take +const ( + PersonPoliticalExposureExisting PersonPoliticalExposure = "existing" + PersonPoliticalExposureNone PersonPoliticalExposure = "none" +) + +// The persons ethnicity +type PersonUSCfpbDataEthnicityDetailsEthnicity string + +// List of values that PersonUSCfpbDataEthnicityDetailsEthnicity can take +const ( + PersonUSCfpbDataEthnicityDetailsEthnicityCuban PersonUSCfpbDataEthnicityDetailsEthnicity = "cuban" + PersonUSCfpbDataEthnicityDetailsEthnicityHispanicOrLatino PersonUSCfpbDataEthnicityDetailsEthnicity = "hispanic_or_latino" + PersonUSCfpbDataEthnicityDetailsEthnicityMexican PersonUSCfpbDataEthnicityDetailsEthnicity = "mexican" + PersonUSCfpbDataEthnicityDetailsEthnicityNotHispanicOrLatino PersonUSCfpbDataEthnicityDetailsEthnicity = "not_hispanic_or_latino" + PersonUSCfpbDataEthnicityDetailsEthnicityOtherHispanicOrLatino PersonUSCfpbDataEthnicityDetailsEthnicity = "other_hispanic_or_latino" + PersonUSCfpbDataEthnicityDetailsEthnicityPreferNotToAnswer PersonUSCfpbDataEthnicityDetailsEthnicity = "prefer_not_to_answer" + PersonUSCfpbDataEthnicityDetailsEthnicityPuertoRican PersonUSCfpbDataEthnicityDetailsEthnicity = "puerto_rican" +) + +// The persons race. +type PersonUSCfpbDataRaceDetailsRace string + +// List of values that PersonUSCfpbDataRaceDetailsRace can take +const ( + PersonUSCfpbDataRaceDetailsRaceAfricanAmerican PersonUSCfpbDataRaceDetailsRace = "african_american" + PersonUSCfpbDataRaceDetailsRaceAmericanIndianOrAlaskaNative PersonUSCfpbDataRaceDetailsRace = "american_indian_or_alaska_native" + PersonUSCfpbDataRaceDetailsRaceAsian PersonUSCfpbDataRaceDetailsRace = "asian" + PersonUSCfpbDataRaceDetailsRaceAsianIndian PersonUSCfpbDataRaceDetailsRace = "asian_indian" + PersonUSCfpbDataRaceDetailsRaceBlackOrAfricanAmerican PersonUSCfpbDataRaceDetailsRace = "black_or_african_american" + PersonUSCfpbDataRaceDetailsRaceChinese PersonUSCfpbDataRaceDetailsRace = "chinese" + PersonUSCfpbDataRaceDetailsRaceEthiopian PersonUSCfpbDataRaceDetailsRace = "ethiopian" + PersonUSCfpbDataRaceDetailsRaceFilipino PersonUSCfpbDataRaceDetailsRace = "filipino" + PersonUSCfpbDataRaceDetailsRaceGuamanianOrChamorro PersonUSCfpbDataRaceDetailsRace = "guamanian_or_chamorro" + PersonUSCfpbDataRaceDetailsRaceHaitian PersonUSCfpbDataRaceDetailsRace = "haitian" + PersonUSCfpbDataRaceDetailsRaceJamaican PersonUSCfpbDataRaceDetailsRace = "jamaican" + PersonUSCfpbDataRaceDetailsRaceJapanese PersonUSCfpbDataRaceDetailsRace = "japanese" + PersonUSCfpbDataRaceDetailsRaceKorean PersonUSCfpbDataRaceDetailsRace = "korean" + PersonUSCfpbDataRaceDetailsRaceNativeHawaiian PersonUSCfpbDataRaceDetailsRace = "native_hawaiian" + PersonUSCfpbDataRaceDetailsRaceNativeHawaiianOrOtherPacificIslander PersonUSCfpbDataRaceDetailsRace = "native_hawaiian_or_other_pacific_islander" + PersonUSCfpbDataRaceDetailsRaceNigerian PersonUSCfpbDataRaceDetailsRace = "nigerian" + PersonUSCfpbDataRaceDetailsRaceOtherAsian PersonUSCfpbDataRaceDetailsRace = "other_asian" + PersonUSCfpbDataRaceDetailsRaceOtherBlackOrAfricanAmerican PersonUSCfpbDataRaceDetailsRace = "other_black_or_african_american" + PersonUSCfpbDataRaceDetailsRaceOtherPacificIslander PersonUSCfpbDataRaceDetailsRace = "other_pacific_islander" + PersonUSCfpbDataRaceDetailsRacePreferNotToAnswer PersonUSCfpbDataRaceDetailsRace = "prefer_not_to_answer" + PersonUSCfpbDataRaceDetailsRaceSamoan PersonUSCfpbDataRaceDetailsRace = "samoan" + PersonUSCfpbDataRaceDetailsRaceSomali PersonUSCfpbDataRaceDetailsRace = "somali" + PersonUSCfpbDataRaceDetailsRaceVietnamese PersonUSCfpbDataRaceDetailsRace = "vietnamese" + PersonUSCfpbDataRaceDetailsRaceWhite PersonUSCfpbDataRaceDetailsRace = "white" +) + +// One of `document_corrupt`, `document_country_not_supported`, `document_expired`, `document_failed_copy`, `document_failed_other`, `document_failed_test_mode`, `document_fraudulent`, `document_failed_greyscale`, `document_incomplete`, `document_invalid`, `document_manipulated`, `document_missing_back`, `document_missing_front`, `document_not_readable`, `document_not_uploaded`, `document_photo_mismatch`, `document_too_large`, or `document_type_not_supported`. A machine-readable code specifying the verification state for this document. +type PersonVerificationDocumentDetailsCode string + +// List of values that PersonVerificationDocumentDetailsCode can take +const ( + PersonVerificationDocumentDetailsCodeDocumentCorrupt PersonVerificationDocumentDetailsCode = "document_corrupt" + PersonVerificationDocumentDetailsCodeDocumentCountryNotSupported PersonVerificationDocumentDetailsCode = "document_country_not_supported" + PersonVerificationDocumentDetailsCodeDocumentExpired PersonVerificationDocumentDetailsCode = "document_expired" + PersonVerificationDocumentDetailsCodeDocumentFailedCopy PersonVerificationDocumentDetailsCode = "document_failed_copy" + PersonVerificationDocumentDetailsCodeDocumentFailedOther PersonVerificationDocumentDetailsCode = "document_failed_other" + PersonVerificationDocumentDetailsCodeDocumentFailedTestMode PersonVerificationDocumentDetailsCode = "document_failed_test_mode" + PersonVerificationDocumentDetailsCodeDocumentFraudulent PersonVerificationDocumentDetailsCode = "document_fraudulent" + PersonVerificationDocumentDetailsCodeDocumentIDTypeNotSupported PersonVerificationDocumentDetailsCode = "document_id_type_not_supported" + PersonVerificationDocumentDetailsCodeDocumentIDCountryNotSupported PersonVerificationDocumentDetailsCode = "document_id_country_not_supported" + PersonVerificationDocumentDetailsCodeDocumentFailedGreyscale PersonVerificationDocumentDetailsCode = "document_failed_greyscale" + PersonVerificationDocumentDetailsCodeDocumentIncomplete PersonVerificationDocumentDetailsCode = "document_incomplete" + PersonVerificationDocumentDetailsCodeDocumentInvalid PersonVerificationDocumentDetailsCode = "document_invalid" + PersonVerificationDocumentDetailsCodeDocumentManipulated PersonVerificationDocumentDetailsCode = "document_manipulated" + PersonVerificationDocumentDetailsCodeDocumentMissingBack PersonVerificationDocumentDetailsCode = "document_missing_back" + PersonVerificationDocumentDetailsCodeDocumentMissingFront PersonVerificationDocumentDetailsCode = "document_missing_front" + PersonVerificationDocumentDetailsCodeDocumentNotReadable PersonVerificationDocumentDetailsCode = "document_not_readable" + PersonVerificationDocumentDetailsCodeDocumentNotUploaded PersonVerificationDocumentDetailsCode = "document_not_uploaded" + PersonVerificationDocumentDetailsCodeDocumentPhotoMismatch PersonVerificationDocumentDetailsCode = "document_photo_mismatch" + PersonVerificationDocumentDetailsCodeDocumentTooLarge PersonVerificationDocumentDetailsCode = "document_too_large" + PersonVerificationDocumentDetailsCodeDocumentTypeNotSupported PersonVerificationDocumentDetailsCode = "document_type_not_supported" +) + +// One of `document_address_mismatch`, `document_dob_mismatch`, `document_duplicate_type`, `document_id_number_mismatch`, `document_name_mismatch`, `document_nationality_mismatch`, `failed_keyed_identity`, or `failed_other`. A machine-readable code specifying the verification state for the person. +type PersonVerificationDetailsCode string + +// List of values that PersonVerificationDetailsCode can take +const ( + PersonVerificationDetailsCodeFailedKeyedIdentity PersonVerificationDetailsCode = "failed_keyed_identity" + PersonVerificationDetailsCodeFailedOther PersonVerificationDetailsCode = "failed_other" + PersonVerificationDetailsCodeScanNameMismatch PersonVerificationDetailsCode = "scan_name_mismatch" + PersonVerificationDetailsCodeDocumentAddressMismatch PersonVerificationDetailsCode = "document_address_mismatch" + PersonVerificationDetailsCodeDocumentDOBMismatch PersonVerificationDetailsCode = "document_dob_mismatch" + PersonVerificationDetailsCodeDocumentDuplicateType PersonVerificationDetailsCode = "document_duplicate_type" + PersonVerificationDetailsCodeDocumentIDNumberMismatch PersonVerificationDetailsCode = "document_id_number_mismatch" + PersonVerificationDetailsCodeDocumentNameMismatch PersonVerificationDetailsCode = "document_name_mismatch" + PersonVerificationDetailsCodeDocumentNationalityMismatch PersonVerificationDetailsCode = "document_nationality_mismatch" +) + +// The state of verification for the person. Possible values are `unverified`, `pending`, or `verified`. Please refer [guide](https://stripe.com/docs/connect/handling-api-verification) to handle verification updates. +type PersonVerificationStatus string + +// List of values that PersonVerificationStatus can take +const ( + PersonVerificationStatusPending PersonVerificationStatus = "pending" + PersonVerificationStatusUnverified PersonVerificationStatus = "unverified" + PersonVerificationStatusVerified PersonVerificationStatus = "verified" +) + +// Deletes an existing person's relationship to the account's legal entity. Any person with a relationship for an account can be deleted through the API, except if the person is the account_opener. If your integration is using the executive parameter, you cannot delete the only verified executive on file. +type PersonParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL + // Details on the legal guardian's or authorizer's acceptance of the required Stripe agreements. + AdditionalTOSAcceptances *PersonAdditionalTOSAcceptancesParams `form:"additional_tos_acceptances"` + // The person's address. + Address *AddressParams `form:"address"` + // The Kana variation of the person's address (Japan only). + AddressKana *PersonAddressKanaParams `form:"address_kana"` + // The Kanji variation of the person's address (Japan only). + AddressKanji *PersonAddressKanjiParams `form:"address_kanji"` + // The person's date of birth. + DOB *PersonDOBParams `form:"dob"` + // Documents that may be submitted to satisfy various informational requests. + Documents *PersonDocumentsParams `form:"documents"` + // The person's email address. + Email *string `form:"email"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The person's first name. + FirstName *string `form:"first_name"` + // The Kana variation of the person's first name (Japan only). + FirstNameKana *string `form:"first_name_kana"` + // The Kanji variation of the person's first name (Japan only). + FirstNameKanji *string `form:"first_name_kanji"` + // A list of alternate names or aliases that the person is known by. + FullNameAliases []*string `form:"full_name_aliases"` + // The person's gender (International regulations require either "male" or "female"). + Gender *string `form:"gender"` + // The person's ID number, as appropriate for their country. For example, a social security number in the U.S., social insurance number in Canada, etc. Instead of the number itself, you can also provide a [PII token provided by Stripe.js](https://docs.stripe.com/js/tokens/create_token?type=pii). + IDNumber *string `form:"id_number"` + // The person's secondary ID number, as appropriate for their country, will be used for enhanced verification checks. In Thailand, this would be the laser code found on the back of an ID card. Instead of the number itself, you can also provide a [PII token provided by Stripe.js](https://docs.stripe.com/js/tokens/create_token?type=pii). + IDNumberSecondary *string `form:"id_number_secondary"` + // The person's last name. + LastName *string `form:"last_name"` + // The Kana variation of the person's last name (Japan only). + LastNameKana *string `form:"last_name_kana"` + // The Kanji variation of the person's last name (Japan only). + LastNameKanji *string `form:"last_name_kanji"` + // The person's maiden name. + MaidenName *string `form:"maiden_name"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The country where the person is a national. Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)), or "XX" if unavailable. + Nationality *string `form:"nationality"` + // A [person token](https://docs.stripe.com/connect/account-tokens), used to securely provide details to the person. + PersonToken *string `form:"person_token"` + // The person's phone number. + Phone *string `form:"phone"` + // Indicates if the person or any of their representatives, family members, or other closely related persons, declares that they hold or have held an important public job or function, in any jurisdiction. + PoliticalExposure *string `form:"political_exposure"` + // The person's registered address. + RegisteredAddress *AddressParams `form:"registered_address"` + // The relationship that this person has with the account's legal entity. + Relationship *PersonRelationshipParams `form:"relationship"` + // The last four digits of the person's Social Security number (U.S. only). + SSNLast4 *string `form:"ssn_last_4"` + // Demographic data related to the person. + USCfpbData *PersonUSCfpbDataParams `form:"us_cfpb_data"` + // The person's verification status. + Verification *PersonVerificationParams `form:"verification"` +} + +// AddExpand appends a new field to expand. +func (p *PersonParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PersonParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Details on the legal guardian's acceptance of the main Stripe service agreement. +type PersonAdditionalTOSAcceptancesAccountParams struct { + // The Unix timestamp marking when the account representative accepted the service agreement. + Date *int64 `form:"date"` + // The IP address from which the account representative accepted the service agreement. + IP *string `form:"ip"` + // The user agent of the browser from which the account representative accepted the service agreement. + UserAgent *string `form:"user_agent"` +} + +// Details on the legal guardian's or authorizer's acceptance of the required Stripe agreements. +type PersonAdditionalTOSAcceptancesParams struct { + // Details on the legal guardian's acceptance of the main Stripe service agreement. + Account *PersonAdditionalTOSAcceptancesAccountParams `form:"account"` +} + +// The Kana variation of the person's address (Japan only). +type PersonAddressKanaParams struct { + // City or ward. + City *string `form:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // Block or building number. + Line1 *string `form:"line1"` + // Building details. + Line2 *string `form:"line2"` + // Postal code. + PostalCode *string `form:"postal_code"` + // Prefecture. + State *string `form:"state"` + // Town or cho-me. + Town *string `form:"town"` +} + +// The Kanji variation of the person's address (Japan only). +type PersonAddressKanjiParams struct { + // City or ward. + City *string `form:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // Block or building number. + Line1 *string `form:"line1"` + // Building details. + Line2 *string `form:"line2"` + // Postal code. + PostalCode *string `form:"postal_code"` + // Prefecture. + State *string `form:"state"` + // Town or cho-me. + Town *string `form:"town"` +} + +// The person's date of birth. +type PersonDOBParams struct { + // The day of birth, between 1 and 31. + Day *int64 `form:"day"` + // The month of birth, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of birth. + Year *int64 `form:"year"` +} + +// One or more documents that demonstrate proof that this person is authorized to represent the company. +type PersonDocumentsCompanyAuthorizationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents showing the person's passport page with photo and personal data. +type PersonDocumentsPassportParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents showing the person's visa required for living in the country where they are residing. +type PersonDocumentsVisaParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// Documents that may be submitted to satisfy various informational requests. +type PersonDocumentsParams struct { + // One or more documents that demonstrate proof that this person is authorized to represent the company. + CompanyAuthorization *PersonDocumentsCompanyAuthorizationParams `form:"company_authorization"` + // One or more documents showing the person's passport page with photo and personal data. + Passport *PersonDocumentsPassportParams `form:"passport"` + // One or more documents showing the person's visa required for living in the country where they are residing. + Visa *PersonDocumentsVisaParams `form:"visa"` +} + +// The relationship that this person has with the account's legal entity. +type PersonRelationshipParams struct { + // Whether the person is the authorizer of the account's representative. + Authorizer *bool `form:"authorizer"` + // Whether the person is a director of the account's legal entity. Directors are typically members of the governing board of the company, or responsible for ensuring the company meets its regulatory obligations. + Director *bool `form:"director"` + // Whether the person has significant responsibility to control, manage, or direct the organization. + Executive *bool `form:"executive"` + // Whether the person is the legal guardian of the account's representative. + LegalGuardian *bool `form:"legal_guardian"` + // Whether the person is an owner of the account's legal entity. + Owner *bool `form:"owner"` + // The percent owned by the person of the account's legal entity. + PercentOwnership *float64 `form:"percent_ownership"` + // Whether the person is authorized as the primary representative of the account. This is the person nominated by the business to provide information about themselves, and general information about the account. There can only be one representative at any given time. At the time the account is created, this person should be set to the person responsible for opening the account. + Representative *bool `form:"representative"` + // The person's title (e.g., CEO, Support Engineer). + Title *string `form:"title"` +} + +// The persons ethnicity details +type PersonUSCfpbDataEthnicityDetailsParams struct { + // The persons ethnicity + Ethnicity []*string `form:"ethnicity"` + // Please specify your origin, when other is selected. + EthnicityOther *string `form:"ethnicity_other"` +} + +// The persons race details +type PersonUSCfpbDataRaceDetailsParams struct { + // The persons race. + Race []*string `form:"race"` + // Please specify your race, when other is selected. + RaceOther *string `form:"race_other"` +} + +// Demographic data related to the person. +type PersonUSCfpbDataParams struct { + // The persons ethnicity details + EthnicityDetails *PersonUSCfpbDataEthnicityDetailsParams `form:"ethnicity_details"` + // The persons race details + RaceDetails *PersonUSCfpbDataRaceDetailsParams `form:"race_details"` + // The persons self-identified gender + SelfIdentifiedGender *string `form:"self_identified_gender"` +} + +// A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. +type PersonVerificationDocumentParams struct { + // The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Back *string `form:"back"` + // The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Front *string `form:"front"` +} + +// The person's verification status. +type PersonVerificationParams struct { + // A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. + AdditionalDocument *PersonVerificationDocumentParams `form:"additional_document"` + // An identifying document, either a passport or local ID card. + Document *PersonVerificationDocumentParams `form:"document"` +} + +// Filters on the list of people returned based on the person's relationship to the account's company. +type PersonListRelationshipParams struct { + // A filter on the list of people returned based on whether these people are authorizers of the account's representative. + Authorizer *bool `form:"authorizer"` + // A filter on the list of people returned based on whether these people are directors of the account's company. + Director *bool `form:"director"` + // A filter on the list of people returned based on whether these people are executives of the account's company. + Executive *bool `form:"executive"` + // A filter on the list of people returned based on whether these people are legal guardians of the account's representative. + LegalGuardian *bool `form:"legal_guardian"` + // A filter on the list of people returned based on whether these people are owners of the account's company. + Owner *bool `form:"owner"` + // A filter on the list of people returned based on whether these people are the representative of the account's company. + Representative *bool `form:"representative"` +} + +// Returns a list of people associated with the account's legal entity. The people are returned sorted by creation date, with the most recent people appearing first. +type PersonListParams struct { + ListParams `form:"*"` + Account *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Filters on the list of people returned based on the person's relationship to the account's company. + Relationship *PersonListRelationshipParams `form:"relationship"` +} + +// AddExpand appends a new field to expand. +func (p *PersonListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Deletes an existing person's relationship to the account's legal entity. Any person with a relationship for an account can be deleted through the API, except if the person is the account_opener. If your integration is using the executive parameter, you cannot delete the only verified executive on file. +type PersonDeleteParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL +} + +// Retrieves an existing person. +type PersonRetrieveParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PersonRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Details on the legal guardian's acceptance of the main Stripe service agreement. +type PersonUpdateAdditionalTOSAcceptancesAccountParams struct { + // The Unix timestamp marking when the account representative accepted the service agreement. + Date *int64 `form:"date"` + // The IP address from which the account representative accepted the service agreement. + IP *string `form:"ip"` + // The user agent of the browser from which the account representative accepted the service agreement. + UserAgent *string `form:"user_agent"` +} + +// Details on the legal guardian's or authorizer's acceptance of the required Stripe agreements. +type PersonUpdateAdditionalTOSAcceptancesParams struct { + // Details on the legal guardian's acceptance of the main Stripe service agreement. + Account *PersonUpdateAdditionalTOSAcceptancesAccountParams `form:"account"` +} + +// The Kana variation of the person's address (Japan only). +type PersonUpdateAddressKanaParams struct { + // City or ward. + City *string `form:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // Block or building number. + Line1 *string `form:"line1"` + // Building details. + Line2 *string `form:"line2"` + // Postal code. + PostalCode *string `form:"postal_code"` + // Prefecture. + State *string `form:"state"` + // Town or cho-me. + Town *string `form:"town"` +} + +// The Kanji variation of the person's address (Japan only). +type PersonUpdateAddressKanjiParams struct { + // City or ward. + City *string `form:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // Block or building number. + Line1 *string `form:"line1"` + // Building details. + Line2 *string `form:"line2"` + // Postal code. + PostalCode *string `form:"postal_code"` + // Prefecture. + State *string `form:"state"` + // Town or cho-me. + Town *string `form:"town"` +} + +// The person's date of birth. +type PersonUpdateDOBParams struct { + // The day of birth, between 1 and 31. + Day *int64 `form:"day"` + // The month of birth, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of birth. + Year *int64 `form:"year"` +} + +// One or more documents that demonstrate proof that this person is authorized to represent the company. +type PersonUpdateDocumentsCompanyAuthorizationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents showing the person's passport page with photo and personal data. +type PersonUpdateDocumentsPassportParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents showing the person's visa required for living in the country where they are residing. +type PersonUpdateDocumentsVisaParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// Documents that may be submitted to satisfy various informational requests. +type PersonUpdateDocumentsParams struct { + // One or more documents that demonstrate proof that this person is authorized to represent the company. + CompanyAuthorization *PersonUpdateDocumentsCompanyAuthorizationParams `form:"company_authorization"` + // One or more documents showing the person's passport page with photo and personal data. + Passport *PersonUpdateDocumentsPassportParams `form:"passport"` + // One or more documents showing the person's visa required for living in the country where they are residing. + Visa *PersonUpdateDocumentsVisaParams `form:"visa"` +} + +// The relationship that this person has with the account's legal entity. +type PersonUpdateRelationshipParams struct { + // Whether the person is the authorizer of the account's representative. + Authorizer *bool `form:"authorizer"` + // Whether the person is a director of the account's legal entity. Directors are typically members of the governing board of the company, or responsible for ensuring the company meets its regulatory obligations. + Director *bool `form:"director"` + // Whether the person has significant responsibility to control, manage, or direct the organization. + Executive *bool `form:"executive"` + // Whether the person is the legal guardian of the account's representative. + LegalGuardian *bool `form:"legal_guardian"` + // Whether the person is an owner of the account's legal entity. + Owner *bool `form:"owner"` + // The percent owned by the person of the account's legal entity. + PercentOwnership *float64 `form:"percent_ownership"` + // Whether the person is authorized as the primary representative of the account. This is the person nominated by the business to provide information about themselves, and general information about the account. There can only be one representative at any given time. At the time the account is created, this person should be set to the person responsible for opening the account. + Representative *bool `form:"representative"` + // The person's title (e.g., CEO, Support Engineer). + Title *string `form:"title"` +} + +// The persons ethnicity details +type PersonUpdateUSCfpbDataEthnicityDetailsParams struct { + // The persons ethnicity + Ethnicity []*string `form:"ethnicity"` + // Please specify your origin, when other is selected. + EthnicityOther *string `form:"ethnicity_other"` +} + +// The persons race details +type PersonUpdateUSCfpbDataRaceDetailsParams struct { + // The persons race. + Race []*string `form:"race"` + // Please specify your race, when other is selected. + RaceOther *string `form:"race_other"` +} + +// Demographic data related to the person. +type PersonUpdateUSCfpbDataParams struct { + // The persons ethnicity details + EthnicityDetails *PersonUpdateUSCfpbDataEthnicityDetailsParams `form:"ethnicity_details"` + // The persons race details + RaceDetails *PersonUpdateUSCfpbDataRaceDetailsParams `form:"race_details"` + // The persons self-identified gender + SelfIdentifiedGender *string `form:"self_identified_gender"` +} + +// A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. +type PersonUpdateVerificationAdditionalDocumentParams struct { + // The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Back *string `form:"back"` + // The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Front *string `form:"front"` +} + +// An identifying document, either a passport or local ID card. +type PersonUpdateVerificationDocumentParams struct { + // The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Back *string `form:"back"` + // The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Front *string `form:"front"` +} + +// The person's verification status. +type PersonUpdateVerificationParams struct { + // A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. + AdditionalDocument *PersonUpdateVerificationAdditionalDocumentParams `form:"additional_document"` + // An identifying document, either a passport or local ID card. + Document *PersonUpdateVerificationDocumentParams `form:"document"` +} + +// Updates an existing person. +type PersonUpdateParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL + // Details on the legal guardian's or authorizer's acceptance of the required Stripe agreements. + AdditionalTOSAcceptances *PersonUpdateAdditionalTOSAcceptancesParams `form:"additional_tos_acceptances"` + // The person's address. + Address *AddressParams `form:"address"` + // The Kana variation of the person's address (Japan only). + AddressKana *PersonUpdateAddressKanaParams `form:"address_kana"` + // The Kanji variation of the person's address (Japan only). + AddressKanji *PersonUpdateAddressKanjiParams `form:"address_kanji"` + // The person's date of birth. + DOB *PersonUpdateDOBParams `form:"dob"` + // Documents that may be submitted to satisfy various informational requests. + Documents *PersonUpdateDocumentsParams `form:"documents"` + // The person's email address. + Email *string `form:"email"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The person's first name. + FirstName *string `form:"first_name"` + // The Kana variation of the person's first name (Japan only). + FirstNameKana *string `form:"first_name_kana"` + // The Kanji variation of the person's first name (Japan only). + FirstNameKanji *string `form:"first_name_kanji"` + // A list of alternate names or aliases that the person is known by. + FullNameAliases []*string `form:"full_name_aliases"` + // The person's gender (International regulations require either "male" or "female"). + Gender *string `form:"gender"` + // The person's ID number, as appropriate for their country. For example, a social security number in the U.S., social insurance number in Canada, etc. Instead of the number itself, you can also provide a [PII token provided by Stripe.js](https://docs.stripe.com/js/tokens/create_token?type=pii). + IDNumber *string `form:"id_number"` + // The person's secondary ID number, as appropriate for their country, will be used for enhanced verification checks. In Thailand, this would be the laser code found on the back of an ID card. Instead of the number itself, you can also provide a [PII token provided by Stripe.js](https://docs.stripe.com/js/tokens/create_token?type=pii). + IDNumberSecondary *string `form:"id_number_secondary"` + // The person's last name. + LastName *string `form:"last_name"` + // The Kana variation of the person's last name (Japan only). + LastNameKana *string `form:"last_name_kana"` + // The Kanji variation of the person's last name (Japan only). + LastNameKanji *string `form:"last_name_kanji"` + // The person's maiden name. + MaidenName *string `form:"maiden_name"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The country where the person is a national. Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)), or "XX" if unavailable. + Nationality *string `form:"nationality"` + // A [person token](https://docs.stripe.com/connect/account-tokens), used to securely provide details to the person. + PersonToken *string `form:"person_token"` + // The person's phone number. + Phone *string `form:"phone"` + // Indicates if the person or any of their representatives, family members, or other closely related persons, declares that they hold or have held an important public job or function, in any jurisdiction. + PoliticalExposure *string `form:"political_exposure"` + // The person's registered address. + RegisteredAddress *AddressParams `form:"registered_address"` + // The relationship that this person has with the account's legal entity. + Relationship *PersonUpdateRelationshipParams `form:"relationship"` + // The last four digits of the person's Social Security number (U.S. only). + SSNLast4 *string `form:"ssn_last_4"` + // Demographic data related to the person. + USCfpbData *PersonUpdateUSCfpbDataParams `form:"us_cfpb_data"` + // The person's verification status. + Verification *PersonUpdateVerificationParams `form:"verification"` +} + +// AddExpand appends a new field to expand. +func (p *PersonUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PersonUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Details on the legal guardian's acceptance of the main Stripe service agreement. +type PersonCreateAdditionalTOSAcceptancesAccountParams struct { + // The Unix timestamp marking when the account representative accepted the service agreement. + Date *int64 `form:"date"` + // The IP address from which the account representative accepted the service agreement. + IP *string `form:"ip"` + // The user agent of the browser from which the account representative accepted the service agreement. + UserAgent *string `form:"user_agent"` +} + +// Details on the legal guardian's or authorizer's acceptance of the required Stripe agreements. +type PersonCreateAdditionalTOSAcceptancesParams struct { + // Details on the legal guardian's acceptance of the main Stripe service agreement. + Account *PersonCreateAdditionalTOSAcceptancesAccountParams `form:"account"` +} + +// The Kana variation of the person's address (Japan only). +type PersonCreateAddressKanaParams struct { + // City or ward. + City *string `form:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // Block or building number. + Line1 *string `form:"line1"` + // Building details. + Line2 *string `form:"line2"` + // Postal code. + PostalCode *string `form:"postal_code"` + // Prefecture. + State *string `form:"state"` + // Town or cho-me. + Town *string `form:"town"` +} + +// The Kanji variation of the person's address (Japan only). +type PersonCreateAddressKanjiParams struct { + // City or ward. + City *string `form:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // Block or building number. + Line1 *string `form:"line1"` + // Building details. + Line2 *string `form:"line2"` + // Postal code. + PostalCode *string `form:"postal_code"` + // Prefecture. + State *string `form:"state"` + // Town or cho-me. + Town *string `form:"town"` +} + +// The person's date of birth. +type PersonCreateDOBParams struct { + // The day of birth, between 1 and 31. + Day *int64 `form:"day"` + // The month of birth, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of birth. + Year *int64 `form:"year"` +} + +// One or more documents that demonstrate proof that this person is authorized to represent the company. +type PersonCreateDocumentsCompanyAuthorizationParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents showing the person's passport page with photo and personal data. +type PersonCreateDocumentsPassportParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// One or more documents showing the person's visa required for living in the country where they are residing. +type PersonCreateDocumentsVisaParams struct { + // One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + Files []*string `form:"files"` +} + +// Documents that may be submitted to satisfy various informational requests. +type PersonCreateDocumentsParams struct { + // One or more documents that demonstrate proof that this person is authorized to represent the company. + CompanyAuthorization *PersonCreateDocumentsCompanyAuthorizationParams `form:"company_authorization"` + // One or more documents showing the person's passport page with photo and personal data. + Passport *PersonCreateDocumentsPassportParams `form:"passport"` + // One or more documents showing the person's visa required for living in the country where they are residing. + Visa *PersonCreateDocumentsVisaParams `form:"visa"` +} + +// The relationship that this person has with the account's legal entity. +type PersonCreateRelationshipParams struct { + // Whether the person is the authorizer of the account's representative. + Authorizer *bool `form:"authorizer"` + // Whether the person is a director of the account's legal entity. Directors are typically members of the governing board of the company, or responsible for ensuring the company meets its regulatory obligations. + Director *bool `form:"director"` + // Whether the person has significant responsibility to control, manage, or direct the organization. + Executive *bool `form:"executive"` + // Whether the person is the legal guardian of the account's representative. + LegalGuardian *bool `form:"legal_guardian"` + // Whether the person is an owner of the account's legal entity. + Owner *bool `form:"owner"` + // The percent owned by the person of the account's legal entity. + PercentOwnership *float64 `form:"percent_ownership"` + // Whether the person is authorized as the primary representative of the account. This is the person nominated by the business to provide information about themselves, and general information about the account. There can only be one representative at any given time. At the time the account is created, this person should be set to the person responsible for opening the account. + Representative *bool `form:"representative"` + // The person's title (e.g., CEO, Support Engineer). + Title *string `form:"title"` +} + +// The persons ethnicity details +type PersonCreateUSCfpbDataEthnicityDetailsParams struct { + // The persons ethnicity + Ethnicity []*string `form:"ethnicity"` + // Please specify your origin, when other is selected. + EthnicityOther *string `form:"ethnicity_other"` +} + +// The persons race details +type PersonCreateUSCfpbDataRaceDetailsParams struct { + // The persons race. + Race []*string `form:"race"` + // Please specify your race, when other is selected. + RaceOther *string `form:"race_other"` +} + +// Demographic data related to the person. +type PersonCreateUSCfpbDataParams struct { + // The persons ethnicity details + EthnicityDetails *PersonCreateUSCfpbDataEthnicityDetailsParams `form:"ethnicity_details"` + // The persons race details + RaceDetails *PersonCreateUSCfpbDataRaceDetailsParams `form:"race_details"` + // The persons self-identified gender + SelfIdentifiedGender *string `form:"self_identified_gender"` +} + +// A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. +type PersonCreateVerificationAdditionalDocumentParams struct { + // The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Back *string `form:"back"` + // The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Front *string `form:"front"` +} + +// An identifying document, either a passport or local ID card. +type PersonCreateVerificationDocumentParams struct { + // The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Back *string `form:"back"` + // The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + Front *string `form:"front"` +} + +// The person's verification status. +type PersonCreateVerificationParams struct { + // A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. + AdditionalDocument *PersonCreateVerificationAdditionalDocumentParams `form:"additional_document"` + // An identifying document, either a passport or local ID card. + Document *PersonCreateVerificationDocumentParams `form:"document"` +} + +// Creates a new person. +type PersonCreateParams struct { + Params `form:"*"` + Account *string `form:"-"` // Included in URL + // Details on the legal guardian's or authorizer's acceptance of the required Stripe agreements. + AdditionalTOSAcceptances *PersonCreateAdditionalTOSAcceptancesParams `form:"additional_tos_acceptances"` + // The person's address. + Address *AddressParams `form:"address"` + // The Kana variation of the person's address (Japan only). + AddressKana *PersonCreateAddressKanaParams `form:"address_kana"` + // The Kanji variation of the person's address (Japan only). + AddressKanji *PersonCreateAddressKanjiParams `form:"address_kanji"` + // The person's date of birth. + DOB *PersonCreateDOBParams `form:"dob"` + // Documents that may be submitted to satisfy various informational requests. + Documents *PersonCreateDocumentsParams `form:"documents"` + // The person's email address. + Email *string `form:"email"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The person's first name. + FirstName *string `form:"first_name"` + // The Kana variation of the person's first name (Japan only). + FirstNameKana *string `form:"first_name_kana"` + // The Kanji variation of the person's first name (Japan only). + FirstNameKanji *string `form:"first_name_kanji"` + // A list of alternate names or aliases that the person is known by. + FullNameAliases []*string `form:"full_name_aliases"` + // The person's gender (International regulations require either "male" or "female"). + Gender *string `form:"gender"` + // The person's ID number, as appropriate for their country. For example, a social security number in the U.S., social insurance number in Canada, etc. Instead of the number itself, you can also provide a [PII token provided by Stripe.js](https://docs.stripe.com/js/tokens/create_token?type=pii). + IDNumber *string `form:"id_number"` + // The person's secondary ID number, as appropriate for their country, will be used for enhanced verification checks. In Thailand, this would be the laser code found on the back of an ID card. Instead of the number itself, you can also provide a [PII token provided by Stripe.js](https://docs.stripe.com/js/tokens/create_token?type=pii). + IDNumberSecondary *string `form:"id_number_secondary"` + // The person's last name. + LastName *string `form:"last_name"` + // The Kana variation of the person's last name (Japan only). + LastNameKana *string `form:"last_name_kana"` + // The Kanji variation of the person's last name (Japan only). + LastNameKanji *string `form:"last_name_kanji"` + // The person's maiden name. + MaidenName *string `form:"maiden_name"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The country where the person is a national. Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)), or "XX" if unavailable. + Nationality *string `form:"nationality"` + // A [person token](https://docs.stripe.com/connect/account-tokens), used to securely provide details to the person. + PersonToken *string `form:"person_token"` + // The person's phone number. + Phone *string `form:"phone"` + // Indicates if the person or any of their representatives, family members, or other closely related persons, declares that they hold or have held an important public job or function, in any jurisdiction. + PoliticalExposure *string `form:"political_exposure"` + // The person's registered address. + RegisteredAddress *AddressParams `form:"registered_address"` + // The relationship that this person has with the account's legal entity. + Relationship *PersonCreateRelationshipParams `form:"relationship"` + // The last four digits of the person's Social Security number (U.S. only). + SSNLast4 *string `form:"ssn_last_4"` + // Demographic data related to the person. + USCfpbData *PersonCreateUSCfpbDataParams `form:"us_cfpb_data"` + // The person's verification status. + Verification *PersonCreateVerificationParams `form:"verification"` +} + +// AddExpand appends a new field to expand. +func (p *PersonCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PersonCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Details on the legal guardian's acceptance of the main Stripe service agreement. +type PersonAdditionalTOSAcceptancesAccount struct { + // The Unix timestamp marking when the legal guardian accepted the service agreement. + Date int64 `json:"date"` + // The IP address from which the legal guardian accepted the service agreement. + IP string `json:"ip"` + // The user agent of the browser from which the legal guardian accepted the service agreement. + UserAgent string `json:"user_agent"` +} +type PersonAdditionalTOSAcceptances struct { + // Details on the legal guardian's acceptance of the main Stripe service agreement. + Account *PersonAdditionalTOSAcceptancesAccount `json:"account"` +} + +// The Kana variation of the person's address (Japan only). +type PersonAddressKana struct { + // City/Ward. + City string `json:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country string `json:"country"` + // Block/Building number. + Line1 string `json:"line1"` + // Building details. + Line2 string `json:"line2"` + // ZIP or postal code. + PostalCode string `json:"postal_code"` + // Prefecture. + State string `json:"state"` + // Town/cho-me. + Town string `json:"town"` +} + +// The Kanji variation of the person's address (Japan only). +type PersonAddressKanji struct { + // City/Ward. + City string `json:"city"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country string `json:"country"` + // Block/Building number. + Line1 string `json:"line1"` + // Building details. + Line2 string `json:"line2"` + // ZIP or postal code. + PostalCode string `json:"postal_code"` + // Prefecture. + State string `json:"state"` + // Town/cho-me. + Town string `json:"town"` +} +type PersonDOB struct { + // The day of birth, between 1 and 31. + Day int64 `json:"day"` + // The month of birth, between 1 and 12. + Month int64 `json:"month"` + // The four-digit year of birth. + Year int64 `json:"year"` +} + +// Fields that are due and can be satisfied by providing the corresponding alternative fields instead. +type PersonFutureRequirementsAlternative struct { + // Fields that can be provided to satisfy all fields in `original_fields_due`. + AlternativeFieldsDue []string `json:"alternative_fields_due"` + // Fields that are due and can be satisfied by providing all fields in `alternative_fields_due`. + OriginalFieldsDue []string `json:"original_fields_due"` +} + +// Fields that are `currently_due` and need to be collected again because validation or verification failed. +type PersonFutureRequirementsError struct { + // The code for the type of error. + Code string `json:"code"` + // An informative message that indicates the error type and provides additional details about the error. + Reason string `json:"reason"` + // The specific user onboarding requirement field (in the requirements hash) that needs to be resolved. + Requirement string `json:"requirement"` +} + +// Information about the [upcoming new requirements for this person](https://stripe.com/docs/connect/custom-accounts/future-requirements), including what information needs to be collected, and by when. +type PersonFutureRequirements struct { + // Fields that are due and can be satisfied by providing the corresponding alternative fields instead. + Alternatives []*PersonFutureRequirementsAlternative `json:"alternatives"` + // Fields that need to be collected to keep the person's account enabled. If not collected by the account's `future_requirements[current_deadline]`, these fields will transition to the main `requirements` hash, and may immediately become `past_due`, but the account may also be given a grace period depending on the account's enablement state prior to transition. + CurrentlyDue []string `json:"currently_due"` + // Fields that are `currently_due` and need to be collected again because validation or verification failed. + Errors []*PersonFutureRequirementsError `json:"errors"` + // Fields you must collect when all thresholds are reached. As they become required, they appear in `currently_due` as well, and the account's `future_requirements[current_deadline]` becomes set. + EventuallyDue []string `json:"eventually_due"` + // Fields that weren't collected by the account's `requirements.current_deadline`. These fields need to be collected to enable the person's account. New fields will never appear here; `future_requirements.past_due` will always be a subset of `requirements.past_due`. + PastDue []string `json:"past_due"` + // Fields that might become required depending on the results of verification or review. It's an empty array unless an asynchronous verification is pending. If verification fails, these fields move to `eventually_due` or `currently_due`. Fields might appear in `eventually_due` or `currently_due` and in `pending_verification` if verification fails but another verification is still pending. + PendingVerification []string `json:"pending_verification"` +} +type PersonRelationship struct { + // Whether the person is the authorizer of the account's representative. + Authorizer bool `json:"authorizer"` + // Whether the person is a director of the account's legal entity. Directors are typically members of the governing board of the company, or responsible for ensuring the company meets its regulatory obligations. + Director bool `json:"director"` + // Whether the person has significant responsibility to control, manage, or direct the organization. + Executive bool `json:"executive"` + // Whether the person is the legal guardian of the account's representative. + LegalGuardian bool `json:"legal_guardian"` + // Whether the person is an owner of the account's legal entity. + Owner bool `json:"owner"` + // The percent owned by the person of the account's legal entity. + PercentOwnership float64 `json:"percent_ownership"` + // Whether the person is authorized as the primary representative of the account. This is the person nominated by the business to provide information about themselves, and general information about the account. There can only be one representative at any given time. At the time the account is created, this person should be set to the person responsible for opening the account. + Representative bool `json:"representative"` + // The person's title (e.g., CEO, Support Engineer). + Title string `json:"title"` +} + +// Fields that are due and can be satisfied by providing the corresponding alternative fields instead. +type PersonRequirementsAlternative struct { + // Fields that can be provided to satisfy all fields in `original_fields_due`. + AlternativeFieldsDue []string `json:"alternative_fields_due"` + // Fields that are due and can be satisfied by providing all fields in `alternative_fields_due`. + OriginalFieldsDue []string `json:"original_fields_due"` +} + +// Information about the requirements for this person, including what information needs to be collected, and by when. +type PersonRequirements struct { + // Fields that are due and can be satisfied by providing the corresponding alternative fields instead. + Alternatives []*PersonRequirementsAlternative `json:"alternatives"` + // Fields that need to be collected to keep the person's account enabled. If not collected by the account's `current_deadline`, these fields appear in `past_due` as well, and the account is disabled. + CurrentlyDue []string `json:"currently_due"` + // Fields that are `currently_due` and need to be collected again because validation or verification failed. + Errors []*AccountRequirementsError `json:"errors"` + // Fields you must collect when all thresholds are reached. As they become required, they appear in `currently_due` as well, and the account's `current_deadline` becomes set. + EventuallyDue []string `json:"eventually_due"` + // Fields that weren't collected by the account's `current_deadline`. These fields need to be collected to enable the person's account. + PastDue []string `json:"past_due"` + // Fields that might become required depending on the results of verification or review. It's an empty array unless an asynchronous verification is pending. If verification fails, these fields move to `eventually_due`, `currently_due`, or `past_due`. Fields might appear in `eventually_due`, `currently_due`, or `past_due` and in `pending_verification` if verification fails but another verification is still pending. + PendingVerification []string `json:"pending_verification"` +} + +// The persons ethnicity details +type PersonUSCfpbDataEthnicityDetails struct { + // The persons ethnicity + Ethnicity []PersonUSCfpbDataEthnicityDetailsEthnicity `json:"ethnicity"` + // Please specify your origin, when other is selected. + EthnicityOther string `json:"ethnicity_other"` +} + +// The persons race details +type PersonUSCfpbDataRaceDetails struct { + // The persons race. + Race []PersonUSCfpbDataRaceDetailsRace `json:"race"` + // Please specify your race, when other is selected. + RaceOther string `json:"race_other"` +} + +// Demographic data related to the person. +type PersonUSCfpbData struct { + // The persons ethnicity details + EthnicityDetails *PersonUSCfpbDataEthnicityDetails `json:"ethnicity_details"` + // The persons race details + RaceDetails *PersonUSCfpbDataRaceDetails `json:"race_details"` + // The persons self-identified gender + SelfIdentifiedGender string `json:"self_identified_gender"` +} + +// A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. +type PersonVerificationDocument struct { + // The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + Back *File `json:"back"` + // A user-displayable string describing the verification state of this document. For example, if a document is uploaded and the picture is too fuzzy, this may say "Identity document is too unclear to read". + Details string `json:"details"` + // One of `document_corrupt`, `document_country_not_supported`, `document_expired`, `document_failed_copy`, `document_failed_other`, `document_failed_test_mode`, `document_fraudulent`, `document_failed_greyscale`, `document_incomplete`, `document_invalid`, `document_manipulated`, `document_missing_back`, `document_missing_front`, `document_not_readable`, `document_not_uploaded`, `document_photo_mismatch`, `document_too_large`, or `document_type_not_supported`. A machine-readable code specifying the verification state for this document. + DetailsCode PersonVerificationDocumentDetailsCode `json:"details_code"` + // The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + Front *File `json:"front"` +} +type PersonVerification struct { + // A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. + AdditionalDocument *PersonVerificationDocument `json:"additional_document"` + // A user-displayable string describing the verification state for the person. For example, this may say "Provided identity information could not be verified". + Details string `json:"details"` + // One of `document_address_mismatch`, `document_dob_mismatch`, `document_duplicate_type`, `document_id_number_mismatch`, `document_name_mismatch`, `document_nationality_mismatch`, `failed_keyed_identity`, or `failed_other`. A machine-readable code specifying the verification state for the person. + DetailsCode PersonVerificationDetailsCode `json:"details_code"` + Document *PersonVerificationDocument `json:"document"` + // The state of verification for the person. Possible values are `unverified`, `pending`, or `verified`. Please refer [guide](https://stripe.com/docs/connect/handling-api-verification) to handle verification updates. + Status PersonVerificationStatus `json:"status"` +} + +// This is an object representing a person associated with a Stripe account. +// +// A platform can only access a subset of data in a person for an account where [account.controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`, which includes Standard and Express accounts, after creating an Account Link or Account Session to start Connect onboarding. +// +// See the [Standard onboarding](https://docs.stripe.com/connect/standard-accounts) or [Express onboarding](https://docs.stripe.com/connect/express-accounts) documentation for information about prefilling information and account onboarding steps. Learn more about [handling identity verification with the API](https://docs.stripe.com/connect/handling-api-verification#person-information). +type Person struct { + APIResource + // The account the person is associated with. + Account string `json:"account"` + AdditionalTOSAcceptances *PersonAdditionalTOSAcceptances `json:"additional_tos_acceptances"` + Address *Address `json:"address"` + // The Kana variation of the person's address (Japan only). + AddressKana *PersonAddressKana `json:"address_kana"` + // The Kanji variation of the person's address (Japan only). + AddressKanji *PersonAddressKanji `json:"address_kanji"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + Deleted bool `json:"deleted"` + DOB *PersonDOB `json:"dob"` + // The person's email address. Also available for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`. + Email string `json:"email"` + // The person's first name. Also available for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`. + FirstName string `json:"first_name"` + // The Kana variation of the person's first name (Japan only). Also available for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`. + FirstNameKana string `json:"first_name_kana"` + // The Kanji variation of the person's first name (Japan only). Also available for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`. + FirstNameKanji string `json:"first_name_kanji"` + // A list of alternate names or aliases that the person is known by. Also available for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`. + FullNameAliases []string `json:"full_name_aliases"` + // Information about the [upcoming new requirements for this person](https://stripe.com/docs/connect/custom-accounts/future-requirements), including what information needs to be collected, and by when. + FutureRequirements *PersonFutureRequirements `json:"future_requirements"` + // The person's gender. + Gender string `json:"gender"` + // Unique identifier for the object. + ID string `json:"id"` + // Whether the person's `id_number` was provided. True if either the full ID number was provided or if only the required part of the ID number was provided (ex. last four of an individual's SSN for the US indicated by `ssn_last_4_provided`). + IDNumberProvided bool `json:"id_number_provided"` + // Whether the person's `id_number_secondary` was provided. + IDNumberSecondaryProvided bool `json:"id_number_secondary_provided"` + // The person's last name. Also available for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`. + LastName string `json:"last_name"` + // The Kana variation of the person's last name (Japan only). Also available for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`. + LastNameKana string `json:"last_name_kana"` + // The Kanji variation of the person's last name (Japan only). Also available for accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is `stripe`. + LastNameKanji string `json:"last_name_kanji"` + // The person's maiden name. + MaidenName string `json:"maiden_name"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // The country where the person is a national. + Nationality string `json:"nationality"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The person's phone number. + Phone string `json:"phone"` + // Indicates if the person or any of their representatives, family members, or other closely related persons, declares that they hold or have held an important public job or function, in any jurisdiction. + PoliticalExposure PersonPoliticalExposure `json:"political_exposure"` + RegisteredAddress *Address `json:"registered_address"` + Relationship *PersonRelationship `json:"relationship"` + // Information about the requirements for this person, including what information needs to be collected, and by when. + Requirements *PersonRequirements `json:"requirements"` + // Whether the last four digits of the person's Social Security number have been provided (U.S. only). + SSNLast4Provided bool `json:"ssn_last_4_provided"` + // Demographic data related to the person. + USCfpbData *PersonUSCfpbData `json:"us_cfpb_data"` + Verification *PersonVerification `json:"verification"` +} + +// PersonList is a list of Persons as retrieved from a list endpoint. +type PersonList struct { + APIResource + ListMeta + Data []*Person `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/person_service.go b/vendor/github.com/stripe/stripe-go/v82/person_service.go new file mode 100644 index 00000000..fd04ff7c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/person_service.go @@ -0,0 +1,90 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1PersonService is used to invoke /v1/accounts/{account}/persons APIs. +type v1PersonService struct { + B Backend + Key string +} + +// Creates a new person. +func (c v1PersonService) Create(ctx context.Context, params *PersonCreateParams) (*Person, error) { + if params == nil { + params = &PersonCreateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/accounts/%s/persons", StringValue(params.Account)) + person := &Person{} + err := c.B.Call(http.MethodPost, path, c.Key, params, person) + return person, err +} + +// Retrieves an existing person. +func (c v1PersonService) Retrieve(ctx context.Context, id string, params *PersonRetrieveParams) (*Person, error) { + if params == nil { + params = &PersonRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/persons/%s", StringValue(params.Account), id) + person := &Person{} + err := c.B.Call(http.MethodGet, path, c.Key, params, person) + return person, err +} + +// Updates an existing person. +func (c v1PersonService) Update(ctx context.Context, id string, params *PersonUpdateParams) (*Person, error) { + if params == nil { + params = &PersonUpdateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/persons/%s", StringValue(params.Account), id) + person := &Person{} + err := c.B.Call(http.MethodPost, path, c.Key, params, person) + return person, err +} + +// Deletes an existing person's relationship to the account's legal entity. Any person with a relationship for an account can be deleted through the API, except if the person is the account_opener. If your integration is using the executive parameter, you cannot delete the only verified executive on file. +func (c v1PersonService) Delete(ctx context.Context, id string, params *PersonDeleteParams) (*Person, error) { + if params == nil { + params = &PersonDeleteParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/persons/%s", StringValue(params.Account), id) + person := &Person{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, person) + return person, err +} + +// Returns a list of people associated with the account's legal entity. The people are returned sorted by creation date, with the most recent people appearing first. +func (c v1PersonService) List(ctx context.Context, listParams *PersonListParams) Seq2[*Person, error] { + if listParams == nil { + listParams = &PersonListParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/accounts/%s/persons", StringValue(listParams.Account)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Person, ListContainer, error) { + list := &PersonList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/plan.go b/vendor/github.com/stripe/stripe-go/v82/plan.go new file mode 100644 index 00000000..a3be1211 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/plan.go @@ -0,0 +1,467 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "encoding/json" + "github.com/stripe/stripe-go/v82/form" + "strconv" +) + +// Describes how to compute the price per period. Either `per_unit` or `tiered`. `per_unit` indicates that the fixed amount (specified in `amount`) will be charged per unit in `quantity` (for plans with `usage_type=licensed`), or per unit of total usage (for plans with `usage_type=metered`). `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. +type PlanBillingScheme string + +// List of values that PlanBillingScheme can take +const ( + PlanBillingSchemePerUnit PlanBillingScheme = "per_unit" + PlanBillingSchemeTiered PlanBillingScheme = "tiered" +) + +// The frequency at which a subscription is billed. One of `day`, `week`, `month` or `year`. +type PlanInterval string + +// List of values that PlanInterval can take +const ( + PlanIntervalDay PlanInterval = "day" + PlanIntervalMonth PlanInterval = "month" + PlanIntervalWeek PlanInterval = "week" + PlanIntervalYear PlanInterval = "year" +) + +// Defines if the tiering price should be `graduated` or `volume` based. In `volume`-based tiering, the maximum quantity within a period determines the per unit price. In `graduated` tiering, pricing can change as the quantity grows. +type PlanTiersMode string + +// List of values that PlanTiersMode can take +const ( + PlanTiersModeGraduated PlanTiersMode = "graduated" + PlanTiersModeVolume PlanTiersMode = "volume" +) + +// After division, either round the result `up` or `down`. +type PlanTransformUsageRound string + +// List of values that PlanTransformUsageRound can take +const ( + PlanTransformUsageRoundDown PlanTransformUsageRound = "down" + PlanTransformUsageRoundUp PlanTransformUsageRound = "up" +) + +// Configures how the quantity per period should be determined. Can be either `metered` or `licensed`. `licensed` automatically bills the `quantity` set when adding it to a subscription. `metered` aggregates the total usage based on usage records. Defaults to `licensed`. +type PlanUsageType string + +// List of values that PlanUsageType can take +const ( + PlanUsageTypeLicensed PlanUsageType = "licensed" + PlanUsageTypeMetered PlanUsageType = "metered" +) + +// Deleting plans means new subscribers can't be added. Existing subscribers aren't affected. +type PlanParams struct { + Params `form:"*"` + // Whether the plan is currently available for new subscriptions. Defaults to `true`. + Active *bool `form:"active"` + // A positive integer in cents (or local equivalent) (or 0 for a free plan) representing how much to charge on a recurring basis. + Amount *int64 `form:"amount"` + // Same as `amount`, but accepts a decimal value with at most 12 decimal places. Only one of `amount` and `amount_decimal` can be set. + AmountDecimal *float64 `form:"amount_decimal,high_precision"` + // Describes how to compute the price per period. Either `per_unit` or `tiered`. `per_unit` indicates that the fixed amount (specified in `amount`) will be charged per unit in `quantity` (for plans with `usage_type=licensed`), or per unit of total usage (for plans with `usage_type=metered`). `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. + BillingScheme *string `form:"billing_scheme"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // An identifier randomly generated by Stripe. Used to identify this plan when subscribing a customer. You can optionally override this ID, but the ID must be unique across all plans in your Stripe account. You can, however, use the same plan ID in both live and test modes. + ID *string `form:"id"` + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The meter tracking the usage of a metered price + Meter *string `form:"meter"` + // A brief description of the plan, hidden from customers. + Nickname *string `form:"nickname"` + // The product the plan belongs to. This cannot be changed once it has been used in a subscription or subscription schedule. + Product *PlanProductParams `form:"product"` + // The product the plan belongs to. This cannot be changed once it has been used in a subscription or subscription schedule. + ProductID *string `form:"product"` + // Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + Tiers []*PlanTierParams `form:"tiers"` + // Defines if the tiering price should be `graduated` or `volume` based. In `volume`-based tiering, the maximum quantity within a period determines the per unit price, in `graduated` tiering pricing can successively change as the quantity grows. + TiersMode *string `form:"tiers_mode"` + // Apply a transformation to the reported usage or set quantity before computing the billed price. Cannot be combined with `tiers`. + TransformUsage *PlanTransformUsageParams `form:"transform_usage"` + // Default number of trial days when subscribing a customer to this plan using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan). + TrialPeriodDays *int64 `form:"trial_period_days"` + // Configures how the quantity per period should be determined. Can be either `metered` or `licensed`. `licensed` automatically bills the `quantity` set when adding it to a subscription. `metered` aggregates the total usage based on usage records. Defaults to `licensed`. + UsageType *string `form:"usage_type"` +} + +// AddExpand appends a new field to expand. +func (p *PlanParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PlanParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Returns a list of your plans. +type PlanListParams struct { + ListParams `form:"*"` + // Only return plans that are active or inactive (e.g., pass `false` to list all inactive plans). + Active *bool `form:"active"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + Created *int64 `form:"created"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return plans for the given product. + Product *string `form:"product"` +} + +// AddExpand appends a new field to expand. +func (p *PlanListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type PlanProductParams struct { + // Whether the product is currently available for purchase. Defaults to `true`. + Active *bool `form:"active"` + // The identifier for the product. Must be unique. If not provided, an identifier will be randomly generated. + ID *string `form:"id"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The product's name, meant to be displayable to the customer. + Name *string `form:"name"` + // An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all. + // + // This may be up to 22 characters. The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped. + StatementDescriptor *string `form:"statement_descriptor"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` + // A label that represents units of this product. When set, this will be included in customers' receipts, invoices, Checkout, and the customer portal. + UnitLabel *string `form:"unit_label"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PlanProductParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. +type PlanTierParams struct { + Params `form:"*"` + // The flat billing amount for an entire tier, regardless of the number of units in the tier. + FlatAmount *int64 `form:"flat_amount"` + // Same as `flat_amount`, but accepts a decimal value representing an integer in the minor units of the currency. Only one of `flat_amount` and `flat_amount_decimal` can be set. + FlatAmountDecimal *float64 `form:"flat_amount_decimal,high_precision"` + // The per unit billing amount for each individual unit for which this tier applies. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` + // Specifies the upper bound of this tier. The lower bound of a tier is the upper bound of the previous tier adding one. Use `inf` to define a fallback tier. + UpTo *int64 `form:"-"` // See custom AppendTo + UpToInf *bool `form:"-"` // See custom AppendTo +} + +// AppendTo implements custom encoding logic for PlanTierParams. +func (p *PlanTierParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.UpToInf) { + body.Add(form.FormatKey(append(keyParts, "up_to")), "inf") + } else { + body.Add( + form.FormatKey(append(keyParts, "up_to")), strconv.FormatInt( + Int64Value(p.UpTo), 10)) + } +} + +// Apply a transformation to the reported usage or set quantity before computing the billed price. Cannot be combined with `tiers`. +type PlanTransformUsageParams struct { + // Divide usage by this number. + DivideBy *int64 `form:"divide_by"` + // After division, either round the result `up` or `down`. + Round *string `form:"round"` +} + +// Deleting plans means new subscribers can't be added. Existing subscribers aren't affected. +type PlanDeleteParams struct { + Params `form:"*"` +} + +// Retrieves the plan with the given ID. +type PlanRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PlanRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the specified plan by setting the values of the parameters passed. Any parameters not provided are left unchanged. By design, you cannot change a plan's ID, amount, currency, or billing cycle. +type PlanUpdateParams struct { + Params `form:"*"` + // Whether the plan is currently available for new subscriptions. + Active *bool `form:"active"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // A brief description of the plan, hidden from customers. + Nickname *string `form:"nickname"` + // The product the plan belongs to. This cannot be changed once it has been used in a subscription or subscription schedule. + Product *string `form:"product"` + // Default number of trial days when subscribing a customer to this plan using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan). + TrialPeriodDays *int64 `form:"trial_period_days"` +} + +// AddExpand appends a new field to expand. +func (p *PlanUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PlanUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +type PlanCreateProductParams struct { + // Whether the product is currently available for purchase. Defaults to `true`. + Active *bool `form:"active"` + // The identifier for the product. Must be unique. If not provided, an identifier will be randomly generated. + ID *string `form:"id"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The product's name, meant to be displayable to the customer. + Name *string `form:"name"` + // An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all. + // + // This may be up to 22 characters. The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped. + StatementDescriptor *string `form:"statement_descriptor"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` + // A label that represents units of this product. When set, this will be included in customers' receipts, invoices, Checkout, and the customer portal. + UnitLabel *string `form:"unit_label"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PlanCreateProductParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. +type PlanCreateTierParams struct { + Params `form:"*"` + // The flat billing amount for an entire tier, regardless of the number of units in the tier. + FlatAmount *int64 `form:"flat_amount"` + // Same as `flat_amount`, but accepts a decimal value representing an integer in the minor units of the currency. Only one of `flat_amount` and `flat_amount_decimal` can be set. + FlatAmountDecimal *float64 `form:"flat_amount_decimal,high_precision"` + // The per unit billing amount for each individual unit for which this tier applies. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` + // Specifies the upper bound of this tier. The lower bound of a tier is the upper bound of the previous tier adding one. Use `inf` to define a fallback tier. + UpTo *int64 `form:"-"` // See custom AppendTo + UpToInf *bool `form:"-"` // See custom AppendTo +} + +// AppendTo implements custom encoding logic for PlanCreateTierParams. +func (p *PlanCreateTierParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.UpToInf) { + body.Add(form.FormatKey(append(keyParts, "up_to")), "inf") + } else { + body.Add( + form.FormatKey(append(keyParts, "up_to")), strconv.FormatInt( + Int64Value(p.UpTo), 10)) + } +} + +// Apply a transformation to the reported usage or set quantity before computing the billed price. Cannot be combined with `tiers`. +type PlanCreateTransformUsageParams struct { + // Divide usage by this number. + DivideBy *int64 `form:"divide_by"` + // After division, either round the result `up` or `down`. + Round *string `form:"round"` +} + +// You can now model subscriptions more flexibly using the [Prices API](https://docs.stripe.com/api#prices). It replaces the Plans API and is backwards compatible to simplify your migration. +type PlanCreateParams struct { + Params `form:"*"` + // Whether the plan is currently available for new subscriptions. Defaults to `true`. + Active *bool `form:"active"` + // A positive integer in cents (or local equivalent) (or 0 for a free plan) representing how much to charge on a recurring basis. + Amount *int64 `form:"amount"` + // Same as `amount`, but accepts a decimal value with at most 12 decimal places. Only one of `amount` and `amount_decimal` can be set. + AmountDecimal *float64 `form:"amount_decimal,high_precision"` + // Describes how to compute the price per period. Either `per_unit` or `tiered`. `per_unit` indicates that the fixed amount (specified in `amount`) will be charged per unit in `quantity` (for plans with `usage_type=licensed`), or per unit of total usage (for plans with `usage_type=metered`). `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. + BillingScheme *string `form:"billing_scheme"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // An identifier randomly generated by Stripe. Used to identify this plan when subscribing a customer. You can optionally override this ID, but the ID must be unique across all plans in your Stripe account. You can, however, use the same plan ID in both live and test modes. + ID *string `form:"id"` + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The meter tracking the usage of a metered price + Meter *string `form:"meter"` + // A brief description of the plan, hidden from customers. + Nickname *string `form:"nickname"` + Product *PlanCreateProductParams `form:"product"` + ProductID *string `form:"product"` + // Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + Tiers []*PlanCreateTierParams `form:"tiers"` + // Defines if the tiering price should be `graduated` or `volume` based. In `volume`-based tiering, the maximum quantity within a period determines the per unit price, in `graduated` tiering pricing can successively change as the quantity grows. + TiersMode *string `form:"tiers_mode"` + // Apply a transformation to the reported usage or set quantity before computing the billed price. Cannot be combined with `tiers`. + TransformUsage *PlanCreateTransformUsageParams `form:"transform_usage"` + // Default number of trial days when subscribing a customer to this plan using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan). + TrialPeriodDays *int64 `form:"trial_period_days"` + // Configures how the quantity per period should be determined. Can be either `metered` or `licensed`. `licensed` automatically bills the `quantity` set when adding it to a subscription. `metered` aggregates the total usage based on usage records. Defaults to `licensed`. + UsageType *string `form:"usage_type"` +} + +// AddExpand appends a new field to expand. +func (p *PlanCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PlanCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. +type PlanTier struct { + // Price for the entire tier. + FlatAmount int64 `json:"flat_amount"` + // Same as `flat_amount`, but contains a decimal value with at most 12 decimal places. + FlatAmountDecimal float64 `json:"flat_amount_decimal,string"` + // Per unit price for units relevant to the tier. + UnitAmount int64 `json:"unit_amount"` + // Same as `unit_amount`, but contains a decimal value with at most 12 decimal places. + UnitAmountDecimal float64 `json:"unit_amount_decimal,string"` + // Up to and including to this quantity will be contained in the tier. + UpTo int64 `json:"up_to"` +} + +// Apply a transformation to the reported usage or set quantity before computing the amount billed. Cannot be combined with `tiers`. +type PlanTransformUsage struct { + // Divide usage by this number. + DivideBy int64 `json:"divide_by"` + // After division, either round the result `up` or `down`. + Round PlanTransformUsageRound `json:"round"` +} + +// You can now model subscriptions more flexibly using the [Prices API](https://stripe.com/docs/api#prices). It replaces the Plans API and is backwards compatible to simplify your migration. +// +// Plans define the base price, currency, and billing cycle for recurring purchases of products. +// [Products](https://stripe.com/docs/api#products) help you track inventory or provisioning, and plans help you track pricing. Different physical goods or levels of service should be represented by products, and pricing options should be represented by plans. This approach lets you change prices without having to change your provisioning scheme. +// +// For example, you might have a single "gold" product that has plans for $10/month, $100/year, €9/month, and €90/year. +// +// Related guides: [Set up a subscription](https://stripe.com/docs/billing/subscriptions/set-up-subscription) and more about [products and prices](https://stripe.com/docs/products-prices/overview). +type Plan struct { + APIResource + // Whether the plan can be used for new purchases. + Active bool `json:"active"` + // The unit amount in cents (or local equivalent) to be charged, represented as a whole integer if possible. Only set if `billing_scheme=per_unit`. + Amount int64 `json:"amount"` + // The unit amount in cents (or local equivalent) to be charged, represented as a decimal string with at most 12 decimal places. Only set if `billing_scheme=per_unit`. + AmountDecimal float64 `json:"amount_decimal,string"` + // Describes how to compute the price per period. Either `per_unit` or `tiered`. `per_unit` indicates that the fixed amount (specified in `amount`) will be charged per unit in `quantity` (for plans with `usage_type=licensed`), or per unit of total usage (for plans with `usage_type=metered`). `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. + BillingScheme PlanBillingScheme `json:"billing_scheme"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + Deleted bool `json:"deleted"` + // Unique identifier for the object. + ID string `json:"id"` + // The frequency at which a subscription is billed. One of `day`, `week`, `month` or `year`. + Interval PlanInterval `json:"interval"` + // The number of intervals (specified in the `interval` attribute) between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. + IntervalCount int64 `json:"interval_count"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // The meter tracking the usage of a metered price + Meter string `json:"meter"` + // A brief description of the plan, hidden from customers. + Nickname string `json:"nickname"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The product whose pricing this plan determines. + Product *Product `json:"product"` + // Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + Tiers []*PlanTier `json:"tiers"` + // Defines if the tiering price should be `graduated` or `volume` based. In `volume`-based tiering, the maximum quantity within a period determines the per unit price. In `graduated` tiering, pricing can change as the quantity grows. + TiersMode PlanTiersMode `json:"tiers_mode"` + // Apply a transformation to the reported usage or set quantity before computing the amount billed. Cannot be combined with `tiers`. + TransformUsage *PlanTransformUsage `json:"transform_usage"` + // Default number of trial days when subscribing a customer to this plan using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan). + TrialPeriodDays int64 `json:"trial_period_days"` + // Configures how the quantity per period should be determined. Can be either `metered` or `licensed`. `licensed` automatically bills the `quantity` set when adding it to a subscription. `metered` aggregates the total usage based on usage records. Defaults to `licensed`. + UsageType PlanUsageType `json:"usage_type"` +} + +// PlanList is a list of Plans as retrieved from a list endpoint. +type PlanList struct { + APIResource + ListMeta + Data []*Plan `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Plan. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (p *Plan) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + p.ID = id + return nil + } + + type plan Plan + var v plan + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *p = Plan(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/plan_service.go b/vendor/github.com/stripe/stripe-go/v82/plan_service.go new file mode 100644 index 00000000..fa0cfd44 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/plan_service.go @@ -0,0 +1,84 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1PlanService is used to invoke /v1/plans APIs. +type v1PlanService struct { + B Backend + Key string +} + +// You can now model subscriptions more flexibly using the [Prices API](https://docs.stripe.com/api#prices). It replaces the Plans API and is backwards compatible to simplify your migration. +func (c v1PlanService) Create(ctx context.Context, params *PlanCreateParams) (*Plan, error) { + if params == nil { + params = &PlanCreateParams{} + } + params.Context = ctx + plan := &Plan{} + err := c.B.Call(http.MethodPost, "/v1/plans", c.Key, params, plan) + return plan, err +} + +// Retrieves the plan with the given ID. +func (c v1PlanService) Retrieve(ctx context.Context, id string, params *PlanRetrieveParams) (*Plan, error) { + if params == nil { + params = &PlanRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/plans/%s", id) + plan := &Plan{} + err := c.B.Call(http.MethodGet, path, c.Key, params, plan) + return plan, err +} + +// Updates the specified plan by setting the values of the parameters passed. Any parameters not provided are left unchanged. By design, you cannot change a plan's ID, amount, currency, or billing cycle. +func (c v1PlanService) Update(ctx context.Context, id string, params *PlanUpdateParams) (*Plan, error) { + if params == nil { + params = &PlanUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/plans/%s", id) + plan := &Plan{} + err := c.B.Call(http.MethodPost, path, c.Key, params, plan) + return plan, err +} + +// Deleting plans means new subscribers can't be added. Existing subscribers aren't affected. +func (c v1PlanService) Delete(ctx context.Context, id string, params *PlanDeleteParams) (*Plan, error) { + if params == nil { + params = &PlanDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/plans/%s", id) + plan := &Plan{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, plan) + return plan, err +} + +// Returns a list of your plans. +func (c v1PlanService) List(ctx context.Context, listParams *PlanListParams) Seq2[*Plan, error] { + if listParams == nil { + listParams = &PlanListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Plan, ListContainer, error) { + list := &PlanList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/plans", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/price.go b/vendor/github.com/stripe/stripe-go/v82/price.go new file mode 100644 index 00000000..aea27273 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/price.go @@ -0,0 +1,788 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "encoding/json" + "github.com/stripe/stripe-go/v82/form" +) + +// Describes how to compute the price per period. Either `per_unit` or `tiered`. `per_unit` indicates that the fixed amount (specified in `unit_amount` or `unit_amount_decimal`) will be charged per unit in `quantity` (for prices with `usage_type=licensed`), or per unit of total usage (for prices with `usage_type=metered`). `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. +type PriceBillingScheme string + +// List of values that PriceBillingScheme can take +const ( + PriceBillingSchemePerUnit PriceBillingScheme = "per_unit" + PriceBillingSchemeTiered PriceBillingScheme = "tiered" +) + +// Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. +type PriceCurrencyOptionsTaxBehavior string + +// List of values that PriceCurrencyOptionsTaxBehavior can take +const ( + PriceCurrencyOptionsTaxBehaviorExclusive PriceCurrencyOptionsTaxBehavior = "exclusive" + PriceCurrencyOptionsTaxBehaviorInclusive PriceCurrencyOptionsTaxBehavior = "inclusive" + PriceCurrencyOptionsTaxBehaviorUnspecified PriceCurrencyOptionsTaxBehavior = "unspecified" +) + +// The frequency at which a subscription is billed. One of `day`, `week`, `month` or `year`. +type PriceRecurringInterval string + +// List of values that PriceRecurringInterval can take +const ( + PriceRecurringIntervalDay PriceRecurringInterval = "day" + PriceRecurringIntervalMonth PriceRecurringInterval = "month" + PriceRecurringIntervalWeek PriceRecurringInterval = "week" + PriceRecurringIntervalYear PriceRecurringInterval = "year" +) + +// Configures how the quantity per period should be determined. Can be either `metered` or `licensed`. `licensed` automatically bills the `quantity` set when adding it to a subscription. `metered` aggregates the total usage based on usage records. Defaults to `licensed`. +type PriceRecurringUsageType string + +// List of values that PriceRecurringUsageType can take +const ( + PriceRecurringUsageTypeLicensed PriceRecurringUsageType = "licensed" + PriceRecurringUsageTypeMetered PriceRecurringUsageType = "metered" +) + +// Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. +type PriceTaxBehavior string + +// List of values that PriceTaxBehavior can take +const ( + PriceTaxBehaviorExclusive PriceTaxBehavior = "exclusive" + PriceTaxBehaviorInclusive PriceTaxBehavior = "inclusive" + PriceTaxBehaviorUnspecified PriceTaxBehavior = "unspecified" +) + +// Defines if the tiering price should be `graduated` or `volume` based. In `volume`-based tiering, the maximum quantity within a period determines the per unit price. In `graduated` tiering, pricing can change as the quantity grows. +type PriceTiersMode string + +// List of values that PriceTiersMode can take +const ( + PriceTiersModeGraduated PriceTiersMode = "graduated" + PriceTiersModeVolume PriceTiersMode = "volume" +) + +// After division, either round the result `up` or `down`. +type PriceTransformQuantityRound string + +// List of values that PriceTransformQuantityRound can take +const ( + PriceTransformQuantityRoundDown PriceTransformQuantityRound = "down" + PriceTransformQuantityRoundUp PriceTransformQuantityRound = "up" +) + +// One of `one_time` or `recurring` depending on whether the price is for a one-time purchase or a recurring (subscription) purchase. +type PriceType string + +// List of values that PriceType can take +const ( + PriceTypeOneTime PriceType = "one_time" + PriceTypeRecurring PriceType = "recurring" +) + +// Only return prices with these recurring fields. +type PriceListRecurringParams struct { + // Filter by billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // Filter by the price's meter. + Meter *string `form:"meter"` + // Filter by the usage type for this price. Can be either `metered` or `licensed`. + UsageType *string `form:"usage_type"` +} + +// Returns a list of your active prices, excluding [inline prices](https://docs.stripe.com/docs/products-prices/pricing-models#inline-pricing). For the list of inactive prices, set active to false. +type PriceListParams struct { + ListParams `form:"*"` + // Only return prices that are active or inactive (e.g., pass `false` to list all inactive prices). + Active *bool `form:"active"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + Created *int64 `form:"created"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + CreatedRange *RangeQueryParams `form:"created"` + // Only return prices for the given currency. + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return the price with these lookup_keys, if any exist. You can specify up to 10 lookup_keys. + LookupKeys []*string `form:"lookup_keys"` + // Only return prices for the given product. + Product *string `form:"product"` + // Only return prices with these recurring fields. + Recurring *PriceListRecurringParams `form:"recurring"` + // Only return prices of type `recurring` or `one_time`. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *PriceListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. +type PriceCurrencyOptionsCustomUnitAmountParams struct { + // Pass in `true` to enable `custom_unit_amount`, otherwise omit `custom_unit_amount`. + Enabled *bool `form:"enabled"` + // The maximum unit amount the customer can specify for this item. + Maximum *int64 `form:"maximum"` + // The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + Minimum *int64 `form:"minimum"` + // The starting unit amount which can be updated by the customer. + Preset *int64 `form:"preset"` +} + +// Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. +type PriceCurrencyOptionsTierParams struct { + // The flat billing amount for an entire tier, regardless of the number of units in the tier. + FlatAmount *int64 `form:"flat_amount"` + // Same as `flat_amount`, but accepts a decimal value representing an integer in the minor units of the currency. Only one of `flat_amount` and `flat_amount_decimal` can be set. + FlatAmountDecimal *float64 `form:"flat_amount_decimal,high_precision"` + // The per unit billing amount for each individual unit for which this tier applies. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` + // Specifies the upper bound of this tier. The lower bound of a tier is the upper bound of the previous tier adding one. Use `inf` to define a fallback tier. + UpTo *int64 `form:"up_to"` + UpToInf *bool `form:"-"` // See custom AppendTo +} + +// AppendTo implements custom encoding logic for PriceCurrencyOptionsTierParams. +func (p *PriceCurrencyOptionsTierParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.UpToInf) { + body.Add(form.FormatKey(append(keyParts, "up_to")), "inf") + } +} + +// Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type PriceCurrencyOptionsParams struct { + // When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + CustomUnitAmount *PriceCurrencyOptionsCustomUnitAmountParams `form:"custom_unit_amount"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + Tiers []*PriceCurrencyOptionsTierParams `form:"tiers"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. +type PriceCustomUnitAmountParams struct { + // Pass in `true` to enable `custom_unit_amount`, otherwise omit `custom_unit_amount`. + Enabled *bool `form:"enabled"` + // The maximum unit amount the customer can specify for this item. + Maximum *int64 `form:"maximum"` + // The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + Minimum *int64 `form:"minimum"` + // The starting unit amount which can be updated by the customer. + Preset *int64 `form:"preset"` +} + +// These fields can be used to create a new product that this price will belong to. +type PriceProductDataParams struct { + // Whether the product is currently available for purchase. Defaults to `true`. + Active *bool `form:"active"` + // The identifier for the product. Must be unique. If not provided, an identifier will be randomly generated. + ID *string `form:"id"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The product's name, meant to be displayable to the customer. + Name *string `form:"name"` + // An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all. + // + // This may be up to 22 characters. The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped. + StatementDescriptor *string `form:"statement_descriptor"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` + // A label that represents units of this product. When set, this will be included in customers' receipts, invoices, Checkout, and the customer portal. + UnitLabel *string `form:"unit_label"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PriceProductDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The recurring components of a price such as `interval` and `usage_type`. +type PriceRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` + // The meter tracking the usage of a metered price + Meter *string `form:"meter"` + // Default number of trial days when subscribing a customer to this price using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan). + TrialPeriodDays *int64 `form:"trial_period_days"` + // Configures how the quantity per period should be determined. Can be either `metered` or `licensed`. `licensed` automatically bills the `quantity` set when adding it to a subscription. `metered` aggregates the total usage based on usage records. Defaults to `licensed`. + UsageType *string `form:"usage_type"` +} + +// Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. +type PriceTierParams struct { + // The flat billing amount for an entire tier, regardless of the number of units in the tier. + FlatAmount *int64 `form:"flat_amount"` + // Same as `flat_amount`, but accepts a decimal value representing an integer in the minor units of the currency. Only one of `flat_amount` and `flat_amount_decimal` can be set. + FlatAmountDecimal *float64 `form:"flat_amount_decimal,high_precision"` + // The per unit billing amount for each individual unit for which this tier applies. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` + // Specifies the upper bound of this tier. The lower bound of a tier is the upper bound of the previous tier adding one. Use `inf` to define a fallback tier. + UpTo *int64 `form:"up_to"` + UpToInf *bool `form:"-"` // See custom AppendTo +} + +// AppendTo implements custom encoding logic for PriceTierParams. +func (p *PriceTierParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.UpToInf) { + body.Add(form.FormatKey(append(keyParts, "up_to")), "inf") + } +} + +// Apply a transformation to the reported usage or set quantity before computing the billed price. Cannot be combined with `tiers`. +type PriceTransformQuantityParams struct { + // Divide usage by this number. + DivideBy *int64 `form:"divide_by"` + // After division, either round the result `up` or `down`. + Round *string `form:"round"` +} + +// Creates a new [Price for an existing Product](https://docs.stripe.com/api/prices). The Price can be recurring or one-time. +type PriceParams struct { + Params `form:"*"` + // Whether the price can be used for new purchases. Defaults to `true`. + Active *bool `form:"active"` + // Describes how to compute the price per period. Either `per_unit` or `tiered`. `per_unit` indicates that the fixed amount (specified in `unit_amount` or `unit_amount_decimal`) will be charged per unit in `quantity` (for prices with `usage_type=licensed`), or per unit of total usage (for prices with `usage_type=metered`). `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. + BillingScheme *string `form:"billing_scheme"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*PriceCurrencyOptionsParams `form:"currency_options"` + // When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + CustomUnitAmount *PriceCustomUnitAmountParams `form:"custom_unit_amount"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A lookup key used to retrieve prices dynamically from a static string. This may be up to 200 characters. + LookupKey *string `form:"lookup_key"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // A brief description of the price, hidden from customers. + Nickname *string `form:"nickname"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // These fields can be used to create a new product that this price will belong to. + ProductData *PriceProductDataParams `form:"product_data"` + // The recurring components of a price such as `interval` and `usage_type`. + Recurring *PriceRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + Tiers []*PriceTierParams `form:"tiers"` + // Defines if the tiering price should be `graduated` or `volume` based. In `volume`-based tiering, the maximum quantity within a period determines the per unit price, in `graduated` tiering pricing can successively change as the quantity grows. + TiersMode *string `form:"tiers_mode"` + // If set to true, will atomically remove the lookup key from the existing price, and assign it to this price. + TransferLookupKey *bool `form:"transfer_lookup_key"` + // Apply a transformation to the reported usage or set quantity before computing the billed price. Cannot be combined with `tiers`. + TransformQuantity *PriceTransformQuantityParams `form:"transform_quantity"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. One of `unit_amount`, `unit_amount_decimal`, or `custom_unit_amount` is required, unless `billing_scheme=tiered`. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// AddExpand appends a new field to expand. +func (p *PriceParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PriceParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Search for prices you've previously created using Stripe's [Search Query Language](https://docs.stripe.com/docs/search#search-query-language). +// Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating +// conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up +// to an hour behind during outages. Search functionality is not available to merchants in India. +type PriceSearchParams struct { + SearchParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + Page *string `form:"page"` +} + +// AddExpand appends a new field to expand. +func (p *PriceSearchParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. +type PriceCreateCurrencyOptionsCustomUnitAmountParams struct { + // Pass in `true` to enable `custom_unit_amount`, otherwise omit `custom_unit_amount`. + Enabled *bool `form:"enabled"` + // The maximum unit amount the customer can specify for this item. + Maximum *int64 `form:"maximum"` + // The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + Minimum *int64 `form:"minimum"` + // The starting unit amount which can be updated by the customer. + Preset *int64 `form:"preset"` +} + +// Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. +type PriceCreateCurrencyOptionsTierParams struct { + // The flat billing amount for an entire tier, regardless of the number of units in the tier. + FlatAmount *int64 `form:"flat_amount"` + // Same as `flat_amount`, but accepts a decimal value representing an integer in the minor units of the currency. Only one of `flat_amount` and `flat_amount_decimal` can be set. + FlatAmountDecimal *float64 `form:"flat_amount_decimal,high_precision"` + // The per unit billing amount for each individual unit for which this tier applies. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` + // Specifies the upper bound of this tier. The lower bound of a tier is the upper bound of the previous tier adding one. Use `inf` to define a fallback tier. + UpTo *int64 `form:"up_to"` + UpToInf *bool `form:"-"` // See custom AppendTo +} + +// AppendTo implements custom encoding logic for PriceCreateCurrencyOptionsTierParams. +func (p *PriceCreateCurrencyOptionsTierParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.UpToInf) { + body.Add(form.FormatKey(append(keyParts, "up_to")), "inf") + } +} + +// Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type PriceCreateCurrencyOptionsParams struct { + // When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + CustomUnitAmount *PriceCreateCurrencyOptionsCustomUnitAmountParams `form:"custom_unit_amount"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + Tiers []*PriceCreateCurrencyOptionsTierParams `form:"tiers"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. +type PriceCreateCustomUnitAmountParams struct { + // Pass in `true` to enable `custom_unit_amount`, otherwise omit `custom_unit_amount`. + Enabled *bool `form:"enabled"` + // The maximum unit amount the customer can specify for this item. + Maximum *int64 `form:"maximum"` + // The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + Minimum *int64 `form:"minimum"` + // The starting unit amount which can be updated by the customer. + Preset *int64 `form:"preset"` +} + +// These fields can be used to create a new product that this price will belong to. +type PriceCreateProductDataParams struct { + // Whether the product is currently available for purchase. Defaults to `true`. + Active *bool `form:"active"` + // The identifier for the product. Must be unique. If not provided, an identifier will be randomly generated. + ID *string `form:"id"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The product's name, meant to be displayable to the customer. + Name *string `form:"name"` + // An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all. + // + // This may be up to 22 characters. The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped. + StatementDescriptor *string `form:"statement_descriptor"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` + // A label that represents units of this product. When set, this will be included in customers' receipts, invoices, Checkout, and the customer portal. + UnitLabel *string `form:"unit_label"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PriceCreateProductDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The recurring components of a price such as `interval` and `usage_type`. +type PriceCreateRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` + // The meter tracking the usage of a metered price + Meter *string `form:"meter"` + // Default number of trial days when subscribing a customer to this price using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan). + TrialPeriodDays *int64 `form:"trial_period_days"` + // Configures how the quantity per period should be determined. Can be either `metered` or `licensed`. `licensed` automatically bills the `quantity` set when adding it to a subscription. `metered` aggregates the total usage based on usage records. Defaults to `licensed`. + UsageType *string `form:"usage_type"` +} + +// Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. +type PriceCreateTierParams struct { + // The flat billing amount for an entire tier, regardless of the number of units in the tier. + FlatAmount *int64 `form:"flat_amount"` + // Same as `flat_amount`, but accepts a decimal value representing an integer in the minor units of the currency. Only one of `flat_amount` and `flat_amount_decimal` can be set. + FlatAmountDecimal *float64 `form:"flat_amount_decimal,high_precision"` + // The per unit billing amount for each individual unit for which this tier applies. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` + // Specifies the upper bound of this tier. The lower bound of a tier is the upper bound of the previous tier adding one. Use `inf` to define a fallback tier. + UpTo *int64 `form:"up_to"` + UpToInf *bool `form:"-"` // See custom AppendTo +} + +// AppendTo implements custom encoding logic for PriceCreateTierParams. +func (p *PriceCreateTierParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.UpToInf) { + body.Add(form.FormatKey(append(keyParts, "up_to")), "inf") + } +} + +// Apply a transformation to the reported usage or set quantity before computing the billed price. Cannot be combined with `tiers`. +type PriceCreateTransformQuantityParams struct { + // Divide usage by this number. + DivideBy *int64 `form:"divide_by"` + // After division, either round the result `up` or `down`. + Round *string `form:"round"` +} + +// Creates a new [Price for an existing Product](https://docs.stripe.com/api/prices). The Price can be recurring or one-time. +type PriceCreateParams struct { + Params `form:"*"` + // Whether the price can be used for new purchases. Defaults to `true`. + Active *bool `form:"active"` + // Describes how to compute the price per period. Either `per_unit` or `tiered`. `per_unit` indicates that the fixed amount (specified in `unit_amount` or `unit_amount_decimal`) will be charged per unit in `quantity` (for prices with `usage_type=licensed`), or per unit of total usage (for prices with `usage_type=metered`). `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. + BillingScheme *string `form:"billing_scheme"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*PriceCreateCurrencyOptionsParams `form:"currency_options"` + // When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + CustomUnitAmount *PriceCreateCustomUnitAmountParams `form:"custom_unit_amount"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A lookup key used to retrieve prices dynamically from a static string. This may be up to 200 characters. + LookupKey *string `form:"lookup_key"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // A brief description of the price, hidden from customers. + Nickname *string `form:"nickname"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // These fields can be used to create a new product that this price will belong to. + ProductData *PriceCreateProductDataParams `form:"product_data"` + // The recurring components of a price such as `interval` and `usage_type`. + Recurring *PriceCreateRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + Tiers []*PriceCreateTierParams `form:"tiers"` + // Defines if the tiering price should be `graduated` or `volume` based. In `volume`-based tiering, the maximum quantity within a period determines the per unit price, in `graduated` tiering pricing can successively change as the quantity grows. + TiersMode *string `form:"tiers_mode"` + // If set to true, will atomically remove the lookup key from the existing price, and assign it to this price. + TransferLookupKey *bool `form:"transfer_lookup_key"` + // Apply a transformation to the reported usage or set quantity before computing the billed price. Cannot be combined with `tiers`. + TransformQuantity *PriceCreateTransformQuantityParams `form:"transform_quantity"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. One of `unit_amount`, `unit_amount_decimal`, or `custom_unit_amount` is required, unless `billing_scheme=tiered`. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// AddExpand appends a new field to expand. +func (p *PriceCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PriceCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the price with the given ID. +type PriceRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PriceRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. +type PriceUpdateCurrencyOptionsCustomUnitAmountParams struct { + // Pass in `true` to enable `custom_unit_amount`, otherwise omit `custom_unit_amount`. + Enabled *bool `form:"enabled"` + // The maximum unit amount the customer can specify for this item. + Maximum *int64 `form:"maximum"` + // The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + Minimum *int64 `form:"minimum"` + // The starting unit amount which can be updated by the customer. + Preset *int64 `form:"preset"` +} + +// Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. +type PriceUpdateCurrencyOptionsTierParams struct { + // The flat billing amount for an entire tier, regardless of the number of units in the tier. + FlatAmount *int64 `form:"flat_amount"` + // Same as `flat_amount`, but accepts a decimal value representing an integer in the minor units of the currency. Only one of `flat_amount` and `flat_amount_decimal` can be set. + FlatAmountDecimal *float64 `form:"flat_amount_decimal,high_precision"` + // The per unit billing amount for each individual unit for which this tier applies. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` + // Specifies the upper bound of this tier. The lower bound of a tier is the upper bound of the previous tier adding one. Use `inf` to define a fallback tier. + UpTo *int64 `form:"up_to"` + UpToInf *bool `form:"-"` // See custom AppendTo +} + +// AppendTo implements custom encoding logic for PriceUpdateCurrencyOptionsTierParams. +func (p *PriceUpdateCurrencyOptionsTierParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.UpToInf) { + body.Add(form.FormatKey(append(keyParts, "up_to")), "inf") + } +} + +// Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type PriceUpdateCurrencyOptionsParams struct { + // When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + CustomUnitAmount *PriceUpdateCurrencyOptionsCustomUnitAmountParams `form:"custom_unit_amount"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + Tiers []*PriceUpdateCurrencyOptionsTierParams `form:"tiers"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// Updates the specified price by setting the values of the parameters passed. Any parameters not provided are left unchanged. +type PriceUpdateParams struct { + Params `form:"*"` + // Whether the price can be used for new purchases. Defaults to `true`. + Active *bool `form:"active"` + // Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*PriceUpdateCurrencyOptionsParams `form:"currency_options"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A lookup key used to retrieve prices dynamically from a static string. This may be up to 200 characters. + LookupKey *string `form:"lookup_key"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // A brief description of the price, hidden from customers. + Nickname *string `form:"nickname"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // If set to true, will atomically remove the lookup key from the existing price, and assign it to this price. + TransferLookupKey *bool `form:"transfer_lookup_key"` +} + +// AddExpand appends a new field to expand. +func (p *PriceUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PriceUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. +type PriceCurrencyOptionsCustomUnitAmount struct { + // The maximum unit amount the customer can specify for this item. + Maximum int64 `json:"maximum"` + // The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + Minimum int64 `json:"minimum"` + // The starting unit amount which can be updated by the customer. + Preset int64 `json:"preset"` +} + +// Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. +type PriceCurrencyOptionsTier struct { + // Price for the entire tier. + FlatAmount int64 `json:"flat_amount"` + // Same as `flat_amount`, but contains a decimal value with at most 12 decimal places. + FlatAmountDecimal float64 `json:"flat_amount_decimal,string"` + // Per unit price for units relevant to the tier. + UnitAmount int64 `json:"unit_amount"` + // Same as `unit_amount`, but contains a decimal value with at most 12 decimal places. + UnitAmountDecimal float64 `json:"unit_amount_decimal,string"` + // Up to and including to this quantity will be contained in the tier. + UpTo int64 `json:"up_to"` +} + +// Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type PriceCurrencyOptions struct { + // When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + CustomUnitAmount *PriceCurrencyOptionsCustomUnitAmount `json:"custom_unit_amount"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior PriceCurrencyOptionsTaxBehavior `json:"tax_behavior"` + // Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + Tiers []*PriceCurrencyOptionsTier `json:"tiers"` + // The unit amount in cents (or local equivalent) to be charged, represented as a whole integer if possible. Only set if `billing_scheme=per_unit`. + UnitAmount int64 `json:"unit_amount"` + // The unit amount in cents (or local equivalent) to be charged, represented as a decimal string with at most 12 decimal places. Only set if `billing_scheme=per_unit`. + UnitAmountDecimal float64 `json:"unit_amount_decimal,string"` +} + +// When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. +type PriceCustomUnitAmount struct { + // The maximum unit amount the customer can specify for this item. + Maximum int64 `json:"maximum"` + // The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + Minimum int64 `json:"minimum"` + // The starting unit amount which can be updated by the customer. + Preset int64 `json:"preset"` +} + +// The recurring components of a price such as `interval` and `usage_type`. +type PriceRecurring struct { + // The frequency at which a subscription is billed. One of `day`, `week`, `month` or `year`. + Interval PriceRecurringInterval `json:"interval"` + // The number of intervals (specified in the `interval` attribute) between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. + IntervalCount int64 `json:"interval_count"` + // The meter tracking the usage of a metered price + Meter string `json:"meter"` + // Default number of trial days when subscribing a customer to this price using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan). + TrialPeriodDays int64 `json:"trial_period_days"` + // Configures how the quantity per period should be determined. Can be either `metered` or `licensed`. `licensed` automatically bills the `quantity` set when adding it to a subscription. `metered` aggregates the total usage based on usage records. Defaults to `licensed`. + UsageType PriceRecurringUsageType `json:"usage_type"` +} + +// Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. +type PriceTier struct { + // Price for the entire tier. + FlatAmount int64 `json:"flat_amount"` + // Same as `flat_amount`, but contains a decimal value with at most 12 decimal places. + FlatAmountDecimal float64 `json:"flat_amount_decimal,string"` + // Per unit price for units relevant to the tier. + UnitAmount int64 `json:"unit_amount"` + // Same as `unit_amount`, but contains a decimal value with at most 12 decimal places. + UnitAmountDecimal float64 `json:"unit_amount_decimal,string"` + // Up to and including to this quantity will be contained in the tier. + UpTo int64 `json:"up_to"` +} + +// Apply a transformation to the reported usage or set quantity before computing the amount billed. Cannot be combined with `tiers`. +type PriceTransformQuantity struct { + // Divide usage by this number. + DivideBy int64 `json:"divide_by"` + // After division, either round the result `up` or `down`. + Round PriceTransformQuantityRound `json:"round"` +} + +// Prices define the unit cost, currency, and (optional) billing cycle for both recurring and one-time purchases of products. +// [Products](https://stripe.com/docs/api#products) help you track inventory or provisioning, and prices help you track payment terms. Different physical goods or levels of service should be represented by products, and pricing options should be represented by prices. This approach lets you change prices without having to change your provisioning scheme. +// +// For example, you might have a single "gold" product that has prices for $10/month, $100/year, and €9 once. +// +// Related guides: [Set up a subscription](https://stripe.com/docs/billing/subscriptions/set-up-subscription), [create an invoice](https://stripe.com/docs/billing/invoices/create), and more about [products and prices](https://stripe.com/docs/products-prices/overview). +type Price struct { + APIResource + // Whether the price can be used for new purchases. + Active bool `json:"active"` + // Describes how to compute the price per period. Either `per_unit` or `tiered`. `per_unit` indicates that the fixed amount (specified in `unit_amount` or `unit_amount_decimal`) will be charged per unit in `quantity` (for prices with `usage_type=licensed`), or per unit of total usage (for prices with `usage_type=metered`). `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. + BillingScheme PriceBillingScheme `json:"billing_scheme"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*PriceCurrencyOptions `json:"currency_options"` + // When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + CustomUnitAmount *PriceCustomUnitAmount `json:"custom_unit_amount"` + Deleted bool `json:"deleted"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // A lookup key used to retrieve prices dynamically from a static string. This may be up to 200 characters. + LookupKey string `json:"lookup_key"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // A brief description of the price, hidden from customers. + Nickname string `json:"nickname"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The ID of the product this price is associated with. + Product *Product `json:"product"` + // The recurring components of a price such as `interval` and `usage_type`. + Recurring *PriceRecurring `json:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior PriceTaxBehavior `json:"tax_behavior"` + // Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + Tiers []*PriceTier `json:"tiers"` + // Defines if the tiering price should be `graduated` or `volume` based. In `volume`-based tiering, the maximum quantity within a period determines the per unit price. In `graduated` tiering, pricing can change as the quantity grows. + TiersMode PriceTiersMode `json:"tiers_mode"` + // Apply a transformation to the reported usage or set quantity before computing the amount billed. Cannot be combined with `tiers`. + TransformQuantity *PriceTransformQuantity `json:"transform_quantity"` + // One of `one_time` or `recurring` depending on whether the price is for a one-time purchase or a recurring (subscription) purchase. + Type PriceType `json:"type"` + // The unit amount in cents (or local equivalent) to be charged, represented as a whole integer if possible. Only set if `billing_scheme=per_unit`. + UnitAmount int64 `json:"unit_amount"` + // The unit amount in cents (or local equivalent) to be charged, represented as a decimal string with at most 12 decimal places. Only set if `billing_scheme=per_unit`. + UnitAmountDecimal float64 `json:"unit_amount_decimal,string"` +} + +// PriceList is a list of Prices as retrieved from a list endpoint. +type PriceList struct { + APIResource + ListMeta + Data []*Price `json:"data"` +} + +// PriceSearchResult is a list of Price search results as retrieved from a search endpoint. +type PriceSearchResult struct { + APIResource + SearchMeta + Data []*Price `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Price. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (p *Price) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + p.ID = id + return nil + } + + type price Price + var v price + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *p = Price(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/price_service.go b/vendor/github.com/stripe/stripe-go/v82/price_service.go new file mode 100644 index 00000000..d6533b5e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/price_service.go @@ -0,0 +1,92 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1PriceService is used to invoke /v1/prices APIs. +type v1PriceService struct { + B Backend + Key string +} + +// Creates a new [Price for an existing Product](https://docs.stripe.com/api/prices). The Price can be recurring or one-time. +func (c v1PriceService) Create(ctx context.Context, params *PriceCreateParams) (*Price, error) { + if params == nil { + params = &PriceCreateParams{} + } + params.Context = ctx + price := &Price{} + err := c.B.Call(http.MethodPost, "/v1/prices", c.Key, params, price) + return price, err +} + +// Retrieves the price with the given ID. +func (c v1PriceService) Retrieve(ctx context.Context, id string, params *PriceRetrieveParams) (*Price, error) { + if params == nil { + params = &PriceRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/prices/%s", id) + price := &Price{} + err := c.B.Call(http.MethodGet, path, c.Key, params, price) + return price, err +} + +// Updates the specified price by setting the values of the parameters passed. Any parameters not provided are left unchanged. +func (c v1PriceService) Update(ctx context.Context, id string, params *PriceUpdateParams) (*Price, error) { + if params == nil { + params = &PriceUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/prices/%s", id) + price := &Price{} + err := c.B.Call(http.MethodPost, path, c.Key, params, price) + return price, err +} + +// Returns a list of your active prices, excluding [inline prices](https://docs.stripe.com/docs/products-prices/pricing-models#inline-pricing). For the list of inactive prices, set active to false. +func (c v1PriceService) List(ctx context.Context, listParams *PriceListParams) Seq2[*Price, error] { + if listParams == nil { + listParams = &PriceListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Price, ListContainer, error) { + list := &PriceList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/prices", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// Search for prices you've previously created using Stripe's [Search Query Language](https://docs.stripe.com/docs/search#search-query-language). +// Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating +// conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up +// to an hour behind during outages. Search functionality is not available to merchants in India. +func (c v1PriceService) Search(ctx context.Context, params *PriceSearchParams) Seq2[*Price, error] { + if params == nil { + params = &PriceSearchParams{} + } + params.Context = ctx + return newV1SearchList(params, func(p *Params, b *form.Values) ([]*Price, SearchContainer, error) { + list := &PriceSearchResult{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/prices/search", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/product.go b/vendor/github.com/stripe/stripe-go/v82/product.go new file mode 100644 index 00000000..754bb496 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/product.go @@ -0,0 +1,591 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "encoding/json" + "github.com/stripe/stripe-go/v82/form" +) + +// The type of the product. The product is either of type `good`, which is eligible for use with Orders and SKUs, or `service`, which is eligible for use with Subscriptions and Plans. +type ProductType string + +// List of values that ProductType can take +const ( + ProductTypeGood ProductType = "good" + ProductTypeService ProductType = "service" +) + +// Delete a product. Deleting a product is only possible if it has no prices associated with it. Additionally, deleting a product with type=good is only possible if it has no SKUs associated with it. +type ProductParams struct { + Params `form:"*"` + // Whether the product is currently available for purchase. Defaults to `true`. + Active *bool `form:"active"` + // The ID of the [Price](https://stripe.com/docs/api/prices) object that is the default price for this product. + DefaultPrice *string `form:"default_price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object. This Price will be set as the default price for this product. + DefaultPriceData *ProductDefaultPriceDataParams `form:"default_price_data"` + // The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // An identifier will be randomly generated by Stripe. You can optionally override this ID, but the ID must be unique across all products in your Stripe account. + ID *string `form:"id"` + // A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + Images []*string `form:"images"` + // A list of up to 15 marketing features for this product. These are displayed in [pricing tables](https://stripe.com/docs/payments/checkout/pricing-table). + MarketingFeatures []*ProductMarketingFeatureParams `form:"marketing_features"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The product's name, meant to be displayable to the customer. + Name *string `form:"name"` + // The dimensions of this product for shipping purposes. + PackageDimensions *ProductPackageDimensionsParams `form:"package_dimensions"` + // Whether this product is shipped (i.e., physical goods). + Shippable *bool `form:"shippable"` + // An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all. + // + // This may be up to 22 characters. The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped. + // It must contain at least one letter. May only be set if `type=service`. Only used for subscription payments. + StatementDescriptor *string `form:"statement_descriptor"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` + // The type of the product. Defaults to `service` if not explicitly specified, enabling use of this product with Subscriptions and Plans. Set this parameter to `good` to use this product with Orders and SKUs. On API versions before `2018-02-05`, this field defaults to `good` for compatibility reasons. + Type *string `form:"type"` + // A label that represents units of this product. When set, this will be included in customers' receipts, invoices, Checkout, and the customer portal. May only be set if `type=service`. + UnitLabel *string `form:"unit_label"` + // A URL of a publicly-accessible webpage for this product. + URL *string `form:"url"` +} + +// AddExpand appends a new field to expand. +func (p *ProductParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ProductParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A list of up to 15 marketing features for this product. These are displayed in [pricing tables](https://stripe.com/docs/payments/checkout/pricing-table). +type ProductMarketingFeatureParams struct { + // The marketing feature name. Up to 80 characters long. + Name *string `form:"name"` +} + +// The dimensions of this product for shipping purposes. +type ProductPackageDimensionsParams struct { + // Height, in inches. Maximum precision is 2 decimal places. + Height *float64 `form:"height"` + // Length, in inches. Maximum precision is 2 decimal places. + Length *float64 `form:"length"` + // Weight, in ounces. Maximum precision is 2 decimal places. + Weight *float64 `form:"weight"` + // Width, in inches. Maximum precision is 2 decimal places. + Width *float64 `form:"width"` +} + +// Returns a list of your products. The products are returned sorted by creation date, with the most recently created products appearing first. +type ProductListParams struct { + ListParams `form:"*"` + // Only return products that are active or inactive (e.g., pass `false` to list all inactive products). + Active *bool `form:"active"` + // Only return products that were created during the given date interval. + Created *int64 `form:"created"` + // Only return products that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return products with the given IDs. Cannot be used with [starting_after](https://stripe.com/docs/api#list_products-starting_after) or [ending_before](https://stripe.com/docs/api#list_products-ending_before). + IDs []*string `form:"ids"` + // Only return products that can be shipped (i.e., physical, not digital products). + Shippable *bool `form:"shippable"` + // Only return products of this type. + Type *string `form:"type"` + // Only return products with the given url. + URL *string `form:"url"` +} + +// AddExpand appends a new field to expand. +func (p *ProductListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. +type ProductDefaultPriceDataCurrencyOptionsCustomUnitAmountParams struct { + // Pass in `true` to enable `custom_unit_amount`, otherwise omit `custom_unit_amount`. + Enabled *bool `form:"enabled"` + // The maximum unit amount the customer can specify for this item. + Maximum *int64 `form:"maximum"` + // The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + Minimum *int64 `form:"minimum"` + // The starting unit amount which can be updated by the customer. + Preset *int64 `form:"preset"` +} + +// Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. +type ProductDefaultPriceDataCurrencyOptionsTierParams struct { + // The flat billing amount for an entire tier, regardless of the number of units in the tier. + FlatAmount *int64 `form:"flat_amount"` + // Same as `flat_amount`, but accepts a decimal value representing an integer in the minor units of the currency. Only one of `flat_amount` and `flat_amount_decimal` can be set. + FlatAmountDecimal *float64 `form:"flat_amount_decimal,high_precision"` + // The per unit billing amount for each individual unit for which this tier applies. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` + // Specifies the upper bound of this tier. The lower bound of a tier is the upper bound of the previous tier adding one. Use `inf` to define a fallback tier. + UpTo *int64 `form:"up_to"` + UpToInf *bool `form:"-"` // See custom AppendTo +} + +// AppendTo implements custom encoding logic for ProductDefaultPriceDataCurrencyOptionsTierParams. +func (p *ProductDefaultPriceDataCurrencyOptionsTierParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.UpToInf) { + body.Add(form.FormatKey(append(keyParts, "up_to")), "inf") + } +} + +// Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type ProductDefaultPriceDataCurrencyOptionsParams struct { + // When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + CustomUnitAmount *ProductDefaultPriceDataCurrencyOptionsCustomUnitAmountParams `form:"custom_unit_amount"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + Tiers []*ProductDefaultPriceDataCurrencyOptionsTierParams `form:"tiers"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. +type ProductDefaultPriceDataCustomUnitAmountParams struct { + // Pass in `true` to enable `custom_unit_amount`, otherwise omit `custom_unit_amount`. + Enabled *bool `form:"enabled"` + // The maximum unit amount the customer can specify for this item. + Maximum *int64 `form:"maximum"` + // The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + Minimum *int64 `form:"minimum"` + // The starting unit amount which can be updated by the customer. + Preset *int64 `form:"preset"` +} + +// The recurring components of a price such as `interval` and `interval_count`. +type ProductDefaultPriceDataRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object. This Price will be set as the default price for this product. +type ProductDefaultPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*ProductDefaultPriceDataCurrencyOptionsParams `form:"currency_options"` + // When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + CustomUnitAmount *ProductDefaultPriceDataCustomUnitAmountParams `form:"custom_unit_amount"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The recurring components of a price such as `interval` and `interval_count`. + Recurring *ProductDefaultPriceDataRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. One of `unit_amount`, `unit_amount_decimal`, or `custom_unit_amount` is required. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ProductDefaultPriceDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Search for products you've previously created using Stripe's [Search Query Language](https://docs.stripe.com/docs/search#search-query-language). +// Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating +// conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up +// to an hour behind during outages. Search functionality is not available to merchants in India. +type ProductSearchParams struct { + SearchParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + Page *string `form:"page"` +} + +// AddExpand appends a new field to expand. +func (p *ProductSearchParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Delete a product. Deleting a product is only possible if it has no prices associated with it. Additionally, deleting a product with type=good is only possible if it has no SKUs associated with it. +type ProductDeleteParams struct { + Params `form:"*"` +} + +// Retrieves the details of an existing product. Supply the unique product ID from either a product creation request or the product list, and Stripe will return the corresponding product information. +type ProductRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ProductRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A list of up to 15 marketing features for this product. These are displayed in [pricing tables](https://stripe.com/docs/payments/checkout/pricing-table). +type ProductUpdateMarketingFeatureParams struct { + // The marketing feature name. Up to 80 characters long. + Name *string `form:"name"` +} + +// The dimensions of this product for shipping purposes. +type ProductUpdatePackageDimensionsParams struct { + // Height, in inches. Maximum precision is 2 decimal places. + Height *float64 `form:"height"` + // Length, in inches. Maximum precision is 2 decimal places. + Length *float64 `form:"length"` + // Weight, in ounces. Maximum precision is 2 decimal places. + Weight *float64 `form:"weight"` + // Width, in inches. Maximum precision is 2 decimal places. + Width *float64 `form:"width"` +} + +// Updates the specific product by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +type ProductUpdateParams struct { + Params `form:"*"` + // Whether the product is available for purchase. + Active *bool `form:"active"` + // The ID of the [Price](https://stripe.com/docs/api/prices) object that is the default price for this product. + DefaultPrice *string `form:"default_price"` + // The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + Images []*string `form:"images"` + // A list of up to 15 marketing features for this product. These are displayed in [pricing tables](https://stripe.com/docs/payments/checkout/pricing-table). + MarketingFeatures []*ProductUpdateMarketingFeatureParams `form:"marketing_features"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The product's name, meant to be displayable to the customer. + Name *string `form:"name"` + // The dimensions of this product for shipping purposes. + PackageDimensions *ProductUpdatePackageDimensionsParams `form:"package_dimensions"` + // Whether this product is shipped (i.e., physical goods). + Shippable *bool `form:"shippable"` + // An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all. + // + // This may be up to 22 characters. The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped. + // It must contain at least one letter. May only be set if `type=service`. Only used for subscription payments. + StatementDescriptor *string `form:"statement_descriptor"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` + // A label that represents units of this product. When set, this will be included in customers' receipts, invoices, Checkout, and the customer portal. May only be set if `type=service`. + UnitLabel *string `form:"unit_label"` + // A URL of a publicly-accessible webpage for this product. + URL *string `form:"url"` +} + +// AddExpand appends a new field to expand. +func (p *ProductUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ProductUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. +type ProductCreateDefaultPriceDataCurrencyOptionsCustomUnitAmountParams struct { + // Pass in `true` to enable `custom_unit_amount`, otherwise omit `custom_unit_amount`. + Enabled *bool `form:"enabled"` + // The maximum unit amount the customer can specify for this item. + Maximum *int64 `form:"maximum"` + // The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + Minimum *int64 `form:"minimum"` + // The starting unit amount which can be updated by the customer. + Preset *int64 `form:"preset"` +} + +// Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. +type ProductCreateDefaultPriceDataCurrencyOptionsTierParams struct { + // The flat billing amount for an entire tier, regardless of the number of units in the tier. + FlatAmount *int64 `form:"flat_amount"` + // Same as `flat_amount`, but accepts a decimal value representing an integer in the minor units of the currency. Only one of `flat_amount` and `flat_amount_decimal` can be set. + FlatAmountDecimal *float64 `form:"flat_amount_decimal,high_precision"` + // The per unit billing amount for each individual unit for which this tier applies. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` + // Specifies the upper bound of this tier. The lower bound of a tier is the upper bound of the previous tier adding one. Use `inf` to define a fallback tier. + UpTo *int64 `form:"up_to"` + UpToInf *bool `form:"-"` // See custom AppendTo +} + +// AppendTo implements custom encoding logic for ProductCreateDefaultPriceDataCurrencyOptionsTierParams. +func (p *ProductCreateDefaultPriceDataCurrencyOptionsTierParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.UpToInf) { + body.Add(form.FormatKey(append(keyParts, "up_to")), "inf") + } +} + +// Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type ProductCreateDefaultPriceDataCurrencyOptionsParams struct { + // When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + CustomUnitAmount *ProductCreateDefaultPriceDataCurrencyOptionsCustomUnitAmountParams `form:"custom_unit_amount"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + Tiers []*ProductCreateDefaultPriceDataCurrencyOptionsTierParams `form:"tiers"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. +type ProductCreateDefaultPriceDataCustomUnitAmountParams struct { + // Pass in `true` to enable `custom_unit_amount`, otherwise omit `custom_unit_amount`. + Enabled *bool `form:"enabled"` + // The maximum unit amount the customer can specify for this item. + Maximum *int64 `form:"maximum"` + // The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + Minimum *int64 `form:"minimum"` + // The starting unit amount which can be updated by the customer. + Preset *int64 `form:"preset"` +} + +// The recurring components of a price such as `interval` and `interval_count`. +type ProductCreateDefaultPriceDataRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object. This Price will be set as the default price for this product. +type ProductCreateDefaultPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*ProductCreateDefaultPriceDataCurrencyOptionsParams `form:"currency_options"` + // When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + CustomUnitAmount *ProductCreateDefaultPriceDataCustomUnitAmountParams `form:"custom_unit_amount"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The recurring components of a price such as `interval` and `interval_count`. + Recurring *ProductCreateDefaultPriceDataRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. One of `unit_amount`, `unit_amount_decimal`, or `custom_unit_amount` is required. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ProductCreateDefaultPriceDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A list of up to 15 marketing features for this product. These are displayed in [pricing tables](https://stripe.com/docs/payments/checkout/pricing-table). +type ProductCreateMarketingFeatureParams struct { + // The marketing feature name. Up to 80 characters long. + Name *string `form:"name"` +} + +// The dimensions of this product for shipping purposes. +type ProductCreatePackageDimensionsParams struct { + // Height, in inches. Maximum precision is 2 decimal places. + Height *float64 `form:"height"` + // Length, in inches. Maximum precision is 2 decimal places. + Length *float64 `form:"length"` + // Weight, in ounces. Maximum precision is 2 decimal places. + Weight *float64 `form:"weight"` + // Width, in inches. Maximum precision is 2 decimal places. + Width *float64 `form:"width"` +} + +// Creates a new product object. +type ProductCreateParams struct { + Params `form:"*"` + // Whether the product is currently available for purchase. Defaults to `true`. + Active *bool `form:"active"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object. This Price will be set as the default price for this product. + DefaultPriceData *ProductCreateDefaultPriceDataParams `form:"default_price_data"` + // The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // An identifier will be randomly generated by Stripe. You can optionally override this ID, but the ID must be unique across all products in your Stripe account. + ID *string `form:"id"` + // A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + Images []*string `form:"images"` + // A list of up to 15 marketing features for this product. These are displayed in [pricing tables](https://stripe.com/docs/payments/checkout/pricing-table). + MarketingFeatures []*ProductCreateMarketingFeatureParams `form:"marketing_features"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The product's name, meant to be displayable to the customer. + Name *string `form:"name"` + // The dimensions of this product for shipping purposes. + PackageDimensions *ProductCreatePackageDimensionsParams `form:"package_dimensions"` + // Whether this product is shipped (i.e., physical goods). + Shippable *bool `form:"shippable"` + // An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all. + // + // This may be up to 22 characters. The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped. + // It must contain at least one letter. Only used for subscription payments. + StatementDescriptor *string `form:"statement_descriptor"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` + // The type of the product. Defaults to `service` if not explicitly specified, enabling use of this product with Subscriptions and Plans. Set this parameter to `good` to use this product with Orders and SKUs. On API versions before `2018-02-05`, this field defaults to `good` for compatibility reasons. + Type *string `form:"type"` + // A label that represents units of this product. When set, this will be included in customers' receipts, invoices, Checkout, and the customer portal. + UnitLabel *string `form:"unit_label"` + // A URL of a publicly-accessible webpage for this product. + URL *string `form:"url"` +} + +// AddExpand appends a new field to expand. +func (p *ProductCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ProductCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A list of up to 15 marketing features for this product. These are displayed in [pricing tables](https://stripe.com/docs/payments/checkout/pricing-table). +type ProductMarketingFeature struct { + // The marketing feature name. Up to 80 characters long. + Name string `json:"name"` +} + +// The dimensions of this product for shipping purposes. +type ProductPackageDimensions struct { + // Height, in inches. + Height float64 `json:"height"` + // Length, in inches. + Length float64 `json:"length"` + // Weight, in ounces. + Weight float64 `json:"weight"` + // Width, in inches. + Width float64 `json:"width"` +} + +// Products describe the specific goods or services you offer to your customers. +// For example, you might offer a Standard and Premium version of your goods or service; each version would be a separate Product. +// They can be used in conjunction with [Prices](https://stripe.com/docs/api#prices) to configure pricing in Payment Links, Checkout, and Subscriptions. +// +// Related guides: [Set up a subscription](https://stripe.com/docs/billing/subscriptions/set-up-subscription), +// [share a Payment Link](https://stripe.com/docs/payment-links), +// [accept payments with Checkout](https://stripe.com/docs/payments/accept-a-payment#create-product-prices-upfront), +// and more about [Products and Prices](https://stripe.com/docs/products-prices/overview) +type Product struct { + APIResource + // Whether the product is currently available for purchase. + Active bool `json:"active"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The ID of the [Price](https://stripe.com/docs/api/prices) object that is the default price for this product. + DefaultPrice *Price `json:"default_price"` + Deleted bool `json:"deleted"` + // The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + Description string `json:"description"` + // Unique identifier for the object. + ID string `json:"id"` + // A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + Images []string `json:"images"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // A list of up to 15 marketing features for this product. These are displayed in [pricing tables](https://stripe.com/docs/payments/checkout/pricing-table). + MarketingFeatures []*ProductMarketingFeature `json:"marketing_features"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // The product's name, meant to be displayable to the customer. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The dimensions of this product for shipping purposes. + PackageDimensions *ProductPackageDimensions `json:"package_dimensions"` + // Whether this product is shipped (i.e., physical goods). + Shippable bool `json:"shippable"` + // Extra information about a product which will appear on your customer's credit card statement. In the case that multiple products are billed at once, the first statement descriptor will be used. Only used for subscription payments. + StatementDescriptor string `json:"statement_descriptor"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *TaxCode `json:"tax_code"` + // The type of the product. The product is either of type `good`, which is eligible for use with Orders and SKUs, or `service`, which is eligible for use with Subscriptions and Plans. + Type ProductType `json:"type"` + // A label that represents units of this product. When set, this will be included in customers' receipts, invoices, Checkout, and the customer portal. + UnitLabel string `json:"unit_label"` + // Time at which the object was last updated. Measured in seconds since the Unix epoch. + Updated int64 `json:"updated"` + // A URL of a publicly-accessible webpage for this product. + URL string `json:"url"` +} + +// ProductList is a list of Products as retrieved from a list endpoint. +type ProductList struct { + APIResource + ListMeta + Data []*Product `json:"data"` +} + +// ProductSearchResult is a list of Product search results as retrieved from a search endpoint. +type ProductSearchResult struct { + APIResource + SearchMeta + Data []*Product `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Product. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (p *Product) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + p.ID = id + return nil + } + + type product Product + var v product + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *p = Product(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/product_service.go b/vendor/github.com/stripe/stripe-go/v82/product_service.go new file mode 100644 index 00000000..e46e3367 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/product_service.go @@ -0,0 +1,104 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1ProductService is used to invoke /v1/products APIs. +type v1ProductService struct { + B Backend + Key string +} + +// Creates a new product object. +func (c v1ProductService) Create(ctx context.Context, params *ProductCreateParams) (*Product, error) { + if params == nil { + params = &ProductCreateParams{} + } + params.Context = ctx + product := &Product{} + err := c.B.Call(http.MethodPost, "/v1/products", c.Key, params, product) + return product, err +} + +// Retrieves the details of an existing product. Supply the unique product ID from either a product creation request or the product list, and Stripe will return the corresponding product information. +func (c v1ProductService) Retrieve(ctx context.Context, id string, params *ProductRetrieveParams) (*Product, error) { + if params == nil { + params = &ProductRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/products/%s", id) + product := &Product{} + err := c.B.Call(http.MethodGet, path, c.Key, params, product) + return product, err +} + +// Updates the specific product by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +func (c v1ProductService) Update(ctx context.Context, id string, params *ProductUpdateParams) (*Product, error) { + if params == nil { + params = &ProductUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/products/%s", id) + product := &Product{} + err := c.B.Call(http.MethodPost, path, c.Key, params, product) + return product, err +} + +// Delete a product. Deleting a product is only possible if it has no prices associated with it. Additionally, deleting a product with type=good is only possible if it has no SKUs associated with it. +func (c v1ProductService) Delete(ctx context.Context, id string, params *ProductDeleteParams) (*Product, error) { + if params == nil { + params = &ProductDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/products/%s", id) + product := &Product{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, product) + return product, err +} + +// Returns a list of your products. The products are returned sorted by creation date, with the most recently created products appearing first. +func (c v1ProductService) List(ctx context.Context, listParams *ProductListParams) Seq2[*Product, error] { + if listParams == nil { + listParams = &ProductListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Product, ListContainer, error) { + list := &ProductList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/products", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// Search for products you've previously created using Stripe's [Search Query Language](https://docs.stripe.com/docs/search#search-query-language). +// Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating +// conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up +// to an hour behind during outages. Search functionality is not available to merchants in India. +func (c v1ProductService) Search(ctx context.Context, params *ProductSearchParams) Seq2[*Product, error] { + if params == nil { + params = &ProductSearchParams{} + } + params.Context = ctx + return newV1SearchList(params, func(p *Params, b *form.Values) ([]*Product, SearchContainer, error) { + list := &ProductSearchResult{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/products/search", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/productfeature.go b/vendor/github.com/stripe/stripe-go/v82/productfeature.go new file mode 100644 index 00000000..f0fe0052 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/productfeature.go @@ -0,0 +1,92 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Deletes the feature attachment to a product +type ProductFeatureParams struct { + Params `form:"*"` + Product *string `form:"-"` // Included in URL + // The ID of the [Feature](https://stripe.com/docs/api/entitlements/feature) object attached to this product. + EntitlementFeature *string `form:"entitlement_feature"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ProductFeatureParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieve a list of features for a product +type ProductFeatureListParams struct { + ListParams `form:"*"` + Product *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ProductFeatureListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Deletes the feature attachment to a product +type ProductFeatureDeleteParams struct { + Params `form:"*"` + Product *string `form:"-"` // Included in URL +} + +// Retrieves a product_feature, which represents a feature attachment to a product +type ProductFeatureRetrieveParams struct { + Params `form:"*"` + Product *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ProductFeatureRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates a product_feature, which represents a feature attachment to a product +type ProductFeatureCreateParams struct { + Params `form:"*"` + Product *string `form:"-"` // Included in URL + // The ID of the [Feature](https://stripe.com/docs/api/entitlements/feature) object attached to this product. + EntitlementFeature *string `form:"entitlement_feature"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ProductFeatureCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A product_feature represents an attachment between a feature and a product. +// When a product is purchased that has a feature attached, Stripe will create an entitlement to the feature for the purchasing customer. +type ProductFeature struct { + APIResource + Deleted bool `json:"deleted"` + // A feature represents a monetizable ability or functionality in your system. + // Features can be assigned to products, and when those products are purchased, Stripe will create an entitlement to the feature for the purchasing customer. + EntitlementFeature *EntitlementsFeature `json:"entitlement_feature"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} + +// ProductFeatureList is a list of ProductFeatures as retrieved from a list endpoint. +type ProductFeatureList struct { + APIResource + ListMeta + Data []*ProductFeature `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/productfeature_service.go b/vendor/github.com/stripe/stripe-go/v82/productfeature_service.go new file mode 100644 index 00000000..736b4176 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/productfeature_service.go @@ -0,0 +1,77 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1ProductFeatureService is used to invoke /v1/products/{product}/features APIs. +type v1ProductFeatureService struct { + B Backend + Key string +} + +// Creates a product_feature, which represents a feature attachment to a product +func (c v1ProductFeatureService) Create(ctx context.Context, params *ProductFeatureCreateParams) (*ProductFeature, error) { + if params == nil { + params = &ProductFeatureCreateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/products/%s/features", StringValue(params.Product)) + productfeature := &ProductFeature{} + err := c.B.Call(http.MethodPost, path, c.Key, params, productfeature) + return productfeature, err +} + +// Retrieves a product_feature, which represents a feature attachment to a product +func (c v1ProductFeatureService) Retrieve(ctx context.Context, id string, params *ProductFeatureRetrieveParams) (*ProductFeature, error) { + if params == nil { + params = &ProductFeatureRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/products/%s/features/%s", StringValue(params.Product), id) + productfeature := &ProductFeature{} + err := c.B.Call(http.MethodGet, path, c.Key, params, productfeature) + return productfeature, err +} + +// Deletes the feature attachment to a product +func (c v1ProductFeatureService) Delete(ctx context.Context, id string, params *ProductFeatureDeleteParams) (*ProductFeature, error) { + if params == nil { + params = &ProductFeatureDeleteParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/products/%s/features/%s", StringValue(params.Product), id) + productfeature := &ProductFeature{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, productfeature) + return productfeature, err +} + +// Retrieve a list of features for a product +func (c v1ProductFeatureService) List(ctx context.Context, listParams *ProductFeatureListParams) Seq2[*ProductFeature, error] { + if listParams == nil { + listParams = &ProductFeatureListParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/products/%s/features", StringValue(listParams.Product)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*ProductFeature, ListContainer, error) { + list := &ProductFeatureList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/promotioncode.go b/vendor/github.com/stripe/stripe-go/v82/promotioncode.go new file mode 100644 index 00000000..1f01af31 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/promotioncode.go @@ -0,0 +1,273 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Returns a list of your promotion codes. +type PromotionCodeListParams struct { + ListParams `form:"*"` + // Filter promotion codes by whether they are active. + Active *bool `form:"active"` + // Only return promotion codes that have this case-insensitive code. + Code *string `form:"code"` + // Only return promotion codes for this coupon. + Coupon *string `form:"coupon"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + Created *int64 `form:"created"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + CreatedRange *RangeQueryParams `form:"created"` + // Only return promotion codes that are restricted to this customer. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PromotionCodeListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Promotion codes defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type PromotionCodeRestrictionsCurrencyOptionsParams struct { + // Minimum amount required to redeem this Promotion Code into a Coupon (e.g., a purchase must be $100 or more to work). + MinimumAmount *int64 `form:"minimum_amount"` +} + +// Settings that restrict the redemption of the promotion code. +type PromotionCodeRestrictionsParams struct { + // Promotion codes defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*PromotionCodeRestrictionsCurrencyOptionsParams `form:"currency_options"` + // A Boolean indicating if the Promotion Code should only be redeemed for Customers without any successful payments or invoices + FirstTimeTransaction *bool `form:"first_time_transaction"` + // Minimum amount required to redeem this Promotion Code into a Coupon (e.g., a purchase must be $100 or more to work). + MinimumAmount *int64 `form:"minimum_amount"` + // Three-letter [ISO code](https://stripe.com/docs/currencies) for minimum_amount + MinimumAmountCurrency *string `form:"minimum_amount_currency"` +} + +// A promotion code points to a coupon. You can optionally restrict the code to a specific customer, redemption limit, and expiration date. +type PromotionCodeParams struct { + Params `form:"*"` + // Whether the promotion code is currently active. A promotion code can only be reactivated when the coupon is still valid and the promotion code is otherwise redeemable. + Active *bool `form:"active"` + // The customer-facing code. Regardless of case, this code must be unique across all active promotion codes for a specific customer. Valid characters are lower case letters (a-z), upper case letters (A-Z), and digits (0-9). + // + // If left blank, we will generate one automatically. + Code *string `form:"code"` + // The coupon for this promotion code. + Coupon *string `form:"coupon"` + // The customer that this promotion code can be used by. If not set, the promotion code can be used by all customers. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The timestamp at which this promotion code will expire. If the coupon has specified a `redeems_by`, then this value cannot be after the coupon's `redeems_by`. + ExpiresAt *int64 `form:"expires_at"` + // A positive integer specifying the number of times the promotion code can be redeemed. If the coupon has specified a `max_redemptions`, then this value cannot be greater than the coupon's `max_redemptions`. + MaxRedemptions *int64 `form:"max_redemptions"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Settings that restrict the redemption of the promotion code. + Restrictions *PromotionCodeRestrictionsParams `form:"restrictions"` +} + +// AddExpand appends a new field to expand. +func (p *PromotionCodeParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PromotionCodeParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Promotion codes defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type PromotionCodeCreateRestrictionsCurrencyOptionsParams struct { + // Minimum amount required to redeem this Promotion Code into a Coupon (e.g., a purchase must be $100 or more to work). + MinimumAmount *int64 `form:"minimum_amount"` +} + +// Settings that restrict the redemption of the promotion code. +type PromotionCodeCreateRestrictionsParams struct { + // Promotion codes defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*PromotionCodeCreateRestrictionsCurrencyOptionsParams `form:"currency_options"` + // A Boolean indicating if the Promotion Code should only be redeemed for Customers without any successful payments or invoices + FirstTimeTransaction *bool `form:"first_time_transaction"` + // Minimum amount required to redeem this Promotion Code into a Coupon (e.g., a purchase must be $100 or more to work). + MinimumAmount *int64 `form:"minimum_amount"` + // Three-letter [ISO code](https://stripe.com/docs/currencies) for minimum_amount + MinimumAmountCurrency *string `form:"minimum_amount_currency"` +} + +// A promotion code points to a coupon. You can optionally restrict the code to a specific customer, redemption limit, and expiration date. +type PromotionCodeCreateParams struct { + Params `form:"*"` + // Whether the promotion code is currently active. + Active *bool `form:"active"` + // The customer-facing code. Regardless of case, this code must be unique across all active promotion codes for a specific customer. Valid characters are lower case letters (a-z), upper case letters (A-Z), and digits (0-9). + // + // If left blank, we will generate one automatically. + Code *string `form:"code"` + // The coupon for this promotion code. + Coupon *string `form:"coupon"` + // The customer that this promotion code can be used by. If not set, the promotion code can be used by all customers. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The timestamp at which this promotion code will expire. If the coupon has specified a `redeems_by`, then this value cannot be after the coupon's `redeems_by`. + ExpiresAt *int64 `form:"expires_at"` + // A positive integer specifying the number of times the promotion code can be redeemed. If the coupon has specified a `max_redemptions`, then this value cannot be greater than the coupon's `max_redemptions`. + MaxRedemptions *int64 `form:"max_redemptions"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Settings that restrict the redemption of the promotion code. + Restrictions *PromotionCodeCreateRestrictionsParams `form:"restrictions"` +} + +// AddExpand appends a new field to expand. +func (p *PromotionCodeCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PromotionCodeCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the promotion code with the given ID. In order to retrieve a promotion code by the customer-facing code use [list](https://docs.stripe.com/docs/api/promotion_codes/list) with the desired code. +type PromotionCodeRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *PromotionCodeRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Promotion codes defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type PromotionCodeUpdateRestrictionsCurrencyOptionsParams struct { + // Minimum amount required to redeem this Promotion Code into a Coupon (e.g., a purchase must be $100 or more to work). + MinimumAmount *int64 `form:"minimum_amount"` +} + +// Settings that restrict the redemption of the promotion code. +type PromotionCodeUpdateRestrictionsParams struct { + // Promotion codes defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*PromotionCodeUpdateRestrictionsCurrencyOptionsParams `form:"currency_options"` +} + +// Updates the specified promotion code by setting the values of the parameters passed. Most fields are, by design, not editable. +type PromotionCodeUpdateParams struct { + Params `form:"*"` + // Whether the promotion code is currently active. A promotion code can only be reactivated when the coupon is still valid and the promotion code is otherwise redeemable. + Active *bool `form:"active"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Settings that restrict the redemption of the promotion code. + Restrictions *PromotionCodeUpdateRestrictionsParams `form:"restrictions"` +} + +// AddExpand appends a new field to expand. +func (p *PromotionCodeUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *PromotionCodeUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Promotion code restrictions defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type PromotionCodeRestrictionsCurrencyOptions struct { + // Minimum amount required to redeem this Promotion Code into a Coupon (e.g., a purchase must be $100 or more to work). + MinimumAmount int64 `json:"minimum_amount"` +} +type PromotionCodeRestrictions struct { + // Promotion code restrictions defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*PromotionCodeRestrictionsCurrencyOptions `json:"currency_options"` + // A Boolean indicating if the Promotion Code should only be redeemed for Customers without any successful payments or invoices + FirstTimeTransaction bool `json:"first_time_transaction"` + // Minimum amount required to redeem this Promotion Code into a Coupon (e.g., a purchase must be $100 or more to work). + MinimumAmount int64 `json:"minimum_amount"` + // Three-letter [ISO code](https://stripe.com/docs/currencies) for minimum_amount + MinimumAmountCurrency Currency `json:"minimum_amount_currency"` +} + +// A Promotion Code represents a customer-redeemable code for a [coupon](https://stripe.com/docs/api#coupons). It can be used to +// create multiple codes for a single coupon. +type PromotionCode struct { + APIResource + // Whether the promotion code is currently active. A promotion code is only active if the coupon is also valid. + Active bool `json:"active"` + // The customer-facing code. Regardless of case, this code must be unique across all active promotion codes for each customer. Valid characters are lower case letters (a-z), upper case letters (A-Z), and digits (0-9). + Code string `json:"code"` + // A coupon contains information about a percent-off or amount-off discount you + // might want to apply to a customer. Coupons may be applied to [subscriptions](https://stripe.com/docs/api#subscriptions), [invoices](https://stripe.com/docs/api#invoices), + // [checkout sessions](https://stripe.com/docs/api/checkout/sessions), [quotes](https://stripe.com/docs/api#quotes), and more. Coupons do not work with conventional one-off [charges](https://stripe.com/docs/api#create_charge) or [payment intents](https://stripe.com/docs/api/payment_intents). + Coupon *Coupon `json:"coupon"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The customer that this promotion code can be used by. + Customer *Customer `json:"customer"` + // Date at which the promotion code can no longer be redeemed. + ExpiresAt int64 `json:"expires_at"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Maximum number of times this promotion code can be redeemed. + MaxRedemptions int64 `json:"max_redemptions"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + Restrictions *PromotionCodeRestrictions `json:"restrictions"` + // Number of times this promotion code has been used. + TimesRedeemed int64 `json:"times_redeemed"` +} + +// PromotionCodeList is a list of PromotionCodes as retrieved from a list endpoint. +type PromotionCodeList struct { + APIResource + ListMeta + Data []*PromotionCode `json:"data"` +} + +// UnmarshalJSON handles deserialization of a PromotionCode. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (p *PromotionCode) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + p.ID = id + return nil + } + + type promotionCode PromotionCode + var v promotionCode + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *p = PromotionCode(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/promotioncode_service.go b/vendor/github.com/stripe/stripe-go/v82/promotioncode_service.go new file mode 100644 index 00000000..c01261f0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/promotioncode_service.go @@ -0,0 +1,73 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1PromotionCodeService is used to invoke /v1/promotion_codes APIs. +type v1PromotionCodeService struct { + B Backend + Key string +} + +// A promotion code points to a coupon. You can optionally restrict the code to a specific customer, redemption limit, and expiration date. +func (c v1PromotionCodeService) Create(ctx context.Context, params *PromotionCodeCreateParams) (*PromotionCode, error) { + if params == nil { + params = &PromotionCodeCreateParams{} + } + params.Context = ctx + promotioncode := &PromotionCode{} + err := c.B.Call( + http.MethodPost, "/v1/promotion_codes", c.Key, params, promotioncode) + return promotioncode, err +} + +// Retrieves the promotion code with the given ID. In order to retrieve a promotion code by the customer-facing code use [list](https://docs.stripe.com/docs/api/promotion_codes/list) with the desired code. +func (c v1PromotionCodeService) Retrieve(ctx context.Context, id string, params *PromotionCodeRetrieveParams) (*PromotionCode, error) { + if params == nil { + params = &PromotionCodeRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/promotion_codes/%s", id) + promotioncode := &PromotionCode{} + err := c.B.Call(http.MethodGet, path, c.Key, params, promotioncode) + return promotioncode, err +} + +// Updates the specified promotion code by setting the values of the parameters passed. Most fields are, by design, not editable. +func (c v1PromotionCodeService) Update(ctx context.Context, id string, params *PromotionCodeUpdateParams) (*PromotionCode, error) { + if params == nil { + params = &PromotionCodeUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/promotion_codes/%s", id) + promotioncode := &PromotionCode{} + err := c.B.Call(http.MethodPost, path, c.Key, params, promotioncode) + return promotioncode, err +} + +// Returns a list of your promotion codes. +func (c v1PromotionCodeService) List(ctx context.Context, listParams *PromotionCodeListParams) Seq2[*PromotionCode, error] { + if listParams == nil { + listParams = &PromotionCodeListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*PromotionCode, ListContainer, error) { + list := &PromotionCodeList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/promotion_codes", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/quote.go b/vendor/github.com/stripe/stripe-go/v82/quote.go new file mode 100644 index 00000000..152452eb --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/quote.go @@ -0,0 +1,1162 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "encoding/json" + "github.com/stripe/stripe-go/v82/form" +) + +// Type of the account referenced. +type QuoteAutomaticTaxLiabilityType string + +// List of values that QuoteAutomaticTaxLiabilityType can take +const ( + QuoteAutomaticTaxLiabilityTypeAccount QuoteAutomaticTaxLiabilityType = "account" + QuoteAutomaticTaxLiabilityTypeSelf QuoteAutomaticTaxLiabilityType = "self" +) + +// The status of the most recent automated tax calculation for this quote. +type QuoteAutomaticTaxStatus string + +// List of values that QuoteAutomaticTaxStatus can take +const ( + QuoteAutomaticTaxStatusComplete QuoteAutomaticTaxStatus = "complete" + QuoteAutomaticTaxStatusFailed QuoteAutomaticTaxStatus = "failed" + QuoteAutomaticTaxStatusRequiresLocationInputs QuoteAutomaticTaxStatus = "requires_location_inputs" +) + +// Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay invoices at the end of the subscription cycle or on finalization using the default payment method attached to the subscription or customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically`. +type QuoteCollectionMethod string + +// List of values that QuoteCollectionMethod can take +const ( + QuoteCollectionMethodChargeAutomatically QuoteCollectionMethod = "charge_automatically" + QuoteCollectionMethodSendInvoice QuoteCollectionMethod = "send_invoice" +) + +// The frequency at which a subscription is billed. One of `day`, `week`, `month` or `year`. +type QuoteComputedRecurringInterval string + +// List of values that QuoteComputedRecurringInterval can take +const ( + QuoteComputedRecurringIntervalDay QuoteComputedRecurringInterval = "day" + QuoteComputedRecurringIntervalMonth QuoteComputedRecurringInterval = "month" + QuoteComputedRecurringIntervalWeek QuoteComputedRecurringInterval = "week" + QuoteComputedRecurringIntervalYear QuoteComputedRecurringInterval = "year" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason string + +// List of values that QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason can take +const ( + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonCustomerExempt QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "customer_exempt" + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonNotCollecting QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "not_collecting" + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonNotSubjectToTax QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "not_subject_to_tax" + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonNotSupported QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "not_supported" + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonPortionProductExempt QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "portion_product_exempt" + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonPortionReducedRated QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "portion_reduced_rated" + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonPortionStandardRated QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "portion_standard_rated" + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonProductExempt QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "product_exempt" + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonProductExemptHoliday QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "product_exempt_holiday" + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonProportionallyRated QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "proportionally_rated" + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonReducedRated QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "reduced_rated" + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonReverseCharge QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "reverse_charge" + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonStandardRated QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "standard_rated" + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonTaxableBasisReduced QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "taxable_basis_reduced" + QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReasonZeroRated QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason = "zero_rated" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason string + +// List of values that QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason can take +const ( + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonCustomerExempt QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "customer_exempt" + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonNotCollecting QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "not_collecting" + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonNotSubjectToTax QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "not_subject_to_tax" + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonNotSupported QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "not_supported" + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonPortionProductExempt QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "portion_product_exempt" + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonPortionReducedRated QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "portion_reduced_rated" + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonPortionStandardRated QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "portion_standard_rated" + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonProductExempt QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "product_exempt" + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonProductExemptHoliday QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "product_exempt_holiday" + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonProportionallyRated QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "proportionally_rated" + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonReducedRated QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "reduced_rated" + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonReverseCharge QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "reverse_charge" + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonStandardRated QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "standard_rated" + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonTaxableBasisReduced QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "taxable_basis_reduced" + QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReasonZeroRated QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason = "zero_rated" +) + +// Type of the account referenced. +type QuoteInvoiceSettingsIssuerType string + +// List of values that QuoteInvoiceSettingsIssuerType can take +const ( + QuoteInvoiceSettingsIssuerTypeAccount QuoteInvoiceSettingsIssuerType = "account" + QuoteInvoiceSettingsIssuerTypeSelf QuoteInvoiceSettingsIssuerType = "self" +) + +// The status of the quote. +type QuoteStatus string + +// List of values that QuoteStatus can take +const ( + QuoteStatusAccepted QuoteStatus = "accepted" + QuoteStatusCanceled QuoteStatus = "canceled" + QuoteStatusDraft QuoteStatus = "draft" + QuoteStatusOpen QuoteStatus = "open" +) + +// Controls how prorations and invoices for subscriptions are calculated and orchestrated. +type QuoteSubscriptionDataBillingModeType string + +// List of values that QuoteSubscriptionDataBillingModeType can take +const ( + QuoteSubscriptionDataBillingModeTypeClassic QuoteSubscriptionDataBillingModeType = "classic" + QuoteSubscriptionDataBillingModeTypeFlexible QuoteSubscriptionDataBillingModeType = "flexible" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type QuoteTotalDetailsBreakdownTaxTaxabilityReason string + +// List of values that QuoteTotalDetailsBreakdownTaxTaxabilityReason can take +const ( + QuoteTotalDetailsBreakdownTaxTaxabilityReasonCustomerExempt QuoteTotalDetailsBreakdownTaxTaxabilityReason = "customer_exempt" + QuoteTotalDetailsBreakdownTaxTaxabilityReasonNotCollecting QuoteTotalDetailsBreakdownTaxTaxabilityReason = "not_collecting" + QuoteTotalDetailsBreakdownTaxTaxabilityReasonNotSubjectToTax QuoteTotalDetailsBreakdownTaxTaxabilityReason = "not_subject_to_tax" + QuoteTotalDetailsBreakdownTaxTaxabilityReasonNotSupported QuoteTotalDetailsBreakdownTaxTaxabilityReason = "not_supported" + QuoteTotalDetailsBreakdownTaxTaxabilityReasonPortionProductExempt QuoteTotalDetailsBreakdownTaxTaxabilityReason = "portion_product_exempt" + QuoteTotalDetailsBreakdownTaxTaxabilityReasonPortionReducedRated QuoteTotalDetailsBreakdownTaxTaxabilityReason = "portion_reduced_rated" + QuoteTotalDetailsBreakdownTaxTaxabilityReasonPortionStandardRated QuoteTotalDetailsBreakdownTaxTaxabilityReason = "portion_standard_rated" + QuoteTotalDetailsBreakdownTaxTaxabilityReasonProductExempt QuoteTotalDetailsBreakdownTaxTaxabilityReason = "product_exempt" + QuoteTotalDetailsBreakdownTaxTaxabilityReasonProductExemptHoliday QuoteTotalDetailsBreakdownTaxTaxabilityReason = "product_exempt_holiday" + QuoteTotalDetailsBreakdownTaxTaxabilityReasonProportionallyRated QuoteTotalDetailsBreakdownTaxTaxabilityReason = "proportionally_rated" + QuoteTotalDetailsBreakdownTaxTaxabilityReasonReducedRated QuoteTotalDetailsBreakdownTaxTaxabilityReason = "reduced_rated" + QuoteTotalDetailsBreakdownTaxTaxabilityReasonReverseCharge QuoteTotalDetailsBreakdownTaxTaxabilityReason = "reverse_charge" + QuoteTotalDetailsBreakdownTaxTaxabilityReasonStandardRated QuoteTotalDetailsBreakdownTaxTaxabilityReason = "standard_rated" + QuoteTotalDetailsBreakdownTaxTaxabilityReasonTaxableBasisReduced QuoteTotalDetailsBreakdownTaxTaxabilityReason = "taxable_basis_reduced" + QuoteTotalDetailsBreakdownTaxTaxabilityReasonZeroRated QuoteTotalDetailsBreakdownTaxTaxabilityReason = "zero_rated" +) + +// Returns a list of your quotes. +type QuoteListParams struct { + ListParams `form:"*"` + // The ID of the customer whose quotes will be retrieved. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The status of the quote. + Status *string `form:"status"` + // Provides a list of quotes that are associated with the specified test clock. The response will not include quotes with test clocks if this and the customer parameter is not set. + TestClock *string `form:"test_clock"` +} + +// AddExpand appends a new field to expand. +func (p *QuoteListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type QuoteAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Settings for automatic tax lookup for this quote and resulting invoices and subscriptions. +type QuoteAutomaticTaxParams struct { + // Controls whether Stripe will automatically compute tax on the resulting invoices or subscriptions as well as the quote itself. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *QuoteAutomaticTaxLiabilityParams `form:"liability"` +} + +// The discounts applied to the quote. +type QuoteDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// Clone an existing quote. The new quote will be created in `status=draft`. When using this parameter, you cannot specify any other parameters except for `expires_at`. +type QuoteFromQuoteParams struct { + // Whether this quote is a revision of the previous quote. + IsRevision *bool `form:"is_revision"` + // The `id` of the quote that will be cloned. + Quote *string `form:"quote"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type QuoteInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type QuoteInvoiceSettingsParams struct { + // Number of days within which a customer must pay the invoice generated by this quote. This value will be `null` for quotes where `collection_method=charge_automatically`. + DaysUntilDue *int64 `form:"days_until_due"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *QuoteInvoiceSettingsIssuerParams `form:"issuer"` +} + +// The discounts applied to this line item. +type QuoteLineItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The recurring components of a price such as `interval` and `interval_count`. +type QuoteLineItemPriceDataRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. +type QuoteLineItemPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // The recurring components of a price such as `interval` and `interval_count`. + Recurring *QuoteLineItemPriceDataRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// A list of line items the customer is being quoted for. Each line item includes information about the product, the quantity, and the resulting cost. +type QuoteLineItemParams struct { + // The discounts applied to this line item. + Discounts []*QuoteLineItemDiscountParams `form:"discounts"` + // The ID of an existing line item on the quote. + ID *string `form:"id"` + // The ID of the price object. One of `price` or `price_data` is required. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *QuoteLineItemPriceDataParams `form:"price_data"` + // The quantity of the line item. + Quantity *int64 `form:"quantity"` + // The tax rates which apply to the line item. When set, the `default_tax_rates` on the quote do not apply to this line item. + TaxRates []*string `form:"tax_rates"` +} + +// Controls how prorations and invoices for subscriptions are calculated and orchestrated. +type QuoteSubscriptionDataBillingModeParams struct { + Type *string `form:"type"` +} + +// When creating a subscription or subscription schedule, the specified configuration data will be used. There must be at least one line item with a recurring price for a subscription or subscription schedule to be created. A subscription schedule is created if `subscription_data[effective_date]` is present and in the future, otherwise a subscription is created. +type QuoteSubscriptionDataParams struct { + // Controls how prorations and invoices for subscriptions are calculated and orchestrated. + BillingMode *QuoteSubscriptionDataBillingModeParams `form:"billing_mode"` + // The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // When creating a new subscription, the date of which the subscription schedule will start after the quote is accepted. The `effective_date` is ignored if it is in the past when the quote is accepted. + EffectiveDate *int64 `form:"effective_date"` + EffectiveDateCurrentPeriodEnd *bool `form:"-"` // See custom AppendTo + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will set metadata on the subscription or subscription schedule when the quote is accepted. If a recurring price is included in `line_items`, this field will be passed to the resulting subscription's `metadata` field. If `subscription_data.effective_date` is used, this field will be passed to the resulting subscription schedule's `phases.metadata` field. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + Metadata map[string]string `form:"metadata"` + // Integer representing the number of trial period days before the customer is charged for the first time. + TrialPeriodDays *int64 `form:"trial_period_days"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *QuoteSubscriptionDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// AppendTo implements custom encoding logic for QuoteSubscriptionDataParams. +func (p *QuoteSubscriptionDataParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.EffectiveDateCurrentPeriodEnd) { + body.Add(form.FormatKey(append(keyParts, "effective_date")), "current_period_end") + } +} + +// The data with which to automatically create a Transfer for each of the invoices. +type QuoteTransferDataParams struct { + // The amount that will be transferred automatically when the invoice is paid. If no amount is set, the full amount is transferred. There cannot be any line items with recurring prices when using this field. + Amount *int64 `form:"amount"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. There must be at least 1 line item with a recurring price to use this field. + AmountPercent *float64 `form:"amount_percent"` + // ID of an existing, connected Stripe account. + Destination *string `form:"destination"` +} + +// A quote models prices and services for a customer. Default options for header, description, footer, and expires_at can be set in the dashboard via the [quote template](https://dashboard.stripe.com/settings/billing/quote). +type QuoteParams struct { + Params `form:"*"` + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. There cannot be any line items with recurring prices when using this field. + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. There must be at least 1 line item with a recurring price to use this field. + ApplicationFeePercent *float64 `form:"application_fee_percent"` + // Settings for automatic tax lookup for this quote and resulting invoices and subscriptions. + AutomaticTax *QuoteAutomaticTaxParams `form:"automatic_tax"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay invoices at the end of the subscription cycle or at invoice finalization using the default payment method attached to the subscription or customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically`. + CollectionMethod *string `form:"collection_method"` + // The customer for which this quote belongs to. A customer is required before finalizing the quote. Once specified, it cannot be changed. + Customer *string `form:"customer"` + // The tax rates that will apply to any line item that does not have `tax_rates` set. + DefaultTaxRates []*string `form:"default_tax_rates"` + // A description that will be displayed on the quote PDF. If no value is passed, the default description configured in your [quote template settings](https://dashboard.stripe.com/settings/billing/quote) will be used. + Description *string `form:"description"` + // The discounts applied to the quote. + Discounts []*QuoteDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A future timestamp on which the quote will be canceled if in `open` or `draft` status. Measured in seconds since the Unix epoch. If no value is passed, the default expiration date configured in your [quote template settings](https://dashboard.stripe.com/settings/billing/quote) will be used. + ExpiresAt *int64 `form:"expires_at"` + // A footer that will be displayed on the quote PDF. If no value is passed, the default footer configured in your [quote template settings](https://dashboard.stripe.com/settings/billing/quote) will be used. + Footer *string `form:"footer"` + // Clone an existing quote. The new quote will be created in `status=draft`. When using this parameter, you cannot specify any other parameters except for `expires_at`. + FromQuote *QuoteFromQuoteParams `form:"from_quote"` + // A header that will be displayed on the quote PDF. If no value is passed, the default header configured in your [quote template settings](https://dashboard.stripe.com/settings/billing/quote) will be used. + Header *string `form:"header"` + // All invoices will be billed using the specified settings. + InvoiceSettings *QuoteInvoiceSettingsParams `form:"invoice_settings"` + // A list of line items the customer is being quoted for. Each line item includes information about the product, the quantity, and the resulting cost. + LineItems []*QuoteLineItemParams `form:"line_items"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The account on behalf of which to charge. + OnBehalfOf *string `form:"on_behalf_of"` + // When creating a subscription or subscription schedule, the specified configuration data will be used. There must be at least one line item with a recurring price for a subscription or subscription schedule to be created. A subscription schedule is created if `subscription_data[effective_date]` is present and in the future, otherwise a subscription is created. + SubscriptionData *QuoteSubscriptionDataParams `form:"subscription_data"` + // ID of the test clock to attach to the quote. + TestClock *string `form:"test_clock"` + // The data with which to automatically create a Transfer for each of the invoices. + TransferData *QuoteTransferDataParams `form:"transfer_data"` +} + +// AddExpand appends a new field to expand. +func (p *QuoteParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *QuoteParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// When retrieving a quote, there is an includable [computed.upfront.line_items](https://stripe.com/docs/api/quotes/object#quote_object-computed-upfront-line_items) property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of upfront line items. +type QuoteListComputedUpfrontLineItemsParams struct { + ListParams `form:"*"` + Quote *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *QuoteListComputedUpfrontLineItemsParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When retrieving a quote, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. +type QuoteListLineItemsParams struct { + ListParams `form:"*"` + Quote *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *QuoteListLineItemsParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Accepts the specified quote. +type QuoteAcceptParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *QuoteAcceptParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Cancels the quote. +type QuoteCancelParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *QuoteCancelParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Finalizes the quote. +type QuoteFinalizeQuoteParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A future timestamp on which the quote will be canceled if in `open` or `draft` status. Measured in seconds since the Unix epoch. + ExpiresAt *int64 `form:"expires_at"` +} + +// AddExpand appends a new field to expand. +func (p *QuoteFinalizeQuoteParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Download the PDF for a finalized quote. Explanation for special handling can be found [here](https://docs.stripe.com/quotes/overview#quote_pdf) +type QuotePDFParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *QuotePDFParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type QuoteCreateAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Settings for automatic tax lookup for this quote and resulting invoices and subscriptions. +type QuoteCreateAutomaticTaxParams struct { + // Controls whether Stripe will automatically compute tax on the resulting invoices or subscriptions as well as the quote itself. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *QuoteCreateAutomaticTaxLiabilityParams `form:"liability"` +} + +// The discounts applied to the quote. +type QuoteCreateDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// Clone an existing quote. The new quote will be created in `status=draft`. When using this parameter, you cannot specify any other parameters except for `expires_at`. +type QuoteCreateFromQuoteParams struct { + // Whether this quote is a revision of the previous quote. + IsRevision *bool `form:"is_revision"` + // The `id` of the quote that will be cloned. + Quote *string `form:"quote"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type QuoteCreateInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type QuoteCreateInvoiceSettingsParams struct { + // Number of days within which a customer must pay the invoice generated by this quote. This value will be `null` for quotes where `collection_method=charge_automatically`. + DaysUntilDue *int64 `form:"days_until_due"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *QuoteCreateInvoiceSettingsIssuerParams `form:"issuer"` +} + +// The discounts applied to this line item. +type QuoteCreateLineItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The recurring components of a price such as `interval` and `interval_count`. +type QuoteCreateLineItemPriceDataRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. +type QuoteCreateLineItemPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // The recurring components of a price such as `interval` and `interval_count`. + Recurring *QuoteCreateLineItemPriceDataRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// A list of line items the customer is being quoted for. Each line item includes information about the product, the quantity, and the resulting cost. +type QuoteCreateLineItemParams struct { + // The discounts applied to this line item. + Discounts []*QuoteCreateLineItemDiscountParams `form:"discounts"` + // The ID of the price object. One of `price` or `price_data` is required. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *QuoteCreateLineItemPriceDataParams `form:"price_data"` + // The quantity of the line item. + Quantity *int64 `form:"quantity"` + // The tax rates which apply to the line item. When set, the `default_tax_rates` on the quote do not apply to this line item. + TaxRates []*string `form:"tax_rates"` +} + +// Controls how prorations and invoices for subscriptions are calculated and orchestrated. +type QuoteCreateSubscriptionDataBillingModeParams struct { + Type *string `form:"type"` +} + +// When creating a subscription or subscription schedule, the specified configuration data will be used. There must be at least one line item with a recurring price for a subscription or subscription schedule to be created. A subscription schedule is created if `subscription_data[effective_date]` is present and in the future, otherwise a subscription is created. +type QuoteCreateSubscriptionDataParams struct { + // Controls how prorations and invoices for subscriptions are calculated and orchestrated. + BillingMode *QuoteCreateSubscriptionDataBillingModeParams `form:"billing_mode"` + // The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // When creating a new subscription, the date of which the subscription schedule will start after the quote is accepted. The `effective_date` is ignored if it is in the past when the quote is accepted. + EffectiveDate *int64 `form:"effective_date"` + EffectiveDateCurrentPeriodEnd *bool `form:"-"` // See custom AppendTo + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will set metadata on the subscription or subscription schedule when the quote is accepted. If a recurring price is included in `line_items`, this field will be passed to the resulting subscription's `metadata` field. If `subscription_data.effective_date` is used, this field will be passed to the resulting subscription schedule's `phases.metadata` field. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + Metadata map[string]string `form:"metadata"` + // Integer representing the number of trial period days before the customer is charged for the first time. + TrialPeriodDays *int64 `form:"trial_period_days"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *QuoteCreateSubscriptionDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// AppendTo implements custom encoding logic for QuoteCreateSubscriptionDataParams. +func (p *QuoteCreateSubscriptionDataParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.EffectiveDateCurrentPeriodEnd) { + body.Add(form.FormatKey(append(keyParts, "effective_date")), "current_period_end") + } +} + +// The data with which to automatically create a Transfer for each of the invoices. +type QuoteCreateTransferDataParams struct { + // The amount that will be transferred automatically when the invoice is paid. If no amount is set, the full amount is transferred. There cannot be any line items with recurring prices when using this field. + Amount *int64 `form:"amount"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. There must be at least 1 line item with a recurring price to use this field. + AmountPercent *float64 `form:"amount_percent"` + // ID of an existing, connected Stripe account. + Destination *string `form:"destination"` +} + +// A quote models prices and services for a customer. Default options for header, description, footer, and expires_at can be set in the dashboard via the [quote template](https://dashboard.stripe.com/settings/billing/quote). +type QuoteCreateParams struct { + Params `form:"*"` + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. There cannot be any line items with recurring prices when using this field. + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. There must be at least 1 line item with a recurring price to use this field. + ApplicationFeePercent *float64 `form:"application_fee_percent"` + // Settings for automatic tax lookup for this quote and resulting invoices and subscriptions. + AutomaticTax *QuoteCreateAutomaticTaxParams `form:"automatic_tax"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay invoices at the end of the subscription cycle or at invoice finalization using the default payment method attached to the subscription or customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically`. + CollectionMethod *string `form:"collection_method"` + // The customer for which this quote belongs to. A customer is required before finalizing the quote. Once specified, it cannot be changed. + Customer *string `form:"customer"` + // The tax rates that will apply to any line item that does not have `tax_rates` set. + DefaultTaxRates []*string `form:"default_tax_rates"` + // A description that will be displayed on the quote PDF. If no value is passed, the default description configured in your [quote template settings](https://dashboard.stripe.com/settings/billing/quote) will be used. + Description *string `form:"description"` + // The discounts applied to the quote. + Discounts []*QuoteCreateDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A future timestamp on which the quote will be canceled if in `open` or `draft` status. Measured in seconds since the Unix epoch. If no value is passed, the default expiration date configured in your [quote template settings](https://dashboard.stripe.com/settings/billing/quote) will be used. + ExpiresAt *int64 `form:"expires_at"` + // A footer that will be displayed on the quote PDF. If no value is passed, the default footer configured in your [quote template settings](https://dashboard.stripe.com/settings/billing/quote) will be used. + Footer *string `form:"footer"` + // Clone an existing quote. The new quote will be created in `status=draft`. When using this parameter, you cannot specify any other parameters except for `expires_at`. + FromQuote *QuoteCreateFromQuoteParams `form:"from_quote"` + // A header that will be displayed on the quote PDF. If no value is passed, the default header configured in your [quote template settings](https://dashboard.stripe.com/settings/billing/quote) will be used. + Header *string `form:"header"` + // All invoices will be billed using the specified settings. + InvoiceSettings *QuoteCreateInvoiceSettingsParams `form:"invoice_settings"` + // A list of line items the customer is being quoted for. Each line item includes information about the product, the quantity, and the resulting cost. + LineItems []*QuoteCreateLineItemParams `form:"line_items"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The account on behalf of which to charge. + OnBehalfOf *string `form:"on_behalf_of"` + // When creating a subscription or subscription schedule, the specified configuration data will be used. There must be at least one line item with a recurring price for a subscription or subscription schedule to be created. A subscription schedule is created if `subscription_data[effective_date]` is present and in the future, otherwise a subscription is created. + SubscriptionData *QuoteCreateSubscriptionDataParams `form:"subscription_data"` + // ID of the test clock to attach to the quote. + TestClock *string `form:"test_clock"` + // The data with which to automatically create a Transfer for each of the invoices. + TransferData *QuoteCreateTransferDataParams `form:"transfer_data"` +} + +// AddExpand appends a new field to expand. +func (p *QuoteCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *QuoteCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the quote with the given ID. +type QuoteRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *QuoteRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type QuoteUpdateAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Settings for automatic tax lookup for this quote and resulting invoices and subscriptions. +type QuoteUpdateAutomaticTaxParams struct { + // Controls whether Stripe will automatically compute tax on the resulting invoices or subscriptions as well as the quote itself. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *QuoteUpdateAutomaticTaxLiabilityParams `form:"liability"` +} + +// The discounts applied to the quote. +type QuoteUpdateDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type QuoteUpdateInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type QuoteUpdateInvoiceSettingsParams struct { + // Number of days within which a customer must pay the invoice generated by this quote. This value will be `null` for quotes where `collection_method=charge_automatically`. + DaysUntilDue *int64 `form:"days_until_due"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *QuoteUpdateInvoiceSettingsIssuerParams `form:"issuer"` +} + +// The discounts applied to this line item. +type QuoteUpdateLineItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The recurring components of a price such as `interval` and `interval_count`. +type QuoteUpdateLineItemPriceDataRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. +type QuoteUpdateLineItemPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // The recurring components of a price such as `interval` and `interval_count`. + Recurring *QuoteUpdateLineItemPriceDataRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// A list of line items the customer is being quoted for. Each line item includes information about the product, the quantity, and the resulting cost. +type QuoteUpdateLineItemParams struct { + // The discounts applied to this line item. + Discounts []*QuoteUpdateLineItemDiscountParams `form:"discounts"` + // The ID of an existing line item on the quote. + ID *string `form:"id"` + // The ID of the price object. One of `price` or `price_data` is required. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *QuoteUpdateLineItemPriceDataParams `form:"price_data"` + // The quantity of the line item. + Quantity *int64 `form:"quantity"` + // The tax rates which apply to the line item. When set, the `default_tax_rates` on the quote do not apply to this line item. + TaxRates []*string `form:"tax_rates"` +} + +// When creating a subscription or subscription schedule, the specified configuration data will be used. There must be at least one line item with a recurring price for a subscription or subscription schedule to be created. A subscription schedule is created if `subscription_data[effective_date]` is present and in the future, otherwise a subscription is created. +type QuoteUpdateSubscriptionDataParams struct { + // The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // When creating a new subscription, the date of which the subscription schedule will start after the quote is accepted. The `effective_date` is ignored if it is in the past when the quote is accepted. + EffectiveDate *int64 `form:"effective_date"` + EffectiveDateCurrentPeriodEnd *bool `form:"-"` // See custom AppendTo + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will set metadata on the subscription or subscription schedule when the quote is accepted. If a recurring price is included in `line_items`, this field will be passed to the resulting subscription's `metadata` field. If `subscription_data.effective_date` is used, this field will be passed to the resulting subscription schedule's `phases.metadata` field. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + Metadata map[string]string `form:"metadata"` + // Integer representing the number of trial period days before the customer is charged for the first time. + TrialPeriodDays *int64 `form:"trial_period_days"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *QuoteUpdateSubscriptionDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// AppendTo implements custom encoding logic for QuoteUpdateSubscriptionDataParams. +func (p *QuoteUpdateSubscriptionDataParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.EffectiveDateCurrentPeriodEnd) { + body.Add(form.FormatKey(append(keyParts, "effective_date")), "current_period_end") + } +} + +// The data with which to automatically create a Transfer for each of the invoices. +type QuoteUpdateTransferDataParams struct { + // The amount that will be transferred automatically when the invoice is paid. If no amount is set, the full amount is transferred. There cannot be any line items with recurring prices when using this field. + Amount *int64 `form:"amount"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. There must be at least 1 line item with a recurring price to use this field. + AmountPercent *float64 `form:"amount_percent"` + // ID of an existing, connected Stripe account. + Destination *string `form:"destination"` +} + +// A quote models prices and services for a customer. +type QuoteUpdateParams struct { + Params `form:"*"` + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. There cannot be any line items with recurring prices when using this field. + ApplicationFeeAmount *int64 `form:"application_fee_amount"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. There must be at least 1 line item with a recurring price to use this field. + ApplicationFeePercent *float64 `form:"application_fee_percent"` + // Settings for automatic tax lookup for this quote and resulting invoices and subscriptions. + AutomaticTax *QuoteUpdateAutomaticTaxParams `form:"automatic_tax"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay invoices at the end of the subscription cycle or at invoice finalization using the default payment method attached to the subscription or customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically`. + CollectionMethod *string `form:"collection_method"` + // The customer for which this quote belongs to. A customer is required before finalizing the quote. Once specified, it cannot be changed. + Customer *string `form:"customer"` + // The tax rates that will apply to any line item that does not have `tax_rates` set. + DefaultTaxRates []*string `form:"default_tax_rates"` + // A description that will be displayed on the quote PDF. + Description *string `form:"description"` + // The discounts applied to the quote. + Discounts []*QuoteUpdateDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A future timestamp on which the quote will be canceled if in `open` or `draft` status. Measured in seconds since the Unix epoch. + ExpiresAt *int64 `form:"expires_at"` + // A footer that will be displayed on the quote PDF. + Footer *string `form:"footer"` + // A header that will be displayed on the quote PDF. + Header *string `form:"header"` + // All invoices will be billed using the specified settings. + InvoiceSettings *QuoteUpdateInvoiceSettingsParams `form:"invoice_settings"` + // A list of line items the customer is being quoted for. Each line item includes information about the product, the quantity, and the resulting cost. + LineItems []*QuoteUpdateLineItemParams `form:"line_items"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The account on behalf of which to charge. + OnBehalfOf *string `form:"on_behalf_of"` + // When creating a subscription or subscription schedule, the specified configuration data will be used. There must be at least one line item with a recurring price for a subscription or subscription schedule to be created. A subscription schedule is created if `subscription_data[effective_date]` is present and in the future, otherwise a subscription is created. + SubscriptionData *QuoteUpdateSubscriptionDataParams `form:"subscription_data"` + // The data with which to automatically create a Transfer for each of the invoices. + TransferData *QuoteUpdateTransferDataParams `form:"transfer_data"` +} + +// AddExpand appends a new field to expand. +func (p *QuoteUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *QuoteUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type QuoteAutomaticTaxLiability struct { + // The connected account being referenced when `type` is `account`. + Account *Account `json:"account"` + // Type of the account referenced. + Type QuoteAutomaticTaxLiabilityType `json:"type"` +} +type QuoteAutomaticTax struct { + // Automatically calculate taxes + Enabled bool `json:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *QuoteAutomaticTaxLiability `json:"liability"` + // The tax provider powering automatic tax. + Provider string `json:"provider"` + // The status of the most recent automated tax calculation for this quote. + Status QuoteAutomaticTaxStatus `json:"status"` +} + +// The aggregated discounts. +type QuoteComputedRecurringTotalDetailsBreakdownDiscount struct { + // The amount discounted. + Amount int64 `json:"amount"` + // A discount represents the actual application of a [coupon](https://stripe.com/docs/api#coupons) or [promotion code](https://stripe.com/docs/api#promotion_codes). + // It contains information about when the discount began, when it will end, and what it is applied to. + // + // Related guide: [Applying discounts to subscriptions](https://stripe.com/docs/billing/subscriptions/discounts) + Discount *Discount `json:"discount"` +} + +// The aggregated tax amounts by rate. +type QuoteComputedRecurringTotalDetailsBreakdownTax struct { + // Amount of tax applied for this rate. + Amount int64 `json:"amount"` + // Tax rates can be applied to [invoices](https://docs.stripe.com/invoicing/taxes/tax-rates), [subscriptions](https://docs.stripe.com/billing/taxes/tax-rates) and [Checkout Sessions](https://docs.stripe.com/payments/checkout/use-manual-tax-rates) to collect tax. + // + // Related guide: [Tax rates](https://docs.stripe.com/billing/taxes/tax-rates) + Rate *TaxRate `json:"rate"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason QuoteComputedRecurringTotalDetailsBreakdownTaxTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount int64 `json:"taxable_amount"` +} +type QuoteComputedRecurringTotalDetailsBreakdown struct { + // The aggregated discounts. + Discounts []*QuoteComputedRecurringTotalDetailsBreakdownDiscount `json:"discounts"` + // The aggregated tax amounts by rate. + Taxes []*QuoteComputedRecurringTotalDetailsBreakdownTax `json:"taxes"` +} +type QuoteComputedRecurringTotalDetails struct { + // This is the sum of all the discounts. + AmountDiscount int64 `json:"amount_discount"` + // This is the sum of all the shipping amounts. + AmountShipping int64 `json:"amount_shipping"` + // This is the sum of all the tax amounts. + AmountTax int64 `json:"amount_tax"` + Breakdown *QuoteComputedRecurringTotalDetailsBreakdown `json:"breakdown"` +} + +// The definitive totals and line items the customer will be charged on a recurring basis. Takes into account the line items with recurring prices and discounts with `duration=forever` coupons only. Defaults to `null` if no inputted line items with recurring prices. +type QuoteComputedRecurring struct { + // Total before any discounts or taxes are applied. + AmountSubtotal int64 `json:"amount_subtotal"` + // Total after discounts and taxes are applied. + AmountTotal int64 `json:"amount_total"` + // The frequency at which a subscription is billed. One of `day`, `week`, `month` or `year`. + Interval QuoteComputedRecurringInterval `json:"interval"` + // The number of intervals (specified in the `interval` attribute) between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. + IntervalCount int64 `json:"interval_count"` + TotalDetails *QuoteComputedRecurringTotalDetails `json:"total_details"` +} + +// The aggregated discounts. +type QuoteComputedUpfrontTotalDetailsBreakdownDiscount struct { + // The amount discounted. + Amount int64 `json:"amount"` + // A discount represents the actual application of a [coupon](https://stripe.com/docs/api#coupons) or [promotion code](https://stripe.com/docs/api#promotion_codes). + // It contains information about when the discount began, when it will end, and what it is applied to. + // + // Related guide: [Applying discounts to subscriptions](https://stripe.com/docs/billing/subscriptions/discounts) + Discount *Discount `json:"discount"` +} + +// The aggregated tax amounts by rate. +type QuoteComputedUpfrontTotalDetailsBreakdownTax struct { + // Amount of tax applied for this rate. + Amount int64 `json:"amount"` + // Tax rates can be applied to [invoices](https://docs.stripe.com/invoicing/taxes/tax-rates), [subscriptions](https://docs.stripe.com/billing/taxes/tax-rates) and [Checkout Sessions](https://docs.stripe.com/payments/checkout/use-manual-tax-rates) to collect tax. + // + // Related guide: [Tax rates](https://docs.stripe.com/billing/taxes/tax-rates) + Rate *TaxRate `json:"rate"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason QuoteComputedUpfrontTotalDetailsBreakdownTaxTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount int64 `json:"taxable_amount"` +} +type QuoteComputedUpfrontTotalDetailsBreakdown struct { + // The aggregated discounts. + Discounts []*QuoteComputedUpfrontTotalDetailsBreakdownDiscount `json:"discounts"` + // The aggregated tax amounts by rate. + Taxes []*QuoteComputedUpfrontTotalDetailsBreakdownTax `json:"taxes"` +} +type QuoteComputedUpfrontTotalDetails struct { + // This is the sum of all the discounts. + AmountDiscount int64 `json:"amount_discount"` + // This is the sum of all the shipping amounts. + AmountShipping int64 `json:"amount_shipping"` + // This is the sum of all the tax amounts. + AmountTax int64 `json:"amount_tax"` + Breakdown *QuoteComputedUpfrontTotalDetailsBreakdown `json:"breakdown"` +} +type QuoteComputedUpfront struct { + // Total before any discounts or taxes are applied. + AmountSubtotal int64 `json:"amount_subtotal"` + // Total after discounts and taxes are applied. + AmountTotal int64 `json:"amount_total"` + // The line items that will appear on the next invoice after this quote is accepted. This does not include pending invoice items that exist on the customer but may still be included in the next invoice. + LineItems *LineItemList `json:"line_items"` + TotalDetails *QuoteComputedUpfrontTotalDetails `json:"total_details"` +} +type QuoteComputed struct { + // The definitive totals and line items the customer will be charged on a recurring basis. Takes into account the line items with recurring prices and discounts with `duration=forever` coupons only. Defaults to `null` if no inputted line items with recurring prices. + Recurring *QuoteComputedRecurring `json:"recurring"` + Upfront *QuoteComputedUpfront `json:"upfront"` +} + +// Details of the quote that was cloned. See the [cloning documentation](https://stripe.com/docs/quotes/clone) for more details. +type QuoteFromQuote struct { + // Whether this quote is a revision of a different quote. + IsRevision bool `json:"is_revision"` + // The quote that was cloned. + Quote *Quote `json:"quote"` +} +type QuoteInvoiceSettingsIssuer struct { + // The connected account being referenced when `type` is `account`. + Account *Account `json:"account"` + // Type of the account referenced. + Type QuoteInvoiceSettingsIssuerType `json:"type"` +} +type QuoteInvoiceSettings struct { + // Number of days within which a customer must pay invoices generated by this quote. This value will be `null` for quotes where `collection_method=charge_automatically`. + DaysUntilDue int64 `json:"days_until_due"` + Issuer *QuoteInvoiceSettingsIssuer `json:"issuer"` +} +type QuoteStatusTransitions struct { + // The time that the quote was accepted. Measured in seconds since Unix epoch. + AcceptedAt int64 `json:"accepted_at"` + // The time that the quote was canceled. Measured in seconds since Unix epoch. + CanceledAt int64 `json:"canceled_at"` + // The time that the quote was finalized. Measured in seconds since Unix epoch. + FinalizedAt int64 `json:"finalized_at"` +} + +// The billing mode of the quote. +type QuoteSubscriptionDataBillingMode struct { + // Controls how prorations and invoices for subscriptions are calculated and orchestrated. + Type QuoteSubscriptionDataBillingModeType `json:"type"` +} +type QuoteSubscriptionData struct { + // The billing mode of the quote. + BillingMode *QuoteSubscriptionDataBillingMode `json:"billing_mode"` + // The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description string `json:"description"` + // When creating a new subscription, the date of which the subscription schedule will start after the quote is accepted. This date is ignored if it is in the past when the quote is accepted. Measured in seconds since the Unix epoch. + EffectiveDate int64 `json:"effective_date"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will set metadata on the subscription or subscription schedule when the quote is accepted. If a recurring price is included in `line_items`, this field will be passed to the resulting subscription's `metadata` field. If `subscription_data.effective_date` is used, this field will be passed to the resulting subscription schedule's `phases.metadata` field. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + Metadata map[string]string `json:"metadata"` + // Integer representing the number of trial period days before the customer is charged for the first time. + TrialPeriodDays int64 `json:"trial_period_days"` +} + +// The aggregated discounts. +type QuoteTotalDetailsBreakdownDiscount struct { + // The amount discounted. + Amount int64 `json:"amount"` + // A discount represents the actual application of a [coupon](https://stripe.com/docs/api#coupons) or [promotion code](https://stripe.com/docs/api#promotion_codes). + // It contains information about when the discount began, when it will end, and what it is applied to. + // + // Related guide: [Applying discounts to subscriptions](https://stripe.com/docs/billing/subscriptions/discounts) + Discount *Discount `json:"discount"` +} + +// The aggregated tax amounts by rate. +type QuoteTotalDetailsBreakdownTax struct { + // Amount of tax applied for this rate. + Amount int64 `json:"amount"` + // Tax rates can be applied to [invoices](https://docs.stripe.com/invoicing/taxes/tax-rates), [subscriptions](https://docs.stripe.com/billing/taxes/tax-rates) and [Checkout Sessions](https://docs.stripe.com/payments/checkout/use-manual-tax-rates) to collect tax. + // + // Related guide: [Tax rates](https://docs.stripe.com/billing/taxes/tax-rates) + Rate *TaxRate `json:"rate"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason QuoteTotalDetailsBreakdownTaxTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in cents (or local equivalent). + TaxableAmount int64 `json:"taxable_amount"` +} +type QuoteTotalDetailsBreakdown struct { + // The aggregated discounts. + Discounts []*QuoteTotalDetailsBreakdownDiscount `json:"discounts"` + // The aggregated tax amounts by rate. + Taxes []*QuoteTotalDetailsBreakdownTax `json:"taxes"` +} +type QuoteTotalDetails struct { + // This is the sum of all the discounts. + AmountDiscount int64 `json:"amount_discount"` + // This is the sum of all the shipping amounts. + AmountShipping int64 `json:"amount_shipping"` + // This is the sum of all the tax amounts. + AmountTax int64 `json:"amount_tax"` + Breakdown *QuoteTotalDetailsBreakdown `json:"breakdown"` +} + +// The account (if any) the payments will be attributed to for tax reporting, and where funds from each payment will be transferred to for each of the invoices. +type QuoteTransferData struct { + // The amount in cents (or local equivalent) that will be transferred to the destination account when the invoice is paid. By default, the entire amount is transferred to the destination. + Amount int64 `json:"amount"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount will be transferred to the destination. + AmountPercent float64 `json:"amount_percent"` + // The account where funds from the payment will be transferred to upon payment success. + Destination *Account `json:"destination"` +} + +// A Quote is a way to model prices that you'd like to provide to a customer. +// Once accepted, it will automatically create an invoice, subscription or subscription schedule. +type Quote struct { + APIResource + // Total before any discounts or taxes are applied. + AmountSubtotal int64 `json:"amount_subtotal"` + // Total after discounts and taxes are applied. + AmountTotal int64 `json:"amount_total"` + // ID of the Connect Application that created the quote. + Application *Application `json:"application"` + // The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. Only applicable if there are no line items with recurring prices on the quote. + ApplicationFeeAmount int64 `json:"application_fee_amount"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. Only applicable if there are line items with recurring prices on the quote. + ApplicationFeePercent float64 `json:"application_fee_percent"` + AutomaticTax *QuoteAutomaticTax `json:"automatic_tax"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay invoices at the end of the subscription cycle or on finalization using the default payment method attached to the subscription or customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically`. + CollectionMethod QuoteCollectionMethod `json:"collection_method"` + Computed *QuoteComputed `json:"computed"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // The customer which this quote belongs to. A customer is required before finalizing the quote. Once specified, it cannot be changed. + Customer *Customer `json:"customer"` + // The tax rates applied to this quote. + DefaultTaxRates []*TaxRate `json:"default_tax_rates"` + // A description that will be displayed on the quote PDF. + Description string `json:"description"` + // The discounts applied to this quote. + Discounts []*Discount `json:"discounts"` + // The date on which the quote will be canceled if in `open` or `draft` status. Measured in seconds since the Unix epoch. + ExpiresAt int64 `json:"expires_at"` + // A footer that will be displayed on the quote PDF. + Footer string `json:"footer"` + // Details of the quote that was cloned. See the [cloning documentation](https://stripe.com/docs/quotes/clone) for more details. + FromQuote *QuoteFromQuote `json:"from_quote"` + // A header that will be displayed on the quote PDF. + Header string `json:"header"` + // Unique identifier for the object. + ID string `json:"id"` + // The invoice that was created from this quote. + Invoice *Invoice `json:"invoice"` + InvoiceSettings *QuoteInvoiceSettings `json:"invoice_settings"` + // A list of items the customer is being quoted for. + LineItems *LineItemList `json:"line_items"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // A unique number that identifies this particular quote. This number is assigned once the quote is [finalized](https://stripe.com/docs/quotes/overview#finalize). + Number string `json:"number"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The account on behalf of which to charge. See the [Connect documentation](https://support.stripe.com/questions/sending-invoices-on-behalf-of-connected-accounts) for details. + OnBehalfOf *Account `json:"on_behalf_of"` + // The status of the quote. + Status QuoteStatus `json:"status"` + StatusTransitions *QuoteStatusTransitions `json:"status_transitions"` + // The subscription that was created or updated from this quote. + Subscription *Subscription `json:"subscription"` + SubscriptionData *QuoteSubscriptionData `json:"subscription_data"` + // The subscription schedule that was created or updated from this quote. + SubscriptionSchedule *SubscriptionSchedule `json:"subscription_schedule"` + // ID of the test clock this quote belongs to. + TestClock *TestHelpersTestClock `json:"test_clock"` + TotalDetails *QuoteTotalDetails `json:"total_details"` + // The account (if any) the payments will be attributed to for tax reporting, and where funds from each payment will be transferred to for each of the invoices. + TransferData *QuoteTransferData `json:"transfer_data"` +} + +// QuoteList is a list of Quotes as retrieved from a list endpoint. +type QuoteList struct { + APIResource + ListMeta + Data []*Quote `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Quote. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (q *Quote) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + q.ID = id + return nil + } + + type quote Quote + var v quote + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *q = Quote(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/quote_service.go b/vendor/github.com/stripe/stripe-go/v82/quote_service.go new file mode 100644 index 00000000..b1ab91c5 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/quote_service.go @@ -0,0 +1,159 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1QuoteService is used to invoke /v1/quotes APIs. +type v1QuoteService struct { + B Backend + BUploads Backend + Key string +} + +// A quote models prices and services for a customer. Default options for header, description, footer, and expires_at can be set in the dashboard via the [quote template](https://dashboard.stripe.com/settings/billing/quote). +func (c v1QuoteService) Create(ctx context.Context, params *QuoteCreateParams) (*Quote, error) { + if params == nil { + params = &QuoteCreateParams{} + } + params.Context = ctx + quote := &Quote{} + err := c.B.Call(http.MethodPost, "/v1/quotes", c.Key, params, quote) + return quote, err +} + +// Retrieves the quote with the given ID. +func (c v1QuoteService) Retrieve(ctx context.Context, id string, params *QuoteRetrieveParams) (*Quote, error) { + if params == nil { + params = &QuoteRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/quotes/%s", id) + quote := &Quote{} + err := c.B.Call(http.MethodGet, path, c.Key, params, quote) + return quote, err +} + +// A quote models prices and services for a customer. +func (c v1QuoteService) Update(ctx context.Context, id string, params *QuoteUpdateParams) (*Quote, error) { + if params == nil { + params = &QuoteUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/quotes/%s", id) + quote := &Quote{} + err := c.B.Call(http.MethodPost, path, c.Key, params, quote) + return quote, err +} + +// Accepts the specified quote. +func (c v1QuoteService) Accept(ctx context.Context, id string, params *QuoteAcceptParams) (*Quote, error) { + if params == nil { + params = &QuoteAcceptParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/quotes/%s/accept", id) + quote := &Quote{} + err := c.B.Call(http.MethodPost, path, c.Key, params, quote) + return quote, err +} + +// Cancels the quote. +func (c v1QuoteService) Cancel(ctx context.Context, id string, params *QuoteCancelParams) (*Quote, error) { + if params == nil { + params = &QuoteCancelParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/quotes/%s/cancel", id) + quote := &Quote{} + err := c.B.Call(http.MethodPost, path, c.Key, params, quote) + return quote, err +} + +// Finalizes the quote. +func (c v1QuoteService) FinalizeQuote(ctx context.Context, id string, params *QuoteFinalizeQuoteParams) (*Quote, error) { + if params == nil { + params = &QuoteFinalizeQuoteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/quotes/%s/finalize", id) + quote := &Quote{} + err := c.B.Call(http.MethodPost, path, c.Key, params, quote) + return quote, err +} + +// Download the PDF for a finalized quote. Explanation for special handling can be found [here](https://docs.stripe.com/quotes/overview#quote_pdf) +func (c v1QuoteService) PDF(ctx context.Context, id string, params *QuotePDFParams) (*APIStream, error) { + if params == nil { + params = &QuotePDFParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/quotes/%s/pdf", id) + stream := &APIStream{} + err := c.BUploads.CallStreaming(http.MethodGet, path, c.Key, params, stream) + return stream, err +} + +// Returns a list of your quotes. +func (c v1QuoteService) List(ctx context.Context, listParams *QuoteListParams) Seq2[*Quote, error] { + if listParams == nil { + listParams = &QuoteListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Quote, ListContainer, error) { + list := &QuoteList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/quotes", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// When retrieving a quote, there is an includable [computed.upfront.line_items](https://stripe.com/docs/api/quotes/object#quote_object-computed-upfront-line_items) property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of upfront line items. +func (c v1QuoteService) ListComputedUpfrontLineItems(ctx context.Context, listParams *QuoteListComputedUpfrontLineItemsParams) Seq2[*LineItem, error] { + if listParams == nil { + listParams = &QuoteListComputedUpfrontLineItemsParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/quotes/%s/computed_upfront_line_items", StringValue(listParams.Quote)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*LineItem, ListContainer, error) { + list := &LineItemList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// When retrieving a quote, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. +func (c v1QuoteService) ListLineItems(ctx context.Context, listParams *QuoteListLineItemsParams) Seq2[*LineItem, error] { + if listParams == nil { + listParams = &QuoteListLineItemsParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/quotes/%s/line_items", StringValue(listParams.Quote)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*LineItem, ListContainer, error) { + list := &LineItemList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/radar_earlyfraudwarning.go b/vendor/github.com/stripe/stripe-go/v82/radar_earlyfraudwarning.go new file mode 100644 index 00000000..9db4dd7f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/radar_earlyfraudwarning.go @@ -0,0 +1,100 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The type of fraud labelled by the issuer. One of `card_never_received`, `fraudulent_card_application`, `made_with_counterfeit_card`, `made_with_lost_card`, `made_with_stolen_card`, `misc`, `unauthorized_use_of_card`. +type RadarEarlyFraudWarningFraudType string + +// List of values that RadarEarlyFraudWarningFraudType can take +const ( + RadarEarlyFraudWarningFraudTypeCardNeverReceived RadarEarlyFraudWarningFraudType = "card_never_received" + RadarEarlyFraudWarningFraudTypeFraudulentCardApplication RadarEarlyFraudWarningFraudType = "fraudulent_card_application" + RadarEarlyFraudWarningFraudTypeMadeWithCounterfeitCard RadarEarlyFraudWarningFraudType = "made_with_counterfeit_card" + RadarEarlyFraudWarningFraudTypeMadeWithLostCard RadarEarlyFraudWarningFraudType = "made_with_lost_card" + RadarEarlyFraudWarningFraudTypeMadeWithStolenCard RadarEarlyFraudWarningFraudType = "made_with_stolen_card" + RadarEarlyFraudWarningFraudTypeMisc RadarEarlyFraudWarningFraudType = "misc" + RadarEarlyFraudWarningFraudTypeUnauthorizedUseOfCard RadarEarlyFraudWarningFraudType = "unauthorized_use_of_card" +) + +// Returns a list of early fraud warnings. +type RadarEarlyFraudWarningListParams struct { + ListParams `form:"*"` + // Only return early fraud warnings for the charge specified by this charge ID. + Charge *string `form:"charge"` + // Only return early fraud warnings that were created during the given date interval. + Created *int64 `form:"created"` + // Only return early fraud warnings that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return early fraud warnings for charges that were created by the PaymentIntent specified by this PaymentIntent ID. + PaymentIntent *string `form:"payment_intent"` +} + +// AddExpand appends a new field to expand. +func (p *RadarEarlyFraudWarningListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an early fraud warning that has previously been created. +// +// Please refer to the [early fraud warning](https://docs.stripe.com/api#early_fraud_warning_object) object reference for more details. +type RadarEarlyFraudWarningParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *RadarEarlyFraudWarningParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an early fraud warning that has previously been created. +// +// Please refer to the [early fraud warning](https://docs.stripe.com/api#early_fraud_warning_object) object reference for more details. +type RadarEarlyFraudWarningRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *RadarEarlyFraudWarningRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// An early fraud warning indicates that the card issuer has notified us that a +// charge may be fraudulent. +// +// Related guide: [Early fraud warnings](https://stripe.com/docs/disputes/measuring#early-fraud-warnings) +type RadarEarlyFraudWarning struct { + APIResource + // An EFW is actionable if it has not received a dispute and has not been fully refunded. You may wish to proactively refund a charge that receives an EFW, in order to avoid receiving a dispute later. + Actionable bool `json:"actionable"` + // ID of the charge this early fraud warning is for, optionally expanded. + Charge *Charge `json:"charge"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The type of fraud labelled by the issuer. One of `card_never_received`, `fraudulent_card_application`, `made_with_counterfeit_card`, `made_with_lost_card`, `made_with_stolen_card`, `misc`, `unauthorized_use_of_card`. + FraudType RadarEarlyFraudWarningFraudType `json:"fraud_type"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // ID of the Payment Intent this early fraud warning is for, optionally expanded. + PaymentIntent *PaymentIntent `json:"payment_intent"` +} + +// RadarEarlyFraudWarningList is a list of EarlyFraudWarnings as retrieved from a list endpoint. +type RadarEarlyFraudWarningList struct { + APIResource + ListMeta + Data []*RadarEarlyFraudWarning `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/radar_earlyfraudwarning_service.go b/vendor/github.com/stripe/stripe-go/v82/radar_earlyfraudwarning_service.go new file mode 100644 index 00000000..c301c3e0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/radar_earlyfraudwarning_service.go @@ -0,0 +1,51 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1RadarEarlyFraudWarningService is used to invoke /v1/radar/early_fraud_warnings APIs. +type v1RadarEarlyFraudWarningService struct { + B Backend + Key string +} + +// Retrieves the details of an early fraud warning that has previously been created. +// +// Please refer to the [early fraud warning](https://docs.stripe.com/api#early_fraud_warning_object) object reference for more details. +func (c v1RadarEarlyFraudWarningService) Retrieve(ctx context.Context, id string, params *RadarEarlyFraudWarningRetrieveParams) (*RadarEarlyFraudWarning, error) { + if params == nil { + params = &RadarEarlyFraudWarningRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/radar/early_fraud_warnings/%s", id) + earlyfraudwarning := &RadarEarlyFraudWarning{} + err := c.B.Call(http.MethodGet, path, c.Key, params, earlyfraudwarning) + return earlyfraudwarning, err +} + +// Returns a list of early fraud warnings. +func (c v1RadarEarlyFraudWarningService) List(ctx context.Context, listParams *RadarEarlyFraudWarningListParams) Seq2[*RadarEarlyFraudWarning, error] { + if listParams == nil { + listParams = &RadarEarlyFraudWarningListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*RadarEarlyFraudWarning, ListContainer, error) { + list := &RadarEarlyFraudWarningList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/radar/early_fraud_warnings", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/radar_valuelist.go b/vendor/github.com/stripe/stripe-go/v82/radar_valuelist.go new file mode 100644 index 00000000..37c0f463 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/radar_valuelist.go @@ -0,0 +1,181 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The type of items in the value list. One of `card_fingerprint`, `us_bank_account_fingerprint`, `sepa_debit_fingerprint`, `card_bin`, `email`, `ip_address`, `country`, `string`, `case_sensitive_string`, or `customer_id`. +type RadarValueListItemType string + +// List of values that RadarValueListItemType can take +const ( + RadarValueListItemTypeCardBin RadarValueListItemType = "card_bin" + RadarValueListItemTypeCardFingerprint RadarValueListItemType = "card_fingerprint" + RadarValueListItemTypeCaseSensitiveString RadarValueListItemType = "case_sensitive_string" + RadarValueListItemTypeCountry RadarValueListItemType = "country" + RadarValueListItemTypeCustomerID RadarValueListItemType = "customer_id" + RadarValueListItemTypeEmail RadarValueListItemType = "email" + RadarValueListItemTypeIPAddress RadarValueListItemType = "ip_address" + RadarValueListItemTypeSEPADebitFingerprint RadarValueListItemType = "sepa_debit_fingerprint" + RadarValueListItemTypeString RadarValueListItemType = "string" + RadarValueListItemTypeUSBankAccountFingerprint RadarValueListItemType = "us_bank_account_fingerprint" +) + +// Deletes a ValueList object, also deleting any items contained within the value list. To be deleted, a value list must not be referenced in any rules. +type RadarValueListParams struct { + Params `form:"*"` + // The name of the value list for use in rules. + Alias *string `form:"alias"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Type of the items in the value list. One of `card_fingerprint`, `us_bank_account_fingerprint`, `sepa_debit_fingerprint`, `card_bin`, `email`, `ip_address`, `country`, `string`, `case_sensitive_string`, or `customer_id`. Use `string` if the item type is unknown or mixed. + ItemType *string `form:"item_type"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The human-readable name of the value list. + Name *string `form:"name"` +} + +// AddExpand appends a new field to expand. +func (p *RadarValueListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *RadarValueListParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Returns a list of ValueList objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +type RadarValueListListParams struct { + ListParams `form:"*"` + // The alias used to reference the value list when writing rules. + Alias *string `form:"alias"` + // A value contained within a value list - returns all value lists containing this value. + Contains *string `form:"contains"` + // Only return value lists that were created during the given date interval. + Created *int64 `form:"created"` + // Only return value lists that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *RadarValueListListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Deletes a ValueList object, also deleting any items contained within the value list. To be deleted, a value list must not be referenced in any rules. +type RadarValueListDeleteParams struct { + Params `form:"*"` +} + +// Retrieves a ValueList object. +type RadarValueListRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *RadarValueListRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates a ValueList object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. Note that item_type is immutable. +type RadarValueListUpdateParams struct { + Params `form:"*"` + // The name of the value list for use in rules. + Alias *string `form:"alias"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The human-readable name of the value list. + Name *string `form:"name"` +} + +// AddExpand appends a new field to expand. +func (p *RadarValueListUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *RadarValueListUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Creates a new ValueList object, which can then be referenced in rules. +type RadarValueListCreateParams struct { + Params `form:"*"` + // The name of the value list for use in rules. + Alias *string `form:"alias"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Type of the items in the value list. One of `card_fingerprint`, `us_bank_account_fingerprint`, `sepa_debit_fingerprint`, `card_bin`, `email`, `ip_address`, `country`, `string`, `case_sensitive_string`, or `customer_id`. Use `string` if the item type is unknown or mixed. + ItemType *string `form:"item_type"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The human-readable name of the value list. + Name *string `form:"name"` +} + +// AddExpand appends a new field to expand. +func (p *RadarValueListCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *RadarValueListCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Value lists allow you to group values together which can then be referenced in rules. +// +// Related guide: [Default Stripe lists](https://stripe.com/docs/radar/lists#managing-list-items) +type RadarValueList struct { + APIResource + // The name of the value list for use in rules. + Alias string `json:"alias"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The name or email address of the user who created this value list. + CreatedBy string `json:"created_by"` + Deleted bool `json:"deleted"` + // Unique identifier for the object. + ID string `json:"id"` + // The type of items in the value list. One of `card_fingerprint`, `us_bank_account_fingerprint`, `sepa_debit_fingerprint`, `card_bin`, `email`, `ip_address`, `country`, `string`, `case_sensitive_string`, or `customer_id`. + ItemType RadarValueListItemType `json:"item_type"` + // List of items contained within this value list. + ListItems *RadarValueListItemList `json:"list_items"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // The name of the value list. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} + +// RadarValueListList is a list of ValueLists as retrieved from a list endpoint. +type RadarValueListList struct { + APIResource + ListMeta + Data []*RadarValueList `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/radar_valuelist_service.go b/vendor/github.com/stripe/stripe-go/v82/radar_valuelist_service.go new file mode 100644 index 00000000..69584e9e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/radar_valuelist_service.go @@ -0,0 +1,85 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1RadarValueListService is used to invoke /v1/radar/value_lists APIs. +type v1RadarValueListService struct { + B Backend + Key string +} + +// Creates a new ValueList object, which can then be referenced in rules. +func (c v1RadarValueListService) Create(ctx context.Context, params *RadarValueListCreateParams) (*RadarValueList, error) { + if params == nil { + params = &RadarValueListCreateParams{} + } + params.Context = ctx + valuelist := &RadarValueList{} + err := c.B.Call( + http.MethodPost, "/v1/radar/value_lists", c.Key, params, valuelist) + return valuelist, err +} + +// Retrieves a ValueList object. +func (c v1RadarValueListService) Retrieve(ctx context.Context, id string, params *RadarValueListRetrieveParams) (*RadarValueList, error) { + if params == nil { + params = &RadarValueListRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/radar/value_lists/%s", id) + valuelist := &RadarValueList{} + err := c.B.Call(http.MethodGet, path, c.Key, params, valuelist) + return valuelist, err +} + +// Updates a ValueList object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. Note that item_type is immutable. +func (c v1RadarValueListService) Update(ctx context.Context, id string, params *RadarValueListUpdateParams) (*RadarValueList, error) { + if params == nil { + params = &RadarValueListUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/radar/value_lists/%s", id) + valuelist := &RadarValueList{} + err := c.B.Call(http.MethodPost, path, c.Key, params, valuelist) + return valuelist, err +} + +// Deletes a ValueList object, also deleting any items contained within the value list. To be deleted, a value list must not be referenced in any rules. +func (c v1RadarValueListService) Delete(ctx context.Context, id string, params *RadarValueListDeleteParams) (*RadarValueList, error) { + if params == nil { + params = &RadarValueListDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/radar/value_lists/%s", id) + valuelist := &RadarValueList{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, valuelist) + return valuelist, err +} + +// Returns a list of ValueList objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +func (c v1RadarValueListService) List(ctx context.Context, listParams *RadarValueListListParams) Seq2[*RadarValueList, error] { + if listParams == nil { + listParams = &RadarValueListListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*RadarValueList, ListContainer, error) { + list := &RadarValueListList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/radar/value_lists", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/radar_valuelistitem.go b/vendor/github.com/stripe/stripe-go/v82/radar_valuelistitem.go new file mode 100644 index 00000000..d74e3b56 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/radar_valuelistitem.go @@ -0,0 +1,105 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Deletes a ValueListItem object, removing it from its parent value list. +type RadarValueListItemParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The value of the item (whose type must match the type of the parent value list). + Value *string `form:"value"` + // The identifier of the value list which the created item will be added to. + ValueList *string `form:"value_list"` +} + +// AddExpand appends a new field to expand. +func (p *RadarValueListItemParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Returns a list of ValueListItem objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +type RadarValueListItemListParams struct { + ListParams `form:"*"` + // Only return items that were created during the given date interval. + Created *int64 `form:"created"` + // Only return items that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Return items belonging to the parent list whose value matches the specified value (using an "is like" match). + Value *string `form:"value"` + // Identifier for the parent value list this item belongs to. + ValueList *string `form:"value_list"` +} + +// AddExpand appends a new field to expand. +func (p *RadarValueListItemListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Deletes a ValueListItem object, removing it from its parent value list. +type RadarValueListItemDeleteParams struct { + Params `form:"*"` +} + +// Retrieves a ValueListItem object. +type RadarValueListItemRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *RadarValueListItemRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates a new ValueListItem object, which is added to the specified parent value list. +type RadarValueListItemCreateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The value of the item (whose type must match the type of the parent value list). + Value *string `form:"value"` + // The identifier of the value list which the created item will be added to. + ValueList *string `form:"value_list"` +} + +// AddExpand appends a new field to expand. +func (p *RadarValueListItemCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Value list items allow you to add specific values to a given Radar value list, which can then be used in rules. +// +// Related guide: [Managing list items](https://stripe.com/docs/radar/lists#managing-list-items) +type RadarValueListItem struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The name or email address of the user who added this item to the value list. + CreatedBy string `json:"created_by"` + Deleted bool `json:"deleted"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The value of the item. + Value string `json:"value"` + // The identifier of the value list this item belongs to. + ValueList string `json:"value_list"` +} + +// RadarValueListItemList is a list of ValueListItems as retrieved from a list endpoint. +type RadarValueListItemList struct { + APIResource + ListMeta + Data []*RadarValueListItem `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/radar_valuelistitem_service.go b/vendor/github.com/stripe/stripe-go/v82/radar_valuelistitem_service.go new file mode 100644 index 00000000..2415e5e3 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/radar_valuelistitem_service.go @@ -0,0 +1,73 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1RadarValueListItemService is used to invoke /v1/radar/value_list_items APIs. +type v1RadarValueListItemService struct { + B Backend + Key string +} + +// Creates a new ValueListItem object, which is added to the specified parent value list. +func (c v1RadarValueListItemService) Create(ctx context.Context, params *RadarValueListItemCreateParams) (*RadarValueListItem, error) { + if params == nil { + params = &RadarValueListItemCreateParams{} + } + params.Context = ctx + valuelistitem := &RadarValueListItem{} + err := c.B.Call( + http.MethodPost, "/v1/radar/value_list_items", c.Key, params, valuelistitem) + return valuelistitem, err +} + +// Retrieves a ValueListItem object. +func (c v1RadarValueListItemService) Retrieve(ctx context.Context, id string, params *RadarValueListItemRetrieveParams) (*RadarValueListItem, error) { + if params == nil { + params = &RadarValueListItemRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/radar/value_list_items/%s", id) + valuelistitem := &RadarValueListItem{} + err := c.B.Call(http.MethodGet, path, c.Key, params, valuelistitem) + return valuelistitem, err +} + +// Deletes a ValueListItem object, removing it from its parent value list. +func (c v1RadarValueListItemService) Delete(ctx context.Context, id string, params *RadarValueListItemDeleteParams) (*RadarValueListItem, error) { + if params == nil { + params = &RadarValueListItemDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/radar/value_list_items/%s", id) + valuelistitem := &RadarValueListItem{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, valuelistitem) + return valuelistitem, err +} + +// Returns a list of ValueListItem objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +func (c v1RadarValueListItemService) List(ctx context.Context, listParams *RadarValueListItemListParams) Seq2[*RadarValueListItem, error] { + if listParams == nil { + listParams = &RadarValueListItemListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*RadarValueListItem, ListContainer, error) { + list := &RadarValueListItemList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/radar/value_list_items", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/refund.go b/vendor/github.com/stripe/stripe-go/v82/refund.go new file mode 100644 index 00000000..0de63287 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/refund.go @@ -0,0 +1,479 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The type of refund. This can be `refund`, `reversal`, or `pending`. +type RefundDestinationDetailsCardType string + +// List of values that RefundDestinationDetailsCardType can take +const ( + RefundDestinationDetailsCardTypePending RefundDestinationDetailsCardType = "pending" + RefundDestinationDetailsCardTypeRefund RefundDestinationDetailsCardType = "refund" + RefundDestinationDetailsCardTypeReversal RefundDestinationDetailsCardType = "reversal" +) + +// Provides the reason for the refund failure. Possible values are: `lost_or_stolen_card`, `expired_or_canceled_card`, `charge_for_pending_refund_disputed`, `insufficient_funds`, `declined`, `merchant_request`, or `unknown`. +type RefundFailureReason string + +// List of values that RefundFailureReason can take +const ( + RefundFailureReasonExpiredOrCanceledCard RefundFailureReason = "expired_or_canceled_card" + RefundFailureReasonLostOrStolenCard RefundFailureReason = "lost_or_stolen_card" + RefundFailureReasonUnknown RefundFailureReason = "unknown" +) + +// Provides the reason for why the refund is pending. Possible values are: `processing`, `insufficient_funds`, or `charge_pending`. +type RefundPendingReason string + +// List of values that RefundPendingReason can take +const ( + RefundPendingReasonChargePending RefundPendingReason = "charge_pending" + RefundPendingReasonInsufficientFunds RefundPendingReason = "insufficient_funds" + RefundPendingReasonProcessing RefundPendingReason = "processing" +) + +// Reason for the refund, which is either user-provided (`duplicate`, `fraudulent`, or `requested_by_customer`) or generated by Stripe internally (`expired_uncaptured_charge`). +type RefundReason string + +// List of values that RefundReason can take +const ( + RefundReasonDuplicate RefundReason = "duplicate" + RefundReasonExpiredUncapturedCharge RefundReason = "expired_uncaptured_charge" + RefundReasonFraudulent RefundReason = "fraudulent" + RefundReasonRequestedByCustomer RefundReason = "requested_by_customer" +) + +// Status of the refund. This can be `pending`, `requires_action`, `succeeded`, `failed`, or `canceled`. Learn more about [failed refunds](https://stripe.com/docs/refunds#failed-refunds). +type RefundStatus string + +// List of values that RefundStatus can take +const ( + RefundStatusCanceled RefundStatus = "canceled" + RefundStatusFailed RefundStatus = "failed" + RefundStatusPending RefundStatus = "pending" + RefundStatusSucceeded RefundStatus = "succeeded" + RefundStatusRequiresAction RefundStatus = "requires_action" +) + +// Returns a list of all refunds you created. We return the refunds in sorted order, with the most recent refunds appearing first. The 10 most recent refunds are always available by default on the Charge object. +type RefundListParams struct { + ListParams `form:"*"` + // Only return refunds for the charge specified by this charge ID. + Charge *string `form:"charge"` + // Only return refunds that were created during the given date interval. + Created *int64 `form:"created"` + // Only return refunds that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return refunds for the PaymentIntent specified by this ID. + PaymentIntent *string `form:"payment_intent"` +} + +// AddExpand appends a new field to expand. +func (p *RefundListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When you create a new refund, you must specify a Charge or a PaymentIntent object on which to create it. +// +// Creating a new refund will refund a charge that has previously been created but not yet refunded. +// Funds will be refunded to the credit or debit card that was originally charged. +// +// You can optionally refund only part of a charge. +// You can do so multiple times, until the entire charge has been refunded. +// +// Once entirely refunded, a charge can't be refunded again. +// This method will raise an error when called on an already-refunded charge, +// or when trying to refund more money than is left on a charge. +type RefundParams struct { + Params `form:"*"` + Amount *int64 `form:"amount"` + // The identifier of the charge to refund. + Charge *string `form:"charge"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Customer whose customer balance to refund from. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // For payment methods without native refund support (e.g., Konbini, PromptPay), use this email from the customer to receive refund instructions. + InstructionsEmail *string `form:"instructions_email"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Origin of the refund + Origin *string `form:"origin"` + // The identifier of the PaymentIntent to refund. + PaymentIntent *string `form:"payment_intent"` + // String indicating the reason for the refund. If set, possible values are `duplicate`, `fraudulent`, and `requested_by_customer`. If you believe the charge to be fraudulent, specifying `fraudulent` as the reason will add the associated card and email to your [block lists](https://stripe.com/docs/radar/lists), and will also help us improve our fraud detection algorithms. + Reason *string `form:"reason"` + // Boolean indicating whether the application fee should be refunded when refunding this charge. If a full charge refund is given, the full application fee will be refunded. Otherwise, the application fee will be refunded in an amount proportional to the amount of the charge refunded. An application fee can be refunded only by the application that created the charge. + RefundApplicationFee *bool `form:"refund_application_fee"` + // Boolean indicating whether the transfer should be reversed when refunding this charge. The transfer will be reversed proportionally to the amount being refunded (either the entire or partial amount). + // + // A transfer can be reversed only by the application that created the charge. + ReverseTransfer *bool `form:"reverse_transfer"` +} + +// AddExpand appends a new field to expand. +func (p *RefundParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *RefundParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Cancels a refund with a status of requires_action. +// +// You can't cancel refunds in other states. Only refunds for payment methods that require customer action can enter the requires_action state. +type RefundCancelParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *RefundCancelParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When you create a new refund, you must specify a Charge or a PaymentIntent object on which to create it. +// +// Creating a new refund will refund a charge that has previously been created but not yet refunded. +// Funds will be refunded to the credit or debit card that was originally charged. +// +// You can optionally refund only part of a charge. +// You can do so multiple times, until the entire charge has been refunded. +// +// Once entirely refunded, a charge can't be refunded again. +// This method will raise an error when called on an already-refunded charge, +// or when trying to refund more money than is left on a charge. +type RefundCreateParams struct { + Params `form:"*"` + Amount *int64 `form:"amount"` + // The identifier of the charge to refund. + Charge *string `form:"charge"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Customer whose customer balance to refund from. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // For payment methods without native refund support (e.g., Konbini, PromptPay), use this email from the customer to receive refund instructions. + InstructionsEmail *string `form:"instructions_email"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Origin of the refund + Origin *string `form:"origin"` + // The identifier of the PaymentIntent to refund. + PaymentIntent *string `form:"payment_intent"` + // String indicating the reason for the refund. If set, possible values are `duplicate`, `fraudulent`, and `requested_by_customer`. If you believe the charge to be fraudulent, specifying `fraudulent` as the reason will add the associated card and email to your [block lists](https://stripe.com/docs/radar/lists), and will also help us improve our fraud detection algorithms. + Reason *string `form:"reason"` + // Boolean indicating whether the application fee should be refunded when refunding this charge. If a full charge refund is given, the full application fee will be refunded. Otherwise, the application fee will be refunded in an amount proportional to the amount of the charge refunded. An application fee can be refunded only by the application that created the charge. + RefundApplicationFee *bool `form:"refund_application_fee"` + // Boolean indicating whether the transfer should be reversed when refunding this charge. The transfer will be reversed proportionally to the amount being refunded (either the entire or partial amount). + // + // A transfer can be reversed only by the application that created the charge. + ReverseTransfer *bool `form:"reverse_transfer"` +} + +// AddExpand appends a new field to expand. +func (p *RefundCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *RefundCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the details of an existing refund. +type RefundRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *RefundRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the refund that you specify by setting the values of the passed parameters. Any parameters that you don't provide remain unchanged. +// +// This request only accepts metadata as an argument. +type RefundUpdateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *RefundUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *RefundUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +type RefundDestinationDetailsAffirm struct{} +type RefundDestinationDetailsAfterpayClearpay struct{} +type RefundDestinationDetailsAlipay struct{} +type RefundDestinationDetailsAlma struct{} +type RefundDestinationDetailsAmazonPay struct{} +type RefundDestinationDetailsAuBankTransfer struct{} +type RefundDestinationDetailsBLIK struct { + // For refunds declined by the network, a decline code provided by the network which indicates the reason the refund failed. + NetworkDeclineCode string `json:"network_decline_code"` + // The reference assigned to the refund. + Reference string `json:"reference"` + // Status of the reference on the refund. This can be `pending`, `available` or `unavailable`. + ReferenceStatus string `json:"reference_status"` +} +type RefundDestinationDetailsBrBankTransfer struct { + // The reference assigned to the refund. + Reference string `json:"reference"` + // Status of the reference on the refund. This can be `pending`, `available` or `unavailable`. + ReferenceStatus string `json:"reference_status"` +} +type RefundDestinationDetailsCard struct { + // Value of the reference number assigned to the refund. + Reference string `json:"reference"` + // Status of the reference number on the refund. This can be `pending`, `available` or `unavailable`. + ReferenceStatus string `json:"reference_status"` + // Type of the reference number assigned to the refund. + ReferenceType string `json:"reference_type"` + // The type of refund. This can be `refund`, `reversal`, or `pending`. + Type RefundDestinationDetailsCardType `json:"type"` +} +type RefundDestinationDetailsCashApp struct{} +type RefundDestinationDetailsCustomerCashBalance struct{} +type RefundDestinationDetailsEPS struct{} +type RefundDestinationDetailsEUBankTransfer struct { + // The reference assigned to the refund. + Reference string `json:"reference"` + // Status of the reference on the refund. This can be `pending`, `available` or `unavailable`. + ReferenceStatus string `json:"reference_status"` +} +type RefundDestinationDetailsGBBankTransfer struct { + // The reference assigned to the refund. + Reference string `json:"reference"` + // Status of the reference on the refund. This can be `pending`, `available` or `unavailable`. + ReferenceStatus string `json:"reference_status"` +} +type RefundDestinationDetailsGiropay struct{} +type RefundDestinationDetailsGrabpay struct{} +type RefundDestinationDetailsJPBankTransfer struct { + // The reference assigned to the refund. + Reference string `json:"reference"` + // Status of the reference on the refund. This can be `pending`, `available` or `unavailable`. + ReferenceStatus string `json:"reference_status"` +} +type RefundDestinationDetailsKlarna struct{} +type RefundDestinationDetailsMultibanco struct { + // The reference assigned to the refund. + Reference string `json:"reference"` + // Status of the reference on the refund. This can be `pending`, `available` or `unavailable`. + ReferenceStatus string `json:"reference_status"` +} +type RefundDestinationDetailsMXBankTransfer struct { + // The reference assigned to the refund. + Reference string `json:"reference"` + // Status of the reference on the refund. This can be `pending`, `available` or `unavailable`. + ReferenceStatus string `json:"reference_status"` +} +type RefundDestinationDetailsNzBankTransfer struct{} +type RefundDestinationDetailsP24 struct { + // The reference assigned to the refund. + Reference string `json:"reference"` + // Status of the reference on the refund. This can be `pending`, `available` or `unavailable`. + ReferenceStatus string `json:"reference_status"` +} +type RefundDestinationDetailsPayNow struct{} +type RefundDestinationDetailsPaypal struct { + // For refunds declined by the network, a decline code provided by the network which indicates the reason the refund failed. + NetworkDeclineCode string `json:"network_decline_code"` +} +type RefundDestinationDetailsPix struct{} +type RefundDestinationDetailsRevolut struct{} +type RefundDestinationDetailsSofort struct{} +type RefundDestinationDetailsSwish struct { + // For refunds declined by the network, a decline code provided by the network which indicates the reason the refund failed. + NetworkDeclineCode string `json:"network_decline_code"` + // The reference assigned to the refund. + Reference string `json:"reference"` + // Status of the reference on the refund. This can be `pending`, `available` or `unavailable`. + ReferenceStatus string `json:"reference_status"` +} +type RefundDestinationDetailsTHBankTransfer struct { + // The reference assigned to the refund. + Reference string `json:"reference"` + // Status of the reference on the refund. This can be `pending`, `available` or `unavailable`. + ReferenceStatus string `json:"reference_status"` +} +type RefundDestinationDetailsUSBankTransfer struct { + // The reference assigned to the refund. + Reference string `json:"reference"` + // Status of the reference on the refund. This can be `pending`, `available` or `unavailable`. + ReferenceStatus string `json:"reference_status"` +} +type RefundDestinationDetailsWeChatPay struct{} +type RefundDestinationDetailsZip struct{} +type RefundDestinationDetails struct { + Affirm *RefundDestinationDetailsAffirm `json:"affirm"` + AfterpayClearpay *RefundDestinationDetailsAfterpayClearpay `json:"afterpay_clearpay"` + Alipay *RefundDestinationDetailsAlipay `json:"alipay"` + Alma *RefundDestinationDetailsAlma `json:"alma"` + AmazonPay *RefundDestinationDetailsAmazonPay `json:"amazon_pay"` + AuBankTransfer *RefundDestinationDetailsAuBankTransfer `json:"au_bank_transfer"` + BLIK *RefundDestinationDetailsBLIK `json:"blik"` + BrBankTransfer *RefundDestinationDetailsBrBankTransfer `json:"br_bank_transfer"` + Card *RefundDestinationDetailsCard `json:"card"` + CashApp *RefundDestinationDetailsCashApp `json:"cashapp"` + CustomerCashBalance *RefundDestinationDetailsCustomerCashBalance `json:"customer_cash_balance"` + EPS *RefundDestinationDetailsEPS `json:"eps"` + EUBankTransfer *RefundDestinationDetailsEUBankTransfer `json:"eu_bank_transfer"` + GBBankTransfer *RefundDestinationDetailsGBBankTransfer `json:"gb_bank_transfer"` + Giropay *RefundDestinationDetailsGiropay `json:"giropay"` + Grabpay *RefundDestinationDetailsGrabpay `json:"grabpay"` + JPBankTransfer *RefundDestinationDetailsJPBankTransfer `json:"jp_bank_transfer"` + Klarna *RefundDestinationDetailsKlarna `json:"klarna"` + Multibanco *RefundDestinationDetailsMultibanco `json:"multibanco"` + MXBankTransfer *RefundDestinationDetailsMXBankTransfer `json:"mx_bank_transfer"` + NzBankTransfer *RefundDestinationDetailsNzBankTransfer `json:"nz_bank_transfer"` + P24 *RefundDestinationDetailsP24 `json:"p24"` + PayNow *RefundDestinationDetailsPayNow `json:"paynow"` + Paypal *RefundDestinationDetailsPaypal `json:"paypal"` + Pix *RefundDestinationDetailsPix `json:"pix"` + Revolut *RefundDestinationDetailsRevolut `json:"revolut"` + Sofort *RefundDestinationDetailsSofort `json:"sofort"` + Swish *RefundDestinationDetailsSwish `json:"swish"` + THBankTransfer *RefundDestinationDetailsTHBankTransfer `json:"th_bank_transfer"` + // The type of transaction-specific details of the payment method used in the refund (e.g., `card`). An additional hash is included on `destination_details` with a name matching this value. It contains information specific to the refund transaction. + Type string `json:"type"` + USBankTransfer *RefundDestinationDetailsUSBankTransfer `json:"us_bank_transfer"` + WeChatPay *RefundDestinationDetailsWeChatPay `json:"wechat_pay"` + Zip *RefundDestinationDetailsZip `json:"zip"` +} +type RefundNextActionDisplayDetailsEmailSent struct { + // The timestamp when the email was sent. + EmailSentAt int64 `json:"email_sent_at"` + // The recipient's email address. + EmailSentTo string `json:"email_sent_to"` +} +type RefundNextActionDisplayDetails struct { + EmailSent *RefundNextActionDisplayDetailsEmailSent `json:"email_sent"` + // The expiry timestamp. + ExpiresAt int64 `json:"expires_at"` +} +type RefundNextAction struct { + DisplayDetails *RefundNextActionDisplayDetails `json:"display_details"` + // Type of the next action to perform. + Type string `json:"type"` +} +type RefundPresentmentDetails struct { + // Amount intended to be collected by this payment, denominated in presentment_currency. + PresentmentAmount int64 `json:"presentment_amount"` + // Currency presented to the customer during payment. + PresentmentCurrency Currency `json:"presentment_currency"` +} + +// Refund objects allow you to refund a previously created charge that isn't +// refunded yet. Funds are refunded to the credit or debit card that's +// initially charged. +// +// Related guide: [Refunds](https://stripe.com/docs/refunds) +type Refund struct { + APIResource + // Amount, in cents (or local equivalent). + Amount int64 `json:"amount"` + // Balance transaction that describes the impact on your account balance. + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + // ID of the charge that's refunded. + Charge *Charge `json:"charge"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // An arbitrary string attached to the object. You can use this for displaying to users (available on non-card refunds only). + Description string `json:"description"` + DestinationDetails *RefundDestinationDetails `json:"destination_details"` + // After the refund fails, this balance transaction describes the adjustment made on your account balance that reverses the initial balance transaction. + FailureBalanceTransaction *BalanceTransaction `json:"failure_balance_transaction"` + // Provides the reason for the refund failure. Possible values are: `lost_or_stolen_card`, `expired_or_canceled_card`, `charge_for_pending_refund_disputed`, `insufficient_funds`, `declined`, `merchant_request`, or `unknown`. + FailureReason RefundFailureReason `json:"failure_reason"` + // Unique identifier for the object. + ID string `json:"id"` + // For payment methods without native refund support (for example, Konbini, PromptPay), provide an email address for the customer to receive refund instructions. + InstructionsEmail string `json:"instructions_email"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + NextAction *RefundNextAction `json:"next_action"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // ID of the PaymentIntent that's refunded. + PaymentIntent *PaymentIntent `json:"payment_intent"` + // Provides the reason for why the refund is pending. Possible values are: `processing`, `insufficient_funds`, or `charge_pending`. + PendingReason RefundPendingReason `json:"pending_reason"` + PresentmentDetails *RefundPresentmentDetails `json:"presentment_details"` + // Reason for the refund, which is either user-provided (`duplicate`, `fraudulent`, or `requested_by_customer`) or generated by Stripe internally (`expired_uncaptured_charge`). + Reason RefundReason `json:"reason"` + // This is the transaction number that appears on email receipts sent for this refund. + ReceiptNumber string `json:"receipt_number"` + // The transfer reversal that's associated with the refund. Only present if the charge came from another Stripe account. + SourceTransferReversal *TransferReversal `json:"source_transfer_reversal"` + // Status of the refund. This can be `pending`, `requires_action`, `succeeded`, `failed`, or `canceled`. Learn more about [failed refunds](https://stripe.com/docs/refunds#failed-refunds). + Status RefundStatus `json:"status"` + // This refers to the transfer reversal object if the accompanying transfer reverses. This is only applicable if the charge was created using the destination parameter. + TransferReversal *TransferReversal `json:"transfer_reversal"` +} + +// RefundList is a list of Refunds as retrieved from a list endpoint. +type RefundList struct { + APIResource + ListMeta + Data []*Refund `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Refund. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (r *Refund) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + r.ID = id + return nil + } + + type refund Refund + var v refund + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *r = Refund(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/refund_service.go b/vendor/github.com/stripe/stripe-go/v82/refund_service.go new file mode 100644 index 00000000..cdaf79be --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/refund_service.go @@ -0,0 +1,98 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1RefundService is used to invoke /v1/refunds APIs. +type v1RefundService struct { + B Backend + Key string +} + +// When you create a new refund, you must specify a Charge or a PaymentIntent object on which to create it. +// +// Creating a new refund will refund a charge that has previously been created but not yet refunded. +// Funds will be refunded to the credit or debit card that was originally charged. +// +// You can optionally refund only part of a charge. +// You can do so multiple times, until the entire charge has been refunded. +// +// Once entirely refunded, a charge can't be refunded again. +// This method will raise an error when called on an already-refunded charge, +// or when trying to refund more money than is left on a charge. +func (c v1RefundService) Create(ctx context.Context, params *RefundCreateParams) (*Refund, error) { + if params == nil { + params = &RefundCreateParams{} + } + params.Context = ctx + refund := &Refund{} + err := c.B.Call(http.MethodPost, "/v1/refunds", c.Key, params, refund) + return refund, err +} + +// Retrieves the details of an existing refund. +func (c v1RefundService) Retrieve(ctx context.Context, id string, params *RefundRetrieveParams) (*Refund, error) { + if params == nil { + params = &RefundRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/refunds/%s", id) + refund := &Refund{} + err := c.B.Call(http.MethodGet, path, c.Key, params, refund) + return refund, err +} + +// Updates the refund that you specify by setting the values of the passed parameters. Any parameters that you don't provide remain unchanged. +// +// This request only accepts metadata as an argument. +func (c v1RefundService) Update(ctx context.Context, id string, params *RefundUpdateParams) (*Refund, error) { + if params == nil { + params = &RefundUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/refunds/%s", id) + refund := &Refund{} + err := c.B.Call(http.MethodPost, path, c.Key, params, refund) + return refund, err +} + +// Cancels a refund with a status of requires_action. +// +// You can't cancel refunds in other states. Only refunds for payment methods that require customer action can enter the requires_action state. +func (c v1RefundService) Cancel(ctx context.Context, id string, params *RefundCancelParams) (*Refund, error) { + if params == nil { + params = &RefundCancelParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/refunds/%s/cancel", id) + refund := &Refund{} + err := c.B.Call(http.MethodPost, path, c.Key, params, refund) + return refund, err +} + +// Returns a list of all refunds you created. We return the refunds in sorted order, with the most recent refunds appearing first. The 10 most recent refunds are always available by default on the Charge object. +func (c v1RefundService) List(ctx context.Context, listParams *RefundListParams) Seq2[*Refund, error] { + if listParams == nil { + listParams = &RefundListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Refund, ListContainer, error) { + list := &RefundList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/refunds", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/reporting_reportrun.go b/vendor/github.com/stripe/stripe-go/v82/reporting_reportrun.go new file mode 100644 index 00000000..7daf6699 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/reporting_reportrun.go @@ -0,0 +1,182 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Status of this report run. This will be `pending` when the run is initially created. +// +// When the run finishes, this will be set to `succeeded` and the `result` field will be populated. +// Rarely, we may encounter an error, at which point this will be set to `failed` and the `error` field will be populated. +type ReportingReportRunStatus string + +// List of values that ReportingReportRunStatus can take +const ( + ReportingReportRunStatusFailed ReportingReportRunStatus = "failed" + ReportingReportRunStatusPending ReportingReportRunStatus = "pending" + ReportingReportRunStatusSucceeded ReportingReportRunStatus = "succeeded" +) + +// Returns a list of Report Runs, with the most recent appearing first. +type ReportingReportRunListParams struct { + ListParams `form:"*"` + // Only return Report Runs that were created during the given date interval. + Created *int64 `form:"created"` + // Only return Report Runs that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ReportingReportRunListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Parameters specifying how the report should be run. Different Report Types have different required and optional parameters, listed in the [API Access to Reports](https://stripe.com/docs/reporting/statements/api) documentation. +type ReportingReportRunParametersParams struct { + // The set of report columns to include in the report output. If omitted, the Report Type is run with its default column set. + Columns []*string `form:"columns"` + // Connected account ID to filter for in the report run. + ConnectedAccount *string `form:"connected_account"` + // Currency of objects to be included in the report run. + Currency *string `form:"currency"` + // Ending timestamp of data to be included in the report run (exclusive). + IntervalEnd *int64 `form:"interval_end"` + // Starting timestamp of data to be included in the report run. + IntervalStart *int64 `form:"interval_start"` + // Payout ID by which to filter the report run. + Payout *string `form:"payout"` + // Category of balance transactions to be included in the report run. + ReportingCategory *string `form:"reporting_category"` + // Defaults to `Etc/UTC`. The output timezone for all timestamps in the report. A list of possible time zone values is maintained at the [IANA Time Zone Database](http://www.iana.org/time-zones). Has no effect on `interval_start` or `interval_end`. + Timezone *string `form:"timezone"` +} + +// Creates a new object and begin running the report. (Certain report types require a [live-mode API key](https://stripe.com/docs/keys#test-live-modes).) +type ReportingReportRunParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Parameters specifying how the report should be run. Different Report Types have different required and optional parameters, listed in the [API Access to Reports](https://stripe.com/docs/reporting/statements/api) documentation. + Parameters *ReportingReportRunParametersParams `form:"parameters"` + // The ID of the [report type](https://stripe.com/docs/reporting/statements/api#report-types) to run, such as `"balance.summary.1"`. + ReportType *string `form:"report_type"` +} + +// AddExpand appends a new field to expand. +func (p *ReportingReportRunParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Parameters specifying how the report should be run. Different Report Types have different required and optional parameters, listed in the [API Access to Reports](https://stripe.com/docs/reporting/statements/api) documentation. +type ReportingReportRunCreateParametersParams struct { + // The set of report columns to include in the report output. If omitted, the Report Type is run with its default column set. + Columns []*string `form:"columns"` + // Connected account ID to filter for in the report run. + ConnectedAccount *string `form:"connected_account"` + // Currency of objects to be included in the report run. + Currency *string `form:"currency"` + // Ending timestamp of data to be included in the report run (exclusive). + IntervalEnd *int64 `form:"interval_end"` + // Starting timestamp of data to be included in the report run. + IntervalStart *int64 `form:"interval_start"` + // Payout ID by which to filter the report run. + Payout *string `form:"payout"` + // Category of balance transactions to be included in the report run. + ReportingCategory *string `form:"reporting_category"` + // Defaults to `Etc/UTC`. The output timezone for all timestamps in the report. A list of possible time zone values is maintained at the [IANA Time Zone Database](http://www.iana.org/time-zones). Has no effect on `interval_start` or `interval_end`. + Timezone *string `form:"timezone"` +} + +// Creates a new object and begin running the report. (Certain report types require a [live-mode API key](https://stripe.com/docs/keys#test-live-modes).) +type ReportingReportRunCreateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Parameters specifying how the report should be run. Different Report Types have different required and optional parameters, listed in the [API Access to Reports](https://stripe.com/docs/reporting/statements/api) documentation. + Parameters *ReportingReportRunCreateParametersParams `form:"parameters"` + // The ID of the [report type](https://stripe.com/docs/reporting/statements/api#report-types) to run, such as `"balance.summary.1"`. + ReportType *string `form:"report_type"` +} + +// AddExpand appends a new field to expand. +func (p *ReportingReportRunCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an existing Report Run. +type ReportingReportRunRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ReportingReportRunRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type ReportingReportRunParameters struct { + // The set of output columns requested for inclusion in the report run. + Columns []string `json:"columns"` + // Connected account ID by which to filter the report run. + ConnectedAccount string `json:"connected_account"` + // Currency of objects to be included in the report run. + Currency Currency `json:"currency"` + // Ending timestamp of data to be included in the report run. Can be any UTC timestamp between 1 second after the user specified `interval_start` and 1 second before this report's last `data_available_end` value. + IntervalEnd int64 `json:"interval_end"` + // Starting timestamp of data to be included in the report run. Can be any UTC timestamp between 1 second after this report's `data_available_start` and 1 second before the user specified `interval_end` value. + IntervalStart int64 `json:"interval_start"` + // Payout ID by which to filter the report run. + Payout string `json:"payout"` + // Category of balance transactions to be included in the report run. + ReportingCategory string `json:"reporting_category"` + // Defaults to `Etc/UTC`. The output timezone for all timestamps in the report. A list of possible time zone values is maintained at the [IANA Time Zone Database](http://www.iana.org/time-zones). Has no effect on `interval_start` or `interval_end`. + Timezone string `json:"timezone"` +} + +// The Report Run object represents an instance of a report type generated with +// specific run parameters. Once the object is created, Stripe begins processing the report. +// When the report has finished running, it will give you a reference to a file +// where you can retrieve your results. For an overview, see +// [API Access to Reports](https://stripe.com/docs/reporting/statements/api). +// +// Note that certain report types can only be run based on your live-mode data (not test-mode +// data), and will error when queried without a [live-mode API key](https://stripe.com/docs/keys#test-live-modes). +type ReportingReportRun struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // If something should go wrong during the run, a message about the failure (populated when + // `status=failed`). + Error string `json:"error"` + // Unique identifier for the object. + ID string `json:"id"` + // `true` if the report is run on live mode data and `false` if it is run on test mode data. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + Parameters *ReportingReportRunParameters `json:"parameters"` + // The ID of the [report type](https://stripe.com/docs/reports/report-types) to run, such as `"balance.summary.1"`. + ReportType string `json:"report_type"` + // The file object representing the result of the report run (populated when + // `status=succeeded`). + Result *File `json:"result"` + // Status of this report run. This will be `pending` when the run is initially created. + // When the run finishes, this will be set to `succeeded` and the `result` field will be populated. + // Rarely, we may encounter an error, at which point this will be set to `failed` and the `error` field will be populated. + Status ReportingReportRunStatus `json:"status"` + // Timestamp at which this run successfully finished (populated when + // `status=succeeded`). Measured in seconds since the Unix epoch. + SucceededAt int64 `json:"succeeded_at"` +} + +// ReportingReportRunList is a list of ReportRuns as retrieved from a list endpoint. +type ReportingReportRunList struct { + APIResource + ListMeta + Data []*ReportingReportRun `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/reporting_reportrun_service.go b/vendor/github.com/stripe/stripe-go/v82/reporting_reportrun_service.go new file mode 100644 index 00000000..3212934f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/reporting_reportrun_service.go @@ -0,0 +1,61 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1ReportingReportRunService is used to invoke /v1/reporting/report_runs APIs. +type v1ReportingReportRunService struct { + B Backend + Key string +} + +// Creates a new object and begin running the report. (Certain report types require a [live-mode API key](https://stripe.com/docs/keys#test-live-modes).) +func (c v1ReportingReportRunService) Create(ctx context.Context, params *ReportingReportRunCreateParams) (*ReportingReportRun, error) { + if params == nil { + params = &ReportingReportRunCreateParams{} + } + params.Context = ctx + reportrun := &ReportingReportRun{} + err := c.B.Call( + http.MethodPost, "/v1/reporting/report_runs", c.Key, params, reportrun) + return reportrun, err +} + +// Retrieves the details of an existing Report Run. +func (c v1ReportingReportRunService) Retrieve(ctx context.Context, id string, params *ReportingReportRunRetrieveParams) (*ReportingReportRun, error) { + if params == nil { + params = &ReportingReportRunRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/reporting/report_runs/%s", id) + reportrun := &ReportingReportRun{} + err := c.B.Call(http.MethodGet, path, c.Key, params, reportrun) + return reportrun, err +} + +// Returns a list of Report Runs, with the most recent appearing first. +func (c v1ReportingReportRunService) List(ctx context.Context, listParams *ReportingReportRunListParams) Seq2[*ReportingReportRun, error] { + if listParams == nil { + listParams = &ReportingReportRunListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*ReportingReportRun, ListContainer, error) { + list := &ReportingReportRunList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/reporting/report_runs", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/reporting_reporttype.go b/vendor/github.com/stripe/stripe-go/v82/reporting_reporttype.go new file mode 100644 index 00000000..d181a7b6 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/reporting_reporttype.go @@ -0,0 +1,80 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Returns a full list of Report Types. +type ReportingReportTypeListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ReportingReportTypeListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of a Report Type. (Certain report types require a [live-mode API key](https://stripe.com/docs/keys#test-live-modes).) +type ReportingReportTypeParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ReportingReportTypeParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of a Report Type. (Certain report types require a [live-mode API key](https://stripe.com/docs/keys#test-live-modes).) +type ReportingReportTypeRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ReportingReportTypeRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The Report Type resource corresponds to a particular type of report, such as +// the "Activity summary" or "Itemized payouts" reports. These objects are +// identified by an ID belonging to a set of enumerated values. See +// [API Access to Reports documentation](https://stripe.com/docs/reporting/statements/api) +// for those Report Type IDs, along with required and optional parameters. +// +// Note that certain report types can only be run based on your live-mode data (not test-mode +// data), and will error when queried without a [live-mode API key](https://stripe.com/docs/keys#test-live-modes). +type ReportingReportType struct { + APIResource + // Most recent time for which this Report Type is available. Measured in seconds since the Unix epoch. + DataAvailableEnd int64 `json:"data_available_end"` + // Earliest time for which this Report Type is available. Measured in seconds since the Unix epoch. + DataAvailableStart int64 `json:"data_available_start"` + // List of column names that are included by default when this Report Type gets run. (If the Report Type doesn't support the `columns` parameter, this will be null.) + DefaultColumns []string `json:"default_columns"` + // The [ID of the Report Type](https://stripe.com/docs/reporting/statements/api#available-report-types), such as `balance.summary.1`. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Human-readable name of the Report Type + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // When this Report Type was latest updated. Measured in seconds since the Unix epoch. + Updated int64 `json:"updated"` + // Version of the Report Type. Different versions report with the same ID will have the same purpose, but may take different run parameters or have different result schemas. + Version int64 `json:"version"` +} + +// ReportingReportTypeList is a list of ReportTypes as retrieved from a list endpoint. +type ReportingReportTypeList struct { + APIResource + ListMeta + Data []*ReportingReportType `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/reporting_reporttype_service.go b/vendor/github.com/stripe/stripe-go/v82/reporting_reporttype_service.go new file mode 100644 index 00000000..987051ab --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/reporting_reporttype_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1ReportingReportTypeService is used to invoke /v1/reporting/report_types APIs. +type v1ReportingReportTypeService struct { + B Backend + Key string +} + +// Retrieves the details of a Report Type. (Certain report types require a [live-mode API key](https://stripe.com/docs/keys#test-live-modes).) +func (c v1ReportingReportTypeService) Retrieve(ctx context.Context, id string, params *ReportingReportTypeRetrieveParams) (*ReportingReportType, error) { + if params == nil { + params = &ReportingReportTypeRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/reporting/report_types/%s", id) + reporttype := &ReportingReportType{} + err := c.B.Call(http.MethodGet, path, c.Key, params, reporttype) + return reporttype, err +} + +// Returns a full list of Report Types. +func (c v1ReportingReportTypeService) List(ctx context.Context, listParams *ReportingReportTypeListParams) Seq2[*ReportingReportType, error] { + if listParams == nil { + listParams = &ReportingReportTypeListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*ReportingReportType, ListContainer, error) { + list := &ReportingReportTypeList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/reporting/report_types", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/reservetransaction.go b/vendor/github.com/stripe/stripe-go/v82/reservetransaction.go new file mode 100644 index 00000000..eb9a07af --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/reservetransaction.go @@ -0,0 +1,40 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +type ReserveTransaction struct { + Amount int64 `json:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // Unique identifier for the object. + ID string `json:"id"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} + +// UnmarshalJSON handles deserialization of a ReserveTransaction. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (r *ReserveTransaction) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + r.ID = id + return nil + } + + type reserveTransaction ReserveTransaction + var v reserveTransaction + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *r = ReserveTransaction(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/review.go b/vendor/github.com/stripe/stripe-go/v82/review.go new file mode 100644 index 00000000..0dee0b67 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/review.go @@ -0,0 +1,186 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The reason the review was closed, or null if it has not yet been closed. One of `approved`, `refunded`, `refunded_as_fraud`, `disputed`, `redacted`, or `canceled`. +type ReviewClosedReason string + +// List of values that ReviewClosedReason can take +const ( + ReviewClosedReasonApproved ReviewClosedReason = "approved" + ReviewClosedReasonCanceled ReviewClosedReason = "canceled" + ReviewClosedReasonDisputed ReviewClosedReason = "disputed" + ReviewClosedReasonRedacted ReviewClosedReason = "redacted" + ReviewClosedReasonRefunded ReviewClosedReason = "refunded" + ReviewClosedReasonRefundedAsFraud ReviewClosedReason = "refunded_as_fraud" +) + +// The reason the review was opened. One of `rule` or `manual`. +type ReviewOpenedReason string + +// List of values that ReviewOpenedReason can take +const ( + ReviewOpenedReasonManual ReviewOpenedReason = "manual" + ReviewOpenedReasonRule ReviewOpenedReason = "rule" +) + +// The reason the review is currently open or closed. One of `rule`, `manual`, `approved`, `refunded`, `refunded_as_fraud`, `disputed`, `redacted`, or `canceled`. +type ReviewReason string + +// List of values that ReviewReason can take +const ( + ReviewReasonApproved ReviewReason = "approved" + ReviewReasonCanceled ReviewReason = "canceled" + ReviewReasonDisputed ReviewReason = "disputed" + ReviewReasonManual ReviewReason = "manual" + ReviewReasonRefunded ReviewReason = "refunded" + ReviewReasonRefundedAsFraud ReviewReason = "refunded_as_fraud" + ReviewReasonRedacted ReviewReason = "redacted" + ReviewReasonRule ReviewReason = "rule" +) + +// Returns a list of Review objects that have open set to true. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +type ReviewListParams struct { + ListParams `form:"*"` + // Only return reviews that were created during the given date interval. + Created *int64 `form:"created"` + // Only return reviews that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ReviewListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a Review object. +type ReviewParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ReviewParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Approves a Review object, closing it and removing it from the list of reviews. +type ReviewApproveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ReviewApproveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a Review object. +type ReviewRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ReviewRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Information related to the location of the payment. Note that this information is an approximation and attempts to locate the nearest population center - it should not be used to determine a specific address. +type ReviewIPAddressLocation struct { + // The city where the payment originated. + City string `json:"city"` + // Two-letter ISO code representing the country where the payment originated. + Country string `json:"country"` + // The geographic latitude where the payment originated. + Latitude float64 `json:"latitude"` + // The geographic longitude where the payment originated. + Longitude float64 `json:"longitude"` + // The state/county/province/region where the payment originated. + Region string `json:"region"` +} + +// Information related to the browsing session of the user who initiated the payment. +type ReviewSession struct { + // The browser used in this browser session (e.g., `Chrome`). + Browser string `json:"browser"` + // Information about the device used for the browser session (e.g., `Samsung SM-G930T`). + Device string `json:"device"` + // The platform for the browser session (e.g., `Macintosh`). + Platform string `json:"platform"` + // The version for the browser session (e.g., `61.0.3163.100`). + Version string `json:"version"` +} + +// Reviews can be used to supplement automated fraud detection with human expertise. +// +// Learn more about [Radar](https://docs.stripe.com/radar) and reviewing payments +// [here](https://stripe.com/docs/radar/reviews). +type Review struct { + APIResource + // The ZIP or postal code of the card used, if applicable. + BillingZip string `json:"billing_zip"` + // The charge associated with this review. + Charge *Charge `json:"charge"` + // The reason the review was closed, or null if it has not yet been closed. One of `approved`, `refunded`, `refunded_as_fraud`, `disputed`, `redacted`, or `canceled`. + ClosedReason ReviewClosedReason `json:"closed_reason"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Unique identifier for the object. + ID string `json:"id"` + // The IP address where the payment originated. + IPAddress string `json:"ip_address"` + // Information related to the location of the payment. Note that this information is an approximation and attempts to locate the nearest population center - it should not be used to determine a specific address. + IPAddressLocation *ReviewIPAddressLocation `json:"ip_address_location"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // If `true`, the review needs action. + Open bool `json:"open"` + // The reason the review was opened. One of `rule` or `manual`. + OpenedReason ReviewOpenedReason `json:"opened_reason"` + // The PaymentIntent ID associated with this review, if one exists. + PaymentIntent *PaymentIntent `json:"payment_intent"` + // The reason the review is currently open or closed. One of `rule`, `manual`, `approved`, `refunded`, `refunded_as_fraud`, `disputed`, `redacted`, or `canceled`. + Reason ReviewReason `json:"reason"` + // Information related to the browsing session of the user who initiated the payment. + Session *ReviewSession `json:"session"` +} + +// ReviewList is a list of Reviews as retrieved from a list endpoint. +type ReviewList struct { + APIResource + ListMeta + Data []*Review `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Review. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (r *Review) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + r.ID = id + return nil + } + + type review Review + var v review + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *r = Review(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/review_service.go b/vendor/github.com/stripe/stripe-go/v82/review_service.go new file mode 100644 index 00000000..1250d654 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/review_service.go @@ -0,0 +1,61 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1ReviewService is used to invoke /v1/reviews APIs. +type v1ReviewService struct { + B Backend + Key string +} + +// Retrieves a Review object. +func (c v1ReviewService) Retrieve(ctx context.Context, id string, params *ReviewRetrieveParams) (*Review, error) { + if params == nil { + params = &ReviewRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/reviews/%s", id) + review := &Review{} + err := c.B.Call(http.MethodGet, path, c.Key, params, review) + return review, err +} + +// Approves a Review object, closing it and removing it from the list of reviews. +func (c v1ReviewService) Approve(ctx context.Context, id string, params *ReviewApproveParams) (*Review, error) { + if params == nil { + params = &ReviewApproveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/reviews/%s/approve", id) + review := &Review{} + err := c.B.Call(http.MethodPost, path, c.Key, params, review) + return review, err +} + +// Returns a list of Review objects that have open set to true. The objects are sorted in descending order by creation date, with the most recently created object appearing first. +func (c v1ReviewService) List(ctx context.Context, listParams *ReviewListParams) Seq2[*Review, error] { + if listParams == nil { + listParams = &ReviewListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Review, ListContainer, error) { + list := &ReviewList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/reviews", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/search_iter.go b/vendor/github.com/stripe/stripe-go/v82/search_iter.go new file mode 100644 index 00000000..2c883a58 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/search_iter.go @@ -0,0 +1,224 @@ +package stripe + +import ( + "reflect" + + "github.com/stripe/stripe-go/v82/form" +) + +// +// Public constants +// + +// Contains constants for the names of parameters used for pagination in search APIs. +const ( + Page = "page" +) + +// +// Public types +// + +// SearchIter provides a convenient interface +// for iterating over the elements +// returned from paginated search API calls. +// Successive calls to the Next method +// will step through each item in the search results, +// fetching pages of items as needed. +// Iterators are not thread-safe, so they should not be consumed +// across multiple goroutines. +type SearchIter struct { + cur interface{} + err error + formValues *form.Values + searchContainer SearchContainer + searchParams SearchParams + meta *SearchMeta + query SearchQuery + values []interface{} +} + +// Current returns the most recent item +// visited by a call to Next. +func (it *SearchIter) Current() interface{} { + return it.cur +} + +// Err returns the error, if any, +// that caused the SearchIter to stop. +// It must be inspected +// after Next returns false. +func (it *SearchIter) Err() error { + return it.err +} + +// SearchResult returns the current search result container which the iterator is currently using. +// Objects will change as new API calls are made to continue pagination. +func (it *SearchIter) SearchResult() SearchContainer { + return it.searchContainer +} + +// Meta returns the search metadata. +func (it *SearchIter) Meta() *SearchMeta { + return it.meta +} + +// Next advances the SearchIter to the next item in the search results, +// which will then be available +// through the Current method. +// It returns false when the iterator stops +// at the end of the search results. +func (it *SearchIter) Next() bool { + if len(it.values) == 0 && it.meta.HasMore && !it.searchParams.Single { + if it.meta.NextPage != nil { + it.formValues.Set(Page, *it.meta.NextPage) + it.getPage() + } + } + if len(it.values) == 0 { + return false + } + it.cur = it.values[0] + it.values = it.values[1:] + return true +} + +func (it *SearchIter) getPage() { + it.values, it.searchContainer, it.err = it.query(it.searchParams.GetParams(), it.formValues) + it.meta = it.searchContainer.GetSearchMeta() +} + +// SearchQuery is the function used to get search results. +type SearchQuery func(*Params, *form.Values) ([]interface{}, SearchContainer, error) + +// +// Public functions +// + +// GetSearchIter returns a new SearchIter for a given query and its options. +func GetSearchIter(container SearchParamsContainer, query SearchQuery) *SearchIter { + var searchParams *SearchParams + formValues := &form.Values{} + + if container != nil { + reflectValue := reflect.ValueOf(container) + + // See the comment on Call in stripe.go. + if reflectValue.Kind() == reflect.Ptr && !reflectValue.IsNil() { + searchParams = container.GetSearchParams() + form.AppendTo(formValues, container) + } + } + + if searchParams == nil { + searchParams = &SearchParams{} + } + iter := &SearchIter{ + formValues: formValues, + searchParams: *searchParams, + query: query, + } + + iter.getPage() + + return iter +} + +// v1SearchList provides a convenient interface for iterating over the elements +// returned from paginated list API calls. It is meant to be an improvement +// over the SearchIter type, which was written before Go introduced generics and iter.Seq2. +// Calling the `All` allows you to iterate over all items in the list, +// with automatic pagination. +type v1SearchList[T any] struct { + cur *T + err error + formValues *form.Values + searchContainer SearchContainer + searchParams SearchParams + meta *SearchMeta + query v1SearchQuery[T] + values []*T +} + +func (it *v1SearchList[T]) All() Seq2[*T, error] { + return func(yield func(*T, error) bool) { + for it.next() { + if !yield(it.cur, nil) { + return + } + } + if it.err != nil { + if !yield(nil, it.err) { + return + } + } + } +} + +// next advances the v1SearchList to the next item in the list, +// which will then be available +// through the current method. +// It returns false when the iterator stops +// at the end of the list. +func (it *v1SearchList[T]) next() bool { + // Refresh the page if there is an more data to fetch + if len(it.values) == 0 && it.meta.HasMore && !it.searchParams.Single && it.meta.NextPage != nil { + it.formValues.Set(Page, *it.meta.NextPage) + it.getPage() + } + // If there was no new data after fetching, return false + if len(it.values) == 0 { + return false + } + it.cur = it.values[0] + it.values = it.values[1:] + return true +} + +func (it *v1SearchList[T]) getPage() { + it.values, it.searchContainer, it.err = it.query(it.searchParams.GetParams(), it.formValues) + it.meta = it.searchContainer.GetSearchMeta() +} + +// SearchQuery is the function used to get search results. +type v1SearchQuery[T any] func(*Params, *form.Values) ([]*T, SearchContainer, error) + +// +// Public functions +// + +// GetSearchIter returns a new SearchIter for a given query and its options. +func newV1SearchList[T any](container SearchParamsContainer, query v1SearchQuery[T]) *v1SearchList[T] { + var searchParams *SearchParams + formValues := &form.Values{} + + if container != nil { + reflectValue := reflect.ValueOf(container) + + // This is a little unfortunate, but Go makes it impossible to compare + // an interface value to nil without the use of the reflect package and + // its true disciples insist that this is a feature and not a bug. + // + // Here we do invoke reflect because (1) we have to reflect anyway to + // use encode with the form package, and (2) the corresponding removal + // of boilerplate that this enables makes the small performance penalty + // worth it. + if reflectValue.Kind() == reflect.Ptr && !reflectValue.IsNil() { + searchParams = container.GetSearchParams() + form.AppendTo(formValues, container) + } + } + + if searchParams == nil { + searchParams = &SearchParams{} + } + iter := &v1SearchList[T]{ + formValues: formValues, + searchParams: *searchParams, + query: query, + } + + iter.getPage() + + return iter +} diff --git a/vendor/github.com/stripe/stripe-go/v82/search_params.go b/vendor/github.com/stripe/stripe-go/v82/search_params.go new file mode 100644 index 00000000..0d958616 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/search_params.go @@ -0,0 +1,109 @@ +package stripe + +import ( + "context" +) + +// +// Public types +// + +// SearchContainer is a general interface for which all search result object structs +// should comply. They achieve this by embedding a SearchMeta struct and +// inheriting its implementation of this interface. +type SearchContainer interface { + GetSearchMeta() *SearchMeta +} + +// SearchMeta is the structure that contains the common properties of the search iterators +type SearchMeta struct { + HasMore bool `json:"has_more"` + NextPage *string `json:"next_page"` + URL string `json:"url"` + // TotalCount is the total number of objects in the search result (beyond just + // on the current page). + // The value is returned only when `total_count` is specified in `expand` parameter. + TotalCount *uint32 `json:"total_count"` +} + +// GetSearchMeta returns a SearchMeta struct (itself). It exists because any +// structs that embed SearchMeta will inherit it, and thus implement the +// SearchContainer interface. +func (l *SearchMeta) GetSearchMeta() *SearchMeta { + return l +} + +// SearchParams is the structure that contains the common properties +// of any *SearchParams structure. +type SearchParams struct { + // Context used for request. It may carry deadlines, cancelation signals, + // and other request-scoped values across API boundaries and between + // processes. + // + // Note that a cancelled or timed out context does not provide any + // guarantee whether the operation was or was not completed on Stripe's API + // servers. For certainty, you must either retry with the same idempotency + // key or query the state of the API. + Context context.Context `form:"-"` + + Query string `form:"query"` + Limit *int64 `form:"limit"` + Page *string `form:"page"` + // Deprecated: Please use Expand in the surrounding struct instead. + Expand []*string `form:"expand"` + + // Single specifies whether this is a single page iterator. By default, + // listing through an iterator will automatically grab additional pages as + // the query progresses. To change this behavior and just load a single + // page, set this to true. + Single bool `form:"-"` // Not an API parameter + + // StripeAccount may contain the ID of a connected account. By including + // this field, the request is made as if it originated from the connected + // account instead of under the account of the owner of the configured + // Stripe key. + StripeAccount *string `form:"-"` // Passed as header +} + +// AddExpand on the embedded SearchParams struct is deprecated +// Deprecated: please use .AddExpand of the surrounding struct instead. +func (p *SearchParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// GetSearchParams returns a SearchParams struct (itself). It exists because any +// structs that embed SearchParams will inherit it, and thus implement the +// SearchParamsContainer interface. +func (p *SearchParams) GetSearchParams() *SearchParams { + return p +} + +// GetParams returns SearchParams as a Params struct. It exists because any +// structs that embed Params will inherit it, and thus implement the +// ParamsContainer interface. +func (p *SearchParams) GetParams() *Params { + return p.ToParams() +} + +// SetStripeAccount sets a value for the Stripe-Account header. +func (p *SearchParams) SetStripeAccount(val string) { + p.StripeAccount = &val +} + +// ToParams converts a SearchParams to a Params by moving over any fields that +// have valid targets in the new type. This is useful because fields in +// Params can be injected directly into an http.Request while generally +// SearchParams is only used to build a set of parameters. +func (p *SearchParams) ToParams() *Params { + return &Params{ + Context: p.Context, + StripeAccount: p.StripeAccount, + } +} + +// SearchParamsContainer is a general interface for which all search parameter +// structs should comply. They achieve this by embedding a SearchParams struct +// and inheriting its implementation of this interface. +type SearchParamsContainer interface { + GetSearchParams() *SearchParams +} diff --git a/vendor/github.com/stripe/stripe-go/v82/setupattempt.go b/vendor/github.com/stripe/stripe-go/v82/setupattempt.go new file mode 100644 index 00000000..fdda302e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/setupattempt.go @@ -0,0 +1,395 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Indicates the directions of money movement for which this payment method is intended to be used. +// +// Include `inbound` if you intend to use the payment method as the origin to pull funds from. Include `outbound` if you intend to use the payment method as the destination to send funds to. You can include both if you intend to use the payment method for both purposes. +type SetupAttemptFlowDirection string + +// List of values that SetupAttemptFlowDirection can take +const ( + SetupAttemptFlowDirectionInbound SetupAttemptFlowDirection = "inbound" + SetupAttemptFlowDirectionOutbound SetupAttemptFlowDirection = "outbound" +) + +// For authenticated transactions: how the customer was authenticated by +// the issuing bank. +type SetupAttemptPaymentMethodDetailsCardThreeDSecureAuthenticationFlow string + +// List of values that SetupAttemptPaymentMethodDetailsCardThreeDSecureAuthenticationFlow can take +const ( + SetupAttemptPaymentMethodDetailsCardThreeDSecureAuthenticationFlowChallenge SetupAttemptPaymentMethodDetailsCardThreeDSecureAuthenticationFlow = "challenge" + SetupAttemptPaymentMethodDetailsCardThreeDSecureAuthenticationFlowFrictionless SetupAttemptPaymentMethodDetailsCardThreeDSecureAuthenticationFlow = "frictionless" +) + +// The Electronic Commerce Indicator (ECI). A protocol-level field +// indicating what degree of authentication was performed. +type SetupAttemptPaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator string + +// List of values that SetupAttemptPaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator can take +const ( + SetupAttemptPaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator01 SetupAttemptPaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator = "01" + SetupAttemptPaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator02 SetupAttemptPaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator = "02" + SetupAttemptPaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator05 SetupAttemptPaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator = "05" + SetupAttemptPaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator06 SetupAttemptPaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator = "06" + SetupAttemptPaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator07 SetupAttemptPaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator = "07" +) + +// Indicates the outcome of 3D Secure authentication. +type SetupAttemptPaymentMethodDetailsCardThreeDSecureResult string + +// List of values that SetupAttemptPaymentMethodDetailsCardThreeDSecureResult can take +const ( + SetupAttemptPaymentMethodDetailsCardThreeDSecureResultAttemptAcknowledged SetupAttemptPaymentMethodDetailsCardThreeDSecureResult = "attempt_acknowledged" + SetupAttemptPaymentMethodDetailsCardThreeDSecureResultAuthenticated SetupAttemptPaymentMethodDetailsCardThreeDSecureResult = "authenticated" + SetupAttemptPaymentMethodDetailsCardThreeDSecureResultExempted SetupAttemptPaymentMethodDetailsCardThreeDSecureResult = "exempted" + SetupAttemptPaymentMethodDetailsCardThreeDSecureResultFailed SetupAttemptPaymentMethodDetailsCardThreeDSecureResult = "failed" + SetupAttemptPaymentMethodDetailsCardThreeDSecureResultNotSupported SetupAttemptPaymentMethodDetailsCardThreeDSecureResult = "not_supported" + SetupAttemptPaymentMethodDetailsCardThreeDSecureResultProcessingError SetupAttemptPaymentMethodDetailsCardThreeDSecureResult = "processing_error" +) + +// Additional information about why 3D Secure succeeded or failed based +// on the `result`. +type SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReason string + +// List of values that SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReason can take +const ( + SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReasonAbandoned SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReason = "abandoned" + SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReasonBypassed SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReason = "bypassed" + SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReasonCanceled SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReason = "canceled" + SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReasonCardNotEnrolled SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReason = "card_not_enrolled" + SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReasonNetworkNotSupported SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReason = "network_not_supported" + SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReasonProtocolError SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReason = "protocol_error" + SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReasonRejected SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReason = "rejected" +) + +// The type of the card wallet, one of `apple_pay`, `google_pay`, or `link`. An additional hash is included on the Wallet subhash with a name matching this value. It contains additional information specific to the card wallet type. +type SetupAttemptPaymentMethodDetailsCardWalletType string + +// List of values that SetupAttemptPaymentMethodDetailsCardWalletType can take +const ( + SetupAttemptPaymentMethodDetailsCardWalletTypeApplePay SetupAttemptPaymentMethodDetailsCardWalletType = "apple_pay" + SetupAttemptPaymentMethodDetailsCardWalletTypeGooglePay SetupAttemptPaymentMethodDetailsCardWalletType = "google_pay" + SetupAttemptPaymentMethodDetailsCardWalletTypeLink SetupAttemptPaymentMethodDetailsCardWalletType = "link" +) + +// The method used to process this payment method offline. Only deferred is allowed. +type SetupAttemptPaymentMethodDetailsCardPresentOfflineType string + +// List of values that SetupAttemptPaymentMethodDetailsCardPresentOfflineType can take +const ( + SetupAttemptPaymentMethodDetailsCardPresentOfflineTypeDeferred SetupAttemptPaymentMethodDetailsCardPresentOfflineType = "deferred" +) + +// The type of the payment method used in the SetupIntent (e.g., `card`). An additional hash is included on `payment_method_details` with a name matching this value. It contains confirmation-specific information for the payment method. +type SetupAttemptPaymentMethodDetailsType string + +// List of values that SetupAttemptPaymentMethodDetailsType can take +const ( + SetupAttemptPaymentMethodDetailsTypeCard SetupAttemptPaymentMethodDetailsType = "card" +) + +// Status of this SetupAttempt, one of `requires_confirmation`, `requires_action`, `processing`, `succeeded`, `failed`, or `abandoned`. +type SetupAttemptStatus string + +// List of values that SetupAttemptStatus can take +const ( + SetupAttemptStatusAbandoned SetupAttemptStatus = "abandoned" + SetupAttemptStatusFailed SetupAttemptStatus = "failed" + SetupAttemptStatusProcessing SetupAttemptStatus = "processing" + SetupAttemptStatusRequiresAction SetupAttemptStatus = "requires_action" + SetupAttemptStatusRequiresConfirmation SetupAttemptStatus = "requires_confirmation" + SetupAttemptStatusSucceeded SetupAttemptStatus = "succeeded" +) + +// The value of [usage](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-usage) on the SetupIntent at the time of this confirmation, one of `off_session` or `on_session`. +type SetupAttemptUsage string + +// List of values that SetupAttemptUsage can take +const ( + SetupAttemptUsageOffSession SetupAttemptUsage = "off_session" + SetupAttemptUsageOnSession SetupAttemptUsage = "on_session" +) + +// Returns a list of SetupAttempts that associate with a provided SetupIntent. +type SetupAttemptListParams struct { + ListParams `form:"*"` + // A filter on the list, based on the object `created` field. The value + // can be a string with an integer Unix timestamp or a + // dictionary with a number of different query options. + Created *int64 `form:"created"` + // A filter on the list, based on the object `created` field. The value + // can be a string with an integer Unix timestamp or a + // dictionary with a number of different query options. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return SetupAttempts created by the SetupIntent specified by + // this ID. + SetupIntent *string `form:"setup_intent"` +} + +// AddExpand appends a new field to expand. +func (p *SetupAttemptListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type SetupAttemptPaymentMethodDetailsACSSDebit struct{} +type SetupAttemptPaymentMethodDetailsAmazonPay struct{} +type SetupAttemptPaymentMethodDetailsAUBECSDebit struct{} +type SetupAttemptPaymentMethodDetailsBACSDebit struct{} +type SetupAttemptPaymentMethodDetailsBancontact struct { + // Bank code of bank associated with the bank account. + BankCode string `json:"bank_code"` + // Name of the bank associated with the bank account. + BankName string `json:"bank_name"` + // Bank Identifier Code of the bank associated with the bank account. + BIC string `json:"bic"` + // The ID of the SEPA Direct Debit PaymentMethod which was generated by this SetupAttempt. + GeneratedSEPADebit *PaymentMethod `json:"generated_sepa_debit"` + // The mandate for the SEPA Direct Debit PaymentMethod which was generated by this SetupAttempt. + GeneratedSEPADebitMandate *Mandate `json:"generated_sepa_debit_mandate"` + // Last four characters of the IBAN. + IBANLast4 string `json:"iban_last4"` + // Preferred language of the Bancontact authorization page that the customer is redirected to. + // Can be one of `en`, `de`, `fr`, or `nl` + PreferredLanguage string `json:"preferred_language"` + // Owner's verified full name. Values are verified or provided by Bancontact directly + // (if supported) at the time of authorization or settlement. They cannot be set or mutated. + VerifiedName string `json:"verified_name"` +} +type SetupAttemptPaymentMethodDetailsBoleto struct{} + +// Check results by Card networks on Card address and CVC at the time of authorization +type SetupAttemptPaymentMethodDetailsCardChecks struct { + // If a address line1 was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + AddressLine1Check string `json:"address_line1_check"` + // If a address postal code was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + AddressPostalCodeCheck string `json:"address_postal_code_check"` + // If a CVC was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + CVCCheck string `json:"cvc_check"` +} + +// Populated if this authorization used 3D Secure authentication. +type SetupAttemptPaymentMethodDetailsCardThreeDSecure struct { + // For authenticated transactions: how the customer was authenticated by + // the issuing bank. + AuthenticationFlow SetupAttemptPaymentMethodDetailsCardThreeDSecureAuthenticationFlow `json:"authentication_flow"` + // The Electronic Commerce Indicator (ECI). A protocol-level field + // indicating what degree of authentication was performed. + ElectronicCommerceIndicator SetupAttemptPaymentMethodDetailsCardThreeDSecureElectronicCommerceIndicator `json:"electronic_commerce_indicator"` + // Indicates the outcome of 3D Secure authentication. + Result SetupAttemptPaymentMethodDetailsCardThreeDSecureResult `json:"result"` + // Additional information about why 3D Secure succeeded or failed based + // on the `result`. + ResultReason SetupAttemptPaymentMethodDetailsCardThreeDSecureResultReason `json:"result_reason"` + // The 3D Secure 1 XID or 3D Secure 2 Directory Server Transaction ID + // (dsTransId) for this payment. + TransactionID string `json:"transaction_id"` + // The version of 3D Secure that was used. + Version string `json:"version"` +} +type SetupAttemptPaymentMethodDetailsCardWalletApplePay struct{} +type SetupAttemptPaymentMethodDetailsCardWalletGooglePay struct{} + +// If this Card is part of a card wallet, this contains the details of the card wallet. +type SetupAttemptPaymentMethodDetailsCardWallet struct { + ApplePay *SetupAttemptPaymentMethodDetailsCardWalletApplePay `json:"apple_pay"` + GooglePay *SetupAttemptPaymentMethodDetailsCardWalletGooglePay `json:"google_pay"` + // The type of the card wallet, one of `apple_pay`, `google_pay`, or `link`. An additional hash is included on the Wallet subhash with a name matching this value. It contains additional information specific to the card wallet type. + Type SetupAttemptPaymentMethodDetailsCardWalletType `json:"type"` +} +type SetupAttemptPaymentMethodDetailsCard struct { + // Card brand. Can be `amex`, `diners`, `discover`, `eftpos_au`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Brand string `json:"brand"` + // Check results by Card networks on Card address and CVC at the time of authorization + Checks *SetupAttemptPaymentMethodDetailsCardChecks `json:"checks"` + // Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you've collected. + Country string `json:"country"` + // A high-level description of the type of cards issued in this range. (For internal use only and not typically available in standard API requests.) + Description string `json:"description"` + // Two-digit number representing the card's expiration month. + ExpMonth int64 `json:"exp_month"` + // Four-digit number representing the card's expiration year. + ExpYear int64 `json:"exp_year"` + // Uniquely identifies this particular card number. You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + // + // *As of May 1, 2021, card fingerprint in India for Connect changed to allow two fingerprints for the same card---one for India and one for the rest of the world.* + Fingerprint string `json:"fingerprint"` + // Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + Funding string `json:"funding"` + // Issuer identification number of the card. (For internal use only and not typically available in standard API requests.) + IIN string `json:"iin"` + // The name of the card's issuing bank. (For internal use only and not typically available in standard API requests.) + Issuer string `json:"issuer"` + // The last four digits of the card. + Last4 string `json:"last4"` + // Identifies which network this charge was processed on. Can be `amex`, `cartes_bancaires`, `diners`, `discover`, `eftpos_au`, `interac`, `jcb`, `link`, `mastercard`, `unionpay`, `visa`, or `unknown`. + Network string `json:"network"` + // Populated if this authorization used 3D Secure authentication. + ThreeDSecure *SetupAttemptPaymentMethodDetailsCardThreeDSecure `json:"three_d_secure"` + // If this Card is part of a card wallet, this contains the details of the card wallet. + Wallet *SetupAttemptPaymentMethodDetailsCardWallet `json:"wallet"` +} + +// Details about payments collected offline. +type SetupAttemptPaymentMethodDetailsCardPresentOffline struct { + // Time at which the payment was collected while offline + StoredAt int64 `json:"stored_at"` + // The method used to process this payment method offline. Only deferred is allowed. + Type SetupAttemptPaymentMethodDetailsCardPresentOfflineType `json:"type"` +} +type SetupAttemptPaymentMethodDetailsCardPresent struct { + // The ID of the Card PaymentMethod which was generated by this SetupAttempt. + GeneratedCard *PaymentMethod `json:"generated_card"` + // Details about payments collected offline. + Offline *SetupAttemptPaymentMethodDetailsCardPresentOffline `json:"offline"` +} +type SetupAttemptPaymentMethodDetailsCashApp struct{} +type SetupAttemptPaymentMethodDetailsIDEAL struct { + // The customer's bank. Can be one of `abn_amro`, `asn_bank`, `bunq`, `buut`, `handelsbanken`, `ing`, `knab`, `moneyou`, `n26`, `nn`, `rabobank`, `regiobank`, `revolut`, `sns_bank`, `triodos_bank`, `van_lanschot`, or `yoursafe`. + Bank string `json:"bank"` + // The Bank Identifier Code of the customer's bank. + BIC string `json:"bic"` + // The ID of the SEPA Direct Debit PaymentMethod which was generated by this SetupAttempt. + GeneratedSEPADebit *PaymentMethod `json:"generated_sepa_debit"` + // The mandate for the SEPA Direct Debit PaymentMethod which was generated by this SetupAttempt. + GeneratedSEPADebitMandate *Mandate `json:"generated_sepa_debit_mandate"` + // Last four characters of the IBAN. + IBANLast4 string `json:"iban_last4"` + // Owner's verified full name. Values are verified or provided by iDEAL directly + // (if supported) at the time of authorization or settlement. They cannot be set or mutated. + VerifiedName string `json:"verified_name"` +} +type SetupAttemptPaymentMethodDetailsKakaoPay struct{} +type SetupAttemptPaymentMethodDetailsKlarna struct{} +type SetupAttemptPaymentMethodDetailsKrCard struct{} +type SetupAttemptPaymentMethodDetailsLink struct{} +type SetupAttemptPaymentMethodDetailsNaverPay struct { + // Uniquely identifies this particular Naver Pay account. You can use this attribute to check whether two Naver Pay accounts are the same. + BuyerID string `json:"buyer_id"` +} +type SetupAttemptPaymentMethodDetailsNzBankAccount struct{} +type SetupAttemptPaymentMethodDetailsPaypal struct{} +type SetupAttemptPaymentMethodDetailsRevolutPay struct{} +type SetupAttemptPaymentMethodDetailsSEPADebit struct{} +type SetupAttemptPaymentMethodDetailsSofort struct { + // Bank code of bank associated with the bank account. + BankCode string `json:"bank_code"` + // Name of the bank associated with the bank account. + BankName string `json:"bank_name"` + // Bank Identifier Code of the bank associated with the bank account. + BIC string `json:"bic"` + // The ID of the SEPA Direct Debit PaymentMethod which was generated by this SetupAttempt. + GeneratedSEPADebit *PaymentMethod `json:"generated_sepa_debit"` + // The mandate for the SEPA Direct Debit PaymentMethod which was generated by this SetupAttempt. + GeneratedSEPADebitMandate *Mandate `json:"generated_sepa_debit_mandate"` + // Last four characters of the IBAN. + IBANLast4 string `json:"iban_last4"` + // Preferred language of the Sofort authorization page that the customer is redirected to. + // Can be one of `en`, `de`, `fr`, or `nl` + PreferredLanguage string `json:"preferred_language"` + // Owner's verified full name. Values are verified or provided by Sofort directly + // (if supported) at the time of authorization or settlement. They cannot be set or mutated. + VerifiedName string `json:"verified_name"` +} +type SetupAttemptPaymentMethodDetailsUSBankAccount struct{} +type SetupAttemptPaymentMethodDetails struct { + ACSSDebit *SetupAttemptPaymentMethodDetailsACSSDebit `json:"acss_debit"` + AmazonPay *SetupAttemptPaymentMethodDetailsAmazonPay `json:"amazon_pay"` + AUBECSDebit *SetupAttemptPaymentMethodDetailsAUBECSDebit `json:"au_becs_debit"` + BACSDebit *SetupAttemptPaymentMethodDetailsBACSDebit `json:"bacs_debit"` + Bancontact *SetupAttemptPaymentMethodDetailsBancontact `json:"bancontact"` + Boleto *SetupAttemptPaymentMethodDetailsBoleto `json:"boleto"` + Card *SetupAttemptPaymentMethodDetailsCard `json:"card"` + CardPresent *SetupAttemptPaymentMethodDetailsCardPresent `json:"card_present"` + CashApp *SetupAttemptPaymentMethodDetailsCashApp `json:"cashapp"` + IDEAL *SetupAttemptPaymentMethodDetailsIDEAL `json:"ideal"` + KakaoPay *SetupAttemptPaymentMethodDetailsKakaoPay `json:"kakao_pay"` + Klarna *SetupAttemptPaymentMethodDetailsKlarna `json:"klarna"` + KrCard *SetupAttemptPaymentMethodDetailsKrCard `json:"kr_card"` + Link *SetupAttemptPaymentMethodDetailsLink `json:"link"` + NaverPay *SetupAttemptPaymentMethodDetailsNaverPay `json:"naver_pay"` + NzBankAccount *SetupAttemptPaymentMethodDetailsNzBankAccount `json:"nz_bank_account"` + Paypal *SetupAttemptPaymentMethodDetailsPaypal `json:"paypal"` + RevolutPay *SetupAttemptPaymentMethodDetailsRevolutPay `json:"revolut_pay"` + SEPADebit *SetupAttemptPaymentMethodDetailsSEPADebit `json:"sepa_debit"` + Sofort *SetupAttemptPaymentMethodDetailsSofort `json:"sofort"` + // The type of the payment method used in the SetupIntent (e.g., `card`). An additional hash is included on `payment_method_details` with a name matching this value. It contains confirmation-specific information for the payment method. + Type SetupAttemptPaymentMethodDetailsType `json:"type"` + USBankAccount *SetupAttemptPaymentMethodDetailsUSBankAccount `json:"us_bank_account"` +} + +// A SetupAttempt describes one attempted confirmation of a SetupIntent, +// whether that confirmation is successful or unsuccessful. You can use +// SetupAttempts to inspect details of a specific attempt at setting up a +// payment method using a SetupIntent. +type SetupAttempt struct { + APIResource + // The value of [application](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-application) on the SetupIntent at the time of this confirmation. + Application *Application `json:"application"` + // If present, the SetupIntent's payment method will be attached to the in-context Stripe Account. + // + // It can only be used for this Stripe Account's own money movement flows like InboundTransfer and OutboundTransfers. It cannot be set to true when setting up a PaymentMethod for a Customer, and defaults to false when attaching a PaymentMethod to a Customer. + AttachToSelf bool `json:"attach_to_self"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The value of [customer](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-customer) on the SetupIntent at the time of this confirmation. + Customer *Customer `json:"customer"` + // Indicates the directions of money movement for which this payment method is intended to be used. + // + // Include `inbound` if you intend to use the payment method as the origin to pull funds from. Include `outbound` if you intend to use the payment method as the destination to send funds to. You can include both if you intend to use the payment method for both purposes. + FlowDirections []SetupAttemptFlowDirection `json:"flow_directions"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The value of [on_behalf_of](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-on_behalf_of) on the SetupIntent at the time of this confirmation. + OnBehalfOf *Account `json:"on_behalf_of"` + // ID of the payment method used with this SetupAttempt. + PaymentMethod *PaymentMethod `json:"payment_method"` + PaymentMethodDetails *SetupAttemptPaymentMethodDetails `json:"payment_method_details"` + // The error encountered during this attempt to confirm the SetupIntent, if any. + SetupError *Error `json:"setup_error"` + // ID of the SetupIntent that this attempt belongs to. + SetupIntent *SetupIntent `json:"setup_intent"` + // Status of this SetupAttempt, one of `requires_confirmation`, `requires_action`, `processing`, `succeeded`, `failed`, or `abandoned`. + Status SetupAttemptStatus `json:"status"` + // The value of [usage](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-usage) on the SetupIntent at the time of this confirmation, one of `off_session` or `on_session`. + Usage SetupAttemptUsage `json:"usage"` +} + +// SetupAttemptList is a list of SetupAttempts as retrieved from a list endpoint. +type SetupAttemptList struct { + APIResource + ListMeta + Data []*SetupAttempt `json:"data"` +} + +// UnmarshalJSON handles deserialization of a SetupAttempt. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (s *SetupAttempt) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + s.ID = id + return nil + } + + type setupAttempt SetupAttempt + var v setupAttempt + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *s = SetupAttempt(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/setupattempt_service.go b/vendor/github.com/stripe/stripe-go/v82/setupattempt_service.go new file mode 100644 index 00000000..247d6d1b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/setupattempt_service.go @@ -0,0 +1,37 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1SetupAttemptService is used to invoke /v1/setup_attempts APIs. +type v1SetupAttemptService struct { + B Backend + Key string +} + +// Returns a list of SetupAttempts that associate with a provided SetupIntent. +func (c v1SetupAttemptService) List(ctx context.Context, listParams *SetupAttemptListParams) Seq2[*SetupAttempt, error] { + if listParams == nil { + listParams = &SetupAttemptListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*SetupAttempt, ListContainer, error) { + list := &SetupAttemptList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/setup_attempts", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/setupintent.go b/vendor/github.com/stripe/stripe-go/v82/setupintent.go new file mode 100644 index 00000000..520807e1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/setupintent.go @@ -0,0 +1,3219 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Controls whether this SetupIntent will accept redirect-based payment methods. +// +// Redirect-based payment methods may require your customer to be redirected to a payment method's app or site for authentication or additional steps. To [confirm](https://stripe.com/docs/api/setup_intents/confirm) this SetupIntent, you may be required to provide a `return_url` to redirect customers back to your site after they authenticate or complete the setup. +type SetupIntentAutomaticPaymentMethodsAllowRedirects string + +// List of values that SetupIntentAutomaticPaymentMethodsAllowRedirects can take +const ( + SetupIntentAutomaticPaymentMethodsAllowRedirectsAlways SetupIntentAutomaticPaymentMethodsAllowRedirects = "always" + SetupIntentAutomaticPaymentMethodsAllowRedirectsNever SetupIntentAutomaticPaymentMethodsAllowRedirects = "never" +) + +// Reason for cancellation of this SetupIntent, one of `abandoned`, `requested_by_customer`, or `duplicate`. +type SetupIntentCancellationReason string + +// List of values that SetupIntentCancellationReason can take +const ( + SetupIntentCancellationReasonAbandoned SetupIntentCancellationReason = "abandoned" + SetupIntentCancellationReasonDuplicate SetupIntentCancellationReason = "duplicate" + SetupIntentCancellationReasonRequestedByCustomer SetupIntentCancellationReason = "requested_by_customer" +) + +// Indicates the directions of money movement for which this payment method is intended to be used. +// +// Include `inbound` if you intend to use the payment method as the origin to pull funds from. Include `outbound` if you intend to use the payment method as the destination to send funds to. You can include both if you intend to use the payment method for both purposes. +type SetupIntentFlowDirection string + +// List of values that SetupIntentFlowDirection can take +const ( + SetupIntentFlowDirectionInbound SetupIntentFlowDirection = "inbound" + SetupIntentFlowDirectionOutbound SetupIntentFlowDirection = "outbound" +) + +// Type of the next action to perform. Refer to the other child attributes under `next_action` for available values. Examples include: `redirect_to_url`, `use_stripe_sdk`, `alipay_handle_redirect`, `oxxo_display_details`, or `verify_with_microdeposits`. +type SetupIntentNextActionType string + +// List of values that SetupIntentNextActionType can take +const ( + SetupIntentNextActionTypeRedirectToURL SetupIntentNextActionType = "redirect_to_url" + SetupIntentNextActionTypeUseStripeSDK SetupIntentNextActionType = "use_stripe_sdk" + SetupIntentNextActionTypeAlipayHandleRedirect SetupIntentNextActionType = "alipay_handle_redirect" + SetupIntentNextActionTypeOXXODisplayDetails SetupIntentNextActionType = "oxxo_display_details" + SetupIntentNextActionTypeVerifyWithMicrodeposits SetupIntentNextActionType = "verify_with_microdeposits" +) + +// The type of the microdeposit sent to the customer. Used to distinguish between different verification methods. +type SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType string + +// List of values that SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType can take +const ( + SetupIntentNextActionVerifyWithMicrodepositsMicrodepositTypeAmounts SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType = "amounts" + SetupIntentNextActionVerifyWithMicrodepositsMicrodepositTypeDescriptorCode SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType = "descriptor_code" +) + +// Currency supported by the bank account +type SetupIntentPaymentMethodOptionsACSSDebitCurrency string + +// List of values that SetupIntentPaymentMethodOptionsACSSDebitCurrency can take +const ( + SetupIntentPaymentMethodOptionsACSSDebitCurrencyCAD SetupIntentPaymentMethodOptionsACSSDebitCurrency = "cad" + SetupIntentPaymentMethodOptionsACSSDebitCurrencyUSD SetupIntentPaymentMethodOptionsACSSDebitCurrency = "usd" +) + +// List of Stripe products where this mandate can be selected automatically. +type SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsDefaultFor string + +// List of values that SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsDefaultFor can take +const ( + SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsDefaultForInvoice SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsDefaultFor = "invoice" + SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsDefaultForSubscription SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsDefaultFor = "subscription" +) + +// Payment schedule for the mandate. +type SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule string + +// List of values that SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule can take +const ( + SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentScheduleCombined SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule = "combined" + SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentScheduleInterval SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule = "interval" + SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentScheduleSporadic SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule = "sporadic" +) + +// Transaction type of the mandate. +type SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsTransactionType string + +// List of values that SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsTransactionType can take +const ( + SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsTransactionTypeBusiness SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsTransactionType = "business" + SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsTransactionTypePersonal SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsTransactionType = "personal" +) + +// Bank account verification method. +type SetupIntentPaymentMethodOptionsACSSDebitVerificationMethod string + +// List of values that SetupIntentPaymentMethodOptionsACSSDebitVerificationMethod can take +const ( + SetupIntentPaymentMethodOptionsACSSDebitVerificationMethodAutomatic SetupIntentPaymentMethodOptionsACSSDebitVerificationMethod = "automatic" + SetupIntentPaymentMethodOptionsACSSDebitVerificationMethodInstant SetupIntentPaymentMethodOptionsACSSDebitVerificationMethod = "instant" + SetupIntentPaymentMethodOptionsACSSDebitVerificationMethodMicrodeposits SetupIntentPaymentMethodOptionsACSSDebitVerificationMethod = "microdeposits" +) + +// One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. +type SetupIntentPaymentMethodOptionsCardMandateOptionsAmountType string + +// List of values that SetupIntentPaymentMethodOptionsCardMandateOptionsAmountType can take +const ( + SetupIntentPaymentMethodOptionsCardMandateOptionsAmountTypeFixed SetupIntentPaymentMethodOptionsCardMandateOptionsAmountType = "fixed" + SetupIntentPaymentMethodOptionsCardMandateOptionsAmountTypeMaximum SetupIntentPaymentMethodOptionsCardMandateOptionsAmountType = "maximum" +) + +// Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. +type SetupIntentPaymentMethodOptionsCardMandateOptionsInterval string + +// List of values that SetupIntentPaymentMethodOptionsCardMandateOptionsInterval can take +const ( + SetupIntentPaymentMethodOptionsCardMandateOptionsIntervalDay SetupIntentPaymentMethodOptionsCardMandateOptionsInterval = "day" + SetupIntentPaymentMethodOptionsCardMandateOptionsIntervalMonth SetupIntentPaymentMethodOptionsCardMandateOptionsInterval = "month" + SetupIntentPaymentMethodOptionsCardMandateOptionsIntervalSporadic SetupIntentPaymentMethodOptionsCardMandateOptionsInterval = "sporadic" + SetupIntentPaymentMethodOptionsCardMandateOptionsIntervalWeek SetupIntentPaymentMethodOptionsCardMandateOptionsInterval = "week" + SetupIntentPaymentMethodOptionsCardMandateOptionsIntervalYear SetupIntentPaymentMethodOptionsCardMandateOptionsInterval = "year" +) + +// Specifies the type of mandates supported. Possible values are `india`. +type SetupIntentPaymentMethodOptionsCardMandateOptionsSupportedType string + +// List of values that SetupIntentPaymentMethodOptionsCardMandateOptionsSupportedType can take +const ( + SetupIntentPaymentMethodOptionsCardMandateOptionsSupportedTypeIndia SetupIntentPaymentMethodOptionsCardMandateOptionsSupportedType = "india" +) + +// Selected network to process this SetupIntent on. Depends on the available networks of the card attached to the setup intent. Can be only set confirm-time. +type SetupIntentPaymentMethodOptionsCardNetwork string + +// List of values that SetupIntentPaymentMethodOptionsCardNetwork can take +const ( + SetupIntentPaymentMethodOptionsCardNetworkAmex SetupIntentPaymentMethodOptionsCardNetwork = "amex" + SetupIntentPaymentMethodOptionsCardNetworkCartesBancaires SetupIntentPaymentMethodOptionsCardNetwork = "cartes_bancaires" + SetupIntentPaymentMethodOptionsCardNetworkDiners SetupIntentPaymentMethodOptionsCardNetwork = "diners" + SetupIntentPaymentMethodOptionsCardNetworkDiscover SetupIntentPaymentMethodOptionsCardNetwork = "discover" + SetupIntentPaymentMethodOptionsCardNetworkEFTPOSAU SetupIntentPaymentMethodOptionsCardNetwork = "eftpos_au" + SetupIntentPaymentMethodOptionsCardNetworkGirocard SetupIntentPaymentMethodOptionsCardNetwork = "girocard" + SetupIntentPaymentMethodOptionsCardNetworkInterac SetupIntentPaymentMethodOptionsCardNetwork = "interac" + SetupIntentPaymentMethodOptionsCardNetworkJCB SetupIntentPaymentMethodOptionsCardNetwork = "jcb" + SetupIntentPaymentMethodOptionsCardNetworkLink SetupIntentPaymentMethodOptionsCardNetwork = "link" + SetupIntentPaymentMethodOptionsCardNetworkMastercard SetupIntentPaymentMethodOptionsCardNetwork = "mastercard" + SetupIntentPaymentMethodOptionsCardNetworkUnionpay SetupIntentPaymentMethodOptionsCardNetwork = "unionpay" + SetupIntentPaymentMethodOptionsCardNetworkUnknown SetupIntentPaymentMethodOptionsCardNetwork = "unknown" + SetupIntentPaymentMethodOptionsCardNetworkVisa SetupIntentPaymentMethodOptionsCardNetwork = "visa" +) + +// We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. +type SetupIntentPaymentMethodOptionsCardRequestThreeDSecure string + +// List of values that SetupIntentPaymentMethodOptionsCardRequestThreeDSecure can take +const ( + SetupIntentPaymentMethodOptionsCardRequestThreeDSecureAny SetupIntentPaymentMethodOptionsCardRequestThreeDSecure = "any" + SetupIntentPaymentMethodOptionsCardRequestThreeDSecureAutomatic SetupIntentPaymentMethodOptionsCardRequestThreeDSecure = "automatic" + SetupIntentPaymentMethodOptionsCardRequestThreeDSecureChallenge SetupIntentPaymentMethodOptionsCardRequestThreeDSecure = "challenge" +) + +// The account subcategories to use to filter for possible accounts to link. Valid subcategories are `checking` and `savings`. +type SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory string + +// List of values that SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory can take +const ( + SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategoryChecking SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory = "checking" + SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategorySavings SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory = "savings" +) + +// The list of permissions to request. The `payment_method` permission must be included. +type SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission string + +// List of values that SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission can take +const ( + SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionBalances SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "balances" + SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionOwnership SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "ownership" + SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionPaymentMethod SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "payment_method" + SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionTransactions SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "transactions" +) + +// Data features requested to be retrieved upon account creation. +type SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch string + +// List of values that SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch can take +const ( + SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchBalances SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "balances" + SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchOwnership SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "ownership" + SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchTransactions SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "transactions" +) + +// Mandate collection method +type SetupIntentPaymentMethodOptionsUSBankAccountMandateOptionsCollectionMethod string + +// List of values that SetupIntentPaymentMethodOptionsUSBankAccountMandateOptionsCollectionMethod can take +const ( + SetupIntentPaymentMethodOptionsUSBankAccountMandateOptionsCollectionMethodPaper SetupIntentPaymentMethodOptionsUSBankAccountMandateOptionsCollectionMethod = "paper" +) + +// Bank account verification method. +type SetupIntentPaymentMethodOptionsUSBankAccountVerificationMethod string + +// List of values that SetupIntentPaymentMethodOptionsUSBankAccountVerificationMethod can take +const ( + SetupIntentPaymentMethodOptionsUSBankAccountVerificationMethodAutomatic SetupIntentPaymentMethodOptionsUSBankAccountVerificationMethod = "automatic" + SetupIntentPaymentMethodOptionsUSBankAccountVerificationMethodInstant SetupIntentPaymentMethodOptionsUSBankAccountVerificationMethod = "instant" + SetupIntentPaymentMethodOptionsUSBankAccountVerificationMethodMicrodeposits SetupIntentPaymentMethodOptionsUSBankAccountVerificationMethod = "microdeposits" +) + +// [Status](https://stripe.com/docs/payments/intents#intent-statuses) of this SetupIntent, one of `requires_payment_method`, `requires_confirmation`, `requires_action`, `processing`, `canceled`, or `succeeded`. +type SetupIntentStatus string + +// List of values that SetupIntentStatus can take +const ( + SetupIntentStatusCanceled SetupIntentStatus = "canceled" + SetupIntentStatusProcessing SetupIntentStatus = "processing" + SetupIntentStatusRequiresAction SetupIntentStatus = "requires_action" + SetupIntentStatusRequiresConfirmation SetupIntentStatus = "requires_confirmation" + SetupIntentStatusRequiresPaymentMethod SetupIntentStatus = "requires_payment_method" + SetupIntentStatusSucceeded SetupIntentStatus = "succeeded" +) + +// Indicates how the payment method is intended to be used in the future. +// +// Use `on_session` if you intend to only reuse the payment method when the customer is in your checkout flow. Use `off_session` if your customer may or may not be in your checkout flow. If not provided, this value defaults to `off_session`. +type SetupIntentUsage string + +// List of values that SetupIntentUsage can take +const ( + SetupIntentUsageOffSession SetupIntentUsage = "off_session" + SetupIntentUsageOnSession SetupIntentUsage = "on_session" +) + +// Returns a list of SetupIntents. +type SetupIntentListParams struct { + ListParams `form:"*"` + // If present, the SetupIntent's payment method will be attached to the in-context Stripe Account. + // + // It can only be used for this Stripe Account's own money movement flows like InboundTransfer and OutboundTransfers. It cannot be set to true when setting up a PaymentMethod for a Customer, and defaults to false when attaching a PaymentMethod to a Customer. + AttachToSelf *bool `form:"attach_to_self"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + Created *int64 `form:"created"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + CreatedRange *RangeQueryParams `form:"created"` + // Only return SetupIntents for the customer specified by this customer ID. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return SetupIntents that associate with the specified payment method. + PaymentMethod *string `form:"payment_method"` +} + +// AddExpand appends a new field to expand. +func (p *SetupIntentListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When you enable this parameter, this SetupIntent accepts payment methods that you enable in the Dashboard and that are compatible with its other parameters. +type SetupIntentAutomaticPaymentMethodsParams struct { + // Controls whether this SetupIntent will accept redirect-based payment methods. + // + // Redirect-based payment methods may require your customer to be redirected to a payment method's app or site for authentication or additional steps. To [confirm](https://stripe.com/docs/api/setup_intents/confirm) this SetupIntent, you may be required to provide a `return_url` to redirect customers back to your site after they authenticate or complete the setup. + AllowRedirects *string `form:"allow_redirects"` + // Whether this feature is enabled. + Enabled *bool `form:"enabled"` +} + +// If this is a Mandate accepted offline, this hash contains details about the offline acceptance. +type SetupIntentMandateDataCustomerAcceptanceOfflineParams struct{} + +// If this is a Mandate accepted online, this hash contains details about the online acceptance. +type SetupIntentMandateDataCustomerAcceptanceOnlineParams struct { + // The IP address from which the Mandate was accepted by the customer. + IPAddress *string `form:"ip_address"` + // The user agent of the browser from which the Mandate was accepted by the customer. + UserAgent *string `form:"user_agent"` +} + +// This hash contains details about the customer acceptance of the Mandate. +type SetupIntentMandateDataCustomerAcceptanceParams struct { + // The time at which the customer accepted the Mandate. + AcceptedAt *int64 `form:"accepted_at"` + // If this is a Mandate accepted offline, this hash contains details about the offline acceptance. + Offline *SetupIntentMandateDataCustomerAcceptanceOfflineParams `form:"offline"` + // If this is a Mandate accepted online, this hash contains details about the online acceptance. + Online *SetupIntentMandateDataCustomerAcceptanceOnlineParams `form:"online"` + // The type of customer acceptance information included with the Mandate. One of `online` or `offline`. + Type MandateCustomerAcceptanceType `form:"type"` +} + +// This hash contains details about the mandate to create. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/setup_intents/create#create_setup_intent-confirm). +type SetupIntentMandateDataParams struct { + // This hash contains details about the customer acceptance of the Mandate. + CustomerAcceptance *SetupIntentMandateDataCustomerAcceptanceParams `form:"customer_acceptance"` +} + +// If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. +type SetupIntentPaymentMethodDataACSSDebitParams struct { + // Customer's bank account number. + AccountNumber *string `form:"account_number"` + // Institution number of the customer's bank. + InstitutionNumber *string `form:"institution_number"` + // Transit number of the customer's bank. + TransitNumber *string `form:"transit_number"` +} + +// If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. +type SetupIntentPaymentMethodDataAffirmParams struct{} + +// If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. +type SetupIntentPaymentMethodDataAfterpayClearpayParams struct{} + +// If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. +type SetupIntentPaymentMethodDataAlipayParams struct{} + +// If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. +type SetupIntentPaymentMethodDataAlmaParams struct{} + +// If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. +type SetupIntentPaymentMethodDataAmazonPayParams struct{} + +// If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. +type SetupIntentPaymentMethodDataAUBECSDebitParams struct { + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // Bank-State-Branch number of the bank account. + BSBNumber *string `form:"bsb_number"` +} + +// If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. +type SetupIntentPaymentMethodDataBACSDebitParams struct { + // Account number of the bank account that the funds will be debited from. + AccountNumber *string `form:"account_number"` + // Sort code of the bank account. (e.g., `10-20-30`) + SortCode *string `form:"sort_code"` +} + +// If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. +type SetupIntentPaymentMethodDataBancontactParams struct{} + +// If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. +type SetupIntentPaymentMethodDataBillieParams struct{} + +// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. +type SetupIntentPaymentMethodDataBillingDetailsParams struct { + // Billing address. + Address *AddressParams `form:"address"` + // Email address. + Email *string `form:"email"` + // Full name. + Name *string `form:"name"` + // Billing phone number (including extension). + Phone *string `form:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID *string `form:"tax_id"` +} + +// If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. +type SetupIntentPaymentMethodDataBLIKParams struct{} + +// If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. +type SetupIntentPaymentMethodDataBoletoParams struct { + // The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + TaxID *string `form:"tax_id"` +} + +// If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. +type SetupIntentPaymentMethodDataCashAppParams struct{} + +// If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. +type SetupIntentPaymentMethodDataCryptoParams struct{} + +// If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. +type SetupIntentPaymentMethodDataCustomerBalanceParams struct{} + +// If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. +type SetupIntentPaymentMethodDataEPSParams struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. +type SetupIntentPaymentMethodDataFPXParams struct { + // Account holder type for FPX transaction + AccountHolderType *string `form:"account_holder_type"` + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. +type SetupIntentPaymentMethodDataGiropayParams struct{} + +// If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. +type SetupIntentPaymentMethodDataGrabpayParams struct{} + +// If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. +type SetupIntentPaymentMethodDataIDEALParams struct { + // The customer's bank. Only use this parameter for existing customers. Don't use it for new customers. + Bank *string `form:"bank"` +} + +// If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. +type SetupIntentPaymentMethodDataInteracPresentParams struct{} + +// If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. +type SetupIntentPaymentMethodDataKakaoPayParams struct{} + +// Customer's date of birth +type SetupIntentPaymentMethodDataKlarnaDOBParams struct { + // The day of birth, between 1 and 31. + Day *int64 `form:"day"` + // The month of birth, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of birth. + Year *int64 `form:"year"` +} + +// If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. +type SetupIntentPaymentMethodDataKlarnaParams struct { + // Customer's date of birth + DOB *SetupIntentPaymentMethodDataKlarnaDOBParams `form:"dob"` +} + +// If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. +type SetupIntentPaymentMethodDataKonbiniParams struct{} + +// If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. +type SetupIntentPaymentMethodDataKrCardParams struct{} + +// If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. +type SetupIntentPaymentMethodDataLinkParams struct{} + +// If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. +type SetupIntentPaymentMethodDataMobilepayParams struct{} + +// If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. +type SetupIntentPaymentMethodDataMultibancoParams struct{} + +// If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. +type SetupIntentPaymentMethodDataNaverPayParams struct { + // Whether to use Naver Pay points or a card to fund this transaction. If not provided, this defaults to `card`. + Funding *string `form:"funding"` +} + +// If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. +type SetupIntentPaymentMethodDataNzBankAccountParams struct { + // The name on the bank account. Only required if the account holder name is different from the name of the authorized signatory collected in the PaymentMethod's billing details. + AccountHolderName *string `form:"account_holder_name"` + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // The numeric code for the bank account's bank. + BankCode *string `form:"bank_code"` + // The numeric code for the bank account's bank branch. + BranchCode *string `form:"branch_code"` + Reference *string `form:"reference"` + // The suffix of the bank account number. + Suffix *string `form:"suffix"` +} + +// If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. +type SetupIntentPaymentMethodDataOXXOParams struct{} + +// If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. +type SetupIntentPaymentMethodDataP24Params struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. +type SetupIntentPaymentMethodDataPayByBankParams struct{} + +// If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. +type SetupIntentPaymentMethodDataPaycoParams struct{} + +// If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. +type SetupIntentPaymentMethodDataPayNowParams struct{} + +// If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. +type SetupIntentPaymentMethodDataPaypalParams struct{} + +// If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. +type SetupIntentPaymentMethodDataPixParams struct{} + +// If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. +type SetupIntentPaymentMethodDataPromptPayParams struct{} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type SetupIntentPaymentMethodDataRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. +type SetupIntentPaymentMethodDataRevolutPayParams struct{} + +// If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. +type SetupIntentPaymentMethodDataSamsungPayParams struct{} + +// If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. +type SetupIntentPaymentMethodDataSatispayParams struct{} + +// If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. +type SetupIntentPaymentMethodDataSEPADebitParams struct { + // IBAN of the bank account. + IBAN *string `form:"iban"` +} + +// If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. +type SetupIntentPaymentMethodDataSofortParams struct { + // Two-letter ISO code representing the country the bank account is located in. + Country *string `form:"country"` +} + +// If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. +type SetupIntentPaymentMethodDataSwishParams struct{} + +// If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. +type SetupIntentPaymentMethodDataTWINTParams struct{} + +// If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. +type SetupIntentPaymentMethodDataUSBankAccountParams struct { + // Account holder type: individual or company. + AccountHolderType *string `form:"account_holder_type"` + // Account number of the bank account. + AccountNumber *string `form:"account_number"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType *string `form:"account_type"` + // The ID of a Financial Connections Account to use as a payment method. + FinancialConnectionsAccount *string `form:"financial_connections_account"` + // Routing number of the bank account. + RoutingNumber *string `form:"routing_number"` +} + +// If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. +type SetupIntentPaymentMethodDataWeChatPayParams struct{} + +// If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. +type SetupIntentPaymentMethodDataZipParams struct{} + +// When included, this hash creates a PaymentMethod that is set as the [`payment_method`](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-payment_method) +// value in the SetupIntent. +type SetupIntentPaymentMethodDataParams struct { + // If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + ACSSDebit *SetupIntentPaymentMethodDataACSSDebitParams `form:"acss_debit"` + // If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + Affirm *SetupIntentPaymentMethodDataAffirmParams `form:"affirm"` + // If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + AfterpayClearpay *SetupIntentPaymentMethodDataAfterpayClearpayParams `form:"afterpay_clearpay"` + // If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + Alipay *SetupIntentPaymentMethodDataAlipayParams `form:"alipay"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to `unspecified`. + AllowRedisplay *string `form:"allow_redisplay"` + // If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. + Alma *SetupIntentPaymentMethodDataAlmaParams `form:"alma"` + // If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. + AmazonPay *SetupIntentPaymentMethodDataAmazonPayParams `form:"amazon_pay"` + // If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + AUBECSDebit *SetupIntentPaymentMethodDataAUBECSDebitParams `form:"au_becs_debit"` + // If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + BACSDebit *SetupIntentPaymentMethodDataBACSDebitParams `form:"bacs_debit"` + // If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + Bancontact *SetupIntentPaymentMethodDataBancontactParams `form:"bancontact"` + // If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. + Billie *SetupIntentPaymentMethodDataBillieParams `form:"billie"` + // Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + BillingDetails *SetupIntentPaymentMethodDataBillingDetailsParams `form:"billing_details"` + // If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + BLIK *SetupIntentPaymentMethodDataBLIKParams `form:"blik"` + // If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + Boleto *SetupIntentPaymentMethodDataBoletoParams `form:"boleto"` + // If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + CashApp *SetupIntentPaymentMethodDataCashAppParams `form:"cashapp"` + // If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. + Crypto *SetupIntentPaymentMethodDataCryptoParams `form:"crypto"` + // If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + CustomerBalance *SetupIntentPaymentMethodDataCustomerBalanceParams `form:"customer_balance"` + // If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + EPS *SetupIntentPaymentMethodDataEPSParams `form:"eps"` + // If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + FPX *SetupIntentPaymentMethodDataFPXParams `form:"fpx"` + // If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + Giropay *SetupIntentPaymentMethodDataGiropayParams `form:"giropay"` + // If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + Grabpay *SetupIntentPaymentMethodDataGrabpayParams `form:"grabpay"` + // If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + IDEAL *SetupIntentPaymentMethodDataIDEALParams `form:"ideal"` + // If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + InteracPresent *SetupIntentPaymentMethodDataInteracPresentParams `form:"interac_present"` + // If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. + KakaoPay *SetupIntentPaymentMethodDataKakaoPayParams `form:"kakao_pay"` + // If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + Klarna *SetupIntentPaymentMethodDataKlarnaParams `form:"klarna"` + // If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + Konbini *SetupIntentPaymentMethodDataKonbiniParams `form:"konbini"` + // If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. + KrCard *SetupIntentPaymentMethodDataKrCardParams `form:"kr_card"` + // If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + Link *SetupIntentPaymentMethodDataLinkParams `form:"link"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. + Mobilepay *SetupIntentPaymentMethodDataMobilepayParams `form:"mobilepay"` + // If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. + Multibanco *SetupIntentPaymentMethodDataMultibancoParams `form:"multibanco"` + // If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. + NaverPay *SetupIntentPaymentMethodDataNaverPayParams `form:"naver_pay"` + // If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. + NzBankAccount *SetupIntentPaymentMethodDataNzBankAccountParams `form:"nz_bank_account"` + // If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + OXXO *SetupIntentPaymentMethodDataOXXOParams `form:"oxxo"` + // If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + P24 *SetupIntentPaymentMethodDataP24Params `form:"p24"` + // If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. + PayByBank *SetupIntentPaymentMethodDataPayByBankParams `form:"pay_by_bank"` + // If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. + Payco *SetupIntentPaymentMethodDataPaycoParams `form:"payco"` + // If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + PayNow *SetupIntentPaymentMethodDataPayNowParams `form:"paynow"` + // If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + Paypal *SetupIntentPaymentMethodDataPaypalParams `form:"paypal"` + // If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + Pix *SetupIntentPaymentMethodDataPixParams `form:"pix"` + // If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + PromptPay *SetupIntentPaymentMethodDataPromptPayParams `form:"promptpay"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *SetupIntentPaymentMethodDataRadarOptionsParams `form:"radar_options"` + // If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + RevolutPay *SetupIntentPaymentMethodDataRevolutPayParams `form:"revolut_pay"` + // If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. + SamsungPay *SetupIntentPaymentMethodDataSamsungPayParams `form:"samsung_pay"` + // If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. + Satispay *SetupIntentPaymentMethodDataSatispayParams `form:"satispay"` + // If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + SEPADebit *SetupIntentPaymentMethodDataSEPADebitParams `form:"sepa_debit"` + // If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + Sofort *SetupIntentPaymentMethodDataSofortParams `form:"sofort"` + // If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. + Swish *SetupIntentPaymentMethodDataSwishParams `form:"swish"` + // If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. + TWINT *SetupIntentPaymentMethodDataTWINTParams `form:"twint"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type *string `form:"type"` + // If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + USBankAccount *SetupIntentPaymentMethodDataUSBankAccountParams `form:"us_bank_account"` + // If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + WeChatPay *SetupIntentPaymentMethodDataWeChatPayParams `form:"wechat_pay"` + // If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + Zip *SetupIntentPaymentMethodDataZipParams `form:"zip"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SetupIntentPaymentMethodDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Additional fields for Mandate creation +type SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsParams struct { + // A URL for custom mandate text to render during confirmation step. + // The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + // or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + CustomMandateURL *string `form:"custom_mandate_url"` + // List of Stripe products where this mandate can be selected automatically. + DefaultFor []*string `form:"default_for"` + // Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + IntervalDescription *string `form:"interval_description"` + // Payment schedule for the mandate. + PaymentSchedule *string `form:"payment_schedule"` + // Transaction type of the mandate. + TransactionType *string `form:"transaction_type"` +} + +// If this is a `acss_debit` SetupIntent, this sub-hash contains details about the ACSS Debit payment method options. +type SetupIntentPaymentMethodOptionsACSSDebitParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Additional fields for Mandate creation + MandateOptions *SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsParams `form:"mandate_options"` + // Bank account verification method. + VerificationMethod *string `form:"verification_method"` +} + +// If this is a `amazon_pay` SetupIntent, this sub-hash contains details about the AmazonPay payment method options. +type SetupIntentPaymentMethodOptionsAmazonPayParams struct{} + +// Additional fields for Mandate creation +type SetupIntentPaymentMethodOptionsBACSDebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'DDIC' or 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// If this is a `bacs_debit` SetupIntent, this sub-hash contains details about the Bacs Debit payment method options. +type SetupIntentPaymentMethodOptionsBACSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *SetupIntentPaymentMethodOptionsBACSDebitMandateOptionsParams `form:"mandate_options"` +} + +// Configuration options for setting up an eMandate for cards issued in India. +type SetupIntentPaymentMethodOptionsCardMandateOptionsParams struct { + // Amount to be charged for future payments. + Amount *int64 `form:"amount"` + // One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + AmountType *string `form:"amount_type"` + // Currency in which future payments will be charged. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // A description of the mandate or subscription that is meant to be displayed to the customer. + Description *string `form:"description"` + // End date of the mandate or subscription. If not provided, the mandate will be active until canceled. If provided, end date should be after start date. + EndDate *int64 `form:"end_date"` + // Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. + Interval *string `form:"interval"` + // The number of intervals between payments. For example, `interval=month` and `interval_count=3` indicates one payment every three months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). This parameter is optional when `interval=sporadic`. + IntervalCount *int64 `form:"interval_count"` + // Unique identifier for the mandate or subscription. + Reference *string `form:"reference"` + // Start date of the mandate or subscription. Start date should not be lesser than yesterday. + StartDate *int64 `form:"start_date"` + // Specifies the type of mandates supported. Possible values are `india`. + SupportedTypes []*string `form:"supported_types"` +} + +// Cartes Bancaires-specific 3DS fields. +type SetupIntentPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancairesParams struct { + // The cryptogram calculation algorithm used by the card Issuer's ACS + // to calculate the Authentication cryptogram. Also known as `cavvAlgorithm`. + // messageExtension: CB-AVALGO + CbAvalgo *string `form:"cb_avalgo"` + // The exemption indicator returned from Cartes Bancaires in the ARes. + // message extension: CB-EXEMPTION; string (4 characters) + // This is a 3 byte bitmap (low significant byte first and most significant + // bit first) that has been Base64 encoded + CbExemption *string `form:"cb_exemption"` + // The risk score returned from Cartes Bancaires in the ARes. + // message extension: CB-SCORE; numeric value 0-99 + CbScore *int64 `form:"cb_score"` +} + +// Network specific 3DS fields. Network specific arguments require an +// explicit card brand choice. The parameter `payment_method_options.card.network“ +// must be populated accordingly +type SetupIntentPaymentMethodOptionsCardThreeDSecureNetworkOptionsParams struct { + // Cartes Bancaires-specific 3DS fields. + CartesBancaires *SetupIntentPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancairesParams `form:"cartes_bancaires"` +} + +// If 3D Secure authentication was performed with a third-party provider, +// the authentication details to use for this setup. +type SetupIntentPaymentMethodOptionsCardThreeDSecureParams struct { + // The `transStatus` returned from the card Issuer's ACS in the ARes. + AresTransStatus *string `form:"ares_trans_status"` + // The cryptogram, also known as the "authentication value" (AAV, CAVV or + // AEVV). This value is 20 bytes, base64-encoded into a 28-character string. + // (Most 3D Secure providers will return the base64-encoded version, which + // is what you should specify here.) + Cryptogram *string `form:"cryptogram"` + // The Electronic Commerce Indicator (ECI) is returned by your 3D Secure + // provider and indicates what degree of authentication was performed. + ElectronicCommerceIndicator *string `form:"electronic_commerce_indicator"` + // Network specific 3DS fields. Network specific arguments require an + // explicit card brand choice. The parameter `payment_method_options.card.network`` + // must be populated accordingly + NetworkOptions *SetupIntentPaymentMethodOptionsCardThreeDSecureNetworkOptionsParams `form:"network_options"` + // The challenge indicator (`threeDSRequestorChallengeInd`) which was requested in the + // AReq sent to the card Issuer's ACS. A string containing 2 digits from 01-99. + RequestorChallengeIndicator *string `form:"requestor_challenge_indicator"` + // For 3D Secure 1, the XID. For 3D Secure 2, the Directory Server + // Transaction ID (dsTransID). + TransactionID *string `form:"transaction_id"` + // The version of 3D Secure that was performed. + Version *string `form:"version"` +} + +// Configuration for any card setup attempted on this SetupIntent. +type SetupIntentPaymentMethodOptionsCardParams struct { + // Configuration options for setting up an eMandate for cards issued in India. + MandateOptions *SetupIntentPaymentMethodOptionsCardMandateOptionsParams `form:"mandate_options"` + // When specified, this parameter signals that a card has been collected + // as MOTO (Mail Order Telephone Order) and thus out of scope for SCA. This + // parameter can only be provided during confirmation. + MOTO *bool `form:"moto"` + // Selected network to process this SetupIntent on. Depends on the available networks of the card attached to the SetupIntent. Can be only set confirm-time. + Network *string `form:"network"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure *string `form:"request_three_d_secure"` + // If 3D Secure authentication was performed with a third-party provider, + // the authentication details to use for this setup. + ThreeDSecure *SetupIntentPaymentMethodOptionsCardThreeDSecureParams `form:"three_d_secure"` +} + +// If this is a `card_present` PaymentMethod, this sub-hash contains details about the card-present payment method options. +type SetupIntentPaymentMethodOptionsCardPresentParams struct{} + +// On-demand details if setting up a payment method for on-demand payments. +type SetupIntentPaymentMethodOptionsKlarnaOnDemandParams struct { + // Your average amount value. You can use a value across your customer base, or segment based on customer type, country, etc. + AverageAmount *int64 `form:"average_amount"` + // The maximum value you may charge a customer per purchase. You can use a value across your customer base, or segment based on customer type, country, etc. + MaximumAmount *int64 `form:"maximum_amount"` + // The lowest or minimum value you may charge a customer per purchase. You can use a value across your customer base, or segment based on customer type, country, etc. + MinimumAmount *int64 `form:"minimum_amount"` + // Interval at which the customer is making purchases + PurchaseInterval *string `form:"purchase_interval"` + // The number of `purchase_interval` between charges + PurchaseIntervalCount *int64 `form:"purchase_interval_count"` +} + +// Describes the upcoming charge for this subscription. +type SetupIntentPaymentMethodOptionsKlarnaSubscriptionNextBillingParams struct { + // The amount of the next charge for the subscription. + Amount *int64 `form:"amount"` + // The date of the next charge for the subscription in YYYY-MM-DD format. + Date *string `form:"date"` +} + +// Subscription details if setting up or charging a subscription +type SetupIntentPaymentMethodOptionsKlarnaSubscriptionParams struct { + // Unit of time between subscription charges. + Interval *string `form:"interval"` + // The number of intervals (specified in the `interval` attribute) between subscription charges. For example, `interval=month` and `interval_count=3` charges every 3 months. + IntervalCount *int64 `form:"interval_count"` + // Name for subscription. + Name *string `form:"name"` + // Describes the upcoming charge for this subscription. + NextBilling *SetupIntentPaymentMethodOptionsKlarnaSubscriptionNextBillingParams `form:"next_billing"` + // A non-customer-facing reference to correlate subscription charges in the Klarna app. Use a value that persists across subscription charges. + Reference *string `form:"reference"` +} + +// If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method options. +type SetupIntentPaymentMethodOptionsKlarnaParams struct { + // The currency of the SetupIntent. Three letter ISO currency code. + Currency *string `form:"currency"` + // On-demand details if setting up a payment method for on-demand payments. + OnDemand *SetupIntentPaymentMethodOptionsKlarnaOnDemandParams `form:"on_demand"` + // Preferred language of the Klarna authorization page that the customer is redirected to + PreferredLocale *string `form:"preferred_locale"` + // Subscription details if setting up or charging a subscription + Subscriptions []*SetupIntentPaymentMethodOptionsKlarnaSubscriptionParams `form:"subscriptions"` +} + +// If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. +type SetupIntentPaymentMethodOptionsLinkParams struct { + // [Deprecated] This is a legacy parameter that no longer has any function. + // Deprecated: + PersistentToken *string `form:"persistent_token"` +} + +// If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. +type SetupIntentPaymentMethodOptionsPaypalParams struct { + // The PayPal Billing Agreement ID (BAID). This is an ID generated by PayPal which represents the mandate between the merchant and the customer. + BillingAgreementID *string `form:"billing_agreement_id"` +} + +// Additional fields for Mandate creation +type SetupIntentPaymentMethodOptionsSEPADebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// If this is a `sepa_debit` SetupIntent, this sub-hash contains details about the SEPA Debit payment method options. +type SetupIntentPaymentMethodOptionsSEPADebitParams struct { + // Additional fields for Mandate creation + MandateOptions *SetupIntentPaymentMethodOptionsSEPADebitMandateOptionsParams `form:"mandate_options"` +} + +// Provide filters for the linked accounts that the customer can select for the payment method. +type SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams struct { + // The account subcategories to use to filter for selectable accounts. Valid subcategories are `checking` and `savings`. + AccountSubcategories []*string `form:"account_subcategories"` +} + +// Additional fields for Financial Connections Session creation +type SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsParams struct { + // Provide filters for the linked accounts that the customer can select for the payment method. + Filters *SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams `form:"filters"` + // The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` + // For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + ReturnURL *string `form:"return_url"` +} + +// Additional fields for Mandate creation +type SetupIntentPaymentMethodOptionsUSBankAccountMandateOptionsParams struct { + // The method used to collect offline mandate customer acceptance. + CollectionMethod *string `form:"collection_method"` +} + +// Additional fields for network related functions +type SetupIntentPaymentMethodOptionsUSBankAccountNetworksParams struct { + // Triggers validations to run across the selected networks + Requested []*string `form:"requested"` +} + +// If this is a `us_bank_account` SetupIntent, this sub-hash contains details about the US bank account payment method options. +type SetupIntentPaymentMethodOptionsUSBankAccountParams struct { + // Additional fields for Financial Connections Session creation + FinancialConnections *SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsParams `form:"financial_connections"` + // Additional fields for Mandate creation + MandateOptions *SetupIntentPaymentMethodOptionsUSBankAccountMandateOptionsParams `form:"mandate_options"` + // Additional fields for network related functions + Networks *SetupIntentPaymentMethodOptionsUSBankAccountNetworksParams `form:"networks"` + // Bank account verification method. + VerificationMethod *string `form:"verification_method"` +} + +// Payment method-specific configuration for this SetupIntent. +type SetupIntentPaymentMethodOptionsParams struct { + // If this is a `acss_debit` SetupIntent, this sub-hash contains details about the ACSS Debit payment method options. + ACSSDebit *SetupIntentPaymentMethodOptionsACSSDebitParams `form:"acss_debit"` + // If this is a `amazon_pay` SetupIntent, this sub-hash contains details about the AmazonPay payment method options. + AmazonPay *SetupIntentPaymentMethodOptionsAmazonPayParams `form:"amazon_pay"` + // If this is a `bacs_debit` SetupIntent, this sub-hash contains details about the Bacs Debit payment method options. + BACSDebit *SetupIntentPaymentMethodOptionsBACSDebitParams `form:"bacs_debit"` + // Configuration for any card setup attempted on this SetupIntent. + Card *SetupIntentPaymentMethodOptionsCardParams `form:"card"` + // If this is a `card_present` PaymentMethod, this sub-hash contains details about the card-present payment method options. + CardPresent *SetupIntentPaymentMethodOptionsCardPresentParams `form:"card_present"` + // If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method options. + Klarna *SetupIntentPaymentMethodOptionsKlarnaParams `form:"klarna"` + // If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. + Link *SetupIntentPaymentMethodOptionsLinkParams `form:"link"` + // If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. + Paypal *SetupIntentPaymentMethodOptionsPaypalParams `form:"paypal"` + // If this is a `sepa_debit` SetupIntent, this sub-hash contains details about the SEPA Debit payment method options. + SEPADebit *SetupIntentPaymentMethodOptionsSEPADebitParams `form:"sepa_debit"` + // If this is a `us_bank_account` SetupIntent, this sub-hash contains details about the US bank account payment method options. + USBankAccount *SetupIntentPaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` +} + +// If you populate this hash, this SetupIntent generates a `single_use` mandate after successful completion. +// +// Single-use mandates are only valid for the following payment methods: `acss_debit`, `alipay`, `au_becs_debit`, `bacs_debit`, `bancontact`, `boleto`, `ideal`, `link`, `sepa_debit`, and `us_bank_account`. +type SetupIntentSingleUseParams struct { + // Amount the customer is granting permission to collect later. A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` +} + +// Creates a SetupIntent object. +// +// After you create the SetupIntent, attach a payment method and [confirm](https://docs.stripe.com/docs/api/setup_intents/confirm) +// it to collect any required permissions to charge the payment method later. +type SetupIntentParams struct { + Params `form:"*"` + // If present, the SetupIntent's payment method will be attached to the in-context Stripe Account. + // + // It can only be used for this Stripe Account's own money movement flows like InboundTransfer and OutboundTransfers. It cannot be set to true when setting up a PaymentMethod for a Customer, and defaults to false when attaching a PaymentMethod to a Customer. + AttachToSelf *bool `form:"attach_to_self"` + // When you enable this parameter, this SetupIntent accepts payment methods that you enable in the Dashboard and that are compatible with its other parameters. + AutomaticPaymentMethods *SetupIntentAutomaticPaymentMethodsParams `form:"automatic_payment_methods"` + // The client secret of the SetupIntent. We require this string if you use a publishable key to retrieve the SetupIntent. + ClientSecret *string `form:"client_secret"` + // Set to `true` to attempt to confirm this SetupIntent immediately. This parameter defaults to `false`. If a card is the attached payment method, you can provide a `return_url` in case further authentication is necessary. + Confirm *bool `form:"confirm"` + // ID of the ConfirmationToken used to confirm this SetupIntent. + // + // If the provided ConfirmationToken contains properties that are also being provided in this request, such as `payment_method`, then the values in this request will take precedence. + ConfirmationToken *string `form:"confirmation_token"` + // ID of the Customer this SetupIntent belongs to, if one exists. + // + // If present, the SetupIntent's payment method will be attached to the Customer on successful setup. Payment methods attached to other Customers cannot be used with this SetupIntent. + Customer *string `form:"customer"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Indicates the directions of money movement for which this payment method is intended to be used. + // + // Include `inbound` if you intend to use the payment method as the origin to pull funds from. Include `outbound` if you intend to use the payment method as the destination to send funds to. You can include both if you intend to use the payment method for both purposes. + FlowDirections []*string `form:"flow_directions"` + // This hash contains details about the mandate to create. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/setup_intents/create#create_setup_intent-confirm). + MandateData *SetupIntentMandateDataParams `form:"mandate_data"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The Stripe account ID created for this SetupIntent. + OnBehalfOf *string `form:"on_behalf_of"` + // ID of the payment method (a PaymentMethod, Card, or saved Source object) to attach to this SetupIntent. To unset this field to null, pass in an empty string. + PaymentMethod *string `form:"payment_method"` + // The ID of the [payment method configuration](https://stripe.com/docs/api/payment_method_configurations) to use with this SetupIntent. + PaymentMethodConfiguration *string `form:"payment_method_configuration"` + // When included, this hash creates a PaymentMethod that is set as the [`payment_method`](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-payment_method) + // value in the SetupIntent. + PaymentMethodData *SetupIntentPaymentMethodDataParams `form:"payment_method_data"` + // Payment method-specific configuration for this SetupIntent. + PaymentMethodOptions *SetupIntentPaymentMethodOptionsParams `form:"payment_method_options"` + // The list of payment method types (for example, card) that this SetupIntent can set up. If you don't provide this, Stripe will dynamically show relevant payment methods from your [payment method settings](https://dashboard.stripe.com/settings/payment_methods). A list of valid payment method types can be found [here](https://docs.stripe.com/api/payment_methods/object#payment_method_object-type). + PaymentMethodTypes []*string `form:"payment_method_types"` + // The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method's app or site. To redirect to a mobile application, you can alternatively supply an application URI scheme. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/setup_intents/create#create_setup_intent-confirm). + ReturnURL *string `form:"return_url"` + // If you populate this hash, this SetupIntent generates a `single_use` mandate after successful completion. + // + // Single-use mandates are only valid for the following payment methods: `acss_debit`, `alipay`, `au_becs_debit`, `bacs_debit`, `bancontact`, `boleto`, `ideal`, `link`, `sepa_debit`, and `us_bank_account`. + SingleUse *SetupIntentSingleUseParams `form:"single_use"` + // Indicates how the payment method is intended to be used in the future. If not provided, this value defaults to `off_session`. + Usage *string `form:"usage"` + // Set to `true` when confirming server-side and using Stripe.js, iOS, or Android client-side SDKs to handle the next actions. + UseStripeSDK *bool `form:"use_stripe_sdk"` +} + +// AddExpand appends a new field to expand. +func (p *SetupIntentParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SetupIntentParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// You can cancel a SetupIntent object when it's in one of these statuses: requires_payment_method, requires_confirmation, or requires_action. +// +// After you cancel it, setup is abandoned and any operations on the SetupIntent fail with an error. You can't cancel the SetupIntent for a Checkout Session. [Expire the Checkout Session](https://docs.stripe.com/docs/api/checkout/sessions/expire) instead. +type SetupIntentCancelParams struct { + Params `form:"*"` + // Reason for canceling this SetupIntent. Possible values are: `abandoned`, `requested_by_customer`, or `duplicate` + CancellationReason *string `form:"cancellation_reason"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *SetupIntentCancelParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. +type SetupIntentConfirmPaymentMethodDataACSSDebitParams struct { + // Customer's bank account number. + AccountNumber *string `form:"account_number"` + // Institution number of the customer's bank. + InstitutionNumber *string `form:"institution_number"` + // Transit number of the customer's bank. + TransitNumber *string `form:"transit_number"` +} + +// If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. +type SetupIntentConfirmPaymentMethodDataAffirmParams struct{} + +// If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. +type SetupIntentConfirmPaymentMethodDataAfterpayClearpayParams struct{} + +// If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. +type SetupIntentConfirmPaymentMethodDataAlipayParams struct{} + +// If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. +type SetupIntentConfirmPaymentMethodDataAlmaParams struct{} + +// If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. +type SetupIntentConfirmPaymentMethodDataAmazonPayParams struct{} + +// If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. +type SetupIntentConfirmPaymentMethodDataAUBECSDebitParams struct { + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // Bank-State-Branch number of the bank account. + BSBNumber *string `form:"bsb_number"` +} + +// If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. +type SetupIntentConfirmPaymentMethodDataBACSDebitParams struct { + // Account number of the bank account that the funds will be debited from. + AccountNumber *string `form:"account_number"` + // Sort code of the bank account. (e.g., `10-20-30`) + SortCode *string `form:"sort_code"` +} + +// If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. +type SetupIntentConfirmPaymentMethodDataBancontactParams struct{} + +// If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. +type SetupIntentConfirmPaymentMethodDataBillieParams struct{} + +// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. +type SetupIntentConfirmPaymentMethodDataBillingDetailsParams struct { + // Billing address. + Address *AddressParams `form:"address"` + // Email address. + Email *string `form:"email"` + // Full name. + Name *string `form:"name"` + // Billing phone number (including extension). + Phone *string `form:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID *string `form:"tax_id"` +} + +// If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. +type SetupIntentConfirmPaymentMethodDataBLIKParams struct{} + +// If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. +type SetupIntentConfirmPaymentMethodDataBoletoParams struct { + // The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + TaxID *string `form:"tax_id"` +} + +// If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. +type SetupIntentConfirmPaymentMethodDataCashAppParams struct{} + +// If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. +type SetupIntentConfirmPaymentMethodDataCryptoParams struct{} + +// If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. +type SetupIntentConfirmPaymentMethodDataCustomerBalanceParams struct{} + +// If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. +type SetupIntentConfirmPaymentMethodDataEPSParams struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. +type SetupIntentConfirmPaymentMethodDataFPXParams struct { + // Account holder type for FPX transaction + AccountHolderType *string `form:"account_holder_type"` + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. +type SetupIntentConfirmPaymentMethodDataGiropayParams struct{} + +// If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. +type SetupIntentConfirmPaymentMethodDataGrabpayParams struct{} + +// If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. +type SetupIntentConfirmPaymentMethodDataIDEALParams struct { + // The customer's bank. Only use this parameter for existing customers. Don't use it for new customers. + Bank *string `form:"bank"` +} + +// If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. +type SetupIntentConfirmPaymentMethodDataInteracPresentParams struct{} + +// If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. +type SetupIntentConfirmPaymentMethodDataKakaoPayParams struct{} + +// Customer's date of birth +type SetupIntentConfirmPaymentMethodDataKlarnaDOBParams struct { + // The day of birth, between 1 and 31. + Day *int64 `form:"day"` + // The month of birth, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of birth. + Year *int64 `form:"year"` +} + +// If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. +type SetupIntentConfirmPaymentMethodDataKlarnaParams struct { + // Customer's date of birth + DOB *SetupIntentConfirmPaymentMethodDataKlarnaDOBParams `form:"dob"` +} + +// If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. +type SetupIntentConfirmPaymentMethodDataKonbiniParams struct{} + +// If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. +type SetupIntentConfirmPaymentMethodDataKrCardParams struct{} + +// If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. +type SetupIntentConfirmPaymentMethodDataLinkParams struct{} + +// If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. +type SetupIntentConfirmPaymentMethodDataMobilepayParams struct{} + +// If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. +type SetupIntentConfirmPaymentMethodDataMultibancoParams struct{} + +// If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. +type SetupIntentConfirmPaymentMethodDataNaverPayParams struct { + // Whether to use Naver Pay points or a card to fund this transaction. If not provided, this defaults to `card`. + Funding *string `form:"funding"` +} + +// If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. +type SetupIntentConfirmPaymentMethodDataNzBankAccountParams struct { + // The name on the bank account. Only required if the account holder name is different from the name of the authorized signatory collected in the PaymentMethod's billing details. + AccountHolderName *string `form:"account_holder_name"` + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // The numeric code for the bank account's bank. + BankCode *string `form:"bank_code"` + // The numeric code for the bank account's bank branch. + BranchCode *string `form:"branch_code"` + Reference *string `form:"reference"` + // The suffix of the bank account number. + Suffix *string `form:"suffix"` +} + +// If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. +type SetupIntentConfirmPaymentMethodDataOXXOParams struct{} + +// If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. +type SetupIntentConfirmPaymentMethodDataP24Params struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. +type SetupIntentConfirmPaymentMethodDataPayByBankParams struct{} + +// If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. +type SetupIntentConfirmPaymentMethodDataPaycoParams struct{} + +// If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. +type SetupIntentConfirmPaymentMethodDataPayNowParams struct{} + +// If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. +type SetupIntentConfirmPaymentMethodDataPaypalParams struct{} + +// If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. +type SetupIntentConfirmPaymentMethodDataPixParams struct{} + +// If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. +type SetupIntentConfirmPaymentMethodDataPromptPayParams struct{} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type SetupIntentConfirmPaymentMethodDataRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. +type SetupIntentConfirmPaymentMethodDataRevolutPayParams struct{} + +// If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. +type SetupIntentConfirmPaymentMethodDataSamsungPayParams struct{} + +// If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. +type SetupIntentConfirmPaymentMethodDataSatispayParams struct{} + +// If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. +type SetupIntentConfirmPaymentMethodDataSEPADebitParams struct { + // IBAN of the bank account. + IBAN *string `form:"iban"` +} + +// If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. +type SetupIntentConfirmPaymentMethodDataSofortParams struct { + // Two-letter ISO code representing the country the bank account is located in. + Country *string `form:"country"` +} + +// If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. +type SetupIntentConfirmPaymentMethodDataSwishParams struct{} + +// If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. +type SetupIntentConfirmPaymentMethodDataTWINTParams struct{} + +// If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. +type SetupIntentConfirmPaymentMethodDataUSBankAccountParams struct { + // Account holder type: individual or company. + AccountHolderType *string `form:"account_holder_type"` + // Account number of the bank account. + AccountNumber *string `form:"account_number"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType *string `form:"account_type"` + // The ID of a Financial Connections Account to use as a payment method. + FinancialConnectionsAccount *string `form:"financial_connections_account"` + // Routing number of the bank account. + RoutingNumber *string `form:"routing_number"` +} + +// If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. +type SetupIntentConfirmPaymentMethodDataWeChatPayParams struct{} + +// If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. +type SetupIntentConfirmPaymentMethodDataZipParams struct{} + +// When included, this hash creates a PaymentMethod that is set as the [`payment_method`](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-payment_method) +// value in the SetupIntent. +type SetupIntentConfirmPaymentMethodDataParams struct { + // If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + ACSSDebit *SetupIntentConfirmPaymentMethodDataACSSDebitParams `form:"acss_debit"` + // If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + Affirm *SetupIntentConfirmPaymentMethodDataAffirmParams `form:"affirm"` + // If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + AfterpayClearpay *SetupIntentConfirmPaymentMethodDataAfterpayClearpayParams `form:"afterpay_clearpay"` + // If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + Alipay *SetupIntentConfirmPaymentMethodDataAlipayParams `form:"alipay"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to `unspecified`. + AllowRedisplay *string `form:"allow_redisplay"` + // If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. + Alma *SetupIntentConfirmPaymentMethodDataAlmaParams `form:"alma"` + // If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. + AmazonPay *SetupIntentConfirmPaymentMethodDataAmazonPayParams `form:"amazon_pay"` + // If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + AUBECSDebit *SetupIntentConfirmPaymentMethodDataAUBECSDebitParams `form:"au_becs_debit"` + // If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + BACSDebit *SetupIntentConfirmPaymentMethodDataBACSDebitParams `form:"bacs_debit"` + // If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + Bancontact *SetupIntentConfirmPaymentMethodDataBancontactParams `form:"bancontact"` + // If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. + Billie *SetupIntentConfirmPaymentMethodDataBillieParams `form:"billie"` + // Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + BillingDetails *SetupIntentConfirmPaymentMethodDataBillingDetailsParams `form:"billing_details"` + // If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + BLIK *SetupIntentConfirmPaymentMethodDataBLIKParams `form:"blik"` + // If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + Boleto *SetupIntentConfirmPaymentMethodDataBoletoParams `form:"boleto"` + // If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + CashApp *SetupIntentConfirmPaymentMethodDataCashAppParams `form:"cashapp"` + // If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. + Crypto *SetupIntentConfirmPaymentMethodDataCryptoParams `form:"crypto"` + // If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + CustomerBalance *SetupIntentConfirmPaymentMethodDataCustomerBalanceParams `form:"customer_balance"` + // If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + EPS *SetupIntentConfirmPaymentMethodDataEPSParams `form:"eps"` + // If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + FPX *SetupIntentConfirmPaymentMethodDataFPXParams `form:"fpx"` + // If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + Giropay *SetupIntentConfirmPaymentMethodDataGiropayParams `form:"giropay"` + // If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + Grabpay *SetupIntentConfirmPaymentMethodDataGrabpayParams `form:"grabpay"` + // If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + IDEAL *SetupIntentConfirmPaymentMethodDataIDEALParams `form:"ideal"` + // If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + InteracPresent *SetupIntentConfirmPaymentMethodDataInteracPresentParams `form:"interac_present"` + // If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. + KakaoPay *SetupIntentConfirmPaymentMethodDataKakaoPayParams `form:"kakao_pay"` + // If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + Klarna *SetupIntentConfirmPaymentMethodDataKlarnaParams `form:"klarna"` + // If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + Konbini *SetupIntentConfirmPaymentMethodDataKonbiniParams `form:"konbini"` + // If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. + KrCard *SetupIntentConfirmPaymentMethodDataKrCardParams `form:"kr_card"` + // If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + Link *SetupIntentConfirmPaymentMethodDataLinkParams `form:"link"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. + Mobilepay *SetupIntentConfirmPaymentMethodDataMobilepayParams `form:"mobilepay"` + // If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. + Multibanco *SetupIntentConfirmPaymentMethodDataMultibancoParams `form:"multibanco"` + // If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. + NaverPay *SetupIntentConfirmPaymentMethodDataNaverPayParams `form:"naver_pay"` + // If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. + NzBankAccount *SetupIntentConfirmPaymentMethodDataNzBankAccountParams `form:"nz_bank_account"` + // If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + OXXO *SetupIntentConfirmPaymentMethodDataOXXOParams `form:"oxxo"` + // If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + P24 *SetupIntentConfirmPaymentMethodDataP24Params `form:"p24"` + // If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. + PayByBank *SetupIntentConfirmPaymentMethodDataPayByBankParams `form:"pay_by_bank"` + // If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. + Payco *SetupIntentConfirmPaymentMethodDataPaycoParams `form:"payco"` + // If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + PayNow *SetupIntentConfirmPaymentMethodDataPayNowParams `form:"paynow"` + // If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + Paypal *SetupIntentConfirmPaymentMethodDataPaypalParams `form:"paypal"` + // If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + Pix *SetupIntentConfirmPaymentMethodDataPixParams `form:"pix"` + // If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + PromptPay *SetupIntentConfirmPaymentMethodDataPromptPayParams `form:"promptpay"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *SetupIntentConfirmPaymentMethodDataRadarOptionsParams `form:"radar_options"` + // If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + RevolutPay *SetupIntentConfirmPaymentMethodDataRevolutPayParams `form:"revolut_pay"` + // If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. + SamsungPay *SetupIntentConfirmPaymentMethodDataSamsungPayParams `form:"samsung_pay"` + // If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. + Satispay *SetupIntentConfirmPaymentMethodDataSatispayParams `form:"satispay"` + // If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + SEPADebit *SetupIntentConfirmPaymentMethodDataSEPADebitParams `form:"sepa_debit"` + // If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + Sofort *SetupIntentConfirmPaymentMethodDataSofortParams `form:"sofort"` + // If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. + Swish *SetupIntentConfirmPaymentMethodDataSwishParams `form:"swish"` + // If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. + TWINT *SetupIntentConfirmPaymentMethodDataTWINTParams `form:"twint"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type *string `form:"type"` + // If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + USBankAccount *SetupIntentConfirmPaymentMethodDataUSBankAccountParams `form:"us_bank_account"` + // If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + WeChatPay *SetupIntentConfirmPaymentMethodDataWeChatPayParams `form:"wechat_pay"` + // If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + Zip *SetupIntentConfirmPaymentMethodDataZipParams `form:"zip"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SetupIntentConfirmPaymentMethodDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Confirm that your customer intends to set up the current or +// provided payment method. For example, you would confirm a SetupIntent +// when a customer hits the “Save” button on a payment method management +// page on your website. +// +// If the selected payment method does not require any additional +// steps from the customer, the SetupIntent will transition to the +// succeeded status. +// +// Otherwise, it will transition to the requires_action status and +// suggest additional actions via next_action. If setup fails, +// the SetupIntent will transition to the +// requires_payment_method status or the canceled status if the +// confirmation limit is reached. +type SetupIntentConfirmParams struct { + Params `form:"*"` + // ID of the ConfirmationToken used to confirm this SetupIntent. + // + // If the provided ConfirmationToken contains properties that are also being provided in this request, such as `payment_method`, then the values in this request will take precedence. + ConfirmationToken *string `form:"confirmation_token"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + MandateData *SetupIntentMandateDataParams `form:"mandate_data"` + // ID of the payment method (a PaymentMethod, Card, or saved Source object) to attach to this SetupIntent. + PaymentMethod *string `form:"payment_method"` + // When included, this hash creates a PaymentMethod that is set as the [`payment_method`](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-payment_method) + // value in the SetupIntent. + PaymentMethodData *SetupIntentConfirmPaymentMethodDataParams `form:"payment_method_data"` + // Payment method-specific configuration for this SetupIntent. + PaymentMethodOptions *SetupIntentPaymentMethodOptionsParams `form:"payment_method_options"` + // The URL to redirect your customer back to after they authenticate on the payment method's app or site. + // If you'd prefer to redirect to a mobile application, you can alternatively supply an application URI scheme. + // This parameter is only used for cards and other redirect-based payment methods. + ReturnURL *string `form:"return_url"` + // Set to `true` when confirming server-side and using Stripe.js, iOS, or Android client-side SDKs to handle the next actions. + UseStripeSDK *bool `form:"use_stripe_sdk"` +} + +// AddExpand appends a new field to expand. +func (p *SetupIntentConfirmParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Verifies microdeposits on a SetupIntent object. +type SetupIntentVerifyMicrodepositsParams struct { + Params `form:"*"` + // Two positive integers, in *cents*, equal to the values of the microdeposits sent to the bank account. + Amounts []*int64 `form:"amounts"` + // A six-character code starting with SM present in the microdeposit sent to the bank account. + DescriptorCode *string `form:"descriptor_code"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *SetupIntentVerifyMicrodepositsParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When you enable this parameter, this SetupIntent accepts payment methods that you enable in the Dashboard and that are compatible with its other parameters. +type SetupIntentCreateAutomaticPaymentMethodsParams struct { + // Controls whether this SetupIntent will accept redirect-based payment methods. + // + // Redirect-based payment methods may require your customer to be redirected to a payment method's app or site for authentication or additional steps. To [confirm](https://stripe.com/docs/api/setup_intents/confirm) this SetupIntent, you may be required to provide a `return_url` to redirect customers back to your site after they authenticate or complete the setup. + AllowRedirects *string `form:"allow_redirects"` + // Whether this feature is enabled. + Enabled *bool `form:"enabled"` +} + +// If this is a Mandate accepted offline, this hash contains details about the offline acceptance. +type SetupIntentCreateMandateDataCustomerAcceptanceOfflineParams struct{} + +// If this is a Mandate accepted online, this hash contains details about the online acceptance. +type SetupIntentCreateMandateDataCustomerAcceptanceOnlineParams struct { + // The IP address from which the Mandate was accepted by the customer. + IPAddress *string `form:"ip_address"` + // The user agent of the browser from which the Mandate was accepted by the customer. + UserAgent *string `form:"user_agent"` +} + +// This hash contains details about the customer acceptance of the Mandate. +type SetupIntentCreateMandateDataCustomerAcceptanceParams struct { + // The time at which the customer accepted the Mandate. + AcceptedAt *int64 `form:"accepted_at"` + // If this is a Mandate accepted offline, this hash contains details about the offline acceptance. + Offline *SetupIntentCreateMandateDataCustomerAcceptanceOfflineParams `form:"offline"` + // If this is a Mandate accepted online, this hash contains details about the online acceptance. + Online *SetupIntentCreateMandateDataCustomerAcceptanceOnlineParams `form:"online"` + // The type of customer acceptance information included with the Mandate. One of `online` or `offline`. + Type *string `form:"type"` +} + +// This hash contains details about the mandate to create. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/setup_intents/create#create_setup_intent-confirm). +type SetupIntentCreateMandateDataParams struct { + // This hash contains details about the customer acceptance of the Mandate. + CustomerAcceptance *SetupIntentCreateMandateDataCustomerAcceptanceParams `form:"customer_acceptance"` +} + +// If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. +type SetupIntentCreatePaymentMethodDataACSSDebitParams struct { + // Customer's bank account number. + AccountNumber *string `form:"account_number"` + // Institution number of the customer's bank. + InstitutionNumber *string `form:"institution_number"` + // Transit number of the customer's bank. + TransitNumber *string `form:"transit_number"` +} + +// If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. +type SetupIntentCreatePaymentMethodDataAffirmParams struct{} + +// If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. +type SetupIntentCreatePaymentMethodDataAfterpayClearpayParams struct{} + +// If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. +type SetupIntentCreatePaymentMethodDataAlipayParams struct{} + +// If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. +type SetupIntentCreatePaymentMethodDataAlmaParams struct{} + +// If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. +type SetupIntentCreatePaymentMethodDataAmazonPayParams struct{} + +// If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. +type SetupIntentCreatePaymentMethodDataAUBECSDebitParams struct { + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // Bank-State-Branch number of the bank account. + BSBNumber *string `form:"bsb_number"` +} + +// If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. +type SetupIntentCreatePaymentMethodDataBACSDebitParams struct { + // Account number of the bank account that the funds will be debited from. + AccountNumber *string `form:"account_number"` + // Sort code of the bank account. (e.g., `10-20-30`) + SortCode *string `form:"sort_code"` +} + +// If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. +type SetupIntentCreatePaymentMethodDataBancontactParams struct{} + +// If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. +type SetupIntentCreatePaymentMethodDataBillieParams struct{} + +// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. +type SetupIntentCreatePaymentMethodDataBillingDetailsParams struct { + // Billing address. + Address *AddressParams `form:"address"` + // Email address. + Email *string `form:"email"` + // Full name. + Name *string `form:"name"` + // Billing phone number (including extension). + Phone *string `form:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID *string `form:"tax_id"` +} + +// If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. +type SetupIntentCreatePaymentMethodDataBLIKParams struct{} + +// If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. +type SetupIntentCreatePaymentMethodDataBoletoParams struct { + // The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + TaxID *string `form:"tax_id"` +} + +// If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. +type SetupIntentCreatePaymentMethodDataCashAppParams struct{} + +// If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. +type SetupIntentCreatePaymentMethodDataCryptoParams struct{} + +// If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. +type SetupIntentCreatePaymentMethodDataCustomerBalanceParams struct{} + +// If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. +type SetupIntentCreatePaymentMethodDataEPSParams struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. +type SetupIntentCreatePaymentMethodDataFPXParams struct { + // Account holder type for FPX transaction + AccountHolderType *string `form:"account_holder_type"` + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. +type SetupIntentCreatePaymentMethodDataGiropayParams struct{} + +// If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. +type SetupIntentCreatePaymentMethodDataGrabpayParams struct{} + +// If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. +type SetupIntentCreatePaymentMethodDataIDEALParams struct { + // The customer's bank. Only use this parameter for existing customers. Don't use it for new customers. + Bank *string `form:"bank"` +} + +// If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. +type SetupIntentCreatePaymentMethodDataInteracPresentParams struct{} + +// If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. +type SetupIntentCreatePaymentMethodDataKakaoPayParams struct{} + +// Customer's date of birth +type SetupIntentCreatePaymentMethodDataKlarnaDOBParams struct { + // The day of birth, between 1 and 31. + Day *int64 `form:"day"` + // The month of birth, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of birth. + Year *int64 `form:"year"` +} + +// If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. +type SetupIntentCreatePaymentMethodDataKlarnaParams struct { + // Customer's date of birth + DOB *SetupIntentCreatePaymentMethodDataKlarnaDOBParams `form:"dob"` +} + +// If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. +type SetupIntentCreatePaymentMethodDataKonbiniParams struct{} + +// If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. +type SetupIntentCreatePaymentMethodDataKrCardParams struct{} + +// If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. +type SetupIntentCreatePaymentMethodDataLinkParams struct{} + +// If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. +type SetupIntentCreatePaymentMethodDataMobilepayParams struct{} + +// If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. +type SetupIntentCreatePaymentMethodDataMultibancoParams struct{} + +// If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. +type SetupIntentCreatePaymentMethodDataNaverPayParams struct { + // Whether to use Naver Pay points or a card to fund this transaction. If not provided, this defaults to `card`. + Funding *string `form:"funding"` +} + +// If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. +type SetupIntentCreatePaymentMethodDataNzBankAccountParams struct { + // The name on the bank account. Only required if the account holder name is different from the name of the authorized signatory collected in the PaymentMethod's billing details. + AccountHolderName *string `form:"account_holder_name"` + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // The numeric code for the bank account's bank. + BankCode *string `form:"bank_code"` + // The numeric code for the bank account's bank branch. + BranchCode *string `form:"branch_code"` + Reference *string `form:"reference"` + // The suffix of the bank account number. + Suffix *string `form:"suffix"` +} + +// If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. +type SetupIntentCreatePaymentMethodDataOXXOParams struct{} + +// If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. +type SetupIntentCreatePaymentMethodDataP24Params struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. +type SetupIntentCreatePaymentMethodDataPayByBankParams struct{} + +// If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. +type SetupIntentCreatePaymentMethodDataPaycoParams struct{} + +// If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. +type SetupIntentCreatePaymentMethodDataPayNowParams struct{} + +// If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. +type SetupIntentCreatePaymentMethodDataPaypalParams struct{} + +// If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. +type SetupIntentCreatePaymentMethodDataPixParams struct{} + +// If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. +type SetupIntentCreatePaymentMethodDataPromptPayParams struct{} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type SetupIntentCreatePaymentMethodDataRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. +type SetupIntentCreatePaymentMethodDataRevolutPayParams struct{} + +// If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. +type SetupIntentCreatePaymentMethodDataSamsungPayParams struct{} + +// If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. +type SetupIntentCreatePaymentMethodDataSatispayParams struct{} + +// If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. +type SetupIntentCreatePaymentMethodDataSEPADebitParams struct { + // IBAN of the bank account. + IBAN *string `form:"iban"` +} + +// If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. +type SetupIntentCreatePaymentMethodDataSofortParams struct { + // Two-letter ISO code representing the country the bank account is located in. + Country *string `form:"country"` +} + +// If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. +type SetupIntentCreatePaymentMethodDataSwishParams struct{} + +// If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. +type SetupIntentCreatePaymentMethodDataTWINTParams struct{} + +// If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. +type SetupIntentCreatePaymentMethodDataUSBankAccountParams struct { + // Account holder type: individual or company. + AccountHolderType *string `form:"account_holder_type"` + // Account number of the bank account. + AccountNumber *string `form:"account_number"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType *string `form:"account_type"` + // The ID of a Financial Connections Account to use as a payment method. + FinancialConnectionsAccount *string `form:"financial_connections_account"` + // Routing number of the bank account. + RoutingNumber *string `form:"routing_number"` +} + +// If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. +type SetupIntentCreatePaymentMethodDataWeChatPayParams struct{} + +// If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. +type SetupIntentCreatePaymentMethodDataZipParams struct{} + +// When included, this hash creates a PaymentMethod that is set as the [`payment_method`](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-payment_method) +// value in the SetupIntent. +type SetupIntentCreatePaymentMethodDataParams struct { + // If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + ACSSDebit *SetupIntentCreatePaymentMethodDataACSSDebitParams `form:"acss_debit"` + // If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + Affirm *SetupIntentCreatePaymentMethodDataAffirmParams `form:"affirm"` + // If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + AfterpayClearpay *SetupIntentCreatePaymentMethodDataAfterpayClearpayParams `form:"afterpay_clearpay"` + // If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + Alipay *SetupIntentCreatePaymentMethodDataAlipayParams `form:"alipay"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to `unspecified`. + AllowRedisplay *string `form:"allow_redisplay"` + // If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. + Alma *SetupIntentCreatePaymentMethodDataAlmaParams `form:"alma"` + // If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. + AmazonPay *SetupIntentCreatePaymentMethodDataAmazonPayParams `form:"amazon_pay"` + // If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + AUBECSDebit *SetupIntentCreatePaymentMethodDataAUBECSDebitParams `form:"au_becs_debit"` + // If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + BACSDebit *SetupIntentCreatePaymentMethodDataBACSDebitParams `form:"bacs_debit"` + // If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + Bancontact *SetupIntentCreatePaymentMethodDataBancontactParams `form:"bancontact"` + // If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. + Billie *SetupIntentCreatePaymentMethodDataBillieParams `form:"billie"` + // Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + BillingDetails *SetupIntentCreatePaymentMethodDataBillingDetailsParams `form:"billing_details"` + // If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + BLIK *SetupIntentCreatePaymentMethodDataBLIKParams `form:"blik"` + // If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + Boleto *SetupIntentCreatePaymentMethodDataBoletoParams `form:"boleto"` + // If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + CashApp *SetupIntentCreatePaymentMethodDataCashAppParams `form:"cashapp"` + // If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. + Crypto *SetupIntentCreatePaymentMethodDataCryptoParams `form:"crypto"` + // If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + CustomerBalance *SetupIntentCreatePaymentMethodDataCustomerBalanceParams `form:"customer_balance"` + // If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + EPS *SetupIntentCreatePaymentMethodDataEPSParams `form:"eps"` + // If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + FPX *SetupIntentCreatePaymentMethodDataFPXParams `form:"fpx"` + // If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + Giropay *SetupIntentCreatePaymentMethodDataGiropayParams `form:"giropay"` + // If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + Grabpay *SetupIntentCreatePaymentMethodDataGrabpayParams `form:"grabpay"` + // If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + IDEAL *SetupIntentCreatePaymentMethodDataIDEALParams `form:"ideal"` + // If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + InteracPresent *SetupIntentCreatePaymentMethodDataInteracPresentParams `form:"interac_present"` + // If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. + KakaoPay *SetupIntentCreatePaymentMethodDataKakaoPayParams `form:"kakao_pay"` + // If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + Klarna *SetupIntentCreatePaymentMethodDataKlarnaParams `form:"klarna"` + // If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + Konbini *SetupIntentCreatePaymentMethodDataKonbiniParams `form:"konbini"` + // If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. + KrCard *SetupIntentCreatePaymentMethodDataKrCardParams `form:"kr_card"` + // If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + Link *SetupIntentCreatePaymentMethodDataLinkParams `form:"link"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. + Mobilepay *SetupIntentCreatePaymentMethodDataMobilepayParams `form:"mobilepay"` + // If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. + Multibanco *SetupIntentCreatePaymentMethodDataMultibancoParams `form:"multibanco"` + // If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. + NaverPay *SetupIntentCreatePaymentMethodDataNaverPayParams `form:"naver_pay"` + // If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. + NzBankAccount *SetupIntentCreatePaymentMethodDataNzBankAccountParams `form:"nz_bank_account"` + // If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + OXXO *SetupIntentCreatePaymentMethodDataOXXOParams `form:"oxxo"` + // If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + P24 *SetupIntentCreatePaymentMethodDataP24Params `form:"p24"` + // If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. + PayByBank *SetupIntentCreatePaymentMethodDataPayByBankParams `form:"pay_by_bank"` + // If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. + Payco *SetupIntentCreatePaymentMethodDataPaycoParams `form:"payco"` + // If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + PayNow *SetupIntentCreatePaymentMethodDataPayNowParams `form:"paynow"` + // If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + Paypal *SetupIntentCreatePaymentMethodDataPaypalParams `form:"paypal"` + // If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + Pix *SetupIntentCreatePaymentMethodDataPixParams `form:"pix"` + // If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + PromptPay *SetupIntentCreatePaymentMethodDataPromptPayParams `form:"promptpay"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *SetupIntentCreatePaymentMethodDataRadarOptionsParams `form:"radar_options"` + // If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + RevolutPay *SetupIntentCreatePaymentMethodDataRevolutPayParams `form:"revolut_pay"` + // If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. + SamsungPay *SetupIntentCreatePaymentMethodDataSamsungPayParams `form:"samsung_pay"` + // If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. + Satispay *SetupIntentCreatePaymentMethodDataSatispayParams `form:"satispay"` + // If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + SEPADebit *SetupIntentCreatePaymentMethodDataSEPADebitParams `form:"sepa_debit"` + // If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + Sofort *SetupIntentCreatePaymentMethodDataSofortParams `form:"sofort"` + // If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. + Swish *SetupIntentCreatePaymentMethodDataSwishParams `form:"swish"` + // If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. + TWINT *SetupIntentCreatePaymentMethodDataTWINTParams `form:"twint"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type *string `form:"type"` + // If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + USBankAccount *SetupIntentCreatePaymentMethodDataUSBankAccountParams `form:"us_bank_account"` + // If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + WeChatPay *SetupIntentCreatePaymentMethodDataWeChatPayParams `form:"wechat_pay"` + // If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + Zip *SetupIntentCreatePaymentMethodDataZipParams `form:"zip"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SetupIntentCreatePaymentMethodDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Additional fields for Mandate creation +type SetupIntentCreatePaymentMethodOptionsACSSDebitMandateOptionsParams struct { + // A URL for custom mandate text to render during confirmation step. + // The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + // or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + CustomMandateURL *string `form:"custom_mandate_url"` + // List of Stripe products where this mandate can be selected automatically. + DefaultFor []*string `form:"default_for"` + // Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + IntervalDescription *string `form:"interval_description"` + // Payment schedule for the mandate. + PaymentSchedule *string `form:"payment_schedule"` + // Transaction type of the mandate. + TransactionType *string `form:"transaction_type"` +} + +// If this is a `acss_debit` SetupIntent, this sub-hash contains details about the ACSS Debit payment method options. +type SetupIntentCreatePaymentMethodOptionsACSSDebitParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Additional fields for Mandate creation + MandateOptions *SetupIntentCreatePaymentMethodOptionsACSSDebitMandateOptionsParams `form:"mandate_options"` + // Bank account verification method. + VerificationMethod *string `form:"verification_method"` +} + +// If this is a `amazon_pay` SetupIntent, this sub-hash contains details about the AmazonPay payment method options. +type SetupIntentCreatePaymentMethodOptionsAmazonPayParams struct{} + +// Additional fields for Mandate creation +type SetupIntentCreatePaymentMethodOptionsBACSDebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'DDIC' or 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// If this is a `bacs_debit` SetupIntent, this sub-hash contains details about the Bacs Debit payment method options. +type SetupIntentCreatePaymentMethodOptionsBACSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *SetupIntentCreatePaymentMethodOptionsBACSDebitMandateOptionsParams `form:"mandate_options"` +} + +// Configuration options for setting up an eMandate for cards issued in India. +type SetupIntentCreatePaymentMethodOptionsCardMandateOptionsParams struct { + // Amount to be charged for future payments. + Amount *int64 `form:"amount"` + // One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + AmountType *string `form:"amount_type"` + // Currency in which future payments will be charged. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // A description of the mandate or subscription that is meant to be displayed to the customer. + Description *string `form:"description"` + // End date of the mandate or subscription. If not provided, the mandate will be active until canceled. If provided, end date should be after start date. + EndDate *int64 `form:"end_date"` + // Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. + Interval *string `form:"interval"` + // The number of intervals between payments. For example, `interval=month` and `interval_count=3` indicates one payment every three months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). This parameter is optional when `interval=sporadic`. + IntervalCount *int64 `form:"interval_count"` + // Unique identifier for the mandate or subscription. + Reference *string `form:"reference"` + // Start date of the mandate or subscription. Start date should not be lesser than yesterday. + StartDate *int64 `form:"start_date"` + // Specifies the type of mandates supported. Possible values are `india`. + SupportedTypes []*string `form:"supported_types"` +} + +// Cartes Bancaires-specific 3DS fields. +type SetupIntentCreatePaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancairesParams struct { + // The cryptogram calculation algorithm used by the card Issuer's ACS + // to calculate the Authentication cryptogram. Also known as `cavvAlgorithm`. + // messageExtension: CB-AVALGO + CbAvalgo *string `form:"cb_avalgo"` + // The exemption indicator returned from Cartes Bancaires in the ARes. + // message extension: CB-EXEMPTION; string (4 characters) + // This is a 3 byte bitmap (low significant byte first and most significant + // bit first) that has been Base64 encoded + CbExemption *string `form:"cb_exemption"` + // The risk score returned from Cartes Bancaires in the ARes. + // message extension: CB-SCORE; numeric value 0-99 + CbScore *int64 `form:"cb_score"` +} + +// Network specific 3DS fields. Network specific arguments require an +// explicit card brand choice. The parameter `payment_method_options.card.network“ +// must be populated accordingly +type SetupIntentCreatePaymentMethodOptionsCardThreeDSecureNetworkOptionsParams struct { + // Cartes Bancaires-specific 3DS fields. + CartesBancaires *SetupIntentCreatePaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancairesParams `form:"cartes_bancaires"` +} + +// If 3D Secure authentication was performed with a third-party provider, +// the authentication details to use for this setup. +type SetupIntentCreatePaymentMethodOptionsCardThreeDSecureParams struct { + // The `transStatus` returned from the card Issuer's ACS in the ARes. + AresTransStatus *string `form:"ares_trans_status"` + // The cryptogram, also known as the "authentication value" (AAV, CAVV or + // AEVV). This value is 20 bytes, base64-encoded into a 28-character string. + // (Most 3D Secure providers will return the base64-encoded version, which + // is what you should specify here.) + Cryptogram *string `form:"cryptogram"` + // The Electronic Commerce Indicator (ECI) is returned by your 3D Secure + // provider and indicates what degree of authentication was performed. + ElectronicCommerceIndicator *string `form:"electronic_commerce_indicator"` + // Network specific 3DS fields. Network specific arguments require an + // explicit card brand choice. The parameter `payment_method_options.card.network`` + // must be populated accordingly + NetworkOptions *SetupIntentCreatePaymentMethodOptionsCardThreeDSecureNetworkOptionsParams `form:"network_options"` + // The challenge indicator (`threeDSRequestorChallengeInd`) which was requested in the + // AReq sent to the card Issuer's ACS. A string containing 2 digits from 01-99. + RequestorChallengeIndicator *string `form:"requestor_challenge_indicator"` + // For 3D Secure 1, the XID. For 3D Secure 2, the Directory Server + // Transaction ID (dsTransID). + TransactionID *string `form:"transaction_id"` + // The version of 3D Secure that was performed. + Version *string `form:"version"` +} + +// Configuration for any card setup attempted on this SetupIntent. +type SetupIntentCreatePaymentMethodOptionsCardParams struct { + // Configuration options for setting up an eMandate for cards issued in India. + MandateOptions *SetupIntentCreatePaymentMethodOptionsCardMandateOptionsParams `form:"mandate_options"` + // When specified, this parameter signals that a card has been collected + // as MOTO (Mail Order Telephone Order) and thus out of scope for SCA. This + // parameter can only be provided during confirmation. + MOTO *bool `form:"moto"` + // Selected network to process this SetupIntent on. Depends on the available networks of the card attached to the SetupIntent. Can be only set confirm-time. + Network *string `form:"network"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure *string `form:"request_three_d_secure"` + // If 3D Secure authentication was performed with a third-party provider, + // the authentication details to use for this setup. + ThreeDSecure *SetupIntentCreatePaymentMethodOptionsCardThreeDSecureParams `form:"three_d_secure"` +} + +// If this is a `card_present` PaymentMethod, this sub-hash contains details about the card-present payment method options. +type SetupIntentCreatePaymentMethodOptionsCardPresentParams struct{} + +// On-demand details if setting up a payment method for on-demand payments. +type SetupIntentCreatePaymentMethodOptionsKlarnaOnDemandParams struct { + // Your average amount value. You can use a value across your customer base, or segment based on customer type, country, etc. + AverageAmount *int64 `form:"average_amount"` + // The maximum value you may charge a customer per purchase. You can use a value across your customer base, or segment based on customer type, country, etc. + MaximumAmount *int64 `form:"maximum_amount"` + // The lowest or minimum value you may charge a customer per purchase. You can use a value across your customer base, or segment based on customer type, country, etc. + MinimumAmount *int64 `form:"minimum_amount"` + // Interval at which the customer is making purchases + PurchaseInterval *string `form:"purchase_interval"` + // The number of `purchase_interval` between charges + PurchaseIntervalCount *int64 `form:"purchase_interval_count"` +} + +// Describes the upcoming charge for this subscription. +type SetupIntentCreatePaymentMethodOptionsKlarnaSubscriptionNextBillingParams struct { + // The amount of the next charge for the subscription. + Amount *int64 `form:"amount"` + // The date of the next charge for the subscription in YYYY-MM-DD format. + Date *string `form:"date"` +} + +// Subscription details if setting up or charging a subscription +type SetupIntentCreatePaymentMethodOptionsKlarnaSubscriptionParams struct { + // Unit of time between subscription charges. + Interval *string `form:"interval"` + // The number of intervals (specified in the `interval` attribute) between subscription charges. For example, `interval=month` and `interval_count=3` charges every 3 months. + IntervalCount *int64 `form:"interval_count"` + // Name for subscription. + Name *string `form:"name"` + // Describes the upcoming charge for this subscription. + NextBilling *SetupIntentCreatePaymentMethodOptionsKlarnaSubscriptionNextBillingParams `form:"next_billing"` + // A non-customer-facing reference to correlate subscription charges in the Klarna app. Use a value that persists across subscription charges. + Reference *string `form:"reference"` +} + +// If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method options. +type SetupIntentCreatePaymentMethodOptionsKlarnaParams struct { + // The currency of the SetupIntent. Three letter ISO currency code. + Currency *string `form:"currency"` + // On-demand details if setting up a payment method for on-demand payments. + OnDemand *SetupIntentCreatePaymentMethodOptionsKlarnaOnDemandParams `form:"on_demand"` + // Preferred language of the Klarna authorization page that the customer is redirected to + PreferredLocale *string `form:"preferred_locale"` + // Subscription details if setting up or charging a subscription + Subscriptions []*SetupIntentCreatePaymentMethodOptionsKlarnaSubscriptionParams `form:"subscriptions"` +} + +// If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. +type SetupIntentCreatePaymentMethodOptionsLinkParams struct { + // [Deprecated] This is a legacy parameter that no longer has any function. + // Deprecated: + PersistentToken *string `form:"persistent_token"` +} + +// If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. +type SetupIntentCreatePaymentMethodOptionsPaypalParams struct { + // The PayPal Billing Agreement ID (BAID). This is an ID generated by PayPal which represents the mandate between the merchant and the customer. + BillingAgreementID *string `form:"billing_agreement_id"` +} + +// Additional fields for Mandate creation +type SetupIntentCreatePaymentMethodOptionsSEPADebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// If this is a `sepa_debit` SetupIntent, this sub-hash contains details about the SEPA Debit payment method options. +type SetupIntentCreatePaymentMethodOptionsSEPADebitParams struct { + // Additional fields for Mandate creation + MandateOptions *SetupIntentCreatePaymentMethodOptionsSEPADebitMandateOptionsParams `form:"mandate_options"` +} + +// Provide filters for the linked accounts that the customer can select for the payment method. +type SetupIntentCreatePaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams struct { + // The account subcategories to use to filter for selectable accounts. Valid subcategories are `checking` and `savings`. + AccountSubcategories []*string `form:"account_subcategories"` +} + +// Additional fields for Financial Connections Session creation +type SetupIntentCreatePaymentMethodOptionsUSBankAccountFinancialConnectionsParams struct { + // Provide filters for the linked accounts that the customer can select for the payment method. + Filters *SetupIntentCreatePaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams `form:"filters"` + // The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` + // For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + ReturnURL *string `form:"return_url"` +} + +// Additional fields for Mandate creation +type SetupIntentCreatePaymentMethodOptionsUSBankAccountMandateOptionsParams struct { + // The method used to collect offline mandate customer acceptance. + CollectionMethod *string `form:"collection_method"` +} + +// Additional fields for network related functions +type SetupIntentCreatePaymentMethodOptionsUSBankAccountNetworksParams struct { + // Triggers validations to run across the selected networks + Requested []*string `form:"requested"` +} + +// If this is a `us_bank_account` SetupIntent, this sub-hash contains details about the US bank account payment method options. +type SetupIntentCreatePaymentMethodOptionsUSBankAccountParams struct { + // Additional fields for Financial Connections Session creation + FinancialConnections *SetupIntentCreatePaymentMethodOptionsUSBankAccountFinancialConnectionsParams `form:"financial_connections"` + // Additional fields for Mandate creation + MandateOptions *SetupIntentCreatePaymentMethodOptionsUSBankAccountMandateOptionsParams `form:"mandate_options"` + // Additional fields for network related functions + Networks *SetupIntentCreatePaymentMethodOptionsUSBankAccountNetworksParams `form:"networks"` + // Bank account verification method. + VerificationMethod *string `form:"verification_method"` +} + +// Payment method-specific configuration for this SetupIntent. +type SetupIntentCreatePaymentMethodOptionsParams struct { + // If this is a `acss_debit` SetupIntent, this sub-hash contains details about the ACSS Debit payment method options. + ACSSDebit *SetupIntentCreatePaymentMethodOptionsACSSDebitParams `form:"acss_debit"` + // If this is a `amazon_pay` SetupIntent, this sub-hash contains details about the AmazonPay payment method options. + AmazonPay *SetupIntentCreatePaymentMethodOptionsAmazonPayParams `form:"amazon_pay"` + // If this is a `bacs_debit` SetupIntent, this sub-hash contains details about the Bacs Debit payment method options. + BACSDebit *SetupIntentCreatePaymentMethodOptionsBACSDebitParams `form:"bacs_debit"` + // Configuration for any card setup attempted on this SetupIntent. + Card *SetupIntentCreatePaymentMethodOptionsCardParams `form:"card"` + // If this is a `card_present` PaymentMethod, this sub-hash contains details about the card-present payment method options. + CardPresent *SetupIntentCreatePaymentMethodOptionsCardPresentParams `form:"card_present"` + // If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method options. + Klarna *SetupIntentCreatePaymentMethodOptionsKlarnaParams `form:"klarna"` + // If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. + Link *SetupIntentCreatePaymentMethodOptionsLinkParams `form:"link"` + // If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. + Paypal *SetupIntentCreatePaymentMethodOptionsPaypalParams `form:"paypal"` + // If this is a `sepa_debit` SetupIntent, this sub-hash contains details about the SEPA Debit payment method options. + SEPADebit *SetupIntentCreatePaymentMethodOptionsSEPADebitParams `form:"sepa_debit"` + // If this is a `us_bank_account` SetupIntent, this sub-hash contains details about the US bank account payment method options. + USBankAccount *SetupIntentCreatePaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` +} + +// If you populate this hash, this SetupIntent generates a `single_use` mandate after successful completion. +// +// Single-use mandates are only valid for the following payment methods: `acss_debit`, `alipay`, `au_becs_debit`, `bacs_debit`, `bancontact`, `boleto`, `ideal`, `link`, `sepa_debit`, and `us_bank_account`. +type SetupIntentCreateSingleUseParams struct { + // Amount the customer is granting permission to collect later. A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` +} + +// Creates a SetupIntent object. +// +// After you create the SetupIntent, attach a payment method and [confirm](https://docs.stripe.com/docs/api/setup_intents/confirm) +// it to collect any required permissions to charge the payment method later. +type SetupIntentCreateParams struct { + Params `form:"*"` + // If present, the SetupIntent's payment method will be attached to the in-context Stripe Account. + // + // It can only be used for this Stripe Account's own money movement flows like InboundTransfer and OutboundTransfers. It cannot be set to true when setting up a PaymentMethod for a Customer, and defaults to false when attaching a PaymentMethod to a Customer. + AttachToSelf *bool `form:"attach_to_self"` + // When you enable this parameter, this SetupIntent accepts payment methods that you enable in the Dashboard and that are compatible with its other parameters. + AutomaticPaymentMethods *SetupIntentCreateAutomaticPaymentMethodsParams `form:"automatic_payment_methods"` + // Set to `true` to attempt to confirm this SetupIntent immediately. This parameter defaults to `false`. If a card is the attached payment method, you can provide a `return_url` in case further authentication is necessary. + Confirm *bool `form:"confirm"` + // ID of the ConfirmationToken used to confirm this SetupIntent. + // + // If the provided ConfirmationToken contains properties that are also being provided in this request, such as `payment_method`, then the values in this request will take precedence. + ConfirmationToken *string `form:"confirmation_token"` + // ID of the Customer this SetupIntent belongs to, if one exists. + // + // If present, the SetupIntent's payment method will be attached to the Customer on successful setup. Payment methods attached to other Customers cannot be used with this SetupIntent. + Customer *string `form:"customer"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Indicates the directions of money movement for which this payment method is intended to be used. + // + // Include `inbound` if you intend to use the payment method as the origin to pull funds from. Include `outbound` if you intend to use the payment method as the destination to send funds to. You can include both if you intend to use the payment method for both purposes. + FlowDirections []*string `form:"flow_directions"` + // This hash contains details about the mandate to create. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/setup_intents/create#create_setup_intent-confirm). + MandateData *SetupIntentCreateMandateDataParams `form:"mandate_data"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The Stripe account ID created for this SetupIntent. + OnBehalfOf *string `form:"on_behalf_of"` + // ID of the payment method (a PaymentMethod, Card, or saved Source object) to attach to this SetupIntent. + PaymentMethod *string `form:"payment_method"` + // The ID of the [payment method configuration](https://stripe.com/docs/api/payment_method_configurations) to use with this SetupIntent. + PaymentMethodConfiguration *string `form:"payment_method_configuration"` + // When included, this hash creates a PaymentMethod that is set as the [`payment_method`](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-payment_method) + // value in the SetupIntent. + PaymentMethodData *SetupIntentCreatePaymentMethodDataParams `form:"payment_method_data"` + // Payment method-specific configuration for this SetupIntent. + PaymentMethodOptions *SetupIntentCreatePaymentMethodOptionsParams `form:"payment_method_options"` + // The list of payment method types (for example, card) that this SetupIntent can use. If you don't provide this, Stripe will dynamically show relevant payment methods from your [payment method settings](https://dashboard.stripe.com/settings/payment_methods). A list of valid payment method types can be found [here](https://docs.stripe.com/api/payment_methods/object#payment_method_object-type). + PaymentMethodTypes []*string `form:"payment_method_types"` + // The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method's app or site. To redirect to a mobile application, you can alternatively supply an application URI scheme. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/setup_intents/create#create_setup_intent-confirm). + ReturnURL *string `form:"return_url"` + // If you populate this hash, this SetupIntent generates a `single_use` mandate after successful completion. + // + // Single-use mandates are only valid for the following payment methods: `acss_debit`, `alipay`, `au_becs_debit`, `bacs_debit`, `bancontact`, `boleto`, `ideal`, `link`, `sepa_debit`, and `us_bank_account`. + SingleUse *SetupIntentCreateSingleUseParams `form:"single_use"` + // Indicates how the payment method is intended to be used in the future. If not provided, this value defaults to `off_session`. + Usage *string `form:"usage"` + // Set to `true` when confirming server-side and using Stripe.js, iOS, or Android client-side SDKs to handle the next actions. + UseStripeSDK *bool `form:"use_stripe_sdk"` +} + +// AddExpand appends a new field to expand. +func (p *SetupIntentCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SetupIntentCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the details of a SetupIntent that has previously been created. +// +// Client-side retrieval using a publishable key is allowed when the client_secret is provided in the query string. +// +// When retrieved with a publishable key, only a subset of properties will be returned. Please refer to the [SetupIntent](https://docs.stripe.com/api#setup_intent_object) object reference for more details. +type SetupIntentRetrieveParams struct { + Params `form:"*"` + // The client secret of the SetupIntent. We require this string if you use a publishable key to retrieve the SetupIntent. + ClientSecret *string `form:"client_secret"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *SetupIntentRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. +type SetupIntentUpdatePaymentMethodDataACSSDebitParams struct { + // Customer's bank account number. + AccountNumber *string `form:"account_number"` + // Institution number of the customer's bank. + InstitutionNumber *string `form:"institution_number"` + // Transit number of the customer's bank. + TransitNumber *string `form:"transit_number"` +} + +// If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. +type SetupIntentUpdatePaymentMethodDataAffirmParams struct{} + +// If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. +type SetupIntentUpdatePaymentMethodDataAfterpayClearpayParams struct{} + +// If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. +type SetupIntentUpdatePaymentMethodDataAlipayParams struct{} + +// If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. +type SetupIntentUpdatePaymentMethodDataAlmaParams struct{} + +// If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. +type SetupIntentUpdatePaymentMethodDataAmazonPayParams struct{} + +// If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. +type SetupIntentUpdatePaymentMethodDataAUBECSDebitParams struct { + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // Bank-State-Branch number of the bank account. + BSBNumber *string `form:"bsb_number"` +} + +// If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. +type SetupIntentUpdatePaymentMethodDataBACSDebitParams struct { + // Account number of the bank account that the funds will be debited from. + AccountNumber *string `form:"account_number"` + // Sort code of the bank account. (e.g., `10-20-30`) + SortCode *string `form:"sort_code"` +} + +// If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. +type SetupIntentUpdatePaymentMethodDataBancontactParams struct{} + +// If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. +type SetupIntentUpdatePaymentMethodDataBillieParams struct{} + +// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. +type SetupIntentUpdatePaymentMethodDataBillingDetailsParams struct { + // Billing address. + Address *AddressParams `form:"address"` + // Email address. + Email *string `form:"email"` + // Full name. + Name *string `form:"name"` + // Billing phone number (including extension). + Phone *string `form:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID *string `form:"tax_id"` +} + +// If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. +type SetupIntentUpdatePaymentMethodDataBLIKParams struct{} + +// If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. +type SetupIntentUpdatePaymentMethodDataBoletoParams struct { + // The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + TaxID *string `form:"tax_id"` +} + +// If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. +type SetupIntentUpdatePaymentMethodDataCashAppParams struct{} + +// If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. +type SetupIntentUpdatePaymentMethodDataCryptoParams struct{} + +// If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. +type SetupIntentUpdatePaymentMethodDataCustomerBalanceParams struct{} + +// If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. +type SetupIntentUpdatePaymentMethodDataEPSParams struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. +type SetupIntentUpdatePaymentMethodDataFPXParams struct { + // Account holder type for FPX transaction + AccountHolderType *string `form:"account_holder_type"` + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. +type SetupIntentUpdatePaymentMethodDataGiropayParams struct{} + +// If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. +type SetupIntentUpdatePaymentMethodDataGrabpayParams struct{} + +// If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. +type SetupIntentUpdatePaymentMethodDataIDEALParams struct { + // The customer's bank. Only use this parameter for existing customers. Don't use it for new customers. + Bank *string `form:"bank"` +} + +// If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. +type SetupIntentUpdatePaymentMethodDataInteracPresentParams struct{} + +// If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. +type SetupIntentUpdatePaymentMethodDataKakaoPayParams struct{} + +// Customer's date of birth +type SetupIntentUpdatePaymentMethodDataKlarnaDOBParams struct { + // The day of birth, between 1 and 31. + Day *int64 `form:"day"` + // The month of birth, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of birth. + Year *int64 `form:"year"` +} + +// If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. +type SetupIntentUpdatePaymentMethodDataKlarnaParams struct { + // Customer's date of birth + DOB *SetupIntentUpdatePaymentMethodDataKlarnaDOBParams `form:"dob"` +} + +// If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. +type SetupIntentUpdatePaymentMethodDataKonbiniParams struct{} + +// If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. +type SetupIntentUpdatePaymentMethodDataKrCardParams struct{} + +// If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. +type SetupIntentUpdatePaymentMethodDataLinkParams struct{} + +// If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. +type SetupIntentUpdatePaymentMethodDataMobilepayParams struct{} + +// If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. +type SetupIntentUpdatePaymentMethodDataMultibancoParams struct{} + +// If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. +type SetupIntentUpdatePaymentMethodDataNaverPayParams struct { + // Whether to use Naver Pay points or a card to fund this transaction. If not provided, this defaults to `card`. + Funding *string `form:"funding"` +} + +// If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. +type SetupIntentUpdatePaymentMethodDataNzBankAccountParams struct { + // The name on the bank account. Only required if the account holder name is different from the name of the authorized signatory collected in the PaymentMethod's billing details. + AccountHolderName *string `form:"account_holder_name"` + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // The numeric code for the bank account's bank. + BankCode *string `form:"bank_code"` + // The numeric code for the bank account's bank branch. + BranchCode *string `form:"branch_code"` + Reference *string `form:"reference"` + // The suffix of the bank account number. + Suffix *string `form:"suffix"` +} + +// If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. +type SetupIntentUpdatePaymentMethodDataOXXOParams struct{} + +// If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. +type SetupIntentUpdatePaymentMethodDataP24Params struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. +type SetupIntentUpdatePaymentMethodDataPayByBankParams struct{} + +// If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. +type SetupIntentUpdatePaymentMethodDataPaycoParams struct{} + +// If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. +type SetupIntentUpdatePaymentMethodDataPayNowParams struct{} + +// If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. +type SetupIntentUpdatePaymentMethodDataPaypalParams struct{} + +// If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. +type SetupIntentUpdatePaymentMethodDataPixParams struct{} + +// If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. +type SetupIntentUpdatePaymentMethodDataPromptPayParams struct{} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type SetupIntentUpdatePaymentMethodDataRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. +type SetupIntentUpdatePaymentMethodDataRevolutPayParams struct{} + +// If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. +type SetupIntentUpdatePaymentMethodDataSamsungPayParams struct{} + +// If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. +type SetupIntentUpdatePaymentMethodDataSatispayParams struct{} + +// If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. +type SetupIntentUpdatePaymentMethodDataSEPADebitParams struct { + // IBAN of the bank account. + IBAN *string `form:"iban"` +} + +// If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. +type SetupIntentUpdatePaymentMethodDataSofortParams struct { + // Two-letter ISO code representing the country the bank account is located in. + Country *string `form:"country"` +} + +// If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. +type SetupIntentUpdatePaymentMethodDataSwishParams struct{} + +// If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. +type SetupIntentUpdatePaymentMethodDataTWINTParams struct{} + +// If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. +type SetupIntentUpdatePaymentMethodDataUSBankAccountParams struct { + // Account holder type: individual or company. + AccountHolderType *string `form:"account_holder_type"` + // Account number of the bank account. + AccountNumber *string `form:"account_number"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType *string `form:"account_type"` + // The ID of a Financial Connections Account to use as a payment method. + FinancialConnectionsAccount *string `form:"financial_connections_account"` + // Routing number of the bank account. + RoutingNumber *string `form:"routing_number"` +} + +// If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. +type SetupIntentUpdatePaymentMethodDataWeChatPayParams struct{} + +// If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. +type SetupIntentUpdatePaymentMethodDataZipParams struct{} + +// When included, this hash creates a PaymentMethod that is set as the [`payment_method`](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-payment_method) +// value in the SetupIntent. +type SetupIntentUpdatePaymentMethodDataParams struct { + // If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + ACSSDebit *SetupIntentUpdatePaymentMethodDataACSSDebitParams `form:"acss_debit"` + // If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + Affirm *SetupIntentUpdatePaymentMethodDataAffirmParams `form:"affirm"` + // If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + AfterpayClearpay *SetupIntentUpdatePaymentMethodDataAfterpayClearpayParams `form:"afterpay_clearpay"` + // If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + Alipay *SetupIntentUpdatePaymentMethodDataAlipayParams `form:"alipay"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to `unspecified`. + AllowRedisplay *string `form:"allow_redisplay"` + // If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. + Alma *SetupIntentUpdatePaymentMethodDataAlmaParams `form:"alma"` + // If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. + AmazonPay *SetupIntentUpdatePaymentMethodDataAmazonPayParams `form:"amazon_pay"` + // If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + AUBECSDebit *SetupIntentUpdatePaymentMethodDataAUBECSDebitParams `form:"au_becs_debit"` + // If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + BACSDebit *SetupIntentUpdatePaymentMethodDataBACSDebitParams `form:"bacs_debit"` + // If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + Bancontact *SetupIntentUpdatePaymentMethodDataBancontactParams `form:"bancontact"` + // If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. + Billie *SetupIntentUpdatePaymentMethodDataBillieParams `form:"billie"` + // Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + BillingDetails *SetupIntentUpdatePaymentMethodDataBillingDetailsParams `form:"billing_details"` + // If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + BLIK *SetupIntentUpdatePaymentMethodDataBLIKParams `form:"blik"` + // If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + Boleto *SetupIntentUpdatePaymentMethodDataBoletoParams `form:"boleto"` + // If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + CashApp *SetupIntentUpdatePaymentMethodDataCashAppParams `form:"cashapp"` + // If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. + Crypto *SetupIntentUpdatePaymentMethodDataCryptoParams `form:"crypto"` + // If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + CustomerBalance *SetupIntentUpdatePaymentMethodDataCustomerBalanceParams `form:"customer_balance"` + // If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + EPS *SetupIntentUpdatePaymentMethodDataEPSParams `form:"eps"` + // If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + FPX *SetupIntentUpdatePaymentMethodDataFPXParams `form:"fpx"` + // If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + Giropay *SetupIntentUpdatePaymentMethodDataGiropayParams `form:"giropay"` + // If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + Grabpay *SetupIntentUpdatePaymentMethodDataGrabpayParams `form:"grabpay"` + // If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + IDEAL *SetupIntentUpdatePaymentMethodDataIDEALParams `form:"ideal"` + // If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + InteracPresent *SetupIntentUpdatePaymentMethodDataInteracPresentParams `form:"interac_present"` + // If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. + KakaoPay *SetupIntentUpdatePaymentMethodDataKakaoPayParams `form:"kakao_pay"` + // If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + Klarna *SetupIntentUpdatePaymentMethodDataKlarnaParams `form:"klarna"` + // If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + Konbini *SetupIntentUpdatePaymentMethodDataKonbiniParams `form:"konbini"` + // If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. + KrCard *SetupIntentUpdatePaymentMethodDataKrCardParams `form:"kr_card"` + // If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + Link *SetupIntentUpdatePaymentMethodDataLinkParams `form:"link"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. + Mobilepay *SetupIntentUpdatePaymentMethodDataMobilepayParams `form:"mobilepay"` + // If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. + Multibanco *SetupIntentUpdatePaymentMethodDataMultibancoParams `form:"multibanco"` + // If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. + NaverPay *SetupIntentUpdatePaymentMethodDataNaverPayParams `form:"naver_pay"` + // If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. + NzBankAccount *SetupIntentUpdatePaymentMethodDataNzBankAccountParams `form:"nz_bank_account"` + // If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + OXXO *SetupIntentUpdatePaymentMethodDataOXXOParams `form:"oxxo"` + // If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + P24 *SetupIntentUpdatePaymentMethodDataP24Params `form:"p24"` + // If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. + PayByBank *SetupIntentUpdatePaymentMethodDataPayByBankParams `form:"pay_by_bank"` + // If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. + Payco *SetupIntentUpdatePaymentMethodDataPaycoParams `form:"payco"` + // If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + PayNow *SetupIntentUpdatePaymentMethodDataPayNowParams `form:"paynow"` + // If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + Paypal *SetupIntentUpdatePaymentMethodDataPaypalParams `form:"paypal"` + // If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + Pix *SetupIntentUpdatePaymentMethodDataPixParams `form:"pix"` + // If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + PromptPay *SetupIntentUpdatePaymentMethodDataPromptPayParams `form:"promptpay"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *SetupIntentUpdatePaymentMethodDataRadarOptionsParams `form:"radar_options"` + // If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + RevolutPay *SetupIntentUpdatePaymentMethodDataRevolutPayParams `form:"revolut_pay"` + // If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. + SamsungPay *SetupIntentUpdatePaymentMethodDataSamsungPayParams `form:"samsung_pay"` + // If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. + Satispay *SetupIntentUpdatePaymentMethodDataSatispayParams `form:"satispay"` + // If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + SEPADebit *SetupIntentUpdatePaymentMethodDataSEPADebitParams `form:"sepa_debit"` + // If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + Sofort *SetupIntentUpdatePaymentMethodDataSofortParams `form:"sofort"` + // If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. + Swish *SetupIntentUpdatePaymentMethodDataSwishParams `form:"swish"` + // If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. + TWINT *SetupIntentUpdatePaymentMethodDataTWINTParams `form:"twint"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type *string `form:"type"` + // If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + USBankAccount *SetupIntentUpdatePaymentMethodDataUSBankAccountParams `form:"us_bank_account"` + // If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + WeChatPay *SetupIntentUpdatePaymentMethodDataWeChatPayParams `form:"wechat_pay"` + // If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + Zip *SetupIntentUpdatePaymentMethodDataZipParams `form:"zip"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SetupIntentUpdatePaymentMethodDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Additional fields for Mandate creation +type SetupIntentUpdatePaymentMethodOptionsACSSDebitMandateOptionsParams struct { + // A URL for custom mandate text to render during confirmation step. + // The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + // or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + CustomMandateURL *string `form:"custom_mandate_url"` + // List of Stripe products where this mandate can be selected automatically. + DefaultFor []*string `form:"default_for"` + // Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + IntervalDescription *string `form:"interval_description"` + // Payment schedule for the mandate. + PaymentSchedule *string `form:"payment_schedule"` + // Transaction type of the mandate. + TransactionType *string `form:"transaction_type"` +} + +// If this is a `acss_debit` SetupIntent, this sub-hash contains details about the ACSS Debit payment method options. +type SetupIntentUpdatePaymentMethodOptionsACSSDebitParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Additional fields for Mandate creation + MandateOptions *SetupIntentUpdatePaymentMethodOptionsACSSDebitMandateOptionsParams `form:"mandate_options"` + // Bank account verification method. + VerificationMethod *string `form:"verification_method"` +} + +// If this is a `amazon_pay` SetupIntent, this sub-hash contains details about the AmazonPay payment method options. +type SetupIntentUpdatePaymentMethodOptionsAmazonPayParams struct{} + +// Additional fields for Mandate creation +type SetupIntentUpdatePaymentMethodOptionsBACSDebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'DDIC' or 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// If this is a `bacs_debit` SetupIntent, this sub-hash contains details about the Bacs Debit payment method options. +type SetupIntentUpdatePaymentMethodOptionsBACSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *SetupIntentUpdatePaymentMethodOptionsBACSDebitMandateOptionsParams `form:"mandate_options"` +} + +// Configuration options for setting up an eMandate for cards issued in India. +type SetupIntentUpdatePaymentMethodOptionsCardMandateOptionsParams struct { + // Amount to be charged for future payments. + Amount *int64 `form:"amount"` + // One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + AmountType *string `form:"amount_type"` + // Currency in which future payments will be charged. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // A description of the mandate or subscription that is meant to be displayed to the customer. + Description *string `form:"description"` + // End date of the mandate or subscription. If not provided, the mandate will be active until canceled. If provided, end date should be after start date. + EndDate *int64 `form:"end_date"` + // Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. + Interval *string `form:"interval"` + // The number of intervals between payments. For example, `interval=month` and `interval_count=3` indicates one payment every three months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). This parameter is optional when `interval=sporadic`. + IntervalCount *int64 `form:"interval_count"` + // Unique identifier for the mandate or subscription. + Reference *string `form:"reference"` + // Start date of the mandate or subscription. Start date should not be lesser than yesterday. + StartDate *int64 `form:"start_date"` + // Specifies the type of mandates supported. Possible values are `india`. + SupportedTypes []*string `form:"supported_types"` +} + +// Cartes Bancaires-specific 3DS fields. +type SetupIntentUpdatePaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancairesParams struct { + // The cryptogram calculation algorithm used by the card Issuer's ACS + // to calculate the Authentication cryptogram. Also known as `cavvAlgorithm`. + // messageExtension: CB-AVALGO + CbAvalgo *string `form:"cb_avalgo"` + // The exemption indicator returned from Cartes Bancaires in the ARes. + // message extension: CB-EXEMPTION; string (4 characters) + // This is a 3 byte bitmap (low significant byte first and most significant + // bit first) that has been Base64 encoded + CbExemption *string `form:"cb_exemption"` + // The risk score returned from Cartes Bancaires in the ARes. + // message extension: CB-SCORE; numeric value 0-99 + CbScore *int64 `form:"cb_score"` +} + +// Network specific 3DS fields. Network specific arguments require an +// explicit card brand choice. The parameter `payment_method_options.card.network“ +// must be populated accordingly +type SetupIntentUpdatePaymentMethodOptionsCardThreeDSecureNetworkOptionsParams struct { + // Cartes Bancaires-specific 3DS fields. + CartesBancaires *SetupIntentUpdatePaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancairesParams `form:"cartes_bancaires"` +} + +// If 3D Secure authentication was performed with a third-party provider, +// the authentication details to use for this setup. +type SetupIntentUpdatePaymentMethodOptionsCardThreeDSecureParams struct { + // The `transStatus` returned from the card Issuer's ACS in the ARes. + AresTransStatus *string `form:"ares_trans_status"` + // The cryptogram, also known as the "authentication value" (AAV, CAVV or + // AEVV). This value is 20 bytes, base64-encoded into a 28-character string. + // (Most 3D Secure providers will return the base64-encoded version, which + // is what you should specify here.) + Cryptogram *string `form:"cryptogram"` + // The Electronic Commerce Indicator (ECI) is returned by your 3D Secure + // provider and indicates what degree of authentication was performed. + ElectronicCommerceIndicator *string `form:"electronic_commerce_indicator"` + // Network specific 3DS fields. Network specific arguments require an + // explicit card brand choice. The parameter `payment_method_options.card.network`` + // must be populated accordingly + NetworkOptions *SetupIntentUpdatePaymentMethodOptionsCardThreeDSecureNetworkOptionsParams `form:"network_options"` + // The challenge indicator (`threeDSRequestorChallengeInd`) which was requested in the + // AReq sent to the card Issuer's ACS. A string containing 2 digits from 01-99. + RequestorChallengeIndicator *string `form:"requestor_challenge_indicator"` + // For 3D Secure 1, the XID. For 3D Secure 2, the Directory Server + // Transaction ID (dsTransID). + TransactionID *string `form:"transaction_id"` + // The version of 3D Secure that was performed. + Version *string `form:"version"` +} + +// Configuration for any card setup attempted on this SetupIntent. +type SetupIntentUpdatePaymentMethodOptionsCardParams struct { + // Configuration options for setting up an eMandate for cards issued in India. + MandateOptions *SetupIntentUpdatePaymentMethodOptionsCardMandateOptionsParams `form:"mandate_options"` + // When specified, this parameter signals that a card has been collected + // as MOTO (Mail Order Telephone Order) and thus out of scope for SCA. This + // parameter can only be provided during confirmation. + MOTO *bool `form:"moto"` + // Selected network to process this SetupIntent on. Depends on the available networks of the card attached to the SetupIntent. Can be only set confirm-time. + Network *string `form:"network"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure *string `form:"request_three_d_secure"` + // If 3D Secure authentication was performed with a third-party provider, + // the authentication details to use for this setup. + ThreeDSecure *SetupIntentUpdatePaymentMethodOptionsCardThreeDSecureParams `form:"three_d_secure"` +} + +// If this is a `card_present` PaymentMethod, this sub-hash contains details about the card-present payment method options. +type SetupIntentUpdatePaymentMethodOptionsCardPresentParams struct{} + +// On-demand details if setting up a payment method for on-demand payments. +type SetupIntentUpdatePaymentMethodOptionsKlarnaOnDemandParams struct { + // Your average amount value. You can use a value across your customer base, or segment based on customer type, country, etc. + AverageAmount *int64 `form:"average_amount"` + // The maximum value you may charge a customer per purchase. You can use a value across your customer base, or segment based on customer type, country, etc. + MaximumAmount *int64 `form:"maximum_amount"` + // The lowest or minimum value you may charge a customer per purchase. You can use a value across your customer base, or segment based on customer type, country, etc. + MinimumAmount *int64 `form:"minimum_amount"` + // Interval at which the customer is making purchases + PurchaseInterval *string `form:"purchase_interval"` + // The number of `purchase_interval` between charges + PurchaseIntervalCount *int64 `form:"purchase_interval_count"` +} + +// Describes the upcoming charge for this subscription. +type SetupIntentUpdatePaymentMethodOptionsKlarnaSubscriptionNextBillingParams struct { + // The amount of the next charge for the subscription. + Amount *int64 `form:"amount"` + // The date of the next charge for the subscription in YYYY-MM-DD format. + Date *string `form:"date"` +} + +// Subscription details if setting up or charging a subscription +type SetupIntentUpdatePaymentMethodOptionsKlarnaSubscriptionParams struct { + // Unit of time between subscription charges. + Interval *string `form:"interval"` + // The number of intervals (specified in the `interval` attribute) between subscription charges. For example, `interval=month` and `interval_count=3` charges every 3 months. + IntervalCount *int64 `form:"interval_count"` + // Name for subscription. + Name *string `form:"name"` + // Describes the upcoming charge for this subscription. + NextBilling *SetupIntentUpdatePaymentMethodOptionsKlarnaSubscriptionNextBillingParams `form:"next_billing"` + // A non-customer-facing reference to correlate subscription charges in the Klarna app. Use a value that persists across subscription charges. + Reference *string `form:"reference"` +} + +// If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method options. +type SetupIntentUpdatePaymentMethodOptionsKlarnaParams struct { + // The currency of the SetupIntent. Three letter ISO currency code. + Currency *string `form:"currency"` + // On-demand details if setting up a payment method for on-demand payments. + OnDemand *SetupIntentUpdatePaymentMethodOptionsKlarnaOnDemandParams `form:"on_demand"` + // Preferred language of the Klarna authorization page that the customer is redirected to + PreferredLocale *string `form:"preferred_locale"` + // Subscription details if setting up or charging a subscription + Subscriptions []*SetupIntentUpdatePaymentMethodOptionsKlarnaSubscriptionParams `form:"subscriptions"` +} + +// If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. +type SetupIntentUpdatePaymentMethodOptionsLinkParams struct { + // [Deprecated] This is a legacy parameter that no longer has any function. + // Deprecated: + PersistentToken *string `form:"persistent_token"` +} + +// If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. +type SetupIntentUpdatePaymentMethodOptionsPaypalParams struct { + // The PayPal Billing Agreement ID (BAID). This is an ID generated by PayPal which represents the mandate between the merchant and the customer. + BillingAgreementID *string `form:"billing_agreement_id"` +} + +// Additional fields for Mandate creation +type SetupIntentUpdatePaymentMethodOptionsSEPADebitMandateOptionsParams struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'STRIPE'. + ReferencePrefix *string `form:"reference_prefix"` +} + +// If this is a `sepa_debit` SetupIntent, this sub-hash contains details about the SEPA Debit payment method options. +type SetupIntentUpdatePaymentMethodOptionsSEPADebitParams struct { + // Additional fields for Mandate creation + MandateOptions *SetupIntentUpdatePaymentMethodOptionsSEPADebitMandateOptionsParams `form:"mandate_options"` +} + +// Provide filters for the linked accounts that the customer can select for the payment method. +type SetupIntentUpdatePaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams struct { + // The account subcategories to use to filter for selectable accounts. Valid subcategories are `checking` and `savings`. + AccountSubcategories []*string `form:"account_subcategories"` +} + +// Additional fields for Financial Connections Session creation +type SetupIntentUpdatePaymentMethodOptionsUSBankAccountFinancialConnectionsParams struct { + // Provide filters for the linked accounts that the customer can select for the payment method. + Filters *SetupIntentUpdatePaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams `form:"filters"` + // The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` + // For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + ReturnURL *string `form:"return_url"` +} + +// Additional fields for Mandate creation +type SetupIntentUpdatePaymentMethodOptionsUSBankAccountMandateOptionsParams struct { + // The method used to collect offline mandate customer acceptance. + CollectionMethod *string `form:"collection_method"` +} + +// Additional fields for network related functions +type SetupIntentUpdatePaymentMethodOptionsUSBankAccountNetworksParams struct { + // Triggers validations to run across the selected networks + Requested []*string `form:"requested"` +} + +// If this is a `us_bank_account` SetupIntent, this sub-hash contains details about the US bank account payment method options. +type SetupIntentUpdatePaymentMethodOptionsUSBankAccountParams struct { + // Additional fields for Financial Connections Session creation + FinancialConnections *SetupIntentUpdatePaymentMethodOptionsUSBankAccountFinancialConnectionsParams `form:"financial_connections"` + // Additional fields for Mandate creation + MandateOptions *SetupIntentUpdatePaymentMethodOptionsUSBankAccountMandateOptionsParams `form:"mandate_options"` + // Additional fields for network related functions + Networks *SetupIntentUpdatePaymentMethodOptionsUSBankAccountNetworksParams `form:"networks"` + // Bank account verification method. + VerificationMethod *string `form:"verification_method"` +} + +// Payment method-specific configuration for this SetupIntent. +type SetupIntentUpdatePaymentMethodOptionsParams struct { + // If this is a `acss_debit` SetupIntent, this sub-hash contains details about the ACSS Debit payment method options. + ACSSDebit *SetupIntentUpdatePaymentMethodOptionsACSSDebitParams `form:"acss_debit"` + // If this is a `amazon_pay` SetupIntent, this sub-hash contains details about the AmazonPay payment method options. + AmazonPay *SetupIntentUpdatePaymentMethodOptionsAmazonPayParams `form:"amazon_pay"` + // If this is a `bacs_debit` SetupIntent, this sub-hash contains details about the Bacs Debit payment method options. + BACSDebit *SetupIntentUpdatePaymentMethodOptionsBACSDebitParams `form:"bacs_debit"` + // Configuration for any card setup attempted on this SetupIntent. + Card *SetupIntentUpdatePaymentMethodOptionsCardParams `form:"card"` + // If this is a `card_present` PaymentMethod, this sub-hash contains details about the card-present payment method options. + CardPresent *SetupIntentUpdatePaymentMethodOptionsCardPresentParams `form:"card_present"` + // If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method options. + Klarna *SetupIntentUpdatePaymentMethodOptionsKlarnaParams `form:"klarna"` + // If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. + Link *SetupIntentUpdatePaymentMethodOptionsLinkParams `form:"link"` + // If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. + Paypal *SetupIntentUpdatePaymentMethodOptionsPaypalParams `form:"paypal"` + // If this is a `sepa_debit` SetupIntent, this sub-hash contains details about the SEPA Debit payment method options. + SEPADebit *SetupIntentUpdatePaymentMethodOptionsSEPADebitParams `form:"sepa_debit"` + // If this is a `us_bank_account` SetupIntent, this sub-hash contains details about the US bank account payment method options. + USBankAccount *SetupIntentUpdatePaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` +} + +// Updates a SetupIntent object. +type SetupIntentUpdateParams struct { + Params `form:"*"` + // If present, the SetupIntent's payment method will be attached to the in-context Stripe Account. + // + // It can only be used for this Stripe Account's own money movement flows like InboundTransfer and OutboundTransfers. It cannot be set to true when setting up a PaymentMethod for a Customer, and defaults to false when attaching a PaymentMethod to a Customer. + AttachToSelf *bool `form:"attach_to_self"` + // ID of the Customer this SetupIntent belongs to, if one exists. + // + // If present, the SetupIntent's payment method will be attached to the Customer on successful setup. Payment methods attached to other Customers cannot be used with this SetupIntent. + Customer *string `form:"customer"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Indicates the directions of money movement for which this payment method is intended to be used. + // + // Include `inbound` if you intend to use the payment method as the origin to pull funds from. Include `outbound` if you intend to use the payment method as the destination to send funds to. You can include both if you intend to use the payment method for both purposes. + FlowDirections []*string `form:"flow_directions"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // ID of the payment method (a PaymentMethod, Card, or saved Source object) to attach to this SetupIntent. To unset this field to null, pass in an empty string. + PaymentMethod *string `form:"payment_method"` + // The ID of the [payment method configuration](https://stripe.com/docs/api/payment_method_configurations) to use with this SetupIntent. + PaymentMethodConfiguration *string `form:"payment_method_configuration"` + // When included, this hash creates a PaymentMethod that is set as the [`payment_method`](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-payment_method) + // value in the SetupIntent. + PaymentMethodData *SetupIntentUpdatePaymentMethodDataParams `form:"payment_method_data"` + // Payment method-specific configuration for this SetupIntent. + PaymentMethodOptions *SetupIntentUpdatePaymentMethodOptionsParams `form:"payment_method_options"` + // The list of payment method types (for example, card) that this SetupIntent can set up. If you don't provide this, Stripe will dynamically show relevant payment methods from your [payment method settings](https://dashboard.stripe.com/settings/payment_methods). A list of valid payment method types can be found [here](https://docs.stripe.com/api/payment_methods/object#payment_method_object-type). + PaymentMethodTypes []*string `form:"payment_method_types"` +} + +// AddExpand appends a new field to expand. +func (p *SetupIntentUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SetupIntentUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Settings for dynamic payment methods compatible with this Setup Intent +type SetupIntentAutomaticPaymentMethods struct { + // Controls whether this SetupIntent will accept redirect-based payment methods. + // + // Redirect-based payment methods may require your customer to be redirected to a payment method's app or site for authentication or additional steps. To [confirm](https://stripe.com/docs/api/setup_intents/confirm) this SetupIntent, you may be required to provide a `return_url` to redirect customers back to your site after they authenticate or complete the setup. + AllowRedirects SetupIntentAutomaticPaymentMethodsAllowRedirects `json:"allow_redirects"` + // Automatically calculates compatible payment methods + Enabled bool `json:"enabled"` +} +type SetupIntentNextActionCashAppHandleRedirectOrDisplayQRCodeQRCode struct { + // The date (unix timestamp) when the QR code expires. + ExpiresAt int64 `json:"expires_at"` + // The image_url_png string used to render QR code + ImageURLPNG string `json:"image_url_png"` + // The image_url_svg string used to render QR code + ImageURLSVG string `json:"image_url_svg"` +} +type SetupIntentNextActionCashAppHandleRedirectOrDisplayQRCode struct { + // The URL to the hosted Cash App Pay instructions page, which allows customers to view the QR code, and supports QR code refreshing on expiration. + HostedInstructionsURL string `json:"hosted_instructions_url"` + // The url for mobile redirect based auth + MobileAuthURL string `json:"mobile_auth_url"` + QRCode *SetupIntentNextActionCashAppHandleRedirectOrDisplayQRCodeQRCode `json:"qr_code"` +} +type SetupIntentNextActionRedirectToURL struct { + // If the customer does not exit their browser while authenticating, they will be redirected to this specified URL after completion. + ReturnURL string `json:"return_url"` + // The URL you must redirect your customer to in order to authenticate. + URL string `json:"url"` +} + +// When confirming a SetupIntent with Stripe.js, Stripe.js depends on the contents of this dictionary to invoke authentication flows. The shape of the contents is subject to change and is only intended to be used by Stripe.js. +type SetupIntentNextActionUseStripeSDK struct{} +type SetupIntentNextActionVerifyWithMicrodeposits struct { + // The timestamp when the microdeposits are expected to land. + ArrivalDate int64 `json:"arrival_date"` + // The URL for the hosted verification page, which allows customers to verify their bank account. + HostedVerificationURL string `json:"hosted_verification_url"` + // The type of the microdeposit sent to the customer. Used to distinguish between different verification methods. + MicrodepositType SetupIntentNextActionVerifyWithMicrodepositsMicrodepositType `json:"microdeposit_type"` +} + +// If present, this property tells you what actions you need to take in order for your customer to continue payment setup. +type SetupIntentNextAction struct { + CashAppHandleRedirectOrDisplayQRCode *SetupIntentNextActionCashAppHandleRedirectOrDisplayQRCode `json:"cashapp_handle_redirect_or_display_qr_code"` + RedirectToURL *SetupIntentNextActionRedirectToURL `json:"redirect_to_url"` + // Type of the next action to perform. Refer to the other child attributes under `next_action` for available values. Examples include: `redirect_to_url`, `use_stripe_sdk`, `alipay_handle_redirect`, `oxxo_display_details`, or `verify_with_microdeposits`. + Type SetupIntentNextActionType `json:"type"` + // When confirming a SetupIntent with Stripe.js, Stripe.js depends on the contents of this dictionary to invoke authentication flows. The shape of the contents is subject to change and is only intended to be used by Stripe.js. + UseStripeSDK *SetupIntentNextActionUseStripeSDK `json:"use_stripe_sdk"` + VerifyWithMicrodeposits *SetupIntentNextActionVerifyWithMicrodeposits `json:"verify_with_microdeposits"` +} + +// Information about the [payment method configuration](https://stripe.com/docs/api/payment_method_configurations) used for this Setup Intent. +type SetupIntentPaymentMethodConfigurationDetails struct { + // ID of the payment method configuration used. + ID string `json:"id"` + // ID of the parent payment method configuration used. + Parent string `json:"parent"` +} +type SetupIntentPaymentMethodOptionsACSSDebitMandateOptions struct { + // A URL for custom mandate text + CustomMandateURL string `json:"custom_mandate_url"` + // List of Stripe products where this mandate can be selected automatically. + DefaultFor []SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsDefaultFor `json:"default_for"` + // Description of the interval. Only required if the 'payment_schedule' parameter is 'interval' or 'combined'. + IntervalDescription string `json:"interval_description"` + // Payment schedule for the mandate. + PaymentSchedule SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsPaymentSchedule `json:"payment_schedule"` + // Transaction type of the mandate. + TransactionType SetupIntentPaymentMethodOptionsACSSDebitMandateOptionsTransactionType `json:"transaction_type"` +} +type SetupIntentPaymentMethodOptionsACSSDebit struct { + // Currency supported by the bank account + Currency SetupIntentPaymentMethodOptionsACSSDebitCurrency `json:"currency"` + MandateOptions *SetupIntentPaymentMethodOptionsACSSDebitMandateOptions `json:"mandate_options"` + // Bank account verification method. + VerificationMethod SetupIntentPaymentMethodOptionsACSSDebitVerificationMethod `json:"verification_method"` +} +type SetupIntentPaymentMethodOptionsAmazonPay struct{} +type SetupIntentPaymentMethodOptionsBACSDebitMandateOptions struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'DDIC' or 'STRIPE'. + ReferencePrefix string `json:"reference_prefix"` +} +type SetupIntentPaymentMethodOptionsBACSDebit struct { + MandateOptions *SetupIntentPaymentMethodOptionsBACSDebitMandateOptions `json:"mandate_options"` +} + +// Configuration options for setting up an eMandate for cards issued in India. +type SetupIntentPaymentMethodOptionsCardMandateOptions struct { + // Amount to be charged for future payments. + Amount int64 `json:"amount"` + // One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + AmountType SetupIntentPaymentMethodOptionsCardMandateOptionsAmountType `json:"amount_type"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // A description of the mandate or subscription that is meant to be displayed to the customer. + Description string `json:"description"` + // End date of the mandate or subscription. If not provided, the mandate will be active until canceled. If provided, end date should be after start date. + EndDate int64 `json:"end_date"` + // Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. + Interval SetupIntentPaymentMethodOptionsCardMandateOptionsInterval `json:"interval"` + // The number of intervals between payments. For example, `interval=month` and `interval_count=3` indicates one payment every three months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). This parameter is optional when `interval=sporadic`. + IntervalCount int64 `json:"interval_count"` + // Unique identifier for the mandate or subscription. + Reference string `json:"reference"` + // Start date of the mandate or subscription. Start date should not be lesser than yesterday. + StartDate int64 `json:"start_date"` + // Specifies the type of mandates supported. Possible values are `india`. + SupportedTypes []SetupIntentPaymentMethodOptionsCardMandateOptionsSupportedType `json:"supported_types"` +} +type SetupIntentPaymentMethodOptionsCard struct { + // Configuration options for setting up an eMandate for cards issued in India. + MandateOptions *SetupIntentPaymentMethodOptionsCardMandateOptions `json:"mandate_options"` + // Selected network to process this SetupIntent on. Depends on the available networks of the card attached to the setup intent. Can be only set confirm-time. + Network SetupIntentPaymentMethodOptionsCardNetwork `json:"network"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure SetupIntentPaymentMethodOptionsCardRequestThreeDSecure `json:"request_three_d_secure"` +} +type SetupIntentPaymentMethodOptionsCardPresent struct{} +type SetupIntentPaymentMethodOptionsKlarna struct { + // The currency of the setup intent. Three letter ISO currency code. + Currency Currency `json:"currency"` + // Preferred locale of the Klarna checkout page that the customer is redirected to. + PreferredLocale string `json:"preferred_locale"` +} +type SetupIntentPaymentMethodOptionsLink struct { + // [Deprecated] This is a legacy parameter that no longer has any function. + // Deprecated: + PersistentToken string `json:"persistent_token"` +} +type SetupIntentPaymentMethodOptionsPaypal struct { + // The PayPal Billing Agreement ID (BAID). This is an ID generated by PayPal which represents the mandate between the merchant and the customer. + BillingAgreementID string `json:"billing_agreement_id"` +} +type SetupIntentPaymentMethodOptionsSEPADebitMandateOptions struct { + // Prefix used to generate the Mandate reference. Must be at most 12 characters long. Must consist of only uppercase letters, numbers, spaces, or the following special characters: '/', '_', '-', '&', '.'. Cannot begin with 'STRIPE'. + ReferencePrefix string `json:"reference_prefix"` +} +type SetupIntentPaymentMethodOptionsSEPADebit struct { + MandateOptions *SetupIntentPaymentMethodOptionsSEPADebitMandateOptions `json:"mandate_options"` +} +type SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFilters struct { + // The account subcategories to use to filter for possible accounts to link. Valid subcategories are `checking` and `savings`. + AccountSubcategories []SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory `json:"account_subcategories"` +} +type SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnections struct { + Filters *SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsFilters `json:"filters"` + // The list of permissions to request. The `payment_method` permission must be included. + Permissions []SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission `json:"permissions"` + // Data features requested to be retrieved upon account creation. + Prefetch []SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch `json:"prefetch"` + // For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + ReturnURL string `json:"return_url"` +} +type SetupIntentPaymentMethodOptionsUSBankAccountMandateOptions struct { + // Mandate collection method + CollectionMethod SetupIntentPaymentMethodOptionsUSBankAccountMandateOptionsCollectionMethod `json:"collection_method"` +} +type SetupIntentPaymentMethodOptionsUSBankAccount struct { + FinancialConnections *SetupIntentPaymentMethodOptionsUSBankAccountFinancialConnections `json:"financial_connections"` + MandateOptions *SetupIntentPaymentMethodOptionsUSBankAccountMandateOptions `json:"mandate_options"` + // Bank account verification method. + VerificationMethod SetupIntentPaymentMethodOptionsUSBankAccountVerificationMethod `json:"verification_method"` +} + +// Payment method-specific configuration for this SetupIntent. +type SetupIntentPaymentMethodOptions struct { + ACSSDebit *SetupIntentPaymentMethodOptionsACSSDebit `json:"acss_debit"` + AmazonPay *SetupIntentPaymentMethodOptionsAmazonPay `json:"amazon_pay"` + BACSDebit *SetupIntentPaymentMethodOptionsBACSDebit `json:"bacs_debit"` + Card *SetupIntentPaymentMethodOptionsCard `json:"card"` + CardPresent *SetupIntentPaymentMethodOptionsCardPresent `json:"card_present"` + Klarna *SetupIntentPaymentMethodOptionsKlarna `json:"klarna"` + Link *SetupIntentPaymentMethodOptionsLink `json:"link"` + Paypal *SetupIntentPaymentMethodOptionsPaypal `json:"paypal"` + SEPADebit *SetupIntentPaymentMethodOptionsSEPADebit `json:"sepa_debit"` + USBankAccount *SetupIntentPaymentMethodOptionsUSBankAccount `json:"us_bank_account"` +} + +// A SetupIntent guides you through the process of setting up and saving a customer's payment credentials for future payments. +// For example, you can use a SetupIntent to set up and save your customer's card without immediately collecting a payment. +// Later, you can use [PaymentIntents](https://stripe.com/docs/api#payment_intents) to drive the payment flow. +// +// Create a SetupIntent when you're ready to collect your customer's payment credentials. +// Don't maintain long-lived, unconfirmed SetupIntents because they might not be valid. +// The SetupIntent transitions through multiple [statuses](https://docs.stripe.com/payments/intents#intent-statuses) as it guides +// you through the setup process. +// +// Successful SetupIntents result in payment credentials that are optimized for future payments. +// For example, cardholders in [certain regions](https://stripe.com/guides/strong-customer-authentication) might need to be run through +// [Strong Customer Authentication](https://docs.stripe.com/strong-customer-authentication) during payment method collection +// to streamline later [off-session payments](https://docs.stripe.com/payments/setup-intents). +// If you use the SetupIntent with a [Customer](https://stripe.com/docs/api#setup_intent_object-customer), +// it automatically attaches the resulting payment method to that Customer after successful setup. +// We recommend using SetupIntents or [setup_future_usage](https://stripe.com/docs/api#payment_intent_object-setup_future_usage) on +// PaymentIntents to save payment methods to prevent saving invalid or unoptimized payment methods. +// +// By using SetupIntents, you can reduce friction for your customers, even as regulations change over time. +// +// Related guide: [Setup Intents API](https://docs.stripe.com/payments/setup-intents) +type SetupIntent struct { + APIResource + // ID of the Connect application that created the SetupIntent. + Application *Application `json:"application"` + // If present, the SetupIntent's payment method will be attached to the in-context Stripe Account. + // + // It can only be used for this Stripe Account's own money movement flows like InboundTransfer and OutboundTransfers. It cannot be set to true when setting up a PaymentMethod for a Customer, and defaults to false when attaching a PaymentMethod to a Customer. + AttachToSelf bool `json:"attach_to_self"` + // Settings for dynamic payment methods compatible with this Setup Intent + AutomaticPaymentMethods *SetupIntentAutomaticPaymentMethods `json:"automatic_payment_methods"` + // Reason for cancellation of this SetupIntent, one of `abandoned`, `requested_by_customer`, or `duplicate`. + CancellationReason SetupIntentCancellationReason `json:"cancellation_reason"` + // The client secret of this SetupIntent. Used for client-side retrieval using a publishable key. + // + // The client secret can be used to complete payment setup from your frontend. It should not be stored, logged, or exposed to anyone other than the customer. Make sure that you have TLS enabled on any page that includes the client secret. + ClientSecret string `json:"client_secret"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // ID of the Customer this SetupIntent belongs to, if one exists. + // + // If present, the SetupIntent's payment method will be attached to the Customer on successful setup. Payment methods attached to other Customers cannot be used with this SetupIntent. + Customer *Customer `json:"customer"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // Indicates the directions of money movement for which this payment method is intended to be used. + // + // Include `inbound` if you intend to use the payment method as the origin to pull funds from. Include `outbound` if you intend to use the payment method as the destination to send funds to. You can include both if you intend to use the payment method for both purposes. + FlowDirections []SetupIntentFlowDirection `json:"flow_directions"` + // Unique identifier for the object. + ID string `json:"id"` + // The error encountered in the previous SetupIntent confirmation. + LastSetupError *Error `json:"last_setup_error"` + // The most recent SetupAttempt for this SetupIntent. + LatestAttempt *SetupAttempt `json:"latest_attempt"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // ID of the multi use Mandate generated by the SetupIntent. + Mandate *Mandate `json:"mandate"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // If present, this property tells you what actions you need to take in order for your customer to continue payment setup. + NextAction *SetupIntentNextAction `json:"next_action"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The account (if any) for which the setup is intended. + OnBehalfOf *Account `json:"on_behalf_of"` + // ID of the payment method used with this SetupIntent. If the payment method is `card_present` and isn't a digital wallet, then the [generated_card](https://docs.stripe.com/api/setup_attempts/object#setup_attempt_object-payment_method_details-card_present-generated_card) associated with the `latest_attempt` is attached to the Customer instead. + PaymentMethod *PaymentMethod `json:"payment_method"` + // Information about the [payment method configuration](https://stripe.com/docs/api/payment_method_configurations) used for this Setup Intent. + PaymentMethodConfigurationDetails *SetupIntentPaymentMethodConfigurationDetails `json:"payment_method_configuration_details"` + // Payment method-specific configuration for this SetupIntent. + PaymentMethodOptions *SetupIntentPaymentMethodOptions `json:"payment_method_options"` + // The list of payment method types (e.g. card) that this SetupIntent is allowed to set up. A list of valid payment method types can be found [here](https://docs.stripe.com/api/payment_methods/object#payment_method_object-type). + PaymentMethodTypes []string `json:"payment_method_types"` + // ID of the single_use Mandate generated by the SetupIntent. + SingleUseMandate *Mandate `json:"single_use_mandate"` + // [Status](https://stripe.com/docs/payments/intents#intent-statuses) of this SetupIntent, one of `requires_payment_method`, `requires_confirmation`, `requires_action`, `processing`, `canceled`, or `succeeded`. + Status SetupIntentStatus `json:"status"` + // Indicates how the payment method is intended to be used in the future. + // + // Use `on_session` if you intend to only reuse the payment method when the customer is in your checkout flow. Use `off_session` if your customer may or may not be in your checkout flow. If not provided, this value defaults to `off_session`. + Usage SetupIntentUsage `json:"usage"` +} + +// SetupIntentList is a list of SetupIntents as retrieved from a list endpoint. +type SetupIntentList struct { + APIResource + ListMeta + Data []*SetupIntent `json:"data"` +} + +// UnmarshalJSON handles deserialization of a SetupIntent. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (s *SetupIntent) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + s.ID = id + return nil + } + + type setupIntent SetupIntent + var v setupIntent + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *s = SetupIntent(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/setupintent_service.go b/vendor/github.com/stripe/stripe-go/v82/setupintent_service.go new file mode 100644 index 00000000..f8b7dcac --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/setupintent_service.go @@ -0,0 +1,131 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1SetupIntentService is used to invoke /v1/setup_intents APIs. +type v1SetupIntentService struct { + B Backend + Key string +} + +// Creates a SetupIntent object. +// +// After you create the SetupIntent, attach a payment method and [confirm](https://docs.stripe.com/docs/api/setup_intents/confirm) +// it to collect any required permissions to charge the payment method later. +func (c v1SetupIntentService) Create(ctx context.Context, params *SetupIntentCreateParams) (*SetupIntent, error) { + if params == nil { + params = &SetupIntentCreateParams{} + } + params.Context = ctx + setupintent := &SetupIntent{} + err := c.B.Call( + http.MethodPost, "/v1/setup_intents", c.Key, params, setupintent) + return setupintent, err +} + +// Retrieves the details of a SetupIntent that has previously been created. +// +// Client-side retrieval using a publishable key is allowed when the client_secret is provided in the query string. +// +// When retrieved with a publishable key, only a subset of properties will be returned. Please refer to the [SetupIntent](https://docs.stripe.com/api#setup_intent_object) object reference for more details. +func (c v1SetupIntentService) Retrieve(ctx context.Context, id string, params *SetupIntentRetrieveParams) (*SetupIntent, error) { + if params == nil { + params = &SetupIntentRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/setup_intents/%s", id) + setupintent := &SetupIntent{} + err := c.B.Call(http.MethodGet, path, c.Key, params, setupintent) + return setupintent, err +} + +// Updates a SetupIntent object. +func (c v1SetupIntentService) Update(ctx context.Context, id string, params *SetupIntentUpdateParams) (*SetupIntent, error) { + if params == nil { + params = &SetupIntentUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/setup_intents/%s", id) + setupintent := &SetupIntent{} + err := c.B.Call(http.MethodPost, path, c.Key, params, setupintent) + return setupintent, err +} + +// You can cancel a SetupIntent object when it's in one of these statuses: requires_payment_method, requires_confirmation, or requires_action. +// +// After you cancel it, setup is abandoned and any operations on the SetupIntent fail with an error. You can't cancel the SetupIntent for a Checkout Session. [Expire the Checkout Session](https://docs.stripe.com/docs/api/checkout/sessions/expire) instead. +func (c v1SetupIntentService) Cancel(ctx context.Context, id string, params *SetupIntentCancelParams) (*SetupIntent, error) { + if params == nil { + params = &SetupIntentCancelParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/setup_intents/%s/cancel", id) + setupintent := &SetupIntent{} + err := c.B.Call(http.MethodPost, path, c.Key, params, setupintent) + return setupintent, err +} + +// Confirm that your customer intends to set up the current or +// provided payment method. For example, you would confirm a SetupIntent +// when a customer hits the “Save” button on a payment method management +// page on your website. +// +// If the selected payment method does not require any additional +// steps from the customer, the SetupIntent will transition to the +// succeeded status. +// +// Otherwise, it will transition to the requires_action status and +// suggest additional actions via next_action. If setup fails, +// the SetupIntent will transition to the +// requires_payment_method status or the canceled status if the +// confirmation limit is reached. +func (c v1SetupIntentService) Confirm(ctx context.Context, id string, params *SetupIntentConfirmParams) (*SetupIntent, error) { + if params == nil { + params = &SetupIntentConfirmParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/setup_intents/%s/confirm", id) + setupintent := &SetupIntent{} + err := c.B.Call(http.MethodPost, path, c.Key, params, setupintent) + return setupintent, err +} + +// Verifies microdeposits on a SetupIntent object. +func (c v1SetupIntentService) VerifyMicrodeposits(ctx context.Context, id string, params *SetupIntentVerifyMicrodepositsParams) (*SetupIntent, error) { + if params == nil { + params = &SetupIntentVerifyMicrodepositsParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/setup_intents/%s/verify_microdeposits", id) + setupintent := &SetupIntent{} + err := c.B.Call(http.MethodPost, path, c.Key, params, setupintent) + return setupintent, err +} + +// Returns a list of SetupIntents. +func (c v1SetupIntentService) List(ctx context.Context, listParams *SetupIntentListParams) Seq2[*SetupIntent, error] { + if listParams == nil { + listParams = &SetupIntentListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*SetupIntent, ListContainer, error) { + list := &SetupIntentList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/setup_intents", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/shippingrate.go b/vendor/github.com/stripe/stripe-go/v82/shippingrate.go new file mode 100644 index 00000000..226ddbf1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/shippingrate.go @@ -0,0 +1,387 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// A unit of time. +type ShippingRateDeliveryEstimateMaximumUnit string + +// List of values that ShippingRateDeliveryEstimateMaximumUnit can take +const ( + ShippingRateDeliveryEstimateMaximumUnitBusinessDay ShippingRateDeliveryEstimateMaximumUnit = "business_day" + ShippingRateDeliveryEstimateMaximumUnitDay ShippingRateDeliveryEstimateMaximumUnit = "day" + ShippingRateDeliveryEstimateMaximumUnitHour ShippingRateDeliveryEstimateMaximumUnit = "hour" + ShippingRateDeliveryEstimateMaximumUnitMonth ShippingRateDeliveryEstimateMaximumUnit = "month" + ShippingRateDeliveryEstimateMaximumUnitWeek ShippingRateDeliveryEstimateMaximumUnit = "week" +) + +// A unit of time. +type ShippingRateDeliveryEstimateMinimumUnit string + +// List of values that ShippingRateDeliveryEstimateMinimumUnit can take +const ( + ShippingRateDeliveryEstimateMinimumUnitBusinessDay ShippingRateDeliveryEstimateMinimumUnit = "business_day" + ShippingRateDeliveryEstimateMinimumUnitDay ShippingRateDeliveryEstimateMinimumUnit = "day" + ShippingRateDeliveryEstimateMinimumUnitHour ShippingRateDeliveryEstimateMinimumUnit = "hour" + ShippingRateDeliveryEstimateMinimumUnitMonth ShippingRateDeliveryEstimateMinimumUnit = "month" + ShippingRateDeliveryEstimateMinimumUnitWeek ShippingRateDeliveryEstimateMinimumUnit = "week" +) + +// Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. +type ShippingRateFixedAmountCurrencyOptionsTaxBehavior string + +// List of values that ShippingRateFixedAmountCurrencyOptionsTaxBehavior can take +const ( + ShippingRateFixedAmountCurrencyOptionsTaxBehaviorExclusive ShippingRateFixedAmountCurrencyOptionsTaxBehavior = "exclusive" + ShippingRateFixedAmountCurrencyOptionsTaxBehaviorInclusive ShippingRateFixedAmountCurrencyOptionsTaxBehavior = "inclusive" + ShippingRateFixedAmountCurrencyOptionsTaxBehaviorUnspecified ShippingRateFixedAmountCurrencyOptionsTaxBehavior = "unspecified" +) + +// Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. +type ShippingRateTaxBehavior string + +// List of values that ShippingRateTaxBehavior can take +const ( + ShippingRateTaxBehaviorExclusive ShippingRateTaxBehavior = "exclusive" + ShippingRateTaxBehaviorInclusive ShippingRateTaxBehavior = "inclusive" + ShippingRateTaxBehaviorUnspecified ShippingRateTaxBehavior = "unspecified" +) + +// The type of calculation to use on the shipping rate. +type ShippingRateType string + +// List of values that ShippingRateType can take +const ( + ShippingRateTypeFixedAmount ShippingRateType = "fixed_amount" +) + +// Returns a list of your shipping rates. +type ShippingRateListParams struct { + ListParams `form:"*"` + // Only return shipping rates that are active or inactive. + Active *bool `form:"active"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + Created *int64 `form:"created"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + CreatedRange *RangeQueryParams `form:"created"` + // Only return shipping rates for the given currency. + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ShippingRateListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. +type ShippingRateDeliveryEstimateMaximumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The lower bound of the estimated range. If empty, represents no lower bound. +type ShippingRateDeliveryEstimateMinimumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. +type ShippingRateDeliveryEstimateParams struct { + // The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. + Maximum *ShippingRateDeliveryEstimateMaximumParams `form:"maximum"` + // The lower bound of the estimated range. If empty, represents no lower bound. + Minimum *ShippingRateDeliveryEstimateMinimumParams `form:"minimum"` +} + +// Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type ShippingRateFixedAmountCurrencyOptionsParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` +} + +// Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. +type ShippingRateFixedAmountParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*ShippingRateFixedAmountCurrencyOptionsParams `form:"currency_options"` +} + +// Creates a new shipping rate object. +type ShippingRateParams struct { + Params `form:"*"` + // Whether the shipping rate can be used for new purchases. Defaults to `true`. + Active *bool `form:"active"` + // The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. + DeliveryEstimate *ShippingRateDeliveryEstimateParams `form:"delivery_estimate"` + // The name of the shipping rate, meant to be displayable to the customer. This will appear on CheckoutSessions. + DisplayName *string `form:"display_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. + FixedAmount *ShippingRateFixedAmountParams `form:"fixed_amount"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. The Shipping tax code is `txcd_92010001`. + TaxCode *string `form:"tax_code"` + // The type of calculation to use on the shipping rate. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *ShippingRateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ShippingRateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. +type ShippingRateCreateDeliveryEstimateMaximumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The lower bound of the estimated range. If empty, represents no lower bound. +type ShippingRateCreateDeliveryEstimateMinimumParams struct { + // A unit of time. + Unit *string `form:"unit"` + // Must be greater than 0. + Value *int64 `form:"value"` +} + +// The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. +type ShippingRateCreateDeliveryEstimateParams struct { + // The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. + Maximum *ShippingRateCreateDeliveryEstimateMaximumParams `form:"maximum"` + // The lower bound of the estimated range. If empty, represents no lower bound. + Minimum *ShippingRateCreateDeliveryEstimateMinimumParams `form:"minimum"` +} + +// Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type ShippingRateCreateFixedAmountCurrencyOptionsParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` +} + +// Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. +type ShippingRateCreateFixedAmountParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*ShippingRateCreateFixedAmountCurrencyOptionsParams `form:"currency_options"` +} + +// Creates a new shipping rate object. +type ShippingRateCreateParams struct { + Params `form:"*"` + // The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. + DeliveryEstimate *ShippingRateCreateDeliveryEstimateParams `form:"delivery_estimate"` + // The name of the shipping rate, meant to be displayable to the customer. This will appear on CheckoutSessions. + DisplayName *string `form:"display_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. + FixedAmount *ShippingRateCreateFixedAmountParams `form:"fixed_amount"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. The Shipping tax code is `txcd_92010001`. + TaxCode *string `form:"tax_code"` + // The type of calculation to use on the shipping rate. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *ShippingRateCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ShippingRateCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Returns the shipping rate object with the given ID. +type ShippingRateRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *ShippingRateRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type ShippingRateUpdateFixedAmountCurrencyOptionsParams struct { + // A non-negative integer in cents representing how much to charge. + Amount *int64 `form:"amount"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` +} + +// Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. +type ShippingRateUpdateFixedAmountParams struct { + // Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*ShippingRateUpdateFixedAmountCurrencyOptionsParams `form:"currency_options"` +} + +// Updates an existing shipping rate object. +type ShippingRateUpdateParams struct { + Params `form:"*"` + // Whether the shipping rate can be used for new purchases. Defaults to `true`. + Active *bool `form:"active"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. + FixedAmount *ShippingRateUpdateFixedAmountParams `form:"fixed_amount"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior *string `form:"tax_behavior"` +} + +// AddExpand appends a new field to expand. +func (p *ShippingRateUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *ShippingRateUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. +type ShippingRateDeliveryEstimateMaximum struct { + // A unit of time. + Unit ShippingRateDeliveryEstimateMaximumUnit `json:"unit"` + // Must be greater than 0. + Value int64 `json:"value"` +} + +// The lower bound of the estimated range. If empty, represents no lower bound. +type ShippingRateDeliveryEstimateMinimum struct { + // A unit of time. + Unit ShippingRateDeliveryEstimateMinimumUnit `json:"unit"` + // Must be greater than 0. + Value int64 `json:"value"` +} + +// The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. +type ShippingRateDeliveryEstimate struct { + // The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. + Maximum *ShippingRateDeliveryEstimateMaximum `json:"maximum"` + // The lower bound of the estimated range. If empty, represents no lower bound. + Minimum *ShippingRateDeliveryEstimateMinimum `json:"minimum"` +} + +// Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). +type ShippingRateFixedAmountCurrencyOptions struct { + // A non-negative integer in cents representing how much to charge. + Amount int64 `json:"amount"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior ShippingRateFixedAmountCurrencyOptionsTaxBehavior `json:"tax_behavior"` +} +type ShippingRateFixedAmount struct { + // A non-negative integer in cents representing how much to charge. + Amount int64 `json:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + CurrencyOptions map[string]*ShippingRateFixedAmountCurrencyOptions `json:"currency_options"` +} + +// Shipping rates describe the price of shipping presented to your customers and +// applied to a purchase. For more information, see [Charge for shipping](https://stripe.com/docs/payments/during-payment/charge-shipping). +type ShippingRate struct { + APIResource + // Whether the shipping rate can be used for new purchases. Defaults to `true`. + Active bool `json:"active"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. + DeliveryEstimate *ShippingRateDeliveryEstimate `json:"delivery_estimate"` + // The name of the shipping rate, meant to be displayable to the customer. This will appear on CheckoutSessions. + DisplayName string `json:"display_name"` + FixedAmount *ShippingRateFixedAmount `json:"fixed_amount"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + TaxBehavior ShippingRateTaxBehavior `json:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. The Shipping tax code is `txcd_92010001`. + TaxCode *TaxCode `json:"tax_code"` + // The type of calculation to use on the shipping rate. + Type ShippingRateType `json:"type"` +} + +// ShippingRateList is a list of ShippingRates as retrieved from a list endpoint. +type ShippingRateList struct { + APIResource + ListMeta + Data []*ShippingRate `json:"data"` +} + +// UnmarshalJSON handles deserialization of a ShippingRate. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (s *ShippingRate) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + s.ID = id + return nil + } + + type shippingRate ShippingRate + var v shippingRate + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *s = ShippingRate(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/shippingrate_service.go b/vendor/github.com/stripe/stripe-go/v82/shippingrate_service.go new file mode 100644 index 00000000..8485d08c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/shippingrate_service.go @@ -0,0 +1,73 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1ShippingRateService is used to invoke /v1/shipping_rates APIs. +type v1ShippingRateService struct { + B Backend + Key string +} + +// Creates a new shipping rate object. +func (c v1ShippingRateService) Create(ctx context.Context, params *ShippingRateCreateParams) (*ShippingRate, error) { + if params == nil { + params = &ShippingRateCreateParams{} + } + params.Context = ctx + shippingrate := &ShippingRate{} + err := c.B.Call( + http.MethodPost, "/v1/shipping_rates", c.Key, params, shippingrate) + return shippingrate, err +} + +// Returns the shipping rate object with the given ID. +func (c v1ShippingRateService) Retrieve(ctx context.Context, id string, params *ShippingRateRetrieveParams) (*ShippingRate, error) { + if params == nil { + params = &ShippingRateRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/shipping_rates/%s", id) + shippingrate := &ShippingRate{} + err := c.B.Call(http.MethodGet, path, c.Key, params, shippingrate) + return shippingrate, err +} + +// Updates an existing shipping rate object. +func (c v1ShippingRateService) Update(ctx context.Context, id string, params *ShippingRateUpdateParams) (*ShippingRate, error) { + if params == nil { + params = &ShippingRateUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/shipping_rates/%s", id) + shippingrate := &ShippingRate{} + err := c.B.Call(http.MethodPost, path, c.Key, params, shippingrate) + return shippingrate, err +} + +// Returns a list of your shipping rates. +func (c v1ShippingRateService) List(ctx context.Context, listParams *ShippingRateListParams) Seq2[*ShippingRate, error] { + if listParams == nil { + listParams = &ShippingRateListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*ShippingRate, ListContainer, error) { + list := &ShippingRateList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/shipping_rates", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/sigma_scheduledqueryrun.go b/vendor/github.com/stripe/stripe-go/v82/sigma_scheduledqueryrun.go new file mode 100644 index 00000000..362ee87e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/sigma_scheduledqueryrun.go @@ -0,0 +1,95 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The query's execution status, which will be `completed` for successful runs, and `canceled`, `failed`, or `timed_out` otherwise. +type SigmaScheduledQueryRunStatus string + +// List of values that SigmaScheduledQueryRunStatus can take +const ( + SigmaScheduledQueryRunStatusCanceled SigmaScheduledQueryRunStatus = "canceled" + SigmaScheduledQueryRunStatusCompleted SigmaScheduledQueryRunStatus = "completed" + SigmaScheduledQueryRunStatusFailed SigmaScheduledQueryRunStatus = "failed" + SigmaScheduledQueryRunStatusTimedOut SigmaScheduledQueryRunStatus = "timed_out" +) + +// Returns a list of scheduled query runs. +type SigmaScheduledQueryRunListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *SigmaScheduledQueryRunListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an scheduled query run. +type SigmaScheduledQueryRunParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *SigmaScheduledQueryRunParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an scheduled query run. +type SigmaScheduledQueryRunRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *SigmaScheduledQueryRunRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type SigmaScheduledQueryRunError struct { + // Information about the run failure. + Message string `json:"message"` +} + +// If you have [scheduled a Sigma query](https://stripe.com/docs/sigma/scheduled-queries), you'll +// receive a `sigma.scheduled_query_run.created` webhook each time the query +// runs. The webhook contains a `ScheduledQueryRun` object, which you can use to +// retrieve the query results. +type SigmaScheduledQueryRun struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // When the query was run, Sigma contained a snapshot of your Stripe data at this time. + DataLoadTime int64 `json:"data_load_time"` + Error *SigmaScheduledQueryRunError `json:"error"` + // The file object representing the results of the query. + File *File `json:"file"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Time at which the result expires and is no longer available for download. + ResultAvailableUntil int64 `json:"result_available_until"` + // SQL for the query. + SQL string `json:"sql"` + // The query's execution status, which will be `completed` for successful runs, and `canceled`, `failed`, or `timed_out` otherwise. + Status SigmaScheduledQueryRunStatus `json:"status"` + // Title of the query. + Title string `json:"title"` +} + +// SigmaScheduledQueryRunList is a list of ScheduledQueryRuns as retrieved from a list endpoint. +type SigmaScheduledQueryRunList struct { + APIResource + ListMeta + Data []*SigmaScheduledQueryRun `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/sigma_scheduledqueryrun_service.go b/vendor/github.com/stripe/stripe-go/v82/sigma_scheduledqueryrun_service.go new file mode 100644 index 00000000..35bbcbc1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/sigma_scheduledqueryrun_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1SigmaScheduledQueryRunService is used to invoke /v1/sigma/scheduled_query_runs APIs. +type v1SigmaScheduledQueryRunService struct { + B Backend + Key string +} + +// Retrieves the details of an scheduled query run. +func (c v1SigmaScheduledQueryRunService) Retrieve(ctx context.Context, id string, params *SigmaScheduledQueryRunRetrieveParams) (*SigmaScheduledQueryRun, error) { + if params == nil { + params = &SigmaScheduledQueryRunRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/sigma/scheduled_query_runs/%s", id) + scheduledqueryrun := &SigmaScheduledQueryRun{} + err := c.B.Call(http.MethodGet, path, c.Key, params, scheduledqueryrun) + return scheduledqueryrun, err +} + +// Returns a list of scheduled query runs. +func (c v1SigmaScheduledQueryRunService) List(ctx context.Context, listParams *SigmaScheduledQueryRunListParams) Seq2[*SigmaScheduledQueryRun, error] { + if listParams == nil { + listParams = &SigmaScheduledQueryRunListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*SigmaScheduledQueryRun, ListContainer, error) { + list := &SigmaScheduledQueryRunList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/sigma/scheduled_query_runs", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/source.go b/vendor/github.com/stripe/stripe-go/v82/source.go new file mode 100644 index 00000000..7bd17a81 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/source.go @@ -0,0 +1,895 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to “unspecified”. +type SourceAllowRedisplay string + +// List of values that SourceAllowRedisplay can take +const ( + SourceAllowRedisplayAlways SourceAllowRedisplay = "always" + SourceAllowRedisplayLimited SourceAllowRedisplay = "limited" + SourceAllowRedisplayUnspecified SourceAllowRedisplay = "unspecified" +) + +// The status of the code verification, either `pending` (awaiting verification, `attempts_remaining` should be greater than 0), `succeeded` (successful verification) or `failed` (failed verification, cannot be verified anymore as `attempts_remaining` should be 0). +type SourceCodeVerificationStatus string + +// List of values that SourceCodeVerificationStatus can take +const ( + SourceCodeVerificationStatusFailed SourceCodeVerificationStatus = "failed" + SourceCodeVerificationStatusPending SourceCodeVerificationStatus = "pending" + SourceCodeVerificationStatusSucceeded SourceCodeVerificationStatus = "succeeded" +) + +// The authentication `flow` of the source. `flow` is one of `redirect`, `receiver`, `code_verification`, `none`. +type SourceFlow string + +// List of values that SourceFlow can take +const ( + SourceFlowCodeVerification SourceFlow = "code_verification" + SourceFlowNone SourceFlow = "none" + SourceFlowReceiver SourceFlow = "receiver" + SourceFlowRedirect SourceFlow = "redirect" +) + +// Type of refund attribute method, one of `email`, `manual`, or `none`. +type SourceReceiverRefundAttributesMethod string + +// List of values that SourceReceiverRefundAttributesMethod can take +const ( + SourceReceiverRefundAttributesMethodEmail SourceReceiverRefundAttributesMethod = "email" + SourceReceiverRefundAttributesMethodManual SourceReceiverRefundAttributesMethod = "manual" + SourceReceiverRefundAttributesMethodNone SourceReceiverRefundAttributesMethod = "none" +) + +// Type of refund attribute status, one of `missing`, `requested`, or `available`. +type SourceReceiverRefundAttributesStatus string + +// List of values that SourceReceiverRefundAttributesStatus can take +const ( + SourceReceiverRefundAttributesStatusAvailable SourceReceiverRefundAttributesStatus = "available" + SourceReceiverRefundAttributesStatusMissing SourceReceiverRefundAttributesStatus = "missing" + SourceReceiverRefundAttributesStatusRequested SourceReceiverRefundAttributesStatus = "requested" +) + +// The failure reason for the redirect, either `user_abort` (the customer aborted or dropped out of the redirect flow), `declined` (the authentication failed or the transaction was declined), or `processing_error` (the redirect failed due to a technical error). Present only if the redirect status is `failed`. +type SourceRedirectFailureReason string + +// List of values that SourceRedirectFailureReason can take +const ( + SourceRedirectFailureReasonDeclined SourceRedirectFailureReason = "declined" + SourceRedirectFailureReasonProcessingError SourceRedirectFailureReason = "processing_error" + SourceRedirectFailureReasonUserAbort SourceRedirectFailureReason = "user_abort" +) + +// The status of the redirect, either `pending` (ready to be used by your customer to authenticate the transaction), `succeeded` (succesful authentication, cannot be reused) or `not_required` (redirect should not be used) or `failed` (failed authentication, cannot be reused). +type SourceRedirectStatus string + +// List of values that SourceRedirectStatus can take +const ( + SourceRedirectStatusFailed SourceRedirectStatus = "failed" + SourceRedirectStatusNotRequired SourceRedirectStatus = "not_required" + SourceRedirectStatusPending SourceRedirectStatus = "pending" + SourceRedirectStatusSucceeded SourceRedirectStatus = "succeeded" +) + +// The type of this order item. Must be `sku`, `tax`, or `shipping`. +type SourceSourceOrderItemType string + +// List of values that SourceSourceOrderItemType can take +const ( + SourceSourceOrderItemTypeDiscount SourceSourceOrderItemType = "discount" + SourceSourceOrderItemTypeSKU SourceSourceOrderItemType = "sku" + SourceSourceOrderItemTypeShipping SourceSourceOrderItemType = "shipping" + SourceSourceOrderItemTypeTax SourceSourceOrderItemType = "tax" +) + +// The status of the source, one of `canceled`, `chargeable`, `consumed`, `failed`, or `pending`. Only `chargeable` sources can be used to create a charge. +type SourceStatus string + +// List of values that SourceStatus can take +const ( + SourceStatusCanceled SourceStatus = "canceled" + SourceStatusChargeable SourceStatus = "chargeable" + SourceStatusConsumed SourceStatus = "consumed" + SourceStatusFailed SourceStatus = "failed" + SourceStatusPending SourceStatus = "pending" +) + +// Either `reusable` or `single_use`. Whether this source should be reusable or not. Some source types may or may not be reusable by construction, while others may leave the option at creation. If an incompatible value is passed, an error will be returned. +type SourceUsage string + +// List of values that SourceUsage can take +const ( + SourceUsageReusable SourceUsage = "reusable" + SourceUsageSingleUse SourceUsage = "single_use" +) + +// Delete a specified source for a given customer. +type SourceDetachParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *SourceDetachParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves an existing source object. Supply the unique source ID from a source creation request and Stripe will return the corresponding up-to-date source object information. +type SourceParams struct { + Params `form:"*"` + // Amount associated with the source. This is the amount for which the source will be chargeable once ready. Required for `single_use` sources. Not supported for `receiver` type sources, where charge amount may not be specified until funds land. + Amount *int64 `form:"amount"` + // The client secret of the source. Required if a publishable key is used to retrieve the source. + ClientSecret *string `form:"client_secret"` + // Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) associated with the source. This is the currency for which the source will be chargeable once ready. + Currency *string `form:"currency"` + // The `Customer` to whom the original source is attached to. Must be set when the original source is not a `Source` (e.g., `Card`). + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The authentication `flow` of the source to create. `flow` is one of `redirect`, `receiver`, `code_verification`, `none`. It is generally inferred unless a type supports multiple flows. + Flow *string `form:"flow"` + // Information about a mandate possibility attached to a source object (generally for bank debits) as well as its acceptance status. + Mandate *SourceMandateParams `form:"mandate"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The source to share. + OriginalSource *string `form:"original_source"` + // Information about the owner of the payment instrument that may be used or required by particular source types. + Owner *SourceOwnerParams `form:"owner"` + // Optional parameters for the receiver flow. Can be set only if the source is a receiver (`flow` is `receiver`). + Receiver *SourceReceiverParams `form:"receiver"` + // Parameters required for the redirect flow. Required if the source is authenticated by a redirect (`flow` is `redirect`). + Redirect *SourceRedirectParams `form:"redirect"` + // Information about the items and shipping associated with the source. Required for transactional credit (for example Klarna) sources before you can charge it. + SourceOrder *SourceSourceOrderParams `form:"source_order"` + // An arbitrary string to be displayed on your customer's statement. As an example, if your website is `RunClub` and the item you're charging for is a race ticket, you may want to specify a `statement_descriptor` of `RunClub 5K race ticket.` While many payment types will display this information, some may not display it at all. + StatementDescriptor *string `form:"statement_descriptor"` + // An optional token used to create the source. When passed, token properties will override source parameters. + Token *string `form:"token"` + // The `type` of the source to create. Required unless `customer` and `original_source` are specified (see the [Cloning card Sources](https://stripe.com/docs/sources/connect#cloning-card-sources) guide) + Type *string `form:"type"` + Usage *string `form:"usage"` +} + +// AddExpand appends a new field to expand. +func (p *SourceParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SourceParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The parameters required to store a mandate accepted offline. Should only be set if `mandate[type]` is `offline` +type SourceMandateAcceptanceOfflineParams struct { + // An email to contact you with if a copy of the mandate is requested, required if `type` is `offline`. + ContactEmail *string `form:"contact_email"` +} + +// The parameters required to store a mandate accepted online. Should only be set if `mandate[type]` is `online` +type SourceMandateAcceptanceOnlineParams struct { + // The Unix timestamp (in seconds) when the mandate was accepted or refused by the customer. + Date *int64 `form:"date"` + // The IP address from which the mandate was accepted or refused by the customer. + IP *string `form:"ip"` + // The user agent of the browser from which the mandate was accepted or refused by the customer. + UserAgent *string `form:"user_agent"` +} + +// The parameters required to notify Stripe of a mandate acceptance or refusal by the customer. +type SourceMandateAcceptanceParams struct { + // The Unix timestamp (in seconds) when the mandate was accepted or refused by the customer. + Date *int64 `form:"date"` + // The IP address from which the mandate was accepted or refused by the customer. + IP *string `form:"ip"` + // The parameters required to store a mandate accepted offline. Should only be set if `mandate[type]` is `offline` + Offline *SourceMandateAcceptanceOfflineParams `form:"offline"` + // The parameters required to store a mandate accepted online. Should only be set if `mandate[type]` is `online` + Online *SourceMandateAcceptanceOnlineParams `form:"online"` + // The status of the mandate acceptance. Either `accepted` (the mandate was accepted) or `refused` (the mandate was refused). + Status *string `form:"status"` + // The type of acceptance information included with the mandate. Either `online` or `offline` + Type *string `form:"type"` + // The user agent of the browser from which the mandate was accepted or refused by the customer. + UserAgent *string `form:"user_agent"` +} + +// Information about a mandate possibility attached to a source object (generally for bank debits) as well as its acceptance status. +type SourceMandateParams struct { + // The parameters required to notify Stripe of a mandate acceptance or refusal by the customer. + Acceptance *SourceMandateAcceptanceParams `form:"acceptance"` + // The amount specified by the mandate. (Leave null for a mandate covering all amounts) + Amount *int64 `form:"amount"` + // The currency specified by the mandate. (Must match `currency` of the source) + Currency *string `form:"currency"` + // The interval of debits permitted by the mandate. Either `one_time` (just permitting a single debit), `scheduled` (with debits on an agreed schedule or for clearly-defined events), or `variable`(for debits with any frequency) + Interval *string `form:"interval"` + // The method Stripe should use to notify the customer of upcoming debit instructions and/or mandate confirmation as required by the underlying debit network. Either `email` (an email is sent directly to the customer), `manual` (a `source.mandate_notification` event is sent to your webhooks endpoint and you should handle the notification) or `none` (the underlying debit network does not require any notification). + NotificationMethod *string `form:"notification_method"` +} + +// Information about the owner of the payment instrument that may be used or required by particular source types. +type SourceOwnerParams struct { + // Owner's address. + Address *AddressParams `form:"address"` + // Owner's email address. + Email *string `form:"email"` + // Owner's full name. + Name *string `form:"name"` + // Owner's phone number. + Phone *string `form:"phone"` +} + +// List of items constituting the order. +type SourceSourceOrderItemParams struct { + Amount *int64 `form:"amount"` + Currency *string `form:"currency"` + Description *string `form:"description"` + // The ID of the SKU being ordered. + Parent *string `form:"parent"` + // The quantity of this order item. When type is `sku`, this is the number of instances of the SKU to be ordered. + Quantity *int64 `form:"quantity"` + Type *string `form:"type"` +} + +// Information about the items and shipping associated with the source. Required for transactional credit (for example Klarna) sources before you can charge it. +type SourceSourceOrderParams struct { + // List of items constituting the order. + Items []*SourceSourceOrderItemParams `form:"items"` + // Shipping address for the order. Required if any of the SKUs are for products that have `shippable` set to true. + Shipping *ShippingDetailsParams `form:"shipping"` +} + +// Optional parameters for the receiver flow. Can be set only if the source is a receiver (`flow` is `receiver`). +type SourceReceiverParams struct { + // The method Stripe should use to request information needed to process a refund or mispayment. Either `email` (an email is sent directly to the customer) or `manual` (a `source.refund_attributes_required` event is sent to your webhooks endpoint). Refer to each payment method's documentation to learn which refund attributes may be required. + RefundAttributesMethod *string `form:"refund_attributes_method"` +} + +// Parameters required for the redirect flow. Required if the source is authenticated by a redirect (`flow` is `redirect`). +type SourceRedirectParams struct { + // The URL you provide to redirect the customer back to you after they authenticated their payment. It can use your application URI scheme in the context of a mobile application. + ReturnURL *string `form:"return_url"` +} + +// Retrieves an existing source object. Supply the unique source ID from a source creation request and Stripe will return the corresponding up-to-date source object information. +type SourceRetrieveParams struct { + Params `form:"*"` + // The client secret of the source. Required if a publishable key is used to retrieve the source. + ClientSecret *string `form:"client_secret"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *SourceRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The parameters required to store a mandate accepted offline. Should only be set if `mandate[type]` is `offline` +type SourceUpdateMandateAcceptanceOfflineParams struct { + // An email to contact you with if a copy of the mandate is requested, required if `type` is `offline`. + ContactEmail *string `form:"contact_email"` +} + +// The parameters required to store a mandate accepted online. Should only be set if `mandate[type]` is `online` +type SourceUpdateMandateAcceptanceOnlineParams struct { + // The Unix timestamp (in seconds) when the mandate was accepted or refused by the customer. + Date *int64 `form:"date"` + // The IP address from which the mandate was accepted or refused by the customer. + IP *string `form:"ip"` + // The user agent of the browser from which the mandate was accepted or refused by the customer. + UserAgent *string `form:"user_agent"` +} + +// The parameters required to notify Stripe of a mandate acceptance or refusal by the customer. +type SourceUpdateMandateAcceptanceParams struct { + // The Unix timestamp (in seconds) when the mandate was accepted or refused by the customer. + Date *int64 `form:"date"` + // The IP address from which the mandate was accepted or refused by the customer. + IP *string `form:"ip"` + // The parameters required to store a mandate accepted offline. Should only be set if `mandate[type]` is `offline` + Offline *SourceUpdateMandateAcceptanceOfflineParams `form:"offline"` + // The parameters required to store a mandate accepted online. Should only be set if `mandate[type]` is `online` + Online *SourceUpdateMandateAcceptanceOnlineParams `form:"online"` + // The status of the mandate acceptance. Either `accepted` (the mandate was accepted) or `refused` (the mandate was refused). + Status *string `form:"status"` + // The type of acceptance information included with the mandate. Either `online` or `offline` + Type *string `form:"type"` + // The user agent of the browser from which the mandate was accepted or refused by the customer. + UserAgent *string `form:"user_agent"` +} + +// Information about a mandate possibility attached to a source object (generally for bank debits) as well as its acceptance status. +type SourceUpdateMandateParams struct { + // The parameters required to notify Stripe of a mandate acceptance or refusal by the customer. + Acceptance *SourceUpdateMandateAcceptanceParams `form:"acceptance"` + // The amount specified by the mandate. (Leave null for a mandate covering all amounts) + Amount *int64 `form:"amount"` + // The currency specified by the mandate. (Must match `currency` of the source) + Currency *string `form:"currency"` + // The interval of debits permitted by the mandate. Either `one_time` (just permitting a single debit), `scheduled` (with debits on an agreed schedule or for clearly-defined events), or `variable`(for debits with any frequency) + Interval *string `form:"interval"` + // The method Stripe should use to notify the customer of upcoming debit instructions and/or mandate confirmation as required by the underlying debit network. Either `email` (an email is sent directly to the customer), `manual` (a `source.mandate_notification` event is sent to your webhooks endpoint and you should handle the notification) or `none` (the underlying debit network does not require any notification). + NotificationMethod *string `form:"notification_method"` +} + +// Information about the owner of the payment instrument that may be used or required by particular source types. +type SourceUpdateOwnerParams struct { + // Owner's address. + Address *AddressParams `form:"address"` + // Owner's email address. + Email *string `form:"email"` + // Owner's full name. + Name *string `form:"name"` + // Owner's phone number. + Phone *string `form:"phone"` +} + +// List of items constituting the order. +type SourceUpdateSourceOrderItemParams struct { + Amount *int64 `form:"amount"` + Currency *string `form:"currency"` + Description *string `form:"description"` + // The ID of the SKU being ordered. + Parent *string `form:"parent"` + // The quantity of this order item. When type is `sku`, this is the number of instances of the SKU to be ordered. + Quantity *int64 `form:"quantity"` + Type *string `form:"type"` +} + +// Information about the items and shipping associated with the source. Required for transactional credit (for example Klarna) sources before you can charge it. +type SourceUpdateSourceOrderParams struct { + // List of items constituting the order. + Items []*SourceUpdateSourceOrderItemParams `form:"items"` + // Shipping address for the order. Required if any of the SKUs are for products that have `shippable` set to true. + Shipping *ShippingDetailsParams `form:"shipping"` +} + +// Updates the specified source by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +// +// This request accepts the metadata and owner as arguments. It is also possible to update type specific information for selected payment methods. Please refer to our [payment method guides](https://docs.stripe.com/docs/sources) for more detail. +type SourceUpdateParams struct { + Params `form:"*"` + // Amount associated with the source. + Amount *int64 `form:"amount"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Information about a mandate possibility attached to a source object (generally for bank debits) as well as its acceptance status. + Mandate *SourceUpdateMandateParams `form:"mandate"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Information about the owner of the payment instrument that may be used or required by particular source types. + Owner *SourceUpdateOwnerParams `form:"owner"` + // Information about the items and shipping associated with the source. Required for transactional credit (for example Klarna) sources before you can charge it. + SourceOrder *SourceUpdateSourceOrderParams `form:"source_order"` +} + +// AddExpand appends a new field to expand. +func (p *SourceUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SourceUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The parameters required to store a mandate accepted offline. Should only be set if `mandate[type]` is `offline` +type SourceCreateMandateAcceptanceOfflineParams struct { + // An email to contact you with if a copy of the mandate is requested, required if `type` is `offline`. + ContactEmail *string `form:"contact_email"` +} + +// The parameters required to store a mandate accepted online. Should only be set if `mandate[type]` is `online` +type SourceCreateMandateAcceptanceOnlineParams struct { + // The Unix timestamp (in seconds) when the mandate was accepted or refused by the customer. + Date *int64 `form:"date"` + // The IP address from which the mandate was accepted or refused by the customer. + IP *string `form:"ip"` + // The user agent of the browser from which the mandate was accepted or refused by the customer. + UserAgent *string `form:"user_agent"` +} + +// The parameters required to notify Stripe of a mandate acceptance or refusal by the customer. +type SourceCreateMandateAcceptanceParams struct { + // The Unix timestamp (in seconds) when the mandate was accepted or refused by the customer. + Date *int64 `form:"date"` + // The IP address from which the mandate was accepted or refused by the customer. + IP *string `form:"ip"` + // The parameters required to store a mandate accepted offline. Should only be set if `mandate[type]` is `offline` + Offline *SourceCreateMandateAcceptanceOfflineParams `form:"offline"` + // The parameters required to store a mandate accepted online. Should only be set if `mandate[type]` is `online` + Online *SourceCreateMandateAcceptanceOnlineParams `form:"online"` + // The status of the mandate acceptance. Either `accepted` (the mandate was accepted) or `refused` (the mandate was refused). + Status *string `form:"status"` + // The type of acceptance information included with the mandate. Either `online` or `offline` + Type *string `form:"type"` + // The user agent of the browser from which the mandate was accepted or refused by the customer. + UserAgent *string `form:"user_agent"` +} + +// Information about a mandate possibility attached to a source object (generally for bank debits) as well as its acceptance status. +type SourceCreateMandateParams struct { + // The parameters required to notify Stripe of a mandate acceptance or refusal by the customer. + Acceptance *SourceCreateMandateAcceptanceParams `form:"acceptance"` + // The amount specified by the mandate. (Leave null for a mandate covering all amounts) + Amount *int64 `form:"amount"` + // The currency specified by the mandate. (Must match `currency` of the source) + Currency *string `form:"currency"` + // The interval of debits permitted by the mandate. Either `one_time` (just permitting a single debit), `scheduled` (with debits on an agreed schedule or for clearly-defined events), or `variable`(for debits with any frequency) + Interval *string `form:"interval"` + // The method Stripe should use to notify the customer of upcoming debit instructions and/or mandate confirmation as required by the underlying debit network. Either `email` (an email is sent directly to the customer), `manual` (a `source.mandate_notification` event is sent to your webhooks endpoint and you should handle the notification) or `none` (the underlying debit network does not require any notification). + NotificationMethod *string `form:"notification_method"` +} + +// Information about the owner of the payment instrument that may be used or required by particular source types. +type SourceCreateOwnerParams struct { + // Owner's address. + Address *AddressParams `form:"address"` + // Owner's email address. + Email *string `form:"email"` + // Owner's full name. + Name *string `form:"name"` + // Owner's phone number. + Phone *string `form:"phone"` +} + +// Optional parameters for the receiver flow. Can be set only if the source is a receiver (`flow` is `receiver`). +type SourceCreateReceiverParams struct { + // The method Stripe should use to request information needed to process a refund or mispayment. Either `email` (an email is sent directly to the customer) or `manual` (a `source.refund_attributes_required` event is sent to your webhooks endpoint). Refer to each payment method's documentation to learn which refund attributes may be required. + RefundAttributesMethod *string `form:"refund_attributes_method"` +} + +// Parameters required for the redirect flow. Required if the source is authenticated by a redirect (`flow` is `redirect`). +type SourceCreateRedirectParams struct { + // The URL you provide to redirect the customer back to you after they authenticated their payment. It can use your application URI scheme in the context of a mobile application. + ReturnURL *string `form:"return_url"` +} + +// List of items constituting the order. +type SourceCreateSourceOrderItemParams struct { + Amount *int64 `form:"amount"` + Currency *string `form:"currency"` + Description *string `form:"description"` + // The ID of the SKU being ordered. + Parent *string `form:"parent"` + // The quantity of this order item. When type is `sku`, this is the number of instances of the SKU to be ordered. + Quantity *int64 `form:"quantity"` + Type *string `form:"type"` +} + +// Information about the items and shipping associated with the source. Required for transactional credit (for example Klarna) sources before you can charge it. +type SourceCreateSourceOrderParams struct { + // List of items constituting the order. + Items []*SourceCreateSourceOrderItemParams `form:"items"` + // Shipping address for the order. Required if any of the SKUs are for products that have `shippable` set to true. + Shipping *ShippingDetailsParams `form:"shipping"` +} + +// Creates a new source object. +type SourceCreateParams struct { + Params `form:"*"` + // Amount associated with the source. This is the amount for which the source will be chargeable once ready. Required for `single_use` sources. Not supported for `receiver` type sources, where charge amount may not be specified until funds land. + Amount *int64 `form:"amount"` + // Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) associated with the source. This is the currency for which the source will be chargeable once ready. + Currency *string `form:"currency"` + // The `Customer` to whom the original source is attached to. Must be set when the original source is not a `Source` (e.g., `Card`). + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The authentication `flow` of the source to create. `flow` is one of `redirect`, `receiver`, `code_verification`, `none`. It is generally inferred unless a type supports multiple flows. + Flow *string `form:"flow"` + // Information about a mandate possibility attached to a source object (generally for bank debits) as well as its acceptance status. + Mandate *SourceCreateMandateParams `form:"mandate"` + Metadata map[string]string `form:"metadata"` + // The source to share. + OriginalSource *string `form:"original_source"` + // Information about the owner of the payment instrument that may be used or required by particular source types. + Owner *SourceCreateOwnerParams `form:"owner"` + // Optional parameters for the receiver flow. Can be set only if the source is a receiver (`flow` is `receiver`). + Receiver *SourceCreateReceiverParams `form:"receiver"` + // Parameters required for the redirect flow. Required if the source is authenticated by a redirect (`flow` is `redirect`). + Redirect *SourceCreateRedirectParams `form:"redirect"` + // Information about the items and shipping associated with the source. Required for transactional credit (for example Klarna) sources before you can charge it. + SourceOrder *SourceCreateSourceOrderParams `form:"source_order"` + // An arbitrary string to be displayed on your customer's statement. As an example, if your website is `RunClub` and the item you're charging for is a race ticket, you may want to specify a `statement_descriptor` of `RunClub 5K race ticket.` While many payment types will display this information, some may not display it at all. + StatementDescriptor *string `form:"statement_descriptor"` + // An optional token used to create the source. When passed, token properties will override source parameters. + Token *string `form:"token"` + // The `type` of the source to create. Required unless `customer` and `original_source` are specified (see the [Cloning card Sources](https://stripe.com/docs/sources/connect#cloning-card-sources) guide) + Type *string `form:"type"` + Usage *string `form:"usage"` +} + +// AddExpand appends a new field to expand. +func (p *SourceCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SourceCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +type SourceACHCreditTransfer struct { + AccountNumber string `json:"account_number"` + BankName string `json:"bank_name"` + Fingerprint string `json:"fingerprint"` + RefundAccountHolderName string `json:"refund_account_holder_name"` + RefundAccountHolderType string `json:"refund_account_holder_type"` + RefundRoutingNumber string `json:"refund_routing_number"` + RoutingNumber string `json:"routing_number"` + SwiftCode string `json:"swift_code"` +} +type SourceACHDebit struct { + BankName string `json:"bank_name"` + Country string `json:"country"` + Fingerprint string `json:"fingerprint"` + Last4 string `json:"last4"` + RoutingNumber string `json:"routing_number"` + Type string `json:"type"` +} +type SourceACSSDebit struct { + BankAddressCity string `json:"bank_address_city"` + BankAddressLine1 string `json:"bank_address_line_1"` + BankAddressLine2 string `json:"bank_address_line_2"` + BankAddressPostalCode string `json:"bank_address_postal_code"` + BankName string `json:"bank_name"` + Category string `json:"category"` + Country string `json:"country"` + Fingerprint string `json:"fingerprint"` + Last4 string `json:"last4"` + RoutingNumber string `json:"routing_number"` +} +type SourceAlipay struct { + DataString string `json:"data_string"` + NativeURL string `json:"native_url"` + StatementDescriptor string `json:"statement_descriptor"` +} +type SourceAUBECSDebit struct { + BSBNumber string `json:"bsb_number"` + Fingerprint string `json:"fingerprint"` + Last4 string `json:"last4"` +} +type SourceBancontact struct { + BankCode string `json:"bank_code"` + BankName string `json:"bank_name"` + BIC string `json:"bic"` + IBANLast4 string `json:"iban_last4"` + PreferredLanguage string `json:"preferred_language"` + StatementDescriptor string `json:"statement_descriptor"` +} +type SourceCard struct { + AddressLine1Check string `json:"address_line1_check"` + AddressZipCheck string `json:"address_zip_check"` + Brand string `json:"brand"` + Country string `json:"country"` + CVCCheck string `json:"cvc_check"` + Description string `json:"description"` + DynamicLast4 string `json:"dynamic_last4"` + ExpMonth int64 `json:"exp_month"` + ExpYear int64 `json:"exp_year"` + Fingerprint string `json:"fingerprint"` + Funding string `json:"funding"` + IIN string `json:"iin"` + Issuer string `json:"issuer"` + Last4 string `json:"last4"` + Name string `json:"name"` + ThreeDSecure string `json:"three_d_secure"` + TokenizationMethod string `json:"tokenization_method"` +} +type SourceCardPresent struct { + ApplicationCryptogram string `json:"application_cryptogram"` + ApplicationPreferredName string `json:"application_preferred_name"` + AuthorizationCode string `json:"authorization_code"` + AuthorizationResponseCode string `json:"authorization_response_code"` + Brand string `json:"brand"` + Country string `json:"country"` + CVMType string `json:"cvm_type"` + DataType string `json:"data_type"` + DedicatedFileName string `json:"dedicated_file_name"` + Description string `json:"description"` + EmvAuthData string `json:"emv_auth_data"` + EvidenceCustomerSignature string `json:"evidence_customer_signature"` + EvidenceTransactionCertificate string `json:"evidence_transaction_certificate"` + ExpMonth int64 `json:"exp_month"` + ExpYear int64 `json:"exp_year"` + Fingerprint string `json:"fingerprint"` + Funding string `json:"funding"` + IIN string `json:"iin"` + Issuer string `json:"issuer"` + Last4 string `json:"last4"` + POSDeviceID string `json:"pos_device_id"` + POSEntryMode string `json:"pos_entry_mode"` + Reader string `json:"reader"` + ReadMethod string `json:"read_method"` + TerminalVerificationResults string `json:"terminal_verification_results"` + TransactionStatusInformation string `json:"transaction_status_information"` +} +type SourceCodeVerification struct { + // The number of attempts remaining to authenticate the source object with a verification code. + AttemptsRemaining int64 `json:"attempts_remaining"` + // The status of the code verification, either `pending` (awaiting verification, `attempts_remaining` should be greater than 0), `succeeded` (successful verification) or `failed` (failed verification, cannot be verified anymore as `attempts_remaining` should be 0). + Status SourceCodeVerificationStatus `json:"status"` +} +type SourceEPS struct { + Reference string `json:"reference"` + StatementDescriptor string `json:"statement_descriptor"` +} +type SourceGiropay struct { + BankCode string `json:"bank_code"` + BankName string `json:"bank_name"` + BIC string `json:"bic"` + StatementDescriptor string `json:"statement_descriptor"` +} +type SourceIDEAL struct { + Bank string `json:"bank"` + BIC string `json:"bic"` + IBANLast4 string `json:"iban_last4"` + StatementDescriptor string `json:"statement_descriptor"` +} +type SourceKlarna struct { + BackgroundImageURL string `json:"background_image_url"` + ClientToken string `json:"client_token"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Locale string `json:"locale"` + LogoURL string `json:"logo_url"` + PageTitle string `json:"page_title"` + PayLaterAssetURLsDescriptive string `json:"pay_later_asset_urls_descriptive"` + PayLaterAssetURLsStandard string `json:"pay_later_asset_urls_standard"` + PayLaterName string `json:"pay_later_name"` + PayLaterRedirectURL string `json:"pay_later_redirect_url"` + PaymentMethodCategories string `json:"payment_method_categories"` + PayNowAssetURLsDescriptive string `json:"pay_now_asset_urls_descriptive"` + PayNowAssetURLsStandard string `json:"pay_now_asset_urls_standard"` + PayNowName string `json:"pay_now_name"` + PayNowRedirectURL string `json:"pay_now_redirect_url"` + PayOverTimeAssetURLsDescriptive string `json:"pay_over_time_asset_urls_descriptive"` + PayOverTimeAssetURLsStandard string `json:"pay_over_time_asset_urls_standard"` + PayOverTimeName string `json:"pay_over_time_name"` + PayOverTimeRedirectURL string `json:"pay_over_time_redirect_url"` + PurchaseCountry string `json:"purchase_country"` + PurchaseType string `json:"purchase_type"` + RedirectURL string `json:"redirect_url"` + ShippingDelay int64 `json:"shipping_delay"` + ShippingFirstName string `json:"shipping_first_name"` + ShippingLastName string `json:"shipping_last_name"` +} +type SourceMultibanco struct { + Entity string `json:"entity"` + Reference string `json:"reference"` + RefundAccountHolderAddressCity string `json:"refund_account_holder_address_city"` + RefundAccountHolderAddressCountry string `json:"refund_account_holder_address_country"` + RefundAccountHolderAddressLine1 string `json:"refund_account_holder_address_line1"` + RefundAccountHolderAddressLine2 string `json:"refund_account_holder_address_line2"` + RefundAccountHolderAddressPostalCode string `json:"refund_account_holder_address_postal_code"` + RefundAccountHolderAddressState string `json:"refund_account_holder_address_state"` + RefundAccountHolderName string `json:"refund_account_holder_name"` + RefundIBAN string `json:"refund_iban"` +} + +// Information about the owner of the payment instrument that may be used or required by particular source types. +type SourceOwner struct { + // Owner's address. + Address *Address `json:"address"` + // Owner's email address. + Email string `json:"email"` + // Owner's full name. + Name string `json:"name"` + // Owner's phone number (including extension). + Phone string `json:"phone"` + // Verified owner's address. Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. They cannot be set or mutated. + VerifiedAddress *Address `json:"verified_address"` + // Verified owner's email address. Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. They cannot be set or mutated. + VerifiedEmail string `json:"verified_email"` + // Verified owner's full name. Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. They cannot be set or mutated. + VerifiedName string `json:"verified_name"` + // Verified owner's phone number (including extension). Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. They cannot be set or mutated. + VerifiedPhone string `json:"verified_phone"` +} +type SourceP24 struct { + Reference string `json:"reference"` +} +type SourceReceiver struct { + // The address of the receiver source. This is the value that should be communicated to the customer to send their funds to. + Address string `json:"address"` + // The total amount that was moved to your balance. This is almost always equal to the amount charged. In rare cases when customers deposit excess funds and we are unable to refund those, those funds get moved to your balance and show up in amount_charged as well. The amount charged is expressed in the source's currency. + AmountCharged int64 `json:"amount_charged"` + // The total amount received by the receiver source. `amount_received = amount_returned + amount_charged` should be true for consumed sources unless customers deposit excess funds. The amount received is expressed in the source's currency. + AmountReceived int64 `json:"amount_received"` + // The total amount that was returned to the customer. The amount returned is expressed in the source's currency. + AmountReturned int64 `json:"amount_returned"` + // Type of refund attribute method, one of `email`, `manual`, or `none`. + RefundAttributesMethod SourceReceiverRefundAttributesMethod `json:"refund_attributes_method"` + // Type of refund attribute status, one of `missing`, `requested`, or `available`. + RefundAttributesStatus SourceReceiverRefundAttributesStatus `json:"refund_attributes_status"` +} +type SourceRedirect struct { + // The failure reason for the redirect, either `user_abort` (the customer aborted or dropped out of the redirect flow), `declined` (the authentication failed or the transaction was declined), or `processing_error` (the redirect failed due to a technical error). Present only if the redirect status is `failed`. + FailureReason SourceRedirectFailureReason `json:"failure_reason"` + // The URL you provide to redirect the customer to after they authenticated their payment. + ReturnURL string `json:"return_url"` + // The status of the redirect, either `pending` (ready to be used by your customer to authenticate the transaction), `succeeded` (succesful authentication, cannot be reused) or `not_required` (redirect should not be used) or `failed` (failed authentication, cannot be reused). + Status SourceRedirectStatus `json:"status"` + // The URL provided to you to redirect a customer to as part of a `redirect` authentication flow. + URL string `json:"url"` +} +type SourceSEPACreditTransfer struct { + BankName string `json:"bank_name"` + BIC string `json:"bic"` + IBAN string `json:"iban"` + RefundAccountHolderAddressCity string `json:"refund_account_holder_address_city"` + RefundAccountHolderAddressCountry string `json:"refund_account_holder_address_country"` + RefundAccountHolderAddressLine1 string `json:"refund_account_holder_address_line1"` + RefundAccountHolderAddressLine2 string `json:"refund_account_holder_address_line2"` + RefundAccountHolderAddressPostalCode string `json:"refund_account_holder_address_postal_code"` + RefundAccountHolderAddressState string `json:"refund_account_holder_address_state"` + RefundAccountHolderName string `json:"refund_account_holder_name"` + RefundIBAN string `json:"refund_iban"` +} +type SourceSEPADebit struct { + BankCode string `json:"bank_code"` + BranchCode string `json:"branch_code"` + Country string `json:"country"` + Fingerprint string `json:"fingerprint"` + Last4 string `json:"last4"` + MandateReference string `json:"mandate_reference"` + MandateURL string `json:"mandate_url"` +} +type SourceSofort struct { + BankCode string `json:"bank_code"` + BankName string `json:"bank_name"` + BIC string `json:"bic"` + Country string `json:"country"` + IBANLast4 string `json:"iban_last4"` + PreferredLanguage string `json:"preferred_language"` + StatementDescriptor string `json:"statement_descriptor"` +} + +// List of items constituting the order. +type SourceSourceOrderItem struct { + // The amount (price) for this order item. + Amount int64 `json:"amount"` + // This currency of this order item. Required when `amount` is present. + Currency Currency `json:"currency"` + // Human-readable description for this order item. + Description string `json:"description"` + // The ID of the associated object for this line item. Expandable if not null (e.g., expandable to a SKU). + Parent string `json:"parent"` + // The quantity of this order item. When type is `sku`, this is the number of instances of the SKU to be ordered. + Quantity int64 `json:"quantity"` + // The type of this order item. Must be `sku`, `tax`, or `shipping`. + Type SourceSourceOrderItemType `json:"type"` +} +type SourceSourceOrder struct { + // A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount for the order. + Amount int64 `json:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // The email address of the customer placing the order. + Email string `json:"email"` + // List of items constituting the order. + Items []*SourceSourceOrderItem `json:"items"` + Shipping ShippingDetails `json:"shipping"` +} +type SourceThreeDSecure struct { + AddressLine1Check string `json:"address_line1_check"` + AddressZipCheck string `json:"address_zip_check"` + Authenticated bool `json:"authenticated"` + Brand string `json:"brand"` + Card string `json:"card"` + Country string `json:"country"` + Customer string `json:"customer"` + CVCCheck string `json:"cvc_check"` + Description string `json:"description"` + DynamicLast4 string `json:"dynamic_last4"` + ExpMonth int64 `json:"exp_month"` + ExpYear int64 `json:"exp_year"` + Fingerprint string `json:"fingerprint"` + Funding string `json:"funding"` + IIN string `json:"iin"` + Issuer string `json:"issuer"` + Last4 string `json:"last4"` + Name string `json:"name"` + ThreeDSecure string `json:"three_d_secure"` + TokenizationMethod string `json:"tokenization_method"` +} +type SourceWeChat struct { + PrepayID string `json:"prepay_id"` + QRCodeURL string `json:"qr_code_url"` + StatementDescriptor string `json:"statement_descriptor"` +} + +// `Source` objects allow you to accept a variety of payment methods. They +// represent a customer's payment instrument, and can be used with the Stripe API +// just like a `Card` object: once chargeable, they can be charged, or can be +// attached to customers. +// +// Stripe doesn't recommend using the deprecated [Sources API](https://stripe.com/docs/api/sources). +// We recommend that you adopt the [PaymentMethods API](https://stripe.com/docs/api/payment_methods). +// This newer API provides access to our latest features and payment method types. +// +// Related guides: [Sources API](https://stripe.com/docs/sources) and [Sources & Customers](https://stripe.com/docs/sources/customers). +type Source struct { + APIResource + ACHCreditTransfer *SourceACHCreditTransfer `json:"ach_credit_transfer"` + ACHDebit *SourceACHDebit `json:"ach_debit"` + ACSSDebit *SourceACSSDebit `json:"acss_debit"` + Alipay *SourceAlipay `json:"alipay"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to “unspecified”. + AllowRedisplay SourceAllowRedisplay `json:"allow_redisplay"` + // A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount associated with the source. This is the amount for which the source will be chargeable once ready. Required for `single_use` sources. + Amount int64 `json:"amount"` + AUBECSDebit *SourceAUBECSDebit `json:"au_becs_debit"` + Bancontact *SourceBancontact `json:"bancontact"` + Card *SourceCard `json:"card"` + CardPresent *SourceCardPresent `json:"card_present"` + // The client secret of the source. Used for client-side retrieval using a publishable key. + ClientSecret string `json:"client_secret"` + CodeVerification *SourceCodeVerification `json:"code_verification"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) associated with the source. This is the currency for which the source will be chargeable once ready. Required for `single_use` sources. + Currency Currency `json:"currency"` + // The ID of the customer to which this source is attached. This will not be present when the source has not been attached to a customer. + Customer string `json:"customer"` + EPS *SourceEPS `json:"eps"` + // The authentication `flow` of the source. `flow` is one of `redirect`, `receiver`, `code_verification`, `none`. + Flow SourceFlow `json:"flow"` + Giropay *SourceGiropay `json:"giropay"` + // Unique identifier for the object. + ID string `json:"id"` + IDEAL *SourceIDEAL `json:"ideal"` + Klarna *SourceKlarna `json:"klarna"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + Multibanco *SourceMultibanco `json:"multibanco"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Information about the owner of the payment instrument that may be used or required by particular source types. + Owner *SourceOwner `json:"owner"` + P24 *SourceP24 `json:"p24"` + Receiver *SourceReceiver `json:"receiver"` + Redirect *SourceRedirect `json:"redirect"` + SEPACreditTransfer *SourceSEPACreditTransfer `json:"sepa_credit_transfer"` + SEPADebit *SourceSEPADebit `json:"sepa_debit"` + Sofort *SourceSofort `json:"sofort"` + SourceOrder *SourceSourceOrder `json:"source_order"` + // Extra information about a source. This will appear on your customer's statement every time you charge the source. + StatementDescriptor string `json:"statement_descriptor"` + // The status of the source, one of `canceled`, `chargeable`, `consumed`, `failed`, or `pending`. Only `chargeable` sources can be used to create a charge. + Status SourceStatus `json:"status"` + ThreeDSecure *SourceThreeDSecure `json:"three_d_secure"` + // The `type` of the source. The `type` is a payment method, one of `ach_credit_transfer`, `ach_debit`, `alipay`, `bancontact`, `card`, `card_present`, `eps`, `giropay`, `ideal`, `multibanco`, `klarna`, `p24`, `sepa_debit`, `sofort`, `three_d_secure`, or `wechat`. An additional hash is included on the source with a name matching this value. It contains additional information specific to the [payment method](https://stripe.com/docs/sources) used. + Type string `json:"type"` + // Either `reusable` or `single_use`. Whether this source should be reusable or not. Some source types may or may not be reusable by construction, while others may leave the option at creation. If an incompatible value is passed, an error will be returned. + Usage SourceUsage `json:"usage"` + WeChat *SourceWeChat `json:"wechat"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/source_service.go b/vendor/github.com/stripe/stripe-go/v82/source_service.go new file mode 100644 index 00000000..1f744914 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/source_service.go @@ -0,0 +1,73 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "fmt" + "net/http" +) + +// v1SourceService is used to invoke /v1/sources APIs. +type v1SourceService struct { + B Backend + Key string +} + +// Creates a new source object. +func (c v1SourceService) Create(ctx context.Context, params *SourceCreateParams) (*Source, error) { + if params == nil { + params = &SourceCreateParams{} + } + params.Context = ctx + source := &Source{} + err := c.B.Call(http.MethodPost, "/v1/sources", c.Key, params, source) + return source, err +} + +// Retrieves an existing source object. Supply the unique source ID from a source creation request and Stripe will return the corresponding up-to-date source object information. +func (c v1SourceService) Retrieve(ctx context.Context, id string, params *SourceRetrieveParams) (*Source, error) { + if params == nil { + params = &SourceRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/sources/%s", id) + source := &Source{} + err := c.B.Call(http.MethodGet, path, c.Key, params, source) + return source, err +} + +// Updates the specified source by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +// +// This request accepts the metadata and owner as arguments. It is also possible to update type specific information for selected payment methods. Please refer to our [payment method guides](https://docs.stripe.com/docs/sources) for more detail. +func (c v1SourceService) Update(ctx context.Context, id string, params *SourceUpdateParams) (*Source, error) { + if params == nil { + params = &SourceUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/sources/%s", id) + source := &Source{} + err := c.B.Call(http.MethodPost, path, c.Key, params, source) + return source, err +} + +// Delete a specified source for a given customer. +func (c v1SourceService) Detach(ctx context.Context, id string, params *SourceDetachParams) (*Source, error) { + if params.Customer == nil { + return nil, fmt.Errorf( + "Invalid source detach params: Customer needs to be set") + } + if params == nil { + params = &SourceDetachParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/customers/%s/sources/%s", StringValue(params.Customer), id) + source := &Source{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, source) + return source, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/sourcetransaction.go b/vendor/github.com/stripe/stripe-go/v82/sourcetransaction.go new file mode 100644 index 00000000..bf61461e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/sourcetransaction.go @@ -0,0 +1,110 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// List source transactions for a given source. +type SourceTransactionListParams struct { + ListParams `form:"*"` + Source *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *SourceTransactionListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type SourceTransactionACHCreditTransfer struct { + // Customer data associated with the transfer. + CustomerData string `json:"customer_data"` + // Bank account fingerprint associated with the transfer. + Fingerprint string `json:"fingerprint"` + // Last 4 digits of the account number associated with the transfer. + Last4 string `json:"last4"` + // Routing number associated with the transfer. + RoutingNumber string `json:"routing_number"` +} +type SourceTransactionCHFCreditTransfer struct { + // Reference associated with the transfer. + Reference string `json:"reference"` + // Sender's country address. + SenderAddressCountry string `json:"sender_address_country"` + // Sender's line 1 address. + SenderAddressLine1 string `json:"sender_address_line1"` + // Sender's bank account IBAN. + SenderIBAN string `json:"sender_iban"` + // Sender's name. + SenderName string `json:"sender_name"` +} +type SourceTransactionGBPCreditTransfer struct { + // Bank account fingerprint associated with the Stripe owned bank account receiving the transfer. + Fingerprint string `json:"fingerprint"` + // The credit transfer rails the sender used to push this transfer. The possible rails are: Faster Payments, BACS, CHAPS, and wire transfers. Currently only Faster Payments is supported. + FundingMethod string `json:"funding_method"` + // Last 4 digits of sender account number associated with the transfer. + Last4 string `json:"last4"` + // Sender entered arbitrary information about the transfer. + Reference string `json:"reference"` + // Sender account number associated with the transfer. + SenderAccountNumber string `json:"sender_account_number"` + // Sender name associated with the transfer. + SenderName string `json:"sender_name"` + // Sender sort code associated with the transfer. + SenderSortCode string `json:"sender_sort_code"` +} +type SourceTransactionPaperCheck struct { + // Time at which the deposited funds will be available for use. Measured in seconds since the Unix epoch. + AvailableAt string `json:"available_at"` + // Comma-separated list of invoice IDs associated with the paper check. + Invoices string `json:"invoices"` +} +type SourceTransactionSEPACreditTransfer struct { + // Reference associated with the transfer. + Reference string `json:"reference"` + // Sender's bank account IBAN. + SenderIBAN string `json:"sender_iban"` + // Sender's name. + SenderName string `json:"sender_name"` +} + +// Some payment methods have no required amount that a customer must send. +// Customers can be instructed to send any amount, and it can be made up of +// multiple transactions. As such, sources can have multiple associated +// transactions. +type SourceTransaction struct { + ACHCreditTransfer *SourceTransactionACHCreditTransfer `json:"ach_credit_transfer"` + // A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the amount your customer has pushed to the receiver. + Amount int64 `json:"amount"` + CHFCreditTransfer *SourceTransactionCHFCreditTransfer `json:"chf_credit_transfer"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + GBPCreditTransfer *SourceTransactionGBPCreditTransfer `json:"gbp_credit_transfer"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + PaperCheck *SourceTransactionPaperCheck `json:"paper_check"` + SEPACreditTransfer *SourceTransactionSEPACreditTransfer `json:"sepa_credit_transfer"` + // The ID of the source this transaction is attached to. + Source string `json:"source"` + // The status of the transaction, one of `succeeded`, `pending`, or `failed`. + Status string `json:"status"` + // The type of source this transaction is attached to. + Type string `json:"type"` +} + +// SourceTransactionList is a list of SourceTransactions as retrieved from a list endpoint. +type SourceTransactionList struct { + APIResource + ListMeta + Data []*SourceTransaction `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/sourcetransaction_service.go b/vendor/github.com/stripe/stripe-go/v82/sourcetransaction_service.go new file mode 100644 index 00000000..a016eeaf --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/sourcetransaction_service.go @@ -0,0 +1,39 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1SourceTransactionService is used to invoke sourcetransaction related APIs. +type v1SourceTransactionService struct { + B Backend + Key string +} + +// List source transactions for a given source. +func (c v1SourceTransactionService) List(ctx context.Context, listParams *SourceTransactionListParams) Seq2[*SourceTransaction, error] { + if listParams == nil { + listParams = &SourceTransactionListParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/sources/%s/source_transactions", StringValue(listParams.Source)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*SourceTransaction, ListContainer, error) { + list := &SourceTransactionList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/staticcheck.conf b/vendor/github.com/stripe/stripe-go/v82/staticcheck.conf new file mode 100644 index 00000000..33b48ea9 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/staticcheck.conf @@ -0,0 +1 @@ +checks = ["all", "-ST1005", "-ST1021"] diff --git a/vendor/github.com/stripe/stripe-go/v82/stripe.go b/vendor/github.com/stripe/stripe-go/v82/stripe.go new file mode 100644 index 00000000..46dbad35 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/stripe.go @@ -0,0 +1,1693 @@ +// Package stripe provides the binding for Stripe REST APIs. +package stripe + +import ( + "bytes" + "context" + "crypto/x509" + "encoding/json" + "errors" + "fmt" + "io" + "io/ioutil" + "math/rand" + "net/http" + "net/url" + "os/exec" + "reflect" + "regexp" + "runtime" + "strings" + "sync" + "time" + + "github.com/stripe/stripe-go/v82/form" +) + +// +// Public constants +// + +const ( + // APIBackend is a constant representing the API service backend. + APIBackend SupportedBackend = "api" + + // APIURL is the URL of the API service backend. + APIURL string = "https://api.stripe.com" + + // ClientVersion is the version of the stripe-go library being used. + ClientVersion string = clientversion + + // ConnectURL is the URL for OAuth. + ConnectURL string = "https://connect.stripe.com" + + // ConnectBackend is a constant representing the connect service backend for + // OAuth. + ConnectBackend SupportedBackend = "connect" + + // DefaultMaxNetworkRetries is the default maximum number of retries made + // by a Stripe client. + DefaultMaxNetworkRetries int64 = 2 + + MeterEventsBackend SupportedBackend = "meterevents" + + MeterEventsURL = "https://meter-events.stripe.com" + + // UnknownPlatform is the string returned as the system name if we couldn't get + // one from `uname`. + UnknownPlatform string = "unknown platform" + + // UploadsBackend is a constant representing the uploads service backend. + UploadsBackend SupportedBackend = "uploads" + + // UploadsURL is the URL of the uploads service backend. + UploadsURL string = "https://files.stripe.com" +) + +// +// Public variables +// + +// EnableTelemetry is a global override for enabling client telemetry, which +// sends request performance metrics to Stripe via the `X-Stripe-Client-Telemetry` +// header. If set to true, all clients will send telemetry metrics. Defaults to +// true. +// +// Telemetry can also be disabled on a per-client basis by instead creating a +// `BackendConfig` with `EnableTelemetry: false`. +var EnableTelemetry = true + +// Key is the Stripe API key used globally in the binding. +var Key string + +// +// Public types +// + +// APIResponse encapsulates some common features of a response from the +// Stripe API. +type APIResponse struct { + // Header contain a map of all HTTP header keys to values. Its behavior and + // caveats are identical to that of http.Header. + Header http.Header + + // IdempotencyKey contains the idempotency key used with this request. + // Idempotency keys are a Stripe-specific concept that helps guarantee that + // requests that fail and need to be retried are not duplicated. + IdempotencyKey string + + // RawJSON contains the response body as raw bytes. + RawJSON []byte + + // RequestID contains a string that uniquely identifies the Stripe request. + // Used for debugging or support purposes. + RequestID string + + // Status is a status code and message. e.g. "200 OK" + Status string + + // StatusCode is a status code as integer. e.g. 200 + StatusCode int + + duration *time.Duration +} + +// StreamingAPIResponse encapsulates some common features of a response from the +// Stripe API whose body can be streamed. This is used for "file downloads", and +// the `Body` property is an io.ReadCloser, so the user can stream it to another +// location such as a file or network request without buffering the entire body +// into memory. +type StreamingAPIResponse struct { + Header http.Header + IdempotencyKey string + Body io.ReadCloser + RequestID string + Status string + StatusCode int + duration *time.Duration +} + +func newAPIResponse(res *http.Response, resBody []byte, requestDuration *time.Duration) *APIResponse { + return &APIResponse{ + Header: res.Header, + IdempotencyKey: res.Header.Get("Idempotency-Key"), + RawJSON: resBody, + RequestID: res.Header.Get("Request-Id"), + Status: res.Status, + StatusCode: res.StatusCode, + duration: requestDuration, + } +} + +func newStreamingAPIResponse(res *http.Response, body io.ReadCloser, requestDuration *time.Duration) *StreamingAPIResponse { + return &StreamingAPIResponse{ + Header: res.Header, + IdempotencyKey: res.Header.Get("Idempotency-Key"), + Body: body, + RequestID: res.Header.Get("Request-Id"), + Status: res.Status, + StatusCode: res.StatusCode, + duration: requestDuration, + } +} + +// APIResource is a type assigned to structs that may come from Stripe API +// endpoints and contains facilities common to all of them. +type APIResource struct { + LastResponse *APIResponse `json:"-"` +} + +// APIStream is a type assigned to streaming responses that may come from Stripe API +type APIStream struct { + LastResponse *StreamingAPIResponse +} + +// SetLastResponse sets the HTTP response that returned the API resource. +func (r *APIResource) SetLastResponse(response *APIResponse) { + r.LastResponse = response +} + +// SetLastResponse sets the HTTP response that returned the API resource. +func (r *APIStream) SetLastResponse(response *StreamingAPIResponse) { + r.LastResponse = response +} + +// AppInfo contains information about the "app" which this integration belongs +// to. This should be reserved for plugins that wish to identify themselves +// with Stripe. +type AppInfo struct { + Name string `json:"name"` + PartnerID string `json:"partner_id"` + URL string `json:"url"` + Version string `json:"version"` +} + +// formatUserAgent formats an AppInfo in a way that's suitable to be appended +// to a User-Agent string. Note that this format is shared between all +// libraries so if it's changed, it should be changed everywhere. +func (a *AppInfo) formatUserAgent() string { + str := a.Name + if a.Version != "" { + str += "/" + a.Version + } + if a.URL != "" { + str += " (" + a.URL + ")" + } + return str +} + +// Backend is an interface for making calls against a Stripe service. +// This interface exists to enable mocking for during testing if needed. +type Backend interface { + Call(method, path, key string, params ParamsContainer, v LastResponseSetter) error + CallStreaming(method, path, key string, params ParamsContainer, v StreamingLastResponseSetter) error + CallRaw(method, path, key string, body []byte, params *Params, v LastResponseSetter) error + CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *Params, v LastResponseSetter) error + SetMaxNetworkRetries(maxNetworkRetries int64) +} + +type RawRequestBackend interface { + RawRequest(method, path, key, content string, params *RawParams) (*APIResponse, error) +} + +// BackendConfig is used to configure a new Stripe backend. +type BackendConfig struct { + // EnableTelemetry allows request metrics (request id and duration) to be sent + // to Stripe in subsequent requests via the `X-Stripe-Client-Telemetry` header. + // + // This value is a pointer to allow us to differentiate an unset versus + // empty value. Use stripe.Bool for an easy way to set this value. + // + // Defaults to false. + EnableTelemetry *bool + + // HTTPClient is an HTTP client instance to use when making API requests. + // + // If left unset, it'll be set to a default HTTP client for the package. + HTTPClient *http.Client + + // LeveledLogger is the logger that the backend will use to log errors, + // warnings, and informational messages. + // + // LeveledLoggerInterface is implemented by LeveledLogger, and one can be + // initialized at the desired level of logging. LeveledLoggerInterface + // also provides out-of-the-box compatibility with a Logrus Logger, but may + // require a thin shim for use with other logging libraries that use less + // standard conventions like Zap. + // + // Defaults to DefaultLeveledLogger. + // + // To set a logger that logs nothing, set this to a stripe.LeveledLogger + // with a Level of LevelNull (simply setting this field to nil will not + // work). + LeveledLogger LeveledLoggerInterface + + // MaxNetworkRetries sets maximum number of times that the library will + // retry requests that appear to have failed due to an intermittent + // problem. + // + // This value is a pointer to allow us to differentiate an unset versus + // empty value. Use stripe.Int64 for an easy way to set this value. + // + // Defaults to DefaultMaxNetworkRetries (2). + MaxNetworkRetries *int64 + + // URL is the base URL to use for API paths. + // + // This value is a pointer to allow us to differentiate an unset versus + // empty value. Use stripe.String for an easy way to set this value. + // + // If left empty, it'll be set to the default for the SupportedBackend. + URL *string + + // StripeContext is used to set the Stripe-Context header on a request. + // The Stripe-Context header can be used to set the account or other context + // for the request. + StripeContext *string +} + +// BackendImplementation is the internal implementation for making HTTP calls +// to Stripe. +// +// The public use of this struct is deprecated. It will be unexported in a +// future version. +type BackendImplementation struct { + Type SupportedBackend + URL string + HTTPClient *http.Client + LeveledLogger LeveledLoggerInterface + MaxNetworkRetries int64 + StripeContext *string + + enableTelemetry bool + + // networkRetriesSleep indicates whether the backend should use the normal + // sleep between retries. + // + // See also SetNetworkRetriesSleep. + networkRetriesSleep bool + + requestMetricsBuffer chan requestMetrics +} + +type metricsResponseSetter struct { + LastResponseSetter + backend *BackendImplementation + params *Params +} + +func (s *metricsResponseSetter) SetLastResponse(response *APIResponse) { + var usage []string + if s.params != nil { + usage = s.params.usage + } + s.backend.maybeEnqueueTelemetryMetrics(response.RequestID, response.duration, usage) + s.LastResponseSetter.SetLastResponse(response) +} + +func (s *metricsResponseSetter) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, s.LastResponseSetter) +} + +type streamingLastResponseSetterWrapper struct { + StreamingLastResponseSetter + f func(*StreamingAPIResponse) +} + +func (l *streamingLastResponseSetterWrapper) SetLastResponse(response *StreamingAPIResponse) { + l.f(response) + l.StreamingLastResponseSetter.SetLastResponse(response) +} +func (l *streamingLastResponseSetterWrapper) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, l.StreamingLastResponseSetter) +} + +func extractParams(params ParamsContainer) (*form.Values, *Params, error) { + var formValues *form.Values + var commonParams *Params + + if params != nil { + // This is a little unfortunate, but Go makes it impossible to compare + // an interface value to nil without the use of the reflect package and + // its true disciples insist that this is a feature and not a bug. + // + // Here we do invoke reflect because (1) we have to reflect anyway to + // use encode with the form package, and (2) the corresponding removal + // of boilerplate that this enables makes the small performance penalty + // worth it. + reflectValue := reflect.ValueOf(params) + + if reflectValue.Kind() == reflect.Ptr && !reflectValue.IsNil() { + commonParams = params.GetParams() + + if !reflectValue.Elem().FieldByName("Metadata").IsZero() { + if commonParams.Metadata != nil { + return nil, nil, fmt.Errorf("You cannot specify both the (deprecated) .Params.Metadata and .Metadata in %s", reflectValue.Elem().Type().Name()) + } + } + + if !reflectValue.Elem().FieldByName("Expand").IsZero() { + if commonParams.Expand != nil { + return nil, nil, fmt.Errorf("You cannot specify both the (deprecated) .Params.Expand and .Expand in %s", reflectValue.Elem().Type().Name()) + } + } + + formValues = &form.Values{} + form.AppendTo(formValues, params) + } + } + return formValues, commonParams, nil +} + +// Call is the Backend.Call implementation for invoking Stripe APIs. +func (s *BackendImplementation) Call(method, path, key string, params ParamsContainer, v LastResponseSetter) error { + bodyParams, commonParams, err := extractParams(params) + if err != nil { + return err + } + ver, err := extractVersion(path) + if err != nil { + return err + } + + // For V1, all parameters are URL-encoded. For V2, for GET/DELETE requests, + // parameters are URL-encoded, and for POST requests, parameters are JSON-encoded. + var body []byte + if ver == V1APIMode || method != http.MethodPost { + body = []byte(bodyParams.Encode()) + } else if params != nil && !(reflect.ValueOf(params).Kind() == reflect.Ptr && reflect.ValueOf(params).IsNil()) { + body, err = json.Marshal(params) + if err != nil { + return err + } + } + + return s.CallRaw(method, path, key, body, commonParams, v) +} + +// CallStreaming is the Backend.Call implementation for invoking Stripe APIs +// without buffering the response into memory. +func (s *BackendImplementation) CallStreaming(method, path, key string, params ParamsContainer, v StreamingLastResponseSetter) error { + formValues, commonParams, err := extractParams(params) + if err != nil { + return err + } + + ver, err := extractVersion(path) + if err != nil { + return err + } + + var body string + if formValues != nil && !formValues.Empty() { + body = formValues.Encode() + + // On `GET`, move the payload into the URL + if method == http.MethodGet { + path += "?" + body + body = "" + } + } + bodyBuffer := bytes.NewBufferString(body) + + req, err := s.NewRequest(method, path, key, ver.contentType(), commonParams) + if err != nil { + return err + } + + responseSetter := streamingLastResponseSetterWrapper{ + v, + func(response *StreamingAPIResponse) { + var usage []string + if commonParams != nil { + usage = commonParams.usage + } + s.maybeEnqueueTelemetryMetrics(response.RequestID, response.duration, usage) + }, + } + + if err := s.DoStreaming(req, bodyBuffer, &responseSetter); err != nil { + return err + } + + return nil +} + +// CallMultipart is the Backend.CallMultipart implementation for invoking Stripe APIs. +func (s *BackendImplementation) CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *Params, v LastResponseSetter) error { + contentType := "multipart/form-data; boundary=" + boundary + + req, err := s.NewRequest(method, path, key, contentType, params) + if err != nil { + return err + } + + if err := s.Do(req, body, v); err != nil { + return err + } + + return nil +} + +// extractVersion ensures the path starts with /v1, /v2, or contains /oauth +// and returns the corresponding APIMode. +func extractVersion(path string) (APIMode, error) { + if strings.HasPrefix(path, "/v1") { + return V1APIMode, nil + } else if strings.HasPrefix(path, "/v2") { + return V2APIMode, nil + } else if strings.Contains(path, "/oauth") { + return V1APIMode, nil + } else { + return APIMode(""), fmt.Errorf("unknown path prefix %s", path) + } +} + +// the stripe API only accepts GET / POST / DELETE +func validateMethod(method string) error { + if method != http.MethodPost && method != http.MethodGet && method != http.MethodDelete { + return fmt.Errorf("method must be POST, GET, or DELETE. Received %s", method) + } + return nil +} + +// RawRequest is the Backend.RawRequest implementation for invoking Stripe APIs. +func (s *BackendImplementation) RawRequest(method, path, key, content string, params *RawParams) (*APIResponse, error) { + err := validateMethod(method) + if err != nil { + return nil, err + } + + ver, err := extractVersion(path) + if err != nil { + return nil, err + } + + _, commonParams, err := extractParams(params) + if err != nil { + return nil, err + } + + req, err := s.NewRequest(method, path, key, ver.contentType(), commonParams) + if err != nil { + return nil, err + } + + if params != nil && params.StripeContext != "" { + req.Header.Set("Stripe-Context", params.StripeContext) + } + + handleResponse := func(res *http.Response, err error) (interface{}, error) { + return s.handleResponseBufferingErrors(res, err) + } + + buf := bytes.NewBufferString(content) + resp, result, requestDuration, err := s.requestWithRetriesAndTelemetry(req, buf, handleResponse) + if err != nil { + return nil, err + } + requestID := resp.Header.Get("Request-Id") + s.maybeEnqueueTelemetryMetrics(requestID, requestDuration, []string{"raw_request"}) + body, err := ioutil.ReadAll(result.(io.ReadCloser)) + if err != nil { + return nil, err + } + return newAPIResponse(resp, body, requestDuration), nil +} + +// CallRaw is the implementation for invoking Stripe APIs internally without a backend. +func (s *BackendImplementation) CallRaw(method, path, key string, body []byte, params *Params, v LastResponseSetter) error { + err := validateMethod(method) + if err != nil { + return err + } + + ver, err := extractVersion(path) + if err != nil { + return err + } + + // On `GET` / `DELETE`, move the payload into the URL. + // No need to add a query string if the body is empty. + if method != http.MethodPost && string(body) != "" { + path += "?" + string(body) + body = nil + } + + req, err := s.NewRequest(method, path, key, ver.contentType(), params) + if err != nil { + return err + } + buf := bytes.NewBuffer(body) + responseSetter := metricsResponseSetter{ + LastResponseSetter: v, + backend: s, + params: params, + } + if err := s.Do(req, buf, &responseSetter); err != nil { + return err + } + return nil +} + +// NewRequest is used by Call to generate an http.Request. It handles encoding +// parameters and attaching the appropriate headers. +func (s *BackendImplementation) NewRequest(method, path, key, contentType string, params *Params) (*http.Request, error) { + if !strings.HasPrefix(path, "/") { + path = "/" + path + } + + // Body is set later by `Do`. + req, err := http.NewRequest(method, s.URL+path, nil) + if err != nil { + s.LeveledLogger.Errorf("Cannot create Stripe request: %v", err) + return nil, err + } + + authorization := "Bearer " + key + + req.Header.Add("Authorization", authorization) + req.Header.Add("Content-Type", contentType) + req.Header.Add("Stripe-Version", APIVersion) + req.Header.Add("User-Agent", encodedUserAgent) + req.Header.Add("X-Stripe-Client-User-Agent", getEncodedStripeUserAgent()) + + if s.StripeContext != nil { + req.Header.Set("Stripe-Context", *s.StripeContext) + } + + if params != nil { + if params.Context != nil { + req = req.WithContext(params.Context) + } + + if params.IdempotencyKey != nil { + idempotencyKey := strings.TrimSpace(*params.IdempotencyKey) + if len(idempotencyKey) > 255 { + return nil, errors.New("cannot use an idempotency key longer than 255 characters") + } + + req.Header.Add("Idempotency-Key", idempotencyKey) + } else if isHTTPWriteMethod(method) { + req.Header.Add("Idempotency-Key", NewIdempotencyKey()) + } + + if params.StripeAccount != nil { + req.Header.Add("Stripe-Account", strings.TrimSpace(*params.StripeAccount)) + } + + // Note that this overrides the StripeContext set by the BackendImplementation + if params.StripeContext != nil { + req.Header.Set("Stripe-Context", *params.StripeContext) + } + + for k, v := range params.Headers { + for _, line := range v { + // Use Set to override the default value possibly set before + req.Header.Set(k, line) + } + } + } + + return req, nil +} + +func (s *BackendImplementation) maybeSetTelemetryHeader(req *http.Request) { + if s.enableTelemetry { + select { + case metrics := <-s.requestMetricsBuffer: + metricsJSON, err := json.Marshal(&requestTelemetry{LastRequestMetrics: metrics}) + if err == nil { + req.Header.Set("X-Stripe-Client-Telemetry", string(metricsJSON)) + } else { + s.LeveledLogger.Warnf("Unable to encode client telemetry: %v", err) + } + default: + // There are no metrics available, so don't send any. + // This default case needs to be here to prevent Do from blocking on an + // empty requestMetricsBuffer. + } + } +} + +func (s *BackendImplementation) maybeEnqueueTelemetryMetrics(requestID string, requestDuration *time.Duration, usage []string) { + if !s.enableTelemetry || requestID == "" { + return + } + // If there's no duration to report and no usage to report, don't bother + if requestDuration == nil && len(usage) == 0 { + return + } + metrics := requestMetrics{ + RequestID: requestID, + } + if requestDuration != nil { + requestDurationMS := int(*requestDuration / time.Millisecond) + metrics.RequestDurationMS = &requestDurationMS + } + if len(usage) > 0 { + metrics.Usage = usage + } + select { + case s.requestMetricsBuffer <- metrics: + default: + } +} + +func resetBodyReader(body *bytes.Buffer, req *http.Request) { + // This might look a little strange, but we set the request's body + // outside of `NewRequest` so that we can get a fresh version every + // time. + // + // The background is that back in the era of old style HTTP, it was + // safe to reuse `Request` objects, but with the addition of HTTP/2, + // it's now only sometimes safe. Reusing a `Request` with a body will + // break. + // + // See some details here: + // + // https://github.com/golang/go/issues/19653#issuecomment-341539160 + // + // And our original bug report here: + // + // https://github.com/stripe/stripe-go/issues/642 + // + // To workaround the problem, we put a fresh `Body` onto the `Request` + // every time we execute it, and this seems to empirically resolve the + // problem. + if body != nil { + // We can safely reuse the same buffer that we used to encode our body, + // but return a new reader to it everytime so that each read is from + // the beginning. + reader := bytes.NewReader(body.Bytes()) + + req.Body = nopReadCloser{reader} + + // And also add the same thing to `Request.GetBody`, which allows + // `net/http` to get a new body in cases like a redirect. This is + // usually not used, but it doesn't hurt to set it in case it's + // needed. See: + // + // https://github.com/stripe/stripe-go/issues/710 + // + req.GetBody = func() (io.ReadCloser, error) { + reader := bytes.NewReader(body.Bytes()) + return nopReadCloser{reader}, nil + } + } +} + +// requestWithRetriesAndTelemetry uses s.HTTPClient to make an HTTP request, +// and handles retries, telemetry, and emitting log statements. It attempts to +// avoid processing the *result* of the HTTP request. It receives a +// "handleResponse" func from the caller, and it defers to that to determine +// whether the request was a failure or success, and to convert the +// response/error into the appropriate type of error or an appropriate result +// type. +func (s *BackendImplementation) requestWithRetriesAndTelemetry( + req *http.Request, + body *bytes.Buffer, + handleResponse func(*http.Response, error) (interface{}, error), +) (*http.Response, interface{}, *time.Duration, error) { + s.LeveledLogger.Infof("Requesting %v %v%v", req.Method, req.URL.Host, req.URL.Path) + s.maybeSetTelemetryHeader(req) + var resp *http.Response + var err error + var requestDuration time.Duration + var result interface{} + for retry := 0; ; { + start := time.Now() + resetBodyReader(body, req) + + resp, err = s.HTTPClient.Do(req) + + requestDuration = time.Since(start) + s.LeveledLogger.Infof("Request completed in %v (retry: %v)", requestDuration, retry) + + result, err = handleResponse(resp, err) + + // If the response was okay, or an error that shouldn't be retried, + // we're done, and it's safe to leave the retry loop. + shouldRetry, noRetryReason := s.shouldRetry(err, req, resp, retry) + + if !shouldRetry { + s.LeveledLogger.Infof("Not retrying request: %v", noRetryReason) + break + } + + sleepDuration := s.sleepTime(retry) + retry++ + + s.LeveledLogger.Warnf("Initiating retry %v for request %v %v%v after sleeping %v", + retry, req.Method, req.URL.Host, req.URL.Path, sleepDuration) + + time.Sleep(sleepDuration) + } + + if err != nil { + return nil, nil, nil, err + } + + return resp, result, &requestDuration, nil +} + +func (s *BackendImplementation) logError(statusCode int, err error) { + if stripeErr, ok := err.(redacter); ok { + // The Stripe API makes a distinction between errors that were + // caused by invalid parameters or something else versus those + // that occurred *despite* valid parameters, the latter coming + // back with status 402. + // + // On a 402, log to info so as to not make an integration's log + // noisy with error messages that they don't have much control + // over. + // + // Note I use the constant 402 instead of an `http.Status*` + // constant because technically 402 is "Payment required". The + // Stripe API doesn't comply to the letter of the specification + // and uses it in a broader sense. + if statusCode == 402 { + s.LeveledLogger.Infof("User-compelled request error from Stripe (status %v): %v", + statusCode, stripeErr.redact()) + } else { + s.LeveledLogger.Errorf("Request error from Stripe (status %v): %v", + statusCode, stripeErr.redact()) + } + } else { + s.LeveledLogger.Errorf("Error decoding error from Stripe: %v", err) + } +} + +func (s *BackendImplementation) handleResponseBufferingErrors(res *http.Response, err error) (io.ReadCloser, error) { + // Some sort of connection error + if err != nil { + s.LeveledLogger.Errorf("Request failed with error: %v", err) + return res.Body, err + } + + // Successful response, return the body ReadCloser + if res.StatusCode < 400 { + return res.Body, err + } + + // Failure: try and parse the json of the response + // when logging the error + var resBody []byte + resBody, err = ioutil.ReadAll(res.Body) + res.Body.Close() + if err == nil { + err = s.ResponseToError(res, resBody) + } else { + s.logError(res.StatusCode, err) + } + + return res.Body, err +} + +// DoStreaming is used by CallStreaming to execute an API request. It uses the +// backend's HTTP client to execure the request. In successful cases, it sets +// a StreamingLastResponse onto v, but in unsuccessful cases handles unmarshaling +// errors returned by the API. +func (s *BackendImplementation) DoStreaming(req *http.Request, body *bytes.Buffer, v StreamingLastResponseSetter) error { + handleResponse := func(res *http.Response, err error) (interface{}, error) { + return s.handleResponseBufferingErrors(res, err) + } + + resp, result, requestDuration, err := s.requestWithRetriesAndTelemetry(req, body, handleResponse) + if err != nil { + return err + } + v.SetLastResponse(newStreamingAPIResponse(resp, result.(io.ReadCloser), requestDuration)) + return nil +} + +// Do is used by Call to execute an API request and parse the response. It uses +// the backend's HTTP client to execute the request and unmarshals the response +// into v. It also handles unmarshaling errors returned by the API. +func (s *BackendImplementation) Do(req *http.Request, body *bytes.Buffer, v LastResponseSetter) error { + handleResponse := func(res *http.Response, err error) (interface{}, error) { + var resBody []byte + if err == nil { + resBody, err = ioutil.ReadAll(res.Body) + res.Body.Close() + } + + ver, pathErr := extractVersion(req.URL.Path) + if pathErr != nil { + return nil, pathErr + } + + switch { + case err != nil: + s.LeveledLogger.Errorf("Request failed with error: %v", err) + case res.StatusCode >= 400 && ver == V1APIMode: + err = s.ResponseToError(res, resBody) + s.logError(res.StatusCode, err) + case res.StatusCode >= 400 && ver == V2APIMode: + err = s.responseToErrorV2(res, resBody) + s.logError(res.StatusCode, err) + } + + return resBody, err + } + + res, result, requestDuration, err := s.requestWithRetriesAndTelemetry(req, body, handleResponse) + if err != nil { + return err + } + resBody := result.([]byte) + s.LeveledLogger.Debugf("Response: %s", string(resBody)) + + err = s.UnmarshalJSONVerbose(res.StatusCode, resBody, v) + v.SetLastResponse(newAPIResponse(res, resBody, requestDuration)) + return err +} + +// ResponseToError converts a stripe response to an Error. +func (s *BackendImplementation) ResponseToError(res *http.Response, resBody []byte) error { + var raw rawError + if s.Type == ConnectBackend { + // If this is an OAuth request, deserialize as Error because OAuth errors + // are a different shape from the standard API errors. + var topLevelError Error + if err := s.UnmarshalJSONVerbose(res.StatusCode, resBody, &topLevelError); err != nil { + return err + } + raw.Error = &topLevelError + } else { + if err := s.UnmarshalJSONVerbose(res.StatusCode, resBody, &raw); err != nil { + return err + } + } + + // no error in resBody + if raw.Error == nil { + err := errors.New(string(resBody)) + return err + } + raw.Error.HTTPStatusCode = res.StatusCode + raw.Error.RequestID = res.Header.Get("Request-Id") + + var typedError error + switch raw.Error.Type { + case ErrorTypeAPI: + typedError = &APIError{stripeErr: raw.Error} + case ErrorTypeCard: + cardErr := &CardError{stripeErr: raw.Error} + + // `DeclineCode` was traditionally only available on `CardError`, but + // we ended up moving it to the top-level error as well. However, keep + // it on `CardError` for backwards compatibility. + if raw.Error.DeclineCode != "" { + cardErr.DeclineCode = raw.Error.DeclineCode + } + + typedError = cardErr + case ErrorTypeIdempotency: + typedError = &IdempotencyError{stripeErr: raw.Error} + case ErrorTypeInvalidRequest: + typedError = &InvalidRequestError{stripeErr: raw.Error} + } + raw.Error.Err = typedError + + raw.Error.SetLastResponse(newAPIResponse(res, resBody, nil)) + + return raw.Error +} + +// responseToErrorV2 converts a stripe V2 response to an error. +func (s *BackendImplementation) responseToErrorV2(res *http.Response, resBody []byte) error { + // First, we partially unmarshal just the error type + var raw struct { + Error *V2RawError `json:"error"` + } + if err := s.UnmarshalJSONVerbose(res.StatusCode, resBody, &raw); err != nil { + return err + } + + // need to return a generic error in this case + if raw.Error == nil { + err := errors.New(string(resBody)) + return err + } + + if raw.Error.Type == nil { + return raw.Error + } + + var typedError error + + // The beginning of the section generated from our OpenAPI spec + switch *raw.Error.Type { + case "temporary_session_expired": + tmp := struct { + Error *TemporarySessionExpiredError `json:"error"` + }{ + Error: &TemporarySessionExpiredError{}, + } + if err := s.UnmarshalJSONVerbose(res.StatusCode, resBody, &tmp); err != nil { + return err + } + tmp.Error.SetLastResponse(newAPIResponse(res, resBody, nil)) + typedError = tmp.Error + default: + typedError = raw.Error + } + // The end of the section generated from our OpenAPI spec + + return typedError +} + +// SetMaxNetworkRetries sets max number of retries on failed requests +// +// This function is deprecated. Please use GetBackendWithConfig instead. +func (s *BackendImplementation) SetMaxNetworkRetries(maxNetworkRetries int64) { + s.MaxNetworkRetries = maxNetworkRetries +} + +// SetNetworkRetriesSleep allows the normal sleep between network retries to be +// enabled or disabled. +// +// This function is available for internal testing only and should never be +// used in production. +func (s *BackendImplementation) SetNetworkRetriesSleep(sleep bool) { + s.networkRetriesSleep = sleep +} + +// UnmarshalJSONVerbose unmarshals JSON, but in case of a failure logs and +// produces a more descriptive error. +func (s *BackendImplementation) UnmarshalJSONVerbose(statusCode int, body []byte, v interface{}) error { + err := json.Unmarshal(body, v) + if err != nil { + // If we got invalid JSON back then something totally unexpected is + // happening (caused by a bug on the server side). Put a sample of the + // response body into the error message so we can get a better feel for + // what the problem was. + bodySample := string(body) + if len(bodySample) > 500 { + bodySample = bodySample[0:500] + " ..." + } + + // Make sure a multi-line response ends up all on one line + bodySample = strings.Replace(bodySample, "\n", "\\n", -1) + + newErr := fmt.Errorf("Couldn't deserialize JSON (response status: %v, body sample: '%s'): %v", + statusCode, bodySample, err) + s.LeveledLogger.Errorf("%s", newErr.Error()) + return newErr + } + + return nil +} + +// Regular expressions used to match a few error types that we know we don't +// want to retry. Unfortunately these errors aren't typed so we match on the +// error's message. +var ( + redirectsErrorRE = regexp.MustCompile(`stopped after \d+ redirects\z`) + schemeErrorRE = regexp.MustCompile(`unsupported protocol scheme`) +) + +// Checks if an error is a problem that we should retry on. This includes both +// socket errors that may represent an intermittent problem and some special +// HTTP statuses. +// +// Returns a boolean indicating whether a client should retry. If false, a +// second string parameter is also returned with a short message indicating why +// no retry should occur. This can be used for logging/informational purposes. +func (s *BackendImplementation) shouldRetry(err error, req *http.Request, resp *http.Response, numRetries int) (bool, string) { + if numRetries >= int(s.MaxNetworkRetries) { + return false, "max retries exceeded" + } + + // Don't retry if the context was canceled or its deadline was exceeded. + if req.Context() != nil && req.Context().Err() != nil { + switch req.Context().Err() { + case context.Canceled: + return false, "context canceled" + case context.DeadlineExceeded: + return false, "context deadline exceeded" + default: + return false, fmt.Sprintf("unknown context error: %v", req.Context().Err()) + } + } + + // All errors from the Stripe API should implement the `retrier` interface. + // Any other error comes from a different layer + if err, ok := err.(retrier); ok { + return err.canRetry(), "not retriable error" + } + + // We retry most errors that come out of HTTP requests except for a curated + // list that we know not to be retryable. This list is probably not + // exhaustive, so it'd be okay to add new errors to it. It'd also be okay to + // flip this to an inverted strategy of retrying only errors that we know + // to be retryable in a future refactor, if a good methodology is found for + // identifying that full set of errors. + if err != nil { + if urlErr, ok := err.(*url.Error); ok { + // Don't retry too many redirects. + if redirectsErrorRE.MatchString(urlErr.Error()) { + return false, urlErr.Error() + } + + // Don't retry invalid protocol scheme. + if schemeErrorRE.MatchString(urlErr.Error()) { + return false, urlErr.Error() + } + + // Don't retry TLS certificate validation problems. + if _, ok := urlErr.Err.(x509.UnknownAuthorityError); ok { + return false, urlErr.Error() + } + } + + // Do retry every other type of non-Stripe error. + return true, "" + } + + // The API may ask us not to retry (e.g. if doing so would be a no-op), or + // advise us to retry (e.g. in cases of lock timeouts). Defer to those + // instructions if given. + if resp.Header.Get("Stripe-Should-Retry") == "false" { + return false, "`Stripe-Should-Retry` header returned `false`" + } + if resp.Header.Get("Stripe-Should-Retry") == "true" { + return true, "" + } + + // 409 Conflict + if resp.StatusCode == http.StatusConflict { + return true, "" + } + + // Retry on 500, 503, and other internal errors. + // + // Note that we expect the stripe-should-retry header to be false + // in most cases when a 500 is returned, since our idempotency framework + // would typically replay it anyway. + if resp.StatusCode >= http.StatusInternalServerError { + return true, "" + } + + return false, "response not known to be safe for retry" +} + +// sleepTime calculates sleeping/delay time in milliseconds between failure and a new one request. +func (s *BackendImplementation) sleepTime(numRetries int) time.Duration { + // We disable sleeping in some cases for tests. + if !s.networkRetriesSleep { + return 0 * time.Second + } + + // Apply exponential backoff with minNetworkRetriesDelay on the + // number of num_retries so far as inputs. + delay := minNetworkRetriesDelay + minNetworkRetriesDelay*time.Duration(numRetries*numRetries) + + // Do not allow the number to exceed maxNetworkRetriesDelay. + if delay > maxNetworkRetriesDelay { + delay = maxNetworkRetriesDelay + } + + // Apply some jitter by randomizing the value in the range of 75%-100%. + jitter := rand.Int63n(int64(delay / 4)) + delay -= time.Duration(jitter) + + // But never sleep less than the base sleep seconds. + if delay < minNetworkRetriesDelay { + delay = minNetworkRetriesDelay + } + + return delay +} + +// Backends are the currently supported endpoints. +type Backends struct { + API, Connect, Uploads, MeterEvents Backend + mu sync.RWMutex +} + +// LastResponseSetter defines a type that contains an HTTP response from a Stripe +// API endpoint. +type LastResponseSetter interface { + SetLastResponse(response *APIResponse) +} + +// StreamingLastResponseSetter defines a type that contains an HTTP response from a Stripe +// API endpoint. +type StreamingLastResponseSetter interface { + SetLastResponse(response *StreamingAPIResponse) +} + +// SupportedBackend is an enumeration of supported Stripe endpoints. +// Currently supported values are "api" and "uploads". +type SupportedBackend string + +// +// Public functions +// + +// Bool returns a pointer to the bool value passed in. +func Bool(v bool) *bool { + return &v +} + +// BoolValue returns the value of the bool pointer passed in or +// false if the pointer is nil. +func BoolValue(v *bool) bool { + if v != nil { + return *v + } + return false +} + +// BoolSlice returns a slice of bool pointers given a slice of bools. +func BoolSlice(v []bool) []*bool { + out := make([]*bool, len(v)) + for i := range v { + out[i] = &v[i] + } + return out +} + +// Float64 returns a pointer to the float64 value passed in. +func Float64(v float64) *float64 { + return &v +} + +// Float64Value returns the value of the float64 pointer passed in or +// 0 if the pointer is nil. +func Float64Value(v *float64) float64 { + if v != nil { + return *v + } + return 0 +} + +// Float64Slice returns a slice of float64 pointers given a slice of float64s. +func Float64Slice(v []float64) []*float64 { + out := make([]*float64, len(v)) + for i := range v { + out[i] = &v[i] + } + return out +} + +// FormatURLPath takes a format string (of the kind used in the fmt package) +// representing a URL path with a number of parameters that belong in the path +// and returns a formatted string. +// +// This is mostly a pass through to Sprintf. It exists to make it +// it impossible to accidentally provide a parameter type that would be +// formatted improperly; for example, a string pointer instead of a string. +// +// It also URL-escapes every given parameter. This usually isn't necessary for +// a standard Stripe ID, but is needed in places where user-provided IDs are +// allowed, like in coupons or plans. We apply it broadly for extra safety. +func FormatURLPath(format string, params ...string) string { + // Convert parameters to interface{} and URL-escape them + untypedParams := make([]interface{}, len(params)) + for i, param := range params { + untypedParams[i] = interface{}(url.QueryEscape(param)) + } + + return fmt.Sprintf(format, untypedParams...) +} + +// GetBackend returns one of the library's supported backends based off of the +// given argument. +// +// It returns an existing default backend if one's already been created. +func GetBackend(backendType SupportedBackend) Backend { + var backend Backend + + backends.mu.RLock() + switch backendType { + case APIBackend: + backend = backends.API + case ConnectBackend: + backend = backends.Connect + case UploadsBackend: + backend = backends.Uploads + case MeterEventsBackend: + backend = backends.MeterEvents + } + backends.mu.RUnlock() + if backend != nil { + return backend + } + + backend = GetBackendWithConfig( + backendType, + &BackendConfig{ + HTTPClient: httpClient, + LeveledLogger: nil, // Set by GetBackendWithConfiguation when nil + MaxNetworkRetries: nil, // Set by GetBackendWithConfiguation when nil + URL: nil, // Set by GetBackendWithConfiguation when nil + }, + ) + + SetBackend(backendType, backend) + + return backend +} + +// GetBackendWithConfig is the same as GetBackend except that it can be given a +// configuration struct that will configure certain aspects of the backend +// that's return. +func GetBackendWithConfig(backendType SupportedBackend, config *BackendConfig) Backend { + cfg := *config + if cfg.HTTPClient == nil { + cfg.HTTPClient = httpClient + } + + if cfg.LeveledLogger == nil { + cfg.LeveledLogger = DefaultLeveledLogger + } + + if cfg.MaxNetworkRetries == nil { + cfg.MaxNetworkRetries = Int64(DefaultMaxNetworkRetries) + } + + switch backendType { + case APIBackend: + if cfg.URL == nil { + cfg.URL = String(APIURL) + } + + cfg.URL = String(normalizeURL(*cfg.URL)) + + return newBackendImplementation(backendType, &cfg) + + case UploadsBackend: + if cfg.URL == nil { + cfg.URL = String(UploadsURL) + } + + cfg.URL = String(normalizeURL(*cfg.URL)) + + return newBackendImplementation(backendType, &cfg) + + case ConnectBackend: + if cfg.URL == nil { + cfg.URL = String(ConnectURL) + } + + cfg.URL = String(normalizeURL(*cfg.URL)) + + return newBackendImplementation(backendType, &cfg) + + case MeterEventsBackend: + if cfg.URL == nil { + cfg.URL = String(MeterEventsURL) + } + + cfg.URL = String(normalizeURL(*cfg.URL)) + + return newBackendImplementation(backendType, &cfg) + } + + return nil +} + +func GetRawRequestBackend(backendType SupportedBackend) (RawRequestBackend, error) { + if bi, ok := GetBackend(backendType).(RawRequestBackend); ok { + return bi, nil + } + return nil, fmt.Errorf("Error: cannot call RawRequest if requested backend type is initialized with a backend that doesn't implement RawRequestBackend") +} + +// Int64 returns a pointer to the int64 value passed in. +func Int64(v int64) *int64 { + return &v +} + +// Int64Value returns the value of the int64 pointer passed in or +// 0 if the pointer is nil. +func Int64Value(v *int64) int64 { + if v != nil { + return *v + } + return 0 +} + +// Int64Slice returns a slice of int64 pointers given a slice of int64s. +func Int64Slice(v []int64) []*int64 { + out := make([]*int64, len(v)) + for i := range v { + out[i] = &v[i] + } + return out +} + +// NewBackends creates a new set of backends with the given HTTP client. +func NewBackends(httpClient *http.Client) *Backends { + apiConfig := &BackendConfig{HTTPClient: httpClient} + connectConfig := &BackendConfig{HTTPClient: httpClient} + uploadConfig := &BackendConfig{HTTPClient: httpClient} + meterConfig := &BackendConfig{HTTPClient: httpClient} + return &Backends{ + API: GetBackendWithConfig(APIBackend, apiConfig), + Connect: GetBackendWithConfig(ConnectBackend, connectConfig), + Uploads: GetBackendWithConfig(UploadsBackend, uploadConfig), + MeterEvents: GetBackendWithConfig(MeterEventsBackend, meterConfig), + } +} + +// NewBackendsWithConfig creates a new set of backends with the given config for all backends. +// Useful for setting up client with a custom logger and http client. +func NewBackendsWithConfig(config *BackendConfig) *Backends { + return &Backends{ + API: GetBackendWithConfig(APIBackend, config), + Connect: GetBackendWithConfig(ConnectBackend, config), + Uploads: GetBackendWithConfig(UploadsBackend, config), + MeterEvents: GetBackendWithConfig(MeterEventsBackend, config), + } +} + +// ParseID attempts to parse a string scalar from a given JSON value which is +// still encoded as []byte. If the value was a string, it returns the string +// along with true as the second return value. If not, false is returned as the +// second return value. +// +// The purpose of this function is to detect whether a given value in a +// response from the Stripe API is a string ID or an expanded object. +func ParseID(data []byte) (string, bool) { + s := string(data) + + if !strings.HasPrefix(s, "\"") { + return "", false + } + + if !strings.HasSuffix(s, "\"") { + return "", false + } + + // Edge case that should never happen; found via fuzzing + if s == "\"" { + return "", false + } + + return s[1 : len(s)-1], true +} + +// SetAppInfo sets app information. See AppInfo. +func SetAppInfo(info *AppInfo) { + if info != nil && info.Name == "" { + panic(fmt.Errorf("App info name cannot be empty")) + } + appInfo = info + + // This is run in init, but we need to reinitialize it now that we have + // some app info. + initUserAgent() +} + +// SetBackend sets the backend used in the binding. +func SetBackend(backend SupportedBackend, b Backend) { + backends.mu.Lock() + defer backends.mu.Unlock() + + switch backend { + case APIBackend: + backends.API = b + case ConnectBackend: + backends.Connect = b + case UploadsBackend: + backends.Uploads = b + case MeterEventsBackend: + backends.MeterEvents = b + } +} + +// SetHTTPClient overrides the default HTTP client. +// This is useful if you're running in a Google AppEngine environment +// where the http.DefaultClient is not available. +func SetHTTPClient(client *http.Client) { + httpClient = client +} + +// String returns a pointer to the string value or enum passed in. +func String[T ~string](v T) *string { + result := string(v) + return &result +} + +// StringValue returns the value of the string pointer passed in or +// "" if the pointer is nil. +func StringValue(v *string) string { + if v != nil { + return *v + } + return "" +} + +// StringSlice returns a slice of string pointers given a slice of strings. +func StringSlice(v []string) []*string { + out := make([]*string, len(v)) + for i := range v { + out[i] = &v[i] + } + return out +} + +// Time returns a pointer to the time.Time value passed in. +func Time(v time.Time) *time.Time { + return &v +} + +// TimeValue returns the value of the time.Time pointer passed in or +// time.Time{} if the pointer is nil. +func TimeValue(v *time.Time) time.Time { + if v != nil { + return *v + } + return time.Time{} +} + +// +// Private constants +// + +// clientversion is the binding version +const clientversion = "82.3.0" + +// defaultHTTPTimeout is the default timeout on the http.Client used by the library. +// This is chosen to be consistent with the other Stripe language libraries and +// to coordinate with other timeouts configured in the Stripe infrastructure. +const defaultHTTPTimeout = 80 * time.Second + +// maxNetworkRetriesDelay and minNetworkRetriesDelay defines sleep time in milliseconds between +// tries to send HTTP request again after network failure. +const maxNetworkRetriesDelay = 5000 * time.Millisecond +const minNetworkRetriesDelay = 500 * time.Millisecond + +// The number of requestMetric objects to buffer for client telemetry. When the +// buffer is full, new requestMetrics are dropped. +const telemetryBufferSize = 16 + +// +// Private types +// + +// nopReadCloser's sole purpose is to give us a way to turn an `io.Reader` into +// an `io.ReadCloser` by adding a no-op implementation of the `Closer` +// interface. We need this because `http.Request`'s `Body` takes an +// `io.ReadCloser` instead of a `io.Reader`. +type nopReadCloser struct { + io.Reader +} + +func (nopReadCloser) Close() error { return nil } + +// stripeClientUserAgent contains information about the current runtime which +// is serialized and sent in the `X-Stripe-Client-User-Agent` as additional +// debugging information. +type stripeClientUserAgent struct { + Application *AppInfo `json:"application"` + BindingsVersion string `json:"bindings_version"` + Language string `json:"lang"` + LanguageVersion string `json:"lang_version"` + Publisher string `json:"publisher"` + Uname string `json:"uname"` +} + +// requestMetrics contains the id and duration of the last request sent +type requestMetrics struct { + RequestDurationMS *int `json:"request_duration_ms"` + RequestID string `json:"request_id"` + Usage []string `json:"usage"` +} + +// requestTelemetry contains the payload sent in the +// `X-Stripe-Client-Telemetry` header when BackendConfig.EnableTelemetry = true. +type requestTelemetry struct { + LastRequestMetrics requestMetrics `json:"last_request_metrics"` +} + +// +// Private variables +// + +var appInfo *AppInfo +var backends Backends +var encodedStripeUserAgent string +var encodedStripeUserAgentReady *sync.Once +var encodedUserAgent string + +// The default HTTP client used for communication with any of Stripe's +// backends. +// +// Can be overridden with the function `SetHTTPClient` or by setting the +// `HTTPClient` value when using `BackendConfig`. +var httpClient = &http.Client{ + Timeout: defaultHTTPTimeout, +} + +// +// Private functions +// + +// getUname tries to get a uname from the system, but not that hard. It tries +// to execute `uname -a`, but swallows any errors in case that didn't work +// (i.e. non-Unix non-Mac system or some other reason). +func getUname() string { + path, err := exec.LookPath("uname") + if err != nil { + return UnknownPlatform + } + + cmd := exec.Command(path, "-a") + var out bytes.Buffer + cmd.Stderr = nil // goes to os.DevNull + cmd.Stdout = &out + err = cmd.Run() + if err != nil { + return UnknownPlatform + } + + return out.String() +} + +func init() { + initUserAgent() +} + +func initUserAgent() { + encodedUserAgent = "Stripe/v1 GoBindings/" + clientversion + if appInfo != nil { + encodedUserAgent += " " + appInfo.formatUserAgent() + } + encodedStripeUserAgentReady = &sync.Once{} +} + +func getEncodedStripeUserAgent() string { + encodedStripeUserAgentReady.Do(func() { + stripeUserAgent := &stripeClientUserAgent{ + Application: appInfo, + BindingsVersion: clientversion, + Language: "go", + LanguageVersion: runtime.Version(), + Publisher: "stripe", + Uname: getUname(), + } + marshaled, err := json.Marshal(stripeUserAgent) + // Encoding this struct should never be a problem, so we're okay to panic + // in case it is for some reason. + if err != nil { + panic(err) + } + encodedStripeUserAgent = string(marshaled) + }) + return encodedStripeUserAgent +} + +func isHTTPWriteMethod(method string) bool { + return method == http.MethodPost || method == http.MethodPut || method == http.MethodPatch || method == http.MethodDelete +} + +// newBackendImplementation returns a new Backend based off a given type and +// fully initialized BackendConfig struct. +// +// The vast majority of the time you should be calling GetBackendWithConfig +// instead of this function. +func newBackendImplementation(backendType SupportedBackend, config *BackendConfig) Backend { + enableTelemetry := EnableTelemetry + if config.EnableTelemetry != nil { + enableTelemetry = *config.EnableTelemetry + } + + var requestMetricsBuffer chan requestMetrics + + // only allocate the requestMetrics buffer if client telemetry is enabled. + if enableTelemetry { + requestMetricsBuffer = make(chan requestMetrics, telemetryBufferSize) + } + + return &BackendImplementation{ + HTTPClient: config.HTTPClient, + LeveledLogger: config.LeveledLogger, + MaxNetworkRetries: *config.MaxNetworkRetries, + Type: backendType, + URL: *config.URL, + StripeContext: config.StripeContext, + enableTelemetry: enableTelemetry, + networkRetriesSleep: true, + requestMetricsBuffer: requestMetricsBuffer, + } +} + +func normalizeURL(url string) string { + // All paths include a leading slash, so to keep logs pretty, trim a + // trailing slash on the URL. + url = strings.TrimSuffix(url, "/") + + // For a long time we had the `/v1` suffix as part of a configured URL + // rather than in the per-package URLs throughout the library. Continue + // to support this for the time being by stripping one that's been + // passed for better backwards compatibility. + url = strings.TrimSuffix(url, "/v1") + + return url +} + +func RawRequest(method, path string, content string, params *RawParams) (*APIResponse, error) { + if bi, ok := GetBackend(APIBackend).(RawRequestBackend); ok { + return bi.RawRequest(method, path, Key, content, params) + } + return nil, fmt.Errorf("Error: cannot call RawRequest if backends.API is initialized with a backend that doesn't implement RawRequestBackend") +} + +// UsageBackend is a wrapper for stripe.Backend that sets the usage parameter +type UsageBackend struct { + B Backend + Usage []string +} + +func (u *UsageBackend) Call(method, path, key string, params ParamsContainer, v LastResponseSetter) error { + if r := reflect.ValueOf(params); r.Kind() == reflect.Ptr && !r.IsNil() { + params.GetParams().InternalSetUsage(u.Usage) + } + return u.B.Call(method, path, key, params, v) +} + +func (u *UsageBackend) CallRaw(method, path, key string, body []byte, params *Params, v LastResponseSetter) error { + params.GetParams().InternalSetUsage(u.Usage) + return u.B.CallRaw(method, path, key, body, params, v) +} + +func (u *UsageBackend) CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *Params, v LastResponseSetter) error { + params.GetParams().InternalSetUsage(u.Usage) + return u.B.CallMultipart(method, path, key, boundary, body, params, v) +} + +func (u *UsageBackend) CallStreaming(method, path, key string, params ParamsContainer, v StreamingLastResponseSetter) error { + if r := reflect.ValueOf(params); r.Kind() == reflect.Ptr && !r.IsNil() { + params.GetParams().InternalSetUsage(u.Usage) + } + return u.B.CallStreaming(method, path, key, params, v) +} + +func (u *UsageBackend) SetMaxNetworkRetries(maxNetworkRetries int64) { + u.B.SetMaxNetworkRetries(maxNetworkRetries) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/stripe_client.go b/vendor/github.com/stripe/stripe-go/v82/stripe_client.go new file mode 100644 index 00000000..1b26039b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/stripe_client.go @@ -0,0 +1,513 @@ +package stripe + +import ( + "encoding/json" +) + +// Client is the Stripe client. It contains all the different services available. +type Client struct { + // stripeClientStruct: The beginning of the section generated from our OpenAPI spec + + // OAuth is the service used to invoke /oauth APIs + OAuth *oauthService + // V1AccountLinks is the service used to invoke /v1/account_links APIs. + V1AccountLinks *v1AccountLinkService + // V1Accounts is the service used to invoke /v1/accounts APIs. + V1Accounts *v1AccountService + // V1AccountSessions is the service used to invoke /v1/account_sessions APIs. + V1AccountSessions *v1AccountSessionService + // V1ApplePayDomains is the service used to invoke /v1/apple_pay/domains APIs. + V1ApplePayDomains *v1ApplePayDomainService + // V1ApplicationFees is the service used to invoke /v1/application_fees APIs. + V1ApplicationFees *v1ApplicationFeeService + // V1AppsSecrets is the service used to invoke /v1/apps/secrets APIs. + V1AppsSecrets *v1AppsSecretService + // V1Balance is the service used to invoke /v1/balance APIs. + V1Balance *v1BalanceService + // V1BalanceTransactions is the service used to invoke /v1/balance_transactions APIs. + V1BalanceTransactions *v1BalanceTransactionService + // V1BankAccounts is the service used to invoke /v1/accounts/{account}/external_accounts APIs. + V1BankAccounts *v1BankAccountService + // V1BillingAlerts is the service used to invoke /v1/billing/alerts APIs. + V1BillingAlerts *v1BillingAlertService + // V1BillingCreditBalanceSummary is the service used to invoke /v1/billing/credit_balance_summary APIs. + V1BillingCreditBalanceSummary *v1BillingCreditBalanceSummaryService + // V1BillingCreditBalanceTransactions is the service used to invoke /v1/billing/credit_balance_transactions APIs. + V1BillingCreditBalanceTransactions *v1BillingCreditBalanceTransactionService + // V1BillingCreditGrants is the service used to invoke /v1/billing/credit_grants APIs. + V1BillingCreditGrants *v1BillingCreditGrantService + // V1BillingMeterEventAdjustments is the service used to invoke /v1/billing/meter_event_adjustments APIs. + V1BillingMeterEventAdjustments *v1BillingMeterEventAdjustmentService + // V1BillingMeterEvents is the service used to invoke /v1/billing/meter_events APIs. + V1BillingMeterEvents *v1BillingMeterEventService + // V1BillingMeterEventSummaries is the service used to invoke /v1/billing/meters/{id}/event_summaries APIs. + V1BillingMeterEventSummaries *v1BillingMeterEventSummaryService + // V1BillingMeters is the service used to invoke /v1/billing/meters APIs. + V1BillingMeters *v1BillingMeterService + // V1BillingPortalConfigurations is the service used to invoke /v1/billing_portal/configurations APIs. + V1BillingPortalConfigurations *v1BillingPortalConfigurationService + // V1BillingPortalSessions is the service used to invoke /v1/billing_portal/sessions APIs. + V1BillingPortalSessions *v1BillingPortalSessionService + // V1Capabilities is the service used to invoke /v1/accounts/{account}/capabilities APIs. + V1Capabilities *v1CapabilityService + // V1Cards is the service used to invoke /v1/accounts/{account}/external_accounts APIs. + V1Cards *v1CardService + // V1CashBalances is the service used to invoke /v1/customers/{customer}/cash_balance APIs. + V1CashBalances *v1CashBalanceService + // V1Charges is the service used to invoke /v1/charges APIs. + V1Charges *v1ChargeService + // V1CheckoutSessions is the service used to invoke /v1/checkout/sessions APIs. + V1CheckoutSessions *v1CheckoutSessionService + // V1ClimateOrders is the service used to invoke /v1/climate/orders APIs. + V1ClimateOrders *v1ClimateOrderService + // V1ClimateProducts is the service used to invoke /v1/climate/products APIs. + V1ClimateProducts *v1ClimateProductService + // V1ClimateSuppliers is the service used to invoke /v1/climate/suppliers APIs. + V1ClimateSuppliers *v1ClimateSupplierService + // V1ConfirmationTokens is the service used to invoke /v1/confirmation_tokens APIs. + V1ConfirmationTokens *v1ConfirmationTokenService + // V1CountrySpecs is the service used to invoke /v1/country_specs APIs. + V1CountrySpecs *v1CountrySpecService + // V1Coupons is the service used to invoke /v1/coupons APIs. + V1Coupons *v1CouponService + // V1CreditNotes is the service used to invoke /v1/credit_notes APIs. + V1CreditNotes *v1CreditNoteService + // V1CustomerBalanceTransactions is the service used to invoke /v1/customers/{customer}/balance_transactions APIs. + V1CustomerBalanceTransactions *v1CustomerBalanceTransactionService + // V1CustomerCashBalanceTransactions is the service used to invoke /v1/customers/{customer}/cash_balance_transactions APIs. + V1CustomerCashBalanceTransactions *v1CustomerCashBalanceTransactionService + // V1Customers is the service used to invoke /v1/customers APIs. + V1Customers *v1CustomerService + // V1CustomerSessions is the service used to invoke /v1/customer_sessions APIs. + V1CustomerSessions *v1CustomerSessionService + // V1Disputes is the service used to invoke /v1/disputes APIs. + V1Disputes *v1DisputeService + // V1EntitlementsActiveEntitlements is the service used to invoke /v1/entitlements/active_entitlements APIs. + V1EntitlementsActiveEntitlements *v1EntitlementsActiveEntitlementService + // V1EntitlementsFeatures is the service used to invoke /v1/entitlements/features APIs. + V1EntitlementsFeatures *v1EntitlementsFeatureService + // V1EphemeralKeys is the service used to invoke /v1/ephemeral_keys APIs. + V1EphemeralKeys *v1EphemeralKeyService + // V1Events is the service used to invoke /v1/events APIs. + V1Events *v1EventService + // V1FeeRefunds is the service used to invoke /v1/application_fees/{id}/refunds APIs. + V1FeeRefunds *v1FeeRefundService + // V1FileLinks is the service used to invoke /v1/file_links APIs. + V1FileLinks *v1FileLinkService + // V1Files is the service used to invoke /v1/files APIs. + V1Files *v1FileService + // V1FinancialConnectionsAccounts is the service used to invoke /v1/financial_connections/accounts APIs. + V1FinancialConnectionsAccounts *v1FinancialConnectionsAccountService + // V1FinancialConnectionsSessions is the service used to invoke /v1/financial_connections/sessions APIs. + V1FinancialConnectionsSessions *v1FinancialConnectionsSessionService + // V1FinancialConnectionsTransactions is the service used to invoke /v1/financial_connections/transactions APIs. + V1FinancialConnectionsTransactions *v1FinancialConnectionsTransactionService + // V1ForwardingRequests is the service used to invoke /v1/forwarding/requests APIs. + V1ForwardingRequests *v1ForwardingRequestService + // V1IdentityVerificationReports is the service used to invoke /v1/identity/verification_reports APIs. + V1IdentityVerificationReports *v1IdentityVerificationReportService + // V1IdentityVerificationSessions is the service used to invoke /v1/identity/verification_sessions APIs. + V1IdentityVerificationSessions *v1IdentityVerificationSessionService + // V1InvoiceItems is the service used to invoke /v1/invoiceitems APIs. + V1InvoiceItems *v1InvoiceItemService + // V1InvoiceLineItems is the service used to invoke /v1/invoices/{invoice}/lines APIs. + V1InvoiceLineItems *v1InvoiceLineItemService + // V1InvoicePayments is the service used to invoke /v1/invoice_payments APIs. + V1InvoicePayments *v1InvoicePaymentService + // V1InvoiceRenderingTemplates is the service used to invoke /v1/invoice_rendering_templates APIs. + V1InvoiceRenderingTemplates *v1InvoiceRenderingTemplateService + // V1Invoices is the service used to invoke /v1/invoices APIs. + V1Invoices *v1InvoiceService + // V1IssuingAuthorizations is the service used to invoke /v1/issuing/authorizations APIs. + V1IssuingAuthorizations *v1IssuingAuthorizationService + // V1IssuingCardholders is the service used to invoke /v1/issuing/cardholders APIs. + V1IssuingCardholders *v1IssuingCardholderService + // V1IssuingCards is the service used to invoke /v1/issuing/cards APIs. + V1IssuingCards *v1IssuingCardService + // V1IssuingDisputes is the service used to invoke /v1/issuing/disputes APIs. + V1IssuingDisputes *v1IssuingDisputeService + // V1IssuingPersonalizationDesigns is the service used to invoke /v1/issuing/personalization_designs APIs. + V1IssuingPersonalizationDesigns *v1IssuingPersonalizationDesignService + // V1IssuingPhysicalBundles is the service used to invoke /v1/issuing/physical_bundles APIs. + V1IssuingPhysicalBundles *v1IssuingPhysicalBundleService + // V1IssuingTokens is the service used to invoke /v1/issuing/tokens APIs. + V1IssuingTokens *v1IssuingTokenService + // V1IssuingTransactions is the service used to invoke /v1/issuing/transactions APIs. + V1IssuingTransactions *v1IssuingTransactionService + // V1LoginLinks is the service used to invoke /v1/accounts/{account}/login_links APIs. + V1LoginLinks *v1LoginLinkService + // V1Mandates is the service used to invoke /v1/mandates APIs. + V1Mandates *v1MandateService + // V1PaymentIntents is the service used to invoke /v1/payment_intents APIs. + V1PaymentIntents *v1PaymentIntentService + // V1PaymentLinks is the service used to invoke /v1/payment_links APIs. + V1PaymentLinks *v1PaymentLinkService + // V1PaymentMethodConfigurations is the service used to invoke /v1/payment_method_configurations APIs. + V1PaymentMethodConfigurations *v1PaymentMethodConfigurationService + // V1PaymentMethodDomains is the service used to invoke /v1/payment_method_domains APIs. + V1PaymentMethodDomains *v1PaymentMethodDomainService + // V1PaymentMethods is the service used to invoke /v1/payment_methods APIs. + V1PaymentMethods *v1PaymentMethodService + // V1PaymentSources is the service used to invoke /v1/customers/{customer}/sources APIs. + V1PaymentSources *v1PaymentSourceService + // V1Payouts is the service used to invoke /v1/payouts APIs. + V1Payouts *v1PayoutService + // V1Persons is the service used to invoke /v1/accounts/{account}/persons APIs. + V1Persons *v1PersonService + // V1Plans is the service used to invoke /v1/plans APIs. + V1Plans *v1PlanService + // V1Prices is the service used to invoke /v1/prices APIs. + V1Prices *v1PriceService + // V1ProductFeatures is the service used to invoke /v1/products/{product}/features APIs. + V1ProductFeatures *v1ProductFeatureService + // V1Products is the service used to invoke /v1/products APIs. + V1Products *v1ProductService + // V1PromotionCodes is the service used to invoke /v1/promotion_codes APIs. + V1PromotionCodes *v1PromotionCodeService + // V1Quotes is the service used to invoke /v1/quotes APIs. + V1Quotes *v1QuoteService + // V1RadarEarlyFraudWarnings is the service used to invoke /v1/radar/early_fraud_warnings APIs. + V1RadarEarlyFraudWarnings *v1RadarEarlyFraudWarningService + // V1RadarValueListItems is the service used to invoke /v1/radar/value_list_items APIs. + V1RadarValueListItems *v1RadarValueListItemService + // V1RadarValueLists is the service used to invoke /v1/radar/value_lists APIs. + V1RadarValueLists *v1RadarValueListService + // V1Refunds is the service used to invoke /v1/refunds APIs. + V1Refunds *v1RefundService + // V1ReportingReportRuns is the service used to invoke /v1/reporting/report_runs APIs. + V1ReportingReportRuns *v1ReportingReportRunService + // V1ReportingReportTypes is the service used to invoke /v1/reporting/report_types APIs. + V1ReportingReportTypes *v1ReportingReportTypeService + // V1Reviews is the service used to invoke /v1/reviews APIs. + V1Reviews *v1ReviewService + // V1SetupAttempts is the service used to invoke /v1/setup_attempts APIs. + V1SetupAttempts *v1SetupAttemptService + // V1SetupIntents is the service used to invoke /v1/setup_intents APIs. + V1SetupIntents *v1SetupIntentService + // V1ShippingRates is the service used to invoke /v1/shipping_rates APIs. + V1ShippingRates *v1ShippingRateService + // V1SigmaScheduledQueryRuns is the service used to invoke /v1/sigma/scheduled_query_runs APIs. + V1SigmaScheduledQueryRuns *v1SigmaScheduledQueryRunService + // V1Sources is the service used to invoke /v1/sources APIs. + V1Sources *v1SourceService + // V1SourceTransactions is the service used to invoke /v1/sources/{source}/source_transactions APIs. + V1SourceTransactions *v1SourceTransactionService + // V1SubscriptionItems is the service used to invoke /v1/subscription_items APIs. + V1SubscriptionItems *v1SubscriptionItemService + // V1Subscriptions is the service used to invoke /v1/subscriptions APIs. + V1Subscriptions *v1SubscriptionService + // V1SubscriptionSchedules is the service used to invoke /v1/subscription_schedules APIs. + V1SubscriptionSchedules *v1SubscriptionScheduleService + // V1TaxCalculations is the service used to invoke /v1/tax/calculations APIs. + V1TaxCalculations *v1TaxCalculationService + // V1TaxCodes is the service used to invoke /v1/tax_codes APIs. + V1TaxCodes *v1TaxCodeService + // V1TaxIDs is the service used to invoke /v1/tax_ids APIs. + V1TaxIDs *v1TaxIDService + // V1TaxRates is the service used to invoke /v1/tax_rates APIs. + V1TaxRates *v1TaxRateService + // V1TaxRegistrations is the service used to invoke /v1/tax/registrations APIs. + V1TaxRegistrations *v1TaxRegistrationService + // V1TaxSettings is the service used to invoke /v1/tax/settings APIs. + V1TaxSettings *v1TaxSettingsService + // V1TaxTransactions is the service used to invoke /v1/tax/transactions APIs. + V1TaxTransactions *v1TaxTransactionService + // V1TerminalConfigurations is the service used to invoke /v1/terminal/configurations APIs. + V1TerminalConfigurations *v1TerminalConfigurationService + // V1TerminalConnectionTokens is the service used to invoke /v1/terminal/connection_tokens APIs. + V1TerminalConnectionTokens *v1TerminalConnectionTokenService + // V1TerminalLocations is the service used to invoke /v1/terminal/locations APIs. + V1TerminalLocations *v1TerminalLocationService + // V1TerminalReaders is the service used to invoke /v1/terminal/readers APIs. + V1TerminalReaders *v1TerminalReaderService + // V1TestHelpersConfirmationTokens is the service used to invoke /v1/confirmation_tokens APIs. + V1TestHelpersConfirmationTokens *v1TestHelpersConfirmationTokenService + // V1TestHelpersCustomers is the service used to invoke /v1/customers APIs. + V1TestHelpersCustomers *v1TestHelpersCustomerService + // V1TestHelpersIssuingAuthorizations is the service used to invoke /v1/issuing/authorizations APIs. + V1TestHelpersIssuingAuthorizations *v1TestHelpersIssuingAuthorizationService + // V1TestHelpersIssuingCards is the service used to invoke /v1/issuing/cards APIs. + V1TestHelpersIssuingCards *v1TestHelpersIssuingCardService + // V1TestHelpersIssuingPersonalizationDesigns is the service used to invoke /v1/issuing/personalization_designs APIs. + V1TestHelpersIssuingPersonalizationDesigns *v1TestHelpersIssuingPersonalizationDesignService + // V1TestHelpersIssuingTransactions is the service used to invoke /v1/issuing/transactions APIs. + V1TestHelpersIssuingTransactions *v1TestHelpersIssuingTransactionService + // V1TestHelpersRefunds is the service used to invoke /v1/refunds APIs. + V1TestHelpersRefunds *v1TestHelpersRefundService + // V1TestHelpersTerminalReaders is the service used to invoke /v1/terminal/readers APIs. + V1TestHelpersTerminalReaders *v1TestHelpersTerminalReaderService + // V1TestHelpersTestClocks is the service used to invoke /v1/test_helpers/test_clocks APIs. + V1TestHelpersTestClocks *v1TestHelpersTestClockService + // V1TestHelpersTreasuryInboundTransfers is the service used to invoke /v1/treasury/inbound_transfers APIs. + V1TestHelpersTreasuryInboundTransfers *v1TestHelpersTreasuryInboundTransferService + // V1TestHelpersTreasuryOutboundPayments is the service used to invoke /v1/treasury/outbound_payments APIs. + V1TestHelpersTreasuryOutboundPayments *v1TestHelpersTreasuryOutboundPaymentService + // V1TestHelpersTreasuryOutboundTransfers is the service used to invoke /v1/treasury/outbound_transfers APIs. + V1TestHelpersTreasuryOutboundTransfers *v1TestHelpersTreasuryOutboundTransferService + // V1TestHelpersTreasuryReceivedCredits is the service used to invoke /v1/treasury/received_credits APIs. + V1TestHelpersTreasuryReceivedCredits *v1TestHelpersTreasuryReceivedCreditService + // V1TestHelpersTreasuryReceivedDebits is the service used to invoke /v1/treasury/received_debits APIs. + V1TestHelpersTreasuryReceivedDebits *v1TestHelpersTreasuryReceivedDebitService + // V1Tokens is the service used to invoke /v1/tokens APIs. + V1Tokens *v1TokenService + // V1Topups is the service used to invoke /v1/topups APIs. + V1Topups *v1TopupService + // V1TransferReversals is the service used to invoke /v1/transfers/{id}/reversals APIs. + V1TransferReversals *v1TransferReversalService + // V1Transfers is the service used to invoke /v1/transfers APIs. + V1Transfers *v1TransferService + // V1TreasuryCreditReversals is the service used to invoke /v1/treasury/credit_reversals APIs. + V1TreasuryCreditReversals *v1TreasuryCreditReversalService + // V1TreasuryDebitReversals is the service used to invoke /v1/treasury/debit_reversals APIs. + V1TreasuryDebitReversals *v1TreasuryDebitReversalService + // V1TreasuryFinancialAccounts is the service used to invoke /v1/treasury/financial_accounts APIs. + V1TreasuryFinancialAccounts *v1TreasuryFinancialAccountService + // V1TreasuryInboundTransfers is the service used to invoke /v1/treasury/inbound_transfers APIs. + V1TreasuryInboundTransfers *v1TreasuryInboundTransferService + // V1TreasuryOutboundPayments is the service used to invoke /v1/treasury/outbound_payments APIs. + V1TreasuryOutboundPayments *v1TreasuryOutboundPaymentService + // V1TreasuryOutboundTransfers is the service used to invoke /v1/treasury/outbound_transfers APIs. + V1TreasuryOutboundTransfers *v1TreasuryOutboundTransferService + // V1TreasuryReceivedCredits is the service used to invoke /v1/treasury/received_credits APIs. + V1TreasuryReceivedCredits *v1TreasuryReceivedCreditService + // V1TreasuryReceivedDebits is the service used to invoke /v1/treasury/received_debits APIs. + V1TreasuryReceivedDebits *v1TreasuryReceivedDebitService + // V1TreasuryTransactionEntries is the service used to invoke /v1/treasury/transaction_entries APIs. + V1TreasuryTransactionEntries *v1TreasuryTransactionEntryService + // V1TreasuryTransactions is the service used to invoke /v1/treasury/transactions APIs. + V1TreasuryTransactions *v1TreasuryTransactionService + // V1WebhookEndpoints is the service used to invoke /v1/webhook_endpoints APIs. + V1WebhookEndpoints *v1WebhookEndpointService + // V2BillingMeterEventAdjustments is the service used to invoke /v2/billing/meter_event_adjustments APIs. + V2BillingMeterEventAdjustments *v2BillingMeterEventAdjustmentService + // V2BillingMeterEvents is the service used to invoke /v2/billing/meter_events APIs. + V2BillingMeterEvents *v2BillingMeterEventService + // V2BillingMeterEventSessions is the service used to invoke /v2/billing/meter_event_session APIs. + V2BillingMeterEventSessions *v2BillingMeterEventSessionService + // V2BillingMeterEventStreams is the service used to invoke /v2/billing/meter_event_stream APIs. + V2BillingMeterEventStreams *v2BillingMeterEventStreamService + // V2CoreEventDestinations is the service used to invoke /v2/core/event_destinations APIs. + V2CoreEventDestinations *v2CoreEventDestinationService + // V2CoreEvents is the service used to invoke /v2/core/events APIs. + V2CoreEvents *v2CoreEventService + // stripeClientStruct: The end of the section generated from our OpenAPI spec +} + +// NewClient creates a new Stripe [Client] with the given API key. +func NewClient(key string, opts ...ClientOption) *Client { + usage := []string{"stripe_client_new"} + client := &Client{} + cfg := clientConfig{key: key, usage: usage} + for _, opt := range opts { + if opt == nil { + continue + } + opt(&cfg) + } + initClient(client, cfg) + return client +} + +func initClient(client *Client, cfg clientConfig) { + if cfg.backends == nil { + cfg.backends = &Backends{ + API: &UsageBackend{B: GetBackend(APIBackend), Usage: cfg.usage}, + Connect: &UsageBackend{B: GetBackend(ConnectBackend), Usage: cfg.usage}, + Uploads: &UsageBackend{B: GetBackend(UploadsBackend), Usage: cfg.usage}, + MeterEvents: &UsageBackend{B: GetBackend(MeterEventsBackend), Usage: cfg.usage}, + } + } + backends := cfg.backends + key := cfg.key + + // stripeClientInit: The beginning of the section generated from our OpenAPI spec + client.OAuth = &oauthService{B: backends.Connect, Key: key} + client.V1AccountLinks = &v1AccountLinkService{B: backends.API, Key: key} + client.V1Accounts = &v1AccountService{B: backends.API, Key: key} + client.V1AccountSessions = &v1AccountSessionService{B: backends.API, Key: key} + client.V1ApplePayDomains = &v1ApplePayDomainService{B: backends.API, Key: key} + client.V1ApplicationFees = &v1ApplicationFeeService{B: backends.API, Key: key} + client.V1AppsSecrets = &v1AppsSecretService{B: backends.API, Key: key} + client.V1Balance = &v1BalanceService{B: backends.API, Key: key} + client.V1BalanceTransactions = &v1BalanceTransactionService{B: backends.API, Key: key} + client.V1BankAccounts = &v1BankAccountService{B: backends.API, Key: key} + client.V1BillingAlerts = &v1BillingAlertService{B: backends.API, Key: key} + client.V1BillingCreditBalanceSummary = &v1BillingCreditBalanceSummaryService{B: backends.API, Key: key} + client.V1BillingCreditBalanceTransactions = &v1BillingCreditBalanceTransactionService{B: backends.API, Key: key} + client.V1BillingCreditGrants = &v1BillingCreditGrantService{B: backends.API, Key: key} + client.V1BillingMeterEventAdjustments = &v1BillingMeterEventAdjustmentService{B: backends.API, Key: key} + client.V1BillingMeterEvents = &v1BillingMeterEventService{B: backends.API, Key: key} + client.V1BillingMeterEventSummaries = &v1BillingMeterEventSummaryService{B: backends.API, Key: key} + client.V1BillingMeters = &v1BillingMeterService{B: backends.API, Key: key} + client.V1BillingPortalConfigurations = &v1BillingPortalConfigurationService{B: backends.API, Key: key} + client.V1BillingPortalSessions = &v1BillingPortalSessionService{B: backends.API, Key: key} + client.V1Capabilities = &v1CapabilityService{B: backends.API, Key: key} + client.V1Cards = &v1CardService{B: backends.API, Key: key} + client.V1CashBalances = &v1CashBalanceService{B: backends.API, Key: key} + client.V1Charges = &v1ChargeService{B: backends.API, Key: key} + client.V1CheckoutSessions = &v1CheckoutSessionService{B: backends.API, Key: key} + client.V1ClimateOrders = &v1ClimateOrderService{B: backends.API, Key: key} + client.V1ClimateProducts = &v1ClimateProductService{B: backends.API, Key: key} + client.V1ClimateSuppliers = &v1ClimateSupplierService{B: backends.API, Key: key} + client.V1ConfirmationTokens = &v1ConfirmationTokenService{B: backends.API, Key: key} + client.V1CountrySpecs = &v1CountrySpecService{B: backends.API, Key: key} + client.V1Coupons = &v1CouponService{B: backends.API, Key: key} + client.V1CreditNotes = &v1CreditNoteService{B: backends.API, Key: key} + client.V1CustomerBalanceTransactions = &v1CustomerBalanceTransactionService{B: backends.API, Key: key} + client.V1CustomerCashBalanceTransactions = &v1CustomerCashBalanceTransactionService{B: backends.API, Key: key} + client.V1Customers = &v1CustomerService{B: backends.API, Key: key} + client.V1CustomerSessions = &v1CustomerSessionService{B: backends.API, Key: key} + client.V1Disputes = &v1DisputeService{B: backends.API, Key: key} + client.V1EntitlementsActiveEntitlements = &v1EntitlementsActiveEntitlementService{B: backends.API, Key: key} + client.V1EntitlementsFeatures = &v1EntitlementsFeatureService{B: backends.API, Key: key} + client.V1EphemeralKeys = &v1EphemeralKeyService{B: backends.API, Key: key} + client.V1Events = &v1EventService{B: backends.API, Key: key} + client.V1FeeRefunds = &v1FeeRefundService{B: backends.API, Key: key} + client.V1FileLinks = &v1FileLinkService{B: backends.API, Key: key} + client.V1Files = &v1FileService{B: backends.API, BUploads: backends.Uploads, Key: key} + client.V1FinancialConnectionsAccounts = &v1FinancialConnectionsAccountService{B: backends.API, Key: key} + client.V1FinancialConnectionsSessions = &v1FinancialConnectionsSessionService{B: backends.API, Key: key} + client.V1FinancialConnectionsTransactions = &v1FinancialConnectionsTransactionService{B: backends.API, Key: key} + client.V1ForwardingRequests = &v1ForwardingRequestService{B: backends.API, Key: key} + client.V1IdentityVerificationReports = &v1IdentityVerificationReportService{B: backends.API, Key: key} + client.V1IdentityVerificationSessions = &v1IdentityVerificationSessionService{B: backends.API, Key: key} + client.V1InvoiceItems = &v1InvoiceItemService{B: backends.API, Key: key} + client.V1InvoiceLineItems = &v1InvoiceLineItemService{B: backends.API, Key: key} + client.V1InvoicePayments = &v1InvoicePaymentService{B: backends.API, Key: key} + client.V1InvoiceRenderingTemplates = &v1InvoiceRenderingTemplateService{B: backends.API, Key: key} + client.V1Invoices = &v1InvoiceService{B: backends.API, Key: key} + client.V1IssuingAuthorizations = &v1IssuingAuthorizationService{B: backends.API, Key: key} + client.V1IssuingCardholders = &v1IssuingCardholderService{B: backends.API, Key: key} + client.V1IssuingCards = &v1IssuingCardService{B: backends.API, Key: key} + client.V1IssuingDisputes = &v1IssuingDisputeService{B: backends.API, Key: key} + client.V1IssuingPersonalizationDesigns = &v1IssuingPersonalizationDesignService{B: backends.API, Key: key} + client.V1IssuingPhysicalBundles = &v1IssuingPhysicalBundleService{B: backends.API, Key: key} + client.V1IssuingTokens = &v1IssuingTokenService{B: backends.API, Key: key} + client.V1IssuingTransactions = &v1IssuingTransactionService{B: backends.API, Key: key} + client.V1LoginLinks = &v1LoginLinkService{B: backends.API, Key: key} + client.V1Mandates = &v1MandateService{B: backends.API, Key: key} + client.V1PaymentIntents = &v1PaymentIntentService{B: backends.API, Key: key} + client.V1PaymentLinks = &v1PaymentLinkService{B: backends.API, Key: key} + client.V1PaymentMethodConfigurations = &v1PaymentMethodConfigurationService{B: backends.API, Key: key} + client.V1PaymentMethodDomains = &v1PaymentMethodDomainService{B: backends.API, Key: key} + client.V1PaymentMethods = &v1PaymentMethodService{B: backends.API, Key: key} + client.V1PaymentSources = &v1PaymentSourceService{B: backends.API, Key: key} + client.V1Payouts = &v1PayoutService{B: backends.API, Key: key} + client.V1Persons = &v1PersonService{B: backends.API, Key: key} + client.V1Plans = &v1PlanService{B: backends.API, Key: key} + client.V1Prices = &v1PriceService{B: backends.API, Key: key} + client.V1ProductFeatures = &v1ProductFeatureService{B: backends.API, Key: key} + client.V1Products = &v1ProductService{B: backends.API, Key: key} + client.V1PromotionCodes = &v1PromotionCodeService{B: backends.API, Key: key} + client.V1Quotes = &v1QuoteService{B: backends.API, BUploads: backends.Uploads, Key: key} + client.V1RadarEarlyFraudWarnings = &v1RadarEarlyFraudWarningService{B: backends.API, Key: key} + client.V1RadarValueListItems = &v1RadarValueListItemService{B: backends.API, Key: key} + client.V1RadarValueLists = &v1RadarValueListService{B: backends.API, Key: key} + client.V1Refunds = &v1RefundService{B: backends.API, Key: key} + client.V1ReportingReportRuns = &v1ReportingReportRunService{B: backends.API, Key: key} + client.V1ReportingReportTypes = &v1ReportingReportTypeService{B: backends.API, Key: key} + client.V1Reviews = &v1ReviewService{B: backends.API, Key: key} + client.V1SetupAttempts = &v1SetupAttemptService{B: backends.API, Key: key} + client.V1SetupIntents = &v1SetupIntentService{B: backends.API, Key: key} + client.V1ShippingRates = &v1ShippingRateService{B: backends.API, Key: key} + client.V1SigmaScheduledQueryRuns = &v1SigmaScheduledQueryRunService{B: backends.API, Key: key} + client.V1Sources = &v1SourceService{B: backends.API, Key: key} + client.V1SourceTransactions = &v1SourceTransactionService{B: backends.API, Key: key} + client.V1SubscriptionItems = &v1SubscriptionItemService{B: backends.API, Key: key} + client.V1Subscriptions = &v1SubscriptionService{B: backends.API, Key: key} + client.V1SubscriptionSchedules = &v1SubscriptionScheduleService{B: backends.API, Key: key} + client.V1TaxCalculations = &v1TaxCalculationService{B: backends.API, Key: key} + client.V1TaxCodes = &v1TaxCodeService{B: backends.API, Key: key} + client.V1TaxIDs = &v1TaxIDService{B: backends.API, Key: key} + client.V1TaxRates = &v1TaxRateService{B: backends.API, Key: key} + client.V1TaxRegistrations = &v1TaxRegistrationService{B: backends.API, Key: key} + client.V1TaxSettings = &v1TaxSettingsService{B: backends.API, Key: key} + client.V1TaxTransactions = &v1TaxTransactionService{B: backends.API, Key: key} + client.V1TerminalConfigurations = &v1TerminalConfigurationService{B: backends.API, Key: key} + client.V1TerminalConnectionTokens = &v1TerminalConnectionTokenService{B: backends.API, Key: key} + client.V1TerminalLocations = &v1TerminalLocationService{B: backends.API, Key: key} + client.V1TerminalReaders = &v1TerminalReaderService{B: backends.API, Key: key} + client.V1TestHelpersConfirmationTokens = &v1TestHelpersConfirmationTokenService{B: backends.API, Key: key} + client.V1TestHelpersCustomers = &v1TestHelpersCustomerService{B: backends.API, Key: key} + client.V1TestHelpersIssuingAuthorizations = &v1TestHelpersIssuingAuthorizationService{B: backends.API, Key: key} + client.V1TestHelpersIssuingCards = &v1TestHelpersIssuingCardService{B: backends.API, Key: key} + client.V1TestHelpersIssuingPersonalizationDesigns = &v1TestHelpersIssuingPersonalizationDesignService{B: backends.API, Key: key} + client.V1TestHelpersIssuingTransactions = &v1TestHelpersIssuingTransactionService{B: backends.API, Key: key} + client.V1TestHelpersRefunds = &v1TestHelpersRefundService{B: backends.API, Key: key} + client.V1TestHelpersTerminalReaders = &v1TestHelpersTerminalReaderService{B: backends.API, Key: key} + client.V1TestHelpersTestClocks = &v1TestHelpersTestClockService{B: backends.API, Key: key} + client.V1TestHelpersTreasuryInboundTransfers = &v1TestHelpersTreasuryInboundTransferService{B: backends.API, Key: key} + client.V1TestHelpersTreasuryOutboundPayments = &v1TestHelpersTreasuryOutboundPaymentService{B: backends.API, Key: key} + client.V1TestHelpersTreasuryOutboundTransfers = &v1TestHelpersTreasuryOutboundTransferService{B: backends.API, Key: key} + client.V1TestHelpersTreasuryReceivedCredits = &v1TestHelpersTreasuryReceivedCreditService{B: backends.API, Key: key} + client.V1TestHelpersTreasuryReceivedDebits = &v1TestHelpersTreasuryReceivedDebitService{B: backends.API, Key: key} + client.V1Tokens = &v1TokenService{B: backends.API, Key: key} + client.V1Topups = &v1TopupService{B: backends.API, Key: key} + client.V1TransferReversals = &v1TransferReversalService{B: backends.API, Key: key} + client.V1Transfers = &v1TransferService{B: backends.API, Key: key} + client.V1TreasuryCreditReversals = &v1TreasuryCreditReversalService{B: backends.API, Key: key} + client.V1TreasuryDebitReversals = &v1TreasuryDebitReversalService{B: backends.API, Key: key} + client.V1TreasuryFinancialAccounts = &v1TreasuryFinancialAccountService{B: backends.API, Key: key} + client.V1TreasuryInboundTransfers = &v1TreasuryInboundTransferService{B: backends.API, Key: key} + client.V1TreasuryOutboundPayments = &v1TreasuryOutboundPaymentService{B: backends.API, Key: key} + client.V1TreasuryOutboundTransfers = &v1TreasuryOutboundTransferService{B: backends.API, Key: key} + client.V1TreasuryReceivedCredits = &v1TreasuryReceivedCreditService{B: backends.API, Key: key} + client.V1TreasuryReceivedDebits = &v1TreasuryReceivedDebitService{B: backends.API, Key: key} + client.V1TreasuryTransactionEntries = &v1TreasuryTransactionEntryService{B: backends.API, Key: key} + client.V1TreasuryTransactions = &v1TreasuryTransactionService{B: backends.API, Key: key} + client.V1WebhookEndpoints = &v1WebhookEndpointService{B: backends.API, Key: key} + client.V2BillingMeterEventAdjustments = &v2BillingMeterEventAdjustmentService{B: backends.API, Key: key} + client.V2BillingMeterEvents = &v2BillingMeterEventService{B: backends.API, Key: key} + client.V2BillingMeterEventSessions = &v2BillingMeterEventSessionService{B: backends.API, Key: key} + client.V2BillingMeterEventStreams = &v2BillingMeterEventStreamService{BMeterEvents: backends.MeterEvents, Key: key} + client.V2CoreEventDestinations = &v2CoreEventDestinationService{B: backends.API, Key: key} + client.V2CoreEvents = &v2CoreEventService{B: backends.API, Key: key} + // stripeClientInit: The end of the section generated from our OpenAPI spec +} + +type clientConfig struct { + backends *Backends + usage []string + key string +} + +// ClientOption allows for functional options to be passed to the NewClient constructor. +type ClientOption func(*clientConfig) + +// WithBackends allows for setting a custom [*Backends] struct when creating a new client. +// This is useful for testing or when you want to use a different backend constructed +// from [NewBackendsWithConfig]. +func WithBackends(backends *Backends) ClientOption { + return func(c *clientConfig) { + c.backends = backends + } +} + +// ParseThinEvent parses a Stripe event from the payload and verifies its signature. +// It returns a ThinEvent object and an error if the parsing or verification fails. +func (c *Client) ParseThinEvent(payload []byte, header string, secret string, opts ...WebhookOption) (*ThinEvent, error) { + if err := ValidatePayload(payload, header, secret, opts...); err != nil { + return nil, err + } + var event ThinEvent + if err := json.Unmarshal(payload, &event); err != nil { + return nil, err + } + return &event, nil +} + +// ConstructEvent initializes an Event object from a JSON webhook payload, validating +// the Stripe-Signature header using the specified signing secret. Returns an error +// if the body or Stripe-Signature header provided are unreadable, if the +// signature doesn't match, or if the timestamp for the signature is older than +// WebhookDefaultTolerance. +// +// NOTE: Stripe will only send Webhook signing headers after you have retrieved +// your signing secret from the Stripe dashboard: +// https://dashboard.stripe.com/webhooks +// +// This will return an error if the event API version does not match the +// APIVersion constant. +func (c *Client) ConstructEvent(payload []byte, header string, secret string, opts ...WebhookOption) (Event, error) { + return ConstructEvent(payload, header, secret, opts...) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/subscription.go b/vendor/github.com/stripe/stripe-go/v82/subscription.go new file mode 100644 index 00000000..714720d4 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/subscription.go @@ -0,0 +1,2073 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "encoding/json" + "github.com/stripe/stripe-go/v82/form" +) + +// If Stripe disabled automatic tax, this enum describes why. +type SubscriptionAutomaticTaxDisabledReason string + +// List of values that SubscriptionAutomaticTaxDisabledReason can take +const ( + SubscriptionAutomaticTaxDisabledReasonRequiresLocationInputs SubscriptionAutomaticTaxDisabledReason = "requires_location_inputs" +) + +// Type of the account referenced. +type SubscriptionAutomaticTaxLiabilityType string + +// List of values that SubscriptionAutomaticTaxLiabilityType can take +const ( + SubscriptionAutomaticTaxLiabilityTypeAccount SubscriptionAutomaticTaxLiabilityType = "account" + SubscriptionAutomaticTaxLiabilityTypeSelf SubscriptionAutomaticTaxLiabilityType = "self" +) + +// Controls how prorations and invoices for subscriptions are calculated and orchestrated. +type SubscriptionBillingModeType string + +// List of values that SubscriptionBillingModeType can take +const ( + SubscriptionBillingModeTypeClassic SubscriptionBillingModeType = "classic" + SubscriptionBillingModeTypeFlexible SubscriptionBillingModeType = "flexible" +) + +// The customer submitted reason for why they canceled, if the subscription was canceled explicitly by the user. +type SubscriptionCancellationDetailsFeedback string + +// List of values that SubscriptionCancellationDetailsFeedback can take +const ( + SubscriptionCancellationDetailsFeedbackCustomerService SubscriptionCancellationDetailsFeedback = "customer_service" + SubscriptionCancellationDetailsFeedbackLowQuality SubscriptionCancellationDetailsFeedback = "low_quality" + SubscriptionCancellationDetailsFeedbackMissingFeatures SubscriptionCancellationDetailsFeedback = "missing_features" + SubscriptionCancellationDetailsFeedbackOther SubscriptionCancellationDetailsFeedback = "other" + SubscriptionCancellationDetailsFeedbackSwitchedService SubscriptionCancellationDetailsFeedback = "switched_service" + SubscriptionCancellationDetailsFeedbackTooComplex SubscriptionCancellationDetailsFeedback = "too_complex" + SubscriptionCancellationDetailsFeedbackTooExpensive SubscriptionCancellationDetailsFeedback = "too_expensive" + SubscriptionCancellationDetailsFeedbackUnused SubscriptionCancellationDetailsFeedback = "unused" +) + +// Why this subscription was canceled. +type SubscriptionCancellationDetailsReason string + +// List of values that SubscriptionCancellationDetailsReason can take +const ( + SubscriptionCancellationDetailsReasonCancellationRequested SubscriptionCancellationDetailsReason = "cancellation_requested" + SubscriptionCancellationDetailsReasonPaymentDisputed SubscriptionCancellationDetailsReason = "payment_disputed" + SubscriptionCancellationDetailsReasonPaymentFailed SubscriptionCancellationDetailsReason = "payment_failed" +) + +// Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. +type SubscriptionCollectionMethod string + +// List of values that SubscriptionCollectionMethod can take +const ( + SubscriptionCollectionMethodChargeAutomatically SubscriptionCollectionMethod = "charge_automatically" + SubscriptionCollectionMethodSendInvoice SubscriptionCollectionMethod = "send_invoice" +) + +// Type of the account referenced. +type SubscriptionInvoiceSettingsIssuerType string + +// List of values that SubscriptionInvoiceSettingsIssuerType can take +const ( + SubscriptionInvoiceSettingsIssuerTypeAccount SubscriptionInvoiceSettingsIssuerType = "account" + SubscriptionInvoiceSettingsIssuerTypeSelf SubscriptionInvoiceSettingsIssuerType = "self" +) + +// The payment collection behavior for this subscription while paused. One of `keep_as_draft`, `mark_uncollectible`, or `void`. +type SubscriptionPauseCollectionBehavior string + +// List of values that SubscriptionPauseCollectionBehavior can take +const ( + SubscriptionPauseCollectionBehaviorKeepAsDraft SubscriptionPauseCollectionBehavior = "keep_as_draft" + SubscriptionPauseCollectionBehaviorMarkUncollectible SubscriptionPauseCollectionBehavior = "mark_uncollectible" + SubscriptionPauseCollectionBehaviorVoid SubscriptionPauseCollectionBehavior = "void" +) + +// Transaction type of the mandate. +type SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsTransactionType string + +// List of values that SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsTransactionType can take +const ( + SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsTransactionTypeBusiness SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsTransactionType = "business" + SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsTransactionTypePersonal SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsTransactionType = "personal" +) + +// Bank account verification method. +type SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethod string + +// List of values that SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethod can take +const ( + SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethodAutomatic SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethod = "automatic" + SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethodInstant SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethod = "instant" + SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethodMicrodeposits SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethod = "microdeposits" +) + +// One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. +type SubscriptionPaymentSettingsPaymentMethodOptionsCardMandateOptionsAmountType string + +// List of values that SubscriptionPaymentSettingsPaymentMethodOptionsCardMandateOptionsAmountType can take +const ( + SubscriptionPaymentSettingsPaymentMethodOptionsCardMandateOptionsAmountTypeFixed SubscriptionPaymentSettingsPaymentMethodOptionsCardMandateOptionsAmountType = "fixed" + SubscriptionPaymentSettingsPaymentMethodOptionsCardMandateOptionsAmountTypeMaximum SubscriptionPaymentSettingsPaymentMethodOptionsCardMandateOptionsAmountType = "maximum" +) + +// Selected network to process this Subscription on. Depends on the available networks of the card attached to the Subscription. Can be only set confirm-time. +type SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork string + +// List of values that SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork can take +const ( + SubscriptionPaymentSettingsPaymentMethodOptionsCardNetworkAmex SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork = "amex" + SubscriptionPaymentSettingsPaymentMethodOptionsCardNetworkCartesBancaires SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork = "cartes_bancaires" + SubscriptionPaymentSettingsPaymentMethodOptionsCardNetworkDiners SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork = "diners" + SubscriptionPaymentSettingsPaymentMethodOptionsCardNetworkDiscover SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork = "discover" + SubscriptionPaymentSettingsPaymentMethodOptionsCardNetworkEFTPOSAU SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork = "eftpos_au" + SubscriptionPaymentSettingsPaymentMethodOptionsCardNetworkGirocard SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork = "girocard" + SubscriptionPaymentSettingsPaymentMethodOptionsCardNetworkInterac SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork = "interac" + SubscriptionPaymentSettingsPaymentMethodOptionsCardNetworkJCB SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork = "jcb" + SubscriptionPaymentSettingsPaymentMethodOptionsCardNetworkLink SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork = "link" + SubscriptionPaymentSettingsPaymentMethodOptionsCardNetworkMastercard SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork = "mastercard" + SubscriptionPaymentSettingsPaymentMethodOptionsCardNetworkUnionpay SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork = "unionpay" + SubscriptionPaymentSettingsPaymentMethodOptionsCardNetworkUnknown SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork = "unknown" + SubscriptionPaymentSettingsPaymentMethodOptionsCardNetworkVisa SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork = "visa" +) + +// We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. +type SubscriptionPaymentSettingsPaymentMethodOptionsCardRequestThreeDSecure string + +// List of values that SubscriptionPaymentSettingsPaymentMethodOptionsCardRequestThreeDSecure can take +const ( + SubscriptionPaymentSettingsPaymentMethodOptionsCardRequestThreeDSecureAny SubscriptionPaymentSettingsPaymentMethodOptionsCardRequestThreeDSecure = "any" + SubscriptionPaymentSettingsPaymentMethodOptionsCardRequestThreeDSecureAutomatic SubscriptionPaymentSettingsPaymentMethodOptionsCardRequestThreeDSecure = "automatic" + SubscriptionPaymentSettingsPaymentMethodOptionsCardRequestThreeDSecureChallenge SubscriptionPaymentSettingsPaymentMethodOptionsCardRequestThreeDSecure = "challenge" +) + +// The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. +type SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceFundingType string + +// List of values that SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceFundingType can take +const ( + SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceFundingTypeBankTransfer SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceFundingType = "bank_transfer" +) + +// The account subcategories to use to filter for possible accounts to link. Valid subcategories are `checking` and `savings`. +type SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory string + +// List of values that SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory can take +const ( + SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategoryChecking SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory = "checking" + SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategorySavings SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory = "savings" +) + +// The list of permissions to request. The `payment_method` permission must be included. +type SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission string + +// List of values that SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission can take +const ( + SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionBalances SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "balances" + SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionOwnership SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "ownership" + SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionPaymentMethod SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "payment_method" + SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermissionTransactions SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission = "transactions" +) + +// Data features requested to be retrieved upon account creation. +type SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch string + +// List of values that SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch can take +const ( + SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchBalances SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "balances" + SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchOwnership SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "ownership" + SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetchTransactions SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch = "transactions" +) + +// Bank account verification method. +type SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethod string + +// List of values that SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethod can take +const ( + SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethodAutomatic SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethod = "automatic" + SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethodInstant SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethod = "instant" + SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethodMicrodeposits SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethod = "microdeposits" +) + +// The list of payment method types to provide to every invoice created by the subscription. If not set, Stripe attempts to automatically determine the types to use by looking at the invoice's default payment method, the subscription's default payment method, the customer's default payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). +type SubscriptionPaymentSettingsPaymentMethodType string + +// List of values that SubscriptionPaymentSettingsPaymentMethodType can take +const ( + SubscriptionPaymentSettingsPaymentMethodTypeACHCreditTransfer SubscriptionPaymentSettingsPaymentMethodType = "ach_credit_transfer" + SubscriptionPaymentSettingsPaymentMethodTypeACHDebit SubscriptionPaymentSettingsPaymentMethodType = "ach_debit" + SubscriptionPaymentSettingsPaymentMethodTypeACSSDebit SubscriptionPaymentSettingsPaymentMethodType = "acss_debit" + SubscriptionPaymentSettingsPaymentMethodTypeAffirm SubscriptionPaymentSettingsPaymentMethodType = "affirm" + SubscriptionPaymentSettingsPaymentMethodTypeAmazonPay SubscriptionPaymentSettingsPaymentMethodType = "amazon_pay" + SubscriptionPaymentSettingsPaymentMethodTypeAUBECSDebit SubscriptionPaymentSettingsPaymentMethodType = "au_becs_debit" + SubscriptionPaymentSettingsPaymentMethodTypeBACSDebit SubscriptionPaymentSettingsPaymentMethodType = "bacs_debit" + SubscriptionPaymentSettingsPaymentMethodTypeBancontact SubscriptionPaymentSettingsPaymentMethodType = "bancontact" + SubscriptionPaymentSettingsPaymentMethodTypeBoleto SubscriptionPaymentSettingsPaymentMethodType = "boleto" + SubscriptionPaymentSettingsPaymentMethodTypeCard SubscriptionPaymentSettingsPaymentMethodType = "card" + SubscriptionPaymentSettingsPaymentMethodTypeCashApp SubscriptionPaymentSettingsPaymentMethodType = "cashapp" + SubscriptionPaymentSettingsPaymentMethodTypeCrypto SubscriptionPaymentSettingsPaymentMethodType = "crypto" + SubscriptionPaymentSettingsPaymentMethodTypeCustomerBalance SubscriptionPaymentSettingsPaymentMethodType = "customer_balance" + SubscriptionPaymentSettingsPaymentMethodTypeEPS SubscriptionPaymentSettingsPaymentMethodType = "eps" + SubscriptionPaymentSettingsPaymentMethodTypeFPX SubscriptionPaymentSettingsPaymentMethodType = "fpx" + SubscriptionPaymentSettingsPaymentMethodTypeGiropay SubscriptionPaymentSettingsPaymentMethodType = "giropay" + SubscriptionPaymentSettingsPaymentMethodTypeGrabpay SubscriptionPaymentSettingsPaymentMethodType = "grabpay" + SubscriptionPaymentSettingsPaymentMethodTypeIDEAL SubscriptionPaymentSettingsPaymentMethodType = "ideal" + SubscriptionPaymentSettingsPaymentMethodTypeJPCreditTransfer SubscriptionPaymentSettingsPaymentMethodType = "jp_credit_transfer" + SubscriptionPaymentSettingsPaymentMethodTypeKakaoPay SubscriptionPaymentSettingsPaymentMethodType = "kakao_pay" + SubscriptionPaymentSettingsPaymentMethodTypeKlarna SubscriptionPaymentSettingsPaymentMethodType = "klarna" + SubscriptionPaymentSettingsPaymentMethodTypeKonbini SubscriptionPaymentSettingsPaymentMethodType = "konbini" + SubscriptionPaymentSettingsPaymentMethodTypeKrCard SubscriptionPaymentSettingsPaymentMethodType = "kr_card" + SubscriptionPaymentSettingsPaymentMethodTypeLink SubscriptionPaymentSettingsPaymentMethodType = "link" + SubscriptionPaymentSettingsPaymentMethodTypeMultibanco SubscriptionPaymentSettingsPaymentMethodType = "multibanco" + SubscriptionPaymentSettingsPaymentMethodTypeNaverPay SubscriptionPaymentSettingsPaymentMethodType = "naver_pay" + SubscriptionPaymentSettingsPaymentMethodTypeNzBankAccount SubscriptionPaymentSettingsPaymentMethodType = "nz_bank_account" + SubscriptionPaymentSettingsPaymentMethodTypeP24 SubscriptionPaymentSettingsPaymentMethodType = "p24" + SubscriptionPaymentSettingsPaymentMethodTypePayco SubscriptionPaymentSettingsPaymentMethodType = "payco" + SubscriptionPaymentSettingsPaymentMethodTypePayNow SubscriptionPaymentSettingsPaymentMethodType = "paynow" + SubscriptionPaymentSettingsPaymentMethodTypePaypal SubscriptionPaymentSettingsPaymentMethodType = "paypal" + SubscriptionPaymentSettingsPaymentMethodTypePromptPay SubscriptionPaymentSettingsPaymentMethodType = "promptpay" + SubscriptionPaymentSettingsPaymentMethodTypeRevolutPay SubscriptionPaymentSettingsPaymentMethodType = "revolut_pay" + SubscriptionPaymentSettingsPaymentMethodTypeSEPACreditTransfer SubscriptionPaymentSettingsPaymentMethodType = "sepa_credit_transfer" + SubscriptionPaymentSettingsPaymentMethodTypeSEPADebit SubscriptionPaymentSettingsPaymentMethodType = "sepa_debit" + SubscriptionPaymentSettingsPaymentMethodTypeSofort SubscriptionPaymentSettingsPaymentMethodType = "sofort" + SubscriptionPaymentSettingsPaymentMethodTypeSwish SubscriptionPaymentSettingsPaymentMethodType = "swish" + SubscriptionPaymentSettingsPaymentMethodTypeUSBankAccount SubscriptionPaymentSettingsPaymentMethodType = "us_bank_account" + SubscriptionPaymentSettingsPaymentMethodTypeWeChatPay SubscriptionPaymentSettingsPaymentMethodType = "wechat_pay" +) + +// Configure whether Stripe updates `subscription.default_payment_method` when payment succeeds. Defaults to `off`. +type SubscriptionPaymentSettingsSaveDefaultPaymentMethod string + +// List of values that SubscriptionPaymentSettingsSaveDefaultPaymentMethod can take +const ( + SubscriptionPaymentSettingsSaveDefaultPaymentMethodOff SubscriptionPaymentSettingsSaveDefaultPaymentMethod = "off" + SubscriptionPaymentSettingsSaveDefaultPaymentMethodOnSubscription SubscriptionPaymentSettingsSaveDefaultPaymentMethod = "on_subscription" +) + +// Specifies invoicing frequency. Either `day`, `week`, `month` or `year`. +type SubscriptionPendingInvoiceItemIntervalInterval string + +// List of values that SubscriptionPendingInvoiceItemIntervalInterval can take +const ( + SubscriptionPendingInvoiceItemIntervalIntervalDay SubscriptionPendingInvoiceItemIntervalInterval = "day" + SubscriptionPendingInvoiceItemIntervalIntervalMonth SubscriptionPendingInvoiceItemIntervalInterval = "month" + SubscriptionPendingInvoiceItemIntervalIntervalWeek SubscriptionPendingInvoiceItemIntervalInterval = "week" + SubscriptionPendingInvoiceItemIntervalIntervalYear SubscriptionPendingInvoiceItemIntervalInterval = "year" +) + +// Possible values are `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `canceled`, `unpaid`, or `paused`. +// +// For `collection_method=charge_automatically` a subscription moves into `incomplete` if the initial payment attempt fails. A subscription in this status can only have metadata and default_source updated. Once the first invoice is paid, the subscription moves into an `active` status. If the first invoice is not paid within 23 hours, the subscription transitions to `incomplete_expired`. This is a terminal status, the open invoice will be voided and no further invoices will be generated. +// +// A subscription that is currently in a trial period is `trialing` and moves to `active` when the trial period is over. +// +// A subscription can only enter a `paused` status [when a trial ends without a payment method](https://stripe.com/docs/billing/subscriptions/trials#create-free-trials-without-payment). A `paused` subscription doesn't generate invoices and can be resumed after your customer adds their payment method. The `paused` status is different from [pausing collection](https://stripe.com/docs/billing/subscriptions/pause-payment), which still generates invoices and leaves the subscription's status unchanged. +// +// If subscription `collection_method=charge_automatically`, it becomes `past_due` when payment is required but cannot be paid (due to failed payment or awaiting additional user actions). Once Stripe has exhausted all payment retry attempts, the subscription will become `canceled` or `unpaid` (depending on your subscriptions settings). +// +// If subscription `collection_method=send_invoice` it becomes `past_due` when its invoice is not paid by the due date, and `canceled` or `unpaid` if it is still not paid by an additional deadline after that. Note that when a subscription has a status of `unpaid`, no subsequent invoices will be attempted (invoices will be created, but then immediately automatically closed). After receiving updated payment information from a customer, you may choose to reopen and pay their closed invoices. +type SubscriptionStatus string + +// List of values that SubscriptionStatus can take +const ( + SubscriptionStatusActive SubscriptionStatus = "active" + SubscriptionStatusCanceled SubscriptionStatus = "canceled" + SubscriptionStatusIncomplete SubscriptionStatus = "incomplete" + SubscriptionStatusIncompleteExpired SubscriptionStatus = "incomplete_expired" + SubscriptionStatusPastDue SubscriptionStatus = "past_due" + SubscriptionStatusPaused SubscriptionStatus = "paused" + SubscriptionStatusTrialing SubscriptionStatus = "trialing" + SubscriptionStatusUnpaid SubscriptionStatus = "unpaid" +) + +// Indicates how the subscription should change when the trial ends if the user did not provide a payment method. +type SubscriptionTrialSettingsEndBehaviorMissingPaymentMethod string + +// List of values that SubscriptionTrialSettingsEndBehaviorMissingPaymentMethod can take +const ( + SubscriptionTrialSettingsEndBehaviorMissingPaymentMethodCancel SubscriptionTrialSettingsEndBehaviorMissingPaymentMethod = "cancel" + SubscriptionTrialSettingsEndBehaviorMissingPaymentMethodCreateInvoice SubscriptionTrialSettingsEndBehaviorMissingPaymentMethod = "create_invoice" + SubscriptionTrialSettingsEndBehaviorMissingPaymentMethodPause SubscriptionTrialSettingsEndBehaviorMissingPaymentMethod = "pause" +) + +// Details about why this subscription was cancelled +type SubscriptionCancelCancellationDetailsParams struct { + // Additional comments about why the user canceled the subscription, if the subscription was canceled explicitly by the user. + Comment *string `form:"comment"` + // The customer submitted reason for why they canceled, if the subscription was canceled explicitly by the user. + Feedback *string `form:"feedback"` +} + +// Cancels a customer's subscription immediately. The customer won't be charged again for the subscription. After it's canceled, you can no longer update the subscription or its [metadata](https://docs.stripe.com/metadata). +// +// Any pending invoice items that you've created are still charged at the end of the period, unless manually [deleted](https://docs.stripe.com/api#delete_invoiceitem). If you've set the subscription to cancel at the end of the period, any pending prorations are also left in place and collected at the end of the period. But if the subscription is set to cancel immediately, pending prorations are removed if invoice_now and prorate are both set to true. +// +// By default, upon subscription cancellation, Stripe stops automatic collection of all finalized invoices for the customer. This is intended to prevent unexpected payment attempts after the customer has canceled a subscription. However, you can resume automatic collection of the invoices manually after subscription cancellation to have us proceed. Or, you could check for unpaid invoices before allowing the customer to cancel the subscription at all. +type SubscriptionCancelParams struct { + Params `form:"*"` + // Details about why this subscription was cancelled + CancellationDetails *SubscriptionCancelCancellationDetailsParams `form:"cancellation_details"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Will generate a final invoice that invoices for any un-invoiced metered usage and new/pending proration invoice items. Defaults to `false`. + InvoiceNow *bool `form:"invoice_now"` + // Will generate a proration invoice item that credits remaining unused time until the subscription period end. Defaults to `false`. + Prorate *bool `form:"prorate"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionCancelParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the subscription with the given ID. +type SubscriptionParams struct { + Params `form:"*"` + // A list of prices and quantities that will generate invoice items appended to the next invoice for this subscription. You may pass up to 20 items. + AddInvoiceItems []*SubscriptionAddInvoiceItemParams `form:"add_invoice_items"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + ApplicationFeePercent *float64 `form:"application_fee_percent"` + // Automatic tax settings for this subscription. We recommend you only include this parameter when the existing value is being changed. + AutomaticTax *SubscriptionAutomaticTaxParams `form:"automatic_tax"` + // A past timestamp to backdate the subscription's start date to. If set, the first invoice will contain line items for the timespan between the start date and the current time. Can be combined with trials and the billing cycle anchor. + BackdateStartDate *int64 `form:"backdate_start_date"` + // A future timestamp in UTC format to anchor the subscription's [billing cycle](https://stripe.com/docs/subscriptions/billing-cycle). The anchor is the reference point that aligns future billing cycle dates. It sets the day of week for `week` intervals, the day of month for `month` and `year` intervals, and the month of year for `year` intervals. + BillingCycleAnchor *int64 `form:"billing_cycle_anchor"` + // Mutually exclusive with billing_cycle_anchor and only valid with monthly and yearly price intervals. When provided, the billing_cycle_anchor is set to the next occurence of the day_of_month at the hour, minute, and second UTC. + BillingCycleAnchorConfig *SubscriptionBillingCycleAnchorConfigParams `form:"billing_cycle_anchor_config"` + BillingCycleAnchorNow *bool `form:"-"` // See custom AppendTo + BillingCycleAnchorUnchanged *bool `form:"-"` // See custom AppendTo + // Controls how prorations and invoices for subscriptions are calculated and orchestrated. + BillingMode *SubscriptionBillingModeParams `form:"billing_mode"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. When updating, pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionBillingThresholdsParams `form:"billing_thresholds"` + // A timestamp at which the subscription should cancel. If set to a date before the current period ends, this will cause a proration if prorations have been enabled using `proration_behavior`. If set during a future period, this will always cause a proration for that period. + CancelAt *int64 `form:"cancel_at"` + // Indicate whether this subscription should cancel at the end of the current period (`current_period_end`). Defaults to `false`. + CancelAtPeriodEnd *bool `form:"cancel_at_period_end"` + // Details about why this subscription was cancelled + CancellationDetails *SubscriptionCancellationDetailsParams `form:"cancellation_details"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically`. + CollectionMethod *string `form:"collection_method"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The identifier of the customer to subscribe. + Customer *string `form:"customer"` + // Number of days a customer has to pay invoices generated by this subscription. Valid only for subscriptions where `collection_method` is set to `send_invoice`. + DaysUntilDue *int64 `form:"days_until_due"` + // ID of the default payment method for the subscription. It must belong to the customer associated with the subscription. This takes precedence over `default_source`. If neither are set, invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + DefaultPaymentMethod *string `form:"default_payment_method"` + // ID of the default payment source for the subscription. It must belong to the customer associated with the subscription and be in a chargeable state. If `default_payment_method` is also set, `default_payment_method` will take precedence. If neither are set, invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + DefaultSource *string `form:"default_source"` + // The tax rates that will apply to any subscription item that does not have `tax_rates` set. Invoices created will have their `default_tax_rates` populated from the subscription. Pass an empty string to remove previously-defined tax rates. + DefaultTaxRates []*string `form:"default_tax_rates"` + // The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // The coupons to redeem into discounts for the subscription. If not specified or empty, inherits the discount from the subscription's customer. + Discounts []*SubscriptionDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // All invoices will be billed using the specified settings. + InvoiceSettings *SubscriptionInvoiceSettingsParams `form:"invoice_settings"` + // A list of up to 20 subscription items, each with an attached price. + Items []*SubscriptionItemsParams `form:"items"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Indicates if a customer is on or off-session while an invoice payment is attempted. Defaults to `false` (on-session). + OffSession *bool `form:"off_session"` + // The account on behalf of which to charge, for each of the subscription's invoices. + OnBehalfOf *string `form:"on_behalf_of"` + // If specified, payment collection for this subscription will be paused. Note that the subscription status will be unchanged and will not be updated to `paused`. Learn more about [pausing collection](https://stripe.com/docs/billing/subscriptions/pause-payment). + PauseCollection *SubscriptionPauseCollectionParams `form:"pause_collection"` + // Only applies to subscriptions with `collection_method=charge_automatically`. + // + // Use `allow_incomplete` to create Subscriptions with `status=incomplete` if the first invoice can't be paid. Creating Subscriptions with this status allows you to manage scenarios where additional customer actions are needed to pay a subscription's invoice. For example, SCA regulation may require 3DS authentication to complete payment. See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. This is the default behavior. + // + // Use `default_incomplete` to create Subscriptions with `status=incomplete` when the first invoice requires payment, otherwise start as active. Subscriptions transition to `status=active` when successfully confirming the PaymentIntent on the first invoice. This allows simpler management of scenarios where additional customer actions are needed to pay a subscription's invoice, such as failed payments, [SCA regulation](https://stripe.com/docs/billing/migration/strong-customer-authentication), or collecting a mandate for a bank debit payment method. If the PaymentIntent is not confirmed within 23 hours Subscriptions transition to `status=incomplete_expired`, which is a terminal state. + // + // Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's first invoice can't be paid. For example, if a payment method requires 3DS authentication due to SCA regulation and further customer action is needed, this parameter doesn't create a Subscription and returns an error instead. This was the default behavior for API versions prior to 2019-03-14. See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + // + // `pending_if_incomplete` is only used with updates and cannot be passed when creating a Subscription. + // + // Subscriptions with `collection_method=send_invoice` are automatically activated regardless of the first Invoice status. + PaymentBehavior *string `form:"payment_behavior"` + // Payment settings to pass to invoices created by the subscription. + PaymentSettings *SubscriptionPaymentSettingsParams `form:"payment_settings"` + // Specifies an interval for how often to bill for any pending invoice items. It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. + PendingInvoiceItemInterval *SubscriptionPendingInvoiceItemIntervalParams `form:"pending_invoice_item_interval"` + // Determines how to handle [prorations](https://stripe.com/docs/billing/subscriptions/prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. The default value is `create_prorations`. + ProrationBehavior *string `form:"proration_behavior"` + // If set, prorations will be calculated as though the subscription was updated at the given time. This can be used to apply exactly the same prorations that were previewed with the [create preview](https://stripe.com/docs/api/invoices/create_preview) endpoint. `proration_date` can also be used to implement custom proration logic, such as prorating by day instead of by second, by providing the time that you wish to use for proration calculations. + ProrationDate *int64 `form:"proration_date"` + // If specified, the funds from the subscription's invoices will be transferred to the destination and the ID of the resulting transfers will be found on the resulting charges. This will be unset if you POST an empty value. + TransferData *SubscriptionTransferDataParams `form:"transfer_data"` + // Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. This will always overwrite any trials that might apply via a subscribed plan. If set, `trial_end` will override the default trial period of the plan the customer is being subscribed to. The `billing_cycle_anchor` will be updated to the `trial_end` value. The special value `now` can be provided to end the customer's trial immediately. Can be at most two years from `billing_cycle_anchor`. + TrialEnd *int64 `form:"trial_end"` + TrialEndNow *bool `form:"-"` // See custom AppendTo + // Indicates if a plan's `trial_period_days` should be applied to the subscription. Setting `trial_end` per subscription is preferred, and this defaults to `false`. Setting this flag to `true` together with `trial_end` is not allowed. See [Using trial periods on subscriptions](https://stripe.com/docs/billing/subscriptions/trials) to learn more. + TrialFromPlan *bool `form:"trial_from_plan"` + // Integer representing the number of trial period days before the customer is charged for the first time. This will always overwrite any trials that might apply via a subscribed plan. See [Using trial periods on subscriptions](https://stripe.com/docs/billing/subscriptions/trials) to learn more. + TrialPeriodDays *int64 `form:"trial_period_days"` + // Settings related to subscription trials. + TrialSettings *SubscriptionTrialSettingsParams `form:"trial_settings"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// AppendTo implements custom encoding logic for SubscriptionParams. +func (p *SubscriptionParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.BillingCycleAnchorNow) { + body.Add(form.FormatKey(append(keyParts, "billing_cycle_anchor")), "now") + } + if BoolValue(p.BillingCycleAnchorUnchanged) { + body.Add(form.FormatKey(append(keyParts, "billing_cycle_anchor")), "unchanged") + } + if BoolValue(p.TrialEndNow) { + body.Add(form.FormatKey(append(keyParts, "trial_end")), "now") + } +} + +// The coupons to redeem into discounts for the item. +type SubscriptionAddInvoiceItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// A list of prices and quantities that will generate invoice items appended to the next invoice for this subscription. You may pass up to 20 items. +type SubscriptionAddInvoiceItemParams struct { + // The coupons to redeem into discounts for the item. + Discounts []*SubscriptionAddInvoiceItemDiscountParams `form:"discounts"` + // The ID of the price object. One of `price` or `price_data` is required. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *InvoiceItemPriceDataParams `form:"price_data"` + // Quantity for this item. Defaults to 1. + Quantity *int64 `form:"quantity"` + // The tax rates which apply to the item. When set, the `default_tax_rates` do not apply to this item. + TaxRates []*string `form:"tax_rates"` +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type SubscriptionAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Automatic tax settings for this subscription. We recommend you only include this parameter when the existing value is being changed. +type SubscriptionAutomaticTaxParams struct { + // Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *SubscriptionAutomaticTaxLiabilityParams `form:"liability"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. When updating, pass an empty string to remove previously-defined thresholds. +type SubscriptionBillingThresholdsParams struct { + // Monetary threshold that triggers the subscription to advance to a new billing period + AmountGTE *int64 `form:"amount_gte"` + // Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + ResetBillingCycleAnchor *bool `form:"reset_billing_cycle_anchor"` +} + +// Details about why this subscription was cancelled +type SubscriptionCancellationDetailsParams struct { + // Additional comments about why the user canceled the subscription, if the subscription was canceled explicitly by the user. + Comment *string `form:"comment"` + // The customer submitted reason for why they canceled, if the subscription was canceled explicitly by the user. + Feedback *string `form:"feedback"` +} + +// The coupons to redeem into discounts for the subscription. If not specified or empty, inherits the discount from the subscription's customer. +type SubscriptionDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type SubscriptionInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type SubscriptionInvoiceSettingsParams struct { + // The account tax IDs associated with the subscription. Will be set on invoices generated by the subscription. + AccountTaxIDs []*string `form:"account_tax_ids"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *SubscriptionInvoiceSettingsIssuerParams `form:"issuer"` +} + +// A list of up to 20 subscription items, each with an attached price. +type SubscriptionItemsParams struct { + Params `form:"*"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionItemBillingThresholdsParams `form:"billing_thresholds"` + // Delete all usage for a given subscription item. You must pass this when deleting a usage records subscription item. `clear_usage` has no effect if the plan has a billing meter attached. + ClearUsage *bool `form:"clear_usage"` + // A flag that, if set to `true`, will delete the specified item. + Deleted *bool `form:"deleted"` + // The coupons to redeem into discounts for the subscription item. + Discounts []*SubscriptionItemDiscountParams `form:"discounts"` + // Subscription item to update. + ID *string `form:"id"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Plan ID for this item, as a string. + Plan *string `form:"plan"` + // The ID of the price object. One of `price` or `price_data` is required. When changing a subscription item's price, `quantity` is set to 1 unless a `quantity` parameter is provided. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *SubscriptionItemPriceDataParams `form:"price_data"` + // Quantity for this item. + Quantity *int64 `form:"quantity"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionItemsParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// If specified, payment collection for this subscription will be paused. Note that the subscription status will be unchanged and will not be updated to `paused`. Learn more about [pausing collection](https://stripe.com/docs/billing/subscriptions/pause-payment). +type SubscriptionPauseCollectionParams struct { + // The payment collection behavior for this subscription while paused. One of `keep_as_draft`, `mark_uncollectible`, or `void`. + Behavior *string `form:"behavior"` + // The time after which the subscription will resume collecting payments. + ResumesAt *int64 `form:"resumes_at"` +} + +// Additional fields for Mandate creation +type SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsParams struct { + // Transaction type of the mandate. + TransactionType *string `form:"transaction_type"` +} + +// This sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. +type SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsParams `form:"mandate_options"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// This sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. +type SubscriptionPaymentSettingsPaymentMethodOptionsBancontactParams struct { + // Preferred language of the Bancontact authorization page that the customer is redirected to. + PreferredLanguage *string `form:"preferred_language"` +} + +// Configuration options for setting up an eMandate for cards issued in India. +type SubscriptionPaymentSettingsPaymentMethodOptionsCardMandateOptionsParams struct { + // Amount to be charged for future payments. + Amount *int64 `form:"amount"` + // One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + AmountType *string `form:"amount_type"` + // A description of the mandate or subscription that is meant to be displayed to the customer. + Description *string `form:"description"` +} + +// This sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. +type SubscriptionPaymentSettingsPaymentMethodOptionsCardParams struct { + // Configuration options for setting up an eMandate for cards issued in India. + MandateOptions *SubscriptionPaymentSettingsPaymentMethodOptionsCardMandateOptionsParams `form:"mandate_options"` + // Selected network to process this Subscription on. Depends on the available networks of the card attached to the Subscription. Can be only set confirm-time. + Network *string `form:"network"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure *string `form:"request_three_d_secure"` +} + +// Configuration for eu_bank_transfer funding type. +type SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country *string `form:"country"` +} + +// Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. +type SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams struct { + // Configuration for eu_bank_transfer funding type. + EUBankTransfer *SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams `form:"eu_bank_transfer"` + // The bank transfer type that can be used for funding. Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + Type *string `form:"type"` +} + +// This sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. +type SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceParams struct { + // Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + BankTransfer *SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams `form:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType *string `form:"funding_type"` +} + +// This sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. +type SubscriptionPaymentSettingsPaymentMethodOptionsKonbiniParams struct{} + +// This sub-hash contains details about the SEPA Direct Debit payment method options to pass to the invoice's PaymentIntent. +type SubscriptionPaymentSettingsPaymentMethodOptionsSEPADebitParams struct{} + +// Provide filters for the linked accounts that the customer can select for the payment method. +type SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams struct { + // The account subcategories to use to filter for selectable accounts. Valid subcategories are `checking` and `savings`. + AccountSubcategories []*string `form:"account_subcategories"` +} + +// Additional fields for Financial Connections Session creation +type SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsParams struct { + // Provide filters for the linked accounts that the customer can select for the payment method. + Filters *SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams `form:"filters"` + // The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` +} + +// This sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. +type SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountParams struct { + // Additional fields for Financial Connections Session creation + FinancialConnections *SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsParams `form:"financial_connections"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// Payment-method-specific configuration to provide to invoices created by the subscription. +type SubscriptionPaymentSettingsPaymentMethodOptionsParams struct { + // This sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. + ACSSDebit *SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitParams `form:"acss_debit"` + // This sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. + Bancontact *SubscriptionPaymentSettingsPaymentMethodOptionsBancontactParams `form:"bancontact"` + // This sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. + Card *SubscriptionPaymentSettingsPaymentMethodOptionsCardParams `form:"card"` + // This sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. + CustomerBalance *SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceParams `form:"customer_balance"` + // This sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. + Konbini *SubscriptionPaymentSettingsPaymentMethodOptionsKonbiniParams `form:"konbini"` + // This sub-hash contains details about the SEPA Direct Debit payment method options to pass to the invoice's PaymentIntent. + SEPADebit *SubscriptionPaymentSettingsPaymentMethodOptionsSEPADebitParams `form:"sepa_debit"` + // This sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. + USBankAccount *SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` +} + +// Payment settings to pass to invoices created by the subscription. +type SubscriptionPaymentSettingsParams struct { + // Payment-method-specific configuration to provide to invoices created by the subscription. + PaymentMethodOptions *SubscriptionPaymentSettingsPaymentMethodOptionsParams `form:"payment_method_options"` + // The list of payment method types (e.g. card) to provide to the invoice's PaymentIntent. If not set, Stripe attempts to automatically determine the types to use by looking at the invoice's default payment method, the subscription's default payment method, the customer's default payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). Should not be specified with payment_method_configuration + PaymentMethodTypes []*string `form:"payment_method_types"` + // Configure whether Stripe updates `subscription.default_payment_method` when payment succeeds. Defaults to `off` if unspecified. + SaveDefaultPaymentMethod *string `form:"save_default_payment_method"` +} + +// Specifies an interval for how often to bill for any pending invoice items. It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. +type SubscriptionPendingInvoiceItemIntervalParams struct { + // Specifies invoicing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between invoices. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// If specified, the funds from the subscription's invoices will be transferred to the destination and the ID of the resulting transfers will be found on the resulting charges. This will be unset if you POST an empty value. +type SubscriptionTransferDataParams struct { + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + AmountPercent *float64 `form:"amount_percent"` + // ID of an existing, connected Stripe account. + Destination *string `form:"destination"` +} + +// Defines how the subscription should behave when the user's free trial ends. +type SubscriptionTrialSettingsEndBehaviorParams struct { + // Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + MissingPaymentMethod *string `form:"missing_payment_method"` +} + +// Settings related to subscription trials. +type SubscriptionTrialSettingsParams struct { + // Defines how the subscription should behave when the user's free trial ends. + EndBehavior *SubscriptionTrialSettingsEndBehaviorParams `form:"end_behavior"` +} + +// Removes the currently applied discount on a subscription. +type SubscriptionDeleteDiscountParams struct { + Params `form:"*"` +} + +// Filter subscriptions by their automatic tax settings. +type SubscriptionListAutomaticTaxParams struct { + // Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + Enabled *bool `form:"enabled"` +} + +// By default, returns a list of subscriptions that have not been canceled. In order to list canceled subscriptions, specify status=canceled. +type SubscriptionListParams struct { + ListParams `form:"*"` + // Filter subscriptions by their automatic tax settings. + AutomaticTax *SubscriptionListAutomaticTaxParams `form:"automatic_tax"` + // The collection method of the subscriptions to retrieve. Either `charge_automatically` or `send_invoice`. + CollectionMethod *string `form:"collection_method"` + // Only return subscriptions that were created during the given date interval. + Created *int64 `form:"created"` + // Only return subscriptions that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Only return subscriptions whose current_period_end falls within the given date interval. + CurrentPeriodEnd *int64 `form:"current_period_end"` + // Only return subscriptions whose current_period_end falls within the given date interval. + CurrentPeriodEndRange *RangeQueryParams `form:"current_period_end"` + // Only return subscriptions whose current_period_start falls within the given date interval. + CurrentPeriodStart *int64 `form:"current_period_start"` + // Only return subscriptions whose current_period_start falls within the given date interval. + CurrentPeriodStartRange *RangeQueryParams `form:"current_period_start"` + // The ID of the customer whose subscriptions will be retrieved. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The ID of the plan whose subscriptions will be retrieved. + Plan *string `form:"plan"` + // Filter for subscriptions that contain this recurring price ID. + Price *string `form:"price"` + // The status of the subscriptions to retrieve. Passing in a value of `canceled` will return all canceled subscriptions, including those belonging to deleted customers. Pass `ended` to find subscriptions that are canceled and subscriptions that are expired due to [incomplete payment](https://stripe.com/docs/billing/subscriptions/overview#subscription-statuses). Passing in a value of `all` will return subscriptions of all statuses. If no value is supplied, all subscriptions that have not been canceled are returned. + Status *string `form:"status"` + // Filter for subscriptions that are associated with the specified test clock. The response will not include subscriptions with test clocks if this and the customer parameter is not set. + TestClock *string `form:"test_clock"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Mutually exclusive with billing_cycle_anchor and only valid with monthly and yearly price intervals. When provided, the billing_cycle_anchor is set to the next occurence of the day_of_month at the hour, minute, and second UTC. +type SubscriptionBillingCycleAnchorConfigParams struct { + // The day of the month the billing_cycle_anchor should be. Ranges from 1 to 31. + DayOfMonth *int64 `form:"day_of_month"` + // The hour of the day the billing_cycle_anchor should be. Ranges from 0 to 23. + Hour *int64 `form:"hour"` + // The minute of the hour the billing_cycle_anchor should be. Ranges from 0 to 59. + Minute *int64 `form:"minute"` + // The month to start full cycle billing periods. Ranges from 1 to 12. + Month *int64 `form:"month"` + // The second of the minute the billing_cycle_anchor should be. Ranges from 0 to 59. + Second *int64 `form:"second"` +} + +// Controls how prorations and invoices for subscriptions are calculated and orchestrated. +type SubscriptionBillingModeParams struct { + Type *string `form:"type"` +} + +// Search for subscriptions you've previously created using Stripe's [Search Query Language](https://docs.stripe.com/docs/search#search-query-language). +// Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating +// conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up +// to an hour behind during outages. Search functionality is not available to merchants in India. +type SubscriptionSearchParams struct { + SearchParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + Page *string `form:"page"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionSearchParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Controls how prorations and invoices for subscriptions are calculated and orchestrated. +type SubscriptionMigrateBillingModeParams struct { + Type *string `form:"type"` +} + +// Upgrade the billing_mode of an existing subscription. +type SubscriptionMigrateParams struct { + Params `form:"*"` + // Controls how prorations and invoices for subscriptions are calculated and orchestrated. + BillingMode *SubscriptionMigrateBillingModeParams `form:"billing_mode"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionMigrateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Initiates resumption of a paused subscription, optionally resetting the billing cycle anchor and creating prorations. If a resumption invoice is generated, it must be paid or marked uncollectible before the subscription will be unpaused. If payment succeeds the subscription will become active, and if payment fails the subscription will be past_due. The resumption invoice will void automatically if not paid by the expiration date. +type SubscriptionResumeParams struct { + Params `form:"*"` + // The billing cycle anchor that applies when the subscription is resumed. Either `now` or `unchanged`. The default is `now`. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + BillingCycleAnchor *string `form:"billing_cycle_anchor"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Determines how to handle [prorations](https://stripe.com/docs/billing/subscriptions/prorations) resulting from the `billing_cycle_anchor` being `unchanged`. When the `billing_cycle_anchor` is set to `now` (default value), no prorations are generated. If no value is passed, the default is `create_prorations`. + ProrationBehavior *string `form:"proration_behavior"` + // If set, prorations will be calculated as though the subscription was resumed at the given time. This can be used to apply exactly the same prorations that were previewed with the [create preview](https://stripe.com/docs/api/invoices/create_preview) endpoint. + ProrationDate *int64 `form:"proration_date"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionResumeParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the subscription with the given ID. +type SubscriptionRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The coupons to redeem into discounts for the item. +type SubscriptionUpdateAddInvoiceItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// A list of prices and quantities that will generate invoice items appended to the next invoice for this subscription. You may pass up to 20 items. +type SubscriptionUpdateAddInvoiceItemParams struct { + // The coupons to redeem into discounts for the item. + Discounts []*SubscriptionUpdateAddInvoiceItemDiscountParams `form:"discounts"` + // The ID of the price object. One of `price` or `price_data` is required. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *InvoiceItemPriceDataParams `form:"price_data"` + // Quantity for this item. Defaults to 1. + Quantity *int64 `form:"quantity"` + // The tax rates which apply to the item. When set, the `default_tax_rates` do not apply to this item. + TaxRates []*string `form:"tax_rates"` +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type SubscriptionUpdateAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Automatic tax settings for this subscription. We recommend you only include this parameter when the existing value is being changed. +type SubscriptionUpdateAutomaticTaxParams struct { + // Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *SubscriptionUpdateAutomaticTaxLiabilityParams `form:"liability"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. When updating, pass an empty string to remove previously-defined thresholds. +type SubscriptionUpdateBillingThresholdsParams struct { + // Monetary threshold that triggers the subscription to advance to a new billing period + AmountGTE *int64 `form:"amount_gte"` + // Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + ResetBillingCycleAnchor *bool `form:"reset_billing_cycle_anchor"` +} + +// Details about why this subscription was cancelled +type SubscriptionUpdateCancellationDetailsParams struct { + // Additional comments about why the user canceled the subscription, if the subscription was canceled explicitly by the user. + Comment *string `form:"comment"` + // The customer submitted reason for why they canceled, if the subscription was canceled explicitly by the user. + Feedback *string `form:"feedback"` +} + +// The coupons to redeem into discounts for the subscription. If not specified or empty, inherits the discount from the subscription's customer. +type SubscriptionUpdateDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type SubscriptionUpdateInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type SubscriptionUpdateInvoiceSettingsParams struct { + // The account tax IDs associated with the subscription. Will be set on invoices generated by the subscription. + AccountTaxIDs []*string `form:"account_tax_ids"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *SubscriptionUpdateInvoiceSettingsIssuerParams `form:"issuer"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type SubscriptionUpdateItemBillingThresholdsParams struct { + // Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + UsageGTE *int64 `form:"usage_gte"` +} + +// The coupons to redeem into discounts for the subscription item. +type SubscriptionUpdateItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The recurring components of a price such as `interval` and `interval_count`. +type SubscriptionUpdateItemPriceDataRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. +type SubscriptionUpdateItemPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // The recurring components of a price such as `interval` and `interval_count`. + Recurring *SubscriptionUpdateItemPriceDataRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// A list of up to 20 subscription items, each with an attached price. +type SubscriptionUpdateItemParams struct { + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionUpdateItemBillingThresholdsParams `form:"billing_thresholds"` + // Delete all usage for a given subscription item. You must pass this when deleting a usage records subscription item. `clear_usage` has no effect if the plan has a billing meter attached. + ClearUsage *bool `form:"clear_usage"` + // A flag that, if set to `true`, will delete the specified item. + Deleted *bool `form:"deleted"` + // The coupons to redeem into discounts for the subscription item. + Discounts []*SubscriptionUpdateItemDiscountParams `form:"discounts"` + // Subscription item to update. + ID *string `form:"id"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Plan ID for this item, as a string. + Plan *string `form:"plan"` + // The ID of the price object. One of `price` or `price_data` is required. When changing a subscription item's price, `quantity` is set to 1 unless a `quantity` parameter is provided. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *SubscriptionUpdateItemPriceDataParams `form:"price_data"` + // Quantity for this item. + Quantity *int64 `form:"quantity"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionUpdateItemParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// If specified, payment collection for this subscription will be paused. Note that the subscription status will be unchanged and will not be updated to `paused`. Learn more about [pausing collection](https://stripe.com/docs/billing/subscriptions/pause-payment). +type SubscriptionUpdatePauseCollectionParams struct { + // The payment collection behavior for this subscription while paused. One of `keep_as_draft`, `mark_uncollectible`, or `void`. + Behavior *string `form:"behavior"` + // The time after which the subscription will resume collecting payments. + ResumesAt *int64 `form:"resumes_at"` +} + +// Additional fields for Mandate creation +type SubscriptionUpdatePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsParams struct { + // Transaction type of the mandate. + TransactionType *string `form:"transaction_type"` +} + +// This sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. +type SubscriptionUpdatePaymentSettingsPaymentMethodOptionsACSSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *SubscriptionUpdatePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsParams `form:"mandate_options"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// This sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. +type SubscriptionUpdatePaymentSettingsPaymentMethodOptionsBancontactParams struct { + // Preferred language of the Bancontact authorization page that the customer is redirected to. + PreferredLanguage *string `form:"preferred_language"` +} + +// Configuration options for setting up an eMandate for cards issued in India. +type SubscriptionUpdatePaymentSettingsPaymentMethodOptionsCardMandateOptionsParams struct { + // Amount to be charged for future payments. + Amount *int64 `form:"amount"` + // One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + AmountType *string `form:"amount_type"` + // A description of the mandate or subscription that is meant to be displayed to the customer. + Description *string `form:"description"` +} + +// This sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. +type SubscriptionUpdatePaymentSettingsPaymentMethodOptionsCardParams struct { + // Configuration options for setting up an eMandate for cards issued in India. + MandateOptions *SubscriptionUpdatePaymentSettingsPaymentMethodOptionsCardMandateOptionsParams `form:"mandate_options"` + // Selected network to process this Subscription on. Depends on the available networks of the card attached to the Subscription. Can be only set confirm-time. + Network *string `form:"network"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure *string `form:"request_three_d_secure"` +} + +// Configuration for eu_bank_transfer funding type. +type SubscriptionUpdatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country *string `form:"country"` +} + +// Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. +type SubscriptionUpdatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams struct { + // Configuration for eu_bank_transfer funding type. + EUBankTransfer *SubscriptionUpdatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams `form:"eu_bank_transfer"` + // The bank transfer type that can be used for funding. Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + Type *string `form:"type"` +} + +// This sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. +type SubscriptionUpdatePaymentSettingsPaymentMethodOptionsCustomerBalanceParams struct { + // Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + BankTransfer *SubscriptionUpdatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams `form:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType *string `form:"funding_type"` +} + +// This sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. +type SubscriptionUpdatePaymentSettingsPaymentMethodOptionsKonbiniParams struct{} + +// This sub-hash contains details about the SEPA Direct Debit payment method options to pass to the invoice's PaymentIntent. +type SubscriptionUpdatePaymentSettingsPaymentMethodOptionsSEPADebitParams struct{} + +// Provide filters for the linked accounts that the customer can select for the payment method. +type SubscriptionUpdatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams struct { + // The account subcategories to use to filter for selectable accounts. Valid subcategories are `checking` and `savings`. + AccountSubcategories []*string `form:"account_subcategories"` +} + +// Additional fields for Financial Connections Session creation +type SubscriptionUpdatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsParams struct { + // Provide filters for the linked accounts that the customer can select for the payment method. + Filters *SubscriptionUpdatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams `form:"filters"` + // The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` +} + +// This sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. +type SubscriptionUpdatePaymentSettingsPaymentMethodOptionsUSBankAccountParams struct { + // Additional fields for Financial Connections Session creation + FinancialConnections *SubscriptionUpdatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsParams `form:"financial_connections"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// Payment-method-specific configuration to provide to invoices created by the subscription. +type SubscriptionUpdatePaymentSettingsPaymentMethodOptionsParams struct { + // This sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. + ACSSDebit *SubscriptionUpdatePaymentSettingsPaymentMethodOptionsACSSDebitParams `form:"acss_debit"` + // This sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. + Bancontact *SubscriptionUpdatePaymentSettingsPaymentMethodOptionsBancontactParams `form:"bancontact"` + // This sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. + Card *SubscriptionUpdatePaymentSettingsPaymentMethodOptionsCardParams `form:"card"` + // This sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. + CustomerBalance *SubscriptionUpdatePaymentSettingsPaymentMethodOptionsCustomerBalanceParams `form:"customer_balance"` + // This sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. + Konbini *SubscriptionUpdatePaymentSettingsPaymentMethodOptionsKonbiniParams `form:"konbini"` + // This sub-hash contains details about the SEPA Direct Debit payment method options to pass to the invoice's PaymentIntent. + SEPADebit *SubscriptionUpdatePaymentSettingsPaymentMethodOptionsSEPADebitParams `form:"sepa_debit"` + // This sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. + USBankAccount *SubscriptionUpdatePaymentSettingsPaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` +} + +// Payment settings to pass to invoices created by the subscription. +type SubscriptionUpdatePaymentSettingsParams struct { + // Payment-method-specific configuration to provide to invoices created by the subscription. + PaymentMethodOptions *SubscriptionUpdatePaymentSettingsPaymentMethodOptionsParams `form:"payment_method_options"` + // The list of payment method types (e.g. card) to provide to the invoice's PaymentIntent. If not set, Stripe attempts to automatically determine the types to use by looking at the invoice's default payment method, the subscription's default payment method, the customer's default payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). Should not be specified with payment_method_configuration + PaymentMethodTypes []*string `form:"payment_method_types"` + // Configure whether Stripe updates `subscription.default_payment_method` when payment succeeds. Defaults to `off` if unspecified. + SaveDefaultPaymentMethod *string `form:"save_default_payment_method"` +} + +// Specifies an interval for how often to bill for any pending invoice items. It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. +type SubscriptionUpdatePendingInvoiceItemIntervalParams struct { + // Specifies invoicing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between invoices. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// If specified, the funds from the subscription's invoices will be transferred to the destination and the ID of the resulting transfers will be found on the resulting charges. This will be unset if you POST an empty value. +type SubscriptionUpdateTransferDataParams struct { + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + AmountPercent *float64 `form:"amount_percent"` + // ID of an existing, connected Stripe account. + Destination *string `form:"destination"` +} + +// Defines how the subscription should behave when the user's free trial ends. +type SubscriptionUpdateTrialSettingsEndBehaviorParams struct { + // Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + MissingPaymentMethod *string `form:"missing_payment_method"` +} + +// Settings related to subscription trials. +type SubscriptionUpdateTrialSettingsParams struct { + // Defines how the subscription should behave when the user's free trial ends. + EndBehavior *SubscriptionUpdateTrialSettingsEndBehaviorParams `form:"end_behavior"` +} + +// Updates an existing subscription to match the specified parameters. +// When changing prices or quantities, we optionally prorate the price we charge next month to make up for any price changes. +// To preview how the proration is calculated, use the [create preview](https://docs.stripe.com/docs/api/invoices/create_preview) endpoint. +// +// By default, we prorate subscription changes. For example, if a customer signs up on May 1 for a 100 price, they'll be billed 100 immediately. If on May 15 they switch to a 200 price, then on June 1 they'll be billed 250 (200 for a renewal of her subscription, plus a 50 prorating adjustment for half of the previous month's 100 difference). Similarly, a downgrade generates a credit that is applied to the next invoice. We also prorate when you make quantity changes. +// +// Switching prices does not normally change the billing date or generate an immediate charge unless: +// +// The billing interval is changed (for example, from monthly to yearly). +// The subscription moves from free to paid. +// A trial starts or ends. +// +// In these cases, we apply a credit for the unused time on the previous price, immediately charge the customer using the new price, and reset the billing date. Learn about how [Stripe immediately attempts payment for subscription changes](https://docs.stripe.com/docs/billing/subscriptions/upgrade-downgrade#immediate-payment). +// +// If you want to charge for an upgrade immediately, pass proration_behavior as always_invoice to create prorations, automatically invoice the customer for those proration adjustments, and attempt to collect payment. If you pass create_prorations, the prorations are created but not automatically invoiced. If you want to bill the customer for the prorations before the subscription's renewal date, you need to manually [invoice the customer](https://docs.stripe.com/docs/api/invoices/create). +// +// If you don't want to prorate, set the proration_behavior option to none. With this option, the customer is billed 100 on May 1 and 200 on June 1. Similarly, if you set proration_behavior to none when switching between different billing intervals (for example, from monthly to yearly), we don't generate any credits for the old subscription's unused time. We still reset the billing date and bill immediately for the new subscription. +// +// Updating the quantity on a subscription many times in an hour may result in [rate limiting. If you need to bill for a frequently changing quantity, consider integrating usage-based billing](https://docs.stripe.com/docs/rate-limits) instead. +type SubscriptionUpdateParams struct { + Params `form:"*"` + // A list of prices and quantities that will generate invoice items appended to the next invoice for this subscription. You may pass up to 20 items. + AddInvoiceItems []*SubscriptionUpdateAddInvoiceItemParams `form:"add_invoice_items"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + ApplicationFeePercent *float64 `form:"application_fee_percent"` + // Automatic tax settings for this subscription. We recommend you only include this parameter when the existing value is being changed. + AutomaticTax *SubscriptionUpdateAutomaticTaxParams `form:"automatic_tax"` + // Either `now` or `unchanged`. Setting the value to `now` resets the subscription's billing cycle anchor to the current time (in UTC). For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + BillingCycleAnchor *int64 `form:"billing_cycle_anchor"` + BillingCycleAnchorNow *bool `form:"-"` // See custom AppendTo + BillingCycleAnchorUnchanged *bool `form:"-"` // See custom AppendTo + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. When updating, pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionUpdateBillingThresholdsParams `form:"billing_thresholds"` + // A timestamp at which the subscription should cancel. If set to a date before the current period ends, this will cause a proration if prorations have been enabled using `proration_behavior`. If set during a future period, this will always cause a proration for that period. + CancelAt *int64 `form:"cancel_at"` + // Indicate whether this subscription should cancel at the end of the current period (`current_period_end`). Defaults to `false`. + CancelAtPeriodEnd *bool `form:"cancel_at_period_end"` + // Details about why this subscription was cancelled + CancellationDetails *SubscriptionUpdateCancellationDetailsParams `form:"cancellation_details"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically`. + CollectionMethod *string `form:"collection_method"` + // Number of days a customer has to pay invoices generated by this subscription. Valid only for subscriptions where `collection_method` is set to `send_invoice`. + DaysUntilDue *int64 `form:"days_until_due"` + // ID of the default payment method for the subscription. It must belong to the customer associated with the subscription. This takes precedence over `default_source`. If neither are set, invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + DefaultPaymentMethod *string `form:"default_payment_method"` + // ID of the default payment source for the subscription. It must belong to the customer associated with the subscription and be in a chargeable state. If `default_payment_method` is also set, `default_payment_method` will take precedence. If neither are set, invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + DefaultSource *string `form:"default_source"` + // The tax rates that will apply to any subscription item that does not have `tax_rates` set. Invoices created will have their `default_tax_rates` populated from the subscription. Pass an empty string to remove previously-defined tax rates. + DefaultTaxRates []*string `form:"default_tax_rates"` + // The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // The coupons to redeem into discounts for the subscription. If not specified or empty, inherits the discount from the subscription's customer. + Discounts []*SubscriptionUpdateDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // All invoices will be billed using the specified settings. + InvoiceSettings *SubscriptionUpdateInvoiceSettingsParams `form:"invoice_settings"` + // A list of up to 20 subscription items, each with an attached price. + Items []*SubscriptionUpdateItemParams `form:"items"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Indicates if a customer is on or off-session while an invoice payment is attempted. Defaults to `false` (on-session). + OffSession *bool `form:"off_session"` + // The account on behalf of which to charge, for each of the subscription's invoices. + OnBehalfOf *string `form:"on_behalf_of"` + // If specified, payment collection for this subscription will be paused. Note that the subscription status will be unchanged and will not be updated to `paused`. Learn more about [pausing collection](https://stripe.com/docs/billing/subscriptions/pause-payment). + PauseCollection *SubscriptionUpdatePauseCollectionParams `form:"pause_collection"` + // Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. For example, SCA regulation may require 3DS authentication to complete payment. See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. This is the default behavior. + // + // Use `default_incomplete` to transition the subscription to `status=past_due` when payment is required and await explicit confirmation of the invoice's payment intent. This allows simpler management of scenarios where additional user actions are needed to pay a subscription's invoice. Such as failed payments, [SCA regulation](https://stripe.com/docs/billing/migration/strong-customer-authentication), or collecting a mandate for a bank debit payment method. + // + // Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). + // + // Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's invoice cannot be paid. For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not update the subscription and returns an error instead. This was the default behavior for API versions prior to 2019-03-14. See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + PaymentBehavior *string `form:"payment_behavior"` + // Payment settings to pass to invoices created by the subscription. + PaymentSettings *SubscriptionUpdatePaymentSettingsParams `form:"payment_settings"` + // Specifies an interval for how often to bill for any pending invoice items. It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. + PendingInvoiceItemInterval *SubscriptionUpdatePendingInvoiceItemIntervalParams `form:"pending_invoice_item_interval"` + // Determines how to handle [prorations](https://stripe.com/docs/billing/subscriptions/prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. The default value is `create_prorations`. + ProrationBehavior *string `form:"proration_behavior"` + // If set, prorations will be calculated as though the subscription was updated at the given time. This can be used to apply exactly the same prorations that were previewed with the [create preview](https://stripe.com/docs/api/invoices/create_preview) endpoint. `proration_date` can also be used to implement custom proration logic, such as prorating by day instead of by second, by providing the time that you wish to use for proration calculations. + ProrationDate *int64 `form:"proration_date"` + // If specified, the funds from the subscription's invoices will be transferred to the destination and the ID of the resulting transfers will be found on the resulting charges. This will be unset if you POST an empty value. + TransferData *SubscriptionUpdateTransferDataParams `form:"transfer_data"` + // Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. This will always overwrite any trials that might apply via a subscribed plan. If set, `trial_end` will override the default trial period of the plan the customer is being subscribed to. The `billing_cycle_anchor` will be updated to the `trial_end` value. The special value `now` can be provided to end the customer's trial immediately. Can be at most two years from `billing_cycle_anchor`. + TrialEnd *int64 `form:"trial_end"` + TrialEndNow *bool `form:"-"` // See custom AppendTo + // Indicates if a plan's `trial_period_days` should be applied to the subscription. Setting `trial_end` per subscription is preferred, and this defaults to `false`. Setting this flag to `true` together with `trial_end` is not allowed. See [Using trial periods on subscriptions](https://stripe.com/docs/billing/subscriptions/trials) to learn more. + TrialFromPlan *bool `form:"trial_from_plan"` + // Settings related to subscription trials. + TrialSettings *SubscriptionUpdateTrialSettingsParams `form:"trial_settings"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// AppendTo implements custom encoding logic for SubscriptionUpdateParams. +func (p *SubscriptionUpdateParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.BillingCycleAnchorNow) { + body.Add(form.FormatKey(append(keyParts, "billing_cycle_anchor")), "now") + } + if BoolValue(p.BillingCycleAnchorUnchanged) { + body.Add(form.FormatKey(append(keyParts, "billing_cycle_anchor")), "unchanged") + } + if BoolValue(p.TrialEndNow) { + body.Add(form.FormatKey(append(keyParts, "trial_end")), "now") + } +} + +// The coupons to redeem into discounts for the item. +type SubscriptionCreateAddInvoiceItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// A list of prices and quantities that will generate invoice items appended to the next invoice for this subscription. You may pass up to 20 items. +type SubscriptionCreateAddInvoiceItemParams struct { + // The coupons to redeem into discounts for the item. + Discounts []*SubscriptionCreateAddInvoiceItemDiscountParams `form:"discounts"` + // The ID of the price object. One of `price` or `price_data` is required. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *InvoiceItemPriceDataParams `form:"price_data"` + // Quantity for this item. Defaults to 1. + Quantity *int64 `form:"quantity"` + // The tax rates which apply to the item. When set, the `default_tax_rates` do not apply to this item. + TaxRates []*string `form:"tax_rates"` +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type SubscriptionCreateAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Automatic tax settings for this subscription. +type SubscriptionCreateAutomaticTaxParams struct { + // Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *SubscriptionCreateAutomaticTaxLiabilityParams `form:"liability"` +} + +// Mutually exclusive with billing_cycle_anchor and only valid with monthly and yearly price intervals. When provided, the billing_cycle_anchor is set to the next occurence of the day_of_month at the hour, minute, and second UTC. +type SubscriptionCreateBillingCycleAnchorConfigParams struct { + // The day of the month the billing_cycle_anchor should be. Ranges from 1 to 31. + DayOfMonth *int64 `form:"day_of_month"` + // The hour of the day the billing_cycle_anchor should be. Ranges from 0 to 23. + Hour *int64 `form:"hour"` + // The minute of the hour the billing_cycle_anchor should be. Ranges from 0 to 59. + Minute *int64 `form:"minute"` + // The month to start full cycle billing periods. Ranges from 1 to 12. + Month *int64 `form:"month"` + // The second of the minute the billing_cycle_anchor should be. Ranges from 0 to 59. + Second *int64 `form:"second"` +} + +// Controls how prorations and invoices for subscriptions are calculated and orchestrated. +type SubscriptionCreateBillingModeParams struct { + Type *string `form:"type"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. When updating, pass an empty string to remove previously-defined thresholds. +type SubscriptionCreateBillingThresholdsParams struct { + // Monetary threshold that triggers the subscription to advance to a new billing period + AmountGTE *int64 `form:"amount_gte"` + // Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + ResetBillingCycleAnchor *bool `form:"reset_billing_cycle_anchor"` +} + +// The coupons to redeem into discounts for the subscription. If not specified or empty, inherits the discount from the subscription's customer. +type SubscriptionCreateDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type SubscriptionCreateInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type SubscriptionCreateInvoiceSettingsParams struct { + // The account tax IDs associated with the subscription. Will be set on invoices generated by the subscription. + AccountTaxIDs []*string `form:"account_tax_ids"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *SubscriptionCreateInvoiceSettingsIssuerParams `form:"issuer"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type SubscriptionCreateItemBillingThresholdsParams struct { + // Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + UsageGTE *int64 `form:"usage_gte"` +} + +// The coupons to redeem into discounts for the subscription item. +type SubscriptionCreateItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The recurring components of a price such as `interval` and `interval_count`. +type SubscriptionCreateItemPriceDataRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. +type SubscriptionCreateItemPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // The recurring components of a price such as `interval` and `interval_count`. + Recurring *SubscriptionCreateItemPriceDataRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// A list of up to 20 subscription items, each with an attached price. +type SubscriptionCreateItemParams struct { + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionCreateItemBillingThresholdsParams `form:"billing_thresholds"` + // The coupons to redeem into discounts for the subscription item. + Discounts []*SubscriptionCreateItemDiscountParams `form:"discounts"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Plan ID for this item, as a string. + Plan *string `form:"plan"` + // The ID of the price object. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + PriceData *SubscriptionCreateItemPriceDataParams `form:"price_data"` + // Quantity for this item. + Quantity *int64 `form:"quantity"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionCreateItemParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Additional fields for Mandate creation +type SubscriptionCreatePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsParams struct { + // Transaction type of the mandate. + TransactionType *string `form:"transaction_type"` +} + +// This sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. +type SubscriptionCreatePaymentSettingsPaymentMethodOptionsACSSDebitParams struct { + // Additional fields for Mandate creation + MandateOptions *SubscriptionCreatePaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsParams `form:"mandate_options"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// This sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. +type SubscriptionCreatePaymentSettingsPaymentMethodOptionsBancontactParams struct { + // Preferred language of the Bancontact authorization page that the customer is redirected to. + PreferredLanguage *string `form:"preferred_language"` +} + +// Configuration options for setting up an eMandate for cards issued in India. +type SubscriptionCreatePaymentSettingsPaymentMethodOptionsCardMandateOptionsParams struct { + // Amount to be charged for future payments. + Amount *int64 `form:"amount"` + // One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + AmountType *string `form:"amount_type"` + // A description of the mandate or subscription that is meant to be displayed to the customer. + Description *string `form:"description"` +} + +// This sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. +type SubscriptionCreatePaymentSettingsPaymentMethodOptionsCardParams struct { + // Configuration options for setting up an eMandate for cards issued in India. + MandateOptions *SubscriptionCreatePaymentSettingsPaymentMethodOptionsCardMandateOptionsParams `form:"mandate_options"` + // Selected network to process this Subscription on. Depends on the available networks of the card attached to the Subscription. Can be only set confirm-time. + Network *string `form:"network"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure *string `form:"request_three_d_secure"` +} + +// Configuration for eu_bank_transfer funding type. +type SubscriptionCreatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country *string `form:"country"` +} + +// Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. +type SubscriptionCreatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams struct { + // Configuration for eu_bank_transfer funding type. + EUBankTransfer *SubscriptionCreatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransferParams `form:"eu_bank_transfer"` + // The bank transfer type that can be used for funding. Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + Type *string `form:"type"` +} + +// This sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. +type SubscriptionCreatePaymentSettingsPaymentMethodOptionsCustomerBalanceParams struct { + // Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + BankTransfer *SubscriptionCreatePaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferParams `form:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType *string `form:"funding_type"` +} + +// This sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. +type SubscriptionCreatePaymentSettingsPaymentMethodOptionsKonbiniParams struct{} + +// This sub-hash contains details about the SEPA Direct Debit payment method options to pass to the invoice's PaymentIntent. +type SubscriptionCreatePaymentSettingsPaymentMethodOptionsSEPADebitParams struct{} + +// Provide filters for the linked accounts that the customer can select for the payment method. +type SubscriptionCreatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams struct { + // The account subcategories to use to filter for selectable accounts. Valid subcategories are `checking` and `savings`. + AccountSubcategories []*string `form:"account_subcategories"` +} + +// Additional fields for Financial Connections Session creation +type SubscriptionCreatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsParams struct { + // Provide filters for the linked accounts that the customer can select for the payment method. + Filters *SubscriptionCreatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersParams `form:"filters"` + // The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + Permissions []*string `form:"permissions"` + // List of data features that you would like to retrieve upon account creation. + Prefetch []*string `form:"prefetch"` +} + +// This sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. +type SubscriptionCreatePaymentSettingsPaymentMethodOptionsUSBankAccountParams struct { + // Additional fields for Financial Connections Session creation + FinancialConnections *SubscriptionCreatePaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsParams `form:"financial_connections"` + // Verification method for the intent + VerificationMethod *string `form:"verification_method"` +} + +// Payment-method-specific configuration to provide to invoices created by the subscription. +type SubscriptionCreatePaymentSettingsPaymentMethodOptionsParams struct { + // This sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. + ACSSDebit *SubscriptionCreatePaymentSettingsPaymentMethodOptionsACSSDebitParams `form:"acss_debit"` + // This sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. + Bancontact *SubscriptionCreatePaymentSettingsPaymentMethodOptionsBancontactParams `form:"bancontact"` + // This sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. + Card *SubscriptionCreatePaymentSettingsPaymentMethodOptionsCardParams `form:"card"` + // This sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. + CustomerBalance *SubscriptionCreatePaymentSettingsPaymentMethodOptionsCustomerBalanceParams `form:"customer_balance"` + // This sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. + Konbini *SubscriptionCreatePaymentSettingsPaymentMethodOptionsKonbiniParams `form:"konbini"` + // This sub-hash contains details about the SEPA Direct Debit payment method options to pass to the invoice's PaymentIntent. + SEPADebit *SubscriptionCreatePaymentSettingsPaymentMethodOptionsSEPADebitParams `form:"sepa_debit"` + // This sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. + USBankAccount *SubscriptionCreatePaymentSettingsPaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` +} + +// Payment settings to pass to invoices created by the subscription. +type SubscriptionCreatePaymentSettingsParams struct { + // Payment-method-specific configuration to provide to invoices created by the subscription. + PaymentMethodOptions *SubscriptionCreatePaymentSettingsPaymentMethodOptionsParams `form:"payment_method_options"` + // The list of payment method types (e.g. card) to provide to the invoice's PaymentIntent. If not set, Stripe attempts to automatically determine the types to use by looking at the invoice's default payment method, the subscription's default payment method, the customer's default payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). Should not be specified with payment_method_configuration + PaymentMethodTypes []*string `form:"payment_method_types"` + // Configure whether Stripe updates `subscription.default_payment_method` when payment succeeds. Defaults to `off` if unspecified. + SaveDefaultPaymentMethod *string `form:"save_default_payment_method"` +} + +// Specifies an interval for how often to bill for any pending invoice items. It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. +type SubscriptionCreatePendingInvoiceItemIntervalParams struct { + // Specifies invoicing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between invoices. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// If specified, the funds from the subscription's invoices will be transferred to the destination and the ID of the resulting transfers will be found on the resulting charges. +type SubscriptionCreateTransferDataParams struct { + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + AmountPercent *float64 `form:"amount_percent"` + // ID of an existing, connected Stripe account. + Destination *string `form:"destination"` +} + +// Defines how the subscription should behave when the user's free trial ends. +type SubscriptionCreateTrialSettingsEndBehaviorParams struct { + // Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + MissingPaymentMethod *string `form:"missing_payment_method"` +} + +// Settings related to subscription trials. +type SubscriptionCreateTrialSettingsParams struct { + // Defines how the subscription should behave when the user's free trial ends. + EndBehavior *SubscriptionCreateTrialSettingsEndBehaviorParams `form:"end_behavior"` +} + +// Creates a new subscription on an existing customer. Each customer can have up to 500 active or scheduled subscriptions. +// +// When you create a subscription with collection_method=charge_automatically, the first invoice is finalized as part of the request. +// The payment_behavior parameter determines the exact behavior of the initial payment. +// +// To start subscriptions where the first invoice always begins in a draft status, use [subscription schedules](https://docs.stripe.com/docs/billing/subscriptions/subscription-schedules#managing) instead. +// Schedules provide the flexibility to model more complex billing configurations that change over time. +type SubscriptionCreateParams struct { + Params `form:"*"` + // A list of prices and quantities that will generate invoice items appended to the next invoice for this subscription. You may pass up to 20 items. + AddInvoiceItems []*SubscriptionCreateAddInvoiceItemParams `form:"add_invoice_items"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + ApplicationFeePercent *float64 `form:"application_fee_percent"` + // Automatic tax settings for this subscription. + AutomaticTax *SubscriptionCreateAutomaticTaxParams `form:"automatic_tax"` + // A past timestamp to backdate the subscription's start date to. If set, the first invoice will contain line items for the timespan between the start date and the current time. Can be combined with trials and the billing cycle anchor. + BackdateStartDate *int64 `form:"backdate_start_date"` + // A future timestamp in UTC format to anchor the subscription's [billing cycle](https://stripe.com/docs/subscriptions/billing-cycle). The anchor is the reference point that aligns future billing cycle dates. It sets the day of week for `week` intervals, the day of month for `month` and `year` intervals, and the month of year for `year` intervals. + BillingCycleAnchor *int64 `form:"billing_cycle_anchor"` + // Mutually exclusive with billing_cycle_anchor and only valid with monthly and yearly price intervals. When provided, the billing_cycle_anchor is set to the next occurence of the day_of_month at the hour, minute, and second UTC. + BillingCycleAnchorConfig *SubscriptionCreateBillingCycleAnchorConfigParams `form:"billing_cycle_anchor_config"` + BillingCycleAnchorNow *bool `form:"-"` // See custom AppendTo + BillingCycleAnchorUnchanged *bool `form:"-"` // See custom AppendTo + // Controls how prorations and invoices for subscriptions are calculated and orchestrated. + BillingMode *SubscriptionCreateBillingModeParams `form:"billing_mode"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. When updating, pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionCreateBillingThresholdsParams `form:"billing_thresholds"` + // A timestamp at which the subscription should cancel. If set to a date before the current period ends, this will cause a proration if prorations have been enabled using `proration_behavior`. If set during a future period, this will always cause a proration for that period. + CancelAt *int64 `form:"cancel_at"` + // Indicate whether this subscription should cancel at the end of the current period (`current_period_end`). Defaults to `false`. + CancelAtPeriodEnd *bool `form:"cancel_at_period_end"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically`. + CollectionMethod *string `form:"collection_method"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The identifier of the customer to subscribe. + Customer *string `form:"customer"` + // Number of days a customer has to pay invoices generated by this subscription. Valid only for subscriptions where `collection_method` is set to `send_invoice`. + DaysUntilDue *int64 `form:"days_until_due"` + // ID of the default payment method for the subscription. It must belong to the customer associated with the subscription. This takes precedence over `default_source`. If neither are set, invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + DefaultPaymentMethod *string `form:"default_payment_method"` + // ID of the default payment source for the subscription. It must belong to the customer associated with the subscription and be in a chargeable state. If `default_payment_method` is also set, `default_payment_method` will take precedence. If neither are set, invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + DefaultSource *string `form:"default_source"` + // The tax rates that will apply to any subscription item that does not have `tax_rates` set. Invoices created will have their `default_tax_rates` populated from the subscription. + DefaultTaxRates []*string `form:"default_tax_rates"` + // The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // The coupons to redeem into discounts for the subscription. If not specified or empty, inherits the discount from the subscription's customer. + Discounts []*SubscriptionCreateDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // All invoices will be billed using the specified settings. + InvoiceSettings *SubscriptionCreateInvoiceSettingsParams `form:"invoice_settings"` + // A list of up to 20 subscription items, each with an attached price. + Items []*SubscriptionCreateItemParams `form:"items"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Indicates if a customer is on or off-session while an invoice payment is attempted. Defaults to `false` (on-session). + OffSession *bool `form:"off_session"` + // The account on behalf of which to charge, for each of the subscription's invoices. + OnBehalfOf *string `form:"on_behalf_of"` + // Only applies to subscriptions with `collection_method=charge_automatically`. + // + // Use `allow_incomplete` to create Subscriptions with `status=incomplete` if the first invoice can't be paid. Creating Subscriptions with this status allows you to manage scenarios where additional customer actions are needed to pay a subscription's invoice. For example, SCA regulation may require 3DS authentication to complete payment. See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. This is the default behavior. + // + // Use `default_incomplete` to create Subscriptions with `status=incomplete` when the first invoice requires payment, otherwise start as active. Subscriptions transition to `status=active` when successfully confirming the PaymentIntent on the first invoice. This allows simpler management of scenarios where additional customer actions are needed to pay a subscription's invoice, such as failed payments, [SCA regulation](https://stripe.com/docs/billing/migration/strong-customer-authentication), or collecting a mandate for a bank debit payment method. If the PaymentIntent is not confirmed within 23 hours Subscriptions transition to `status=incomplete_expired`, which is a terminal state. + // + // Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's first invoice can't be paid. For example, if a payment method requires 3DS authentication due to SCA regulation and further customer action is needed, this parameter doesn't create a Subscription and returns an error instead. This was the default behavior for API versions prior to 2019-03-14. See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + // + // `pending_if_incomplete` is only used with updates and cannot be passed when creating a Subscription. + // + // Subscriptions with `collection_method=send_invoice` are automatically activated regardless of the first Invoice status. + PaymentBehavior *string `form:"payment_behavior"` + // Payment settings to pass to invoices created by the subscription. + PaymentSettings *SubscriptionCreatePaymentSettingsParams `form:"payment_settings"` + // Specifies an interval for how often to bill for any pending invoice items. It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. + PendingInvoiceItemInterval *SubscriptionCreatePendingInvoiceItemIntervalParams `form:"pending_invoice_item_interval"` + // Determines how to handle [prorations](https://stripe.com/docs/billing/subscriptions/prorations) resulting from the `billing_cycle_anchor`. If no value is passed, the default is `create_prorations`. + ProrationBehavior *string `form:"proration_behavior"` + // If specified, the funds from the subscription's invoices will be transferred to the destination and the ID of the resulting transfers will be found on the resulting charges. + TransferData *SubscriptionCreateTransferDataParams `form:"transfer_data"` + // Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. If set, trial_end will override the default trial period of the plan the customer is being subscribed to. The special value `now` can be provided to end the customer's trial immediately. Can be at most two years from `billing_cycle_anchor`. See [Using trial periods on subscriptions](https://stripe.com/docs/billing/subscriptions/trials) to learn more. + TrialEnd *int64 `form:"trial_end"` + TrialEndNow *bool `form:"-"` // See custom AppendTo + // Indicates if a plan's `trial_period_days` should be applied to the subscription. Setting `trial_end` per subscription is preferred, and this defaults to `false`. Setting this flag to `true` together with `trial_end` is not allowed. See [Using trial periods on subscriptions](https://stripe.com/docs/billing/subscriptions/trials) to learn more. + TrialFromPlan *bool `form:"trial_from_plan"` + // Integer representing the number of trial period days before the customer is charged for the first time. This will always overwrite any trials that might apply via a subscribed plan. See [Using trial periods on subscriptions](https://stripe.com/docs/billing/subscriptions/trials) to learn more. + TrialPeriodDays *int64 `form:"trial_period_days"` + // Settings related to subscription trials. + TrialSettings *SubscriptionCreateTrialSettingsParams `form:"trial_settings"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// AppendTo implements custom encoding logic for SubscriptionCreateParams. +func (p *SubscriptionCreateParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.BillingCycleAnchorNow) { + body.Add(form.FormatKey(append(keyParts, "billing_cycle_anchor")), "now") + } + if BoolValue(p.BillingCycleAnchorUnchanged) { + body.Add(form.FormatKey(append(keyParts, "billing_cycle_anchor")), "unchanged") + } + if BoolValue(p.TrialEndNow) { + body.Add(form.FormatKey(append(keyParts, "trial_end")), "now") + } +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type SubscriptionAutomaticTaxLiability struct { + // The connected account being referenced when `type` is `account`. + Account *Account `json:"account"` + // Type of the account referenced. + Type SubscriptionAutomaticTaxLiabilityType `json:"type"` +} +type SubscriptionAutomaticTax struct { + // If Stripe disabled automatic tax, this enum describes why. + DisabledReason SubscriptionAutomaticTaxDisabledReason `json:"disabled_reason"` + // Whether Stripe automatically computes tax on this subscription. + Enabled bool `json:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *SubscriptionAutomaticTaxLiability `json:"liability"` +} + +// The fixed values used to calculate the `billing_cycle_anchor`. +type SubscriptionBillingCycleAnchorConfig struct { + // The day of the month of the billing_cycle_anchor. + DayOfMonth int64 `json:"day_of_month"` + // The hour of the day of the billing_cycle_anchor. + Hour int64 `json:"hour"` + // The minute of the hour of the billing_cycle_anchor. + Minute int64 `json:"minute"` + // The month to start full cycle billing periods. + Month int64 `json:"month"` + // The second of the minute of the billing_cycle_anchor. + Second int64 `json:"second"` +} + +// The billing mode of the subscription. +type SubscriptionBillingMode struct { + // Controls how prorations and invoices for subscriptions are calculated and orchestrated. + Type SubscriptionBillingModeType `json:"type"` + // Details on when the current billing_mode was adopted. + UpdatedAt int64 `json:"updated_at"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period +type SubscriptionBillingThresholds struct { + // Monetary threshold that triggers the subscription to create an invoice + AmountGTE int64 `json:"amount_gte"` + // Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. This value may not be `true` if the subscription contains items with plans that have `aggregate_usage=last_ever`. + ResetBillingCycleAnchor bool `json:"reset_billing_cycle_anchor"` +} + +// Details about why this subscription was cancelled +type SubscriptionCancellationDetails struct { + // Additional comments about why the user canceled the subscription, if the subscription was canceled explicitly by the user. + Comment string `json:"comment"` + // The customer submitted reason for why they canceled, if the subscription was canceled explicitly by the user. + Feedback SubscriptionCancellationDetailsFeedback `json:"feedback"` + // Why this subscription was canceled. + Reason SubscriptionCancellationDetailsReason `json:"reason"` +} +type SubscriptionInvoiceSettingsIssuer struct { + // The connected account being referenced when `type` is `account`. + Account *Account `json:"account"` + // Type of the account referenced. + Type SubscriptionInvoiceSettingsIssuerType `json:"type"` +} +type SubscriptionInvoiceSettings struct { + // The account tax IDs associated with the subscription. Will be set on invoices generated by the subscription. + AccountTaxIDs []*TaxID `json:"account_tax_ids"` + Issuer *SubscriptionInvoiceSettingsIssuer `json:"issuer"` +} + +// If specified, payment collection for this subscription will be paused. Note that the subscription status will be unchanged and will not be updated to `paused`. Learn more about [pausing collection](https://stripe.com/docs/billing/subscriptions/pause-payment). +type SubscriptionPauseCollection struct { + // The payment collection behavior for this subscription while paused. One of `keep_as_draft`, `mark_uncollectible`, or `void`. + Behavior SubscriptionPauseCollectionBehavior `json:"behavior"` + // The time after which the subscription will resume collecting payments. + ResumesAt int64 `json:"resumes_at"` +} +type SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitMandateOptions struct { + // Transaction type of the mandate. + TransactionType SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitMandateOptionsTransactionType `json:"transaction_type"` +} + +// This sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to invoices created by the subscription. +type SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebit struct { + MandateOptions *SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitMandateOptions `json:"mandate_options"` + // Bank account verification method. + VerificationMethod SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebitVerificationMethod `json:"verification_method"` +} + +// This sub-hash contains details about the Bancontact payment method options to pass to invoices created by the subscription. +type SubscriptionPaymentSettingsPaymentMethodOptionsBancontact struct { + // Preferred language of the Bancontact authorization page that the customer is redirected to. + PreferredLanguage string `json:"preferred_language"` +} +type SubscriptionPaymentSettingsPaymentMethodOptionsCardMandateOptions struct { + // Amount to be charged for future payments. + Amount int64 `json:"amount"` + // One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + AmountType SubscriptionPaymentSettingsPaymentMethodOptionsCardMandateOptionsAmountType `json:"amount_type"` + // A description of the mandate or subscription that is meant to be displayed to the customer. + Description string `json:"description"` +} + +// This sub-hash contains details about the Card payment method options to pass to invoices created by the subscription. +type SubscriptionPaymentSettingsPaymentMethodOptionsCard struct { + MandateOptions *SubscriptionPaymentSettingsPaymentMethodOptionsCardMandateOptions `json:"mandate_options"` + // Selected network to process this Subscription on. Depends on the available networks of the card attached to the Subscription. Can be only set confirm-time. + Network SubscriptionPaymentSettingsPaymentMethodOptionsCardNetwork `json:"network"` + // We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure/authentication-flow#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + RequestThreeDSecure SubscriptionPaymentSettingsPaymentMethodOptionsCardRequestThreeDSecure `json:"request_three_d_secure"` +} +type SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransfer struct { + // The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + Country string `json:"country"` +} +type SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer struct { + EUBankTransfer *SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEUBankTransfer `json:"eu_bank_transfer"` + // The bank transfer type that can be used for funding. Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + Type string `json:"type"` +} + +// This sub-hash contains details about the Bank transfer payment method options to pass to invoices created by the subscription. +type SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalance struct { + BankTransfer *SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer `json:"bank_transfer"` + // The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + FundingType SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalanceFundingType `json:"funding_type"` +} + +// This sub-hash contains details about the Konbini payment method options to pass to invoices created by the subscription. +type SubscriptionPaymentSettingsPaymentMethodOptionsKonbini struct{} + +// This sub-hash contains details about the SEPA Direct Debit payment method options to pass to invoices created by the subscription. +type SubscriptionPaymentSettingsPaymentMethodOptionsSEPADebit struct{} +type SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFilters struct { + // The account subcategories to use to filter for possible accounts to link. Valid subcategories are `checking` and `savings`. + AccountSubcategories []SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFiltersAccountSubcategory `json:"account_subcategories"` +} +type SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnections struct { + Filters *SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsFilters `json:"filters"` + // The list of permissions to request. The `payment_method` permission must be included. + Permissions []SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPermission `json:"permissions"` + // Data features requested to be retrieved upon account creation. + Prefetch []SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnectionsPrefetch `json:"prefetch"` +} + +// This sub-hash contains details about the ACH direct debit payment method options to pass to invoices created by the subscription. +type SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccount struct { + FinancialConnections *SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountFinancialConnections `json:"financial_connections"` + // Bank account verification method. + VerificationMethod SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccountVerificationMethod `json:"verification_method"` +} + +// Payment-method-specific configuration to provide to invoices created by the subscription. +type SubscriptionPaymentSettingsPaymentMethodOptions struct { + // This sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to invoices created by the subscription. + ACSSDebit *SubscriptionPaymentSettingsPaymentMethodOptionsACSSDebit `json:"acss_debit"` + // This sub-hash contains details about the Bancontact payment method options to pass to invoices created by the subscription. + Bancontact *SubscriptionPaymentSettingsPaymentMethodOptionsBancontact `json:"bancontact"` + // This sub-hash contains details about the Card payment method options to pass to invoices created by the subscription. + Card *SubscriptionPaymentSettingsPaymentMethodOptionsCard `json:"card"` + // This sub-hash contains details about the Bank transfer payment method options to pass to invoices created by the subscription. + CustomerBalance *SubscriptionPaymentSettingsPaymentMethodOptionsCustomerBalance `json:"customer_balance"` + // This sub-hash contains details about the Konbini payment method options to pass to invoices created by the subscription. + Konbini *SubscriptionPaymentSettingsPaymentMethodOptionsKonbini `json:"konbini"` + // This sub-hash contains details about the SEPA Direct Debit payment method options to pass to invoices created by the subscription. + SEPADebit *SubscriptionPaymentSettingsPaymentMethodOptionsSEPADebit `json:"sepa_debit"` + // This sub-hash contains details about the ACH direct debit payment method options to pass to invoices created by the subscription. + USBankAccount *SubscriptionPaymentSettingsPaymentMethodOptionsUSBankAccount `json:"us_bank_account"` +} + +// Payment settings passed on to invoices created by the subscription. +type SubscriptionPaymentSettings struct { + // Payment-method-specific configuration to provide to invoices created by the subscription. + PaymentMethodOptions *SubscriptionPaymentSettingsPaymentMethodOptions `json:"payment_method_options"` + // The list of payment method types to provide to every invoice created by the subscription. If not set, Stripe attempts to automatically determine the types to use by looking at the invoice's default payment method, the subscription's default payment method, the customer's default payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). + PaymentMethodTypes []SubscriptionPaymentSettingsPaymentMethodType `json:"payment_method_types"` + // Configure whether Stripe updates `subscription.default_payment_method` when payment succeeds. Defaults to `off`. + SaveDefaultPaymentMethod SubscriptionPaymentSettingsSaveDefaultPaymentMethod `json:"save_default_payment_method"` +} + +// Specifies an interval for how often to bill for any pending invoice items. It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. +type SubscriptionPendingInvoiceItemInterval struct { + // Specifies invoicing frequency. Either `day`, `week`, `month` or `year`. + Interval SubscriptionPendingInvoiceItemIntervalInterval `json:"interval"` + // The number of intervals between invoices. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). + IntervalCount int64 `json:"interval_count"` +} + +// If specified, [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates) that will be applied to the subscription once the `latest_invoice` has been paid. +type SubscriptionPendingUpdate struct { + // If the update is applied, determines the date of the first full invoice, and, for plans with `month` or `year` intervals, the day of the month for subsequent invoices. The timestamp is in UTC format. + BillingCycleAnchor int64 `json:"billing_cycle_anchor"` + // The point after which the changes reflected by this update will be discarded and no longer applied. + ExpiresAt int64 `json:"expires_at"` + // List of subscription items, each with an attached plan, that will be set if the update is applied. + SubscriptionItems []*SubscriptionItem `json:"subscription_items"` + // Unix timestamp representing the end of the trial period the customer will get before being charged for the first time, if the update is applied. + TrialEnd int64 `json:"trial_end"` + // Indicates if a plan's `trial_period_days` should be applied to the subscription. Setting `trial_end` per subscription is preferred, and this defaults to `false`. Setting this flag to `true` together with `trial_end` is not allowed. See [Using trial periods on subscriptions](https://stripe.com/docs/billing/subscriptions/trials) to learn more. + TrialFromPlan bool `json:"trial_from_plan"` +} + +// The account (if any) the subscription's payments will be attributed to for tax reporting, and where funds from each payment will be transferred to for each of the subscription's invoices. +type SubscriptionTransferData struct { + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + AmountPercent float64 `json:"amount_percent"` + // The account where funds from the payment will be transferred to upon payment success. + Destination *Account `json:"destination"` +} + +// Defines how a subscription behaves when a free trial ends. +type SubscriptionTrialSettingsEndBehavior struct { + // Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + MissingPaymentMethod SubscriptionTrialSettingsEndBehaviorMissingPaymentMethod `json:"missing_payment_method"` +} + +// Settings related to subscription trials. +type SubscriptionTrialSettings struct { + // Defines how a subscription behaves when a free trial ends. + EndBehavior *SubscriptionTrialSettingsEndBehavior `json:"end_behavior"` +} + +// Subscriptions allow you to charge a customer on a recurring basis. +// +// Related guide: [Creating subscriptions](https://stripe.com/docs/billing/subscriptions/creating) +type Subscription struct { + APIResource + // ID of the Connect Application that created the subscription. + Application *Application `json:"application"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. + ApplicationFeePercent float64 `json:"application_fee_percent"` + AutomaticTax *SubscriptionAutomaticTax `json:"automatic_tax"` + // The reference point that aligns future [billing cycle](https://stripe.com/docs/subscriptions/billing-cycle) dates. It sets the day of week for `week` intervals, the day of month for `month` and `year` intervals, and the month of year for `year` intervals. The timestamp is in UTC format. + BillingCycleAnchor int64 `json:"billing_cycle_anchor"` + // The fixed values used to calculate the `billing_cycle_anchor`. + BillingCycleAnchorConfig *SubscriptionBillingCycleAnchorConfig `json:"billing_cycle_anchor_config"` + // The billing mode of the subscription. + BillingMode *SubscriptionBillingMode `json:"billing_mode"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period + BillingThresholds *SubscriptionBillingThresholds `json:"billing_thresholds"` + // A date in the future at which the subscription will automatically get canceled + CancelAt int64 `json:"cancel_at"` + // Whether this subscription will (if `status=active`) or did (if `status=canceled`) cancel at the end of the current billing period. + CancelAtPeriodEnd bool `json:"cancel_at_period_end"` + // If the subscription has been canceled, the date of that cancellation. If the subscription was canceled with `cancel_at_period_end`, `canceled_at` will reflect the time of the most recent update request, not the end of the subscription period when the subscription is automatically moved to a canceled state. + CanceledAt int64 `json:"canceled_at"` + // Details about why this subscription was cancelled + CancellationDetails *SubscriptionCancellationDetails `json:"cancellation_details"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. + CollectionMethod SubscriptionCollectionMethod `json:"collection_method"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // ID of the customer who owns the subscription. + Customer *Customer `json:"customer"` + // Number of days a customer has to pay invoices generated by this subscription. This value will be `null` for subscriptions where `collection_method=charge_automatically`. + DaysUntilDue int64 `json:"days_until_due"` + // ID of the default payment method for the subscription. It must belong to the customer associated with the subscription. This takes precedence over `default_source`. If neither are set, invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + DefaultPaymentMethod *PaymentMethod `json:"default_payment_method"` + // ID of the default payment source for the subscription. It must belong to the customer associated with the subscription and be in a chargeable state. If `default_payment_method` is also set, `default_payment_method` will take precedence. If neither are set, invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + DefaultSource *PaymentSource `json:"default_source"` + // The tax rates that will apply to any subscription item that does not have `tax_rates` set. Invoices created will have their `default_tax_rates` populated from the subscription. + DefaultTaxRates []*TaxRate `json:"default_tax_rates"` + // The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description string `json:"description"` + // The discounts applied to the subscription. Subscription item discounts are applied before subscription discounts. Use `expand[]=discounts` to expand each discount. + Discounts []*Discount `json:"discounts"` + // If the subscription has ended, the date the subscription ended. + EndedAt int64 `json:"ended_at"` + // Unique identifier for the object. + ID string `json:"id"` + InvoiceSettings *SubscriptionInvoiceSettings `json:"invoice_settings"` + // List of subscription items, each with an attached price. + Items *SubscriptionItemList `json:"items"` + // The most recent invoice this subscription has generated. + LatestInvoice *Invoice `json:"latest_invoice"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // Specifies the approximate timestamp on which any pending invoice items will be billed according to the schedule provided at `pending_invoice_item_interval`. + NextPendingInvoiceItemInvoice int64 `json:"next_pending_invoice_item_invoice"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The account (if any) the charge was made on behalf of for charges associated with this subscription. See the [Connect documentation](https://stripe.com/docs/connect/subscriptions#on-behalf-of) for details. + OnBehalfOf *Account `json:"on_behalf_of"` + // If specified, payment collection for this subscription will be paused. Note that the subscription status will be unchanged and will not be updated to `paused`. Learn more about [pausing collection](https://stripe.com/docs/billing/subscriptions/pause-payment). + PauseCollection *SubscriptionPauseCollection `json:"pause_collection"` + // Payment settings passed on to invoices created by the subscription. + PaymentSettings *SubscriptionPaymentSettings `json:"payment_settings"` + // Specifies an interval for how often to bill for any pending invoice items. It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. + PendingInvoiceItemInterval *SubscriptionPendingInvoiceItemInterval `json:"pending_invoice_item_interval"` + // You can use this [SetupIntent](https://stripe.com/docs/api/setup_intents) to collect user authentication when creating a subscription without immediate payment or updating a subscription's payment method, allowing you to optimize for off-session payments. Learn more in the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication#scenario-2). + PendingSetupIntent *SetupIntent `json:"pending_setup_intent"` + // If specified, [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates) that will be applied to the subscription once the `latest_invoice` has been paid. + PendingUpdate *SubscriptionPendingUpdate `json:"pending_update"` + // The schedule attached to the subscription + Schedule *SubscriptionSchedule `json:"schedule"` + // Date when the subscription was first created. The date might differ from the `created` date due to backdating. + StartDate int64 `json:"start_date"` + // Possible values are `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `canceled`, `unpaid`, or `paused`. + // + // For `collection_method=charge_automatically` a subscription moves into `incomplete` if the initial payment attempt fails. A subscription in this status can only have metadata and default_source updated. Once the first invoice is paid, the subscription moves into an `active` status. If the first invoice is not paid within 23 hours, the subscription transitions to `incomplete_expired`. This is a terminal status, the open invoice will be voided and no further invoices will be generated. + // + // A subscription that is currently in a trial period is `trialing` and moves to `active` when the trial period is over. + // + // A subscription can only enter a `paused` status [when a trial ends without a payment method](https://stripe.com/docs/billing/subscriptions/trials#create-free-trials-without-payment). A `paused` subscription doesn't generate invoices and can be resumed after your customer adds their payment method. The `paused` status is different from [pausing collection](https://stripe.com/docs/billing/subscriptions/pause-payment), which still generates invoices and leaves the subscription's status unchanged. + // + // If subscription `collection_method=charge_automatically`, it becomes `past_due` when payment is required but cannot be paid (due to failed payment or awaiting additional user actions). Once Stripe has exhausted all payment retry attempts, the subscription will become `canceled` or `unpaid` (depending on your subscriptions settings). + // + // If subscription `collection_method=send_invoice` it becomes `past_due` when its invoice is not paid by the due date, and `canceled` or `unpaid` if it is still not paid by an additional deadline after that. Note that when a subscription has a status of `unpaid`, no subsequent invoices will be attempted (invoices will be created, but then immediately automatically closed). After receiving updated payment information from a customer, you may choose to reopen and pay their closed invoices. + Status SubscriptionStatus `json:"status"` + // ID of the test clock this subscription belongs to. + TestClock *TestHelpersTestClock `json:"test_clock"` + // The account (if any) the subscription's payments will be attributed to for tax reporting, and where funds from each payment will be transferred to for each of the subscription's invoices. + TransferData *SubscriptionTransferData `json:"transfer_data"` + // If the subscription has a trial, the end of that trial. + TrialEnd int64 `json:"trial_end"` + // Settings related to subscription trials. + TrialSettings *SubscriptionTrialSettings `json:"trial_settings"` + // If the subscription has a trial, the beginning of that trial. + TrialStart int64 `json:"trial_start"` +} + +// SubscriptionList is a list of Subscriptions as retrieved from a list endpoint. +type SubscriptionList struct { + APIResource + ListMeta + Data []*Subscription `json:"data"` +} + +// SubscriptionSearchResult is a list of Subscription search results as retrieved from a search endpoint. +type SubscriptionSearchResult struct { + APIResource + SearchMeta + Data []*Subscription `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Subscription. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (s *Subscription) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + s.ID = id + return nil + } + + type subscription Subscription + var v subscription + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *s = Subscription(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/subscription_service.go b/vendor/github.com/stripe/stripe-go/v82/subscription_service.go new file mode 100644 index 00000000..8ad227c8 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/subscription_service.go @@ -0,0 +1,169 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1SubscriptionService is used to invoke /v1/subscriptions APIs. +type v1SubscriptionService struct { + B Backend + Key string +} + +// Creates a new subscription on an existing customer. Each customer can have up to 500 active or scheduled subscriptions. +// +// When you create a subscription with collection_method=charge_automatically, the first invoice is finalized as part of the request. +// The payment_behavior parameter determines the exact behavior of the initial payment. +// +// To start subscriptions where the first invoice always begins in a draft status, use [subscription schedules](https://docs.stripe.com/docs/billing/subscriptions/subscription-schedules#managing) instead. +// Schedules provide the flexibility to model more complex billing configurations that change over time. +func (c v1SubscriptionService) Create(ctx context.Context, params *SubscriptionCreateParams) (*Subscription, error) { + if params == nil { + params = &SubscriptionCreateParams{} + } + params.Context = ctx + subscription := &Subscription{} + err := c.B.Call( + http.MethodPost, "/v1/subscriptions", c.Key, params, subscription) + return subscription, err +} + +// Retrieves the subscription with the given ID. +func (c v1SubscriptionService) Retrieve(ctx context.Context, id string, params *SubscriptionRetrieveParams) (*Subscription, error) { + if params == nil { + params = &SubscriptionRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/subscriptions/%s", id) + subscription := &Subscription{} + err := c.B.Call(http.MethodGet, path, c.Key, params, subscription) + return subscription, err +} + +// Updates an existing subscription to match the specified parameters. +// When changing prices or quantities, we optionally prorate the price we charge next month to make up for any price changes. +// To preview how the proration is calculated, use the [create preview](https://docs.stripe.com/docs/api/invoices/create_preview) endpoint. +// +// By default, we prorate subscription changes. For example, if a customer signs up on May 1 for a 100 price, they'll be billed 100 immediately. If on May 15 they switch to a 200 price, then on June 1 they'll be billed 250 (200 for a renewal of her subscription, plus a 50 prorating adjustment for half of the previous month's 100 difference). Similarly, a downgrade generates a credit that is applied to the next invoice. We also prorate when you make quantity changes. +// +// Switching prices does not normally change the billing date or generate an immediate charge unless: +// +// The billing interval is changed (for example, from monthly to yearly). +// The subscription moves from free to paid. +// A trial starts or ends. +// +// In these cases, we apply a credit for the unused time on the previous price, immediately charge the customer using the new price, and reset the billing date. Learn about how [Stripe immediately attempts payment for subscription changes](https://docs.stripe.com/docs/billing/subscriptions/upgrade-downgrade#immediate-payment). +// +// If you want to charge for an upgrade immediately, pass proration_behavior as always_invoice to create prorations, automatically invoice the customer for those proration adjustments, and attempt to collect payment. If you pass create_prorations, the prorations are created but not automatically invoiced. If you want to bill the customer for the prorations before the subscription's renewal date, you need to manually [invoice the customer](https://docs.stripe.com/docs/api/invoices/create). +// +// If you don't want to prorate, set the proration_behavior option to none. With this option, the customer is billed 100 on May 1 and 200 on June 1. Similarly, if you set proration_behavior to none when switching between different billing intervals (for example, from monthly to yearly), we don't generate any credits for the old subscription's unused time. We still reset the billing date and bill immediately for the new subscription. +// +// Updating the quantity on a subscription many times in an hour may result in [rate limiting. If you need to bill for a frequently changing quantity, consider integrating usage-based billing](https://docs.stripe.com/docs/rate-limits) instead. +func (c v1SubscriptionService) Update(ctx context.Context, id string, params *SubscriptionUpdateParams) (*Subscription, error) { + if params == nil { + params = &SubscriptionUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/subscriptions/%s", id) + subscription := &Subscription{} + err := c.B.Call(http.MethodPost, path, c.Key, params, subscription) + return subscription, err +} + +// Cancels a customer's subscription immediately. The customer won't be charged again for the subscription. After it's canceled, you can no longer update the subscription or its [metadata](https://docs.stripe.com/metadata). +// +// Any pending invoice items that you've created are still charged at the end of the period, unless manually [deleted](https://docs.stripe.com/api#delete_invoiceitem). If you've set the subscription to cancel at the end of the period, any pending prorations are also left in place and collected at the end of the period. But if the subscription is set to cancel immediately, pending prorations are removed if invoice_now and prorate are both set to true. +// +// By default, upon subscription cancellation, Stripe stops automatic collection of all finalized invoices for the customer. This is intended to prevent unexpected payment attempts after the customer has canceled a subscription. However, you can resume automatic collection of the invoices manually after subscription cancellation to have us proceed. Or, you could check for unpaid invoices before allowing the customer to cancel the subscription at all. +func (c v1SubscriptionService) Cancel(ctx context.Context, id string, params *SubscriptionCancelParams) (*Subscription, error) { + if params == nil { + params = &SubscriptionCancelParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/subscriptions/%s", id) + subscription := &Subscription{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, subscription) + return subscription, err +} + +// Removes the currently applied discount on a subscription. +func (c v1SubscriptionService) DeleteDiscount(ctx context.Context, id string, params *SubscriptionDeleteDiscountParams) (*Subscription, error) { + if params == nil { + params = &SubscriptionDeleteDiscountParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/subscriptions/%s/discount", id) + subscription := &Subscription{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, subscription) + return subscription, err +} + +// Upgrade the billing_mode of an existing subscription. +func (c v1SubscriptionService) Migrate(ctx context.Context, id string, params *SubscriptionMigrateParams) (*Subscription, error) { + if params == nil { + params = &SubscriptionMigrateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/subscriptions/%s/migrate", id) + subscription := &Subscription{} + err := c.B.Call(http.MethodPost, path, c.Key, params, subscription) + return subscription, err +} + +// Initiates resumption of a paused subscription, optionally resetting the billing cycle anchor and creating prorations. If a resumption invoice is generated, it must be paid or marked uncollectible before the subscription will be unpaused. If payment succeeds the subscription will become active, and if payment fails the subscription will be past_due. The resumption invoice will void automatically if not paid by the expiration date. +func (c v1SubscriptionService) Resume(ctx context.Context, id string, params *SubscriptionResumeParams) (*Subscription, error) { + if params == nil { + params = &SubscriptionResumeParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/subscriptions/%s/resume", id) + subscription := &Subscription{} + err := c.B.Call(http.MethodPost, path, c.Key, params, subscription) + return subscription, err +} + +// By default, returns a list of subscriptions that have not been canceled. In order to list canceled subscriptions, specify status=canceled. +func (c v1SubscriptionService) List(ctx context.Context, listParams *SubscriptionListParams) Seq2[*Subscription, error] { + if listParams == nil { + listParams = &SubscriptionListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Subscription, ListContainer, error) { + list := &SubscriptionList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/subscriptions", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} + +// Search for subscriptions you've previously created using Stripe's [Search Query Language](https://docs.stripe.com/docs/search#search-query-language). +// Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating +// conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up +// to an hour behind during outages. Search functionality is not available to merchants in India. +func (c v1SubscriptionService) Search(ctx context.Context, params *SubscriptionSearchParams) Seq2[*Subscription, error] { + if params == nil { + params = &SubscriptionSearchParams{} + } + params.Context = ctx + return newV1SearchList(params, func(p *Params, b *form.Values) ([]*Subscription, SearchContainer, error) { + list := &SubscriptionSearchResult{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/subscriptions/search", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/subscriptionitem.go b/vendor/github.com/stripe/stripe-go/v82/subscriptionitem.go new file mode 100644 index 00000000..8f700b2a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/subscriptionitem.go @@ -0,0 +1,380 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Deletes an item from the subscription. Removing a subscription item from a subscription will not cancel the subscription. +type SubscriptionItemParams struct { + Params `form:"*"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionItemBillingThresholdsParams `form:"billing_thresholds"` + // Delete all usage for the given subscription item. Allowed only when the current plan's `usage_type` is `metered`. + ClearUsage *bool `form:"clear_usage"` + // The coupons to redeem into discounts for the subscription item. + Discounts []*SubscriptionItemDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Only supported on update + // Indicates if a customer is on or off-session while an invoice payment is attempted. Defaults to `false` (on-session). + OffSession *bool `form:"off_session"` + // Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. For example, SCA regulation may require 3DS authentication to complete payment. See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. This is the default behavior. + // + // Use `default_incomplete` to transition the subscription to `status=past_due` when payment is required and await explicit confirmation of the invoice's payment intent. This allows simpler management of scenarios where additional user actions are needed to pay a subscription's invoice. Such as failed payments, [SCA regulation](https://stripe.com/docs/billing/migration/strong-customer-authentication), or collecting a mandate for a bank debit payment method. + // + // Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). + // + // Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's invoice cannot be paid. For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not update the subscription and returns an error instead. This was the default behavior for API versions prior to 2019-03-14. See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + PaymentBehavior *string `form:"payment_behavior"` + // The identifier of the new plan for this subscription item. + Plan *string `form:"plan"` + // The ID of the price object. One of `price` or `price_data` is required. When changing a subscription item's price, `quantity` is set to 1 unless a `quantity` parameter is provided. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *SubscriptionItemPriceDataParams `form:"price_data"` + // Determines how to handle [prorations](https://stripe.com/docs/billing/subscriptions/prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. The default value is `create_prorations`. + ProrationBehavior *string `form:"proration_behavior"` + // If set, the proration will be calculated as though the subscription was updated at the given time. This can be used to apply the same proration that was previewed with the [upcoming invoice](https://stripe.com/docs/api#retrieve_customer_invoice) endpoint. + ProrationDate *int64 `form:"proration_date"` + // The quantity you'd like to apply to the subscription item you're creating. + Quantity *int64 `form:"quantity"` + // The identifier of the subscription to modify. + Subscription *string `form:"subscription"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionItemParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionItemParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type SubscriptionItemBillingThresholdsParams struct { + // Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + UsageGTE *int64 `form:"usage_gte"` +} + +// The coupons to redeem into discounts for the subscription item. +type SubscriptionItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The recurring components of a price such as `interval` and `interval_count`. +type SubscriptionItemPriceDataRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. +type SubscriptionItemPriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // The recurring components of a price such as `interval` and `interval_count`. + Recurring *SubscriptionItemPriceDataRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// Returns a list of your subscription items for a given subscription. +type SubscriptionItemListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The ID of the subscription whose items will be retrieved. + Subscription *string `form:"subscription"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionItemListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Deletes an item from the subscription. Removing a subscription item from a subscription will not cancel the subscription. +type SubscriptionItemDeleteParams struct { + Params `form:"*"` + // Delete all usage for the given subscription item. Allowed only when the current plan's `usage_type` is `metered`. + ClearUsage *bool `form:"clear_usage"` + // Determines how to handle [prorations](https://stripe.com/docs/billing/subscriptions/prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. The default value is `create_prorations`. + ProrationBehavior *string `form:"proration_behavior"` + // If set, the proration will be calculated as though the subscription was updated at the given time. This can be used to apply the same proration that was previewed with the [upcoming invoice](https://stripe.com/docs/api#retrieve_customer_invoice) endpoint. + ProrationDate *int64 `form:"proration_date"` +} + +// Retrieves the subscription item with the given ID. +type SubscriptionItemRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionItemRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type SubscriptionItemUpdateBillingThresholdsParams struct { + // Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + UsageGTE *int64 `form:"usage_gte"` +} + +// The coupons to redeem into discounts for the subscription item. +type SubscriptionItemUpdateDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The recurring components of a price such as `interval` and `interval_count`. +type SubscriptionItemUpdatePriceDataRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. +type SubscriptionItemUpdatePriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // The recurring components of a price such as `interval` and `interval_count`. + Recurring *SubscriptionItemUpdatePriceDataRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// Updates the plan or quantity of an item on a current subscription. +type SubscriptionItemUpdateParams struct { + Params `form:"*"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionItemUpdateBillingThresholdsParams `form:"billing_thresholds"` + // The coupons to redeem into discounts for the subscription item. + Discounts []*SubscriptionItemUpdateDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Indicates if a customer is on or off-session while an invoice payment is attempted. Defaults to `false` (on-session). + OffSession *bool `form:"off_session"` + // Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. For example, SCA regulation may require 3DS authentication to complete payment. See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. This is the default behavior. + // + // Use `default_incomplete` to transition the subscription to `status=past_due` when payment is required and await explicit confirmation of the invoice's payment intent. This allows simpler management of scenarios where additional user actions are needed to pay a subscription's invoice. Such as failed payments, [SCA regulation](https://stripe.com/docs/billing/migration/strong-customer-authentication), or collecting a mandate for a bank debit payment method. + // + // Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). + // + // Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's invoice cannot be paid. For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not update the subscription and returns an error instead. This was the default behavior for API versions prior to 2019-03-14. See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + PaymentBehavior *string `form:"payment_behavior"` + // The identifier of the new plan for this subscription item. + Plan *string `form:"plan"` + // The ID of the price object. One of `price` or `price_data` is required. When changing a subscription item's price, `quantity` is set to 1 unless a `quantity` parameter is provided. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *SubscriptionItemUpdatePriceDataParams `form:"price_data"` + // Determines how to handle [prorations](https://stripe.com/docs/billing/subscriptions/prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. The default value is `create_prorations`. + ProrationBehavior *string `form:"proration_behavior"` + // If set, the proration will be calculated as though the subscription was updated at the given time. This can be used to apply the same proration that was previewed with the [upcoming invoice](https://stripe.com/docs/api#retrieve_customer_invoice) endpoint. + ProrationDate *int64 `form:"proration_date"` + // The quantity you'd like to apply to the subscription item you're creating. + Quantity *int64 `form:"quantity"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionItemUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionItemUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type SubscriptionItemCreateBillingThresholdsParams struct { + // Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + UsageGTE *int64 `form:"usage_gte"` +} + +// The coupons to redeem into discounts for the subscription item. +type SubscriptionItemCreateDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The recurring components of a price such as `interval` and `interval_count`. +type SubscriptionItemCreatePriceDataRecurringParams struct { + // Specifies billing frequency. Either `day`, `week`, `month` or `year`. + Interval *string `form:"interval"` + // The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + IntervalCount *int64 `form:"interval_count"` +} + +// Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. +type SubscriptionItemCreatePriceDataParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of the [Product](https://docs.stripe.com/api/products) that this [Price](https://docs.stripe.com/api/prices) will belong to. + Product *string `form:"product"` + // The recurring components of a price such as `interval` and `interval_count`. + Recurring *SubscriptionItemCreatePriceDataRecurringParams `form:"recurring"` + // Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + TaxBehavior *string `form:"tax_behavior"` + // A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + UnitAmount *int64 `form:"unit_amount"` + // Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"` +} + +// Adds a new item to an existing subscription. No existing items will be changed or replaced. +type SubscriptionItemCreateParams struct { + Params `form:"*"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionItemCreateBillingThresholdsParams `form:"billing_thresholds"` + // The coupons to redeem into discounts for the subscription item. + Discounts []*SubscriptionItemCreateDiscountParams `form:"discounts"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. For example, SCA regulation may require 3DS authentication to complete payment. See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. This is the default behavior. + // + // Use `default_incomplete` to transition the subscription to `status=past_due` when payment is required and await explicit confirmation of the invoice's payment intent. This allows simpler management of scenarios where additional user actions are needed to pay a subscription's invoice. Such as failed payments, [SCA regulation](https://stripe.com/docs/billing/migration/strong-customer-authentication), or collecting a mandate for a bank debit payment method. + // + // Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). + // + // Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's invoice cannot be paid. For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not update the subscription and returns an error instead. This was the default behavior for API versions prior to 2019-03-14. See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + PaymentBehavior *string `form:"payment_behavior"` + // The identifier of the plan to add to the subscription. + Plan *string `form:"plan"` + // The ID of the price object. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + PriceData *SubscriptionItemCreatePriceDataParams `form:"price_data"` + // Determines how to handle [prorations](https://stripe.com/docs/billing/subscriptions/prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. The default value is `create_prorations`. + ProrationBehavior *string `form:"proration_behavior"` + // If set, the proration will be calculated as though the subscription was updated at the given time. This can be used to apply the same proration that was previewed with the [upcoming invoice](https://stripe.com/docs/api#retrieve_customer_invoice) endpoint. + ProrationDate *int64 `form:"proration_date"` + // The quantity you'd like to apply to the subscription item you're creating. + Quantity *int64 `form:"quantity"` + // The identifier of the subscription to modify. + Subscription *string `form:"subscription"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionItemCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionItemCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Define thresholds at which an invoice will be sent, and the related subscription advanced to a new billing period +type SubscriptionItemBillingThresholds struct { + // Usage threshold that triggers the subscription to create an invoice + UsageGTE int64 `json:"usage_gte"` +} + +// Subscription items allow you to create customer subscriptions with more than +// one plan, making it easy to represent complex billing relationships. +type SubscriptionItem struct { + APIResource + // Define thresholds at which an invoice will be sent, and the related subscription advanced to a new billing period + BillingThresholds *SubscriptionItemBillingThresholds `json:"billing_thresholds"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // The end time of this subscription item's current billing period. + CurrentPeriodEnd int64 `json:"current_period_end"` + // The start time of this subscription item's current billing period. + CurrentPeriodStart int64 `json:"current_period_start"` + Deleted bool `json:"deleted"` + // The discounts applied to the subscription item. Subscription item discounts are applied before subscription discounts. Use `expand[]=discounts` to expand each discount. + Discounts []*Discount `json:"discounts"` + // Unique identifier for the object. + ID string `json:"id"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // You can now model subscriptions more flexibly using the [Prices API](https://stripe.com/docs/api#prices). It replaces the Plans API and is backwards compatible to simplify your migration. + // + // Plans define the base price, currency, and billing cycle for recurring purchases of products. + // [Products](https://stripe.com/docs/api#products) help you track inventory or provisioning, and plans help you track pricing. Different physical goods or levels of service should be represented by products, and pricing options should be represented by plans. This approach lets you change prices without having to change your provisioning scheme. + // + // For example, you might have a single "gold" product that has plans for $10/month, $100/year, €9/month, and €90/year. + // + // Related guides: [Set up a subscription](https://stripe.com/docs/billing/subscriptions/set-up-subscription) and more about [products and prices](https://stripe.com/docs/products-prices/overview). + Plan *Plan `json:"plan"` + // Prices define the unit cost, currency, and (optional) billing cycle for both recurring and one-time purchases of products. + // [Products](https://stripe.com/docs/api#products) help you track inventory or provisioning, and prices help you track payment terms. Different physical goods or levels of service should be represented by products, and pricing options should be represented by prices. This approach lets you change prices without having to change your provisioning scheme. + // + // For example, you might have a single "gold" product that has prices for $10/month, $100/year, and €9 once. + // + // Related guides: [Set up a subscription](https://stripe.com/docs/billing/subscriptions/set-up-subscription), [create an invoice](https://stripe.com/docs/billing/invoices/create), and more about [products and prices](https://stripe.com/docs/products-prices/overview). + Price *Price `json:"price"` + // The [quantity](https://stripe.com/docs/subscriptions/quantities) of the plan to which the customer should be subscribed. + Quantity int64 `json:"quantity"` + // The `subscription` this `subscription_item` belongs to. + Subscription string `json:"subscription"` + // The tax rates which apply to this `subscription_item`. When set, the `default_tax_rates` on the subscription do not apply to this `subscription_item`. + TaxRates []*TaxRate `json:"tax_rates"` +} + +// SubscriptionItemList is a list of SubscriptionItems as retrieved from a list endpoint. +type SubscriptionItemList struct { + APIResource + ListMeta + Data []*SubscriptionItem `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/subscriptionitem_service.go b/vendor/github.com/stripe/stripe-go/v82/subscriptionitem_service.go new file mode 100644 index 00000000..257a22fb --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/subscriptionitem_service.go @@ -0,0 +1,85 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1SubscriptionItemService is used to invoke /v1/subscription_items APIs. +type v1SubscriptionItemService struct { + B Backend + Key string +} + +// Adds a new item to an existing subscription. No existing items will be changed or replaced. +func (c v1SubscriptionItemService) Create(ctx context.Context, params *SubscriptionItemCreateParams) (*SubscriptionItem, error) { + if params == nil { + params = &SubscriptionItemCreateParams{} + } + params.Context = ctx + subscriptionitem := &SubscriptionItem{} + err := c.B.Call( + http.MethodPost, "/v1/subscription_items", c.Key, params, subscriptionitem) + return subscriptionitem, err +} + +// Retrieves the subscription item with the given ID. +func (c v1SubscriptionItemService) Retrieve(ctx context.Context, id string, params *SubscriptionItemRetrieveParams) (*SubscriptionItem, error) { + if params == nil { + params = &SubscriptionItemRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/subscription_items/%s", id) + subscriptionitem := &SubscriptionItem{} + err := c.B.Call(http.MethodGet, path, c.Key, params, subscriptionitem) + return subscriptionitem, err +} + +// Updates the plan or quantity of an item on a current subscription. +func (c v1SubscriptionItemService) Update(ctx context.Context, id string, params *SubscriptionItemUpdateParams) (*SubscriptionItem, error) { + if params == nil { + params = &SubscriptionItemUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/subscription_items/%s", id) + subscriptionitem := &SubscriptionItem{} + err := c.B.Call(http.MethodPost, path, c.Key, params, subscriptionitem) + return subscriptionitem, err +} + +// Deletes an item from the subscription. Removing a subscription item from a subscription will not cancel the subscription. +func (c v1SubscriptionItemService) Delete(ctx context.Context, id string, params *SubscriptionItemDeleteParams) (*SubscriptionItem, error) { + if params == nil { + params = &SubscriptionItemDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/subscription_items/%s", id) + subscriptionitem := &SubscriptionItem{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, subscriptionitem) + return subscriptionitem, err +} + +// Returns a list of your subscription items for a given subscription. +func (c v1SubscriptionItemService) List(ctx context.Context, listParams *SubscriptionItemListParams) Seq2[*SubscriptionItem, error] { + if listParams == nil { + listParams = &SubscriptionItemListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*SubscriptionItem, ListContainer, error) { + list := &SubscriptionItemList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/subscription_items", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/subscriptionschedule.go b/vendor/github.com/stripe/stripe-go/v82/subscriptionschedule.go new file mode 100644 index 00000000..95208414 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/subscriptionschedule.go @@ -0,0 +1,1274 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "encoding/json" + "github.com/stripe/stripe-go/v82/form" +) + +// Controls how prorations and invoices for subscriptions are calculated and orchestrated. +type SubscriptionScheduleBillingModeType string + +// List of values that SubscriptionScheduleBillingModeType can take +const ( + SubscriptionScheduleBillingModeTypeClassic SubscriptionScheduleBillingModeType = "classic" + SubscriptionScheduleBillingModeTypeFlexible SubscriptionScheduleBillingModeType = "flexible" +) + +// Possible values are `phase_start` or `automatic`. If `phase_start` then billing cycle anchor of the subscription is set to the start of the phase when entering the phase. If `automatic` then the billing cycle anchor is automatically modified as needed when entering the phase. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). +type SubscriptionScheduleDefaultSettingsBillingCycleAnchor string + +// List of values that SubscriptionScheduleDefaultSettingsBillingCycleAnchor can take +const ( + SubscriptionScheduleDefaultSettingsBillingCycleAnchorAutomatic SubscriptionScheduleDefaultSettingsBillingCycleAnchor = "automatic" + SubscriptionScheduleDefaultSettingsBillingCycleAnchorPhaseStart SubscriptionScheduleDefaultSettingsBillingCycleAnchor = "phase_start" +) + +// Type of the account referenced. +type SubscriptionScheduleDefaultSettingsInvoiceSettingsIssuerType string + +// List of values that SubscriptionScheduleDefaultSettingsInvoiceSettingsIssuerType can take +const ( + SubscriptionScheduleDefaultSettingsInvoiceSettingsIssuerTypeAccount SubscriptionScheduleDefaultSettingsInvoiceSettingsIssuerType = "account" + SubscriptionScheduleDefaultSettingsInvoiceSettingsIssuerTypeSelf SubscriptionScheduleDefaultSettingsInvoiceSettingsIssuerType = "self" +) + +// Behavior of the subscription schedule and underlying subscription when it ends. Possible values are `release` or `cancel` with the default being `release`. `release` will end the subscription schedule and keep the underlying subscription running. `cancel` will end the subscription schedule and cancel the underlying subscription. +type SubscriptionScheduleEndBehavior string + +// List of values that SubscriptionScheduleEndBehavior can take +const ( + SubscriptionScheduleEndBehaviorCancel SubscriptionScheduleEndBehavior = "cancel" + SubscriptionScheduleEndBehaviorNone SubscriptionScheduleEndBehavior = "none" + SubscriptionScheduleEndBehaviorRelease SubscriptionScheduleEndBehavior = "release" + SubscriptionScheduleEndBehaviorRenew SubscriptionScheduleEndBehavior = "renew" +) + +// Possible values are `phase_start` or `automatic`. If `phase_start` then billing cycle anchor of the subscription is set to the start of the phase when entering the phase. If `automatic` then the billing cycle anchor is automatically modified as needed when entering the phase. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). +type SubscriptionSchedulePhaseBillingCycleAnchor string + +// List of values that SubscriptionSchedulePhaseBillingCycleAnchor can take +const ( + SubscriptionSchedulePhaseBillingCycleAnchorAutomatic SubscriptionSchedulePhaseBillingCycleAnchor = "automatic" + SubscriptionSchedulePhaseBillingCycleAnchorPhaseStart SubscriptionSchedulePhaseBillingCycleAnchor = "phase_start" +) + +// Type of the account referenced. +type SubscriptionSchedulePhaseInvoiceSettingsIssuerType string + +// List of values that SubscriptionSchedulePhaseInvoiceSettingsIssuerType can take +const ( + SubscriptionSchedulePhaseInvoiceSettingsIssuerTypeAccount SubscriptionSchedulePhaseInvoiceSettingsIssuerType = "account" + SubscriptionSchedulePhaseInvoiceSettingsIssuerTypeSelf SubscriptionSchedulePhaseInvoiceSettingsIssuerType = "self" +) + +// When transitioning phases, controls how prorations are handled (if any). Possible values are `create_prorations`, `none`, and `always_invoice`. +type SubscriptionSchedulePhaseProrationBehavior string + +// List of values that SubscriptionSchedulePhaseProrationBehavior can take +const ( + SubscriptionSchedulePhaseProrationBehaviorAlwaysInvoice SubscriptionSchedulePhaseProrationBehavior = "always_invoice" + SubscriptionSchedulePhaseProrationBehaviorCreateProrations SubscriptionSchedulePhaseProrationBehavior = "create_prorations" + SubscriptionSchedulePhaseProrationBehaviorNone SubscriptionSchedulePhaseProrationBehavior = "none" +) + +// The present status of the subscription schedule. Possible values are `not_started`, `active`, `completed`, `released`, and `canceled`. You can read more about the different states in our [behavior guide](https://stripe.com/docs/billing/subscriptions/subscription-schedules). +type SubscriptionScheduleStatus string + +// List of values that SubscriptionScheduleStatus can take +const ( + SubscriptionScheduleStatusActive SubscriptionScheduleStatus = "active" + SubscriptionScheduleStatusCanceled SubscriptionScheduleStatus = "canceled" + SubscriptionScheduleStatusCompleted SubscriptionScheduleStatus = "completed" + SubscriptionScheduleStatusNotStarted SubscriptionScheduleStatus = "not_started" + SubscriptionScheduleStatusReleased SubscriptionScheduleStatus = "released" +) + +// Retrieves the list of your subscription schedules. +type SubscriptionScheduleListParams struct { + ListParams `form:"*"` + // Only return subscription schedules that were created canceled the given date interval. + CanceledAt *int64 `form:"canceled_at"` + // Only return subscription schedules that were created canceled the given date interval. + CanceledAtRange *RangeQueryParams `form:"canceled_at"` + // Only return subscription schedules that completed during the given date interval. + CompletedAt *int64 `form:"completed_at"` + // Only return subscription schedules that completed during the given date interval. + CompletedAtRange *RangeQueryParams `form:"completed_at"` + // Only return subscription schedules that were created during the given date interval. + Created *int64 `form:"created"` + // Only return subscription schedules that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Only return subscription schedules for the given customer. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return subscription schedules that were released during the given date interval. + ReleasedAt *int64 `form:"released_at"` + // Only return subscription schedules that were released during the given date interval. + ReleasedAtRange *RangeQueryParams `form:"released_at"` + // Only return subscription schedules that have not started yet. + Scheduled *bool `form:"scheduled"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionScheduleListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Controls how prorations and invoices for subscriptions are calculated and orchestrated. +type SubscriptionScheduleBillingModeParams struct { + Type *string `form:"type"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type SubscriptionScheduleDefaultSettingsBillingThresholdsParams struct { + // Monetary threshold that triggers the subscription to advance to a new billing period + AmountGTE *int64 `form:"amount_gte"` + // Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + ResetBillingCycleAnchor *bool `form:"reset_billing_cycle_anchor"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type SubscriptionScheduleDefaultSettingsInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type SubscriptionScheduleDefaultSettingsInvoiceSettingsParams struct { + // The account tax IDs associated with the subscription schedule. Will be set on invoices generated by the subscription schedule. + AccountTaxIDs []*string `form:"account_tax_ids"` + // Number of days within which a customer must pay invoices generated by this subscription schedule. This value will be `null` for subscription schedules where `collection_method=charge_automatically`. + DaysUntilDue *int64 `form:"days_until_due"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *SubscriptionScheduleDefaultSettingsInvoiceSettingsIssuerParams `form:"issuer"` +} + +// Object representing the subscription schedule's default settings. +type SubscriptionScheduleDefaultSettingsParams struct { + Params `form:"*"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + ApplicationFeePercent *float64 `form:"application_fee_percent,high_precision"` + // Default settings for automatic tax computation. + AutomaticTax *SubscriptionAutomaticTaxParams `form:"automatic_tax"` + // Can be set to `phase_start` to set the anchor to the start of the phase or `automatic` to automatically change it if needed. Cannot be set to `phase_start` if this phase specifies a trial. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + BillingCycleAnchor *string `form:"billing_cycle_anchor"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionScheduleDefaultSettingsBillingThresholdsParams `form:"billing_thresholds"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically` on creation. + CollectionMethod *string `form:"collection_method"` + // ID of the default payment method for the subscription schedule. It must belong to the customer associated with the subscription schedule. If not set, invoices will use the default payment method in the customer's invoice settings. + DefaultPaymentMethod *string `form:"default_payment_method"` + // Subscription description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // All invoices will be billed using the specified settings. + InvoiceSettings *SubscriptionScheduleDefaultSettingsInvoiceSettingsParams `form:"invoice_settings"` + // The account on behalf of which to charge, for each of the associated subscription's invoices. + OnBehalfOf *string `form:"on_behalf_of"` + // The data with which to automatically create a Transfer for each of the associated subscription's invoices. + TransferData *SubscriptionTransferDataParams `form:"transfer_data"` +} + +// The coupons to redeem into discounts for the item. +type SubscriptionSchedulePhaseAddInvoiceItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// A list of prices and quantities that will generate invoice items appended to the next invoice for this phase. You may pass up to 20 items. +type SubscriptionSchedulePhaseAddInvoiceItemParams struct { + // The coupons to redeem into discounts for the item. + Discounts []*SubscriptionSchedulePhaseAddInvoiceItemDiscountParams `form:"discounts"` + // The ID of the price object. One of `price` or `price_data` is required. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *InvoiceItemPriceDataParams `form:"price_data"` + // Quantity for this item. Defaults to 1. + Quantity *int64 `form:"quantity"` + // The tax rates which apply to the item. When set, the `default_tax_rates` do not apply to this item. + TaxRates []*string `form:"tax_rates"` +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type SubscriptionSchedulePhaseAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Automatic tax settings for this phase. +type SubscriptionSchedulePhaseAutomaticTaxParams struct { + // Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *SubscriptionSchedulePhaseAutomaticTaxLiabilityParams `form:"liability"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type SubscriptionSchedulePhaseBillingThresholdsParams struct { + // Monetary threshold that triggers the subscription to advance to a new billing period + AmountGTE *int64 `form:"amount_gte"` + // Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + ResetBillingCycleAnchor *bool `form:"reset_billing_cycle_anchor"` +} + +// The coupons to redeem into discounts for the schedule phase. If not specified, inherits the discount from the subscription's customer. Pass an empty string to avoid inheriting any discounts. +type SubscriptionSchedulePhaseDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type SubscriptionSchedulePhaseInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type SubscriptionSchedulePhaseInvoiceSettingsParams struct { + // The account tax IDs associated with this phase of the subscription schedule. Will be set on invoices generated by this phase of the subscription schedule. + AccountTaxIDs []*string `form:"account_tax_ids"` + // Number of days within which a customer must pay invoices generated by this subscription schedule. This value will be `null` for subscription schedules where `billing=charge_automatically`. + DaysUntilDue *int64 `form:"days_until_due"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *SubscriptionSchedulePhaseInvoiceSettingsIssuerParams `form:"issuer"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type SubscriptionSchedulePhaseItemBillingThresholdsParams struct { + // Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + UsageGTE *int64 `form:"usage_gte"` +} + +// The coupons to redeem into discounts for the subscription item. +type SubscriptionSchedulePhaseItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// List of configuration items, each with an attached price, to apply during this phase of the subscription schedule. +type SubscriptionSchedulePhaseItemParams struct { + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionSchedulePhaseItemBillingThresholdsParams `form:"billing_thresholds"` + // The coupons to redeem into discounts for the subscription item. + Discounts []*SubscriptionSchedulePhaseItemDiscountParams `form:"discounts"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to a configuration item. Metadata on a configuration item will update the underlying subscription item's `metadata` when the phase is entered, adding new keys and replacing existing keys. Individual keys in the subscription item's `metadata` can be unset by posting an empty value to them in the configuration item's `metadata`. To unset all keys in the subscription item's `metadata`, update the subscription item directly or unset every key individually from the configuration item's `metadata`. + Metadata map[string]string `form:"metadata"` + // The plan ID to subscribe to. You may specify the same ID in `plan` and `price`. + Plan *string `form:"plan"` + // The ID of the price object. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + PriceData *SubscriptionItemPriceDataParams `form:"price_data"` + // Quantity for the given price. Can be set only if the price's `usage_type` is `licensed` and not `metered`. + Quantity *int64 `form:"quantity"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionSchedulePhaseItemParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// List representing phases of the subscription schedule. Each phase can be customized to have different durations, plans, and coupons. If there are multiple phases, the `end_date` of one phase will always equal the `start_date` of the next phase. +type SubscriptionSchedulePhaseParams struct { + // A list of prices and quantities that will generate invoice items appended to the next invoice for this phase. You may pass up to 20 items. + AddInvoiceItems []*SubscriptionSchedulePhaseAddInvoiceItemParams `form:"add_invoice_items"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + ApplicationFeePercent *float64 `form:"application_fee_percent"` + // Automatic tax settings for this phase. + AutomaticTax *SubscriptionSchedulePhaseAutomaticTaxParams `form:"automatic_tax"` + // Can be set to `phase_start` to set the anchor to the start of the phase or `automatic` to automatically change it if needed. Cannot be set to `phase_start` if this phase specifies a trial. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + BillingCycleAnchor *string `form:"billing_cycle_anchor"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionSchedulePhaseBillingThresholdsParams `form:"billing_thresholds"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically` on creation. + CollectionMethod *string `form:"collection_method"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // ID of the default payment method for the subscription schedule. It must belong to the customer associated with the subscription schedule. If not set, invoices will use the default payment method in the customer's invoice settings. + DefaultPaymentMethod *string `form:"default_payment_method"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will set the Subscription's [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates), which means they will be the Invoice's [`default_tax_rates`](https://stripe.com/docs/api/invoices/create#create_invoice-default_tax_rates) for any Invoices issued by the Subscription during this Phase. + DefaultTaxRates []*string `form:"default_tax_rates"` + // Subscription description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // The coupons to redeem into discounts for the schedule phase. If not specified, inherits the discount from the subscription's customer. Pass an empty string to avoid inheriting any discounts. + Discounts []*SubscriptionSchedulePhaseDiscountParams `form:"discounts"` + // The date at which this phase of the subscription schedule ends. If set, `iterations` must not be set. + EndDate *int64 `form:"end_date"` + EndDateNow *bool `form:"-"` // See custom AppendTo + // All invoices will be billed using the specified settings. + InvoiceSettings *SubscriptionSchedulePhaseInvoiceSettingsParams `form:"invoice_settings"` + // List of configuration items, each with an attached price, to apply during this phase of the subscription schedule. + Items []*SubscriptionSchedulePhaseItemParams `form:"items"` + // Integer representing the multiplier applied to the price interval. For example, `iterations=2` applied to a price with `interval=month` and `interval_count=3` results in a phase of duration `2 * 3 months = 6 months`. If set, `end_date` must not be set. + Iterations *int64 `form:"iterations"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to a phase. Metadata on a schedule's phase will update the underlying subscription's `metadata` when the phase is entered, adding new keys and replacing existing keys in the subscription's `metadata`. Individual keys in the subscription's `metadata` can be unset by posting an empty value to them in the phase's `metadata`. To unset all keys in the subscription's `metadata`, update the subscription directly or unset every key individually from the phase's `metadata`. + Metadata map[string]string `form:"metadata"` + // The account on behalf of which to charge, for each of the associated subscription's invoices. + OnBehalfOf *string `form:"on_behalf_of"` + // Controls whether the subscription schedule should create [prorations](https://stripe.com/docs/billing/subscriptions/prorations) when transitioning to this phase if there is a difference in billing configuration. It's different from the request-level [proration_behavior](https://stripe.com/docs/api/subscription_schedules/update#update_subscription_schedule-proration_behavior) parameter which controls what happens if the update request affects the billing configuration (item price, quantity, etc.) of the current phase. + ProrationBehavior *string `form:"proration_behavior"` + // The date at which this phase of the subscription schedule starts or `now`. Must be set on the first phase. + StartDate *int64 `form:"start_date"` + StartDateNow *bool `form:"-"` // See custom AppendTo + // The data with which to automatically create a Transfer for each of the associated subscription's invoices. + TransferData *SubscriptionTransferDataParams `form:"transfer_data"` + // If set to true the entire phase is counted as a trial and the customer will not be charged for any fees. + Trial *bool `form:"trial"` + // Sets the phase to trialing from the start date to this date. Must be before the phase end date, can not be combined with `trial` + TrialEnd *int64 `form:"trial_end"` + TrialEndNow *bool `form:"-"` // See custom AppendTo +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionSchedulePhaseParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// AppendTo implements custom encoding logic for SubscriptionSchedulePhaseParams. +func (p *SubscriptionSchedulePhaseParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.EndDateNow) { + body.Add(form.FormatKey(append(keyParts, "end_date")), "now") + } + if BoolValue(p.TrialEndNow) { + body.Add(form.FormatKey(append(keyParts, "trial_end")), "now") + } + if BoolValue(p.StartDateNow) { + body.Add(form.FormatKey(append(keyParts, "start_date")), "now") + } +} + +// Creates a new subscription schedule object. Each customer can have up to 500 active or scheduled subscriptions. +type SubscriptionScheduleParams struct { + Params `form:"*"` + // Controls how prorations and invoices for subscriptions are calculated and orchestrated. + BillingMode *SubscriptionScheduleBillingModeParams `form:"billing_mode"` + // The identifier of the customer to create the subscription schedule for. + Customer *string `form:"customer"` + // Object representing the subscription schedule's default settings. + DefaultSettings *SubscriptionScheduleDefaultSettingsParams `form:"default_settings"` + // Behavior of the subscription schedule and underlying subscription when it ends. Possible values are `release` or `cancel` with the default being `release`. `release` will end the subscription schedule and keep the underlying subscription running. `cancel` will end the subscription schedule and cancel the underlying subscription. + EndBehavior *string `form:"end_behavior"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Migrate an existing subscription to be managed by a subscription schedule. If this parameter is set, a subscription schedule will be created using the subscription's item(s), set to auto-renew using the subscription's interval. When using this parameter, other parameters (such as phase values) cannot be set. To create a subscription schedule with other modifications, we recommend making two separate API calls. + FromSubscription *string `form:"from_subscription"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // List representing phases of the subscription schedule. Each phase can be customized to have different durations, plans, and coupons. If there are multiple phases, the `end_date` of one phase will always equal the `start_date` of the next phase. Note that past phases can be omitted. + Phases []*SubscriptionSchedulePhaseParams `form:"phases"` + // If the update changes the billing configuration (item price, quantity, etc.) of the current phase, indicates how prorations from this change should be handled. The default value is `create_prorations`. + ProrationBehavior *string `form:"proration_behavior"` + // When the subscription schedule starts. We recommend using `now` so that it starts the subscription immediately. You can also use a Unix timestamp to backdate the subscription so that it starts on a past date, or set a future date for the subscription to start on. + StartDate *int64 `form:"start_date"` + StartDateNow *bool `form:"-"` // See custom AppendTo +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionScheduleParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionScheduleParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// AppendTo implements custom encoding logic for SubscriptionScheduleParams. +func (p *SubscriptionScheduleParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.StartDateNow) { + body.Add(form.FormatKey(append(keyParts, "start_date")), "now") + } +} + +// Cancels a subscription schedule and its associated subscription immediately (if the subscription schedule has an active subscription). A subscription schedule can only be canceled if its status is not_started or active. +type SubscriptionScheduleCancelParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // If the subscription schedule is `active`, indicates if a final invoice will be generated that contains any un-invoiced metered usage and new/pending proration invoice items. Defaults to `true`. + InvoiceNow *bool `form:"invoice_now"` + // If the subscription schedule is `active`, indicates if the cancellation should be prorated. Defaults to `true`. + Prorate *bool `form:"prorate"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionScheduleCancelParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Releases the subscription schedule immediately, which will stop scheduling of its phases, but leave any existing subscription in place. A schedule can only be released if its status is not_started or active. If the subscription schedule is currently associated with a subscription, releasing it will remove its subscription property and set the subscription's ID to the released_subscription property. +type SubscriptionScheduleReleaseParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Keep any cancellation on the subscription that the schedule has set + PreserveCancelDate *bool `form:"preserve_cancel_date"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionScheduleReleaseParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Controls how prorations and invoices for subscriptions are calculated and orchestrated. +type SubscriptionScheduleCreateBillingModeParams struct { + Type *string `form:"type"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type SubscriptionScheduleCreateDefaultSettingsBillingThresholdsParams struct { + // Monetary threshold that triggers the subscription to advance to a new billing period + AmountGTE *int64 `form:"amount_gte"` + // Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + ResetBillingCycleAnchor *bool `form:"reset_billing_cycle_anchor"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type SubscriptionScheduleCreateDefaultSettingsInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type SubscriptionScheduleCreateDefaultSettingsInvoiceSettingsParams struct { + // The account tax IDs associated with the subscription schedule. Will be set on invoices generated by the subscription schedule. + AccountTaxIDs []*string `form:"account_tax_ids"` + // Number of days within which a customer must pay invoices generated by this subscription schedule. This value will be `null` for subscription schedules where `collection_method=charge_automatically`. + DaysUntilDue *int64 `form:"days_until_due"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *SubscriptionScheduleCreateDefaultSettingsInvoiceSettingsIssuerParams `form:"issuer"` +} + +// Object representing the subscription schedule's default settings. +type SubscriptionScheduleCreateDefaultSettingsParams struct { + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + ApplicationFeePercent *float64 `form:"application_fee_percent,high_precision"` + // Default settings for automatic tax computation. + AutomaticTax *SubscriptionAutomaticTaxParams `form:"automatic_tax"` + // Can be set to `phase_start` to set the anchor to the start of the phase or `automatic` to automatically change it if needed. Cannot be set to `phase_start` if this phase specifies a trial. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + BillingCycleAnchor *string `form:"billing_cycle_anchor"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionScheduleCreateDefaultSettingsBillingThresholdsParams `form:"billing_thresholds"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically` on creation. + CollectionMethod *string `form:"collection_method"` + // ID of the default payment method for the subscription schedule. It must belong to the customer associated with the subscription schedule. If not set, invoices will use the default payment method in the customer's invoice settings. + DefaultPaymentMethod *string `form:"default_payment_method"` + // Subscription description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // All invoices will be billed using the specified settings. + InvoiceSettings *SubscriptionScheduleCreateDefaultSettingsInvoiceSettingsParams `form:"invoice_settings"` + // The account on behalf of which to charge, for each of the associated subscription's invoices. + OnBehalfOf *string `form:"on_behalf_of"` + // The data with which to automatically create a Transfer for each of the associated subscription's invoices. + TransferData *SubscriptionTransferDataParams `form:"transfer_data"` +} + +// The coupons to redeem into discounts for the item. +type SubscriptionScheduleCreatePhaseAddInvoiceItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// A list of prices and quantities that will generate invoice items appended to the next invoice for this phase. You may pass up to 20 items. +type SubscriptionScheduleCreatePhaseAddInvoiceItemParams struct { + // The coupons to redeem into discounts for the item. + Discounts []*SubscriptionScheduleCreatePhaseAddInvoiceItemDiscountParams `form:"discounts"` + // The ID of the price object. One of `price` or `price_data` is required. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *InvoiceItemPriceDataParams `form:"price_data"` + // Quantity for this item. Defaults to 1. + Quantity *int64 `form:"quantity"` + // The tax rates which apply to the item. When set, the `default_tax_rates` do not apply to this item. + TaxRates []*string `form:"tax_rates"` +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type SubscriptionScheduleCreatePhaseAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Automatic tax settings for this phase. +type SubscriptionScheduleCreatePhaseAutomaticTaxParams struct { + // Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *SubscriptionScheduleCreatePhaseAutomaticTaxLiabilityParams `form:"liability"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type SubscriptionScheduleCreatePhaseBillingThresholdsParams struct { + // Monetary threshold that triggers the subscription to advance to a new billing period + AmountGTE *int64 `form:"amount_gte"` + // Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + ResetBillingCycleAnchor *bool `form:"reset_billing_cycle_anchor"` +} + +// The coupons to redeem into discounts for the schedule phase. If not specified, inherits the discount from the subscription's customer. Pass an empty string to avoid inheriting any discounts. +type SubscriptionScheduleCreatePhaseDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type SubscriptionScheduleCreatePhaseInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type SubscriptionScheduleCreatePhaseInvoiceSettingsParams struct { + // The account tax IDs associated with this phase of the subscription schedule. Will be set on invoices generated by this phase of the subscription schedule. + AccountTaxIDs []*string `form:"account_tax_ids"` + // Number of days within which a customer must pay invoices generated by this subscription schedule. This value will be `null` for subscription schedules where `billing=charge_automatically`. + DaysUntilDue *int64 `form:"days_until_due"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *SubscriptionScheduleCreatePhaseInvoiceSettingsIssuerParams `form:"issuer"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type SubscriptionScheduleCreatePhaseItemBillingThresholdsParams struct { + // Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + UsageGTE *int64 `form:"usage_gte"` +} + +// The coupons to redeem into discounts for the subscription item. +type SubscriptionScheduleCreatePhaseItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// List of configuration items, each with an attached price, to apply during this phase of the subscription schedule. +type SubscriptionScheduleCreatePhaseItemParams struct { + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionScheduleCreatePhaseItemBillingThresholdsParams `form:"billing_thresholds"` + // The coupons to redeem into discounts for the subscription item. + Discounts []*SubscriptionScheduleCreatePhaseItemDiscountParams `form:"discounts"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to a configuration item. Metadata on a configuration item will update the underlying subscription item's `metadata` when the phase is entered, adding new keys and replacing existing keys. Individual keys in the subscription item's `metadata` can be unset by posting an empty value to them in the configuration item's `metadata`. To unset all keys in the subscription item's `metadata`, update the subscription item directly or unset every key individually from the configuration item's `metadata`. + Metadata map[string]string `form:"metadata"` + // The plan ID to subscribe to. You may specify the same ID in `plan` and `price`. + Plan *string `form:"plan"` + // The ID of the price object. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + PriceData *SubscriptionItemPriceDataParams `form:"price_data"` + // Quantity for the given price. Can be set only if the price's `usage_type` is `licensed` and not `metered`. + Quantity *int64 `form:"quantity"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionScheduleCreatePhaseItemParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// List representing phases of the subscription schedule. Each phase can be customized to have different durations, plans, and coupons. If there are multiple phases, the `end_date` of one phase will always equal the `start_date` of the next phase. +type SubscriptionScheduleCreatePhaseParams struct { + // A list of prices and quantities that will generate invoice items appended to the next invoice for this phase. You may pass up to 20 items. + AddInvoiceItems []*SubscriptionScheduleCreatePhaseAddInvoiceItemParams `form:"add_invoice_items"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + ApplicationFeePercent *float64 `form:"application_fee_percent"` + // Automatic tax settings for this phase. + AutomaticTax *SubscriptionScheduleCreatePhaseAutomaticTaxParams `form:"automatic_tax"` + // Can be set to `phase_start` to set the anchor to the start of the phase or `automatic` to automatically change it if needed. Cannot be set to `phase_start` if this phase specifies a trial. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + BillingCycleAnchor *string `form:"billing_cycle_anchor"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionScheduleCreatePhaseBillingThresholdsParams `form:"billing_thresholds"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically` on creation. + CollectionMethod *string `form:"collection_method"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // ID of the default payment method for the subscription schedule. It must belong to the customer associated with the subscription schedule. If not set, invoices will use the default payment method in the customer's invoice settings. + DefaultPaymentMethod *string `form:"default_payment_method"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will set the Subscription's [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates), which means they will be the Invoice's [`default_tax_rates`](https://stripe.com/docs/api/invoices/create#create_invoice-default_tax_rates) for any Invoices issued by the Subscription during this Phase. + DefaultTaxRates []*string `form:"default_tax_rates"` + // Subscription description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // The coupons to redeem into discounts for the schedule phase. If not specified, inherits the discount from the subscription's customer. Pass an empty string to avoid inheriting any discounts. + Discounts []*SubscriptionScheduleCreatePhaseDiscountParams `form:"discounts"` + // The date at which this phase of the subscription schedule ends. If set, `iterations` must not be set. + EndDate *int64 `form:"end_date"` + // All invoices will be billed using the specified settings. + InvoiceSettings *SubscriptionScheduleCreatePhaseInvoiceSettingsParams `form:"invoice_settings"` + // List of configuration items, each with an attached price, to apply during this phase of the subscription schedule. + Items []*SubscriptionScheduleCreatePhaseItemParams `form:"items"` + // Integer representing the multiplier applied to the price interval. For example, `iterations=2` applied to a price with `interval=month` and `interval_count=3` results in a phase of duration `2 * 3 months = 6 months`. If set, `end_date` must not be set. + Iterations *int64 `form:"iterations"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to a phase. Metadata on a schedule's phase will update the underlying subscription's `metadata` when the phase is entered, adding new keys and replacing existing keys in the subscription's `metadata`. Individual keys in the subscription's `metadata` can be unset by posting an empty value to them in the phase's `metadata`. To unset all keys in the subscription's `metadata`, update the subscription directly or unset every key individually from the phase's `metadata`. + Metadata map[string]string `form:"metadata"` + // The account on behalf of which to charge, for each of the associated subscription's invoices. + OnBehalfOf *string `form:"on_behalf_of"` + // Controls whether the subscription schedule should create [prorations](https://stripe.com/docs/billing/subscriptions/prorations) when transitioning to this phase if there is a difference in billing configuration. It's different from the request-level [proration_behavior](https://stripe.com/docs/api/subscription_schedules/update#update_subscription_schedule-proration_behavior) parameter which controls what happens if the update request affects the billing configuration (item price, quantity, etc.) of the current phase. + ProrationBehavior *string `form:"proration_behavior"` + // The data with which to automatically create a Transfer for each of the associated subscription's invoices. + TransferData *SubscriptionTransferDataParams `form:"transfer_data"` + // If set to true the entire phase is counted as a trial and the customer will not be charged for any fees. + Trial *bool `form:"trial"` + // Sets the phase to trialing from the start date to this date. Must be before the phase end date, can not be combined with `trial` + TrialEnd *int64 `form:"trial_end"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionScheduleCreatePhaseParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Creates a new subscription schedule object. Each customer can have up to 500 active or scheduled subscriptions. +type SubscriptionScheduleCreateParams struct { + Params `form:"*"` + // Controls how prorations and invoices for subscriptions are calculated and orchestrated. + BillingMode *SubscriptionScheduleCreateBillingModeParams `form:"billing_mode"` + // The identifier of the customer to create the subscription schedule for. + Customer *string `form:"customer"` + // Object representing the subscription schedule's default settings. + DefaultSettings *SubscriptionScheduleCreateDefaultSettingsParams `form:"default_settings"` + // Behavior of the subscription schedule and underlying subscription when it ends. Possible values are `release` or `cancel` with the default being `release`. `release` will end the subscription schedule and keep the underlying subscription running. `cancel` will end the subscription schedule and cancel the underlying subscription. + EndBehavior *string `form:"end_behavior"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Migrate an existing subscription to be managed by a subscription schedule. If this parameter is set, a subscription schedule will be created using the subscription's item(s), set to auto-renew using the subscription's interval. When using this parameter, other parameters (such as phase values) cannot be set. To create a subscription schedule with other modifications, we recommend making two separate API calls. + FromSubscription *string `form:"from_subscription"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // List representing phases of the subscription schedule. Each phase can be customized to have different durations, plans, and coupons. If there are multiple phases, the `end_date` of one phase will always equal the `start_date` of the next phase. + Phases []*SubscriptionScheduleCreatePhaseParams `form:"phases"` + // When the subscription schedule starts. We recommend using `now` so that it starts the subscription immediately. You can also use a Unix timestamp to backdate the subscription so that it starts on a past date, or set a future date for the subscription to start on. + StartDate *int64 `form:"start_date"` + StartDateNow *bool `form:"-"` // See custom AppendTo +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionScheduleCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionScheduleCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// AppendTo implements custom encoding logic for SubscriptionScheduleCreateParams. +func (p *SubscriptionScheduleCreateParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.StartDateNow) { + body.Add(form.FormatKey(append(keyParts, "start_date")), "now") + } +} + +// Retrieves the details of an existing subscription schedule. You only need to supply the unique subscription schedule identifier that was returned upon subscription schedule creation. +type SubscriptionScheduleRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionScheduleRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type SubscriptionScheduleUpdateDefaultSettingsBillingThresholdsParams struct { + // Monetary threshold that triggers the subscription to advance to a new billing period + AmountGTE *int64 `form:"amount_gte"` + // Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + ResetBillingCycleAnchor *bool `form:"reset_billing_cycle_anchor"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type SubscriptionScheduleUpdateDefaultSettingsInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type SubscriptionScheduleUpdateDefaultSettingsInvoiceSettingsParams struct { + // The account tax IDs associated with the subscription schedule. Will be set on invoices generated by the subscription schedule. + AccountTaxIDs []*string `form:"account_tax_ids"` + // Number of days within which a customer must pay invoices generated by this subscription schedule. This value will be `null` for subscription schedules where `collection_method=charge_automatically`. + DaysUntilDue *int64 `form:"days_until_due"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *SubscriptionScheduleUpdateDefaultSettingsInvoiceSettingsIssuerParams `form:"issuer"` +} + +// Object representing the subscription schedule's default settings. +type SubscriptionScheduleUpdateDefaultSettingsParams struct { + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + ApplicationFeePercent *float64 `form:"application_fee_percent,high_precision"` + // Default settings for automatic tax computation. + AutomaticTax *SubscriptionAutomaticTaxParams `form:"automatic_tax"` + // Can be set to `phase_start` to set the anchor to the start of the phase or `automatic` to automatically change it if needed. Cannot be set to `phase_start` if this phase specifies a trial. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + BillingCycleAnchor *string `form:"billing_cycle_anchor"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionScheduleUpdateDefaultSettingsBillingThresholdsParams `form:"billing_thresholds"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically` on creation. + CollectionMethod *string `form:"collection_method"` + // ID of the default payment method for the subscription schedule. It must belong to the customer associated with the subscription schedule. If not set, invoices will use the default payment method in the customer's invoice settings. + DefaultPaymentMethod *string `form:"default_payment_method"` + // Subscription description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // All invoices will be billed using the specified settings. + InvoiceSettings *SubscriptionScheduleUpdateDefaultSettingsInvoiceSettingsParams `form:"invoice_settings"` + // The account on behalf of which to charge, for each of the associated subscription's invoices. + OnBehalfOf *string `form:"on_behalf_of"` + // The data with which to automatically create a Transfer for each of the associated subscription's invoices. + TransferData *SubscriptionTransferDataParams `form:"transfer_data"` +} + +// The coupons to redeem into discounts for the item. +type SubscriptionScheduleUpdatePhaseAddInvoiceItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// A list of prices and quantities that will generate invoice items appended to the next invoice for this phase. You may pass up to 20 items. +type SubscriptionScheduleUpdatePhaseAddInvoiceItemParams struct { + // The coupons to redeem into discounts for the item. + Discounts []*SubscriptionScheduleUpdatePhaseAddInvoiceItemDiscountParams `form:"discounts"` + // The ID of the price object. One of `price` or `price_data` is required. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + PriceData *InvoiceItemPriceDataParams `form:"price_data"` + // Quantity for this item. Defaults to 1. + Quantity *int64 `form:"quantity"` + // The tax rates which apply to the item. When set, the `default_tax_rates` do not apply to this item. + TaxRates []*string `form:"tax_rates"` +} + +// The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. +type SubscriptionScheduleUpdatePhaseAutomaticTaxLiabilityParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// Automatic tax settings for this phase. +type SubscriptionScheduleUpdatePhaseAutomaticTaxParams struct { + // Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + Enabled *bool `form:"enabled"` + // The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + Liability *SubscriptionScheduleUpdatePhaseAutomaticTaxLiabilityParams `form:"liability"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type SubscriptionScheduleUpdatePhaseBillingThresholdsParams struct { + // Monetary threshold that triggers the subscription to advance to a new billing period + AmountGTE *int64 `form:"amount_gte"` + // Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + ResetBillingCycleAnchor *bool `form:"reset_billing_cycle_anchor"` +} + +// The coupons to redeem into discounts for the schedule phase. If not specified, inherits the discount from the subscription's customer. Pass an empty string to avoid inheriting any discounts. +type SubscriptionScheduleUpdatePhaseDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type SubscriptionScheduleUpdatePhaseInvoiceSettingsIssuerParams struct { + // The connected account being referenced when `type` is `account`. + Account *string `form:"account"` + // Type of the account referenced in the request. + Type *string `form:"type"` +} + +// All invoices will be billed using the specified settings. +type SubscriptionScheduleUpdatePhaseInvoiceSettingsParams struct { + // The account tax IDs associated with this phase of the subscription schedule. Will be set on invoices generated by this phase of the subscription schedule. + AccountTaxIDs []*string `form:"account_tax_ids"` + // Number of days within which a customer must pay invoices generated by this subscription schedule. This value will be `null` for subscription schedules where `billing=charge_automatically`. + DaysUntilDue *int64 `form:"days_until_due"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *SubscriptionScheduleUpdatePhaseInvoiceSettingsIssuerParams `form:"issuer"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. +type SubscriptionScheduleUpdatePhaseItemBillingThresholdsParams struct { + // Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + UsageGTE *int64 `form:"usage_gte"` +} + +// The coupons to redeem into discounts for the subscription item. +type SubscriptionScheduleUpdatePhaseItemDiscountParams struct { + // ID of the coupon to create a new discount for. + Coupon *string `form:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *string `form:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *string `form:"promotion_code"` +} + +// List of configuration items, each with an attached price, to apply during this phase of the subscription schedule. +type SubscriptionScheduleUpdatePhaseItemParams struct { + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionScheduleUpdatePhaseItemBillingThresholdsParams `form:"billing_thresholds"` + // The coupons to redeem into discounts for the subscription item. + Discounts []*SubscriptionScheduleUpdatePhaseItemDiscountParams `form:"discounts"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to a configuration item. Metadata on a configuration item will update the underlying subscription item's `metadata` when the phase is entered, adding new keys and replacing existing keys. Individual keys in the subscription item's `metadata` can be unset by posting an empty value to them in the configuration item's `metadata`. To unset all keys in the subscription item's `metadata`, update the subscription item directly or unset every key individually from the configuration item's `metadata`. + Metadata map[string]string `form:"metadata"` + // The plan ID to subscribe to. You may specify the same ID in `plan` and `price`. + Plan *string `form:"plan"` + // The ID of the price object. + Price *string `form:"price"` + // Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + PriceData *SubscriptionItemPriceDataParams `form:"price_data"` + // Quantity for the given price. Can be set only if the price's `usage_type` is `licensed` and not `metered`. + Quantity *int64 `form:"quantity"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + TaxRates []*string `form:"tax_rates"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionScheduleUpdatePhaseItemParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// List representing phases of the subscription schedule. Each phase can be customized to have different durations, plans, and coupons. If there are multiple phases, the `end_date` of one phase will always equal the `start_date` of the next phase. Note that past phases can be omitted. +type SubscriptionScheduleUpdatePhaseParams struct { + // A list of prices and quantities that will generate invoice items appended to the next invoice for this phase. You may pass up to 20 items. + AddInvoiceItems []*SubscriptionScheduleUpdatePhaseAddInvoiceItemParams `form:"add_invoice_items"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + ApplicationFeePercent *float64 `form:"application_fee_percent"` + // Automatic tax settings for this phase. + AutomaticTax *SubscriptionScheduleUpdatePhaseAutomaticTaxParams `form:"automatic_tax"` + // Can be set to `phase_start` to set the anchor to the start of the phase or `automatic` to automatically change it if needed. Cannot be set to `phase_start` if this phase specifies a trial. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + BillingCycleAnchor *string `form:"billing_cycle_anchor"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + BillingThresholds *SubscriptionScheduleUpdatePhaseBillingThresholdsParams `form:"billing_thresholds"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically` on creation. + CollectionMethod *string `form:"collection_method"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // ID of the default payment method for the subscription schedule. It must belong to the customer associated with the subscription schedule. If not set, invoices will use the default payment method in the customer's invoice settings. + DefaultPaymentMethod *string `form:"default_payment_method"` + // A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will set the Subscription's [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates), which means they will be the Invoice's [`default_tax_rates`](https://stripe.com/docs/api/invoices/create#create_invoice-default_tax_rates) for any Invoices issued by the Subscription during this Phase. + DefaultTaxRates []*string `form:"default_tax_rates"` + // Subscription description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description *string `form:"description"` + // The coupons to redeem into discounts for the schedule phase. If not specified, inherits the discount from the subscription's customer. Pass an empty string to avoid inheriting any discounts. + Discounts []*SubscriptionScheduleUpdatePhaseDiscountParams `form:"discounts"` + // The date at which this phase of the subscription schedule ends. If set, `iterations` must not be set. + EndDate *int64 `form:"end_date"` + EndDateNow *bool `form:"-"` // See custom AppendTo + // All invoices will be billed using the specified settings. + InvoiceSettings *SubscriptionScheduleUpdatePhaseInvoiceSettingsParams `form:"invoice_settings"` + // List of configuration items, each with an attached price, to apply during this phase of the subscription schedule. + Items []*SubscriptionScheduleUpdatePhaseItemParams `form:"items"` + // Integer representing the multiplier applied to the price interval. For example, `iterations=2` applied to a price with `interval=month` and `interval_count=3` results in a phase of duration `2 * 3 months = 6 months`. If set, `end_date` must not be set. + Iterations *int64 `form:"iterations"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to a phase. Metadata on a schedule's phase will update the underlying subscription's `metadata` when the phase is entered, adding new keys and replacing existing keys in the subscription's `metadata`. Individual keys in the subscription's `metadata` can be unset by posting an empty value to them in the phase's `metadata`. To unset all keys in the subscription's `metadata`, update the subscription directly or unset every key individually from the phase's `metadata`. + Metadata map[string]string `form:"metadata"` + // The account on behalf of which to charge, for each of the associated subscription's invoices. + OnBehalfOf *string `form:"on_behalf_of"` + // Controls whether the subscription schedule should create [prorations](https://stripe.com/docs/billing/subscriptions/prorations) when transitioning to this phase if there is a difference in billing configuration. It's different from the request-level [proration_behavior](https://stripe.com/docs/api/subscription_schedules/update#update_subscription_schedule-proration_behavior) parameter which controls what happens if the update request affects the billing configuration (item price, quantity, etc.) of the current phase. + ProrationBehavior *string `form:"proration_behavior"` + // The date at which this phase of the subscription schedule starts or `now`. Must be set on the first phase. + StartDate *int64 `form:"start_date"` + StartDateNow *bool `form:"-"` // See custom AppendTo + // The data with which to automatically create a Transfer for each of the associated subscription's invoices. + TransferData *SubscriptionTransferDataParams `form:"transfer_data"` + // If set to true the entire phase is counted as a trial and the customer will not be charged for any fees. + Trial *bool `form:"trial"` + // Sets the phase to trialing from the start date to this date. Must be before the phase end date, can not be combined with `trial` + TrialEnd *int64 `form:"trial_end"` + TrialEndNow *bool `form:"-"` // See custom AppendTo +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionScheduleUpdatePhaseParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// AppendTo implements custom encoding logic for SubscriptionScheduleUpdatePhaseParams. +func (p *SubscriptionScheduleUpdatePhaseParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.EndDateNow) { + body.Add(form.FormatKey(append(keyParts, "end_date")), "now") + } + if BoolValue(p.StartDateNow) { + body.Add(form.FormatKey(append(keyParts, "start_date")), "now") + } + if BoolValue(p.TrialEndNow) { + body.Add(form.FormatKey(append(keyParts, "trial_end")), "now") + } +} + +// Updates an existing subscription schedule. +type SubscriptionScheduleUpdateParams struct { + Params `form:"*"` + // Object representing the subscription schedule's default settings. + DefaultSettings *SubscriptionScheduleUpdateDefaultSettingsParams `form:"default_settings"` + // Behavior of the subscription schedule and underlying subscription when it ends. Possible values are `release` or `cancel` with the default being `release`. `release` will end the subscription schedule and keep the underlying subscription running. `cancel` will end the subscription schedule and cancel the underlying subscription. + EndBehavior *string `form:"end_behavior"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // List representing phases of the subscription schedule. Each phase can be customized to have different durations, plans, and coupons. If there are multiple phases, the `end_date` of one phase will always equal the `start_date` of the next phase. Note that past phases can be omitted. + Phases []*SubscriptionScheduleUpdatePhaseParams `form:"phases"` + // If the update changes the billing configuration (item price, quantity, etc.) of the current phase, indicates how prorations from this change should be handled. The default value is `create_prorations`. + ProrationBehavior *string `form:"proration_behavior"` +} + +// AddExpand appends a new field to expand. +func (p *SubscriptionScheduleUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *SubscriptionScheduleUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The billing mode of the subscription. +type SubscriptionScheduleBillingMode struct { + // Controls how prorations and invoices for subscriptions are calculated and orchestrated. + Type SubscriptionScheduleBillingModeType `json:"type"` + // Details on when the current billing_mode was adopted. + UpdatedAt int64 `json:"updated_at"` +} + +// Object representing the start and end dates for the current phase of the subscription schedule, if it is `active`. +type SubscriptionScheduleCurrentPhase struct { + // The end of this phase of the subscription schedule. + EndDate int64 `json:"end_date"` + // The start of this phase of the subscription schedule. + StartDate int64 `json:"start_date"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period +type SubscriptionScheduleDefaultSettingsBillingThresholds struct { + // Monetary threshold that triggers the subscription to create an invoice + AmountGTE int64 `json:"amount_gte"` + // Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. This value may not be `true` if the subscription contains items with plans that have `aggregate_usage=last_ever`. + ResetBillingCycleAnchor bool `json:"reset_billing_cycle_anchor"` +} +type SubscriptionScheduleDefaultSettingsInvoiceSettingsIssuer struct { + // The connected account being referenced when `type` is `account`. + Account *Account `json:"account"` + // Type of the account referenced. + Type SubscriptionScheduleDefaultSettingsInvoiceSettingsIssuerType `json:"type"` +} +type SubscriptionScheduleDefaultSettingsInvoiceSettings struct { + // The account tax IDs associated with the subscription schedule. Will be set on invoices generated by the subscription schedule. + AccountTaxIDs []*TaxID `json:"account_tax_ids"` + // Number of days within which a customer must pay invoices generated by this subscription schedule. This value will be `null` for subscription schedules where `billing=charge_automatically`. + DaysUntilDue int64 `json:"days_until_due"` + Issuer *SubscriptionScheduleDefaultSettingsInvoiceSettingsIssuer `json:"issuer"` +} +type SubscriptionScheduleDefaultSettings struct { + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account during this phase of the schedule. + ApplicationFeePercent float64 `json:"application_fee_percent"` + AutomaticTax *SubscriptionAutomaticTax `json:"automatic_tax"` + // Possible values are `phase_start` or `automatic`. If `phase_start` then billing cycle anchor of the subscription is set to the start of the phase when entering the phase. If `automatic` then the billing cycle anchor is automatically modified as needed when entering the phase. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + BillingCycleAnchor SubscriptionScheduleDefaultSettingsBillingCycleAnchor `json:"billing_cycle_anchor"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period + BillingThresholds *SubscriptionScheduleDefaultSettingsBillingThresholds `json:"billing_thresholds"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. + CollectionMethod *SubscriptionCollectionMethod `json:"collection_method"` + // ID of the default payment method for the subscription schedule. If not set, invoices will use the default payment method in the customer's invoice settings. + DefaultPaymentMethod *PaymentMethod `json:"default_payment_method"` + // Subscription description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description string `json:"description"` + InvoiceSettings *SubscriptionScheduleDefaultSettingsInvoiceSettings `json:"invoice_settings"` + // The account (if any) the charge was made on behalf of for charges associated with the schedule's subscription. See the Connect documentation for details. + OnBehalfOf *Account `json:"on_behalf_of"` + // The account (if any) the associated subscription's payments will be attributed to for tax reporting, and where funds from each payment will be transferred to for each of the subscription's invoices. + TransferData *SubscriptionTransferData `json:"transfer_data"` +} + +// The stackable discounts that will be applied to the item. +type SubscriptionSchedulePhaseAddInvoiceItemDiscount struct { + // ID of the coupon to create a new discount for. + Coupon *Coupon `json:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *Discount `json:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *PromotionCode `json:"promotion_code"` +} + +// A list of prices and quantities that will generate invoice items appended to the next invoice for this phase. +type SubscriptionSchedulePhaseAddInvoiceItem struct { + // The stackable discounts that will be applied to the item. + Discounts []*SubscriptionSchedulePhaseAddInvoiceItemDiscount `json:"discounts"` + // ID of the price used to generate the invoice item. + Price *Price `json:"price"` + // The quantity of the invoice item. + Quantity int64 `json:"quantity"` + // The tax rates which apply to the item. When set, the `default_tax_rates` do not apply to this item. + TaxRates []*TaxRate `json:"tax_rates"` +} + +// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period +type SubscriptionSchedulePhaseBillingThresholds struct { + // Monetary threshold that triggers the subscription to create an invoice + AmountGTE int64 `json:"amount_gte"` + // Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. This value may not be `true` if the subscription contains items with plans that have `aggregate_usage=last_ever`. + ResetBillingCycleAnchor bool `json:"reset_billing_cycle_anchor"` +} + +// The stackable discounts that will be applied to the subscription on this phase. Subscription item discounts are applied before subscription discounts. +type SubscriptionSchedulePhaseDiscount struct { + // ID of the coupon to create a new discount for. + Coupon *Coupon `json:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *Discount `json:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *PromotionCode `json:"promotion_code"` +} + +// The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. +type SubscriptionSchedulePhaseInvoiceSettingsIssuer struct { + // The connected account being referenced when `type` is `account`. + Account *Account `json:"account"` + // Type of the account referenced. + Type SubscriptionSchedulePhaseInvoiceSettingsIssuerType `json:"type"` +} + +// The invoice settings applicable during this phase. +type SubscriptionSchedulePhaseInvoiceSettings struct { + // The account tax IDs associated with this phase of the subscription schedule. Will be set on invoices generated by this phase of the subscription schedule. + AccountTaxIDs []*TaxID `json:"account_tax_ids"` + // Number of days within which a customer must pay invoices generated by this subscription schedule. This value will be `null` for subscription schedules where `billing=charge_automatically`. + DaysUntilDue int64 `json:"days_until_due"` + // The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + Issuer *SubscriptionSchedulePhaseInvoiceSettingsIssuer `json:"issuer"` +} + +// Define thresholds at which an invoice will be sent, and the related subscription advanced to a new billing period +type SubscriptionSchedulePhaseItemBillingThresholds struct { + // Usage threshold that triggers the subscription to create an invoice + UsageGTE int64 `json:"usage_gte"` +} + +// The discounts applied to the subscription item. Subscription item discounts are applied before subscription discounts. Use `expand[]=discounts` to expand each discount. +type SubscriptionSchedulePhaseItemDiscount struct { + // ID of the coupon to create a new discount for. + Coupon *Coupon `json:"coupon"` + // ID of an existing discount on the object (or one of its ancestors) to reuse. + Discount *Discount `json:"discount"` + // ID of the promotion code to create a new discount for. + PromotionCode *PromotionCode `json:"promotion_code"` +} + +// Subscription items to configure the subscription to during this phase of the subscription schedule. +type SubscriptionSchedulePhaseItem struct { + // Define thresholds at which an invoice will be sent, and the related subscription advanced to a new billing period + BillingThresholds *SubscriptionSchedulePhaseItemBillingThresholds `json:"billing_thresholds"` + // The discounts applied to the subscription item. Subscription item discounts are applied before subscription discounts. Use `expand[]=discounts` to expand each discount. + Discounts []*SubscriptionSchedulePhaseItemDiscount `json:"discounts"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an item. Metadata on this item will update the underlying subscription item's `metadata` when the phase is entered. + Metadata map[string]string `json:"metadata"` + // ID of the plan to which the customer should be subscribed. + Plan *Plan `json:"plan"` + // ID of the price to which the customer should be subscribed. + Price *Price `json:"price"` + // Quantity of the plan to which the customer should be subscribed. + Quantity int64 `json:"quantity"` + // The tax rates which apply to this `phase_item`. When set, the `default_tax_rates` on the phase do not apply to this `phase_item`. + TaxRates []*TaxRate `json:"tax_rates"` +} + +// Configuration for the subscription schedule's phases. +type SubscriptionSchedulePhase struct { + // A list of prices and quantities that will generate invoice items appended to the next invoice for this phase. + AddInvoiceItems []*SubscriptionSchedulePhaseAddInvoiceItem `json:"add_invoice_items"` + // A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account during this phase of the schedule. + ApplicationFeePercent float64 `json:"application_fee_percent"` + AutomaticTax *SubscriptionAutomaticTax `json:"automatic_tax"` + // Possible values are `phase_start` or `automatic`. If `phase_start` then billing cycle anchor of the subscription is set to the start of the phase when entering the phase. If `automatic` then the billing cycle anchor is automatically modified as needed when entering the phase. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + BillingCycleAnchor SubscriptionSchedulePhaseBillingCycleAnchor `json:"billing_cycle_anchor"` + // Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period + BillingThresholds *SubscriptionSchedulePhaseBillingThresholds `json:"billing_thresholds"` + // Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. + CollectionMethod *SubscriptionCollectionMethod `json:"collection_method"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // ID of the default payment method for the subscription schedule. It must belong to the customer associated with the subscription schedule. If not set, invoices will use the default payment method in the customer's invoice settings. + DefaultPaymentMethod *PaymentMethod `json:"default_payment_method"` + // The default tax rates to apply to the subscription during this phase of the subscription schedule. + DefaultTaxRates []*TaxRate `json:"default_tax_rates"` + // Subscription description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + Description string `json:"description"` + // The stackable discounts that will be applied to the subscription on this phase. Subscription item discounts are applied before subscription discounts. + Discounts []*SubscriptionSchedulePhaseDiscount `json:"discounts"` + // The end of this phase of the subscription schedule. + EndDate int64 `json:"end_date"` + // The invoice settings applicable during this phase. + InvoiceSettings *SubscriptionSchedulePhaseInvoiceSettings `json:"invoice_settings"` + // Subscription items to configure the subscription to during this phase of the subscription schedule. + Items []*SubscriptionSchedulePhaseItem `json:"items"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to a phase. Metadata on a schedule's phase will update the underlying subscription's `metadata` when the phase is entered. Updating the underlying subscription's `metadata` directly will not affect the current phase's `metadata`. + Metadata map[string]string `json:"metadata"` + // The account (if any) the charge was made on behalf of for charges associated with the schedule's subscription. See the Connect documentation for details. + OnBehalfOf *Account `json:"on_behalf_of"` + // When transitioning phases, controls how prorations are handled (if any). Possible values are `create_prorations`, `none`, and `always_invoice`. + ProrationBehavior SubscriptionSchedulePhaseProrationBehavior `json:"proration_behavior"` + // The start of this phase of the subscription schedule. + StartDate int64 `json:"start_date"` + // The account (if any) the associated subscription's payments will be attributed to for tax reporting, and where funds from each payment will be transferred to for each of the subscription's invoices. + TransferData *SubscriptionTransferData `json:"transfer_data"` + // When the trial ends within the phase. + TrialEnd int64 `json:"trial_end"` +} + +// A subscription schedule allows you to create and manage the lifecycle of a subscription by predefining expected changes. +// +// Related guide: [Subscription schedules](https://stripe.com/docs/billing/subscriptions/subscription-schedules) +type SubscriptionSchedule struct { + APIResource + // ID of the Connect Application that created the schedule. + Application *Application `json:"application"` + // The billing mode of the subscription. + BillingMode *SubscriptionScheduleBillingMode `json:"billing_mode"` + // Time at which the subscription schedule was canceled. Measured in seconds since the Unix epoch. + CanceledAt int64 `json:"canceled_at"` + // Time at which the subscription schedule was completed. Measured in seconds since the Unix epoch. + CompletedAt int64 `json:"completed_at"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Object representing the start and end dates for the current phase of the subscription schedule, if it is `active`. + CurrentPhase *SubscriptionScheduleCurrentPhase `json:"current_phase"` + // ID of the customer who owns the subscription schedule. + Customer *Customer `json:"customer"` + DefaultSettings *SubscriptionScheduleDefaultSettings `json:"default_settings"` + // Behavior of the subscription schedule and underlying subscription when it ends. Possible values are `release` or `cancel` with the default being `release`. `release` will end the subscription schedule and keep the underlying subscription running. `cancel` will end the subscription schedule and cancel the underlying subscription. + EndBehavior SubscriptionScheduleEndBehavior `json:"end_behavior"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Configuration for the subscription schedule's phases. + Phases []*SubscriptionSchedulePhase `json:"phases"` + // Time at which the subscription schedule was released. Measured in seconds since the Unix epoch. + ReleasedAt int64 `json:"released_at"` + // ID of the subscription once managed by the subscription schedule (if it is released). + ReleasedSubscription *Subscription `json:"released_subscription"` + // The present status of the subscription schedule. Possible values are `not_started`, `active`, `completed`, `released`, and `canceled`. You can read more about the different states in our [behavior guide](https://stripe.com/docs/billing/subscriptions/subscription-schedules). + Status SubscriptionScheduleStatus `json:"status"` + // ID of the subscription managed by the subscription schedule. + Subscription *Subscription `json:"subscription"` + // ID of the test clock this subscription schedule belongs to. + TestClock *TestHelpersTestClock `json:"test_clock"` +} + +// SubscriptionScheduleList is a list of SubscriptionSchedules as retrieved from a list endpoint. +type SubscriptionScheduleList struct { + APIResource + ListMeta + Data []*SubscriptionSchedule `json:"data"` +} + +// UnmarshalJSON handles deserialization of a SubscriptionSchedule. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (s *SubscriptionSchedule) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + s.ID = id + return nil + } + + type subscriptionSchedule SubscriptionSchedule + var v subscriptionSchedule + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *s = SubscriptionSchedule(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/subscriptionschedule_service.go b/vendor/github.com/stripe/stripe-go/v82/subscriptionschedule_service.go new file mode 100644 index 00000000..c95ae088 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/subscriptionschedule_service.go @@ -0,0 +1,97 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1SubscriptionScheduleService is used to invoke /v1/subscription_schedules APIs. +type v1SubscriptionScheduleService struct { + B Backend + Key string +} + +// Creates a new subscription schedule object. Each customer can have up to 500 active or scheduled subscriptions. +func (c v1SubscriptionScheduleService) Create(ctx context.Context, params *SubscriptionScheduleCreateParams) (*SubscriptionSchedule, error) { + if params == nil { + params = &SubscriptionScheduleCreateParams{} + } + params.Context = ctx + subscriptionschedule := &SubscriptionSchedule{} + err := c.B.Call( + http.MethodPost, "/v1/subscription_schedules", c.Key, params, subscriptionschedule) + return subscriptionschedule, err +} + +// Retrieves the details of an existing subscription schedule. You only need to supply the unique subscription schedule identifier that was returned upon subscription schedule creation. +func (c v1SubscriptionScheduleService) Retrieve(ctx context.Context, id string, params *SubscriptionScheduleRetrieveParams) (*SubscriptionSchedule, error) { + if params == nil { + params = &SubscriptionScheduleRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/subscription_schedules/%s", id) + subscriptionschedule := &SubscriptionSchedule{} + err := c.B.Call(http.MethodGet, path, c.Key, params, subscriptionschedule) + return subscriptionschedule, err +} + +// Updates an existing subscription schedule. +func (c v1SubscriptionScheduleService) Update(ctx context.Context, id string, params *SubscriptionScheduleUpdateParams) (*SubscriptionSchedule, error) { + if params == nil { + params = &SubscriptionScheduleUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/subscription_schedules/%s", id) + subscriptionschedule := &SubscriptionSchedule{} + err := c.B.Call(http.MethodPost, path, c.Key, params, subscriptionschedule) + return subscriptionschedule, err +} + +// Cancels a subscription schedule and its associated subscription immediately (if the subscription schedule has an active subscription). A subscription schedule can only be canceled if its status is not_started or active. +func (c v1SubscriptionScheduleService) Cancel(ctx context.Context, id string, params *SubscriptionScheduleCancelParams) (*SubscriptionSchedule, error) { + if params == nil { + params = &SubscriptionScheduleCancelParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/subscription_schedules/%s/cancel", id) + subscriptionschedule := &SubscriptionSchedule{} + err := c.B.Call(http.MethodPost, path, c.Key, params, subscriptionschedule) + return subscriptionschedule, err +} + +// Releases the subscription schedule immediately, which will stop scheduling of its phases, but leave any existing subscription in place. A schedule can only be released if its status is not_started or active. If the subscription schedule is currently associated with a subscription, releasing it will remove its subscription property and set the subscription's ID to the released_subscription property. +func (c v1SubscriptionScheduleService) Release(ctx context.Context, id string, params *SubscriptionScheduleReleaseParams) (*SubscriptionSchedule, error) { + if params == nil { + params = &SubscriptionScheduleReleaseParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/subscription_schedules/%s/release", id) + subscriptionschedule := &SubscriptionSchedule{} + err := c.B.Call(http.MethodPost, path, c.Key, params, subscriptionschedule) + return subscriptionschedule, err +} + +// Retrieves the list of your subscription schedules. +func (c v1SubscriptionScheduleService) List(ctx context.Context, listParams *SubscriptionScheduleListParams) Seq2[*SubscriptionSchedule, error] { + if listParams == nil { + listParams = &SubscriptionScheduleListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*SubscriptionSchedule, ListContainer, error) { + list := &SubscriptionScheduleList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/subscription_schedules", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/tax_calculation.go b/vendor/github.com/stripe/stripe-go/v82/tax_calculation.go new file mode 100644 index 00000000..c8dd56c8 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/tax_calculation.go @@ -0,0 +1,629 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The type of customer address provided. +type TaxCalculationCustomerDetailsAddressSource string + +// List of values that TaxCalculationCustomerDetailsAddressSource can take +const ( + TaxCalculationCustomerDetailsAddressSourceBilling TaxCalculationCustomerDetailsAddressSource = "billing" + TaxCalculationCustomerDetailsAddressSourceShipping TaxCalculationCustomerDetailsAddressSource = "shipping" +) + +// The type of the tax ID, one of `ad_nrt`, `ar_cuit`, `eu_vat`, `bo_tin`, `br_cnpj`, `br_cpf`, `cn_tin`, `co_nit`, `cr_tin`, `do_rcn`, `ec_ruc`, `eu_oss_vat`, `hr_oib`, `pe_ruc`, `ro_tin`, `rs_pib`, `sv_nit`, `uy_ruc`, `ve_rif`, `vn_tin`, `gb_vat`, `nz_gst`, `au_abn`, `au_arn`, `in_gst`, `no_vat`, `no_voec`, `za_vat`, `ch_vat`, `mx_rfc`, `sg_uen`, `ru_inn`, `ru_kpp`, `ca_bn`, `hk_br`, `es_cif`, `tw_vat`, `th_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `li_uid`, `li_vat`, `my_itn`, `us_ein`, `kr_brn`, `ca_qst`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `my_sst`, `sg_gst`, `ae_trn`, `cl_tin`, `sa_vat`, `id_npwp`, `my_frp`, `il_vat`, `ge_vat`, `ua_vat`, `is_vat`, `bg_uic`, `hu_tin`, `si_tin`, `ke_pin`, `tr_tin`, `eg_tin`, `ph_tin`, `al_tin`, `bh_vat`, `kz_bin`, `ng_tin`, `om_vat`, `de_stn`, `ch_uid`, `tz_vat`, `uz_vat`, `uz_tin`, `md_vat`, `ma_vat`, `by_tin`, `ao_tin`, `bs_tin`, `bb_tin`, `cd_nif`, `mr_nif`, `me_pib`, `zw_tin`, `ba_tin`, `gn_nif`, `mk_vat`, `sr_fin`, `sn_ninea`, `am_tin`, `np_pan`, `tj_tin`, `ug_tin`, `zm_tin`, `kh_tin`, `aw_tin`, `az_tin`, `bd_bin`, `bj_ifu`, `et_tin`, `kg_tin`, `la_tin`, `cm_niu`, `cv_nif`, `bf_ifu`, or `unknown` +type TaxCalculationCustomerDetailsTaxIDType string + +// List of values that TaxCalculationCustomerDetailsTaxIDType can take +const ( + TaxCalculationCustomerDetailsTaxIDTypeADNRT TaxCalculationCustomerDetailsTaxIDType = "ad_nrt" + TaxCalculationCustomerDetailsTaxIDTypeAETRN TaxCalculationCustomerDetailsTaxIDType = "ae_trn" + TaxCalculationCustomerDetailsTaxIDTypeAlTin TaxCalculationCustomerDetailsTaxIDType = "al_tin" + TaxCalculationCustomerDetailsTaxIDTypeAmTin TaxCalculationCustomerDetailsTaxIDType = "am_tin" + TaxCalculationCustomerDetailsTaxIDTypeAoTin TaxCalculationCustomerDetailsTaxIDType = "ao_tin" + TaxCalculationCustomerDetailsTaxIDTypeARCUIT TaxCalculationCustomerDetailsTaxIDType = "ar_cuit" + TaxCalculationCustomerDetailsTaxIDTypeAUABN TaxCalculationCustomerDetailsTaxIDType = "au_abn" + TaxCalculationCustomerDetailsTaxIDTypeAUARN TaxCalculationCustomerDetailsTaxIDType = "au_arn" + TaxCalculationCustomerDetailsTaxIDTypeAwTin TaxCalculationCustomerDetailsTaxIDType = "aw_tin" + TaxCalculationCustomerDetailsTaxIDTypeAzTin TaxCalculationCustomerDetailsTaxIDType = "az_tin" + TaxCalculationCustomerDetailsTaxIDTypeBaTin TaxCalculationCustomerDetailsTaxIDType = "ba_tin" + TaxCalculationCustomerDetailsTaxIDTypeBbTin TaxCalculationCustomerDetailsTaxIDType = "bb_tin" + TaxCalculationCustomerDetailsTaxIDTypeBdBin TaxCalculationCustomerDetailsTaxIDType = "bd_bin" + TaxCalculationCustomerDetailsTaxIDTypeBfIfu TaxCalculationCustomerDetailsTaxIDType = "bf_ifu" + TaxCalculationCustomerDetailsTaxIDTypeBGUIC TaxCalculationCustomerDetailsTaxIDType = "bg_uic" + TaxCalculationCustomerDetailsTaxIDTypeBhVAT TaxCalculationCustomerDetailsTaxIDType = "bh_vat" + TaxCalculationCustomerDetailsTaxIDTypeBjIfu TaxCalculationCustomerDetailsTaxIDType = "bj_ifu" + TaxCalculationCustomerDetailsTaxIDTypeBOTIN TaxCalculationCustomerDetailsTaxIDType = "bo_tin" + TaxCalculationCustomerDetailsTaxIDTypeBRCNPJ TaxCalculationCustomerDetailsTaxIDType = "br_cnpj" + TaxCalculationCustomerDetailsTaxIDTypeBRCPF TaxCalculationCustomerDetailsTaxIDType = "br_cpf" + TaxCalculationCustomerDetailsTaxIDTypeBsTin TaxCalculationCustomerDetailsTaxIDType = "bs_tin" + TaxCalculationCustomerDetailsTaxIDTypeByTin TaxCalculationCustomerDetailsTaxIDType = "by_tin" + TaxCalculationCustomerDetailsTaxIDTypeCABN TaxCalculationCustomerDetailsTaxIDType = "ca_bn" + TaxCalculationCustomerDetailsTaxIDTypeCAGSTHST TaxCalculationCustomerDetailsTaxIDType = "ca_gst_hst" + TaxCalculationCustomerDetailsTaxIDTypeCAPSTBC TaxCalculationCustomerDetailsTaxIDType = "ca_pst_bc" + TaxCalculationCustomerDetailsTaxIDTypeCAPSTMB TaxCalculationCustomerDetailsTaxIDType = "ca_pst_mb" + TaxCalculationCustomerDetailsTaxIDTypeCAPSTSK TaxCalculationCustomerDetailsTaxIDType = "ca_pst_sk" + TaxCalculationCustomerDetailsTaxIDTypeCAQST TaxCalculationCustomerDetailsTaxIDType = "ca_qst" + TaxCalculationCustomerDetailsTaxIDTypeCdNif TaxCalculationCustomerDetailsTaxIDType = "cd_nif" + TaxCalculationCustomerDetailsTaxIDTypeCHUID TaxCalculationCustomerDetailsTaxIDType = "ch_uid" + TaxCalculationCustomerDetailsTaxIDTypeCHVAT TaxCalculationCustomerDetailsTaxIDType = "ch_vat" + TaxCalculationCustomerDetailsTaxIDTypeCLTIN TaxCalculationCustomerDetailsTaxIDType = "cl_tin" + TaxCalculationCustomerDetailsTaxIDTypeCmNiu TaxCalculationCustomerDetailsTaxIDType = "cm_niu" + TaxCalculationCustomerDetailsTaxIDTypeCNTIN TaxCalculationCustomerDetailsTaxIDType = "cn_tin" + TaxCalculationCustomerDetailsTaxIDTypeCONIT TaxCalculationCustomerDetailsTaxIDType = "co_nit" + TaxCalculationCustomerDetailsTaxIDTypeCRTIN TaxCalculationCustomerDetailsTaxIDType = "cr_tin" + TaxCalculationCustomerDetailsTaxIDTypeCvNif TaxCalculationCustomerDetailsTaxIDType = "cv_nif" + TaxCalculationCustomerDetailsTaxIDTypeDEStn TaxCalculationCustomerDetailsTaxIDType = "de_stn" + TaxCalculationCustomerDetailsTaxIDTypeDORCN TaxCalculationCustomerDetailsTaxIDType = "do_rcn" + TaxCalculationCustomerDetailsTaxIDTypeECRUC TaxCalculationCustomerDetailsTaxIDType = "ec_ruc" + TaxCalculationCustomerDetailsTaxIDTypeEGTIN TaxCalculationCustomerDetailsTaxIDType = "eg_tin" + TaxCalculationCustomerDetailsTaxIDTypeESCIF TaxCalculationCustomerDetailsTaxIDType = "es_cif" + TaxCalculationCustomerDetailsTaxIDTypeETTin TaxCalculationCustomerDetailsTaxIDType = "et_tin" + TaxCalculationCustomerDetailsTaxIDTypeEUOSSVAT TaxCalculationCustomerDetailsTaxIDType = "eu_oss_vat" + TaxCalculationCustomerDetailsTaxIDTypeEUVAT TaxCalculationCustomerDetailsTaxIDType = "eu_vat" + TaxCalculationCustomerDetailsTaxIDTypeGBVAT TaxCalculationCustomerDetailsTaxIDType = "gb_vat" + TaxCalculationCustomerDetailsTaxIDTypeGEVAT TaxCalculationCustomerDetailsTaxIDType = "ge_vat" + TaxCalculationCustomerDetailsTaxIDTypeGnNif TaxCalculationCustomerDetailsTaxIDType = "gn_nif" + TaxCalculationCustomerDetailsTaxIDTypeHKBR TaxCalculationCustomerDetailsTaxIDType = "hk_br" + TaxCalculationCustomerDetailsTaxIDTypeHROIB TaxCalculationCustomerDetailsTaxIDType = "hr_oib" + TaxCalculationCustomerDetailsTaxIDTypeHUTIN TaxCalculationCustomerDetailsTaxIDType = "hu_tin" + TaxCalculationCustomerDetailsTaxIDTypeIDNPWP TaxCalculationCustomerDetailsTaxIDType = "id_npwp" + TaxCalculationCustomerDetailsTaxIDTypeILVAT TaxCalculationCustomerDetailsTaxIDType = "il_vat" + TaxCalculationCustomerDetailsTaxIDTypeINGST TaxCalculationCustomerDetailsTaxIDType = "in_gst" + TaxCalculationCustomerDetailsTaxIDTypeISVAT TaxCalculationCustomerDetailsTaxIDType = "is_vat" + TaxCalculationCustomerDetailsTaxIDTypeJPCN TaxCalculationCustomerDetailsTaxIDType = "jp_cn" + TaxCalculationCustomerDetailsTaxIDTypeJPRN TaxCalculationCustomerDetailsTaxIDType = "jp_rn" + TaxCalculationCustomerDetailsTaxIDTypeJPTRN TaxCalculationCustomerDetailsTaxIDType = "jp_trn" + TaxCalculationCustomerDetailsTaxIDTypeKEPIN TaxCalculationCustomerDetailsTaxIDType = "ke_pin" + TaxCalculationCustomerDetailsTaxIDTypeKgTin TaxCalculationCustomerDetailsTaxIDType = "kg_tin" + TaxCalculationCustomerDetailsTaxIDTypeKhTin TaxCalculationCustomerDetailsTaxIDType = "kh_tin" + TaxCalculationCustomerDetailsTaxIDTypeKRBRN TaxCalculationCustomerDetailsTaxIDType = "kr_brn" + TaxCalculationCustomerDetailsTaxIDTypeKzBin TaxCalculationCustomerDetailsTaxIDType = "kz_bin" + TaxCalculationCustomerDetailsTaxIDTypeLaTin TaxCalculationCustomerDetailsTaxIDType = "la_tin" + TaxCalculationCustomerDetailsTaxIDTypeLIUID TaxCalculationCustomerDetailsTaxIDType = "li_uid" + TaxCalculationCustomerDetailsTaxIDTypeLiVAT TaxCalculationCustomerDetailsTaxIDType = "li_vat" + TaxCalculationCustomerDetailsTaxIDTypeMaVAT TaxCalculationCustomerDetailsTaxIDType = "ma_vat" + TaxCalculationCustomerDetailsTaxIDTypeMdVAT TaxCalculationCustomerDetailsTaxIDType = "md_vat" + TaxCalculationCustomerDetailsTaxIDTypeMePib TaxCalculationCustomerDetailsTaxIDType = "me_pib" + TaxCalculationCustomerDetailsTaxIDTypeMkVAT TaxCalculationCustomerDetailsTaxIDType = "mk_vat" + TaxCalculationCustomerDetailsTaxIDTypeMrNif TaxCalculationCustomerDetailsTaxIDType = "mr_nif" + TaxCalculationCustomerDetailsTaxIDTypeMXRFC TaxCalculationCustomerDetailsTaxIDType = "mx_rfc" + TaxCalculationCustomerDetailsTaxIDTypeMYFRP TaxCalculationCustomerDetailsTaxIDType = "my_frp" + TaxCalculationCustomerDetailsTaxIDTypeMYITN TaxCalculationCustomerDetailsTaxIDType = "my_itn" + TaxCalculationCustomerDetailsTaxIDTypeMYSST TaxCalculationCustomerDetailsTaxIDType = "my_sst" + TaxCalculationCustomerDetailsTaxIDTypeNgTin TaxCalculationCustomerDetailsTaxIDType = "ng_tin" + TaxCalculationCustomerDetailsTaxIDTypeNOVAT TaxCalculationCustomerDetailsTaxIDType = "no_vat" + TaxCalculationCustomerDetailsTaxIDTypeNOVOEC TaxCalculationCustomerDetailsTaxIDType = "no_voec" + TaxCalculationCustomerDetailsTaxIDTypeNpPan TaxCalculationCustomerDetailsTaxIDType = "np_pan" + TaxCalculationCustomerDetailsTaxIDTypeNZGST TaxCalculationCustomerDetailsTaxIDType = "nz_gst" + TaxCalculationCustomerDetailsTaxIDTypeOmVAT TaxCalculationCustomerDetailsTaxIDType = "om_vat" + TaxCalculationCustomerDetailsTaxIDTypePERUC TaxCalculationCustomerDetailsTaxIDType = "pe_ruc" + TaxCalculationCustomerDetailsTaxIDTypePHTIN TaxCalculationCustomerDetailsTaxIDType = "ph_tin" + TaxCalculationCustomerDetailsTaxIDTypeROTIN TaxCalculationCustomerDetailsTaxIDType = "ro_tin" + TaxCalculationCustomerDetailsTaxIDTypeRSPIB TaxCalculationCustomerDetailsTaxIDType = "rs_pib" + TaxCalculationCustomerDetailsTaxIDTypeRUINN TaxCalculationCustomerDetailsTaxIDType = "ru_inn" + TaxCalculationCustomerDetailsTaxIDTypeRUKPP TaxCalculationCustomerDetailsTaxIDType = "ru_kpp" + TaxCalculationCustomerDetailsTaxIDTypeSAVAT TaxCalculationCustomerDetailsTaxIDType = "sa_vat" + TaxCalculationCustomerDetailsTaxIDTypeSGGST TaxCalculationCustomerDetailsTaxIDType = "sg_gst" + TaxCalculationCustomerDetailsTaxIDTypeSGUEN TaxCalculationCustomerDetailsTaxIDType = "sg_uen" + TaxCalculationCustomerDetailsTaxIDTypeSITIN TaxCalculationCustomerDetailsTaxIDType = "si_tin" + TaxCalculationCustomerDetailsTaxIDTypeSnNinea TaxCalculationCustomerDetailsTaxIDType = "sn_ninea" + TaxCalculationCustomerDetailsTaxIDTypeSrFin TaxCalculationCustomerDetailsTaxIDType = "sr_fin" + TaxCalculationCustomerDetailsTaxIDTypeSVNIT TaxCalculationCustomerDetailsTaxIDType = "sv_nit" + TaxCalculationCustomerDetailsTaxIDTypeTHVAT TaxCalculationCustomerDetailsTaxIDType = "th_vat" + TaxCalculationCustomerDetailsTaxIDTypeTjTin TaxCalculationCustomerDetailsTaxIDType = "tj_tin" + TaxCalculationCustomerDetailsTaxIDTypeTRTIN TaxCalculationCustomerDetailsTaxIDType = "tr_tin" + TaxCalculationCustomerDetailsTaxIDTypeTWVAT TaxCalculationCustomerDetailsTaxIDType = "tw_vat" + TaxCalculationCustomerDetailsTaxIDTypeTzVAT TaxCalculationCustomerDetailsTaxIDType = "tz_vat" + TaxCalculationCustomerDetailsTaxIDTypeUAVAT TaxCalculationCustomerDetailsTaxIDType = "ua_vat" + TaxCalculationCustomerDetailsTaxIDTypeUgTin TaxCalculationCustomerDetailsTaxIDType = "ug_tin" + TaxCalculationCustomerDetailsTaxIDTypeUnknown TaxCalculationCustomerDetailsTaxIDType = "unknown" + TaxCalculationCustomerDetailsTaxIDTypeUSEIN TaxCalculationCustomerDetailsTaxIDType = "us_ein" + TaxCalculationCustomerDetailsTaxIDTypeUYRUC TaxCalculationCustomerDetailsTaxIDType = "uy_ruc" + TaxCalculationCustomerDetailsTaxIDTypeUzTin TaxCalculationCustomerDetailsTaxIDType = "uz_tin" + TaxCalculationCustomerDetailsTaxIDTypeUzVAT TaxCalculationCustomerDetailsTaxIDType = "uz_vat" + TaxCalculationCustomerDetailsTaxIDTypeVERIF TaxCalculationCustomerDetailsTaxIDType = "ve_rif" + TaxCalculationCustomerDetailsTaxIDTypeVNTIN TaxCalculationCustomerDetailsTaxIDType = "vn_tin" + TaxCalculationCustomerDetailsTaxIDTypeZAVAT TaxCalculationCustomerDetailsTaxIDType = "za_vat" + TaxCalculationCustomerDetailsTaxIDTypeZmTin TaxCalculationCustomerDetailsTaxIDType = "zm_tin" + TaxCalculationCustomerDetailsTaxIDTypeZwTin TaxCalculationCustomerDetailsTaxIDType = "zw_tin" +) + +// The taxability override used for taxation. +type TaxCalculationCustomerDetailsTaxabilityOverride string + +// List of values that TaxCalculationCustomerDetailsTaxabilityOverride can take +const ( + TaxCalculationCustomerDetailsTaxabilityOverrideCustomerExempt TaxCalculationCustomerDetailsTaxabilityOverride = "customer_exempt" + TaxCalculationCustomerDetailsTaxabilityOverrideNone TaxCalculationCustomerDetailsTaxabilityOverride = "none" + TaxCalculationCustomerDetailsTaxabilityOverrideReverseCharge TaxCalculationCustomerDetailsTaxabilityOverride = "reverse_charge" +) + +// Specifies whether the `amount` includes taxes. If `tax_behavior=inclusive`, then the amount includes taxes. +type TaxCalculationShippingCostTaxBehavior string + +// List of values that TaxCalculationShippingCostTaxBehavior can take +const ( + TaxCalculationShippingCostTaxBehaviorExclusive TaxCalculationShippingCostTaxBehavior = "exclusive" + TaxCalculationShippingCostTaxBehaviorInclusive TaxCalculationShippingCostTaxBehavior = "inclusive" +) + +// Indicates the level of the jurisdiction imposing the tax. +type TaxCalculationShippingCostTaxBreakdownJurisdictionLevel string + +// List of values that TaxCalculationShippingCostTaxBreakdownJurisdictionLevel can take +const ( + TaxCalculationShippingCostTaxBreakdownJurisdictionLevelCity TaxCalculationShippingCostTaxBreakdownJurisdictionLevel = "city" + TaxCalculationShippingCostTaxBreakdownJurisdictionLevelCountry TaxCalculationShippingCostTaxBreakdownJurisdictionLevel = "country" + TaxCalculationShippingCostTaxBreakdownJurisdictionLevelCounty TaxCalculationShippingCostTaxBreakdownJurisdictionLevel = "county" + TaxCalculationShippingCostTaxBreakdownJurisdictionLevelDistrict TaxCalculationShippingCostTaxBreakdownJurisdictionLevel = "district" + TaxCalculationShippingCostTaxBreakdownJurisdictionLevelState TaxCalculationShippingCostTaxBreakdownJurisdictionLevel = "state" +) + +// Indicates whether the jurisdiction was determined by the origin (merchant's address) or destination (customer's address). +type TaxCalculationShippingCostTaxBreakdownSourcing string + +// List of values that TaxCalculationShippingCostTaxBreakdownSourcing can take +const ( + TaxCalculationShippingCostTaxBreakdownSourcingDestination TaxCalculationShippingCostTaxBreakdownSourcing = "destination" + TaxCalculationShippingCostTaxBreakdownSourcingOrigin TaxCalculationShippingCostTaxBreakdownSourcing = "origin" +) + +// The tax type, such as `vat` or `sales_tax`. +type TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType string + +// List of values that TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType can take +const ( + TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxTypeAmusementTax TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType = "amusement_tax" + TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxTypeCommunicationsTax TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType = "communications_tax" + TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxTypeGST TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType = "gst" + TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxTypeHST TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType = "hst" + TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxTypeIGST TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType = "igst" + TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxTypeJCT TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType = "jct" + TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxTypeLeaseTax TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType = "lease_tax" + TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxTypePST TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType = "pst" + TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxTypeQST TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType = "qst" + TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxTypeRetailDeliveryFee TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType = "retail_delivery_fee" + TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxTypeRST TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType = "rst" + TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxTypeSalesTax TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType = "sales_tax" + TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxTypeServiceTax TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType = "service_tax" + TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxTypeVAT TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType = "vat" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type TaxCalculationShippingCostTaxBreakdownTaxabilityReason string + +// List of values that TaxCalculationShippingCostTaxBreakdownTaxabilityReason can take +const ( + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonCustomerExempt TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "customer_exempt" + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonNotCollecting TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "not_collecting" + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonNotSubjectToTax TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "not_subject_to_tax" + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonNotSupported TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "not_supported" + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonPortionProductExempt TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "portion_product_exempt" + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonPortionReducedRated TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "portion_reduced_rated" + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonPortionStandardRated TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "portion_standard_rated" + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonProductExempt TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "product_exempt" + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonProductExemptHoliday TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "product_exempt_holiday" + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonProportionallyRated TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "proportionally_rated" + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonReducedRated TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "reduced_rated" + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonReverseCharge TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "reverse_charge" + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonStandardRated TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "standard_rated" + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonTaxableBasisReduced TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "taxable_basis_reduced" + TaxCalculationShippingCostTaxBreakdownTaxabilityReasonZeroRated TaxCalculationShippingCostTaxBreakdownTaxabilityReason = "zero_rated" +) + +// Indicates the type of tax rate applied to the taxable amount. This value can be `null` when no tax applies to the location. This field is only present for TaxRates created by Stripe Tax. +type TaxCalculationTaxBreakdownTaxRateDetailsRateType string + +// List of values that TaxCalculationTaxBreakdownTaxRateDetailsRateType can take +const ( + TaxCalculationTaxBreakdownTaxRateDetailsRateTypeFlatAmount TaxCalculationTaxBreakdownTaxRateDetailsRateType = "flat_amount" + TaxCalculationTaxBreakdownTaxRateDetailsRateTypePercentage TaxCalculationTaxBreakdownTaxRateDetailsRateType = "percentage" +) + +// The tax type, such as `vat` or `sales_tax`. +type TaxCalculationTaxBreakdownTaxRateDetailsTaxType string + +// List of values that TaxCalculationTaxBreakdownTaxRateDetailsTaxType can take +const ( + TaxCalculationTaxBreakdownTaxRateDetailsTaxTypeAmusementTax TaxCalculationTaxBreakdownTaxRateDetailsTaxType = "amusement_tax" + TaxCalculationTaxBreakdownTaxRateDetailsTaxTypeCommunicationsTax TaxCalculationTaxBreakdownTaxRateDetailsTaxType = "communications_tax" + TaxCalculationTaxBreakdownTaxRateDetailsTaxTypeGST TaxCalculationTaxBreakdownTaxRateDetailsTaxType = "gst" + TaxCalculationTaxBreakdownTaxRateDetailsTaxTypeHST TaxCalculationTaxBreakdownTaxRateDetailsTaxType = "hst" + TaxCalculationTaxBreakdownTaxRateDetailsTaxTypeIGST TaxCalculationTaxBreakdownTaxRateDetailsTaxType = "igst" + TaxCalculationTaxBreakdownTaxRateDetailsTaxTypeJCT TaxCalculationTaxBreakdownTaxRateDetailsTaxType = "jct" + TaxCalculationTaxBreakdownTaxRateDetailsTaxTypeLeaseTax TaxCalculationTaxBreakdownTaxRateDetailsTaxType = "lease_tax" + TaxCalculationTaxBreakdownTaxRateDetailsTaxTypePST TaxCalculationTaxBreakdownTaxRateDetailsTaxType = "pst" + TaxCalculationTaxBreakdownTaxRateDetailsTaxTypeQST TaxCalculationTaxBreakdownTaxRateDetailsTaxType = "qst" + TaxCalculationTaxBreakdownTaxRateDetailsTaxTypeRetailDeliveryFee TaxCalculationTaxBreakdownTaxRateDetailsTaxType = "retail_delivery_fee" + TaxCalculationTaxBreakdownTaxRateDetailsTaxTypeRST TaxCalculationTaxBreakdownTaxRateDetailsTaxType = "rst" + TaxCalculationTaxBreakdownTaxRateDetailsTaxTypeSalesTax TaxCalculationTaxBreakdownTaxRateDetailsTaxType = "sales_tax" + TaxCalculationTaxBreakdownTaxRateDetailsTaxTypeServiceTax TaxCalculationTaxBreakdownTaxRateDetailsTaxType = "service_tax" + TaxCalculationTaxBreakdownTaxRateDetailsTaxTypeVAT TaxCalculationTaxBreakdownTaxRateDetailsTaxType = "vat" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. We might extend the possible values for this field to support new tax rules. +type TaxCalculationTaxBreakdownTaxabilityReason string + +// List of values that TaxCalculationTaxBreakdownTaxabilityReason can take +const ( + TaxCalculationTaxBreakdownTaxabilityReasonCustomerExempt TaxCalculationTaxBreakdownTaxabilityReason = "customer_exempt" + TaxCalculationTaxBreakdownTaxabilityReasonNotCollecting TaxCalculationTaxBreakdownTaxabilityReason = "not_collecting" + TaxCalculationTaxBreakdownTaxabilityReasonNotSubjectToTax TaxCalculationTaxBreakdownTaxabilityReason = "not_subject_to_tax" + TaxCalculationTaxBreakdownTaxabilityReasonNotSupported TaxCalculationTaxBreakdownTaxabilityReason = "not_supported" + TaxCalculationTaxBreakdownTaxabilityReasonPortionProductExempt TaxCalculationTaxBreakdownTaxabilityReason = "portion_product_exempt" + TaxCalculationTaxBreakdownTaxabilityReasonPortionReducedRated TaxCalculationTaxBreakdownTaxabilityReason = "portion_reduced_rated" + TaxCalculationTaxBreakdownTaxabilityReasonPortionStandardRated TaxCalculationTaxBreakdownTaxabilityReason = "portion_standard_rated" + TaxCalculationTaxBreakdownTaxabilityReasonProductExempt TaxCalculationTaxBreakdownTaxabilityReason = "product_exempt" + TaxCalculationTaxBreakdownTaxabilityReasonProductExemptHoliday TaxCalculationTaxBreakdownTaxabilityReason = "product_exempt_holiday" + TaxCalculationTaxBreakdownTaxabilityReasonProportionallyRated TaxCalculationTaxBreakdownTaxabilityReason = "proportionally_rated" + TaxCalculationTaxBreakdownTaxabilityReasonReducedRated TaxCalculationTaxBreakdownTaxabilityReason = "reduced_rated" + TaxCalculationTaxBreakdownTaxabilityReasonReverseCharge TaxCalculationTaxBreakdownTaxabilityReason = "reverse_charge" + TaxCalculationTaxBreakdownTaxabilityReasonStandardRated TaxCalculationTaxBreakdownTaxabilityReason = "standard_rated" + TaxCalculationTaxBreakdownTaxabilityReasonTaxableBasisReduced TaxCalculationTaxBreakdownTaxabilityReason = "taxable_basis_reduced" + TaxCalculationTaxBreakdownTaxabilityReasonZeroRated TaxCalculationTaxBreakdownTaxabilityReason = "zero_rated" +) + +// Retrieves a Tax Calculation object, if the calculation hasn't expired. +type TaxCalculationParams struct { + Params `form:"*"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of an existing customer to use for this calculation. If provided, the customer's address and tax IDs are copied to `customer_details`. + Customer *string `form:"customer"` + // Details about the customer, including address and tax IDs. + CustomerDetails *TaxCalculationCustomerDetailsParams `form:"customer_details"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A list of items the customer is purchasing. + LineItems []*TaxCalculationLineItemParams `form:"line_items"` + // Details about the address from which the goods are being shipped. + ShipFromDetails *TaxCalculationShipFromDetailsParams `form:"ship_from_details"` + // Shipping cost details to be used for the calculation. + ShippingCost *TaxCalculationShippingCostParams `form:"shipping_cost"` + // Timestamp of date at which the tax rules and rates in effect applies for the calculation. Measured in seconds since the Unix epoch. Can be up to 48 hours in the past, and up to 48 hours in the future. + TaxDate *int64 `form:"tax_date"` +} + +// AddExpand appends a new field to expand. +func (p *TaxCalculationParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the line items of a tax calculation as a collection, if the calculation hasn't expired. +type TaxCalculationListLineItemsParams struct { + ListParams `form:"*"` + Calculation *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TaxCalculationListLineItemsParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The customer's tax IDs. Stripe Tax might consider a transaction with applicable tax IDs to be B2B, which might affect the tax calculation result. Stripe Tax doesn't validate tax IDs for correctness. +type TaxCalculationCustomerDetailsTaxIDParams struct { + // Type of the tax ID, one of `ad_nrt`, `ae_trn`, `al_tin`, `am_tin`, `ao_tin`, `ar_cuit`, `au_abn`, `au_arn`, `aw_tin`, `az_tin`, `ba_tin`, `bb_tin`, `bd_bin`, `bf_ifu`, `bg_uic`, `bh_vat`, `bj_ifu`, `bo_tin`, `br_cnpj`, `br_cpf`, `bs_tin`, `by_tin`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `ca_qst`, `cd_nif`, `ch_uid`, `ch_vat`, `cl_tin`, `cm_niu`, `cn_tin`, `co_nit`, `cr_tin`, `cv_nif`, `de_stn`, `do_rcn`, `ec_ruc`, `eg_tin`, `es_cif`, `et_tin`, `eu_oss_vat`, `eu_vat`, `gb_vat`, `ge_vat`, `gn_nif`, `hk_br`, `hr_oib`, `hu_tin`, `id_npwp`, `il_vat`, `in_gst`, `is_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `ke_pin`, `kg_tin`, `kh_tin`, `kr_brn`, `kz_bin`, `la_tin`, `li_uid`, `li_vat`, `ma_vat`, `md_vat`, `me_pib`, `mk_vat`, `mr_nif`, `mx_rfc`, `my_frp`, `my_itn`, `my_sst`, `ng_tin`, `no_vat`, `no_voec`, `np_pan`, `nz_gst`, `om_vat`, `pe_ruc`, `ph_tin`, `ro_tin`, `rs_pib`, `ru_inn`, `ru_kpp`, `sa_vat`, `sg_gst`, `sg_uen`, `si_tin`, `sn_ninea`, `sr_fin`, `sv_nit`, `th_vat`, `tj_tin`, `tr_tin`, `tw_vat`, `tz_vat`, `ua_vat`, `ug_tin`, `us_ein`, `uy_ruc`, `uz_tin`, `uz_vat`, `ve_rif`, `vn_tin`, `za_vat`, `zm_tin`, or `zw_tin` + Type *string `form:"type"` + // Value of the tax ID. + Value *string `form:"value"` +} + +// Details about the customer, including address and tax IDs. +type TaxCalculationCustomerDetailsParams struct { + // The customer's postal address (for example, home or business location). + Address *AddressParams `form:"address"` + // The type of customer address provided. + AddressSource *string `form:"address_source"` + // The customer's IP address (IPv4 or IPv6). + IPAddress *string `form:"ip_address"` + // Overrides the tax calculation result to allow you to not collect tax from your customer. Use this if you've manually checked your customer's tax exemptions. Prefer providing the customer's `tax_ids` where possible, which automatically determines whether `reverse_charge` applies. + TaxabilityOverride *string `form:"taxability_override"` + // The customer's tax IDs. Stripe Tax might consider a transaction with applicable tax IDs to be B2B, which might affect the tax calculation result. Stripe Tax doesn't validate tax IDs for correctness. + TaxIDs []*TaxCalculationCustomerDetailsTaxIDParams `form:"tax_ids"` +} + +// A list of items the customer is purchasing. +type TaxCalculationLineItemParams struct { + // A positive integer representing the line item's total price in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + // If `tax_behavior=inclusive`, then this amount includes taxes. Otherwise, taxes are calculated on top of this amount. + Amount *int64 `form:"amount"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `form:"metadata"` + // If provided, the product's `tax_code` will be used as the line item's `tax_code`. + Product *string `form:"product"` + // The number of units of the item being purchased. Used to calculate the per-unit price from the total `amount` for the line. For example, if `amount=100` and `quantity=4`, the calculated unit price is 25. + Quantity *int64 `form:"quantity"` + // A custom identifier for this line item, which must be unique across the line items in the calculation. The reference helps identify each line item in exported [tax reports](https://stripe.com/docs/tax/reports). + Reference *string `form:"reference"` + // Specifies whether the `amount` includes taxes. Defaults to `exclusive`. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID to use for this line item. If not provided, we will use the tax code from the provided `product` param. If neither `tax_code` nor `product` is provided, we will use the default tax code from your Tax Settings. + TaxCode *string `form:"tax_code"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TaxCalculationLineItemParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Details about the address from which the goods are being shipped. +type TaxCalculationShipFromDetailsParams struct { + // The address from which the goods are being shipped from. + Address *AddressParams `form:"address"` +} + +// Shipping cost details to be used for the calculation. +type TaxCalculationShippingCostParams struct { + // A positive integer in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) representing the shipping charge. If `tax_behavior=inclusive`, then this amount includes taxes. Otherwise, taxes are calculated on top of this amount. + Amount *int64 `form:"amount"` + // If provided, the [shipping rate](https://stripe.com/docs/api/shipping_rates/object)'s `amount`, `tax_code` and `tax_behavior` are used. If you provide a shipping rate, then you cannot pass the `amount`, `tax_code`, or `tax_behavior` parameters. + ShippingRate *string `form:"shipping_rate"` + // Specifies whether the `amount` includes taxes. If `tax_behavior=inclusive`, then the amount includes taxes. Defaults to `exclusive`. + TaxBehavior *string `form:"tax_behavior"` + // The [tax code](https://stripe.com/docs/tax/tax-categories) used to calculate tax on shipping. If not provided, the default shipping tax code from your [Tax Settings](https://dashboard.stripe.com/settings/tax) is used. + TaxCode *string `form:"tax_code"` +} + +// Retrieves a Tax Calculation object, if the calculation hasn't expired. +type TaxCalculationRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TaxCalculationRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The customer's tax IDs. Stripe Tax might consider a transaction with applicable tax IDs to be B2B, which might affect the tax calculation result. Stripe Tax doesn't validate tax IDs for correctness. +type TaxCalculationCreateCustomerDetailsTaxIDParams struct { + // Type of the tax ID, one of `ad_nrt`, `ae_trn`, `al_tin`, `am_tin`, `ao_tin`, `ar_cuit`, `au_abn`, `au_arn`, `aw_tin`, `az_tin`, `ba_tin`, `bb_tin`, `bd_bin`, `bf_ifu`, `bg_uic`, `bh_vat`, `bj_ifu`, `bo_tin`, `br_cnpj`, `br_cpf`, `bs_tin`, `by_tin`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `ca_qst`, `cd_nif`, `ch_uid`, `ch_vat`, `cl_tin`, `cm_niu`, `cn_tin`, `co_nit`, `cr_tin`, `cv_nif`, `de_stn`, `do_rcn`, `ec_ruc`, `eg_tin`, `es_cif`, `et_tin`, `eu_oss_vat`, `eu_vat`, `gb_vat`, `ge_vat`, `gn_nif`, `hk_br`, `hr_oib`, `hu_tin`, `id_npwp`, `il_vat`, `in_gst`, `is_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `ke_pin`, `kg_tin`, `kh_tin`, `kr_brn`, `kz_bin`, `la_tin`, `li_uid`, `li_vat`, `ma_vat`, `md_vat`, `me_pib`, `mk_vat`, `mr_nif`, `mx_rfc`, `my_frp`, `my_itn`, `my_sst`, `ng_tin`, `no_vat`, `no_voec`, `np_pan`, `nz_gst`, `om_vat`, `pe_ruc`, `ph_tin`, `ro_tin`, `rs_pib`, `ru_inn`, `ru_kpp`, `sa_vat`, `sg_gst`, `sg_uen`, `si_tin`, `sn_ninea`, `sr_fin`, `sv_nit`, `th_vat`, `tj_tin`, `tr_tin`, `tw_vat`, `tz_vat`, `ua_vat`, `ug_tin`, `us_ein`, `uy_ruc`, `uz_tin`, `uz_vat`, `ve_rif`, `vn_tin`, `za_vat`, `zm_tin`, or `zw_tin` + Type *string `form:"type"` + // Value of the tax ID. + Value *string `form:"value"` +} + +// Details about the customer, including address and tax IDs. +type TaxCalculationCreateCustomerDetailsParams struct { + // The customer's postal address (for example, home or business location). + Address *AddressParams `form:"address"` + // The type of customer address provided. + AddressSource *string `form:"address_source"` + // The customer's IP address (IPv4 or IPv6). + IPAddress *string `form:"ip_address"` + // Overrides the tax calculation result to allow you to not collect tax from your customer. Use this if you've manually checked your customer's tax exemptions. Prefer providing the customer's `tax_ids` where possible, which automatically determines whether `reverse_charge` applies. + TaxabilityOverride *string `form:"taxability_override"` + // The customer's tax IDs. Stripe Tax might consider a transaction with applicable tax IDs to be B2B, which might affect the tax calculation result. Stripe Tax doesn't validate tax IDs for correctness. + TaxIDs []*TaxCalculationCreateCustomerDetailsTaxIDParams `form:"tax_ids"` +} + +// A list of items the customer is purchasing. +type TaxCalculationCreateLineItemParams struct { + // A positive integer representing the line item's total price in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + // If `tax_behavior=inclusive`, then this amount includes taxes. Otherwise, taxes are calculated on top of this amount. + Amount *int64 `form:"amount"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `form:"metadata"` + // If provided, the product's `tax_code` will be used as the line item's `tax_code`. + Product *string `form:"product"` + // The number of units of the item being purchased. Used to calculate the per-unit price from the total `amount` for the line. For example, if `amount=100` and `quantity=4`, the calculated unit price is 25. + Quantity *int64 `form:"quantity"` + // A custom identifier for this line item, which must be unique across the line items in the calculation. The reference helps identify each line item in exported [tax reports](https://stripe.com/docs/tax/reports). + Reference *string `form:"reference"` + // Specifies whether the `amount` includes taxes. Defaults to `exclusive`. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID to use for this line item. If not provided, we will use the tax code from the provided `product` param. If neither `tax_code` nor `product` is provided, we will use the default tax code from your Tax Settings. + TaxCode *string `form:"tax_code"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TaxCalculationCreateLineItemParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Details about the address from which the goods are being shipped. +type TaxCalculationCreateShipFromDetailsParams struct { + // The address from which the goods are being shipped from. + Address *AddressParams `form:"address"` +} + +// Shipping cost details to be used for the calculation. +type TaxCalculationCreateShippingCostParams struct { + // A positive integer in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) representing the shipping charge. If `tax_behavior=inclusive`, then this amount includes taxes. Otherwise, taxes are calculated on top of this amount. + Amount *int64 `form:"amount"` + // If provided, the [shipping rate](https://stripe.com/docs/api/shipping_rates/object)'s `amount`, `tax_code` and `tax_behavior` are used. If you provide a shipping rate, then you cannot pass the `amount`, `tax_code`, or `tax_behavior` parameters. + ShippingRate *string `form:"shipping_rate"` + // Specifies whether the `amount` includes taxes. If `tax_behavior=inclusive`, then the amount includes taxes. Defaults to `exclusive`. + TaxBehavior *string `form:"tax_behavior"` + // The [tax code](https://stripe.com/docs/tax/tax-categories) used to calculate tax on shipping. If not provided, the default shipping tax code from your [Tax Settings](https://dashboard.stripe.com/settings/tax) is used. + TaxCode *string `form:"tax_code"` +} + +// Calculates tax based on the input and returns a Tax Calculation object. +type TaxCalculationCreateParams struct { + Params `form:"*"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // The ID of an existing customer to use for this calculation. If provided, the customer's address and tax IDs are copied to `customer_details`. + Customer *string `form:"customer"` + // Details about the customer, including address and tax IDs. + CustomerDetails *TaxCalculationCreateCustomerDetailsParams `form:"customer_details"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A list of items the customer is purchasing. + LineItems []*TaxCalculationCreateLineItemParams `form:"line_items"` + // Details about the address from which the goods are being shipped. + ShipFromDetails *TaxCalculationCreateShipFromDetailsParams `form:"ship_from_details"` + // Shipping cost details to be used for the calculation. + ShippingCost *TaxCalculationCreateShippingCostParams `form:"shipping_cost"` + // Timestamp of date at which the tax rules and rates in effect applies for the calculation. Measured in seconds since the Unix epoch. Can be up to 48 hours in the past, and up to 48 hours in the future. + TaxDate *int64 `form:"tax_date"` +} + +// AddExpand appends a new field to expand. +func (p *TaxCalculationCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The customer's tax IDs (for example, EU VAT numbers). +type TaxCalculationCustomerDetailsTaxID struct { + // The type of the tax ID, one of `ad_nrt`, `ar_cuit`, `eu_vat`, `bo_tin`, `br_cnpj`, `br_cpf`, `cn_tin`, `co_nit`, `cr_tin`, `do_rcn`, `ec_ruc`, `eu_oss_vat`, `hr_oib`, `pe_ruc`, `ro_tin`, `rs_pib`, `sv_nit`, `uy_ruc`, `ve_rif`, `vn_tin`, `gb_vat`, `nz_gst`, `au_abn`, `au_arn`, `in_gst`, `no_vat`, `no_voec`, `za_vat`, `ch_vat`, `mx_rfc`, `sg_uen`, `ru_inn`, `ru_kpp`, `ca_bn`, `hk_br`, `es_cif`, `tw_vat`, `th_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `li_uid`, `li_vat`, `my_itn`, `us_ein`, `kr_brn`, `ca_qst`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `my_sst`, `sg_gst`, `ae_trn`, `cl_tin`, `sa_vat`, `id_npwp`, `my_frp`, `il_vat`, `ge_vat`, `ua_vat`, `is_vat`, `bg_uic`, `hu_tin`, `si_tin`, `ke_pin`, `tr_tin`, `eg_tin`, `ph_tin`, `al_tin`, `bh_vat`, `kz_bin`, `ng_tin`, `om_vat`, `de_stn`, `ch_uid`, `tz_vat`, `uz_vat`, `uz_tin`, `md_vat`, `ma_vat`, `by_tin`, `ao_tin`, `bs_tin`, `bb_tin`, `cd_nif`, `mr_nif`, `me_pib`, `zw_tin`, `ba_tin`, `gn_nif`, `mk_vat`, `sr_fin`, `sn_ninea`, `am_tin`, `np_pan`, `tj_tin`, `ug_tin`, `zm_tin`, `kh_tin`, `aw_tin`, `az_tin`, `bd_bin`, `bj_ifu`, `et_tin`, `kg_tin`, `la_tin`, `cm_niu`, `cv_nif`, `bf_ifu`, or `unknown` + Type TaxCalculationCustomerDetailsTaxIDType `json:"type"` + // The value of the tax ID. + Value string `json:"value"` +} +type TaxCalculationCustomerDetails struct { + // The customer's postal address (for example, home or business location). + Address *Address `json:"address"` + // The type of customer address provided. + AddressSource TaxCalculationCustomerDetailsAddressSource `json:"address_source"` + // The customer's IP address (IPv4 or IPv6). + IPAddress string `json:"ip_address"` + // The taxability override used for taxation. + TaxabilityOverride TaxCalculationCustomerDetailsTaxabilityOverride `json:"taxability_override"` + // The customer's tax IDs (for example, EU VAT numbers). + TaxIDs []*TaxCalculationCustomerDetailsTaxID `json:"tax_ids"` +} + +// The details of the ship from location, such as the address. +type TaxCalculationShipFromDetails struct { + Address *Address `json:"address"` +} +type TaxCalculationShippingCostTaxBreakdownJurisdiction struct { + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country string `json:"country"` + // A human-readable name for the jurisdiction imposing the tax. + DisplayName string `json:"display_name"` + // Indicates the level of the jurisdiction imposing the tax. + Level TaxCalculationShippingCostTaxBreakdownJurisdictionLevel `json:"level"` + // [ISO 3166-2 subdivision code](https://en.wikipedia.org/wiki/ISO_3166-2), without country prefix. For example, "NY" for New York, United States. + State string `json:"state"` +} + +// Details regarding the rate for this tax. This field will be `null` when the tax is not imposed, for example if the product is exempt from tax. +type TaxCalculationShippingCostTaxBreakdownTaxRateDetails struct { + // A localized display name for tax type, intended to be human-readable. For example, "Local Sales and Use Tax", "Value-added tax (VAT)", or "Umsatzsteuer (USt.)". + DisplayName string `json:"display_name"` + // The tax rate percentage as a string. For example, 8.5% is represented as "8.5". + PercentageDecimal string `json:"percentage_decimal"` + // The tax type, such as `vat` or `sales_tax`. + TaxType TaxCalculationShippingCostTaxBreakdownTaxRateDetailsTaxType `json:"tax_type"` +} + +// Detailed account of taxes relevant to shipping cost. +type TaxCalculationShippingCostTaxBreakdown struct { + // The amount of tax, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Amount int64 `json:"amount"` + Jurisdiction *TaxCalculationShippingCostTaxBreakdownJurisdiction `json:"jurisdiction"` + // Indicates whether the jurisdiction was determined by the origin (merchant's address) or destination (customer's address). + Sourcing TaxCalculationShippingCostTaxBreakdownSourcing `json:"sourcing"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason TaxCalculationShippingCostTaxBreakdownTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + TaxableAmount int64 `json:"taxable_amount"` + // Details regarding the rate for this tax. This field will be `null` when the tax is not imposed, for example if the product is exempt from tax. + TaxRateDetails *TaxCalculationShippingCostTaxBreakdownTaxRateDetails `json:"tax_rate_details"` +} + +// The shipping cost details for the calculation. +type TaxCalculationShippingCost struct { + // The shipping amount in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). If `tax_behavior=inclusive`, then this amount includes taxes. Otherwise, taxes were calculated on top of this amount. + Amount int64 `json:"amount"` + // The amount of tax calculated for shipping, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + AmountTax int64 `json:"amount_tax"` + // The ID of an existing [ShippingRate](https://stripe.com/docs/api/shipping_rates/object). + ShippingRate string `json:"shipping_rate"` + // Specifies whether the `amount` includes taxes. If `tax_behavior=inclusive`, then the amount includes taxes. + TaxBehavior TaxCalculationShippingCostTaxBehavior `json:"tax_behavior"` + // Detailed account of taxes relevant to shipping cost. + TaxBreakdown []*TaxCalculationShippingCostTaxBreakdown `json:"tax_breakdown"` + // The [tax code](https://stripe.com/docs/tax/tax-categories) ID used for shipping. + TaxCode string `json:"tax_code"` +} + +// The amount of the tax rate when the `rate_type` is `flat_amount`. Tax rates with `rate_type` `percentage` can vary based on the transaction, resulting in this field being `null`. This field exposes the amount and currency of the flat tax rate. +type TaxCalculationTaxBreakdownTaxRateDetailsFlatAmount struct { + // Amount of the tax when the `rate_type` is `flat_amount`. This positive integer represents how much to charge in the smallest currency unit (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + Amount int64 `json:"amount"` + // Three-letter ISO currency code, in lowercase. + Currency Currency `json:"currency"` +} +type TaxCalculationTaxBreakdownTaxRateDetails struct { + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country string `json:"country"` + // The amount of the tax rate when the `rate_type` is `flat_amount`. Tax rates with `rate_type` `percentage` can vary based on the transaction, resulting in this field being `null`. This field exposes the amount and currency of the flat tax rate. + FlatAmount *TaxCalculationTaxBreakdownTaxRateDetailsFlatAmount `json:"flat_amount"` + // The tax rate percentage as a string. For example, 8.5% is represented as `"8.5"`. + PercentageDecimal string `json:"percentage_decimal"` + // Indicates the type of tax rate applied to the taxable amount. This value can be `null` when no tax applies to the location. This field is only present for TaxRates created by Stripe Tax. + RateType TaxCalculationTaxBreakdownTaxRateDetailsRateType `json:"rate_type"` + // State, county, province, or region. + State string `json:"state"` + // The tax type, such as `vat` or `sales_tax`. + TaxType TaxCalculationTaxBreakdownTaxRateDetailsTaxType `json:"tax_type"` +} + +// Breakdown of individual tax amounts that add up to the total. +type TaxCalculationTaxBreakdown struct { + // The amount of tax, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Amount int64 `json:"amount"` + // Specifies whether the tax amount is included in the line item amount. + Inclusive bool `json:"inclusive"` + // The reasoning behind this tax, for example, if the product is tax exempt. We might extend the possible values for this field to support new tax rules. + TaxabilityReason TaxCalculationTaxBreakdownTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + TaxableAmount int64 `json:"taxable_amount"` + TaxRateDetails *TaxCalculationTaxBreakdownTaxRateDetails `json:"tax_rate_details"` +} + +// A Tax Calculation allows you to calculate the tax to collect from your customer. +// +// Related guide: [Calculate tax in your custom payment flow](https://stripe.com/docs/tax/custom) +type TaxCalculation struct { + APIResource + // Total amount after taxes in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + AmountTotal int64 `json:"amount_total"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // The ID of an existing [Customer](https://stripe.com/docs/api/customers/object) used for the resource. + Customer string `json:"customer"` + CustomerDetails *TaxCalculationCustomerDetails `json:"customer_details"` + // Timestamp of date at which the tax calculation will expire. + ExpiresAt int64 `json:"expires_at"` + // Unique identifier for the calculation. + ID string `json:"id"` + // The list of items the customer is purchasing. + LineItems *TaxCalculationLineItemList `json:"line_items"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The details of the ship from location, such as the address. + ShipFromDetails *TaxCalculationShipFromDetails `json:"ship_from_details"` + // The shipping cost details for the calculation. + ShippingCost *TaxCalculationShippingCost `json:"shipping_cost"` + // The amount of tax to be collected on top of the line item prices. + TaxAmountExclusive int64 `json:"tax_amount_exclusive"` + // The amount of tax already included in the line item prices. + TaxAmountInclusive int64 `json:"tax_amount_inclusive"` + // Breakdown of individual tax amounts that add up to the total. + TaxBreakdown []*TaxCalculationTaxBreakdown `json:"tax_breakdown"` + // Timestamp of date at which the tax rules and rates in effect applies for the calculation. + TaxDate int64 `json:"tax_date"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/tax_calculation_service.go b/vendor/github.com/stripe/stripe-go/v82/tax_calculation_service.go new file mode 100644 index 00000000..894f8034 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/tax_calculation_service.go @@ -0,0 +1,63 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TaxCalculationService is used to invoke /v1/tax/calculations APIs. +type v1TaxCalculationService struct { + B Backend + Key string +} + +// Calculates tax based on the input and returns a Tax Calculation object. +func (c v1TaxCalculationService) Create(ctx context.Context, params *TaxCalculationCreateParams) (*TaxCalculation, error) { + if params == nil { + params = &TaxCalculationCreateParams{} + } + params.Context = ctx + calculation := &TaxCalculation{} + err := c.B.Call( + http.MethodPost, "/v1/tax/calculations", c.Key, params, calculation) + return calculation, err +} + +// Retrieves a Tax Calculation object, if the calculation hasn't expired. +func (c v1TaxCalculationService) Retrieve(ctx context.Context, id string, params *TaxCalculationRetrieveParams) (*TaxCalculation, error) { + if params == nil { + params = &TaxCalculationRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/tax/calculations/%s", id) + calculation := &TaxCalculation{} + err := c.B.Call(http.MethodGet, path, c.Key, params, calculation) + return calculation, err +} + +// Retrieves the line items of a tax calculation as a collection, if the calculation hasn't expired. +func (c v1TaxCalculationService) ListLineItems(ctx context.Context, listParams *TaxCalculationListLineItemsParams) Seq2[*TaxCalculationLineItem, error] { + if listParams == nil { + listParams = &TaxCalculationListLineItemsParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/tax/calculations/%s/line_items", StringValue(listParams.Calculation)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TaxCalculationLineItem, ListContainer, error) { + list := &TaxCalculationLineItemList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/tax_calculationlineitem.go b/vendor/github.com/stripe/stripe-go/v82/tax_calculationlineitem.go new file mode 100644 index 00000000..eab47fd4 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/tax_calculationlineitem.go @@ -0,0 +1,149 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Specifies whether the `amount` includes taxes. If `tax_behavior=inclusive`, then the amount includes taxes. +type TaxCalculationLineItemTaxBehavior string + +// List of values that TaxCalculationLineItemTaxBehavior can take +const ( + TaxCalculationLineItemTaxBehaviorExclusive TaxCalculationLineItemTaxBehavior = "exclusive" + TaxCalculationLineItemTaxBehaviorInclusive TaxCalculationLineItemTaxBehavior = "inclusive" +) + +// Indicates the level of the jurisdiction imposing the tax. +type TaxCalculationLineItemTaxBreakdownJurisdictionLevel string + +// List of values that TaxCalculationLineItemTaxBreakdownJurisdictionLevel can take +const ( + TaxCalculationLineItemTaxBreakdownJurisdictionLevelCity TaxCalculationLineItemTaxBreakdownJurisdictionLevel = "city" + TaxCalculationLineItemTaxBreakdownJurisdictionLevelCountry TaxCalculationLineItemTaxBreakdownJurisdictionLevel = "country" + TaxCalculationLineItemTaxBreakdownJurisdictionLevelCounty TaxCalculationLineItemTaxBreakdownJurisdictionLevel = "county" + TaxCalculationLineItemTaxBreakdownJurisdictionLevelDistrict TaxCalculationLineItemTaxBreakdownJurisdictionLevel = "district" + TaxCalculationLineItemTaxBreakdownJurisdictionLevelState TaxCalculationLineItemTaxBreakdownJurisdictionLevel = "state" +) + +// Indicates whether the jurisdiction was determined by the origin (merchant's address) or destination (customer's address). +type TaxCalculationLineItemTaxBreakdownSourcing string + +// List of values that TaxCalculationLineItemTaxBreakdownSourcing can take +const ( + TaxCalculationLineItemTaxBreakdownSourcingDestination TaxCalculationLineItemTaxBreakdownSourcing = "destination" + TaxCalculationLineItemTaxBreakdownSourcingOrigin TaxCalculationLineItemTaxBreakdownSourcing = "origin" +) + +// The tax type, such as `vat` or `sales_tax`. +type TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType string + +// List of values that TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType can take +const ( + TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxTypeAmusementTax TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType = "amusement_tax" + TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxTypeCommunicationsTax TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType = "communications_tax" + TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxTypeGST TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType = "gst" + TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxTypeHST TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType = "hst" + TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxTypeIGST TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType = "igst" + TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxTypeJCT TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType = "jct" + TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxTypeLeaseTax TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType = "lease_tax" + TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxTypePST TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType = "pst" + TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxTypeQST TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType = "qst" + TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxTypeRetailDeliveryFee TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType = "retail_delivery_fee" + TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxTypeRST TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType = "rst" + TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxTypeSalesTax TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType = "sales_tax" + TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxTypeServiceTax TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType = "service_tax" + TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxTypeVAT TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType = "vat" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type TaxCalculationLineItemTaxBreakdownTaxabilityReason string + +// List of values that TaxCalculationLineItemTaxBreakdownTaxabilityReason can take +const ( + TaxCalculationLineItemTaxBreakdownTaxabilityReasonCustomerExempt TaxCalculationLineItemTaxBreakdownTaxabilityReason = "customer_exempt" + TaxCalculationLineItemTaxBreakdownTaxabilityReasonNotCollecting TaxCalculationLineItemTaxBreakdownTaxabilityReason = "not_collecting" + TaxCalculationLineItemTaxBreakdownTaxabilityReasonNotSubjectToTax TaxCalculationLineItemTaxBreakdownTaxabilityReason = "not_subject_to_tax" + TaxCalculationLineItemTaxBreakdownTaxabilityReasonNotSupported TaxCalculationLineItemTaxBreakdownTaxabilityReason = "not_supported" + TaxCalculationLineItemTaxBreakdownTaxabilityReasonPortionProductExempt TaxCalculationLineItemTaxBreakdownTaxabilityReason = "portion_product_exempt" + TaxCalculationLineItemTaxBreakdownTaxabilityReasonPortionReducedRated TaxCalculationLineItemTaxBreakdownTaxabilityReason = "portion_reduced_rated" + TaxCalculationLineItemTaxBreakdownTaxabilityReasonPortionStandardRated TaxCalculationLineItemTaxBreakdownTaxabilityReason = "portion_standard_rated" + TaxCalculationLineItemTaxBreakdownTaxabilityReasonProductExempt TaxCalculationLineItemTaxBreakdownTaxabilityReason = "product_exempt" + TaxCalculationLineItemTaxBreakdownTaxabilityReasonProductExemptHoliday TaxCalculationLineItemTaxBreakdownTaxabilityReason = "product_exempt_holiday" + TaxCalculationLineItemTaxBreakdownTaxabilityReasonProportionallyRated TaxCalculationLineItemTaxBreakdownTaxabilityReason = "proportionally_rated" + TaxCalculationLineItemTaxBreakdownTaxabilityReasonReducedRated TaxCalculationLineItemTaxBreakdownTaxabilityReason = "reduced_rated" + TaxCalculationLineItemTaxBreakdownTaxabilityReasonReverseCharge TaxCalculationLineItemTaxBreakdownTaxabilityReason = "reverse_charge" + TaxCalculationLineItemTaxBreakdownTaxabilityReasonStandardRated TaxCalculationLineItemTaxBreakdownTaxabilityReason = "standard_rated" + TaxCalculationLineItemTaxBreakdownTaxabilityReasonTaxableBasisReduced TaxCalculationLineItemTaxBreakdownTaxabilityReason = "taxable_basis_reduced" + TaxCalculationLineItemTaxBreakdownTaxabilityReasonZeroRated TaxCalculationLineItemTaxBreakdownTaxabilityReason = "zero_rated" +) + +type TaxCalculationLineItemTaxBreakdownJurisdiction struct { + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country string `json:"country"` + // A human-readable name for the jurisdiction imposing the tax. + DisplayName string `json:"display_name"` + // Indicates the level of the jurisdiction imposing the tax. + Level TaxCalculationLineItemTaxBreakdownJurisdictionLevel `json:"level"` + // [ISO 3166-2 subdivision code](https://en.wikipedia.org/wiki/ISO_3166-2), without country prefix. For example, "NY" for New York, United States. + State string `json:"state"` +} + +// Details regarding the rate for this tax. This field will be `null` when the tax is not imposed, for example if the product is exempt from tax. +type TaxCalculationLineItemTaxBreakdownTaxRateDetails struct { + // A localized display name for tax type, intended to be human-readable. For example, "Local Sales and Use Tax", "Value-added tax (VAT)", or "Umsatzsteuer (USt.)". + DisplayName string `json:"display_name"` + // The tax rate percentage as a string. For example, 8.5% is represented as "8.5". + PercentageDecimal string `json:"percentage_decimal"` + // The tax type, such as `vat` or `sales_tax`. + TaxType TaxCalculationLineItemTaxBreakdownTaxRateDetailsTaxType `json:"tax_type"` +} + +// Detailed account of taxes relevant to this line item. +type TaxCalculationLineItemTaxBreakdown struct { + // The amount of tax, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Amount int64 `json:"amount"` + Jurisdiction *TaxCalculationLineItemTaxBreakdownJurisdiction `json:"jurisdiction"` + // Indicates whether the jurisdiction was determined by the origin (merchant's address) or destination (customer's address). + Sourcing TaxCalculationLineItemTaxBreakdownSourcing `json:"sourcing"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason TaxCalculationLineItemTaxBreakdownTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + TaxableAmount int64 `json:"taxable_amount"` + // Details regarding the rate for this tax. This field will be `null` when the tax is not imposed, for example if the product is exempt from tax. + TaxRateDetails *TaxCalculationLineItemTaxBreakdownTaxRateDetails `json:"tax_rate_details"` +} +type TaxCalculationLineItem struct { + // The line item amount in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). If `tax_behavior=inclusive`, then this amount includes taxes. Otherwise, taxes were calculated on top of this amount. + Amount int64 `json:"amount"` + // The amount of tax calculated for this line item, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + AmountTax int64 `json:"amount_tax"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The ID of an existing [Product](https://stripe.com/docs/api/products/object). + Product string `json:"product"` + // The number of units of the item being purchased. For reversals, this is the quantity reversed. + Quantity int64 `json:"quantity"` + // A custom identifier for this line item. + Reference string `json:"reference"` + // Specifies whether the `amount` includes taxes. If `tax_behavior=inclusive`, then the amount includes taxes. + TaxBehavior TaxCalculationLineItemTaxBehavior `json:"tax_behavior"` + // Detailed account of taxes relevant to this line item. + TaxBreakdown []*TaxCalculationLineItemTaxBreakdown `json:"tax_breakdown"` + // The [tax code](https://stripe.com/docs/tax/tax-categories) ID used for this resource. + TaxCode string `json:"tax_code"` +} + +// TaxCalculationLineItemList is a list of CalculationLineItems as retrieved from a list endpoint. +type TaxCalculationLineItemList struct { + APIResource + ListMeta + Data []*TaxCalculationLineItem `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/tax_registration.go b/vendor/github.com/stripe/stripe-go/v82/tax_registration.go new file mode 100644 index 00000000..fb200082 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/tax_registration.go @@ -0,0 +1,4071 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "github.com/stripe/stripe-go/v82/form" + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsAeType string + +// List of values that TaxRegistrationCountryOptionsAeType can take +const ( + TaxRegistrationCountryOptionsAeTypeStandard TaxRegistrationCountryOptionsAeType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsAlType string + +// List of values that TaxRegistrationCountryOptionsAlType can take +const ( + TaxRegistrationCountryOptionsAlTypeStandard TaxRegistrationCountryOptionsAlType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsAmType string + +// List of values that TaxRegistrationCountryOptionsAmType can take +const ( + TaxRegistrationCountryOptionsAmTypeSimplified TaxRegistrationCountryOptionsAmType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsAoType string + +// List of values that TaxRegistrationCountryOptionsAoType can take +const ( + TaxRegistrationCountryOptionsAoTypeStandard TaxRegistrationCountryOptionsAoType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsAtStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsAtStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsAtStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsAtStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsAtStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsAtStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsAtType string + +// List of values that TaxRegistrationCountryOptionsAtType can take +const ( + TaxRegistrationCountryOptionsAtTypeIoss TaxRegistrationCountryOptionsAtType = "ioss" + TaxRegistrationCountryOptionsAtTypeOssNonUnion TaxRegistrationCountryOptionsAtType = "oss_non_union" + TaxRegistrationCountryOptionsAtTypeOssUnion TaxRegistrationCountryOptionsAtType = "oss_union" + TaxRegistrationCountryOptionsAtTypeStandard TaxRegistrationCountryOptionsAtType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsAuType string + +// List of values that TaxRegistrationCountryOptionsAuType can take +const ( + TaxRegistrationCountryOptionsAuTypeStandard TaxRegistrationCountryOptionsAuType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsAwType string + +// List of values that TaxRegistrationCountryOptionsAwType can take +const ( + TaxRegistrationCountryOptionsAwTypeStandard TaxRegistrationCountryOptionsAwType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsAzType string + +// List of values that TaxRegistrationCountryOptionsAzType can take +const ( + TaxRegistrationCountryOptionsAzTypeSimplified TaxRegistrationCountryOptionsAzType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsBaType string + +// List of values that TaxRegistrationCountryOptionsBaType can take +const ( + TaxRegistrationCountryOptionsBaTypeStandard TaxRegistrationCountryOptionsBaType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsBbType string + +// List of values that TaxRegistrationCountryOptionsBbType can take +const ( + TaxRegistrationCountryOptionsBbTypeStandard TaxRegistrationCountryOptionsBbType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsBdType string + +// List of values that TaxRegistrationCountryOptionsBdType can take +const ( + TaxRegistrationCountryOptionsBdTypeStandard TaxRegistrationCountryOptionsBdType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsBeStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsBeStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsBeStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsBeStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsBeStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsBeStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsBeType string + +// List of values that TaxRegistrationCountryOptionsBeType can take +const ( + TaxRegistrationCountryOptionsBeTypeIoss TaxRegistrationCountryOptionsBeType = "ioss" + TaxRegistrationCountryOptionsBeTypeOssNonUnion TaxRegistrationCountryOptionsBeType = "oss_non_union" + TaxRegistrationCountryOptionsBeTypeOssUnion TaxRegistrationCountryOptionsBeType = "oss_union" + TaxRegistrationCountryOptionsBeTypeStandard TaxRegistrationCountryOptionsBeType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsBfType string + +// List of values that TaxRegistrationCountryOptionsBfType can take +const ( + TaxRegistrationCountryOptionsBfTypeStandard TaxRegistrationCountryOptionsBfType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsBGStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsBGStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsBGStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsBGStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsBGStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsBGStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsBGType string + +// List of values that TaxRegistrationCountryOptionsBGType can take +const ( + TaxRegistrationCountryOptionsBGTypeIoss TaxRegistrationCountryOptionsBGType = "ioss" + TaxRegistrationCountryOptionsBGTypeOssNonUnion TaxRegistrationCountryOptionsBGType = "oss_non_union" + TaxRegistrationCountryOptionsBGTypeOssUnion TaxRegistrationCountryOptionsBGType = "oss_union" + TaxRegistrationCountryOptionsBGTypeStandard TaxRegistrationCountryOptionsBGType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsBhType string + +// List of values that TaxRegistrationCountryOptionsBhType can take +const ( + TaxRegistrationCountryOptionsBhTypeStandard TaxRegistrationCountryOptionsBhType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsBjType string + +// List of values that TaxRegistrationCountryOptionsBjType can take +const ( + TaxRegistrationCountryOptionsBjTypeSimplified TaxRegistrationCountryOptionsBjType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsBsType string + +// List of values that TaxRegistrationCountryOptionsBsType can take +const ( + TaxRegistrationCountryOptionsBsTypeStandard TaxRegistrationCountryOptionsBsType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsByType string + +// List of values that TaxRegistrationCountryOptionsByType can take +const ( + TaxRegistrationCountryOptionsByTypeSimplified TaxRegistrationCountryOptionsByType = "simplified" +) + +// Type of registration in Canada. +type TaxRegistrationCountryOptionsCaType string + +// List of values that TaxRegistrationCountryOptionsCaType can take +const ( + TaxRegistrationCountryOptionsCaTypeProvinceStandard TaxRegistrationCountryOptionsCaType = "province_standard" + TaxRegistrationCountryOptionsCaTypeSimplified TaxRegistrationCountryOptionsCaType = "simplified" + TaxRegistrationCountryOptionsCaTypeStandard TaxRegistrationCountryOptionsCaType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsCdType string + +// List of values that TaxRegistrationCountryOptionsCdType can take +const ( + TaxRegistrationCountryOptionsCdTypeStandard TaxRegistrationCountryOptionsCdType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsChType string + +// List of values that TaxRegistrationCountryOptionsChType can take +const ( + TaxRegistrationCountryOptionsChTypeStandard TaxRegistrationCountryOptionsChType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsClType string + +// List of values that TaxRegistrationCountryOptionsClType can take +const ( + TaxRegistrationCountryOptionsClTypeSimplified TaxRegistrationCountryOptionsClType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsCmType string + +// List of values that TaxRegistrationCountryOptionsCmType can take +const ( + TaxRegistrationCountryOptionsCmTypeSimplified TaxRegistrationCountryOptionsCmType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsCoType string + +// List of values that TaxRegistrationCountryOptionsCoType can take +const ( + TaxRegistrationCountryOptionsCoTypeSimplified TaxRegistrationCountryOptionsCoType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsCrType string + +// List of values that TaxRegistrationCountryOptionsCrType can take +const ( + TaxRegistrationCountryOptionsCrTypeSimplified TaxRegistrationCountryOptionsCrType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsCvType string + +// List of values that TaxRegistrationCountryOptionsCvType can take +const ( + TaxRegistrationCountryOptionsCvTypeSimplified TaxRegistrationCountryOptionsCvType = "simplified" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsCyStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsCyStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsCyStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsCyStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsCyStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsCyStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsCyType string + +// List of values that TaxRegistrationCountryOptionsCyType can take +const ( + TaxRegistrationCountryOptionsCyTypeIoss TaxRegistrationCountryOptionsCyType = "ioss" + TaxRegistrationCountryOptionsCyTypeOssNonUnion TaxRegistrationCountryOptionsCyType = "oss_non_union" + TaxRegistrationCountryOptionsCyTypeOssUnion TaxRegistrationCountryOptionsCyType = "oss_union" + TaxRegistrationCountryOptionsCyTypeStandard TaxRegistrationCountryOptionsCyType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsCzStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsCzStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsCzStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsCzStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsCzStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsCzStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsCzType string + +// List of values that TaxRegistrationCountryOptionsCzType can take +const ( + TaxRegistrationCountryOptionsCzTypeIoss TaxRegistrationCountryOptionsCzType = "ioss" + TaxRegistrationCountryOptionsCzTypeOssNonUnion TaxRegistrationCountryOptionsCzType = "oss_non_union" + TaxRegistrationCountryOptionsCzTypeOssUnion TaxRegistrationCountryOptionsCzType = "oss_union" + TaxRegistrationCountryOptionsCzTypeStandard TaxRegistrationCountryOptionsCzType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsDEStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsDEStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsDEStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsDEStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsDEStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsDEStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsDEType string + +// List of values that TaxRegistrationCountryOptionsDEType can take +const ( + TaxRegistrationCountryOptionsDETypeIoss TaxRegistrationCountryOptionsDEType = "ioss" + TaxRegistrationCountryOptionsDETypeOssNonUnion TaxRegistrationCountryOptionsDEType = "oss_non_union" + TaxRegistrationCountryOptionsDETypeOssUnion TaxRegistrationCountryOptionsDEType = "oss_union" + TaxRegistrationCountryOptionsDETypeStandard TaxRegistrationCountryOptionsDEType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsDkStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsDkStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsDkStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsDkStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsDkStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsDkStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsDkType string + +// List of values that TaxRegistrationCountryOptionsDkType can take +const ( + TaxRegistrationCountryOptionsDkTypeIoss TaxRegistrationCountryOptionsDkType = "ioss" + TaxRegistrationCountryOptionsDkTypeOssNonUnion TaxRegistrationCountryOptionsDkType = "oss_non_union" + TaxRegistrationCountryOptionsDkTypeOssUnion TaxRegistrationCountryOptionsDkType = "oss_union" + TaxRegistrationCountryOptionsDkTypeStandard TaxRegistrationCountryOptionsDkType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsEcType string + +// List of values that TaxRegistrationCountryOptionsEcType can take +const ( + TaxRegistrationCountryOptionsEcTypeSimplified TaxRegistrationCountryOptionsEcType = "simplified" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsEeStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsEeStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsEeStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsEeStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsEeStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsEeStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsEeType string + +// List of values that TaxRegistrationCountryOptionsEeType can take +const ( + TaxRegistrationCountryOptionsEeTypeIoss TaxRegistrationCountryOptionsEeType = "ioss" + TaxRegistrationCountryOptionsEeTypeOssNonUnion TaxRegistrationCountryOptionsEeType = "oss_non_union" + TaxRegistrationCountryOptionsEeTypeOssUnion TaxRegistrationCountryOptionsEeType = "oss_union" + TaxRegistrationCountryOptionsEeTypeStandard TaxRegistrationCountryOptionsEeType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsEgType string + +// List of values that TaxRegistrationCountryOptionsEgType can take +const ( + TaxRegistrationCountryOptionsEgTypeSimplified TaxRegistrationCountryOptionsEgType = "simplified" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsESStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsESStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsESStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsESStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsESStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsESStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsESType string + +// List of values that TaxRegistrationCountryOptionsESType can take +const ( + TaxRegistrationCountryOptionsESTypeIoss TaxRegistrationCountryOptionsESType = "ioss" + TaxRegistrationCountryOptionsESTypeOssNonUnion TaxRegistrationCountryOptionsESType = "oss_non_union" + TaxRegistrationCountryOptionsESTypeOssUnion TaxRegistrationCountryOptionsESType = "oss_union" + TaxRegistrationCountryOptionsESTypeStandard TaxRegistrationCountryOptionsESType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsETType string + +// List of values that TaxRegistrationCountryOptionsETType can take +const ( + TaxRegistrationCountryOptionsETTypeStandard TaxRegistrationCountryOptionsETType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsFIStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsFIStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsFIStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsFIStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsFIStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsFIStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsFIType string + +// List of values that TaxRegistrationCountryOptionsFIType can take +const ( + TaxRegistrationCountryOptionsFITypeIoss TaxRegistrationCountryOptionsFIType = "ioss" + TaxRegistrationCountryOptionsFITypeOssNonUnion TaxRegistrationCountryOptionsFIType = "oss_non_union" + TaxRegistrationCountryOptionsFITypeOssUnion TaxRegistrationCountryOptionsFIType = "oss_union" + TaxRegistrationCountryOptionsFITypeStandard TaxRegistrationCountryOptionsFIType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsFRStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsFRStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsFRStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsFRStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsFRStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsFRStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsFRType string + +// List of values that TaxRegistrationCountryOptionsFRType can take +const ( + TaxRegistrationCountryOptionsFRTypeIoss TaxRegistrationCountryOptionsFRType = "ioss" + TaxRegistrationCountryOptionsFRTypeOssNonUnion TaxRegistrationCountryOptionsFRType = "oss_non_union" + TaxRegistrationCountryOptionsFRTypeOssUnion TaxRegistrationCountryOptionsFRType = "oss_union" + TaxRegistrationCountryOptionsFRTypeStandard TaxRegistrationCountryOptionsFRType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsGBType string + +// List of values that TaxRegistrationCountryOptionsGBType can take +const ( + TaxRegistrationCountryOptionsGBTypeStandard TaxRegistrationCountryOptionsGBType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsGeType string + +// List of values that TaxRegistrationCountryOptionsGeType can take +const ( + TaxRegistrationCountryOptionsGeTypeSimplified TaxRegistrationCountryOptionsGeType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsGnType string + +// List of values that TaxRegistrationCountryOptionsGnType can take +const ( + TaxRegistrationCountryOptionsGnTypeStandard TaxRegistrationCountryOptionsGnType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsGrStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsGrStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsGrStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsGrStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsGrStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsGrStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsGrType string + +// List of values that TaxRegistrationCountryOptionsGrType can take +const ( + TaxRegistrationCountryOptionsGrTypeIoss TaxRegistrationCountryOptionsGrType = "ioss" + TaxRegistrationCountryOptionsGrTypeOssNonUnion TaxRegistrationCountryOptionsGrType = "oss_non_union" + TaxRegistrationCountryOptionsGrTypeOssUnion TaxRegistrationCountryOptionsGrType = "oss_union" + TaxRegistrationCountryOptionsGrTypeStandard TaxRegistrationCountryOptionsGrType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsHRStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsHRStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsHRStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsHRStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsHRStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsHRStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsHRType string + +// List of values that TaxRegistrationCountryOptionsHRType can take +const ( + TaxRegistrationCountryOptionsHRTypeIoss TaxRegistrationCountryOptionsHRType = "ioss" + TaxRegistrationCountryOptionsHRTypeOssNonUnion TaxRegistrationCountryOptionsHRType = "oss_non_union" + TaxRegistrationCountryOptionsHRTypeOssUnion TaxRegistrationCountryOptionsHRType = "oss_union" + TaxRegistrationCountryOptionsHRTypeStandard TaxRegistrationCountryOptionsHRType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsHUStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsHUStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsHUStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsHUStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsHUStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsHUStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsHUType string + +// List of values that TaxRegistrationCountryOptionsHUType can take +const ( + TaxRegistrationCountryOptionsHUTypeIoss TaxRegistrationCountryOptionsHUType = "ioss" + TaxRegistrationCountryOptionsHUTypeOssNonUnion TaxRegistrationCountryOptionsHUType = "oss_non_union" + TaxRegistrationCountryOptionsHUTypeOssUnion TaxRegistrationCountryOptionsHUType = "oss_union" + TaxRegistrationCountryOptionsHUTypeStandard TaxRegistrationCountryOptionsHUType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsIDType string + +// List of values that TaxRegistrationCountryOptionsIDType can take +const ( + TaxRegistrationCountryOptionsIDTypeSimplified TaxRegistrationCountryOptionsIDType = "simplified" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsIeStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsIeStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsIeStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsIeStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsIeStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsIeStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsIeType string + +// List of values that TaxRegistrationCountryOptionsIeType can take +const ( + TaxRegistrationCountryOptionsIeTypeIoss TaxRegistrationCountryOptionsIeType = "ioss" + TaxRegistrationCountryOptionsIeTypeOssNonUnion TaxRegistrationCountryOptionsIeType = "oss_non_union" + TaxRegistrationCountryOptionsIeTypeOssUnion TaxRegistrationCountryOptionsIeType = "oss_union" + TaxRegistrationCountryOptionsIeTypeStandard TaxRegistrationCountryOptionsIeType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsInType string + +// List of values that TaxRegistrationCountryOptionsInType can take +const ( + TaxRegistrationCountryOptionsInTypeSimplified TaxRegistrationCountryOptionsInType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsIsType string + +// List of values that TaxRegistrationCountryOptionsIsType can take +const ( + TaxRegistrationCountryOptionsIsTypeStandard TaxRegistrationCountryOptionsIsType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsITStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsITStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsITStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsITStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsITStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsITStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsITType string + +// List of values that TaxRegistrationCountryOptionsITType can take +const ( + TaxRegistrationCountryOptionsITTypeIoss TaxRegistrationCountryOptionsITType = "ioss" + TaxRegistrationCountryOptionsITTypeOssNonUnion TaxRegistrationCountryOptionsITType = "oss_non_union" + TaxRegistrationCountryOptionsITTypeOssUnion TaxRegistrationCountryOptionsITType = "oss_union" + TaxRegistrationCountryOptionsITTypeStandard TaxRegistrationCountryOptionsITType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsJPType string + +// List of values that TaxRegistrationCountryOptionsJPType can take +const ( + TaxRegistrationCountryOptionsJPTypeStandard TaxRegistrationCountryOptionsJPType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsKeType string + +// List of values that TaxRegistrationCountryOptionsKeType can take +const ( + TaxRegistrationCountryOptionsKeTypeSimplified TaxRegistrationCountryOptionsKeType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsKgType string + +// List of values that TaxRegistrationCountryOptionsKgType can take +const ( + TaxRegistrationCountryOptionsKgTypeSimplified TaxRegistrationCountryOptionsKgType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsKhType string + +// List of values that TaxRegistrationCountryOptionsKhType can take +const ( + TaxRegistrationCountryOptionsKhTypeSimplified TaxRegistrationCountryOptionsKhType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsKrType string + +// List of values that TaxRegistrationCountryOptionsKrType can take +const ( + TaxRegistrationCountryOptionsKrTypeSimplified TaxRegistrationCountryOptionsKrType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsKzType string + +// List of values that TaxRegistrationCountryOptionsKzType can take +const ( + TaxRegistrationCountryOptionsKzTypeSimplified TaxRegistrationCountryOptionsKzType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsLaType string + +// List of values that TaxRegistrationCountryOptionsLaType can take +const ( + TaxRegistrationCountryOptionsLaTypeSimplified TaxRegistrationCountryOptionsLaType = "simplified" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsLTStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsLTStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsLTStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsLTStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsLTStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsLTStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsLTType string + +// List of values that TaxRegistrationCountryOptionsLTType can take +const ( + TaxRegistrationCountryOptionsLTTypeIoss TaxRegistrationCountryOptionsLTType = "ioss" + TaxRegistrationCountryOptionsLTTypeOssNonUnion TaxRegistrationCountryOptionsLTType = "oss_non_union" + TaxRegistrationCountryOptionsLTTypeOssUnion TaxRegistrationCountryOptionsLTType = "oss_union" + TaxRegistrationCountryOptionsLTTypeStandard TaxRegistrationCountryOptionsLTType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsLuStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsLuStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsLuStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsLuStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsLuStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsLuStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsLuType string + +// List of values that TaxRegistrationCountryOptionsLuType can take +const ( + TaxRegistrationCountryOptionsLuTypeIoss TaxRegistrationCountryOptionsLuType = "ioss" + TaxRegistrationCountryOptionsLuTypeOssNonUnion TaxRegistrationCountryOptionsLuType = "oss_non_union" + TaxRegistrationCountryOptionsLuTypeOssUnion TaxRegistrationCountryOptionsLuType = "oss_union" + TaxRegistrationCountryOptionsLuTypeStandard TaxRegistrationCountryOptionsLuType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsLVStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsLVStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsLVStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsLVStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsLVStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsLVStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsLVType string + +// List of values that TaxRegistrationCountryOptionsLVType can take +const ( + TaxRegistrationCountryOptionsLVTypeIoss TaxRegistrationCountryOptionsLVType = "ioss" + TaxRegistrationCountryOptionsLVTypeOssNonUnion TaxRegistrationCountryOptionsLVType = "oss_non_union" + TaxRegistrationCountryOptionsLVTypeOssUnion TaxRegistrationCountryOptionsLVType = "oss_union" + TaxRegistrationCountryOptionsLVTypeStandard TaxRegistrationCountryOptionsLVType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsMaType string + +// List of values that TaxRegistrationCountryOptionsMaType can take +const ( + TaxRegistrationCountryOptionsMaTypeSimplified TaxRegistrationCountryOptionsMaType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsMdType string + +// List of values that TaxRegistrationCountryOptionsMdType can take +const ( + TaxRegistrationCountryOptionsMdTypeSimplified TaxRegistrationCountryOptionsMdType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsMeType string + +// List of values that TaxRegistrationCountryOptionsMeType can take +const ( + TaxRegistrationCountryOptionsMeTypeStandard TaxRegistrationCountryOptionsMeType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsMkType string + +// List of values that TaxRegistrationCountryOptionsMkType can take +const ( + TaxRegistrationCountryOptionsMkTypeStandard TaxRegistrationCountryOptionsMkType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsMrType string + +// List of values that TaxRegistrationCountryOptionsMrType can take +const ( + TaxRegistrationCountryOptionsMrTypeStandard TaxRegistrationCountryOptionsMrType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsMTStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsMTStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsMTStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsMTStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsMTStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsMTStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsMTType string + +// List of values that TaxRegistrationCountryOptionsMTType can take +const ( + TaxRegistrationCountryOptionsMTTypeIoss TaxRegistrationCountryOptionsMTType = "ioss" + TaxRegistrationCountryOptionsMTTypeOssNonUnion TaxRegistrationCountryOptionsMTType = "oss_non_union" + TaxRegistrationCountryOptionsMTTypeOssUnion TaxRegistrationCountryOptionsMTType = "oss_union" + TaxRegistrationCountryOptionsMTTypeStandard TaxRegistrationCountryOptionsMTType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsMXType string + +// List of values that TaxRegistrationCountryOptionsMXType can take +const ( + TaxRegistrationCountryOptionsMXTypeSimplified TaxRegistrationCountryOptionsMXType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsMyType string + +// List of values that TaxRegistrationCountryOptionsMyType can take +const ( + TaxRegistrationCountryOptionsMyTypeSimplified TaxRegistrationCountryOptionsMyType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsNgType string + +// List of values that TaxRegistrationCountryOptionsNgType can take +const ( + TaxRegistrationCountryOptionsNgTypeSimplified TaxRegistrationCountryOptionsNgType = "simplified" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsNLStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsNLStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsNLStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsNLStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsNLStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsNLStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsNLType string + +// List of values that TaxRegistrationCountryOptionsNLType can take +const ( + TaxRegistrationCountryOptionsNLTypeIoss TaxRegistrationCountryOptionsNLType = "ioss" + TaxRegistrationCountryOptionsNLTypeOssNonUnion TaxRegistrationCountryOptionsNLType = "oss_non_union" + TaxRegistrationCountryOptionsNLTypeOssUnion TaxRegistrationCountryOptionsNLType = "oss_union" + TaxRegistrationCountryOptionsNLTypeStandard TaxRegistrationCountryOptionsNLType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsNoType string + +// List of values that TaxRegistrationCountryOptionsNoType can take +const ( + TaxRegistrationCountryOptionsNoTypeStandard TaxRegistrationCountryOptionsNoType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsNpType string + +// List of values that TaxRegistrationCountryOptionsNpType can take +const ( + TaxRegistrationCountryOptionsNpTypeSimplified TaxRegistrationCountryOptionsNpType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsNzType string + +// List of values that TaxRegistrationCountryOptionsNzType can take +const ( + TaxRegistrationCountryOptionsNzTypeStandard TaxRegistrationCountryOptionsNzType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsOmType string + +// List of values that TaxRegistrationCountryOptionsOmType can take +const ( + TaxRegistrationCountryOptionsOmTypeStandard TaxRegistrationCountryOptionsOmType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsPeType string + +// List of values that TaxRegistrationCountryOptionsPeType can take +const ( + TaxRegistrationCountryOptionsPeTypeSimplified TaxRegistrationCountryOptionsPeType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsPhType string + +// List of values that TaxRegistrationCountryOptionsPhType can take +const ( + TaxRegistrationCountryOptionsPhTypeSimplified TaxRegistrationCountryOptionsPhType = "simplified" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsPLStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsPLStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsPLStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsPLStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsPLStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsPLStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsPLType string + +// List of values that TaxRegistrationCountryOptionsPLType can take +const ( + TaxRegistrationCountryOptionsPLTypeIoss TaxRegistrationCountryOptionsPLType = "ioss" + TaxRegistrationCountryOptionsPLTypeOssNonUnion TaxRegistrationCountryOptionsPLType = "oss_non_union" + TaxRegistrationCountryOptionsPLTypeOssUnion TaxRegistrationCountryOptionsPLType = "oss_union" + TaxRegistrationCountryOptionsPLTypeStandard TaxRegistrationCountryOptionsPLType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsPTStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsPTStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsPTStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsPTStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsPTStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsPTStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsPTType string + +// List of values that TaxRegistrationCountryOptionsPTType can take +const ( + TaxRegistrationCountryOptionsPTTypeIoss TaxRegistrationCountryOptionsPTType = "ioss" + TaxRegistrationCountryOptionsPTTypeOssNonUnion TaxRegistrationCountryOptionsPTType = "oss_non_union" + TaxRegistrationCountryOptionsPTTypeOssUnion TaxRegistrationCountryOptionsPTType = "oss_union" + TaxRegistrationCountryOptionsPTTypeStandard TaxRegistrationCountryOptionsPTType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsROStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsROStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsROStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsROStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsROStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsROStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsROType string + +// List of values that TaxRegistrationCountryOptionsROType can take +const ( + TaxRegistrationCountryOptionsROTypeIoss TaxRegistrationCountryOptionsROType = "ioss" + TaxRegistrationCountryOptionsROTypeOssNonUnion TaxRegistrationCountryOptionsROType = "oss_non_union" + TaxRegistrationCountryOptionsROTypeOssUnion TaxRegistrationCountryOptionsROType = "oss_union" + TaxRegistrationCountryOptionsROTypeStandard TaxRegistrationCountryOptionsROType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsRsType string + +// List of values that TaxRegistrationCountryOptionsRsType can take +const ( + TaxRegistrationCountryOptionsRsTypeStandard TaxRegistrationCountryOptionsRsType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsRUType string + +// List of values that TaxRegistrationCountryOptionsRUType can take +const ( + TaxRegistrationCountryOptionsRUTypeSimplified TaxRegistrationCountryOptionsRUType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsSaType string + +// List of values that TaxRegistrationCountryOptionsSaType can take +const ( + TaxRegistrationCountryOptionsSaTypeSimplified TaxRegistrationCountryOptionsSaType = "simplified" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsSeStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsSeStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsSeStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsSeStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsSeStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsSeStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsSeType string + +// List of values that TaxRegistrationCountryOptionsSeType can take +const ( + TaxRegistrationCountryOptionsSeTypeIoss TaxRegistrationCountryOptionsSeType = "ioss" + TaxRegistrationCountryOptionsSeTypeOssNonUnion TaxRegistrationCountryOptionsSeType = "oss_non_union" + TaxRegistrationCountryOptionsSeTypeOssUnion TaxRegistrationCountryOptionsSeType = "oss_union" + TaxRegistrationCountryOptionsSeTypeStandard TaxRegistrationCountryOptionsSeType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsSgType string + +// List of values that TaxRegistrationCountryOptionsSgType can take +const ( + TaxRegistrationCountryOptionsSgTypeStandard TaxRegistrationCountryOptionsSgType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsSiStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsSiStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsSiStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsSiStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsSiStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsSiStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsSiType string + +// List of values that TaxRegistrationCountryOptionsSiType can take +const ( + TaxRegistrationCountryOptionsSiTypeIoss TaxRegistrationCountryOptionsSiType = "ioss" + TaxRegistrationCountryOptionsSiTypeOssNonUnion TaxRegistrationCountryOptionsSiType = "oss_non_union" + TaxRegistrationCountryOptionsSiTypeOssUnion TaxRegistrationCountryOptionsSiType = "oss_union" + TaxRegistrationCountryOptionsSiTypeStandard TaxRegistrationCountryOptionsSiType = "standard" +) + +// Place of supply scheme used in an EU standard registration. +type TaxRegistrationCountryOptionsSKStandardPlaceOfSupplyScheme string + +// List of values that TaxRegistrationCountryOptionsSKStandardPlaceOfSupplyScheme can take +const ( + TaxRegistrationCountryOptionsSKStandardPlaceOfSupplySchemeSmallSeller TaxRegistrationCountryOptionsSKStandardPlaceOfSupplyScheme = "small_seller" + TaxRegistrationCountryOptionsSKStandardPlaceOfSupplySchemeStandard TaxRegistrationCountryOptionsSKStandardPlaceOfSupplyScheme = "standard" +) + +// Type of registration in an EU country. +type TaxRegistrationCountryOptionsSKType string + +// List of values that TaxRegistrationCountryOptionsSKType can take +const ( + TaxRegistrationCountryOptionsSKTypeIoss TaxRegistrationCountryOptionsSKType = "ioss" + TaxRegistrationCountryOptionsSKTypeOssNonUnion TaxRegistrationCountryOptionsSKType = "oss_non_union" + TaxRegistrationCountryOptionsSKTypeOssUnion TaxRegistrationCountryOptionsSKType = "oss_union" + TaxRegistrationCountryOptionsSKTypeStandard TaxRegistrationCountryOptionsSKType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsSnType string + +// List of values that TaxRegistrationCountryOptionsSnType can take +const ( + TaxRegistrationCountryOptionsSnTypeSimplified TaxRegistrationCountryOptionsSnType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsSrType string + +// List of values that TaxRegistrationCountryOptionsSrType can take +const ( + TaxRegistrationCountryOptionsSrTypeStandard TaxRegistrationCountryOptionsSrType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsTHType string + +// List of values that TaxRegistrationCountryOptionsTHType can take +const ( + TaxRegistrationCountryOptionsTHTypeSimplified TaxRegistrationCountryOptionsTHType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsTjType string + +// List of values that TaxRegistrationCountryOptionsTjType can take +const ( + TaxRegistrationCountryOptionsTjTypeSimplified TaxRegistrationCountryOptionsTjType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsTRType string + +// List of values that TaxRegistrationCountryOptionsTRType can take +const ( + TaxRegistrationCountryOptionsTRTypeSimplified TaxRegistrationCountryOptionsTRType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsTzType string + +// List of values that TaxRegistrationCountryOptionsTzType can take +const ( + TaxRegistrationCountryOptionsTzTypeSimplified TaxRegistrationCountryOptionsTzType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsUaType string + +// List of values that TaxRegistrationCountryOptionsUaType can take +const ( + TaxRegistrationCountryOptionsUaTypeSimplified TaxRegistrationCountryOptionsUaType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsUgType string + +// List of values that TaxRegistrationCountryOptionsUgType can take +const ( + TaxRegistrationCountryOptionsUgTypeSimplified TaxRegistrationCountryOptionsUgType = "simplified" +) + +// The type of the election for the state sales tax registration. +type TaxRegistrationCountryOptionsUSStateSalesTaxElectionType string + +// List of values that TaxRegistrationCountryOptionsUSStateSalesTaxElectionType can take +const ( + TaxRegistrationCountryOptionsUSStateSalesTaxElectionTypeLocalUseTax TaxRegistrationCountryOptionsUSStateSalesTaxElectionType = "local_use_tax" + TaxRegistrationCountryOptionsUSStateSalesTaxElectionTypeSimplifiedSellersUseTax TaxRegistrationCountryOptionsUSStateSalesTaxElectionType = "simplified_sellers_use_tax" + TaxRegistrationCountryOptionsUSStateSalesTaxElectionTypeSingleLocalUseTax TaxRegistrationCountryOptionsUSStateSalesTaxElectionType = "single_local_use_tax" +) + +// Type of registration in the US. +type TaxRegistrationCountryOptionsUSType string + +// List of values that TaxRegistrationCountryOptionsUSType can take +const ( + TaxRegistrationCountryOptionsUSTypeLocalAmusementTax TaxRegistrationCountryOptionsUSType = "local_amusement_tax" + TaxRegistrationCountryOptionsUSTypeLocalLeaseTax TaxRegistrationCountryOptionsUSType = "local_lease_tax" + TaxRegistrationCountryOptionsUSTypeStateCommunicationsTax TaxRegistrationCountryOptionsUSType = "state_communications_tax" + TaxRegistrationCountryOptionsUSTypeStateRetailDeliveryFee TaxRegistrationCountryOptionsUSType = "state_retail_delivery_fee" + TaxRegistrationCountryOptionsUSTypeStateSalesTax TaxRegistrationCountryOptionsUSType = "state_sales_tax" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsUyType string + +// List of values that TaxRegistrationCountryOptionsUyType can take +const ( + TaxRegistrationCountryOptionsUyTypeStandard TaxRegistrationCountryOptionsUyType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsUzType string + +// List of values that TaxRegistrationCountryOptionsUzType can take +const ( + TaxRegistrationCountryOptionsUzTypeSimplified TaxRegistrationCountryOptionsUzType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsVnType string + +// List of values that TaxRegistrationCountryOptionsVnType can take +const ( + TaxRegistrationCountryOptionsVnTypeSimplified TaxRegistrationCountryOptionsVnType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsZaType string + +// List of values that TaxRegistrationCountryOptionsZaType can take +const ( + TaxRegistrationCountryOptionsZaTypeStandard TaxRegistrationCountryOptionsZaType = "standard" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsZmType string + +// List of values that TaxRegistrationCountryOptionsZmType can take +const ( + TaxRegistrationCountryOptionsZmTypeSimplified TaxRegistrationCountryOptionsZmType = "simplified" +) + +// Type of registration in `country`. +type TaxRegistrationCountryOptionsZwType string + +// List of values that TaxRegistrationCountryOptionsZwType can take +const ( + TaxRegistrationCountryOptionsZwTypeStandard TaxRegistrationCountryOptionsZwType = "standard" +) + +// The status of the registration. This field is present for convenience and can be deduced from `active_from` and `expires_at`. +type TaxRegistrationStatus string + +// List of values that TaxRegistrationStatus can take +const ( + TaxRegistrationStatusActive TaxRegistrationStatus = "active" + TaxRegistrationStatusExpired TaxRegistrationStatus = "expired" + TaxRegistrationStatusScheduled TaxRegistrationStatus = "scheduled" +) + +// Returns a list of Tax Registration objects. +type TaxRegistrationListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The status of the Tax Registration. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *TaxRegistrationListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Options for the registration in AE. +type TaxRegistrationCountryOptionsAeParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in AL. +type TaxRegistrationCountryOptionsAlParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in AM. +type TaxRegistrationCountryOptionsAmParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in AO. +type TaxRegistrationCountryOptionsAoParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsAtStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in AT. +type TaxRegistrationCountryOptionsAtParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsAtStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in AU. +type TaxRegistrationCountryOptionsAuParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in AW. +type TaxRegistrationCountryOptionsAwParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in AZ. +type TaxRegistrationCountryOptionsAzParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in BA. +type TaxRegistrationCountryOptionsBaParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in BB. +type TaxRegistrationCountryOptionsBbParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in BD. +type TaxRegistrationCountryOptionsBdParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsBeStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in BE. +type TaxRegistrationCountryOptionsBeParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsBeStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in BF. +type TaxRegistrationCountryOptionsBfParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsBGStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in BG. +type TaxRegistrationCountryOptionsBGParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsBGStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in BH. +type TaxRegistrationCountryOptionsBhParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in BJ. +type TaxRegistrationCountryOptionsBjParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in BS. +type TaxRegistrationCountryOptionsBsParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in BY. +type TaxRegistrationCountryOptionsByParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the provincial tax registration. +type TaxRegistrationCountryOptionsCaProvinceStandardParams struct { + // Two-letter CA province code ([ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2)). + Province *string `form:"province"` +} + +// Options for the registration in CA. +type TaxRegistrationCountryOptionsCaParams struct { + // Options for the provincial tax registration. + ProvinceStandard *TaxRegistrationCountryOptionsCaProvinceStandardParams `form:"province_standard"` + // Type of registration to be created in Canada. + Type *string `form:"type"` +} + +// Options for the registration in CD. +type TaxRegistrationCountryOptionsCdParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in CH. +type TaxRegistrationCountryOptionsChParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in CL. +type TaxRegistrationCountryOptionsClParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in CM. +type TaxRegistrationCountryOptionsCmParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in CO. +type TaxRegistrationCountryOptionsCoParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in CR. +type TaxRegistrationCountryOptionsCrParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in CV. +type TaxRegistrationCountryOptionsCvParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsCyStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in CY. +type TaxRegistrationCountryOptionsCyParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsCyStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsCzStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in CZ. +type TaxRegistrationCountryOptionsCzParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsCzStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsDEStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in DE. +type TaxRegistrationCountryOptionsDEParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsDEStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsDkStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in DK. +type TaxRegistrationCountryOptionsDkParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsDkStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in EC. +type TaxRegistrationCountryOptionsEcParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsEeStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in EE. +type TaxRegistrationCountryOptionsEeParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsEeStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in EG. +type TaxRegistrationCountryOptionsEgParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsESStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in ES. +type TaxRegistrationCountryOptionsESParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsESStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in ET. +type TaxRegistrationCountryOptionsETParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsFIStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in FI. +type TaxRegistrationCountryOptionsFIParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsFIStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsFRStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in FR. +type TaxRegistrationCountryOptionsFRParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsFRStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in GB. +type TaxRegistrationCountryOptionsGBParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in GE. +type TaxRegistrationCountryOptionsGeParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in GN. +type TaxRegistrationCountryOptionsGnParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsGrStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in GR. +type TaxRegistrationCountryOptionsGrParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsGrStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsHRStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in HR. +type TaxRegistrationCountryOptionsHRParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsHRStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsHUStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in HU. +type TaxRegistrationCountryOptionsHUParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsHUStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in ID. +type TaxRegistrationCountryOptionsIDParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsIeStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in IE. +type TaxRegistrationCountryOptionsIeParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsIeStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in IN. +type TaxRegistrationCountryOptionsInParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in IS. +type TaxRegistrationCountryOptionsIsParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsITStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in IT. +type TaxRegistrationCountryOptionsITParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsITStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in JP. +type TaxRegistrationCountryOptionsJPParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in KE. +type TaxRegistrationCountryOptionsKeParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in KG. +type TaxRegistrationCountryOptionsKgParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in KH. +type TaxRegistrationCountryOptionsKhParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in KR. +type TaxRegistrationCountryOptionsKrParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in KZ. +type TaxRegistrationCountryOptionsKzParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in LA. +type TaxRegistrationCountryOptionsLaParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsLTStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in LT. +type TaxRegistrationCountryOptionsLTParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsLTStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsLuStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in LU. +type TaxRegistrationCountryOptionsLuParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsLuStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsLVStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in LV. +type TaxRegistrationCountryOptionsLVParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsLVStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in MA. +type TaxRegistrationCountryOptionsMaParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in MD. +type TaxRegistrationCountryOptionsMdParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in ME. +type TaxRegistrationCountryOptionsMeParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in MK. +type TaxRegistrationCountryOptionsMkParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in MR. +type TaxRegistrationCountryOptionsMrParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsMTStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in MT. +type TaxRegistrationCountryOptionsMTParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsMTStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in MX. +type TaxRegistrationCountryOptionsMXParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in MY. +type TaxRegistrationCountryOptionsMyParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in NG. +type TaxRegistrationCountryOptionsNgParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsNLStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in NL. +type TaxRegistrationCountryOptionsNLParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsNLStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in NO. +type TaxRegistrationCountryOptionsNoParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in NP. +type TaxRegistrationCountryOptionsNpParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in NZ. +type TaxRegistrationCountryOptionsNzParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in OM. +type TaxRegistrationCountryOptionsOmParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in PE. +type TaxRegistrationCountryOptionsPeParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in PH. +type TaxRegistrationCountryOptionsPhParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsPLStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in PL. +type TaxRegistrationCountryOptionsPLParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsPLStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsPTStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in PT. +type TaxRegistrationCountryOptionsPTParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsPTStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsROStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in RO. +type TaxRegistrationCountryOptionsROParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsROStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in RS. +type TaxRegistrationCountryOptionsRsParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in RU. +type TaxRegistrationCountryOptionsRUParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in SA. +type TaxRegistrationCountryOptionsSaParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsSeStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in SE. +type TaxRegistrationCountryOptionsSeParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsSeStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in SG. +type TaxRegistrationCountryOptionsSgParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsSiStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in SI. +type TaxRegistrationCountryOptionsSiParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsSiStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCountryOptionsSKStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in SK. +type TaxRegistrationCountryOptionsSKParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCountryOptionsSKStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in SN. +type TaxRegistrationCountryOptionsSnParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in SR. +type TaxRegistrationCountryOptionsSrParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in TH. +type TaxRegistrationCountryOptionsTHParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in TJ. +type TaxRegistrationCountryOptionsTjParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in TR. +type TaxRegistrationCountryOptionsTRParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in TZ. +type TaxRegistrationCountryOptionsTzParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in UA. +type TaxRegistrationCountryOptionsUaParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in UG. +type TaxRegistrationCountryOptionsUgParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the local amusement tax registration. +type TaxRegistrationCountryOptionsUSLocalAmusementTaxParams struct { + // A [FIPS code](https://www.census.gov/library/reference/code-lists/ansi.html) representing the local jurisdiction. Supported FIPS codes are: `14000` (Chicago), `06613` (Bloomington), `21696` (East Dundee), `24582` (Evanston), `45421` (Lynwood), `48892` (Midlothian), `64343` (River Grove), and `68081` (Schiller Park). + Jurisdiction *string `form:"jurisdiction"` +} + +// Options for the local lease tax registration. +type TaxRegistrationCountryOptionsUSLocalLeaseTaxParams struct { + // A [FIPS code](https://www.census.gov/library/reference/code-lists/ansi.html) representing the local jurisdiction. Supported FIPS codes are: `14000` (Chicago). + Jurisdiction *string `form:"jurisdiction"` +} + +// Elections for the state sales tax registration. +type TaxRegistrationCountryOptionsUSStateSalesTaxElectionParams struct { + // A [FIPS code](https://www.census.gov/library/reference/code-lists/ansi.html) representing the local jurisdiction. Supported FIPS codes are: `003` (Allegheny County) and `60000` (Philadelphia City). + Jurisdiction *string `form:"jurisdiction"` + // The type of the election for the state sales tax registration. + Type *string `form:"type"` +} + +// Options for the state sales tax registration. +type TaxRegistrationCountryOptionsUSStateSalesTaxParams struct { + // Elections for the state sales tax registration. + Elections []*TaxRegistrationCountryOptionsUSStateSalesTaxElectionParams `form:"elections"` +} + +// Options for the registration in US. +type TaxRegistrationCountryOptionsUSParams struct { + // Options for the local amusement tax registration. + LocalAmusementTax *TaxRegistrationCountryOptionsUSLocalAmusementTaxParams `form:"local_amusement_tax"` + // Options for the local lease tax registration. + LocalLeaseTax *TaxRegistrationCountryOptionsUSLocalLeaseTaxParams `form:"local_lease_tax"` + // Two-letter US state code ([ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2)). + State *string `form:"state"` + // Options for the state sales tax registration. + StateSalesTax *TaxRegistrationCountryOptionsUSStateSalesTaxParams `form:"state_sales_tax"` + // Type of registration to be created in the US. + Type *string `form:"type"` +} + +// Options for the registration in UY. +type TaxRegistrationCountryOptionsUyParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in UZ. +type TaxRegistrationCountryOptionsUzParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in VN. +type TaxRegistrationCountryOptionsVnParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in ZA. +type TaxRegistrationCountryOptionsZaParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in ZM. +type TaxRegistrationCountryOptionsZmParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in ZW. +type TaxRegistrationCountryOptionsZwParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Specific options for a registration in the specified `country`. +type TaxRegistrationCountryOptionsParams struct { + // Options for the registration in AE. + Ae *TaxRegistrationCountryOptionsAeParams `form:"ae"` + // Options for the registration in AL. + Al *TaxRegistrationCountryOptionsAlParams `form:"al"` + // Options for the registration in AM. + Am *TaxRegistrationCountryOptionsAmParams `form:"am"` + // Options for the registration in AO. + Ao *TaxRegistrationCountryOptionsAoParams `form:"ao"` + // Options for the registration in AT. + At *TaxRegistrationCountryOptionsAtParams `form:"at"` + // Options for the registration in AU. + Au *TaxRegistrationCountryOptionsAuParams `form:"au"` + // Options for the registration in AW. + Aw *TaxRegistrationCountryOptionsAwParams `form:"aw"` + // Options for the registration in AZ. + Az *TaxRegistrationCountryOptionsAzParams `form:"az"` + // Options for the registration in BA. + Ba *TaxRegistrationCountryOptionsBaParams `form:"ba"` + // Options for the registration in BB. + Bb *TaxRegistrationCountryOptionsBbParams `form:"bb"` + // Options for the registration in BD. + Bd *TaxRegistrationCountryOptionsBdParams `form:"bd"` + // Options for the registration in BE. + Be *TaxRegistrationCountryOptionsBeParams `form:"be"` + // Options for the registration in BF. + Bf *TaxRegistrationCountryOptionsBfParams `form:"bf"` + // Options for the registration in BG. + BG *TaxRegistrationCountryOptionsBGParams `form:"bg"` + // Options for the registration in BH. + Bh *TaxRegistrationCountryOptionsBhParams `form:"bh"` + // Options for the registration in BJ. + Bj *TaxRegistrationCountryOptionsBjParams `form:"bj"` + // Options for the registration in BS. + Bs *TaxRegistrationCountryOptionsBsParams `form:"bs"` + // Options for the registration in BY. + By *TaxRegistrationCountryOptionsByParams `form:"by"` + // Options for the registration in CA. + Ca *TaxRegistrationCountryOptionsCaParams `form:"ca"` + // Options for the registration in CD. + Cd *TaxRegistrationCountryOptionsCdParams `form:"cd"` + // Options for the registration in CH. + Ch *TaxRegistrationCountryOptionsChParams `form:"ch"` + // Options for the registration in CL. + Cl *TaxRegistrationCountryOptionsClParams `form:"cl"` + // Options for the registration in CM. + Cm *TaxRegistrationCountryOptionsCmParams `form:"cm"` + // Options for the registration in CO. + Co *TaxRegistrationCountryOptionsCoParams `form:"co"` + // Options for the registration in CR. + Cr *TaxRegistrationCountryOptionsCrParams `form:"cr"` + // Options for the registration in CV. + Cv *TaxRegistrationCountryOptionsCvParams `form:"cv"` + // Options for the registration in CY. + Cy *TaxRegistrationCountryOptionsCyParams `form:"cy"` + // Options for the registration in CZ. + Cz *TaxRegistrationCountryOptionsCzParams `form:"cz"` + // Options for the registration in DE. + DE *TaxRegistrationCountryOptionsDEParams `form:"de"` + // Options for the registration in DK. + Dk *TaxRegistrationCountryOptionsDkParams `form:"dk"` + // Options for the registration in EC. + Ec *TaxRegistrationCountryOptionsEcParams `form:"ec"` + // Options for the registration in EE. + Ee *TaxRegistrationCountryOptionsEeParams `form:"ee"` + // Options for the registration in EG. + Eg *TaxRegistrationCountryOptionsEgParams `form:"eg"` + // Options for the registration in ES. + ES *TaxRegistrationCountryOptionsESParams `form:"es"` + // Options for the registration in ET. + ET *TaxRegistrationCountryOptionsETParams `form:"et"` + // Options for the registration in FI. + FI *TaxRegistrationCountryOptionsFIParams `form:"fi"` + // Options for the registration in FR. + FR *TaxRegistrationCountryOptionsFRParams `form:"fr"` + // Options for the registration in GB. + GB *TaxRegistrationCountryOptionsGBParams `form:"gb"` + // Options for the registration in GE. + Ge *TaxRegistrationCountryOptionsGeParams `form:"ge"` + // Options for the registration in GN. + Gn *TaxRegistrationCountryOptionsGnParams `form:"gn"` + // Options for the registration in GR. + Gr *TaxRegistrationCountryOptionsGrParams `form:"gr"` + // Options for the registration in HR. + HR *TaxRegistrationCountryOptionsHRParams `form:"hr"` + // Options for the registration in HU. + HU *TaxRegistrationCountryOptionsHUParams `form:"hu"` + // Options for the registration in ID. + ID *TaxRegistrationCountryOptionsIDParams `form:"id"` + // Options for the registration in IE. + Ie *TaxRegistrationCountryOptionsIeParams `form:"ie"` + // Options for the registration in IN. + In *TaxRegistrationCountryOptionsInParams `form:"in"` + // Options for the registration in IS. + Is *TaxRegistrationCountryOptionsIsParams `form:"is"` + // Options for the registration in IT. + IT *TaxRegistrationCountryOptionsITParams `form:"it"` + // Options for the registration in JP. + JP *TaxRegistrationCountryOptionsJPParams `form:"jp"` + // Options for the registration in KE. + Ke *TaxRegistrationCountryOptionsKeParams `form:"ke"` + // Options for the registration in KG. + Kg *TaxRegistrationCountryOptionsKgParams `form:"kg"` + // Options for the registration in KH. + Kh *TaxRegistrationCountryOptionsKhParams `form:"kh"` + // Options for the registration in KR. + Kr *TaxRegistrationCountryOptionsKrParams `form:"kr"` + // Options for the registration in KZ. + Kz *TaxRegistrationCountryOptionsKzParams `form:"kz"` + // Options for the registration in LA. + La *TaxRegistrationCountryOptionsLaParams `form:"la"` + // Options for the registration in LT. + LT *TaxRegistrationCountryOptionsLTParams `form:"lt"` + // Options for the registration in LU. + Lu *TaxRegistrationCountryOptionsLuParams `form:"lu"` + // Options for the registration in LV. + LV *TaxRegistrationCountryOptionsLVParams `form:"lv"` + // Options for the registration in MA. + Ma *TaxRegistrationCountryOptionsMaParams `form:"ma"` + // Options for the registration in MD. + Md *TaxRegistrationCountryOptionsMdParams `form:"md"` + // Options for the registration in ME. + Me *TaxRegistrationCountryOptionsMeParams `form:"me"` + // Options for the registration in MK. + Mk *TaxRegistrationCountryOptionsMkParams `form:"mk"` + // Options for the registration in MR. + Mr *TaxRegistrationCountryOptionsMrParams `form:"mr"` + // Options for the registration in MT. + MT *TaxRegistrationCountryOptionsMTParams `form:"mt"` + // Options for the registration in MX. + MX *TaxRegistrationCountryOptionsMXParams `form:"mx"` + // Options for the registration in MY. + My *TaxRegistrationCountryOptionsMyParams `form:"my"` + // Options for the registration in NG. + Ng *TaxRegistrationCountryOptionsNgParams `form:"ng"` + // Options for the registration in NL. + NL *TaxRegistrationCountryOptionsNLParams `form:"nl"` + // Options for the registration in NO. + No *TaxRegistrationCountryOptionsNoParams `form:"no"` + // Options for the registration in NP. + Np *TaxRegistrationCountryOptionsNpParams `form:"np"` + // Options for the registration in NZ. + Nz *TaxRegistrationCountryOptionsNzParams `form:"nz"` + // Options for the registration in OM. + Om *TaxRegistrationCountryOptionsOmParams `form:"om"` + // Options for the registration in PE. + Pe *TaxRegistrationCountryOptionsPeParams `form:"pe"` + // Options for the registration in PH. + Ph *TaxRegistrationCountryOptionsPhParams `form:"ph"` + // Options for the registration in PL. + PL *TaxRegistrationCountryOptionsPLParams `form:"pl"` + // Options for the registration in PT. + PT *TaxRegistrationCountryOptionsPTParams `form:"pt"` + // Options for the registration in RO. + RO *TaxRegistrationCountryOptionsROParams `form:"ro"` + // Options for the registration in RS. + Rs *TaxRegistrationCountryOptionsRsParams `form:"rs"` + // Options for the registration in RU. + RU *TaxRegistrationCountryOptionsRUParams `form:"ru"` + // Options for the registration in SA. + Sa *TaxRegistrationCountryOptionsSaParams `form:"sa"` + // Options for the registration in SE. + Se *TaxRegistrationCountryOptionsSeParams `form:"se"` + // Options for the registration in SG. + Sg *TaxRegistrationCountryOptionsSgParams `form:"sg"` + // Options for the registration in SI. + Si *TaxRegistrationCountryOptionsSiParams `form:"si"` + // Options for the registration in SK. + SK *TaxRegistrationCountryOptionsSKParams `form:"sk"` + // Options for the registration in SN. + Sn *TaxRegistrationCountryOptionsSnParams `form:"sn"` + // Options for the registration in SR. + Sr *TaxRegistrationCountryOptionsSrParams `form:"sr"` + // Options for the registration in TH. + TH *TaxRegistrationCountryOptionsTHParams `form:"th"` + // Options for the registration in TJ. + Tj *TaxRegistrationCountryOptionsTjParams `form:"tj"` + // Options for the registration in TR. + TR *TaxRegistrationCountryOptionsTRParams `form:"tr"` + // Options for the registration in TZ. + Tz *TaxRegistrationCountryOptionsTzParams `form:"tz"` + // Options for the registration in UA. + Ua *TaxRegistrationCountryOptionsUaParams `form:"ua"` + // Options for the registration in UG. + Ug *TaxRegistrationCountryOptionsUgParams `form:"ug"` + // Options for the registration in US. + US *TaxRegistrationCountryOptionsUSParams `form:"us"` + // Options for the registration in UY. + Uy *TaxRegistrationCountryOptionsUyParams `form:"uy"` + // Options for the registration in UZ. + Uz *TaxRegistrationCountryOptionsUzParams `form:"uz"` + // Options for the registration in VN. + Vn *TaxRegistrationCountryOptionsVnParams `form:"vn"` + // Options for the registration in ZA. + Za *TaxRegistrationCountryOptionsZaParams `form:"za"` + // Options for the registration in ZM. + Zm *TaxRegistrationCountryOptionsZmParams `form:"zm"` + // Options for the registration in ZW. + Zw *TaxRegistrationCountryOptionsZwParams `form:"zw"` +} + +// Creates a new Tax Registration object. +type TaxRegistrationParams struct { + Params `form:"*"` + // Time at which the Tax Registration becomes active. It can be either `now` to indicate the current time, or a future timestamp measured in seconds since the Unix epoch. + ActiveFrom *int64 `form:"active_from"` + ActiveFromNow *bool `form:"-"` // See custom AppendTo + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // Specific options for a registration in the specified `country`. + CountryOptions *TaxRegistrationCountryOptionsParams `form:"country_options"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // If set, the registration stops being active at this time. If not set, the registration will be active indefinitely. It can be either `now` to indicate the current time, or a timestamp measured in seconds since the Unix epoch. + ExpiresAt *int64 `form:"expires_at"` + ExpiresAtNow *bool `form:"-"` // See custom AppendTo +} + +// AddExpand appends a new field to expand. +func (p *TaxRegistrationParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AppendTo implements custom encoding logic for TaxRegistrationParams. +func (p *TaxRegistrationParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.ActiveFromNow) { + body.Add(form.FormatKey(append(keyParts, "active_from")), "now") + } + if BoolValue(p.ExpiresAtNow) { + body.Add(form.FormatKey(append(keyParts, "expires_at")), "now") + } +} + +// Options for the registration in AE. +type TaxRegistrationCreateCountryOptionsAeParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in AL. +type TaxRegistrationCreateCountryOptionsAlParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in AM. +type TaxRegistrationCreateCountryOptionsAmParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in AO. +type TaxRegistrationCreateCountryOptionsAoParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsAtStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in AT. +type TaxRegistrationCreateCountryOptionsAtParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsAtStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in AU. +type TaxRegistrationCreateCountryOptionsAuParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in AW. +type TaxRegistrationCreateCountryOptionsAwParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in AZ. +type TaxRegistrationCreateCountryOptionsAzParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in BA. +type TaxRegistrationCreateCountryOptionsBaParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in BB. +type TaxRegistrationCreateCountryOptionsBbParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in BD. +type TaxRegistrationCreateCountryOptionsBdParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsBeStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in BE. +type TaxRegistrationCreateCountryOptionsBeParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsBeStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in BF. +type TaxRegistrationCreateCountryOptionsBfParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsBGStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in BG. +type TaxRegistrationCreateCountryOptionsBGParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsBGStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in BH. +type TaxRegistrationCreateCountryOptionsBhParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in BJ. +type TaxRegistrationCreateCountryOptionsBjParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in BS. +type TaxRegistrationCreateCountryOptionsBsParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in BY. +type TaxRegistrationCreateCountryOptionsByParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the provincial tax registration. +type TaxRegistrationCreateCountryOptionsCaProvinceStandardParams struct { + // Two-letter CA province code ([ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2)). + Province *string `form:"province"` +} + +// Options for the registration in CA. +type TaxRegistrationCreateCountryOptionsCaParams struct { + // Options for the provincial tax registration. + ProvinceStandard *TaxRegistrationCreateCountryOptionsCaProvinceStandardParams `form:"province_standard"` + // Type of registration to be created in Canada. + Type *string `form:"type"` +} + +// Options for the registration in CD. +type TaxRegistrationCreateCountryOptionsCdParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in CH. +type TaxRegistrationCreateCountryOptionsChParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in CL. +type TaxRegistrationCreateCountryOptionsClParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in CM. +type TaxRegistrationCreateCountryOptionsCmParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in CO. +type TaxRegistrationCreateCountryOptionsCoParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in CR. +type TaxRegistrationCreateCountryOptionsCrParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in CV. +type TaxRegistrationCreateCountryOptionsCvParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsCyStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in CY. +type TaxRegistrationCreateCountryOptionsCyParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsCyStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsCzStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in CZ. +type TaxRegistrationCreateCountryOptionsCzParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsCzStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsDEStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in DE. +type TaxRegistrationCreateCountryOptionsDEParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsDEStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsDkStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in DK. +type TaxRegistrationCreateCountryOptionsDkParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsDkStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in EC. +type TaxRegistrationCreateCountryOptionsEcParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsEeStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in EE. +type TaxRegistrationCreateCountryOptionsEeParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsEeStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in EG. +type TaxRegistrationCreateCountryOptionsEgParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsESStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in ES. +type TaxRegistrationCreateCountryOptionsESParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsESStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in ET. +type TaxRegistrationCreateCountryOptionsETParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsFIStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in FI. +type TaxRegistrationCreateCountryOptionsFIParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsFIStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsFRStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in FR. +type TaxRegistrationCreateCountryOptionsFRParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsFRStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in GB. +type TaxRegistrationCreateCountryOptionsGBParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in GE. +type TaxRegistrationCreateCountryOptionsGeParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in GN. +type TaxRegistrationCreateCountryOptionsGnParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsGrStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in GR. +type TaxRegistrationCreateCountryOptionsGrParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsGrStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsHRStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in HR. +type TaxRegistrationCreateCountryOptionsHRParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsHRStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsHUStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in HU. +type TaxRegistrationCreateCountryOptionsHUParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsHUStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in ID. +type TaxRegistrationCreateCountryOptionsIDParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsIeStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in IE. +type TaxRegistrationCreateCountryOptionsIeParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsIeStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in IN. +type TaxRegistrationCreateCountryOptionsInParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in IS. +type TaxRegistrationCreateCountryOptionsIsParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsITStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in IT. +type TaxRegistrationCreateCountryOptionsITParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsITStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in JP. +type TaxRegistrationCreateCountryOptionsJPParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in KE. +type TaxRegistrationCreateCountryOptionsKeParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in KG. +type TaxRegistrationCreateCountryOptionsKgParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in KH. +type TaxRegistrationCreateCountryOptionsKhParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in KR. +type TaxRegistrationCreateCountryOptionsKrParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in KZ. +type TaxRegistrationCreateCountryOptionsKzParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in LA. +type TaxRegistrationCreateCountryOptionsLaParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsLTStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in LT. +type TaxRegistrationCreateCountryOptionsLTParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsLTStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsLuStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in LU. +type TaxRegistrationCreateCountryOptionsLuParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsLuStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsLVStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in LV. +type TaxRegistrationCreateCountryOptionsLVParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsLVStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in MA. +type TaxRegistrationCreateCountryOptionsMaParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in MD. +type TaxRegistrationCreateCountryOptionsMdParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in ME. +type TaxRegistrationCreateCountryOptionsMeParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in MK. +type TaxRegistrationCreateCountryOptionsMkParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in MR. +type TaxRegistrationCreateCountryOptionsMrParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsMTStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in MT. +type TaxRegistrationCreateCountryOptionsMTParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsMTStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in MX. +type TaxRegistrationCreateCountryOptionsMXParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in MY. +type TaxRegistrationCreateCountryOptionsMyParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in NG. +type TaxRegistrationCreateCountryOptionsNgParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsNLStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in NL. +type TaxRegistrationCreateCountryOptionsNLParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsNLStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in NO. +type TaxRegistrationCreateCountryOptionsNoParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in NP. +type TaxRegistrationCreateCountryOptionsNpParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in NZ. +type TaxRegistrationCreateCountryOptionsNzParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in OM. +type TaxRegistrationCreateCountryOptionsOmParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in PE. +type TaxRegistrationCreateCountryOptionsPeParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in PH. +type TaxRegistrationCreateCountryOptionsPhParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsPLStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in PL. +type TaxRegistrationCreateCountryOptionsPLParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsPLStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsPTStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in PT. +type TaxRegistrationCreateCountryOptionsPTParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsPTStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsROStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in RO. +type TaxRegistrationCreateCountryOptionsROParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsROStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in RS. +type TaxRegistrationCreateCountryOptionsRsParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in RU. +type TaxRegistrationCreateCountryOptionsRUParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in SA. +type TaxRegistrationCreateCountryOptionsSaParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsSeStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in SE. +type TaxRegistrationCreateCountryOptionsSeParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsSeStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in SG. +type TaxRegistrationCreateCountryOptionsSgParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsSiStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in SI. +type TaxRegistrationCreateCountryOptionsSiParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsSiStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the standard registration. +type TaxRegistrationCreateCountryOptionsSKStandardParams struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme *string `form:"place_of_supply_scheme"` +} + +// Options for the registration in SK. +type TaxRegistrationCreateCountryOptionsSKParams struct { + // Options for the standard registration. + Standard *TaxRegistrationCreateCountryOptionsSKStandardParams `form:"standard"` + // Type of registration to be created in an EU country. + Type *string `form:"type"` +} + +// Options for the registration in SN. +type TaxRegistrationCreateCountryOptionsSnParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in SR. +type TaxRegistrationCreateCountryOptionsSrParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in TH. +type TaxRegistrationCreateCountryOptionsTHParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in TJ. +type TaxRegistrationCreateCountryOptionsTjParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in TR. +type TaxRegistrationCreateCountryOptionsTRParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in TZ. +type TaxRegistrationCreateCountryOptionsTzParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in UA. +type TaxRegistrationCreateCountryOptionsUaParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in UG. +type TaxRegistrationCreateCountryOptionsUgParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the local amusement tax registration. +type TaxRegistrationCreateCountryOptionsUSLocalAmusementTaxParams struct { + // A [FIPS code](https://www.census.gov/library/reference/code-lists/ansi.html) representing the local jurisdiction. Supported FIPS codes are: `14000` (Chicago), `06613` (Bloomington), `21696` (East Dundee), `24582` (Evanston), `45421` (Lynwood), `48892` (Midlothian), `64343` (River Grove), and `68081` (Schiller Park). + Jurisdiction *string `form:"jurisdiction"` +} + +// Options for the local lease tax registration. +type TaxRegistrationCreateCountryOptionsUSLocalLeaseTaxParams struct { + // A [FIPS code](https://www.census.gov/library/reference/code-lists/ansi.html) representing the local jurisdiction. Supported FIPS codes are: `14000` (Chicago). + Jurisdiction *string `form:"jurisdiction"` +} + +// Elections for the state sales tax registration. +type TaxRegistrationCreateCountryOptionsUSStateSalesTaxElectionParams struct { + // A [FIPS code](https://www.census.gov/library/reference/code-lists/ansi.html) representing the local jurisdiction. Supported FIPS codes are: `003` (Allegheny County) and `60000` (Philadelphia City). + Jurisdiction *string `form:"jurisdiction"` + // The type of the election for the state sales tax registration. + Type *string `form:"type"` +} + +// Options for the state sales tax registration. +type TaxRegistrationCreateCountryOptionsUSStateSalesTaxParams struct { + // Elections for the state sales tax registration. + Elections []*TaxRegistrationCreateCountryOptionsUSStateSalesTaxElectionParams `form:"elections"` +} + +// Options for the registration in US. +type TaxRegistrationCreateCountryOptionsUSParams struct { + // Options for the local amusement tax registration. + LocalAmusementTax *TaxRegistrationCreateCountryOptionsUSLocalAmusementTaxParams `form:"local_amusement_tax"` + // Options for the local lease tax registration. + LocalLeaseTax *TaxRegistrationCreateCountryOptionsUSLocalLeaseTaxParams `form:"local_lease_tax"` + // Two-letter US state code ([ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2)). + State *string `form:"state"` + // Options for the state sales tax registration. + StateSalesTax *TaxRegistrationCreateCountryOptionsUSStateSalesTaxParams `form:"state_sales_tax"` + // Type of registration to be created in the US. + Type *string `form:"type"` +} + +// Options for the registration in UY. +type TaxRegistrationCreateCountryOptionsUyParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in UZ. +type TaxRegistrationCreateCountryOptionsUzParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in VN. +type TaxRegistrationCreateCountryOptionsVnParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in ZA. +type TaxRegistrationCreateCountryOptionsZaParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in ZM. +type TaxRegistrationCreateCountryOptionsZmParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Options for the registration in ZW. +type TaxRegistrationCreateCountryOptionsZwParams struct { + // Type of registration to be created in `country`. + Type *string `form:"type"` +} + +// Specific options for a registration in the specified `country`. +type TaxRegistrationCreateCountryOptionsParams struct { + // Options for the registration in AE. + Ae *TaxRegistrationCreateCountryOptionsAeParams `form:"ae"` + // Options for the registration in AL. + Al *TaxRegistrationCreateCountryOptionsAlParams `form:"al"` + // Options for the registration in AM. + Am *TaxRegistrationCreateCountryOptionsAmParams `form:"am"` + // Options for the registration in AO. + Ao *TaxRegistrationCreateCountryOptionsAoParams `form:"ao"` + // Options for the registration in AT. + At *TaxRegistrationCreateCountryOptionsAtParams `form:"at"` + // Options for the registration in AU. + Au *TaxRegistrationCreateCountryOptionsAuParams `form:"au"` + // Options for the registration in AW. + Aw *TaxRegistrationCreateCountryOptionsAwParams `form:"aw"` + // Options for the registration in AZ. + Az *TaxRegistrationCreateCountryOptionsAzParams `form:"az"` + // Options for the registration in BA. + Ba *TaxRegistrationCreateCountryOptionsBaParams `form:"ba"` + // Options for the registration in BB. + Bb *TaxRegistrationCreateCountryOptionsBbParams `form:"bb"` + // Options for the registration in BD. + Bd *TaxRegistrationCreateCountryOptionsBdParams `form:"bd"` + // Options for the registration in BE. + Be *TaxRegistrationCreateCountryOptionsBeParams `form:"be"` + // Options for the registration in BF. + Bf *TaxRegistrationCreateCountryOptionsBfParams `form:"bf"` + // Options for the registration in BG. + BG *TaxRegistrationCreateCountryOptionsBGParams `form:"bg"` + // Options for the registration in BH. + Bh *TaxRegistrationCreateCountryOptionsBhParams `form:"bh"` + // Options for the registration in BJ. + Bj *TaxRegistrationCreateCountryOptionsBjParams `form:"bj"` + // Options for the registration in BS. + Bs *TaxRegistrationCreateCountryOptionsBsParams `form:"bs"` + // Options for the registration in BY. + By *TaxRegistrationCreateCountryOptionsByParams `form:"by"` + // Options for the registration in CA. + Ca *TaxRegistrationCreateCountryOptionsCaParams `form:"ca"` + // Options for the registration in CD. + Cd *TaxRegistrationCreateCountryOptionsCdParams `form:"cd"` + // Options for the registration in CH. + Ch *TaxRegistrationCreateCountryOptionsChParams `form:"ch"` + // Options for the registration in CL. + Cl *TaxRegistrationCreateCountryOptionsClParams `form:"cl"` + // Options for the registration in CM. + Cm *TaxRegistrationCreateCountryOptionsCmParams `form:"cm"` + // Options for the registration in CO. + Co *TaxRegistrationCreateCountryOptionsCoParams `form:"co"` + // Options for the registration in CR. + Cr *TaxRegistrationCreateCountryOptionsCrParams `form:"cr"` + // Options for the registration in CV. + Cv *TaxRegistrationCreateCountryOptionsCvParams `form:"cv"` + // Options for the registration in CY. + Cy *TaxRegistrationCreateCountryOptionsCyParams `form:"cy"` + // Options for the registration in CZ. + Cz *TaxRegistrationCreateCountryOptionsCzParams `form:"cz"` + // Options for the registration in DE. + DE *TaxRegistrationCreateCountryOptionsDEParams `form:"de"` + // Options for the registration in DK. + Dk *TaxRegistrationCreateCountryOptionsDkParams `form:"dk"` + // Options for the registration in EC. + Ec *TaxRegistrationCreateCountryOptionsEcParams `form:"ec"` + // Options for the registration in EE. + Ee *TaxRegistrationCreateCountryOptionsEeParams `form:"ee"` + // Options for the registration in EG. + Eg *TaxRegistrationCreateCountryOptionsEgParams `form:"eg"` + // Options for the registration in ES. + ES *TaxRegistrationCreateCountryOptionsESParams `form:"es"` + // Options for the registration in ET. + ET *TaxRegistrationCreateCountryOptionsETParams `form:"et"` + // Options for the registration in FI. + FI *TaxRegistrationCreateCountryOptionsFIParams `form:"fi"` + // Options for the registration in FR. + FR *TaxRegistrationCreateCountryOptionsFRParams `form:"fr"` + // Options for the registration in GB. + GB *TaxRegistrationCreateCountryOptionsGBParams `form:"gb"` + // Options for the registration in GE. + Ge *TaxRegistrationCreateCountryOptionsGeParams `form:"ge"` + // Options for the registration in GN. + Gn *TaxRegistrationCreateCountryOptionsGnParams `form:"gn"` + // Options for the registration in GR. + Gr *TaxRegistrationCreateCountryOptionsGrParams `form:"gr"` + // Options for the registration in HR. + HR *TaxRegistrationCreateCountryOptionsHRParams `form:"hr"` + // Options for the registration in HU. + HU *TaxRegistrationCreateCountryOptionsHUParams `form:"hu"` + // Options for the registration in ID. + ID *TaxRegistrationCreateCountryOptionsIDParams `form:"id"` + // Options for the registration in IE. + Ie *TaxRegistrationCreateCountryOptionsIeParams `form:"ie"` + // Options for the registration in IN. + In *TaxRegistrationCreateCountryOptionsInParams `form:"in"` + // Options for the registration in IS. + Is *TaxRegistrationCreateCountryOptionsIsParams `form:"is"` + // Options for the registration in IT. + IT *TaxRegistrationCreateCountryOptionsITParams `form:"it"` + // Options for the registration in JP. + JP *TaxRegistrationCreateCountryOptionsJPParams `form:"jp"` + // Options for the registration in KE. + Ke *TaxRegistrationCreateCountryOptionsKeParams `form:"ke"` + // Options for the registration in KG. + Kg *TaxRegistrationCreateCountryOptionsKgParams `form:"kg"` + // Options for the registration in KH. + Kh *TaxRegistrationCreateCountryOptionsKhParams `form:"kh"` + // Options for the registration in KR. + Kr *TaxRegistrationCreateCountryOptionsKrParams `form:"kr"` + // Options for the registration in KZ. + Kz *TaxRegistrationCreateCountryOptionsKzParams `form:"kz"` + // Options for the registration in LA. + La *TaxRegistrationCreateCountryOptionsLaParams `form:"la"` + // Options for the registration in LT. + LT *TaxRegistrationCreateCountryOptionsLTParams `form:"lt"` + // Options for the registration in LU. + Lu *TaxRegistrationCreateCountryOptionsLuParams `form:"lu"` + // Options for the registration in LV. + LV *TaxRegistrationCreateCountryOptionsLVParams `form:"lv"` + // Options for the registration in MA. + Ma *TaxRegistrationCreateCountryOptionsMaParams `form:"ma"` + // Options for the registration in MD. + Md *TaxRegistrationCreateCountryOptionsMdParams `form:"md"` + // Options for the registration in ME. + Me *TaxRegistrationCreateCountryOptionsMeParams `form:"me"` + // Options for the registration in MK. + Mk *TaxRegistrationCreateCountryOptionsMkParams `form:"mk"` + // Options for the registration in MR. + Mr *TaxRegistrationCreateCountryOptionsMrParams `form:"mr"` + // Options for the registration in MT. + MT *TaxRegistrationCreateCountryOptionsMTParams `form:"mt"` + // Options for the registration in MX. + MX *TaxRegistrationCreateCountryOptionsMXParams `form:"mx"` + // Options for the registration in MY. + My *TaxRegistrationCreateCountryOptionsMyParams `form:"my"` + // Options for the registration in NG. + Ng *TaxRegistrationCreateCountryOptionsNgParams `form:"ng"` + // Options for the registration in NL. + NL *TaxRegistrationCreateCountryOptionsNLParams `form:"nl"` + // Options for the registration in NO. + No *TaxRegistrationCreateCountryOptionsNoParams `form:"no"` + // Options for the registration in NP. + Np *TaxRegistrationCreateCountryOptionsNpParams `form:"np"` + // Options for the registration in NZ. + Nz *TaxRegistrationCreateCountryOptionsNzParams `form:"nz"` + // Options for the registration in OM. + Om *TaxRegistrationCreateCountryOptionsOmParams `form:"om"` + // Options for the registration in PE. + Pe *TaxRegistrationCreateCountryOptionsPeParams `form:"pe"` + // Options for the registration in PH. + Ph *TaxRegistrationCreateCountryOptionsPhParams `form:"ph"` + // Options for the registration in PL. + PL *TaxRegistrationCreateCountryOptionsPLParams `form:"pl"` + // Options for the registration in PT. + PT *TaxRegistrationCreateCountryOptionsPTParams `form:"pt"` + // Options for the registration in RO. + RO *TaxRegistrationCreateCountryOptionsROParams `form:"ro"` + // Options for the registration in RS. + Rs *TaxRegistrationCreateCountryOptionsRsParams `form:"rs"` + // Options for the registration in RU. + RU *TaxRegistrationCreateCountryOptionsRUParams `form:"ru"` + // Options for the registration in SA. + Sa *TaxRegistrationCreateCountryOptionsSaParams `form:"sa"` + // Options for the registration in SE. + Se *TaxRegistrationCreateCountryOptionsSeParams `form:"se"` + // Options for the registration in SG. + Sg *TaxRegistrationCreateCountryOptionsSgParams `form:"sg"` + // Options for the registration in SI. + Si *TaxRegistrationCreateCountryOptionsSiParams `form:"si"` + // Options for the registration in SK. + SK *TaxRegistrationCreateCountryOptionsSKParams `form:"sk"` + // Options for the registration in SN. + Sn *TaxRegistrationCreateCountryOptionsSnParams `form:"sn"` + // Options for the registration in SR. + Sr *TaxRegistrationCreateCountryOptionsSrParams `form:"sr"` + // Options for the registration in TH. + TH *TaxRegistrationCreateCountryOptionsTHParams `form:"th"` + // Options for the registration in TJ. + Tj *TaxRegistrationCreateCountryOptionsTjParams `form:"tj"` + // Options for the registration in TR. + TR *TaxRegistrationCreateCountryOptionsTRParams `form:"tr"` + // Options for the registration in TZ. + Tz *TaxRegistrationCreateCountryOptionsTzParams `form:"tz"` + // Options for the registration in UA. + Ua *TaxRegistrationCreateCountryOptionsUaParams `form:"ua"` + // Options for the registration in UG. + Ug *TaxRegistrationCreateCountryOptionsUgParams `form:"ug"` + // Options for the registration in US. + US *TaxRegistrationCreateCountryOptionsUSParams `form:"us"` + // Options for the registration in UY. + Uy *TaxRegistrationCreateCountryOptionsUyParams `form:"uy"` + // Options for the registration in UZ. + Uz *TaxRegistrationCreateCountryOptionsUzParams `form:"uz"` + // Options for the registration in VN. + Vn *TaxRegistrationCreateCountryOptionsVnParams `form:"vn"` + // Options for the registration in ZA. + Za *TaxRegistrationCreateCountryOptionsZaParams `form:"za"` + // Options for the registration in ZM. + Zm *TaxRegistrationCreateCountryOptionsZmParams `form:"zm"` + // Options for the registration in ZW. + Zw *TaxRegistrationCreateCountryOptionsZwParams `form:"zw"` +} + +// Creates a new Tax Registration object. +type TaxRegistrationCreateParams struct { + Params `form:"*"` + // Time at which the Tax Registration becomes active. It can be either `now` to indicate the current time, or a future timestamp measured in seconds since the Unix epoch. + ActiveFrom *int64 `form:"active_from"` + ActiveFromNow *bool `form:"-"` // See custom AppendTo + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // Specific options for a registration in the specified `country`. + CountryOptions *TaxRegistrationCreateCountryOptionsParams `form:"country_options"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // If set, the Tax Registration stops being active at this time. If not set, the Tax Registration will be active indefinitely. Timestamp measured in seconds since the Unix epoch. + ExpiresAt *int64 `form:"expires_at"` +} + +// AddExpand appends a new field to expand. +func (p *TaxRegistrationCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AppendTo implements custom encoding logic for TaxRegistrationCreateParams. +func (p *TaxRegistrationCreateParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.ActiveFromNow) { + body.Add(form.FormatKey(append(keyParts, "active_from")), "now") + } +} + +// Returns a Tax Registration object. +type TaxRegistrationRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TaxRegistrationRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates an existing Tax Registration object. +// +// A registration cannot be deleted after it has been created. If you wish to end a registration you may do so by setting expires_at. +type TaxRegistrationUpdateParams struct { + Params `form:"*"` + // Time at which the registration becomes active. It can be either `now` to indicate the current time, or a timestamp measured in seconds since the Unix epoch. + ActiveFrom *int64 `form:"active_from"` + ActiveFromNow *bool `form:"-"` // See custom AppendTo + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // If set, the registration stops being active at this time. If not set, the registration will be active indefinitely. It can be either `now` to indicate the current time, or a timestamp measured in seconds since the Unix epoch. + ExpiresAt *int64 `form:"expires_at"` + ExpiresAtNow *bool `form:"-"` // See custom AppendTo +} + +// AddExpand appends a new field to expand. +func (p *TaxRegistrationUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AppendTo implements custom encoding logic for TaxRegistrationUpdateParams. +func (p *TaxRegistrationUpdateParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.ActiveFromNow) { + body.Add(form.FormatKey(append(keyParts, "active_from")), "now") + } + if BoolValue(p.ExpiresAtNow) { + body.Add(form.FormatKey(append(keyParts, "expires_at")), "now") + } +} + +type TaxRegistrationCountryOptionsAe struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsAeType `json:"type"` +} +type TaxRegistrationCountryOptionsAl struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsAlType `json:"type"` +} +type TaxRegistrationCountryOptionsAm struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsAmType `json:"type"` +} +type TaxRegistrationCountryOptionsAo struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsAoType `json:"type"` +} +type TaxRegistrationCountryOptionsAtStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsAtStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsAt struct { + Standard *TaxRegistrationCountryOptionsAtStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsAtType `json:"type"` +} +type TaxRegistrationCountryOptionsAu struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsAuType `json:"type"` +} +type TaxRegistrationCountryOptionsAw struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsAwType `json:"type"` +} +type TaxRegistrationCountryOptionsAz struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsAzType `json:"type"` +} +type TaxRegistrationCountryOptionsBa struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsBaType `json:"type"` +} +type TaxRegistrationCountryOptionsBb struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsBbType `json:"type"` +} +type TaxRegistrationCountryOptionsBd struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsBdType `json:"type"` +} +type TaxRegistrationCountryOptionsBeStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsBeStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsBe struct { + Standard *TaxRegistrationCountryOptionsBeStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsBeType `json:"type"` +} +type TaxRegistrationCountryOptionsBf struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsBfType `json:"type"` +} +type TaxRegistrationCountryOptionsBGStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsBGStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsBG struct { + Standard *TaxRegistrationCountryOptionsBGStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsBGType `json:"type"` +} +type TaxRegistrationCountryOptionsBh struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsBhType `json:"type"` +} +type TaxRegistrationCountryOptionsBj struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsBjType `json:"type"` +} +type TaxRegistrationCountryOptionsBs struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsBsType `json:"type"` +} +type TaxRegistrationCountryOptionsBy struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsByType `json:"type"` +} +type TaxRegistrationCountryOptionsCaProvinceStandard struct { + // Two-letter CA province code ([ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2)). + Province string `json:"province"` +} +type TaxRegistrationCountryOptionsCa struct { + ProvinceStandard *TaxRegistrationCountryOptionsCaProvinceStandard `json:"province_standard"` + // Type of registration in Canada. + Type TaxRegistrationCountryOptionsCaType `json:"type"` +} +type TaxRegistrationCountryOptionsCd struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsCdType `json:"type"` +} +type TaxRegistrationCountryOptionsCh struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsChType `json:"type"` +} +type TaxRegistrationCountryOptionsCl struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsClType `json:"type"` +} +type TaxRegistrationCountryOptionsCm struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsCmType `json:"type"` +} +type TaxRegistrationCountryOptionsCo struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsCoType `json:"type"` +} +type TaxRegistrationCountryOptionsCr struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsCrType `json:"type"` +} +type TaxRegistrationCountryOptionsCv struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsCvType `json:"type"` +} +type TaxRegistrationCountryOptionsCyStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsCyStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsCy struct { + Standard *TaxRegistrationCountryOptionsCyStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsCyType `json:"type"` +} +type TaxRegistrationCountryOptionsCzStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsCzStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsCz struct { + Standard *TaxRegistrationCountryOptionsCzStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsCzType `json:"type"` +} +type TaxRegistrationCountryOptionsDEStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsDEStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsDE struct { + Standard *TaxRegistrationCountryOptionsDEStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsDEType `json:"type"` +} +type TaxRegistrationCountryOptionsDkStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsDkStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsDk struct { + Standard *TaxRegistrationCountryOptionsDkStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsDkType `json:"type"` +} +type TaxRegistrationCountryOptionsEc struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsEcType `json:"type"` +} +type TaxRegistrationCountryOptionsEeStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsEeStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsEe struct { + Standard *TaxRegistrationCountryOptionsEeStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsEeType `json:"type"` +} +type TaxRegistrationCountryOptionsEg struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsEgType `json:"type"` +} +type TaxRegistrationCountryOptionsESStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsESStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsES struct { + Standard *TaxRegistrationCountryOptionsESStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsESType `json:"type"` +} +type TaxRegistrationCountryOptionsET struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsETType `json:"type"` +} +type TaxRegistrationCountryOptionsFIStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsFIStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsFI struct { + Standard *TaxRegistrationCountryOptionsFIStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsFIType `json:"type"` +} +type TaxRegistrationCountryOptionsFRStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsFRStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsFR struct { + Standard *TaxRegistrationCountryOptionsFRStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsFRType `json:"type"` +} +type TaxRegistrationCountryOptionsGB struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsGBType `json:"type"` +} +type TaxRegistrationCountryOptionsGe struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsGeType `json:"type"` +} +type TaxRegistrationCountryOptionsGn struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsGnType `json:"type"` +} +type TaxRegistrationCountryOptionsGrStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsGrStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsGr struct { + Standard *TaxRegistrationCountryOptionsGrStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsGrType `json:"type"` +} +type TaxRegistrationCountryOptionsHRStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsHRStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsHR struct { + Standard *TaxRegistrationCountryOptionsHRStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsHRType `json:"type"` +} +type TaxRegistrationCountryOptionsHUStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsHUStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsHU struct { + Standard *TaxRegistrationCountryOptionsHUStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsHUType `json:"type"` +} +type TaxRegistrationCountryOptionsID struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsIDType `json:"type"` +} +type TaxRegistrationCountryOptionsIeStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsIeStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsIe struct { + Standard *TaxRegistrationCountryOptionsIeStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsIeType `json:"type"` +} +type TaxRegistrationCountryOptionsIn struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsInType `json:"type"` +} +type TaxRegistrationCountryOptionsIs struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsIsType `json:"type"` +} +type TaxRegistrationCountryOptionsITStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsITStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsIT struct { + Standard *TaxRegistrationCountryOptionsITStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsITType `json:"type"` +} +type TaxRegistrationCountryOptionsJP struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsJPType `json:"type"` +} +type TaxRegistrationCountryOptionsKe struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsKeType `json:"type"` +} +type TaxRegistrationCountryOptionsKg struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsKgType `json:"type"` +} +type TaxRegistrationCountryOptionsKh struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsKhType `json:"type"` +} +type TaxRegistrationCountryOptionsKr struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsKrType `json:"type"` +} +type TaxRegistrationCountryOptionsKz struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsKzType `json:"type"` +} +type TaxRegistrationCountryOptionsLa struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsLaType `json:"type"` +} +type TaxRegistrationCountryOptionsLTStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsLTStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsLT struct { + Standard *TaxRegistrationCountryOptionsLTStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsLTType `json:"type"` +} +type TaxRegistrationCountryOptionsLuStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsLuStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsLu struct { + Standard *TaxRegistrationCountryOptionsLuStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsLuType `json:"type"` +} +type TaxRegistrationCountryOptionsLVStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsLVStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsLV struct { + Standard *TaxRegistrationCountryOptionsLVStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsLVType `json:"type"` +} +type TaxRegistrationCountryOptionsMa struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsMaType `json:"type"` +} +type TaxRegistrationCountryOptionsMd struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsMdType `json:"type"` +} +type TaxRegistrationCountryOptionsMe struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsMeType `json:"type"` +} +type TaxRegistrationCountryOptionsMk struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsMkType `json:"type"` +} +type TaxRegistrationCountryOptionsMr struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsMrType `json:"type"` +} +type TaxRegistrationCountryOptionsMTStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsMTStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsMT struct { + Standard *TaxRegistrationCountryOptionsMTStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsMTType `json:"type"` +} +type TaxRegistrationCountryOptionsMX struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsMXType `json:"type"` +} +type TaxRegistrationCountryOptionsMy struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsMyType `json:"type"` +} +type TaxRegistrationCountryOptionsNg struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsNgType `json:"type"` +} +type TaxRegistrationCountryOptionsNLStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsNLStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsNL struct { + Standard *TaxRegistrationCountryOptionsNLStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsNLType `json:"type"` +} +type TaxRegistrationCountryOptionsNo struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsNoType `json:"type"` +} +type TaxRegistrationCountryOptionsNp struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsNpType `json:"type"` +} +type TaxRegistrationCountryOptionsNz struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsNzType `json:"type"` +} +type TaxRegistrationCountryOptionsOm struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsOmType `json:"type"` +} +type TaxRegistrationCountryOptionsPe struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsPeType `json:"type"` +} +type TaxRegistrationCountryOptionsPh struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsPhType `json:"type"` +} +type TaxRegistrationCountryOptionsPLStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsPLStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsPL struct { + Standard *TaxRegistrationCountryOptionsPLStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsPLType `json:"type"` +} +type TaxRegistrationCountryOptionsPTStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsPTStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsPT struct { + Standard *TaxRegistrationCountryOptionsPTStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsPTType `json:"type"` +} +type TaxRegistrationCountryOptionsROStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsROStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsRO struct { + Standard *TaxRegistrationCountryOptionsROStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsROType `json:"type"` +} +type TaxRegistrationCountryOptionsRs struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsRsType `json:"type"` +} +type TaxRegistrationCountryOptionsRU struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsRUType `json:"type"` +} +type TaxRegistrationCountryOptionsSa struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsSaType `json:"type"` +} +type TaxRegistrationCountryOptionsSeStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsSeStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsSe struct { + Standard *TaxRegistrationCountryOptionsSeStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsSeType `json:"type"` +} +type TaxRegistrationCountryOptionsSg struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsSgType `json:"type"` +} +type TaxRegistrationCountryOptionsSiStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsSiStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsSi struct { + Standard *TaxRegistrationCountryOptionsSiStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsSiType `json:"type"` +} +type TaxRegistrationCountryOptionsSKStandard struct { + // Place of supply scheme used in an EU standard registration. + PlaceOfSupplyScheme TaxRegistrationCountryOptionsSKStandardPlaceOfSupplyScheme `json:"place_of_supply_scheme"` +} +type TaxRegistrationCountryOptionsSK struct { + Standard *TaxRegistrationCountryOptionsSKStandard `json:"standard"` + // Type of registration in an EU country. + Type TaxRegistrationCountryOptionsSKType `json:"type"` +} +type TaxRegistrationCountryOptionsSn struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsSnType `json:"type"` +} +type TaxRegistrationCountryOptionsSr struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsSrType `json:"type"` +} +type TaxRegistrationCountryOptionsTH struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsTHType `json:"type"` +} +type TaxRegistrationCountryOptionsTj struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsTjType `json:"type"` +} +type TaxRegistrationCountryOptionsTR struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsTRType `json:"type"` +} +type TaxRegistrationCountryOptionsTz struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsTzType `json:"type"` +} +type TaxRegistrationCountryOptionsUa struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsUaType `json:"type"` +} +type TaxRegistrationCountryOptionsUg struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsUgType `json:"type"` +} +type TaxRegistrationCountryOptionsUSLocalAmusementTax struct { + // A [FIPS code](https://www.census.gov/library/reference/code-lists/ansi.html) representing the local jurisdiction. + Jurisdiction string `json:"jurisdiction"` +} +type TaxRegistrationCountryOptionsUSLocalLeaseTax struct { + // A [FIPS code](https://www.census.gov/library/reference/code-lists/ansi.html) representing the local jurisdiction. + Jurisdiction string `json:"jurisdiction"` +} + +// Elections for the state sales tax registration. +type TaxRegistrationCountryOptionsUSStateSalesTaxElection struct { + // A [FIPS code](https://www.census.gov/library/reference/code-lists/ansi.html) representing the local jurisdiction. + Jurisdiction string `json:"jurisdiction"` + // The type of the election for the state sales tax registration. + Type TaxRegistrationCountryOptionsUSStateSalesTaxElectionType `json:"type"` +} +type TaxRegistrationCountryOptionsUSStateSalesTax struct { + // Elections for the state sales tax registration. + Elections []*TaxRegistrationCountryOptionsUSStateSalesTaxElection `json:"elections"` +} +type TaxRegistrationCountryOptionsUS struct { + LocalAmusementTax *TaxRegistrationCountryOptionsUSLocalAmusementTax `json:"local_amusement_tax"` + LocalLeaseTax *TaxRegistrationCountryOptionsUSLocalLeaseTax `json:"local_lease_tax"` + // Two-letter US state code ([ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2)). + State string `json:"state"` + StateSalesTax *TaxRegistrationCountryOptionsUSStateSalesTax `json:"state_sales_tax"` + // Type of registration in the US. + Type TaxRegistrationCountryOptionsUSType `json:"type"` +} +type TaxRegistrationCountryOptionsUy struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsUyType `json:"type"` +} +type TaxRegistrationCountryOptionsUz struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsUzType `json:"type"` +} +type TaxRegistrationCountryOptionsVn struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsVnType `json:"type"` +} +type TaxRegistrationCountryOptionsZa struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsZaType `json:"type"` +} +type TaxRegistrationCountryOptionsZm struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsZmType `json:"type"` +} +type TaxRegistrationCountryOptionsZw struct { + // Type of registration in `country`. + Type TaxRegistrationCountryOptionsZwType `json:"type"` +} +type TaxRegistrationCountryOptions struct { + Ae *TaxRegistrationCountryOptionsAe `json:"ae"` + Al *TaxRegistrationCountryOptionsAl `json:"al"` + Am *TaxRegistrationCountryOptionsAm `json:"am"` + Ao *TaxRegistrationCountryOptionsAo `json:"ao"` + At *TaxRegistrationCountryOptionsAt `json:"at"` + Au *TaxRegistrationCountryOptionsAu `json:"au"` + Aw *TaxRegistrationCountryOptionsAw `json:"aw"` + Az *TaxRegistrationCountryOptionsAz `json:"az"` + Ba *TaxRegistrationCountryOptionsBa `json:"ba"` + Bb *TaxRegistrationCountryOptionsBb `json:"bb"` + Bd *TaxRegistrationCountryOptionsBd `json:"bd"` + Be *TaxRegistrationCountryOptionsBe `json:"be"` + Bf *TaxRegistrationCountryOptionsBf `json:"bf"` + BG *TaxRegistrationCountryOptionsBG `json:"bg"` + Bh *TaxRegistrationCountryOptionsBh `json:"bh"` + Bj *TaxRegistrationCountryOptionsBj `json:"bj"` + Bs *TaxRegistrationCountryOptionsBs `json:"bs"` + By *TaxRegistrationCountryOptionsBy `json:"by"` + Ca *TaxRegistrationCountryOptionsCa `json:"ca"` + Cd *TaxRegistrationCountryOptionsCd `json:"cd"` + Ch *TaxRegistrationCountryOptionsCh `json:"ch"` + Cl *TaxRegistrationCountryOptionsCl `json:"cl"` + Cm *TaxRegistrationCountryOptionsCm `json:"cm"` + Co *TaxRegistrationCountryOptionsCo `json:"co"` + Cr *TaxRegistrationCountryOptionsCr `json:"cr"` + Cv *TaxRegistrationCountryOptionsCv `json:"cv"` + Cy *TaxRegistrationCountryOptionsCy `json:"cy"` + Cz *TaxRegistrationCountryOptionsCz `json:"cz"` + DE *TaxRegistrationCountryOptionsDE `json:"de"` + Dk *TaxRegistrationCountryOptionsDk `json:"dk"` + Ec *TaxRegistrationCountryOptionsEc `json:"ec"` + Ee *TaxRegistrationCountryOptionsEe `json:"ee"` + Eg *TaxRegistrationCountryOptionsEg `json:"eg"` + ES *TaxRegistrationCountryOptionsES `json:"es"` + ET *TaxRegistrationCountryOptionsET `json:"et"` + FI *TaxRegistrationCountryOptionsFI `json:"fi"` + FR *TaxRegistrationCountryOptionsFR `json:"fr"` + GB *TaxRegistrationCountryOptionsGB `json:"gb"` + Ge *TaxRegistrationCountryOptionsGe `json:"ge"` + Gn *TaxRegistrationCountryOptionsGn `json:"gn"` + Gr *TaxRegistrationCountryOptionsGr `json:"gr"` + HR *TaxRegistrationCountryOptionsHR `json:"hr"` + HU *TaxRegistrationCountryOptionsHU `json:"hu"` + ID *TaxRegistrationCountryOptionsID `json:"id"` + Ie *TaxRegistrationCountryOptionsIe `json:"ie"` + In *TaxRegistrationCountryOptionsIn `json:"in"` + Is *TaxRegistrationCountryOptionsIs `json:"is"` + IT *TaxRegistrationCountryOptionsIT `json:"it"` + JP *TaxRegistrationCountryOptionsJP `json:"jp"` + Ke *TaxRegistrationCountryOptionsKe `json:"ke"` + Kg *TaxRegistrationCountryOptionsKg `json:"kg"` + Kh *TaxRegistrationCountryOptionsKh `json:"kh"` + Kr *TaxRegistrationCountryOptionsKr `json:"kr"` + Kz *TaxRegistrationCountryOptionsKz `json:"kz"` + La *TaxRegistrationCountryOptionsLa `json:"la"` + LT *TaxRegistrationCountryOptionsLT `json:"lt"` + Lu *TaxRegistrationCountryOptionsLu `json:"lu"` + LV *TaxRegistrationCountryOptionsLV `json:"lv"` + Ma *TaxRegistrationCountryOptionsMa `json:"ma"` + Md *TaxRegistrationCountryOptionsMd `json:"md"` + Me *TaxRegistrationCountryOptionsMe `json:"me"` + Mk *TaxRegistrationCountryOptionsMk `json:"mk"` + Mr *TaxRegistrationCountryOptionsMr `json:"mr"` + MT *TaxRegistrationCountryOptionsMT `json:"mt"` + MX *TaxRegistrationCountryOptionsMX `json:"mx"` + My *TaxRegistrationCountryOptionsMy `json:"my"` + Ng *TaxRegistrationCountryOptionsNg `json:"ng"` + NL *TaxRegistrationCountryOptionsNL `json:"nl"` + No *TaxRegistrationCountryOptionsNo `json:"no"` + Np *TaxRegistrationCountryOptionsNp `json:"np"` + Nz *TaxRegistrationCountryOptionsNz `json:"nz"` + Om *TaxRegistrationCountryOptionsOm `json:"om"` + Pe *TaxRegistrationCountryOptionsPe `json:"pe"` + Ph *TaxRegistrationCountryOptionsPh `json:"ph"` + PL *TaxRegistrationCountryOptionsPL `json:"pl"` + PT *TaxRegistrationCountryOptionsPT `json:"pt"` + RO *TaxRegistrationCountryOptionsRO `json:"ro"` + Rs *TaxRegistrationCountryOptionsRs `json:"rs"` + RU *TaxRegistrationCountryOptionsRU `json:"ru"` + Sa *TaxRegistrationCountryOptionsSa `json:"sa"` + Se *TaxRegistrationCountryOptionsSe `json:"se"` + Sg *TaxRegistrationCountryOptionsSg `json:"sg"` + Si *TaxRegistrationCountryOptionsSi `json:"si"` + SK *TaxRegistrationCountryOptionsSK `json:"sk"` + Sn *TaxRegistrationCountryOptionsSn `json:"sn"` + Sr *TaxRegistrationCountryOptionsSr `json:"sr"` + TH *TaxRegistrationCountryOptionsTH `json:"th"` + Tj *TaxRegistrationCountryOptionsTj `json:"tj"` + TR *TaxRegistrationCountryOptionsTR `json:"tr"` + Tz *TaxRegistrationCountryOptionsTz `json:"tz"` + Ua *TaxRegistrationCountryOptionsUa `json:"ua"` + Ug *TaxRegistrationCountryOptionsUg `json:"ug"` + US *TaxRegistrationCountryOptionsUS `json:"us"` + Uy *TaxRegistrationCountryOptionsUy `json:"uy"` + Uz *TaxRegistrationCountryOptionsUz `json:"uz"` + Vn *TaxRegistrationCountryOptionsVn `json:"vn"` + Za *TaxRegistrationCountryOptionsZa `json:"za"` + Zm *TaxRegistrationCountryOptionsZm `json:"zm"` + Zw *TaxRegistrationCountryOptionsZw `json:"zw"` +} + +// A Tax `Registration` lets us know that your business is registered to collect tax on payments within a region, enabling you to [automatically collect tax](https://stripe.com/docs/tax). +// +// Stripe doesn't register on your behalf with the relevant authorities when you create a Tax `Registration` object. For more information on how to register to collect tax, see [our guide](https://stripe.com/docs/tax/registering). +// +// Related guide: [Using the Registrations API](https://stripe.com/docs/tax/registrations-api) +type TaxRegistration struct { + APIResource + // Time at which the registration becomes active. Measured in seconds since the Unix epoch. + ActiveFrom int64 `json:"active_from"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country string `json:"country"` + CountryOptions *TaxRegistrationCountryOptions `json:"country_options"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // If set, the registration stops being active at this time. If not set, the registration will be active indefinitely. Measured in seconds since the Unix epoch. + ExpiresAt int64 `json:"expires_at"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The status of the registration. This field is present for convenience and can be deduced from `active_from` and `expires_at`. + Status TaxRegistrationStatus `json:"status"` +} + +// TaxRegistrationList is a list of Registrations as retrieved from a list endpoint. +type TaxRegistrationList struct { + APIResource + ListMeta + Data []*TaxRegistration `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/tax_registration_service.go b/vendor/github.com/stripe/stripe-go/v82/tax_registration_service.go new file mode 100644 index 00000000..fd2c0ac2 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/tax_registration_service.go @@ -0,0 +1,75 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TaxRegistrationService is used to invoke /v1/tax/registrations APIs. +type v1TaxRegistrationService struct { + B Backend + Key string +} + +// Creates a new Tax Registration object. +func (c v1TaxRegistrationService) Create(ctx context.Context, params *TaxRegistrationCreateParams) (*TaxRegistration, error) { + if params == nil { + params = &TaxRegistrationCreateParams{} + } + params.Context = ctx + registration := &TaxRegistration{} + err := c.B.Call( + http.MethodPost, "/v1/tax/registrations", c.Key, params, registration) + return registration, err +} + +// Returns a Tax Registration object. +func (c v1TaxRegistrationService) Retrieve(ctx context.Context, id string, params *TaxRegistrationRetrieveParams) (*TaxRegistration, error) { + if params == nil { + params = &TaxRegistrationRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/tax/registrations/%s", id) + registration := &TaxRegistration{} + err := c.B.Call(http.MethodGet, path, c.Key, params, registration) + return registration, err +} + +// Updates an existing Tax Registration object. +// +// A registration cannot be deleted after it has been created. If you wish to end a registration you may do so by setting expires_at. +func (c v1TaxRegistrationService) Update(ctx context.Context, id string, params *TaxRegistrationUpdateParams) (*TaxRegistration, error) { + if params == nil { + params = &TaxRegistrationUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/tax/registrations/%s", id) + registration := &TaxRegistration{} + err := c.B.Call(http.MethodPost, path, c.Key, params, registration) + return registration, err +} + +// Returns a list of Tax Registration objects. +func (c v1TaxRegistrationService) List(ctx context.Context, listParams *TaxRegistrationListParams) Seq2[*TaxRegistration, error] { + if listParams == nil { + listParams = &TaxRegistrationListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TaxRegistration, ListContainer, error) { + list := &TaxRegistrationList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/tax/registrations", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/tax_settings.go b/vendor/github.com/stripe/stripe-go/v82/tax_settings.go new file mode 100644 index 00000000..6b24b067 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/tax_settings.go @@ -0,0 +1,136 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Default [tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#tax-behavior) used to specify whether the price is considered inclusive of taxes or exclusive of taxes. If the item's price has a tax behavior set, it will take precedence over the default tax behavior. +type TaxSettingsDefaultsTaxBehavior string + +// List of values that TaxSettingsDefaultsTaxBehavior can take +const ( + TaxSettingsDefaultsTaxBehaviorExclusive TaxSettingsDefaultsTaxBehavior = "exclusive" + TaxSettingsDefaultsTaxBehaviorInclusive TaxSettingsDefaultsTaxBehavior = "inclusive" + TaxSettingsDefaultsTaxBehaviorInferredByCurrency TaxSettingsDefaultsTaxBehavior = "inferred_by_currency" +) + +// The status of the Tax `Settings`. +type TaxSettingsStatus string + +// List of values that TaxSettingsStatus can take +const ( + TaxSettingsStatusActive TaxSettingsStatus = "active" + TaxSettingsStatusPending TaxSettingsStatus = "pending" +) + +// Retrieves Tax Settings for a merchant. +type TaxSettingsParams struct { + Params `form:"*"` + // Default configuration to be used on Stripe Tax calculations. + Defaults *TaxSettingsDefaultsParams `form:"defaults"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The place where your business is located. + HeadOffice *TaxSettingsHeadOfficeParams `form:"head_office"` +} + +// AddExpand appends a new field to expand. +func (p *TaxSettingsParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Default configuration to be used on Stripe Tax calculations. +type TaxSettingsDefaultsParams struct { + // Specifies the default [tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#tax-behavior) to be used when the item's price has unspecified tax behavior. One of inclusive, exclusive, or inferred_by_currency. Once specified, it cannot be changed back to null. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` +} + +// The place where your business is located. +type TaxSettingsHeadOfficeParams struct { + // The location of the business for tax purposes. + Address *AddressParams `form:"address"` +} + +// Retrieves Tax Settings for a merchant. +type TaxSettingsRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TaxSettingsRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Default configuration to be used on Stripe Tax calculations. +type TaxSettingsUpdateDefaultsParams struct { + // Specifies the default [tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#tax-behavior) to be used when the item's price has unspecified tax behavior. One of inclusive, exclusive, or inferred_by_currency. Once specified, it cannot be changed back to null. + TaxBehavior *string `form:"tax_behavior"` + // A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + TaxCode *string `form:"tax_code"` +} + +// The place where your business is located. +type TaxSettingsUpdateHeadOfficeParams struct { + // The location of the business for tax purposes. + Address *AddressParams `form:"address"` +} + +// Updates Tax Settings parameters used in tax calculations. All parameters are editable but none can be removed once set. +type TaxSettingsUpdateParams struct { + Params `form:"*"` + // Default configuration to be used on Stripe Tax calculations. + Defaults *TaxSettingsUpdateDefaultsParams `form:"defaults"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The place where your business is located. + HeadOffice *TaxSettingsUpdateHeadOfficeParams `form:"head_office"` +} + +// AddExpand appends a new field to expand. +func (p *TaxSettingsUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type TaxSettingsDefaults struct { + // Default [tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#tax-behavior) used to specify whether the price is considered inclusive of taxes or exclusive of taxes. If the item's price has a tax behavior set, it will take precedence over the default tax behavior. + TaxBehavior TaxSettingsDefaultsTaxBehavior `json:"tax_behavior"` + // Default [tax code](https://stripe.com/docs/tax/tax-categories) used to classify your products and prices. + TaxCode string `json:"tax_code"` +} + +// The place where your business is located. +type TaxSettingsHeadOffice struct { + Address *Address `json:"address"` +} +type TaxSettingsStatusDetailsActive struct{} +type TaxSettingsStatusDetailsPending struct { + // The list of missing fields that are required to perform calculations. It includes the entry `head_office` when the status is `pending`. It is recommended to set the optional values even if they aren't listed as required for calculating taxes. Calculations can fail if missing fields aren't explicitly provided on every call. + MissingFields []string `json:"missing_fields"` +} +type TaxSettingsStatusDetails struct { + Active *TaxSettingsStatusDetailsActive `json:"active"` + Pending *TaxSettingsStatusDetailsPending `json:"pending"` +} + +// You can use Tax `Settings` to manage configurations used by Stripe Tax calculations. +// +// Related guide: [Using the Settings API](https://stripe.com/docs/tax/settings-api) +type TaxSettings struct { + APIResource + Defaults *TaxSettingsDefaults `json:"defaults"` + // The place where your business is located. + HeadOffice *TaxSettingsHeadOffice `json:"head_office"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The status of the Tax `Settings`. + Status TaxSettingsStatus `json:"status"` + StatusDetails *TaxSettingsStatusDetails `json:"status_details"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/tax_settings_service.go b/vendor/github.com/stripe/stripe-go/v82/tax_settings_service.go new file mode 100644 index 00000000..d90555a0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/tax_settings_service.go @@ -0,0 +1,40 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TaxSettingsService is used to invoke /v1/tax/settings APIs. +type v1TaxSettingsService struct { + B Backend + Key string +} + +// Retrieves Tax Settings for a merchant. +func (c v1TaxSettingsService) Retrieve(ctx context.Context, params *TaxSettingsRetrieveParams) (*TaxSettings, error) { + if params == nil { + params = &TaxSettingsRetrieveParams{} + } + params.Context = ctx + settings := &TaxSettings{} + err := c.B.Call(http.MethodGet, "/v1/tax/settings", c.Key, params, settings) + return settings, err +} + +// Updates Tax Settings parameters used in tax calculations. All parameters are editable but none can be removed once set. +func (c v1TaxSettingsService) Update(ctx context.Context, params *TaxSettingsUpdateParams) (*TaxSettings, error) { + if params == nil { + params = &TaxSettingsUpdateParams{} + } + params.Context = ctx + settings := &TaxSettings{} + err := c.B.Call(http.MethodPost, "/v1/tax/settings", c.Key, params, settings) + return settings, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/tax_transaction.go b/vendor/github.com/stripe/stripe-go/v82/tax_transaction.go new file mode 100644 index 00000000..a26bdad3 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/tax_transaction.go @@ -0,0 +1,480 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The type of customer address provided. +type TaxTransactionCustomerDetailsAddressSource string + +// List of values that TaxTransactionCustomerDetailsAddressSource can take +const ( + TaxTransactionCustomerDetailsAddressSourceBilling TaxTransactionCustomerDetailsAddressSource = "billing" + TaxTransactionCustomerDetailsAddressSourceShipping TaxTransactionCustomerDetailsAddressSource = "shipping" +) + +// The type of the tax ID, one of `ad_nrt`, `ar_cuit`, `eu_vat`, `bo_tin`, `br_cnpj`, `br_cpf`, `cn_tin`, `co_nit`, `cr_tin`, `do_rcn`, `ec_ruc`, `eu_oss_vat`, `hr_oib`, `pe_ruc`, `ro_tin`, `rs_pib`, `sv_nit`, `uy_ruc`, `ve_rif`, `vn_tin`, `gb_vat`, `nz_gst`, `au_abn`, `au_arn`, `in_gst`, `no_vat`, `no_voec`, `za_vat`, `ch_vat`, `mx_rfc`, `sg_uen`, `ru_inn`, `ru_kpp`, `ca_bn`, `hk_br`, `es_cif`, `tw_vat`, `th_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `li_uid`, `li_vat`, `my_itn`, `us_ein`, `kr_brn`, `ca_qst`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `my_sst`, `sg_gst`, `ae_trn`, `cl_tin`, `sa_vat`, `id_npwp`, `my_frp`, `il_vat`, `ge_vat`, `ua_vat`, `is_vat`, `bg_uic`, `hu_tin`, `si_tin`, `ke_pin`, `tr_tin`, `eg_tin`, `ph_tin`, `al_tin`, `bh_vat`, `kz_bin`, `ng_tin`, `om_vat`, `de_stn`, `ch_uid`, `tz_vat`, `uz_vat`, `uz_tin`, `md_vat`, `ma_vat`, `by_tin`, `ao_tin`, `bs_tin`, `bb_tin`, `cd_nif`, `mr_nif`, `me_pib`, `zw_tin`, `ba_tin`, `gn_nif`, `mk_vat`, `sr_fin`, `sn_ninea`, `am_tin`, `np_pan`, `tj_tin`, `ug_tin`, `zm_tin`, `kh_tin`, `aw_tin`, `az_tin`, `bd_bin`, `bj_ifu`, `et_tin`, `kg_tin`, `la_tin`, `cm_niu`, `cv_nif`, `bf_ifu`, or `unknown` +type TaxTransactionCustomerDetailsTaxIDType string + +// List of values that TaxTransactionCustomerDetailsTaxIDType can take +const ( + TaxTransactionCustomerDetailsTaxIDTypeADNRT TaxTransactionCustomerDetailsTaxIDType = "ad_nrt" + TaxTransactionCustomerDetailsTaxIDTypeAETRN TaxTransactionCustomerDetailsTaxIDType = "ae_trn" + TaxTransactionCustomerDetailsTaxIDTypeAlTin TaxTransactionCustomerDetailsTaxIDType = "al_tin" + TaxTransactionCustomerDetailsTaxIDTypeAmTin TaxTransactionCustomerDetailsTaxIDType = "am_tin" + TaxTransactionCustomerDetailsTaxIDTypeAoTin TaxTransactionCustomerDetailsTaxIDType = "ao_tin" + TaxTransactionCustomerDetailsTaxIDTypeARCUIT TaxTransactionCustomerDetailsTaxIDType = "ar_cuit" + TaxTransactionCustomerDetailsTaxIDTypeAUABN TaxTransactionCustomerDetailsTaxIDType = "au_abn" + TaxTransactionCustomerDetailsTaxIDTypeAUARN TaxTransactionCustomerDetailsTaxIDType = "au_arn" + TaxTransactionCustomerDetailsTaxIDTypeAwTin TaxTransactionCustomerDetailsTaxIDType = "aw_tin" + TaxTransactionCustomerDetailsTaxIDTypeAzTin TaxTransactionCustomerDetailsTaxIDType = "az_tin" + TaxTransactionCustomerDetailsTaxIDTypeBaTin TaxTransactionCustomerDetailsTaxIDType = "ba_tin" + TaxTransactionCustomerDetailsTaxIDTypeBbTin TaxTransactionCustomerDetailsTaxIDType = "bb_tin" + TaxTransactionCustomerDetailsTaxIDTypeBdBin TaxTransactionCustomerDetailsTaxIDType = "bd_bin" + TaxTransactionCustomerDetailsTaxIDTypeBfIfu TaxTransactionCustomerDetailsTaxIDType = "bf_ifu" + TaxTransactionCustomerDetailsTaxIDTypeBGUIC TaxTransactionCustomerDetailsTaxIDType = "bg_uic" + TaxTransactionCustomerDetailsTaxIDTypeBhVAT TaxTransactionCustomerDetailsTaxIDType = "bh_vat" + TaxTransactionCustomerDetailsTaxIDTypeBjIfu TaxTransactionCustomerDetailsTaxIDType = "bj_ifu" + TaxTransactionCustomerDetailsTaxIDTypeBOTIN TaxTransactionCustomerDetailsTaxIDType = "bo_tin" + TaxTransactionCustomerDetailsTaxIDTypeBRCNPJ TaxTransactionCustomerDetailsTaxIDType = "br_cnpj" + TaxTransactionCustomerDetailsTaxIDTypeBRCPF TaxTransactionCustomerDetailsTaxIDType = "br_cpf" + TaxTransactionCustomerDetailsTaxIDTypeBsTin TaxTransactionCustomerDetailsTaxIDType = "bs_tin" + TaxTransactionCustomerDetailsTaxIDTypeByTin TaxTransactionCustomerDetailsTaxIDType = "by_tin" + TaxTransactionCustomerDetailsTaxIDTypeCABN TaxTransactionCustomerDetailsTaxIDType = "ca_bn" + TaxTransactionCustomerDetailsTaxIDTypeCAGSTHST TaxTransactionCustomerDetailsTaxIDType = "ca_gst_hst" + TaxTransactionCustomerDetailsTaxIDTypeCAPSTBC TaxTransactionCustomerDetailsTaxIDType = "ca_pst_bc" + TaxTransactionCustomerDetailsTaxIDTypeCAPSTMB TaxTransactionCustomerDetailsTaxIDType = "ca_pst_mb" + TaxTransactionCustomerDetailsTaxIDTypeCAPSTSK TaxTransactionCustomerDetailsTaxIDType = "ca_pst_sk" + TaxTransactionCustomerDetailsTaxIDTypeCAQST TaxTransactionCustomerDetailsTaxIDType = "ca_qst" + TaxTransactionCustomerDetailsTaxIDTypeCdNif TaxTransactionCustomerDetailsTaxIDType = "cd_nif" + TaxTransactionCustomerDetailsTaxIDTypeCHUID TaxTransactionCustomerDetailsTaxIDType = "ch_uid" + TaxTransactionCustomerDetailsTaxIDTypeCHVAT TaxTransactionCustomerDetailsTaxIDType = "ch_vat" + TaxTransactionCustomerDetailsTaxIDTypeCLTIN TaxTransactionCustomerDetailsTaxIDType = "cl_tin" + TaxTransactionCustomerDetailsTaxIDTypeCmNiu TaxTransactionCustomerDetailsTaxIDType = "cm_niu" + TaxTransactionCustomerDetailsTaxIDTypeCNTIN TaxTransactionCustomerDetailsTaxIDType = "cn_tin" + TaxTransactionCustomerDetailsTaxIDTypeCONIT TaxTransactionCustomerDetailsTaxIDType = "co_nit" + TaxTransactionCustomerDetailsTaxIDTypeCRTIN TaxTransactionCustomerDetailsTaxIDType = "cr_tin" + TaxTransactionCustomerDetailsTaxIDTypeCvNif TaxTransactionCustomerDetailsTaxIDType = "cv_nif" + TaxTransactionCustomerDetailsTaxIDTypeDEStn TaxTransactionCustomerDetailsTaxIDType = "de_stn" + TaxTransactionCustomerDetailsTaxIDTypeDORCN TaxTransactionCustomerDetailsTaxIDType = "do_rcn" + TaxTransactionCustomerDetailsTaxIDTypeECRUC TaxTransactionCustomerDetailsTaxIDType = "ec_ruc" + TaxTransactionCustomerDetailsTaxIDTypeEGTIN TaxTransactionCustomerDetailsTaxIDType = "eg_tin" + TaxTransactionCustomerDetailsTaxIDTypeESCIF TaxTransactionCustomerDetailsTaxIDType = "es_cif" + TaxTransactionCustomerDetailsTaxIDTypeETTin TaxTransactionCustomerDetailsTaxIDType = "et_tin" + TaxTransactionCustomerDetailsTaxIDTypeEUOSSVAT TaxTransactionCustomerDetailsTaxIDType = "eu_oss_vat" + TaxTransactionCustomerDetailsTaxIDTypeEUVAT TaxTransactionCustomerDetailsTaxIDType = "eu_vat" + TaxTransactionCustomerDetailsTaxIDTypeGBVAT TaxTransactionCustomerDetailsTaxIDType = "gb_vat" + TaxTransactionCustomerDetailsTaxIDTypeGEVAT TaxTransactionCustomerDetailsTaxIDType = "ge_vat" + TaxTransactionCustomerDetailsTaxIDTypeGnNif TaxTransactionCustomerDetailsTaxIDType = "gn_nif" + TaxTransactionCustomerDetailsTaxIDTypeHKBR TaxTransactionCustomerDetailsTaxIDType = "hk_br" + TaxTransactionCustomerDetailsTaxIDTypeHROIB TaxTransactionCustomerDetailsTaxIDType = "hr_oib" + TaxTransactionCustomerDetailsTaxIDTypeHUTIN TaxTransactionCustomerDetailsTaxIDType = "hu_tin" + TaxTransactionCustomerDetailsTaxIDTypeIDNPWP TaxTransactionCustomerDetailsTaxIDType = "id_npwp" + TaxTransactionCustomerDetailsTaxIDTypeILVAT TaxTransactionCustomerDetailsTaxIDType = "il_vat" + TaxTransactionCustomerDetailsTaxIDTypeINGST TaxTransactionCustomerDetailsTaxIDType = "in_gst" + TaxTransactionCustomerDetailsTaxIDTypeISVAT TaxTransactionCustomerDetailsTaxIDType = "is_vat" + TaxTransactionCustomerDetailsTaxIDTypeJPCN TaxTransactionCustomerDetailsTaxIDType = "jp_cn" + TaxTransactionCustomerDetailsTaxIDTypeJPRN TaxTransactionCustomerDetailsTaxIDType = "jp_rn" + TaxTransactionCustomerDetailsTaxIDTypeJPTRN TaxTransactionCustomerDetailsTaxIDType = "jp_trn" + TaxTransactionCustomerDetailsTaxIDTypeKEPIN TaxTransactionCustomerDetailsTaxIDType = "ke_pin" + TaxTransactionCustomerDetailsTaxIDTypeKgTin TaxTransactionCustomerDetailsTaxIDType = "kg_tin" + TaxTransactionCustomerDetailsTaxIDTypeKhTin TaxTransactionCustomerDetailsTaxIDType = "kh_tin" + TaxTransactionCustomerDetailsTaxIDTypeKRBRN TaxTransactionCustomerDetailsTaxIDType = "kr_brn" + TaxTransactionCustomerDetailsTaxIDTypeKzBin TaxTransactionCustomerDetailsTaxIDType = "kz_bin" + TaxTransactionCustomerDetailsTaxIDTypeLaTin TaxTransactionCustomerDetailsTaxIDType = "la_tin" + TaxTransactionCustomerDetailsTaxIDTypeLIUID TaxTransactionCustomerDetailsTaxIDType = "li_uid" + TaxTransactionCustomerDetailsTaxIDTypeLiVAT TaxTransactionCustomerDetailsTaxIDType = "li_vat" + TaxTransactionCustomerDetailsTaxIDTypeMaVAT TaxTransactionCustomerDetailsTaxIDType = "ma_vat" + TaxTransactionCustomerDetailsTaxIDTypeMdVAT TaxTransactionCustomerDetailsTaxIDType = "md_vat" + TaxTransactionCustomerDetailsTaxIDTypeMePib TaxTransactionCustomerDetailsTaxIDType = "me_pib" + TaxTransactionCustomerDetailsTaxIDTypeMkVAT TaxTransactionCustomerDetailsTaxIDType = "mk_vat" + TaxTransactionCustomerDetailsTaxIDTypeMrNif TaxTransactionCustomerDetailsTaxIDType = "mr_nif" + TaxTransactionCustomerDetailsTaxIDTypeMXRFC TaxTransactionCustomerDetailsTaxIDType = "mx_rfc" + TaxTransactionCustomerDetailsTaxIDTypeMYFRP TaxTransactionCustomerDetailsTaxIDType = "my_frp" + TaxTransactionCustomerDetailsTaxIDTypeMYITN TaxTransactionCustomerDetailsTaxIDType = "my_itn" + TaxTransactionCustomerDetailsTaxIDTypeMYSST TaxTransactionCustomerDetailsTaxIDType = "my_sst" + TaxTransactionCustomerDetailsTaxIDTypeNgTin TaxTransactionCustomerDetailsTaxIDType = "ng_tin" + TaxTransactionCustomerDetailsTaxIDTypeNOVAT TaxTransactionCustomerDetailsTaxIDType = "no_vat" + TaxTransactionCustomerDetailsTaxIDTypeNOVOEC TaxTransactionCustomerDetailsTaxIDType = "no_voec" + TaxTransactionCustomerDetailsTaxIDTypeNpPan TaxTransactionCustomerDetailsTaxIDType = "np_pan" + TaxTransactionCustomerDetailsTaxIDTypeNZGST TaxTransactionCustomerDetailsTaxIDType = "nz_gst" + TaxTransactionCustomerDetailsTaxIDTypeOmVAT TaxTransactionCustomerDetailsTaxIDType = "om_vat" + TaxTransactionCustomerDetailsTaxIDTypePERUC TaxTransactionCustomerDetailsTaxIDType = "pe_ruc" + TaxTransactionCustomerDetailsTaxIDTypePHTIN TaxTransactionCustomerDetailsTaxIDType = "ph_tin" + TaxTransactionCustomerDetailsTaxIDTypeROTIN TaxTransactionCustomerDetailsTaxIDType = "ro_tin" + TaxTransactionCustomerDetailsTaxIDTypeRSPIB TaxTransactionCustomerDetailsTaxIDType = "rs_pib" + TaxTransactionCustomerDetailsTaxIDTypeRUINN TaxTransactionCustomerDetailsTaxIDType = "ru_inn" + TaxTransactionCustomerDetailsTaxIDTypeRUKPP TaxTransactionCustomerDetailsTaxIDType = "ru_kpp" + TaxTransactionCustomerDetailsTaxIDTypeSAVAT TaxTransactionCustomerDetailsTaxIDType = "sa_vat" + TaxTransactionCustomerDetailsTaxIDTypeSGGST TaxTransactionCustomerDetailsTaxIDType = "sg_gst" + TaxTransactionCustomerDetailsTaxIDTypeSGUEN TaxTransactionCustomerDetailsTaxIDType = "sg_uen" + TaxTransactionCustomerDetailsTaxIDTypeSITIN TaxTransactionCustomerDetailsTaxIDType = "si_tin" + TaxTransactionCustomerDetailsTaxIDTypeSnNinea TaxTransactionCustomerDetailsTaxIDType = "sn_ninea" + TaxTransactionCustomerDetailsTaxIDTypeSrFin TaxTransactionCustomerDetailsTaxIDType = "sr_fin" + TaxTransactionCustomerDetailsTaxIDTypeSVNIT TaxTransactionCustomerDetailsTaxIDType = "sv_nit" + TaxTransactionCustomerDetailsTaxIDTypeTHVAT TaxTransactionCustomerDetailsTaxIDType = "th_vat" + TaxTransactionCustomerDetailsTaxIDTypeTjTin TaxTransactionCustomerDetailsTaxIDType = "tj_tin" + TaxTransactionCustomerDetailsTaxIDTypeTRTIN TaxTransactionCustomerDetailsTaxIDType = "tr_tin" + TaxTransactionCustomerDetailsTaxIDTypeTWVAT TaxTransactionCustomerDetailsTaxIDType = "tw_vat" + TaxTransactionCustomerDetailsTaxIDTypeTzVAT TaxTransactionCustomerDetailsTaxIDType = "tz_vat" + TaxTransactionCustomerDetailsTaxIDTypeUAVAT TaxTransactionCustomerDetailsTaxIDType = "ua_vat" + TaxTransactionCustomerDetailsTaxIDTypeUgTin TaxTransactionCustomerDetailsTaxIDType = "ug_tin" + TaxTransactionCustomerDetailsTaxIDTypeUnknown TaxTransactionCustomerDetailsTaxIDType = "unknown" + TaxTransactionCustomerDetailsTaxIDTypeUSEIN TaxTransactionCustomerDetailsTaxIDType = "us_ein" + TaxTransactionCustomerDetailsTaxIDTypeUYRUC TaxTransactionCustomerDetailsTaxIDType = "uy_ruc" + TaxTransactionCustomerDetailsTaxIDTypeUzTin TaxTransactionCustomerDetailsTaxIDType = "uz_tin" + TaxTransactionCustomerDetailsTaxIDTypeUzVAT TaxTransactionCustomerDetailsTaxIDType = "uz_vat" + TaxTransactionCustomerDetailsTaxIDTypeVERIF TaxTransactionCustomerDetailsTaxIDType = "ve_rif" + TaxTransactionCustomerDetailsTaxIDTypeVNTIN TaxTransactionCustomerDetailsTaxIDType = "vn_tin" + TaxTransactionCustomerDetailsTaxIDTypeZAVAT TaxTransactionCustomerDetailsTaxIDType = "za_vat" + TaxTransactionCustomerDetailsTaxIDTypeZmTin TaxTransactionCustomerDetailsTaxIDType = "zm_tin" + TaxTransactionCustomerDetailsTaxIDTypeZwTin TaxTransactionCustomerDetailsTaxIDType = "zw_tin" +) + +// The taxability override used for taxation. +type TaxTransactionCustomerDetailsTaxabilityOverride string + +// List of values that TaxTransactionCustomerDetailsTaxabilityOverride can take +const ( + TaxTransactionCustomerDetailsTaxabilityOverrideCustomerExempt TaxTransactionCustomerDetailsTaxabilityOverride = "customer_exempt" + TaxTransactionCustomerDetailsTaxabilityOverrideNone TaxTransactionCustomerDetailsTaxabilityOverride = "none" + TaxTransactionCustomerDetailsTaxabilityOverrideReverseCharge TaxTransactionCustomerDetailsTaxabilityOverride = "reverse_charge" +) + +// Specifies whether the `amount` includes taxes. If `tax_behavior=inclusive`, then the amount includes taxes. +type TaxTransactionShippingCostTaxBehavior string + +// List of values that TaxTransactionShippingCostTaxBehavior can take +const ( + TaxTransactionShippingCostTaxBehaviorExclusive TaxTransactionShippingCostTaxBehavior = "exclusive" + TaxTransactionShippingCostTaxBehaviorInclusive TaxTransactionShippingCostTaxBehavior = "inclusive" +) + +// Indicates the level of the jurisdiction imposing the tax. +type TaxTransactionShippingCostTaxBreakdownJurisdictionLevel string + +// List of values that TaxTransactionShippingCostTaxBreakdownJurisdictionLevel can take +const ( + TaxTransactionShippingCostTaxBreakdownJurisdictionLevelCity TaxTransactionShippingCostTaxBreakdownJurisdictionLevel = "city" + TaxTransactionShippingCostTaxBreakdownJurisdictionLevelCountry TaxTransactionShippingCostTaxBreakdownJurisdictionLevel = "country" + TaxTransactionShippingCostTaxBreakdownJurisdictionLevelCounty TaxTransactionShippingCostTaxBreakdownJurisdictionLevel = "county" + TaxTransactionShippingCostTaxBreakdownJurisdictionLevelDistrict TaxTransactionShippingCostTaxBreakdownJurisdictionLevel = "district" + TaxTransactionShippingCostTaxBreakdownJurisdictionLevelState TaxTransactionShippingCostTaxBreakdownJurisdictionLevel = "state" +) + +// Indicates whether the jurisdiction was determined by the origin (merchant's address) or destination (customer's address). +type TaxTransactionShippingCostTaxBreakdownSourcing string + +// List of values that TaxTransactionShippingCostTaxBreakdownSourcing can take +const ( + TaxTransactionShippingCostTaxBreakdownSourcingDestination TaxTransactionShippingCostTaxBreakdownSourcing = "destination" + TaxTransactionShippingCostTaxBreakdownSourcingOrigin TaxTransactionShippingCostTaxBreakdownSourcing = "origin" +) + +// The tax type, such as `vat` or `sales_tax`. +type TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType string + +// List of values that TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType can take +const ( + TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxTypeAmusementTax TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType = "amusement_tax" + TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxTypeCommunicationsTax TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType = "communications_tax" + TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxTypeGST TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType = "gst" + TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxTypeHST TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType = "hst" + TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxTypeIGST TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType = "igst" + TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxTypeJCT TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType = "jct" + TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxTypeLeaseTax TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType = "lease_tax" + TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxTypePST TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType = "pst" + TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxTypeQST TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType = "qst" + TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxTypeRetailDeliveryFee TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType = "retail_delivery_fee" + TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxTypeRST TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType = "rst" + TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxTypeSalesTax TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType = "sales_tax" + TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxTypeServiceTax TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType = "service_tax" + TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxTypeVAT TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType = "vat" +) + +// The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. +type TaxTransactionShippingCostTaxBreakdownTaxabilityReason string + +// List of values that TaxTransactionShippingCostTaxBreakdownTaxabilityReason can take +const ( + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonCustomerExempt TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "customer_exempt" + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonNotCollecting TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "not_collecting" + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonNotSubjectToTax TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "not_subject_to_tax" + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonNotSupported TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "not_supported" + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonPortionProductExempt TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "portion_product_exempt" + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonPortionReducedRated TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "portion_reduced_rated" + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonPortionStandardRated TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "portion_standard_rated" + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonProductExempt TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "product_exempt" + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonProductExemptHoliday TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "product_exempt_holiday" + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonProportionallyRated TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "proportionally_rated" + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonReducedRated TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "reduced_rated" + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonReverseCharge TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "reverse_charge" + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonStandardRated TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "standard_rated" + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonTaxableBasisReduced TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "taxable_basis_reduced" + TaxTransactionShippingCostTaxBreakdownTaxabilityReasonZeroRated TaxTransactionShippingCostTaxBreakdownTaxabilityReason = "zero_rated" +) + +// If `reversal`, this transaction reverses an earlier transaction. +type TaxTransactionType string + +// List of values that TaxTransactionType can take +const ( + TaxTransactionTypeReversal TaxTransactionType = "reversal" + TaxTransactionTypeTransaction TaxTransactionType = "transaction" +) + +// Retrieves a Tax Transaction object. +type TaxTransactionParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TaxTransactionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the line items of a committed standalone transaction as a collection. +type TaxTransactionListLineItemsParams struct { + ListParams `form:"*"` + Transaction *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TaxTransactionListLineItemsParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates a Tax Transaction from a calculation, if that calculation hasn't expired. Calculations expire after 90 days. +type TaxTransactionCreateFromCalculationParams struct { + Params `form:"*"` + // Tax Calculation ID to be used as input when creating the transaction. + Calculation *string `form:"calculation"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The Unix timestamp representing when the tax liability is assumed or reduced, which determines the liability posting period and handling in tax liability reports. The timestamp must fall within the `tax_date` and the current time, unless the `tax_date` is scheduled in advance. Defaults to the current time. + PostedAt *int64 `form:"posted_at"` + // A custom order or sale identifier, such as 'myOrder_123'. Must be unique across all transactions, including reversals. + Reference *string `form:"reference"` +} + +// AddExpand appends a new field to expand. +func (p *TaxTransactionCreateFromCalculationParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TaxTransactionCreateFromCalculationParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The line item amounts to reverse. +type TaxTransactionCreateReversalLineItemParams struct { + // The amount to reverse, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) in negative. + Amount *int64 `form:"amount"` + // The amount of tax to reverse, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) in negative. + AmountTax *int64 `form:"amount_tax"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `form:"metadata"` + // The `id` of the line item to reverse in the original transaction. + OriginalLineItem *string `form:"original_line_item"` + // The quantity reversed. Appears in [tax exports](https://stripe.com/docs/tax/reports), but does not affect the amount of tax reversed. + Quantity *int64 `form:"quantity"` + // A custom identifier for this line item in the reversal transaction, such as 'L1-refund'. + Reference *string `form:"reference"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TaxTransactionCreateReversalLineItemParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The shipping cost to reverse. +type TaxTransactionCreateReversalShippingCostParams struct { + // The amount to reverse, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) in negative. + Amount *int64 `form:"amount"` + // The amount of tax to reverse, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) in negative. + AmountTax *int64 `form:"amount_tax"` +} + +// Partially or fully reverses a previously created Transaction. +type TaxTransactionCreateReversalParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A flat amount to reverse across the entire transaction, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) in negative. This value represents the total amount to refund from the transaction, including taxes. + FlatAmount *int64 `form:"flat_amount"` + // The line item amounts to reverse. + LineItems []*TaxTransactionCreateReversalLineItemParams `form:"line_items"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // If `partial`, the provided line item or shipping cost amounts are reversed. If `full`, the original transaction is fully reversed. + Mode *string `form:"mode"` + // The ID of the Transaction to partially or fully reverse. + OriginalTransaction *string `form:"original_transaction"` + // A custom identifier for this reversal, such as `myOrder_123-refund_1`, which must be unique across all transactions. The reference helps identify this reversal transaction in exported [tax reports](https://stripe.com/docs/tax/reports). + Reference *string `form:"reference"` + // The shipping cost to reverse. + ShippingCost *TaxTransactionCreateReversalShippingCostParams `form:"shipping_cost"` +} + +// AddExpand appends a new field to expand. +func (p *TaxTransactionCreateReversalParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TaxTransactionCreateReversalParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves a Tax Transaction object. +type TaxTransactionRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TaxTransactionRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The customer's tax IDs (for example, EU VAT numbers). +type TaxTransactionCustomerDetailsTaxID struct { + // The type of the tax ID, one of `ad_nrt`, `ar_cuit`, `eu_vat`, `bo_tin`, `br_cnpj`, `br_cpf`, `cn_tin`, `co_nit`, `cr_tin`, `do_rcn`, `ec_ruc`, `eu_oss_vat`, `hr_oib`, `pe_ruc`, `ro_tin`, `rs_pib`, `sv_nit`, `uy_ruc`, `ve_rif`, `vn_tin`, `gb_vat`, `nz_gst`, `au_abn`, `au_arn`, `in_gst`, `no_vat`, `no_voec`, `za_vat`, `ch_vat`, `mx_rfc`, `sg_uen`, `ru_inn`, `ru_kpp`, `ca_bn`, `hk_br`, `es_cif`, `tw_vat`, `th_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `li_uid`, `li_vat`, `my_itn`, `us_ein`, `kr_brn`, `ca_qst`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `my_sst`, `sg_gst`, `ae_trn`, `cl_tin`, `sa_vat`, `id_npwp`, `my_frp`, `il_vat`, `ge_vat`, `ua_vat`, `is_vat`, `bg_uic`, `hu_tin`, `si_tin`, `ke_pin`, `tr_tin`, `eg_tin`, `ph_tin`, `al_tin`, `bh_vat`, `kz_bin`, `ng_tin`, `om_vat`, `de_stn`, `ch_uid`, `tz_vat`, `uz_vat`, `uz_tin`, `md_vat`, `ma_vat`, `by_tin`, `ao_tin`, `bs_tin`, `bb_tin`, `cd_nif`, `mr_nif`, `me_pib`, `zw_tin`, `ba_tin`, `gn_nif`, `mk_vat`, `sr_fin`, `sn_ninea`, `am_tin`, `np_pan`, `tj_tin`, `ug_tin`, `zm_tin`, `kh_tin`, `aw_tin`, `az_tin`, `bd_bin`, `bj_ifu`, `et_tin`, `kg_tin`, `la_tin`, `cm_niu`, `cv_nif`, `bf_ifu`, or `unknown` + Type TaxTransactionCustomerDetailsTaxIDType `json:"type"` + // The value of the tax ID. + Value string `json:"value"` +} +type TaxTransactionCustomerDetails struct { + // The customer's postal address (for example, home or business location). + Address *Address `json:"address"` + // The type of customer address provided. + AddressSource TaxTransactionCustomerDetailsAddressSource `json:"address_source"` + // The customer's IP address (IPv4 or IPv6). + IPAddress string `json:"ip_address"` + // The taxability override used for taxation. + TaxabilityOverride TaxTransactionCustomerDetailsTaxabilityOverride `json:"taxability_override"` + // The customer's tax IDs (for example, EU VAT numbers). + TaxIDs []*TaxTransactionCustomerDetailsTaxID `json:"tax_ids"` +} + +// If `type=reversal`, contains information about what was reversed. +type TaxTransactionReversal struct { + // The `id` of the reversed `Transaction` object. + OriginalTransaction string `json:"original_transaction"` +} + +// The details of the ship from location, such as the address. +type TaxTransactionShipFromDetails struct { + Address *Address `json:"address"` +} +type TaxTransactionShippingCostTaxBreakdownJurisdiction struct { + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country string `json:"country"` + // A human-readable name for the jurisdiction imposing the tax. + DisplayName string `json:"display_name"` + // Indicates the level of the jurisdiction imposing the tax. + Level TaxTransactionShippingCostTaxBreakdownJurisdictionLevel `json:"level"` + // [ISO 3166-2 subdivision code](https://en.wikipedia.org/wiki/ISO_3166-2), without country prefix. For example, "NY" for New York, United States. + State string `json:"state"` +} + +// Details regarding the rate for this tax. This field will be `null` when the tax is not imposed, for example if the product is exempt from tax. +type TaxTransactionShippingCostTaxBreakdownTaxRateDetails struct { + // A localized display name for tax type, intended to be human-readable. For example, "Local Sales and Use Tax", "Value-added tax (VAT)", or "Umsatzsteuer (USt.)". + DisplayName string `json:"display_name"` + // The tax rate percentage as a string. For example, 8.5% is represented as "8.5". + PercentageDecimal string `json:"percentage_decimal"` + // The tax type, such as `vat` or `sales_tax`. + TaxType TaxTransactionShippingCostTaxBreakdownTaxRateDetailsTaxType `json:"tax_type"` +} + +// Detailed account of taxes relevant to shipping cost. (It is not populated for the transaction resource object and will be removed in the next API version.) +type TaxTransactionShippingCostTaxBreakdown struct { + // The amount of tax, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Amount int64 `json:"amount"` + Jurisdiction *TaxTransactionShippingCostTaxBreakdownJurisdiction `json:"jurisdiction"` + // Indicates whether the jurisdiction was determined by the origin (merchant's address) or destination (customer's address). + Sourcing TaxTransactionShippingCostTaxBreakdownSourcing `json:"sourcing"` + // The reasoning behind this tax, for example, if the product is tax exempt. The possible values for this field may be extended as new tax rules are supported. + TaxabilityReason TaxTransactionShippingCostTaxBreakdownTaxabilityReason `json:"taxability_reason"` + // The amount on which tax is calculated, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + TaxableAmount int64 `json:"taxable_amount"` + // Details regarding the rate for this tax. This field will be `null` when the tax is not imposed, for example if the product is exempt from tax. + TaxRateDetails *TaxTransactionShippingCostTaxBreakdownTaxRateDetails `json:"tax_rate_details"` +} + +// The shipping cost details for the transaction. +type TaxTransactionShippingCost struct { + // The shipping amount in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). If `tax_behavior=inclusive`, then this amount includes taxes. Otherwise, taxes were calculated on top of this amount. + Amount int64 `json:"amount"` + // The amount of tax calculated for shipping, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + AmountTax int64 `json:"amount_tax"` + // The ID of an existing [ShippingRate](https://stripe.com/docs/api/shipping_rates/object). + ShippingRate string `json:"shipping_rate"` + // Specifies whether the `amount` includes taxes. If `tax_behavior=inclusive`, then the amount includes taxes. + TaxBehavior TaxTransactionShippingCostTaxBehavior `json:"tax_behavior"` + // Detailed account of taxes relevant to shipping cost. (It is not populated for the transaction resource object and will be removed in the next API version.) + TaxBreakdown []*TaxTransactionShippingCostTaxBreakdown `json:"tax_breakdown"` + // The [tax code](https://stripe.com/docs/tax/tax-categories) ID used for shipping. + TaxCode string `json:"tax_code"` +} + +// A Tax Transaction records the tax collected from or refunded to your customer. +// +// Related guide: [Calculate tax in your custom payment flow](https://stripe.com/docs/tax/custom#tax-transaction) +type TaxTransaction struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // The ID of an existing [Customer](https://stripe.com/docs/api/customers/object) used for the resource. + Customer string `json:"customer"` + CustomerDetails *TaxTransactionCustomerDetails `json:"customer_details"` + // Unique identifier for the transaction. + ID string `json:"id"` + // The tax collected or refunded, by line item. + LineItems *TaxTransactionLineItemList `json:"line_items"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The Unix timestamp representing when the tax liability is assumed or reduced. + PostedAt int64 `json:"posted_at"` + // A custom unique identifier, such as 'myOrder_123'. + Reference string `json:"reference"` + // If `type=reversal`, contains information about what was reversed. + Reversal *TaxTransactionReversal `json:"reversal"` + // The details of the ship from location, such as the address. + ShipFromDetails *TaxTransactionShipFromDetails `json:"ship_from_details"` + // The shipping cost details for the transaction. + ShippingCost *TaxTransactionShippingCost `json:"shipping_cost"` + // Timestamp of date at which the tax rules and rates in effect applies for the calculation. + TaxDate int64 `json:"tax_date"` + // If `reversal`, this transaction reverses an earlier transaction. + Type TaxTransactionType `json:"type"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/tax_transaction_service.go b/vendor/github.com/stripe/stripe-go/v82/tax_transaction_service.go new file mode 100644 index 00000000..bb449de3 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/tax_transaction_service.go @@ -0,0 +1,75 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TaxTransactionService is used to invoke /v1/tax/transactions APIs. +type v1TaxTransactionService struct { + B Backend + Key string +} + +// Retrieves a Tax Transaction object. +func (c v1TaxTransactionService) Retrieve(ctx context.Context, id string, params *TaxTransactionRetrieveParams) (*TaxTransaction, error) { + if params == nil { + params = &TaxTransactionRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/tax/transactions/%s", id) + transaction := &TaxTransaction{} + err := c.B.Call(http.MethodGet, path, c.Key, params, transaction) + return transaction, err +} + +// Creates a Tax Transaction from a calculation, if that calculation hasn't expired. Calculations expire after 90 days. +func (c v1TaxTransactionService) CreateFromCalculation(ctx context.Context, params *TaxTransactionCreateFromCalculationParams) (*TaxTransaction, error) { + if params == nil { + params = &TaxTransactionCreateFromCalculationParams{} + } + params.Context = ctx + transaction := &TaxTransaction{} + err := c.B.Call( + http.MethodPost, "/v1/tax/transactions/create_from_calculation", c.Key, params, transaction) + return transaction, err +} + +// Partially or fully reverses a previously created Transaction. +func (c v1TaxTransactionService) CreateReversal(ctx context.Context, params *TaxTransactionCreateReversalParams) (*TaxTransaction, error) { + if params == nil { + params = &TaxTransactionCreateReversalParams{} + } + params.Context = ctx + transaction := &TaxTransaction{} + err := c.B.Call( + http.MethodPost, "/v1/tax/transactions/create_reversal", c.Key, params, transaction) + return transaction, err +} + +// Retrieves the line items of a committed standalone transaction as a collection. +func (c v1TaxTransactionService) ListLineItems(ctx context.Context, listParams *TaxTransactionListLineItemsParams) Seq2[*TaxTransactionLineItem, error] { + if listParams == nil { + listParams = &TaxTransactionListLineItemsParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/tax/transactions/%s/line_items", StringValue(listParams.Transaction)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TaxTransactionLineItem, ListContainer, error) { + list := &TaxTransactionLineItemList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/tax_transactionlineitem.go b/vendor/github.com/stripe/stripe-go/v82/tax_transactionlineitem.go new file mode 100644 index 00000000..c0f1f491 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/tax_transactionlineitem.go @@ -0,0 +1,66 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Specifies whether the `amount` includes taxes. If `tax_behavior=inclusive`, then the amount includes taxes. +type TaxTransactionLineItemTaxBehavior string + +// List of values that TaxTransactionLineItemTaxBehavior can take +const ( + TaxTransactionLineItemTaxBehaviorExclusive TaxTransactionLineItemTaxBehavior = "exclusive" + TaxTransactionLineItemTaxBehaviorInclusive TaxTransactionLineItemTaxBehavior = "inclusive" +) + +// If `reversal`, this line item reverses an earlier transaction. +type TaxTransactionLineItemType string + +// List of values that TaxTransactionLineItemType can take +const ( + TaxTransactionLineItemTypeReversal TaxTransactionLineItemType = "reversal" + TaxTransactionLineItemTypeTransaction TaxTransactionLineItemType = "transaction" +) + +// If `type=reversal`, contains information about what was reversed. +type TaxTransactionLineItemReversal struct { + // The `id` of the line item to reverse in the original transaction. + OriginalLineItem string `json:"original_line_item"` +} +type TaxTransactionLineItem struct { + // The line item amount in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). If `tax_behavior=inclusive`, then this amount includes taxes. Otherwise, taxes were calculated on top of this amount. + Amount int64 `json:"amount"` + // The amount of tax calculated for this line item, in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + AmountTax int64 `json:"amount_tax"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The ID of an existing [Product](https://stripe.com/docs/api/products/object). + Product string `json:"product"` + // The number of units of the item being purchased. For reversals, this is the quantity reversed. + Quantity int64 `json:"quantity"` + // A custom identifier for this line item in the transaction. + Reference string `json:"reference"` + // If `type=reversal`, contains information about what was reversed. + Reversal *TaxTransactionLineItemReversal `json:"reversal"` + // Specifies whether the `amount` includes taxes. If `tax_behavior=inclusive`, then the amount includes taxes. + TaxBehavior TaxTransactionLineItemTaxBehavior `json:"tax_behavior"` + // The [tax code](https://stripe.com/docs/tax/tax-categories) ID used for this resource. + TaxCode string `json:"tax_code"` + // If `reversal`, this line item reverses an earlier transaction. + Type TaxTransactionLineItemType `json:"type"` +} + +// TaxTransactionLineItemList is a list of TransactionLineItems as retrieved from a list endpoint. +type TaxTransactionLineItemList struct { + APIResource + ListMeta + Data []*TaxTransactionLineItem `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/taxcode.go b/vendor/github.com/stripe/stripe-go/v82/taxcode.go new file mode 100644 index 00000000..eddb0e09 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/taxcode.go @@ -0,0 +1,84 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// A list of [all tax codes available](https://stripe.com/docs/tax/tax-categories) to add to Products in order to allow specific tax calculations. +type TaxCodeListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TaxCodeListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an existing tax code. Supply the unique tax code ID and Stripe will return the corresponding tax code information. +type TaxCodeParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TaxCodeParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an existing tax code. Supply the unique tax code ID and Stripe will return the corresponding tax code information. +type TaxCodeRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TaxCodeRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// [Tax codes](https://stripe.com/docs/tax/tax-categories) classify goods and services for tax purposes. +type TaxCode struct { + APIResource + // A detailed description of which types of products the tax code represents. + Description string `json:"description"` + // Unique identifier for the object. + ID string `json:"id"` + // A short name for the tax code. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} + +// TaxCodeList is a list of TaxCodes as retrieved from a list endpoint. +type TaxCodeList struct { + APIResource + ListMeta + Data []*TaxCode `json:"data"` +} + +// UnmarshalJSON handles deserialization of a TaxCode. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (t *TaxCode) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + t.ID = id + return nil + } + + type taxCode TaxCode + var v taxCode + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *t = TaxCode(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/taxcode_service.go b/vendor/github.com/stripe/stripe-go/v82/taxcode_service.go new file mode 100644 index 00000000..b6f2d2d0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/taxcode_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TaxCodeService is used to invoke /v1/tax_codes APIs. +type v1TaxCodeService struct { + B Backend + Key string +} + +// Retrieves the details of an existing tax code. Supply the unique tax code ID and Stripe will return the corresponding tax code information. +func (c v1TaxCodeService) Retrieve(ctx context.Context, id string, params *TaxCodeRetrieveParams) (*TaxCode, error) { + if params == nil { + params = &TaxCodeRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/tax_codes/%s", id) + taxcode := &TaxCode{} + err := c.B.Call(http.MethodGet, path, c.Key, params, taxcode) + return taxcode, err +} + +// A list of [all tax codes available](https://stripe.com/docs/tax/tax-categories) to add to Products in order to allow specific tax calculations. +func (c v1TaxCodeService) List(ctx context.Context, listParams *TaxCodeListParams) Seq2[*TaxCode, error] { + if listParams == nil { + listParams = &TaxCodeListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TaxCode, ListContainer, error) { + list := &TaxCodeList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/tax_codes", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/taxdeductedatsource.go b/vendor/github.com/stripe/stripe-go/v82/taxdeductedatsource.go new file mode 100644 index 00000000..2f12f218 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/taxdeductedatsource.go @@ -0,0 +1,41 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +type TaxDeductedAtSource struct { + // Unique identifier for the object. + ID string `json:"id"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The end of the invoicing period. This TDS applies to Stripe fees collected during this invoicing period. + PeriodEnd int64 `json:"period_end"` + // The start of the invoicing period. This TDS applies to Stripe fees collected during this invoicing period. + PeriodStart int64 `json:"period_start"` + // The TAN that was supplied to Stripe when TDS was assessed + TaxDeductionAccountNumber string `json:"tax_deduction_account_number"` +} + +// UnmarshalJSON handles deserialization of a TaxDeductedAtSource. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (t *TaxDeductedAtSource) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + t.ID = id + return nil + } + + type taxDeductedAtSource TaxDeductedAtSource + var v taxDeductedAtSource + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *t = TaxDeductedAtSource(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/taxid.go b/vendor/github.com/stripe/stripe-go/v82/taxid.go new file mode 100644 index 00000000..00dba71f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/taxid.go @@ -0,0 +1,292 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Type of owner referenced. +type TaxIDOwnerType string + +// List of values that TaxIDOwnerType can take +const ( + TaxIDOwnerTypeAccount TaxIDOwnerType = "account" + TaxIDOwnerTypeApplication TaxIDOwnerType = "application" + TaxIDOwnerTypeCustomer TaxIDOwnerType = "customer" + TaxIDOwnerTypeSelf TaxIDOwnerType = "self" +) + +// Type of the tax ID, one of `ad_nrt`, `ae_trn`, `al_tin`, `am_tin`, `ao_tin`, `ar_cuit`, `au_abn`, `au_arn`, `aw_tin`, `az_tin`, `ba_tin`, `bb_tin`, `bd_bin`, `bf_ifu`, `bg_uic`, `bh_vat`, `bj_ifu`, `bo_tin`, `br_cnpj`, `br_cpf`, `bs_tin`, `by_tin`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `ca_qst`, `cd_nif`, `ch_uid`, `ch_vat`, `cl_tin`, `cm_niu`, `cn_tin`, `co_nit`, `cr_tin`, `cv_nif`, `de_stn`, `do_rcn`, `ec_ruc`, `eg_tin`, `es_cif`, `et_tin`, `eu_oss_vat`, `eu_vat`, `gb_vat`, `ge_vat`, `gn_nif`, `hk_br`, `hr_oib`, `hu_tin`, `id_npwp`, `il_vat`, `in_gst`, `is_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `ke_pin`, `kg_tin`, `kh_tin`, `kr_brn`, `kz_bin`, `la_tin`, `li_uid`, `li_vat`, `ma_vat`, `md_vat`, `me_pib`, `mk_vat`, `mr_nif`, `mx_rfc`, `my_frp`, `my_itn`, `my_sst`, `ng_tin`, `no_vat`, `no_voec`, `np_pan`, `nz_gst`, `om_vat`, `pe_ruc`, `ph_tin`, `ro_tin`, `rs_pib`, `ru_inn`, `ru_kpp`, `sa_vat`, `sg_gst`, `sg_uen`, `si_tin`, `sn_ninea`, `sr_fin`, `sv_nit`, `th_vat`, `tj_tin`, `tr_tin`, `tw_vat`, `tz_vat`, `ua_vat`, `ug_tin`, `us_ein`, `uy_ruc`, `uz_tin`, `uz_vat`, `ve_rif`, `vn_tin`, `za_vat`, `zm_tin`, or `zw_tin`. Note that some legacy tax IDs have type `unknown` +type TaxIDType string + +// List of values that TaxIDType can take +const ( + TaxIDTypeADNRT TaxIDType = "ad_nrt" + TaxIDTypeAETRN TaxIDType = "ae_trn" + TaxIDTypeAlTin TaxIDType = "al_tin" + TaxIDTypeAmTin TaxIDType = "am_tin" + TaxIDTypeAoTin TaxIDType = "ao_tin" + TaxIDTypeARCUIT TaxIDType = "ar_cuit" + TaxIDTypeAUABN TaxIDType = "au_abn" + TaxIDTypeAUARN TaxIDType = "au_arn" + TaxIDTypeAwTin TaxIDType = "aw_tin" + TaxIDTypeAzTin TaxIDType = "az_tin" + TaxIDTypeBaTin TaxIDType = "ba_tin" + TaxIDTypeBbTin TaxIDType = "bb_tin" + TaxIDTypeBdBin TaxIDType = "bd_bin" + TaxIDTypeBfIfu TaxIDType = "bf_ifu" + TaxIDTypeBGUIC TaxIDType = "bg_uic" + TaxIDTypeBhVAT TaxIDType = "bh_vat" + TaxIDTypeBjIfu TaxIDType = "bj_ifu" + TaxIDTypeBOTIN TaxIDType = "bo_tin" + TaxIDTypeBRCNPJ TaxIDType = "br_cnpj" + TaxIDTypeBRCPF TaxIDType = "br_cpf" + TaxIDTypeBsTin TaxIDType = "bs_tin" + TaxIDTypeByTin TaxIDType = "by_tin" + TaxIDTypeCABN TaxIDType = "ca_bn" + TaxIDTypeCAGSTHST TaxIDType = "ca_gst_hst" + TaxIDTypeCAPSTBC TaxIDType = "ca_pst_bc" + TaxIDTypeCAPSTMB TaxIDType = "ca_pst_mb" + TaxIDTypeCAPSTSK TaxIDType = "ca_pst_sk" + TaxIDTypeCAQST TaxIDType = "ca_qst" + TaxIDTypeCdNif TaxIDType = "cd_nif" + TaxIDTypeCHUID TaxIDType = "ch_uid" + TaxIDTypeCHVAT TaxIDType = "ch_vat" + TaxIDTypeCLTIN TaxIDType = "cl_tin" + TaxIDTypeCmNiu TaxIDType = "cm_niu" + TaxIDTypeCNTIN TaxIDType = "cn_tin" + TaxIDTypeCONIT TaxIDType = "co_nit" + TaxIDTypeCRTIN TaxIDType = "cr_tin" + TaxIDTypeCvNif TaxIDType = "cv_nif" + TaxIDTypeDEStn TaxIDType = "de_stn" + TaxIDTypeDORCN TaxIDType = "do_rcn" + TaxIDTypeECRUC TaxIDType = "ec_ruc" + TaxIDTypeEGTIN TaxIDType = "eg_tin" + TaxIDTypeESCIF TaxIDType = "es_cif" + TaxIDTypeETTin TaxIDType = "et_tin" + TaxIDTypeEUOSSVAT TaxIDType = "eu_oss_vat" + TaxIDTypeEUVAT TaxIDType = "eu_vat" + TaxIDTypeGBVAT TaxIDType = "gb_vat" + TaxIDTypeGEVAT TaxIDType = "ge_vat" + TaxIDTypeGnNif TaxIDType = "gn_nif" + TaxIDTypeHKBR TaxIDType = "hk_br" + TaxIDTypeHROIB TaxIDType = "hr_oib" + TaxIDTypeHUTIN TaxIDType = "hu_tin" + TaxIDTypeIDNPWP TaxIDType = "id_npwp" + TaxIDTypeILVAT TaxIDType = "il_vat" + TaxIDTypeINGST TaxIDType = "in_gst" + TaxIDTypeISVAT TaxIDType = "is_vat" + TaxIDTypeJPCN TaxIDType = "jp_cn" + TaxIDTypeJPRN TaxIDType = "jp_rn" + TaxIDTypeJPTRN TaxIDType = "jp_trn" + TaxIDTypeKEPIN TaxIDType = "ke_pin" + TaxIDTypeKgTin TaxIDType = "kg_tin" + TaxIDTypeKhTin TaxIDType = "kh_tin" + TaxIDTypeKRBRN TaxIDType = "kr_brn" + TaxIDTypeKzBin TaxIDType = "kz_bin" + TaxIDTypeLaTin TaxIDType = "la_tin" + TaxIDTypeLIUID TaxIDType = "li_uid" + TaxIDTypeLiVAT TaxIDType = "li_vat" + TaxIDTypeMaVAT TaxIDType = "ma_vat" + TaxIDTypeMdVAT TaxIDType = "md_vat" + TaxIDTypeMePib TaxIDType = "me_pib" + TaxIDTypeMkVAT TaxIDType = "mk_vat" + TaxIDTypeMrNif TaxIDType = "mr_nif" + TaxIDTypeMXRFC TaxIDType = "mx_rfc" + TaxIDTypeMYFRP TaxIDType = "my_frp" + TaxIDTypeMYITN TaxIDType = "my_itn" + TaxIDTypeMYSST TaxIDType = "my_sst" + TaxIDTypeNgTin TaxIDType = "ng_tin" + TaxIDTypeNOVAT TaxIDType = "no_vat" + TaxIDTypeNOVOEC TaxIDType = "no_voec" + TaxIDTypeNpPan TaxIDType = "np_pan" + TaxIDTypeNZGST TaxIDType = "nz_gst" + TaxIDTypeOmVAT TaxIDType = "om_vat" + TaxIDTypePERUC TaxIDType = "pe_ruc" + TaxIDTypePHTIN TaxIDType = "ph_tin" + TaxIDTypeROTIN TaxIDType = "ro_tin" + TaxIDTypeRSPIB TaxIDType = "rs_pib" + TaxIDTypeRUINN TaxIDType = "ru_inn" + TaxIDTypeRUKPP TaxIDType = "ru_kpp" + TaxIDTypeSAVAT TaxIDType = "sa_vat" + TaxIDTypeSGGST TaxIDType = "sg_gst" + TaxIDTypeSGUEN TaxIDType = "sg_uen" + TaxIDTypeSITIN TaxIDType = "si_tin" + TaxIDTypeSnNinea TaxIDType = "sn_ninea" + TaxIDTypeSrFin TaxIDType = "sr_fin" + TaxIDTypeSVNIT TaxIDType = "sv_nit" + TaxIDTypeTHVAT TaxIDType = "th_vat" + TaxIDTypeTjTin TaxIDType = "tj_tin" + TaxIDTypeTRTIN TaxIDType = "tr_tin" + TaxIDTypeTWVAT TaxIDType = "tw_vat" + TaxIDTypeTzVAT TaxIDType = "tz_vat" + TaxIDTypeUAVAT TaxIDType = "ua_vat" + TaxIDTypeUgTin TaxIDType = "ug_tin" + TaxIDTypeUnknown TaxIDType = "unknown" + TaxIDTypeUSEIN TaxIDType = "us_ein" + TaxIDTypeUYRUC TaxIDType = "uy_ruc" + TaxIDTypeUzTin TaxIDType = "uz_tin" + TaxIDTypeUzVAT TaxIDType = "uz_vat" + TaxIDTypeVERIF TaxIDType = "ve_rif" + TaxIDTypeVNTIN TaxIDType = "vn_tin" + TaxIDTypeZAVAT TaxIDType = "za_vat" + TaxIDTypeZmTin TaxIDType = "zm_tin" + TaxIDTypeZwTin TaxIDType = "zw_tin" +) + +// Verification status, one of `pending`, `verified`, `unverified`, or `unavailable`. +type TaxIDVerificationStatus string + +// List of values that TaxIDVerificationStatus can take +const ( + TaxIDVerificationStatusPending TaxIDVerificationStatus = "pending" + TaxIDVerificationStatusUnavailable TaxIDVerificationStatus = "unavailable" + TaxIDVerificationStatusUnverified TaxIDVerificationStatus = "unverified" + TaxIDVerificationStatusVerified TaxIDVerificationStatus = "verified" +) + +// Deletes an existing tax_id object. +type TaxIDParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Type of the tax ID, one of `ad_nrt`, `ae_trn`, `al_tin`, `am_tin`, `ao_tin`, `ar_cuit`, `au_abn`, `au_arn`, `aw_tin`, `az_tin`, `ba_tin`, `bb_tin`, `bd_bin`, `bf_ifu`, `bg_uic`, `bh_vat`, `bj_ifu`, `bo_tin`, `br_cnpj`, `br_cpf`, `bs_tin`, `by_tin`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `ca_qst`, `cd_nif`, `ch_uid`, `ch_vat`, `cl_tin`, `cm_niu`, `cn_tin`, `co_nit`, `cr_tin`, `cv_nif`, `de_stn`, `do_rcn`, `ec_ruc`, `eg_tin`, `es_cif`, `et_tin`, `eu_oss_vat`, `eu_vat`, `gb_vat`, `ge_vat`, `gn_nif`, `hk_br`, `hr_oib`, `hu_tin`, `id_npwp`, `il_vat`, `in_gst`, `is_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `ke_pin`, `kg_tin`, `kh_tin`, `kr_brn`, `kz_bin`, `la_tin`, `li_uid`, `li_vat`, `ma_vat`, `md_vat`, `me_pib`, `mk_vat`, `mr_nif`, `mx_rfc`, `my_frp`, `my_itn`, `my_sst`, `ng_tin`, `no_vat`, `no_voec`, `np_pan`, `nz_gst`, `om_vat`, `pe_ruc`, `ph_tin`, `ro_tin`, `rs_pib`, `ru_inn`, `ru_kpp`, `sa_vat`, `sg_gst`, `sg_uen`, `si_tin`, `sn_ninea`, `sr_fin`, `sv_nit`, `th_vat`, `tj_tin`, `tr_tin`, `tw_vat`, `tz_vat`, `ua_vat`, `ug_tin`, `us_ein`, `uy_ruc`, `uz_tin`, `uz_vat`, `ve_rif`, `vn_tin`, `za_vat`, `zm_tin`, or `zw_tin` + Type *string `form:"type"` + // Value of the tax ID. + Value *string `form:"value"` +} + +// AddExpand appends a new field to expand. +func (p *TaxIDParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Returns a list of tax IDs for a customer. +type TaxIDListParams struct { + ListParams `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TaxIDListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Deletes an existing tax_id object. +type TaxIDDeleteParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL +} + +// Retrieves the tax_id object with the given identifier. +type TaxIDRetrieveParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TaxIDRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates a new tax_id object for a customer. +type TaxIDCreateParams struct { + Params `form:"*"` + Customer *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Type of the tax ID, one of `ad_nrt`, `ae_trn`, `al_tin`, `am_tin`, `ao_tin`, `ar_cuit`, `au_abn`, `au_arn`, `aw_tin`, `az_tin`, `ba_tin`, `bb_tin`, `bd_bin`, `bf_ifu`, `bg_uic`, `bh_vat`, `bj_ifu`, `bo_tin`, `br_cnpj`, `br_cpf`, `bs_tin`, `by_tin`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `ca_qst`, `cd_nif`, `ch_uid`, `ch_vat`, `cl_tin`, `cm_niu`, `cn_tin`, `co_nit`, `cr_tin`, `cv_nif`, `de_stn`, `do_rcn`, `ec_ruc`, `eg_tin`, `es_cif`, `et_tin`, `eu_oss_vat`, `eu_vat`, `gb_vat`, `ge_vat`, `gn_nif`, `hk_br`, `hr_oib`, `hu_tin`, `id_npwp`, `il_vat`, `in_gst`, `is_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `ke_pin`, `kg_tin`, `kh_tin`, `kr_brn`, `kz_bin`, `la_tin`, `li_uid`, `li_vat`, `ma_vat`, `md_vat`, `me_pib`, `mk_vat`, `mr_nif`, `mx_rfc`, `my_frp`, `my_itn`, `my_sst`, `ng_tin`, `no_vat`, `no_voec`, `np_pan`, `nz_gst`, `om_vat`, `pe_ruc`, `ph_tin`, `ro_tin`, `rs_pib`, `ru_inn`, `ru_kpp`, `sa_vat`, `sg_gst`, `sg_uen`, `si_tin`, `sn_ninea`, `sr_fin`, `sv_nit`, `th_vat`, `tj_tin`, `tr_tin`, `tw_vat`, `tz_vat`, `ua_vat`, `ug_tin`, `us_ein`, `uy_ruc`, `uz_tin`, `uz_vat`, `ve_rif`, `vn_tin`, `za_vat`, `zm_tin`, or `zw_tin` + Type *string `form:"type"` + // Value of the tax ID. + Value *string `form:"value"` +} + +// AddExpand appends a new field to expand. +func (p *TaxIDCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The account or customer the tax ID belongs to. +type TaxIDOwner struct { + // The account being referenced when `type` is `account`. + Account *Account `json:"account"` + // The Connect Application being referenced when `type` is `application`. + Application *Application `json:"application"` + // The customer being referenced when `type` is `customer`. + Customer *Customer `json:"customer"` + // Type of owner referenced. + Type TaxIDOwnerType `json:"type"` +} + +// Tax ID verification information. +type TaxIDVerification struct { + // Verification status, one of `pending`, `verified`, `unverified`, or `unavailable`. + Status TaxIDVerificationStatus `json:"status"` + // Verified address. + VerifiedAddress string `json:"verified_address"` + // Verified name. + VerifiedName string `json:"verified_name"` +} + +// You can add one or multiple tax IDs to a [customer](https://stripe.com/docs/api/customers) or account. +// Customer and account tax IDs get displayed on related invoices and credit notes. +// +// Related guides: [Customer tax identification numbers](https://stripe.com/docs/billing/taxes/tax-ids), [Account tax IDs](https://stripe.com/docs/invoicing/connect#account-tax-ids) +type TaxID struct { + APIResource + // Two-letter ISO code representing the country of the tax ID. + Country string `json:"country"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // ID of the customer. + Customer *Customer `json:"customer"` + Deleted bool `json:"deleted"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The account or customer the tax ID belongs to. + Owner *TaxIDOwner `json:"owner"` + // Type of the tax ID, one of `ad_nrt`, `ae_trn`, `al_tin`, `am_tin`, `ao_tin`, `ar_cuit`, `au_abn`, `au_arn`, `aw_tin`, `az_tin`, `ba_tin`, `bb_tin`, `bd_bin`, `bf_ifu`, `bg_uic`, `bh_vat`, `bj_ifu`, `bo_tin`, `br_cnpj`, `br_cpf`, `bs_tin`, `by_tin`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `ca_qst`, `cd_nif`, `ch_uid`, `ch_vat`, `cl_tin`, `cm_niu`, `cn_tin`, `co_nit`, `cr_tin`, `cv_nif`, `de_stn`, `do_rcn`, `ec_ruc`, `eg_tin`, `es_cif`, `et_tin`, `eu_oss_vat`, `eu_vat`, `gb_vat`, `ge_vat`, `gn_nif`, `hk_br`, `hr_oib`, `hu_tin`, `id_npwp`, `il_vat`, `in_gst`, `is_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `ke_pin`, `kg_tin`, `kh_tin`, `kr_brn`, `kz_bin`, `la_tin`, `li_uid`, `li_vat`, `ma_vat`, `md_vat`, `me_pib`, `mk_vat`, `mr_nif`, `mx_rfc`, `my_frp`, `my_itn`, `my_sst`, `ng_tin`, `no_vat`, `no_voec`, `np_pan`, `nz_gst`, `om_vat`, `pe_ruc`, `ph_tin`, `ro_tin`, `rs_pib`, `ru_inn`, `ru_kpp`, `sa_vat`, `sg_gst`, `sg_uen`, `si_tin`, `sn_ninea`, `sr_fin`, `sv_nit`, `th_vat`, `tj_tin`, `tr_tin`, `tw_vat`, `tz_vat`, `ua_vat`, `ug_tin`, `us_ein`, `uy_ruc`, `uz_tin`, `uz_vat`, `ve_rif`, `vn_tin`, `za_vat`, `zm_tin`, or `zw_tin`. Note that some legacy tax IDs have type `unknown` + Type TaxIDType `json:"type"` + // Value of the tax ID. + Value string `json:"value"` + // Tax ID verification information. + Verification *TaxIDVerification `json:"verification"` +} + +// TaxIDList is a list of TaxIds as retrieved from a list endpoint. +type TaxIDList struct { + APIResource + ListMeta + Data []*TaxID `json:"data"` +} + +// UnmarshalJSON handles deserialization of a TaxID. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (t *TaxID) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + t.ID = id + return nil + } + + type taxID TaxID + var v taxID + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *t = TaxID(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/taxid_service.go b/vendor/github.com/stripe/stripe-go/v82/taxid_service.go new file mode 100644 index 00000000..220b98b0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/taxid_service.go @@ -0,0 +1,90 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TaxIDService is used to invoke /v1/tax_ids APIs. +type v1TaxIDService struct { + B Backend + Key string +} + +// Creates a new tax_id object for a customer. +func (c v1TaxIDService) Create(ctx context.Context, params *TaxIDCreateParams) (*TaxID, error) { + path := "/v1/tax_ids" + if params == nil { + params = &TaxIDCreateParams{} + } + params.Context = ctx + if params.Customer != nil { + path = FormatURLPath( + "/v1/customers/%s/tax_ids", StringValue(params.Customer)) + } + taxid := &TaxID{} + err := c.B.Call(http.MethodPost, path, c.Key, params, taxid) + return taxid, err +} + +// Retrieves the tax_id object with the given identifier. +func (c v1TaxIDService) Retrieve(ctx context.Context, id string, params *TaxIDRetrieveParams) (*TaxID, error) { + path := FormatURLPath("/v1/tax_ids/%s", id) + if params == nil { + params = &TaxIDRetrieveParams{} + } + params.Context = ctx + if params.Customer != nil { + path = FormatURLPath( + "/v1/customers/%s/tax_ids/%s", StringValue(params.Customer), id) + } + taxid := &TaxID{} + err := c.B.Call(http.MethodGet, path, c.Key, params, taxid) + return taxid, err +} + +// Deletes an existing tax_id object. +func (c v1TaxIDService) Delete(ctx context.Context, id string, params *TaxIDDeleteParams) (*TaxID, error) { + path := FormatURLPath("/v1/tax_ids/%s", id) + if params == nil { + params = &TaxIDDeleteParams{} + } + params.Context = ctx + if params.Customer != nil { + path = FormatURLPath( + "/v1/customers/%s/tax_ids/%s", StringValue(params.Customer), id) + } + taxid := &TaxID{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, taxid) + return taxid, err +} + +// Returns a list of tax IDs for a customer. +func (c v1TaxIDService) List(ctx context.Context, listParams *TaxIDListParams) Seq2[*TaxID, error] { + path := "/v1/tax_ids" + if listParams != nil && listParams.Customer != nil { + path = FormatURLPath( + "/v1/customers/%s/tax_ids", StringValue(listParams.Customer)) + } + if listParams == nil { + listParams = &TaxIDListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TaxID, ListContainer, error) { + list := &TaxIDList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/taxrate.go b/vendor/github.com/stripe/stripe-go/v82/taxrate.go new file mode 100644 index 00000000..040cbd5b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/taxrate.go @@ -0,0 +1,282 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The level of the jurisdiction that imposes this tax rate. Will be `null` for manually defined tax rates. +type TaxRateJurisdictionLevel string + +// List of values that TaxRateJurisdictionLevel can take +const ( + TaxRateJurisdictionLevelCity TaxRateJurisdictionLevel = "city" + TaxRateJurisdictionLevelCountry TaxRateJurisdictionLevel = "country" + TaxRateJurisdictionLevelCounty TaxRateJurisdictionLevel = "county" + TaxRateJurisdictionLevelDistrict TaxRateJurisdictionLevel = "district" + TaxRateJurisdictionLevelMultiple TaxRateJurisdictionLevel = "multiple" + TaxRateJurisdictionLevelState TaxRateJurisdictionLevel = "state" +) + +// Indicates the type of tax rate applied to the taxable amount. This value can be `null` when no tax applies to the location. This field is only present for TaxRates created by Stripe Tax. +type TaxRateRateType string + +// List of values that TaxRateRateType can take +const ( + TaxRateRateTypeFlatAmount TaxRateRateType = "flat_amount" + TaxRateRateTypePercentage TaxRateRateType = "percentage" +) + +// The high-level tax type, such as `vat` or `sales_tax`. +type TaxRateTaxType string + +// List of values that TaxRateTaxType can take +const ( + TaxRateTaxTypeAmusementTax TaxRateTaxType = "amusement_tax" + TaxRateTaxTypeCommunicationsTax TaxRateTaxType = "communications_tax" + TaxRateTaxTypeGST TaxRateTaxType = "gst" + TaxRateTaxTypeHST TaxRateTaxType = "hst" + TaxRateTaxTypeIGST TaxRateTaxType = "igst" + TaxRateTaxTypeJCT TaxRateTaxType = "jct" + TaxRateTaxTypeLeaseTax TaxRateTaxType = "lease_tax" + TaxRateTaxTypePST TaxRateTaxType = "pst" + TaxRateTaxTypeQST TaxRateTaxType = "qst" + TaxRateTaxTypeRetailDeliveryFee TaxRateTaxType = "retail_delivery_fee" + TaxRateTaxTypeRST TaxRateTaxType = "rst" + TaxRateTaxTypeSalesTax TaxRateTaxType = "sales_tax" + TaxRateTaxTypeServiceTax TaxRateTaxType = "service_tax" + TaxRateTaxTypeVAT TaxRateTaxType = "vat" +) + +// Returns a list of your tax rates. Tax rates are returned sorted by creation date, with the most recently created tax rates appearing first. +type TaxRateListParams struct { + ListParams `form:"*"` + // Optional flag to filter by tax rates that are either active or inactive (archived). + Active *bool `form:"active"` + // Optional range for filtering created date. + Created *int64 `form:"created"` + // Optional range for filtering created date. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Optional flag to filter by tax rates that are inclusive (or those that are not inclusive). + Inclusive *bool `form:"inclusive"` +} + +// AddExpand appends a new field to expand. +func (p *TaxRateListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates a new tax rate. +type TaxRateParams struct { + Params `form:"*"` + // Flag determining whether the tax rate is active or inactive (archived). Inactive tax rates cannot be used with new applications or Checkout Sessions, but will still work for subscriptions and invoices that already have it set. + Active *bool `form:"active"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // An arbitrary string attached to the tax rate for your internal use only. It will not be visible to your customers. + Description *string `form:"description"` + // The display name of the tax rate, which will be shown to users. + DisplayName *string `form:"display_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // This specifies if the tax rate is inclusive or exclusive. + Inclusive *bool `form:"inclusive"` + // The jurisdiction for the tax rate. You can use this label field for tax reporting purposes. It also appears on your customer's invoice. + Jurisdiction *string `form:"jurisdiction"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // This represents the tax rate percent out of 100. + Percentage *float64 `form:"percentage"` + // [ISO 3166-2 subdivision code](https://en.wikipedia.org/wiki/ISO_3166-2), without country prefix. For example, "NY" for New York, United States. + State *string `form:"state"` + // The high-level tax type, such as `vat` or `sales_tax`. + TaxType *string `form:"tax_type"` +} + +// AddExpand appends a new field to expand. +func (p *TaxRateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TaxRateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Creates a new tax rate. +type TaxRateCreateParams struct { + Params `form:"*"` + // Flag determining whether the tax rate is active or inactive (archived). Inactive tax rates cannot be used with new applications or Checkout Sessions, but will still work for subscriptions and invoices that already have it set. + Active *bool `form:"active"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // An arbitrary string attached to the tax rate for your internal use only. It will not be visible to your customers. + Description *string `form:"description"` + // The display name of the tax rate, which will be shown to users. + DisplayName *string `form:"display_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // This specifies if the tax rate is inclusive or exclusive. + Inclusive *bool `form:"inclusive"` + // The jurisdiction for the tax rate. You can use this label field for tax reporting purposes. It also appears on your customer's invoice. + Jurisdiction *string `form:"jurisdiction"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // This represents the tax rate percent out of 100. + Percentage *float64 `form:"percentage"` + // [ISO 3166-2 subdivision code](https://en.wikipedia.org/wiki/ISO_3166-2), without country prefix. For example, "NY" for New York, United States. + State *string `form:"state"` + // The high-level tax type, such as `vat` or `sales_tax`. + TaxType *string `form:"tax_type"` +} + +// AddExpand appends a new field to expand. +func (p *TaxRateCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TaxRateCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves a tax rate with the given ID +type TaxRateRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TaxRateRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates an existing tax rate. +type TaxRateUpdateParams struct { + Params `form:"*"` + // Flag determining whether the tax rate is active or inactive (archived). Inactive tax rates cannot be used with new applications or Checkout Sessions, but will still work for subscriptions and invoices that already have it set. + Active *bool `form:"active"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country *string `form:"country"` + // An arbitrary string attached to the tax rate for your internal use only. It will not be visible to your customers. + Description *string `form:"description"` + // The display name of the tax rate, which will be shown to users. + DisplayName *string `form:"display_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The jurisdiction for the tax rate. You can use this label field for tax reporting purposes. It also appears on your customer's invoice. + Jurisdiction *string `form:"jurisdiction"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // [ISO 3166-2 subdivision code](https://en.wikipedia.org/wiki/ISO_3166-2), without country prefix. For example, "NY" for New York, United States. + State *string `form:"state"` + // The high-level tax type, such as `vat` or `sales_tax`. + TaxType *string `form:"tax_type"` +} + +// AddExpand appends a new field to expand. +func (p *TaxRateUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TaxRateUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The amount of the tax rate when the `rate_type` is `flat_amount`. Tax rates with `rate_type` `percentage` can vary based on the transaction, resulting in this field being `null`. This field exposes the amount and currency of the flat tax rate. +type TaxRateFlatAmount struct { + // Amount of the tax when the `rate_type` is `flat_amount`. This positive integer represents how much to charge in the smallest currency unit (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + Amount int64 `json:"amount"` + // Three-letter ISO currency code, in lowercase. + Currency Currency `json:"currency"` +} + +// Tax rates can be applied to [invoices](https://docs.stripe.com/invoicing/taxes/tax-rates), [subscriptions](https://docs.stripe.com/billing/taxes/tax-rates) and [Checkout Sessions](https://docs.stripe.com/payments/checkout/use-manual-tax-rates) to collect tax. +// +// Related guide: [Tax rates](https://docs.stripe.com/billing/taxes/tax-rates) +type TaxRate struct { + APIResource + // Defaults to `true`. When set to `false`, this tax rate cannot be used with new applications or Checkout Sessions, but will still work for subscriptions and invoices that already have it set. + Active bool `json:"active"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country string `json:"country"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // An arbitrary string attached to the tax rate for your internal use only. It will not be visible to your customers. + Description string `json:"description"` + // The display name of the tax rates as it will appear to your customer on their receipt email, PDF, and the hosted invoice page. + DisplayName string `json:"display_name"` + // Actual/effective tax rate percentage out of 100. For tax calculations with automatic_tax[enabled]=true, + // this percentage reflects the rate actually used to calculate tax based on the product's taxability + // and whether the user is registered to collect taxes in the corresponding jurisdiction. + EffectivePercentage float64 `json:"effective_percentage"` + // The amount of the tax rate when the `rate_type` is `flat_amount`. Tax rates with `rate_type` `percentage` can vary based on the transaction, resulting in this field being `null`. This field exposes the amount and currency of the flat tax rate. + FlatAmount *TaxRateFlatAmount `json:"flat_amount"` + // Unique identifier for the object. + ID string `json:"id"` + // This specifies if the tax rate is inclusive or exclusive. + Inclusive bool `json:"inclusive"` + // The jurisdiction for the tax rate. You can use this label field for tax reporting purposes. It also appears on your customer's invoice. + Jurisdiction string `json:"jurisdiction"` + // The level of the jurisdiction that imposes this tax rate. Will be `null` for manually defined tax rates. + JurisdictionLevel TaxRateJurisdictionLevel `json:"jurisdiction_level"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Tax rate percentage out of 100. For tax calculations with automatic_tax[enabled]=true, this percentage includes the statutory tax rate of non-taxable jurisdictions. + Percentage float64 `json:"percentage"` + // Indicates the type of tax rate applied to the taxable amount. This value can be `null` when no tax applies to the location. This field is only present for TaxRates created by Stripe Tax. + RateType TaxRateRateType `json:"rate_type"` + // [ISO 3166-2 subdivision code](https://en.wikipedia.org/wiki/ISO_3166-2), without country prefix. For example, "NY" for New York, United States. + State string `json:"state"` + // The high-level tax type, such as `vat` or `sales_tax`. + TaxType TaxRateTaxType `json:"tax_type"` +} + +// TaxRateList is a list of TaxRates as retrieved from a list endpoint. +type TaxRateList struct { + APIResource + ListMeta + Data []*TaxRate `json:"data"` +} + +// UnmarshalJSON handles deserialization of a TaxRate. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (t *TaxRate) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + t.ID = id + return nil + } + + type taxRate TaxRate + var v taxRate + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *t = TaxRate(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/taxrate_service.go b/vendor/github.com/stripe/stripe-go/v82/taxrate_service.go new file mode 100644 index 00000000..c837ae4f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/taxrate_service.go @@ -0,0 +1,72 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TaxRateService is used to invoke /v1/tax_rates APIs. +type v1TaxRateService struct { + B Backend + Key string +} + +// Creates a new tax rate. +func (c v1TaxRateService) Create(ctx context.Context, params *TaxRateCreateParams) (*TaxRate, error) { + if params == nil { + params = &TaxRateCreateParams{} + } + params.Context = ctx + taxrate := &TaxRate{} + err := c.B.Call(http.MethodPost, "/v1/tax_rates", c.Key, params, taxrate) + return taxrate, err +} + +// Retrieves a tax rate with the given ID +func (c v1TaxRateService) Retrieve(ctx context.Context, id string, params *TaxRateRetrieveParams) (*TaxRate, error) { + if params == nil { + params = &TaxRateRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/tax_rates/%s", id) + taxrate := &TaxRate{} + err := c.B.Call(http.MethodGet, path, c.Key, params, taxrate) + return taxrate, err +} + +// Updates an existing tax rate. +func (c v1TaxRateService) Update(ctx context.Context, id string, params *TaxRateUpdateParams) (*TaxRate, error) { + if params == nil { + params = &TaxRateUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/tax_rates/%s", id) + taxrate := &TaxRate{} + err := c.B.Call(http.MethodPost, path, c.Key, params, taxrate) + return taxrate, err +} + +// Returns a list of your tax rates. Tax rates are returned sorted by creation date, with the most recently created tax rates appearing first. +func (c v1TaxRateService) List(ctx context.Context, listParams *TaxRateListParams) Seq2[*TaxRate, error] { + if listParams == nil { + listParams = &TaxRateListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TaxRate, ListContainer, error) { + list := &TaxRateList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/tax_rates", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/terminal_configuration.go b/vendor/github.com/stripe/stripe-go/v82/terminal_configuration.go new file mode 100644 index 00000000..cdf22aee --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/terminal_configuration.go @@ -0,0 +1,1189 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Security type of the WiFi network. The hash with the corresponding name contains the credentials for this security type. +type TerminalConfigurationWifiType string + +// List of values that TerminalConfigurationWifiType can take +const ( + TerminalConfigurationWifiTypeEnterpriseEapPeap TerminalConfigurationWifiType = "enterprise_eap_peap" + TerminalConfigurationWifiTypeEnterpriseEapTLS TerminalConfigurationWifiType = "enterprise_eap_tls" + TerminalConfigurationWifiTypePersonalPsk TerminalConfigurationWifiType = "personal_psk" +) + +// Deletes a Configuration object. +type TerminalConfigurationParams struct { + Params `form:"*"` + // An object containing device type specific settings for BBPOS WisePOS E readers + BBPOSWisePOSE *TerminalConfigurationBBPOSWisePOSEParams `form:"bbpos_wisepos_e"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Name of the configuration + Name *string `form:"name"` + // Configurations for collecting transactions offline. + Offline *TerminalConfigurationOfflineParams `form:"offline"` + // Reboot time settings for readers that support customized reboot time configuration. + RebootWindow *TerminalConfigurationRebootWindowParams `form:"reboot_window"` + // An object containing device type specific settings for Stripe S700 readers + StripeS700 *TerminalConfigurationStripeS700Params `form:"stripe_s700"` + // Tipping configurations for readers supporting on-reader tips + Tipping *TerminalConfigurationTippingParams `form:"tipping"` + // An object containing device type specific settings for Verifone P400 readers + VerifoneP400 *TerminalConfigurationVerifoneP400Params `form:"verifone_p400"` + // Configurations for connecting to a WiFi network. + Wifi *TerminalConfigurationWifiParams `form:"wifi"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalConfigurationParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// An object containing device type specific settings for BBPOS WisePOS E readers +type TerminalConfigurationBBPOSWisePOSEParams struct { + // A File ID representing an image to display on the reader + Splashscreen *string `form:"splashscreen"` +} + +// Configurations for collecting transactions offline. +type TerminalConfigurationOfflineParams struct { + // Determines whether to allow transactions to be collected while reader is offline. Defaults to false. + Enabled *bool `form:"enabled"` +} + +// Reboot time settings for readers that support customized reboot time configuration. +type TerminalConfigurationRebootWindowParams struct { + // Integer between 0 to 23 that represents the end hour of the reboot time window. The value must be different than the start_hour. + EndHour *int64 `form:"end_hour"` + // Integer between 0 to 23 that represents the start hour of the reboot time window. + StartHour *int64 `form:"start_hour"` +} + +// An object containing device type specific settings for Stripe S700 readers +type TerminalConfigurationStripeS700Params struct { + // A File ID representing an image you would like displayed on the reader. + Splashscreen *string `form:"splashscreen"` +} + +// Tipping configuration for AUD +type TerminalConfigurationTippingAUDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for CAD +type TerminalConfigurationTippingCADParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for CHF +type TerminalConfigurationTippingCHFParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for CZK +type TerminalConfigurationTippingCZKParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for DKK +type TerminalConfigurationTippingDKKParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for EUR +type TerminalConfigurationTippingEURParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for GBP +type TerminalConfigurationTippingGBPParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for HKD +type TerminalConfigurationTippingHKDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for JPY +type TerminalConfigurationTippingJPYParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for MYR +type TerminalConfigurationTippingMYRParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for NOK +type TerminalConfigurationTippingNOKParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for NZD +type TerminalConfigurationTippingNZDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for PLN +type TerminalConfigurationTippingPLNParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for SEK +type TerminalConfigurationTippingSEKParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for SGD +type TerminalConfigurationTippingSGDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for USD +type TerminalConfigurationTippingUSDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configurations for readers supporting on-reader tips +type TerminalConfigurationTippingParams struct { + // Tipping configuration for AUD + AUD *TerminalConfigurationTippingAUDParams `form:"aud"` + // Tipping configuration for CAD + CAD *TerminalConfigurationTippingCADParams `form:"cad"` + // Tipping configuration for CHF + CHF *TerminalConfigurationTippingCHFParams `form:"chf"` + // Tipping configuration for CZK + CZK *TerminalConfigurationTippingCZKParams `form:"czk"` + // Tipping configuration for DKK + DKK *TerminalConfigurationTippingDKKParams `form:"dkk"` + // Tipping configuration for EUR + EUR *TerminalConfigurationTippingEURParams `form:"eur"` + // Tipping configuration for GBP + GBP *TerminalConfigurationTippingGBPParams `form:"gbp"` + // Tipping configuration for HKD + HKD *TerminalConfigurationTippingHKDParams `form:"hkd"` + // Tipping configuration for JPY + JPY *TerminalConfigurationTippingJPYParams `form:"jpy"` + // Tipping configuration for MYR + MYR *TerminalConfigurationTippingMYRParams `form:"myr"` + // Tipping configuration for NOK + NOK *TerminalConfigurationTippingNOKParams `form:"nok"` + // Tipping configuration for NZD + NZD *TerminalConfigurationTippingNZDParams `form:"nzd"` + // Tipping configuration for PLN + PLN *TerminalConfigurationTippingPLNParams `form:"pln"` + // Tipping configuration for SEK + SEK *TerminalConfigurationTippingSEKParams `form:"sek"` + // Tipping configuration for SGD + SGD *TerminalConfigurationTippingSGDParams `form:"sgd"` + // Tipping configuration for USD + USD *TerminalConfigurationTippingUSDParams `form:"usd"` +} + +// An object containing device type specific settings for Verifone P400 readers +type TerminalConfigurationVerifoneP400Params struct { + // A File ID representing an image you would like displayed on the reader. + Splashscreen *string `form:"splashscreen"` +} + +// Credentials for a WPA-Enterprise WiFi network using the EAP-PEAP authentication method. +type TerminalConfigurationWifiEnterpriseEapPeapParams struct { + // A File ID representing a PEM file containing the server certificate + CaCertificateFile *string `form:"ca_certificate_file"` + // Password for connecting to the WiFi network + Password *string `form:"password"` + // Name of the WiFi network + Ssid *string `form:"ssid"` + // Username for connecting to the WiFi network + Username *string `form:"username"` +} + +// Credentials for a WPA-Enterprise WiFi network using the EAP-TLS authentication method. +type TerminalConfigurationWifiEnterpriseEapTLSParams struct { + // A File ID representing a PEM file containing the server certificate + CaCertificateFile *string `form:"ca_certificate_file"` + // A File ID representing a PEM file containing the client certificate + ClientCertificateFile *string `form:"client_certificate_file"` + // A File ID representing a PEM file containing the client RSA private key + PrivateKeyFile *string `form:"private_key_file"` + // Password for the private key file + PrivateKeyFilePassword *string `form:"private_key_file_password"` + // Name of the WiFi network + Ssid *string `form:"ssid"` +} + +// Credentials for a WPA-Personal WiFi network. +type TerminalConfigurationWifiPersonalPskParams struct { + // Password for connecting to the WiFi network + Password *string `form:"password"` + // Name of the WiFi network + Ssid *string `form:"ssid"` +} + +// Configurations for connecting to a WiFi network. +type TerminalConfigurationWifiParams struct { + // Credentials for a WPA-Enterprise WiFi network using the EAP-PEAP authentication method. + EnterpriseEapPeap *TerminalConfigurationWifiEnterpriseEapPeapParams `form:"enterprise_eap_peap"` + // Credentials for a WPA-Enterprise WiFi network using the EAP-TLS authentication method. + EnterpriseEapTLS *TerminalConfigurationWifiEnterpriseEapTLSParams `form:"enterprise_eap_tls"` + // Credentials for a WPA-Personal WiFi network. + PersonalPsk *TerminalConfigurationWifiPersonalPskParams `form:"personal_psk"` + // Security type of the WiFi network. Fill out the hash with the corresponding name to provide the set of credentials for this security type. + Type *string `form:"type"` +} + +// Returns a list of Configuration objects. +type TerminalConfigurationListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // if present, only return the account default or non-default configurations. + IsAccountDefault *bool `form:"is_account_default"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalConfigurationListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Deletes a Configuration object. +type TerminalConfigurationDeleteParams struct { + Params `form:"*"` +} + +// Retrieves a Configuration object. +type TerminalConfigurationRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalConfigurationRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// An object containing device type specific settings for BBPOS WisePOS E readers +type TerminalConfigurationUpdateBBPOSWisePOSEParams struct { + // A File ID representing an image to display on the reader + Splashscreen *string `form:"splashscreen"` +} + +// Configurations for collecting transactions offline. +type TerminalConfigurationUpdateOfflineParams struct { + // Determines whether to allow transactions to be collected while reader is offline. Defaults to false. + Enabled *bool `form:"enabled"` +} + +// Reboot time settings for readers that support customized reboot time configuration. +type TerminalConfigurationUpdateRebootWindowParams struct { + // Integer between 0 to 23 that represents the end hour of the reboot time window. The value must be different than the start_hour. + EndHour *int64 `form:"end_hour"` + // Integer between 0 to 23 that represents the start hour of the reboot time window. + StartHour *int64 `form:"start_hour"` +} + +// An object containing device type specific settings for Stripe S700 readers +type TerminalConfigurationUpdateStripeS700Params struct { + // A File ID representing an image you would like displayed on the reader. + Splashscreen *string `form:"splashscreen"` +} + +// Tipping configuration for AUD +type TerminalConfigurationUpdateTippingAUDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for CAD +type TerminalConfigurationUpdateTippingCADParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for CHF +type TerminalConfigurationUpdateTippingCHFParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for CZK +type TerminalConfigurationUpdateTippingCZKParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for DKK +type TerminalConfigurationUpdateTippingDKKParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for EUR +type TerminalConfigurationUpdateTippingEURParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for GBP +type TerminalConfigurationUpdateTippingGBPParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for HKD +type TerminalConfigurationUpdateTippingHKDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for JPY +type TerminalConfigurationUpdateTippingJPYParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for MYR +type TerminalConfigurationUpdateTippingMYRParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for NOK +type TerminalConfigurationUpdateTippingNOKParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for NZD +type TerminalConfigurationUpdateTippingNZDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for PLN +type TerminalConfigurationUpdateTippingPLNParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for SEK +type TerminalConfigurationUpdateTippingSEKParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for SGD +type TerminalConfigurationUpdateTippingSGDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for USD +type TerminalConfigurationUpdateTippingUSDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configurations for readers supporting on-reader tips +type TerminalConfigurationUpdateTippingParams struct { + // Tipping configuration for AUD + AUD *TerminalConfigurationUpdateTippingAUDParams `form:"aud"` + // Tipping configuration for CAD + CAD *TerminalConfigurationUpdateTippingCADParams `form:"cad"` + // Tipping configuration for CHF + CHF *TerminalConfigurationUpdateTippingCHFParams `form:"chf"` + // Tipping configuration for CZK + CZK *TerminalConfigurationUpdateTippingCZKParams `form:"czk"` + // Tipping configuration for DKK + DKK *TerminalConfigurationUpdateTippingDKKParams `form:"dkk"` + // Tipping configuration for EUR + EUR *TerminalConfigurationUpdateTippingEURParams `form:"eur"` + // Tipping configuration for GBP + GBP *TerminalConfigurationUpdateTippingGBPParams `form:"gbp"` + // Tipping configuration for HKD + HKD *TerminalConfigurationUpdateTippingHKDParams `form:"hkd"` + // Tipping configuration for JPY + JPY *TerminalConfigurationUpdateTippingJPYParams `form:"jpy"` + // Tipping configuration for MYR + MYR *TerminalConfigurationUpdateTippingMYRParams `form:"myr"` + // Tipping configuration for NOK + NOK *TerminalConfigurationUpdateTippingNOKParams `form:"nok"` + // Tipping configuration for NZD + NZD *TerminalConfigurationUpdateTippingNZDParams `form:"nzd"` + // Tipping configuration for PLN + PLN *TerminalConfigurationUpdateTippingPLNParams `form:"pln"` + // Tipping configuration for SEK + SEK *TerminalConfigurationUpdateTippingSEKParams `form:"sek"` + // Tipping configuration for SGD + SGD *TerminalConfigurationUpdateTippingSGDParams `form:"sgd"` + // Tipping configuration for USD + USD *TerminalConfigurationUpdateTippingUSDParams `form:"usd"` +} + +// An object containing device type specific settings for Verifone P400 readers +type TerminalConfigurationUpdateVerifoneP400Params struct { + // A File ID representing an image you would like displayed on the reader. + Splashscreen *string `form:"splashscreen"` +} + +// Credentials for a WPA-Enterprise WiFi network using the EAP-PEAP authentication method. +type TerminalConfigurationUpdateWifiEnterpriseEapPeapParams struct { + // A File ID representing a PEM file containing the server certificate + CaCertificateFile *string `form:"ca_certificate_file"` + // Password for connecting to the WiFi network + Password *string `form:"password"` + // Name of the WiFi network + Ssid *string `form:"ssid"` + // Username for connecting to the WiFi network + Username *string `form:"username"` +} + +// Credentials for a WPA-Enterprise WiFi network using the EAP-TLS authentication method. +type TerminalConfigurationUpdateWifiEnterpriseEapTLSParams struct { + // A File ID representing a PEM file containing the server certificate + CaCertificateFile *string `form:"ca_certificate_file"` + // A File ID representing a PEM file containing the client certificate + ClientCertificateFile *string `form:"client_certificate_file"` + // A File ID representing a PEM file containing the client RSA private key + PrivateKeyFile *string `form:"private_key_file"` + // Password for the private key file + PrivateKeyFilePassword *string `form:"private_key_file_password"` + // Name of the WiFi network + Ssid *string `form:"ssid"` +} + +// Credentials for a WPA-Personal WiFi network. +type TerminalConfigurationUpdateWifiPersonalPskParams struct { + // Password for connecting to the WiFi network + Password *string `form:"password"` + // Name of the WiFi network + Ssid *string `form:"ssid"` +} + +// Configurations for connecting to a WiFi network. +type TerminalConfigurationUpdateWifiParams struct { + // Credentials for a WPA-Enterprise WiFi network using the EAP-PEAP authentication method. + EnterpriseEapPeap *TerminalConfigurationUpdateWifiEnterpriseEapPeapParams `form:"enterprise_eap_peap"` + // Credentials for a WPA-Enterprise WiFi network using the EAP-TLS authentication method. + EnterpriseEapTLS *TerminalConfigurationUpdateWifiEnterpriseEapTLSParams `form:"enterprise_eap_tls"` + // Credentials for a WPA-Personal WiFi network. + PersonalPsk *TerminalConfigurationUpdateWifiPersonalPskParams `form:"personal_psk"` + // Security type of the WiFi network. Fill out the hash with the corresponding name to provide the set of credentials for this security type. + Type *string `form:"type"` +} + +// Updates a new Configuration object. +type TerminalConfigurationUpdateParams struct { + Params `form:"*"` + // An object containing device type specific settings for BBPOS WisePOS E readers + BBPOSWisePOSE *TerminalConfigurationUpdateBBPOSWisePOSEParams `form:"bbpos_wisepos_e"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Name of the configuration + Name *string `form:"name"` + // Configurations for collecting transactions offline. + Offline *TerminalConfigurationUpdateOfflineParams `form:"offline"` + // Reboot time settings for readers that support customized reboot time configuration. + RebootWindow *TerminalConfigurationUpdateRebootWindowParams `form:"reboot_window"` + // An object containing device type specific settings for Stripe S700 readers + StripeS700 *TerminalConfigurationUpdateStripeS700Params `form:"stripe_s700"` + // Tipping configurations for readers supporting on-reader tips + Tipping *TerminalConfigurationUpdateTippingParams `form:"tipping"` + // An object containing device type specific settings for Verifone P400 readers + VerifoneP400 *TerminalConfigurationUpdateVerifoneP400Params `form:"verifone_p400"` + // Configurations for connecting to a WiFi network. + Wifi *TerminalConfigurationUpdateWifiParams `form:"wifi"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalConfigurationUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// An object containing device type specific settings for BBPOS WisePOS E readers +type TerminalConfigurationCreateBBPOSWisePOSEParams struct { + // A File ID representing an image to display on the reader + Splashscreen *string `form:"splashscreen"` +} + +// Configurations for collecting transactions offline. +type TerminalConfigurationCreateOfflineParams struct { + // Determines whether to allow transactions to be collected while reader is offline. Defaults to false. + Enabled *bool `form:"enabled"` +} + +// Reboot time settings for readers that support customized reboot time configuration. +type TerminalConfigurationCreateRebootWindowParams struct { + // Integer between 0 to 23 that represents the end hour of the reboot time window. The value must be different than the start_hour. + EndHour *int64 `form:"end_hour"` + // Integer between 0 to 23 that represents the start hour of the reboot time window. + StartHour *int64 `form:"start_hour"` +} + +// An object containing device type specific settings for Stripe S700 readers +type TerminalConfigurationCreateStripeS700Params struct { + // A File ID representing an image you would like displayed on the reader. + Splashscreen *string `form:"splashscreen"` +} + +// Tipping configuration for AUD +type TerminalConfigurationCreateTippingAUDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for CAD +type TerminalConfigurationCreateTippingCADParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for CHF +type TerminalConfigurationCreateTippingCHFParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for CZK +type TerminalConfigurationCreateTippingCZKParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for DKK +type TerminalConfigurationCreateTippingDKKParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for EUR +type TerminalConfigurationCreateTippingEURParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for GBP +type TerminalConfigurationCreateTippingGBPParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for HKD +type TerminalConfigurationCreateTippingHKDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for JPY +type TerminalConfigurationCreateTippingJPYParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for MYR +type TerminalConfigurationCreateTippingMYRParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for NOK +type TerminalConfigurationCreateTippingNOKParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for NZD +type TerminalConfigurationCreateTippingNZDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for PLN +type TerminalConfigurationCreateTippingPLNParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for SEK +type TerminalConfigurationCreateTippingSEKParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for SGD +type TerminalConfigurationCreateTippingSGDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configuration for USD +type TerminalConfigurationCreateTippingUSDParams struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []*int64 `form:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []*int64 `form:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold *int64 `form:"smart_tip_threshold"` +} + +// Tipping configurations for readers supporting on-reader tips +type TerminalConfigurationCreateTippingParams struct { + // Tipping configuration for AUD + AUD *TerminalConfigurationCreateTippingAUDParams `form:"aud"` + // Tipping configuration for CAD + CAD *TerminalConfigurationCreateTippingCADParams `form:"cad"` + // Tipping configuration for CHF + CHF *TerminalConfigurationCreateTippingCHFParams `form:"chf"` + // Tipping configuration for CZK + CZK *TerminalConfigurationCreateTippingCZKParams `form:"czk"` + // Tipping configuration for DKK + DKK *TerminalConfigurationCreateTippingDKKParams `form:"dkk"` + // Tipping configuration for EUR + EUR *TerminalConfigurationCreateTippingEURParams `form:"eur"` + // Tipping configuration for GBP + GBP *TerminalConfigurationCreateTippingGBPParams `form:"gbp"` + // Tipping configuration for HKD + HKD *TerminalConfigurationCreateTippingHKDParams `form:"hkd"` + // Tipping configuration for JPY + JPY *TerminalConfigurationCreateTippingJPYParams `form:"jpy"` + // Tipping configuration for MYR + MYR *TerminalConfigurationCreateTippingMYRParams `form:"myr"` + // Tipping configuration for NOK + NOK *TerminalConfigurationCreateTippingNOKParams `form:"nok"` + // Tipping configuration for NZD + NZD *TerminalConfigurationCreateTippingNZDParams `form:"nzd"` + // Tipping configuration for PLN + PLN *TerminalConfigurationCreateTippingPLNParams `form:"pln"` + // Tipping configuration for SEK + SEK *TerminalConfigurationCreateTippingSEKParams `form:"sek"` + // Tipping configuration for SGD + SGD *TerminalConfigurationCreateTippingSGDParams `form:"sgd"` + // Tipping configuration for USD + USD *TerminalConfigurationCreateTippingUSDParams `form:"usd"` +} + +// An object containing device type specific settings for Verifone P400 readers +type TerminalConfigurationCreateVerifoneP400Params struct { + // A File ID representing an image you would like displayed on the reader. + Splashscreen *string `form:"splashscreen"` +} + +// Credentials for a WPA-Enterprise WiFi network using the EAP-PEAP authentication method. +type TerminalConfigurationCreateWifiEnterpriseEapPeapParams struct { + // A File ID representing a PEM file containing the server certificate + CaCertificateFile *string `form:"ca_certificate_file"` + // Password for connecting to the WiFi network + Password *string `form:"password"` + // Name of the WiFi network + Ssid *string `form:"ssid"` + // Username for connecting to the WiFi network + Username *string `form:"username"` +} + +// Credentials for a WPA-Enterprise WiFi network using the EAP-TLS authentication method. +type TerminalConfigurationCreateWifiEnterpriseEapTLSParams struct { + // A File ID representing a PEM file containing the server certificate + CaCertificateFile *string `form:"ca_certificate_file"` + // A File ID representing a PEM file containing the client certificate + ClientCertificateFile *string `form:"client_certificate_file"` + // A File ID representing a PEM file containing the client RSA private key + PrivateKeyFile *string `form:"private_key_file"` + // Password for the private key file + PrivateKeyFilePassword *string `form:"private_key_file_password"` + // Name of the WiFi network + Ssid *string `form:"ssid"` +} + +// Credentials for a WPA-Personal WiFi network. +type TerminalConfigurationCreateWifiPersonalPskParams struct { + // Password for connecting to the WiFi network + Password *string `form:"password"` + // Name of the WiFi network + Ssid *string `form:"ssid"` +} + +// Configurations for connecting to a WiFi network. +type TerminalConfigurationCreateWifiParams struct { + // Credentials for a WPA-Enterprise WiFi network using the EAP-PEAP authentication method. + EnterpriseEapPeap *TerminalConfigurationCreateWifiEnterpriseEapPeapParams `form:"enterprise_eap_peap"` + // Credentials for a WPA-Enterprise WiFi network using the EAP-TLS authentication method. + EnterpriseEapTLS *TerminalConfigurationCreateWifiEnterpriseEapTLSParams `form:"enterprise_eap_tls"` + // Credentials for a WPA-Personal WiFi network. + PersonalPsk *TerminalConfigurationCreateWifiPersonalPskParams `form:"personal_psk"` + // Security type of the WiFi network. Fill out the hash with the corresponding name to provide the set of credentials for this security type. + Type *string `form:"type"` +} + +// Creates a new Configuration object. +type TerminalConfigurationCreateParams struct { + Params `form:"*"` + // An object containing device type specific settings for BBPOS WisePOS E readers + BBPOSWisePOSE *TerminalConfigurationCreateBBPOSWisePOSEParams `form:"bbpos_wisepos_e"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Name of the configuration + Name *string `form:"name"` + // Configurations for collecting transactions offline. + Offline *TerminalConfigurationCreateOfflineParams `form:"offline"` + // Reboot time settings for readers that support customized reboot time configuration. + RebootWindow *TerminalConfigurationCreateRebootWindowParams `form:"reboot_window"` + // An object containing device type specific settings for Stripe S700 readers + StripeS700 *TerminalConfigurationCreateStripeS700Params `form:"stripe_s700"` + // Tipping configurations for readers supporting on-reader tips + Tipping *TerminalConfigurationCreateTippingParams `form:"tipping"` + // An object containing device type specific settings for Verifone P400 readers + VerifoneP400 *TerminalConfigurationCreateVerifoneP400Params `form:"verifone_p400"` + // Configurations for connecting to a WiFi network. + Wifi *TerminalConfigurationCreateWifiParams `form:"wifi"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalConfigurationCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type TerminalConfigurationBBPOSWisePOSE struct { + // A File ID representing an image to display on the reader + Splashscreen *File `json:"splashscreen"` +} +type TerminalConfigurationOffline struct { + // Determines whether to allow transactions to be collected while reader is offline. Defaults to false. + Enabled bool `json:"enabled"` +} +type TerminalConfigurationRebootWindow struct { + // Integer between 0 to 23 that represents the end hour of the reboot time window. The value must be different than the start_hour. + EndHour int64 `json:"end_hour"` + // Integer between 0 to 23 that represents the start hour of the reboot time window. + StartHour int64 `json:"start_hour"` +} +type TerminalConfigurationStripeS700 struct { + // A File ID representing an image to display on the reader + Splashscreen *File `json:"splashscreen"` +} +type TerminalConfigurationTippingAUD struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingCAD struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingCHF struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingCZK struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingDKK struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingEUR struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingGBP struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingHKD struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingJPY struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingMYR struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingNOK struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingNZD struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingPLN struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingSEK struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingSGD struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTippingUSD struct { + // Fixed amounts displayed when collecting a tip + FixedAmounts []int64 `json:"fixed_amounts"` + // Percentages displayed when collecting a tip + Percentages []int64 `json:"percentages"` + // Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + SmartTipThreshold int64 `json:"smart_tip_threshold"` +} +type TerminalConfigurationTipping struct { + AUD *TerminalConfigurationTippingAUD `json:"aud"` + CAD *TerminalConfigurationTippingCAD `json:"cad"` + CHF *TerminalConfigurationTippingCHF `json:"chf"` + CZK *TerminalConfigurationTippingCZK `json:"czk"` + DKK *TerminalConfigurationTippingDKK `json:"dkk"` + EUR *TerminalConfigurationTippingEUR `json:"eur"` + GBP *TerminalConfigurationTippingGBP `json:"gbp"` + HKD *TerminalConfigurationTippingHKD `json:"hkd"` + JPY *TerminalConfigurationTippingJPY `json:"jpy"` + MYR *TerminalConfigurationTippingMYR `json:"myr"` + NOK *TerminalConfigurationTippingNOK `json:"nok"` + NZD *TerminalConfigurationTippingNZD `json:"nzd"` + PLN *TerminalConfigurationTippingPLN `json:"pln"` + SEK *TerminalConfigurationTippingSEK `json:"sek"` + SGD *TerminalConfigurationTippingSGD `json:"sgd"` + USD *TerminalConfigurationTippingUSD `json:"usd"` +} +type TerminalConfigurationVerifoneP400 struct { + // A File ID representing an image to display on the reader + Splashscreen *File `json:"splashscreen"` +} +type TerminalConfigurationWifiEnterpriseEapPeap struct { + // A File ID representing a PEM file containing the server certificate + CaCertificateFile string `json:"ca_certificate_file"` + // Password for connecting to the WiFi network + Password string `json:"password"` + // Name of the WiFi network + Ssid string `json:"ssid"` + // Username for connecting to the WiFi network + Username string `json:"username"` +} +type TerminalConfigurationWifiEnterpriseEapTLS struct { + // A File ID representing a PEM file containing the server certificate + CaCertificateFile string `json:"ca_certificate_file"` + // A File ID representing a PEM file containing the client certificate + ClientCertificateFile string `json:"client_certificate_file"` + // A File ID representing a PEM file containing the client RSA private key + PrivateKeyFile string `json:"private_key_file"` + // Password for the private key file + PrivateKeyFilePassword string `json:"private_key_file_password"` + // Name of the WiFi network + Ssid string `json:"ssid"` +} +type TerminalConfigurationWifiPersonalPsk struct { + // Password for connecting to the WiFi network + Password string `json:"password"` + // Name of the WiFi network + Ssid string `json:"ssid"` +} +type TerminalConfigurationWifi struct { + EnterpriseEapPeap *TerminalConfigurationWifiEnterpriseEapPeap `json:"enterprise_eap_peap"` + EnterpriseEapTLS *TerminalConfigurationWifiEnterpriseEapTLS `json:"enterprise_eap_tls"` + PersonalPsk *TerminalConfigurationWifiPersonalPsk `json:"personal_psk"` + // Security type of the WiFi network. The hash with the corresponding name contains the credentials for this security type. + Type TerminalConfigurationWifiType `json:"type"` +} + +// A Configurations object represents how features should be configured for terminal readers. +// For information about how to use it, see the [Terminal configurations documentation](https://docs.stripe.com/terminal/fleet/configurations-overview). +type TerminalConfiguration struct { + APIResource + BBPOSWisePOSE *TerminalConfigurationBBPOSWisePOSE `json:"bbpos_wisepos_e"` + Deleted bool `json:"deleted"` + // Unique identifier for the object. + ID string `json:"id"` + // Whether this Configuration is the default for your account + IsAccountDefault bool `json:"is_account_default"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String indicating the name of the Configuration object, set by the user + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + Offline *TerminalConfigurationOffline `json:"offline"` + RebootWindow *TerminalConfigurationRebootWindow `json:"reboot_window"` + StripeS700 *TerminalConfigurationStripeS700 `json:"stripe_s700"` + Tipping *TerminalConfigurationTipping `json:"tipping"` + VerifoneP400 *TerminalConfigurationVerifoneP400 `json:"verifone_p400"` + Wifi *TerminalConfigurationWifi `json:"wifi"` +} + +// TerminalConfigurationList is a list of Configurations as retrieved from a list endpoint. +type TerminalConfigurationList struct { + APIResource + ListMeta + Data []*TerminalConfiguration `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/terminal_configuration_service.go b/vendor/github.com/stripe/stripe-go/v82/terminal_configuration_service.go new file mode 100644 index 00000000..81cf89ea --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/terminal_configuration_service.go @@ -0,0 +1,85 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TerminalConfigurationService is used to invoke /v1/terminal/configurations APIs. +type v1TerminalConfigurationService struct { + B Backend + Key string +} + +// Creates a new Configuration object. +func (c v1TerminalConfigurationService) Create(ctx context.Context, params *TerminalConfigurationCreateParams) (*TerminalConfiguration, error) { + if params == nil { + params = &TerminalConfigurationCreateParams{} + } + params.Context = ctx + configuration := &TerminalConfiguration{} + err := c.B.Call( + http.MethodPost, "/v1/terminal/configurations", c.Key, params, configuration) + return configuration, err +} + +// Retrieves a Configuration object. +func (c v1TerminalConfigurationService) Retrieve(ctx context.Context, id string, params *TerminalConfigurationRetrieveParams) (*TerminalConfiguration, error) { + if params == nil { + params = &TerminalConfigurationRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/configurations/%s", id) + configuration := &TerminalConfiguration{} + err := c.B.Call(http.MethodGet, path, c.Key, params, configuration) + return configuration, err +} + +// Updates a new Configuration object. +func (c v1TerminalConfigurationService) Update(ctx context.Context, id string, params *TerminalConfigurationUpdateParams) (*TerminalConfiguration, error) { + if params == nil { + params = &TerminalConfigurationUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/configurations/%s", id) + configuration := &TerminalConfiguration{} + err := c.B.Call(http.MethodPost, path, c.Key, params, configuration) + return configuration, err +} + +// Deletes a Configuration object. +func (c v1TerminalConfigurationService) Delete(ctx context.Context, id string, params *TerminalConfigurationDeleteParams) (*TerminalConfiguration, error) { + if params == nil { + params = &TerminalConfigurationDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/configurations/%s", id) + configuration := &TerminalConfiguration{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, configuration) + return configuration, err +} + +// Returns a list of Configuration objects. +func (c v1TerminalConfigurationService) List(ctx context.Context, listParams *TerminalConfigurationListParams) Seq2[*TerminalConfiguration, error] { + if listParams == nil { + listParams = &TerminalConfigurationListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TerminalConfiguration, ListContainer, error) { + list := &TerminalConfigurationList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/terminal/configurations", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/terminal_connectiontoken.go b/vendor/github.com/stripe/stripe-go/v82/terminal_connectiontoken.go new file mode 100644 index 00000000..1baf252a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/terminal_connectiontoken.go @@ -0,0 +1,48 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// To connect to a reader the Stripe Terminal SDK needs to retrieve a short-lived connection token from Stripe, proxied through your server. On your backend, add an endpoint that creates and returns a connection token. +type TerminalConnectionTokenParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The id of the location that this connection token is scoped to. If specified the connection token will only be usable with readers assigned to that location, otherwise the connection token will be usable with all readers. Note that location scoping only applies to internet-connected readers. For more details, see [the docs on scoping connection tokens](https://docs.stripe.com/terminal/fleet/locations-and-zones?dashboard-or-api=api#connection-tokens). + Location *string `form:"location"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalConnectionTokenParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// To connect to a reader the Stripe Terminal SDK needs to retrieve a short-lived connection token from Stripe, proxied through your server. On your backend, add an endpoint that creates and returns a connection token. +type TerminalConnectionTokenCreateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The id of the location that this connection token is scoped to. If specified the connection token will only be usable with readers assigned to that location, otherwise the connection token will be usable with all readers. Note that location scoping only applies to internet-connected readers. For more details, see [the docs on scoping connection tokens](https://docs.stripe.com/terminal/fleet/locations-and-zones?dashboard-or-api=api#connection-tokens). + Location *string `form:"location"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalConnectionTokenCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A Connection Token is used by the Stripe Terminal SDK to connect to a reader. +// +// Related guide: [Fleet management](https://stripe.com/docs/terminal/fleet/locations) +type TerminalConnectionToken struct { + APIResource + // The id of the location that this connection token is scoped to. Note that location scoping only applies to internet-connected readers. For more details, see [the docs on scoping connection tokens](https://docs.stripe.com/terminal/fleet/locations-and-zones?dashboard-or-api=api#connection-tokens). + Location string `json:"location"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Your application should pass this token to the Stripe Terminal SDK. + Secret string `json:"secret"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/terminal_connectiontoken_service.go b/vendor/github.com/stripe/stripe-go/v82/terminal_connectiontoken_service.go new file mode 100644 index 00000000..492c8011 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/terminal_connectiontoken_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TerminalConnectionTokenService is used to invoke /v1/terminal/connection_tokens APIs. +type v1TerminalConnectionTokenService struct { + B Backend + Key string +} + +// To connect to a reader the Stripe Terminal SDK needs to retrieve a short-lived connection token from Stripe, proxied through your server. On your backend, add an endpoint that creates and returns a connection token. +func (c v1TerminalConnectionTokenService) Create(ctx context.Context, params *TerminalConnectionTokenCreateParams) (*TerminalConnectionToken, error) { + if params == nil { + params = &TerminalConnectionTokenCreateParams{} + } + params.Context = ctx + connectiontoken := &TerminalConnectionToken{} + err := c.B.Call( + http.MethodPost, "/v1/terminal/connection_tokens", c.Key, params, connectiontoken) + return connectiontoken, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/terminal_location.go b/vendor/github.com/stripe/stripe-go/v82/terminal_location.go new file mode 100644 index 00000000..b459a119 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/terminal_location.go @@ -0,0 +1,173 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Deletes a Location object. +type TerminalLocationParams struct { + Params `form:"*"` + // The full address of the location. You can't change the location's `country`. If you need to modify the `country` field, create a new `Location` object and re-register any existing readers to that location. + Address *AddressParams `form:"address"` + // The ID of a configuration that will be used to customize all readers in this location. + ConfigurationOverrides *string `form:"configuration_overrides"` + // A name for the location. Maximum length is 1000 characters. + DisplayName *string `form:"display_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalLocationParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TerminalLocationParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Returns a list of Location objects. +type TerminalLocationListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalLocationListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Deletes a Location object. +type TerminalLocationDeleteParams struct { + Params `form:"*"` +} + +// Retrieves a Location object. +type TerminalLocationRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalLocationRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates a Location object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +type TerminalLocationUpdateParams struct { + Params `form:"*"` + // The full address of the location. You can't change the location's `country`. If you need to modify the `country` field, create a new `Location` object and re-register any existing readers to that location. + Address *AddressParams `form:"address"` + // The ID of a configuration that will be used to customize all readers in this location. + ConfigurationOverrides *string `form:"configuration_overrides"` + // A name for the location. + DisplayName *string `form:"display_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalLocationUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TerminalLocationUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Creates a new Location object. +// For further details, including which address fields are required in each country, see the [Manage locations](https://docs.stripe.com/docs/terminal/fleet/locations) guide. +type TerminalLocationCreateParams struct { + Params `form:"*"` + // The full address of the location. + Address *AddressParams `form:"address"` + // The ID of a configuration that will be used to customize all readers in this location. + ConfigurationOverrides *string `form:"configuration_overrides"` + // A name for the location. Maximum length is 1000 characters. + DisplayName *string `form:"display_name"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalLocationCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TerminalLocationCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A Location represents a grouping of readers. +// +// Related guide: [Fleet management](https://stripe.com/docs/terminal/fleet/locations) +type TerminalLocation struct { + APIResource + Address *Address `json:"address"` + // The ID of a configuration that will be used to customize all readers in this location. + ConfigurationOverrides string `json:"configuration_overrides"` + Deleted bool `json:"deleted"` + // The display name of the location. + DisplayName string `json:"display_name"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` +} + +// TerminalLocationList is a list of Locations as retrieved from a list endpoint. +type TerminalLocationList struct { + APIResource + ListMeta + Data []*TerminalLocation `json:"data"` +} + +// UnmarshalJSON handles deserialization of a TerminalLocation. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (t *TerminalLocation) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + t.ID = id + return nil + } + + type terminalLocation TerminalLocation + var v terminalLocation + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *t = TerminalLocation(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/terminal_location_service.go b/vendor/github.com/stripe/stripe-go/v82/terminal_location_service.go new file mode 100644 index 00000000..73e101e5 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/terminal_location_service.go @@ -0,0 +1,86 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TerminalLocationService is used to invoke /v1/terminal/locations APIs. +type v1TerminalLocationService struct { + B Backend + Key string +} + +// Creates a new Location object. +// For further details, including which address fields are required in each country, see the [Manage locations](https://docs.stripe.com/docs/terminal/fleet/locations) guide. +func (c v1TerminalLocationService) Create(ctx context.Context, params *TerminalLocationCreateParams) (*TerminalLocation, error) { + if params == nil { + params = &TerminalLocationCreateParams{} + } + params.Context = ctx + location := &TerminalLocation{} + err := c.B.Call( + http.MethodPost, "/v1/terminal/locations", c.Key, params, location) + return location, err +} + +// Retrieves a Location object. +func (c v1TerminalLocationService) Retrieve(ctx context.Context, id string, params *TerminalLocationRetrieveParams) (*TerminalLocation, error) { + if params == nil { + params = &TerminalLocationRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/locations/%s", id) + location := &TerminalLocation{} + err := c.B.Call(http.MethodGet, path, c.Key, params, location) + return location, err +} + +// Updates a Location object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +func (c v1TerminalLocationService) Update(ctx context.Context, id string, params *TerminalLocationUpdateParams) (*TerminalLocation, error) { + if params == nil { + params = &TerminalLocationUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/locations/%s", id) + location := &TerminalLocation{} + err := c.B.Call(http.MethodPost, path, c.Key, params, location) + return location, err +} + +// Deletes a Location object. +func (c v1TerminalLocationService) Delete(ctx context.Context, id string, params *TerminalLocationDeleteParams) (*TerminalLocation, error) { + if params == nil { + params = &TerminalLocationDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/locations/%s", id) + location := &TerminalLocation{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, location) + return location, err +} + +// Returns a list of Location objects. +func (c v1TerminalLocationService) List(ctx context.Context, listParams *TerminalLocationListParams) Seq2[*TerminalLocation, error] { + if listParams == nil { + listParams = &TerminalLocationListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TerminalLocation, ListContainer, error) { + list := &TerminalLocationList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/terminal/locations", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/terminal_reader.go b/vendor/github.com/stripe/stripe-go/v82/terminal_reader.go new file mode 100644 index 00000000..019df5cd --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/terminal_reader.go @@ -0,0 +1,835 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The button style for the choice +type TerminalReaderActionCollectInputsInputSelectionChoiceStyle string + +// List of values that TerminalReaderActionCollectInputsInputSelectionChoiceStyle can take +const ( + TerminalReaderActionCollectInputsInputSelectionChoiceStylePrimary TerminalReaderActionCollectInputsInputSelectionChoiceStyle = "primary" + TerminalReaderActionCollectInputsInputSelectionChoiceStyleSecondary TerminalReaderActionCollectInputsInputSelectionChoiceStyle = "secondary" +) + +// The toggle's default value +type TerminalReaderActionCollectInputsInputToggleDefaultValue string + +// List of values that TerminalReaderActionCollectInputsInputToggleDefaultValue can take +const ( + TerminalReaderActionCollectInputsInputToggleDefaultValueDisabled TerminalReaderActionCollectInputsInputToggleDefaultValue = "disabled" + TerminalReaderActionCollectInputsInputToggleDefaultValueEnabled TerminalReaderActionCollectInputsInputToggleDefaultValue = "enabled" +) + +// The toggle's collected value +type TerminalReaderActionCollectInputsInputToggleValue string + +// List of values that TerminalReaderActionCollectInputsInputToggleValue can take +const ( + TerminalReaderActionCollectInputsInputToggleValueDisabled TerminalReaderActionCollectInputsInputToggleValue = "disabled" + TerminalReaderActionCollectInputsInputToggleValueEnabled TerminalReaderActionCollectInputsInputToggleValue = "enabled" +) + +// Type of input being collected. +type TerminalReaderActionCollectInputsInputType string + +// List of values that TerminalReaderActionCollectInputsInputType can take +const ( + TerminalReaderActionCollectInputsInputTypeEmail TerminalReaderActionCollectInputsInputType = "email" + TerminalReaderActionCollectInputsInputTypeNumeric TerminalReaderActionCollectInputsInputType = "numeric" + TerminalReaderActionCollectInputsInputTypePhone TerminalReaderActionCollectInputsInputType = "phone" + TerminalReaderActionCollectInputsInputTypeSelection TerminalReaderActionCollectInputsInputType = "selection" + TerminalReaderActionCollectInputsInputTypeSignature TerminalReaderActionCollectInputsInputType = "signature" + TerminalReaderActionCollectInputsInputTypeText TerminalReaderActionCollectInputsInputType = "text" +) + +// The reason for the refund. +type TerminalReaderActionRefundPaymentReason string + +// List of values that TerminalReaderActionRefundPaymentReason can take +const ( + TerminalReaderActionRefundPaymentReasonDuplicate TerminalReaderActionRefundPaymentReason = "duplicate" + TerminalReaderActionRefundPaymentReasonFraudulent TerminalReaderActionRefundPaymentReason = "fraudulent" + TerminalReaderActionRefundPaymentReasonRequestedByCustomer TerminalReaderActionRefundPaymentReason = "requested_by_customer" +) + +// Type of information to be displayed by the reader. +type TerminalReaderActionSetReaderDisplayType string + +// List of values that TerminalReaderActionSetReaderDisplayType can take +const ( + TerminalReaderActionSetReaderDisplayTypeCart TerminalReaderActionSetReaderDisplayType = "cart" +) + +// Status of the action performed by the reader. +type TerminalReaderActionStatus string + +// List of values that TerminalReaderActionStatus can take +const ( + TerminalReaderActionStatusFailed TerminalReaderActionStatus = "failed" + TerminalReaderActionStatusInProgress TerminalReaderActionStatus = "in_progress" + TerminalReaderActionStatusSucceeded TerminalReaderActionStatus = "succeeded" +) + +// Type of action performed by the reader. +type TerminalReaderActionType string + +// List of values that TerminalReaderActionType can take +const ( + TerminalReaderActionTypeCollectInputs TerminalReaderActionType = "collect_inputs" + TerminalReaderActionTypeCollectPaymentMethod TerminalReaderActionType = "collect_payment_method" + TerminalReaderActionTypeConfirmPaymentIntent TerminalReaderActionType = "confirm_payment_intent" + TerminalReaderActionTypeProcessPaymentIntent TerminalReaderActionType = "process_payment_intent" + TerminalReaderActionTypeProcessSetupIntent TerminalReaderActionType = "process_setup_intent" + TerminalReaderActionTypeRefundPayment TerminalReaderActionType = "refund_payment" + TerminalReaderActionTypeSetReaderDisplay TerminalReaderActionType = "set_reader_display" +) + +// Device type of the reader. +type TerminalReaderDeviceType string + +// List of values that TerminalReaderDeviceType can take +const ( + TerminalReaderDeviceTypeBBPOSChipper2X TerminalReaderDeviceType = "bbpos_chipper2x" + TerminalReaderDeviceTypeBBPOSWisePad3 TerminalReaderDeviceType = "bbpos_wisepad3" + TerminalReaderDeviceTypeBBPOSWisePOSE TerminalReaderDeviceType = "bbpos_wisepos_e" + TerminalReaderDeviceTypeMobilePhoneReader TerminalReaderDeviceType = "mobile_phone_reader" + TerminalReaderDeviceTypeSimulatedStripeS700 TerminalReaderDeviceType = "simulated_stripe_s700" + TerminalReaderDeviceTypeSimulatedWisePOSE TerminalReaderDeviceType = "simulated_wisepos_e" + TerminalReaderDeviceTypeStripeM2 TerminalReaderDeviceType = "stripe_m2" + TerminalReaderDeviceTypeStripeS700 TerminalReaderDeviceType = "stripe_s700" + TerminalReaderDeviceTypeVerifoneP400 TerminalReaderDeviceType = "verifone_P400" +) + +// The networking status of the reader. We do not recommend using this field in flows that may block taking payments. +type TerminalReaderStatus string + +// List of values that TerminalReaderStatus can take +const ( + TerminalReaderStatusOffline TerminalReaderStatus = "offline" + TerminalReaderStatusOnline TerminalReaderStatus = "online" +) + +// Deletes a Reader object. +type TerminalReaderParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Custom label given to the reader for easier identification. If no label is specified, the registration code will be used. + Label *string `form:"label"` + // The location to assign the reader to. + Location *string `form:"location"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // A code generated by the reader used for registering to an account. + RegistrationCode *string `form:"registration_code"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalReaderParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TerminalReaderParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Returns a list of Reader objects. +type TerminalReaderListParams struct { + ListParams `form:"*"` + // Filters readers by device type + DeviceType *string `form:"device_type"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A location ID to filter the response list to only readers at the specific location + Location *string `form:"location"` + // Filters readers by serial number + SerialNumber *string `form:"serial_number"` + // A status filter to filter readers to only offline or online readers + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalReaderListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Cancels the current reader action. +type TerminalReaderCancelActionParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalReaderCancelActionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Customize the text which will be displayed while collecting this input +type TerminalReaderCollectInputsInputCustomTextParams struct { + // The description which will be displayed when collecting this input + Description *string `form:"description"` + // The skip button text + SkipButton *string `form:"skip_button"` + // The submit button text + SubmitButton *string `form:"submit_button"` + // The title which will be displayed when collecting this input + Title *string `form:"title"` +} + +// List of choices for the `selection` input +type TerminalReaderCollectInputsInputSelectionChoiceParams struct { + // The unique identifier for this choice + ID *string `form:"id"` + // The style of the button which will be shown for this choice + Style *string `form:"style"` + // The text which will be shown on the button for this choice + Text *string `form:"text"` +} + +// Options for the `selection` input +type TerminalReaderCollectInputsInputSelectionParams struct { + // List of choices for the `selection` input + Choices []*TerminalReaderCollectInputsInputSelectionChoiceParams `form:"choices"` +} + +// List of toggles to be displayed and customization for the toggles +type TerminalReaderCollectInputsInputToggleParams struct { + // The default value of the toggle + DefaultValue *string `form:"default_value"` + // The description which will be displayed for the toggle + Description *string `form:"description"` + // The title which will be displayed for the toggle + Title *string `form:"title"` +} + +// List of inputs to be collected using the Reader +type TerminalReaderCollectInputsInputParams struct { + // Customize the text which will be displayed while collecting this input + CustomText *TerminalReaderCollectInputsInputCustomTextParams `form:"custom_text"` + // Indicate that this input is required, disabling the skip button + Required *bool `form:"required"` + // Options for the `selection` input + Selection *TerminalReaderCollectInputsInputSelectionParams `form:"selection"` + // List of toggles to be displayed and customization for the toggles + Toggles []*TerminalReaderCollectInputsInputToggleParams `form:"toggles"` + // The type of input to collect + Type *string `form:"type"` +} + +// Initiates an input collection flow on a Reader. +type TerminalReaderCollectInputsParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // List of inputs to be collected using the Reader + Inputs []*TerminalReaderCollectInputsInputParams `form:"inputs"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalReaderCollectInputsParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TerminalReaderCollectInputsParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Tipping configuration for this transaction. +type TerminalReaderCollectPaymentMethodCollectConfigTippingParams struct { + // Amount used to calculate tip suggestions on tipping selection screen for this transaction. Must be a positive integer in the smallest currency unit (e.g., 100 cents to represent $1.00 or 100 to represent ¥100, a zero-decimal currency). + AmountEligible *int64 `form:"amount_eligible"` +} + +// Configuration overrides. +type TerminalReaderCollectPaymentMethodCollectConfigParams struct { + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. + AllowRedisplay *string `form:"allow_redisplay"` + // Enables cancel button on transaction screens. + EnableCustomerCancellation *bool `form:"enable_customer_cancellation"` + // Override showing a tipping selection screen on this transaction. + SkipTipping *bool `form:"skip_tipping"` + // Tipping configuration for this transaction. + Tipping *TerminalReaderCollectPaymentMethodCollectConfigTippingParams `form:"tipping"` +} + +// Initiates a payment flow on a Reader and updates the PaymentIntent with card details before manual confirmation. +type TerminalReaderCollectPaymentMethodParams struct { + Params `form:"*"` + // Configuration overrides. + CollectConfig *TerminalReaderCollectPaymentMethodCollectConfigParams `form:"collect_config"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // PaymentIntent ID. + PaymentIntent *string `form:"payment_intent"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalReaderCollectPaymentMethodParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Configuration overrides. +type TerminalReaderConfirmPaymentIntentConfirmConfigParams struct { + // The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method's app or site. If you'd prefer to redirect to a mobile application, you can alternatively supply an application URI scheme. + ReturnURL *string `form:"return_url"` +} + +// Finalizes a payment on a Reader. +type TerminalReaderConfirmPaymentIntentParams struct { + Params `form:"*"` + // Configuration overrides. + ConfirmConfig *TerminalReaderConfirmPaymentIntentConfirmConfigParams `form:"confirm_config"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // PaymentIntent ID. + PaymentIntent *string `form:"payment_intent"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalReaderConfirmPaymentIntentParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Tipping configuration for this transaction. +type TerminalReaderProcessPaymentIntentProcessConfigTippingParams struct { + // Amount used to calculate tip suggestions on tipping selection screen for this transaction. Must be a positive integer in the smallest currency unit (e.g., 100 cents to represent $1.00 or 100 to represent ¥100, a zero-decimal currency). + AmountEligible *int64 `form:"amount_eligible"` +} + +// Configuration overrides +type TerminalReaderProcessPaymentIntentProcessConfigParams struct { + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. + AllowRedisplay *string `form:"allow_redisplay"` + // Enables cancel button on transaction screens. + EnableCustomerCancellation *bool `form:"enable_customer_cancellation"` + // The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method's app or site. If you'd prefer to redirect to a mobile application, you can alternatively supply an application URI scheme. + ReturnURL *string `form:"return_url"` + // Override showing a tipping selection screen on this transaction. + SkipTipping *bool `form:"skip_tipping"` + // Tipping configuration for this transaction. + Tipping *TerminalReaderProcessPaymentIntentProcessConfigTippingParams `form:"tipping"` +} + +// Initiates a payment flow on a Reader. +type TerminalReaderProcessPaymentIntentParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // PaymentIntent ID + PaymentIntent *string `form:"payment_intent"` + // Configuration overrides + ProcessConfig *TerminalReaderProcessPaymentIntentProcessConfigParams `form:"process_config"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalReaderProcessPaymentIntentParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Configuration overrides +type TerminalReaderProcessSetupIntentProcessConfigParams struct { + // Enables cancel button on transaction screens. + EnableCustomerCancellation *bool `form:"enable_customer_cancellation"` +} + +// Initiates a setup intent flow on a Reader. +type TerminalReaderProcessSetupIntentParams struct { + Params `form:"*"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. + AllowRedisplay *string `form:"allow_redisplay"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Configuration overrides + ProcessConfig *TerminalReaderProcessSetupIntentProcessConfigParams `form:"process_config"` + // SetupIntent ID + SetupIntent *string `form:"setup_intent"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalReaderProcessSetupIntentParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Configuration overrides +type TerminalReaderRefundPaymentRefundPaymentConfigParams struct { + // Enables cancel button on transaction screens. + EnableCustomerCancellation *bool `form:"enable_customer_cancellation"` +} + +// Initiates a refund on a Reader +type TerminalReaderRefundPaymentParams struct { + Params `form:"*"` + // A positive integer in __cents__ representing how much of this charge to refund. + Amount *int64 `form:"amount"` + // ID of the Charge to refund. + Charge *string `form:"charge"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // ID of the PaymentIntent to refund. + PaymentIntent *string `form:"payment_intent"` + // Boolean indicating whether the application fee should be refunded when refunding this charge. If a full charge refund is given, the full application fee will be refunded. Otherwise, the application fee will be refunded in an amount proportional to the amount of the charge refunded. An application fee can be refunded only by the application that created the charge. + RefundApplicationFee *bool `form:"refund_application_fee"` + // Configuration overrides + RefundPaymentConfig *TerminalReaderRefundPaymentRefundPaymentConfigParams `form:"refund_payment_config"` + // Boolean indicating whether the transfer should be reversed when refunding this charge. The transfer will be reversed proportionally to the amount being refunded (either the entire or partial amount). A transfer can be reversed only by the application that created the charge. + ReverseTransfer *bool `form:"reverse_transfer"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalReaderRefundPaymentParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TerminalReaderRefundPaymentParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Array of line items that were purchased. +type TerminalReaderSetReaderDisplayCartLineItemParams struct { + // The price of the item in cents. + Amount *int64 `form:"amount"` + // The description or name of the item. + Description *string `form:"description"` + // The quantity of the line item being purchased. + Quantity *int64 `form:"quantity"` +} + +// Cart +type TerminalReaderSetReaderDisplayCartParams struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Array of line items that were purchased. + LineItems []*TerminalReaderSetReaderDisplayCartLineItemParams `form:"line_items"` + // The amount of tax in cents. + Tax *int64 `form:"tax"` + // Total balance of cart due in cents. + Total *int64 `form:"total"` +} + +// Sets reader display to show cart details. +type TerminalReaderSetReaderDisplayParams struct { + Params `form:"*"` + // Cart + Cart *TerminalReaderSetReaderDisplayCartParams `form:"cart"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Type + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalReaderSetReaderDisplayParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Deletes a Reader object. +type TerminalReaderDeleteParams struct { + Params `form:"*"` +} + +// Retrieves a Reader object. +type TerminalReaderRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalReaderRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates a Reader object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +type TerminalReaderUpdateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The new label of the reader. + Label *string `form:"label"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalReaderUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TerminalReaderUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Creates a new Reader object. +type TerminalReaderCreateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Custom label given to the reader for easier identification. If no label is specified, the registration code will be used. + Label *string `form:"label"` + // The location to assign the reader to. + Location *string `form:"location"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // A code generated by the reader used for registering to an account. + RegistrationCode *string `form:"registration_code"` +} + +// AddExpand appends a new field to expand. +func (p *TerminalReaderCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TerminalReaderCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Default text of input being collected. +type TerminalReaderActionCollectInputsInputCustomText struct { + // Customize the default description for this input + Description string `json:"description"` + // Customize the default label for this input's skip button + SkipButton string `json:"skip_button"` + // Customize the default label for this input's submit button + SubmitButton string `json:"submit_button"` + // Customize the default title for this input + Title string `json:"title"` +} + +// Information about a email being collected using a reader +type TerminalReaderActionCollectInputsInputEmail struct { + // The collected email address + Value string `json:"value"` +} + +// Information about a number being collected using a reader +type TerminalReaderActionCollectInputsInputNumeric struct { + // The collected number + Value string `json:"value"` +} + +// Information about a phone number being collected using a reader +type TerminalReaderActionCollectInputsInputPhone struct { + // The collected phone number + Value string `json:"value"` +} + +// List of possible choices to be selected +type TerminalReaderActionCollectInputsInputSelectionChoice struct { + // The id to be selected + ID string `json:"id"` + // The button style for the choice + Style TerminalReaderActionCollectInputsInputSelectionChoiceStyle `json:"style"` + // The text to be selected + Text string `json:"text"` +} + +// Information about a selection being collected using a reader +type TerminalReaderActionCollectInputsInputSelection struct { + // List of possible choices to be selected + Choices []*TerminalReaderActionCollectInputsInputSelectionChoice `json:"choices"` + // The id of the selected choice + ID string `json:"id"` + // The text of the selected choice + Text string `json:"text"` +} + +// Information about a signature being collected using a reader +type TerminalReaderActionCollectInputsInputSignature struct { + // The File ID of a collected signature image + Value string `json:"value"` +} + +// Information about text being collected using a reader +type TerminalReaderActionCollectInputsInputText struct { + // The collected text value + Value string `json:"value"` +} + +// List of toggles being collected. Values are present if collection is complete. +type TerminalReaderActionCollectInputsInputToggle struct { + // The toggle's default value + DefaultValue TerminalReaderActionCollectInputsInputToggleDefaultValue `json:"default_value"` + // The toggle's description text + Description string `json:"description"` + // The toggle's title text + Title string `json:"title"` + // The toggle's collected value + Value TerminalReaderActionCollectInputsInputToggleValue `json:"value"` +} + +// List of inputs to be collected. +type TerminalReaderActionCollectInputsInput struct { + // Default text of input being collected. + CustomText *TerminalReaderActionCollectInputsInputCustomText `json:"custom_text"` + // Information about a email being collected using a reader + Email *TerminalReaderActionCollectInputsInputEmail `json:"email"` + // Information about a number being collected using a reader + Numeric *TerminalReaderActionCollectInputsInputNumeric `json:"numeric"` + // Information about a phone number being collected using a reader + Phone *TerminalReaderActionCollectInputsInputPhone `json:"phone"` + // Indicate that this input is required, disabling the skip button. + Required bool `json:"required"` + // Information about a selection being collected using a reader + Selection *TerminalReaderActionCollectInputsInputSelection `json:"selection"` + // Information about a signature being collected using a reader + Signature *TerminalReaderActionCollectInputsInputSignature `json:"signature"` + // Indicate that this input was skipped by the user. + Skipped bool `json:"skipped"` + // Information about text being collected using a reader + Text *TerminalReaderActionCollectInputsInputText `json:"text"` + // List of toggles being collected. Values are present if collection is complete. + Toggles []*TerminalReaderActionCollectInputsInputToggle `json:"toggles"` + // Type of input being collected. + Type TerminalReaderActionCollectInputsInputType `json:"type"` +} + +// Represents a reader action to collect customer inputs +type TerminalReaderActionCollectInputs struct { + // List of inputs to be collected. + Inputs []*TerminalReaderActionCollectInputsInput `json:"inputs"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` +} + +// Represents a per-transaction tipping configuration +type TerminalReaderActionCollectPaymentMethodCollectConfigTipping struct { + // Amount used to calculate tip suggestions on tipping selection screen for this transaction. Must be a positive integer in the smallest currency unit (e.g., 100 cents to represent $1.00 or 100 to represent ¥100, a zero-decimal currency). + AmountEligible int64 `json:"amount_eligible"` +} + +// Represents a per-transaction override of a reader configuration +type TerminalReaderActionCollectPaymentMethodCollectConfig struct { + // Enable customer-initiated cancellation when processing this payment. + EnableCustomerCancellation bool `json:"enable_customer_cancellation"` + // Override showing a tipping selection screen on this transaction. + SkipTipping bool `json:"skip_tipping"` + // Represents a per-transaction tipping configuration + Tipping *TerminalReaderActionCollectPaymentMethodCollectConfigTipping `json:"tipping"` +} + +// Represents a reader action to collect a payment method +type TerminalReaderActionCollectPaymentMethod struct { + // Represents a per-transaction override of a reader configuration + CollectConfig *TerminalReaderActionCollectPaymentMethodCollectConfig `json:"collect_config"` + // Most recent PaymentIntent processed by the reader. + PaymentIntent *PaymentIntent `json:"payment_intent"` + // PaymentMethod objects represent your customer's payment instruments. + // You can use them with [PaymentIntents](https://stripe.com/docs/payments/payment-intents) to collect payments or save them to + // Customer objects to store instrument details for future payments. + // + // Related guides: [Payment Methods](https://stripe.com/docs/payments/payment-methods) and [More Payment Scenarios](https://stripe.com/docs/payments/more-payment-scenarios). + PaymentMethod *PaymentMethod `json:"payment_method"` +} + +// Represents a per-transaction override of a reader configuration +type TerminalReaderActionConfirmPaymentIntentConfirmConfig struct { + // If the customer doesn't abandon authenticating the payment, they're redirected to this URL after completion. + ReturnURL string `json:"return_url"` +} + +// Represents a reader action to confirm a payment +type TerminalReaderActionConfirmPaymentIntent struct { + // Represents a per-transaction override of a reader configuration + ConfirmConfig *TerminalReaderActionConfirmPaymentIntentConfirmConfig `json:"confirm_config"` + // Most recent PaymentIntent processed by the reader. + PaymentIntent *PaymentIntent `json:"payment_intent"` +} + +// Represents a per-transaction tipping configuration +type TerminalReaderActionProcessPaymentIntentProcessConfigTipping struct { + // Amount used to calculate tip suggestions on tipping selection screen for this transaction. Must be a positive integer in the smallest currency unit (e.g., 100 cents to represent $1.00 or 100 to represent ¥100, a zero-decimal currency). + AmountEligible int64 `json:"amount_eligible"` +} + +// Represents a per-transaction override of a reader configuration +type TerminalReaderActionProcessPaymentIntentProcessConfig struct { + // Enable customer-initiated cancellation when processing this payment. + EnableCustomerCancellation bool `json:"enable_customer_cancellation"` + // If the customer doesn't abandon authenticating the payment, they're redirected to this URL after completion. + ReturnURL string `json:"return_url"` + // Override showing a tipping selection screen on this transaction. + SkipTipping bool `json:"skip_tipping"` + // Represents a per-transaction tipping configuration + Tipping *TerminalReaderActionProcessPaymentIntentProcessConfigTipping `json:"tipping"` +} + +// Represents a reader action to process a payment intent +type TerminalReaderActionProcessPaymentIntent struct { + // Most recent PaymentIntent processed by the reader. + PaymentIntent *PaymentIntent `json:"payment_intent"` + // Represents a per-transaction override of a reader configuration + ProcessConfig *TerminalReaderActionProcessPaymentIntentProcessConfig `json:"process_config"` +} + +// Represents a per-setup override of a reader configuration +type TerminalReaderActionProcessSetupIntentProcessConfig struct { + // Enable customer-initiated cancellation when processing this SetupIntent. + EnableCustomerCancellation bool `json:"enable_customer_cancellation"` +} + +// Represents a reader action to process a setup intent +type TerminalReaderActionProcessSetupIntent struct { + // ID of a card PaymentMethod generated from the card_present PaymentMethod that may be attached to a Customer for future transactions. Only present if it was possible to generate a card PaymentMethod. + GeneratedCard string `json:"generated_card"` + // Represents a per-setup override of a reader configuration + ProcessConfig *TerminalReaderActionProcessSetupIntentProcessConfig `json:"process_config"` + // Most recent SetupIntent processed by the reader. + SetupIntent *SetupIntent `json:"setup_intent"` +} + +// Represents a per-transaction override of a reader configuration +type TerminalReaderActionRefundPaymentRefundPaymentConfig struct { + // Enable customer-initiated cancellation when refunding this payment. + EnableCustomerCancellation bool `json:"enable_customer_cancellation"` +} + +// Represents a reader action to refund a payment +type TerminalReaderActionRefundPayment struct { + // The amount being refunded. + Amount int64 `json:"amount"` + // Charge that is being refunded. + Charge *Charge `json:"charge"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // Payment intent that is being refunded. + PaymentIntent *PaymentIntent `json:"payment_intent"` + // The reason for the refund. + Reason TerminalReaderActionRefundPaymentReason `json:"reason"` + // Unique identifier for the refund object. + Refund *Refund `json:"refund"` + // Boolean indicating whether the application fee should be refunded when refunding this charge. If a full charge refund is given, the full application fee will be refunded. Otherwise, the application fee will be refunded in an amount proportional to the amount of the charge refunded. An application fee can be refunded only by the application that created the charge. + RefundApplicationFee bool `json:"refund_application_fee"` + // Represents a per-transaction override of a reader configuration + RefundPaymentConfig *TerminalReaderActionRefundPaymentRefundPaymentConfig `json:"refund_payment_config"` + // Boolean indicating whether the transfer should be reversed when refunding this charge. The transfer will be reversed proportionally to the amount being refunded (either the entire or partial amount). A transfer can be reversed only by the application that created the charge. + ReverseTransfer bool `json:"reverse_transfer"` +} + +// List of line items in the cart. +type TerminalReaderActionSetReaderDisplayCartLineItem struct { + // The amount of the line item. A positive integer in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Amount int64 `json:"amount"` + // Description of the line item. + Description string `json:"description"` + // The quantity of the line item. + Quantity int64 `json:"quantity"` +} + +// Cart object to be displayed by the reader. +type TerminalReaderActionSetReaderDisplayCart struct { + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // List of line items in the cart. + LineItems []*TerminalReaderActionSetReaderDisplayCartLineItem `json:"line_items"` + // Tax amount for the entire cart. A positive integer in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Tax int64 `json:"tax"` + // Total amount for the entire cart, including tax. A positive integer in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Total int64 `json:"total"` +} + +// Represents a reader action to set the reader display +type TerminalReaderActionSetReaderDisplay struct { + // Cart object to be displayed by the reader. + Cart *TerminalReaderActionSetReaderDisplayCart `json:"cart"` + // Type of information to be displayed by the reader. + Type TerminalReaderActionSetReaderDisplayType `json:"type"` +} + +// The most recent action performed by the reader. +type TerminalReaderAction struct { + // Represents a reader action to collect customer inputs + CollectInputs *TerminalReaderActionCollectInputs `json:"collect_inputs"` + // Represents a reader action to collect a payment method + CollectPaymentMethod *TerminalReaderActionCollectPaymentMethod `json:"collect_payment_method"` + // Represents a reader action to confirm a payment + ConfirmPaymentIntent *TerminalReaderActionConfirmPaymentIntent `json:"confirm_payment_intent"` + // Failure code, only set if status is `failed`. + FailureCode string `json:"failure_code"` + // Detailed failure message, only set if status is `failed`. + FailureMessage string `json:"failure_message"` + // Represents a reader action to process a payment intent + ProcessPaymentIntent *TerminalReaderActionProcessPaymentIntent `json:"process_payment_intent"` + // Represents a reader action to process a setup intent + ProcessSetupIntent *TerminalReaderActionProcessSetupIntent `json:"process_setup_intent"` + // Represents a reader action to refund a payment + RefundPayment *TerminalReaderActionRefundPayment `json:"refund_payment"` + // Represents a reader action to set the reader display + SetReaderDisplay *TerminalReaderActionSetReaderDisplay `json:"set_reader_display"` + // Status of the action performed by the reader. + Status TerminalReaderActionStatus `json:"status"` + // Type of action performed by the reader. + Type TerminalReaderActionType `json:"type"` +} + +// A Reader represents a physical device for accepting payment details. +// +// Related guide: [Connecting to a reader](https://stripe.com/docs/terminal/payments/connect-reader) +type TerminalReader struct { + APIResource + // The most recent action performed by the reader. + Action *TerminalReaderAction `json:"action"` + Deleted bool `json:"deleted"` + // The current software version of the reader. + DeviceSwVersion string `json:"device_sw_version"` + // Device type of the reader. + DeviceType TerminalReaderDeviceType `json:"device_type"` + // Unique identifier for the object. + ID string `json:"id"` + // The local IP address of the reader. + IPAddress string `json:"ip_address"` + // Custom label given to the reader for easier identification. + Label string `json:"label"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // The location identifier of the reader. + Location *TerminalLocation `json:"location"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Serial number of the reader. + SerialNumber string `json:"serial_number"` + // The networking status of the reader. We do not recommend using this field in flows that may block taking payments. + Status TerminalReaderStatus `json:"status"` +} + +// TerminalReaderList is a list of Readers as retrieved from a list endpoint. +type TerminalReaderList struct { + APIResource + ListMeta + Data []*TerminalReader `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/terminal_reader_service.go b/vendor/github.com/stripe/stripe-go/v82/terminal_reader_service.go new file mode 100644 index 00000000..002ffd10 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/terminal_reader_service.go @@ -0,0 +1,181 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TerminalReaderService is used to invoke /v1/terminal/readers APIs. +type v1TerminalReaderService struct { + B Backend + Key string +} + +// Creates a new Reader object. +func (c v1TerminalReaderService) Create(ctx context.Context, params *TerminalReaderCreateParams) (*TerminalReader, error) { + if params == nil { + params = &TerminalReaderCreateParams{} + } + params.Context = ctx + reader := &TerminalReader{} + err := c.B.Call( + http.MethodPost, "/v1/terminal/readers", c.Key, params, reader) + return reader, err +} + +// Retrieves a Reader object. +func (c v1TerminalReaderService) Retrieve(ctx context.Context, id string, params *TerminalReaderRetrieveParams) (*TerminalReader, error) { + if params == nil { + params = &TerminalReaderRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/readers/%s", id) + reader := &TerminalReader{} + err := c.B.Call(http.MethodGet, path, c.Key, params, reader) + return reader, err +} + +// Updates a Reader object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +func (c v1TerminalReaderService) Update(ctx context.Context, id string, params *TerminalReaderUpdateParams) (*TerminalReader, error) { + if params == nil { + params = &TerminalReaderUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/readers/%s", id) + reader := &TerminalReader{} + err := c.B.Call(http.MethodPost, path, c.Key, params, reader) + return reader, err +} + +// Deletes a Reader object. +func (c v1TerminalReaderService) Delete(ctx context.Context, id string, params *TerminalReaderDeleteParams) (*TerminalReader, error) { + if params == nil { + params = &TerminalReaderDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/readers/%s", id) + reader := &TerminalReader{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, reader) + return reader, err +} + +// Cancels the current reader action. +func (c v1TerminalReaderService) CancelAction(ctx context.Context, id string, params *TerminalReaderCancelActionParams) (*TerminalReader, error) { + if params == nil { + params = &TerminalReaderCancelActionParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/readers/%s/cancel_action", id) + reader := &TerminalReader{} + err := c.B.Call(http.MethodPost, path, c.Key, params, reader) + return reader, err +} + +// Initiates an input collection flow on a Reader. +func (c v1TerminalReaderService) CollectInputs(ctx context.Context, id string, params *TerminalReaderCollectInputsParams) (*TerminalReader, error) { + if params == nil { + params = &TerminalReaderCollectInputsParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/readers/%s/collect_inputs", id) + reader := &TerminalReader{} + err := c.B.Call(http.MethodPost, path, c.Key, params, reader) + return reader, err +} + +// Initiates a payment flow on a Reader and updates the PaymentIntent with card details before manual confirmation. +func (c v1TerminalReaderService) CollectPaymentMethod(ctx context.Context, id string, params *TerminalReaderCollectPaymentMethodParams) (*TerminalReader, error) { + if params == nil { + params = &TerminalReaderCollectPaymentMethodParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/readers/%s/collect_payment_method", id) + reader := &TerminalReader{} + err := c.B.Call(http.MethodPost, path, c.Key, params, reader) + return reader, err +} + +// Finalizes a payment on a Reader. +func (c v1TerminalReaderService) ConfirmPaymentIntent(ctx context.Context, id string, params *TerminalReaderConfirmPaymentIntentParams) (*TerminalReader, error) { + if params == nil { + params = &TerminalReaderConfirmPaymentIntentParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/readers/%s/confirm_payment_intent", id) + reader := &TerminalReader{} + err := c.B.Call(http.MethodPost, path, c.Key, params, reader) + return reader, err +} + +// Initiates a payment flow on a Reader. +func (c v1TerminalReaderService) ProcessPaymentIntent(ctx context.Context, id string, params *TerminalReaderProcessPaymentIntentParams) (*TerminalReader, error) { + if params == nil { + params = &TerminalReaderProcessPaymentIntentParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/readers/%s/process_payment_intent", id) + reader := &TerminalReader{} + err := c.B.Call(http.MethodPost, path, c.Key, params, reader) + return reader, err +} + +// Initiates a setup intent flow on a Reader. +func (c v1TerminalReaderService) ProcessSetupIntent(ctx context.Context, id string, params *TerminalReaderProcessSetupIntentParams) (*TerminalReader, error) { + if params == nil { + params = &TerminalReaderProcessSetupIntentParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/readers/%s/process_setup_intent", id) + reader := &TerminalReader{} + err := c.B.Call(http.MethodPost, path, c.Key, params, reader) + return reader, err +} + +// Initiates a refund on a Reader +func (c v1TerminalReaderService) RefundPayment(ctx context.Context, id string, params *TerminalReaderRefundPaymentParams) (*TerminalReader, error) { + if params == nil { + params = &TerminalReaderRefundPaymentParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/readers/%s/refund_payment", id) + reader := &TerminalReader{} + err := c.B.Call(http.MethodPost, path, c.Key, params, reader) + return reader, err +} + +// Sets reader display to show cart details. +func (c v1TerminalReaderService) SetReaderDisplay(ctx context.Context, id string, params *TerminalReaderSetReaderDisplayParams) (*TerminalReader, error) { + if params == nil { + params = &TerminalReaderSetReaderDisplayParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/terminal/readers/%s/set_reader_display", id) + reader := &TerminalReader{} + err := c.B.Call(http.MethodPost, path, c.Key, params, reader) + return reader, err +} + +// Returns a list of Reader objects. +func (c v1TerminalReaderService) List(ctx context.Context, listParams *TerminalReaderListParams) Seq2[*TerminalReader, error] { + if listParams == nil { + listParams = &TerminalReaderListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TerminalReader, ListContainer, error) { + list := &TerminalReaderList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/terminal/readers", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpers_confirmationtoken.go b/vendor/github.com/stripe/stripe-go/v82/testhelpers_confirmationtoken.go new file mode 100644 index 00000000..5e9b08d5 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpers_confirmationtoken.go @@ -0,0 +1,865 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. +type TestHelpersConfirmationTokenPaymentMethodDataACSSDebitParams struct { + // Customer's bank account number. + AccountNumber *string `form:"account_number"` + // Institution number of the customer's bank. + InstitutionNumber *string `form:"institution_number"` + // Transit number of the customer's bank. + TransitNumber *string `form:"transit_number"` +} + +// If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. +type TestHelpersConfirmationTokenPaymentMethodDataAffirmParams struct{} + +// If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. +type TestHelpersConfirmationTokenPaymentMethodDataAfterpayClearpayParams struct{} + +// If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. +type TestHelpersConfirmationTokenPaymentMethodDataAlipayParams struct{} + +// If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. +type TestHelpersConfirmationTokenPaymentMethodDataAlmaParams struct{} + +// If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. +type TestHelpersConfirmationTokenPaymentMethodDataAmazonPayParams struct{} + +// If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. +type TestHelpersConfirmationTokenPaymentMethodDataAUBECSDebitParams struct { + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // Bank-State-Branch number of the bank account. + BSBNumber *string `form:"bsb_number"` +} + +// If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. +type TestHelpersConfirmationTokenPaymentMethodDataBACSDebitParams struct { + // Account number of the bank account that the funds will be debited from. + AccountNumber *string `form:"account_number"` + // Sort code of the bank account. (e.g., `10-20-30`) + SortCode *string `form:"sort_code"` +} + +// If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. +type TestHelpersConfirmationTokenPaymentMethodDataBancontactParams struct{} + +// If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. +type TestHelpersConfirmationTokenPaymentMethodDataBillieParams struct{} + +// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. +type TestHelpersConfirmationTokenPaymentMethodDataBillingDetailsParams struct { + // Billing address. + Address *AddressParams `form:"address"` + // Email address. + Email *string `form:"email"` + // Full name. + Name *string `form:"name"` + // Billing phone number (including extension). + Phone *string `form:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID *string `form:"tax_id"` +} + +// If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. +type TestHelpersConfirmationTokenPaymentMethodDataBLIKParams struct{} + +// If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. +type TestHelpersConfirmationTokenPaymentMethodDataBoletoParams struct { + // The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + TaxID *string `form:"tax_id"` +} + +// If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. +type TestHelpersConfirmationTokenPaymentMethodDataCashAppParams struct{} + +// If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. +type TestHelpersConfirmationTokenPaymentMethodDataCryptoParams struct{} + +// If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. +type TestHelpersConfirmationTokenPaymentMethodDataCustomerBalanceParams struct{} + +// If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. +type TestHelpersConfirmationTokenPaymentMethodDataEPSParams struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. +type TestHelpersConfirmationTokenPaymentMethodDataFPXParams struct { + // Account holder type for FPX transaction + AccountHolderType *string `form:"account_holder_type"` + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. +type TestHelpersConfirmationTokenPaymentMethodDataGiropayParams struct{} + +// If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. +type TestHelpersConfirmationTokenPaymentMethodDataGrabpayParams struct{} + +// If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. +type TestHelpersConfirmationTokenPaymentMethodDataIDEALParams struct { + // The customer's bank. Only use this parameter for existing customers. Don't use it for new customers. + Bank *string `form:"bank"` +} + +// If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. +type TestHelpersConfirmationTokenPaymentMethodDataInteracPresentParams struct{} + +// If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. +type TestHelpersConfirmationTokenPaymentMethodDataKakaoPayParams struct{} + +// Customer's date of birth +type TestHelpersConfirmationTokenPaymentMethodDataKlarnaDOBParams struct { + // The day of birth, between 1 and 31. + Day *int64 `form:"day"` + // The month of birth, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of birth. + Year *int64 `form:"year"` +} + +// If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. +type TestHelpersConfirmationTokenPaymentMethodDataKlarnaParams struct { + // Customer's date of birth + DOB *TestHelpersConfirmationTokenPaymentMethodDataKlarnaDOBParams `form:"dob"` +} + +// If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. +type TestHelpersConfirmationTokenPaymentMethodDataKonbiniParams struct{} + +// If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. +type TestHelpersConfirmationTokenPaymentMethodDataKrCardParams struct{} + +// If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. +type TestHelpersConfirmationTokenPaymentMethodDataLinkParams struct{} + +// If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. +type TestHelpersConfirmationTokenPaymentMethodDataMobilepayParams struct{} + +// If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. +type TestHelpersConfirmationTokenPaymentMethodDataMultibancoParams struct{} + +// If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. +type TestHelpersConfirmationTokenPaymentMethodDataNaverPayParams struct { + // Whether to use Naver Pay points or a card to fund this transaction. If not provided, this defaults to `card`. + Funding *string `form:"funding"` +} + +// If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. +type TestHelpersConfirmationTokenPaymentMethodDataNzBankAccountParams struct { + // The name on the bank account. Only required if the account holder name is different from the name of the authorized signatory collected in the PaymentMethod's billing details. + AccountHolderName *string `form:"account_holder_name"` + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // The numeric code for the bank account's bank. + BankCode *string `form:"bank_code"` + // The numeric code for the bank account's bank branch. + BranchCode *string `form:"branch_code"` + Reference *string `form:"reference"` + // The suffix of the bank account number. + Suffix *string `form:"suffix"` +} + +// If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. +type TestHelpersConfirmationTokenPaymentMethodDataOXXOParams struct{} + +// If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. +type TestHelpersConfirmationTokenPaymentMethodDataP24Params struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. +type TestHelpersConfirmationTokenPaymentMethodDataPayByBankParams struct{} + +// If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. +type TestHelpersConfirmationTokenPaymentMethodDataPaycoParams struct{} + +// If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. +type TestHelpersConfirmationTokenPaymentMethodDataPayNowParams struct{} + +// If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. +type TestHelpersConfirmationTokenPaymentMethodDataPaypalParams struct{} + +// If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. +type TestHelpersConfirmationTokenPaymentMethodDataPixParams struct{} + +// If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. +type TestHelpersConfirmationTokenPaymentMethodDataPromptPayParams struct{} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type TestHelpersConfirmationTokenPaymentMethodDataRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. +type TestHelpersConfirmationTokenPaymentMethodDataRevolutPayParams struct{} + +// If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. +type TestHelpersConfirmationTokenPaymentMethodDataSamsungPayParams struct{} + +// If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. +type TestHelpersConfirmationTokenPaymentMethodDataSatispayParams struct{} + +// If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. +type TestHelpersConfirmationTokenPaymentMethodDataSEPADebitParams struct { + // IBAN of the bank account. + IBAN *string `form:"iban"` +} + +// If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. +type TestHelpersConfirmationTokenPaymentMethodDataSofortParams struct { + // Two-letter ISO code representing the country the bank account is located in. + Country *string `form:"country"` +} + +// If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. +type TestHelpersConfirmationTokenPaymentMethodDataSwishParams struct{} + +// If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. +type TestHelpersConfirmationTokenPaymentMethodDataTWINTParams struct{} + +// If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. +type TestHelpersConfirmationTokenPaymentMethodDataUSBankAccountParams struct { + // Account holder type: individual or company. + AccountHolderType *string `form:"account_holder_type"` + // Account number of the bank account. + AccountNumber *string `form:"account_number"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType *string `form:"account_type"` + // The ID of a Financial Connections Account to use as a payment method. + FinancialConnectionsAccount *string `form:"financial_connections_account"` + // Routing number of the bank account. + RoutingNumber *string `form:"routing_number"` +} + +// If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. +type TestHelpersConfirmationTokenPaymentMethodDataWeChatPayParams struct{} + +// If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. +type TestHelpersConfirmationTokenPaymentMethodDataZipParams struct{} + +// If provided, this hash will be used to create a PaymentMethod. +type TestHelpersConfirmationTokenPaymentMethodDataParams struct { + // If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + ACSSDebit *TestHelpersConfirmationTokenPaymentMethodDataACSSDebitParams `form:"acss_debit"` + // If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + Affirm *TestHelpersConfirmationTokenPaymentMethodDataAffirmParams `form:"affirm"` + // If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + AfterpayClearpay *TestHelpersConfirmationTokenPaymentMethodDataAfterpayClearpayParams `form:"afterpay_clearpay"` + // If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + Alipay *TestHelpersConfirmationTokenPaymentMethodDataAlipayParams `form:"alipay"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to `unspecified`. + AllowRedisplay *string `form:"allow_redisplay"` + // If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. + Alma *TestHelpersConfirmationTokenPaymentMethodDataAlmaParams `form:"alma"` + // If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. + AmazonPay *TestHelpersConfirmationTokenPaymentMethodDataAmazonPayParams `form:"amazon_pay"` + // If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + AUBECSDebit *TestHelpersConfirmationTokenPaymentMethodDataAUBECSDebitParams `form:"au_becs_debit"` + // If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + BACSDebit *TestHelpersConfirmationTokenPaymentMethodDataBACSDebitParams `form:"bacs_debit"` + // If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + Bancontact *TestHelpersConfirmationTokenPaymentMethodDataBancontactParams `form:"bancontact"` + // If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. + Billie *TestHelpersConfirmationTokenPaymentMethodDataBillieParams `form:"billie"` + // Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + BillingDetails *TestHelpersConfirmationTokenPaymentMethodDataBillingDetailsParams `form:"billing_details"` + // If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + BLIK *TestHelpersConfirmationTokenPaymentMethodDataBLIKParams `form:"blik"` + // If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + Boleto *TestHelpersConfirmationTokenPaymentMethodDataBoletoParams `form:"boleto"` + // If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + CashApp *TestHelpersConfirmationTokenPaymentMethodDataCashAppParams `form:"cashapp"` + // If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. + Crypto *TestHelpersConfirmationTokenPaymentMethodDataCryptoParams `form:"crypto"` + // If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + CustomerBalance *TestHelpersConfirmationTokenPaymentMethodDataCustomerBalanceParams `form:"customer_balance"` + // If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + EPS *TestHelpersConfirmationTokenPaymentMethodDataEPSParams `form:"eps"` + // If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + FPX *TestHelpersConfirmationTokenPaymentMethodDataFPXParams `form:"fpx"` + // If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + Giropay *TestHelpersConfirmationTokenPaymentMethodDataGiropayParams `form:"giropay"` + // If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + Grabpay *TestHelpersConfirmationTokenPaymentMethodDataGrabpayParams `form:"grabpay"` + // If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + IDEAL *TestHelpersConfirmationTokenPaymentMethodDataIDEALParams `form:"ideal"` + // If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + InteracPresent *TestHelpersConfirmationTokenPaymentMethodDataInteracPresentParams `form:"interac_present"` + // If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. + KakaoPay *TestHelpersConfirmationTokenPaymentMethodDataKakaoPayParams `form:"kakao_pay"` + // If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + Klarna *TestHelpersConfirmationTokenPaymentMethodDataKlarnaParams `form:"klarna"` + // If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + Konbini *TestHelpersConfirmationTokenPaymentMethodDataKonbiniParams `form:"konbini"` + // If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. + KrCard *TestHelpersConfirmationTokenPaymentMethodDataKrCardParams `form:"kr_card"` + // If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + Link *TestHelpersConfirmationTokenPaymentMethodDataLinkParams `form:"link"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. + Mobilepay *TestHelpersConfirmationTokenPaymentMethodDataMobilepayParams `form:"mobilepay"` + // If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. + Multibanco *TestHelpersConfirmationTokenPaymentMethodDataMultibancoParams `form:"multibanco"` + // If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. + NaverPay *TestHelpersConfirmationTokenPaymentMethodDataNaverPayParams `form:"naver_pay"` + // If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. + NzBankAccount *TestHelpersConfirmationTokenPaymentMethodDataNzBankAccountParams `form:"nz_bank_account"` + // If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + OXXO *TestHelpersConfirmationTokenPaymentMethodDataOXXOParams `form:"oxxo"` + // If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + P24 *TestHelpersConfirmationTokenPaymentMethodDataP24Params `form:"p24"` + // If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. + PayByBank *TestHelpersConfirmationTokenPaymentMethodDataPayByBankParams `form:"pay_by_bank"` + // If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. + Payco *TestHelpersConfirmationTokenPaymentMethodDataPaycoParams `form:"payco"` + // If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + PayNow *TestHelpersConfirmationTokenPaymentMethodDataPayNowParams `form:"paynow"` + // If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + Paypal *TestHelpersConfirmationTokenPaymentMethodDataPaypalParams `form:"paypal"` + // If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + Pix *TestHelpersConfirmationTokenPaymentMethodDataPixParams `form:"pix"` + // If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + PromptPay *TestHelpersConfirmationTokenPaymentMethodDataPromptPayParams `form:"promptpay"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *TestHelpersConfirmationTokenPaymentMethodDataRadarOptionsParams `form:"radar_options"` + // If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + RevolutPay *TestHelpersConfirmationTokenPaymentMethodDataRevolutPayParams `form:"revolut_pay"` + // If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. + SamsungPay *TestHelpersConfirmationTokenPaymentMethodDataSamsungPayParams `form:"samsung_pay"` + // If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. + Satispay *TestHelpersConfirmationTokenPaymentMethodDataSatispayParams `form:"satispay"` + // If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + SEPADebit *TestHelpersConfirmationTokenPaymentMethodDataSEPADebitParams `form:"sepa_debit"` + // If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + Sofort *TestHelpersConfirmationTokenPaymentMethodDataSofortParams `form:"sofort"` + // If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. + Swish *TestHelpersConfirmationTokenPaymentMethodDataSwishParams `form:"swish"` + // If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. + TWINT *TestHelpersConfirmationTokenPaymentMethodDataTWINTParams `form:"twint"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type *string `form:"type"` + // If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + USBankAccount *TestHelpersConfirmationTokenPaymentMethodDataUSBankAccountParams `form:"us_bank_account"` + // If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + WeChatPay *TestHelpersConfirmationTokenPaymentMethodDataWeChatPayParams `form:"wechat_pay"` + // If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + Zip *TestHelpersConfirmationTokenPaymentMethodDataZipParams `form:"zip"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TestHelpersConfirmationTokenPaymentMethodDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The selected installment plan to use for this payment attempt. +// This parameter can only be provided during confirmation. +type TestHelpersConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanParams struct { + // For `fixed_count` installment plans, this is required. It represents the number of installment payments your customer will make to their credit card. + Count *int64 `form:"count"` + // For `fixed_count` installment plans, this is required. It represents the interval between installment payments your customer will make to their credit card. + // One of `month`. + Interval *string `form:"interval"` + // Type of installment plan, one of `fixed_count`, `bonus`, or `revolving`. + Type *string `form:"type"` +} + +// Installment configuration for payments confirmed using this ConfirmationToken. +type TestHelpersConfirmationTokenPaymentMethodOptionsCardInstallmentsParams struct { + // The selected installment plan to use for this payment attempt. + // This parameter can only be provided during confirmation. + Plan *TestHelpersConfirmationTokenPaymentMethodOptionsCardInstallmentsPlanParams `form:"plan"` +} + +// Configuration for any card payments confirmed using this ConfirmationToken. +type TestHelpersConfirmationTokenPaymentMethodOptionsCardParams struct { + // Installment configuration for payments confirmed using this ConfirmationToken. + Installments *TestHelpersConfirmationTokenPaymentMethodOptionsCardInstallmentsParams `form:"installments"` +} + +// Payment-method-specific configuration for this ConfirmationToken. +type TestHelpersConfirmationTokenPaymentMethodOptionsParams struct { + // Configuration for any card payments confirmed using this ConfirmationToken. + Card *TestHelpersConfirmationTokenPaymentMethodOptionsCardParams `form:"card"` +} + +// Shipping information for this ConfirmationToken. +type TestHelpersConfirmationTokenShippingParams struct { + // Shipping address + Address *AddressParams `form:"address"` + // Recipient name. + Name *string `form:"name"` + // Recipient phone (including extension) + Phone *string `form:"phone"` +} + +// Creates a test mode Confirmation Token server side for your integration tests. +type TestHelpersConfirmationTokenParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // ID of an existing PaymentMethod. + PaymentMethod *string `form:"payment_method"` + // If provided, this hash will be used to create a PaymentMethod. + PaymentMethodData *TestHelpersConfirmationTokenPaymentMethodDataParams `form:"payment_method_data"` + // Payment-method-specific configuration for this ConfirmationToken. + PaymentMethodOptions *TestHelpersConfirmationTokenPaymentMethodOptionsParams `form:"payment_method_options"` + // Return URL used to confirm the Intent. + ReturnURL *string `form:"return_url"` + // Indicates that you intend to make future payments with this ConfirmationToken's payment method. + // + // The presence of this property will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. + SetupFutureUsage *string `form:"setup_future_usage"` + // Shipping information for this ConfirmationToken. + Shipping *TestHelpersConfirmationTokenShippingParams `form:"shipping"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersConfirmationTokenParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataACSSDebitParams struct { + // Customer's bank account number. + AccountNumber *string `form:"account_number"` + // Institution number of the customer's bank. + InstitutionNumber *string `form:"institution_number"` + // Transit number of the customer's bank. + TransitNumber *string `form:"transit_number"` +} + +// If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataAffirmParams struct{} + +// If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataAfterpayClearpayParams struct{} + +// If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataAlipayParams struct{} + +// If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataAlmaParams struct{} + +// If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataAmazonPayParams struct{} + +// If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. +type TestHelpersConfirmationTokenCreatePaymentMethodDataAUBECSDebitParams struct { + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // Bank-State-Branch number of the bank account. + BSBNumber *string `form:"bsb_number"` +} + +// If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. +type TestHelpersConfirmationTokenCreatePaymentMethodDataBACSDebitParams struct { + // Account number of the bank account that the funds will be debited from. + AccountNumber *string `form:"account_number"` + // Sort code of the bank account. (e.g., `10-20-30`) + SortCode *string `form:"sort_code"` +} + +// If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataBancontactParams struct{} + +// If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataBillieParams struct{} + +// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. +type TestHelpersConfirmationTokenCreatePaymentMethodDataBillingDetailsParams struct { + // Billing address. + Address *AddressParams `form:"address"` + // Email address. + Email *string `form:"email"` + // Full name. + Name *string `form:"name"` + // Billing phone number (including extension). + Phone *string `form:"phone"` + // Taxpayer identification number. Used only for transactions between LATAM buyers and non-LATAM sellers. + TaxID *string `form:"tax_id"` +} + +// If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataBLIKParams struct{} + +// If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataBoletoParams struct { + // The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + TaxID *string `form:"tax_id"` +} + +// If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataCashAppParams struct{} + +// If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataCryptoParams struct{} + +// If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataCustomerBalanceParams struct{} + +// If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataEPSParams struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataFPXParams struct { + // Account holder type for FPX transaction + AccountHolderType *string `form:"account_holder_type"` + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataGiropayParams struct{} + +// If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataGrabpayParams struct{} + +// If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataIDEALParams struct { + // The customer's bank. Only use this parameter for existing customers. Don't use it for new customers. + Bank *string `form:"bank"` +} + +// If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataInteracPresentParams struct{} + +// If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataKakaoPayParams struct{} + +// Customer's date of birth +type TestHelpersConfirmationTokenCreatePaymentMethodDataKlarnaDOBParams struct { + // The day of birth, between 1 and 31. + Day *int64 `form:"day"` + // The month of birth, between 1 and 12. + Month *int64 `form:"month"` + // The four-digit year of birth. + Year *int64 `form:"year"` +} + +// If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataKlarnaParams struct { + // Customer's date of birth + DOB *TestHelpersConfirmationTokenCreatePaymentMethodDataKlarnaDOBParams `form:"dob"` +} + +// If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataKonbiniParams struct{} + +// If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataKrCardParams struct{} + +// If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataLinkParams struct{} + +// If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataMobilepayParams struct{} + +// If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataMultibancoParams struct{} + +// If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataNaverPayParams struct { + // Whether to use Naver Pay points or a card to fund this transaction. If not provided, this defaults to `card`. + Funding *string `form:"funding"` +} + +// If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataNzBankAccountParams struct { + // The name on the bank account. Only required if the account holder name is different from the name of the authorized signatory collected in the PaymentMethod's billing details. + AccountHolderName *string `form:"account_holder_name"` + // The account number for the bank account. + AccountNumber *string `form:"account_number"` + // The numeric code for the bank account's bank. + BankCode *string `form:"bank_code"` + // The numeric code for the bank account's bank branch. + BranchCode *string `form:"branch_code"` + Reference *string `form:"reference"` + // The suffix of the bank account number. + Suffix *string `form:"suffix"` +} + +// If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataOXXOParams struct{} + +// If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataP24Params struct { + // The customer's bank. + Bank *string `form:"bank"` +} + +// If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataPayByBankParams struct{} + +// If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataPaycoParams struct{} + +// If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataPayNowParams struct{} + +// If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataPaypalParams struct{} + +// If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataPixParams struct{} + +// If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataPromptPayParams struct{} + +// Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. +type TestHelpersConfirmationTokenCreatePaymentMethodDataRadarOptionsParams struct { + // A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + Session *string `form:"session"` +} + +// If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataRevolutPayParams struct{} + +// If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataSamsungPayParams struct{} + +// If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataSatispayParams struct{} + +// If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. +type TestHelpersConfirmationTokenCreatePaymentMethodDataSEPADebitParams struct { + // IBAN of the bank account. + IBAN *string `form:"iban"` +} + +// If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataSofortParams struct { + // Two-letter ISO code representing the country the bank account is located in. + Country *string `form:"country"` +} + +// If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataSwishParams struct{} + +// If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataTWINTParams struct{} + +// If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataUSBankAccountParams struct { + // Account holder type: individual or company. + AccountHolderType *string `form:"account_holder_type"` + // Account number of the bank account. + AccountNumber *string `form:"account_number"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType *string `form:"account_type"` + // The ID of a Financial Connections Account to use as a payment method. + FinancialConnectionsAccount *string `form:"financial_connections_account"` + // Routing number of the bank account. + RoutingNumber *string `form:"routing_number"` +} + +// If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataWeChatPayParams struct{} + +// If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. +type TestHelpersConfirmationTokenCreatePaymentMethodDataZipParams struct{} + +// If provided, this hash will be used to create a PaymentMethod. +type TestHelpersConfirmationTokenCreatePaymentMethodDataParams struct { + // If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + ACSSDebit *TestHelpersConfirmationTokenCreatePaymentMethodDataACSSDebitParams `form:"acss_debit"` + // If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + Affirm *TestHelpersConfirmationTokenCreatePaymentMethodDataAffirmParams `form:"affirm"` + // If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + AfterpayClearpay *TestHelpersConfirmationTokenCreatePaymentMethodDataAfterpayClearpayParams `form:"afterpay_clearpay"` + // If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + Alipay *TestHelpersConfirmationTokenCreatePaymentMethodDataAlipayParams `form:"alipay"` + // This field indicates whether this payment method can be shown again to its customer in a checkout flow. Stripe products such as Checkout and Elements use this field to determine whether a payment method can be shown as a saved payment method in a checkout flow. The field defaults to `unspecified`. + AllowRedisplay *string `form:"allow_redisplay"` + // If this is a Alma PaymentMethod, this hash contains details about the Alma payment method. + Alma *TestHelpersConfirmationTokenCreatePaymentMethodDataAlmaParams `form:"alma"` + // If this is a AmazonPay PaymentMethod, this hash contains details about the AmazonPay payment method. + AmazonPay *TestHelpersConfirmationTokenCreatePaymentMethodDataAmazonPayParams `form:"amazon_pay"` + // If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + AUBECSDebit *TestHelpersConfirmationTokenCreatePaymentMethodDataAUBECSDebitParams `form:"au_becs_debit"` + // If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + BACSDebit *TestHelpersConfirmationTokenCreatePaymentMethodDataBACSDebitParams `form:"bacs_debit"` + // If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + Bancontact *TestHelpersConfirmationTokenCreatePaymentMethodDataBancontactParams `form:"bancontact"` + // If this is a `billie` PaymentMethod, this hash contains details about the Billie payment method. + Billie *TestHelpersConfirmationTokenCreatePaymentMethodDataBillieParams `form:"billie"` + // Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + BillingDetails *TestHelpersConfirmationTokenCreatePaymentMethodDataBillingDetailsParams `form:"billing_details"` + // If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + BLIK *TestHelpersConfirmationTokenCreatePaymentMethodDataBLIKParams `form:"blik"` + // If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + Boleto *TestHelpersConfirmationTokenCreatePaymentMethodDataBoletoParams `form:"boleto"` + // If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + CashApp *TestHelpersConfirmationTokenCreatePaymentMethodDataCashAppParams `form:"cashapp"` + // If this is a Crypto PaymentMethod, this hash contains details about the Crypto payment method. + Crypto *TestHelpersConfirmationTokenCreatePaymentMethodDataCryptoParams `form:"crypto"` + // If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + CustomerBalance *TestHelpersConfirmationTokenCreatePaymentMethodDataCustomerBalanceParams `form:"customer_balance"` + // If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + EPS *TestHelpersConfirmationTokenCreatePaymentMethodDataEPSParams `form:"eps"` + // If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + FPX *TestHelpersConfirmationTokenCreatePaymentMethodDataFPXParams `form:"fpx"` + // If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + Giropay *TestHelpersConfirmationTokenCreatePaymentMethodDataGiropayParams `form:"giropay"` + // If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + Grabpay *TestHelpersConfirmationTokenCreatePaymentMethodDataGrabpayParams `form:"grabpay"` + // If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + IDEAL *TestHelpersConfirmationTokenCreatePaymentMethodDataIDEALParams `form:"ideal"` + // If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + InteracPresent *TestHelpersConfirmationTokenCreatePaymentMethodDataInteracPresentParams `form:"interac_present"` + // If this is a `kakao_pay` PaymentMethod, this hash contains details about the Kakao Pay payment method. + KakaoPay *TestHelpersConfirmationTokenCreatePaymentMethodDataKakaoPayParams `form:"kakao_pay"` + // If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + Klarna *TestHelpersConfirmationTokenCreatePaymentMethodDataKlarnaParams `form:"klarna"` + // If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + Konbini *TestHelpersConfirmationTokenCreatePaymentMethodDataKonbiniParams `form:"konbini"` + // If this is a `kr_card` PaymentMethod, this hash contains details about the Korean Card payment method. + KrCard *TestHelpersConfirmationTokenCreatePaymentMethodDataKrCardParams `form:"kr_card"` + // If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + Link *TestHelpersConfirmationTokenCreatePaymentMethodDataLinkParams `form:"link"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // If this is a `mobilepay` PaymentMethod, this hash contains details about the MobilePay payment method. + Mobilepay *TestHelpersConfirmationTokenCreatePaymentMethodDataMobilepayParams `form:"mobilepay"` + // If this is a `multibanco` PaymentMethod, this hash contains details about the Multibanco payment method. + Multibanco *TestHelpersConfirmationTokenCreatePaymentMethodDataMultibancoParams `form:"multibanco"` + // If this is a `naver_pay` PaymentMethod, this hash contains details about the Naver Pay payment method. + NaverPay *TestHelpersConfirmationTokenCreatePaymentMethodDataNaverPayParams `form:"naver_pay"` + // If this is an nz_bank_account PaymentMethod, this hash contains details about the nz_bank_account payment method. + NzBankAccount *TestHelpersConfirmationTokenCreatePaymentMethodDataNzBankAccountParams `form:"nz_bank_account"` + // If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + OXXO *TestHelpersConfirmationTokenCreatePaymentMethodDataOXXOParams `form:"oxxo"` + // If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + P24 *TestHelpersConfirmationTokenCreatePaymentMethodDataP24Params `form:"p24"` + // If this is a `pay_by_bank` PaymentMethod, this hash contains details about the PayByBank payment method. + PayByBank *TestHelpersConfirmationTokenCreatePaymentMethodDataPayByBankParams `form:"pay_by_bank"` + // If this is a `payco` PaymentMethod, this hash contains details about the PAYCO payment method. + Payco *TestHelpersConfirmationTokenCreatePaymentMethodDataPaycoParams `form:"payco"` + // If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + PayNow *TestHelpersConfirmationTokenCreatePaymentMethodDataPayNowParams `form:"paynow"` + // If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + Paypal *TestHelpersConfirmationTokenCreatePaymentMethodDataPaypalParams `form:"paypal"` + // If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + Pix *TestHelpersConfirmationTokenCreatePaymentMethodDataPixParams `form:"pix"` + // If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + PromptPay *TestHelpersConfirmationTokenCreatePaymentMethodDataPromptPayParams `form:"promptpay"` + // Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + RadarOptions *TestHelpersConfirmationTokenCreatePaymentMethodDataRadarOptionsParams `form:"radar_options"` + // If this is a `revolut_pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + RevolutPay *TestHelpersConfirmationTokenCreatePaymentMethodDataRevolutPayParams `form:"revolut_pay"` + // If this is a `samsung_pay` PaymentMethod, this hash contains details about the SamsungPay payment method. + SamsungPay *TestHelpersConfirmationTokenCreatePaymentMethodDataSamsungPayParams `form:"samsung_pay"` + // If this is a `satispay` PaymentMethod, this hash contains details about the Satispay payment method. + Satispay *TestHelpersConfirmationTokenCreatePaymentMethodDataSatispayParams `form:"satispay"` + // If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + SEPADebit *TestHelpersConfirmationTokenCreatePaymentMethodDataSEPADebitParams `form:"sepa_debit"` + // If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + Sofort *TestHelpersConfirmationTokenCreatePaymentMethodDataSofortParams `form:"sofort"` + // If this is a `swish` PaymentMethod, this hash contains details about the Swish payment method. + Swish *TestHelpersConfirmationTokenCreatePaymentMethodDataSwishParams `form:"swish"` + // If this is a TWINT PaymentMethod, this hash contains details about the TWINT payment method. + TWINT *TestHelpersConfirmationTokenCreatePaymentMethodDataTWINTParams `form:"twint"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type *string `form:"type"` + // If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + USBankAccount *TestHelpersConfirmationTokenCreatePaymentMethodDataUSBankAccountParams `form:"us_bank_account"` + // If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + WeChatPay *TestHelpersConfirmationTokenCreatePaymentMethodDataWeChatPayParams `form:"wechat_pay"` + // If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + Zip *TestHelpersConfirmationTokenCreatePaymentMethodDataZipParams `form:"zip"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TestHelpersConfirmationTokenCreatePaymentMethodDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// The selected installment plan to use for this payment attempt. +// This parameter can only be provided during confirmation. +type TestHelpersConfirmationTokenCreatePaymentMethodOptionsCardInstallmentsPlanParams struct { + // For `fixed_count` installment plans, this is required. It represents the number of installment payments your customer will make to their credit card. + Count *int64 `form:"count"` + // For `fixed_count` installment plans, this is required. It represents the interval between installment payments your customer will make to their credit card. + // One of `month`. + Interval *string `form:"interval"` + // Type of installment plan, one of `fixed_count`, `bonus`, or `revolving`. + Type *string `form:"type"` +} + +// Installment configuration for payments confirmed using this ConfirmationToken. +type TestHelpersConfirmationTokenCreatePaymentMethodOptionsCardInstallmentsParams struct { + // The selected installment plan to use for this payment attempt. + // This parameter can only be provided during confirmation. + Plan *TestHelpersConfirmationTokenCreatePaymentMethodOptionsCardInstallmentsPlanParams `form:"plan"` +} + +// Configuration for any card payments confirmed using this ConfirmationToken. +type TestHelpersConfirmationTokenCreatePaymentMethodOptionsCardParams struct { + // Installment configuration for payments confirmed using this ConfirmationToken. + Installments *TestHelpersConfirmationTokenCreatePaymentMethodOptionsCardInstallmentsParams `form:"installments"` +} + +// Payment-method-specific configuration for this ConfirmationToken. +type TestHelpersConfirmationTokenCreatePaymentMethodOptionsParams struct { + // Configuration for any card payments confirmed using this ConfirmationToken. + Card *TestHelpersConfirmationTokenCreatePaymentMethodOptionsCardParams `form:"card"` +} + +// Shipping information for this ConfirmationToken. +type TestHelpersConfirmationTokenCreateShippingParams struct { + // Shipping address + Address *AddressParams `form:"address"` + // Recipient name. + Name *string `form:"name"` + // Recipient phone (including extension) + Phone *string `form:"phone"` +} + +// Creates a test mode Confirmation Token server side for your integration tests. +type TestHelpersConfirmationTokenCreateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // ID of an existing PaymentMethod. + PaymentMethod *string `form:"payment_method"` + // If provided, this hash will be used to create a PaymentMethod. + PaymentMethodData *TestHelpersConfirmationTokenCreatePaymentMethodDataParams `form:"payment_method_data"` + // Payment-method-specific configuration for this ConfirmationToken. + PaymentMethodOptions *TestHelpersConfirmationTokenCreatePaymentMethodOptionsParams `form:"payment_method_options"` + // Return URL used to confirm the Intent. + ReturnURL *string `form:"return_url"` + // Indicates that you intend to make future payments with this ConfirmationToken's payment method. + // + // The presence of this property will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. + SetupFutureUsage *string `form:"setup_future_usage"` + // Shipping information for this ConfirmationToken. + Shipping *TestHelpersConfirmationTokenCreateShippingParams `form:"shipping"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersConfirmationTokenCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpers_confirmationtoken_service.go b/vendor/github.com/stripe/stripe-go/v82/testhelpers_confirmationtoken_service.go new file mode 100644 index 00000000..e73269a1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpers_confirmationtoken_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TestHelpersConfirmationTokenService is used to invoke /v1/confirmation_tokens APIs. +type v1TestHelpersConfirmationTokenService struct { + B Backend + Key string +} + +// Creates a test mode Confirmation Token server side for your integration tests. +func (c v1TestHelpersConfirmationTokenService) Create(ctx context.Context, params *TestHelpersConfirmationTokenCreateParams) (*ConfirmationToken, error) { + if params == nil { + params = &TestHelpersConfirmationTokenCreateParams{} + } + params.Context = ctx + confirmationtoken := &ConfirmationToken{} + err := c.B.Call( + http.MethodPost, "/v1/test_helpers/confirmation_tokens", c.Key, params, confirmationtoken) + return confirmationtoken, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpers_customer.go b/vendor/github.com/stripe/stripe-go/v82/testhelpers_customer.go new file mode 100644 index 00000000..dc6b7de6 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpers_customer.go @@ -0,0 +1,25 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Create an incoming testmode bank transfer +type TestHelpersCustomerFundCashBalanceParams struct { + Params `form:"*"` + // Amount to be used for this test cash balance transaction. A positive integer representing how much to fund in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to fund $1.00 or 100 to fund ¥100, a zero-decimal currency). + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A description of the test funding. This simulates free-text references supplied by customers when making bank transfers to their cash balance. You can use this to test how Stripe's [reconciliation algorithm](https://stripe.com/docs/payments/customer-balance/reconciliation) applies to different user inputs. + Reference *string `form:"reference"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersCustomerFundCashBalanceParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpers_customer_service.go b/vendor/github.com/stripe/stripe-go/v82/testhelpers_customer_service.go new file mode 100644 index 00000000..a0419761 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpers_customer_service.go @@ -0,0 +1,31 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TestHelpersCustomerService is used to invoke /v1/customers APIs. +type v1TestHelpersCustomerService struct { + B Backend + Key string +} + +// Create an incoming testmode bank transfer +func (c v1TestHelpersCustomerService) FundCashBalance(ctx context.Context, id string, params *TestHelpersCustomerFundCashBalanceParams) (*CustomerCashBalanceTransaction, error) { + if params == nil { + params = &TestHelpersCustomerFundCashBalanceParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/test_helpers/customers/%s/fund_cash_balance", id) + customercashbalancetransaction := &CustomerCashBalanceTransaction{} + err := c.B.Call( + http.MethodPost, path, c.Key, params, customercashbalancetransaction) + return customercashbalancetransaction, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpers_refund.go b/vendor/github.com/stripe/stripe-go/v82/testhelpers_refund.go new file mode 100644 index 00000000..fbba1dd2 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpers_refund.go @@ -0,0 +1,19 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Expire a refund with a status of requires_action. +type TestHelpersRefundExpireParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersRefundExpireParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpers_refund_service.go b/vendor/github.com/stripe/stripe-go/v82/testhelpers_refund_service.go new file mode 100644 index 00000000..39888f46 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpers_refund_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TestHelpersRefundService is used to invoke /v1/refunds APIs. +type v1TestHelpersRefundService struct { + B Backend + Key string +} + +// Expire a refund with a status of requires_action. +func (c v1TestHelpersRefundService) Expire(ctx context.Context, id string, params *TestHelpersRefundExpireParams) (*Refund, error) { + if params == nil { + params = &TestHelpersRefundExpireParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/test_helpers/refunds/%s/expire", id) + refund := &Refund{} + err := c.B.Call(http.MethodPost, path, c.Key, params, refund) + return refund, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpers_testclock.go b/vendor/github.com/stripe/stripe-go/v82/testhelpers_testclock.go new file mode 100644 index 00000000..c7dd912a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpers_testclock.go @@ -0,0 +1,153 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The status of the Test Clock. +type TestHelpersTestClockStatus string + +// List of values that TestHelpersTestClockStatus can take +const ( + TestHelpersTestClockStatusAdvancing TestHelpersTestClockStatus = "advancing" + TestHelpersTestClockStatusInternalFailure TestHelpersTestClockStatus = "internal_failure" + TestHelpersTestClockStatusReady TestHelpersTestClockStatus = "ready" +) + +// Deletes a test clock. +type TestHelpersTestClockParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The initial frozen time for this test clock. + FrozenTime *int64 `form:"frozen_time"` + // The name for this test clock. + Name *string `form:"name"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTestClockParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Returns a list of your test clocks. +type TestHelpersTestClockListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTestClockListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Starts advancing a test clock to a specified time in the future. Advancement is done when status changes to Ready. +type TestHelpersTestClockAdvanceParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The time to advance the test clock. Must be after the test clock's current frozen time. Cannot be more than two intervals in the future from the shortest subscription in this test clock. If there are no subscriptions in this test clock, it cannot be more than two years in the future. + FrozenTime *int64 `form:"frozen_time"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTestClockAdvanceParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Deletes a test clock. +type TestHelpersTestClockDeleteParams struct { + Params `form:"*"` +} + +// Retrieves a test clock. +type TestHelpersTestClockRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTestClockRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates a new test clock that can be attached to new customers and quotes. +type TestHelpersTestClockCreateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The initial frozen time for this test clock. + FrozenTime *int64 `form:"frozen_time"` + // The name for this test clock. + Name *string `form:"name"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTestClockCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type TestHelpersTestClockStatusDetailsAdvancing struct { + // The `frozen_time` that the Test Clock is advancing towards. + TargetFrozenTime int64 `json:"target_frozen_time"` +} +type TestHelpersTestClockStatusDetails struct { + Advancing *TestHelpersTestClockStatusDetailsAdvancing `json:"advancing"` +} + +// A test clock enables deterministic control over objects in testmode. With a test clock, you can create +// objects at a frozen time in the past or future, and advance to a specific future time to observe webhooks and state changes. After the clock advances, +// you can either validate the current state of your scenario (and test your assumptions), change the current state of your scenario (and test more complex scenarios), or keep advancing forward in time. +type TestHelpersTestClock struct { + APIResource + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + Deleted bool `json:"deleted"` + // Time at which this clock is scheduled to auto delete. + DeletesAfter int64 `json:"deletes_after"` + // Time at which all objects belonging to this clock are frozen. + FrozenTime int64 `json:"frozen_time"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // The custom name supplied at creation. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The status of the Test Clock. + Status TestHelpersTestClockStatus `json:"status"` + StatusDetails *TestHelpersTestClockStatusDetails `json:"status_details"` +} + +// TestHelpersTestClockList is a list of TestClocks as retrieved from a list endpoint. +type TestHelpersTestClockList struct { + APIResource + ListMeta + Data []*TestHelpersTestClock `json:"data"` +} + +// UnmarshalJSON handles deserialization of a TestHelpersTestClock. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (t *TestHelpersTestClock) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + t.ID = id + return nil + } + + type testHelpersTestClock TestHelpersTestClock + var v testHelpersTestClock + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *t = TestHelpersTestClock(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpers_testclock_service.go b/vendor/github.com/stripe/stripe-go/v82/testhelpers_testclock_service.go new file mode 100644 index 00000000..32a473e3 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpers_testclock_service.go @@ -0,0 +1,85 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TestHelpersTestClockService is used to invoke /v1/test_helpers/test_clocks APIs. +type v1TestHelpersTestClockService struct { + B Backend + Key string +} + +// Creates a new test clock that can be attached to new customers and quotes. +func (c v1TestHelpersTestClockService) Create(ctx context.Context, params *TestHelpersTestClockCreateParams) (*TestHelpersTestClock, error) { + if params == nil { + params = &TestHelpersTestClockCreateParams{} + } + params.Context = ctx + testclock := &TestHelpersTestClock{} + err := c.B.Call( + http.MethodPost, "/v1/test_helpers/test_clocks", c.Key, params, testclock) + return testclock, err +} + +// Retrieves a test clock. +func (c v1TestHelpersTestClockService) Retrieve(ctx context.Context, id string, params *TestHelpersTestClockRetrieveParams) (*TestHelpersTestClock, error) { + if params == nil { + params = &TestHelpersTestClockRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/test_helpers/test_clocks/%s", id) + testclock := &TestHelpersTestClock{} + err := c.B.Call(http.MethodGet, path, c.Key, params, testclock) + return testclock, err +} + +// Deletes a test clock. +func (c v1TestHelpersTestClockService) Delete(ctx context.Context, id string, params *TestHelpersTestClockDeleteParams) (*TestHelpersTestClock, error) { + if params == nil { + params = &TestHelpersTestClockDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/test_helpers/test_clocks/%s", id) + testclock := &TestHelpersTestClock{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, testclock) + return testclock, err +} + +// Starts advancing a test clock to a specified time in the future. Advancement is done when status changes to Ready. +func (c v1TestHelpersTestClockService) Advance(ctx context.Context, id string, params *TestHelpersTestClockAdvanceParams) (*TestHelpersTestClock, error) { + if params == nil { + params = &TestHelpersTestClockAdvanceParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/test_helpers/test_clocks/%s/advance", id) + testclock := &TestHelpersTestClock{} + err := c.B.Call(http.MethodPost, path, c.Key, params, testclock) + return testclock, err +} + +// Returns a list of your test clocks. +func (c v1TestHelpersTestClockService) List(ctx context.Context, listParams *TestHelpersTestClockListParams) Seq2[*TestHelpersTestClock, error] { + if listParams == nil { + listParams = &TestHelpersTestClockListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TestHelpersTestClock, ListContainer, error) { + list := &TestHelpersTestClockList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/test_helpers/test_clocks", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_authorization.go b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_authorization.go new file mode 100644 index 00000000..1fcf260f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_authorization.go @@ -0,0 +1,653 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Detailed breakdown of amount components. These amounts are denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). +type TestHelpersIssuingAuthorizationAmountDetailsParams struct { + // The ATM withdrawal fee. + ATMFee *int64 `form:"atm_fee"` + // The amount of cash requested by the cardholder. + CashbackAmount *int64 `form:"cashback_amount"` +} + +// Answers to prompts presented to the cardholder at the point of sale. Prompted fields vary depending on the configuration of your physical fleet cards. Typical points of sale support only numeric entry. +type TestHelpersIssuingAuthorizationFleetCardholderPromptDataParams struct { + // Driver ID. + DriverID *string `form:"driver_id"` + // Odometer reading. + Odometer *int64 `form:"odometer"` + // An alphanumeric ID. This field is used when a vehicle ID, driver ID, or generic ID is entered by the cardholder, but the merchant or card network did not specify the prompt type. + UnspecifiedID *string `form:"unspecified_id"` + // User ID. + UserID *string `form:"user_id"` + // Vehicle number. + VehicleNumber *string `form:"vehicle_number"` +} + +// Breakdown of fuel portion of the purchase. +type TestHelpersIssuingAuthorizationFleetReportedBreakdownFuelParams struct { + // Gross fuel amount that should equal Fuel Volume multipled by Fuel Unit Cost, inclusive of taxes. + GrossAmountDecimal *float64 `form:"gross_amount_decimal,high_precision"` +} + +// Breakdown of non-fuel portion of the purchase. +type TestHelpersIssuingAuthorizationFleetReportedBreakdownNonFuelParams struct { + // Gross non-fuel amount that should equal the sum of the line items, inclusive of taxes. + GrossAmountDecimal *float64 `form:"gross_amount_decimal,high_precision"` +} + +// Information about tax included in this transaction. +type TestHelpersIssuingAuthorizationFleetReportedBreakdownTaxParams struct { + // Amount of state or provincial Sales Tax included in the transaction amount. Null if not reported by merchant or not subject to tax. + LocalAmountDecimal *float64 `form:"local_amount_decimal,high_precision"` + // Amount of national Sales Tax or VAT included in the transaction amount. Null if not reported by merchant or not subject to tax. + NationalAmountDecimal *float64 `form:"national_amount_decimal,high_precision"` +} + +// More information about the total amount. This information is not guaranteed to be accurate as some merchants may provide unreliable data. +type TestHelpersIssuingAuthorizationFleetReportedBreakdownParams struct { + // Breakdown of fuel portion of the purchase. + Fuel *TestHelpersIssuingAuthorizationFleetReportedBreakdownFuelParams `form:"fuel"` + // Breakdown of non-fuel portion of the purchase. + NonFuel *TestHelpersIssuingAuthorizationFleetReportedBreakdownNonFuelParams `form:"non_fuel"` + // Information about tax included in this transaction. + Tax *TestHelpersIssuingAuthorizationFleetReportedBreakdownTaxParams `form:"tax"` +} + +// Fleet-specific information for authorizations using Fleet cards. +type TestHelpersIssuingAuthorizationFleetParams struct { + // Answers to prompts presented to the cardholder at the point of sale. Prompted fields vary depending on the configuration of your physical fleet cards. Typical points of sale support only numeric entry. + CardholderPromptData *TestHelpersIssuingAuthorizationFleetCardholderPromptDataParams `form:"cardholder_prompt_data"` + // The type of purchase. One of `fuel_purchase`, `non_fuel_purchase`, or `fuel_and_non_fuel_purchase`. + PurchaseType *string `form:"purchase_type"` + // More information about the total amount. This information is not guaranteed to be accurate as some merchants may provide unreliable data. + ReportedBreakdown *TestHelpersIssuingAuthorizationFleetReportedBreakdownParams `form:"reported_breakdown"` + // The type of fuel service. One of `non_fuel_transaction`, `full_service`, or `self_service`. + ServiceType *string `form:"service_type"` +} + +// Information about fuel that was purchased with this transaction. +type TestHelpersIssuingAuthorizationFuelParams struct { + // [Conexxus Payment System Product Code](https://www.conexxus.org/conexxus-payment-system-product-codes) identifying the primary fuel product purchased. + IndustryProductCode *string `form:"industry_product_code"` + // The quantity of `unit`s of fuel that was dispensed, represented as a decimal string with at most 12 decimal places. + QuantityDecimal *float64 `form:"quantity_decimal,high_precision"` + // The type of fuel that was purchased. One of `diesel`, `unleaded_plus`, `unleaded_regular`, `unleaded_super`, or `other`. + Type *string `form:"type"` + // The units for `quantity_decimal`. One of `charging_minute`, `imperial_gallon`, `kilogram`, `kilowatt_hour`, `liter`, `pound`, `us_gallon`, or `other`. + Unit *string `form:"unit"` + // The cost in cents per each unit of fuel, represented as a decimal string with at most 12 decimal places. + UnitCostDecimal *float64 `form:"unit_cost_decimal,high_precision"` +} + +// Details about the seller (grocery store, e-commerce website, etc.) where the card authorization happened. +type TestHelpersIssuingAuthorizationMerchantDataParams struct { + // A categorization of the seller's type of business. See our [merchant categories guide](https://stripe.com/docs/issuing/merchant-categories) for a list of possible values. + Category *string `form:"category"` + // City where the seller is located + City *string `form:"city"` + // Country where the seller is located + Country *string `form:"country"` + // Name of the seller + Name *string `form:"name"` + // Identifier assigned to the seller by the card network. Different card networks may assign different network_id fields to the same merchant. + NetworkID *string `form:"network_id"` + // Postal code where the seller is located + PostalCode *string `form:"postal_code"` + // State where the seller is located + State *string `form:"state"` + // An ID assigned by the seller to the location of the sale. + TerminalID *string `form:"terminal_id"` + // URL provided by the merchant on a 3DS request + URL *string `form:"url"` +} + +// Details about the authorization, such as identifiers, set by the card network. +type TestHelpersIssuingAuthorizationNetworkDataParams struct { + // Identifier assigned to the acquirer by the card network. + AcquiringInstitutionID *string `form:"acquiring_institution_id"` +} + +// The exemption applied to this authorization. +type TestHelpersIssuingAuthorizationVerificationDataAuthenticationExemptionParams struct { + // The entity that requested the exemption, either the acquiring merchant or the Issuing user. + ClaimedBy *string `form:"claimed_by"` + // The specific exemption claimed for this authorization. + Type *string `form:"type"` +} + +// 3D Secure details. +type TestHelpersIssuingAuthorizationVerificationDataThreeDSecureParams struct { + // The outcome of the 3D Secure authentication request. + Result *string `form:"result"` +} + +// Verifications that Stripe performed on information that the cardholder provided to the merchant. +type TestHelpersIssuingAuthorizationVerificationDataParams struct { + // Whether the cardholder provided an address first line and if it matched the cardholder's `billing.address.line1`. + AddressLine1Check *string `form:"address_line1_check"` + // Whether the cardholder provided a postal code and if it matched the cardholder's `billing.address.postal_code`. + AddressPostalCodeCheck *string `form:"address_postal_code_check"` + // The exemption applied to this authorization. + AuthenticationExemption *TestHelpersIssuingAuthorizationVerificationDataAuthenticationExemptionParams `form:"authentication_exemption"` + // Whether the cardholder provided a CVC and if it matched Stripe's record. + CVCCheck *string `form:"cvc_check"` + // Whether the cardholder provided an expiry date and if it matched Stripe's record. + ExpiryCheck *string `form:"expiry_check"` + // 3D Secure details. + ThreeDSecure *TestHelpersIssuingAuthorizationVerificationDataThreeDSecureParams `form:"three_d_secure"` +} + +// Create a test-mode authorization. +type TestHelpersIssuingAuthorizationParams struct { + Params `form:"*"` + // The total amount to attempt to authorize. This amount is in the provided currency, or defaults to the card's currency, and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Amount *int64 `form:"amount"` + // Detailed breakdown of amount components. These amounts are denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + AmountDetails *TestHelpersIssuingAuthorizationAmountDetailsParams `form:"amount_details"` + // How the card details were provided. Defaults to online. + AuthorizationMethod *string `form:"authorization_method"` + // Card associated with this authorization. + Card *string `form:"card"` + // The currency of the authorization. If not provided, defaults to the currency of the card. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Fleet-specific information for authorizations using Fleet cards. + Fleet *TestHelpersIssuingAuthorizationFleetParams `form:"fleet"` + // Information about fuel that was purchased with this transaction. + Fuel *TestHelpersIssuingAuthorizationFuelParams `form:"fuel"` + // If set `true`, you may provide [amount](https://stripe.com/docs/api/issuing/authorizations/approve#approve_issuing_authorization-amount) to control how much to hold for the authorization. + IsAmountControllable *bool `form:"is_amount_controllable"` + // The total amount to attempt to authorize. This amount is in the provided merchant currency, and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + MerchantAmount *int64 `form:"merchant_amount"` + // The currency of the authorization. If not provided, defaults to the currency of the card. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + MerchantCurrency *string `form:"merchant_currency"` + // Details about the seller (grocery store, e-commerce website, etc.) where the card authorization happened. + MerchantData *TestHelpersIssuingAuthorizationMerchantDataParams `form:"merchant_data"` + // Details about the authorization, such as identifiers, set by the card network. + NetworkData *TestHelpersIssuingAuthorizationNetworkDataParams `form:"network_data"` + // Verifications that Stripe performed on information that the cardholder provided to the merchant. + VerificationData *TestHelpersIssuingAuthorizationVerificationDataParams `form:"verification_data"` + // The digital wallet used for this transaction. One of `apple_pay`, `google_pay`, or `samsung_pay`. Will populate as `null` when no digital wallet was utilized. + Wallet *string `form:"wallet"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingAuthorizationParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Answers to prompts presented to the cardholder at the point of sale. Prompted fields vary depending on the configuration of your physical fleet cards. Typical points of sale support only numeric entry. +type TestHelpersIssuingAuthorizationCapturePurchaseDetailsFleetCardholderPromptDataParams struct { + // Driver ID. + DriverID *string `form:"driver_id"` + // Odometer reading. + Odometer *int64 `form:"odometer"` + // An alphanumeric ID. This field is used when a vehicle ID, driver ID, or generic ID is entered by the cardholder, but the merchant or card network did not specify the prompt type. + UnspecifiedID *string `form:"unspecified_id"` + // User ID. + UserID *string `form:"user_id"` + // Vehicle number. + VehicleNumber *string `form:"vehicle_number"` +} + +// Breakdown of fuel portion of the purchase. +type TestHelpersIssuingAuthorizationCapturePurchaseDetailsFleetReportedBreakdownFuelParams struct { + // Gross fuel amount that should equal Fuel Volume multipled by Fuel Unit Cost, inclusive of taxes. + GrossAmountDecimal *float64 `form:"gross_amount_decimal,high_precision"` +} + +// Breakdown of non-fuel portion of the purchase. +type TestHelpersIssuingAuthorizationCapturePurchaseDetailsFleetReportedBreakdownNonFuelParams struct { + // Gross non-fuel amount that should equal the sum of the line items, inclusive of taxes. + GrossAmountDecimal *float64 `form:"gross_amount_decimal,high_precision"` +} + +// Information about tax included in this transaction. +type TestHelpersIssuingAuthorizationCapturePurchaseDetailsFleetReportedBreakdownTaxParams struct { + // Amount of state or provincial Sales Tax included in the transaction amount. Null if not reported by merchant or not subject to tax. + LocalAmountDecimal *float64 `form:"local_amount_decimal,high_precision"` + // Amount of national Sales Tax or VAT included in the transaction amount. Null if not reported by merchant or not subject to tax. + NationalAmountDecimal *float64 `form:"national_amount_decimal,high_precision"` +} + +// More information about the total amount. This information is not guaranteed to be accurate as some merchants may provide unreliable data. +type TestHelpersIssuingAuthorizationCapturePurchaseDetailsFleetReportedBreakdownParams struct { + // Breakdown of fuel portion of the purchase. + Fuel *TestHelpersIssuingAuthorizationCapturePurchaseDetailsFleetReportedBreakdownFuelParams `form:"fuel"` + // Breakdown of non-fuel portion of the purchase. + NonFuel *TestHelpersIssuingAuthorizationCapturePurchaseDetailsFleetReportedBreakdownNonFuelParams `form:"non_fuel"` + // Information about tax included in this transaction. + Tax *TestHelpersIssuingAuthorizationCapturePurchaseDetailsFleetReportedBreakdownTaxParams `form:"tax"` +} + +// Fleet-specific information for transactions using Fleet cards. +type TestHelpersIssuingAuthorizationCapturePurchaseDetailsFleetParams struct { + // Answers to prompts presented to the cardholder at the point of sale. Prompted fields vary depending on the configuration of your physical fleet cards. Typical points of sale support only numeric entry. + CardholderPromptData *TestHelpersIssuingAuthorizationCapturePurchaseDetailsFleetCardholderPromptDataParams `form:"cardholder_prompt_data"` + // The type of purchase. One of `fuel_purchase`, `non_fuel_purchase`, or `fuel_and_non_fuel_purchase`. + PurchaseType *string `form:"purchase_type"` + // More information about the total amount. This information is not guaranteed to be accurate as some merchants may provide unreliable data. + ReportedBreakdown *TestHelpersIssuingAuthorizationCapturePurchaseDetailsFleetReportedBreakdownParams `form:"reported_breakdown"` + // The type of fuel service. One of `non_fuel_transaction`, `full_service`, or `self_service`. + ServiceType *string `form:"service_type"` +} + +// The legs of the trip. +type TestHelpersIssuingAuthorizationCapturePurchaseDetailsFlightSegmentParams struct { + // The three-letter IATA airport code of the flight's destination. + ArrivalAirportCode *string `form:"arrival_airport_code"` + // The airline carrier code. + Carrier *string `form:"carrier"` + // The three-letter IATA airport code that the flight departed from. + DepartureAirportCode *string `form:"departure_airport_code"` + // The flight number. + FlightNumber *string `form:"flight_number"` + // The flight's service class. + ServiceClass *string `form:"service_class"` + // Whether a stopover is allowed on this flight. + StopoverAllowed *bool `form:"stopover_allowed"` +} + +// Information about the flight that was purchased with this transaction. +type TestHelpersIssuingAuthorizationCapturePurchaseDetailsFlightParams struct { + // The time that the flight departed. + DepartureAt *int64 `form:"departure_at"` + // The name of the passenger. + PassengerName *string `form:"passenger_name"` + // Whether the ticket is refundable. + Refundable *bool `form:"refundable"` + // The legs of the trip. + Segments []*TestHelpersIssuingAuthorizationCapturePurchaseDetailsFlightSegmentParams `form:"segments"` + // The travel agency that issued the ticket. + TravelAgency *string `form:"travel_agency"` +} + +// Information about fuel that was purchased with this transaction. +type TestHelpersIssuingAuthorizationCapturePurchaseDetailsFuelParams struct { + // [Conexxus Payment System Product Code](https://www.conexxus.org/conexxus-payment-system-product-codes) identifying the primary fuel product purchased. + IndustryProductCode *string `form:"industry_product_code"` + // The quantity of `unit`s of fuel that was dispensed, represented as a decimal string with at most 12 decimal places. + QuantityDecimal *float64 `form:"quantity_decimal,high_precision"` + // The type of fuel that was purchased. One of `diesel`, `unleaded_plus`, `unleaded_regular`, `unleaded_super`, or `other`. + Type *string `form:"type"` + // The units for `quantity_decimal`. One of `charging_minute`, `imperial_gallon`, `kilogram`, `kilowatt_hour`, `liter`, `pound`, `us_gallon`, or `other`. + Unit *string `form:"unit"` + // The cost in cents per each unit of fuel, represented as a decimal string with at most 12 decimal places. + UnitCostDecimal *float64 `form:"unit_cost_decimal,high_precision"` +} + +// Information about lodging that was purchased with this transaction. +type TestHelpersIssuingAuthorizationCapturePurchaseDetailsLodgingParams struct { + // The time of checking into the lodging. + CheckInAt *int64 `form:"check_in_at"` + // The number of nights stayed at the lodging. + Nights *int64 `form:"nights"` +} + +// The line items in the purchase. +type TestHelpersIssuingAuthorizationCapturePurchaseDetailsReceiptParams struct { + Description *string `form:"description"` + Quantity *float64 `form:"quantity,high_precision"` + Total *int64 `form:"total"` + UnitCost *int64 `form:"unit_cost"` +} + +// Additional purchase information that is optionally provided by the merchant. +type TestHelpersIssuingAuthorizationCapturePurchaseDetailsParams struct { + // Fleet-specific information for transactions using Fleet cards. + Fleet *TestHelpersIssuingAuthorizationCapturePurchaseDetailsFleetParams `form:"fleet"` + // Information about the flight that was purchased with this transaction. + Flight *TestHelpersIssuingAuthorizationCapturePurchaseDetailsFlightParams `form:"flight"` + // Information about fuel that was purchased with this transaction. + Fuel *TestHelpersIssuingAuthorizationCapturePurchaseDetailsFuelParams `form:"fuel"` + // Information about lodging that was purchased with this transaction. + Lodging *TestHelpersIssuingAuthorizationCapturePurchaseDetailsLodgingParams `form:"lodging"` + // The line items in the purchase. + Receipt []*TestHelpersIssuingAuthorizationCapturePurchaseDetailsReceiptParams `form:"receipt"` + // A merchant-specific order number. + Reference *string `form:"reference"` +} + +// Capture a test-mode authorization. +type TestHelpersIssuingAuthorizationCaptureParams struct { + Params `form:"*"` + // The amount to capture from the authorization. If not provided, the full amount of the authorization will be captured. This amount is in the authorization currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + CaptureAmount *int64 `form:"capture_amount"` + // Whether to close the authorization after capture. Defaults to true. Set to false to enable multi-capture flows. + CloseAuthorization *bool `form:"close_authorization"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Additional purchase information that is optionally provided by the merchant. + PurchaseDetails *TestHelpersIssuingAuthorizationCapturePurchaseDetailsParams `form:"purchase_details"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingAuthorizationCaptureParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Expire a test-mode Authorization. +type TestHelpersIssuingAuthorizationExpireParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingAuthorizationExpireParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Answers to prompts presented to the cardholder at the point of sale. Prompted fields vary depending on the configuration of your physical fleet cards. Typical points of sale support only numeric entry. +type TestHelpersIssuingAuthorizationFinalizeAmountFleetCardholderPromptDataParams struct { + // Driver ID. + DriverID *string `form:"driver_id"` + // Odometer reading. + Odometer *int64 `form:"odometer"` + // An alphanumeric ID. This field is used when a vehicle ID, driver ID, or generic ID is entered by the cardholder, but the merchant or card network did not specify the prompt type. + UnspecifiedID *string `form:"unspecified_id"` + // User ID. + UserID *string `form:"user_id"` + // Vehicle number. + VehicleNumber *string `form:"vehicle_number"` +} + +// Breakdown of fuel portion of the purchase. +type TestHelpersIssuingAuthorizationFinalizeAmountFleetReportedBreakdownFuelParams struct { + // Gross fuel amount that should equal Fuel Volume multipled by Fuel Unit Cost, inclusive of taxes. + GrossAmountDecimal *float64 `form:"gross_amount_decimal,high_precision"` +} + +// Breakdown of non-fuel portion of the purchase. +type TestHelpersIssuingAuthorizationFinalizeAmountFleetReportedBreakdownNonFuelParams struct { + // Gross non-fuel amount that should equal the sum of the line items, inclusive of taxes. + GrossAmountDecimal *float64 `form:"gross_amount_decimal,high_precision"` +} + +// Information about tax included in this transaction. +type TestHelpersIssuingAuthorizationFinalizeAmountFleetReportedBreakdownTaxParams struct { + // Amount of state or provincial Sales Tax included in the transaction amount. Null if not reported by merchant or not subject to tax. + LocalAmountDecimal *float64 `form:"local_amount_decimal,high_precision"` + // Amount of national Sales Tax or VAT included in the transaction amount. Null if not reported by merchant or not subject to tax. + NationalAmountDecimal *float64 `form:"national_amount_decimal,high_precision"` +} + +// More information about the total amount. This information is not guaranteed to be accurate as some merchants may provide unreliable data. +type TestHelpersIssuingAuthorizationFinalizeAmountFleetReportedBreakdownParams struct { + // Breakdown of fuel portion of the purchase. + Fuel *TestHelpersIssuingAuthorizationFinalizeAmountFleetReportedBreakdownFuelParams `form:"fuel"` + // Breakdown of non-fuel portion of the purchase. + NonFuel *TestHelpersIssuingAuthorizationFinalizeAmountFleetReportedBreakdownNonFuelParams `form:"non_fuel"` + // Information about tax included in this transaction. + Tax *TestHelpersIssuingAuthorizationFinalizeAmountFleetReportedBreakdownTaxParams `form:"tax"` +} + +// Fleet-specific information for authorizations using Fleet cards. +type TestHelpersIssuingAuthorizationFinalizeAmountFleetParams struct { + // Answers to prompts presented to the cardholder at the point of sale. Prompted fields vary depending on the configuration of your physical fleet cards. Typical points of sale support only numeric entry. + CardholderPromptData *TestHelpersIssuingAuthorizationFinalizeAmountFleetCardholderPromptDataParams `form:"cardholder_prompt_data"` + // The type of purchase. One of `fuel_purchase`, `non_fuel_purchase`, or `fuel_and_non_fuel_purchase`. + PurchaseType *string `form:"purchase_type"` + // More information about the total amount. This information is not guaranteed to be accurate as some merchants may provide unreliable data. + ReportedBreakdown *TestHelpersIssuingAuthorizationFinalizeAmountFleetReportedBreakdownParams `form:"reported_breakdown"` + // The type of fuel service. One of `non_fuel_transaction`, `full_service`, or `self_service`. + ServiceType *string `form:"service_type"` +} + +// Information about fuel that was purchased with this transaction. +type TestHelpersIssuingAuthorizationFinalizeAmountFuelParams struct { + // [Conexxus Payment System Product Code](https://www.conexxus.org/conexxus-payment-system-product-codes) identifying the primary fuel product purchased. + IndustryProductCode *string `form:"industry_product_code"` + // The quantity of `unit`s of fuel that was dispensed, represented as a decimal string with at most 12 decimal places. + QuantityDecimal *float64 `form:"quantity_decimal,high_precision"` + // The type of fuel that was purchased. One of `diesel`, `unleaded_plus`, `unleaded_regular`, `unleaded_super`, or `other`. + Type *string `form:"type"` + // The units for `quantity_decimal`. One of `charging_minute`, `imperial_gallon`, `kilogram`, `kilowatt_hour`, `liter`, `pound`, `us_gallon`, or `other`. + Unit *string `form:"unit"` + // The cost in cents per each unit of fuel, represented as a decimal string with at most 12 decimal places. + UnitCostDecimal *float64 `form:"unit_cost_decimal,high_precision"` +} + +// Finalize the amount on an Authorization prior to capture, when the initial authorization was for an estimated amount. +type TestHelpersIssuingAuthorizationFinalizeAmountParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The final authorization amount that will be captured by the merchant. This amount is in the authorization currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + FinalAmount *int64 `form:"final_amount"` + // Fleet-specific information for authorizations using Fleet cards. + Fleet *TestHelpersIssuingAuthorizationFinalizeAmountFleetParams `form:"fleet"` + // Information about fuel that was purchased with this transaction. + Fuel *TestHelpersIssuingAuthorizationFinalizeAmountFuelParams `form:"fuel"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingAuthorizationFinalizeAmountParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Respond to a fraud challenge on a testmode Issuing authorization, simulating either a confirmation of fraud or a correction of legitimacy. +type TestHelpersIssuingAuthorizationRespondParams struct { + Params `form:"*"` + // Whether to simulate the user confirming that the transaction was legitimate (true) or telling Stripe that it was fraudulent (false). + Confirmed *bool `form:"confirmed"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingAuthorizationRespondParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Increment a test-mode Authorization. +type TestHelpersIssuingAuthorizationIncrementParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The amount to increment the authorization by. This amount is in the authorization currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + IncrementAmount *int64 `form:"increment_amount"` + // If set `true`, you may provide [amount](https://stripe.com/docs/api/issuing/authorizations/approve#approve_issuing_authorization-amount) to control how much to hold for the authorization. + IsAmountControllable *bool `form:"is_amount_controllable"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingAuthorizationIncrementParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Reverse a test-mode Authorization. +type TestHelpersIssuingAuthorizationReverseParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The amount to reverse from the authorization. If not provided, the full amount of the authorization will be reversed. This amount is in the authorization currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + ReverseAmount *int64 `form:"reverse_amount"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingAuthorizationReverseParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Detailed breakdown of amount components. These amounts are denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). +type TestHelpersIssuingAuthorizationCreateAmountDetailsParams struct { + // The ATM withdrawal fee. + ATMFee *int64 `form:"atm_fee"` + // The amount of cash requested by the cardholder. + CashbackAmount *int64 `form:"cashback_amount"` +} + +// Answers to prompts presented to the cardholder at the point of sale. Prompted fields vary depending on the configuration of your physical fleet cards. Typical points of sale support only numeric entry. +type TestHelpersIssuingAuthorizationCreateFleetCardholderPromptDataParams struct { + // Driver ID. + DriverID *string `form:"driver_id"` + // Odometer reading. + Odometer *int64 `form:"odometer"` + // An alphanumeric ID. This field is used when a vehicle ID, driver ID, or generic ID is entered by the cardholder, but the merchant or card network did not specify the prompt type. + UnspecifiedID *string `form:"unspecified_id"` + // User ID. + UserID *string `form:"user_id"` + // Vehicle number. + VehicleNumber *string `form:"vehicle_number"` +} + +// Breakdown of fuel portion of the purchase. +type TestHelpersIssuingAuthorizationCreateFleetReportedBreakdownFuelParams struct { + // Gross fuel amount that should equal Fuel Volume multipled by Fuel Unit Cost, inclusive of taxes. + GrossAmountDecimal *float64 `form:"gross_amount_decimal,high_precision"` +} + +// Breakdown of non-fuel portion of the purchase. +type TestHelpersIssuingAuthorizationCreateFleetReportedBreakdownNonFuelParams struct { + // Gross non-fuel amount that should equal the sum of the line items, inclusive of taxes. + GrossAmountDecimal *float64 `form:"gross_amount_decimal,high_precision"` +} + +// Information about tax included in this transaction. +type TestHelpersIssuingAuthorizationCreateFleetReportedBreakdownTaxParams struct { + // Amount of state or provincial Sales Tax included in the transaction amount. Null if not reported by merchant or not subject to tax. + LocalAmountDecimal *float64 `form:"local_amount_decimal,high_precision"` + // Amount of national Sales Tax or VAT included in the transaction amount. Null if not reported by merchant or not subject to tax. + NationalAmountDecimal *float64 `form:"national_amount_decimal,high_precision"` +} + +// More information about the total amount. This information is not guaranteed to be accurate as some merchants may provide unreliable data. +type TestHelpersIssuingAuthorizationCreateFleetReportedBreakdownParams struct { + // Breakdown of fuel portion of the purchase. + Fuel *TestHelpersIssuingAuthorizationCreateFleetReportedBreakdownFuelParams `form:"fuel"` + // Breakdown of non-fuel portion of the purchase. + NonFuel *TestHelpersIssuingAuthorizationCreateFleetReportedBreakdownNonFuelParams `form:"non_fuel"` + // Information about tax included in this transaction. + Tax *TestHelpersIssuingAuthorizationCreateFleetReportedBreakdownTaxParams `form:"tax"` +} + +// Fleet-specific information for authorizations using Fleet cards. +type TestHelpersIssuingAuthorizationCreateFleetParams struct { + // Answers to prompts presented to the cardholder at the point of sale. Prompted fields vary depending on the configuration of your physical fleet cards. Typical points of sale support only numeric entry. + CardholderPromptData *TestHelpersIssuingAuthorizationCreateFleetCardholderPromptDataParams `form:"cardholder_prompt_data"` + // The type of purchase. One of `fuel_purchase`, `non_fuel_purchase`, or `fuel_and_non_fuel_purchase`. + PurchaseType *string `form:"purchase_type"` + // More information about the total amount. This information is not guaranteed to be accurate as some merchants may provide unreliable data. + ReportedBreakdown *TestHelpersIssuingAuthorizationCreateFleetReportedBreakdownParams `form:"reported_breakdown"` + // The type of fuel service. One of `non_fuel_transaction`, `full_service`, or `self_service`. + ServiceType *string `form:"service_type"` +} + +// Information about fuel that was purchased with this transaction. +type TestHelpersIssuingAuthorizationCreateFuelParams struct { + // [Conexxus Payment System Product Code](https://www.conexxus.org/conexxus-payment-system-product-codes) identifying the primary fuel product purchased. + IndustryProductCode *string `form:"industry_product_code"` + // The quantity of `unit`s of fuel that was dispensed, represented as a decimal string with at most 12 decimal places. + QuantityDecimal *float64 `form:"quantity_decimal,high_precision"` + // The type of fuel that was purchased. One of `diesel`, `unleaded_plus`, `unleaded_regular`, `unleaded_super`, or `other`. + Type *string `form:"type"` + // The units for `quantity_decimal`. One of `charging_minute`, `imperial_gallon`, `kilogram`, `kilowatt_hour`, `liter`, `pound`, `us_gallon`, or `other`. + Unit *string `form:"unit"` + // The cost in cents per each unit of fuel, represented as a decimal string with at most 12 decimal places. + UnitCostDecimal *float64 `form:"unit_cost_decimal,high_precision"` +} + +// Details about the seller (grocery store, e-commerce website, etc.) where the card authorization happened. +type TestHelpersIssuingAuthorizationCreateMerchantDataParams struct { + // A categorization of the seller's type of business. See our [merchant categories guide](https://stripe.com/docs/issuing/merchant-categories) for a list of possible values. + Category *string `form:"category"` + // City where the seller is located + City *string `form:"city"` + // Country where the seller is located + Country *string `form:"country"` + // Name of the seller + Name *string `form:"name"` + // Identifier assigned to the seller by the card network. Different card networks may assign different network_id fields to the same merchant. + NetworkID *string `form:"network_id"` + // Postal code where the seller is located + PostalCode *string `form:"postal_code"` + // State where the seller is located + State *string `form:"state"` + // An ID assigned by the seller to the location of the sale. + TerminalID *string `form:"terminal_id"` + // URL provided by the merchant on a 3DS request + URL *string `form:"url"` +} + +// Details about the authorization, such as identifiers, set by the card network. +type TestHelpersIssuingAuthorizationCreateNetworkDataParams struct { + // Identifier assigned to the acquirer by the card network. + AcquiringInstitutionID *string `form:"acquiring_institution_id"` +} + +// The exemption applied to this authorization. +type TestHelpersIssuingAuthorizationCreateVerificationDataAuthenticationExemptionParams struct { + // The entity that requested the exemption, either the acquiring merchant or the Issuing user. + ClaimedBy *string `form:"claimed_by"` + // The specific exemption claimed for this authorization. + Type *string `form:"type"` +} + +// 3D Secure details. +type TestHelpersIssuingAuthorizationCreateVerificationDataThreeDSecureParams struct { + // The outcome of the 3D Secure authentication request. + Result *string `form:"result"` +} + +// Verifications that Stripe performed on information that the cardholder provided to the merchant. +type TestHelpersIssuingAuthorizationCreateVerificationDataParams struct { + // Whether the cardholder provided an address first line and if it matched the cardholder's `billing.address.line1`. + AddressLine1Check *string `form:"address_line1_check"` + // Whether the cardholder provided a postal code and if it matched the cardholder's `billing.address.postal_code`. + AddressPostalCodeCheck *string `form:"address_postal_code_check"` + // The exemption applied to this authorization. + AuthenticationExemption *TestHelpersIssuingAuthorizationCreateVerificationDataAuthenticationExemptionParams `form:"authentication_exemption"` + // Whether the cardholder provided a CVC and if it matched Stripe's record. + CVCCheck *string `form:"cvc_check"` + // Whether the cardholder provided an expiry date and if it matched Stripe's record. + ExpiryCheck *string `form:"expiry_check"` + // 3D Secure details. + ThreeDSecure *TestHelpersIssuingAuthorizationCreateVerificationDataThreeDSecureParams `form:"three_d_secure"` +} + +// Create a test-mode authorization. +type TestHelpersIssuingAuthorizationCreateParams struct { + Params `form:"*"` + // The total amount to attempt to authorize. This amount is in the provided currency, or defaults to the card's currency, and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Amount *int64 `form:"amount"` + // Detailed breakdown of amount components. These amounts are denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + AmountDetails *TestHelpersIssuingAuthorizationCreateAmountDetailsParams `form:"amount_details"` + // How the card details were provided. Defaults to online. + AuthorizationMethod *string `form:"authorization_method"` + // Card associated with this authorization. + Card *string `form:"card"` + // The currency of the authorization. If not provided, defaults to the currency of the card. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Fleet-specific information for authorizations using Fleet cards. + Fleet *TestHelpersIssuingAuthorizationCreateFleetParams `form:"fleet"` + // Information about fuel that was purchased with this transaction. + Fuel *TestHelpersIssuingAuthorizationCreateFuelParams `form:"fuel"` + // If set `true`, you may provide [amount](https://stripe.com/docs/api/issuing/authorizations/approve#approve_issuing_authorization-amount) to control how much to hold for the authorization. + IsAmountControllable *bool `form:"is_amount_controllable"` + // The total amount to attempt to authorize. This amount is in the provided merchant currency, and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + MerchantAmount *int64 `form:"merchant_amount"` + // The currency of the authorization. If not provided, defaults to the currency of the card. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + MerchantCurrency *string `form:"merchant_currency"` + // Details about the seller (grocery store, e-commerce website, etc.) where the card authorization happened. + MerchantData *TestHelpersIssuingAuthorizationCreateMerchantDataParams `form:"merchant_data"` + // Details about the authorization, such as identifiers, set by the card network. + NetworkData *TestHelpersIssuingAuthorizationCreateNetworkDataParams `form:"network_data"` + // Verifications that Stripe performed on information that the cardholder provided to the merchant. + VerificationData *TestHelpersIssuingAuthorizationCreateVerificationDataParams `form:"verification_data"` + // The digital wallet used for this transaction. One of `apple_pay`, `google_pay`, or `samsung_pay`. Will populate as `null` when no digital wallet was utilized. + Wallet *string `form:"wallet"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingAuthorizationCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_authorization_service.go b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_authorization_service.go new file mode 100644 index 00000000..8f46d8f2 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_authorization_service.go @@ -0,0 +1,107 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TestHelpersIssuingAuthorizationService is used to invoke /v1/issuing/authorizations APIs. +type v1TestHelpersIssuingAuthorizationService struct { + B Backend + Key string +} + +// Create a test-mode authorization. +func (c v1TestHelpersIssuingAuthorizationService) Create(ctx context.Context, params *TestHelpersIssuingAuthorizationCreateParams) (*IssuingAuthorization, error) { + if params == nil { + params = &TestHelpersIssuingAuthorizationCreateParams{} + } + params.Context = ctx + authorization := &IssuingAuthorization{} + err := c.B.Call( + http.MethodPost, "/v1/test_helpers/issuing/authorizations", c.Key, params, authorization) + return authorization, err +} + +// Capture a test-mode authorization. +func (c v1TestHelpersIssuingAuthorizationService) Capture(ctx context.Context, id string, params *TestHelpersIssuingAuthorizationCaptureParams) (*IssuingAuthorization, error) { + if params == nil { + params = &TestHelpersIssuingAuthorizationCaptureParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/issuing/authorizations/%s/capture", id) + authorization := &IssuingAuthorization{} + err := c.B.Call(http.MethodPost, path, c.Key, params, authorization) + return authorization, err +} + +// Expire a test-mode Authorization. +func (c v1TestHelpersIssuingAuthorizationService) Expire(ctx context.Context, id string, params *TestHelpersIssuingAuthorizationExpireParams) (*IssuingAuthorization, error) { + if params == nil { + params = &TestHelpersIssuingAuthorizationExpireParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/test_helpers/issuing/authorizations/%s/expire", id) + authorization := &IssuingAuthorization{} + err := c.B.Call(http.MethodPost, path, c.Key, params, authorization) + return authorization, err +} + +// Finalize the amount on an Authorization prior to capture, when the initial authorization was for an estimated amount. +func (c v1TestHelpersIssuingAuthorizationService) FinalizeAmount(ctx context.Context, id string, params *TestHelpersIssuingAuthorizationFinalizeAmountParams) (*IssuingAuthorization, error) { + if params == nil { + params = &TestHelpersIssuingAuthorizationFinalizeAmountParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/issuing/authorizations/%s/finalize_amount", id) + authorization := &IssuingAuthorization{} + err := c.B.Call(http.MethodPost, path, c.Key, params, authorization) + return authorization, err +} + +// Increment a test-mode Authorization. +func (c v1TestHelpersIssuingAuthorizationService) Increment(ctx context.Context, id string, params *TestHelpersIssuingAuthorizationIncrementParams) (*IssuingAuthorization, error) { + if params == nil { + params = &TestHelpersIssuingAuthorizationIncrementParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/issuing/authorizations/%s/increment", id) + authorization := &IssuingAuthorization{} + err := c.B.Call(http.MethodPost, path, c.Key, params, authorization) + return authorization, err +} + +// Respond to a fraud challenge on a testmode Issuing authorization, simulating either a confirmation of fraud or a correction of legitimacy. +func (c v1TestHelpersIssuingAuthorizationService) Respond(ctx context.Context, id string, params *TestHelpersIssuingAuthorizationRespondParams) (*IssuingAuthorization, error) { + if params == nil { + params = &TestHelpersIssuingAuthorizationRespondParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/issuing/authorizations/%s/fraud_challenges/respond", id) + authorization := &IssuingAuthorization{} + err := c.B.Call(http.MethodPost, path, c.Key, params, authorization) + return authorization, err +} + +// Reverse a test-mode Authorization. +func (c v1TestHelpersIssuingAuthorizationService) Reverse(ctx context.Context, id string, params *TestHelpersIssuingAuthorizationReverseParams) (*IssuingAuthorization, error) { + if params == nil { + params = &TestHelpersIssuingAuthorizationReverseParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/issuing/authorizations/%s/reverse", id) + authorization := &IssuingAuthorization{} + err := c.B.Call(http.MethodPost, path, c.Key, params, authorization) + return authorization, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_card.go b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_card.go new file mode 100644 index 00000000..c42a3ff9 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_card.go @@ -0,0 +1,67 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Updates the shipping status of the specified Issuing Card object to delivered. +type TestHelpersIssuingCardDeliverCardParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingCardDeliverCardParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the shipping status of the specified Issuing Card object to failure. +type TestHelpersIssuingCardFailCardParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingCardFailCardParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the shipping status of the specified Issuing Card object to returned. +type TestHelpersIssuingCardReturnCardParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingCardReturnCardParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the shipping status of the specified Issuing Card object to shipped. +type TestHelpersIssuingCardShipCardParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingCardShipCardParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the shipping status of the specified Issuing Card object to submitted. This method requires Stripe Version ‘2024-09-30.acacia' or later. +type TestHelpersIssuingCardSubmitCardParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingCardSubmitCardParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_card_service.go b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_card_service.go new file mode 100644 index 00000000..04b6e705 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_card_service.go @@ -0,0 +1,79 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TestHelpersIssuingCardService is used to invoke /v1/issuing/cards APIs. +type v1TestHelpersIssuingCardService struct { + B Backend + Key string +} + +// Updates the shipping status of the specified Issuing Card object to delivered. +func (c v1TestHelpersIssuingCardService) DeliverCard(ctx context.Context, id string, params *TestHelpersIssuingCardDeliverCardParams) (*IssuingCard, error) { + if params == nil { + params = &TestHelpersIssuingCardDeliverCardParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/issuing/cards/%s/shipping/deliver", id) + card := &IssuingCard{} + err := c.B.Call(http.MethodPost, path, c.Key, params, card) + return card, err +} + +// Updates the shipping status of the specified Issuing Card object to failure. +func (c v1TestHelpersIssuingCardService) FailCard(ctx context.Context, id string, params *TestHelpersIssuingCardFailCardParams) (*IssuingCard, error) { + if params == nil { + params = &TestHelpersIssuingCardFailCardParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/test_helpers/issuing/cards/%s/shipping/fail", id) + card := &IssuingCard{} + err := c.B.Call(http.MethodPost, path, c.Key, params, card) + return card, err +} + +// Updates the shipping status of the specified Issuing Card object to returned. +func (c v1TestHelpersIssuingCardService) ReturnCard(ctx context.Context, id string, params *TestHelpersIssuingCardReturnCardParams) (*IssuingCard, error) { + if params == nil { + params = &TestHelpersIssuingCardReturnCardParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/test_helpers/issuing/cards/%s/shipping/return", id) + card := &IssuingCard{} + err := c.B.Call(http.MethodPost, path, c.Key, params, card) + return card, err +} + +// Updates the shipping status of the specified Issuing Card object to shipped. +func (c v1TestHelpersIssuingCardService) ShipCard(ctx context.Context, id string, params *TestHelpersIssuingCardShipCardParams) (*IssuingCard, error) { + if params == nil { + params = &TestHelpersIssuingCardShipCardParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/test_helpers/issuing/cards/%s/shipping/ship", id) + card := &IssuingCard{} + err := c.B.Call(http.MethodPost, path, c.Key, params, card) + return card, err +} + +// Updates the shipping status of the specified Issuing Card object to submitted. This method requires Stripe Version ‘2024-09-30.acacia' or later. +func (c v1TestHelpersIssuingCardService) SubmitCard(ctx context.Context, id string, params *TestHelpersIssuingCardSubmitCardParams) (*IssuingCard, error) { + if params == nil { + params = &TestHelpersIssuingCardSubmitCardParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/test_helpers/issuing/cards/%s/shipping/submit", id) + card := &IssuingCard{} + err := c.B.Call(http.MethodPost, path, c.Key, params, card) + return card, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_personalizationdesign.go b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_personalizationdesign.go new file mode 100644 index 00000000..72b58bbc --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_personalizationdesign.go @@ -0,0 +1,53 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Updates the status of the specified testmode personalization design object to active. +type TestHelpersIssuingPersonalizationDesignActivateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingPersonalizationDesignActivateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the status of the specified testmode personalization design object to inactive. +type TestHelpersIssuingPersonalizationDesignDeactivateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingPersonalizationDesignDeactivateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// The reason(s) the personalization design was rejected. +type TestHelpersIssuingPersonalizationDesignRejectRejectionReasonsParams struct { + // The reason(s) the card logo was rejected. + CardLogo []*string `form:"card_logo"` + // The reason(s) the carrier text was rejected. + CarrierText []*string `form:"carrier_text"` +} + +// Updates the status of the specified testmode personalization design object to rejected. +type TestHelpersIssuingPersonalizationDesignRejectParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The reason(s) the personalization design was rejected. + RejectionReasons *TestHelpersIssuingPersonalizationDesignRejectRejectionReasonsParams `form:"rejection_reasons"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingPersonalizationDesignRejectParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_personalizationdesign_service.go b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_personalizationdesign_service.go new file mode 100644 index 00000000..3ae81c70 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_personalizationdesign_service.go @@ -0,0 +1,57 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TestHelpersIssuingPersonalizationDesignService is used to invoke /v1/issuing/personalization_designs APIs. +type v1TestHelpersIssuingPersonalizationDesignService struct { + B Backend + Key string +} + +// Updates the status of the specified testmode personalization design object to active. +func (c v1TestHelpersIssuingPersonalizationDesignService) Activate(ctx context.Context, id string, params *TestHelpersIssuingPersonalizationDesignActivateParams) (*IssuingPersonalizationDesign, error) { + if params == nil { + params = &TestHelpersIssuingPersonalizationDesignActivateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/issuing/personalization_designs/%s/activate", id) + personalizationdesign := &IssuingPersonalizationDesign{} + err := c.B.Call(http.MethodPost, path, c.Key, params, personalizationdesign) + return personalizationdesign, err +} + +// Updates the status of the specified testmode personalization design object to inactive. +func (c v1TestHelpersIssuingPersonalizationDesignService) Deactivate(ctx context.Context, id string, params *TestHelpersIssuingPersonalizationDesignDeactivateParams) (*IssuingPersonalizationDesign, error) { + if params == nil { + params = &TestHelpersIssuingPersonalizationDesignDeactivateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/issuing/personalization_designs/%s/deactivate", id) + personalizationdesign := &IssuingPersonalizationDesign{} + err := c.B.Call(http.MethodPost, path, c.Key, params, personalizationdesign) + return personalizationdesign, err +} + +// Updates the status of the specified testmode personalization design object to rejected. +func (c v1TestHelpersIssuingPersonalizationDesignService) Reject(ctx context.Context, id string, params *TestHelpersIssuingPersonalizationDesignRejectParams) (*IssuingPersonalizationDesign, error) { + if params == nil { + params = &TestHelpersIssuingPersonalizationDesignRejectParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/issuing/personalization_designs/%s/reject", id) + personalizationdesign := &IssuingPersonalizationDesign{} + err := c.B.Call(http.MethodPost, path, c.Key, params, personalizationdesign) + return personalizationdesign, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_transaction.go b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_transaction.go new file mode 100644 index 00000000..e7ca05a1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_transaction.go @@ -0,0 +1,373 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Refund a test-mode Transaction. +type TestHelpersIssuingTransactionRefundParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The total amount to attempt to refund. This amount is in the provided currency, or defaults to the cards currency, and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + RefundAmount *int64 `form:"refund_amount"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingTransactionRefundParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Details about the seller (grocery store, e-commerce website, etc.) where the card authorization happened. +type TestHelpersIssuingTransactionCreateForceCaptureMerchantDataParams struct { + // A categorization of the seller's type of business. See our [merchant categories guide](https://stripe.com/docs/issuing/merchant-categories) for a list of possible values. + Category *string `form:"category"` + // City where the seller is located + City *string `form:"city"` + // Country where the seller is located + Country *string `form:"country"` + // Name of the seller + Name *string `form:"name"` + // Identifier assigned to the seller by the card network. Different card networks may assign different network_id fields to the same merchant. + NetworkID *string `form:"network_id"` + // Postal code where the seller is located + PostalCode *string `form:"postal_code"` + // State where the seller is located + State *string `form:"state"` + // An ID assigned by the seller to the location of the sale. + TerminalID *string `form:"terminal_id"` + // URL provided by the merchant on a 3DS request + URL *string `form:"url"` +} + +// Answers to prompts presented to the cardholder at the point of sale. Prompted fields vary depending on the configuration of your physical fleet cards. Typical points of sale support only numeric entry. +type TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFleetCardholderPromptDataParams struct { + // Driver ID. + DriverID *string `form:"driver_id"` + // Odometer reading. + Odometer *int64 `form:"odometer"` + // An alphanumeric ID. This field is used when a vehicle ID, driver ID, or generic ID is entered by the cardholder, but the merchant or card network did not specify the prompt type. + UnspecifiedID *string `form:"unspecified_id"` + // User ID. + UserID *string `form:"user_id"` + // Vehicle number. + VehicleNumber *string `form:"vehicle_number"` +} + +// Breakdown of fuel portion of the purchase. +type TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFleetReportedBreakdownFuelParams struct { + // Gross fuel amount that should equal Fuel Volume multipled by Fuel Unit Cost, inclusive of taxes. + GrossAmountDecimal *float64 `form:"gross_amount_decimal,high_precision"` +} + +// Breakdown of non-fuel portion of the purchase. +type TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFleetReportedBreakdownNonFuelParams struct { + // Gross non-fuel amount that should equal the sum of the line items, inclusive of taxes. + GrossAmountDecimal *float64 `form:"gross_amount_decimal,high_precision"` +} + +// Information about tax included in this transaction. +type TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFleetReportedBreakdownTaxParams struct { + // Amount of state or provincial Sales Tax included in the transaction amount. Null if not reported by merchant or not subject to tax. + LocalAmountDecimal *float64 `form:"local_amount_decimal,high_precision"` + // Amount of national Sales Tax or VAT included in the transaction amount. Null if not reported by merchant or not subject to tax. + NationalAmountDecimal *float64 `form:"national_amount_decimal,high_precision"` +} + +// More information about the total amount. This information is not guaranteed to be accurate as some merchants may provide unreliable data. +type TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFleetReportedBreakdownParams struct { + // Breakdown of fuel portion of the purchase. + Fuel *TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFleetReportedBreakdownFuelParams `form:"fuel"` + // Breakdown of non-fuel portion of the purchase. + NonFuel *TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFleetReportedBreakdownNonFuelParams `form:"non_fuel"` + // Information about tax included in this transaction. + Tax *TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFleetReportedBreakdownTaxParams `form:"tax"` +} + +// Fleet-specific information for transactions using Fleet cards. +type TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFleetParams struct { + // Answers to prompts presented to the cardholder at the point of sale. Prompted fields vary depending on the configuration of your physical fleet cards. Typical points of sale support only numeric entry. + CardholderPromptData *TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFleetCardholderPromptDataParams `form:"cardholder_prompt_data"` + // The type of purchase. One of `fuel_purchase`, `non_fuel_purchase`, or `fuel_and_non_fuel_purchase`. + PurchaseType *string `form:"purchase_type"` + // More information about the total amount. This information is not guaranteed to be accurate as some merchants may provide unreliable data. + ReportedBreakdown *TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFleetReportedBreakdownParams `form:"reported_breakdown"` + // The type of fuel service. One of `non_fuel_transaction`, `full_service`, or `self_service`. + ServiceType *string `form:"service_type"` +} + +// The legs of the trip. +type TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFlightSegmentParams struct { + // The three-letter IATA airport code of the flight's destination. + ArrivalAirportCode *string `form:"arrival_airport_code"` + // The airline carrier code. + Carrier *string `form:"carrier"` + // The three-letter IATA airport code that the flight departed from. + DepartureAirportCode *string `form:"departure_airport_code"` + // The flight number. + FlightNumber *string `form:"flight_number"` + // The flight's service class. + ServiceClass *string `form:"service_class"` + // Whether a stopover is allowed on this flight. + StopoverAllowed *bool `form:"stopover_allowed"` +} + +// Information about the flight that was purchased with this transaction. +type TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFlightParams struct { + // The time that the flight departed. + DepartureAt *int64 `form:"departure_at"` + // The name of the passenger. + PassengerName *string `form:"passenger_name"` + // Whether the ticket is refundable. + Refundable *bool `form:"refundable"` + // The legs of the trip. + Segments []*TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFlightSegmentParams `form:"segments"` + // The travel agency that issued the ticket. + TravelAgency *string `form:"travel_agency"` +} + +// Information about fuel that was purchased with this transaction. +type TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFuelParams struct { + // [Conexxus Payment System Product Code](https://www.conexxus.org/conexxus-payment-system-product-codes) identifying the primary fuel product purchased. + IndustryProductCode *string `form:"industry_product_code"` + // The quantity of `unit`s of fuel that was dispensed, represented as a decimal string with at most 12 decimal places. + QuantityDecimal *float64 `form:"quantity_decimal,high_precision"` + // The type of fuel that was purchased. One of `diesel`, `unleaded_plus`, `unleaded_regular`, `unleaded_super`, or `other`. + Type *string `form:"type"` + // The units for `quantity_decimal`. One of `charging_minute`, `imperial_gallon`, `kilogram`, `kilowatt_hour`, `liter`, `pound`, `us_gallon`, or `other`. + Unit *string `form:"unit"` + // The cost in cents per each unit of fuel, represented as a decimal string with at most 12 decimal places. + UnitCostDecimal *float64 `form:"unit_cost_decimal,high_precision"` +} + +// Information about lodging that was purchased with this transaction. +type TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsLodgingParams struct { + // The time of checking into the lodging. + CheckInAt *int64 `form:"check_in_at"` + // The number of nights stayed at the lodging. + Nights *int64 `form:"nights"` +} + +// The line items in the purchase. +type TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsReceiptParams struct { + Description *string `form:"description"` + Quantity *float64 `form:"quantity,high_precision"` + Total *int64 `form:"total"` + UnitCost *int64 `form:"unit_cost"` +} + +// Additional purchase information that is optionally provided by the merchant. +type TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsParams struct { + // Fleet-specific information for transactions using Fleet cards. + Fleet *TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFleetParams `form:"fleet"` + // Information about the flight that was purchased with this transaction. + Flight *TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFlightParams `form:"flight"` + // Information about fuel that was purchased with this transaction. + Fuel *TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsFuelParams `form:"fuel"` + // Information about lodging that was purchased with this transaction. + Lodging *TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsLodgingParams `form:"lodging"` + // The line items in the purchase. + Receipt []*TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsReceiptParams `form:"receipt"` + // A merchant-specific order number. + Reference *string `form:"reference"` +} + +// Allows the user to capture an arbitrary amount, also known as a forced capture. +type TestHelpersIssuingTransactionCreateForceCaptureParams struct { + Params `form:"*"` + // The total amount to attempt to capture. This amount is in the provided currency, or defaults to the cards currency, and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Amount *int64 `form:"amount"` + // Card associated with this transaction. + Card *string `form:"card"` + // The currency of the capture. If not provided, defaults to the currency of the card. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Details about the seller (grocery store, e-commerce website, etc.) where the card authorization happened. + MerchantData *TestHelpersIssuingTransactionCreateForceCaptureMerchantDataParams `form:"merchant_data"` + // Additional purchase information that is optionally provided by the merchant. + PurchaseDetails *TestHelpersIssuingTransactionCreateForceCapturePurchaseDetailsParams `form:"purchase_details"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingTransactionCreateForceCaptureParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Details about the seller (grocery store, e-commerce website, etc.) where the card authorization happened. +type TestHelpersIssuingTransactionCreateUnlinkedRefundMerchantDataParams struct { + // A categorization of the seller's type of business. See our [merchant categories guide](https://stripe.com/docs/issuing/merchant-categories) for a list of possible values. + Category *string `form:"category"` + // City where the seller is located + City *string `form:"city"` + // Country where the seller is located + Country *string `form:"country"` + // Name of the seller + Name *string `form:"name"` + // Identifier assigned to the seller by the card network. Different card networks may assign different network_id fields to the same merchant. + NetworkID *string `form:"network_id"` + // Postal code where the seller is located + PostalCode *string `form:"postal_code"` + // State where the seller is located + State *string `form:"state"` + // An ID assigned by the seller to the location of the sale. + TerminalID *string `form:"terminal_id"` + // URL provided by the merchant on a 3DS request + URL *string `form:"url"` +} + +// Answers to prompts presented to the cardholder at the point of sale. Prompted fields vary depending on the configuration of your physical fleet cards. Typical points of sale support only numeric entry. +type TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFleetCardholderPromptDataParams struct { + // Driver ID. + DriverID *string `form:"driver_id"` + // Odometer reading. + Odometer *int64 `form:"odometer"` + // An alphanumeric ID. This field is used when a vehicle ID, driver ID, or generic ID is entered by the cardholder, but the merchant or card network did not specify the prompt type. + UnspecifiedID *string `form:"unspecified_id"` + // User ID. + UserID *string `form:"user_id"` + // Vehicle number. + VehicleNumber *string `form:"vehicle_number"` +} + +// Breakdown of fuel portion of the purchase. +type TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFleetReportedBreakdownFuelParams struct { + // Gross fuel amount that should equal Fuel Volume multipled by Fuel Unit Cost, inclusive of taxes. + GrossAmountDecimal *float64 `form:"gross_amount_decimal,high_precision"` +} + +// Breakdown of non-fuel portion of the purchase. +type TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFleetReportedBreakdownNonFuelParams struct { + // Gross non-fuel amount that should equal the sum of the line items, inclusive of taxes. + GrossAmountDecimal *float64 `form:"gross_amount_decimal,high_precision"` +} + +// Information about tax included in this transaction. +type TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFleetReportedBreakdownTaxParams struct { + // Amount of state or provincial Sales Tax included in the transaction amount. Null if not reported by merchant or not subject to tax. + LocalAmountDecimal *float64 `form:"local_amount_decimal,high_precision"` + // Amount of national Sales Tax or VAT included in the transaction amount. Null if not reported by merchant or not subject to tax. + NationalAmountDecimal *float64 `form:"national_amount_decimal,high_precision"` +} + +// More information about the total amount. This information is not guaranteed to be accurate as some merchants may provide unreliable data. +type TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFleetReportedBreakdownParams struct { + // Breakdown of fuel portion of the purchase. + Fuel *TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFleetReportedBreakdownFuelParams `form:"fuel"` + // Breakdown of non-fuel portion of the purchase. + NonFuel *TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFleetReportedBreakdownNonFuelParams `form:"non_fuel"` + // Information about tax included in this transaction. + Tax *TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFleetReportedBreakdownTaxParams `form:"tax"` +} + +// Fleet-specific information for transactions using Fleet cards. +type TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFleetParams struct { + // Answers to prompts presented to the cardholder at the point of sale. Prompted fields vary depending on the configuration of your physical fleet cards. Typical points of sale support only numeric entry. + CardholderPromptData *TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFleetCardholderPromptDataParams `form:"cardholder_prompt_data"` + // The type of purchase. One of `fuel_purchase`, `non_fuel_purchase`, or `fuel_and_non_fuel_purchase`. + PurchaseType *string `form:"purchase_type"` + // More information about the total amount. This information is not guaranteed to be accurate as some merchants may provide unreliable data. + ReportedBreakdown *TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFleetReportedBreakdownParams `form:"reported_breakdown"` + // The type of fuel service. One of `non_fuel_transaction`, `full_service`, or `self_service`. + ServiceType *string `form:"service_type"` +} + +// The legs of the trip. +type TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFlightSegmentParams struct { + // The three-letter IATA airport code of the flight's destination. + ArrivalAirportCode *string `form:"arrival_airport_code"` + // The airline carrier code. + Carrier *string `form:"carrier"` + // The three-letter IATA airport code that the flight departed from. + DepartureAirportCode *string `form:"departure_airport_code"` + // The flight number. + FlightNumber *string `form:"flight_number"` + // The flight's service class. + ServiceClass *string `form:"service_class"` + // Whether a stopover is allowed on this flight. + StopoverAllowed *bool `form:"stopover_allowed"` +} + +// Information about the flight that was purchased with this transaction. +type TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFlightParams struct { + // The time that the flight departed. + DepartureAt *int64 `form:"departure_at"` + // The name of the passenger. + PassengerName *string `form:"passenger_name"` + // Whether the ticket is refundable. + Refundable *bool `form:"refundable"` + // The legs of the trip. + Segments []*TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFlightSegmentParams `form:"segments"` + // The travel agency that issued the ticket. + TravelAgency *string `form:"travel_agency"` +} + +// Information about fuel that was purchased with this transaction. +type TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFuelParams struct { + // [Conexxus Payment System Product Code](https://www.conexxus.org/conexxus-payment-system-product-codes) identifying the primary fuel product purchased. + IndustryProductCode *string `form:"industry_product_code"` + // The quantity of `unit`s of fuel that was dispensed, represented as a decimal string with at most 12 decimal places. + QuantityDecimal *float64 `form:"quantity_decimal,high_precision"` + // The type of fuel that was purchased. One of `diesel`, `unleaded_plus`, `unleaded_regular`, `unleaded_super`, or `other`. + Type *string `form:"type"` + // The units for `quantity_decimal`. One of `charging_minute`, `imperial_gallon`, `kilogram`, `kilowatt_hour`, `liter`, `pound`, `us_gallon`, or `other`. + Unit *string `form:"unit"` + // The cost in cents per each unit of fuel, represented as a decimal string with at most 12 decimal places. + UnitCostDecimal *float64 `form:"unit_cost_decimal,high_precision"` +} + +// Information about lodging that was purchased with this transaction. +type TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsLodgingParams struct { + // The time of checking into the lodging. + CheckInAt *int64 `form:"check_in_at"` + // The number of nights stayed at the lodging. + Nights *int64 `form:"nights"` +} + +// The line items in the purchase. +type TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsReceiptParams struct { + Description *string `form:"description"` + Quantity *float64 `form:"quantity,high_precision"` + Total *int64 `form:"total"` + UnitCost *int64 `form:"unit_cost"` +} + +// Additional purchase information that is optionally provided by the merchant. +type TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsParams struct { + // Fleet-specific information for transactions using Fleet cards. + Fleet *TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFleetParams `form:"fleet"` + // Information about the flight that was purchased with this transaction. + Flight *TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFlightParams `form:"flight"` + // Information about fuel that was purchased with this transaction. + Fuel *TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsFuelParams `form:"fuel"` + // Information about lodging that was purchased with this transaction. + Lodging *TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsLodgingParams `form:"lodging"` + // The line items in the purchase. + Receipt []*TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsReceiptParams `form:"receipt"` + // A merchant-specific order number. + Reference *string `form:"reference"` +} + +// Allows the user to refund an arbitrary amount, also known as a unlinked refund. +type TestHelpersIssuingTransactionCreateUnlinkedRefundParams struct { + Params `form:"*"` + // The total amount to attempt to refund. This amount is in the provided currency, or defaults to the cards currency, and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Amount *int64 `form:"amount"` + // Card associated with this unlinked refund transaction. + Card *string `form:"card"` + // The currency of the unlinked refund. If not provided, defaults to the currency of the card. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Details about the seller (grocery store, e-commerce website, etc.) where the card authorization happened. + MerchantData *TestHelpersIssuingTransactionCreateUnlinkedRefundMerchantDataParams `form:"merchant_data"` + // Additional purchase information that is optionally provided by the merchant. + PurchaseDetails *TestHelpersIssuingTransactionCreateUnlinkedRefundPurchaseDetailsParams `form:"purchase_details"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersIssuingTransactionCreateUnlinkedRefundParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_transaction_service.go b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_transaction_service.go new file mode 100644 index 00000000..6d6b5799 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpersissuing_transaction_service.go @@ -0,0 +1,54 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TestHelpersIssuingTransactionService is used to invoke /v1/issuing/transactions APIs. +type v1TestHelpersIssuingTransactionService struct { + B Backend + Key string +} + +// Allows the user to capture an arbitrary amount, also known as a forced capture. +func (c v1TestHelpersIssuingTransactionService) CreateForceCapture(ctx context.Context, params *TestHelpersIssuingTransactionCreateForceCaptureParams) (*IssuingTransaction, error) { + if params == nil { + params = &TestHelpersIssuingTransactionCreateForceCaptureParams{} + } + params.Context = ctx + transaction := &IssuingTransaction{} + err := c.B.Call( + http.MethodPost, "/v1/test_helpers/issuing/transactions/create_force_capture", c.Key, params, transaction) + return transaction, err +} + +// Allows the user to refund an arbitrary amount, also known as a unlinked refund. +func (c v1TestHelpersIssuingTransactionService) CreateUnlinkedRefund(ctx context.Context, params *TestHelpersIssuingTransactionCreateUnlinkedRefundParams) (*IssuingTransaction, error) { + if params == nil { + params = &TestHelpersIssuingTransactionCreateUnlinkedRefundParams{} + } + params.Context = ctx + transaction := &IssuingTransaction{} + err := c.B.Call( + http.MethodPost, "/v1/test_helpers/issuing/transactions/create_unlinked_refund", c.Key, params, transaction) + return transaction, err +} + +// Refund a test-mode Transaction. +func (c v1TestHelpersIssuingTransactionService) Refund(ctx context.Context, id string, params *TestHelpersIssuingTransactionRefundParams) (*IssuingTransaction, error) { + if params == nil { + params = &TestHelpersIssuingTransactionRefundParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/test_helpers/issuing/transactions/%s/refund", id) + transaction := &IssuingTransaction{} + err := c.B.Call(http.MethodPost, path, c.Key, params, transaction) + return transaction, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpersterminal_reader.go b/vendor/github.com/stripe/stripe-go/v82/testhelpersterminal_reader.go new file mode 100644 index 00000000..1c82c7b9 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpersterminal_reader.go @@ -0,0 +1,65 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Simulated data for the card_present payment method. +type TestHelpersTerminalReaderPresentPaymentMethodCardPresentParams struct { + // The card number, as a string without any separators. + Number *string `form:"number"` +} + +// Simulated data for the interac_present payment method. +type TestHelpersTerminalReaderPresentPaymentMethodInteracPresentParams struct { + // Card Number + Number *string `form:"number"` +} + +// Presents a payment method on a simulated reader. Can be used to simulate accepting a payment, saving a card or refunding a transaction. +type TestHelpersTerminalReaderPresentPaymentMethodParams struct { + Params `form:"*"` + // Simulated on-reader tip amount. + AmountTip *int64 `form:"amount_tip"` + // Simulated data for the card_present payment method. + CardPresent *TestHelpersTerminalReaderPresentPaymentMethodCardPresentParams `form:"card_present"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Simulated data for the interac_present payment method. + InteracPresent *TestHelpersTerminalReaderPresentPaymentMethodInteracPresentParams `form:"interac_present"` + // Simulated payment type. + Type *string `form:"type"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTerminalReaderPresentPaymentMethodParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Use this endpoint to trigger a successful input collection on a simulated reader. +type TestHelpersTerminalReaderSucceedInputCollectionParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // This parameter defines the skip behavior for input collection. + SkipNonRequiredInputs *string `form:"skip_non_required_inputs"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTerminalReaderSucceedInputCollectionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Use this endpoint to complete an input collection with a timeout error on a simulated reader. +type TestHelpersTerminalReaderTimeoutInputCollectionParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTerminalReaderTimeoutInputCollectionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelpersterminal_reader_service.go b/vendor/github.com/stripe/stripe-go/v82/testhelpersterminal_reader_service.go new file mode 100644 index 00000000..2a076a99 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelpersterminal_reader_service.go @@ -0,0 +1,57 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TestHelpersTerminalReaderService is used to invoke /v1/terminal/readers APIs. +type v1TestHelpersTerminalReaderService struct { + B Backend + Key string +} + +// Presents a payment method on a simulated reader. Can be used to simulate accepting a payment, saving a card or refunding a transaction. +func (c v1TestHelpersTerminalReaderService) PresentPaymentMethod(ctx context.Context, id string, params *TestHelpersTerminalReaderPresentPaymentMethodParams) (*TerminalReader, error) { + if params == nil { + params = &TestHelpersTerminalReaderPresentPaymentMethodParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/terminal/readers/%s/present_payment_method", id) + reader := &TerminalReader{} + err := c.B.Call(http.MethodPost, path, c.Key, params, reader) + return reader, err +} + +// Use this endpoint to trigger a successful input collection on a simulated reader. +func (c v1TestHelpersTerminalReaderService) SucceedInputCollection(ctx context.Context, id string, params *TestHelpersTerminalReaderSucceedInputCollectionParams) (*TerminalReader, error) { + if params == nil { + params = &TestHelpersTerminalReaderSucceedInputCollectionParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/terminal/readers/%s/succeed_input_collection", id) + reader := &TerminalReader{} + err := c.B.Call(http.MethodPost, path, c.Key, params, reader) + return reader, err +} + +// Use this endpoint to complete an input collection with a timeout error on a simulated reader. +func (c v1TestHelpersTerminalReaderService) TimeoutInputCollection(ctx context.Context, id string, params *TestHelpersTerminalReaderTimeoutInputCollectionParams) (*TerminalReader, error) { + if params == nil { + params = &TestHelpersTerminalReaderTimeoutInputCollectionParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/terminal/readers/%s/timeout_input_collection", id) + reader := &TerminalReader{} + err := c.B.Call(http.MethodPost, path, c.Key, params, reader) + return reader, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_inboundtransfer.go b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_inboundtransfer.go new file mode 100644 index 00000000..bc55de0e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_inboundtransfer.go @@ -0,0 +1,51 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Details about a failed InboundTransfer. +type TestHelpersTreasuryInboundTransferFailFailureDetailsParams struct { + // Reason for the failure. + Code *string `form:"code"` +} + +// Transitions a test mode created InboundTransfer to the failed status. The InboundTransfer must already be in the processing state. +type TestHelpersTreasuryInboundTransferFailParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Details about a failed InboundTransfer. + FailureDetails *TestHelpersTreasuryInboundTransferFailFailureDetailsParams `form:"failure_details"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryInboundTransferFailParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Marks the test mode InboundTransfer object as returned and links the InboundTransfer to a ReceivedDebit. The InboundTransfer must already be in the succeeded state. +type TestHelpersTreasuryInboundTransferReturnInboundTransferParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryInboundTransferReturnInboundTransferParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Transitions a test mode created InboundTransfer to the succeeded status. The InboundTransfer must already be in the processing state. +type TestHelpersTreasuryInboundTransferSucceedParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryInboundTransferSucceedParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_inboundtransfer_service.go b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_inboundtransfer_service.go new file mode 100644 index 00000000..41766d8e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_inboundtransfer_service.go @@ -0,0 +1,57 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TestHelpersTreasuryInboundTransferService is used to invoke /v1/treasury/inbound_transfers APIs. +type v1TestHelpersTreasuryInboundTransferService struct { + B Backend + Key string +} + +// Transitions a test mode created InboundTransfer to the failed status. The InboundTransfer must already be in the processing state. +func (c v1TestHelpersTreasuryInboundTransferService) Fail(ctx context.Context, id string, params *TestHelpersTreasuryInboundTransferFailParams) (*TreasuryInboundTransfer, error) { + if params == nil { + params = &TestHelpersTreasuryInboundTransferFailParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/treasury/inbound_transfers/%s/fail", id) + inboundtransfer := &TreasuryInboundTransfer{} + err := c.B.Call(http.MethodPost, path, c.Key, params, inboundtransfer) + return inboundtransfer, err +} + +// Marks the test mode InboundTransfer object as returned and links the InboundTransfer to a ReceivedDebit. The InboundTransfer must already be in the succeeded state. +func (c v1TestHelpersTreasuryInboundTransferService) ReturnInboundTransfer(ctx context.Context, id string, params *TestHelpersTreasuryInboundTransferReturnInboundTransferParams) (*TreasuryInboundTransfer, error) { + if params == nil { + params = &TestHelpersTreasuryInboundTransferReturnInboundTransferParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/treasury/inbound_transfers/%s/return", id) + inboundtransfer := &TreasuryInboundTransfer{} + err := c.B.Call(http.MethodPost, path, c.Key, params, inboundtransfer) + return inboundtransfer, err +} + +// Transitions a test mode created InboundTransfer to the succeeded status. The InboundTransfer must already be in the processing state. +func (c v1TestHelpersTreasuryInboundTransferService) Succeed(ctx context.Context, id string, params *TestHelpersTreasuryInboundTransferSucceedParams) (*TreasuryInboundTransfer, error) { + if params == nil { + params = &TestHelpersTreasuryInboundTransferSucceedParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/treasury/inbound_transfers/%s/succeed", id) + inboundtransfer := &TreasuryInboundTransfer{} + err := c.B.Call(http.MethodPost, path, c.Key, params, inboundtransfer) + return inboundtransfer, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_outboundpayment.go b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_outboundpayment.go new file mode 100644 index 00000000..81ca29b7 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_outboundpayment.go @@ -0,0 +1,131 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// ACH network tracking details. +type TestHelpersTreasuryOutboundPaymentTrackingDetailsACHParams struct { + // ACH trace ID for funds sent over the `ach` network. + TraceID *string `form:"trace_id"` +} + +// US domestic wire network tracking details. +type TestHelpersTreasuryOutboundPaymentTrackingDetailsUSDomesticWireParams struct { + // CHIPS System Sequence Number (SSN) for funds sent over the `us_domestic_wire` network. + Chips *string `form:"chips"` + // IMAD for funds sent over the `us_domestic_wire` network. + Imad *string `form:"imad"` + // OMAD for funds sent over the `us_domestic_wire` network. + Omad *string `form:"omad"` +} + +// Details about network-specific tracking information. +type TestHelpersTreasuryOutboundPaymentTrackingDetailsParams struct { + // ACH network tracking details. + ACH *TestHelpersTreasuryOutboundPaymentTrackingDetailsACHParams `form:"ach"` + // The US bank account network used to send funds. + Type *string `form:"type"` + // US domestic wire network tracking details. + USDomesticWire *TestHelpersTreasuryOutboundPaymentTrackingDetailsUSDomesticWireParams `form:"us_domestic_wire"` +} + +// Updates a test mode created OutboundPayment with tracking details. The OutboundPayment must not be cancelable, and cannot be in the canceled or failed states. +type TestHelpersTreasuryOutboundPaymentParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Details about network-specific tracking information. + TrackingDetails *TestHelpersTreasuryOutboundPaymentTrackingDetailsParams `form:"tracking_details"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryOutboundPaymentParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Transitions a test mode created OutboundPayment to the failed status. The OutboundPayment must already be in the processing state. +type TestHelpersTreasuryOutboundPaymentFailParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryOutboundPaymentFailParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Transitions a test mode created OutboundPayment to the posted status. The OutboundPayment must already be in the processing state. +type TestHelpersTreasuryOutboundPaymentPostParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryOutboundPaymentPostParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Optional hash to set the return code. +type TestHelpersTreasuryOutboundPaymentReturnOutboundPaymentReturnedDetailsParams struct { + // The return code to be set on the OutboundPayment object. + Code *string `form:"code"` +} + +// Transitions a test mode created OutboundPayment to the returned status. The OutboundPayment must already be in the processing state. +type TestHelpersTreasuryOutboundPaymentReturnOutboundPaymentParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Optional hash to set the return code. + ReturnedDetails *TestHelpersTreasuryOutboundPaymentReturnOutboundPaymentReturnedDetailsParams `form:"returned_details"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryOutboundPaymentReturnOutboundPaymentParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// ACH network tracking details. +type TestHelpersTreasuryOutboundPaymentUpdateTrackingDetailsACHParams struct { + // ACH trace ID for funds sent over the `ach` network. + TraceID *string `form:"trace_id"` +} + +// US domestic wire network tracking details. +type TestHelpersTreasuryOutboundPaymentUpdateTrackingDetailsUSDomesticWireParams struct { + // CHIPS System Sequence Number (SSN) for funds sent over the `us_domestic_wire` network. + Chips *string `form:"chips"` + // IMAD for funds sent over the `us_domestic_wire` network. + Imad *string `form:"imad"` + // OMAD for funds sent over the `us_domestic_wire` network. + Omad *string `form:"omad"` +} + +// Details about network-specific tracking information. +type TestHelpersTreasuryOutboundPaymentUpdateTrackingDetailsParams struct { + // ACH network tracking details. + ACH *TestHelpersTreasuryOutboundPaymentUpdateTrackingDetailsACHParams `form:"ach"` + // The US bank account network used to send funds. + Type *string `form:"type"` + // US domestic wire network tracking details. + USDomesticWire *TestHelpersTreasuryOutboundPaymentUpdateTrackingDetailsUSDomesticWireParams `form:"us_domestic_wire"` +} + +// Updates a test mode created OutboundPayment with tracking details. The OutboundPayment must not be cancelable, and cannot be in the canceled or failed states. +type TestHelpersTreasuryOutboundPaymentUpdateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Details about network-specific tracking information. + TrackingDetails *TestHelpersTreasuryOutboundPaymentUpdateTrackingDetailsParams `form:"tracking_details"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryOutboundPaymentUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_outboundpayment_service.go b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_outboundpayment_service.go new file mode 100644 index 00000000..54888955 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_outboundpayment_service.go @@ -0,0 +1,69 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TestHelpersTreasuryOutboundPaymentService is used to invoke /v1/treasury/outbound_payments APIs. +type v1TestHelpersTreasuryOutboundPaymentService struct { + B Backend + Key string +} + +// Updates a test mode created OutboundPayment with tracking details. The OutboundPayment must not be cancelable, and cannot be in the canceled or failed states. +func (c v1TestHelpersTreasuryOutboundPaymentService) Update(ctx context.Context, id string, params *TestHelpersTreasuryOutboundPaymentUpdateParams) (*TreasuryOutboundPayment, error) { + if params == nil { + params = &TestHelpersTreasuryOutboundPaymentUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/test_helpers/treasury/outbound_payments/%s", id) + outboundpayment := &TreasuryOutboundPayment{} + err := c.B.Call(http.MethodPost, path, c.Key, params, outboundpayment) + return outboundpayment, err +} + +// Transitions a test mode created OutboundPayment to the failed status. The OutboundPayment must already be in the processing state. +func (c v1TestHelpersTreasuryOutboundPaymentService) Fail(ctx context.Context, id string, params *TestHelpersTreasuryOutboundPaymentFailParams) (*TreasuryOutboundPayment, error) { + if params == nil { + params = &TestHelpersTreasuryOutboundPaymentFailParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/treasury/outbound_payments/%s/fail", id) + outboundpayment := &TreasuryOutboundPayment{} + err := c.B.Call(http.MethodPost, path, c.Key, params, outboundpayment) + return outboundpayment, err +} + +// Transitions a test mode created OutboundPayment to the posted status. The OutboundPayment must already be in the processing state. +func (c v1TestHelpersTreasuryOutboundPaymentService) Post(ctx context.Context, id string, params *TestHelpersTreasuryOutboundPaymentPostParams) (*TreasuryOutboundPayment, error) { + if params == nil { + params = &TestHelpersTreasuryOutboundPaymentPostParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/treasury/outbound_payments/%s/post", id) + outboundpayment := &TreasuryOutboundPayment{} + err := c.B.Call(http.MethodPost, path, c.Key, params, outboundpayment) + return outboundpayment, err +} + +// Transitions a test mode created OutboundPayment to the returned status. The OutboundPayment must already be in the processing state. +func (c v1TestHelpersTreasuryOutboundPaymentService) ReturnOutboundPayment(ctx context.Context, id string, params *TestHelpersTreasuryOutboundPaymentReturnOutboundPaymentParams) (*TreasuryOutboundPayment, error) { + if params == nil { + params = &TestHelpersTreasuryOutboundPaymentReturnOutboundPaymentParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/treasury/outbound_payments/%s/return", id) + outboundpayment := &TreasuryOutboundPayment{} + err := c.B.Call(http.MethodPost, path, c.Key, params, outboundpayment) + return outboundpayment, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_outboundtransfer.go b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_outboundtransfer.go new file mode 100644 index 00000000..974fe19d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_outboundtransfer.go @@ -0,0 +1,131 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// ACH network tracking details. +type TestHelpersTreasuryOutboundTransferTrackingDetailsACHParams struct { + // ACH trace ID for funds sent over the `ach` network. + TraceID *string `form:"trace_id"` +} + +// US domestic wire network tracking details. +type TestHelpersTreasuryOutboundTransferTrackingDetailsUSDomesticWireParams struct { + // CHIPS System Sequence Number (SSN) for funds sent over the `us_domestic_wire` network. + Chips *string `form:"chips"` + // IMAD for funds sent over the `us_domestic_wire` network. + Imad *string `form:"imad"` + // OMAD for funds sent over the `us_domestic_wire` network. + Omad *string `form:"omad"` +} + +// Details about network-specific tracking information. +type TestHelpersTreasuryOutboundTransferTrackingDetailsParams struct { + // ACH network tracking details. + ACH *TestHelpersTreasuryOutboundTransferTrackingDetailsACHParams `form:"ach"` + // The US bank account network used to send funds. + Type *string `form:"type"` + // US domestic wire network tracking details. + USDomesticWire *TestHelpersTreasuryOutboundTransferTrackingDetailsUSDomesticWireParams `form:"us_domestic_wire"` +} + +// Updates a test mode created OutboundTransfer with tracking details. The OutboundTransfer must not be cancelable, and cannot be in the canceled or failed states. +type TestHelpersTreasuryOutboundTransferParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Details about network-specific tracking information. + TrackingDetails *TestHelpersTreasuryOutboundTransferTrackingDetailsParams `form:"tracking_details"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryOutboundTransferParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Transitions a test mode created OutboundTransfer to the failed status. The OutboundTransfer must already be in the processing state. +type TestHelpersTreasuryOutboundTransferFailParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryOutboundTransferFailParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Transitions a test mode created OutboundTransfer to the posted status. The OutboundTransfer must already be in the processing state. +type TestHelpersTreasuryOutboundTransferPostParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryOutboundTransferPostParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Details about a returned OutboundTransfer. +type TestHelpersTreasuryOutboundTransferReturnOutboundTransferReturnedDetailsParams struct { + // Reason for the return. + Code *string `form:"code"` +} + +// Transitions a test mode created OutboundTransfer to the returned status. The OutboundTransfer must already be in the processing state. +type TestHelpersTreasuryOutboundTransferReturnOutboundTransferParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Details about a returned OutboundTransfer. + ReturnedDetails *TestHelpersTreasuryOutboundTransferReturnOutboundTransferReturnedDetailsParams `form:"returned_details"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryOutboundTransferReturnOutboundTransferParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// ACH network tracking details. +type TestHelpersTreasuryOutboundTransferUpdateTrackingDetailsACHParams struct { + // ACH trace ID for funds sent over the `ach` network. + TraceID *string `form:"trace_id"` +} + +// US domestic wire network tracking details. +type TestHelpersTreasuryOutboundTransferUpdateTrackingDetailsUSDomesticWireParams struct { + // CHIPS System Sequence Number (SSN) for funds sent over the `us_domestic_wire` network. + Chips *string `form:"chips"` + // IMAD for funds sent over the `us_domestic_wire` network. + Imad *string `form:"imad"` + // OMAD for funds sent over the `us_domestic_wire` network. + Omad *string `form:"omad"` +} + +// Details about network-specific tracking information. +type TestHelpersTreasuryOutboundTransferUpdateTrackingDetailsParams struct { + // ACH network tracking details. + ACH *TestHelpersTreasuryOutboundTransferUpdateTrackingDetailsACHParams `form:"ach"` + // The US bank account network used to send funds. + Type *string `form:"type"` + // US domestic wire network tracking details. + USDomesticWire *TestHelpersTreasuryOutboundTransferUpdateTrackingDetailsUSDomesticWireParams `form:"us_domestic_wire"` +} + +// Updates a test mode created OutboundTransfer with tracking details. The OutboundTransfer must not be cancelable, and cannot be in the canceled or failed states. +type TestHelpersTreasuryOutboundTransferUpdateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Details about network-specific tracking information. + TrackingDetails *TestHelpersTreasuryOutboundTransferUpdateTrackingDetailsParams `form:"tracking_details"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryOutboundTransferUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_outboundtransfer_service.go b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_outboundtransfer_service.go new file mode 100644 index 00000000..eb210105 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_outboundtransfer_service.go @@ -0,0 +1,69 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TestHelpersTreasuryOutboundTransferService is used to invoke /v1/treasury/outbound_transfers APIs. +type v1TestHelpersTreasuryOutboundTransferService struct { + B Backend + Key string +} + +// Updates a test mode created OutboundTransfer with tracking details. The OutboundTransfer must not be cancelable, and cannot be in the canceled or failed states. +func (c v1TestHelpersTreasuryOutboundTransferService) Update(ctx context.Context, id string, params *TestHelpersTreasuryOutboundTransferUpdateParams) (*TreasuryOutboundTransfer, error) { + if params == nil { + params = &TestHelpersTreasuryOutboundTransferUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/test_helpers/treasury/outbound_transfers/%s", id) + outboundtransfer := &TreasuryOutboundTransfer{} + err := c.B.Call(http.MethodPost, path, c.Key, params, outboundtransfer) + return outboundtransfer, err +} + +// Transitions a test mode created OutboundTransfer to the failed status. The OutboundTransfer must already be in the processing state. +func (c v1TestHelpersTreasuryOutboundTransferService) Fail(ctx context.Context, id string, params *TestHelpersTreasuryOutboundTransferFailParams) (*TreasuryOutboundTransfer, error) { + if params == nil { + params = &TestHelpersTreasuryOutboundTransferFailParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/treasury/outbound_transfers/%s/fail", id) + outboundtransfer := &TreasuryOutboundTransfer{} + err := c.B.Call(http.MethodPost, path, c.Key, params, outboundtransfer) + return outboundtransfer, err +} + +// Transitions a test mode created OutboundTransfer to the posted status. The OutboundTransfer must already be in the processing state. +func (c v1TestHelpersTreasuryOutboundTransferService) Post(ctx context.Context, id string, params *TestHelpersTreasuryOutboundTransferPostParams) (*TreasuryOutboundTransfer, error) { + if params == nil { + params = &TestHelpersTreasuryOutboundTransferPostParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/treasury/outbound_transfers/%s/post", id) + outboundtransfer := &TreasuryOutboundTransfer{} + err := c.B.Call(http.MethodPost, path, c.Key, params, outboundtransfer) + return outboundtransfer, err +} + +// Transitions a test mode created OutboundTransfer to the returned status. The OutboundTransfer must already be in the processing state. +func (c v1TestHelpersTreasuryOutboundTransferService) ReturnOutboundTransfer(ctx context.Context, id string, params *TestHelpersTreasuryOutboundTransferReturnOutboundTransferParams) (*TreasuryOutboundTransfer, error) { + if params == nil { + params = &TestHelpersTreasuryOutboundTransferReturnOutboundTransferParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/test_helpers/treasury/outbound_transfers/%s/return", id) + outboundtransfer := &TreasuryOutboundTransfer{} + err := c.B.Call(http.MethodPost, path, c.Key, params, outboundtransfer) + return outboundtransfer, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_receivedcredit.go b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_receivedcredit.go new file mode 100644 index 00000000..39c3dacc --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_receivedcredit.go @@ -0,0 +1,91 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Optional fields for `us_bank_account`. +type TestHelpersTreasuryReceivedCreditInitiatingPaymentMethodDetailsUSBankAccountParams struct { + // The bank account holder's name. + AccountHolderName *string `form:"account_holder_name"` + // The bank account number. + AccountNumber *string `form:"account_number"` + // The bank account's routing number. + RoutingNumber *string `form:"routing_number"` +} + +// Initiating payment method details for the object. +type TestHelpersTreasuryReceivedCreditInitiatingPaymentMethodDetailsParams struct { + // The source type. + Type *string `form:"type"` + // Optional fields for `us_bank_account`. + USBankAccount *TestHelpersTreasuryReceivedCreditInitiatingPaymentMethodDetailsUSBankAccountParams `form:"us_bank_account"` +} + +// Use this endpoint to simulate a test mode ReceivedCredit initiated by a third party. In live mode, you can't directly create ReceivedCredits initiated by third parties. +type TestHelpersTreasuryReceivedCreditParams struct { + Params `form:"*"` + // Amount (in cents) to be transferred. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The FinancialAccount to send funds to. + FinancialAccount *string `form:"financial_account"` + // Initiating payment method details for the object. + InitiatingPaymentMethodDetails *TestHelpersTreasuryReceivedCreditInitiatingPaymentMethodDetailsParams `form:"initiating_payment_method_details"` + // Specifies the network rails to be used. If not set, will default to the PaymentMethod's preferred network. See the [docs](https://stripe.com/docs/treasury/money-movement/timelines) to learn more about money movement timelines for each network type. + Network *string `form:"network"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryReceivedCreditParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Optional fields for `us_bank_account`. +type TestHelpersTreasuryReceivedCreditCreateInitiatingPaymentMethodDetailsUSBankAccountParams struct { + // The bank account holder's name. + AccountHolderName *string `form:"account_holder_name"` + // The bank account number. + AccountNumber *string `form:"account_number"` + // The bank account's routing number. + RoutingNumber *string `form:"routing_number"` +} + +// Initiating payment method details for the object. +type TestHelpersTreasuryReceivedCreditCreateInitiatingPaymentMethodDetailsParams struct { + // The source type. + Type *string `form:"type"` + // Optional fields for `us_bank_account`. + USBankAccount *TestHelpersTreasuryReceivedCreditCreateInitiatingPaymentMethodDetailsUSBankAccountParams `form:"us_bank_account"` +} + +// Use this endpoint to simulate a test mode ReceivedCredit initiated by a third party. In live mode, you can't directly create ReceivedCredits initiated by third parties. +type TestHelpersTreasuryReceivedCreditCreateParams struct { + Params `form:"*"` + // Amount (in cents) to be transferred. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The FinancialAccount to send funds to. + FinancialAccount *string `form:"financial_account"` + // Initiating payment method details for the object. + InitiatingPaymentMethodDetails *TestHelpersTreasuryReceivedCreditCreateInitiatingPaymentMethodDetailsParams `form:"initiating_payment_method_details"` + // Specifies the network rails to be used. If not set, will default to the PaymentMethod's preferred network. See the [docs](https://stripe.com/docs/treasury/money-movement/timelines) to learn more about money movement timelines for each network type. + Network *string `form:"network"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryReceivedCreditCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_receivedcredit_service.go b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_receivedcredit_service.go new file mode 100644 index 00000000..ff9e1920 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_receivedcredit_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TestHelpersTreasuryReceivedCreditService is used to invoke /v1/treasury/received_credits APIs. +type v1TestHelpersTreasuryReceivedCreditService struct { + B Backend + Key string +} + +// Use this endpoint to simulate a test mode ReceivedCredit initiated by a third party. In live mode, you can't directly create ReceivedCredits initiated by third parties. +func (c v1TestHelpersTreasuryReceivedCreditService) Create(ctx context.Context, params *TestHelpersTreasuryReceivedCreditCreateParams) (*TreasuryReceivedCredit, error) { + if params == nil { + params = &TestHelpersTreasuryReceivedCreditCreateParams{} + } + params.Context = ctx + receivedcredit := &TreasuryReceivedCredit{} + err := c.B.Call( + http.MethodPost, "/v1/test_helpers/treasury/received_credits", c.Key, params, receivedcredit) + return receivedcredit, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_receiveddebit.go b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_receiveddebit.go new file mode 100644 index 00000000..790c05fb --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_receiveddebit.go @@ -0,0 +1,91 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Optional fields for `us_bank_account`. +type TestHelpersTreasuryReceivedDebitInitiatingPaymentMethodDetailsUSBankAccountParams struct { + // The bank account holder's name. + AccountHolderName *string `form:"account_holder_name"` + // The bank account number. + AccountNumber *string `form:"account_number"` + // The bank account's routing number. + RoutingNumber *string `form:"routing_number"` +} + +// Initiating payment method details for the object. +type TestHelpersTreasuryReceivedDebitInitiatingPaymentMethodDetailsParams struct { + // The source type. + Type *string `form:"type"` + // Optional fields for `us_bank_account`. + USBankAccount *TestHelpersTreasuryReceivedDebitInitiatingPaymentMethodDetailsUSBankAccountParams `form:"us_bank_account"` +} + +// Use this endpoint to simulate a test mode ReceivedDebit initiated by a third party. In live mode, you can't directly create ReceivedDebits initiated by third parties. +type TestHelpersTreasuryReceivedDebitParams struct { + Params `form:"*"` + // Amount (in cents) to be transferred. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The FinancialAccount to pull funds from. + FinancialAccount *string `form:"financial_account"` + // Initiating payment method details for the object. + InitiatingPaymentMethodDetails *TestHelpersTreasuryReceivedDebitInitiatingPaymentMethodDetailsParams `form:"initiating_payment_method_details"` + // Specifies the network rails to be used. If not set, will default to the PaymentMethod's preferred network. See the [docs](https://stripe.com/docs/treasury/money-movement/timelines) to learn more about money movement timelines for each network type. + Network *string `form:"network"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryReceivedDebitParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Optional fields for `us_bank_account`. +type TestHelpersTreasuryReceivedDebitCreateInitiatingPaymentMethodDetailsUSBankAccountParams struct { + // The bank account holder's name. + AccountHolderName *string `form:"account_holder_name"` + // The bank account number. + AccountNumber *string `form:"account_number"` + // The bank account's routing number. + RoutingNumber *string `form:"routing_number"` +} + +// Initiating payment method details for the object. +type TestHelpersTreasuryReceivedDebitCreateInitiatingPaymentMethodDetailsParams struct { + // The source type. + Type *string `form:"type"` + // Optional fields for `us_bank_account`. + USBankAccount *TestHelpersTreasuryReceivedDebitCreateInitiatingPaymentMethodDetailsUSBankAccountParams `form:"us_bank_account"` +} + +// Use this endpoint to simulate a test mode ReceivedDebit initiated by a third party. In live mode, you can't directly create ReceivedDebits initiated by third parties. +type TestHelpersTreasuryReceivedDebitCreateParams struct { + Params `form:"*"` + // Amount (in cents) to be transferred. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The FinancialAccount to pull funds from. + FinancialAccount *string `form:"financial_account"` + // Initiating payment method details for the object. + InitiatingPaymentMethodDetails *TestHelpersTreasuryReceivedDebitCreateInitiatingPaymentMethodDetailsParams `form:"initiating_payment_method_details"` + // Specifies the network rails to be used. If not set, will default to the PaymentMethod's preferred network. See the [docs](https://stripe.com/docs/treasury/money-movement/timelines) to learn more about money movement timelines for each network type. + Network *string `form:"network"` +} + +// AddExpand appends a new field to expand. +func (p *TestHelpersTreasuryReceivedDebitCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} diff --git a/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_receiveddebit_service.go b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_receiveddebit_service.go new file mode 100644 index 00000000..359f2a41 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/testhelperstreasury_receiveddebit_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TestHelpersTreasuryReceivedDebitService is used to invoke /v1/treasury/received_debits APIs. +type v1TestHelpersTreasuryReceivedDebitService struct { + B Backend + Key string +} + +// Use this endpoint to simulate a test mode ReceivedDebit initiated by a third party. In live mode, you can't directly create ReceivedDebits initiated by third parties. +func (c v1TestHelpersTreasuryReceivedDebitService) Create(ctx context.Context, params *TestHelpersTreasuryReceivedDebitCreateParams) (*TreasuryReceivedDebit, error) { + if params == nil { + params = &TestHelpersTreasuryReceivedDebitCreateParams{} + } + params.Context = ctx + receiveddebit := &TreasuryReceivedDebit{} + err := c.B.Call( + http.MethodPost, "/v1/test_helpers/treasury/received_debits", c.Key, params, receiveddebit) + return receiveddebit, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/thinevent.go b/vendor/github.com/stripe/stripe-go/v82/thinevent.go new file mode 100644 index 00000000..66441b17 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/thinevent.go @@ -0,0 +1,32 @@ +package stripe + +import "time" + +// ThinEvent represents the json that's delivered from an Event Destination. +// Use it to check basic information about a delivered event. +// If you want more details, use `sc.V2Events.Get(thinEvent.ID)` +// to fetch the full event object. +type ThinEvent struct { + // Unique identifier for the event + ID string `json:"id"` + // The string "event" + Object string `json:"object"` + // The type of the event + Type string `json:"type"` + // Livemode indicates if the event is from a production(true) or test(false) account + Livemode bool `json:"livemode"` + // Time at which the event was created + Created time.Time `json:"created"` + // [Optional] Object containing the reference to API resource relevant to the event + RelatedObject *RelatedObject `json:"related_object"` + // [Optional] Authentication context needed to fetch the event or related object + Context *string `json:"context"` + // [Optional] Reason for the event + Reason *V2EventReason `json:"reason"` +} + +type RelatedObject struct { + ID string `json:"id"` + Type string `json:"type"` + URL string `json:"url"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/token.go b/vendor/github.com/stripe/stripe-go/v82/token.go new file mode 100644 index 00000000..1dce92d7 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/token.go @@ -0,0 +1,184 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Type of the token: `account`, `bank_account`, `card`, or `pii`. +type TokenType string + +// List of values that TokenType can take +const ( + TokenTypeAccount TokenType = "account" + TokenTypeBankAccount TokenType = "bank_account" + TokenTypeCard TokenType = "card" + TokenTypeCVCUpdate TokenType = "cvc_update" + TokenTypePII TokenType = "pii" +) + +// Retrieves the token with the given ID. +type TokenParams struct { + Params `form:"*"` + // Information for the account this token represents. + Account *TokenAccountParams `form:"account"` + // The bank account this token will represent. + BankAccount *BankAccountParams `form:"bank_account"` + // The card this token will represent. If you also pass in a customer, the card must be the ID of a card belonging to the customer. Otherwise, if you do not pass in a customer, this is a dictionary containing a user's credit card details, with the options described below. + Card *CardParams `form:"card"` + // Create a token for the customer, which is owned by the application's account. You can only use this with an [OAuth access token](https://stripe.com/docs/connect/standard-accounts) or [Stripe-Account header](https://stripe.com/docs/connect/authentication). Learn more about [cloning saved payment methods](https://stripe.com/docs/connect/cloning-saved-payment-methods). + Customer *string `form:"customer"` + // The updated CVC value this token represents. + CVCUpdate *TokenCVCUpdateParams `form:"cvc_update"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Information for the person this token represents. + Person *PersonParams `form:"person"` + // The PII this token represents. + PII *TokenPIIParams `form:"pii"` +} + +// AddExpand appends a new field to expand. +func (p *TokenParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Information for the account this token represents. +type TokenAccountParams struct { + // The business type. + BusinessType *string `form:"business_type"` + // Information about the company or business. + Company *AccountCompanyParams `form:"company"` + // Information about the person represented by the account. + Individual *PersonParams `form:"individual"` + // Whether the user described by the data in the token has been shown [the Stripe Connected Account Agreement](https://docs.stripe.com/connect/account-tokens#stripe-connected-account-agreement). When creating an account token to create a new Connect account, this value must be `true`. + TOSShownAndAccepted *bool `form:"tos_shown_and_accepted"` +} + +// The updated CVC value this token represents. +type TokenCVCUpdateParams struct { + // The CVC value, in string form. + CVC *string `form:"cvc"` +} + +// The PII this token represents. +type TokenPIIParams struct { + // The `id_number` for the PII, in string form. + IDNumber *string `form:"id_number"` +} + +// Retrieves the token with the given ID. +type TokenRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TokenRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Information for the account this token represents. +type TokenCreateAccountParams struct { + // The business type. + BusinessType *string `form:"business_type"` + // Information about the company or business. + Company *AccountCompanyParams `form:"company"` + // Information about the person represented by the account. + Individual *PersonParams `form:"individual"` + // Whether the user described by the data in the token has been shown [the Stripe Connected Account Agreement](https://docs.stripe.com/connect/account-tokens#stripe-connected-account-agreement). When creating an account token to create a new Connect account, this value must be `true`. + TOSShownAndAccepted *bool `form:"tos_shown_and_accepted"` +} + +// The updated CVC value this token represents. +type TokenCreateCVCUpdateParams struct { + // The CVC value, in string form. + CVC *string `form:"cvc"` +} + +// The PII this token represents. +type TokenCreatePIIParams struct { + // The `id_number` for the PII, in string form. + IDNumber *string `form:"id_number"` +} + +// Creates a single-use token that represents a bank account's details. +// You can use this token with any v1 API method in place of a bank account dictionary. You can only use this token once. To do so, attach it to a [connected account](https://docs.stripe.com/api#accounts) where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is application, which includes Custom accounts. +type TokenCreateParams struct { + Params `form:"*"` + // Information for the account this token represents. + Account *TokenCreateAccountParams `form:"account"` + // The bank account this token will represent. + BankAccount *BankAccountParams `form:"bank_account"` + // The card this token will represent. If you also pass in a customer, the card must be the ID of a card belonging to the customer. Otherwise, if you do not pass in a customer, this is a dictionary containing a user's credit card details, with the options described below. + Card *CardParams `form:"card"` + // Create a token for the customer, which is owned by the application's account. You can only use this with an [OAuth access token](https://stripe.com/docs/connect/standard-accounts) or [Stripe-Account header](https://stripe.com/docs/connect/authentication). Learn more about [cloning saved payment methods](https://stripe.com/docs/connect/cloning-saved-payment-methods). + Customer *string `form:"customer"` + // The updated CVC value this token represents. + CVCUpdate *TokenCreateCVCUpdateParams `form:"cvc_update"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Information for the person this token represents. + Person *PersonParams `form:"person"` + // The PII this token represents. + PII *TokenCreatePIIParams `form:"pii"` +} + +// AddExpand appends a new field to expand. +func (p *TokenCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Tokenization is the process Stripe uses to collect sensitive card or bank +// account details, or personally identifiable information (PII), directly from +// your customers in a secure manner. A token representing this information is +// returned to your server to use. Use our +// [recommended payments integrations](https://stripe.com/docs/payments) to perform this process +// on the client-side. This guarantees that no sensitive card data touches your server, +// and allows your integration to operate in a PCI-compliant way. +// +// If you can't use client-side tokenization, you can also create tokens using +// the API with either your publishable or secret API key. If +// your integration uses this method, you're responsible for any PCI compliance +// that it might require, and you must keep your secret API key safe. Unlike with +// client-side tokenization, your customer's information isn't sent directly to +// Stripe, so we can't determine how it's handled or stored. +// +// You can't store or use tokens more than once. To store card or bank account +// information for later use, create [Customer](https://stripe.com/docs/api#customers) +// objects or [External accounts](https://docs.stripe.com/api#external_accounts). +// [Radar](https://stripe.com/docs/radar), our integrated solution for automatic fraud protection, +// performs best with integrations that use client-side tokenization. +type Token struct { + APIResource + // These bank accounts are payment methods on `Customer` objects. + // + // On the other hand [External Accounts](https://docs.stripe.com/api#external_accounts) are transfer + // destinations on `Account` objects for connected accounts. + // They can be bank accounts or debit cards as well, and are documented in the links above. + // + // Related guide: [Bank debits and transfers](https://docs.stripe.com/payments/bank-debits-transfers) + BankAccount *BankAccount `json:"bank_account"` + // You can store multiple cards on a customer in order to charge the customer + // later. You can also store multiple debit cards on a recipient in order to + // transfer to those cards later. + // + // Related guide: [Card payments with Sources](https://stripe.com/docs/sources/cards) + Card *Card `json:"card"` + // IP address of the client that generates the token. + ClientIP string `json:"client_ip"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Type of the token: `account`, `bank_account`, `card`, or `pii`. + Type TokenType `json:"type"` + // Determines if you have already used this token (you can only use tokens once). + Used bool `json:"used"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/token_service.go b/vendor/github.com/stripe/stripe-go/v82/token_service.go new file mode 100644 index 00000000..5a21cff4 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/token_service.go @@ -0,0 +1,42 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v1TokenService is used to invoke /v1/tokens APIs. +type v1TokenService struct { + B Backend + Key string +} + +// Creates a single-use token that represents a bank account's details. +// You can use this token with any v1 API method in place of a bank account dictionary. You can only use this token once. To do so, attach it to a [connected account](https://docs.stripe.com/api#accounts) where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-requirement_collection) is application, which includes Custom accounts. +func (c v1TokenService) Create(ctx context.Context, params *TokenCreateParams) (*Token, error) { + if params == nil { + params = &TokenCreateParams{} + } + params.Context = ctx + token := &Token{} + err := c.B.Call(http.MethodPost, "/v1/tokens", c.Key, params, token) + return token, err +} + +// Retrieves the token with the given ID. +func (c v1TokenService) Retrieve(ctx context.Context, id string, params *TokenRetrieveParams) (*Token, error) { + if params == nil { + params = &TokenRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/tokens/%s", id) + token := &Token{} + err := c.B.Call(http.MethodGet, path, c.Key, params, token) + return token, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/topup.go b/vendor/github.com/stripe/stripe-go/v82/topup.go new file mode 100644 index 00000000..f952eb29 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/topup.go @@ -0,0 +1,232 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The status of the top-up is either `canceled`, `failed`, `pending`, `reversed`, or `succeeded`. +type TopupStatus string + +// List of values that TopupStatus can take +const ( + TopupStatusCanceled TopupStatus = "canceled" + TopupStatusFailed TopupStatus = "failed" + TopupStatusPending TopupStatus = "pending" + TopupStatusReversed TopupStatus = "reversed" + TopupStatusSucceeded TopupStatus = "succeeded" +) + +// Returns a list of top-ups. +type TopupListParams struct { + ListParams `form:"*"` + // A positive integer representing how much to transfer. + Amount *int64 `form:"amount"` + // A positive integer representing how much to transfer. + AmountRange *RangeQueryParams `form:"amount"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + Created *int64 `form:"created"` + // A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return top-ups that have the given status. One of `canceled`, `failed`, `pending` or `succeeded`. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *TopupListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Top up the balance of an account +type TopupParams struct { + Params `form:"*"` + // A positive integer representing how much to transfer. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The ID of a source to transfer funds from. For most users, this should be left unspecified which will use the bank account that was set up in the dashboard for the specified currency. In test mode, this can be a test bank token (see [Testing Top-ups](https://stripe.com/docs/connect/testing#testing-top-ups)). + Source *string `form:"source"` + // Extra information about a top-up for the source's bank statement. Limited to 15 ASCII characters. + StatementDescriptor *string `form:"statement_descriptor"` + // A string that identifies this top-up as part of a group. + TransferGroup *string `form:"transfer_group"` +} + +// AddExpand appends a new field to expand. +func (p *TopupParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TopupParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Top up the balance of an account +type TopupCreateParams struct { + Params `form:"*"` + // A positive integer representing how much to transfer. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The ID of a source to transfer funds from. For most users, this should be left unspecified which will use the bank account that was set up in the dashboard for the specified currency. In test mode, this can be a test bank token (see [Testing Top-ups](https://stripe.com/docs/connect/testing#testing-top-ups)). + Source *string `form:"source"` + // Extra information about a top-up for the source's bank statement. Limited to 15 ASCII characters. + StatementDescriptor *string `form:"statement_descriptor"` + // A string that identifies this top-up as part of a group. + TransferGroup *string `form:"transfer_group"` +} + +// AddExpand appends a new field to expand. +func (p *TopupCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TopupCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Cancels a top-up. Only pending top-ups can be canceled. +type TopupCancelParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TopupCancelParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of a top-up that has previously been created. Supply the unique top-up ID that was returned from your previous request, and Stripe will return the corresponding top-up information. +type TopupRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TopupRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the metadata of a top-up. Other top-up details are not editable by design. +type TopupUpdateParams struct { + Params `form:"*"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *TopupUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TopupUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// To top up your Stripe balance, you create a top-up object. You can retrieve +// individual top-ups, as well as list all top-ups. Top-ups are identified by a +// unique, random ID. +// +// Related guide: [Topping up your platform account](https://stripe.com/docs/connect/top-ups) +type Topup struct { + APIResource + // Amount transferred. + Amount int64 `json:"amount"` + // ID of the balance transaction that describes the impact of this top-up on your account balance. May not be specified depending on status of top-up. + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // Date the funds are expected to arrive in your Stripe account for payouts. This factors in delays like weekends or bank holidays. May not be specified depending on status of top-up. + ExpectedAvailabilityDate int64 `json:"expected_availability_date"` + // Error code explaining reason for top-up failure if available (see [the errors section](https://stripe.com/docs/api#errors) for a list of codes). + FailureCode string `json:"failure_code"` + // Message to user further explaining reason for top-up failure if available. + FailureMessage string `json:"failure_message"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The source field is deprecated. It might not always be present in the API response. + Source *PaymentSource `json:"source"` + // Extra information about a top-up. This will appear on your source's bank statement. It must contain at least one letter. + StatementDescriptor string `json:"statement_descriptor"` + // The status of the top-up is either `canceled`, `failed`, `pending`, `reversed`, or `succeeded`. + Status TopupStatus `json:"status"` + // A string that identifies this top-up as part of a group. + TransferGroup string `json:"transfer_group"` + + // The following property is deprecated + ArrivalDate int64 `json:"arrival_date"` +} + +// TopupList is a list of Topups as retrieved from a list endpoint. +type TopupList struct { + APIResource + ListMeta + Data []*Topup `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Topup. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (t *Topup) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + t.ID = id + return nil + } + + type topup Topup + var v topup + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *t = Topup(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/topup_service.go b/vendor/github.com/stripe/stripe-go/v82/topup_service.go new file mode 100644 index 00000000..ab842295 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/topup_service.go @@ -0,0 +1,84 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TopupService is used to invoke /v1/topups APIs. +type v1TopupService struct { + B Backend + Key string +} + +// Top up the balance of an account +func (c v1TopupService) Create(ctx context.Context, params *TopupCreateParams) (*Topup, error) { + if params == nil { + params = &TopupCreateParams{} + } + params.Context = ctx + topup := &Topup{} + err := c.B.Call(http.MethodPost, "/v1/topups", c.Key, params, topup) + return topup, err +} + +// Retrieves the details of a top-up that has previously been created. Supply the unique top-up ID that was returned from your previous request, and Stripe will return the corresponding top-up information. +func (c v1TopupService) Retrieve(ctx context.Context, id string, params *TopupRetrieveParams) (*Topup, error) { + if params == nil { + params = &TopupRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/topups/%s", id) + topup := &Topup{} + err := c.B.Call(http.MethodGet, path, c.Key, params, topup) + return topup, err +} + +// Updates the metadata of a top-up. Other top-up details are not editable by design. +func (c v1TopupService) Update(ctx context.Context, id string, params *TopupUpdateParams) (*Topup, error) { + if params == nil { + params = &TopupUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/topups/%s", id) + topup := &Topup{} + err := c.B.Call(http.MethodPost, path, c.Key, params, topup) + return topup, err +} + +// Cancels a top-up. Only pending top-ups can be canceled. +func (c v1TopupService) Cancel(ctx context.Context, id string, params *TopupCancelParams) (*Topup, error) { + path := FormatURLPath("/v1/topups/%s/cancel", id) + topup := &Topup{} + if params == nil { + params = &TopupCancelParams{} + } + params.Context = ctx + err := c.B.Call(http.MethodPost, path, c.Key, params, topup) + return topup, err +} + +// Returns a list of top-ups. +func (c v1TopupService) List(ctx context.Context, listParams *TopupListParams) Seq2[*Topup, error] { + if listParams == nil { + listParams = &TopupListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Topup, ListContainer, error) { + list := &TopupList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/topups", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/transfer.go b/vendor/github.com/stripe/stripe-go/v82/transfer.go new file mode 100644 index 00000000..b75baa99 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/transfer.go @@ -0,0 +1,226 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// The source balance this transfer came from. One of `card`, `fpx`, or `bank_account`. +type TransferSourceType string + +// List of values that TransferSourceType can take +const ( + TransferSourceTypeBankAccount TransferSourceType = "bank_account" + TransferSourceTypeCard TransferSourceType = "card" + TransferSourceTypeFPX TransferSourceType = "fpx" +) + +// Returns a list of existing transfers sent to connected accounts. The transfers are returned in sorted order, with the most recently created transfers appearing first. +type TransferListParams struct { + ListParams `form:"*"` + // Only return transfers that were created during the given date interval. + Created *int64 `form:"created"` + // Only return transfers that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Only return transfers for the destination specified by this account ID. + Destination *string `form:"destination"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return transfers with the specified transfer group. + TransferGroup *string `form:"transfer_group"` +} + +// AddExpand appends a new field to expand. +func (p *TransferListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// To send funds from your Stripe account to a connected account, you create a new transfer object. Your [Stripe balance](https://docs.stripe.com/api#balance) must be able to cover the transfer amount, or you'll receive an “Insufficient Funds” error. +type TransferParams struct { + Params `form:"*"` + // A positive integer in cents (or local equivalent) representing how much to transfer. + Amount *int64 `form:"amount"` + // Three-letter [ISO code for currency](https://www.iso.org/iso-4217-currency-codes.html) in lowercase. Must be a [supported currency](https://docs.stripe.com/currencies). + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // The ID of a connected Stripe account. [See the Connect documentation](https://docs.stripe.com/docs/connect/separate-charges-and-transfers) for details. + Destination *string `form:"destination"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // You can use this parameter to transfer funds from a charge before they are added to your available balance. A pending balance will transfer immediately but the funds will not become available until the original charge becomes available. [See the Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-availability) for details. + SourceTransaction *string `form:"source_transaction"` + // The source balance to use for this transfer. One of `bank_account`, `card`, or `fpx`. For most users, this will default to `card`. + SourceType *string `form:"source_type"` + // A string that identifies this transaction as part of a group. See the [Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-options) for details. + TransferGroup *string `form:"transfer_group"` +} + +// AddExpand appends a new field to expand. +func (p *TransferParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TransferParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// To send funds from your Stripe account to a connected account, you create a new transfer object. Your [Stripe balance](https://docs.stripe.com/api#balance) must be able to cover the transfer amount, or you'll receive an “Insufficient Funds” error. +type TransferCreateParams struct { + Params `form:"*"` + // A positive integer in cents (or local equivalent) representing how much to transfer. + Amount *int64 `form:"amount"` + // Three-letter [ISO code for currency](https://www.iso.org/iso-4217-currency-codes.html) in lowercase. Must be a [supported currency](https://docs.stripe.com/currencies). + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // The ID of a connected Stripe account. [See the Connect documentation](https://docs.stripe.com/docs/connect/separate-charges-and-transfers) for details. + Destination *string `form:"destination"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // You can use this parameter to transfer funds from a charge before they are added to your available balance. A pending balance will transfer immediately but the funds will not become available until the original charge becomes available. [See the Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-availability) for details. + SourceTransaction *string `form:"source_transaction"` + // The source balance to use for this transfer. One of `bank_account`, `card`, or `fpx`. For most users, this will default to `card`. + SourceType *string `form:"source_type"` + // A string that identifies this transaction as part of a group. See the [Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-options) for details. + TransferGroup *string `form:"transfer_group"` +} + +// AddExpand appends a new field to expand. +func (p *TransferCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TransferCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the details of an existing transfer. Supply the unique transfer ID from either a transfer creation request or the transfer list, and Stripe will return the corresponding transfer information. +type TransferRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TransferRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the specified transfer by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +// +// This request accepts only metadata as an argument. +type TransferUpdateParams struct { + Params `form:"*"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *TransferUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TransferUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A `Transfer` object is created when you move funds between Stripe accounts as +// part of Connect. +// +// Before April 6, 2017, transfers also represented movement of funds from a +// Stripe account to a card or bank account. This behavior has since been split +// out into a [Payout](https://stripe.com/docs/api#payout_object) object, with corresponding payout endpoints. For more +// information, read about the +// [transfer/payout split](https://stripe.com/docs/transfer-payout-split). +// +// Related guide: [Creating separate charges and transfers](https://stripe.com/docs/connect/separate-charges-and-transfers) +type Transfer struct { + APIResource + // Amount in cents (or local equivalent) to be transferred. + Amount int64 `json:"amount"` + // Amount in cents (or local equivalent) reversed (can be less than the amount attribute on the transfer if a partial reversal was issued). + AmountReversed int64 `json:"amount_reversed"` + // Balance transaction that describes the impact of this transfer on your account balance. + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + // Time that this record of the transfer was first created. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // ID of the Stripe account the transfer was sent to. + Destination *Account `json:"destination"` + // If the destination is a Stripe account, this will be the ID of the payment that the destination account received for the transfer. + DestinationPayment *Charge `json:"destination_payment"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // A list of reversals that have been applied to the transfer. + Reversals *TransferReversalList `json:"reversals"` + // Whether the transfer has been fully reversed. If the transfer is only partially reversed, this attribute will still be false. + Reversed bool `json:"reversed"` + // ID of the charge that was used to fund the transfer. If null, the transfer was funded from the available balance. + SourceTransaction *Charge `json:"source_transaction"` + // The source balance this transfer came from. One of `card`, `fpx`, or `bank_account`. + SourceType TransferSourceType `json:"source_type"` + // A string that identifies this transaction as part of a group. See the [Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-options) for details. + TransferGroup string `json:"transfer_group"` +} + +// TransferList is a list of Transfers as retrieved from a list endpoint. +type TransferList struct { + APIResource + ListMeta + Data []*Transfer `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Transfer. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (t *Transfer) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + t.ID = id + return nil + } + + type transfer Transfer + var v transfer + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *t = Transfer(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/transfer_service.go b/vendor/github.com/stripe/stripe-go/v82/transfer_service.go new file mode 100644 index 00000000..4da6f42a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/transfer_service.go @@ -0,0 +1,74 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TransferService is used to invoke /v1/transfers APIs. +type v1TransferService struct { + B Backend + Key string +} + +// To send funds from your Stripe account to a connected account, you create a new transfer object. Your [Stripe balance](https://docs.stripe.com/api#balance) must be able to cover the transfer amount, or you'll receive an “Insufficient Funds” error. +func (c v1TransferService) Create(ctx context.Context, params *TransferCreateParams) (*Transfer, error) { + if params == nil { + params = &TransferCreateParams{} + } + params.Context = ctx + transfer := &Transfer{} + err := c.B.Call(http.MethodPost, "/v1/transfers", c.Key, params, transfer) + return transfer, err +} + +// Retrieves the details of an existing transfer. Supply the unique transfer ID from either a transfer creation request or the transfer list, and Stripe will return the corresponding transfer information. +func (c v1TransferService) Retrieve(ctx context.Context, id string, params *TransferRetrieveParams) (*Transfer, error) { + if params == nil { + params = &TransferRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/transfers/%s", id) + transfer := &Transfer{} + err := c.B.Call(http.MethodGet, path, c.Key, params, transfer) + return transfer, err +} + +// Updates the specified transfer by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +// +// This request accepts only metadata as an argument. +func (c v1TransferService) Update(ctx context.Context, id string, params *TransferUpdateParams) (*Transfer, error) { + if params == nil { + params = &TransferUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/transfers/%s", id) + transfer := &Transfer{} + err := c.B.Call(http.MethodPost, path, c.Key, params, transfer) + return transfer, err +} + +// Returns a list of existing transfers sent to connected accounts. The transfers are returned in sorted order, with the most recently created transfers appearing first. +func (c v1TransferService) List(ctx context.Context, listParams *TransferListParams) Seq2[*Transfer, error] { + if listParams == nil { + listParams = &TransferListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*Transfer, ListContainer, error) { + list := &TransferList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/transfers", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/transferreversal.go b/vendor/github.com/stripe/stripe-go/v82/transferreversal.go new file mode 100644 index 00000000..b64413b4 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/transferreversal.go @@ -0,0 +1,192 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// You can see a list of the reversals belonging to a specific transfer. Note that the 10 most recent reversals are always available by default on the transfer object. If you need more than those 10, you can use this API method and the limit and starting_after parameters to page through additional reversals. +type TransferReversalListParams struct { + ListParams `form:"*"` + ID *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TransferReversalListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// When you create a new reversal, you must specify a transfer to create it on. +// +// When reversing transfers, you can optionally reverse part of the transfer. You can do so as many times as you wish until the entire transfer has been reversed. +// +// Once entirely reversed, a transfer can't be reversed again. This method will return an error when called on an already-reversed transfer, or when trying to reverse more money than is left on a transfer. +type TransferReversalParams struct { + Params `form:"*"` + ID *string `form:"-"` // Included in URL + // A positive integer in cents (or local equivalent) representing how much of this transfer to reverse. Can only reverse up to the unreversed amount remaining of the transfer. Partial transfer reversals are only allowed for transfers to Stripe Accounts. Defaults to the entire transfer amount. + Amount *int64 `form:"amount"` + // An arbitrary string which you can attach to a reversal object. This will be unset if you POST an empty value. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Boolean indicating whether the application fee should be refunded when reversing this transfer. If a full transfer reversal is given, the full application fee will be refunded. Otherwise, the application fee will be refunded with an amount proportional to the amount of the transfer reversed. + RefundApplicationFee *bool `form:"refund_application_fee"` +} + +// AddExpand appends a new field to expand. +func (p *TransferReversalParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TransferReversalParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// When you create a new reversal, you must specify a transfer to create it on. +// +// When reversing transfers, you can optionally reverse part of the transfer. You can do so as many times as you wish until the entire transfer has been reversed. +// +// Once entirely reversed, a transfer can't be reversed again. This method will return an error when called on an already-reversed transfer, or when trying to reverse more money than is left on a transfer. +type TransferReversalCreateParams struct { + Params `form:"*"` + ID *string `form:"-"` // Included in URL + // A positive integer in cents (or local equivalent) representing how much of this transfer to reverse. Can only reverse up to the unreversed amount remaining of the transfer. Partial transfer reversals are only allowed for transfers to Stripe Accounts. Defaults to the entire transfer amount. + Amount *int64 `form:"amount"` + // An arbitrary string which you can attach to a reversal object. This will be unset if you POST an empty value. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Boolean indicating whether the application fee should be refunded when reversing this transfer. If a full transfer reversal is given, the full application fee will be refunded. Otherwise, the application fee will be refunded with an amount proportional to the amount of the transfer reversed. + RefundApplicationFee *bool `form:"refund_application_fee"` +} + +// AddExpand appends a new field to expand. +func (p *TransferReversalCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TransferReversalCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// By default, you can see the 10 most recent reversals stored directly on the transfer object, but you can also retrieve details about a specific reversal stored on the transfer. +type TransferReversalRetrieveParams struct { + Params `form:"*"` + ID *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TransferReversalRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the specified reversal by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +// +// This request only accepts metadata and description as arguments. +type TransferReversalUpdateParams struct { + Params `form:"*"` + ID *string `form:"-"` // Included in URL + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` +} + +// AddExpand appends a new field to expand. +func (p *TransferReversalUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TransferReversalUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// [Stripe Connect](https://stripe.com/docs/connect) platforms can reverse transfers made to a +// connected account, either entirely or partially, and can also specify whether +// to refund any related application fees. Transfer reversals add to the +// platform's balance and subtract from the destination account's balance. +// +// Reversing a transfer that was made for a [destination +// charge](https://docs.stripe.com/docs/connect/destination-charges) is allowed only up to the amount of +// the charge. It is possible to reverse a +// [transfer_group](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-options) +// transfer only if the destination account has enough balance to cover the +// reversal. +// +// Related guide: [Reverse transfers](https://stripe.com/docs/connect/separate-charges-and-transfers#reverse-transfers) +type TransferReversal struct { + APIResource + // Amount, in cents (or local equivalent). + Amount int64 `json:"amount"` + // Balance transaction that describes the impact on your account balance. + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // Linked payment refund for the transfer reversal. + DestinationPaymentRefund *Refund `json:"destination_payment_refund"` + // Unique identifier for the object. + ID string `json:"id"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // ID of the refund responsible for the transfer reversal. + SourceRefund *Refund `json:"source_refund"` + // ID of the transfer that was reversed. + Transfer *Transfer `json:"transfer"` +} + +// TransferReversalList is a list of TransferReversals as retrieved from a list endpoint. +type TransferReversalList struct { + APIResource + ListMeta + Data []*TransferReversal `json:"data"` +} + +// UnmarshalJSON handles deserialization of a TransferReversal. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (t *TransferReversal) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + t.ID = id + return nil + } + + type transferReversal TransferReversal + var v transferReversal + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *t = TransferReversal(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/transferreversal_service.go b/vendor/github.com/stripe/stripe-go/v82/transferreversal_service.go new file mode 100644 index 00000000..d4d9021d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/transferreversal_service.go @@ -0,0 +1,83 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TransferReversalService is used to invoke /v1/transfers/{id}/reversals APIs. +type v1TransferReversalService struct { + B Backend + Key string +} + +// When you create a new reversal, you must specify a transfer to create it on. +// +// When reversing transfers, you can optionally reverse part of the transfer. You can do so as many times as you wish until the entire transfer has been reversed. +// +// Once entirely reversed, a transfer can't be reversed again. This method will return an error when called on an already-reversed transfer, or when trying to reverse more money than is left on a transfer. +func (c v1TransferReversalService) Create(ctx context.Context, params *TransferReversalCreateParams) (*TransferReversal, error) { + if params == nil { + params = &TransferReversalCreateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/transfers/%s/reversals", StringValue(params.ID)) + transferreversal := &TransferReversal{} + err := c.B.Call(http.MethodPost, path, c.Key, params, transferreversal) + return transferreversal, err +} + +// By default, you can see the 10 most recent reversals stored directly on the transfer object, but you can also retrieve details about a specific reversal stored on the transfer. +func (c v1TransferReversalService) Retrieve(ctx context.Context, id string, params *TransferReversalRetrieveParams) (*TransferReversal, error) { + if params == nil { + params = &TransferReversalRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/transfers/%s/reversals/%s", StringValue(params.ID), id) + transferreversal := &TransferReversal{} + err := c.B.Call(http.MethodGet, path, c.Key, params, transferreversal) + return transferreversal, err +} + +// Updates the specified reversal by setting the values of the parameters passed. Any parameters not provided will be left unchanged. +// +// This request only accepts metadata and description as arguments. +func (c v1TransferReversalService) Update(ctx context.Context, id string, params *TransferReversalUpdateParams) (*TransferReversal, error) { + if params == nil { + params = &TransferReversalUpdateParams{} + } + params.Context = ctx + path := FormatURLPath( + "/v1/transfers/%s/reversals/%s", StringValue(params.ID), id) + transferreversal := &TransferReversal{} + err := c.B.Call(http.MethodPost, path, c.Key, params, transferreversal) + return transferreversal, err +} + +// You can see a list of the reversals belonging to a specific transfer. Note that the 10 most recent reversals are always available by default on the transfer object. If you need more than those 10, you can use this API method and the limit and starting_after parameters to page through additional reversals. +func (c v1TransferReversalService) List(ctx context.Context, listParams *TransferReversalListParams) Seq2[*TransferReversal, error] { + if listParams == nil { + listParams = &TransferReversalListParams{} + } + listParams.Context = ctx + path := FormatURLPath( + "/v1/transfers/%s/reversals", StringValue(listParams.ID)) + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TransferReversal, ListContainer, error) { + list := &TransferReversalList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, path, c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_creditreversal.go b/vendor/github.com/stripe/stripe-go/v82/treasury_creditreversal.go new file mode 100644 index 00000000..106ba13f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_creditreversal.go @@ -0,0 +1,150 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The rails used to reverse the funds. +type TreasuryCreditReversalNetwork string + +// List of values that TreasuryCreditReversalNetwork can take +const ( + TreasuryCreditReversalNetworkACH TreasuryCreditReversalNetwork = "ach" + TreasuryCreditReversalNetworkStripe TreasuryCreditReversalNetwork = "stripe" +) + +// Status of the CreditReversal +type TreasuryCreditReversalStatus string + +// List of values that TreasuryCreditReversalStatus can take +const ( + TreasuryCreditReversalStatusCanceled TreasuryCreditReversalStatus = "canceled" + TreasuryCreditReversalStatusPosted TreasuryCreditReversalStatus = "posted" + TreasuryCreditReversalStatusProcessing TreasuryCreditReversalStatus = "processing" +) + +// Returns a list of CreditReversals. +type TreasuryCreditReversalListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Returns objects associated with this FinancialAccount. + FinancialAccount *string `form:"financial_account"` + // Only return CreditReversals for the ReceivedCredit ID. + ReceivedCredit *string `form:"received_credit"` + // Only return CreditReversals for a given status. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryCreditReversalListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Reverses a ReceivedCredit and creates a CreditReversal object. +type TreasuryCreditReversalParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The ReceivedCredit to reverse. + ReceivedCredit *string `form:"received_credit"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryCreditReversalParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryCreditReversalParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Reverses a ReceivedCredit and creates a CreditReversal object. +type TreasuryCreditReversalCreateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The ReceivedCredit to reverse. + ReceivedCredit *string `form:"received_credit"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryCreditReversalCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryCreditReversalCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the details of an existing CreditReversal by passing the unique CreditReversal ID from either the CreditReversal creation request or CreditReversal list +type TreasuryCreditReversalRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryCreditReversalRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type TreasuryCreditReversalStatusTransitions struct { + // Timestamp describing when the CreditReversal changed status to `posted` + PostedAt int64 `json:"posted_at"` +} + +// You can reverse some [ReceivedCredits](https://stripe.com/docs/api#received_credits) depending on their network and source flow. Reversing a ReceivedCredit leads to the creation of a new object known as a CreditReversal. +type TreasuryCreditReversal struct { + APIResource + // Amount (in cents) transferred. + Amount int64 `json:"amount"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // The FinancialAccount to reverse funds from. + FinancialAccount string `json:"financial_account"` + // A [hosted transaction receipt](https://stripe.com/docs/treasury/moving-money/regulatory-receipts) URL that is provided when money movement is considered regulated under Stripe's money transmission licenses. + HostedRegulatoryReceiptURL string `json:"hosted_regulatory_receipt_url"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // The rails used to reverse the funds. + Network TreasuryCreditReversalNetwork `json:"network"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The ReceivedCredit being reversed. + ReceivedCredit string `json:"received_credit"` + // Status of the CreditReversal + Status TreasuryCreditReversalStatus `json:"status"` + StatusTransitions *TreasuryCreditReversalStatusTransitions `json:"status_transitions"` + // The Transaction associated with this object. + Transaction *TreasuryTransaction `json:"transaction"` +} + +// TreasuryCreditReversalList is a list of CreditReversals as retrieved from a list endpoint. +type TreasuryCreditReversalList struct { + APIResource + ListMeta + Data []*TreasuryCreditReversal `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_creditreversal_service.go b/vendor/github.com/stripe/stripe-go/v82/treasury_creditreversal_service.go new file mode 100644 index 00000000..627e076c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_creditreversal_service.go @@ -0,0 +1,61 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TreasuryCreditReversalService is used to invoke /v1/treasury/credit_reversals APIs. +type v1TreasuryCreditReversalService struct { + B Backend + Key string +} + +// Reverses a ReceivedCredit and creates a CreditReversal object. +func (c v1TreasuryCreditReversalService) Create(ctx context.Context, params *TreasuryCreditReversalCreateParams) (*TreasuryCreditReversal, error) { + if params == nil { + params = &TreasuryCreditReversalCreateParams{} + } + params.Context = ctx + creditreversal := &TreasuryCreditReversal{} + err := c.B.Call( + http.MethodPost, "/v1/treasury/credit_reversals", c.Key, params, creditreversal) + return creditreversal, err +} + +// Retrieves the details of an existing CreditReversal by passing the unique CreditReversal ID from either the CreditReversal creation request or CreditReversal list +func (c v1TreasuryCreditReversalService) Retrieve(ctx context.Context, id string, params *TreasuryCreditReversalRetrieveParams) (*TreasuryCreditReversal, error) { + if params == nil { + params = &TreasuryCreditReversalRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/credit_reversals/%s", id) + creditreversal := &TreasuryCreditReversal{} + err := c.B.Call(http.MethodGet, path, c.Key, params, creditreversal) + return creditreversal, err +} + +// Returns a list of CreditReversals. +func (c v1TreasuryCreditReversalService) List(ctx context.Context, listParams *TreasuryCreditReversalListParams) Seq2[*TreasuryCreditReversal, error] { + if listParams == nil { + listParams = &TreasuryCreditReversalListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TreasuryCreditReversal, ListContainer, error) { + list := &TreasuryCreditReversalList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/treasury/credit_reversals", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_debitreversal.go b/vendor/github.com/stripe/stripe-go/v82/treasury_debitreversal.go new file mode 100644 index 00000000..a114577a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_debitreversal.go @@ -0,0 +1,159 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The rails used to reverse the funds. +type TreasuryDebitReversalNetwork string + +// List of values that TreasuryDebitReversalNetwork can take +const ( + TreasuryDebitReversalNetworkACH TreasuryDebitReversalNetwork = "ach" + TreasuryDebitReversalNetworkCard TreasuryDebitReversalNetwork = "card" +) + +// Status of the DebitReversal +type TreasuryDebitReversalStatus string + +// List of values that TreasuryDebitReversalStatus can take +const ( + TreasuryDebitReversalStatusFailed TreasuryDebitReversalStatus = "failed" + TreasuryDebitReversalStatusProcessing TreasuryDebitReversalStatus = "processing" + TreasuryDebitReversalStatusSucceeded TreasuryDebitReversalStatus = "succeeded" +) + +// Returns a list of DebitReversals. +type TreasuryDebitReversalListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Returns objects associated with this FinancialAccount. + FinancialAccount *string `form:"financial_account"` + // Only return DebitReversals for the ReceivedDebit ID. + ReceivedDebit *string `form:"received_debit"` + // Only return DebitReversals for a given resolution. + Resolution *string `form:"resolution"` + // Only return DebitReversals for a given status. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryDebitReversalListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Reverses a ReceivedDebit and creates a DebitReversal object. +type TreasuryDebitReversalParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The ReceivedDebit to reverse. + ReceivedDebit *string `form:"received_debit"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryDebitReversalParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryDebitReversalParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Reverses a ReceivedDebit and creates a DebitReversal object. +type TreasuryDebitReversalCreateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The ReceivedDebit to reverse. + ReceivedDebit *string `form:"received_debit"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryDebitReversalCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryDebitReversalCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves a DebitReversal object. +type TreasuryDebitReversalRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryDebitReversalRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Other flows linked to a DebitReversal. +type TreasuryDebitReversalLinkedFlows struct { + // Set if there is an Issuing dispute associated with the DebitReversal. + IssuingDispute string `json:"issuing_dispute"` +} +type TreasuryDebitReversalStatusTransitions struct { + // Timestamp describing when the DebitReversal changed status to `completed`. + CompletedAt int64 `json:"completed_at"` +} + +// You can reverse some [ReceivedDebits](https://stripe.com/docs/api#received_debits) depending on their network and source flow. Reversing a ReceivedDebit leads to the creation of a new object known as a DebitReversal. +type TreasuryDebitReversal struct { + APIResource + // Amount (in cents) transferred. + Amount int64 `json:"amount"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // The FinancialAccount to reverse funds from. + FinancialAccount string `json:"financial_account"` + // A [hosted transaction receipt](https://stripe.com/docs/treasury/moving-money/regulatory-receipts) URL that is provided when money movement is considered regulated under Stripe's money transmission licenses. + HostedRegulatoryReceiptURL string `json:"hosted_regulatory_receipt_url"` + // Unique identifier for the object. + ID string `json:"id"` + // Other flows linked to a DebitReversal. + LinkedFlows *TreasuryDebitReversalLinkedFlows `json:"linked_flows"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // The rails used to reverse the funds. + Network TreasuryDebitReversalNetwork `json:"network"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The ReceivedDebit being reversed. + ReceivedDebit string `json:"received_debit"` + // Status of the DebitReversal + Status TreasuryDebitReversalStatus `json:"status"` + StatusTransitions *TreasuryDebitReversalStatusTransitions `json:"status_transitions"` + // The Transaction associated with this object. + Transaction *TreasuryTransaction `json:"transaction"` +} + +// TreasuryDebitReversalList is a list of DebitReversals as retrieved from a list endpoint. +type TreasuryDebitReversalList struct { + APIResource + ListMeta + Data []*TreasuryDebitReversal `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_debitreversal_service.go b/vendor/github.com/stripe/stripe-go/v82/treasury_debitreversal_service.go new file mode 100644 index 00000000..61bc45ea --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_debitreversal_service.go @@ -0,0 +1,61 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TreasuryDebitReversalService is used to invoke /v1/treasury/debit_reversals APIs. +type v1TreasuryDebitReversalService struct { + B Backend + Key string +} + +// Reverses a ReceivedDebit and creates a DebitReversal object. +func (c v1TreasuryDebitReversalService) Create(ctx context.Context, params *TreasuryDebitReversalCreateParams) (*TreasuryDebitReversal, error) { + if params == nil { + params = &TreasuryDebitReversalCreateParams{} + } + params.Context = ctx + debitreversal := &TreasuryDebitReversal{} + err := c.B.Call( + http.MethodPost, "/v1/treasury/debit_reversals", c.Key, params, debitreversal) + return debitreversal, err +} + +// Retrieves a DebitReversal object. +func (c v1TreasuryDebitReversalService) Retrieve(ctx context.Context, id string, params *TreasuryDebitReversalRetrieveParams) (*TreasuryDebitReversal, error) { + if params == nil { + params = &TreasuryDebitReversalRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/debit_reversals/%s", id) + debitreversal := &TreasuryDebitReversal{} + err := c.B.Call(http.MethodGet, path, c.Key, params, debitreversal) + return debitreversal, err +} + +// Returns a list of DebitReversals. +func (c v1TreasuryDebitReversalService) List(ctx context.Context, listParams *TreasuryDebitReversalListParams) Seq2[*TreasuryDebitReversal, error] { + if listParams == nil { + listParams = &TreasuryDebitReversalListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TreasuryDebitReversal, ListContainer, error) { + list := &TreasuryDebitReversalList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/treasury/debit_reversals", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_financialaccount.go b/vendor/github.com/stripe/stripe-go/v82/treasury_financialaccount.go new file mode 100644 index 00000000..2f72ec4d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_financialaccount.go @@ -0,0 +1,728 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The array of paths to active Features in the Features hash. +type TreasuryFinancialAccountActiveFeature string + +// List of values that TreasuryFinancialAccountActiveFeature can take +const ( + TreasuryFinancialAccountActiveFeatureCardIssuing TreasuryFinancialAccountActiveFeature = "card_issuing" + TreasuryFinancialAccountActiveFeatureDepositInsurance TreasuryFinancialAccountActiveFeature = "deposit_insurance" + TreasuryFinancialAccountActiveFeatureFinancialAddressesABA TreasuryFinancialAccountActiveFeature = "financial_addresses.aba" + TreasuryFinancialAccountActiveFeatureFinancialAddressesABAForwarding TreasuryFinancialAccountActiveFeature = "financial_addresses.aba.forwarding" + TreasuryFinancialAccountActiveFeatureInboundTransfersACH TreasuryFinancialAccountActiveFeature = "inbound_transfers.ach" + TreasuryFinancialAccountActiveFeatureIntraStripeFlows TreasuryFinancialAccountActiveFeature = "intra_stripe_flows" + TreasuryFinancialAccountActiveFeatureOutboundPaymentsACH TreasuryFinancialAccountActiveFeature = "outbound_payments.ach" + TreasuryFinancialAccountActiveFeatureOutboundPaymentsUSDomesticWire TreasuryFinancialAccountActiveFeature = "outbound_payments.us_domestic_wire" + TreasuryFinancialAccountActiveFeatureOutboundTransfersACH TreasuryFinancialAccountActiveFeature = "outbound_transfers.ach" + TreasuryFinancialAccountActiveFeatureOutboundTransfersUSDomesticWire TreasuryFinancialAccountActiveFeature = "outbound_transfers.us_domestic_wire" + TreasuryFinancialAccountActiveFeatureRemoteDepositCapture TreasuryFinancialAccountActiveFeature = "remote_deposit_capture" +) + +// The list of networks that the address supports +type TreasuryFinancialAccountFinancialAddressSupportedNetwork string + +// List of values that TreasuryFinancialAccountFinancialAddressSupportedNetwork can take +const ( + TreasuryFinancialAccountFinancialAddressSupportedNetworkACH TreasuryFinancialAccountFinancialAddressSupportedNetwork = "ach" + TreasuryFinancialAccountFinancialAddressSupportedNetworkUSDomesticWire TreasuryFinancialAccountFinancialAddressSupportedNetwork = "us_domestic_wire" +) + +// The type of financial address +type TreasuryFinancialAccountFinancialAddressType string + +// List of values that TreasuryFinancialAccountFinancialAddressType can take +const ( + TreasuryFinancialAccountFinancialAddressTypeABA TreasuryFinancialAccountFinancialAddressType = "aba" +) + +// The array of paths to pending Features in the Features hash. +type TreasuryFinancialAccountPendingFeature string + +// List of values that TreasuryFinancialAccountPendingFeature can take +const ( + TreasuryFinancialAccountPendingFeatureCardIssuing TreasuryFinancialAccountPendingFeature = "card_issuing" + TreasuryFinancialAccountPendingFeatureDepositInsurance TreasuryFinancialAccountPendingFeature = "deposit_insurance" + TreasuryFinancialAccountPendingFeatureFinancialAddressesABA TreasuryFinancialAccountPendingFeature = "financial_addresses.aba" + TreasuryFinancialAccountPendingFeatureFinancialAddressesABAForwarding TreasuryFinancialAccountPendingFeature = "financial_addresses.aba.forwarding" + TreasuryFinancialAccountPendingFeatureInboundTransfersACH TreasuryFinancialAccountPendingFeature = "inbound_transfers.ach" + TreasuryFinancialAccountPendingFeatureIntraStripeFlows TreasuryFinancialAccountPendingFeature = "intra_stripe_flows" + TreasuryFinancialAccountPendingFeatureOutboundPaymentsACH TreasuryFinancialAccountPendingFeature = "outbound_payments.ach" + TreasuryFinancialAccountPendingFeatureOutboundPaymentsUSDomesticWire TreasuryFinancialAccountPendingFeature = "outbound_payments.us_domestic_wire" + TreasuryFinancialAccountPendingFeatureOutboundTransfersACH TreasuryFinancialAccountPendingFeature = "outbound_transfers.ach" + TreasuryFinancialAccountPendingFeatureOutboundTransfersUSDomesticWire TreasuryFinancialAccountPendingFeature = "outbound_transfers.us_domestic_wire" + TreasuryFinancialAccountPendingFeatureRemoteDepositCapture TreasuryFinancialAccountPendingFeature = "remote_deposit_capture" +) + +// Restricts all inbound money movement. +type TreasuryFinancialAccountPlatformRestrictionsInboundFlows string + +// List of values that TreasuryFinancialAccountPlatformRestrictionsInboundFlows can take +const ( + TreasuryFinancialAccountPlatformRestrictionsInboundFlowsRestricted TreasuryFinancialAccountPlatformRestrictionsInboundFlows = "restricted" + TreasuryFinancialAccountPlatformRestrictionsInboundFlowsUnrestricted TreasuryFinancialAccountPlatformRestrictionsInboundFlows = "unrestricted" +) + +// Restricts all outbound money movement. +type TreasuryFinancialAccountPlatformRestrictionsOutboundFlows string + +// List of values that TreasuryFinancialAccountPlatformRestrictionsOutboundFlows can take +const ( + TreasuryFinancialAccountPlatformRestrictionsOutboundFlowsRestricted TreasuryFinancialAccountPlatformRestrictionsOutboundFlows = "restricted" + TreasuryFinancialAccountPlatformRestrictionsOutboundFlowsUnrestricted TreasuryFinancialAccountPlatformRestrictionsOutboundFlows = "unrestricted" +) + +// The array of paths to restricted Features in the Features hash. +type TreasuryFinancialAccountRestrictedFeature string + +// List of values that TreasuryFinancialAccountRestrictedFeature can take +const ( + TreasuryFinancialAccountRestrictedFeatureCardIssuing TreasuryFinancialAccountRestrictedFeature = "card_issuing" + TreasuryFinancialAccountRestrictedFeatureDepositInsurance TreasuryFinancialAccountRestrictedFeature = "deposit_insurance" + TreasuryFinancialAccountRestrictedFeatureFinancialAddressesABA TreasuryFinancialAccountRestrictedFeature = "financial_addresses.aba" + TreasuryFinancialAccountRestrictedFeatureFinancialAddressesABAForwarding TreasuryFinancialAccountRestrictedFeature = "financial_addresses.aba.forwarding" + TreasuryFinancialAccountRestrictedFeatureInboundTransfersACH TreasuryFinancialAccountRestrictedFeature = "inbound_transfers.ach" + TreasuryFinancialAccountRestrictedFeatureIntraStripeFlows TreasuryFinancialAccountRestrictedFeature = "intra_stripe_flows" + TreasuryFinancialAccountRestrictedFeatureOutboundPaymentsACH TreasuryFinancialAccountRestrictedFeature = "outbound_payments.ach" + TreasuryFinancialAccountRestrictedFeatureOutboundPaymentsUSDomesticWire TreasuryFinancialAccountRestrictedFeature = "outbound_payments.us_domestic_wire" + TreasuryFinancialAccountRestrictedFeatureOutboundTransfersACH TreasuryFinancialAccountRestrictedFeature = "outbound_transfers.ach" + TreasuryFinancialAccountRestrictedFeatureOutboundTransfersUSDomesticWire TreasuryFinancialAccountRestrictedFeature = "outbound_transfers.us_domestic_wire" + TreasuryFinancialAccountRestrictedFeatureRemoteDepositCapture TreasuryFinancialAccountRestrictedFeature = "remote_deposit_capture" +) + +// Status of this FinancialAccount. +type TreasuryFinancialAccountStatus string + +// List of values that TreasuryFinancialAccountStatus can take +const ( + TreasuryFinancialAccountStatusClosed TreasuryFinancialAccountStatus = "closed" + TreasuryFinancialAccountStatusOpen TreasuryFinancialAccountStatus = "open" +) + +// The array that contains reasons for a FinancialAccount closure. +type TreasuryFinancialAccountStatusDetailsClosedReason string + +// List of values that TreasuryFinancialAccountStatusDetailsClosedReason can take +const ( + TreasuryFinancialAccountStatusDetailsClosedReasonAccountRejected TreasuryFinancialAccountStatusDetailsClosedReason = "account_rejected" + TreasuryFinancialAccountStatusDetailsClosedReasonClosedByPlatform TreasuryFinancialAccountStatusDetailsClosedReason = "closed_by_platform" + TreasuryFinancialAccountStatusDetailsClosedReasonOther TreasuryFinancialAccountStatusDetailsClosedReason = "other" +) + +// Returns a list of FinancialAccounts. +type TreasuryFinancialAccountListParams struct { + ListParams `form:"*"` + // Only return FinancialAccounts that were created during the given date interval. + Created *int64 `form:"created"` + // Only return FinancialAccounts that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Only return FinancialAccounts that have the given status: `open` or `closed` + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryFinancialAccountListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Encodes the FinancialAccount's ability to be used with the Issuing product, including attaching cards to and drawing funds from the FinancialAccount. +type TreasuryFinancialAccountFeaturesCardIssuingParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Represents whether this FinancialAccount is eligible for deposit insurance. Various factors determine the insurance amount. +type TreasuryFinancialAccountFeaturesDepositInsuranceParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Adds an ABA FinancialAddress to the FinancialAccount. +type TreasuryFinancialAccountFeaturesFinancialAddressesABAParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Contains Features that add FinancialAddresses to the FinancialAccount. +type TreasuryFinancialAccountFeaturesFinancialAddressesParams struct { + // Adds an ABA FinancialAddress to the FinancialAccount. + ABA *TreasuryFinancialAccountFeaturesFinancialAddressesABAParams `form:"aba"` +} + +// Enables ACH Debits via the InboundTransfers API. +type TreasuryFinancialAccountFeaturesInboundTransfersACHParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Contains settings related to adding funds to a FinancialAccount from another Account with the same owner. +type TreasuryFinancialAccountFeaturesInboundTransfersParams struct { + // Enables ACH Debits via the InboundTransfers API. + ACH *TreasuryFinancialAccountFeaturesInboundTransfersACHParams `form:"ach"` +} + +// Represents the ability for the FinancialAccount to send money to, or receive money from other FinancialAccounts (for example, via OutboundPayment). +type TreasuryFinancialAccountFeaturesIntraStripeFlowsParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Enables ACH transfers via the OutboundPayments API. +type TreasuryFinancialAccountFeaturesOutboundPaymentsACHParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Enables US domestic wire transfers via the OutboundPayments API. +type TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Includes Features related to initiating money movement out of the FinancialAccount to someone else's bucket of money. +type TreasuryFinancialAccountFeaturesOutboundPaymentsParams struct { + // Enables ACH transfers via the OutboundPayments API. + ACH *TreasuryFinancialAccountFeaturesOutboundPaymentsACHParams `form:"ach"` + // Enables US domestic wire transfers via the OutboundPayments API. + USDomesticWire *TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireParams `form:"us_domestic_wire"` +} + +// Enables ACH transfers via the OutboundTransfers API. +type TreasuryFinancialAccountFeaturesOutboundTransfersACHParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Enables US domestic wire transfers via the OutboundTransfers API. +type TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Contains a Feature and settings related to moving money out of the FinancialAccount into another Account with the same owner. +type TreasuryFinancialAccountFeaturesOutboundTransfersParams struct { + // Enables ACH transfers via the OutboundTransfers API. + ACH *TreasuryFinancialAccountFeaturesOutboundTransfersACHParams `form:"ach"` + // Enables US domestic wire transfers via the OutboundTransfers API. + USDomesticWire *TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireParams `form:"us_domestic_wire"` +} + +// Encodes whether a FinancialAccount has access to a particular feature. Stripe or the platform can control features via the requested field. +type TreasuryFinancialAccountFeaturesParams struct { + // Encodes the FinancialAccount's ability to be used with the Issuing product, including attaching cards to and drawing funds from the FinancialAccount. + CardIssuing *TreasuryFinancialAccountFeaturesCardIssuingParams `form:"card_issuing"` + // Represents whether this FinancialAccount is eligible for deposit insurance. Various factors determine the insurance amount. + DepositInsurance *TreasuryFinancialAccountFeaturesDepositInsuranceParams `form:"deposit_insurance"` + // Contains Features that add FinancialAddresses to the FinancialAccount. + FinancialAddresses *TreasuryFinancialAccountFeaturesFinancialAddressesParams `form:"financial_addresses"` + // Contains settings related to adding funds to a FinancialAccount from another Account with the same owner. + InboundTransfers *TreasuryFinancialAccountFeaturesInboundTransfersParams `form:"inbound_transfers"` + // Represents the ability for the FinancialAccount to send money to, or receive money from other FinancialAccounts (for example, via OutboundPayment). + IntraStripeFlows *TreasuryFinancialAccountFeaturesIntraStripeFlowsParams `form:"intra_stripe_flows"` + // Includes Features related to initiating money movement out of the FinancialAccount to someone else's bucket of money. + OutboundPayments *TreasuryFinancialAccountFeaturesOutboundPaymentsParams `form:"outbound_payments"` + // Contains a Feature and settings related to moving money out of the FinancialAccount into another Account with the same owner. + OutboundTransfers *TreasuryFinancialAccountFeaturesOutboundTransfersParams `form:"outbound_transfers"` +} + +// The set of functionalities that the platform can restrict on the FinancialAccount. +type TreasuryFinancialAccountPlatformRestrictionsParams struct { + // Restricts all inbound money movement. + InboundFlows *string `form:"inbound_flows"` + // Restricts all outbound money movement. + OutboundFlows *string `form:"outbound_flows"` +} + +// Creates a new FinancialAccount. Each connected account can have up to three FinancialAccounts by default. +type TreasuryFinancialAccountParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Encodes whether a FinancialAccount has access to a particular feature, with a status enum and associated `status_details`. Stripe or the platform may control features via the requested field. + Features *TreasuryFinancialAccountFeaturesParams `form:"features"` + // A different bank account where funds can be deposited/debited in order to get the closing FA's balance to $0 + ForwardingSettings *TreasuryFinancialAccountForwardingSettingsParams `form:"forwarding_settings"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The nickname for the FinancialAccount. + Nickname *string `form:"nickname"` + // The set of functionalities that the platform can restrict on the FinancialAccount. + PlatformRestrictions *TreasuryFinancialAccountPlatformRestrictionsParams `form:"platform_restrictions"` + // The currencies the FinancialAccount can hold a balance in. + SupportedCurrencies []*string `form:"supported_currencies"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryFinancialAccountParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryFinancialAccountParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A different bank account where funds can be deposited/debited in order to get the closing FA's balance to $0 +type TreasuryFinancialAccountForwardingSettingsParams struct { + // The financial_account id + FinancialAccount *string `form:"financial_account"` + // The payment_method or bank account id. This needs to be a verified bank account. + PaymentMethod *string `form:"payment_method"` + // The type of the bank account provided. This can be either "financial_account" or "payment_method" + Type *string `form:"type"` +} + +// Retrieves Features information associated with the FinancialAccount. +type TreasuryFinancialAccountRetrieveFeaturesParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryFinancialAccountRetrieveFeaturesParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Encodes the FinancialAccount's ability to be used with the Issuing product, including attaching cards to and drawing funds from the FinancialAccount. +type TreasuryFinancialAccountUpdateFeaturesCardIssuingParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Represents whether this FinancialAccount is eligible for deposit insurance. Various factors determine the insurance amount. +type TreasuryFinancialAccountUpdateFeaturesDepositInsuranceParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Adds an ABA FinancialAddress to the FinancialAccount. +type TreasuryFinancialAccountUpdateFeaturesFinancialAddressesABAParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Contains Features that add FinancialAddresses to the FinancialAccount. +type TreasuryFinancialAccountUpdateFeaturesFinancialAddressesParams struct { + // Adds an ABA FinancialAddress to the FinancialAccount. + ABA *TreasuryFinancialAccountUpdateFeaturesFinancialAddressesABAParams `form:"aba"` +} + +// Enables ACH Debits via the InboundTransfers API. +type TreasuryFinancialAccountUpdateFeaturesInboundTransfersACHParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Contains settings related to adding funds to a FinancialAccount from another Account with the same owner. +type TreasuryFinancialAccountUpdateFeaturesInboundTransfersParams struct { + // Enables ACH Debits via the InboundTransfers API. + ACH *TreasuryFinancialAccountUpdateFeaturesInboundTransfersACHParams `form:"ach"` +} + +// Represents the ability for the FinancialAccount to send money to, or receive money from other FinancialAccounts (for example, via OutboundPayment). +type TreasuryFinancialAccountUpdateFeaturesIntraStripeFlowsParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Enables ACH transfers via the OutboundPayments API. +type TreasuryFinancialAccountUpdateFeaturesOutboundPaymentsACHParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Enables US domestic wire transfers via the OutboundPayments API. +type TreasuryFinancialAccountUpdateFeaturesOutboundPaymentsUSDomesticWireParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Includes Features related to initiating money movement out of the FinancialAccount to someone else's bucket of money. +type TreasuryFinancialAccountUpdateFeaturesOutboundPaymentsParams struct { + // Enables ACH transfers via the OutboundPayments API. + ACH *TreasuryFinancialAccountUpdateFeaturesOutboundPaymentsACHParams `form:"ach"` + // Enables US domestic wire transfers via the OutboundPayments API. + USDomesticWire *TreasuryFinancialAccountUpdateFeaturesOutboundPaymentsUSDomesticWireParams `form:"us_domestic_wire"` +} + +// Enables ACH transfers via the OutboundTransfers API. +type TreasuryFinancialAccountUpdateFeaturesOutboundTransfersACHParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Enables US domestic wire transfers via the OutboundTransfers API. +type TreasuryFinancialAccountUpdateFeaturesOutboundTransfersUSDomesticWireParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Contains a Feature and settings related to moving money out of the FinancialAccount into another Account with the same owner. +type TreasuryFinancialAccountUpdateFeaturesOutboundTransfersParams struct { + // Enables ACH transfers via the OutboundTransfers API. + ACH *TreasuryFinancialAccountUpdateFeaturesOutboundTransfersACHParams `form:"ach"` + // Enables US domestic wire transfers via the OutboundTransfers API. + USDomesticWire *TreasuryFinancialAccountUpdateFeaturesOutboundTransfersUSDomesticWireParams `form:"us_domestic_wire"` +} + +// Encodes whether a FinancialAccount has access to a particular feature, with a status enum and associated `status_details`. Stripe or the platform may control features via the requested field. +type TreasuryFinancialAccountUpdateFeaturesParams struct { + Params `form:"*"` + // Encodes the FinancialAccount's ability to be used with the Issuing product, including attaching cards to and drawing funds from the FinancialAccount. + CardIssuing *TreasuryFinancialAccountUpdateFeaturesCardIssuingParams `form:"card_issuing"` + // Represents whether this FinancialAccount is eligible for deposit insurance. Various factors determine the insurance amount. + DepositInsurance *TreasuryFinancialAccountUpdateFeaturesDepositInsuranceParams `form:"deposit_insurance"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Contains Features that add FinancialAddresses to the FinancialAccount. + FinancialAddresses *TreasuryFinancialAccountUpdateFeaturesFinancialAddressesParams `form:"financial_addresses"` + // Contains settings related to adding funds to a FinancialAccount from another Account with the same owner. + InboundTransfers *TreasuryFinancialAccountUpdateFeaturesInboundTransfersParams `form:"inbound_transfers"` + // Represents the ability for the FinancialAccount to send money to, or receive money from other FinancialAccounts (for example, via OutboundPayment). + IntraStripeFlows *TreasuryFinancialAccountUpdateFeaturesIntraStripeFlowsParams `form:"intra_stripe_flows"` + // Includes Features related to initiating money movement out of the FinancialAccount to someone else's bucket of money. + OutboundPayments *TreasuryFinancialAccountUpdateFeaturesOutboundPaymentsParams `form:"outbound_payments"` + // Contains a Feature and settings related to moving money out of the FinancialAccount into another Account with the same owner. + OutboundTransfers *TreasuryFinancialAccountUpdateFeaturesOutboundTransfersParams `form:"outbound_transfers"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryFinancialAccountUpdateFeaturesParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A different bank account where funds can be deposited/debited in order to get the closing FA's balance to $0 +type TreasuryFinancialAccountCloseForwardingSettingsParams struct { + // The financial_account id + FinancialAccount *string `form:"financial_account"` + // The payment_method or bank account id. This needs to be a verified bank account. + PaymentMethod *string `form:"payment_method"` + // The type of the bank account provided. This can be either "financial_account" or "payment_method" + Type *string `form:"type"` +} + +// Closes a FinancialAccount. A FinancialAccount can only be closed if it has a zero balance, has no pending InboundTransfers, and has canceled all attached Issuing cards. +type TreasuryFinancialAccountCloseParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // A different bank account where funds can be deposited/debited in order to get the closing FA's balance to $0 + ForwardingSettings *TreasuryFinancialAccountCloseForwardingSettingsParams `form:"forwarding_settings"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryFinancialAccountCloseParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Encodes the FinancialAccount's ability to be used with the Issuing product, including attaching cards to and drawing funds from the FinancialAccount. +type TreasuryFinancialAccountCreateFeaturesCardIssuingParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Represents whether this FinancialAccount is eligible for deposit insurance. Various factors determine the insurance amount. +type TreasuryFinancialAccountCreateFeaturesDepositInsuranceParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Adds an ABA FinancialAddress to the FinancialAccount. +type TreasuryFinancialAccountCreateFeaturesFinancialAddressesABAParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Contains Features that add FinancialAddresses to the FinancialAccount. +type TreasuryFinancialAccountCreateFeaturesFinancialAddressesParams struct { + // Adds an ABA FinancialAddress to the FinancialAccount. + ABA *TreasuryFinancialAccountCreateFeaturesFinancialAddressesABAParams `form:"aba"` +} + +// Enables ACH Debits via the InboundTransfers API. +type TreasuryFinancialAccountCreateFeaturesInboundTransfersACHParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Contains settings related to adding funds to a FinancialAccount from another Account with the same owner. +type TreasuryFinancialAccountCreateFeaturesInboundTransfersParams struct { + // Enables ACH Debits via the InboundTransfers API. + ACH *TreasuryFinancialAccountCreateFeaturesInboundTransfersACHParams `form:"ach"` +} + +// Represents the ability for the FinancialAccount to send money to, or receive money from other FinancialAccounts (for example, via OutboundPayment). +type TreasuryFinancialAccountCreateFeaturesIntraStripeFlowsParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Enables ACH transfers via the OutboundPayments API. +type TreasuryFinancialAccountCreateFeaturesOutboundPaymentsACHParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Enables US domestic wire transfers via the OutboundPayments API. +type TreasuryFinancialAccountCreateFeaturesOutboundPaymentsUSDomesticWireParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Includes Features related to initiating money movement out of the FinancialAccount to someone else's bucket of money. +type TreasuryFinancialAccountCreateFeaturesOutboundPaymentsParams struct { + // Enables ACH transfers via the OutboundPayments API. + ACH *TreasuryFinancialAccountCreateFeaturesOutboundPaymentsACHParams `form:"ach"` + // Enables US domestic wire transfers via the OutboundPayments API. + USDomesticWire *TreasuryFinancialAccountCreateFeaturesOutboundPaymentsUSDomesticWireParams `form:"us_domestic_wire"` +} + +// Enables ACH transfers via the OutboundTransfers API. +type TreasuryFinancialAccountCreateFeaturesOutboundTransfersACHParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Enables US domestic wire transfers via the OutboundTransfers API. +type TreasuryFinancialAccountCreateFeaturesOutboundTransfersUSDomesticWireParams struct { + // Whether the FinancialAccount should have the Feature. + Requested *bool `form:"requested"` +} + +// Contains a Feature and settings related to moving money out of the FinancialAccount into another Account with the same owner. +type TreasuryFinancialAccountCreateFeaturesOutboundTransfersParams struct { + // Enables ACH transfers via the OutboundTransfers API. + ACH *TreasuryFinancialAccountCreateFeaturesOutboundTransfersACHParams `form:"ach"` + // Enables US domestic wire transfers via the OutboundTransfers API. + USDomesticWire *TreasuryFinancialAccountCreateFeaturesOutboundTransfersUSDomesticWireParams `form:"us_domestic_wire"` +} + +// Encodes whether a FinancialAccount has access to a particular feature. Stripe or the platform can control features via the requested field. +type TreasuryFinancialAccountCreateFeaturesParams struct { + // Encodes the FinancialAccount's ability to be used with the Issuing product, including attaching cards to and drawing funds from the FinancialAccount. + CardIssuing *TreasuryFinancialAccountCreateFeaturesCardIssuingParams `form:"card_issuing"` + // Represents whether this FinancialAccount is eligible for deposit insurance. Various factors determine the insurance amount. + DepositInsurance *TreasuryFinancialAccountCreateFeaturesDepositInsuranceParams `form:"deposit_insurance"` + // Contains Features that add FinancialAddresses to the FinancialAccount. + FinancialAddresses *TreasuryFinancialAccountCreateFeaturesFinancialAddressesParams `form:"financial_addresses"` + // Contains settings related to adding funds to a FinancialAccount from another Account with the same owner. + InboundTransfers *TreasuryFinancialAccountCreateFeaturesInboundTransfersParams `form:"inbound_transfers"` + // Represents the ability for the FinancialAccount to send money to, or receive money from other FinancialAccounts (for example, via OutboundPayment). + IntraStripeFlows *TreasuryFinancialAccountCreateFeaturesIntraStripeFlowsParams `form:"intra_stripe_flows"` + // Includes Features related to initiating money movement out of the FinancialAccount to someone else's bucket of money. + OutboundPayments *TreasuryFinancialAccountCreateFeaturesOutboundPaymentsParams `form:"outbound_payments"` + // Contains a Feature and settings related to moving money out of the FinancialAccount into another Account with the same owner. + OutboundTransfers *TreasuryFinancialAccountCreateFeaturesOutboundTransfersParams `form:"outbound_transfers"` +} + +// The set of functionalities that the platform can restrict on the FinancialAccount. +type TreasuryFinancialAccountCreatePlatformRestrictionsParams struct { + // Restricts all inbound money movement. + InboundFlows *string `form:"inbound_flows"` + // Restricts all outbound money movement. + OutboundFlows *string `form:"outbound_flows"` +} + +// Creates a new FinancialAccount. Each connected account can have up to three FinancialAccounts by default. +type TreasuryFinancialAccountCreateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Encodes whether a FinancialAccount has access to a particular feature. Stripe or the platform can control features via the requested field. + Features *TreasuryFinancialAccountCreateFeaturesParams `form:"features"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The nickname for the FinancialAccount. + Nickname *string `form:"nickname"` + // The set of functionalities that the platform can restrict on the FinancialAccount. + PlatformRestrictions *TreasuryFinancialAccountCreatePlatformRestrictionsParams `form:"platform_restrictions"` + // The currencies the FinancialAccount can hold a balance in. + SupportedCurrencies []*string `form:"supported_currencies"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryFinancialAccountCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryFinancialAccountCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the details of a FinancialAccount. +type TreasuryFinancialAccountRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryFinancialAccountRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// A different bank account where funds can be deposited/debited in order to get the closing FA's balance to $0 +type TreasuryFinancialAccountUpdateForwardingSettingsParams struct { + // The financial_account id + FinancialAccount *string `form:"financial_account"` + // The payment_method or bank account id. This needs to be a verified bank account. + PaymentMethod *string `form:"payment_method"` + // The type of the bank account provided. This can be either "financial_account" or "payment_method" + Type *string `form:"type"` +} + +// The set of functionalities that the platform can restrict on the FinancialAccount. +type TreasuryFinancialAccountUpdatePlatformRestrictionsParams struct { + // Restricts all inbound money movement. + InboundFlows *string `form:"inbound_flows"` + // Restricts all outbound money movement. + OutboundFlows *string `form:"outbound_flows"` +} + +// Updates the details of a FinancialAccount. +type TreasuryFinancialAccountUpdateParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Encodes whether a FinancialAccount has access to a particular feature, with a status enum and associated `status_details`. Stripe or the platform may control features via the requested field. + Features *TreasuryFinancialAccountUpdateFeaturesParams `form:"features"` + // A different bank account where funds can be deposited/debited in order to get the closing FA's balance to $0 + ForwardingSettings *TreasuryFinancialAccountUpdateForwardingSettingsParams `form:"forwarding_settings"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The nickname for the FinancialAccount. + Nickname *string `form:"nickname"` + // The set of functionalities that the platform can restrict on the FinancialAccount. + PlatformRestrictions *TreasuryFinancialAccountUpdatePlatformRestrictionsParams `form:"platform_restrictions"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryFinancialAccountUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryFinancialAccountUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Balance information for the FinancialAccount +type TreasuryFinancialAccountBalance struct { + // Funds the user can spend right now. + Cash map[string]int64 `json:"cash"` + // Funds not spendable yet, but will become available at a later time. + InboundPending map[string]int64 `json:"inbound_pending"` + // Funds in the account, but not spendable because they are being held for pending outbound flows. + OutboundPending map[string]int64 `json:"outbound_pending"` +} + +// ABA Records contain U.S. bank account details per the ABA format. +type TreasuryFinancialAccountFinancialAddressABA struct { + // The name of the person or business that owns the bank account. + AccountHolderName string `json:"account_holder_name"` + // The account number. + AccountNumber string `json:"account_number"` + // The last four characters of the account number. + AccountNumberLast4 string `json:"account_number_last4"` + // Name of the bank. + BankName string `json:"bank_name"` + // Routing number for the account. + RoutingNumber string `json:"routing_number"` +} + +// The set of credentials that resolve to a FinancialAccount. +type TreasuryFinancialAccountFinancialAddress struct { + // ABA Records contain U.S. bank account details per the ABA format. + ABA *TreasuryFinancialAccountFinancialAddressABA `json:"aba"` + // The list of networks that the address supports + SupportedNetworks []TreasuryFinancialAccountFinancialAddressSupportedNetwork `json:"supported_networks"` + // The type of financial address + Type TreasuryFinancialAccountFinancialAddressType `json:"type"` +} + +// The set of functionalities that the platform can restrict on the FinancialAccount. +type TreasuryFinancialAccountPlatformRestrictions struct { + // Restricts all inbound money movement. + InboundFlows TreasuryFinancialAccountPlatformRestrictionsInboundFlows `json:"inbound_flows"` + // Restricts all outbound money movement. + OutboundFlows TreasuryFinancialAccountPlatformRestrictionsOutboundFlows `json:"outbound_flows"` +} + +// Details related to the closure of this FinancialAccount +type TreasuryFinancialAccountStatusDetailsClosed struct { + // The array that contains reasons for a FinancialAccount closure. + Reasons []TreasuryFinancialAccountStatusDetailsClosedReason `json:"reasons"` +} +type TreasuryFinancialAccountStatusDetails struct { + // Details related to the closure of this FinancialAccount + Closed *TreasuryFinancialAccountStatusDetailsClosed `json:"closed"` +} + +// Stripe Treasury provides users with a container for money called a FinancialAccount that is separate from their Payments balance. +// FinancialAccounts serve as the source and destination of Treasury's money movement APIs. +type TreasuryFinancialAccount struct { + APIResource + // The array of paths to active Features in the Features hash. + ActiveFeatures []TreasuryFinancialAccountActiveFeature `json:"active_features"` + // Balance information for the FinancialAccount + Balance *TreasuryFinancialAccountBalance `json:"balance"` + // Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + Country string `json:"country"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Encodes whether a FinancialAccount has access to a particular Feature, with a `status` enum and associated `status_details`. + // Stripe or the platform can control Features via the requested field. + Features *TreasuryFinancialAccountFeatures `json:"features"` + // The set of credentials that resolve to a FinancialAccount. + FinancialAddresses []*TreasuryFinancialAccountFinancialAddress `json:"financial_addresses"` + // Unique identifier for the object. + ID string `json:"id"` + IsDefault bool `json:"is_default"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // The nickname for the FinancialAccount. + Nickname string `json:"nickname"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The array of paths to pending Features in the Features hash. + PendingFeatures []TreasuryFinancialAccountPendingFeature `json:"pending_features"` + // The set of functionalities that the platform can restrict on the FinancialAccount. + PlatformRestrictions *TreasuryFinancialAccountPlatformRestrictions `json:"platform_restrictions"` + // The array of paths to restricted Features in the Features hash. + RestrictedFeatures []TreasuryFinancialAccountRestrictedFeature `json:"restricted_features"` + // Status of this FinancialAccount. + Status TreasuryFinancialAccountStatus `json:"status"` + StatusDetails *TreasuryFinancialAccountStatusDetails `json:"status_details"` + // The currencies the FinancialAccount can hold a balance in. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + SupportedCurrencies []Currency `json:"supported_currencies"` +} + +// TreasuryFinancialAccountList is a list of FinancialAccounts as retrieved from a list endpoint. +type TreasuryFinancialAccountList struct { + APIResource + ListMeta + Data []*TreasuryFinancialAccount `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_financialaccount_service.go b/vendor/github.com/stripe/stripe-go/v82/treasury_financialaccount_service.go new file mode 100644 index 00000000..41e21834 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_financialaccount_service.go @@ -0,0 +1,110 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TreasuryFinancialAccountService is used to invoke /v1/treasury/financial_accounts APIs. +type v1TreasuryFinancialAccountService struct { + B Backend + Key string +} + +// Creates a new FinancialAccount. Each connected account can have up to three FinancialAccounts by default. +func (c v1TreasuryFinancialAccountService) Create(ctx context.Context, params *TreasuryFinancialAccountCreateParams) (*TreasuryFinancialAccount, error) { + if params == nil { + params = &TreasuryFinancialAccountCreateParams{} + } + params.Context = ctx + financialaccount := &TreasuryFinancialAccount{} + err := c.B.Call( + http.MethodPost, "/v1/treasury/financial_accounts", c.Key, params, financialaccount) + return financialaccount, err +} + +// Retrieves the details of a FinancialAccount. +func (c v1TreasuryFinancialAccountService) Retrieve(ctx context.Context, id string, params *TreasuryFinancialAccountRetrieveParams) (*TreasuryFinancialAccount, error) { + if params == nil { + params = &TreasuryFinancialAccountRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/financial_accounts/%s", id) + financialaccount := &TreasuryFinancialAccount{} + err := c.B.Call(http.MethodGet, path, c.Key, params, financialaccount) + return financialaccount, err +} + +// Updates the details of a FinancialAccount. +func (c v1TreasuryFinancialAccountService) Update(ctx context.Context, id string, params *TreasuryFinancialAccountUpdateParams) (*TreasuryFinancialAccount, error) { + if params == nil { + params = &TreasuryFinancialAccountUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/financial_accounts/%s", id) + financialaccount := &TreasuryFinancialAccount{} + err := c.B.Call(http.MethodPost, path, c.Key, params, financialaccount) + return financialaccount, err +} + +// Closes a FinancialAccount. A FinancialAccount can only be closed if it has a zero balance, has no pending InboundTransfers, and has canceled all attached Issuing cards. +func (c v1TreasuryFinancialAccountService) Close(ctx context.Context, id string, params *TreasuryFinancialAccountCloseParams) (*TreasuryFinancialAccount, error) { + if params == nil { + params = &TreasuryFinancialAccountCloseParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/financial_accounts/%s/close", id) + financialaccount := &TreasuryFinancialAccount{} + err := c.B.Call(http.MethodPost, path, c.Key, params, financialaccount) + return financialaccount, err +} + +// Retrieves Features information associated with the FinancialAccount. +func (c v1TreasuryFinancialAccountService) RetrieveFeatures(ctx context.Context, id string, params *TreasuryFinancialAccountRetrieveFeaturesParams) (*TreasuryFinancialAccountFeatures, error) { + if params == nil { + params = &TreasuryFinancialAccountRetrieveFeaturesParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/financial_accounts/%s/features", id) + financialaccountfeatures := &TreasuryFinancialAccountFeatures{} + err := c.B.Call(http.MethodGet, path, c.Key, params, financialaccountfeatures) + return financialaccountfeatures, err +} + +// Updates the Features associated with a FinancialAccount. +func (c v1TreasuryFinancialAccountService) UpdateFeatures(ctx context.Context, id string, params *TreasuryFinancialAccountUpdateFeaturesParams) (*TreasuryFinancialAccountFeatures, error) { + if params == nil { + params = &TreasuryFinancialAccountUpdateFeaturesParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/financial_accounts/%s/features", id) + financialaccountfeatures := &TreasuryFinancialAccountFeatures{} + err := c.B.Call( + http.MethodPost, path, c.Key, params, financialaccountfeatures) + return financialaccountfeatures, err +} + +// Returns a list of FinancialAccounts. +func (c v1TreasuryFinancialAccountService) List(ctx context.Context, listParams *TreasuryFinancialAccountListParams) Seq2[*TreasuryFinancialAccount, error] { + if listParams == nil { + listParams = &TreasuryFinancialAccountListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TreasuryFinancialAccount, ListContainer, error) { + list := &TreasuryFinancialAccountList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/treasury/financial_accounts", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_financialaccountfeatures.go b/vendor/github.com/stripe/stripe-go/v82/treasury_financialaccountfeatures.go new file mode 100644 index 00000000..80947d9b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_financialaccountfeatures.go @@ -0,0 +1,642 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Whether the Feature is operational. +type TreasuryFinancialAccountFeaturesCardIssuingStatus string + +// List of values that TreasuryFinancialAccountFeaturesCardIssuingStatus can take +const ( + TreasuryFinancialAccountFeaturesCardIssuingStatusActive TreasuryFinancialAccountFeaturesCardIssuingStatus = "active" + TreasuryFinancialAccountFeaturesCardIssuingStatusPending TreasuryFinancialAccountFeaturesCardIssuingStatus = "pending" + TreasuryFinancialAccountFeaturesCardIssuingStatusRestricted TreasuryFinancialAccountFeaturesCardIssuingStatus = "restricted" +) + +// Represents the reason why the status is `pending` or `restricted`. +type TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCode string + +// List of values that TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCode can take +const ( + TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCodeActivating TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCode = "activating" + TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCodeCapabilityNotRequested TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCode = "capability_not_requested" + TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCodeFinancialAccountClosed TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCode = "financial_account_closed" + TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCodeRejectedOther TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCode = "rejected_other" + TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCodeRejectedUnsupportedBusiness TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCode = "rejected_unsupported_business" + TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCodeRequirementsPastDue TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCode = "requirements_past_due" + TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCodeRequirementsPendingVerification TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCode = "requirements_pending_verification" + TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCodeRestrictedByPlatform TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCode = "restricted_by_platform" + TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCodeRestrictedOther TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCode = "restricted_other" +) + +// Represents what the user should do, if anything, to activate the Feature. +type TreasuryFinancialAccountFeaturesCardIssuingStatusDetailResolution string + +// List of values that TreasuryFinancialAccountFeaturesCardIssuingStatusDetailResolution can take +const ( + TreasuryFinancialAccountFeaturesCardIssuingStatusDetailResolutionContactStripe TreasuryFinancialAccountFeaturesCardIssuingStatusDetailResolution = "contact_stripe" + TreasuryFinancialAccountFeaturesCardIssuingStatusDetailResolutionProvideInformation TreasuryFinancialAccountFeaturesCardIssuingStatusDetailResolution = "provide_information" + TreasuryFinancialAccountFeaturesCardIssuingStatusDetailResolutionRemoveRestriction TreasuryFinancialAccountFeaturesCardIssuingStatusDetailResolution = "remove_restriction" +) + +// The `platform_restrictions` that are restricting this Feature. +type TreasuryFinancialAccountFeaturesCardIssuingStatusDetailRestriction string + +// List of values that TreasuryFinancialAccountFeaturesCardIssuingStatusDetailRestriction can take +const ( + TreasuryFinancialAccountFeaturesCardIssuingStatusDetailRestrictionInboundFlows TreasuryFinancialAccountFeaturesCardIssuingStatusDetailRestriction = "inbound_flows" + TreasuryFinancialAccountFeaturesCardIssuingStatusDetailRestrictionOutboundFlows TreasuryFinancialAccountFeaturesCardIssuingStatusDetailRestriction = "outbound_flows" +) + +// Whether the Feature is operational. +type TreasuryFinancialAccountFeaturesDepositInsuranceStatus string + +// List of values that TreasuryFinancialAccountFeaturesDepositInsuranceStatus can take +const ( + TreasuryFinancialAccountFeaturesDepositInsuranceStatusActive TreasuryFinancialAccountFeaturesDepositInsuranceStatus = "active" + TreasuryFinancialAccountFeaturesDepositInsuranceStatusPending TreasuryFinancialAccountFeaturesDepositInsuranceStatus = "pending" + TreasuryFinancialAccountFeaturesDepositInsuranceStatusRestricted TreasuryFinancialAccountFeaturesDepositInsuranceStatus = "restricted" +) + +// Represents the reason why the status is `pending` or `restricted`. +type TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCode string + +// List of values that TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCode can take +const ( + TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCodeActivating TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCode = "activating" + TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCodeCapabilityNotRequested TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCode = "capability_not_requested" + TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCodeFinancialAccountClosed TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCode = "financial_account_closed" + TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCodeRejectedOther TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCode = "rejected_other" + TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCodeRejectedUnsupportedBusiness TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCode = "rejected_unsupported_business" + TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCodeRequirementsPastDue TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCode = "requirements_past_due" + TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCodeRequirementsPendingVerification TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCode = "requirements_pending_verification" + TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCodeRestrictedByPlatform TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCode = "restricted_by_platform" + TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCodeRestrictedOther TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCode = "restricted_other" +) + +// Represents what the user should do, if anything, to activate the Feature. +type TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailResolution string + +// List of values that TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailResolution can take +const ( + TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailResolutionContactStripe TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailResolution = "contact_stripe" + TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailResolutionProvideInformation TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailResolution = "provide_information" + TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailResolutionRemoveRestriction TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailResolution = "remove_restriction" +) + +// The `platform_restrictions` that are restricting this Feature. +type TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailRestriction string + +// List of values that TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailRestriction can take +const ( + TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailRestrictionInboundFlows TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailRestriction = "inbound_flows" + TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailRestrictionOutboundFlows TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailRestriction = "outbound_flows" +) + +// Whether the Feature is operational. +type TreasuryFinancialAccountFeaturesFinancialAddressesABAStatus string + +// List of values that TreasuryFinancialAccountFeaturesFinancialAddressesABAStatus can take +const ( + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusActive TreasuryFinancialAccountFeaturesFinancialAddressesABAStatus = "active" + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusPending TreasuryFinancialAccountFeaturesFinancialAddressesABAStatus = "pending" + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusRestricted TreasuryFinancialAccountFeaturesFinancialAddressesABAStatus = "restricted" +) + +// Represents the reason why the status is `pending` or `restricted`. +type TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCode string + +// List of values that TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCode can take +const ( + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCodeActivating TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCode = "activating" + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCodeCapabilityNotRequested TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCode = "capability_not_requested" + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCodeFinancialAccountClosed TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCode = "financial_account_closed" + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCodeRejectedOther TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCode = "rejected_other" + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCodeRejectedUnsupportedBusiness TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCode = "rejected_unsupported_business" + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCodeRequirementsPastDue TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCode = "requirements_past_due" + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCodeRequirementsPendingVerification TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCode = "requirements_pending_verification" + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCodeRestrictedByPlatform TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCode = "restricted_by_platform" + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCodeRestrictedOther TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCode = "restricted_other" +) + +// Represents what the user should do, if anything, to activate the Feature. +type TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailResolution string + +// List of values that TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailResolution can take +const ( + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailResolutionContactStripe TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailResolution = "contact_stripe" + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailResolutionProvideInformation TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailResolution = "provide_information" + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailResolutionRemoveRestriction TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailResolution = "remove_restriction" +) + +// The `platform_restrictions` that are restricting this Feature. +type TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailRestriction string + +// List of values that TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailRestriction can take +const ( + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailRestrictionInboundFlows TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailRestriction = "inbound_flows" + TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailRestrictionOutboundFlows TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailRestriction = "outbound_flows" +) + +// Whether the Feature is operational. +type TreasuryFinancialAccountFeaturesInboundTransfersACHStatus string + +// List of values that TreasuryFinancialAccountFeaturesInboundTransfersACHStatus can take +const ( + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusActive TreasuryFinancialAccountFeaturesInboundTransfersACHStatus = "active" + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusPending TreasuryFinancialAccountFeaturesInboundTransfersACHStatus = "pending" + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusRestricted TreasuryFinancialAccountFeaturesInboundTransfersACHStatus = "restricted" +) + +// Represents the reason why the status is `pending` or `restricted`. +type TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCode string + +// List of values that TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCode can take +const ( + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCodeActivating TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCode = "activating" + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCodeCapabilityNotRequested TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCode = "capability_not_requested" + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCodeFinancialAccountClosed TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCode = "financial_account_closed" + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCodeRejectedOther TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCode = "rejected_other" + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCodeRejectedUnsupportedBusiness TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCode = "rejected_unsupported_business" + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCodeRequirementsPastDue TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCode = "requirements_past_due" + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCodeRequirementsPendingVerification TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCode = "requirements_pending_verification" + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCodeRestrictedByPlatform TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCode = "restricted_by_platform" + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCodeRestrictedOther TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCode = "restricted_other" +) + +// Represents what the user should do, if anything, to activate the Feature. +type TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailResolution string + +// List of values that TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailResolution can take +const ( + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailResolutionContactStripe TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailResolution = "contact_stripe" + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailResolutionProvideInformation TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailResolution = "provide_information" + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailResolutionRemoveRestriction TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailResolution = "remove_restriction" +) + +// The `platform_restrictions` that are restricting this Feature. +type TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailRestriction string + +// List of values that TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailRestriction can take +const ( + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailRestrictionInboundFlows TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailRestriction = "inbound_flows" + TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailRestrictionOutboundFlows TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailRestriction = "outbound_flows" +) + +// Whether the Feature is operational. +type TreasuryFinancialAccountFeaturesIntraStripeFlowsStatus string + +// List of values that TreasuryFinancialAccountFeaturesIntraStripeFlowsStatus can take +const ( + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusActive TreasuryFinancialAccountFeaturesIntraStripeFlowsStatus = "active" + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusPending TreasuryFinancialAccountFeaturesIntraStripeFlowsStatus = "pending" + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusRestricted TreasuryFinancialAccountFeaturesIntraStripeFlowsStatus = "restricted" +) + +// Represents the reason why the status is `pending` or `restricted`. +type TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCode string + +// List of values that TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCode can take +const ( + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCodeActivating TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCode = "activating" + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCodeCapabilityNotRequested TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCode = "capability_not_requested" + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCodeFinancialAccountClosed TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCode = "financial_account_closed" + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCodeRejectedOther TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCode = "rejected_other" + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCodeRejectedUnsupportedBusiness TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCode = "rejected_unsupported_business" + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCodeRequirementsPastDue TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCode = "requirements_past_due" + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCodeRequirementsPendingVerification TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCode = "requirements_pending_verification" + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCodeRestrictedByPlatform TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCode = "restricted_by_platform" + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCodeRestrictedOther TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCode = "restricted_other" +) + +// Represents what the user should do, if anything, to activate the Feature. +type TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailResolution string + +// List of values that TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailResolution can take +const ( + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailResolutionContactStripe TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailResolution = "contact_stripe" + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailResolutionProvideInformation TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailResolution = "provide_information" + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailResolutionRemoveRestriction TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailResolution = "remove_restriction" +) + +// The `platform_restrictions` that are restricting this Feature. +type TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailRestriction string + +// List of values that TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailRestriction can take +const ( + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailRestrictionInboundFlows TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailRestriction = "inbound_flows" + TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailRestrictionOutboundFlows TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailRestriction = "outbound_flows" +) + +// Whether the Feature is operational. +type TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatus string + +// List of values that TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatus can take +const ( + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusActive TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatus = "active" + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusPending TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatus = "pending" + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusRestricted TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatus = "restricted" +) + +// Represents the reason why the status is `pending` or `restricted`. +type TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCode string + +// List of values that TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCode can take +const ( + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCodeActivating TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCode = "activating" + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCodeCapabilityNotRequested TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCode = "capability_not_requested" + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCodeFinancialAccountClosed TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCode = "financial_account_closed" + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCodeRejectedOther TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCode = "rejected_other" + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCodeRejectedUnsupportedBusiness TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCode = "rejected_unsupported_business" + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCodeRequirementsPastDue TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCode = "requirements_past_due" + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCodeRequirementsPendingVerification TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCode = "requirements_pending_verification" + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCodeRestrictedByPlatform TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCode = "restricted_by_platform" + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCodeRestrictedOther TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCode = "restricted_other" +) + +// Represents what the user should do, if anything, to activate the Feature. +type TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailResolution string + +// List of values that TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailResolution can take +const ( + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailResolutionContactStripe TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailResolution = "contact_stripe" + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailResolutionProvideInformation TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailResolution = "provide_information" + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailResolutionRemoveRestriction TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailResolution = "remove_restriction" +) + +// The `platform_restrictions` that are restricting this Feature. +type TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailRestriction string + +// List of values that TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailRestriction can take +const ( + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailRestrictionInboundFlows TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailRestriction = "inbound_flows" + TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailRestrictionOutboundFlows TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailRestriction = "outbound_flows" +) + +// Whether the Feature is operational. +type TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatus string + +// List of values that TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatus can take +const ( + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusActive TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatus = "active" + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusPending TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatus = "pending" + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusRestricted TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatus = "restricted" +) + +// Represents the reason why the status is `pending` or `restricted`. +type TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCode string + +// List of values that TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCode can take +const ( + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCodeActivating TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCode = "activating" + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCodeCapabilityNotRequested TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCode = "capability_not_requested" + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCodeFinancialAccountClosed TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCode = "financial_account_closed" + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCodeRejectedOther TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCode = "rejected_other" + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCodeRejectedUnsupportedBusiness TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCode = "rejected_unsupported_business" + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCodeRequirementsPastDue TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCode = "requirements_past_due" + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCodeRequirementsPendingVerification TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCode = "requirements_pending_verification" + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCodeRestrictedByPlatform TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCode = "restricted_by_platform" + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCodeRestrictedOther TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCode = "restricted_other" +) + +// Represents what the user should do, if anything, to activate the Feature. +type TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailResolution string + +// List of values that TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailResolution can take +const ( + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailResolutionContactStripe TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailResolution = "contact_stripe" + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailResolutionProvideInformation TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailResolution = "provide_information" + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailResolutionRemoveRestriction TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailResolution = "remove_restriction" +) + +// The `platform_restrictions` that are restricting this Feature. +type TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailRestriction string + +// List of values that TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailRestriction can take +const ( + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailRestrictionInboundFlows TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailRestriction = "inbound_flows" + TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailRestrictionOutboundFlows TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailRestriction = "outbound_flows" +) + +// Whether the Feature is operational. +type TreasuryFinancialAccountFeaturesOutboundTransfersACHStatus string + +// List of values that TreasuryFinancialAccountFeaturesOutboundTransfersACHStatus can take +const ( + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusActive TreasuryFinancialAccountFeaturesOutboundTransfersACHStatus = "active" + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusPending TreasuryFinancialAccountFeaturesOutboundTransfersACHStatus = "pending" + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusRestricted TreasuryFinancialAccountFeaturesOutboundTransfersACHStatus = "restricted" +) + +// Represents the reason why the status is `pending` or `restricted`. +type TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCode string + +// List of values that TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCode can take +const ( + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCodeActivating TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCode = "activating" + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCodeCapabilityNotRequested TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCode = "capability_not_requested" + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCodeFinancialAccountClosed TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCode = "financial_account_closed" + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCodeRejectedOther TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCode = "rejected_other" + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCodeRejectedUnsupportedBusiness TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCode = "rejected_unsupported_business" + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCodeRequirementsPastDue TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCode = "requirements_past_due" + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCodeRequirementsPendingVerification TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCode = "requirements_pending_verification" + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCodeRestrictedByPlatform TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCode = "restricted_by_platform" + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCodeRestrictedOther TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCode = "restricted_other" +) + +// Represents what the user should do, if anything, to activate the Feature. +type TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailResolution string + +// List of values that TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailResolution can take +const ( + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailResolutionContactStripe TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailResolution = "contact_stripe" + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailResolutionProvideInformation TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailResolution = "provide_information" + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailResolutionRemoveRestriction TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailResolution = "remove_restriction" +) + +// The `platform_restrictions` that are restricting this Feature. +type TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailRestriction string + +// List of values that TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailRestriction can take +const ( + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailRestrictionInboundFlows TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailRestriction = "inbound_flows" + TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailRestrictionOutboundFlows TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailRestriction = "outbound_flows" +) + +// Whether the Feature is operational. +type TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatus string + +// List of values that TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatus can take +const ( + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusActive TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatus = "active" + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusPending TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatus = "pending" + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusRestricted TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatus = "restricted" +) + +// Represents the reason why the status is `pending` or `restricted`. +type TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCode string + +// List of values that TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCode can take +const ( + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCodeActivating TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCode = "activating" + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCodeCapabilityNotRequested TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCode = "capability_not_requested" + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCodeFinancialAccountClosed TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCode = "financial_account_closed" + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCodeRejectedOther TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCode = "rejected_other" + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCodeRejectedUnsupportedBusiness TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCode = "rejected_unsupported_business" + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCodeRequirementsPastDue TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCode = "requirements_past_due" + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCodeRequirementsPendingVerification TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCode = "requirements_pending_verification" + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCodeRestrictedByPlatform TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCode = "restricted_by_platform" + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCodeRestrictedOther TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCode = "restricted_other" +) + +// Represents what the user should do, if anything, to activate the Feature. +type TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailResolution string + +// List of values that TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailResolution can take +const ( + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailResolutionContactStripe TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailResolution = "contact_stripe" + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailResolutionProvideInformation TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailResolution = "provide_information" + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailResolutionRemoveRestriction TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailResolution = "remove_restriction" +) + +// The `platform_restrictions` that are restricting this Feature. +type TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailRestriction string + +// List of values that TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailRestriction can take +const ( + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailRestrictionInboundFlows TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailRestriction = "inbound_flows" + TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailRestrictionOutboundFlows TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailRestriction = "outbound_flows" +) + +// Additional details; includes at least one entry when the status is not `active`. +type TreasuryFinancialAccountFeaturesCardIssuingStatusDetail struct { + // Represents the reason why the status is `pending` or `restricted`. + Code TreasuryFinancialAccountFeaturesCardIssuingStatusDetailCode `json:"code"` + // Represents what the user should do, if anything, to activate the Feature. + Resolution TreasuryFinancialAccountFeaturesCardIssuingStatusDetailResolution `json:"resolution"` + // The `platform_restrictions` that are restricting this Feature. + Restriction TreasuryFinancialAccountFeaturesCardIssuingStatusDetailRestriction `json:"restriction"` +} + +// Toggle settings for enabling/disabling a feature +type TreasuryFinancialAccountFeaturesCardIssuing struct { + // Whether the FinancialAccount should have the Feature. + Requested bool `json:"requested"` + // Whether the Feature is operational. + Status TreasuryFinancialAccountFeaturesCardIssuingStatus `json:"status"` + // Additional details; includes at least one entry when the status is not `active`. + StatusDetails []*TreasuryFinancialAccountFeaturesCardIssuingStatusDetail `json:"status_details"` +} + +// Additional details; includes at least one entry when the status is not `active`. +type TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetail struct { + // Represents the reason why the status is `pending` or `restricted`. + Code TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailCode `json:"code"` + // Represents what the user should do, if anything, to activate the Feature. + Resolution TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailResolution `json:"resolution"` + // The `platform_restrictions` that are restricting this Feature. + Restriction TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetailRestriction `json:"restriction"` +} + +// Toggle settings for enabling/disabling a feature +type TreasuryFinancialAccountFeaturesDepositInsurance struct { + // Whether the FinancialAccount should have the Feature. + Requested bool `json:"requested"` + // Whether the Feature is operational. + Status TreasuryFinancialAccountFeaturesDepositInsuranceStatus `json:"status"` + // Additional details; includes at least one entry when the status is not `active`. + StatusDetails []*TreasuryFinancialAccountFeaturesDepositInsuranceStatusDetail `json:"status_details"` +} + +// Additional details; includes at least one entry when the status is not `active`. +type TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetail struct { + // Represents the reason why the status is `pending` or `restricted`. + Code TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailCode `json:"code"` + // Represents what the user should do, if anything, to activate the Feature. + Resolution TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailResolution `json:"resolution"` + // The `platform_restrictions` that are restricting this Feature. + Restriction TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetailRestriction `json:"restriction"` +} + +// Toggle settings for enabling/disabling the ABA address feature +type TreasuryFinancialAccountFeaturesFinancialAddressesABA struct { + // Whether the FinancialAccount should have the Feature. + Requested bool `json:"requested"` + // Whether the Feature is operational. + Status TreasuryFinancialAccountFeaturesFinancialAddressesABAStatus `json:"status"` + // Additional details; includes at least one entry when the status is not `active`. + StatusDetails []*TreasuryFinancialAccountFeaturesFinancialAddressesABAStatusDetail `json:"status_details"` +} + +// Settings related to Financial Addresses features on a Financial Account +type TreasuryFinancialAccountFeaturesFinancialAddresses struct { + // Toggle settings for enabling/disabling the ABA address feature + ABA *TreasuryFinancialAccountFeaturesFinancialAddressesABA `json:"aba"` +} + +// Additional details; includes at least one entry when the status is not `active`. +type TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetail struct { + // Represents the reason why the status is `pending` or `restricted`. + Code TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailCode `json:"code"` + // Represents what the user should do, if anything, to activate the Feature. + Resolution TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailResolution `json:"resolution"` + // The `platform_restrictions` that are restricting this Feature. + Restriction TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetailRestriction `json:"restriction"` +} + +// Toggle settings for enabling/disabling an inbound ACH specific feature +type TreasuryFinancialAccountFeaturesInboundTransfersACH struct { + // Whether the FinancialAccount should have the Feature. + Requested bool `json:"requested"` + // Whether the Feature is operational. + Status TreasuryFinancialAccountFeaturesInboundTransfersACHStatus `json:"status"` + // Additional details; includes at least one entry when the status is not `active`. + StatusDetails []*TreasuryFinancialAccountFeaturesInboundTransfersACHStatusDetail `json:"status_details"` +} + +// InboundTransfers contains inbound transfers features for a FinancialAccount. +type TreasuryFinancialAccountFeaturesInboundTransfers struct { + // Toggle settings for enabling/disabling an inbound ACH specific feature + ACH *TreasuryFinancialAccountFeaturesInboundTransfersACH `json:"ach"` +} + +// Additional details; includes at least one entry when the status is not `active`. +type TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetail struct { + // Represents the reason why the status is `pending` or `restricted`. + Code TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailCode `json:"code"` + // Represents what the user should do, if anything, to activate the Feature. + Resolution TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailResolution `json:"resolution"` + // The `platform_restrictions` that are restricting this Feature. + Restriction TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetailRestriction `json:"restriction"` +} + +// Toggle settings for enabling/disabling a feature +type TreasuryFinancialAccountFeaturesIntraStripeFlows struct { + // Whether the FinancialAccount should have the Feature. + Requested bool `json:"requested"` + // Whether the Feature is operational. + Status TreasuryFinancialAccountFeaturesIntraStripeFlowsStatus `json:"status"` + // Additional details; includes at least one entry when the status is not `active`. + StatusDetails []*TreasuryFinancialAccountFeaturesIntraStripeFlowsStatusDetail `json:"status_details"` +} + +// Additional details; includes at least one entry when the status is not `active`. +type TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetail struct { + // Represents the reason why the status is `pending` or `restricted`. + Code TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailCode `json:"code"` + // Represents what the user should do, if anything, to activate the Feature. + Resolution TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailResolution `json:"resolution"` + // The `platform_restrictions` that are restricting this Feature. + Restriction TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetailRestriction `json:"restriction"` +} + +// Toggle settings for enabling/disabling an outbound ACH specific feature +type TreasuryFinancialAccountFeaturesOutboundPaymentsACH struct { + // Whether the FinancialAccount should have the Feature. + Requested bool `json:"requested"` + // Whether the Feature is operational. + Status TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatus `json:"status"` + // Additional details; includes at least one entry when the status is not `active`. + StatusDetails []*TreasuryFinancialAccountFeaturesOutboundPaymentsACHStatusDetail `json:"status_details"` +} + +// Additional details; includes at least one entry when the status is not `active`. +type TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetail struct { + // Represents the reason why the status is `pending` or `restricted`. + Code TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailCode `json:"code"` + // Represents what the user should do, if anything, to activate the Feature. + Resolution TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailResolution `json:"resolution"` + // The `platform_restrictions` that are restricting this Feature. + Restriction TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetailRestriction `json:"restriction"` +} + +// Toggle settings for enabling/disabling a feature +type TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWire struct { + // Whether the FinancialAccount should have the Feature. + Requested bool `json:"requested"` + // Whether the Feature is operational. + Status TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatus `json:"status"` + // Additional details; includes at least one entry when the status is not `active`. + StatusDetails []*TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWireStatusDetail `json:"status_details"` +} + +// Settings related to Outbound Payments features on a Financial Account +type TreasuryFinancialAccountFeaturesOutboundPayments struct { + // Toggle settings for enabling/disabling an outbound ACH specific feature + ACH *TreasuryFinancialAccountFeaturesOutboundPaymentsACH `json:"ach"` + // Toggle settings for enabling/disabling a feature + USDomesticWire *TreasuryFinancialAccountFeaturesOutboundPaymentsUSDomesticWire `json:"us_domestic_wire"` +} + +// Additional details; includes at least one entry when the status is not `active`. +type TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetail struct { + // Represents the reason why the status is `pending` or `restricted`. + Code TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailCode `json:"code"` + // Represents what the user should do, if anything, to activate the Feature. + Resolution TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailResolution `json:"resolution"` + // The `platform_restrictions` that are restricting this Feature. + Restriction TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetailRestriction `json:"restriction"` +} + +// Toggle settings for enabling/disabling an outbound ACH specific feature +type TreasuryFinancialAccountFeaturesOutboundTransfersACH struct { + // Whether the FinancialAccount should have the Feature. + Requested bool `json:"requested"` + // Whether the Feature is operational. + Status TreasuryFinancialAccountFeaturesOutboundTransfersACHStatus `json:"status"` + // Additional details; includes at least one entry when the status is not `active`. + StatusDetails []*TreasuryFinancialAccountFeaturesOutboundTransfersACHStatusDetail `json:"status_details"` +} + +// Additional details; includes at least one entry when the status is not `active`. +type TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetail struct { + // Represents the reason why the status is `pending` or `restricted`. + Code TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailCode `json:"code"` + // Represents what the user should do, if anything, to activate the Feature. + Resolution TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailResolution `json:"resolution"` + // The `platform_restrictions` that are restricting this Feature. + Restriction TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetailRestriction `json:"restriction"` +} + +// Toggle settings for enabling/disabling a feature +type TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWire struct { + // Whether the FinancialAccount should have the Feature. + Requested bool `json:"requested"` + // Whether the Feature is operational. + Status TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatus `json:"status"` + // Additional details; includes at least one entry when the status is not `active`. + StatusDetails []*TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWireStatusDetail `json:"status_details"` +} + +// OutboundTransfers contains outbound transfers features for a FinancialAccount. +type TreasuryFinancialAccountFeaturesOutboundTransfers struct { + // Toggle settings for enabling/disabling an outbound ACH specific feature + ACH *TreasuryFinancialAccountFeaturesOutboundTransfersACH `json:"ach"` + // Toggle settings for enabling/disabling a feature + USDomesticWire *TreasuryFinancialAccountFeaturesOutboundTransfersUSDomesticWire `json:"us_domestic_wire"` +} + +// Encodes whether a FinancialAccount has access to a particular Feature, with a `status` enum and associated `status_details`. +// Stripe or the platform can control Features via the requested field. +type TreasuryFinancialAccountFeatures struct { + APIResource + // Toggle settings for enabling/disabling a feature + CardIssuing *TreasuryFinancialAccountFeaturesCardIssuing `json:"card_issuing"` + // Toggle settings for enabling/disabling a feature + DepositInsurance *TreasuryFinancialAccountFeaturesDepositInsurance `json:"deposit_insurance"` + // Settings related to Financial Addresses features on a Financial Account + FinancialAddresses *TreasuryFinancialAccountFeaturesFinancialAddresses `json:"financial_addresses"` + // InboundTransfers contains inbound transfers features for a FinancialAccount. + InboundTransfers *TreasuryFinancialAccountFeaturesInboundTransfers `json:"inbound_transfers"` + // Toggle settings for enabling/disabling a feature + IntraStripeFlows *TreasuryFinancialAccountFeaturesIntraStripeFlows `json:"intra_stripe_flows"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Settings related to Outbound Payments features on a Financial Account + OutboundPayments *TreasuryFinancialAccountFeaturesOutboundPayments `json:"outbound_payments"` + // OutboundTransfers contains outbound transfers features for a FinancialAccount. + OutboundTransfers *TreasuryFinancialAccountFeaturesOutboundTransfers `json:"outbound_transfers"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_inboundtransfer.go b/vendor/github.com/stripe/stripe-go/v82/treasury_inboundtransfer.go new file mode 100644 index 00000000..df2f17c8 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_inboundtransfer.go @@ -0,0 +1,285 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Reason for the failure. +type TreasuryInboundTransferFailureDetailsCode string + +// List of values that TreasuryInboundTransferFailureDetailsCode can take +const ( + TreasuryInboundTransferFailureDetailsCodeAccountClosed TreasuryInboundTransferFailureDetailsCode = "account_closed" + TreasuryInboundTransferFailureDetailsCodeAccountFrozen TreasuryInboundTransferFailureDetailsCode = "account_frozen" + TreasuryInboundTransferFailureDetailsCodeBankAccountRestricted TreasuryInboundTransferFailureDetailsCode = "bank_account_restricted" + TreasuryInboundTransferFailureDetailsCodeBankOwnershipChanged TreasuryInboundTransferFailureDetailsCode = "bank_ownership_changed" + TreasuryInboundTransferFailureDetailsCodeDebitNotAuthorized TreasuryInboundTransferFailureDetailsCode = "debit_not_authorized" + TreasuryInboundTransferFailureDetailsCodeIncorrectAccountHolderAddress TreasuryInboundTransferFailureDetailsCode = "incorrect_account_holder_address" + TreasuryInboundTransferFailureDetailsCodeIncorrectAccountHolderName TreasuryInboundTransferFailureDetailsCode = "incorrect_account_holder_name" + TreasuryInboundTransferFailureDetailsCodeIncorrectAccountHolderTaxID TreasuryInboundTransferFailureDetailsCode = "incorrect_account_holder_tax_id" + TreasuryInboundTransferFailureDetailsCodeInsufficientFunds TreasuryInboundTransferFailureDetailsCode = "insufficient_funds" + TreasuryInboundTransferFailureDetailsCodeInvalidAccountNumber TreasuryInboundTransferFailureDetailsCode = "invalid_account_number" + TreasuryInboundTransferFailureDetailsCodeInvalidCurrency TreasuryInboundTransferFailureDetailsCode = "invalid_currency" + TreasuryInboundTransferFailureDetailsCodeNoAccount TreasuryInboundTransferFailureDetailsCode = "no_account" + TreasuryInboundTransferFailureDetailsCodeOther TreasuryInboundTransferFailureDetailsCode = "other" +) + +// The type of the payment method used in the InboundTransfer. +type TreasuryInboundTransferOriginPaymentMethodDetailsType string + +// List of values that TreasuryInboundTransferOriginPaymentMethodDetailsType can take +const ( + TreasuryInboundTransferOriginPaymentMethodDetailsTypeUSBankAccount TreasuryInboundTransferOriginPaymentMethodDetailsType = "us_bank_account" +) + +// Account holder type: individual or company. +type TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountAccountHolderType string + +// List of values that TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountAccountHolderType can take +const ( + TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountAccountHolderTypeCompany TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountAccountHolderType = "company" + TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountAccountHolderTypeIndividual TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountAccountHolderType = "individual" +) + +// Account type: checkings or savings. Defaults to checking if omitted. +type TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountAccountType string + +// List of values that TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountAccountType can take +const ( + TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountAccountTypeChecking TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountAccountType = "checking" + TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountAccountTypeSavings TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountAccountType = "savings" +) + +// The network rails used. See the [docs](https://stripe.com/docs/treasury/money-movement/timelines) to learn more about money movement timelines for each network type. +type TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountNetwork string + +// List of values that TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountNetwork can take +const ( + TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountNetworkACH TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountNetwork = "ach" +) + +// Status of the InboundTransfer: `processing`, `succeeded`, `failed`, and `canceled`. An InboundTransfer is `processing` if it is created and pending. The status changes to `succeeded` once the funds have been "confirmed" and a `transaction` is created and posted. The status changes to `failed` if the transfer fails. +type TreasuryInboundTransferStatus string + +// List of values that TreasuryInboundTransferStatus can take +const ( + TreasuryInboundTransferStatusCanceled TreasuryInboundTransferStatus = "canceled" + TreasuryInboundTransferStatusFailed TreasuryInboundTransferStatus = "failed" + TreasuryInboundTransferStatusProcessing TreasuryInboundTransferStatus = "processing" + TreasuryInboundTransferStatusSucceeded TreasuryInboundTransferStatus = "succeeded" +) + +// Returns a list of InboundTransfers sent from the specified FinancialAccount. +type TreasuryInboundTransferListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Returns objects associated with this FinancialAccount. + FinancialAccount *string `form:"financial_account"` + // Only return InboundTransfers that have the given status: `processing`, `succeeded`, `failed` or `canceled`. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryInboundTransferListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates an InboundTransfer. +type TreasuryInboundTransferParams struct { + Params `form:"*"` + // Amount (in cents) to be transferred. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The FinancialAccount to send funds to. + FinancialAccount *string `form:"financial_account"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The origin payment method to be debited for the InboundTransfer. + OriginPaymentMethod *string `form:"origin_payment_method"` + // The complete description that appears on your customers' statements. Maximum 10 characters. + StatementDescriptor *string `form:"statement_descriptor"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryInboundTransferParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryInboundTransferParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Cancels an InboundTransfer. +type TreasuryInboundTransferCancelParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryInboundTransferCancelParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Creates an InboundTransfer. +type TreasuryInboundTransferCreateParams struct { + Params `form:"*"` + // Amount (in cents) to be transferred. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The FinancialAccount to send funds to. + FinancialAccount *string `form:"financial_account"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The origin payment method to be debited for the InboundTransfer. + OriginPaymentMethod *string `form:"origin_payment_method"` + // The complete description that appears on your customers' statements. Maximum 10 characters. + StatementDescriptor *string `form:"statement_descriptor"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryInboundTransferCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryInboundTransferCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the details of an existing InboundTransfer. +type TreasuryInboundTransferRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryInboundTransferRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Details about this InboundTransfer's failure. Only set when status is `failed`. +type TreasuryInboundTransferFailureDetails struct { + // Reason for the failure. + Code TreasuryInboundTransferFailureDetailsCode `json:"code"` +} +type TreasuryInboundTransferLinkedFlows struct { + // If funds for this flow were returned after the flow went to the `succeeded` state, this field contains a reference to the ReceivedDebit return. + ReceivedDebit string `json:"received_debit"` +} +type TreasuryInboundTransferOriginPaymentMethodDetailsBillingDetails struct { + Address *Address `json:"address"` + // Email address. + Email string `json:"email"` + // Full name. + Name string `json:"name"` +} +type TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccount struct { + // Account holder type: individual or company. + AccountHolderType TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountAccountHolderType `json:"account_holder_type"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountAccountType `json:"account_type"` + // Name of the bank associated with the bank account. + BankName string `json:"bank_name"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // ID of the mandate used to make this payment. + Mandate *Mandate `json:"mandate"` + // The network rails used. See the [docs](https://stripe.com/docs/treasury/money-movement/timelines) to learn more about money movement timelines for each network type. + Network TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccountNetwork `json:"network"` + // Routing number of the bank account. + RoutingNumber string `json:"routing_number"` +} + +// Details about the PaymentMethod for an InboundTransfer. +type TreasuryInboundTransferOriginPaymentMethodDetails struct { + BillingDetails *TreasuryInboundTransferOriginPaymentMethodDetailsBillingDetails `json:"billing_details"` + // The type of the payment method used in the InboundTransfer. + Type TreasuryInboundTransferOriginPaymentMethodDetailsType `json:"type"` + USBankAccount *TreasuryInboundTransferOriginPaymentMethodDetailsUSBankAccount `json:"us_bank_account"` +} +type TreasuryInboundTransferStatusTransitions struct { + // Timestamp describing when an InboundTransfer changed status to `canceled`. + CanceledAt int64 `json:"canceled_at"` + // Timestamp describing when an InboundTransfer changed status to `failed`. + FailedAt int64 `json:"failed_at"` + // Timestamp describing when an InboundTransfer changed status to `succeeded`. + SucceededAt int64 `json:"succeeded_at"` +} + +// Use [InboundTransfers](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/into/inbound-transfers) to add funds to your [FinancialAccount](https://stripe.com/docs/api#financial_accounts) via a PaymentMethod that is owned by you. The funds will be transferred via an ACH debit. +// +// Related guide: [Moving money with Treasury using InboundTransfer objects](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/into/inbound-transfers) +type TreasuryInboundTransfer struct { + APIResource + // Amount (in cents) transferred. + Amount int64 `json:"amount"` + // Returns `true` if the InboundTransfer is able to be canceled. + Cancelable bool `json:"cancelable"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // Details about this InboundTransfer's failure. Only set when status is `failed`. + FailureDetails *TreasuryInboundTransferFailureDetails `json:"failure_details"` + // The FinancialAccount that received the funds. + FinancialAccount string `json:"financial_account"` + // A [hosted transaction receipt](https://stripe.com/docs/treasury/moving-money/regulatory-receipts) URL that is provided when money movement is considered regulated under Stripe's money transmission licenses. + HostedRegulatoryReceiptURL string `json:"hosted_regulatory_receipt_url"` + // Unique identifier for the object. + ID string `json:"id"` + LinkedFlows *TreasuryInboundTransferLinkedFlows `json:"linked_flows"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The origin payment method to be debited for an InboundTransfer. + OriginPaymentMethod string `json:"origin_payment_method"` + // Details about the PaymentMethod for an InboundTransfer. + OriginPaymentMethodDetails *TreasuryInboundTransferOriginPaymentMethodDetails `json:"origin_payment_method_details"` + // Returns `true` if the funds for an InboundTransfer were returned after the InboundTransfer went to the `succeeded` state. + Returned bool `json:"returned"` + // Statement descriptor shown when funds are debited from the source. Not all payment networks support `statement_descriptor`. + StatementDescriptor string `json:"statement_descriptor"` + // Status of the InboundTransfer: `processing`, `succeeded`, `failed`, and `canceled`. An InboundTransfer is `processing` if it is created and pending. The status changes to `succeeded` once the funds have been "confirmed" and a `transaction` is created and posted. The status changes to `failed` if the transfer fails. + Status TreasuryInboundTransferStatus `json:"status"` + StatusTransitions *TreasuryInboundTransferStatusTransitions `json:"status_transitions"` + // The Transaction associated with this object. + Transaction *TreasuryTransaction `json:"transaction"` +} + +// TreasuryInboundTransferList is a list of InboundTransfers as retrieved from a list endpoint. +type TreasuryInboundTransferList struct { + APIResource + ListMeta + Data []*TreasuryInboundTransfer `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_inboundtransfer_service.go b/vendor/github.com/stripe/stripe-go/v82/treasury_inboundtransfer_service.go new file mode 100644 index 00000000..4bb7b52b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_inboundtransfer_service.go @@ -0,0 +1,73 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TreasuryInboundTransferService is used to invoke /v1/treasury/inbound_transfers APIs. +type v1TreasuryInboundTransferService struct { + B Backend + Key string +} + +// Creates an InboundTransfer. +func (c v1TreasuryInboundTransferService) Create(ctx context.Context, params *TreasuryInboundTransferCreateParams) (*TreasuryInboundTransfer, error) { + if params == nil { + params = &TreasuryInboundTransferCreateParams{} + } + params.Context = ctx + inboundtransfer := &TreasuryInboundTransfer{} + err := c.B.Call( + http.MethodPost, "/v1/treasury/inbound_transfers", c.Key, params, inboundtransfer) + return inboundtransfer, err +} + +// Retrieves the details of an existing InboundTransfer. +func (c v1TreasuryInboundTransferService) Retrieve(ctx context.Context, id string, params *TreasuryInboundTransferRetrieveParams) (*TreasuryInboundTransfer, error) { + if params == nil { + params = &TreasuryInboundTransferRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/inbound_transfers/%s", id) + inboundtransfer := &TreasuryInboundTransfer{} + err := c.B.Call(http.MethodGet, path, c.Key, params, inboundtransfer) + return inboundtransfer, err +} + +// Cancels an InboundTransfer. +func (c v1TreasuryInboundTransferService) Cancel(ctx context.Context, id string, params *TreasuryInboundTransferCancelParams) (*TreasuryInboundTransfer, error) { + if params == nil { + params = &TreasuryInboundTransferCancelParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/inbound_transfers/%s/cancel", id) + inboundtransfer := &TreasuryInboundTransfer{} + err := c.B.Call(http.MethodPost, path, c.Key, params, inboundtransfer) + return inboundtransfer, err +} + +// Returns a list of InboundTransfers sent from the specified FinancialAccount. +func (c v1TreasuryInboundTransferService) List(ctx context.Context, listParams *TreasuryInboundTransferListParams) Seq2[*TreasuryInboundTransfer, error] { + if listParams == nil { + listParams = &TreasuryInboundTransferListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TreasuryInboundTransfer, ListContainer, error) { + list := &TreasuryInboundTransferList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/treasury/inbound_transfers", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_outboundpayment.go b/vendor/github.com/stripe/stripe-go/v82/treasury_outboundpayment.go new file mode 100644 index 00000000..ef81e1ce --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_outboundpayment.go @@ -0,0 +1,505 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The rails used to send funds. +type TreasuryOutboundPaymentDestinationPaymentMethodDetailsFinancialAccountNetwork string + +// List of values that TreasuryOutboundPaymentDestinationPaymentMethodDetailsFinancialAccountNetwork can take +const ( + TreasuryOutboundPaymentDestinationPaymentMethodDetailsFinancialAccountNetworkStripe TreasuryOutboundPaymentDestinationPaymentMethodDetailsFinancialAccountNetwork = "stripe" +) + +// The type of the payment method used in the OutboundPayment. +type TreasuryOutboundPaymentDestinationPaymentMethodDetailsType string + +// List of values that TreasuryOutboundPaymentDestinationPaymentMethodDetailsType can take +const ( + TreasuryOutboundPaymentDestinationPaymentMethodDetailsTypeFinancialAccount TreasuryOutboundPaymentDestinationPaymentMethodDetailsType = "financial_account" + TreasuryOutboundPaymentDestinationPaymentMethodDetailsTypeUSBankAccount TreasuryOutboundPaymentDestinationPaymentMethodDetailsType = "us_bank_account" +) + +// Account holder type: individual or company. +type TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountAccountHolderType string + +// List of values that TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountAccountHolderType can take +const ( + TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountAccountHolderTypeCompany TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountAccountHolderType = "company" + TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountAccountHolderTypeIndividual TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountAccountHolderType = "individual" +) + +// Account type: checkings or savings. Defaults to checking if omitted. +type TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountAccountType string + +// List of values that TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountAccountType can take +const ( + TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountAccountTypeChecking TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountAccountType = "checking" + TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountAccountTypeSavings TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountAccountType = "savings" +) + +// The network rails used. See the [docs](https://stripe.com/docs/treasury/money-movement/timelines) to learn more about money movement timelines for each network type. +type TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountNetwork string + +// List of values that TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountNetwork can take +const ( + TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountNetworkACH TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountNetwork = "ach" + TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountNetworkUSDomesticWire TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountNetwork = "us_domestic_wire" +) + +// Reason for the return. +type TreasuryOutboundPaymentReturnedDetailsCode string + +// List of values that TreasuryOutboundPaymentReturnedDetailsCode can take +const ( + TreasuryOutboundPaymentReturnedDetailsCodeAccountClosed TreasuryOutboundPaymentReturnedDetailsCode = "account_closed" + TreasuryOutboundPaymentReturnedDetailsCodeAccountFrozen TreasuryOutboundPaymentReturnedDetailsCode = "account_frozen" + TreasuryOutboundPaymentReturnedDetailsCodeBankAccountRestricted TreasuryOutboundPaymentReturnedDetailsCode = "bank_account_restricted" + TreasuryOutboundPaymentReturnedDetailsCodeBankOwnershipChanged TreasuryOutboundPaymentReturnedDetailsCode = "bank_ownership_changed" + TreasuryOutboundPaymentReturnedDetailsCodeDeclined TreasuryOutboundPaymentReturnedDetailsCode = "declined" + TreasuryOutboundPaymentReturnedDetailsCodeIncorrectAccountHolderName TreasuryOutboundPaymentReturnedDetailsCode = "incorrect_account_holder_name" + TreasuryOutboundPaymentReturnedDetailsCodeInvalidAccountNumber TreasuryOutboundPaymentReturnedDetailsCode = "invalid_account_number" + TreasuryOutboundPaymentReturnedDetailsCodeInvalidCurrency TreasuryOutboundPaymentReturnedDetailsCode = "invalid_currency" + TreasuryOutboundPaymentReturnedDetailsCodeNoAccount TreasuryOutboundPaymentReturnedDetailsCode = "no_account" + TreasuryOutboundPaymentReturnedDetailsCodeOther TreasuryOutboundPaymentReturnedDetailsCode = "other" +) + +// Current status of the OutboundPayment: `processing`, `failed`, `posted`, `returned`, `canceled`. An OutboundPayment is `processing` if it has been created and is pending. The status changes to `posted` once the OutboundPayment has been "confirmed" and funds have left the account, or to `failed` or `canceled`. If an OutboundPayment fails to arrive at its destination, its status will change to `returned`. +type TreasuryOutboundPaymentStatus string + +// List of values that TreasuryOutboundPaymentStatus can take +const ( + TreasuryOutboundPaymentStatusCanceled TreasuryOutboundPaymentStatus = "canceled" + TreasuryOutboundPaymentStatusFailed TreasuryOutboundPaymentStatus = "failed" + TreasuryOutboundPaymentStatusPosted TreasuryOutboundPaymentStatus = "posted" + TreasuryOutboundPaymentStatusProcessing TreasuryOutboundPaymentStatus = "processing" + TreasuryOutboundPaymentStatusReturned TreasuryOutboundPaymentStatus = "returned" +) + +// The US bank account network used to send funds. +type TreasuryOutboundPaymentTrackingDetailsType string + +// List of values that TreasuryOutboundPaymentTrackingDetailsType can take +const ( + TreasuryOutboundPaymentTrackingDetailsTypeACH TreasuryOutboundPaymentTrackingDetailsType = "ach" + TreasuryOutboundPaymentTrackingDetailsTypeUSDomesticWire TreasuryOutboundPaymentTrackingDetailsType = "us_domestic_wire" +) + +// Returns a list of OutboundPayments sent from the specified FinancialAccount. +type TreasuryOutboundPaymentListParams struct { + ListParams `form:"*"` + // Only return OutboundPayments that were created during the given date interval. + Created *int64 `form:"created"` + // Only return OutboundPayments that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Only return OutboundPayments sent to this customer. + Customer *string `form:"customer"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Returns objects associated with this FinancialAccount. + FinancialAccount *string `form:"financial_account"` + // Only return OutboundPayments that have the given status: `processing`, `failed`, `posted`, `returned`, or `canceled`. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryOutboundPaymentListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. +type TreasuryOutboundPaymentDestinationPaymentMethodDataBillingDetailsParams struct { + // Billing address. + Address *AddressParams `form:"address"` + // Email address. + Email *string `form:"email"` + // Full name. + Name *string `form:"name"` + // Billing phone number (including extension). + Phone *string `form:"phone"` +} + +// Required hash if type is set to `us_bank_account`. +type TreasuryOutboundPaymentDestinationPaymentMethodDataUSBankAccountParams struct { + // Account holder type: individual or company. + AccountHolderType *string `form:"account_holder_type"` + // Account number of the bank account. + AccountNumber *string `form:"account_number"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType *string `form:"account_type"` + // The ID of a Financial Connections Account to use as a payment method. + FinancialConnectionsAccount *string `form:"financial_connections_account"` + // Routing number of the bank account. + RoutingNumber *string `form:"routing_number"` +} + +// Hash used to generate the PaymentMethod to be used for this OutboundPayment. Exclusive with `destination_payment_method`. +type TreasuryOutboundPaymentDestinationPaymentMethodDataParams struct { + // Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + BillingDetails *TreasuryOutboundPaymentDestinationPaymentMethodDataBillingDetailsParams `form:"billing_details"` + // Required if type is set to `financial_account`. The FinancialAccount ID to send funds to. + FinancialAccount *string `form:"financial_account"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type *string `form:"type"` + // Required hash if type is set to `us_bank_account`. + USBankAccount *TreasuryOutboundPaymentDestinationPaymentMethodDataUSBankAccountParams `form:"us_bank_account"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryOutboundPaymentDestinationPaymentMethodDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Optional fields for `us_bank_account`. +type TreasuryOutboundPaymentDestinationPaymentMethodOptionsUSBankAccountParams struct { + // Specifies the network rails to be used. If not set, will default to the PaymentMethod's preferred network. See the [docs](https://stripe.com/docs/treasury/money-movement/timelines) to learn more about money movement timelines for each network type. + Network *string `form:"network"` +} + +// Payment method-specific configuration for this OutboundPayment. +type TreasuryOutboundPaymentDestinationPaymentMethodOptionsParams struct { + // Optional fields for `us_bank_account`. + USBankAccount *TreasuryOutboundPaymentDestinationPaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` +} + +// End user details. +type TreasuryOutboundPaymentEndUserDetailsParams struct { + // IP address of the user initiating the OutboundPayment. Must be supplied if `present` is set to `true`. + IPAddress *string `form:"ip_address"` + // `True` if the OutboundPayment creation request is being made on behalf of an end user by a platform. Otherwise, `false`. + Present *bool `form:"present"` +} + +// Creates an OutboundPayment. +type TreasuryOutboundPaymentParams struct { + Params `form:"*"` + // Amount (in cents) to be transferred. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // ID of the customer to whom the OutboundPayment is sent. Must match the Customer attached to the `destination_payment_method` passed in. + Customer *string `form:"customer"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // The PaymentMethod to use as the payment instrument for the OutboundPayment. Exclusive with `destination_payment_method_data`. + DestinationPaymentMethod *string `form:"destination_payment_method"` + // Hash used to generate the PaymentMethod to be used for this OutboundPayment. Exclusive with `destination_payment_method`. + DestinationPaymentMethodData *TreasuryOutboundPaymentDestinationPaymentMethodDataParams `form:"destination_payment_method_data"` + // Payment method-specific configuration for this OutboundPayment. + DestinationPaymentMethodOptions *TreasuryOutboundPaymentDestinationPaymentMethodOptionsParams `form:"destination_payment_method_options"` + // End user details. + EndUserDetails *TreasuryOutboundPaymentEndUserDetailsParams `form:"end_user_details"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The FinancialAccount to pull funds from. + FinancialAccount *string `form:"financial_account"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The description that appears on the receiving end for this OutboundPayment (for example, bank statement for external bank transfer). Maximum 10 characters for `ach` payments, 140 characters for `us_domestic_wire` payments, or 500 characters for `stripe` network transfers. The default value is "payment". + StatementDescriptor *string `form:"statement_descriptor"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryOutboundPaymentParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryOutboundPaymentParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Cancel an OutboundPayment. +type TreasuryOutboundPaymentCancelParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryOutboundPaymentCancelParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. +type TreasuryOutboundPaymentCreateDestinationPaymentMethodDataBillingDetailsParams struct { + // Billing address. + Address *AddressParams `form:"address"` + // Email address. + Email *string `form:"email"` + // Full name. + Name *string `form:"name"` + // Billing phone number (including extension). + Phone *string `form:"phone"` +} + +// Required hash if type is set to `us_bank_account`. +type TreasuryOutboundPaymentCreateDestinationPaymentMethodDataUSBankAccountParams struct { + // Account holder type: individual or company. + AccountHolderType *string `form:"account_holder_type"` + // Account number of the bank account. + AccountNumber *string `form:"account_number"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType *string `form:"account_type"` + // The ID of a Financial Connections Account to use as a payment method. + FinancialConnectionsAccount *string `form:"financial_connections_account"` + // Routing number of the bank account. + RoutingNumber *string `form:"routing_number"` +} + +// Hash used to generate the PaymentMethod to be used for this OutboundPayment. Exclusive with `destination_payment_method`. +type TreasuryOutboundPaymentCreateDestinationPaymentMethodDataParams struct { + // Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + BillingDetails *TreasuryOutboundPaymentCreateDestinationPaymentMethodDataBillingDetailsParams `form:"billing_details"` + // Required if type is set to `financial_account`. The FinancialAccount ID to send funds to. + FinancialAccount *string `form:"financial_account"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + Type *string `form:"type"` + // Required hash if type is set to `us_bank_account`. + USBankAccount *TreasuryOutboundPaymentCreateDestinationPaymentMethodDataUSBankAccountParams `form:"us_bank_account"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryOutboundPaymentCreateDestinationPaymentMethodDataParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Optional fields for `us_bank_account`. +type TreasuryOutboundPaymentCreateDestinationPaymentMethodOptionsUSBankAccountParams struct { + // Specifies the network rails to be used. If not set, will default to the PaymentMethod's preferred network. See the [docs](https://stripe.com/docs/treasury/money-movement/timelines) to learn more about money movement timelines for each network type. + Network *string `form:"network"` +} + +// Payment method-specific configuration for this OutboundPayment. +type TreasuryOutboundPaymentCreateDestinationPaymentMethodOptionsParams struct { + // Optional fields for `us_bank_account`. + USBankAccount *TreasuryOutboundPaymentCreateDestinationPaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` +} + +// End user details. +type TreasuryOutboundPaymentCreateEndUserDetailsParams struct { + // IP address of the user initiating the OutboundPayment. Must be supplied if `present` is set to `true`. + IPAddress *string `form:"ip_address"` + // `True` if the OutboundPayment creation request is being made on behalf of an end user by a platform. Otherwise, `false`. + Present *bool `form:"present"` +} + +// Creates an OutboundPayment. +type TreasuryOutboundPaymentCreateParams struct { + Params `form:"*"` + // Amount (in cents) to be transferred. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // ID of the customer to whom the OutboundPayment is sent. Must match the Customer attached to the `destination_payment_method` passed in. + Customer *string `form:"customer"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // The PaymentMethod to use as the payment instrument for the OutboundPayment. Exclusive with `destination_payment_method_data`. + DestinationPaymentMethod *string `form:"destination_payment_method"` + // Hash used to generate the PaymentMethod to be used for this OutboundPayment. Exclusive with `destination_payment_method`. + DestinationPaymentMethodData *TreasuryOutboundPaymentCreateDestinationPaymentMethodDataParams `form:"destination_payment_method_data"` + // Payment method-specific configuration for this OutboundPayment. + DestinationPaymentMethodOptions *TreasuryOutboundPaymentCreateDestinationPaymentMethodOptionsParams `form:"destination_payment_method_options"` + // End user details. + EndUserDetails *TreasuryOutboundPaymentCreateEndUserDetailsParams `form:"end_user_details"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The FinancialAccount to pull funds from. + FinancialAccount *string `form:"financial_account"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The description that appears on the receiving end for this OutboundPayment (for example, bank statement for external bank transfer). Maximum 10 characters for `ach` payments, 140 characters for `us_domestic_wire` payments, or 500 characters for `stripe` network transfers. The default value is "payment". + StatementDescriptor *string `form:"statement_descriptor"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryOutboundPaymentCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryOutboundPaymentCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the details of an existing OutboundPayment by passing the unique OutboundPayment ID from either the OutboundPayment creation request or OutboundPayment list. +type TreasuryOutboundPaymentRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryOutboundPaymentRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type TreasuryOutboundPaymentDestinationPaymentMethodDetailsBillingDetails struct { + Address *Address `json:"address"` + // Email address. + Email string `json:"email"` + // Full name. + Name string `json:"name"` +} +type TreasuryOutboundPaymentDestinationPaymentMethodDetailsFinancialAccount struct { + // Token of the FinancialAccount. + ID string `json:"id"` + // The rails used to send funds. + Network TreasuryOutboundPaymentDestinationPaymentMethodDetailsFinancialAccountNetwork `json:"network"` +} +type TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccount struct { + // Account holder type: individual or company. + AccountHolderType TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountAccountHolderType `json:"account_holder_type"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountAccountType `json:"account_type"` + // Name of the bank associated with the bank account. + BankName string `json:"bank_name"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // ID of the mandate used to make this payment. + Mandate *Mandate `json:"mandate"` + // The network rails used. See the [docs](https://stripe.com/docs/treasury/money-movement/timelines) to learn more about money movement timelines for each network type. + Network TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccountNetwork `json:"network"` + // Routing number of the bank account. + RoutingNumber string `json:"routing_number"` +} + +// Details about the PaymentMethod for an OutboundPayment. +type TreasuryOutboundPaymentDestinationPaymentMethodDetails struct { + BillingDetails *TreasuryOutboundPaymentDestinationPaymentMethodDetailsBillingDetails `json:"billing_details"` + FinancialAccount *TreasuryOutboundPaymentDestinationPaymentMethodDetailsFinancialAccount `json:"financial_account"` + // The type of the payment method used in the OutboundPayment. + Type TreasuryOutboundPaymentDestinationPaymentMethodDetailsType `json:"type"` + USBankAccount *TreasuryOutboundPaymentDestinationPaymentMethodDetailsUSBankAccount `json:"us_bank_account"` +} + +// Details about the end user. +type TreasuryOutboundPaymentEndUserDetails struct { + // IP address of the user initiating the OutboundPayment. Set if `present` is set to `true`. IP address collection is required for risk and compliance reasons. This will be used to help determine if the OutboundPayment is authorized or should be blocked. + IPAddress string `json:"ip_address"` + // `true` if the OutboundPayment creation request is being made on behalf of an end user by a platform. Otherwise, `false`. + Present bool `json:"present"` +} + +// Details about a returned OutboundPayment. Only set when the status is `returned`. +type TreasuryOutboundPaymentReturnedDetails struct { + // Reason for the return. + Code TreasuryOutboundPaymentReturnedDetailsCode `json:"code"` + // The Transaction associated with this object. + Transaction *TreasuryTransaction `json:"transaction"` +} +type TreasuryOutboundPaymentStatusTransitions struct { + // Timestamp describing when an OutboundPayment changed status to `canceled`. + CanceledAt int64 `json:"canceled_at"` + // Timestamp describing when an OutboundPayment changed status to `failed`. + FailedAt int64 `json:"failed_at"` + // Timestamp describing when an OutboundPayment changed status to `posted`. + PostedAt int64 `json:"posted_at"` + // Timestamp describing when an OutboundPayment changed status to `returned`. + ReturnedAt int64 `json:"returned_at"` +} +type TreasuryOutboundPaymentTrackingDetailsACH struct { + // ACH trace ID of the OutboundPayment for payments sent over the `ach` network. + TraceID string `json:"trace_id"` +} +type TreasuryOutboundPaymentTrackingDetailsUSDomesticWire struct { + // CHIPS System Sequence Number (SSN) of the OutboundPayment for payments sent over the `us_domestic_wire` network. + Chips string `json:"chips"` + // IMAD of the OutboundPayment for payments sent over the `us_domestic_wire` network. + Imad string `json:"imad"` + // OMAD of the OutboundPayment for payments sent over the `us_domestic_wire` network. + Omad string `json:"omad"` +} + +// Details about network-specific tracking information if available. +type TreasuryOutboundPaymentTrackingDetails struct { + ACH *TreasuryOutboundPaymentTrackingDetailsACH `json:"ach"` + // The US bank account network used to send funds. + Type TreasuryOutboundPaymentTrackingDetailsType `json:"type"` + USDomesticWire *TreasuryOutboundPaymentTrackingDetailsUSDomesticWire `json:"us_domestic_wire"` +} + +// Use [OutboundPayments](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-payments) to send funds to another party's external bank account or [FinancialAccount](https://stripe.com/docs/api#financial_accounts). To send money to an account belonging to the same user, use an [OutboundTransfer](https://stripe.com/docs/api#outbound_transfers). +// +// Simulate OutboundPayment state changes with the `/v1/test_helpers/treasury/outbound_payments` endpoints. These methods can only be called on test mode objects. +// +// Related guide: [Moving money with Treasury using OutboundPayment objects](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-payments) +type TreasuryOutboundPayment struct { + APIResource + // Amount (in cents) transferred. + Amount int64 `json:"amount"` + // Returns `true` if the object can be canceled, and `false` otherwise. + Cancelable bool `json:"cancelable"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // ID of the [customer](https://stripe.com/docs/api/customers) to whom an OutboundPayment is sent. + Customer string `json:"customer"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // The PaymentMethod via which an OutboundPayment is sent. This field can be empty if the OutboundPayment was created using `destination_payment_method_data`. + DestinationPaymentMethod string `json:"destination_payment_method"` + // Details about the PaymentMethod for an OutboundPayment. + DestinationPaymentMethodDetails *TreasuryOutboundPaymentDestinationPaymentMethodDetails `json:"destination_payment_method_details"` + // Details about the end user. + EndUserDetails *TreasuryOutboundPaymentEndUserDetails `json:"end_user_details"` + // The date when funds are expected to arrive in the destination account. + ExpectedArrivalDate int64 `json:"expected_arrival_date"` + // The FinancialAccount that funds were pulled from. + FinancialAccount string `json:"financial_account"` + // A [hosted transaction receipt](https://stripe.com/docs/treasury/moving-money/regulatory-receipts) URL that is provided when money movement is considered regulated under Stripe's money transmission licenses. + HostedRegulatoryReceiptURL string `json:"hosted_regulatory_receipt_url"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Details about a returned OutboundPayment. Only set when the status is `returned`. + ReturnedDetails *TreasuryOutboundPaymentReturnedDetails `json:"returned_details"` + // The description that appears on the receiving end for an OutboundPayment (for example, bank statement for external bank transfer). + StatementDescriptor string `json:"statement_descriptor"` + // Current status of the OutboundPayment: `processing`, `failed`, `posted`, `returned`, `canceled`. An OutboundPayment is `processing` if it has been created and is pending. The status changes to `posted` once the OutboundPayment has been "confirmed" and funds have left the account, or to `failed` or `canceled`. If an OutboundPayment fails to arrive at its destination, its status will change to `returned`. + Status TreasuryOutboundPaymentStatus `json:"status"` + StatusTransitions *TreasuryOutboundPaymentStatusTransitions `json:"status_transitions"` + // Details about network-specific tracking information if available. + TrackingDetails *TreasuryOutboundPaymentTrackingDetails `json:"tracking_details"` + // The Transaction associated with this object. + Transaction *TreasuryTransaction `json:"transaction"` +} + +// TreasuryOutboundPaymentList is a list of OutboundPayments as retrieved from a list endpoint. +type TreasuryOutboundPaymentList struct { + APIResource + ListMeta + Data []*TreasuryOutboundPayment `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_outboundpayment_service.go b/vendor/github.com/stripe/stripe-go/v82/treasury_outboundpayment_service.go new file mode 100644 index 00000000..9b6d7889 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_outboundpayment_service.go @@ -0,0 +1,73 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TreasuryOutboundPaymentService is used to invoke /v1/treasury/outbound_payments APIs. +type v1TreasuryOutboundPaymentService struct { + B Backend + Key string +} + +// Creates an OutboundPayment. +func (c v1TreasuryOutboundPaymentService) Create(ctx context.Context, params *TreasuryOutboundPaymentCreateParams) (*TreasuryOutboundPayment, error) { + if params == nil { + params = &TreasuryOutboundPaymentCreateParams{} + } + params.Context = ctx + outboundpayment := &TreasuryOutboundPayment{} + err := c.B.Call( + http.MethodPost, "/v1/treasury/outbound_payments", c.Key, params, outboundpayment) + return outboundpayment, err +} + +// Retrieves the details of an existing OutboundPayment by passing the unique OutboundPayment ID from either the OutboundPayment creation request or OutboundPayment list. +func (c v1TreasuryOutboundPaymentService) Retrieve(ctx context.Context, id string, params *TreasuryOutboundPaymentRetrieveParams) (*TreasuryOutboundPayment, error) { + if params == nil { + params = &TreasuryOutboundPaymentRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/outbound_payments/%s", id) + outboundpayment := &TreasuryOutboundPayment{} + err := c.B.Call(http.MethodGet, path, c.Key, params, outboundpayment) + return outboundpayment, err +} + +// Cancel an OutboundPayment. +func (c v1TreasuryOutboundPaymentService) Cancel(ctx context.Context, id string, params *TreasuryOutboundPaymentCancelParams) (*TreasuryOutboundPayment, error) { + if params == nil { + params = &TreasuryOutboundPaymentCancelParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/outbound_payments/%s/cancel", id) + outboundpayment := &TreasuryOutboundPayment{} + err := c.B.Call(http.MethodPost, path, c.Key, params, outboundpayment) + return outboundpayment, err +} + +// Returns a list of OutboundPayments sent from the specified FinancialAccount. +func (c v1TreasuryOutboundPaymentService) List(ctx context.Context, listParams *TreasuryOutboundPaymentListParams) Seq2[*TreasuryOutboundPayment, error] { + if listParams == nil { + listParams = &TreasuryOutboundPaymentListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TreasuryOutboundPayment, ListContainer, error) { + list := &TreasuryOutboundPaymentList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/treasury/outbound_payments", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_outboundtransfer.go b/vendor/github.com/stripe/stripe-go/v82/treasury_outboundtransfer.go new file mode 100644 index 00000000..e67d0a72 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_outboundtransfer.go @@ -0,0 +1,378 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// The rails used to send funds. +type TreasuryOutboundTransferDestinationPaymentMethodDetailsFinancialAccountNetwork string + +// List of values that TreasuryOutboundTransferDestinationPaymentMethodDetailsFinancialAccountNetwork can take +const ( + TreasuryOutboundTransferDestinationPaymentMethodDetailsFinancialAccountNetworkStripe TreasuryOutboundTransferDestinationPaymentMethodDetailsFinancialAccountNetwork = "stripe" +) + +// The type of the payment method used in the OutboundTransfer. +type TreasuryOutboundTransferDestinationPaymentMethodDetailsType string + +// List of values that TreasuryOutboundTransferDestinationPaymentMethodDetailsType can take +const ( + TreasuryOutboundTransferDestinationPaymentMethodDetailsTypeFinancialAccount TreasuryOutboundTransferDestinationPaymentMethodDetailsType = "financial_account" + TreasuryOutboundTransferDestinationPaymentMethodDetailsTypeUSBankAccount TreasuryOutboundTransferDestinationPaymentMethodDetailsType = "us_bank_account" +) + +// Account holder type: individual or company. +type TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountAccountHolderType string + +// List of values that TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountAccountHolderType can take +const ( + TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountAccountHolderTypeCompany TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountAccountHolderType = "company" + TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountAccountHolderTypeIndividual TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountAccountHolderType = "individual" +) + +// Account type: checkings or savings. Defaults to checking if omitted. +type TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountAccountType string + +// List of values that TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountAccountType can take +const ( + TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountAccountTypeChecking TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountAccountType = "checking" + TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountAccountTypeSavings TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountAccountType = "savings" +) + +// The network rails used. See the [docs](https://stripe.com/docs/treasury/money-movement/timelines) to learn more about money movement timelines for each network type. +type TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountNetwork string + +// List of values that TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountNetwork can take +const ( + TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountNetworkACH TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountNetwork = "ach" + TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountNetworkUSDomesticWire TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountNetwork = "us_domestic_wire" +) + +// Reason for the return. +type TreasuryOutboundTransferReturnedDetailsCode string + +// List of values that TreasuryOutboundTransferReturnedDetailsCode can take +const ( + TreasuryOutboundTransferReturnedDetailsCodeAccountClosed TreasuryOutboundTransferReturnedDetailsCode = "account_closed" + TreasuryOutboundTransferReturnedDetailsCodeAccountFrozen TreasuryOutboundTransferReturnedDetailsCode = "account_frozen" + TreasuryOutboundTransferReturnedDetailsCodeBankAccountRestricted TreasuryOutboundTransferReturnedDetailsCode = "bank_account_restricted" + TreasuryOutboundTransferReturnedDetailsCodeBankOwnershipChanged TreasuryOutboundTransferReturnedDetailsCode = "bank_ownership_changed" + TreasuryOutboundTransferReturnedDetailsCodeDeclined TreasuryOutboundTransferReturnedDetailsCode = "declined" + TreasuryOutboundTransferReturnedDetailsCodeIncorrectAccountHolderName TreasuryOutboundTransferReturnedDetailsCode = "incorrect_account_holder_name" + TreasuryOutboundTransferReturnedDetailsCodeInvalidAccountNumber TreasuryOutboundTransferReturnedDetailsCode = "invalid_account_number" + TreasuryOutboundTransferReturnedDetailsCodeInvalidCurrency TreasuryOutboundTransferReturnedDetailsCode = "invalid_currency" + TreasuryOutboundTransferReturnedDetailsCodeNoAccount TreasuryOutboundTransferReturnedDetailsCode = "no_account" + TreasuryOutboundTransferReturnedDetailsCodeOther TreasuryOutboundTransferReturnedDetailsCode = "other" +) + +// Current status of the OutboundTransfer: `processing`, `failed`, `canceled`, `posted`, `returned`. An OutboundTransfer is `processing` if it has been created and is pending. The status changes to `posted` once the OutboundTransfer has been "confirmed" and funds have left the account, or to `failed` or `canceled`. If an OutboundTransfer fails to arrive at its destination, its status will change to `returned`. +type TreasuryOutboundTransferStatus string + +// List of values that TreasuryOutboundTransferStatus can take +const ( + TreasuryOutboundTransferStatusCanceled TreasuryOutboundTransferStatus = "canceled" + TreasuryOutboundTransferStatusFailed TreasuryOutboundTransferStatus = "failed" + TreasuryOutboundTransferStatusPosted TreasuryOutboundTransferStatus = "posted" + TreasuryOutboundTransferStatusProcessing TreasuryOutboundTransferStatus = "processing" + TreasuryOutboundTransferStatusReturned TreasuryOutboundTransferStatus = "returned" +) + +// The US bank account network used to send funds. +type TreasuryOutboundTransferTrackingDetailsType string + +// List of values that TreasuryOutboundTransferTrackingDetailsType can take +const ( + TreasuryOutboundTransferTrackingDetailsTypeACH TreasuryOutboundTransferTrackingDetailsType = "ach" + TreasuryOutboundTransferTrackingDetailsTypeUSDomesticWire TreasuryOutboundTransferTrackingDetailsType = "us_domestic_wire" +) + +// Returns a list of OutboundTransfers sent from the specified FinancialAccount. +type TreasuryOutboundTransferListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Returns objects associated with this FinancialAccount. + FinancialAccount *string `form:"financial_account"` + // Only return OutboundTransfers that have the given status: `processing`, `canceled`, `failed`, `posted`, or `returned`. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryOutboundTransferListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Hash used to generate the PaymentMethod to be used for this OutboundTransfer. Exclusive with `destination_payment_method`. +type TreasuryOutboundTransferDestinationPaymentMethodDataParams struct { + // Required if type is set to `financial_account`. The FinancialAccount ID to send funds to. + FinancialAccount *string `form:"financial_account"` + // The type of the destination. + Type *string `form:"type"` +} + +// Optional fields for `us_bank_account`. +type TreasuryOutboundTransferDestinationPaymentMethodOptionsUSBankAccountParams struct { + // Specifies the network rails to be used. If not set, will default to the PaymentMethod's preferred network. See the [docs](https://stripe.com/docs/treasury/money-movement/timelines) to learn more about money movement timelines for each network type. + Network *string `form:"network"` +} + +// Hash describing payment method configuration details. +type TreasuryOutboundTransferDestinationPaymentMethodOptionsParams struct { + // Optional fields for `us_bank_account`. + USBankAccount *TreasuryOutboundTransferDestinationPaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` +} + +// Creates an OutboundTransfer. +type TreasuryOutboundTransferParams struct { + Params `form:"*"` + // Amount (in cents) to be transferred. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // The PaymentMethod to use as the payment instrument for the OutboundTransfer. + DestinationPaymentMethod *string `form:"destination_payment_method"` + // Hash used to generate the PaymentMethod to be used for this OutboundTransfer. Exclusive with `destination_payment_method`. + DestinationPaymentMethodData *TreasuryOutboundTransferDestinationPaymentMethodDataParams `form:"destination_payment_method_data"` + // Hash describing payment method configuration details. + DestinationPaymentMethodOptions *TreasuryOutboundTransferDestinationPaymentMethodOptionsParams `form:"destination_payment_method_options"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The FinancialAccount to pull funds from. + FinancialAccount *string `form:"financial_account"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Statement descriptor to be shown on the receiving end of an OutboundTransfer. Maximum 10 characters for `ach` transfers or 140 characters for `us_domestic_wire` transfers. The default value is "transfer". + StatementDescriptor *string `form:"statement_descriptor"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryOutboundTransferParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryOutboundTransferParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// An OutboundTransfer can be canceled if the funds have not yet been paid out. +type TreasuryOutboundTransferCancelParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryOutboundTransferCancelParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Hash used to generate the PaymentMethod to be used for this OutboundTransfer. Exclusive with `destination_payment_method`. +type TreasuryOutboundTransferCreateDestinationPaymentMethodDataParams struct { + // Required if type is set to `financial_account`. The FinancialAccount ID to send funds to. + FinancialAccount *string `form:"financial_account"` + // The type of the destination. + Type *string `form:"type"` +} + +// Optional fields for `us_bank_account`. +type TreasuryOutboundTransferCreateDestinationPaymentMethodOptionsUSBankAccountParams struct { + // Specifies the network rails to be used. If not set, will default to the PaymentMethod's preferred network. See the [docs](https://stripe.com/docs/treasury/money-movement/timelines) to learn more about money movement timelines for each network type. + Network *string `form:"network"` +} + +// Hash describing payment method configuration details. +type TreasuryOutboundTransferCreateDestinationPaymentMethodOptionsParams struct { + // Optional fields for `us_bank_account`. + USBankAccount *TreasuryOutboundTransferCreateDestinationPaymentMethodOptionsUSBankAccountParams `form:"us_bank_account"` +} + +// Creates an OutboundTransfer. +type TreasuryOutboundTransferCreateParams struct { + Params `form:"*"` + // Amount (in cents) to be transferred. + Amount *int64 `form:"amount"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency *string `form:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description *string `form:"description"` + // The PaymentMethod to use as the payment instrument for the OutboundTransfer. + DestinationPaymentMethod *string `form:"destination_payment_method"` + // Hash used to generate the PaymentMethod to be used for this OutboundTransfer. Exclusive with `destination_payment_method`. + DestinationPaymentMethodData *TreasuryOutboundTransferCreateDestinationPaymentMethodDataParams `form:"destination_payment_method_data"` + // Hash describing payment method configuration details. + DestinationPaymentMethodOptions *TreasuryOutboundTransferCreateDestinationPaymentMethodOptionsParams `form:"destination_payment_method_options"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The FinancialAccount to pull funds from. + FinancialAccount *string `form:"financial_account"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // Statement descriptor to be shown on the receiving end of an OutboundTransfer. Maximum 10 characters for `ach` transfers or 140 characters for `us_domestic_wire` transfers. The default value is "transfer". + StatementDescriptor *string `form:"statement_descriptor"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryOutboundTransferCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *TreasuryOutboundTransferCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Retrieves the details of an existing OutboundTransfer by passing the unique OutboundTransfer ID from either the OutboundTransfer creation request or OutboundTransfer list. +type TreasuryOutboundTransferRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryOutboundTransferRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type TreasuryOutboundTransferDestinationPaymentMethodDetailsBillingDetails struct { + Address *Address `json:"address"` + // Email address. + Email string `json:"email"` + // Full name. + Name string `json:"name"` +} +type TreasuryOutboundTransferDestinationPaymentMethodDetailsFinancialAccount struct { + // Token of the FinancialAccount. + ID string `json:"id"` + // The rails used to send funds. + Network TreasuryOutboundTransferDestinationPaymentMethodDetailsFinancialAccountNetwork `json:"network"` +} +type TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccount struct { + // Account holder type: individual or company. + AccountHolderType TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountAccountHolderType `json:"account_holder_type"` + // Account type: checkings or savings. Defaults to checking if omitted. + AccountType TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountAccountType `json:"account_type"` + // Name of the bank associated with the bank account. + BankName string `json:"bank_name"` + // Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + Fingerprint string `json:"fingerprint"` + // Last four digits of the bank account number. + Last4 string `json:"last4"` + // ID of the mandate used to make this payment. + Mandate *Mandate `json:"mandate"` + // The network rails used. See the [docs](https://stripe.com/docs/treasury/money-movement/timelines) to learn more about money movement timelines for each network type. + Network TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccountNetwork `json:"network"` + // Routing number of the bank account. + RoutingNumber string `json:"routing_number"` +} +type TreasuryOutboundTransferDestinationPaymentMethodDetails struct { + BillingDetails *TreasuryOutboundTransferDestinationPaymentMethodDetailsBillingDetails `json:"billing_details"` + FinancialAccount *TreasuryOutboundTransferDestinationPaymentMethodDetailsFinancialAccount `json:"financial_account"` + // The type of the payment method used in the OutboundTransfer. + Type TreasuryOutboundTransferDestinationPaymentMethodDetailsType `json:"type"` + USBankAccount *TreasuryOutboundTransferDestinationPaymentMethodDetailsUSBankAccount `json:"us_bank_account"` +} + +// Details about a returned OutboundTransfer. Only set when the status is `returned`. +type TreasuryOutboundTransferReturnedDetails struct { + // Reason for the return. + Code TreasuryOutboundTransferReturnedDetailsCode `json:"code"` + // The Transaction associated with this object. + Transaction *TreasuryTransaction `json:"transaction"` +} +type TreasuryOutboundTransferStatusTransitions struct { + // Timestamp describing when an OutboundTransfer changed status to `canceled` + CanceledAt int64 `json:"canceled_at"` + // Timestamp describing when an OutboundTransfer changed status to `failed` + FailedAt int64 `json:"failed_at"` + // Timestamp describing when an OutboundTransfer changed status to `posted` + PostedAt int64 `json:"posted_at"` + // Timestamp describing when an OutboundTransfer changed status to `returned` + ReturnedAt int64 `json:"returned_at"` +} +type TreasuryOutboundTransferTrackingDetailsACH struct { + // ACH trace ID of the OutboundTransfer for transfers sent over the `ach` network. + TraceID string `json:"trace_id"` +} +type TreasuryOutboundTransferTrackingDetailsUSDomesticWire struct { + // CHIPS System Sequence Number (SSN) of the OutboundTransfer for transfers sent over the `us_domestic_wire` network. + Chips string `json:"chips"` + // IMAD of the OutboundTransfer for transfers sent over the `us_domestic_wire` network. + Imad string `json:"imad"` + // OMAD of the OutboundTransfer for transfers sent over the `us_domestic_wire` network. + Omad string `json:"omad"` +} + +// Details about network-specific tracking information if available. +type TreasuryOutboundTransferTrackingDetails struct { + ACH *TreasuryOutboundTransferTrackingDetailsACH `json:"ach"` + // The US bank account network used to send funds. + Type TreasuryOutboundTransferTrackingDetailsType `json:"type"` + USDomesticWire *TreasuryOutboundTransferTrackingDetailsUSDomesticWire `json:"us_domestic_wire"` +} + +// Use [OutboundTransfers](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-transfers) to transfer funds from a [FinancialAccount](https://stripe.com/docs/api#financial_accounts) to a PaymentMethod belonging to the same entity. To send funds to a different party, use [OutboundPayments](https://stripe.com/docs/api#outbound_payments) instead. You can send funds over ACH rails or through a domestic wire transfer to a user's own external bank account. +// +// Simulate OutboundTransfer state changes with the `/v1/test_helpers/treasury/outbound_transfers` endpoints. These methods can only be called on test mode objects. +// +// Related guide: [Moving money with Treasury using OutboundTransfer objects](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-transfers) +type TreasuryOutboundTransfer struct { + APIResource + // Amount (in cents) transferred. + Amount int64 `json:"amount"` + // Returns `true` if the object can be canceled, and `false` otherwise. + Cancelable bool `json:"cancelable"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // The PaymentMethod used as the payment instrument for an OutboundTransfer. + DestinationPaymentMethod string `json:"destination_payment_method"` + DestinationPaymentMethodDetails *TreasuryOutboundTransferDestinationPaymentMethodDetails `json:"destination_payment_method_details"` + // The date when funds are expected to arrive in the destination account. + ExpectedArrivalDate int64 `json:"expected_arrival_date"` + // The FinancialAccount that funds were pulled from. + FinancialAccount string `json:"financial_account"` + // A [hosted transaction receipt](https://stripe.com/docs/treasury/moving-money/regulatory-receipts) URL that is provided when money movement is considered regulated under Stripe's money transmission licenses. + HostedRegulatoryReceiptURL string `json:"hosted_regulatory_receipt_url"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Details about a returned OutboundTransfer. Only set when the status is `returned`. + ReturnedDetails *TreasuryOutboundTransferReturnedDetails `json:"returned_details"` + // Information about the OutboundTransfer to be sent to the recipient account. + StatementDescriptor string `json:"statement_descriptor"` + // Current status of the OutboundTransfer: `processing`, `failed`, `canceled`, `posted`, `returned`. An OutboundTransfer is `processing` if it has been created and is pending. The status changes to `posted` once the OutboundTransfer has been "confirmed" and funds have left the account, or to `failed` or `canceled`. If an OutboundTransfer fails to arrive at its destination, its status will change to `returned`. + Status TreasuryOutboundTransferStatus `json:"status"` + StatusTransitions *TreasuryOutboundTransferStatusTransitions `json:"status_transitions"` + // Details about network-specific tracking information if available. + TrackingDetails *TreasuryOutboundTransferTrackingDetails `json:"tracking_details"` + // The Transaction associated with this object. + Transaction *TreasuryTransaction `json:"transaction"` +} + +// TreasuryOutboundTransferList is a list of OutboundTransfers as retrieved from a list endpoint. +type TreasuryOutboundTransferList struct { + APIResource + ListMeta + Data []*TreasuryOutboundTransfer `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_outboundtransfer_service.go b/vendor/github.com/stripe/stripe-go/v82/treasury_outboundtransfer_service.go new file mode 100644 index 00000000..70e50a83 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_outboundtransfer_service.go @@ -0,0 +1,73 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TreasuryOutboundTransferService is used to invoke /v1/treasury/outbound_transfers APIs. +type v1TreasuryOutboundTransferService struct { + B Backend + Key string +} + +// Creates an OutboundTransfer. +func (c v1TreasuryOutboundTransferService) Create(ctx context.Context, params *TreasuryOutboundTransferCreateParams) (*TreasuryOutboundTransfer, error) { + if params == nil { + params = &TreasuryOutboundTransferCreateParams{} + } + params.Context = ctx + outboundtransfer := &TreasuryOutboundTransfer{} + err := c.B.Call( + http.MethodPost, "/v1/treasury/outbound_transfers", c.Key, params, outboundtransfer) + return outboundtransfer, err +} + +// Retrieves the details of an existing OutboundTransfer by passing the unique OutboundTransfer ID from either the OutboundTransfer creation request or OutboundTransfer list. +func (c v1TreasuryOutboundTransferService) Retrieve(ctx context.Context, id string, params *TreasuryOutboundTransferRetrieveParams) (*TreasuryOutboundTransfer, error) { + if params == nil { + params = &TreasuryOutboundTransferRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/outbound_transfers/%s", id) + outboundtransfer := &TreasuryOutboundTransfer{} + err := c.B.Call(http.MethodGet, path, c.Key, params, outboundtransfer) + return outboundtransfer, err +} + +// An OutboundTransfer can be canceled if the funds have not yet been paid out. +func (c v1TreasuryOutboundTransferService) Cancel(ctx context.Context, id string, params *TreasuryOutboundTransferCancelParams) (*TreasuryOutboundTransfer, error) { + if params == nil { + params = &TreasuryOutboundTransferCancelParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/outbound_transfers/%s/cancel", id) + outboundtransfer := &TreasuryOutboundTransfer{} + err := c.B.Call(http.MethodPost, path, c.Key, params, outboundtransfer) + return outboundtransfer, err +} + +// Returns a list of OutboundTransfers sent from the specified FinancialAccount. +func (c v1TreasuryOutboundTransferService) List(ctx context.Context, listParams *TreasuryOutboundTransferListParams) Seq2[*TreasuryOutboundTransfer, error] { + if listParams == nil { + listParams = &TreasuryOutboundTransferListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TreasuryOutboundTransfer, ListContainer, error) { + list := &TreasuryOutboundTransferList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/treasury/outbound_transfers", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_receivedcredit.go b/vendor/github.com/stripe/stripe-go/v82/treasury_receivedcredit.go new file mode 100644 index 00000000..175299a7 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_receivedcredit.go @@ -0,0 +1,264 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Reason for the failure. A ReceivedCredit might fail because the receiving FinancialAccount is closed or frozen. +type TreasuryReceivedCreditFailureCode string + +// List of values that TreasuryReceivedCreditFailureCode can take +const ( + TreasuryReceivedCreditFailureCodeAccountClosed TreasuryReceivedCreditFailureCode = "account_closed" + TreasuryReceivedCreditFailureCodeAccountFrozen TreasuryReceivedCreditFailureCode = "account_frozen" + TreasuryReceivedCreditFailureCodeInternationalTransaction TreasuryReceivedCreditFailureCode = "international_transaction" + TreasuryReceivedCreditFailureCodeOther TreasuryReceivedCreditFailureCode = "other" +) + +// Set when `type` is `balance`. +type TreasuryReceivedCreditInitiatingPaymentMethodDetailsBalance string + +// List of values that TreasuryReceivedCreditInitiatingPaymentMethodDetailsBalance can take +const ( + TreasuryReceivedCreditInitiatingPaymentMethodDetailsBalancePayments TreasuryReceivedCreditInitiatingPaymentMethodDetailsBalance = "payments" +) + +// The rails the ReceivedCredit was sent over. A FinancialAccount can only send funds over `stripe`. +type TreasuryReceivedCreditInitiatingPaymentMethodDetailsFinancialAccountNetwork string + +// List of values that TreasuryReceivedCreditInitiatingPaymentMethodDetailsFinancialAccountNetwork can take +const ( + TreasuryReceivedCreditInitiatingPaymentMethodDetailsFinancialAccountNetworkStripe TreasuryReceivedCreditInitiatingPaymentMethodDetailsFinancialAccountNetwork = "stripe" +) + +// Polymorphic type matching the originating money movement's source. This can be an external account, a Stripe balance, or a FinancialAccount. +type TreasuryReceivedCreditInitiatingPaymentMethodDetailsType string + +// List of values that TreasuryReceivedCreditInitiatingPaymentMethodDetailsType can take +const ( + TreasuryReceivedCreditInitiatingPaymentMethodDetailsTypeBalance TreasuryReceivedCreditInitiatingPaymentMethodDetailsType = "balance" + TreasuryReceivedCreditInitiatingPaymentMethodDetailsTypeFinancialAccount TreasuryReceivedCreditInitiatingPaymentMethodDetailsType = "financial_account" + TreasuryReceivedCreditInitiatingPaymentMethodDetailsTypeIssuingCard TreasuryReceivedCreditInitiatingPaymentMethodDetailsType = "issuing_card" + TreasuryReceivedCreditInitiatingPaymentMethodDetailsTypeStripe TreasuryReceivedCreditInitiatingPaymentMethodDetailsType = "stripe" + TreasuryReceivedCreditInitiatingPaymentMethodDetailsTypeUSBankAccount TreasuryReceivedCreditInitiatingPaymentMethodDetailsType = "us_bank_account" +) + +// The type of the source flow that originated the ReceivedCredit. +type TreasuryReceivedCreditLinkedFlowsSourceFlowDetailsType string + +// List of values that TreasuryReceivedCreditLinkedFlowsSourceFlowDetailsType can take +const ( + TreasuryReceivedCreditLinkedFlowsSourceFlowDetailsTypeCreditReversal TreasuryReceivedCreditLinkedFlowsSourceFlowDetailsType = "credit_reversal" + TreasuryReceivedCreditLinkedFlowsSourceFlowDetailsTypeOther TreasuryReceivedCreditLinkedFlowsSourceFlowDetailsType = "other" + TreasuryReceivedCreditLinkedFlowsSourceFlowDetailsTypeOutboundPayment TreasuryReceivedCreditLinkedFlowsSourceFlowDetailsType = "outbound_payment" + TreasuryReceivedCreditLinkedFlowsSourceFlowDetailsTypeOutboundTransfer TreasuryReceivedCreditLinkedFlowsSourceFlowDetailsType = "outbound_transfer" + TreasuryReceivedCreditLinkedFlowsSourceFlowDetailsTypePayout TreasuryReceivedCreditLinkedFlowsSourceFlowDetailsType = "payout" +) + +// The rails used to send the funds. +type TreasuryReceivedCreditNetwork string + +// List of values that TreasuryReceivedCreditNetwork can take +const ( + TreasuryReceivedCreditNetworkACH TreasuryReceivedCreditNetwork = "ach" + TreasuryReceivedCreditNetworkCard TreasuryReceivedCreditNetwork = "card" + TreasuryReceivedCreditNetworkStripe TreasuryReceivedCreditNetwork = "stripe" + TreasuryReceivedCreditNetworkUSDomesticWire TreasuryReceivedCreditNetwork = "us_domestic_wire" +) + +// Set if a ReceivedCredit cannot be reversed. +type TreasuryReceivedCreditReversalDetailsRestrictedReason string + +// List of values that TreasuryReceivedCreditReversalDetailsRestrictedReason can take +const ( + TreasuryReceivedCreditReversalDetailsRestrictedReasonAlreadyReversed TreasuryReceivedCreditReversalDetailsRestrictedReason = "already_reversed" + TreasuryReceivedCreditReversalDetailsRestrictedReasonDeadlinePassed TreasuryReceivedCreditReversalDetailsRestrictedReason = "deadline_passed" + TreasuryReceivedCreditReversalDetailsRestrictedReasonNetworkRestricted TreasuryReceivedCreditReversalDetailsRestrictedReason = "network_restricted" + TreasuryReceivedCreditReversalDetailsRestrictedReasonOther TreasuryReceivedCreditReversalDetailsRestrictedReason = "other" + TreasuryReceivedCreditReversalDetailsRestrictedReasonSourceFlowRestricted TreasuryReceivedCreditReversalDetailsRestrictedReason = "source_flow_restricted" +) + +// Status of the ReceivedCredit. ReceivedCredits are created either `succeeded` (approved) or `failed` (declined). If a ReceivedCredit is declined, the failure reason can be found in the `failure_code` field. +type TreasuryReceivedCreditStatus string + +// List of values that TreasuryReceivedCreditStatus can take +const ( + TreasuryReceivedCreditStatusFailed TreasuryReceivedCreditStatus = "failed" + TreasuryReceivedCreditStatusSucceeded TreasuryReceivedCreditStatus = "succeeded" +) + +// Only return ReceivedCredits described by the flow. +type TreasuryReceivedCreditListLinkedFlowsParams struct { + // The source flow type. + SourceFlowType *string `form:"source_flow_type"` +} + +// Returns a list of ReceivedCredits. +type TreasuryReceivedCreditListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The FinancialAccount that received the funds. + FinancialAccount *string `form:"financial_account"` + // Only return ReceivedCredits described by the flow. + LinkedFlows *TreasuryReceivedCreditListLinkedFlowsParams `form:"linked_flows"` + // Only return ReceivedCredits that have the given status: `succeeded` or `failed`. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryReceivedCreditListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an existing ReceivedCredit by passing the unique ReceivedCredit ID from the ReceivedCredit list. +type TreasuryReceivedCreditParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryReceivedCreditParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an existing ReceivedCredit by passing the unique ReceivedCredit ID from the ReceivedCredit list. +type TreasuryReceivedCreditRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryReceivedCreditRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type TreasuryReceivedCreditInitiatingPaymentMethodDetailsBillingDetails struct { + Address *Address `json:"address"` + // Email address. + Email string `json:"email"` + // Full name. + Name string `json:"name"` +} +type TreasuryReceivedCreditInitiatingPaymentMethodDetailsFinancialAccount struct { + // The FinancialAccount ID. + ID string `json:"id"` + // The rails the ReceivedCredit was sent over. A FinancialAccount can only send funds over `stripe`. + Network TreasuryReceivedCreditInitiatingPaymentMethodDetailsFinancialAccountNetwork `json:"network"` +} +type TreasuryReceivedCreditInitiatingPaymentMethodDetailsUSBankAccount struct { + // Bank name. + BankName string `json:"bank_name"` + // The last four digits of the bank account number. + Last4 string `json:"last4"` + // The routing number for the bank account. + RoutingNumber string `json:"routing_number"` +} +type TreasuryReceivedCreditInitiatingPaymentMethodDetails struct { + // Set when `type` is `balance`. + Balance TreasuryReceivedCreditInitiatingPaymentMethodDetailsBalance `json:"balance"` + BillingDetails *TreasuryReceivedCreditInitiatingPaymentMethodDetailsBillingDetails `json:"billing_details"` + FinancialAccount *TreasuryReceivedCreditInitiatingPaymentMethodDetailsFinancialAccount `json:"financial_account"` + // Set when `type` is `issuing_card`. This is an [Issuing Card](https://stripe.com/docs/api#issuing_cards) ID. + IssuingCard string `json:"issuing_card"` + // Polymorphic type matching the originating money movement's source. This can be an external account, a Stripe balance, or a FinancialAccount. + Type TreasuryReceivedCreditInitiatingPaymentMethodDetailsType `json:"type"` + USBankAccount *TreasuryReceivedCreditInitiatingPaymentMethodDetailsUSBankAccount `json:"us_bank_account"` +} + +// The expandable object of the source flow. +type TreasuryReceivedCreditLinkedFlowsSourceFlowDetails struct { + // You can reverse some [ReceivedCredits](https://stripe.com/docs/api#received_credits) depending on their network and source flow. Reversing a ReceivedCredit leads to the creation of a new object known as a CreditReversal. + CreditReversal *TreasuryCreditReversal `json:"credit_reversal"` + // Use [OutboundPayments](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-payments) to send funds to another party's external bank account or [FinancialAccount](https://stripe.com/docs/api#financial_accounts). To send money to an account belonging to the same user, use an [OutboundTransfer](https://stripe.com/docs/api#outbound_transfers). + // + // Simulate OutboundPayment state changes with the `/v1/test_helpers/treasury/outbound_payments` endpoints. These methods can only be called on test mode objects. + // + // Related guide: [Moving money with Treasury using OutboundPayment objects](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-payments) + OutboundPayment *TreasuryOutboundPayment `json:"outbound_payment"` + // Use [OutboundTransfers](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-transfers) to transfer funds from a [FinancialAccount](https://stripe.com/docs/api#financial_accounts) to a PaymentMethod belonging to the same entity. To send funds to a different party, use [OutboundPayments](https://stripe.com/docs/api#outbound_payments) instead. You can send funds over ACH rails or through a domestic wire transfer to a user's own external bank account. + // + // Simulate OutboundTransfer state changes with the `/v1/test_helpers/treasury/outbound_transfers` endpoints. These methods can only be called on test mode objects. + // + // Related guide: [Moving money with Treasury using OutboundTransfer objects](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-transfers) + OutboundTransfer *TreasuryOutboundTransfer `json:"outbound_transfer"` + // A `Payout` object is created when you receive funds from Stripe, or when you + // initiate a payout to either a bank account or debit card of a [connected + // Stripe account](https://docs.stripe.com/docs/connect/bank-debit-card-payouts). You can retrieve individual payouts, + // and list all payouts. Payouts are made on [varying + // schedules](https://docs.stripe.com/docs/connect/manage-payout-schedule), depending on your country and + // industry. + // + // Related guide: [Receiving payouts](https://stripe.com/docs/payouts) + Payout *Payout `json:"payout"` + // The type of the source flow that originated the ReceivedCredit. + Type TreasuryReceivedCreditLinkedFlowsSourceFlowDetailsType `json:"type"` +} +type TreasuryReceivedCreditLinkedFlows struct { + // The CreditReversal created as a result of this ReceivedCredit being reversed. + CreditReversal string `json:"credit_reversal"` + // Set if the ReceivedCredit was created due to an [Issuing Authorization](https://stripe.com/docs/api#issuing_authorizations) object. + IssuingAuthorization string `json:"issuing_authorization"` + // Set if the ReceivedCredit is also viewable as an [Issuing transaction](https://stripe.com/docs/api#issuing_transactions) object. + IssuingTransaction string `json:"issuing_transaction"` + // ID of the source flow. Set if `network` is `stripe` and the source flow is visible to the user. Examples of source flows include OutboundPayments, payouts, or CreditReversals. + SourceFlow string `json:"source_flow"` + // The expandable object of the source flow. + SourceFlowDetails *TreasuryReceivedCreditLinkedFlowsSourceFlowDetails `json:"source_flow_details"` + // The type of flow that originated the ReceivedCredit (for example, `outbound_payment`). + SourceFlowType string `json:"source_flow_type"` +} + +// Details describing when a ReceivedCredit may be reversed. +type TreasuryReceivedCreditReversalDetails struct { + // Time before which a ReceivedCredit can be reversed. + Deadline int64 `json:"deadline"` + // Set if a ReceivedCredit cannot be reversed. + RestrictedReason TreasuryReceivedCreditReversalDetailsRestrictedReason `json:"restricted_reason"` +} + +// ReceivedCredits represent funds sent to a [FinancialAccount](https://stripe.com/docs/api#financial_accounts) (for example, via ACH or wire). These money movements are not initiated from the FinancialAccount. +type TreasuryReceivedCredit struct { + APIResource + // Amount (in cents) transferred. + Amount int64 `json:"amount"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // Reason for the failure. A ReceivedCredit might fail because the receiving FinancialAccount is closed or frozen. + FailureCode TreasuryReceivedCreditFailureCode `json:"failure_code"` + // The FinancialAccount that received the funds. + FinancialAccount string `json:"financial_account"` + // A [hosted transaction receipt](https://stripe.com/docs/treasury/moving-money/regulatory-receipts) URL that is provided when money movement is considered regulated under Stripe's money transmission licenses. + HostedRegulatoryReceiptURL string `json:"hosted_regulatory_receipt_url"` + // Unique identifier for the object. + ID string `json:"id"` + InitiatingPaymentMethodDetails *TreasuryReceivedCreditInitiatingPaymentMethodDetails `json:"initiating_payment_method_details"` + LinkedFlows *TreasuryReceivedCreditLinkedFlows `json:"linked_flows"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // The rails used to send the funds. + Network TreasuryReceivedCreditNetwork `json:"network"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Details describing when a ReceivedCredit may be reversed. + ReversalDetails *TreasuryReceivedCreditReversalDetails `json:"reversal_details"` + // Status of the ReceivedCredit. ReceivedCredits are created either `succeeded` (approved) or `failed` (declined). If a ReceivedCredit is declined, the failure reason can be found in the `failure_code` field. + Status TreasuryReceivedCreditStatus `json:"status"` + // The Transaction associated with this object. + Transaction *TreasuryTransaction `json:"transaction"` +} + +// TreasuryReceivedCreditList is a list of ReceivedCredits as retrieved from a list endpoint. +type TreasuryReceivedCreditList struct { + APIResource + ListMeta + Data []*TreasuryReceivedCredit `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_receivedcredit_service.go b/vendor/github.com/stripe/stripe-go/v82/treasury_receivedcredit_service.go new file mode 100644 index 00000000..dfea657b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_receivedcredit_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TreasuryReceivedCreditService is used to invoke /v1/treasury/received_credits APIs. +type v1TreasuryReceivedCreditService struct { + B Backend + Key string +} + +// Retrieves the details of an existing ReceivedCredit by passing the unique ReceivedCredit ID from the ReceivedCredit list. +func (c v1TreasuryReceivedCreditService) Retrieve(ctx context.Context, id string, params *TreasuryReceivedCreditRetrieveParams) (*TreasuryReceivedCredit, error) { + if params == nil { + params = &TreasuryReceivedCreditRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/received_credits/%s", id) + receivedcredit := &TreasuryReceivedCredit{} + err := c.B.Call(http.MethodGet, path, c.Key, params, receivedcredit) + return receivedcredit, err +} + +// Returns a list of ReceivedCredits. +func (c v1TreasuryReceivedCreditService) List(ctx context.Context, listParams *TreasuryReceivedCreditListParams) Seq2[*TreasuryReceivedCredit, error] { + if listParams == nil { + listParams = &TreasuryReceivedCreditListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TreasuryReceivedCredit, ListContainer, error) { + list := &TreasuryReceivedCreditList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/treasury/received_credits", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_receiveddebit.go b/vendor/github.com/stripe/stripe-go/v82/treasury_receiveddebit.go new file mode 100644 index 00000000..d7d6855b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_receiveddebit.go @@ -0,0 +1,213 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Reason for the failure. A ReceivedDebit might fail because the FinancialAccount doesn't have sufficient funds, is closed, or is frozen. +type TreasuryReceivedDebitFailureCode string + +// List of values that TreasuryReceivedDebitFailureCode can take +const ( + TreasuryReceivedDebitFailureCodeAccountClosed TreasuryReceivedDebitFailureCode = "account_closed" + TreasuryReceivedDebitFailureCodeAccountFrozen TreasuryReceivedDebitFailureCode = "account_frozen" + TreasuryReceivedDebitFailureCodeInsufficientFunds TreasuryReceivedDebitFailureCode = "insufficient_funds" + TreasuryReceivedDebitFailureCodeInternationalTransaction TreasuryReceivedDebitFailureCode = "international_transaction" + TreasuryReceivedDebitFailureCodeOther TreasuryReceivedDebitFailureCode = "other" +) + +// Set when `type` is `balance`. +type TreasuryReceivedDebitInitiatingPaymentMethodDetailsBalance string + +// List of values that TreasuryReceivedDebitInitiatingPaymentMethodDetailsBalance can take +const ( + TreasuryReceivedDebitInitiatingPaymentMethodDetailsBalancePayments TreasuryReceivedDebitInitiatingPaymentMethodDetailsBalance = "payments" +) + +// The rails the ReceivedCredit was sent over. A FinancialAccount can only send funds over `stripe`. +type TreasuryReceivedDebitInitiatingPaymentMethodDetailsFinancialAccountNetwork string + +// List of values that TreasuryReceivedDebitInitiatingPaymentMethodDetailsFinancialAccountNetwork can take +const ( + TreasuryReceivedDebitInitiatingPaymentMethodDetailsFinancialAccountNetworkStripe TreasuryReceivedDebitInitiatingPaymentMethodDetailsFinancialAccountNetwork = "stripe" +) + +// Polymorphic type matching the originating money movement's source. This can be an external account, a Stripe balance, or a FinancialAccount. +type TreasuryReceivedDebitInitiatingPaymentMethodDetailsType string + +// List of values that TreasuryReceivedDebitInitiatingPaymentMethodDetailsType can take +const ( + TreasuryReceivedDebitInitiatingPaymentMethodDetailsTypeBalance TreasuryReceivedDebitInitiatingPaymentMethodDetailsType = "balance" + TreasuryReceivedDebitInitiatingPaymentMethodDetailsTypeFinancialAccount TreasuryReceivedDebitInitiatingPaymentMethodDetailsType = "financial_account" + TreasuryReceivedDebitInitiatingPaymentMethodDetailsTypeIssuingCard TreasuryReceivedDebitInitiatingPaymentMethodDetailsType = "issuing_card" + TreasuryReceivedDebitInitiatingPaymentMethodDetailsTypeStripe TreasuryReceivedDebitInitiatingPaymentMethodDetailsType = "stripe" + TreasuryReceivedDebitInitiatingPaymentMethodDetailsTypeUSBankAccount TreasuryReceivedDebitInitiatingPaymentMethodDetailsType = "us_bank_account" +) + +// The network used for the ReceivedDebit. +type TreasuryReceivedDebitNetwork string + +// List of values that TreasuryReceivedDebitNetwork can take +const ( + TreasuryReceivedDebitNetworkACH TreasuryReceivedDebitNetwork = "ach" + TreasuryReceivedDebitNetworkCard TreasuryReceivedDebitNetwork = "card" + TreasuryReceivedDebitNetworkStripe TreasuryReceivedDebitNetwork = "stripe" +) + +// Set if a ReceivedDebit can't be reversed. +type TreasuryReceivedDebitReversalDetailsRestrictedReason string + +// List of values that TreasuryReceivedDebitReversalDetailsRestrictedReason can take +const ( + TreasuryReceivedDebitReversalDetailsRestrictedReasonAlreadyReversed TreasuryReceivedDebitReversalDetailsRestrictedReason = "already_reversed" + TreasuryReceivedDebitReversalDetailsRestrictedReasonDeadlinePassed TreasuryReceivedDebitReversalDetailsRestrictedReason = "deadline_passed" + TreasuryReceivedDebitReversalDetailsRestrictedReasonNetworkRestricted TreasuryReceivedDebitReversalDetailsRestrictedReason = "network_restricted" + TreasuryReceivedDebitReversalDetailsRestrictedReasonOther TreasuryReceivedDebitReversalDetailsRestrictedReason = "other" + TreasuryReceivedDebitReversalDetailsRestrictedReasonSourceFlowRestricted TreasuryReceivedDebitReversalDetailsRestrictedReason = "source_flow_restricted" +) + +// Status of the ReceivedDebit. ReceivedDebits are created with a status of either `succeeded` (approved) or `failed` (declined). The failure reason can be found under the `failure_code`. +type TreasuryReceivedDebitStatus string + +// List of values that TreasuryReceivedDebitStatus can take +const ( + TreasuryReceivedDebitStatusFailed TreasuryReceivedDebitStatus = "failed" + TreasuryReceivedDebitStatusSucceeded TreasuryReceivedDebitStatus = "succeeded" +) + +// Returns a list of ReceivedDebits. +type TreasuryReceivedDebitListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // The FinancialAccount that funds were pulled from. + FinancialAccount *string `form:"financial_account"` + // Only return ReceivedDebits that have the given status: `succeeded` or `failed`. + Status *string `form:"status"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryReceivedDebitListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an existing ReceivedDebit by passing the unique ReceivedDebit ID from the ReceivedDebit list +type TreasuryReceivedDebitParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryReceivedDebitParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an existing ReceivedDebit by passing the unique ReceivedDebit ID from the ReceivedDebit list +type TreasuryReceivedDebitRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryReceivedDebitRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +type TreasuryReceivedDebitInitiatingPaymentMethodDetailsBillingDetails struct { + Address *Address `json:"address"` + // Email address. + Email string `json:"email"` + // Full name. + Name string `json:"name"` +} +type TreasuryReceivedDebitInitiatingPaymentMethodDetailsFinancialAccount struct { + // The FinancialAccount ID. + ID string `json:"id"` + // The rails the ReceivedCredit was sent over. A FinancialAccount can only send funds over `stripe`. + Network TreasuryReceivedDebitInitiatingPaymentMethodDetailsFinancialAccountNetwork `json:"network"` +} +type TreasuryReceivedDebitInitiatingPaymentMethodDetailsUSBankAccount struct { + // Bank name. + BankName string `json:"bank_name"` + // The last four digits of the bank account number. + Last4 string `json:"last4"` + // The routing number for the bank account. + RoutingNumber string `json:"routing_number"` +} +type TreasuryReceivedDebitInitiatingPaymentMethodDetails struct { + // Set when `type` is `balance`. + Balance TreasuryReceivedDebitInitiatingPaymentMethodDetailsBalance `json:"balance"` + BillingDetails *TreasuryReceivedDebitInitiatingPaymentMethodDetailsBillingDetails `json:"billing_details"` + FinancialAccount *TreasuryReceivedDebitInitiatingPaymentMethodDetailsFinancialAccount `json:"financial_account"` + // Set when `type` is `issuing_card`. This is an [Issuing Card](https://stripe.com/docs/api#issuing_cards) ID. + IssuingCard string `json:"issuing_card"` + // Polymorphic type matching the originating money movement's source. This can be an external account, a Stripe balance, or a FinancialAccount. + Type TreasuryReceivedDebitInitiatingPaymentMethodDetailsType `json:"type"` + USBankAccount *TreasuryReceivedDebitInitiatingPaymentMethodDetailsUSBankAccount `json:"us_bank_account"` +} +type TreasuryReceivedDebitLinkedFlows struct { + // The DebitReversal created as a result of this ReceivedDebit being reversed. + DebitReversal string `json:"debit_reversal"` + // Set if the ReceivedDebit is associated with an InboundTransfer's return of funds. + InboundTransfer string `json:"inbound_transfer"` + // Set if the ReceivedDebit was created due to an [Issuing Authorization](https://stripe.com/docs/api#issuing_authorizations) object. + IssuingAuthorization string `json:"issuing_authorization"` + // Set if the ReceivedDebit is also viewable as an [Issuing Dispute](https://stripe.com/docs/api#issuing_disputes) object. + IssuingTransaction string `json:"issuing_transaction"` + // Set if the ReceivedDebit was created due to a [Payout](https://stripe.com/docs/api#payouts) object. + Payout string `json:"payout"` +} + +// Details describing when a ReceivedDebit might be reversed. +type TreasuryReceivedDebitReversalDetails struct { + // Time before which a ReceivedDebit can be reversed. + Deadline int64 `json:"deadline"` + // Set if a ReceivedDebit can't be reversed. + RestrictedReason TreasuryReceivedDebitReversalDetailsRestrictedReason `json:"restricted_reason"` +} + +// ReceivedDebits represent funds pulled from a [FinancialAccount](https://stripe.com/docs/api#financial_accounts). These are not initiated from the FinancialAccount. +type TreasuryReceivedDebit struct { + APIResource + // Amount (in cents) transferred. + Amount int64 `json:"amount"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // Reason for the failure. A ReceivedDebit might fail because the FinancialAccount doesn't have sufficient funds, is closed, or is frozen. + FailureCode TreasuryReceivedDebitFailureCode `json:"failure_code"` + // The FinancialAccount that funds were pulled from. + FinancialAccount string `json:"financial_account"` + // A [hosted transaction receipt](https://stripe.com/docs/treasury/moving-money/regulatory-receipts) URL that is provided when money movement is considered regulated under Stripe's money transmission licenses. + HostedRegulatoryReceiptURL string `json:"hosted_regulatory_receipt_url"` + // Unique identifier for the object. + ID string `json:"id"` + InitiatingPaymentMethodDetails *TreasuryReceivedDebitInitiatingPaymentMethodDetails `json:"initiating_payment_method_details"` + LinkedFlows *TreasuryReceivedDebitLinkedFlows `json:"linked_flows"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // The network used for the ReceivedDebit. + Network TreasuryReceivedDebitNetwork `json:"network"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Details describing when a ReceivedDebit might be reversed. + ReversalDetails *TreasuryReceivedDebitReversalDetails `json:"reversal_details"` + // Status of the ReceivedDebit. ReceivedDebits are created with a status of either `succeeded` (approved) or `failed` (declined). The failure reason can be found under the `failure_code`. + Status TreasuryReceivedDebitStatus `json:"status"` + // The Transaction associated with this object. + Transaction *TreasuryTransaction `json:"transaction"` +} + +// TreasuryReceivedDebitList is a list of ReceivedDebits as retrieved from a list endpoint. +type TreasuryReceivedDebitList struct { + APIResource + ListMeta + Data []*TreasuryReceivedDebit `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_receiveddebit_service.go b/vendor/github.com/stripe/stripe-go/v82/treasury_receiveddebit_service.go new file mode 100644 index 00000000..2aaa5c63 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_receiveddebit_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TreasuryReceivedDebitService is used to invoke /v1/treasury/received_debits APIs. +type v1TreasuryReceivedDebitService struct { + B Backend + Key string +} + +// Retrieves the details of an existing ReceivedDebit by passing the unique ReceivedDebit ID from the ReceivedDebit list +func (c v1TreasuryReceivedDebitService) Retrieve(ctx context.Context, id string, params *TreasuryReceivedDebitRetrieveParams) (*TreasuryReceivedDebit, error) { + if params == nil { + params = &TreasuryReceivedDebitRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/received_debits/%s", id) + receiveddebit := &TreasuryReceivedDebit{} + err := c.B.Call(http.MethodGet, path, c.Key, params, receiveddebit) + return receiveddebit, err +} + +// Returns a list of ReceivedDebits. +func (c v1TreasuryReceivedDebitService) List(ctx context.Context, listParams *TreasuryReceivedDebitListParams) Seq2[*TreasuryReceivedDebit, error] { + if listParams == nil { + listParams = &TreasuryReceivedDebitListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TreasuryReceivedDebit, ListContainer, error) { + list := &TreasuryReceivedDebitList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/treasury/received_debits", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_transaction.go b/vendor/github.com/stripe/stripe-go/v82/treasury_transaction.go new file mode 100644 index 00000000..ec29027f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_transaction.go @@ -0,0 +1,219 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "encoding/json" + +// Type of the flow that created the Transaction. Set to the same value as `flow_type`. +type TreasuryTransactionFlowDetailsType string + +// List of values that TreasuryTransactionFlowDetailsType can take +const ( + TreasuryTransactionFlowDetailsTypeCreditReversal TreasuryTransactionFlowDetailsType = "credit_reversal" + TreasuryTransactionFlowDetailsTypeDebitReversal TreasuryTransactionFlowDetailsType = "debit_reversal" + TreasuryTransactionFlowDetailsTypeInboundTransfer TreasuryTransactionFlowDetailsType = "inbound_transfer" + TreasuryTransactionFlowDetailsTypeIssuingAuthorization TreasuryTransactionFlowDetailsType = "issuing_authorization" + TreasuryTransactionFlowDetailsTypeOther TreasuryTransactionFlowDetailsType = "other" + TreasuryTransactionFlowDetailsTypeOutboundPayment TreasuryTransactionFlowDetailsType = "outbound_payment" + TreasuryTransactionFlowDetailsTypeOutboundTransfer TreasuryTransactionFlowDetailsType = "outbound_transfer" + TreasuryTransactionFlowDetailsTypeReceivedCredit TreasuryTransactionFlowDetailsType = "received_credit" + TreasuryTransactionFlowDetailsTypeReceivedDebit TreasuryTransactionFlowDetailsType = "received_debit" +) + +// Type of the flow that created the Transaction. +type TreasuryTransactionFlowType string + +// List of values that TreasuryTransactionFlowType can take +const ( + TreasuryTransactionFlowTypeCreditReversal TreasuryTransactionFlowType = "credit_reversal" + TreasuryTransactionFlowTypeDebitReversal TreasuryTransactionFlowType = "debit_reversal" + TreasuryTransactionFlowTypeInboundTransfer TreasuryTransactionFlowType = "inbound_transfer" + TreasuryTransactionFlowTypeIssuingAuthorization TreasuryTransactionFlowType = "issuing_authorization" + TreasuryTransactionFlowTypeOther TreasuryTransactionFlowType = "other" + TreasuryTransactionFlowTypeOutboundPayment TreasuryTransactionFlowType = "outbound_payment" + TreasuryTransactionFlowTypeOutboundTransfer TreasuryTransactionFlowType = "outbound_transfer" + TreasuryTransactionFlowTypeReceivedCredit TreasuryTransactionFlowType = "received_credit" + TreasuryTransactionFlowTypeReceivedDebit TreasuryTransactionFlowType = "received_debit" +) + +// Status of the Transaction. +type TreasuryTransactionStatus string + +// List of values that TreasuryTransactionStatus can take +const ( + TreasuryTransactionStatusOpen TreasuryTransactionStatus = "open" + TreasuryTransactionStatusPosted TreasuryTransactionStatus = "posted" + TreasuryTransactionStatusVoid TreasuryTransactionStatus = "void" +) + +// A filter for the `status_transitions.posted_at` timestamp. When using this filter, `status=posted` and `order_by=posted_at` must also be specified. +type TreasuryTransactionListStatusTransitionsParams struct { + // Returns Transactions with `posted_at` within the specified range. + PostedAt *int64 `form:"posted_at"` + // Returns Transactions with `posted_at` within the specified range. + PostedAtRange *RangeQueryParams `form:"posted_at"` +} + +// Retrieves a list of Transaction objects. +type TreasuryTransactionListParams struct { + ListParams `form:"*"` + // Only return Transactions that were created during the given date interval. + Created *int64 `form:"created"` + // Only return Transactions that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Returns objects associated with this FinancialAccount. + FinancialAccount *string `form:"financial_account"` + // The results are in reverse chronological order by `created` or `posted_at`. The default is `created`. + OrderBy *string `form:"order_by"` + // Only return Transactions that have the given status: `open`, `posted`, or `void`. + Status *string `form:"status"` + // A filter for the `status_transitions.posted_at` timestamp. When using this filter, `status=posted` and `order_by=posted_at` must also be specified. + StatusTransitions *TreasuryTransactionListStatusTransitionsParams `form:"status_transitions"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryTransactionListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an existing Transaction. +type TreasuryTransactionParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryTransactionParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves the details of an existing Transaction. +type TreasuryTransactionRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryTransactionRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Change to a FinancialAccount's balance +type TreasuryTransactionBalanceImpact struct { + // The change made to funds the user can spend right now. + Cash int64 `json:"cash"` + // The change made to funds that are not spendable yet, but will become available at a later time. + InboundPending int64 `json:"inbound_pending"` + // The change made to funds in the account, but not spendable because they are being held for pending outbound flows. + OutboundPending int64 `json:"outbound_pending"` +} + +// Details of the flow that created the Transaction. +type TreasuryTransactionFlowDetails struct { + // You can reverse some [ReceivedCredits](https://stripe.com/docs/api#received_credits) depending on their network and source flow. Reversing a ReceivedCredit leads to the creation of a new object known as a CreditReversal. + CreditReversal *TreasuryCreditReversal `json:"credit_reversal"` + // You can reverse some [ReceivedDebits](https://stripe.com/docs/api#received_debits) depending on their network and source flow. Reversing a ReceivedDebit leads to the creation of a new object known as a DebitReversal. + DebitReversal *TreasuryDebitReversal `json:"debit_reversal"` + // Use [InboundTransfers](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/into/inbound-transfers) to add funds to your [FinancialAccount](https://stripe.com/docs/api#financial_accounts) via a PaymentMethod that is owned by you. The funds will be transferred via an ACH debit. + // + // Related guide: [Moving money with Treasury using InboundTransfer objects](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/into/inbound-transfers) + InboundTransfer *TreasuryInboundTransfer `json:"inbound_transfer"` + // When an [issued card](https://stripe.com/docs/issuing) is used to make a purchase, an Issuing `Authorization` + // object is created. [Authorizations](https://stripe.com/docs/issuing/purchases/authorizations) must be approved for the + // purchase to be completed successfully. + // + // Related guide: [Issued card authorizations](https://stripe.com/docs/issuing/purchases/authorizations) + IssuingAuthorization *IssuingAuthorization `json:"issuing_authorization"` + // Use [OutboundPayments](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-payments) to send funds to another party's external bank account or [FinancialAccount](https://stripe.com/docs/api#financial_accounts). To send money to an account belonging to the same user, use an [OutboundTransfer](https://stripe.com/docs/api#outbound_transfers). + // + // Simulate OutboundPayment state changes with the `/v1/test_helpers/treasury/outbound_payments` endpoints. These methods can only be called on test mode objects. + // + // Related guide: [Moving money with Treasury using OutboundPayment objects](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-payments) + OutboundPayment *TreasuryOutboundPayment `json:"outbound_payment"` + // Use [OutboundTransfers](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-transfers) to transfer funds from a [FinancialAccount](https://stripe.com/docs/api#financial_accounts) to a PaymentMethod belonging to the same entity. To send funds to a different party, use [OutboundPayments](https://stripe.com/docs/api#outbound_payments) instead. You can send funds over ACH rails or through a domestic wire transfer to a user's own external bank account. + // + // Simulate OutboundTransfer state changes with the `/v1/test_helpers/treasury/outbound_transfers` endpoints. These methods can only be called on test mode objects. + // + // Related guide: [Moving money with Treasury using OutboundTransfer objects](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-transfers) + OutboundTransfer *TreasuryOutboundTransfer `json:"outbound_transfer"` + // ReceivedCredits represent funds sent to a [FinancialAccount](https://stripe.com/docs/api#financial_accounts) (for example, via ACH or wire). These money movements are not initiated from the FinancialAccount. + ReceivedCredit *TreasuryReceivedCredit `json:"received_credit"` + // ReceivedDebits represent funds pulled from a [FinancialAccount](https://stripe.com/docs/api#financial_accounts). These are not initiated from the FinancialAccount. + ReceivedDebit *TreasuryReceivedDebit `json:"received_debit"` + // Type of the flow that created the Transaction. Set to the same value as `flow_type`. + Type TreasuryTransactionFlowDetailsType `json:"type"` +} +type TreasuryTransactionStatusTransitions struct { + // Timestamp describing when the Transaction changed status to `posted`. + PostedAt int64 `json:"posted_at"` + // Timestamp describing when the Transaction changed status to `void`. + VoidAt int64 `json:"void_at"` +} + +// Transactions represent changes to a [FinancialAccount's](https://stripe.com/docs/api#financial_accounts) balance. +type TreasuryTransaction struct { + APIResource + // Amount (in cents) transferred. + Amount int64 `json:"amount"` + // Change to a FinancialAccount's balance + BalanceImpact *TreasuryTransactionBalanceImpact `json:"balance_impact"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // An arbitrary string attached to the object. Often useful for displaying to users. + Description string `json:"description"` + // A list of TransactionEntries that are part of this Transaction. This cannot be expanded in any list endpoints. + Entries *TreasuryTransactionEntryList `json:"entries"` + // The FinancialAccount associated with this object. + FinancialAccount string `json:"financial_account"` + // ID of the flow that created the Transaction. + Flow string `json:"flow"` + // Details of the flow that created the Transaction. + FlowDetails *TreasuryTransactionFlowDetails `json:"flow_details"` + // Type of the flow that created the Transaction. + FlowType TreasuryTransactionFlowType `json:"flow_type"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // Status of the Transaction. + Status TreasuryTransactionStatus `json:"status"` + StatusTransitions *TreasuryTransactionStatusTransitions `json:"status_transitions"` +} + +// TreasuryTransactionList is a list of Transactions as retrieved from a list endpoint. +type TreasuryTransactionList struct { + APIResource + ListMeta + Data []*TreasuryTransaction `json:"data"` +} + +// UnmarshalJSON handles deserialization of a TreasuryTransaction. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (t *TreasuryTransaction) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + t.ID = id + return nil + } + + type treasuryTransaction TreasuryTransaction + var v treasuryTransaction + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *t = TreasuryTransaction(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_transaction_service.go b/vendor/github.com/stripe/stripe-go/v82/treasury_transaction_service.go new file mode 100644 index 00000000..3cc2aedc --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_transaction_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TreasuryTransactionService is used to invoke /v1/treasury/transactions APIs. +type v1TreasuryTransactionService struct { + B Backend + Key string +} + +// Retrieves the details of an existing Transaction. +func (c v1TreasuryTransactionService) Retrieve(ctx context.Context, id string, params *TreasuryTransactionRetrieveParams) (*TreasuryTransaction, error) { + if params == nil { + params = &TreasuryTransactionRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/transactions/%s", id) + transaction := &TreasuryTransaction{} + err := c.B.Call(http.MethodGet, path, c.Key, params, transaction) + return transaction, err +} + +// Retrieves a list of Transaction objects. +func (c v1TreasuryTransactionService) List(ctx context.Context, listParams *TreasuryTransactionListParams) Seq2[*TreasuryTransaction, error] { + if listParams == nil { + listParams = &TreasuryTransactionListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TreasuryTransaction, ListContainer, error) { + list := &TreasuryTransactionList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/treasury/transactions", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_transactionentry.go b/vendor/github.com/stripe/stripe-go/v82/treasury_transactionentry.go new file mode 100644 index 00000000..e49c6342 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_transactionentry.go @@ -0,0 +1,198 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Type of the flow that created the Transaction. Set to the same value as `flow_type`. +type TreasuryTransactionEntryFlowDetailsType string + +// List of values that TreasuryTransactionEntryFlowDetailsType can take +const ( + TreasuryTransactionEntryFlowDetailsTypeCreditReversal TreasuryTransactionEntryFlowDetailsType = "credit_reversal" + TreasuryTransactionEntryFlowDetailsTypeDebitReversal TreasuryTransactionEntryFlowDetailsType = "debit_reversal" + TreasuryTransactionEntryFlowDetailsTypeInboundTransfer TreasuryTransactionEntryFlowDetailsType = "inbound_transfer" + TreasuryTransactionEntryFlowDetailsTypeIssuingAuthorization TreasuryTransactionEntryFlowDetailsType = "issuing_authorization" + TreasuryTransactionEntryFlowDetailsTypeOther TreasuryTransactionEntryFlowDetailsType = "other" + TreasuryTransactionEntryFlowDetailsTypeOutboundPayment TreasuryTransactionEntryFlowDetailsType = "outbound_payment" + TreasuryTransactionEntryFlowDetailsTypeOutboundTransfer TreasuryTransactionEntryFlowDetailsType = "outbound_transfer" + TreasuryTransactionEntryFlowDetailsTypeReceivedCredit TreasuryTransactionEntryFlowDetailsType = "received_credit" + TreasuryTransactionEntryFlowDetailsTypeReceivedDebit TreasuryTransactionEntryFlowDetailsType = "received_debit" +) + +// Type of the flow associated with the TransactionEntry. +type TreasuryTransactionEntryFlowType string + +// List of values that TreasuryTransactionEntryFlowType can take +const ( + TreasuryTransactionEntryFlowTypeCreditReversal TreasuryTransactionEntryFlowType = "credit_reversal" + TreasuryTransactionEntryFlowTypeDebitReversal TreasuryTransactionEntryFlowType = "debit_reversal" + TreasuryTransactionEntryFlowTypeInboundTransfer TreasuryTransactionEntryFlowType = "inbound_transfer" + TreasuryTransactionEntryFlowTypeIssuingAuthorization TreasuryTransactionEntryFlowType = "issuing_authorization" + TreasuryTransactionEntryFlowTypeOther TreasuryTransactionEntryFlowType = "other" + TreasuryTransactionEntryFlowTypeOutboundPayment TreasuryTransactionEntryFlowType = "outbound_payment" + TreasuryTransactionEntryFlowTypeOutboundTransfer TreasuryTransactionEntryFlowType = "outbound_transfer" + TreasuryTransactionEntryFlowTypeReceivedCredit TreasuryTransactionEntryFlowType = "received_credit" + TreasuryTransactionEntryFlowTypeReceivedDebit TreasuryTransactionEntryFlowType = "received_debit" +) + +// The specific money movement that generated the TransactionEntry. +type TreasuryTransactionEntryType string + +// List of values that TreasuryTransactionEntryType can take +const ( + TreasuryTransactionEntryTypeCreditReversal TreasuryTransactionEntryType = "credit_reversal" + TreasuryTransactionEntryTypeCreditReversalPosting TreasuryTransactionEntryType = "credit_reversal_posting" + TreasuryTransactionEntryTypeDebitReversal TreasuryTransactionEntryType = "debit_reversal" + TreasuryTransactionEntryTypeInboundTransfer TreasuryTransactionEntryType = "inbound_transfer" + TreasuryTransactionEntryTypeInboundTransferReturn TreasuryTransactionEntryType = "inbound_transfer_return" + TreasuryTransactionEntryTypeIssuingAuthorizationHold TreasuryTransactionEntryType = "issuing_authorization_hold" + TreasuryTransactionEntryTypeIssuingAuthorizationRelease TreasuryTransactionEntryType = "issuing_authorization_release" + TreasuryTransactionEntryTypeOther TreasuryTransactionEntryType = "other" + TreasuryTransactionEntryTypeOutboundPayment TreasuryTransactionEntryType = "outbound_payment" + TreasuryTransactionEntryTypeOutboundPaymentCancellation TreasuryTransactionEntryType = "outbound_payment_cancellation" + TreasuryTransactionEntryTypeOutboundPaymentFailure TreasuryTransactionEntryType = "outbound_payment_failure" + TreasuryTransactionEntryTypeOutboundPaymentPosting TreasuryTransactionEntryType = "outbound_payment_posting" + TreasuryTransactionEntryTypeOutboundPaymentReturn TreasuryTransactionEntryType = "outbound_payment_return" + TreasuryTransactionEntryTypeOutboundTransfer TreasuryTransactionEntryType = "outbound_transfer" + TreasuryTransactionEntryTypeOutboundTransferCancellation TreasuryTransactionEntryType = "outbound_transfer_cancellation" + TreasuryTransactionEntryTypeOutboundTransferFailure TreasuryTransactionEntryType = "outbound_transfer_failure" + TreasuryTransactionEntryTypeOutboundTransferPosting TreasuryTransactionEntryType = "outbound_transfer_posting" + TreasuryTransactionEntryTypeOutboundTransferReturn TreasuryTransactionEntryType = "outbound_transfer_return" + TreasuryTransactionEntryTypeReceivedCredit TreasuryTransactionEntryType = "received_credit" + TreasuryTransactionEntryTypeReceivedDebit TreasuryTransactionEntryType = "received_debit" +) + +// Retrieves a list of TransactionEntry objects. +type TreasuryTransactionEntryListParams struct { + ListParams `form:"*"` + // Only return TransactionEntries that were created during the given date interval. + Created *int64 `form:"created"` + // Only return TransactionEntries that were created during the given date interval. + CreatedRange *RangeQueryParams `form:"created"` + EffectiveAt *int64 `form:"effective_at"` + EffectiveAtRange *RangeQueryParams `form:"effective_at"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Returns objects associated with this FinancialAccount. + FinancialAccount *string `form:"financial_account"` + // The results are in reverse chronological order by `created` or `effective_at`. The default is `created`. + OrderBy *string `form:"order_by"` + // Only return TransactionEntries associated with this Transaction. + Transaction *string `form:"transaction"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryTransactionEntryListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a TransactionEntry object. +type TreasuryTransactionEntryParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryTransactionEntryParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Retrieves a TransactionEntry object. +type TreasuryTransactionEntryRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *TreasuryTransactionEntryRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Change to a FinancialAccount's balance +type TreasuryTransactionEntryBalanceImpact struct { + // The change made to funds the user can spend right now. + Cash int64 `json:"cash"` + // The change made to funds that are not spendable yet, but will become available at a later time. + InboundPending int64 `json:"inbound_pending"` + // The change made to funds in the account, but not spendable because they are being held for pending outbound flows. + OutboundPending int64 `json:"outbound_pending"` +} + +// Details of the flow associated with the TransactionEntry. +type TreasuryTransactionEntryFlowDetails struct { + // You can reverse some [ReceivedCredits](https://stripe.com/docs/api#received_credits) depending on their network and source flow. Reversing a ReceivedCredit leads to the creation of a new object known as a CreditReversal. + CreditReversal *TreasuryCreditReversal `json:"credit_reversal"` + // You can reverse some [ReceivedDebits](https://stripe.com/docs/api#received_debits) depending on their network and source flow. Reversing a ReceivedDebit leads to the creation of a new object known as a DebitReversal. + DebitReversal *TreasuryDebitReversal `json:"debit_reversal"` + // Use [InboundTransfers](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/into/inbound-transfers) to add funds to your [FinancialAccount](https://stripe.com/docs/api#financial_accounts) via a PaymentMethod that is owned by you. The funds will be transferred via an ACH debit. + // + // Related guide: [Moving money with Treasury using InboundTransfer objects](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/into/inbound-transfers) + InboundTransfer *TreasuryInboundTransfer `json:"inbound_transfer"` + // When an [issued card](https://stripe.com/docs/issuing) is used to make a purchase, an Issuing `Authorization` + // object is created. [Authorizations](https://stripe.com/docs/issuing/purchases/authorizations) must be approved for the + // purchase to be completed successfully. + // + // Related guide: [Issued card authorizations](https://stripe.com/docs/issuing/purchases/authorizations) + IssuingAuthorization *IssuingAuthorization `json:"issuing_authorization"` + // Use [OutboundPayments](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-payments) to send funds to another party's external bank account or [FinancialAccount](https://stripe.com/docs/api#financial_accounts). To send money to an account belonging to the same user, use an [OutboundTransfer](https://stripe.com/docs/api#outbound_transfers). + // + // Simulate OutboundPayment state changes with the `/v1/test_helpers/treasury/outbound_payments` endpoints. These methods can only be called on test mode objects. + // + // Related guide: [Moving money with Treasury using OutboundPayment objects](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-payments) + OutboundPayment *TreasuryOutboundPayment `json:"outbound_payment"` + // Use [OutboundTransfers](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-transfers) to transfer funds from a [FinancialAccount](https://stripe.com/docs/api#financial_accounts) to a PaymentMethod belonging to the same entity. To send funds to a different party, use [OutboundPayments](https://stripe.com/docs/api#outbound_payments) instead. You can send funds over ACH rails or through a domestic wire transfer to a user's own external bank account. + // + // Simulate OutboundTransfer state changes with the `/v1/test_helpers/treasury/outbound_transfers` endpoints. These methods can only be called on test mode objects. + // + // Related guide: [Moving money with Treasury using OutboundTransfer objects](https://docs.stripe.com/docs/treasury/moving-money/financial-accounts/out-of/outbound-transfers) + OutboundTransfer *TreasuryOutboundTransfer `json:"outbound_transfer"` + // ReceivedCredits represent funds sent to a [FinancialAccount](https://stripe.com/docs/api#financial_accounts) (for example, via ACH or wire). These money movements are not initiated from the FinancialAccount. + ReceivedCredit *TreasuryReceivedCredit `json:"received_credit"` + // ReceivedDebits represent funds pulled from a [FinancialAccount](https://stripe.com/docs/api#financial_accounts). These are not initiated from the FinancialAccount. + ReceivedDebit *TreasuryReceivedDebit `json:"received_debit"` + // Type of the flow that created the Transaction. Set to the same value as `flow_type`. + Type TreasuryTransactionEntryFlowDetailsType `json:"type"` +} + +// TransactionEntries represent individual units of money movements within a single [Transaction](https://stripe.com/docs/api#transactions). +type TreasuryTransactionEntry struct { + APIResource + // Change to a FinancialAccount's balance + BalanceImpact *TreasuryTransactionEntryBalanceImpact `json:"balance_impact"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + // Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + Currency Currency `json:"currency"` + // When the TransactionEntry will impact the FinancialAccount's balance. + EffectiveAt int64 `json:"effective_at"` + // The FinancialAccount associated with this object. + FinancialAccount string `json:"financial_account"` + // Token of the flow associated with the TransactionEntry. + Flow string `json:"flow"` + // Details of the flow associated with the TransactionEntry. + FlowDetails *TreasuryTransactionEntryFlowDetails `json:"flow_details"` + // Type of the flow associated with the TransactionEntry. + FlowType TreasuryTransactionEntryFlowType `json:"flow_type"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The Transaction associated with this object. + Transaction *TreasuryTransaction `json:"transaction"` + // The specific money movement that generated the TransactionEntry. + Type TreasuryTransactionEntryType `json:"type"` +} + +// TreasuryTransactionEntryList is a list of TransactionEntries as retrieved from a list endpoint. +type TreasuryTransactionEntryList struct { + APIResource + ListMeta + Data []*TreasuryTransactionEntry `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/treasury_transactionentry_service.go b/vendor/github.com/stripe/stripe-go/v82/treasury_transactionentry_service.go new file mode 100644 index 00000000..41638970 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/treasury_transactionentry_service.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1TreasuryTransactionEntryService is used to invoke /v1/treasury/transaction_entries APIs. +type v1TreasuryTransactionEntryService struct { + B Backend + Key string +} + +// Retrieves a TransactionEntry object. +func (c v1TreasuryTransactionEntryService) Retrieve(ctx context.Context, id string, params *TreasuryTransactionEntryRetrieveParams) (*TreasuryTransactionEntry, error) { + if params == nil { + params = &TreasuryTransactionEntryRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/treasury/transaction_entries/%s", id) + transactionentry := &TreasuryTransactionEntry{} + err := c.B.Call(http.MethodGet, path, c.Key, params, transactionentry) + return transactionentry, err +} + +// Retrieves a list of TransactionEntry objects. +func (c v1TreasuryTransactionEntryService) List(ctx context.Context, listParams *TreasuryTransactionEntryListParams) Seq2[*TreasuryTransactionEntry, error] { + if listParams == nil { + listParams = &TreasuryTransactionEntryListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*TreasuryTransactionEntry, ListContainer, error) { + list := &TreasuryTransactionEntryList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/treasury/transaction_entries", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2_event.go b/vendor/github.com/stripe/stripe-go/v82/v2_event.go new file mode 100644 index 00000000..3e97f21f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2_event.go @@ -0,0 +1,56 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "time" + +// Event reason type. +type V2EventReasonType string + +// List of values that V2EventReasonType can take +const ( + V2EventReasonTypeRequest V2EventReasonType = "request" +) + +// Information on the API request that instigated the event. +type V2EventReasonRequest struct { + // ID of the API request that caused the event. + ID string `json:"id"` + // The idempotency key transmitted during the request. + IdempotencyKey string `json:"idempotency_key"` +} + +// Reason for the event. +type V2EventReason struct { + // Information on the API request that instigated the event. + Request *V2EventReasonRequest `json:"request"` + // Event reason type. + Type V2EventReasonType `json:"type"` +} + +// Events are generated to keep you informed of activity in your business account. APIs in the /v2 namespace generate [thin events](https://docs.stripe.com/event-destinations#benefits-of-thin-events) which have small, unversioned payloads that include a reference to the ID of the object that has changed. The Events v2 API returns these new thin events. [Retrieve the event object](https://docs.stripe.com/event-destinations#fetch-data) for additional data about the event. Use the related object ID in the event payload to [fetch the API resource](https://docs.stripe.com/event-destinations#retrieve-the-object-associated-with-thin-events) of the object associated with the event. Comparatively, events generated by most API v1 include a versioned snapshot of an API object in their payload. +type V2BaseEvent struct { + APIResource + // Authentication context needed to fetch the event or related object. + Context string `json:"context"` + // Time at which the object was created. + Created time.Time `json:"created"` + // Unique identifier for the event. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value of the object field. + Object string `json:"object"` + // Reason for the event. + Reason *V2EventReason `json:"reason"` + // The type of the event. + Type string `json:"type"` +} + +func (e *V2BaseEvent) getBaseEvent() *V2BaseEvent { + return e +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2_eventdestination.go b/vendor/github.com/stripe/stripe-go/v82/v2_eventdestination.go new file mode 100644 index 00000000..d0891287 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2_eventdestination.go @@ -0,0 +1,134 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "time" + +// Payload type of events being subscribed to. +type V2EventDestinationEventPayload string + +// List of values that V2EventDestinationEventPayload can take +const ( + V2EventDestinationEventPayloadSnapshot V2EventDestinationEventPayload = "snapshot" + V2EventDestinationEventPayloadThin V2EventDestinationEventPayload = "thin" +) + +// Where events should be routed from. +type V2EventDestinationEventsFrom string + +// List of values that V2EventDestinationEventsFrom can take +const ( + V2EventDestinationEventsFromOtherAccounts V2EventDestinationEventsFrom = "other_accounts" + V2EventDestinationEventsFromSelf V2EventDestinationEventsFrom = "self" +) + +// Status. It can be set to either enabled or disabled. +type V2EventDestinationStatus string + +// List of values that V2EventDestinationStatus can take +const ( + V2EventDestinationStatusDisabled V2EventDestinationStatus = "disabled" + V2EventDestinationStatusEnabled V2EventDestinationStatus = "enabled" +) + +// Reason event destination has been disabled. +type V2EventDestinationStatusDetailsDisabledReason string + +// List of values that V2EventDestinationStatusDetailsDisabledReason can take +const ( + V2EventDestinationStatusDetailsDisabledReasonNoAwsEventSourceExists V2EventDestinationStatusDetailsDisabledReason = "no_aws_event_source_exists" + V2EventDestinationStatusDetailsDisabledReasonUser V2EventDestinationStatusDetailsDisabledReason = "user" +) + +// Event destination type. +type V2EventDestinationType string + +// List of values that V2EventDestinationType can take +const ( + V2EventDestinationTypeAmazonEventbridge V2EventDestinationType = "amazon_eventbridge" + V2EventDestinationTypeWebhookEndpoint V2EventDestinationType = "webhook_endpoint" +) + +// The state of the AWS event source. +type V2EventDestinationAmazonEventbridgeAwsEventSourceStatus string + +// List of values that V2EventDestinationAmazonEventbridgeAwsEventSourceStatus can take +const ( + V2EventDestinationAmazonEventbridgeAwsEventSourceStatusActive V2EventDestinationAmazonEventbridgeAwsEventSourceStatus = "active" + V2EventDestinationAmazonEventbridgeAwsEventSourceStatusDeleted V2EventDestinationAmazonEventbridgeAwsEventSourceStatus = "deleted" + V2EventDestinationAmazonEventbridgeAwsEventSourceStatusPending V2EventDestinationAmazonEventbridgeAwsEventSourceStatus = "pending" + V2EventDestinationAmazonEventbridgeAwsEventSourceStatusUnknown V2EventDestinationAmazonEventbridgeAwsEventSourceStatus = "unknown" +) + +// Details about why the event destination has been disabled. +type V2EventDestinationStatusDetailsDisabled struct { + // Reason event destination has been disabled. + Reason V2EventDestinationStatusDetailsDisabledReason `json:"reason"` +} + +// Additional information about event destination status. +type V2EventDestinationStatusDetails struct { + // Details about why the event destination has been disabled. + Disabled *V2EventDestinationStatusDetailsDisabled `json:"disabled"` +} + +// Amazon EventBridge configuration. +type V2EventDestinationAmazonEventbridge struct { + // The AWS account ID. + AwsAccountID string `json:"aws_account_id"` + // The ARN of the AWS event source. + AwsEventSourceArn string `json:"aws_event_source_arn"` + // The state of the AWS event source. + AwsEventSourceStatus V2EventDestinationAmazonEventbridgeAwsEventSourceStatus `json:"aws_event_source_status"` +} + +// Webhook endpoint configuration. +type V2EventDestinationWebhookEndpoint struct { + // The signing secret of the webhook endpoint, only includable on creation. + SigningSecret string `json:"signing_secret"` + // The URL of the webhook endpoint, includable. + URL string `json:"url"` +} + +// Set up an event destination to receive events from Stripe across multiple destination types, including [webhook endpoints](https://docs.stripe.com/webhooks) and [Amazon EventBridge](https://docs.stripe.com/event-destinations/eventbridge). Event destinations support receiving [thin events](https://docs.stripe.com/api/v2/events) and [snapshot events](https://docs.stripe.com/api/events). +type V2EventDestination struct { + APIResource + // Amazon EventBridge configuration. + AmazonEventbridge *V2EventDestinationAmazonEventbridge `json:"amazon_eventbridge"` + // Time at which the object was created. + Created time.Time `json:"created"` + // An optional description of what the event destination is used for. + Description string `json:"description"` + // The list of events to enable for this endpoint. + EnabledEvents []string `json:"enabled_events"` + // Payload type of events being subscribed to. + EventPayload V2EventDestinationEventPayload `json:"event_payload"` + // Where events should be routed from. + EventsFrom []V2EventDestinationEventsFrom `json:"events_from"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Metadata. + Metadata map[string]string `json:"metadata"` + // Event destination name. + Name string `json:"name"` + // String representing the object's type. Objects of the same type share the same value of the object field. + Object string `json:"object"` + // If using the snapshot event payload, the API version events are rendered as. + SnapshotAPIVersion string `json:"snapshot_api_version"` + // Status. It can be set to either enabled or disabled. + Status V2EventDestinationStatus `json:"status"` + // Additional information about event destination status. + StatusDetails *V2EventDestinationStatusDetails `json:"status_details"` + // Event destination type. + Type V2EventDestinationType `json:"type"` + // Time at which the object was last updated. + Updated time.Time `json:"updated"` + // Webhook endpoint configuration. + WebhookEndpoint *V2EventDestinationWebhookEndpoint `json:"webhook_endpoint"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2_events.go b/vendor/github.com/stripe/stripe-go/v82/v2_events.go new file mode 100644 index 00000000..61c0a7a9 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2_events.go @@ -0,0 +1,221 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "encoding/json" + "net/http" + "time" +) + +// Open Enum. +type V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCode string + +// List of values that V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCode can take +const ( + V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCodeArchivedMeter V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCode = "archived_meter" + V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCodeMeterEventCustomerNotFound V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCode = "meter_event_customer_not_found" + V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCodeMeterEventDimensionCountTooHigh V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCode = "meter_event_dimension_count_too_high" + V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCodeMeterEventInvalidValue V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCode = "meter_event_invalid_value" + V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCodeMeterEventNoCustomerDefined V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCode = "meter_event_no_customer_defined" + V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCodeMissingDimensionPayloadKeys V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCode = "missing_dimension_payload_keys" + V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCodeNoMeter V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCode = "no_meter" + V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCodeTimestampInFuture V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCode = "timestamp_in_future" + V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCodeTimestampTooFarInPast V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCode = "timestamp_too_far_in_past" +) + +// Open Enum. +type V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCode string + +// List of values that V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCode can take +const ( + V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCodeArchivedMeter V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCode = "archived_meter" + V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCodeMeterEventCustomerNotFound V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCode = "meter_event_customer_not_found" + V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCodeMeterEventDimensionCountTooHigh V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCode = "meter_event_dimension_count_too_high" + V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCodeMeterEventInvalidValue V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCode = "meter_event_invalid_value" + V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCodeMeterEventNoCustomerDefined V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCode = "meter_event_no_customer_defined" + V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCodeMissingDimensionPayloadKeys V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCode = "missing_dimension_payload_keys" + V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCodeNoMeter V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCode = "no_meter" + V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCodeTimestampInFuture V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCode = "timestamp_in_future" + V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCodeTimestampTooFarInPast V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCode = "timestamp_too_far_in_past" +) + +// V2Event is the interface implemented by V2 Events. To get the underlying Event, +// use a type switch or type assertion to one of the concrete event types. +type V2Event interface { + getBaseEvent() *V2BaseEvent +} + +// V2RawEvent is the raw event type for V2 events. It is used to unmarshal the +// event data into a generic structure, and can also be used a default event +// type when the event type is not known. +type V2RawEvent struct { + V2BaseEvent + Data *json.RawMessage `json:"data"` + RelatedObject *RelatedObject `json:"related_object"` +} + +// V1BillingMeterErrorReportTriggeredEvent is the Go struct for the "v1.billing.meter.error_report_triggered" event. +// Occurs when a Meter has invalid async usage events. +type V1BillingMeterErrorReportTriggeredEvent struct { + V2BaseEvent + Data V1BillingMeterErrorReportTriggeredEventData `json:"data"` + RelatedObject RelatedObject `json:"related_object"` + fetchRelatedObject func() (*BillingMeter, error) +} + +// FetchRelatedObject fetches the related BillingMeter object for the event. +func (e V1BillingMeterErrorReportTriggeredEvent) FetchRelatedObject() (*BillingMeter, error) { + return e.fetchRelatedObject() +} + +// V1BillingMeterNoMeterFoundEvent is the Go struct for the "v1.billing.meter.no_meter_found" event. +// Occurs when a Meter's id is missing or invalid in async usage events. +type V1BillingMeterNoMeterFoundEvent struct { + V2BaseEvent + Data V1BillingMeterNoMeterFoundEventData `json:"data"` +} + +// V2CoreEventDestinationPingEvent is the Go struct for the "v2.core.event_destination.ping" event. +// A ping event used to test the connection to an EventDestination. +type V2CoreEventDestinationPingEvent struct { + V2BaseEvent + RelatedObject RelatedObject `json:"related_object"` + fetchRelatedObject func() (*V2EventDestination, error) +} + +// FetchRelatedObject fetches the related V2EventDestination object for the event. +func (e V2CoreEventDestinationPingEvent) FetchRelatedObject() (*V2EventDestination, error) { + return e.fetchRelatedObject() +} + +// The request causes the error. +type V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeSampleErrorRequest struct { + // The request idempotency key. + Identifier string `json:"identifier"` +} + +// A list of sample errors of this type. +type V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeSampleError struct { + // The error message. + ErrorMessage string `json:"error_message"` + // The request causes the error. + Request *V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeSampleErrorRequest `json:"request"` +} + +// The error details. +type V1BillingMeterErrorReportTriggeredEventDataReasonErrorType struct { + // Open Enum. + Code V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeCode `json:"code"` + // The number of errors of this type. + ErrorCount int64 `json:"error_count"` + // A list of sample errors of this type. + SampleErrors []*V1BillingMeterErrorReportTriggeredEventDataReasonErrorTypeSampleError `json:"sample_errors"` +} + +// This contains information about why meter error happens. +type V1BillingMeterErrorReportTriggeredEventDataReason struct { + // The total error count within this window. + ErrorCount int64 `json:"error_count"` + // The error details. + ErrorTypes []*V1BillingMeterErrorReportTriggeredEventDataReasonErrorType `json:"error_types"` +} + +// Occurs when a Meter has invalid async usage events. +type V1BillingMeterErrorReportTriggeredEventData struct { + // Extra field included in the event's `data` when fetched from /v2/events. + DeveloperMessageSummary string `json:"developer_message_summary"` + // This contains information about why meter error happens. + Reason *V1BillingMeterErrorReportTriggeredEventDataReason `json:"reason"` + // The end of the window that is encapsulated by this summary. + ValidationEnd time.Time `json:"validation_end"` + // The start of the window that is encapsulated by this summary. + ValidationStart time.Time `json:"validation_start"` +} + +// The request causes the error. +type V1BillingMeterNoMeterFoundEventDataReasonErrorTypeSampleErrorRequest struct { + // The request idempotency key. + Identifier string `json:"identifier"` +} + +// A list of sample errors of this type. +type V1BillingMeterNoMeterFoundEventDataReasonErrorTypeSampleError struct { + // The error message. + ErrorMessage string `json:"error_message"` + // The request causes the error. + Request *V1BillingMeterNoMeterFoundEventDataReasonErrorTypeSampleErrorRequest `json:"request"` +} + +// The error details. +type V1BillingMeterNoMeterFoundEventDataReasonErrorType struct { + // Open Enum. + Code V1BillingMeterNoMeterFoundEventDataReasonErrorTypeCode `json:"code"` + // The number of errors of this type. + ErrorCount int64 `json:"error_count"` + // A list of sample errors of this type. + SampleErrors []*V1BillingMeterNoMeterFoundEventDataReasonErrorTypeSampleError `json:"sample_errors"` +} + +// This contains information about why meter error happens. +type V1BillingMeterNoMeterFoundEventDataReason struct { + // The total error count within this window. + ErrorCount int64 `json:"error_count"` + // The error details. + ErrorTypes []*V1BillingMeterNoMeterFoundEventDataReasonErrorType `json:"error_types"` +} + +// Occurs when a Meter's id is missing or invalid in async usage events. +type V1BillingMeterNoMeterFoundEventData struct { + // Extra field included in the event's `data` when fetched from /v2/events. + DeveloperMessageSummary string `json:"developer_message_summary"` + // This contains information about why meter error happens. + Reason *V1BillingMeterNoMeterFoundEventDataReason `json:"reason"` + // The end of the window that is encapsulated by this summary. + ValidationEnd time.Time `json:"validation_end"` + // The start of the window that is encapsulated by this summary. + ValidationStart time.Time `json:"validation_start"` +} + +// ConvertRawEvent converts a raw event to a concrete event type. +// If the event type is not known, it returns the raw event. +func ConvertRawEvent(event *V2RawEvent, backend Backend, key string) (V2Event, error) { + switch event.Type { + case "v1.billing.meter.error_report_triggered": + result := &V1BillingMeterErrorReportTriggeredEvent{} + result.V2BaseEvent = event.V2BaseEvent + result.RelatedObject = *event.RelatedObject + result.fetchRelatedObject = func() (*BillingMeter, error) { + v := &BillingMeter{} + err := backend.Call(http.MethodGet, event.RelatedObject.URL, key, nil, v) + return v, err + } + if err := json.Unmarshal(*event.Data, &result.Data); err != nil { + return nil, err + } + return result, nil + case "v1.billing.meter.no_meter_found": + result := &V1BillingMeterNoMeterFoundEvent{} + result.V2BaseEvent = event.V2BaseEvent + if err := json.Unmarshal(*event.Data, &result.Data); err != nil { + return nil, err + } + return result, nil + case "v2.core.event_destination.ping": + result := &V2CoreEventDestinationPingEvent{} + result.V2BaseEvent = event.V2BaseEvent + result.RelatedObject = *event.RelatedObject + result.fetchRelatedObject = func() (*V2EventDestination, error) { + v := &V2EventDestination{} + err := backend.Call(http.MethodGet, event.RelatedObject.URL, key, nil, v) + return v, err + } + return result, nil + default: + return event, nil + } +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2billing_meterevent.go b/vendor/github.com/stripe/stripe-go/v82/v2billing_meterevent.go new file mode 100644 index 00000000..5fe77537 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2billing_meterevent.go @@ -0,0 +1,31 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "time" + +// Fix me empty_doc_string. +type V2BillingMeterEvent struct { + APIResource + // The creation time of this meter event. + Created time.Time `json:"created"` + // The name of the meter event. Corresponds with the `event_name` field on a meter. + EventName string `json:"event_name"` + // A unique identifier for the event. If not provided, one will be generated. We recommend using a globally unique identifier for this. We'll enforce uniqueness within a rolling 24 hour period. + Identifier string `json:"identifier"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value of the object field. + Object string `json:"object"` + // The payload of the event. This must contain the fields corresponding to a meter's + // `customer_mapping.event_payload_key` (default is `stripe_customer_id`) and + // `value_settings.event_payload_key` (default is `value`). Read more about the payload. + Payload map[string]string `json:"payload"` + // The time of the event. Must be within the past 35 calendar days or up to + // 5 minutes in the future. Defaults to current timestamp if not specified. + Timestamp time.Time `json:"timestamp"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2billing_meterevent_params.go b/vendor/github.com/stripe/stripe-go/v82/v2billing_meterevent_params.go new file mode 100644 index 00000000..0fe35e2c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2billing_meterevent_params.go @@ -0,0 +1,49 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "time" + +// Creates a meter event. Events are validated synchronously, but are processed asynchronously. Supports up to 1,000 events per second in livemode. For higher rate-limits, please use meter event streams instead. +type V2BillingMeterEventParams struct { + Params `form:"*"` + // The name of the meter event. Corresponds with the `event_name` field on a meter. + EventName *string `form:"event_name" json:"event_name"` + // A unique identifier for the event. If not provided, one will be generated. + // We recommend using a globally unique identifier for this. We'll enforce + // uniqueness within a rolling 24 hour period. + Identifier *string `form:"identifier" json:"identifier,omitempty"` + // The payload of the event. This must contain the fields corresponding to a meter's + // `customer_mapping.event_payload_key` (default is `stripe_customer_id`) and + // `value_settings.event_payload_key` (default is `value`). Read more about + // the + // [payload](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage#payload-key-overrides). + Payload map[string]string `form:"payload" json:"payload"` + // The time of the event. Must be within the past 35 calendar days or up to + // 5 minutes in the future. Defaults to current timestamp if not specified. + Timestamp *time.Time `form:"timestamp" json:"timestamp,omitempty"` +} + +// Creates a meter event. Events are validated synchronously, but are processed asynchronously. Supports up to 1,000 events per second in livemode. For higher rate-limits, please use meter event streams instead. +type V2BillingMeterEventCreateParams struct { + Params `form:"*"` + // The name of the meter event. Corresponds with the `event_name` field on a meter. + EventName *string `form:"event_name" json:"event_name"` + // A unique identifier for the event. If not provided, one will be generated. + // We recommend using a globally unique identifier for this. We'll enforce + // uniqueness within a rolling 24 hour period. + Identifier *string `form:"identifier" json:"identifier,omitempty"` + // The payload of the event. This must contain the fields corresponding to a meter's + // `customer_mapping.event_payload_key` (default is `stripe_customer_id`) and + // `value_settings.event_payload_key` (default is `value`). Read more about + // the + // [payload](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage#payload-key-overrides). + Payload map[string]string `form:"payload" json:"payload"` + // The time of the event. Must be within the past 35 calendar days or up to + // 5 minutes in the future. Defaults to current timestamp if not specified. + Timestamp *time.Time `form:"timestamp" json:"timestamp,omitempty"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2billing_meterevent_service.go b/vendor/github.com/stripe/stripe-go/v82/v2billing_meterevent_service.go new file mode 100644 index 00000000..88f75574 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2billing_meterevent_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v2BillingMeterEventService is used to invoke meterevent related APIs. +type v2BillingMeterEventService struct { + B Backend + Key string +} + +// Creates a meter event. Events are validated synchronously, but are processed asynchronously. Supports up to 1,000 events per second in livemode. For higher rate-limits, please use meter event streams instead. +func (c v2BillingMeterEventService) Create(ctx context.Context, params *V2BillingMeterEventCreateParams) (*V2BillingMeterEvent, error) { + if params == nil { + params = &V2BillingMeterEventCreateParams{} + } + params.Context = ctx + meterevent := &V2BillingMeterEvent{} + err := c.B.Call( + http.MethodPost, "/v2/billing/meter_events", c.Key, params, meterevent) + return meterevent, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventadjustment.go b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventadjustment.go new file mode 100644 index 00000000..395a145f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventadjustment.go @@ -0,0 +1,51 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "time" + +// Open Enum. The meter event adjustment's status. +type V2BillingMeterEventAdjustmentStatus string + +// List of values that V2BillingMeterEventAdjustmentStatus can take +const ( + V2BillingMeterEventAdjustmentStatusComplete V2BillingMeterEventAdjustmentStatus = "complete" + V2BillingMeterEventAdjustmentStatusPending V2BillingMeterEventAdjustmentStatus = "pending" +) + +// Open Enum. Specifies whether to cancel a single event or a range of events for a time period. Time period cancellation is not supported yet. +type V2BillingMeterEventAdjustmentType string + +// List of values that V2BillingMeterEventAdjustmentType can take +const ( + V2BillingMeterEventAdjustmentTypeCancel V2BillingMeterEventAdjustmentType = "cancel" +) + +// Specifies which event to cancel. +type V2BillingMeterEventAdjustmentCancel struct { + // Unique identifier for the event. You can only cancel events within 24 hours of Stripe receiving them. + Identifier string `json:"identifier"` +} +type V2BillingMeterEventAdjustment struct { + APIResource + // Specifies which event to cancel. + Cancel *V2BillingMeterEventAdjustmentCancel `json:"cancel"` + // The time the adjustment was created. + Created time.Time `json:"created"` + // The name of the meter event. Corresponds with the `event_name` field on a meter. + EventName string `json:"event_name"` + // The unique id of this meter event adjustment. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value of the object field. + Object string `json:"object"` + // Open Enum. The meter event adjustment's status. + Status V2BillingMeterEventAdjustmentStatus `json:"status"` + // Open Enum. Specifies whether to cancel a single event or a range of events for a time period. Time period cancellation is not supported yet. + Type V2BillingMeterEventAdjustmentType `json:"type"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventadjustment_params.go b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventadjustment_params.go new file mode 100644 index 00000000..b52a1ad1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventadjustment_params.go @@ -0,0 +1,41 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Specifies which event to cancel. +type V2BillingMeterEventAdjustmentCancelParams struct { + // Unique identifier for the event. You can only cancel events within 24 hours of Stripe receiving them. + Identifier *string `form:"identifier" json:"identifier"` +} + +// Creates a meter event adjustment to cancel a previously sent meter event. +type V2BillingMeterEventAdjustmentParams struct { + Params `form:"*"` + // Specifies which event to cancel. + Cancel *V2BillingMeterEventAdjustmentCancelParams `form:"cancel" json:"cancel"` + // The name of the meter event. Corresponds with the `event_name` field on a meter. + EventName *string `form:"event_name" json:"event_name"` + // Specifies whether to cancel a single event or a range of events for a time period. Time period cancellation is not supported yet. + Type *string `form:"type" json:"type"` +} + +// Specifies which event to cancel. +type V2BillingMeterEventAdjustmentCreateCancelParams struct { + // Unique identifier for the event. You can only cancel events within 24 hours of Stripe receiving them. + Identifier *string `form:"identifier" json:"identifier"` +} + +// Creates a meter event adjustment to cancel a previously sent meter event. +type V2BillingMeterEventAdjustmentCreateParams struct { + Params `form:"*"` + // Specifies which event to cancel. + Cancel *V2BillingMeterEventAdjustmentCreateCancelParams `form:"cancel" json:"cancel"` + // The name of the meter event. Corresponds with the `event_name` field on a meter. + EventName *string `form:"event_name" json:"event_name"` + // Specifies whether to cancel a single event or a range of events for a time period. Time period cancellation is not supported yet. + Type *string `form:"type" json:"type"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventadjustment_service.go b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventadjustment_service.go new file mode 100644 index 00000000..169aae37 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventadjustment_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v2BillingMeterEventAdjustmentService is used to invoke metereventadjustment related APIs. +type v2BillingMeterEventAdjustmentService struct { + B Backend + Key string +} + +// Creates a meter event adjustment to cancel a previously sent meter event. +func (c v2BillingMeterEventAdjustmentService) Create(ctx context.Context, params *V2BillingMeterEventAdjustmentCreateParams) (*V2BillingMeterEventAdjustment, error) { + if params == nil { + params = &V2BillingMeterEventAdjustmentCreateParams{} + } + params.Context = ctx + metereventadjustment := &V2BillingMeterEventAdjustment{} + err := c.B.Call( + http.MethodPost, "/v2/billing/meter_event_adjustments", c.Key, params, metereventadjustment) + return metereventadjustment, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventsession.go b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventsession.go new file mode 100644 index 00000000..24e7abf2 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventsession.go @@ -0,0 +1,26 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "time" + +type V2BillingMeterEventSession struct { + APIResource + // The authentication token for this session. Use this token when calling the + // high-throughput meter event API. + AuthenticationToken string `json:"authentication_token"` + // The creation time of this session. + Created time.Time `json:"created"` + // The time at which this session will expire. + ExpiresAt time.Time `json:"expires_at"` + // The unique id of this auth session. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // String representing the object's type. Objects of the same type share the same value of the object field. + Object string `json:"object"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventsession_params.go b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventsession_params.go new file mode 100644 index 00000000..a7f06fc2 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventsession_params.go @@ -0,0 +1,17 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Creates a meter event session to send usage on the high-throughput meter event stream. Authentication tokens are only valid for 15 minutes, so you will need to create a new meter event session when your token expires. +type V2BillingMeterEventSessionParams struct { + Params `form:"*"` +} + +// Creates a meter event session to send usage on the high-throughput meter event stream. Authentication tokens are only valid for 15 minutes, so you will need to create a new meter event session when your token expires. +type V2BillingMeterEventSessionCreateParams struct { + Params `form:"*"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventsession_service.go b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventsession_service.go new file mode 100644 index 00000000..eb6335b1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventsession_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v2BillingMeterEventSessionService is used to invoke metereventsession related APIs. +type v2BillingMeterEventSessionService struct { + B Backend + Key string +} + +// Creates a meter event session to send usage on the high-throughput meter event stream. Authentication tokens are only valid for 15 minutes, so you will need to create a new meter event session when your token expires. +func (c v2BillingMeterEventSessionService) Create(ctx context.Context, params *V2BillingMeterEventSessionCreateParams) (*V2BillingMeterEventSession, error) { + if params == nil { + params = &V2BillingMeterEventSessionCreateParams{} + } + params.Context = ctx + metereventsession := &V2BillingMeterEventSession{} + err := c.B.Call( + http.MethodPost, "/v2/billing/meter_event_session", c.Key, params, metereventsession) + return metereventsession, err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventstream_params.go b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventstream_params.go new file mode 100644 index 00000000..8319ad24 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventstream_params.go @@ -0,0 +1,61 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import "time" + +// List of meter events to include in the request. +type V2BillingMeterEventStreamEventParams struct { + // The name of the meter event. Corresponds with the `event_name` field on a meter. + EventName *string `form:"event_name" json:"event_name"` + // A unique identifier for the event. If not provided, one will be generated. + // We recommend using a globally unique identifier for this. We'll enforce + // uniqueness within a rolling 24 hour period. + Identifier *string `form:"identifier" json:"identifier,omitempty"` + // The payload of the event. This must contain the fields corresponding to a meter's + // `customer_mapping.event_payload_key` (default is `stripe_customer_id`) and + // `value_settings.event_payload_key` (default is `value`). Read more about + // the + // [payload](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage#payload-key-overrides). + Payload map[string]string `form:"payload" json:"payload"` + // The time of the event. Must be within the past 35 calendar days or up to + // 5 minutes in the future. Defaults to current timestamp if not specified. + Timestamp *time.Time `form:"timestamp" json:"timestamp,omitempty"` +} + +// Creates meter events. Events are processed asynchronously, including validation. Requires a meter event session for authentication. Supports up to 10,000 requests per second in livemode. For even higher rate-limits, contact sales. +type V2BillingMeterEventStreamParams struct { + Params `form:"*"` + // List of meter events to include in the request. + Events []*V2BillingMeterEventStreamEventParams `form:"events" json:"events"` +} + +// List of meter events to include in the request. +type V2BillingMeterEventStreamCreateEventParams struct { + // The name of the meter event. Corresponds with the `event_name` field on a meter. + EventName *string `form:"event_name" json:"event_name"` + // A unique identifier for the event. If not provided, one will be generated. + // We recommend using a globally unique identifier for this. We'll enforce + // uniqueness within a rolling 24 hour period. + Identifier *string `form:"identifier" json:"identifier,omitempty"` + // The payload of the event. This must contain the fields corresponding to a meter's + // `customer_mapping.event_payload_key` (default is `stripe_customer_id`) and + // `value_settings.event_payload_key` (default is `value`). Read more about + // the + // [payload](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage#payload-key-overrides). + Payload map[string]string `form:"payload" json:"payload"` + // The time of the event. Must be within the past 35 calendar days or up to + // 5 minutes in the future. Defaults to current timestamp if not specified. + Timestamp *time.Time `form:"timestamp" json:"timestamp,omitempty"` +} + +// Creates meter events. Events are processed asynchronously, including validation. Requires a meter event session for authentication. Supports up to 10,000 requests per second in livemode. For even higher rate-limits, contact sales. +type V2BillingMeterEventStreamCreateParams struct { + Params `form:"*"` + // List of meter events to include in the request. + Events []*V2BillingMeterEventStreamCreateEventParams `form:"events" json:"events"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventstream_service.go b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventstream_service.go new file mode 100644 index 00000000..ed7a949d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2billing_metereventstream_service.go @@ -0,0 +1,30 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v2BillingMeterEventStreamService is used to invoke metereventstream related APIs. +type v2BillingMeterEventStreamService struct { + BMeterEvents Backend + Key string +} + +// Creates meter events. Events are processed asynchronously, including validation. Requires a meter event session for authentication. Supports up to 10,000 requests per second in livemode. For even higher rate-limits, contact sales. +func (c v2BillingMeterEventStreamService) Create(ctx context.Context, params *V2BillingMeterEventStreamCreateParams) error { + if params == nil { + params = &V2BillingMeterEventStreamCreateParams{} + } + params.Context = ctx + metereventstream := &APIResource{} + err := c.BMeterEvents.Call( + http.MethodPost, "/v2/billing/meter_event_stream", c.Key, params, metereventstream) + return err +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2core_event_params.go b/vendor/github.com/stripe/stripe-go/v82/v2core_event_params.go new file mode 100644 index 00000000..5c842b94 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2core_event_params.go @@ -0,0 +1,26 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// List events, going back up to 30 days. +type V2CoreEventListParams struct { + Params `form:"*"` + // The page size. + Limit *int64 `form:"limit" json:"limit,omitempty"` + // Primary object ID used to retrieve related events. + ObjectID *string `form:"object_id" json:"object_id"` +} + +// Retrieves the details of an event. +type V2CoreEventParams struct { + Params `form:"*"` +} + +// Retrieves the details of an event. +type V2CoreEventRetrieveParams struct { + Params `form:"*"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2core_event_service.go b/vendor/github.com/stripe/stripe-go/v82/v2core_event_service.go new file mode 100644 index 00000000..bcca0bc0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2core_event_service.go @@ -0,0 +1,56 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v2CoreEventService is used to invoke event related APIs. +type v2CoreEventService struct { + B Backend + Key string +} + +// Retrieves the details of an event. +func (c v2CoreEventService) Retrieve(ctx context.Context, id string, params *V2CoreEventRetrieveParams) (V2Event, error) { + if params == nil { + params = &V2CoreEventRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v2/core/events/%s", id) + raw := &V2RawEvent{} + err := c.B.Call(http.MethodGet, path, c.Key, params, raw) + if err != nil { + return nil, err + } + return ConvertRawEvent(raw, c.B, c.Key) +} + +// List events, going back up to 30 days. +func (c v2CoreEventService) List(ctx context.Context, listParams *V2CoreEventListParams) Seq2[V2Event, error] { + if listParams == nil { + listParams = &V2CoreEventListParams{} + } + listParams.Context = ctx + return NewV2List("/v2/core/events", listParams, func(path string, p ParamsContainer) (*V2Page[V2Event], error) { + raw := &V2Page[V2RawEvent]{} + err := c.B.Call(http.MethodGet, path, c.Key, p, raw) + page := &V2Page[V2Event]{} + page.LastResponse = raw.LastResponse + page.NextPageURL = raw.NextPageURL + page.Data = make([]V2Event, len(raw.Data)) + for i := range raw.Data { + page.Data[i], err = ConvertRawEvent(&raw.Data[i], c.B, c.Key) + if err != nil { + return nil, err + } + } + return page, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2core_eventdestination_params.go b/vendor/github.com/stripe/stripe-go/v82/v2core_eventdestination_params.go new file mode 100644 index 00000000..9ef2777f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2core_eventdestination_params.go @@ -0,0 +1,175 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// Lists all event destinations. +type V2CoreEventDestinationListParams struct { + Params `form:"*"` + // Additional fields to include in the response. Currently supports `webhook_endpoint.url`. + Include []*string `form:"include" json:"include,omitempty"` + // The page size. + Limit *int64 `form:"limit" json:"limit,omitempty"` +} + +// Amazon EventBridge configuration. +type V2CoreEventDestinationAmazonEventbridgeParams struct { + // The AWS account ID. + AwsAccountID *string `form:"aws_account_id" json:"aws_account_id"` + // The region of the AWS event source. + AwsRegion *string `form:"aws_region" json:"aws_region"` +} + +// Webhook endpoint configuration. +type V2CoreEventDestinationWebhookEndpointParams struct { + // The URL of the webhook endpoint. + URL *string `form:"url" json:"url"` +} + +// Create a new event destination. +type V2CoreEventDestinationParams struct { + Params `form:"*"` + // Amazon EventBridge configuration. + AmazonEventbridge *V2CoreEventDestinationAmazonEventbridgeParams `form:"amazon_eventbridge" json:"amazon_eventbridge,omitempty"` + // An optional description of what the event destination is used for. + Description *string `form:"description" json:"description,omitempty"` + // The list of events to enable for this endpoint. + EnabledEvents []*string `form:"enabled_events" json:"enabled_events,omitempty"` + // Payload type of events being subscribed to. + EventPayload *string `form:"event_payload" json:"event_payload,omitempty"` + // Where events should be routed from. + EventsFrom []*string `form:"events_from" json:"events_from,omitempty"` + // Additional fields to include in the response. Currently supports `webhook_endpoint.url`. + Include []*string `form:"include" json:"include,omitempty"` + // Metadata. + Metadata map[string]string `form:"metadata" json:"metadata,omitempty"` + // Event destination name. + Name *string `form:"name" json:"name,omitempty"` + // If using the snapshot event payload, the API version events are rendered as. + SnapshotAPIVersion *string `form:"snapshot_api_version" json:"snapshot_api_version,omitempty"` + // Event destination type. + Type *string `form:"type" json:"type,omitempty"` + // Webhook endpoint configuration. + WebhookEndpoint *V2CoreEventDestinationWebhookEndpointParams `form:"webhook_endpoint" json:"webhook_endpoint,omitempty"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *V2CoreEventDestinationParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Disable an event destination. +type V2CoreEventDestinationDisableParams struct { + Params `form:"*"` +} + +// Enable an event destination. +type V2CoreEventDestinationEnableParams struct { + Params `form:"*"` +} + +// Send a `ping` event to an event destination. +type V2CoreEventDestinationPingParams struct { + Params `form:"*"` +} + +// Amazon EventBridge configuration. +type V2CoreEventDestinationCreateAmazonEventbridgeParams struct { + // The AWS account ID. + AwsAccountID *string `form:"aws_account_id" json:"aws_account_id"` + // The region of the AWS event source. + AwsRegion *string `form:"aws_region" json:"aws_region"` +} + +// Webhook endpoint configuration. +type V2CoreEventDestinationCreateWebhookEndpointParams struct { + // The URL of the webhook endpoint. + URL *string `form:"url" json:"url"` +} + +// Create a new event destination. +type V2CoreEventDestinationCreateParams struct { + Params `form:"*"` + // Amazon EventBridge configuration. + AmazonEventbridge *V2CoreEventDestinationCreateAmazonEventbridgeParams `form:"amazon_eventbridge" json:"amazon_eventbridge,omitempty"` + // An optional description of what the event destination is used for. + Description *string `form:"description" json:"description,omitempty"` + // The list of events to enable for this endpoint. + EnabledEvents []*string `form:"enabled_events" json:"enabled_events"` + // Payload type of events being subscribed to. + EventPayload *string `form:"event_payload" json:"event_payload"` + // Where events should be routed from. + EventsFrom []*string `form:"events_from" json:"events_from,omitempty"` + // Additional fields to include in the response. + Include []*string `form:"include" json:"include,omitempty"` + // Metadata. + Metadata map[string]string `form:"metadata" json:"metadata,omitempty"` + // Event destination name. + Name *string `form:"name" json:"name"` + // If using the snapshot event payload, the API version events are rendered as. + SnapshotAPIVersion *string `form:"snapshot_api_version" json:"snapshot_api_version,omitempty"` + // Event destination type. + Type *string `form:"type" json:"type"` + // Webhook endpoint configuration. + WebhookEndpoint *V2CoreEventDestinationCreateWebhookEndpointParams `form:"webhook_endpoint" json:"webhook_endpoint,omitempty"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *V2CoreEventDestinationCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Delete an event destination. +type V2CoreEventDestinationDeleteParams struct { + Params `form:"*"` +} + +// Retrieves the details of an event destination. +type V2CoreEventDestinationRetrieveParams struct { + Params `form:"*"` + // Additional fields to include in the response. + Include []*string `form:"include" json:"include,omitempty"` +} + +// Webhook endpoint configuration. +type V2CoreEventDestinationUpdateWebhookEndpointParams struct { + // The URL of the webhook endpoint. + URL *string `form:"url" json:"url"` +} + +// Update the details of an event destination. +type V2CoreEventDestinationUpdateParams struct { + Params `form:"*"` + // An optional description of what the event destination is used for. + Description *string `form:"description" json:"description,omitempty"` + // The list of events to enable for this endpoint. + EnabledEvents []*string `form:"enabled_events" json:"enabled_events,omitempty"` + // Additional fields to include in the response. Currently supports `webhook_endpoint.url`. + Include []*string `form:"include" json:"include,omitempty"` + // Metadata. + Metadata map[string]string `form:"metadata" json:"metadata,omitempty"` + // Event destination name. + Name *string `form:"name" json:"name,omitempty"` + // Webhook endpoint configuration. + WebhookEndpoint *V2CoreEventDestinationUpdateWebhookEndpointParams `form:"webhook_endpoint" json:"webhook_endpoint,omitempty"` +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *V2CoreEventDestinationUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v2core_eventdestination_service.go b/vendor/github.com/stripe/stripe-go/v82/v2core_eventdestination_service.go new file mode 100644 index 00000000..4055d15c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v2core_eventdestination_service.go @@ -0,0 +1,114 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" +) + +// v2CoreEventDestinationService is used to invoke eventdestination related APIs. +type v2CoreEventDestinationService struct { + B Backend + Key string +} + +// Create a new event destination. +func (c v2CoreEventDestinationService) Create(ctx context.Context, params *V2CoreEventDestinationCreateParams) (*V2EventDestination, error) { + if params == nil { + params = &V2CoreEventDestinationCreateParams{} + } + params.Context = ctx + eventdestination := &V2EventDestination{} + err := c.B.Call( + http.MethodPost, "/v2/core/event_destinations", c.Key, params, eventdestination) + return eventdestination, err +} + +// Retrieves the details of an event destination. +func (c v2CoreEventDestinationService) Retrieve(ctx context.Context, id string, params *V2CoreEventDestinationRetrieveParams) (*V2EventDestination, error) { + if params == nil { + params = &V2CoreEventDestinationRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v2/core/event_destinations/%s", id) + eventdestination := &V2EventDestination{} + err := c.B.Call(http.MethodGet, path, c.Key, params, eventdestination) + return eventdestination, err +} + +// Update the details of an event destination. +func (c v2CoreEventDestinationService) Update(ctx context.Context, id string, params *V2CoreEventDestinationUpdateParams) (*V2EventDestination, error) { + if params == nil { + params = &V2CoreEventDestinationUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v2/core/event_destinations/%s", id) + eventdestination := &V2EventDestination{} + err := c.B.Call(http.MethodPost, path, c.Key, params, eventdestination) + return eventdestination, err +} + +// Delete an event destination. +func (c v2CoreEventDestinationService) Delete(ctx context.Context, id string, params *V2CoreEventDestinationDeleteParams) (*V2EventDestination, error) { + if params == nil { + params = &V2CoreEventDestinationDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v2/core/event_destinations/%s", id) + eventdestination := &V2EventDestination{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, eventdestination) + return eventdestination, err +} + +// Disable an event destination. +func (c v2CoreEventDestinationService) Disable(ctx context.Context, id string, params *V2CoreEventDestinationDisableParams) (*V2EventDestination, error) { + if params == nil { + params = &V2CoreEventDestinationDisableParams{} + } + params.Context = ctx + path := FormatURLPath("/v2/core/event_destinations/%s/disable", id) + eventdestination := &V2EventDestination{} + err := c.B.Call(http.MethodPost, path, c.Key, params, eventdestination) + return eventdestination, err +} + +// Enable an event destination. +func (c v2CoreEventDestinationService) Enable(ctx context.Context, id string, params *V2CoreEventDestinationEnableParams) (*V2EventDestination, error) { + if params == nil { + params = &V2CoreEventDestinationEnableParams{} + } + params.Context = ctx + path := FormatURLPath("/v2/core/event_destinations/%s/enable", id) + eventdestination := &V2EventDestination{} + err := c.B.Call(http.MethodPost, path, c.Key, params, eventdestination) + return eventdestination, err +} + +// Send a `ping` event to an event destination. +func (c v2CoreEventDestinationService) Ping(id string, params *V2CoreEventDestinationPingParams) (V2Event, error) { + path := FormatURLPath("/v2/core/event_destinations/%s/ping", id) + raw := &V2RawEvent{} + err := c.B.Call(http.MethodPost, path, c.Key, params, raw) + if err != nil { + return nil, err + } + return ConvertRawEvent(raw, c.B, c.Key) +} + +// Lists all event destinations. +func (c v2CoreEventDestinationService) List(ctx context.Context, listParams *V2CoreEventDestinationListParams) Seq2[*V2EventDestination, error] { + if listParams == nil { + listParams = &V2CoreEventDestinationListParams{} + } + listParams.Context = ctx + return NewV2List("/v2/core/event_destinations", listParams, func(path string, p ParamsContainer) (*V2Page[*V2EventDestination], error) { + page := &V2Page[*V2EventDestination]{} + err := c.B.Call(http.MethodGet, path, c.Key, p, page) + return page, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/v32_migration_guide.md b/vendor/github.com/stripe/stripe-go/v82/v32_migration_guide.md new file mode 100644 index 00000000..7f09d20c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/v32_migration_guide.md @@ -0,0 +1,146 @@ +# V32 Migration Guide + +Version 32 of stripe-go contains some very sizable breaking changes. + +The major reason that we moved forward on them is that it was previously +impossible when encoding a parameter struct for an API call to make a +distinction between a field that a user had left unset versus a field that had +been set explicitly, but to an empty value. So if we had a parameter struct +like this: + +``` go +type UsageRecordParams struct { + Quantity uint64 `form:"quantity"` +} +``` + +We were unable to differentiate these two cases: + +``` go +// Initialized with no quantity +UsageRecord {} + +// Initialized with an explicitly zero +UsageRecord { + Quantity: 0, +} +``` + +This is because any uninitialized fields on a struct in Go are set to their +type's "zero value", which for an integer is `0`. + +Working around the problem required a secondary field to help explicitly state +that the zero value was intended, which was quite unintuitive for users: + +``` go +type UsageRecordParams struct { + Quantity uint64 `form:"quantity"` + QuantityZero bool `form:"quantity,zero"` +} + +UsageRecord { + QuantityZero: true, +} +``` + +To address the problem, we moved every parameter struct over to use pointers +instead. So the above becomes: + +``` go +type UsageRecordParams struct { + Quantity *int64 `form:"quantity"` +} +``` + +Because in Go you can't take the address of an inline value (`&0`), we provide +a set of helper functions like `stripe.Int64` specifically for initializing +these structs: + +``` go +UsageRecord { + Quantity: stripe.Int64(0), +} +``` + +The zero value for pointers is `nil`, so we can now easily determine which +values on a struct were never set, and which ones were explicitly set to a zero +value, thus eliminating the need for the secondary fields like `QuantityZero`. + +Because this is a large change, we also took the opportunity to do some +housekeeping throughout the library. Most of this involves renaming fields and +some resources to be more accurate according to how they're named in Stripe's +REST API, but it also involves some smaller changes like moving some types and +constants around. + +Please see the list below for the complete set of changes. + +## Major changes + +* All fields on parameter structs (those that end with `*Params`) are now + pointers. Please use the new helper functions to set them: + * `stripe.Bool` + * `stripe.Float64` + * `stripe.Int64` + * `stripe.String` + + This also means that extra fields that used to be solely used for tracking + meaningful zero values like `CouponEmpty` and `QuantityZero` have been + dropped. Use their corresponding field (e.g., `Coupon`, `Quantity`) with an + explicit empty value instead (`stripe.String("")`, `stripe.Int64(0)`). +* Many fields have been renamed so that they're more consistent with their name + in Stripe's REST API. Most of the time, this changes abbreviations to a more + fully expanded form. For example: + * `Desc` becomes `Description`. + * `Live` becomes `Livemode`. +* A few names of API resources (and their corresponding parameter and list + classes) have changed: + * `Fee` becomes `ApplicationFee`. + * `FeeRefund` becomes `ApplicationFeeRefund`. + * `Owner` becomes `AdditionalOwner`. + * `Sub` becomes `Subscription`. + * `SubItem` becomes `SubscriptionItem`. + * `Transaction` becomes `BalanceTransaction`. + * `TxFee` becomes `BalanceTransactionFee`. +* Some sets of constants have been renamed and migrated to the top-level + `stripe` package. All constants now have a prefix according to what they + describe (for example, card brands all start with `CardBrand*` like + `CardBrandVisa`) and all now reside in the `stripe` package (for example + `dispute.Duplicate` is now `stripe.DisputeReasonDuplicate`). +* Some structs that used to be shared between requests and responses are now + broken apart. All API calls should be using only structs that end with a + `*Params` suffix. So for example, if you were using `Address` or `DOB` + before, you should now use `AddressParams` and `DOBParams`. + +## Other changes + +* All integer values now use `int64` as their type. This means that the + `stripe.Int64` helper function is appropriate for setting all integer values. + This usually doesn't require a change because just setting these fields to a + numerical literal didn't require that the type be explicitly stated. +* `Event.GetObjValue` becomes `Event.GetObjectValue` +* `Params.AddMeta` becomes `Params.AddMetadata` +* `Params.End` and `ListParams.End` become `EndingBefore`, and become a pointer + (use `stripe.String` to set them as with other parameters). +* `Params.Expand` and `ListParams.Expand` (the fields) becomes a slice of + pointers (instead of a slice of strings). +* `Params.Expand` and `ListParams.Expand` (the functions) become `AddExpand`. +* `Params.IdempotencyKey` becomes a pointer. +* `Params.Limit` becomes a pointer. +* `Params.Meta` becomes `Params.Metadata` +* `Params.Start` and `ListParams.Start` become `StartingAfter` +* `Params.StripeAccount` and `ListParams.StripeAccount` become pointers. +* List object data is now accessed with `object.Data` instead of `object.List`. + Nothing changes if you were using iterators and `Next`. +* The previously deprecated `FileUploadParams.File` has been removed. Please + use `FileUploadParams.FileReader` instead. +* The previously deprecated `Params.Account` has been removed. Please use + `Params.StripeAccount` instead. + +As usual, if you find bugs, please [open them on the repository][issues], or +reach out to `support@stripe.com` if you have any other questions. + +[issues]: https://github.com/stripe/stripe-go/issues/new + + diff --git a/vendor/github.com/stripe/stripe-go/v82/webhookendpoint.go b/vendor/github.com/stripe/stripe-go/v82/webhookendpoint.go new file mode 100644 index 00000000..9be60830 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/webhookendpoint.go @@ -0,0 +1,180 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +// You can also delete webhook endpoints via the [webhook endpoint management](https://dashboard.stripe.com/account/webhooks) page of the Stripe dashboard. +type WebhookEndpointParams struct { + Params `form:"*"` + // Whether this endpoint should receive events from connected accounts (`true`), or from your account (`false`). Defaults to `false`. + Connect *bool `form:"connect"` + // An optional description of what the webhook is used for. + Description *string `form:"description"` + // Disable the webhook endpoint if set to true. + Disabled *bool `form:"disabled"` + // The list of events to enable for this endpoint. You may specify `['*']` to enable all events, except those that require explicit selection. + EnabledEvents []*string `form:"enabled_events"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The URL of the webhook endpoint. + URL *string `form:"url"` + // This parameter is only available on creation. + // We recommend setting the API version that the library is pinned to. See apiversion in stripe.go + // Events sent to this endpoint will be generated with this Stripe Version instead of your account's default Stripe Version. + APIVersion *string `form:"api_version"` +} + +// AddExpand appends a new field to expand. +func (p *WebhookEndpointParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *WebhookEndpointParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// Returns a list of your webhook endpoints. +type WebhookEndpointListParams struct { + ListParams `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *WebhookEndpointListParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// You can also delete webhook endpoints via the [webhook endpoint management](https://dashboard.stripe.com/account/webhooks) page of the Stripe dashboard. +type WebhookEndpointDeleteParams struct { + Params `form:"*"` +} + +// Retrieves the webhook endpoint with the given ID. +type WebhookEndpointRetrieveParams struct { + Params `form:"*"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` +} + +// AddExpand appends a new field to expand. +func (p *WebhookEndpointRetrieveParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// Updates the webhook endpoint. You may edit the url, the list of enabled_events, and the status of your endpoint. +type WebhookEndpointUpdateParams struct { + Params `form:"*"` + // An optional description of what the webhook is used for. + Description *string `form:"description"` + // Disable the webhook endpoint if set to true. + Disabled *bool `form:"disabled"` + // The list of events to enable for this endpoint. You may specify `['*']` to enable all events, except those that require explicit selection. + EnabledEvents []*string `form:"enabled_events"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The URL of the webhook endpoint. + URL *string `form:"url"` +} + +// AddExpand appends a new field to expand. +func (p *WebhookEndpointUpdateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *WebhookEndpointUpdateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// A webhook endpoint must have a url and a list of enabled_events. You may optionally specify the Boolean connect parameter. If set to true, then a Connect webhook endpoint that notifies the specified url about events from all connected accounts is created; otherwise an account webhook endpoint that notifies the specified url only about events from your account is created. You can also create webhook endpoints in the [webhooks settings](https://dashboard.stripe.com/account/webhooks) section of the Dashboard. +type WebhookEndpointCreateParams struct { + Params `form:"*"` + // Events sent to this endpoint will be generated with this Stripe Version instead of your account's default Stripe Version. + APIVersion *string `form:"api_version"` + // Whether this endpoint should receive events from connected accounts (`true`), or from your account (`false`). Defaults to `false`. + Connect *bool `form:"connect"` + // An optional description of what the webhook is used for. + Description *string `form:"description"` + // The list of events to enable for this endpoint. You may specify `['*']` to enable all events, except those that require explicit selection. + EnabledEvents []*string `form:"enabled_events"` + // Specifies which fields in the response should be expanded. + Expand []*string `form:"expand"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + Metadata map[string]string `form:"metadata"` + // The URL of the webhook endpoint. + URL *string `form:"url"` +} + +// AddExpand appends a new field to expand. +func (p *WebhookEndpointCreateParams) AddExpand(f string) { + p.Expand = append(p.Expand, &f) +} + +// AddMetadata adds a new key-value pair to the Metadata. +func (p *WebhookEndpointCreateParams) AddMetadata(key string, value string) { + if p.Metadata == nil { + p.Metadata = make(map[string]string) + } + + p.Metadata[key] = value +} + +// You can configure [webhook endpoints](https://docs.stripe.com/webhooks/) via the API to be +// notified about events that happen in your Stripe account or connected +// accounts. +// +// Most users configure webhooks from [the dashboard](https://dashboard.stripe.com/webhooks), which provides a user interface for registering and testing your webhook endpoints. +// +// Related guide: [Setting up webhooks](https://docs.stripe.com/webhooks/configure) +type WebhookEndpoint struct { + APIResource + // The API version events are rendered as for this webhook endpoint. + APIVersion string `json:"api_version"` + // The ID of the associated Connect application. + Application string `json:"application"` + // Time at which the object was created. Measured in seconds since the Unix epoch. + Created int64 `json:"created"` + Deleted bool `json:"deleted"` + // An optional description of what the webhook is used for. + Description string `json:"description"` + // The list of events to enable for this endpoint. `['*']` indicates that all events are enabled, except those that require explicit selection. + EnabledEvents []string `json:"enabled_events"` + // Unique identifier for the object. + ID string `json:"id"` + // Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + Livemode bool `json:"livemode"` + // Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + Metadata map[string]string `json:"metadata"` + // String representing the object's type. Objects of the same type share the same value. + Object string `json:"object"` + // The endpoint's secret, used to generate [webhook signatures](https://docs.stripe.com/webhooks/signatures). Only returned at creation. + Secret string `json:"secret"` + // The status of the webhook. It can be `enabled` or `disabled`. + Status string `json:"status"` + // The URL of the webhook endpoint. + URL string `json:"url"` +} + +// WebhookEndpointList is a list of WebhookEndpoints as retrieved from a list endpoint. +type WebhookEndpointList struct { + APIResource + ListMeta + Data []*WebhookEndpoint `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v82/webhookendpoint_service.go b/vendor/github.com/stripe/stripe-go/v82/webhookendpoint_service.go new file mode 100644 index 00000000..9d17d489 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/webhookendpoint_service.go @@ -0,0 +1,85 @@ +// +// +// File generated from our OpenAPI spec +// +// + +package stripe + +import ( + "context" + "net/http" + + "github.com/stripe/stripe-go/v82/form" +) + +// v1WebhookEndpointService is used to invoke /v1/webhook_endpoints APIs. +type v1WebhookEndpointService struct { + B Backend + Key string +} + +// A webhook endpoint must have a url and a list of enabled_events. You may optionally specify the Boolean connect parameter. If set to true, then a Connect webhook endpoint that notifies the specified url about events from all connected accounts is created; otherwise an account webhook endpoint that notifies the specified url only about events from your account is created. You can also create webhook endpoints in the [webhooks settings](https://dashboard.stripe.com/account/webhooks) section of the Dashboard. +func (c v1WebhookEndpointService) Create(ctx context.Context, params *WebhookEndpointCreateParams) (*WebhookEndpoint, error) { + if params == nil { + params = &WebhookEndpointCreateParams{} + } + params.Context = ctx + webhookendpoint := &WebhookEndpoint{} + err := c.B.Call( + http.MethodPost, "/v1/webhook_endpoints", c.Key, params, webhookendpoint) + return webhookendpoint, err +} + +// Retrieves the webhook endpoint with the given ID. +func (c v1WebhookEndpointService) Retrieve(ctx context.Context, id string, params *WebhookEndpointRetrieveParams) (*WebhookEndpoint, error) { + if params == nil { + params = &WebhookEndpointRetrieveParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/webhook_endpoints/%s", id) + webhookendpoint := &WebhookEndpoint{} + err := c.B.Call(http.MethodGet, path, c.Key, params, webhookendpoint) + return webhookendpoint, err +} + +// Updates the webhook endpoint. You may edit the url, the list of enabled_events, and the status of your endpoint. +func (c v1WebhookEndpointService) Update(ctx context.Context, id string, params *WebhookEndpointUpdateParams) (*WebhookEndpoint, error) { + if params == nil { + params = &WebhookEndpointUpdateParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/webhook_endpoints/%s", id) + webhookendpoint := &WebhookEndpoint{} + err := c.B.Call(http.MethodPost, path, c.Key, params, webhookendpoint) + return webhookendpoint, err +} + +// You can also delete webhook endpoints via the [webhook endpoint management](https://dashboard.stripe.com/account/webhooks) page of the Stripe dashboard. +func (c v1WebhookEndpointService) Delete(ctx context.Context, id string, params *WebhookEndpointDeleteParams) (*WebhookEndpoint, error) { + if params == nil { + params = &WebhookEndpointDeleteParams{} + } + params.Context = ctx + path := FormatURLPath("/v1/webhook_endpoints/%s", id) + webhookendpoint := &WebhookEndpoint{} + err := c.B.Call(http.MethodDelete, path, c.Key, params, webhookendpoint) + return webhookendpoint, err +} + +// Returns a list of your webhook endpoints. +func (c v1WebhookEndpointService) List(ctx context.Context, listParams *WebhookEndpointListParams) Seq2[*WebhookEndpoint, error] { + if listParams == nil { + listParams = &WebhookEndpointListParams{} + } + listParams.Context = ctx + return newV1List(listParams, func(p *Params, b *form.Values) ([]*WebhookEndpoint, ListContainer, error) { + list := &WebhookEndpointList{} + if p == nil { + p = &Params{} + } + p.Context = ctx + err := c.B.CallRaw(http.MethodGet, "/v1/webhook_endpoints", c.Key, []byte(b.Encode()), p, list) + return list.Data, list, err + }).All() +} diff --git a/vendor/github.com/stripe/stripe-go/v82/webhooks.go b/vendor/github.com/stripe/stripe-go/v82/webhooks.go new file mode 100644 index 00000000..91b81998 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v82/webhooks.go @@ -0,0 +1,283 @@ +package stripe + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "strconv" + "strings" + "time" +) + +// +// Public constants +// + +const ( + // DefaultTolerance indicates that signatures older than this will be rejected by ConstructEvent. + WebhookDefaultTolerance time.Duration = 300 * time.Second + // signingVersion represents the version of the signature we currently use. + signingVersion string = "v1" +) + +// +// Public variables +// + +// This block represents the list of errors that could be raised when using the webhook package. +var ( + ErrWebhookInvalidHeader = errors.New("webhook has invalid Stripe-Signature header") + ErrWebhookNoValidSignature = errors.New("webhook had no valid signature") + ErrWebhookNotSigned = errors.New("webhook has no Stripe-Signature header") + ErrWebhookTooOld = errors.New("timestamp wasn't within tolerance") +) + +// +// Public functions +// + +// ComputeSignature computes a webhook signature using Stripe's v1 signing +// method. +// +// See https://stripe.com/docs/webhooks#signatures for more information. +func ComputeSignature(t time.Time, payload []byte, secret string) []byte { + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write([]byte(fmt.Sprintf("%d", t.Unix()))) + mac.Write([]byte(".")) + mac.Write(payload) + return mac.Sum(nil) +} + +// ConstructEvent initializes an Event object from a JSON webhook payload, validating +// the Stripe-Signature header using the specified signing secret. Returns an error +// if the body or Stripe-Signature header provided are unreadable, if the +// signature doesn't match, or if the timestamp for the signature is older than +// DefaultTolerance. +// +// NOTE: Stripe will only send Webhook signing headers after you have retrieved +// your signing secret from the Stripe dashboard: +// https://dashboard.stripe.com/webhooks +// +// This will return an error if the event API version does not match the +// APIVersion constant. +func ConstructEvent(payload []byte, header string, secret string, opts ...WebhookOption) (Event, error) { + cfg := webhookConfig{ + Tolerance: WebhookDefaultTolerance, + } + for _, opt := range opts { + if opt == nil { + continue + } + opt(&cfg) + } + return constructEvent(payload, header, secret, cfg) +} + +// ValidatePayload validates the payload against the Stripe-Signature header +// using the specified signing secret. Returns an error if the body or +// Stripe-Signature header provided are unreadable, if the signature doesn't +// match, or if the timestamp for the signature is older than DefaultTolerance. +// +// NOTE: Stripe will only send Webhook signing headers after you have retrieved +// your signing secret from the Stripe dashboard: +// https://dashboard.stripe.com/webhooks +func ValidatePayload(payload []byte, header string, secret string, opts ...WebhookOption) error { + cfg := webhookConfig{ + Tolerance: WebhookDefaultTolerance, + } + for _, opt := range opts { + if opt == nil { + continue + } + opt(&cfg) + } + return validatePayload(payload, header, secret, cfg) +} + +type WebhookOption func(*webhookConfig) + +// WithTolerance validates event timestamps using a custom Tolerance window. If this is +// not set and `IgnoreTolerance` is false, will default to +// `WebhookDefaultTolerance`. +func WithTolerance(tolerance time.Duration) WebhookOption { + return func(w *webhookConfig) { + w.Tolerance = tolerance + } +} + +// WithIgnoreTolerance will ignore the the event signature's timestamp. +func WithIgnoreTolerance() WebhookOption { + return func(w *webhookConfig) { + w.IgnoreTolerance = true + } +} + +// WithIgnoreAPIVersionMismatch will ignore validating whether an event's API version +// matches the stripe-go API version. This is currently only used for ConstructEvent. +func WithIgnoreAPIVersionMismatch() WebhookOption { + return func(w *webhookConfig) { + w.IgnoreAPIVersionMismatch = true + } +} + +type webhookConfig struct { + Tolerance time.Duration + IgnoreTolerance bool + IgnoreAPIVersionMismatch bool +} + +// +// Private types +// + +type signedHeader struct { + timestamp time.Time + signatures [][]byte +} + +// +// Private functions +// + +func isCompatibleAPIVersion(sdkAPIVersion, eventAPIVersion string) bool { + // If the event api version is from before we started adding + // a release train, there's no way its compatible with this + // version + if !strings.Contains(eventAPIVersion, ".") { + return false + } + + // if the SDK is pinned to a preview version, the event's API version must match exactly + var currentReleaseTrain = strings.Split(sdkAPIVersion, ".")[1] + if currentReleaseTrain == "preview" { + return sdkAPIVersion == eventAPIVersion + } + + // versions are yyyy-MM-dd.train + var eventReleaseTrain = strings.Split(eventAPIVersion, ".")[1] + return eventReleaseTrain == currentReleaseTrain +} + +func constructEvent(payload []byte, sigHeader string, secret string, cfg webhookConfig) (Event, error) { + e := Event{} + + if err := validatePayload(payload, sigHeader, secret, cfg); err != nil { + return e, err + } + + if err := json.Unmarshal(payload, &e); err != nil { + return e, fmt.Errorf("Failed to parse webhook body json: %s", err.Error()) + } + + if !cfg.IgnoreAPIVersionMismatch && !isCompatibleAPIVersion(APIVersion, e.APIVersion) { + return e, fmt.Errorf("Received event with API version %s, but stripe-go %s expects API version %s. We recommend that you create a WebhookEndpoint with this API version. Otherwise, you can disable this error by using `ConstructEventWithOptions(..., ConstructEventOptions{..., ignoreAPIVersionMismatch: true})` but be wary that objects may be incorrectly deserialized.", e.APIVersion, ClientVersion, APIVersion) + } + + return e, nil + +} + +func parseSignatureHeader(header string) (*signedHeader, error) { + sh := &signedHeader{} + + if header == "" { + return sh, ErrWebhookNotSigned + } + + // Signed header looks like "t=1495999758,v1=ABC,v1=DEF,v0=GHI" + pairs := strings.Split(header, ",") + for _, pair := range pairs { + parts := strings.Split(pair, "=") + if len(parts) != 2 { + return sh, ErrWebhookInvalidHeader + } + + switch parts[0] { + case "t": + timestamp, err := strconv.ParseInt(parts[1], 10, 64) + if err != nil { + return sh, ErrWebhookInvalidHeader + } + sh.timestamp = time.Unix(timestamp, 0) + + case signingVersion: + sig, err := hex.DecodeString(parts[1]) + if err != nil { + continue // Ignore invalid signatures + } + + sh.signatures = append(sh.signatures, sig) + + default: + continue // Ignore unknown parts of the header + } + } + + if len(sh.signatures) == 0 { + return sh, ErrWebhookNoValidSignature + } + + return sh, nil +} + +func validatePayload(payload []byte, sigHeader string, secret string, cfg webhookConfig) error { + + header, err := parseSignatureHeader(sigHeader) + if err != nil { + return err + } + + expiredTimestamp := time.Since(header.timestamp) > cfg.Tolerance + if !cfg.IgnoreTolerance && expiredTimestamp { + return ErrWebhookTooOld + } + + expectedSignature := ComputeSignature(header.timestamp, payload, secret) + // Check all given v1 signatures, multiple signatures will be sent temporarily in the case of a rolled signature secret + for _, sig := range header.signatures { + if hmac.Equal(expectedSignature, sig) { + return nil + } + } + + return ErrWebhookNoValidSignature +} + +// For mocking webhook events +type UnsignedPayload struct { + Payload []byte + Secret string + Timestamp time.Time + Scheme string +} + +type SignedPayload struct { + UnsignedPayload + + Signature []byte + Header string +} + +func GenerateTestSignedPayload(options *UnsignedPayload) *SignedPayload { + signedPayload := &SignedPayload{UnsignedPayload: *options} + + if signedPayload.Timestamp == (time.Time{}) { + signedPayload.Timestamp = time.Now() + } + + if signedPayload.Scheme == "" { + signedPayload.Scheme = "v1" + } + + signedPayload.Signature = ComputeSignature(signedPayload.Timestamp, signedPayload.Payload, signedPayload.Secret) + signedPayload.Header = generateHeader(*signedPayload) + + return signedPayload +} + +func generateHeader(p SignedPayload) string { + return fmt.Sprintf("t=%d,%s=%s", p.Timestamp.Unix(), p.Scheme, hex.EncodeToString(p.Signature)) +} diff --git a/vendor/github.com/xeipuuv/gojsonpointer/LICENSE-APACHE-2.0.txt b/vendor/github.com/xeipuuv/gojsonpointer/LICENSE-APACHE-2.0.txt new file mode 100644 index 00000000..55ede8a4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonpointer/LICENSE-APACHE-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015 xeipuuv + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/xeipuuv/gojsonpointer/README.md b/vendor/github.com/xeipuuv/gojsonpointer/README.md new file mode 100644 index 00000000..a4f5f145 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonpointer/README.md @@ -0,0 +1,41 @@ +# gojsonpointer +An implementation of JSON Pointer - Go language + +## Usage + jsonText := `{ + "name": "Bobby B", + "occupation": { + "title" : "King", + "years" : 15, + "heir" : "Joffrey B" + } + }` + + var jsonDocument map[string]interface{} + json.Unmarshal([]byte(jsonText), &jsonDocument) + + //create a JSON pointer + pointerString := "/occupation/title" + pointer, _ := NewJsonPointer(pointerString) + + //SET a new value for the "title" in the document + pointer.Set(jsonDocument, "Supreme Leader of Westeros") + + //GET the new "title" from the document + title, _, _ := pointer.Get(jsonDocument) + fmt.Println(title) //outputs "Supreme Leader of Westeros" + + //DELETE the "heir" from the document + deletePointer := NewJsonPointer("/occupation/heir") + deletePointer.Delete(jsonDocument) + + b, _ := json.Marshal(jsonDocument) + fmt.Println(string(b)) + //outputs `{"name":"Bobby B","occupation":{"title":"Supreme Leader of Westeros","years":15}}` + + +## References +https://tools.ietf.org/html/rfc6901 + +### Note +The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, the reference token MUST contain either...' is not implemented. diff --git a/vendor/github.com/xeipuuv/gojsonpointer/pointer.go b/vendor/github.com/xeipuuv/gojsonpointer/pointer.go new file mode 100644 index 00000000..798c1f1c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonpointer/pointer.go @@ -0,0 +1,211 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonpointer +// repository-desc An implementation of JSON Pointer - Go language +// +// description Main and unique file. +// +// created 25-02-2013 + +package gojsonpointer + +import ( + "errors" + "fmt" + "reflect" + "strconv" + "strings" +) + +const ( + const_empty_pointer = `` + const_pointer_separator = `/` + + const_invalid_start = `JSON pointer must be empty or start with a "` + const_pointer_separator + `"` +) + +type implStruct struct { + mode string // "SET" or "GET" + + inDocument interface{} + + setInValue interface{} + + getOutNode interface{} + getOutKind reflect.Kind + outError error +} + +type JsonPointer struct { + referenceTokens []string +} + +// NewJsonPointer parses the given string JSON pointer and returns an object +func NewJsonPointer(jsonPointerString string) (p JsonPointer, err error) { + + // Pointer to the root of the document + if len(jsonPointerString) == 0 { + // Keep referenceTokens nil + return + } + if jsonPointerString[0] != '/' { + return p, errors.New(const_invalid_start) + } + + p.referenceTokens = strings.Split(jsonPointerString[1:], const_pointer_separator) + return +} + +// Uses the pointer to retrieve a value from a JSON document +func (p *JsonPointer) Get(document interface{}) (interface{}, reflect.Kind, error) { + + is := &implStruct{mode: "GET", inDocument: document} + p.implementation(is) + return is.getOutNode, is.getOutKind, is.outError + +} + +// Uses the pointer to update a value from a JSON document +func (p *JsonPointer) Set(document interface{}, value interface{}) (interface{}, error) { + + is := &implStruct{mode: "SET", inDocument: document, setInValue: value} + p.implementation(is) + return document, is.outError + +} + +// Uses the pointer to delete a value from a JSON document +func (p *JsonPointer) Delete(document interface{}) (interface{}, error) { + is := &implStruct{mode: "DEL", inDocument: document} + p.implementation(is) + return document, is.outError +} + +// Both Get and Set functions use the same implementation to avoid code duplication +func (p *JsonPointer) implementation(i *implStruct) { + + kind := reflect.Invalid + + // Full document when empty + if len(p.referenceTokens) == 0 { + i.getOutNode = i.inDocument + i.outError = nil + i.getOutKind = kind + i.outError = nil + return + } + + node := i.inDocument + + previousNodes := make([]interface{}, len(p.referenceTokens)) + previousTokens := make([]string, len(p.referenceTokens)) + + for ti, token := range p.referenceTokens { + + isLastToken := ti == len(p.referenceTokens)-1 + previousNodes[ti] = node + previousTokens[ti] = token + + switch v := node.(type) { + + case map[string]interface{}: + decodedToken := decodeReferenceToken(token) + if _, ok := v[decodedToken]; ok { + node = v[decodedToken] + if isLastToken && i.mode == "SET" { + v[decodedToken] = i.setInValue + } else if isLastToken && i.mode == "DEL" { + delete(v, decodedToken) + } + } else if isLastToken && i.mode == "SET" { + v[decodedToken] = i.setInValue + } else { + i.outError = fmt.Errorf("Object has no key '%s'", decodedToken) + i.getOutKind = reflect.Map + i.getOutNode = nil + return + } + + case []interface{}: + tokenIndex, err := strconv.Atoi(token) + if err != nil { + i.outError = fmt.Errorf("Invalid array index '%s'", token) + i.getOutKind = reflect.Slice + i.getOutNode = nil + return + } + if tokenIndex < 0 || tokenIndex >= len(v) { + i.outError = fmt.Errorf("Out of bound array[0,%d] index '%d'", len(v), tokenIndex) + i.getOutKind = reflect.Slice + i.getOutNode = nil + return + } + + node = v[tokenIndex] + if isLastToken && i.mode == "SET" { + v[tokenIndex] = i.setInValue + } else if isLastToken && i.mode == "DEL" { + v[tokenIndex] = v[len(v)-1] + v[len(v)-1] = nil + v = v[:len(v)-1] + previousNodes[ti-1].(map[string]interface{})[previousTokens[ti-1]] = v + } + + default: + i.outError = fmt.Errorf("Invalid token reference '%s'", token) + i.getOutKind = reflect.ValueOf(node).Kind() + i.getOutNode = nil + return + } + + } + + i.getOutNode = node + i.getOutKind = reflect.ValueOf(node).Kind() + i.outError = nil +} + +// Pointer to string representation function +func (p *JsonPointer) String() string { + + if len(p.referenceTokens) == 0 { + return const_empty_pointer + } + + pointerString := const_pointer_separator + strings.Join(p.referenceTokens, const_pointer_separator) + + return pointerString +} + +// Specific JSON pointer encoding here +// ~0 => ~ +// ~1 => / +// ... and vice versa + +func decodeReferenceToken(token string) string { + step1 := strings.Replace(token, `~1`, `/`, -1) + step2 := strings.Replace(step1, `~0`, `~`, -1) + return step2 +} + +func encodeReferenceToken(token string) string { + step1 := strings.Replace(token, `~`, `~0`, -1) + step2 := strings.Replace(step1, `/`, `~1`, -1) + return step2 +} diff --git a/vendor/github.com/xeipuuv/gojsonreference/LICENSE-APACHE-2.0.txt b/vendor/github.com/xeipuuv/gojsonreference/LICENSE-APACHE-2.0.txt new file mode 100644 index 00000000..55ede8a4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonreference/LICENSE-APACHE-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015 xeipuuv + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/xeipuuv/gojsonreference/README.md b/vendor/github.com/xeipuuv/gojsonreference/README.md new file mode 100644 index 00000000..9ab6e1eb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonreference/README.md @@ -0,0 +1,10 @@ +# gojsonreference +An implementation of JSON Reference - Go language + +## Dependencies +https://github.com/xeipuuv/gojsonpointer + +## References +http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 + +http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 diff --git a/vendor/github.com/xeipuuv/gojsonreference/reference.go b/vendor/github.com/xeipuuv/gojsonreference/reference.go new file mode 100644 index 00000000..64572913 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonreference/reference.go @@ -0,0 +1,147 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonreference +// repository-desc An implementation of JSON Reference - Go language +// +// description Main and unique file. +// +// created 26-02-2013 + +package gojsonreference + +import ( + "errors" + "net/url" + "path/filepath" + "runtime" + "strings" + + "github.com/xeipuuv/gojsonpointer" +) + +const ( + const_fragment_char = `#` +) + +func NewJsonReference(jsonReferenceString string) (JsonReference, error) { + + var r JsonReference + err := r.parse(jsonReferenceString) + return r, err + +} + +type JsonReference struct { + referenceUrl *url.URL + referencePointer gojsonpointer.JsonPointer + + HasFullUrl bool + HasUrlPathOnly bool + HasFragmentOnly bool + HasFileScheme bool + HasFullFilePath bool +} + +func (r *JsonReference) GetUrl() *url.URL { + return r.referenceUrl +} + +func (r *JsonReference) GetPointer() *gojsonpointer.JsonPointer { + return &r.referencePointer +} + +func (r *JsonReference) String() string { + + if r.referenceUrl != nil { + return r.referenceUrl.String() + } + + if r.HasFragmentOnly { + return const_fragment_char + r.referencePointer.String() + } + + return r.referencePointer.String() +} + +func (r *JsonReference) IsCanonical() bool { + return (r.HasFileScheme && r.HasFullFilePath) || (!r.HasFileScheme && r.HasFullUrl) +} + +// "Constructor", parses the given string JSON reference +func (r *JsonReference) parse(jsonReferenceString string) (err error) { + + r.referenceUrl, err = url.Parse(jsonReferenceString) + if err != nil { + return + } + refUrl := r.referenceUrl + + if refUrl.Scheme != "" && refUrl.Host != "" { + r.HasFullUrl = true + } else { + if refUrl.Path != "" { + r.HasUrlPathOnly = true + } else if refUrl.RawQuery == "" && refUrl.Fragment != "" { + r.HasFragmentOnly = true + } + } + + r.HasFileScheme = refUrl.Scheme == "file" + if runtime.GOOS == "windows" { + // on Windows, a file URL may have an extra leading slash, and if it + // doesn't then its first component will be treated as the host by the + // Go runtime + if refUrl.Host == "" && strings.HasPrefix(refUrl.Path, "/") { + r.HasFullFilePath = filepath.IsAbs(refUrl.Path[1:]) + } else { + r.HasFullFilePath = filepath.IsAbs(refUrl.Host + refUrl.Path) + } + } else { + r.HasFullFilePath = filepath.IsAbs(refUrl.Path) + } + + // invalid json-pointer error means url has no json-pointer fragment. simply ignore error + r.referencePointer, _ = gojsonpointer.NewJsonPointer(refUrl.Fragment) + + return +} + +// Creates a new reference from a parent and a child +// If the child cannot inherit from the parent, an error is returned +func (r *JsonReference) Inherits(child JsonReference) (*JsonReference, error) { + if child.GetUrl() == nil { + return nil, errors.New("childUrl is nil!") + } + + if r.GetUrl() == nil { + return nil, errors.New("parentUrl is nil!") + } + + // Get a copy of the parent url to make sure we do not modify the original. + // URL reference resolving fails if the fragment of the child is empty, but the parent's is not. + // The fragment of the child must be used, so the fragment of the parent is manually removed. + parentUrl := *r.GetUrl() + parentUrl.Fragment = "" + + ref, err := NewJsonReference(parentUrl.ResolveReference(child.GetUrl()).String()) + if err != nil { + return nil, err + } + return &ref, err +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/.gitignore b/vendor/github.com/xeipuuv/gojsonschema/.gitignore new file mode 100644 index 00000000..68e993ce --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/.gitignore @@ -0,0 +1,3 @@ +*.sw[nop] +*.iml +.vscode/ diff --git a/vendor/github.com/xeipuuv/gojsonschema/.travis.yml b/vendor/github.com/xeipuuv/gojsonschema/.travis.yml new file mode 100644 index 00000000..3289001c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/.travis.yml @@ -0,0 +1,9 @@ +language: go +go: + - "1.11" + - "1.12" + - "1.13" +before_install: + - go get github.com/xeipuuv/gojsonreference + - go get github.com/xeipuuv/gojsonpointer + - go get github.com/stretchr/testify/assert diff --git a/vendor/github.com/xeipuuv/gojsonschema/LICENSE-APACHE-2.0.txt b/vendor/github.com/xeipuuv/gojsonschema/LICENSE-APACHE-2.0.txt new file mode 100644 index 00000000..55ede8a4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/LICENSE-APACHE-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015 xeipuuv + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/xeipuuv/gojsonschema/README.md b/vendor/github.com/xeipuuv/gojsonschema/README.md new file mode 100644 index 00000000..758f26df --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/README.md @@ -0,0 +1,466 @@ +[![GoDoc](https://godoc.org/github.com/xeipuuv/gojsonschema?status.svg)](https://godoc.org/github.com/xeipuuv/gojsonschema) +[![Build Status](https://travis-ci.org/xeipuuv/gojsonschema.svg)](https://travis-ci.org/xeipuuv/gojsonschema) +[![Go Report Card](https://goreportcard.com/badge/github.com/xeipuuv/gojsonschema)](https://goreportcard.com/report/github.com/xeipuuv/gojsonschema) + +# gojsonschema + +## Description + +An implementation of JSON Schema for the Go programming language. Supports draft-04, draft-06 and draft-07. + +References : + +* http://json-schema.org +* http://json-schema.org/latest/json-schema-core.html +* http://json-schema.org/latest/json-schema-validation.html + +## Installation + +``` +go get github.com/xeipuuv/gojsonschema +``` + +Dependencies : +* [github.com/xeipuuv/gojsonpointer](https://github.com/xeipuuv/gojsonpointer) +* [github.com/xeipuuv/gojsonreference](https://github.com/xeipuuv/gojsonreference) +* [github.com/stretchr/testify/assert](https://github.com/stretchr/testify#assert-package) + +## Usage + +### Example + +```go + +package main + +import ( + "fmt" + "github.com/xeipuuv/gojsonschema" +) + +func main() { + + schemaLoader := gojsonschema.NewReferenceLoader("file:///home/me/schema.json") + documentLoader := gojsonschema.NewReferenceLoader("file:///home/me/document.json") + + result, err := gojsonschema.Validate(schemaLoader, documentLoader) + if err != nil { + panic(err.Error()) + } + + if result.Valid() { + fmt.Printf("The document is valid\n") + } else { + fmt.Printf("The document is not valid. see errors :\n") + for _, desc := range result.Errors() { + fmt.Printf("- %s\n", desc) + } + } +} + + +``` + +#### Loaders + +There are various ways to load your JSON data. +In order to load your schemas and documents, +first declare an appropriate loader : + +* Web / HTTP, using a reference : + +```go +loader := gojsonschema.NewReferenceLoader("http://www.some_host.com/schema.json") +``` + +* Local file, using a reference : + +```go +loader := gojsonschema.NewReferenceLoader("file:///home/me/schema.json") +``` + +References use the URI scheme, the prefix (file://) and a full path to the file are required. + +* JSON strings : + +```go +loader := gojsonschema.NewStringLoader(`{"type": "string"}`) +``` + +* Custom Go types : + +```go +m := map[string]interface{}{"type": "string"} +loader := gojsonschema.NewGoLoader(m) +``` + +And + +```go +type Root struct { + Users []User `json:"users"` +} + +type User struct { + Name string `json:"name"` +} + +... + +data := Root{} +data.Users = append(data.Users, User{"John"}) +data.Users = append(data.Users, User{"Sophia"}) +data.Users = append(data.Users, User{"Bill"}) + +loader := gojsonschema.NewGoLoader(data) +``` + +#### Validation + +Once the loaders are set, validation is easy : + +```go +result, err := gojsonschema.Validate(schemaLoader, documentLoader) +``` + +Alternatively, you might want to load a schema only once and process to multiple validations : + +```go +schema, err := gojsonschema.NewSchema(schemaLoader) +... +result1, err := schema.Validate(documentLoader1) +... +result2, err := schema.Validate(documentLoader2) +... +// etc ... +``` + +To check the result : + +```go + if result.Valid() { + fmt.Printf("The document is valid\n") + } else { + fmt.Printf("The document is not valid. see errors :\n") + for _, err := range result.Errors() { + // Err implements the ResultError interface + fmt.Printf("- %s\n", err) + } + } +``` + + +## Loading local schemas + +By default `file` and `http(s)` references to external schemas are loaded automatically via the file system or via http(s). An external schema can also be loaded using a `SchemaLoader`. + +```go + sl := gojsonschema.NewSchemaLoader() + loader1 := gojsonschema.NewStringLoader(`{ "type" : "string" }`) + err := sl.AddSchema("http://some_host.com/string.json", loader1) +``` + +Alternatively if your schema already has an `$id` you can use the `AddSchemas` function +```go + loader2 := gojsonschema.NewStringLoader(`{ + "$id" : "http://some_host.com/maxlength.json", + "maxLength" : 5 + }`) + err = sl.AddSchemas(loader2) +``` + +The main schema should be passed to the `Compile` function. This main schema can then directly reference the added schemas without needing to download them. +```go + loader3 := gojsonschema.NewStringLoader(`{ + "$id" : "http://some_host.com/main.json", + "allOf" : [ + { "$ref" : "http://some_host.com/string.json" }, + { "$ref" : "http://some_host.com/maxlength.json" } + ] + }`) + + schema, err := sl.Compile(loader3) + + documentLoader := gojsonschema.NewStringLoader(`"hello world"`) + + result, err := schema.Validate(documentLoader) +``` + +It's also possible to pass a `ReferenceLoader` to the `Compile` function that references a loaded schema. + +```go +err = sl.AddSchemas(loader3) +schema, err := sl.Compile(gojsonschema.NewReferenceLoader("http://some_host.com/main.json")) +``` + +Schemas added by `AddSchema` and `AddSchemas` are only validated when the entire schema is compiled, unless meta-schema validation is used. + +## Using a specific draft +By default `gojsonschema` will try to detect the draft of a schema by using the `$schema` keyword and parse it in a strict draft-04, draft-06 or draft-07 mode. If `$schema` is missing, or the draft version is not explicitely set, a hybrid mode is used which merges together functionality of all drafts into one mode. + +Autodectection can be turned off with the `AutoDetect` property. Specific draft versions can be specified with the `Draft` property. + +```go +sl := gojsonschema.NewSchemaLoader() +sl.Draft = gojsonschema.Draft7 +sl.AutoDetect = false +``` + +If autodetection is on (default), a draft-07 schema can savely reference draft-04 schemas and vice-versa, as long as `$schema` is specified in all schemas. + +## Meta-schema validation +Schemas that are added using the `AddSchema`, `AddSchemas` and `Compile` can be validated against their meta-schema by setting the `Validate` property. + +The following example will produce an error as `multipleOf` must be a number. If `Validate` is off (default), this error is only returned at the `Compile` step. + +```go +sl := gojsonschema.NewSchemaLoader() +sl.Validate = true +err := sl.AddSchemas(gojsonschema.NewStringLoader(`{ + $id" : "http://some_host.com/invalid.json", + "$schema": "http://json-schema.org/draft-07/schema#", + "multipleOf" : true +}`)) + ``` +``` + ``` + +Errors returned by meta-schema validation are more readable and contain more information, which helps significantly if you are developing a schema. + +Meta-schema validation also works with a custom `$schema`. In case `$schema` is missing, or `AutoDetect` is set to `false`, the meta-schema of the used draft is used. + + +## Working with Errors + +The library handles string error codes which you can customize by creating your own gojsonschema.locale and setting it +```go +gojsonschema.Locale = YourCustomLocale{} +``` + +However, each error contains additional contextual information. + +Newer versions of `gojsonschema` may have new additional errors, so code that uses a custom locale will need to be updated when this happens. + +**err.Type()**: *string* Returns the "type" of error that occurred. Note you can also type check. See below + +Note: An error of RequiredType has an err.Type() return value of "required" + + "required": RequiredError + "invalid_type": InvalidTypeError + "number_any_of": NumberAnyOfError + "number_one_of": NumberOneOfError + "number_all_of": NumberAllOfError + "number_not": NumberNotError + "missing_dependency": MissingDependencyError + "internal": InternalError + "const": ConstEror + "enum": EnumError + "array_no_additional_items": ArrayNoAdditionalItemsError + "array_min_items": ArrayMinItemsError + "array_max_items": ArrayMaxItemsError + "unique": ItemsMustBeUniqueError + "contains" : ArrayContainsError + "array_min_properties": ArrayMinPropertiesError + "array_max_properties": ArrayMaxPropertiesError + "additional_property_not_allowed": AdditionalPropertyNotAllowedError + "invalid_property_pattern": InvalidPropertyPatternError + "invalid_property_name": InvalidPropertyNameError + "string_gte": StringLengthGTEError + "string_lte": StringLengthLTEError + "pattern": DoesNotMatchPatternError + "multiple_of": MultipleOfError + "number_gte": NumberGTEError + "number_gt": NumberGTError + "number_lte": NumberLTEError + "number_lt": NumberLTError + "condition_then" : ConditionThenError + "condition_else" : ConditionElseError + +**err.Value()**: *interface{}* Returns the value given + +**err.Context()**: *gojsonschema.JsonContext* Returns the context. This has a String() method that will print something like this: (root).firstName + +**err.Field()**: *string* Returns the fieldname in the format firstName, or for embedded properties, person.firstName. This returns the same as the String() method on *err.Context()* but removes the (root). prefix. + +**err.Description()**: *string* The error description. This is based on the locale you are using. See the beginning of this section for overwriting the locale with a custom implementation. + +**err.DescriptionFormat()**: *string* The error description format. This is relevant if you are adding custom validation errors afterwards to the result. + +**err.Details()**: *gojsonschema.ErrorDetails* Returns a map[string]interface{} of additional error details specific to the error. For example, GTE errors will have a "min" value, LTE will have a "max" value. See errors.go for a full description of all the error details. Every error always contains a "field" key that holds the value of *err.Field()* + +Note in most cases, the err.Details() will be used to generate replacement strings in your locales, and not used directly. These strings follow the text/template format i.e. +``` +{{.field}} must be greater than or equal to {{.min}} +``` + +The library allows you to specify custom template functions, should you require more complex error message handling. +```go +gojsonschema.ErrorTemplateFuncs = map[string]interface{}{ + "allcaps": func(s string) string { + return strings.ToUpper(s) + }, +} +``` + +Given the above definition, you can use the custom function `"allcaps"` in your localization templates: +``` +{{allcaps .field}} must be greater than or equal to {{.min}} +``` + +The above error message would then be rendered with the `field` value in capital letters. For example: +``` +"PASSWORD must be greater than or equal to 8" +``` + +Learn more about what types of template functions you can use in `ErrorTemplateFuncs` by referring to Go's [text/template FuncMap](https://golang.org/pkg/text/template/#FuncMap) type. + +## Formats +JSON Schema allows for optional "format" property to validate instances against well-known formats. gojsonschema ships with all of the formats defined in the spec that you can use like this: + +````json +{"type": "string", "format": "email"} +```` + +Not all formats defined in draft-07 are available. Implemented formats are: + +* `date` +* `time` +* `date-time` +* `hostname`. Subdomains that start with a number are also supported, but this means that it doesn't strictly follow [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5) and has the implication that ipv4 addresses are also recognized as valid hostnames. +* `email`. Go's email parser deviates slightly from [RFC5322](https://tools.ietf.org/html/rfc5322). Includes unicode support. +* `idn-email`. Same caveat as `email`. +* `ipv4` +* `ipv6` +* `uri`. Includes unicode support. +* `uri-reference`. Includes unicode support. +* `iri` +* `iri-reference` +* `uri-template` +* `uuid` +* `regex`. Go uses the [RE2](https://github.com/google/re2/wiki/Syntax) engine and is not [ECMA262](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) compatible. +* `json-pointer` +* `relative-json-pointer` + +`email`, `uri` and `uri-reference` use the same validation code as their unicode counterparts `idn-email`, `iri` and `iri-reference`. If you rely on unicode support you should use the specific +unicode enabled formats for the sake of interoperability as other implementations might not support unicode in the regular formats. + +The validation code for `uri`, `idn-email` and their relatives use mostly standard library code. + +For repetitive or more complex formats, you can create custom format checkers and add them to gojsonschema like this: + +```go +// Define the format checker +type RoleFormatChecker struct {} + +// Ensure it meets the gojsonschema.FormatChecker interface +func (f RoleFormatChecker) IsFormat(input interface{}) bool { + + asString, ok := input.(string) + if ok == false { + return false + } + + return strings.HasPrefix("ROLE_", asString) +} + +// Add it to the library +gojsonschema.FormatCheckers.Add("role", RoleFormatChecker{}) +```` + +Now to use in your json schema: +````json +{"type": "string", "format": "role"} +```` + +Another example would be to check if the provided integer matches an id on database: + +JSON schema: +```json +{"type": "integer", "format": "ValidUserId"} +``` + +```go +// Define the format checker +type ValidUserIdFormatChecker struct {} + +// Ensure it meets the gojsonschema.FormatChecker interface +func (f ValidUserIdFormatChecker) IsFormat(input interface{}) bool { + + asFloat64, ok := input.(float64) // Numbers are always float64 here + if ok == false { + return false + } + + // XXX + // do the magic on the database looking for the int(asFloat64) + + return true +} + +// Add it to the library +gojsonschema.FormatCheckers.Add("ValidUserId", ValidUserIdFormatChecker{}) +```` + +Formats can also be removed, for example if you want to override one of the formats that is defined by default. + +```go +gojsonschema.FormatCheckers.Remove("hostname") +``` + + +## Additional custom validation +After the validation has run and you have the results, you may add additional +errors using `Result.AddError`. This is useful to maintain the same format within the resultset instead +of having to add special exceptions for your own errors. Below is an example. + +```go +type AnswerInvalidError struct { + gojsonschema.ResultErrorFields +} + +func newAnswerInvalidError(context *gojsonschema.JsonContext, value interface{}, details gojsonschema.ErrorDetails) *AnswerInvalidError { + err := AnswerInvalidError{} + err.SetContext(context) + err.SetType("custom_invalid_error") + // it is important to use SetDescriptionFormat() as this is used to call SetDescription() after it has been parsed + // using the description of err will be overridden by this. + err.SetDescriptionFormat("Answer to the Ultimate Question of Life, the Universe, and Everything is {{.answer}}") + err.SetValue(value) + err.SetDetails(details) + + return &err +} + +func main() { + // ... + schema, err := gojsonschema.NewSchema(schemaLoader) + result, err := gojsonschema.Validate(schemaLoader, documentLoader) + + if true { // some validation + jsonContext := gojsonschema.NewJsonContext("question", nil) + errDetail := gojsonschema.ErrorDetails{ + "answer": 42, + } + result.AddError( + newAnswerInvalidError( + gojsonschema.NewJsonContext("answer", jsonContext), + 52, + errDetail, + ), + errDetail, + ) + } + + return result, err + +} +``` + +This is especially useful if you want to add validation beyond what the +json schema drafts can provide such business specific logic. + +## Uses + +gojsonschema uses the following test suite : + +https://github.com/json-schema/JSON-Schema-Test-Suite diff --git a/vendor/github.com/xeipuuv/gojsonschema/draft.go b/vendor/github.com/xeipuuv/gojsonschema/draft.go new file mode 100644 index 00000000..61298e7a --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/draft.go @@ -0,0 +1,125 @@ +// Copyright 2018 johandorland ( https://github.com/johandorland ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package gojsonschema + +import ( + "errors" + "math" + "reflect" + + "github.com/xeipuuv/gojsonreference" +) + +// Draft is a JSON-schema draft version +type Draft int + +// Supported Draft versions +const ( + Draft4 Draft = 4 + Draft6 Draft = 6 + Draft7 Draft = 7 + Hybrid Draft = math.MaxInt32 +) + +type draftConfig struct { + Version Draft + MetaSchemaURL string + MetaSchema string +} +type draftConfigs []draftConfig + +var drafts draftConfigs + +func init() { + drafts = []draftConfig{ + { + Version: Draft4, + MetaSchemaURL: "http://json-schema.org/draft-04/schema", + MetaSchema: `{"id":"http://json-schema.org/draft-04/schema#","$schema":"http://json-schema.org/draft-04/schema#","description":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"positiveInteger":{"type":"integer","minimum":0},"positiveIntegerDefault0":{"allOf":[{"$ref":"#/definitions/positiveInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"minItems":1,"uniqueItems":true}},"type":"object","properties":{"id":{"type":"string"},"$schema":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":{},"multipleOf":{"type":"number","minimum":0,"exclusiveMinimum":true},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"boolean","default":false},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"boolean","default":false},"maxLength":{"$ref":"#/definitions/positiveInteger"},"minLength":{"$ref":"#/definitions/positiveIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"anyOf":[{"type":"boolean"},{"$ref":"#"}],"default":{}},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":{}},"maxItems":{"$ref":"#/definitions/positiveInteger"},"minItems":{"$ref":"#/definitions/positiveIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"maxProperties":{"$ref":"#/definitions/positiveInteger"},"minProperties":{"$ref":"#/definitions/positiveIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"anyOf":[{"type":"boolean"},{"$ref":"#"}],"default":{}},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"enum":{"type":"array","minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"dependencies":{"exclusiveMaximum":["maximum"],"exclusiveMinimum":["minimum"]},"default":{}}`, + }, + { + Version: Draft6, + MetaSchemaURL: "http://json-schema.org/draft-06/schema", + MetaSchema: `{"$schema":"http://json-schema.org/draft-06/schema#","$id":"http://json-schema.org/draft-06/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"title":{"type":"string"},"description":{"type":"string"},"default":{},"examples":{"type":"array","items":{}},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":{}},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":{},"enum":{"type":"array","minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":{}}`, + }, + { + Version: Draft7, + MetaSchemaURL: "http://json-schema.org/draft-07/schema", + MetaSchema: `{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}`, + }, + } +} + +func (dc draftConfigs) GetMetaSchema(url string) string { + for _, config := range dc { + if config.MetaSchemaURL == url { + return config.MetaSchema + } + } + return "" +} +func (dc draftConfigs) GetDraftVersion(url string) *Draft { + for _, config := range dc { + if config.MetaSchemaURL == url { + return &config.Version + } + } + return nil +} +func (dc draftConfigs) GetSchemaURL(draft Draft) string { + for _, config := range dc { + if config.Version == draft { + return config.MetaSchemaURL + } + } + return "" +} + +func parseSchemaURL(documentNode interface{}) (string, *Draft, error) { + + if isKind(documentNode, reflect.Bool) { + return "", nil, nil + } + + if !isKind(documentNode, reflect.Map) { + return "", nil, errors.New("schema is invalid") + } + + m := documentNode.(map[string]interface{}) + + if existsMapKey(m, KEY_SCHEMA) { + if !isKind(m[KEY_SCHEMA], reflect.String) { + return "", nil, errors.New(formatErrorDescription( + Locale.MustBeOfType(), + ErrorDetails{ + "key": KEY_SCHEMA, + "type": TYPE_STRING, + }, + )) + } + + schemaReference, err := gojsonreference.NewJsonReference(m[KEY_SCHEMA].(string)) + + if err != nil { + return "", nil, err + } + + schema := schemaReference.String() + + return schema, drafts.GetDraftVersion(schema), nil + } + + return "", nil, nil +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/errors.go b/vendor/github.com/xeipuuv/gojsonschema/errors.go new file mode 100644 index 00000000..e4e9814f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/errors.go @@ -0,0 +1,364 @@ +package gojsonschema + +import ( + "bytes" + "sync" + "text/template" +) + +var errorTemplates = errorTemplate{template.New("errors-new"), sync.RWMutex{}} + +// template.Template is not thread-safe for writing, so some locking is done +// sync.RWMutex is used for efficiently locking when new templates are created +type errorTemplate struct { + *template.Template + sync.RWMutex +} + +type ( + + // FalseError. ErrorDetails: - + FalseError struct { + ResultErrorFields + } + + // RequiredError indicates that a required field is missing + // ErrorDetails: property string + RequiredError struct { + ResultErrorFields + } + + // InvalidTypeError indicates that a field has the incorrect type + // ErrorDetails: expected, given + InvalidTypeError struct { + ResultErrorFields + } + + // NumberAnyOfError is produced in case of a failing "anyOf" validation + // ErrorDetails: - + NumberAnyOfError struct { + ResultErrorFields + } + + // NumberOneOfError is produced in case of a failing "oneOf" validation + // ErrorDetails: - + NumberOneOfError struct { + ResultErrorFields + } + + // NumberAllOfError is produced in case of a failing "allOf" validation + // ErrorDetails: - + NumberAllOfError struct { + ResultErrorFields + } + + // NumberNotError is produced if a "not" validation failed + // ErrorDetails: - + NumberNotError struct { + ResultErrorFields + } + + // MissingDependencyError is produced in case of a "missing dependency" problem + // ErrorDetails: dependency + MissingDependencyError struct { + ResultErrorFields + } + + // InternalError indicates an internal error + // ErrorDetails: error + InternalError struct { + ResultErrorFields + } + + // ConstError indicates a const error + // ErrorDetails: allowed + ConstError struct { + ResultErrorFields + } + + // EnumError indicates an enum error + // ErrorDetails: allowed + EnumError struct { + ResultErrorFields + } + + // ArrayNoAdditionalItemsError is produced if additional items were found, but not allowed + // ErrorDetails: - + ArrayNoAdditionalItemsError struct { + ResultErrorFields + } + + // ArrayMinItemsError is produced if an array contains less items than the allowed minimum + // ErrorDetails: min + ArrayMinItemsError struct { + ResultErrorFields + } + + // ArrayMaxItemsError is produced if an array contains more items than the allowed maximum + // ErrorDetails: max + ArrayMaxItemsError struct { + ResultErrorFields + } + + // ItemsMustBeUniqueError is produced if an array requires unique items, but contains non-unique items + // ErrorDetails: type, i, j + ItemsMustBeUniqueError struct { + ResultErrorFields + } + + // ArrayContainsError is produced if an array contains invalid items + // ErrorDetails: + ArrayContainsError struct { + ResultErrorFields + } + + // ArrayMinPropertiesError is produced if an object contains less properties than the allowed minimum + // ErrorDetails: min + ArrayMinPropertiesError struct { + ResultErrorFields + } + + // ArrayMaxPropertiesError is produced if an object contains more properties than the allowed maximum + // ErrorDetails: max + ArrayMaxPropertiesError struct { + ResultErrorFields + } + + // AdditionalPropertyNotAllowedError is produced if an object has additional properties, but not allowed + // ErrorDetails: property + AdditionalPropertyNotAllowedError struct { + ResultErrorFields + } + + // InvalidPropertyPatternError is produced if an pattern was found + // ErrorDetails: property, pattern + InvalidPropertyPatternError struct { + ResultErrorFields + } + + // InvalidPropertyNameError is produced if an invalid-named property was found + // ErrorDetails: property + InvalidPropertyNameError struct { + ResultErrorFields + } + + // StringLengthGTEError is produced if a string is shorter than the minimum required length + // ErrorDetails: min + StringLengthGTEError struct { + ResultErrorFields + } + + // StringLengthLTEError is produced if a string is longer than the maximum allowed length + // ErrorDetails: max + StringLengthLTEError struct { + ResultErrorFields + } + + // DoesNotMatchPatternError is produced if a string does not match the defined pattern + // ErrorDetails: pattern + DoesNotMatchPatternError struct { + ResultErrorFields + } + + // DoesNotMatchFormatError is produced if a string does not match the defined format + // ErrorDetails: format + DoesNotMatchFormatError struct { + ResultErrorFields + } + + // MultipleOfError is produced if a number is not a multiple of the defined multipleOf + // ErrorDetails: multiple + MultipleOfError struct { + ResultErrorFields + } + + // NumberGTEError is produced if a number is lower than the allowed minimum + // ErrorDetails: min + NumberGTEError struct { + ResultErrorFields + } + + // NumberGTError is produced if a number is lower than, or equal to the specified minimum, and exclusiveMinimum is set + // ErrorDetails: min + NumberGTError struct { + ResultErrorFields + } + + // NumberLTEError is produced if a number is higher than the allowed maximum + // ErrorDetails: max + NumberLTEError struct { + ResultErrorFields + } + + // NumberLTError is produced if a number is higher than, or equal to the specified maximum, and exclusiveMaximum is set + // ErrorDetails: max + NumberLTError struct { + ResultErrorFields + } + + // ConditionThenError is produced if a condition's "then" validation is invalid + // ErrorDetails: - + ConditionThenError struct { + ResultErrorFields + } + + // ConditionElseError is produced if a condition's "else" condition is invalid + // ErrorDetails: - + ConditionElseError struct { + ResultErrorFields + } +) + +// newError takes a ResultError type and sets the type, context, description, details, value, and field +func newError(err ResultError, context *JsonContext, value interface{}, locale locale, details ErrorDetails) { + var t string + var d string + switch err.(type) { + case *FalseError: + t = "false" + d = locale.False() + case *RequiredError: + t = "required" + d = locale.Required() + case *InvalidTypeError: + t = "invalid_type" + d = locale.InvalidType() + case *NumberAnyOfError: + t = "number_any_of" + d = locale.NumberAnyOf() + case *NumberOneOfError: + t = "number_one_of" + d = locale.NumberOneOf() + case *NumberAllOfError: + t = "number_all_of" + d = locale.NumberAllOf() + case *NumberNotError: + t = "number_not" + d = locale.NumberNot() + case *MissingDependencyError: + t = "missing_dependency" + d = locale.MissingDependency() + case *InternalError: + t = "internal" + d = locale.Internal() + case *ConstError: + t = "const" + d = locale.Const() + case *EnumError: + t = "enum" + d = locale.Enum() + case *ArrayNoAdditionalItemsError: + t = "array_no_additional_items" + d = locale.ArrayNoAdditionalItems() + case *ArrayMinItemsError: + t = "array_min_items" + d = locale.ArrayMinItems() + case *ArrayMaxItemsError: + t = "array_max_items" + d = locale.ArrayMaxItems() + case *ItemsMustBeUniqueError: + t = "unique" + d = locale.Unique() + case *ArrayContainsError: + t = "contains" + d = locale.ArrayContains() + case *ArrayMinPropertiesError: + t = "array_min_properties" + d = locale.ArrayMinProperties() + case *ArrayMaxPropertiesError: + t = "array_max_properties" + d = locale.ArrayMaxProperties() + case *AdditionalPropertyNotAllowedError: + t = "additional_property_not_allowed" + d = locale.AdditionalPropertyNotAllowed() + case *InvalidPropertyPatternError: + t = "invalid_property_pattern" + d = locale.InvalidPropertyPattern() + case *InvalidPropertyNameError: + t = "invalid_property_name" + d = locale.InvalidPropertyName() + case *StringLengthGTEError: + t = "string_gte" + d = locale.StringGTE() + case *StringLengthLTEError: + t = "string_lte" + d = locale.StringLTE() + case *DoesNotMatchPatternError: + t = "pattern" + d = locale.DoesNotMatchPattern() + case *DoesNotMatchFormatError: + t = "format" + d = locale.DoesNotMatchFormat() + case *MultipleOfError: + t = "multiple_of" + d = locale.MultipleOf() + case *NumberGTEError: + t = "number_gte" + d = locale.NumberGTE() + case *NumberGTError: + t = "number_gt" + d = locale.NumberGT() + case *NumberLTEError: + t = "number_lte" + d = locale.NumberLTE() + case *NumberLTError: + t = "number_lt" + d = locale.NumberLT() + case *ConditionThenError: + t = "condition_then" + d = locale.ConditionThen() + case *ConditionElseError: + t = "condition_else" + d = locale.ConditionElse() + } + + err.SetType(t) + err.SetContext(context) + err.SetValue(value) + err.SetDetails(details) + err.SetDescriptionFormat(d) + details["field"] = err.Field() + + if _, exists := details["context"]; !exists && context != nil { + details["context"] = context.String() + } + + err.SetDescription(formatErrorDescription(err.DescriptionFormat(), details)) +} + +// formatErrorDescription takes a string in the default text/template +// format and converts it to a string with replacements. The fields come +// from the ErrorDetails struct and vary for each type of error. +func formatErrorDescription(s string, details ErrorDetails) string { + + var tpl *template.Template + var descrAsBuffer bytes.Buffer + var err error + + errorTemplates.RLock() + tpl = errorTemplates.Lookup(s) + errorTemplates.RUnlock() + + if tpl == nil { + errorTemplates.Lock() + tpl = errorTemplates.New(s) + + if ErrorTemplateFuncs != nil { + tpl.Funcs(ErrorTemplateFuncs) + } + + tpl, err = tpl.Parse(s) + errorTemplates.Unlock() + + if err != nil { + return err.Error() + } + } + + err = tpl.Execute(&descrAsBuffer, details) + if err != nil { + return err.Error() + } + + return descrAsBuffer.String() +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/format_checkers.go b/vendor/github.com/xeipuuv/gojsonschema/format_checkers.go new file mode 100644 index 00000000..873ffc7d --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/format_checkers.go @@ -0,0 +1,368 @@ +package gojsonschema + +import ( + "net" + "net/mail" + "net/url" + "regexp" + "strings" + "sync" + "time" +) + +type ( + // FormatChecker is the interface all formatters added to FormatCheckerChain must implement + FormatChecker interface { + // IsFormat checks if input has the correct format and type + IsFormat(input interface{}) bool + } + + // FormatCheckerChain holds the formatters + FormatCheckerChain struct { + formatters map[string]FormatChecker + } + + // EmailFormatChecker verifies email address formats + EmailFormatChecker struct{} + + // IPV4FormatChecker verifies IP addresses in the IPv4 format + IPV4FormatChecker struct{} + + // IPV6FormatChecker verifies IP addresses in the IPv6 format + IPV6FormatChecker struct{} + + // DateTimeFormatChecker verifies date/time formats per RFC3339 5.6 + // + // Valid formats: + // Partial Time: HH:MM:SS + // Full Date: YYYY-MM-DD + // Full Time: HH:MM:SSZ-07:00 + // Date Time: YYYY-MM-DDTHH:MM:SSZ-0700 + // + // Where + // YYYY = 4DIGIT year + // MM = 2DIGIT month ; 01-12 + // DD = 2DIGIT day-month ; 01-28, 01-29, 01-30, 01-31 based on month/year + // HH = 2DIGIT hour ; 00-23 + // MM = 2DIGIT ; 00-59 + // SS = 2DIGIT ; 00-58, 00-60 based on leap second rules + // T = Literal + // Z = Literal + // + // Note: Nanoseconds are also suported in all formats + // + // http://tools.ietf.org/html/rfc3339#section-5.6 + DateTimeFormatChecker struct{} + + // DateFormatChecker verifies date formats + // + // Valid format: + // Full Date: YYYY-MM-DD + // + // Where + // YYYY = 4DIGIT year + // MM = 2DIGIT month ; 01-12 + // DD = 2DIGIT day-month ; 01-28, 01-29, 01-30, 01-31 based on month/year + DateFormatChecker struct{} + + // TimeFormatChecker verifies time formats + // + // Valid formats: + // Partial Time: HH:MM:SS + // Full Time: HH:MM:SSZ-07:00 + // + // Where + // HH = 2DIGIT hour ; 00-23 + // MM = 2DIGIT ; 00-59 + // SS = 2DIGIT ; 00-58, 00-60 based on leap second rules + // T = Literal + // Z = Literal + TimeFormatChecker struct{} + + // URIFormatChecker validates a URI with a valid Scheme per RFC3986 + URIFormatChecker struct{} + + // URIReferenceFormatChecker validates a URI or relative-reference per RFC3986 + URIReferenceFormatChecker struct{} + + // URITemplateFormatChecker validates a URI template per RFC6570 + URITemplateFormatChecker struct{} + + // HostnameFormatChecker validates a hostname is in the correct format + HostnameFormatChecker struct{} + + // UUIDFormatChecker validates a UUID is in the correct format + UUIDFormatChecker struct{} + + // RegexFormatChecker validates a regex is in the correct format + RegexFormatChecker struct{} + + // JSONPointerFormatChecker validates a JSON Pointer per RFC6901 + JSONPointerFormatChecker struct{} + + // RelativeJSONPointerFormatChecker validates a relative JSON Pointer is in the correct format + RelativeJSONPointerFormatChecker struct{} +) + +var ( + // FormatCheckers holds the valid formatters, and is a public variable + // so library users can add custom formatters + FormatCheckers = FormatCheckerChain{ + formatters: map[string]FormatChecker{ + "date": DateFormatChecker{}, + "time": TimeFormatChecker{}, + "date-time": DateTimeFormatChecker{}, + "hostname": HostnameFormatChecker{}, + "email": EmailFormatChecker{}, + "idn-email": EmailFormatChecker{}, + "ipv4": IPV4FormatChecker{}, + "ipv6": IPV6FormatChecker{}, + "uri": URIFormatChecker{}, + "uri-reference": URIReferenceFormatChecker{}, + "iri": URIFormatChecker{}, + "iri-reference": URIReferenceFormatChecker{}, + "uri-template": URITemplateFormatChecker{}, + "uuid": UUIDFormatChecker{}, + "regex": RegexFormatChecker{}, + "json-pointer": JSONPointerFormatChecker{}, + "relative-json-pointer": RelativeJSONPointerFormatChecker{}, + }, + } + + // Regex credit: https://www.socketloop.com/tutorials/golang-validate-hostname + rxHostname = regexp.MustCompile(`^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$`) + + // Use a regex to make sure curly brackets are balanced properly after validating it as a AURI + rxURITemplate = regexp.MustCompile("^([^{]*({[^}]*})?)*$") + + rxUUID = regexp.MustCompile("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$") + + rxJSONPointer = regexp.MustCompile("^(?:/(?:[^~/]|~0|~1)*)*$") + + rxRelJSONPointer = regexp.MustCompile("^(?:0|[1-9][0-9]*)(?:#|(?:/(?:[^~/]|~0|~1)*)*)$") + + lock = new(sync.RWMutex) +) + +// Add adds a FormatChecker to the FormatCheckerChain +// The name used will be the value used for the format key in your json schema +func (c *FormatCheckerChain) Add(name string, f FormatChecker) *FormatCheckerChain { + lock.Lock() + c.formatters[name] = f + lock.Unlock() + + return c +} + +// Remove deletes a FormatChecker from the FormatCheckerChain (if it exists) +func (c *FormatCheckerChain) Remove(name string) *FormatCheckerChain { + lock.Lock() + delete(c.formatters, name) + lock.Unlock() + + return c +} + +// Has checks to see if the FormatCheckerChain holds a FormatChecker with the given name +func (c *FormatCheckerChain) Has(name string) bool { + lock.RLock() + _, ok := c.formatters[name] + lock.RUnlock() + + return ok +} + +// IsFormat will check an input against a FormatChecker with the given name +// to see if it is the correct format +func (c *FormatCheckerChain) IsFormat(name string, input interface{}) bool { + lock.RLock() + f, ok := c.formatters[name] + lock.RUnlock() + + // If a format is unrecognized it should always pass validation + if !ok { + return true + } + + return f.IsFormat(input) +} + +// IsFormat checks if input is a correctly formatted e-mail address +func (f EmailFormatChecker) IsFormat(input interface{}) bool { + asString, ok := input.(string) + if !ok { + return false + } + + _, err := mail.ParseAddress(asString) + return err == nil +} + +// IsFormat checks if input is a correctly formatted IPv4-address +func (f IPV4FormatChecker) IsFormat(input interface{}) bool { + asString, ok := input.(string) + if !ok { + return false + } + + // Credit: https://github.com/asaskevich/govalidator + ip := net.ParseIP(asString) + return ip != nil && strings.Contains(asString, ".") +} + +// IsFormat checks if input is a correctly formatted IPv6=address +func (f IPV6FormatChecker) IsFormat(input interface{}) bool { + asString, ok := input.(string) + if !ok { + return false + } + + // Credit: https://github.com/asaskevich/govalidator + ip := net.ParseIP(asString) + return ip != nil && strings.Contains(asString, ":") +} + +// IsFormat checks if input is a correctly formatted date/time per RFC3339 5.6 +func (f DateTimeFormatChecker) IsFormat(input interface{}) bool { + asString, ok := input.(string) + if !ok { + return false + } + + formats := []string{ + "15:04:05", + "15:04:05Z07:00", + "2006-01-02", + time.RFC3339, + time.RFC3339Nano, + } + + for _, format := range formats { + if _, err := time.Parse(format, asString); err == nil { + return true + } + } + + return false +} + +// IsFormat checks if input is a correctly formatted date (YYYY-MM-DD) +func (f DateFormatChecker) IsFormat(input interface{}) bool { + asString, ok := input.(string) + if !ok { + return false + } + _, err := time.Parse("2006-01-02", asString) + return err == nil +} + +// IsFormat checks if input correctly formatted time (HH:MM:SS or HH:MM:SSZ-07:00) +func (f TimeFormatChecker) IsFormat(input interface{}) bool { + asString, ok := input.(string) + if !ok { + return false + } + + if _, err := time.Parse("15:04:05Z07:00", asString); err == nil { + return true + } + + _, err := time.Parse("15:04:05", asString) + return err == nil +} + +// IsFormat checks if input is correctly formatted URI with a valid Scheme per RFC3986 +func (f URIFormatChecker) IsFormat(input interface{}) bool { + asString, ok := input.(string) + if !ok { + return false + } + + u, err := url.Parse(asString) + + if err != nil || u.Scheme == "" { + return false + } + + return !strings.Contains(asString, `\`) +} + +// IsFormat checks if input is a correctly formatted URI or relative-reference per RFC3986 +func (f URIReferenceFormatChecker) IsFormat(input interface{}) bool { + asString, ok := input.(string) + if !ok { + return false + } + + _, err := url.Parse(asString) + return err == nil && !strings.Contains(asString, `\`) +} + +// IsFormat checks if input is a correctly formatted URI template per RFC6570 +func (f URITemplateFormatChecker) IsFormat(input interface{}) bool { + asString, ok := input.(string) + if !ok { + return false + } + + u, err := url.Parse(asString) + if err != nil || strings.Contains(asString, `\`) { + return false + } + + return rxURITemplate.MatchString(u.Path) +} + +// IsFormat checks if input is a correctly formatted hostname +func (f HostnameFormatChecker) IsFormat(input interface{}) bool { + asString, ok := input.(string) + if !ok { + return false + } + + return rxHostname.MatchString(asString) && len(asString) < 256 +} + +// IsFormat checks if input is a correctly formatted UUID +func (f UUIDFormatChecker) IsFormat(input interface{}) bool { + asString, ok := input.(string) + if !ok { + return false + } + + return rxUUID.MatchString(asString) +} + +// IsFormat checks if input is a correctly formatted regular expression +func (f RegexFormatChecker) IsFormat(input interface{}) bool { + asString, ok := input.(string) + if !ok { + return false + } + + if asString == "" { + return true + } + _, err := regexp.Compile(asString) + return err == nil +} + +// IsFormat checks if input is a correctly formatted JSON Pointer per RFC6901 +func (f JSONPointerFormatChecker) IsFormat(input interface{}) bool { + asString, ok := input.(string) + if !ok { + return false + } + + return rxJSONPointer.MatchString(asString) +} + +// IsFormat checks if input is a correctly formatted relative JSON Pointer +func (f RelativeJSONPointerFormatChecker) IsFormat(input interface{}) bool { + asString, ok := input.(string) + if !ok { + return false + } + + return rxRelJSONPointer.MatchString(asString) +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/glide.yaml b/vendor/github.com/xeipuuv/gojsonschema/glide.yaml new file mode 100644 index 00000000..ab6fb867 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/glide.yaml @@ -0,0 +1,13 @@ +package: github.com/xeipuuv/gojsonschema +license: Apache 2.0 +import: +- package: github.com/xeipuuv/gojsonschema + +- package: github.com/xeipuuv/gojsonpointer + +- package: github.com/xeipuuv/gojsonreference + +testImport: +- package: github.com/stretchr/testify + subpackages: + - assert diff --git a/vendor/github.com/xeipuuv/gojsonschema/internalLog.go b/vendor/github.com/xeipuuv/gojsonschema/internalLog.go new file mode 100644 index 00000000..4ef7a8d0 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/internalLog.go @@ -0,0 +1,37 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Very simple log wrapper. +// Used for debugging/testing purposes. +// +// created 01-01-2015 + +package gojsonschema + +import ( + "log" +) + +const internalLogEnabled = false + +func internalLog(format string, v ...interface{}) { + log.Printf(format, v...) +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/jsonContext.go b/vendor/github.com/xeipuuv/gojsonschema/jsonContext.go new file mode 100644 index 00000000..0e979707 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/jsonContext.go @@ -0,0 +1,73 @@ +// Copyright 2013 MongoDB, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author tolsen +// author-github https://github.com/tolsen +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Implements a persistent (immutable w/ shared structure) singly-linked list of strings for the purpose of storing a json context +// +// created 04-09-2013 + +package gojsonschema + +import "bytes" + +// JsonContext implements a persistent linked-list of strings +type JsonContext struct { + head string + tail *JsonContext +} + +// NewJsonContext creates a new JsonContext +func NewJsonContext(head string, tail *JsonContext) *JsonContext { + return &JsonContext{head, tail} +} + +// String displays the context in reverse. +// This plays well with the data structure's persistent nature with +// Cons and a json document's tree structure. +func (c *JsonContext) String(del ...string) string { + byteArr := make([]byte, 0, c.stringLen()) + buf := bytes.NewBuffer(byteArr) + c.writeStringToBuffer(buf, del) + + return buf.String() +} + +func (c *JsonContext) stringLen() int { + length := 0 + if c.tail != nil { + length = c.tail.stringLen() + 1 // add 1 for "." + } + + length += len(c.head) + return length +} + +func (c *JsonContext) writeStringToBuffer(buf *bytes.Buffer, del []string) { + if c.tail != nil { + c.tail.writeStringToBuffer(buf, del) + + if len(del) > 0 { + buf.WriteString(del[0]) + } else { + buf.WriteString(".") + } + } + + buf.WriteString(c.head) +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go b/vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go new file mode 100644 index 00000000..5d88af26 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go @@ -0,0 +1,386 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Different strategies to load JSON files. +// Includes References (file and HTTP), JSON strings and Go types. +// +// created 01-02-2015 + +package gojsonschema + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "io/ioutil" + "net/http" + "net/url" + "os" + "path/filepath" + "runtime" + "strings" + + "github.com/xeipuuv/gojsonreference" +) + +var osFS = osFileSystem(os.Open) + +// JSONLoader defines the JSON loader interface +type JSONLoader interface { + JsonSource() interface{} + LoadJSON() (interface{}, error) + JsonReference() (gojsonreference.JsonReference, error) + LoaderFactory() JSONLoaderFactory +} + +// JSONLoaderFactory defines the JSON loader factory interface +type JSONLoaderFactory interface { + // New creates a new JSON loader for the given source + New(source string) JSONLoader +} + +// DefaultJSONLoaderFactory is the default JSON loader factory +type DefaultJSONLoaderFactory struct { +} + +// FileSystemJSONLoaderFactory is a JSON loader factory that uses http.FileSystem +type FileSystemJSONLoaderFactory struct { + fs http.FileSystem +} + +// New creates a new JSON loader for the given source +func (d DefaultJSONLoaderFactory) New(source string) JSONLoader { + return &jsonReferenceLoader{ + fs: osFS, + source: source, + } +} + +// New creates a new JSON loader for the given source +func (f FileSystemJSONLoaderFactory) New(source string) JSONLoader { + return &jsonReferenceLoader{ + fs: f.fs, + source: source, + } +} + +// osFileSystem is a functional wrapper for os.Open that implements http.FileSystem. +type osFileSystem func(string) (*os.File, error) + +// Opens a file with the given name +func (o osFileSystem) Open(name string) (http.File, error) { + return o(name) +} + +// JSON Reference loader +// references are used to load JSONs from files and HTTP + +type jsonReferenceLoader struct { + fs http.FileSystem + source string +} + +func (l *jsonReferenceLoader) JsonSource() interface{} { + return l.source +} + +func (l *jsonReferenceLoader) JsonReference() (gojsonreference.JsonReference, error) { + return gojsonreference.NewJsonReference(l.JsonSource().(string)) +} + +func (l *jsonReferenceLoader) LoaderFactory() JSONLoaderFactory { + return &FileSystemJSONLoaderFactory{ + fs: l.fs, + } +} + +// NewReferenceLoader returns a JSON reference loader using the given source and the local OS file system. +func NewReferenceLoader(source string) JSONLoader { + return &jsonReferenceLoader{ + fs: osFS, + source: source, + } +} + +// NewReferenceLoaderFileSystem returns a JSON reference loader using the given source and file system. +func NewReferenceLoaderFileSystem(source string, fs http.FileSystem) JSONLoader { + return &jsonReferenceLoader{ + fs: fs, + source: source, + } +} + +func (l *jsonReferenceLoader) LoadJSON() (interface{}, error) { + + var err error + + reference, err := gojsonreference.NewJsonReference(l.JsonSource().(string)) + if err != nil { + return nil, err + } + + refToURL := reference + refToURL.GetUrl().Fragment = "" + + var document interface{} + + if reference.HasFileScheme { + + filename := strings.TrimPrefix(refToURL.String(), "file://") + filename, err = url.QueryUnescape(filename) + + if err != nil { + return nil, err + } + + if runtime.GOOS == "windows" { + // on Windows, a file URL may have an extra leading slash, use slashes + // instead of backslashes, and have spaces escaped + filename = strings.TrimPrefix(filename, "/") + filename = filepath.FromSlash(filename) + } + + document, err = l.loadFromFile(filename) + if err != nil { + return nil, err + } + + } else { + + document, err = l.loadFromHTTP(refToURL.String()) + if err != nil { + return nil, err + } + + } + + return document, nil + +} + +func (l *jsonReferenceLoader) loadFromHTTP(address string) (interface{}, error) { + + // returned cached versions for metaschemas for drafts 4, 6 and 7 + // for performance and allow for easier offline use + if metaSchema := drafts.GetMetaSchema(address); metaSchema != "" { + return decodeJSONUsingNumber(strings.NewReader(metaSchema)) + } + + resp, err := http.Get(address) + if err != nil { + return nil, err + } + + // must return HTTP Status 200 OK + if resp.StatusCode != http.StatusOK { + return nil, errors.New(formatErrorDescription(Locale.HttpBadStatus(), ErrorDetails{"status": resp.Status})) + } + + bodyBuff, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + return decodeJSONUsingNumber(bytes.NewReader(bodyBuff)) +} + +func (l *jsonReferenceLoader) loadFromFile(path string) (interface{}, error) { + f, err := l.fs.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + + bodyBuff, err := ioutil.ReadAll(f) + if err != nil { + return nil, err + } + + return decodeJSONUsingNumber(bytes.NewReader(bodyBuff)) + +} + +// JSON string loader + +type jsonStringLoader struct { + source string +} + +func (l *jsonStringLoader) JsonSource() interface{} { + return l.source +} + +func (l *jsonStringLoader) JsonReference() (gojsonreference.JsonReference, error) { + return gojsonreference.NewJsonReference("#") +} + +func (l *jsonStringLoader) LoaderFactory() JSONLoaderFactory { + return &DefaultJSONLoaderFactory{} +} + +// NewStringLoader creates a new JSONLoader, taking a string as source +func NewStringLoader(source string) JSONLoader { + return &jsonStringLoader{source: source} +} + +func (l *jsonStringLoader) LoadJSON() (interface{}, error) { + + return decodeJSONUsingNumber(strings.NewReader(l.JsonSource().(string))) + +} + +// JSON bytes loader + +type jsonBytesLoader struct { + source []byte +} + +func (l *jsonBytesLoader) JsonSource() interface{} { + return l.source +} + +func (l *jsonBytesLoader) JsonReference() (gojsonreference.JsonReference, error) { + return gojsonreference.NewJsonReference("#") +} + +func (l *jsonBytesLoader) LoaderFactory() JSONLoaderFactory { + return &DefaultJSONLoaderFactory{} +} + +// NewBytesLoader creates a new JSONLoader, taking a `[]byte` as source +func NewBytesLoader(source []byte) JSONLoader { + return &jsonBytesLoader{source: source} +} + +func (l *jsonBytesLoader) LoadJSON() (interface{}, error) { + return decodeJSONUsingNumber(bytes.NewReader(l.JsonSource().([]byte))) +} + +// JSON Go (types) loader +// used to load JSONs from the code as maps, interface{}, structs ... + +type jsonGoLoader struct { + source interface{} +} + +func (l *jsonGoLoader) JsonSource() interface{} { + return l.source +} + +func (l *jsonGoLoader) JsonReference() (gojsonreference.JsonReference, error) { + return gojsonreference.NewJsonReference("#") +} + +func (l *jsonGoLoader) LoaderFactory() JSONLoaderFactory { + return &DefaultJSONLoaderFactory{} +} + +// NewGoLoader creates a new JSONLoader from a given Go struct +func NewGoLoader(source interface{}) JSONLoader { + return &jsonGoLoader{source: source} +} + +func (l *jsonGoLoader) LoadJSON() (interface{}, error) { + + // convert it to a compliant JSON first to avoid types "mismatches" + + jsonBytes, err := json.Marshal(l.JsonSource()) + if err != nil { + return nil, err + } + + return decodeJSONUsingNumber(bytes.NewReader(jsonBytes)) + +} + +type jsonIOLoader struct { + buf *bytes.Buffer +} + +// NewReaderLoader creates a new JSON loader using the provided io.Reader +func NewReaderLoader(source io.Reader) (JSONLoader, io.Reader) { + buf := &bytes.Buffer{} + return &jsonIOLoader{buf: buf}, io.TeeReader(source, buf) +} + +// NewWriterLoader creates a new JSON loader using the provided io.Writer +func NewWriterLoader(source io.Writer) (JSONLoader, io.Writer) { + buf := &bytes.Buffer{} + return &jsonIOLoader{buf: buf}, io.MultiWriter(source, buf) +} + +func (l *jsonIOLoader) JsonSource() interface{} { + return l.buf.String() +} + +func (l *jsonIOLoader) LoadJSON() (interface{}, error) { + return decodeJSONUsingNumber(l.buf) +} + +func (l *jsonIOLoader) JsonReference() (gojsonreference.JsonReference, error) { + return gojsonreference.NewJsonReference("#") +} + +func (l *jsonIOLoader) LoaderFactory() JSONLoaderFactory { + return &DefaultJSONLoaderFactory{} +} + +// JSON raw loader +// In case the JSON is already marshalled to interface{} use this loader +// This is used for testing as otherwise there is no guarantee the JSON is marshalled +// "properly" by using https://golang.org/pkg/encoding/json/#Decoder.UseNumber +type jsonRawLoader struct { + source interface{} +} + +// NewRawLoader creates a new JSON raw loader for the given source +func NewRawLoader(source interface{}) JSONLoader { + return &jsonRawLoader{source: source} +} +func (l *jsonRawLoader) JsonSource() interface{} { + return l.source +} +func (l *jsonRawLoader) LoadJSON() (interface{}, error) { + return l.source, nil +} +func (l *jsonRawLoader) JsonReference() (gojsonreference.JsonReference, error) { + return gojsonreference.NewJsonReference("#") +} +func (l *jsonRawLoader) LoaderFactory() JSONLoaderFactory { + return &DefaultJSONLoaderFactory{} +} + +func decodeJSONUsingNumber(r io.Reader) (interface{}, error) { + + var document interface{} + + decoder := json.NewDecoder(r) + decoder.UseNumber() + + err := decoder.Decode(&document) + if err != nil { + return nil, err + } + + return document, nil + +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/locales.go b/vendor/github.com/xeipuuv/gojsonschema/locales.go new file mode 100644 index 00000000..a416225c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/locales.go @@ -0,0 +1,472 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Contains const string and messages. +// +// created 01-01-2015 + +package gojsonschema + +type ( + // locale is an interface for defining custom error strings + locale interface { + + // False returns a format-string for "false" schema validation errors + False() string + + // Required returns a format-string for "required" schema validation errors + Required() string + + // InvalidType returns a format-string for "invalid type" schema validation errors + InvalidType() string + + // NumberAnyOf returns a format-string for "anyOf" schema validation errors + NumberAnyOf() string + + // NumberOneOf returns a format-string for "oneOf" schema validation errors + NumberOneOf() string + + // NumberAllOf returns a format-string for "allOf" schema validation errors + NumberAllOf() string + + // NumberNot returns a format-string to format a NumberNotError + NumberNot() string + + // MissingDependency returns a format-string for "missing dependency" schema validation errors + MissingDependency() string + + // Internal returns a format-string for internal errors + Internal() string + + // Const returns a format-string to format a ConstError + Const() string + + // Enum returns a format-string to format an EnumError + Enum() string + + // ArrayNotEnoughItems returns a format-string to format an error for arrays having not enough items to match positional list of schema + ArrayNotEnoughItems() string + + // ArrayNoAdditionalItems returns a format-string to format an ArrayNoAdditionalItemsError + ArrayNoAdditionalItems() string + + // ArrayMinItems returns a format-string to format an ArrayMinItemsError + ArrayMinItems() string + + // ArrayMaxItems returns a format-string to format an ArrayMaxItemsError + ArrayMaxItems() string + + // Unique returns a format-string to format an ItemsMustBeUniqueError + Unique() string + + // ArrayContains returns a format-string to format an ArrayContainsError + ArrayContains() string + + // ArrayMinProperties returns a format-string to format an ArrayMinPropertiesError + ArrayMinProperties() string + + // ArrayMaxProperties returns a format-string to format an ArrayMaxPropertiesError + ArrayMaxProperties() string + + // AdditionalPropertyNotAllowed returns a format-string to format an AdditionalPropertyNotAllowedError + AdditionalPropertyNotAllowed() string + + // InvalidPropertyPattern returns a format-string to format an InvalidPropertyPatternError + InvalidPropertyPattern() string + + // InvalidPropertyName returns a format-string to format an InvalidPropertyNameError + InvalidPropertyName() string + + // StringGTE returns a format-string to format an StringLengthGTEError + StringGTE() string + + // StringLTE returns a format-string to format an StringLengthLTEError + StringLTE() string + + // DoesNotMatchPattern returns a format-string to format an DoesNotMatchPatternError + DoesNotMatchPattern() string + + // DoesNotMatchFormat returns a format-string to format an DoesNotMatchFormatError + DoesNotMatchFormat() string + + // MultipleOf returns a format-string to format an MultipleOfError + MultipleOf() string + + // NumberGTE returns a format-string to format an NumberGTEError + NumberGTE() string + + // NumberGT returns a format-string to format an NumberGTError + NumberGT() string + + // NumberLTE returns a format-string to format an NumberLTEError + NumberLTE() string + + // NumberLT returns a format-string to format an NumberLTError + NumberLT() string + + // Schema validations + + // RegexPattern returns a format-string to format a regex-pattern error + RegexPattern() string + + // GreaterThanZero returns a format-string to format an error where a number must be greater than zero + GreaterThanZero() string + + // MustBeOfA returns a format-string to format an error where a value is of the wrong type + MustBeOfA() string + + // MustBeOfAn returns a format-string to format an error where a value is of the wrong type + MustBeOfAn() string + + // CannotBeUsedWithout returns a format-string to format a "cannot be used without" error + CannotBeUsedWithout() string + + // CannotBeGT returns a format-string to format an error where a value are greater than allowed + CannotBeGT() string + + // MustBeOfType returns a format-string to format an error where a value does not match the required type + MustBeOfType() string + + // MustBeValidRegex returns a format-string to format an error where a regex is invalid + MustBeValidRegex() string + + // MustBeValidFormat returns a format-string to format an error where a value does not match the expected format + MustBeValidFormat() string + + // MustBeGTEZero returns a format-string to format an error where a value must be greater or equal than 0 + MustBeGTEZero() string + + // KeyCannotBeGreaterThan returns a format-string to format an error where a key is greater than the maximum allowed + KeyCannotBeGreaterThan() string + + // KeyItemsMustBeOfType returns a format-string to format an error where a key is of the wrong type + KeyItemsMustBeOfType() string + + // KeyItemsMustBeUnique returns a format-string to format an error where keys are not unique + KeyItemsMustBeUnique() string + + // ReferenceMustBeCanonical returns a format-string to format a "reference must be canonical" error + ReferenceMustBeCanonical() string + + // NotAValidType returns a format-string to format an invalid type error + NotAValidType() string + + // Duplicated returns a format-string to format an error where types are duplicated + Duplicated() string + + // HttpBadStatus returns a format-string for errors when loading a schema using HTTP + HttpBadStatus() string + + // ParseError returns a format-string for JSON parsing errors + ParseError() string + + // ConditionThen returns a format-string for ConditionThenError errors + ConditionThen() string + + // ConditionElse returns a format-string for ConditionElseError errors + ConditionElse() string + + // ErrorFormat returns a format string for errors + ErrorFormat() string + } + + // DefaultLocale is the default locale for this package + DefaultLocale struct{} +) + +// False returns a format-string for "false" schema validation errors +func (l DefaultLocale) False() string { + return "False always fails validation" +} + +// Required returns a format-string for "required" schema validation errors +func (l DefaultLocale) Required() string { + return `{{.property}} is required` +} + +// InvalidType returns a format-string for "invalid type" schema validation errors +func (l DefaultLocale) InvalidType() string { + return `Invalid type. Expected: {{.expected}}, given: {{.given}}` +} + +// NumberAnyOf returns a format-string for "anyOf" schema validation errors +func (l DefaultLocale) NumberAnyOf() string { + return `Must validate at least one schema (anyOf)` +} + +// NumberOneOf returns a format-string for "oneOf" schema validation errors +func (l DefaultLocale) NumberOneOf() string { + return `Must validate one and only one schema (oneOf)` +} + +// NumberAllOf returns a format-string for "allOf" schema validation errors +func (l DefaultLocale) NumberAllOf() string { + return `Must validate all the schemas (allOf)` +} + +// NumberNot returns a format-string to format a NumberNotError +func (l DefaultLocale) NumberNot() string { + return `Must not validate the schema (not)` +} + +// MissingDependency returns a format-string for "missing dependency" schema validation errors +func (l DefaultLocale) MissingDependency() string { + return `Has a dependency on {{.dependency}}` +} + +// Internal returns a format-string for internal errors +func (l DefaultLocale) Internal() string { + return `Internal Error {{.error}}` +} + +// Const returns a format-string to format a ConstError +func (l DefaultLocale) Const() string { + return `{{.field}} does not match: {{.allowed}}` +} + +// Enum returns a format-string to format an EnumError +func (l DefaultLocale) Enum() string { + return `{{.field}} must be one of the following: {{.allowed}}` +} + +// ArrayNoAdditionalItems returns a format-string to format an ArrayNoAdditionalItemsError +func (l DefaultLocale) ArrayNoAdditionalItems() string { + return `No additional items allowed on array` +} + +// ArrayNotEnoughItems returns a format-string to format an error for arrays having not enough items to match positional list of schema +func (l DefaultLocale) ArrayNotEnoughItems() string { + return `Not enough items on array to match positional list of schema` +} + +// ArrayMinItems returns a format-string to format an ArrayMinItemsError +func (l DefaultLocale) ArrayMinItems() string { + return `Array must have at least {{.min}} items` +} + +// ArrayMaxItems returns a format-string to format an ArrayMaxItemsError +func (l DefaultLocale) ArrayMaxItems() string { + return `Array must have at most {{.max}} items` +} + +// Unique returns a format-string to format an ItemsMustBeUniqueError +func (l DefaultLocale) Unique() string { + return `{{.type}} items[{{.i}},{{.j}}] must be unique` +} + +// ArrayContains returns a format-string to format an ArrayContainsError +func (l DefaultLocale) ArrayContains() string { + return `At least one of the items must match` +} + +// ArrayMinProperties returns a format-string to format an ArrayMinPropertiesError +func (l DefaultLocale) ArrayMinProperties() string { + return `Must have at least {{.min}} properties` +} + +// ArrayMaxProperties returns a format-string to format an ArrayMaxPropertiesError +func (l DefaultLocale) ArrayMaxProperties() string { + return `Must have at most {{.max}} properties` +} + +// AdditionalPropertyNotAllowed returns a format-string to format an AdditionalPropertyNotAllowedError +func (l DefaultLocale) AdditionalPropertyNotAllowed() string { + return `Additional property {{.property}} is not allowed` +} + +// InvalidPropertyPattern returns a format-string to format an InvalidPropertyPatternError +func (l DefaultLocale) InvalidPropertyPattern() string { + return `Property "{{.property}}" does not match pattern {{.pattern}}` +} + +// InvalidPropertyName returns a format-string to format an InvalidPropertyNameError +func (l DefaultLocale) InvalidPropertyName() string { + return `Property name of "{{.property}}" does not match` +} + +// StringGTE returns a format-string to format an StringLengthGTEError +func (l DefaultLocale) StringGTE() string { + return `String length must be greater than or equal to {{.min}}` +} + +// StringLTE returns a format-string to format an StringLengthLTEError +func (l DefaultLocale) StringLTE() string { + return `String length must be less than or equal to {{.max}}` +} + +// DoesNotMatchPattern returns a format-string to format an DoesNotMatchPatternError +func (l DefaultLocale) DoesNotMatchPattern() string { + return `Does not match pattern '{{.pattern}}'` +} + +// DoesNotMatchFormat returns a format-string to format an DoesNotMatchFormatError +func (l DefaultLocale) DoesNotMatchFormat() string { + return `Does not match format '{{.format}}'` +} + +// MultipleOf returns a format-string to format an MultipleOfError +func (l DefaultLocale) MultipleOf() string { + return `Must be a multiple of {{.multiple}}` +} + +// NumberGTE returns the format string to format a NumberGTEError +func (l DefaultLocale) NumberGTE() string { + return `Must be greater than or equal to {{.min}}` +} + +// NumberGT returns the format string to format a NumberGTError +func (l DefaultLocale) NumberGT() string { + return `Must be greater than {{.min}}` +} + +// NumberLTE returns the format string to format a NumberLTEError +func (l DefaultLocale) NumberLTE() string { + return `Must be less than or equal to {{.max}}` +} + +// NumberLT returns the format string to format a NumberLTError +func (l DefaultLocale) NumberLT() string { + return `Must be less than {{.max}}` +} + +// Schema validators + +// RegexPattern returns a format-string to format a regex-pattern error +func (l DefaultLocale) RegexPattern() string { + return `Invalid regex pattern '{{.pattern}}'` +} + +// GreaterThanZero returns a format-string to format an error where a number must be greater than zero +func (l DefaultLocale) GreaterThanZero() string { + return `{{.number}} must be strictly greater than 0` +} + +// MustBeOfA returns a format-string to format an error where a value is of the wrong type +func (l DefaultLocale) MustBeOfA() string { + return `{{.x}} must be of a {{.y}}` +} + +// MustBeOfAn returns a format-string to format an error where a value is of the wrong type +func (l DefaultLocale) MustBeOfAn() string { + return `{{.x}} must be of an {{.y}}` +} + +// CannotBeUsedWithout returns a format-string to format a "cannot be used without" error +func (l DefaultLocale) CannotBeUsedWithout() string { + return `{{.x}} cannot be used without {{.y}}` +} + +// CannotBeGT returns a format-string to format an error where a value are greater than allowed +func (l DefaultLocale) CannotBeGT() string { + return `{{.x}} cannot be greater than {{.y}}` +} + +// MustBeOfType returns a format-string to format an error where a value does not match the required type +func (l DefaultLocale) MustBeOfType() string { + return `{{.key}} must be of type {{.type}}` +} + +// MustBeValidRegex returns a format-string to format an error where a regex is invalid +func (l DefaultLocale) MustBeValidRegex() string { + return `{{.key}} must be a valid regex` +} + +// MustBeValidFormat returns a format-string to format an error where a value does not match the expected format +func (l DefaultLocale) MustBeValidFormat() string { + return `{{.key}} must be a valid format {{.given}}` +} + +// MustBeGTEZero returns a format-string to format an error where a value must be greater or equal than 0 +func (l DefaultLocale) MustBeGTEZero() string { + return `{{.key}} must be greater than or equal to 0` +} + +// KeyCannotBeGreaterThan returns a format-string to format an error where a value is greater than the maximum allowed +func (l DefaultLocale) KeyCannotBeGreaterThan() string { + return `{{.key}} cannot be greater than {{.y}}` +} + +// KeyItemsMustBeOfType returns a format-string to format an error where a key is of the wrong type +func (l DefaultLocale) KeyItemsMustBeOfType() string { + return `{{.key}} items must be {{.type}}` +} + +// KeyItemsMustBeUnique returns a format-string to format an error where keys are not unique +func (l DefaultLocale) KeyItemsMustBeUnique() string { + return `{{.key}} items must be unique` +} + +// ReferenceMustBeCanonical returns a format-string to format a "reference must be canonical" error +func (l DefaultLocale) ReferenceMustBeCanonical() string { + return `Reference {{.reference}} must be canonical` +} + +// NotAValidType returns a format-string to format an invalid type error +func (l DefaultLocale) NotAValidType() string { + return `has a primitive type that is NOT VALID -- given: {{.given}} Expected valid values are:{{.expected}}` +} + +// Duplicated returns a format-string to format an error where types are duplicated +func (l DefaultLocale) Duplicated() string { + return `{{.type}} type is duplicated` +} + +// HttpBadStatus returns a format-string for errors when loading a schema using HTTP +func (l DefaultLocale) HttpBadStatus() string { + return `Could not read schema from HTTP, response status is {{.status}}` +} + +// ErrorFormat returns a format string for errors +// Replacement options: field, description, context, value +func (l DefaultLocale) ErrorFormat() string { + return `{{.field}}: {{.description}}` +} + +// ParseError returns a format-string for JSON parsing errors +func (l DefaultLocale) ParseError() string { + return `Expected: {{.expected}}, given: Invalid JSON` +} + +// ConditionThen returns a format-string for ConditionThenError errors +// If/Else +func (l DefaultLocale) ConditionThen() string { + return `Must validate "then" as "if" was valid` +} + +// ConditionElse returns a format-string for ConditionElseError errors +func (l DefaultLocale) ConditionElse() string { + return `Must validate "else" as "if" was not valid` +} + +// constants +const ( + STRING_NUMBER = "number" + STRING_ARRAY_OF_STRINGS = "array of strings" + STRING_ARRAY_OF_SCHEMAS = "array of schemas" + STRING_SCHEMA = "valid schema" + STRING_SCHEMA_OR_ARRAY_OF_STRINGS = "schema or array of strings" + STRING_PROPERTIES = "properties" + STRING_DEPENDENCY = "dependency" + STRING_PROPERTY = "property" + STRING_UNDEFINED = "undefined" + STRING_CONTEXT_ROOT = "(root)" + STRING_ROOT_SCHEMA_PROPERTY = "(root)" +) diff --git a/vendor/github.com/xeipuuv/gojsonschema/result.go b/vendor/github.com/xeipuuv/gojsonschema/result.go new file mode 100644 index 00000000..0a017914 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/result.go @@ -0,0 +1,220 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Result and ResultError implementations. +// +// created 01-01-2015 + +package gojsonschema + +import ( + "fmt" + "strings" +) + +type ( + // ErrorDetails is a map of details specific to each error. + // While the values will vary, every error will contain a "field" value + ErrorDetails map[string]interface{} + + // ResultError is the interface that library errors must implement + ResultError interface { + // Field returns the field name without the root context + // i.e. firstName or person.firstName instead of (root).firstName or (root).person.firstName + Field() string + // SetType sets the error-type + SetType(string) + // Type returns the error-type + Type() string + // SetContext sets the JSON-context for the error + SetContext(*JsonContext) + // Context returns the JSON-context of the error + Context() *JsonContext + // SetDescription sets a description for the error + SetDescription(string) + // Description returns the description of the error + Description() string + // SetDescriptionFormat sets the format for the description in the default text/template format + SetDescriptionFormat(string) + // DescriptionFormat returns the format for the description in the default text/template format + DescriptionFormat() string + // SetValue sets the value related to the error + SetValue(interface{}) + // Value returns the value related to the error + Value() interface{} + // SetDetails sets the details specific to the error + SetDetails(ErrorDetails) + // Details returns details about the error + Details() ErrorDetails + // String returns a string representation of the error + String() string + } + + // ResultErrorFields holds the fields for each ResultError implementation. + // ResultErrorFields implements the ResultError interface, so custom errors + // can be defined by just embedding this type + ResultErrorFields struct { + errorType string // A string with the type of error (i.e. invalid_type) + context *JsonContext // Tree like notation of the part that failed the validation. ex (root).a.b ... + description string // A human readable error message + descriptionFormat string // A format for human readable error message + value interface{} // Value given by the JSON file that is the source of the error + details ErrorDetails + } + + // Result holds the result of a validation + Result struct { + errors []ResultError + // Scores how well the validation matched. Useful in generating + // better error messages for anyOf and oneOf. + score int + } +) + +// Field returns the field name without the root context +// i.e. firstName or person.firstName instead of (root).firstName or (root).person.firstName +func (v *ResultErrorFields) Field() string { + return strings.TrimPrefix(v.context.String(), STRING_ROOT_SCHEMA_PROPERTY+".") +} + +// SetType sets the error-type +func (v *ResultErrorFields) SetType(errorType string) { + v.errorType = errorType +} + +// Type returns the error-type +func (v *ResultErrorFields) Type() string { + return v.errorType +} + +// SetContext sets the JSON-context for the error +func (v *ResultErrorFields) SetContext(context *JsonContext) { + v.context = context +} + +// Context returns the JSON-context of the error +func (v *ResultErrorFields) Context() *JsonContext { + return v.context +} + +// SetDescription sets a description for the error +func (v *ResultErrorFields) SetDescription(description string) { + v.description = description +} + +// Description returns the description of the error +func (v *ResultErrorFields) Description() string { + return v.description +} + +// SetDescriptionFormat sets the format for the description in the default text/template format +func (v *ResultErrorFields) SetDescriptionFormat(descriptionFormat string) { + v.descriptionFormat = descriptionFormat +} + +// DescriptionFormat returns the format for the description in the default text/template format +func (v *ResultErrorFields) DescriptionFormat() string { + return v.descriptionFormat +} + +// SetValue sets the value related to the error +func (v *ResultErrorFields) SetValue(value interface{}) { + v.value = value +} + +// Value returns the value related to the error +func (v *ResultErrorFields) Value() interface{} { + return v.value +} + +// SetDetails sets the details specific to the error +func (v *ResultErrorFields) SetDetails(details ErrorDetails) { + v.details = details +} + +// Details returns details about the error +func (v *ResultErrorFields) Details() ErrorDetails { + return v.details +} + +// String returns a string representation of the error +func (v ResultErrorFields) String() string { + // as a fallback, the value is displayed go style + valueString := fmt.Sprintf("%v", v.value) + + // marshal the go value value to json + if v.value == nil { + valueString = TYPE_NULL + } else { + if vs, err := marshalToJSONString(v.value); err == nil { + if vs == nil { + valueString = TYPE_NULL + } else { + valueString = *vs + } + } + } + + return formatErrorDescription(Locale.ErrorFormat(), ErrorDetails{ + "context": v.context.String(), + "description": v.description, + "value": valueString, + "field": v.Field(), + }) +} + +// Valid indicates if no errors were found +func (v *Result) Valid() bool { + return len(v.errors) == 0 +} + +// Errors returns the errors that were found +func (v *Result) Errors() []ResultError { + return v.errors +} + +// AddError appends a fully filled error to the error set +// SetDescription() will be called with the result of the parsed err.DescriptionFormat() +func (v *Result) AddError(err ResultError, details ErrorDetails) { + if _, exists := details["context"]; !exists && err.Context() != nil { + details["context"] = err.Context().String() + } + + err.SetDescription(formatErrorDescription(err.DescriptionFormat(), details)) + + v.errors = append(v.errors, err) +} + +func (v *Result) addInternalError(err ResultError, context *JsonContext, value interface{}, details ErrorDetails) { + newError(err, context, value, Locale, details) + v.errors = append(v.errors, err) + v.score -= 2 // results in a net -1 when added to the +1 we get at the end of the validation function +} + +// Used to copy errors from a sub-schema to the main one +func (v *Result) mergeErrors(otherResult *Result) { + v.errors = append(v.errors, otherResult.Errors()...) + v.score += otherResult.score +} + +func (v *Result) incrementScore() { + v.score++ +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/schema.go b/vendor/github.com/xeipuuv/gojsonschema/schema.go new file mode 100644 index 00000000..9e93cd79 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/schema.go @@ -0,0 +1,1087 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Defines Schema, the main entry to every subSchema. +// Contains the parsing logic and error checking. +// +// created 26-02-2013 + +package gojsonschema + +import ( + "errors" + "math/big" + "reflect" + "regexp" + "text/template" + + "github.com/xeipuuv/gojsonreference" +) + +var ( + // Locale is the default locale to use + // Library users can overwrite with their own implementation + Locale locale = DefaultLocale{} + + // ErrorTemplateFuncs allows you to define custom template funcs for use in localization. + ErrorTemplateFuncs template.FuncMap +) + +// NewSchema instances a schema using the given JSONLoader +func NewSchema(l JSONLoader) (*Schema, error) { + return NewSchemaLoader().Compile(l) +} + +// Schema holds a schema +type Schema struct { + documentReference gojsonreference.JsonReference + rootSchema *subSchema + pool *schemaPool + referencePool *schemaReferencePool +} + +func (d *Schema) parse(document interface{}, draft Draft) error { + d.rootSchema = &subSchema{property: STRING_ROOT_SCHEMA_PROPERTY, draft: &draft} + return d.parseSchema(document, d.rootSchema) +} + +// SetRootSchemaName sets the root-schema name +func (d *Schema) SetRootSchemaName(name string) { + d.rootSchema.property = name +} + +// Parses a subSchema +// +// Pretty long function ( sorry :) )... but pretty straight forward, repetitive and boring +// Not much magic involved here, most of the job is to validate the key names and their values, +// then the values are copied into subSchema struct +// +func (d *Schema) parseSchema(documentNode interface{}, currentSchema *subSchema) error { + + if currentSchema.draft == nil { + if currentSchema.parent == nil { + return errors.New("Draft not set") + } + currentSchema.draft = currentSchema.parent.draft + } + + // As of draft 6 "true" is equivalent to an empty schema "{}" and false equals "{"not":{}}" + if *currentSchema.draft >= Draft6 && isKind(documentNode, reflect.Bool) { + b := documentNode.(bool) + currentSchema.pass = &b + return nil + } + + if !isKind(documentNode, reflect.Map) { + return errors.New(formatErrorDescription( + Locale.ParseError(), + ErrorDetails{ + "expected": STRING_SCHEMA, + }, + )) + } + + m := documentNode.(map[string]interface{}) + + if currentSchema.parent == nil { + currentSchema.ref = &d.documentReference + currentSchema.id = &d.documentReference + } + + if currentSchema.id == nil && currentSchema.parent != nil { + currentSchema.id = currentSchema.parent.id + } + + // In draft 6 the id keyword was renamed to $id + // Hybrid mode uses the old id by default + var keyID string + + switch *currentSchema.draft { + case Draft4: + keyID = KEY_ID + case Hybrid: + keyID = KEY_ID_NEW + if existsMapKey(m, KEY_ID) { + keyID = KEY_ID + } + default: + keyID = KEY_ID_NEW + } + if existsMapKey(m, keyID) && !isKind(m[keyID], reflect.String) { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_STRING, + "given": keyID, + }, + )) + } + if k, ok := m[keyID].(string); ok { + jsonReference, err := gojsonreference.NewJsonReference(k) + if err != nil { + return err + } + if currentSchema == d.rootSchema { + currentSchema.id = &jsonReference + } else { + ref, err := currentSchema.parent.id.Inherits(jsonReference) + if err != nil { + return err + } + currentSchema.id = ref + } + } + + // definitions + if existsMapKey(m, KEY_DEFINITIONS) { + if isKind(m[KEY_DEFINITIONS], reflect.Map, reflect.Bool) { + for _, dv := range m[KEY_DEFINITIONS].(map[string]interface{}) { + if isKind(dv, reflect.Map, reflect.Bool) { + + newSchema := &subSchema{property: KEY_DEFINITIONS, parent: currentSchema} + + err := d.parseSchema(dv, newSchema) + + if err != nil { + return err + } + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": STRING_ARRAY_OF_SCHEMAS, + "given": KEY_DEFINITIONS, + }, + )) + } + } + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": STRING_ARRAY_OF_SCHEMAS, + "given": KEY_DEFINITIONS, + }, + )) + } + + } + + // title + if existsMapKey(m, KEY_TITLE) && !isKind(m[KEY_TITLE], reflect.String) { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_STRING, + "given": KEY_TITLE, + }, + )) + } + if k, ok := m[KEY_TITLE].(string); ok { + currentSchema.title = &k + } + + // description + if existsMapKey(m, KEY_DESCRIPTION) && !isKind(m[KEY_DESCRIPTION], reflect.String) { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_STRING, + "given": KEY_DESCRIPTION, + }, + )) + } + if k, ok := m[KEY_DESCRIPTION].(string); ok { + currentSchema.description = &k + } + + // $ref + if existsMapKey(m, KEY_REF) && !isKind(m[KEY_REF], reflect.String) { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_STRING, + "given": KEY_REF, + }, + )) + } + + if k, ok := m[KEY_REF].(string); ok { + + jsonReference, err := gojsonreference.NewJsonReference(k) + if err != nil { + return err + } + + currentSchema.ref = &jsonReference + + if sch, ok := d.referencePool.Get(currentSchema.ref.String()); ok { + currentSchema.refSchema = sch + } else { + err := d.parseReference(documentNode, currentSchema) + + if err != nil { + return err + } + + return nil + } + } + + // type + if existsMapKey(m, KEY_TYPE) { + if isKind(m[KEY_TYPE], reflect.String) { + if k, ok := m[KEY_TYPE].(string); ok { + err := currentSchema.types.Add(k) + if err != nil { + return err + } + } + } else { + if isKind(m[KEY_TYPE], reflect.Slice) { + arrayOfTypes := m[KEY_TYPE].([]interface{}) + for _, typeInArray := range arrayOfTypes { + if reflect.ValueOf(typeInArray).Kind() != reflect.String { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_STRING + "/" + STRING_ARRAY_OF_STRINGS, + "given": KEY_TYPE, + }, + )) + } + if err := currentSchema.types.Add(typeInArray.(string)); err != nil { + return err + } + } + + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_STRING + "/" + STRING_ARRAY_OF_STRINGS, + "given": KEY_TYPE, + }, + )) + } + } + } + + // properties + if existsMapKey(m, KEY_PROPERTIES) { + err := d.parseProperties(m[KEY_PROPERTIES], currentSchema) + if err != nil { + return err + } + } + + // additionalProperties + if existsMapKey(m, KEY_ADDITIONAL_PROPERTIES) { + if isKind(m[KEY_ADDITIONAL_PROPERTIES], reflect.Bool) { + currentSchema.additionalProperties = m[KEY_ADDITIONAL_PROPERTIES].(bool) + } else if isKind(m[KEY_ADDITIONAL_PROPERTIES], reflect.Map) { + newSchema := &subSchema{property: KEY_ADDITIONAL_PROPERTIES, parent: currentSchema, ref: currentSchema.ref} + currentSchema.additionalProperties = newSchema + err := d.parseSchema(m[KEY_ADDITIONAL_PROPERTIES], newSchema) + if err != nil { + return errors.New(err.Error()) + } + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_BOOLEAN + "/" + STRING_SCHEMA, + "given": KEY_ADDITIONAL_PROPERTIES, + }, + )) + } + } + + // patternProperties + if existsMapKey(m, KEY_PATTERN_PROPERTIES) { + if isKind(m[KEY_PATTERN_PROPERTIES], reflect.Map) { + patternPropertiesMap := m[KEY_PATTERN_PROPERTIES].(map[string]interface{}) + if len(patternPropertiesMap) > 0 { + currentSchema.patternProperties = make(map[string]*subSchema) + for k, v := range patternPropertiesMap { + _, err := regexp.MatchString(k, "") + if err != nil { + return errors.New(formatErrorDescription( + Locale.RegexPattern(), + ErrorDetails{"pattern": k}, + )) + } + newSchema := &subSchema{property: k, parent: currentSchema, ref: currentSchema.ref} + err = d.parseSchema(v, newSchema) + if err != nil { + return errors.New(err.Error()) + } + currentSchema.patternProperties[k] = newSchema + } + } + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": STRING_SCHEMA, + "given": KEY_PATTERN_PROPERTIES, + }, + )) + } + } + + // propertyNames + if existsMapKey(m, KEY_PROPERTY_NAMES) && *currentSchema.draft >= Draft6 { + if isKind(m[KEY_PROPERTY_NAMES], reflect.Map, reflect.Bool) { + newSchema := &subSchema{property: KEY_PROPERTY_NAMES, parent: currentSchema, ref: currentSchema.ref} + currentSchema.propertyNames = newSchema + err := d.parseSchema(m[KEY_PROPERTY_NAMES], newSchema) + if err != nil { + return err + } + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": STRING_SCHEMA, + "given": KEY_PATTERN_PROPERTIES, + }, + )) + } + } + + // dependencies + if existsMapKey(m, KEY_DEPENDENCIES) { + err := d.parseDependencies(m[KEY_DEPENDENCIES], currentSchema) + if err != nil { + return err + } + } + + // items + if existsMapKey(m, KEY_ITEMS) { + if isKind(m[KEY_ITEMS], reflect.Slice) { + for _, itemElement := range m[KEY_ITEMS].([]interface{}) { + if isKind(itemElement, reflect.Map, reflect.Bool) { + newSchema := &subSchema{parent: currentSchema, property: KEY_ITEMS} + newSchema.ref = currentSchema.ref + currentSchema.itemsChildren = append(currentSchema.itemsChildren, newSchema) + err := d.parseSchema(itemElement, newSchema) + if err != nil { + return err + } + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": STRING_SCHEMA + "/" + STRING_ARRAY_OF_SCHEMAS, + "given": KEY_ITEMS, + }, + )) + } + currentSchema.itemsChildrenIsSingleSchema = false + } + } else if isKind(m[KEY_ITEMS], reflect.Map, reflect.Bool) { + newSchema := &subSchema{parent: currentSchema, property: KEY_ITEMS} + newSchema.ref = currentSchema.ref + currentSchema.itemsChildren = append(currentSchema.itemsChildren, newSchema) + err := d.parseSchema(m[KEY_ITEMS], newSchema) + if err != nil { + return err + } + currentSchema.itemsChildrenIsSingleSchema = true + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": STRING_SCHEMA + "/" + STRING_ARRAY_OF_SCHEMAS, + "given": KEY_ITEMS, + }, + )) + } + } + + // additionalItems + if existsMapKey(m, KEY_ADDITIONAL_ITEMS) { + if isKind(m[KEY_ADDITIONAL_ITEMS], reflect.Bool) { + currentSchema.additionalItems = m[KEY_ADDITIONAL_ITEMS].(bool) + } else if isKind(m[KEY_ADDITIONAL_ITEMS], reflect.Map) { + newSchema := &subSchema{property: KEY_ADDITIONAL_ITEMS, parent: currentSchema, ref: currentSchema.ref} + currentSchema.additionalItems = newSchema + err := d.parseSchema(m[KEY_ADDITIONAL_ITEMS], newSchema) + if err != nil { + return errors.New(err.Error()) + } + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_BOOLEAN + "/" + STRING_SCHEMA, + "given": KEY_ADDITIONAL_ITEMS, + }, + )) + } + } + + // validation : number / integer + + if existsMapKey(m, KEY_MULTIPLE_OF) { + multipleOfValue := mustBeNumber(m[KEY_MULTIPLE_OF]) + if multipleOfValue == nil { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": STRING_NUMBER, + "given": KEY_MULTIPLE_OF, + }, + )) + } + if multipleOfValue.Cmp(big.NewRat(0, 1)) <= 0 { + return errors.New(formatErrorDescription( + Locale.GreaterThanZero(), + ErrorDetails{"number": KEY_MULTIPLE_OF}, + )) + } + currentSchema.multipleOf = multipleOfValue + } + + if existsMapKey(m, KEY_MINIMUM) { + minimumValue := mustBeNumber(m[KEY_MINIMUM]) + if minimumValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfA(), + ErrorDetails{"x": KEY_MINIMUM, "y": STRING_NUMBER}, + )) + } + currentSchema.minimum = minimumValue + } + + if existsMapKey(m, KEY_EXCLUSIVE_MINIMUM) { + switch *currentSchema.draft { + case Draft4: + if !isKind(m[KEY_EXCLUSIVE_MINIMUM], reflect.Bool) { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_BOOLEAN, + "given": KEY_EXCLUSIVE_MINIMUM, + }, + )) + } + if currentSchema.minimum == nil { + return errors.New(formatErrorDescription( + Locale.CannotBeUsedWithout(), + ErrorDetails{"x": KEY_EXCLUSIVE_MINIMUM, "y": KEY_MINIMUM}, + )) + } + if m[KEY_EXCLUSIVE_MINIMUM].(bool) { + currentSchema.exclusiveMinimum = currentSchema.minimum + currentSchema.minimum = nil + } + case Hybrid: + if isKind(m[KEY_EXCLUSIVE_MINIMUM], reflect.Bool) { + if currentSchema.minimum == nil { + return errors.New(formatErrorDescription( + Locale.CannotBeUsedWithout(), + ErrorDetails{"x": KEY_EXCLUSIVE_MINIMUM, "y": KEY_MINIMUM}, + )) + } + if m[KEY_EXCLUSIVE_MINIMUM].(bool) { + currentSchema.exclusiveMinimum = currentSchema.minimum + currentSchema.minimum = nil + } + } else if isJSONNumber(m[KEY_EXCLUSIVE_MINIMUM]) { + currentSchema.exclusiveMinimum = mustBeNumber(m[KEY_EXCLUSIVE_MINIMUM]) + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_BOOLEAN + "/" + TYPE_NUMBER, + "given": KEY_EXCLUSIVE_MINIMUM, + }, + )) + } + default: + if isJSONNumber(m[KEY_EXCLUSIVE_MINIMUM]) { + currentSchema.exclusiveMinimum = mustBeNumber(m[KEY_EXCLUSIVE_MINIMUM]) + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_NUMBER, + "given": KEY_EXCLUSIVE_MINIMUM, + }, + )) + } + } + } + + if existsMapKey(m, KEY_MAXIMUM) { + maximumValue := mustBeNumber(m[KEY_MAXIMUM]) + if maximumValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfA(), + ErrorDetails{"x": KEY_MAXIMUM, "y": STRING_NUMBER}, + )) + } + currentSchema.maximum = maximumValue + } + + if existsMapKey(m, KEY_EXCLUSIVE_MAXIMUM) { + switch *currentSchema.draft { + case Draft4: + if !isKind(m[KEY_EXCLUSIVE_MAXIMUM], reflect.Bool) { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_BOOLEAN, + "given": KEY_EXCLUSIVE_MAXIMUM, + }, + )) + } + if currentSchema.maximum == nil { + return errors.New(formatErrorDescription( + Locale.CannotBeUsedWithout(), + ErrorDetails{"x": KEY_EXCLUSIVE_MAXIMUM, "y": KEY_MAXIMUM}, + )) + } + if m[KEY_EXCLUSIVE_MAXIMUM].(bool) { + currentSchema.exclusiveMaximum = currentSchema.maximum + currentSchema.maximum = nil + } + case Hybrid: + if isKind(m[KEY_EXCLUSIVE_MAXIMUM], reflect.Bool) { + if currentSchema.maximum == nil { + return errors.New(formatErrorDescription( + Locale.CannotBeUsedWithout(), + ErrorDetails{"x": KEY_EXCLUSIVE_MAXIMUM, "y": KEY_MAXIMUM}, + )) + } + if m[KEY_EXCLUSIVE_MAXIMUM].(bool) { + currentSchema.exclusiveMaximum = currentSchema.maximum + currentSchema.maximum = nil + } + } else if isJSONNumber(m[KEY_EXCLUSIVE_MAXIMUM]) { + currentSchema.exclusiveMaximum = mustBeNumber(m[KEY_EXCLUSIVE_MAXIMUM]) + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_BOOLEAN + "/" + TYPE_NUMBER, + "given": KEY_EXCLUSIVE_MAXIMUM, + }, + )) + } + default: + if isJSONNumber(m[KEY_EXCLUSIVE_MAXIMUM]) { + currentSchema.exclusiveMaximum = mustBeNumber(m[KEY_EXCLUSIVE_MAXIMUM]) + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_NUMBER, + "given": KEY_EXCLUSIVE_MAXIMUM, + }, + )) + } + } + } + + // validation : string + + if existsMapKey(m, KEY_MIN_LENGTH) { + minLengthIntegerValue := mustBeInteger(m[KEY_MIN_LENGTH]) + if minLengthIntegerValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_MIN_LENGTH, "y": TYPE_INTEGER}, + )) + } + if *minLengthIntegerValue < 0 { + return errors.New(formatErrorDescription( + Locale.MustBeGTEZero(), + ErrorDetails{"key": KEY_MIN_LENGTH}, + )) + } + currentSchema.minLength = minLengthIntegerValue + } + + if existsMapKey(m, KEY_MAX_LENGTH) { + maxLengthIntegerValue := mustBeInteger(m[KEY_MAX_LENGTH]) + if maxLengthIntegerValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_MAX_LENGTH, "y": TYPE_INTEGER}, + )) + } + if *maxLengthIntegerValue < 0 { + return errors.New(formatErrorDescription( + Locale.MustBeGTEZero(), + ErrorDetails{"key": KEY_MAX_LENGTH}, + )) + } + currentSchema.maxLength = maxLengthIntegerValue + } + + if currentSchema.minLength != nil && currentSchema.maxLength != nil { + if *currentSchema.minLength > *currentSchema.maxLength { + return errors.New(formatErrorDescription( + Locale.CannotBeGT(), + ErrorDetails{"x": KEY_MIN_LENGTH, "y": KEY_MAX_LENGTH}, + )) + } + } + + if existsMapKey(m, KEY_PATTERN) { + if isKind(m[KEY_PATTERN], reflect.String) { + regexpObject, err := regexp.Compile(m[KEY_PATTERN].(string)) + if err != nil { + return errors.New(formatErrorDescription( + Locale.MustBeValidRegex(), + ErrorDetails{"key": KEY_PATTERN}, + )) + } + currentSchema.pattern = regexpObject + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfA(), + ErrorDetails{"x": KEY_PATTERN, "y": TYPE_STRING}, + )) + } + } + + if existsMapKey(m, KEY_FORMAT) { + formatString, ok := m[KEY_FORMAT].(string) + if !ok { + return errors.New(formatErrorDescription( + Locale.MustBeOfType(), + ErrorDetails{"key": KEY_FORMAT, "type": TYPE_STRING}, + )) + } + currentSchema.format = formatString + } + + // validation : object + + if existsMapKey(m, KEY_MIN_PROPERTIES) { + minPropertiesIntegerValue := mustBeInteger(m[KEY_MIN_PROPERTIES]) + if minPropertiesIntegerValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_MIN_PROPERTIES, "y": TYPE_INTEGER}, + )) + } + if *minPropertiesIntegerValue < 0 { + return errors.New(formatErrorDescription( + Locale.MustBeGTEZero(), + ErrorDetails{"key": KEY_MIN_PROPERTIES}, + )) + } + currentSchema.minProperties = minPropertiesIntegerValue + } + + if existsMapKey(m, KEY_MAX_PROPERTIES) { + maxPropertiesIntegerValue := mustBeInteger(m[KEY_MAX_PROPERTIES]) + if maxPropertiesIntegerValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_MAX_PROPERTIES, "y": TYPE_INTEGER}, + )) + } + if *maxPropertiesIntegerValue < 0 { + return errors.New(formatErrorDescription( + Locale.MustBeGTEZero(), + ErrorDetails{"key": KEY_MAX_PROPERTIES}, + )) + } + currentSchema.maxProperties = maxPropertiesIntegerValue + } + + if currentSchema.minProperties != nil && currentSchema.maxProperties != nil { + if *currentSchema.minProperties > *currentSchema.maxProperties { + return errors.New(formatErrorDescription( + Locale.KeyCannotBeGreaterThan(), + ErrorDetails{"key": KEY_MIN_PROPERTIES, "y": KEY_MAX_PROPERTIES}, + )) + } + } + + if existsMapKey(m, KEY_REQUIRED) { + if isKind(m[KEY_REQUIRED], reflect.Slice) { + requiredValues := m[KEY_REQUIRED].([]interface{}) + for _, requiredValue := range requiredValues { + if isKind(requiredValue, reflect.String) { + if isStringInSlice(currentSchema.required, requiredValue.(string)) { + return errors.New(formatErrorDescription( + Locale.KeyItemsMustBeUnique(), + ErrorDetails{"key": KEY_REQUIRED}, + )) + } + currentSchema.required = append(currentSchema.required, requiredValue.(string)) + } else { + return errors.New(formatErrorDescription( + Locale.KeyItemsMustBeOfType(), + ErrorDetails{"key": KEY_REQUIRED, "type": TYPE_STRING}, + )) + } + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_REQUIRED, "y": TYPE_ARRAY}, + )) + } + } + + // validation : array + + if existsMapKey(m, KEY_MIN_ITEMS) { + minItemsIntegerValue := mustBeInteger(m[KEY_MIN_ITEMS]) + if minItemsIntegerValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_MIN_ITEMS, "y": TYPE_INTEGER}, + )) + } + if *minItemsIntegerValue < 0 { + return errors.New(formatErrorDescription( + Locale.MustBeGTEZero(), + ErrorDetails{"key": KEY_MIN_ITEMS}, + )) + } + currentSchema.minItems = minItemsIntegerValue + } + + if existsMapKey(m, KEY_MAX_ITEMS) { + maxItemsIntegerValue := mustBeInteger(m[KEY_MAX_ITEMS]) + if maxItemsIntegerValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_MAX_ITEMS, "y": TYPE_INTEGER}, + )) + } + if *maxItemsIntegerValue < 0 { + return errors.New(formatErrorDescription( + Locale.MustBeGTEZero(), + ErrorDetails{"key": KEY_MAX_ITEMS}, + )) + } + currentSchema.maxItems = maxItemsIntegerValue + } + + if existsMapKey(m, KEY_UNIQUE_ITEMS) { + if isKind(m[KEY_UNIQUE_ITEMS], reflect.Bool) { + currentSchema.uniqueItems = m[KEY_UNIQUE_ITEMS].(bool) + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfA(), + ErrorDetails{"x": KEY_UNIQUE_ITEMS, "y": TYPE_BOOLEAN}, + )) + } + } + + if existsMapKey(m, KEY_CONTAINS) && *currentSchema.draft >= Draft6 { + newSchema := &subSchema{property: KEY_CONTAINS, parent: currentSchema, ref: currentSchema.ref} + currentSchema.contains = newSchema + err := d.parseSchema(m[KEY_CONTAINS], newSchema) + if err != nil { + return err + } + } + + // validation : all + + if existsMapKey(m, KEY_CONST) && *currentSchema.draft >= Draft6 { + is, err := marshalWithoutNumber(m[KEY_CONST]) + if err != nil { + return err + } + currentSchema._const = is + } + + if existsMapKey(m, KEY_ENUM) { + if isKind(m[KEY_ENUM], reflect.Slice) { + for _, v := range m[KEY_ENUM].([]interface{}) { + is, err := marshalWithoutNumber(v) + if err != nil { + return err + } + if isStringInSlice(currentSchema.enum, *is) { + return errors.New(formatErrorDescription( + Locale.KeyItemsMustBeUnique(), + ErrorDetails{"key": KEY_ENUM}, + )) + } + currentSchema.enum = append(currentSchema.enum, *is) + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_ENUM, "y": TYPE_ARRAY}, + )) + } + } + + // validation : subSchema + + if existsMapKey(m, KEY_ONE_OF) { + if isKind(m[KEY_ONE_OF], reflect.Slice) { + for _, v := range m[KEY_ONE_OF].([]interface{}) { + newSchema := &subSchema{property: KEY_ONE_OF, parent: currentSchema, ref: currentSchema.ref} + currentSchema.oneOf = append(currentSchema.oneOf, newSchema) + err := d.parseSchema(v, newSchema) + if err != nil { + return err + } + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_ONE_OF, "y": TYPE_ARRAY}, + )) + } + } + + if existsMapKey(m, KEY_ANY_OF) { + if isKind(m[KEY_ANY_OF], reflect.Slice) { + for _, v := range m[KEY_ANY_OF].([]interface{}) { + newSchema := &subSchema{property: KEY_ANY_OF, parent: currentSchema, ref: currentSchema.ref} + currentSchema.anyOf = append(currentSchema.anyOf, newSchema) + err := d.parseSchema(v, newSchema) + if err != nil { + return err + } + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_ANY_OF, "y": TYPE_ARRAY}, + )) + } + } + + if existsMapKey(m, KEY_ALL_OF) { + if isKind(m[KEY_ALL_OF], reflect.Slice) { + for _, v := range m[KEY_ALL_OF].([]interface{}) { + newSchema := &subSchema{property: KEY_ALL_OF, parent: currentSchema, ref: currentSchema.ref} + currentSchema.allOf = append(currentSchema.allOf, newSchema) + err := d.parseSchema(v, newSchema) + if err != nil { + return err + } + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_ANY_OF, "y": TYPE_ARRAY}, + )) + } + } + + if existsMapKey(m, KEY_NOT) { + if isKind(m[KEY_NOT], reflect.Map, reflect.Bool) { + newSchema := &subSchema{property: KEY_NOT, parent: currentSchema, ref: currentSchema.ref} + currentSchema.not = newSchema + err := d.parseSchema(m[KEY_NOT], newSchema) + if err != nil { + return err + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_NOT, "y": TYPE_OBJECT}, + )) + } + } + + if *currentSchema.draft >= Draft7 { + if existsMapKey(m, KEY_IF) { + if isKind(m[KEY_IF], reflect.Map, reflect.Bool) { + newSchema := &subSchema{property: KEY_IF, parent: currentSchema, ref: currentSchema.ref} + currentSchema._if = newSchema + err := d.parseSchema(m[KEY_IF], newSchema) + if err != nil { + return err + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_IF, "y": TYPE_OBJECT}, + )) + } + } + + if existsMapKey(m, KEY_THEN) { + if isKind(m[KEY_THEN], reflect.Map, reflect.Bool) { + newSchema := &subSchema{property: KEY_THEN, parent: currentSchema, ref: currentSchema.ref} + currentSchema._then = newSchema + err := d.parseSchema(m[KEY_THEN], newSchema) + if err != nil { + return err + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_THEN, "y": TYPE_OBJECT}, + )) + } + } + + if existsMapKey(m, KEY_ELSE) { + if isKind(m[KEY_ELSE], reflect.Map, reflect.Bool) { + newSchema := &subSchema{property: KEY_ELSE, parent: currentSchema, ref: currentSchema.ref} + currentSchema._else = newSchema + err := d.parseSchema(m[KEY_ELSE], newSchema) + if err != nil { + return err + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_ELSE, "y": TYPE_OBJECT}, + )) + } + } + } + + return nil +} + +func (d *Schema) parseReference(documentNode interface{}, currentSchema *subSchema) error { + var ( + refdDocumentNode interface{} + dsp *schemaPoolDocument + err error + ) + + newSchema := &subSchema{property: KEY_REF, parent: currentSchema, ref: currentSchema.ref} + + d.referencePool.Add(currentSchema.ref.String(), newSchema) + + dsp, err = d.pool.GetDocument(*currentSchema.ref) + if err != nil { + return err + } + newSchema.id = currentSchema.ref + + refdDocumentNode = dsp.Document + newSchema.draft = dsp.Draft + + if err != nil { + return err + } + + if !isKind(refdDocumentNode, reflect.Map, reflect.Bool) { + return errors.New(formatErrorDescription( + Locale.MustBeOfType(), + ErrorDetails{"key": STRING_SCHEMA, "type": TYPE_OBJECT}, + )) + } + + err = d.parseSchema(refdDocumentNode, newSchema) + if err != nil { + return err + } + + currentSchema.refSchema = newSchema + + return nil + +} + +func (d *Schema) parseProperties(documentNode interface{}, currentSchema *subSchema) error { + + if !isKind(documentNode, reflect.Map) { + return errors.New(formatErrorDescription( + Locale.MustBeOfType(), + ErrorDetails{"key": STRING_PROPERTIES, "type": TYPE_OBJECT}, + )) + } + + m := documentNode.(map[string]interface{}) + for k := range m { + schemaProperty := k + newSchema := &subSchema{property: schemaProperty, parent: currentSchema, ref: currentSchema.ref} + currentSchema.propertiesChildren = append(currentSchema.propertiesChildren, newSchema) + err := d.parseSchema(m[k], newSchema) + if err != nil { + return err + } + } + + return nil +} + +func (d *Schema) parseDependencies(documentNode interface{}, currentSchema *subSchema) error { + + if !isKind(documentNode, reflect.Map) { + return errors.New(formatErrorDescription( + Locale.MustBeOfType(), + ErrorDetails{"key": KEY_DEPENDENCIES, "type": TYPE_OBJECT}, + )) + } + + m := documentNode.(map[string]interface{}) + currentSchema.dependencies = make(map[string]interface{}) + + for k := range m { + switch reflect.ValueOf(m[k]).Kind() { + + case reflect.Slice: + values := m[k].([]interface{}) + var valuesToRegister []string + + for _, value := range values { + if !isKind(value, reflect.String) { + return errors.New(formatErrorDescription( + Locale.MustBeOfType(), + ErrorDetails{ + "key": STRING_DEPENDENCY, + "type": STRING_SCHEMA_OR_ARRAY_OF_STRINGS, + }, + )) + } + valuesToRegister = append(valuesToRegister, value.(string)) + currentSchema.dependencies[k] = valuesToRegister + } + + case reflect.Map, reflect.Bool: + depSchema := &subSchema{property: k, parent: currentSchema, ref: currentSchema.ref} + err := d.parseSchema(m[k], depSchema) + if err != nil { + return err + } + currentSchema.dependencies[k] = depSchema + + default: + return errors.New(formatErrorDescription( + Locale.MustBeOfType(), + ErrorDetails{ + "key": STRING_DEPENDENCY, + "type": STRING_SCHEMA_OR_ARRAY_OF_STRINGS, + }, + )) + } + + } + + return nil +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/schemaLoader.go b/vendor/github.com/xeipuuv/gojsonschema/schemaLoader.go new file mode 100644 index 00000000..20db0c1f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/schemaLoader.go @@ -0,0 +1,206 @@ +// Copyright 2018 johandorland ( https://github.com/johandorland ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package gojsonschema + +import ( + "bytes" + "errors" + + "github.com/xeipuuv/gojsonreference" +) + +// SchemaLoader is used to load schemas +type SchemaLoader struct { + pool *schemaPool + AutoDetect bool + Validate bool + Draft Draft +} + +// NewSchemaLoader creates a new NewSchemaLoader +func NewSchemaLoader() *SchemaLoader { + + ps := &SchemaLoader{ + pool: &schemaPool{ + schemaPoolDocuments: make(map[string]*schemaPoolDocument), + }, + AutoDetect: true, + Validate: false, + Draft: Hybrid, + } + ps.pool.autoDetect = &ps.AutoDetect + + return ps +} + +func (sl *SchemaLoader) validateMetaschema(documentNode interface{}) error { + + var ( + schema string + err error + ) + if sl.AutoDetect { + schema, _, err = parseSchemaURL(documentNode) + if err != nil { + return err + } + } + + // If no explicit "$schema" is used, use the default metaschema associated with the draft used + if schema == "" { + if sl.Draft == Hybrid { + return nil + } + schema = drafts.GetSchemaURL(sl.Draft) + } + + //Disable validation when loading the metaschema to prevent an infinite recursive loop + sl.Validate = false + + metaSchema, err := sl.Compile(NewReferenceLoader(schema)) + + if err != nil { + return err + } + + sl.Validate = true + + result := metaSchema.validateDocument(documentNode) + + if !result.Valid() { + var res bytes.Buffer + for _, err := range result.Errors() { + res.WriteString(err.String()) + res.WriteString("\n") + } + return errors.New(res.String()) + } + + return nil +} + +// AddSchemas adds an arbritrary amount of schemas to the schema cache. As this function does not require +// an explicit URL, every schema should contain an $id, so that it can be referenced by the main schema +func (sl *SchemaLoader) AddSchemas(loaders ...JSONLoader) error { + emptyRef, _ := gojsonreference.NewJsonReference("") + + for _, loader := range loaders { + doc, err := loader.LoadJSON() + + if err != nil { + return err + } + + if sl.Validate { + if err := sl.validateMetaschema(doc); err != nil { + return err + } + } + + // Directly use the Recursive function, so that it get only added to the schema pool by $id + // and not by the ref of the document as it's empty + if err = sl.pool.parseReferences(doc, emptyRef, false); err != nil { + return err + } + } + + return nil +} + +//AddSchema adds a schema under the provided URL to the schema cache +func (sl *SchemaLoader) AddSchema(url string, loader JSONLoader) error { + + ref, err := gojsonreference.NewJsonReference(url) + + if err != nil { + return err + } + + doc, err := loader.LoadJSON() + + if err != nil { + return err + } + + if sl.Validate { + if err := sl.validateMetaschema(doc); err != nil { + return err + } + } + + return sl.pool.parseReferences(doc, ref, true) +} + +// Compile loads and compiles a schema +func (sl *SchemaLoader) Compile(rootSchema JSONLoader) (*Schema, error) { + + ref, err := rootSchema.JsonReference() + + if err != nil { + return nil, err + } + + d := Schema{} + d.pool = sl.pool + d.pool.jsonLoaderFactory = rootSchema.LoaderFactory() + d.documentReference = ref + d.referencePool = newSchemaReferencePool() + + var doc interface{} + if ref.String() != "" { + // Get document from schema pool + spd, err := d.pool.GetDocument(d.documentReference) + if err != nil { + return nil, err + } + doc = spd.Document + } else { + // Load JSON directly + doc, err = rootSchema.LoadJSON() + if err != nil { + return nil, err + } + // References need only be parsed if loading JSON directly + // as pool.GetDocument already does this for us if loading by reference + err = sl.pool.parseReferences(doc, ref, true) + if err != nil { + return nil, err + } + } + + if sl.Validate { + if err := sl.validateMetaschema(doc); err != nil { + return nil, err + } + } + + draft := sl.Draft + if sl.AutoDetect { + _, detectedDraft, err := parseSchemaURL(doc) + if err != nil { + return nil, err + } + if detectedDraft != nil { + draft = *detectedDraft + } + } + + err = d.parse(doc, draft) + if err != nil { + return nil, err + } + + return &d, nil +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/schemaPool.go b/vendor/github.com/xeipuuv/gojsonschema/schemaPool.go new file mode 100644 index 00000000..35b1cc63 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/schemaPool.go @@ -0,0 +1,215 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Defines resources pooling. +// Eases referencing and avoids downloading the same resource twice. +// +// created 26-02-2013 + +package gojsonschema + +import ( + "errors" + "fmt" + "reflect" + + "github.com/xeipuuv/gojsonreference" +) + +type schemaPoolDocument struct { + Document interface{} + Draft *Draft +} + +type schemaPool struct { + schemaPoolDocuments map[string]*schemaPoolDocument + jsonLoaderFactory JSONLoaderFactory + autoDetect *bool +} + +func (p *schemaPool) parseReferences(document interface{}, ref gojsonreference.JsonReference, pooled bool) error { + + var ( + draft *Draft + err error + reference = ref.String() + ) + // Only the root document should be added to the schema pool if pooled is true + if _, ok := p.schemaPoolDocuments[reference]; pooled && ok { + return fmt.Errorf("Reference already exists: \"%s\"", reference) + } + + if *p.autoDetect { + _, draft, err = parseSchemaURL(document) + if err != nil { + return err + } + } + + err = p.parseReferencesRecursive(document, ref, draft) + + if pooled { + p.schemaPoolDocuments[reference] = &schemaPoolDocument{Document: document, Draft: draft} + } + + return err +} + +func (p *schemaPool) parseReferencesRecursive(document interface{}, ref gojsonreference.JsonReference, draft *Draft) error { + // parseReferencesRecursive parses a JSON document and resolves all $id and $ref references. + // For $ref references it takes into account the $id scope it is in and replaces + // the reference by the absolute resolved reference + + // When encountering errors it fails silently. Error handling is done when the schema + // is syntactically parsed and any error encountered here should also come up there. + switch m := document.(type) { + case []interface{}: + for _, v := range m { + p.parseReferencesRecursive(v, ref, draft) + } + case map[string]interface{}: + localRef := &ref + + keyID := KEY_ID_NEW + if existsMapKey(m, KEY_ID) { + keyID = KEY_ID + } + if existsMapKey(m, keyID) && isKind(m[keyID], reflect.String) { + jsonReference, err := gojsonreference.NewJsonReference(m[keyID].(string)) + if err == nil { + localRef, err = ref.Inherits(jsonReference) + if err == nil { + if _, ok := p.schemaPoolDocuments[localRef.String()]; ok { + return fmt.Errorf("Reference already exists: \"%s\"", localRef.String()) + } + p.schemaPoolDocuments[localRef.String()] = &schemaPoolDocument{Document: document, Draft: draft} + } + } + } + + if existsMapKey(m, KEY_REF) && isKind(m[KEY_REF], reflect.String) { + jsonReference, err := gojsonreference.NewJsonReference(m[KEY_REF].(string)) + if err == nil { + absoluteRef, err := localRef.Inherits(jsonReference) + if err == nil { + m[KEY_REF] = absoluteRef.String() + } + } + } + + for k, v := range m { + // const and enums should be interpreted literally, so ignore them + if k == KEY_CONST || k == KEY_ENUM { + continue + } + // Something like a property or a dependency is not a valid schema, as it might describe properties named "$ref", "$id" or "const", etc + // Therefore don't treat it like a schema. + if k == KEY_PROPERTIES || k == KEY_DEPENDENCIES || k == KEY_PATTERN_PROPERTIES { + if child, ok := v.(map[string]interface{}); ok { + for _, v := range child { + p.parseReferencesRecursive(v, *localRef, draft) + } + } + } else { + p.parseReferencesRecursive(v, *localRef, draft) + } + } + } + return nil +} + +func (p *schemaPool) GetDocument(reference gojsonreference.JsonReference) (*schemaPoolDocument, error) { + + var ( + spd *schemaPoolDocument + draft *Draft + ok bool + err error + ) + + if internalLogEnabled { + internalLog("Get Document ( %s )", reference.String()) + } + + // Create a deep copy, so we can remove the fragment part later on without altering the original + refToURL, _ := gojsonreference.NewJsonReference(reference.String()) + + // First check if the given fragment is a location independent identifier + // http://json-schema.org/latest/json-schema-core.html#rfc.section.8.2.3 + + if spd, ok = p.schemaPoolDocuments[refToURL.String()]; ok { + if internalLogEnabled { + internalLog(" From pool") + } + return spd, nil + } + + // If the given reference is not a location independent identifier, + // strip the fragment and look for a document with it's base URI + + refToURL.GetUrl().Fragment = "" + + if cachedSpd, ok := p.schemaPoolDocuments[refToURL.String()]; ok { + document, _, err := reference.GetPointer().Get(cachedSpd.Document) + + if err != nil { + return nil, err + } + + if internalLogEnabled { + internalLog(" From pool") + } + + spd = &schemaPoolDocument{Document: document, Draft: cachedSpd.Draft} + p.schemaPoolDocuments[reference.String()] = spd + + return spd, nil + } + + // It is not possible to load anything remotely that is not canonical... + if !reference.IsCanonical() { + return nil, errors.New(formatErrorDescription( + Locale.ReferenceMustBeCanonical(), + ErrorDetails{"reference": reference.String()}, + )) + } + + jsonReferenceLoader := p.jsonLoaderFactory.New(reference.String()) + document, err := jsonReferenceLoader.LoadJSON() + + if err != nil { + return nil, err + } + + // add the whole document to the pool for potential re-use + p.parseReferences(document, refToURL, true) + + _, draft, _ = parseSchemaURL(document) + + // resolve the potential fragment and also cache it + document, _, err = reference.GetPointer().Get(document) + + if err != nil { + return nil, err + } + + return &schemaPoolDocument{Document: document, Draft: draft}, nil +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/schemaReferencePool.go b/vendor/github.com/xeipuuv/gojsonschema/schemaReferencePool.go new file mode 100644 index 00000000..6e5e1b5c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/schemaReferencePool.go @@ -0,0 +1,68 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Pool of referenced schemas. +// +// created 25-06-2013 + +package gojsonschema + +import ( + "fmt" +) + +type schemaReferencePool struct { + documents map[string]*subSchema +} + +func newSchemaReferencePool() *schemaReferencePool { + + p := &schemaReferencePool{} + p.documents = make(map[string]*subSchema) + + return p +} + +func (p *schemaReferencePool) Get(ref string) (r *subSchema, o bool) { + + if internalLogEnabled { + internalLog(fmt.Sprintf("Schema Reference ( %s )", ref)) + } + + if sch, ok := p.documents[ref]; ok { + if internalLogEnabled { + internalLog(fmt.Sprintf(" From pool")) + } + return sch, true + } + + return nil, false +} + +func (p *schemaReferencePool) Add(ref string, sch *subSchema) { + + if internalLogEnabled { + internalLog(fmt.Sprintf("Add Schema Reference %s to pool", ref)) + } + if _, ok := p.documents[ref]; !ok { + p.documents[ref] = sch + } +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/schemaType.go b/vendor/github.com/xeipuuv/gojsonschema/schemaType.go new file mode 100644 index 00000000..36b447a2 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/schemaType.go @@ -0,0 +1,83 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Helper structure to handle schema types, and the combination of them. +// +// created 28-02-2013 + +package gojsonschema + +import ( + "errors" + "fmt" + "strings" +) + +type jsonSchemaType struct { + types []string +} + +// Is the schema typed ? that is containing at least one type +// When not typed, the schema does not need any type validation +func (t *jsonSchemaType) IsTyped() bool { + return len(t.types) > 0 +} + +func (t *jsonSchemaType) Add(etype string) error { + + if !isStringInSlice(JSON_TYPES, etype) { + return errors.New(formatErrorDescription(Locale.NotAValidType(), ErrorDetails{"given": "/" + etype + "/", "expected": JSON_TYPES})) + } + + if t.Contains(etype) { + return errors.New(formatErrorDescription(Locale.Duplicated(), ErrorDetails{"type": etype})) + } + + t.types = append(t.types, etype) + + return nil +} + +func (t *jsonSchemaType) Contains(etype string) bool { + + for _, v := range t.types { + if v == etype { + return true + } + } + + return false +} + +func (t *jsonSchemaType) String() string { + + if len(t.types) == 0 { + return STRING_UNDEFINED // should never happen + } + + // Displayed as a list [type1,type2,...] + if len(t.types) > 1 { + return fmt.Sprintf("[%s]", strings.Join(t.types, ",")) + } + + // Only one type: name only + return t.types[0] +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/subSchema.go b/vendor/github.com/xeipuuv/gojsonschema/subSchema.go new file mode 100644 index 00000000..ec779812 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/subSchema.go @@ -0,0 +1,149 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Defines the structure of a sub-subSchema. +// A sub-subSchema can contain other sub-schemas. +// +// created 27-02-2013 + +package gojsonschema + +import ( + "github.com/xeipuuv/gojsonreference" + "math/big" + "regexp" +) + +// Constants +const ( + KEY_SCHEMA = "$schema" + KEY_ID = "id" + KEY_ID_NEW = "$id" + KEY_REF = "$ref" + KEY_TITLE = "title" + KEY_DESCRIPTION = "description" + KEY_TYPE = "type" + KEY_ITEMS = "items" + KEY_ADDITIONAL_ITEMS = "additionalItems" + KEY_PROPERTIES = "properties" + KEY_PATTERN_PROPERTIES = "patternProperties" + KEY_ADDITIONAL_PROPERTIES = "additionalProperties" + KEY_PROPERTY_NAMES = "propertyNames" + KEY_DEFINITIONS = "definitions" + KEY_MULTIPLE_OF = "multipleOf" + KEY_MINIMUM = "minimum" + KEY_MAXIMUM = "maximum" + KEY_EXCLUSIVE_MINIMUM = "exclusiveMinimum" + KEY_EXCLUSIVE_MAXIMUM = "exclusiveMaximum" + KEY_MIN_LENGTH = "minLength" + KEY_MAX_LENGTH = "maxLength" + KEY_PATTERN = "pattern" + KEY_FORMAT = "format" + KEY_MIN_PROPERTIES = "minProperties" + KEY_MAX_PROPERTIES = "maxProperties" + KEY_DEPENDENCIES = "dependencies" + KEY_REQUIRED = "required" + KEY_MIN_ITEMS = "minItems" + KEY_MAX_ITEMS = "maxItems" + KEY_UNIQUE_ITEMS = "uniqueItems" + KEY_CONTAINS = "contains" + KEY_CONST = "const" + KEY_ENUM = "enum" + KEY_ONE_OF = "oneOf" + KEY_ANY_OF = "anyOf" + KEY_ALL_OF = "allOf" + KEY_NOT = "not" + KEY_IF = "if" + KEY_THEN = "then" + KEY_ELSE = "else" +) + +type subSchema struct { + draft *Draft + + // basic subSchema meta properties + id *gojsonreference.JsonReference + title *string + description *string + + property string + + // Quick pass/fail for boolean schemas + pass *bool + + // Types associated with the subSchema + types jsonSchemaType + + // Reference url + ref *gojsonreference.JsonReference + // Schema referenced + refSchema *subSchema + + // hierarchy + parent *subSchema + itemsChildren []*subSchema + itemsChildrenIsSingleSchema bool + propertiesChildren []*subSchema + + // validation : number / integer + multipleOf *big.Rat + maximum *big.Rat + exclusiveMaximum *big.Rat + minimum *big.Rat + exclusiveMinimum *big.Rat + + // validation : string + minLength *int + maxLength *int + pattern *regexp.Regexp + format string + + // validation : object + minProperties *int + maxProperties *int + required []string + + dependencies map[string]interface{} + additionalProperties interface{} + patternProperties map[string]*subSchema + propertyNames *subSchema + + // validation : array + minItems *int + maxItems *int + uniqueItems bool + contains *subSchema + + additionalItems interface{} + + // validation : all + _const *string //const is a golang keyword + enum []string + + // validation : subSchema + oneOf []*subSchema + anyOf []*subSchema + allOf []*subSchema + not *subSchema + _if *subSchema // if/else are golang keywords + _then *subSchema + _else *subSchema +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/types.go b/vendor/github.com/xeipuuv/gojsonschema/types.go new file mode 100644 index 00000000..0e6fd517 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/types.go @@ -0,0 +1,62 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Contains const types for schema and JSON. +// +// created 28-02-2013 + +package gojsonschema + +// Type constants +const ( + TYPE_ARRAY = `array` + TYPE_BOOLEAN = `boolean` + TYPE_INTEGER = `integer` + TYPE_NUMBER = `number` + TYPE_NULL = `null` + TYPE_OBJECT = `object` + TYPE_STRING = `string` +) + +// JSON_TYPES hosts the list of type that are supported in JSON +var JSON_TYPES []string + +// SCHEMA_TYPES hosts the list of type that are supported in schemas +var SCHEMA_TYPES []string + +func init() { + JSON_TYPES = []string{ + TYPE_ARRAY, + TYPE_BOOLEAN, + TYPE_INTEGER, + TYPE_NUMBER, + TYPE_NULL, + TYPE_OBJECT, + TYPE_STRING} + + SCHEMA_TYPES = []string{ + TYPE_ARRAY, + TYPE_BOOLEAN, + TYPE_INTEGER, + TYPE_NUMBER, + TYPE_OBJECT, + TYPE_STRING} +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/utils.go b/vendor/github.com/xeipuuv/gojsonschema/utils.go new file mode 100644 index 00000000..a17d22e3 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/utils.go @@ -0,0 +1,197 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Various utility functions. +// +// created 26-02-2013 + +package gojsonschema + +import ( + "encoding/json" + "math/big" + "reflect" +) + +func isKind(what interface{}, kinds ...reflect.Kind) bool { + target := what + if isJSONNumber(what) { + // JSON Numbers are strings! + target = *mustBeNumber(what) + } + targetKind := reflect.ValueOf(target).Kind() + for _, kind := range kinds { + if targetKind == kind { + return true + } + } + return false +} + +func existsMapKey(m map[string]interface{}, k string) bool { + _, ok := m[k] + return ok +} + +func isStringInSlice(s []string, what string) bool { + for i := range s { + if s[i] == what { + return true + } + } + return false +} + +// indexStringInSlice returns the index of the first instance of 'what' in s or -1 if it is not found in s. +func indexStringInSlice(s []string, what string) int { + for i := range s { + if s[i] == what { + return i + } + } + return -1 +} + +func marshalToJSONString(value interface{}) (*string, error) { + + mBytes, err := json.Marshal(value) + if err != nil { + return nil, err + } + + sBytes := string(mBytes) + return &sBytes, nil +} + +func marshalWithoutNumber(value interface{}) (*string, error) { + + // The JSON is decoded using https://golang.org/pkg/encoding/json/#Decoder.UseNumber + // This means the numbers are internally still represented as strings and therefore 1.00 is unequal to 1 + // One way to eliminate these differences is to decode and encode the JSON one more time without Decoder.UseNumber + // so that these differences in representation are removed + + jsonString, err := marshalToJSONString(value) + if err != nil { + return nil, err + } + + var document interface{} + + err = json.Unmarshal([]byte(*jsonString), &document) + if err != nil { + return nil, err + } + + return marshalToJSONString(document) +} + +func isJSONNumber(what interface{}) bool { + + switch what.(type) { + + case json.Number: + return true + } + + return false +} + +func checkJSONInteger(what interface{}) (isInt bool) { + + jsonNumber := what.(json.Number) + + bigFloat, isValidNumber := new(big.Rat).SetString(string(jsonNumber)) + + return isValidNumber && bigFloat.IsInt() + +} + +// same as ECMA Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER +const ( + maxJSONFloat = float64(1<<53 - 1) // 9007199254740991.0 2^53 - 1 + minJSONFloat = -float64(1<<53 - 1) //-9007199254740991.0 -2^53 - 1 +) + +func mustBeInteger(what interface{}) *int { + + if isJSONNumber(what) { + + number := what.(json.Number) + + isInt := checkJSONInteger(number) + + if isInt { + + int64Value, err := number.Int64() + if err != nil { + return nil + } + + int32Value := int(int64Value) + return &int32Value + } + + } + + return nil +} + +func mustBeNumber(what interface{}) *big.Rat { + + if isJSONNumber(what) { + number := what.(json.Number) + float64Value, success := new(big.Rat).SetString(string(number)) + if success { + return float64Value + } + } + + return nil + +} + +func convertDocumentNode(val interface{}) interface{} { + + if lval, ok := val.([]interface{}); ok { + + res := []interface{}{} + for _, v := range lval { + res = append(res, convertDocumentNode(v)) + } + + return res + + } + + if mval, ok := val.(map[interface{}]interface{}); ok { + + res := map[string]interface{}{} + + for k, v := range mval { + res[k.(string)] = convertDocumentNode(v) + } + + return res + + } + + return val +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/validation.go b/vendor/github.com/xeipuuv/gojsonschema/validation.go new file mode 100644 index 00000000..74091bca --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/validation.go @@ -0,0 +1,858 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Extends Schema and subSchema, implements the validation phase. +// +// created 28-02-2013 + +package gojsonschema + +import ( + "encoding/json" + "math/big" + "reflect" + "regexp" + "strconv" + "strings" + "unicode/utf8" +) + +// Validate loads and validates a JSON schema +func Validate(ls JSONLoader, ld JSONLoader) (*Result, error) { + // load schema + schema, err := NewSchema(ls) + if err != nil { + return nil, err + } + return schema.Validate(ld) +} + +// Validate loads and validates a JSON document +func (v *Schema) Validate(l JSONLoader) (*Result, error) { + root, err := l.LoadJSON() + if err != nil { + return nil, err + } + return v.validateDocument(root), nil +} + +func (v *Schema) validateDocument(root interface{}) *Result { + result := &Result{} + context := NewJsonContext(STRING_CONTEXT_ROOT, nil) + v.rootSchema.validateRecursive(v.rootSchema, root, result, context) + return result +} + +func (v *subSchema) subValidateWithContext(document interface{}, context *JsonContext) *Result { + result := &Result{} + v.validateRecursive(v, document, result, context) + return result +} + +// Walker function to validate the json recursively against the subSchema +func (v *subSchema) validateRecursive(currentSubSchema *subSchema, currentNode interface{}, result *Result, context *JsonContext) { + + if internalLogEnabled { + internalLog("validateRecursive %s", context.String()) + internalLog(" %v", currentNode) + } + + // Handle true/false schema as early as possible as all other fields will be nil + if currentSubSchema.pass != nil { + if !*currentSubSchema.pass { + result.addInternalError( + new(FalseError), + context, + currentNode, + ErrorDetails{}, + ) + } + return + } + + // Handle referenced schemas, returns directly when a $ref is found + if currentSubSchema.refSchema != nil { + v.validateRecursive(currentSubSchema.refSchema, currentNode, result, context) + return + } + + // Check for null value + if currentNode == nil { + if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_NULL) { + result.addInternalError( + new(InvalidTypeError), + context, + currentNode, + ErrorDetails{ + "expected": currentSubSchema.types.String(), + "given": TYPE_NULL, + }, + ) + return + } + + currentSubSchema.validateSchema(currentSubSchema, currentNode, result, context) + v.validateCommon(currentSubSchema, currentNode, result, context) + + } else { // Not a null value + + if isJSONNumber(currentNode) { + + value := currentNode.(json.Number) + + isInt := checkJSONInteger(value) + + validType := currentSubSchema.types.Contains(TYPE_NUMBER) || (isInt && currentSubSchema.types.Contains(TYPE_INTEGER)) + + if currentSubSchema.types.IsTyped() && !validType { + + givenType := TYPE_INTEGER + if !isInt { + givenType = TYPE_NUMBER + } + + result.addInternalError( + new(InvalidTypeError), + context, + currentNode, + ErrorDetails{ + "expected": currentSubSchema.types.String(), + "given": givenType, + }, + ) + return + } + + currentSubSchema.validateSchema(currentSubSchema, value, result, context) + v.validateNumber(currentSubSchema, value, result, context) + v.validateCommon(currentSubSchema, value, result, context) + v.validateString(currentSubSchema, value, result, context) + + } else { + + rValue := reflect.ValueOf(currentNode) + rKind := rValue.Kind() + + switch rKind { + + // Slice => JSON array + + case reflect.Slice: + + if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_ARRAY) { + result.addInternalError( + new(InvalidTypeError), + context, + currentNode, + ErrorDetails{ + "expected": currentSubSchema.types.String(), + "given": TYPE_ARRAY, + }, + ) + return + } + + castCurrentNode := currentNode.([]interface{}) + + currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context) + + v.validateArray(currentSubSchema, castCurrentNode, result, context) + v.validateCommon(currentSubSchema, castCurrentNode, result, context) + + // Map => JSON object + + case reflect.Map: + if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_OBJECT) { + result.addInternalError( + new(InvalidTypeError), + context, + currentNode, + ErrorDetails{ + "expected": currentSubSchema.types.String(), + "given": TYPE_OBJECT, + }, + ) + return + } + + castCurrentNode, ok := currentNode.(map[string]interface{}) + if !ok { + castCurrentNode = convertDocumentNode(currentNode).(map[string]interface{}) + } + + currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context) + + v.validateObject(currentSubSchema, castCurrentNode, result, context) + v.validateCommon(currentSubSchema, castCurrentNode, result, context) + + for _, pSchema := range currentSubSchema.propertiesChildren { + nextNode, ok := castCurrentNode[pSchema.property] + if ok { + subContext := NewJsonContext(pSchema.property, context) + v.validateRecursive(pSchema, nextNode, result, subContext) + } + } + + // Simple JSON values : string, number, boolean + + case reflect.Bool: + + if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_BOOLEAN) { + result.addInternalError( + new(InvalidTypeError), + context, + currentNode, + ErrorDetails{ + "expected": currentSubSchema.types.String(), + "given": TYPE_BOOLEAN, + }, + ) + return + } + + value := currentNode.(bool) + + currentSubSchema.validateSchema(currentSubSchema, value, result, context) + v.validateNumber(currentSubSchema, value, result, context) + v.validateCommon(currentSubSchema, value, result, context) + v.validateString(currentSubSchema, value, result, context) + + case reflect.String: + + if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_STRING) { + result.addInternalError( + new(InvalidTypeError), + context, + currentNode, + ErrorDetails{ + "expected": currentSubSchema.types.String(), + "given": TYPE_STRING, + }, + ) + return + } + + value := currentNode.(string) + + currentSubSchema.validateSchema(currentSubSchema, value, result, context) + v.validateNumber(currentSubSchema, value, result, context) + v.validateCommon(currentSubSchema, value, result, context) + v.validateString(currentSubSchema, value, result, context) + + } + + } + + } + + result.incrementScore() +} + +// Different kinds of validation there, subSchema / common / array / object / string... +func (v *subSchema) validateSchema(currentSubSchema *subSchema, currentNode interface{}, result *Result, context *JsonContext) { + + if internalLogEnabled { + internalLog("validateSchema %s", context.String()) + internalLog(" %v", currentNode) + } + + if len(currentSubSchema.anyOf) > 0 { + + validatedAnyOf := false + var bestValidationResult *Result + + for _, anyOfSchema := range currentSubSchema.anyOf { + if !validatedAnyOf { + validationResult := anyOfSchema.subValidateWithContext(currentNode, context) + validatedAnyOf = validationResult.Valid() + + if !validatedAnyOf && (bestValidationResult == nil || validationResult.score > bestValidationResult.score) { + bestValidationResult = validationResult + } + } + } + if !validatedAnyOf { + + result.addInternalError(new(NumberAnyOfError), context, currentNode, ErrorDetails{}) + + if bestValidationResult != nil { + // add error messages of closest matching subSchema as + // that's probably the one the user was trying to match + result.mergeErrors(bestValidationResult) + } + } + } + + if len(currentSubSchema.oneOf) > 0 { + + nbValidated := 0 + var bestValidationResult *Result + + for _, oneOfSchema := range currentSubSchema.oneOf { + validationResult := oneOfSchema.subValidateWithContext(currentNode, context) + if validationResult.Valid() { + nbValidated++ + } else if nbValidated == 0 && (bestValidationResult == nil || validationResult.score > bestValidationResult.score) { + bestValidationResult = validationResult + } + } + + if nbValidated != 1 { + + result.addInternalError(new(NumberOneOfError), context, currentNode, ErrorDetails{}) + + if nbValidated == 0 { + // add error messages of closest matching subSchema as + // that's probably the one the user was trying to match + result.mergeErrors(bestValidationResult) + } + } + + } + + if len(currentSubSchema.allOf) > 0 { + nbValidated := 0 + + for _, allOfSchema := range currentSubSchema.allOf { + validationResult := allOfSchema.subValidateWithContext(currentNode, context) + if validationResult.Valid() { + nbValidated++ + } + result.mergeErrors(validationResult) + } + + if nbValidated != len(currentSubSchema.allOf) { + result.addInternalError(new(NumberAllOfError), context, currentNode, ErrorDetails{}) + } + } + + if currentSubSchema.not != nil { + validationResult := currentSubSchema.not.subValidateWithContext(currentNode, context) + if validationResult.Valid() { + result.addInternalError(new(NumberNotError), context, currentNode, ErrorDetails{}) + } + } + + if currentSubSchema.dependencies != nil && len(currentSubSchema.dependencies) > 0 { + if isKind(currentNode, reflect.Map) { + for elementKey := range currentNode.(map[string]interface{}) { + if dependency, ok := currentSubSchema.dependencies[elementKey]; ok { + switch dependency := dependency.(type) { + + case []string: + for _, dependOnKey := range dependency { + if _, dependencyResolved := currentNode.(map[string]interface{})[dependOnKey]; !dependencyResolved { + result.addInternalError( + new(MissingDependencyError), + context, + currentNode, + ErrorDetails{"dependency": dependOnKey}, + ) + } + } + + case *subSchema: + dependency.validateRecursive(dependency, currentNode, result, context) + } + } + } + } + } + + if currentSubSchema._if != nil { + validationResultIf := currentSubSchema._if.subValidateWithContext(currentNode, context) + if currentSubSchema._then != nil && validationResultIf.Valid() { + validationResultThen := currentSubSchema._then.subValidateWithContext(currentNode, context) + if !validationResultThen.Valid() { + result.addInternalError(new(ConditionThenError), context, currentNode, ErrorDetails{}) + result.mergeErrors(validationResultThen) + } + } + if currentSubSchema._else != nil && !validationResultIf.Valid() { + validationResultElse := currentSubSchema._else.subValidateWithContext(currentNode, context) + if !validationResultElse.Valid() { + result.addInternalError(new(ConditionElseError), context, currentNode, ErrorDetails{}) + result.mergeErrors(validationResultElse) + } + } + } + + result.incrementScore() +} + +func (v *subSchema) validateCommon(currentSubSchema *subSchema, value interface{}, result *Result, context *JsonContext) { + + if internalLogEnabled { + internalLog("validateCommon %s", context.String()) + internalLog(" %v", value) + } + + // const: + if currentSubSchema._const != nil { + vString, err := marshalWithoutNumber(value) + if err != nil { + result.addInternalError(new(InternalError), context, value, ErrorDetails{"error": err}) + } + if *vString != *currentSubSchema._const { + result.addInternalError(new(ConstError), + context, + value, + ErrorDetails{ + "allowed": *currentSubSchema._const, + }, + ) + } + } + + // enum: + if len(currentSubSchema.enum) > 0 { + vString, err := marshalWithoutNumber(value) + if err != nil { + result.addInternalError(new(InternalError), context, value, ErrorDetails{"error": err}) + } + if !isStringInSlice(currentSubSchema.enum, *vString) { + result.addInternalError( + new(EnumError), + context, + value, + ErrorDetails{ + "allowed": strings.Join(currentSubSchema.enum, ", "), + }, + ) + } + } + + result.incrementScore() +} + +func (v *subSchema) validateArray(currentSubSchema *subSchema, value []interface{}, result *Result, context *JsonContext) { + + if internalLogEnabled { + internalLog("validateArray %s", context.String()) + internalLog(" %v", value) + } + + nbValues := len(value) + + // TODO explain + if currentSubSchema.itemsChildrenIsSingleSchema { + for i := range value { + subContext := NewJsonContext(strconv.Itoa(i), context) + validationResult := currentSubSchema.itemsChildren[0].subValidateWithContext(value[i], subContext) + result.mergeErrors(validationResult) + } + } else { + if currentSubSchema.itemsChildren != nil && len(currentSubSchema.itemsChildren) > 0 { + + nbItems := len(currentSubSchema.itemsChildren) + + // while we have both schemas and values, check them against each other + for i := 0; i != nbItems && i != nbValues; i++ { + subContext := NewJsonContext(strconv.Itoa(i), context) + validationResult := currentSubSchema.itemsChildren[i].subValidateWithContext(value[i], subContext) + result.mergeErrors(validationResult) + } + + if nbItems < nbValues { + // we have less schemas than elements in the instance array, + // but that might be ok if "additionalItems" is specified. + + switch currentSubSchema.additionalItems.(type) { + case bool: + if !currentSubSchema.additionalItems.(bool) { + result.addInternalError(new(ArrayNoAdditionalItemsError), context, value, ErrorDetails{}) + } + case *subSchema: + additionalItemSchema := currentSubSchema.additionalItems.(*subSchema) + for i := nbItems; i != nbValues; i++ { + subContext := NewJsonContext(strconv.Itoa(i), context) + validationResult := additionalItemSchema.subValidateWithContext(value[i], subContext) + result.mergeErrors(validationResult) + } + } + } + } + } + + // minItems & maxItems + if currentSubSchema.minItems != nil { + if nbValues < int(*currentSubSchema.minItems) { + result.addInternalError( + new(ArrayMinItemsError), + context, + value, + ErrorDetails{"min": *currentSubSchema.minItems}, + ) + } + } + if currentSubSchema.maxItems != nil { + if nbValues > int(*currentSubSchema.maxItems) { + result.addInternalError( + new(ArrayMaxItemsError), + context, + value, + ErrorDetails{"max": *currentSubSchema.maxItems}, + ) + } + } + + // uniqueItems: + if currentSubSchema.uniqueItems { + var stringifiedItems = make(map[string]int) + for j, v := range value { + vString, err := marshalWithoutNumber(v) + if err != nil { + result.addInternalError(new(InternalError), context, value, ErrorDetails{"err": err}) + } + if i, ok := stringifiedItems[*vString]; ok { + result.addInternalError( + new(ItemsMustBeUniqueError), + context, + value, + ErrorDetails{"type": TYPE_ARRAY, "i": i, "j": j}, + ) + } + stringifiedItems[*vString] = j + } + } + + // contains: + + if currentSubSchema.contains != nil { + validatedOne := false + var bestValidationResult *Result + + for i, v := range value { + subContext := NewJsonContext(strconv.Itoa(i), context) + + validationResult := currentSubSchema.contains.subValidateWithContext(v, subContext) + if validationResult.Valid() { + validatedOne = true + break + } else { + if bestValidationResult == nil || validationResult.score > bestValidationResult.score { + bestValidationResult = validationResult + } + } + } + if !validatedOne { + result.addInternalError( + new(ArrayContainsError), + context, + value, + ErrorDetails{}, + ) + if bestValidationResult != nil { + result.mergeErrors(bestValidationResult) + } + } + } + + result.incrementScore() +} + +func (v *subSchema) validateObject(currentSubSchema *subSchema, value map[string]interface{}, result *Result, context *JsonContext) { + + if internalLogEnabled { + internalLog("validateObject %s", context.String()) + internalLog(" %v", value) + } + + // minProperties & maxProperties: + if currentSubSchema.minProperties != nil { + if len(value) < int(*currentSubSchema.minProperties) { + result.addInternalError( + new(ArrayMinPropertiesError), + context, + value, + ErrorDetails{"min": *currentSubSchema.minProperties}, + ) + } + } + if currentSubSchema.maxProperties != nil { + if len(value) > int(*currentSubSchema.maxProperties) { + result.addInternalError( + new(ArrayMaxPropertiesError), + context, + value, + ErrorDetails{"max": *currentSubSchema.maxProperties}, + ) + } + } + + // required: + for _, requiredProperty := range currentSubSchema.required { + _, ok := value[requiredProperty] + if ok { + result.incrementScore() + } else { + result.addInternalError( + new(RequiredError), + context, + value, + ErrorDetails{"property": requiredProperty}, + ) + } + } + + // additionalProperty & patternProperty: + for pk := range value { + + // Check whether this property is described by "properties" + found := false + for _, spValue := range currentSubSchema.propertiesChildren { + if pk == spValue.property { + found = true + } + } + + // Check whether this property is described by "patternProperties" + ppMatch := v.validatePatternProperty(currentSubSchema, pk, value[pk], result, context) + + // If it is not described by neither "properties" nor "patternProperties" it must pass "additionalProperties" + if !found && !ppMatch { + switch ap := currentSubSchema.additionalProperties.(type) { + case bool: + // Handle the boolean case separately as it's cleaner to return a specific error than failing to pass the false schema + if !ap { + result.addInternalError( + new(AdditionalPropertyNotAllowedError), + context, + value[pk], + ErrorDetails{"property": pk}, + ) + + } + case *subSchema: + validationResult := ap.subValidateWithContext(value[pk], NewJsonContext(pk, context)) + result.mergeErrors(validationResult) + } + } + } + + // propertyNames: + if currentSubSchema.propertyNames != nil { + for pk := range value { + validationResult := currentSubSchema.propertyNames.subValidateWithContext(pk, context) + if !validationResult.Valid() { + result.addInternalError(new(InvalidPropertyNameError), + context, + value, ErrorDetails{ + "property": pk, + }) + result.mergeErrors(validationResult) + } + } + } + + result.incrementScore() +} + +func (v *subSchema) validatePatternProperty(currentSubSchema *subSchema, key string, value interface{}, result *Result, context *JsonContext) bool { + + if internalLogEnabled { + internalLog("validatePatternProperty %s", context.String()) + internalLog(" %s %v", key, value) + } + + validated := false + + for pk, pv := range currentSubSchema.patternProperties { + if matches, _ := regexp.MatchString(pk, key); matches { + validated = true + subContext := NewJsonContext(key, context) + validationResult := pv.subValidateWithContext(value, subContext) + result.mergeErrors(validationResult) + } + } + + if !validated { + return false + } + + result.incrementScore() + return true +} + +func (v *subSchema) validateString(currentSubSchema *subSchema, value interface{}, result *Result, context *JsonContext) { + + // Ignore JSON numbers + if isJSONNumber(value) { + return + } + + // Ignore non strings + if !isKind(value, reflect.String) { + return + } + + if internalLogEnabled { + internalLog("validateString %s", context.String()) + internalLog(" %v", value) + } + + stringValue := value.(string) + + // minLength & maxLength: + if currentSubSchema.minLength != nil { + if utf8.RuneCount([]byte(stringValue)) < int(*currentSubSchema.minLength) { + result.addInternalError( + new(StringLengthGTEError), + context, + value, + ErrorDetails{"min": *currentSubSchema.minLength}, + ) + } + } + if currentSubSchema.maxLength != nil { + if utf8.RuneCount([]byte(stringValue)) > int(*currentSubSchema.maxLength) { + result.addInternalError( + new(StringLengthLTEError), + context, + value, + ErrorDetails{"max": *currentSubSchema.maxLength}, + ) + } + } + + // pattern: + if currentSubSchema.pattern != nil { + if !currentSubSchema.pattern.MatchString(stringValue) { + result.addInternalError( + new(DoesNotMatchPatternError), + context, + value, + ErrorDetails{"pattern": currentSubSchema.pattern}, + ) + + } + } + + // format + if currentSubSchema.format != "" { + if !FormatCheckers.IsFormat(currentSubSchema.format, stringValue) { + result.addInternalError( + new(DoesNotMatchFormatError), + context, + value, + ErrorDetails{"format": currentSubSchema.format}, + ) + } + } + + result.incrementScore() +} + +func (v *subSchema) validateNumber(currentSubSchema *subSchema, value interface{}, result *Result, context *JsonContext) { + + // Ignore non numbers + if !isJSONNumber(value) { + return + } + + if internalLogEnabled { + internalLog("validateNumber %s", context.String()) + internalLog(" %v", value) + } + + number := value.(json.Number) + float64Value, _ := new(big.Rat).SetString(string(number)) + + // multipleOf: + if currentSubSchema.multipleOf != nil { + if q := new(big.Rat).Quo(float64Value, currentSubSchema.multipleOf); !q.IsInt() { + result.addInternalError( + new(MultipleOfError), + context, + number, + ErrorDetails{ + "multiple": new(big.Float).SetRat(currentSubSchema.multipleOf), + }, + ) + } + } + + //maximum & exclusiveMaximum: + if currentSubSchema.maximum != nil { + if float64Value.Cmp(currentSubSchema.maximum) == 1 { + result.addInternalError( + new(NumberLTEError), + context, + number, + ErrorDetails{ + "max": new(big.Float).SetRat(currentSubSchema.maximum), + }, + ) + } + } + if currentSubSchema.exclusiveMaximum != nil { + if float64Value.Cmp(currentSubSchema.exclusiveMaximum) >= 0 { + result.addInternalError( + new(NumberLTError), + context, + number, + ErrorDetails{ + "max": new(big.Float).SetRat(currentSubSchema.exclusiveMaximum), + }, + ) + } + } + + //minimum & exclusiveMinimum: + if currentSubSchema.minimum != nil { + if float64Value.Cmp(currentSubSchema.minimum) == -1 { + result.addInternalError( + new(NumberGTEError), + context, + number, + ErrorDetails{ + "min": new(big.Float).SetRat(currentSubSchema.minimum), + }, + ) + } + } + if currentSubSchema.exclusiveMinimum != nil { + if float64Value.Cmp(currentSubSchema.exclusiveMinimum) <= 0 { + result.addInternalError( + new(NumberGTError), + context, + number, + ErrorDetails{ + "min": new(big.Float).SetRat(currentSubSchema.exclusiveMinimum), + }, + ) + } + } + + // format + if currentSubSchema.format != "" { + if !FormatCheckers.IsFormat(currentSubSchema.format, float64Value) { + result.addInternalError( + new(DoesNotMatchFormatError), + context, + value, + ErrorDetails{"format": currentSubSchema.format}, + ) + } + } + + result.incrementScore() +} diff --git a/vendor/golang.org/x/crypto/md4/md4.go b/vendor/golang.org/x/crypto/md4/md4.go index 59d34806..d1911c2e 100644 --- a/vendor/golang.org/x/crypto/md4/md4.go +++ b/vendor/golang.org/x/crypto/md4/md4.go @@ -4,7 +4,7 @@ // Package md4 implements the MD4 hash algorithm as defined in RFC 1320. // -// Deprecated: MD4 is cryptographically broken and should should only be used +// Deprecated: MD4 is cryptographically broken and should only be used // where compatibility with legacy systems, not security, is the goal. Instead, // use a secure hash like SHA-256 (from crypto/sha256). package md4 // import "golang.org/x/crypto/md4" diff --git a/vendor/golang.org/x/crypto/ocsp/ocsp.go b/vendor/golang.org/x/crypto/ocsp/ocsp.go index 4269ed11..bf225953 100644 --- a/vendor/golang.org/x/crypto/ocsp/ocsp.go +++ b/vendor/golang.org/x/crypto/ocsp/ocsp.go @@ -279,21 +279,22 @@ func getOIDFromHashAlgorithm(target crypto.Hash) asn1.ObjectIdentifier { // This is the exposed reflection of the internal OCSP structures. -// The status values that can be expressed in OCSP. See RFC 6960. +// The status values that can be expressed in OCSP. See RFC 6960. +// These are used for the Response.Status field. const ( // Good means that the certificate is valid. - Good = iota + Good = 0 // Revoked means that the certificate has been deliberately revoked. - Revoked + Revoked = 1 // Unknown means that the OCSP responder doesn't know about the certificate. - Unknown + Unknown = 2 // ServerFailed is unused and was never used (see // https://go-review.googlesource.com/#/c/18944). ParseResponse will // return a ResponseError when an error response is parsed. - ServerFailed + ServerFailed = 3 ) -// The enumerated reasons for revoking a certificate. See RFC 5280. +// The enumerated reasons for revoking a certificate. See RFC 5280. const ( Unspecified = 0 KeyCompromise = 1 diff --git a/vendor/golang.org/x/net/html/token.go b/vendor/golang.org/x/net/html/token.go index de67f938..3c57880d 100644 --- a/vendor/golang.org/x/net/html/token.go +++ b/vendor/golang.org/x/net/html/token.go @@ -910,9 +910,6 @@ func (z *Tokenizer) readTagAttrKey() { return } switch c { - case ' ', '\n', '\r', '\t', '\f', '/': - z.pendingAttr[0].end = z.raw.end - 1 - return case '=': if z.pendingAttr[0].start+1 == z.raw.end { // WHATWG 13.2.5.32, if we see an equals sign before the attribute name @@ -920,7 +917,9 @@ func (z *Tokenizer) readTagAttrKey() { continue } fallthrough - case '>': + case ' ', '\n', '\r', '\t', '\f', '/', '>': + // WHATWG 13.2.5.33 Attribute name state + // We need to reconsume the char in the after attribute name state to support the / character z.raw.end-- z.pendingAttr[0].end = z.raw.end return @@ -939,6 +938,11 @@ func (z *Tokenizer) readTagAttrVal() { if z.err != nil { return } + if c == '/' { + // WHATWG 13.2.5.34 After attribute name state + // U+002F SOLIDUS (/) - Switch to the self-closing start tag state. + return + } if c != '=' { z.raw.end-- return diff --git a/vendor/golang.org/x/net/http2/frame.go b/vendor/golang.org/x/net/http2/frame.go index c1f6b90d..43557ab7 100644 --- a/vendor/golang.org/x/net/http2/frame.go +++ b/vendor/golang.org/x/net/http2/frame.go @@ -1510,13 +1510,12 @@ func (mh *MetaHeadersFrame) checkPseudos() error { } func (fr *Framer) maxHeaderStringLen() int { - v := fr.maxHeaderListSize() - if uint32(int(v)) == v { - return int(v) + v := int(fr.maxHeaderListSize()) + if v < 0 { + // If maxHeaderListSize overflows an int, use no limit (0). + return 0 } - // They had a crazy big number for MaxHeaderBytes anyway, - // so give them unlimited header lengths: - return 0 + return v } // readMetaFrame returns 0 or more CONTINUATION frames from fr and @@ -1565,6 +1564,7 @@ func (fr *Framer) readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error) { if size > remainSize { hdec.SetEmitEnabled(false) mh.Truncated = true + remainSize = 0 return } remainSize -= size @@ -1577,6 +1577,36 @@ func (fr *Framer) readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error) { var hc headersOrContinuation = hf for { frag := hc.HeaderBlockFragment() + + // Avoid parsing large amounts of headers that we will then discard. + // If the sender exceeds the max header list size by too much, + // skip parsing the fragment and close the connection. + // + // "Too much" is either any CONTINUATION frame after we've already + // exceeded the max header list size (in which case remainSize is 0), + // or a frame whose encoded size is more than twice the remaining + // header list bytes we're willing to accept. + if int64(len(frag)) > int64(2*remainSize) { + if VerboseLogs { + log.Printf("http2: header list too large") + } + // It would be nice to send a RST_STREAM before sending the GOAWAY, + // but the structure of the server's frame writer makes this difficult. + return nil, ConnectionError(ErrCodeProtocol) + } + + // Also close the connection after any CONTINUATION frame following an + // invalid header, since we stop tracking the size of the headers after + // an invalid one. + if invalid != nil { + if VerboseLogs { + log.Printf("http2: invalid header: %v", invalid) + } + // It would be nice to send a RST_STREAM before sending the GOAWAY, + // but the structure of the server's frame writer makes this difficult. + return nil, ConnectionError(ErrCodeProtocol) + } + if _, err := hdec.Write(frag); err != nil { return nil, ConnectionError(ErrCodeCompression) } diff --git a/vendor/golang.org/x/net/http2/pipe.go b/vendor/golang.org/x/net/http2/pipe.go index 684d984f..3b9f06b9 100644 --- a/vendor/golang.org/x/net/http2/pipe.go +++ b/vendor/golang.org/x/net/http2/pipe.go @@ -77,7 +77,10 @@ func (p *pipe) Read(d []byte) (n int, err error) { } } -var errClosedPipeWrite = errors.New("write on closed buffer") +var ( + errClosedPipeWrite = errors.New("write on closed buffer") + errUninitializedPipeWrite = errors.New("write on uninitialized buffer") +) // Write copies bytes from p into the buffer and wakes a reader. // It is an error to write more data than the buffer can hold. @@ -91,6 +94,12 @@ func (p *pipe) Write(d []byte) (n int, err error) { if p.err != nil || p.breakErr != nil { return 0, errClosedPipeWrite } + // pipe.setBuffer is never invoked, leaving the buffer uninitialized. + // We shouldn't try to write to an uninitialized pipe, + // but returning an error is better than panicking. + if p.b == nil { + return 0, errUninitializedPipeWrite + } return p.b.Write(d) } diff --git a/vendor/golang.org/x/net/http2/server.go b/vendor/golang.org/x/net/http2/server.go index ae94c640..ce2e8b40 100644 --- a/vendor/golang.org/x/net/http2/server.go +++ b/vendor/golang.org/x/net/http2/server.go @@ -124,6 +124,7 @@ type Server struct { // IdleTimeout specifies how long until idle clients should be // closed with a GOAWAY frame. PING frames are not considered // activity for the purposes of IdleTimeout. + // If zero or negative, there is no timeout. IdleTimeout time.Duration // MaxUploadBufferPerConnection is the size of the initial flow @@ -434,7 +435,7 @@ func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) { // passes the connection off to us with the deadline already set. // Write deadlines are set per stream in serverConn.newStream. // Disarm the net.Conn write deadline here. - if sc.hs.WriteTimeout != 0 { + if sc.hs.WriteTimeout > 0 { sc.conn.SetWriteDeadline(time.Time{}) } @@ -924,7 +925,7 @@ func (sc *serverConn) serve() { sc.setConnState(http.StateActive) sc.setConnState(http.StateIdle) - if sc.srv.IdleTimeout != 0 { + if sc.srv.IdleTimeout > 0 { sc.idleTimer = time.AfterFunc(sc.srv.IdleTimeout, sc.onIdleTimer) defer sc.idleTimer.Stop() } @@ -1637,7 +1638,7 @@ func (sc *serverConn) closeStream(st *stream, err error) { delete(sc.streams, st.id) if len(sc.streams) == 0 { sc.setConnState(http.StateIdle) - if sc.srv.IdleTimeout != 0 { + if sc.srv.IdleTimeout > 0 { sc.idleTimer.Reset(sc.srv.IdleTimeout) } if h1ServerKeepAlivesDisabled(sc.hs) { @@ -2017,7 +2018,7 @@ func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error { // similar to how the http1 server works. Here it's // technically more like the http1 Server's ReadHeaderTimeout // (in Go 1.8), though. That's a more sane option anyway. - if sc.hs.ReadTimeout != 0 { + if sc.hs.ReadTimeout > 0 { sc.conn.SetReadDeadline(time.Time{}) st.readDeadline = time.AfterFunc(sc.hs.ReadTimeout, st.onReadTimeout) } @@ -2038,7 +2039,7 @@ func (sc *serverConn) upgradeRequest(req *http.Request) { // Disable any read deadline set by the net/http package // prior to the upgrade. - if sc.hs.ReadTimeout != 0 { + if sc.hs.ReadTimeout > 0 { sc.conn.SetReadDeadline(time.Time{}) } @@ -2116,7 +2117,7 @@ func (sc *serverConn) newStream(id, pusherID uint32, state streamState) *stream st.flow.conn = &sc.flow // link to conn-level counter st.flow.add(sc.initialStreamSendWindowSize) st.inflow.init(sc.srv.initialStreamRecvWindowSize()) - if sc.hs.WriteTimeout != 0 { + if sc.hs.WriteTimeout > 0 { st.writeDeadline = time.AfterFunc(sc.hs.WriteTimeout, st.onWriteTimeout) } diff --git a/vendor/golang.org/x/net/http2/testsync.go b/vendor/golang.org/x/net/http2/testsync.go new file mode 100644 index 00000000..61075bd1 --- /dev/null +++ b/vendor/golang.org/x/net/http2/testsync.go @@ -0,0 +1,331 @@ +// Copyright 2024 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 http2 + +import ( + "context" + "sync" + "time" +) + +// testSyncHooks coordinates goroutines in tests. +// +// For example, a call to ClientConn.RoundTrip involves several goroutines, including: +// - the goroutine running RoundTrip; +// - the clientStream.doRequest goroutine, which writes the request; and +// - the clientStream.readLoop goroutine, which reads the response. +// +// Using testSyncHooks, a test can start a RoundTrip and identify when all these goroutines +// are blocked waiting for some condition such as reading the Request.Body or waiting for +// flow control to become available. +// +// The testSyncHooks also manage timers and synthetic time in tests. +// This permits us to, for example, start a request and cause it to time out waiting for +// response headers without resorting to time.Sleep calls. +type testSyncHooks struct { + // active/inactive act as a mutex and condition variable. + // + // - neither chan contains a value: testSyncHooks is locked. + // - active contains a value: unlocked, and at least one goroutine is not blocked + // - inactive contains a value: unlocked, and all goroutines are blocked + active chan struct{} + inactive chan struct{} + + // goroutine counts + total int // total goroutines + condwait map[*sync.Cond]int // blocked in sync.Cond.Wait + blocked []*testBlockedGoroutine // otherwise blocked + + // fake time + now time.Time + timers []*fakeTimer + + // Transport testing: Report various events. + newclientconn func(*ClientConn) + newstream func(*clientStream) +} + +// testBlockedGoroutine is a blocked goroutine. +type testBlockedGoroutine struct { + f func() bool // blocked until f returns true + ch chan struct{} // closed when unblocked +} + +func newTestSyncHooks() *testSyncHooks { + h := &testSyncHooks{ + active: make(chan struct{}, 1), + inactive: make(chan struct{}, 1), + condwait: map[*sync.Cond]int{}, + } + h.inactive <- struct{}{} + h.now = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC) + return h +} + +// lock acquires the testSyncHooks mutex. +func (h *testSyncHooks) lock() { + select { + case <-h.active: + case <-h.inactive: + } +} + +// waitInactive waits for all goroutines to become inactive. +func (h *testSyncHooks) waitInactive() { + for { + <-h.inactive + if !h.unlock() { + break + } + } +} + +// unlock releases the testSyncHooks mutex. +// It reports whether any goroutines are active. +func (h *testSyncHooks) unlock() (active bool) { + // Look for a blocked goroutine which can be unblocked. + blocked := h.blocked[:0] + unblocked := false + for _, b := range h.blocked { + if !unblocked && b.f() { + unblocked = true + close(b.ch) + } else { + blocked = append(blocked, b) + } + } + h.blocked = blocked + + // Count goroutines blocked on condition variables. + condwait := 0 + for _, count := range h.condwait { + condwait += count + } + + if h.total > condwait+len(blocked) { + h.active <- struct{}{} + return true + } else { + h.inactive <- struct{}{} + return false + } +} + +// goRun starts a new goroutine. +func (h *testSyncHooks) goRun(f func()) { + h.lock() + h.total++ + h.unlock() + go func() { + defer func() { + h.lock() + h.total-- + h.unlock() + }() + f() + }() +} + +// blockUntil indicates that a goroutine is blocked waiting for some condition to become true. +// It waits until f returns true before proceeding. +// +// Example usage: +// +// h.blockUntil(func() bool { +// // Is the context done yet? +// select { +// case <-ctx.Done(): +// default: +// return false +// } +// return true +// }) +// // Wait for the context to become done. +// <-ctx.Done() +// +// The function f passed to blockUntil must be non-blocking and idempotent. +func (h *testSyncHooks) blockUntil(f func() bool) { + if f() { + return + } + ch := make(chan struct{}) + h.lock() + h.blocked = append(h.blocked, &testBlockedGoroutine{ + f: f, + ch: ch, + }) + h.unlock() + <-ch +} + +// broadcast is sync.Cond.Broadcast. +func (h *testSyncHooks) condBroadcast(cond *sync.Cond) { + h.lock() + delete(h.condwait, cond) + h.unlock() + cond.Broadcast() +} + +// broadcast is sync.Cond.Wait. +func (h *testSyncHooks) condWait(cond *sync.Cond) { + h.lock() + h.condwait[cond]++ + h.unlock() +} + +// newTimer creates a new fake timer. +func (h *testSyncHooks) newTimer(d time.Duration) timer { + h.lock() + defer h.unlock() + t := &fakeTimer{ + hooks: h, + when: h.now.Add(d), + c: make(chan time.Time), + } + h.timers = append(h.timers, t) + return t +} + +// afterFunc creates a new fake AfterFunc timer. +func (h *testSyncHooks) afterFunc(d time.Duration, f func()) timer { + h.lock() + defer h.unlock() + t := &fakeTimer{ + hooks: h, + when: h.now.Add(d), + f: f, + } + h.timers = append(h.timers, t) + return t +} + +func (h *testSyncHooks) contextWithTimeout(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) { + ctx, cancel := context.WithCancel(ctx) + t := h.afterFunc(d, cancel) + return ctx, func() { + t.Stop() + cancel() + } +} + +func (h *testSyncHooks) timeUntilEvent() time.Duration { + h.lock() + defer h.unlock() + var next time.Time + for _, t := range h.timers { + if next.IsZero() || t.when.Before(next) { + next = t.when + } + } + if d := next.Sub(h.now); d > 0 { + return d + } + return 0 +} + +// advance advances time and causes synthetic timers to fire. +func (h *testSyncHooks) advance(d time.Duration) { + h.lock() + defer h.unlock() + h.now = h.now.Add(d) + timers := h.timers[:0] + for _, t := range h.timers { + t := t // remove after go.mod depends on go1.22 + t.mu.Lock() + switch { + case t.when.After(h.now): + timers = append(timers, t) + case t.when.IsZero(): + // stopped timer + default: + t.when = time.Time{} + if t.c != nil { + close(t.c) + } + if t.f != nil { + h.total++ + go func() { + defer func() { + h.lock() + h.total-- + h.unlock() + }() + t.f() + }() + } + } + t.mu.Unlock() + } + h.timers = timers +} + +// A timer wraps a time.Timer, or a synthetic equivalent in tests. +// Unlike time.Timer, timer is single-use: The timer channel is closed when the timer expires. +type timer interface { + C() <-chan time.Time + Stop() bool + Reset(d time.Duration) bool +} + +// timeTimer implements timer using real time. +type timeTimer struct { + t *time.Timer + c chan time.Time +} + +// newTimeTimer creates a new timer using real time. +func newTimeTimer(d time.Duration) timer { + ch := make(chan time.Time) + t := time.AfterFunc(d, func() { + close(ch) + }) + return &timeTimer{t, ch} +} + +// newTimeAfterFunc creates an AfterFunc timer using real time. +func newTimeAfterFunc(d time.Duration, f func()) timer { + return &timeTimer{ + t: time.AfterFunc(d, f), + } +} + +func (t timeTimer) C() <-chan time.Time { return t.c } +func (t timeTimer) Stop() bool { return t.t.Stop() } +func (t timeTimer) Reset(d time.Duration) bool { return t.t.Reset(d) } + +// fakeTimer implements timer using fake time. +type fakeTimer struct { + hooks *testSyncHooks + + mu sync.Mutex + when time.Time // when the timer will fire + c chan time.Time // closed when the timer fires; mutually exclusive with f + f func() // called when the timer fires; mutually exclusive with c +} + +func (t *fakeTimer) C() <-chan time.Time { return t.c } + +func (t *fakeTimer) Stop() bool { + t.mu.Lock() + defer t.mu.Unlock() + stopped := t.when.IsZero() + t.when = time.Time{} + return stopped +} + +func (t *fakeTimer) Reset(d time.Duration) bool { + if t.c != nil || t.f == nil { + panic("fakeTimer only supports Reset on AfterFunc timers") + } + t.mu.Lock() + defer t.mu.Unlock() + t.hooks.lock() + defer t.hooks.unlock() + active := !t.when.IsZero() + t.when = t.hooks.now.Add(d) + if !active { + t.hooks.timers = append(t.hooks.timers, t) + } + return active +} diff --git a/vendor/golang.org/x/net/http2/transport.go b/vendor/golang.org/x/net/http2/transport.go index df578b86..ce375c8c 100644 --- a/vendor/golang.org/x/net/http2/transport.go +++ b/vendor/golang.org/x/net/http2/transport.go @@ -147,6 +147,12 @@ type Transport struct { // waiting for their turn. StrictMaxConcurrentStreams bool + // IdleConnTimeout is the maximum amount of time an idle + // (keep-alive) connection will remain idle before closing + // itself. + // Zero means no limit. + IdleConnTimeout time.Duration + // ReadIdleTimeout is the timeout after which a health check using ping // frame will be carried out if no frame is received on the connection. // Note that a ping response will is considered a received frame, so if @@ -178,6 +184,8 @@ type Transport struct { connPoolOnce sync.Once connPoolOrDef ClientConnPool // non-nil version of ConnPool + + syncHooks *testSyncHooks } func (t *Transport) maxHeaderListSize() uint32 { @@ -302,7 +310,7 @@ type ClientConn struct { readerErr error // set before readerDone is closed idleTimeout time.Duration // or 0 for never - idleTimer *time.Timer + idleTimer timer mu sync.Mutex // guards following cond *sync.Cond // hold mu; broadcast on flow/closed changes @@ -344,6 +352,60 @@ type ClientConn struct { werr error // first write error that has occurred hbuf bytes.Buffer // HPACK encoder writes into this henc *hpack.Encoder + + syncHooks *testSyncHooks // can be nil +} + +// Hook points used for testing. +// Outside of tests, cc.syncHooks is nil and these all have minimal implementations. +// Inside tests, see the testSyncHooks function docs. + +// goRun starts a new goroutine. +func (cc *ClientConn) goRun(f func()) { + if cc.syncHooks != nil { + cc.syncHooks.goRun(f) + return + } + go f() +} + +// condBroadcast is cc.cond.Broadcast. +func (cc *ClientConn) condBroadcast() { + if cc.syncHooks != nil { + cc.syncHooks.condBroadcast(cc.cond) + } + cc.cond.Broadcast() +} + +// condWait is cc.cond.Wait. +func (cc *ClientConn) condWait() { + if cc.syncHooks != nil { + cc.syncHooks.condWait(cc.cond) + } + cc.cond.Wait() +} + +// newTimer creates a new time.Timer, or a synthetic timer in tests. +func (cc *ClientConn) newTimer(d time.Duration) timer { + if cc.syncHooks != nil { + return cc.syncHooks.newTimer(d) + } + return newTimeTimer(d) +} + +// afterFunc creates a new time.AfterFunc timer, or a synthetic timer in tests. +func (cc *ClientConn) afterFunc(d time.Duration, f func()) timer { + if cc.syncHooks != nil { + return cc.syncHooks.afterFunc(d, f) + } + return newTimeAfterFunc(d, f) +} + +func (cc *ClientConn) contextWithTimeout(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) { + if cc.syncHooks != nil { + return cc.syncHooks.contextWithTimeout(ctx, d) + } + return context.WithTimeout(ctx, d) } // clientStream is the state for a single HTTP/2 stream. One of these @@ -425,7 +487,7 @@ func (cs *clientStream) abortStreamLocked(err error) { // TODO(dneil): Clean up tests where cs.cc.cond is nil. if cs.cc.cond != nil { // Wake up writeRequestBody if it is waiting on flow control. - cs.cc.cond.Broadcast() + cs.cc.condBroadcast() } } @@ -435,7 +497,7 @@ func (cs *clientStream) abortRequestBodyWrite() { defer cc.mu.Unlock() if cs.reqBody != nil && cs.reqBodyClosed == nil { cs.closeReqBodyLocked() - cc.cond.Broadcast() + cc.condBroadcast() } } @@ -445,10 +507,10 @@ func (cs *clientStream) closeReqBodyLocked() { } cs.reqBodyClosed = make(chan struct{}) reqBodyClosed := cs.reqBodyClosed - go func() { + cs.cc.goRun(func() { cs.reqBody.Close() close(reqBodyClosed) - }() + }) } type stickyErrWriter struct { @@ -537,15 +599,6 @@ func authorityAddr(scheme string, authority string) (addr string) { return net.JoinHostPort(host, port) } -var retryBackoffHook func(time.Duration) *time.Timer - -func backoffNewTimer(d time.Duration) *time.Timer { - if retryBackoffHook != nil { - return retryBackoffHook(d) - } - return time.NewTimer(d) -} - // RoundTripOpt is like RoundTrip, but takes options. func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) { if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) { @@ -573,13 +626,27 @@ func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Res backoff := float64(uint(1) << (uint(retry) - 1)) backoff += backoff * (0.1 * mathrand.Float64()) d := time.Second * time.Duration(backoff) - timer := backoffNewTimer(d) + var tm timer + if t.syncHooks != nil { + tm = t.syncHooks.newTimer(d) + t.syncHooks.blockUntil(func() bool { + select { + case <-tm.C(): + case <-req.Context().Done(): + default: + return false + } + return true + }) + } else { + tm = newTimeTimer(d) + } select { - case <-timer.C: + case <-tm.C(): t.vlogf("RoundTrip retrying after failure: %v", roundTripErr) continue case <-req.Context().Done(): - timer.Stop() + tm.Stop() err = req.Context().Err() } } @@ -658,6 +725,9 @@ func canRetryError(err error) bool { } func (t *Transport) dialClientConn(ctx context.Context, addr string, singleUse bool) (*ClientConn, error) { + if t.syncHooks != nil { + return t.newClientConn(nil, singleUse, t.syncHooks) + } host, _, err := net.SplitHostPort(addr) if err != nil { return nil, err @@ -666,7 +736,7 @@ func (t *Transport) dialClientConn(ctx context.Context, addr string, singleUse b if err != nil { return nil, err } - return t.newClientConn(tconn, singleUse) + return t.newClientConn(tconn, singleUse, nil) } func (t *Transport) newTLSConfig(host string) *tls.Config { @@ -732,10 +802,10 @@ func (t *Transport) maxEncoderHeaderTableSize() uint32 { } func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) { - return t.newClientConn(c, t.disableKeepAlives()) + return t.newClientConn(c, t.disableKeepAlives(), nil) } -func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error) { +func (t *Transport) newClientConn(c net.Conn, singleUse bool, hooks *testSyncHooks) (*ClientConn, error) { cc := &ClientConn{ t: t, tconn: c, @@ -750,10 +820,15 @@ func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, erro wantSettingsAck: true, pings: make(map[[8]byte]chan struct{}), reqHeaderMu: make(chan struct{}, 1), + syncHooks: hooks, + } + if hooks != nil { + hooks.newclientconn(cc) + c = cc.tconn } if d := t.idleConnTimeout(); d != 0 { cc.idleTimeout = d - cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout) + cc.idleTimer = cc.afterFunc(d, cc.onIdleTimeout) } if VerboseLogs { t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr()) @@ -818,7 +893,7 @@ func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, erro return nil, cc.werr } - go cc.readLoop() + cc.goRun(cc.readLoop) return cc, nil } @@ -826,7 +901,7 @@ func (cc *ClientConn) healthCheck() { pingTimeout := cc.t.pingTimeout() // We don't need to periodically ping in the health check, because the readLoop of ClientConn will // trigger the healthCheck again if there is no frame received. - ctx, cancel := context.WithTimeout(context.Background(), pingTimeout) + ctx, cancel := cc.contextWithTimeout(context.Background(), pingTimeout) defer cancel() cc.vlogf("http2: Transport sending health check") err := cc.Ping(ctx) @@ -1056,7 +1131,7 @@ func (cc *ClientConn) Shutdown(ctx context.Context) error { // Wait for all in-flight streams to complete or connection to close done := make(chan struct{}) cancelled := false // guarded by cc.mu - go func() { + cc.goRun(func() { cc.mu.Lock() defer cc.mu.Unlock() for { @@ -1068,9 +1143,9 @@ func (cc *ClientConn) Shutdown(ctx context.Context) error { if cancelled { break } - cc.cond.Wait() + cc.condWait() } - }() + }) shutdownEnterWaitStateHook() select { case <-done: @@ -1080,7 +1155,7 @@ func (cc *ClientConn) Shutdown(ctx context.Context) error { cc.mu.Lock() // Free the goroutine above cancelled = true - cc.cond.Broadcast() + cc.condBroadcast() cc.mu.Unlock() return ctx.Err() } @@ -1118,7 +1193,7 @@ func (cc *ClientConn) closeForError(err error) { for _, cs := range cc.streams { cs.abortStreamLocked(err) } - cc.cond.Broadcast() + cc.condBroadcast() cc.mu.Unlock() cc.closeConn() } @@ -1215,6 +1290,10 @@ func (cc *ClientConn) decrStreamReservationsLocked() { } func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { + return cc.roundTrip(req, nil) +} + +func (cc *ClientConn) roundTrip(req *http.Request, streamf func(*clientStream)) (*http.Response, error) { ctx := req.Context() cs := &clientStream{ cc: cc, @@ -1229,9 +1308,23 @@ func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { respHeaderRecv: make(chan struct{}), donec: make(chan struct{}), } - go cs.doRequest(req) + cc.goRun(func() { + cs.doRequest(req) + }) waitDone := func() error { + if cc.syncHooks != nil { + cc.syncHooks.blockUntil(func() bool { + select { + case <-cs.donec: + case <-ctx.Done(): + case <-cs.reqCancel: + default: + return false + } + return true + }) + } select { case <-cs.donec: return nil @@ -1292,7 +1385,24 @@ func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { return err } + if streamf != nil { + streamf(cs) + } + for { + if cc.syncHooks != nil { + cc.syncHooks.blockUntil(func() bool { + select { + case <-cs.respHeaderRecv: + case <-cs.abort: + case <-ctx.Done(): + case <-cs.reqCancel: + default: + return false + } + return true + }) + } select { case <-cs.respHeaderRecv: return handleResponseHeaders() @@ -1348,6 +1458,21 @@ func (cs *clientStream) writeRequest(req *http.Request) (err error) { if cc.reqHeaderMu == nil { panic("RoundTrip on uninitialized ClientConn") // for tests } + var newStreamHook func(*clientStream) + if cc.syncHooks != nil { + newStreamHook = cc.syncHooks.newstream + cc.syncHooks.blockUntil(func() bool { + select { + case cc.reqHeaderMu <- struct{}{}: + <-cc.reqHeaderMu + case <-cs.reqCancel: + case <-ctx.Done(): + default: + return false + } + return true + }) + } select { case cc.reqHeaderMu <- struct{}{}: case <-cs.reqCancel: @@ -1372,6 +1497,10 @@ func (cs *clientStream) writeRequest(req *http.Request) (err error) { } cc.mu.Unlock() + if newStreamHook != nil { + newStreamHook(cs) + } + // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere? if !cc.t.disableCompression() && req.Header.Get("Accept-Encoding") == "" && @@ -1452,15 +1581,30 @@ func (cs *clientStream) writeRequest(req *http.Request) (err error) { var respHeaderTimer <-chan time.Time var respHeaderRecv chan struct{} if d := cc.responseHeaderTimeout(); d != 0 { - timer := time.NewTimer(d) + timer := cc.newTimer(d) defer timer.Stop() - respHeaderTimer = timer.C + respHeaderTimer = timer.C() respHeaderRecv = cs.respHeaderRecv } // Wait until the peer half-closes its end of the stream, // or until the request is aborted (via context, error, or otherwise), // whichever comes first. for { + if cc.syncHooks != nil { + cc.syncHooks.blockUntil(func() bool { + select { + case <-cs.peerClosed: + case <-respHeaderTimer: + case <-respHeaderRecv: + case <-cs.abort: + case <-ctx.Done(): + case <-cs.reqCancel: + default: + return false + } + return true + }) + } select { case <-cs.peerClosed: return nil @@ -1609,7 +1753,7 @@ func (cc *ClientConn) awaitOpenSlotForStreamLocked(cs *clientStream) error { return nil } cc.pendingRequests++ - cc.cond.Wait() + cc.condWait() cc.pendingRequests-- select { case <-cs.abort: @@ -1871,8 +2015,24 @@ func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) cs.flow.take(take) return take, nil } - cc.cond.Wait() + cc.condWait() + } +} + +func validateHeaders(hdrs http.Header) string { + for k, vv := range hdrs { + if !httpguts.ValidHeaderFieldName(k) { + return fmt.Sprintf("name %q", k) + } + for _, v := range vv { + if !httpguts.ValidHeaderFieldValue(v) { + // Don't include the value in the error, + // because it may be sensitive. + return fmt.Sprintf("value for header %q", k) + } + } } + return "" } var errNilRequestURL = errors.New("http2: Request.URI is nil") @@ -1912,19 +2072,14 @@ func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trail } } - // Check for any invalid headers and return an error before we + // Check for any invalid headers+trailers and return an error before we // potentially pollute our hpack state. (We want to be able to // continue to reuse the hpack encoder for future requests) - for k, vv := range req.Header { - if !httpguts.ValidHeaderFieldName(k) { - return nil, fmt.Errorf("invalid HTTP header name %q", k) - } - for _, v := range vv { - if !httpguts.ValidHeaderFieldValue(v) { - // Don't include the value in the error, because it may be sensitive. - return nil, fmt.Errorf("invalid HTTP header value for header %q", k) - } - } + if err := validateHeaders(req.Header); err != "" { + return nil, fmt.Errorf("invalid HTTP header %s", err) + } + if err := validateHeaders(req.Trailer); err != "" { + return nil, fmt.Errorf("invalid HTTP trailer %s", err) } enumerateHeaders := func(f func(name, value string)) { @@ -2143,7 +2298,7 @@ func (cc *ClientConn) forgetStreamID(id uint32) { } // Wake up writeRequestBody via clientStream.awaitFlowControl and // wake up RoundTrip if there is a pending request. - cc.cond.Broadcast() + cc.condBroadcast() closeOnIdle := cc.singleUse || cc.doNotReuse || cc.t.disableKeepAlives() || cc.goAway != nil if closeOnIdle && cc.streamsReserved == 0 && len(cc.streams) == 0 { @@ -2231,7 +2386,7 @@ func (rl *clientConnReadLoop) cleanup() { cs.abortStreamLocked(err) } } - cc.cond.Broadcast() + cc.condBroadcast() cc.mu.Unlock() } @@ -2266,10 +2421,9 @@ func (rl *clientConnReadLoop) run() error { cc := rl.cc gotSettings := false readIdleTimeout := cc.t.ReadIdleTimeout - var t *time.Timer + var t timer if readIdleTimeout != 0 { - t = time.AfterFunc(readIdleTimeout, cc.healthCheck) - defer t.Stop() + t = cc.afterFunc(readIdleTimeout, cc.healthCheck) } for { f, err := cc.fr.ReadFrame() @@ -2684,7 +2838,7 @@ func (rl *clientConnReadLoop) processData(f *DataFrame) error { }) return nil } - if !cs.firstByte { + if !cs.pastHeaders { cc.logf("protocol error: received DATA before a HEADERS frame") rl.endStreamError(cs, StreamError{ StreamID: f.StreamID, @@ -2867,7 +3021,7 @@ func (rl *clientConnReadLoop) processSettingsNoWrite(f *SettingsFrame) error { for _, cs := range cc.streams { cs.flow.add(delta) } - cc.cond.Broadcast() + cc.condBroadcast() cc.initialWindowSize = s.Val case SettingHeaderTableSize: @@ -2911,9 +3065,18 @@ func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error { fl = &cs.flow } if !fl.add(int32(f.Increment)) { + // For stream, the sender sends RST_STREAM with an error code of FLOW_CONTROL_ERROR + if cs != nil { + rl.endStreamError(cs, StreamError{ + StreamID: f.StreamID, + Code: ErrCodeFlowControl, + }) + return nil + } + return ConnectionError(ErrCodeFlowControl) } - cc.cond.Broadcast() + cc.condBroadcast() return nil } @@ -2955,24 +3118,38 @@ func (cc *ClientConn) Ping(ctx context.Context) error { } cc.mu.Unlock() } - errc := make(chan error, 1) - go func() { + var pingError error + errc := make(chan struct{}) + cc.goRun(func() { cc.wmu.Lock() defer cc.wmu.Unlock() - if err := cc.fr.WritePing(false, p); err != nil { - errc <- err + if pingError = cc.fr.WritePing(false, p); pingError != nil { + close(errc) return } - if err := cc.bw.Flush(); err != nil { - errc <- err + if pingError = cc.bw.Flush(); pingError != nil { + close(errc) return } - }() + }) + if cc.syncHooks != nil { + cc.syncHooks.blockUntil(func() bool { + select { + case <-c: + case <-errc: + case <-ctx.Done(): + case <-cc.readerDone: + default: + return false + } + return true + }) + } select { case <-c: return nil - case err := <-errc: - return err + case <-errc: + return pingError case <-ctx.Done(): return ctx.Err() case <-cc.readerDone: @@ -3141,9 +3318,17 @@ func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, err } func (t *Transport) idleConnTimeout() time.Duration { + // to keep things backwards compatible, we use non-zero values of + // IdleConnTimeout, followed by using the IdleConnTimeout on the underlying + // http1 transport, followed by 0 + if t.IdleConnTimeout != 0 { + return t.IdleConnTimeout + } + if t.t1 != nil { return t.t1.IdleConnTimeout } + return 0 } diff --git a/vendor/golang.org/x/sync/LICENSE b/vendor/golang.org/x/sync/LICENSE index 6a66aea5..2a7cf70d 100644 --- a/vendor/golang.org/x/sync/LICENSE +++ b/vendor/golang.org/x/sync/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. +Copyright 2009 The Go Authors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Google Inc. nor the names of its + * Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. diff --git a/vendor/golang.org/x/sync/errgroup/errgroup.go b/vendor/golang.org/x/sync/errgroup/errgroup.go index b18efb74..948a3ee6 100644 --- a/vendor/golang.org/x/sync/errgroup/errgroup.go +++ b/vendor/golang.org/x/sync/errgroup/errgroup.go @@ -4,6 +4,9 @@ // Package errgroup provides synchronization, error propagation, and Context // cancelation for groups of goroutines working on subtasks of a common task. +// +// [errgroup.Group] is related to [sync.WaitGroup] but adds handling of tasks +// returning errors. package errgroup import ( diff --git a/vendor/golang.org/x/sync/semaphore/semaphore.go b/vendor/golang.org/x/sync/semaphore/semaphore.go index 30f632c5..b618162a 100644 --- a/vendor/golang.org/x/sync/semaphore/semaphore.go +++ b/vendor/golang.org/x/sync/semaphore/semaphore.go @@ -35,11 +35,25 @@ type Weighted struct { // Acquire acquires the semaphore with a weight of n, blocking until resources // are available or ctx is done. On success, returns nil. On failure, returns // ctx.Err() and leaves the semaphore unchanged. -// -// If ctx is already done, Acquire may still succeed without blocking. func (s *Weighted) Acquire(ctx context.Context, n int64) error { + done := ctx.Done() + s.mu.Lock() + select { + case <-done: + // ctx becoming done has "happened before" acquiring the semaphore, + // whether it became done before the call began or while we were + // waiting for the mutex. We prefer to fail even if we could acquire + // the mutex without blocking. + s.mu.Unlock() + return ctx.Err() + default: + } if s.size-s.cur >= n && s.waiters.Len() == 0 { + // Since we hold s.mu and haven't synchronized since checking done, if + // ctx becomes done before we return here, it becoming done must have + // "happened concurrently" with this call - it cannot "happen before" + // we return in this branch. So, we're ok to always acquire here. s.cur += n s.mu.Unlock() return nil @@ -48,7 +62,7 @@ func (s *Weighted) Acquire(ctx context.Context, n int64) error { if n > s.size { // Don't make other Acquire calls block on one that's doomed to fail. s.mu.Unlock() - <-ctx.Done() + <-done return ctx.Err() } @@ -58,14 +72,14 @@ func (s *Weighted) Acquire(ctx context.Context, n int64) error { s.mu.Unlock() select { - case <-ctx.Done(): - err := ctx.Err() + case <-done: s.mu.Lock() select { case <-ready: - // Acquired the semaphore after we were canceled. Rather than trying to - // fix up the queue, just pretend we didn't notice the cancelation. - err = nil + // Acquired the semaphore after we were canceled. + // Pretend we didn't and put the tokens back. + s.cur -= n + s.notifyWaiters() default: isFront := s.waiters.Front() == elem s.waiters.Remove(elem) @@ -75,9 +89,19 @@ func (s *Weighted) Acquire(ctx context.Context, n int64) error { } } s.mu.Unlock() - return err + return ctx.Err() case <-ready: + // Acquired the semaphore. Check that ctx isn't already done. + // We check the done channel instead of calling ctx.Err because we + // already have the channel, and ctx.Err is O(n) with the nesting + // depth of ctx. + select { + case <-done: + s.Release(n) + return ctx.Err() + default: + } return nil } } diff --git a/vendor/golang.org/x/sys/LICENSE b/vendor/golang.org/x/sys/LICENSE index 6a66aea5..2a7cf70d 100644 --- a/vendor/golang.org/x/sys/LICENSE +++ b/vendor/golang.org/x/sys/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. +Copyright 2009 The Go Authors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Google Inc. nor the names of its + * Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. diff --git a/vendor/golang.org/x/sys/cpu/asm_darwin_x86_gc.s b/vendor/golang.org/x/sys/cpu/asm_darwin_x86_gc.s new file mode 100644 index 00000000..ec2acfe5 --- /dev/null +++ b/vendor/golang.org/x/sys/cpu/asm_darwin_x86_gc.s @@ -0,0 +1,17 @@ +// Copyright 2024 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. + +//go:build darwin && amd64 && gc + +#include "textflag.h" + +TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_sysctl(SB) +GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 +DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) + +TEXT libc_sysctlbyname_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_sysctlbyname(SB) +GLOBL ·libc_sysctlbyname_trampoline_addr(SB), RODATA, $8 +DATA ·libc_sysctlbyname_trampoline_addr(SB)/8, $libc_sysctlbyname_trampoline<>(SB) diff --git a/vendor/golang.org/x/sys/cpu/cpu.go b/vendor/golang.org/x/sys/cpu/cpu.go index 4756ad5f..02609d5b 100644 --- a/vendor/golang.org/x/sys/cpu/cpu.go +++ b/vendor/golang.org/x/sys/cpu/cpu.go @@ -103,7 +103,10 @@ var ARM64 struct { HasASIMDDP bool // Advanced SIMD double precision instruction set HasSHA512 bool // SHA512 hardware implementation HasSVE bool // Scalable Vector Extensions + HasSVE2 bool // Scalable Vector Extensions 2 HasASIMDFHM bool // Advanced SIMD multiplication FP16 to FP32 + HasDIT bool // Data Independent Timing support + HasI8MM bool // Advanced SIMD Int8 matrix multiplication instructions _ CacheLinePad } @@ -198,6 +201,25 @@ var S390X struct { _ CacheLinePad } +// RISCV64 contains the supported CPU features and performance characteristics for riscv64 +// platforms. The booleans in RISCV64, with the exception of HasFastMisaligned, indicate +// the presence of RISC-V extensions. +// +// It is safe to assume that all the RV64G extensions are supported and so they are omitted from +// this structure. As riscv64 Go programs require at least RV64G, the code that populates +// this structure cannot run successfully if some of the RV64G extensions are missing. +// The struct is padded to avoid false sharing. +var RISCV64 struct { + _ CacheLinePad + HasFastMisaligned bool // Fast misaligned accesses + HasC bool // Compressed instruction-set extension + HasV bool // Vector extension compatible with RVV 1.0 + HasZba bool // Address generation instructions extension + HasZbb bool // Basic bit-manipulation extension + HasZbs bool // Single-bit instructions extension + _ CacheLinePad +} + func init() { archInit() initOptions() diff --git a/vendor/golang.org/x/sys/cpu/cpu_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_arm64.go index f3eb993b..af2aa99f 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_arm64.go +++ b/vendor/golang.org/x/sys/cpu/cpu_arm64.go @@ -28,6 +28,7 @@ func initOptions() { {Name: "sm3", Feature: &ARM64.HasSM3}, {Name: "sm4", Feature: &ARM64.HasSM4}, {Name: "sve", Feature: &ARM64.HasSVE}, + {Name: "sve2", Feature: &ARM64.HasSVE2}, {Name: "crc32", Feature: &ARM64.HasCRC32}, {Name: "atomics", Feature: &ARM64.HasATOMICS}, {Name: "asimdhp", Feature: &ARM64.HasASIMDHP}, @@ -37,6 +38,8 @@ func initOptions() { {Name: "dcpop", Feature: &ARM64.HasDCPOP}, {Name: "asimddp", Feature: &ARM64.HasASIMDDP}, {Name: "asimdfhm", Feature: &ARM64.HasASIMDFHM}, + {Name: "dit", Feature: &ARM64.HasDIT}, + {Name: "i8mm", Feature: &ARM64.HasI8MM}, } } @@ -144,6 +147,11 @@ func parseARM64SystemRegisters(isar0, isar1, pfr0 uint64) { ARM64.HasLRCPC = true } + switch extractBits(isar1, 52, 55) { + case 1: + ARM64.HasI8MM = true + } + // ID_AA64PFR0_EL1 switch extractBits(pfr0, 16, 19) { case 0: @@ -164,6 +172,20 @@ func parseARM64SystemRegisters(isar0, isar1, pfr0 uint64) { switch extractBits(pfr0, 32, 35) { case 1: ARM64.HasSVE = true + + parseARM64SVERegister(getzfr0()) + } + + switch extractBits(pfr0, 48, 51) { + case 1: + ARM64.HasDIT = true + } +} + +func parseARM64SVERegister(zfr0 uint64) { + switch extractBits(zfr0, 0, 3) { + case 1: + ARM64.HasSVE2 = true } } diff --git a/vendor/golang.org/x/sys/cpu/cpu_arm64.s b/vendor/golang.org/x/sys/cpu/cpu_arm64.s index fcb9a388..22cc9984 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_arm64.s +++ b/vendor/golang.org/x/sys/cpu/cpu_arm64.s @@ -29,3 +29,11 @@ TEXT ·getpfr0(SB),NOSPLIT,$0-8 WORD $0xd5380400 MOVD R0, ret+0(FP) RET + +// func getzfr0() uint64 +TEXT ·getzfr0(SB),NOSPLIT,$0-8 + // get SVE Feature Register 0 into x0 + // mrs x0, ID_AA64ZFR0_EL1 = d5380480 + WORD $0xd5380480 + MOVD R0, ret+0(FP) + RET diff --git a/vendor/golang.org/x/sys/cpu/cpu_darwin_x86.go b/vendor/golang.org/x/sys/cpu/cpu_darwin_x86.go new file mode 100644 index 00000000..b838cb9e --- /dev/null +++ b/vendor/golang.org/x/sys/cpu/cpu_darwin_x86.go @@ -0,0 +1,61 @@ +// Copyright 2024 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. + +//go:build darwin && amd64 && gc + +package cpu + +// darwinSupportsAVX512 checks Darwin kernel for AVX512 support via sysctl +// call (see issue 43089). It also restricts AVX512 support for Darwin to +// kernel version 21.3.0 (MacOS 12.2.0) or later (see issue 49233). +// +// Background: +// Darwin implements a special mechanism to economize on thread state when +// AVX512 specific registers are not in use. This scheme minimizes state when +// preempting threads that haven't yet used any AVX512 instructions, but adds +// special requirements to check for AVX512 hardware support at runtime (e.g. +// via sysctl call or commpage inspection). See issue 43089 and link below for +// full background: +// https://github.com/apple-oss-distributions/xnu/blob/xnu-11215.1.10/osfmk/i386/fpu.c#L214-L240 +// +// Additionally, all versions of the Darwin kernel from 19.6.0 through 21.2.0 +// (corresponding to MacOS 10.15.6 - 12.1) have a bug that can cause corruption +// of the AVX512 mask registers (K0-K7) upon signal return. For this reason +// AVX512 is considered unsafe to use on Darwin for kernel versions prior to +// 21.3.0, where a fix has been confirmed. See issue 49233 for full background. +func darwinSupportsAVX512() bool { + return darwinSysctlEnabled([]byte("hw.optional.avx512f\x00")) && darwinKernelVersionCheck(21, 3, 0) +} + +// Ensure Darwin kernel version is at least major.minor.patch, avoiding dependencies +func darwinKernelVersionCheck(major, minor, patch int) bool { + var release [256]byte + err := darwinOSRelease(&release) + if err != nil { + return false + } + + var mmp [3]int + c := 0 +Loop: + for _, b := range release[:] { + switch { + case b >= '0' && b <= '9': + mmp[c] = 10*mmp[c] + int(b-'0') + case b == '.': + c++ + if c > 2 { + return false + } + case b == 0: + break Loop + default: + return false + } + } + if c != 2 { + return false + } + return mmp[0] > major || mmp[0] == major && (mmp[1] > minor || mmp[1] == minor && mmp[2] >= patch) +} diff --git a/vendor/golang.org/x/sys/cpu/cpu_gc_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_gc_arm64.go index a8acd3e3..6ac6e1ef 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_gc_arm64.go +++ b/vendor/golang.org/x/sys/cpu/cpu_gc_arm64.go @@ -9,3 +9,4 @@ package cpu func getisar0() uint64 func getisar1() uint64 func getpfr0() uint64 +func getzfr0() uint64 diff --git a/vendor/golang.org/x/sys/cpu/cpu_gc_x86.go b/vendor/golang.org/x/sys/cpu/cpu_gc_x86.go index 910728fb..32a44514 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_gc_x86.go +++ b/vendor/golang.org/x/sys/cpu/cpu_gc_x86.go @@ -6,10 +6,10 @@ package cpu -// cpuid is implemented in cpu_x86.s for gc compiler +// cpuid is implemented in cpu_gc_x86.s for gc compiler // and in cpu_gccgo.c for gccgo. func cpuid(eaxArg, ecxArg uint32) (eax, ebx, ecx, edx uint32) -// xgetbv with ecx = 0 is implemented in cpu_x86.s for gc compiler +// xgetbv with ecx = 0 is implemented in cpu_gc_x86.s for gc compiler // and in cpu_gccgo.c for gccgo. func xgetbv() (eax, edx uint32) diff --git a/vendor/golang.org/x/sys/cpu/cpu_x86.s b/vendor/golang.org/x/sys/cpu/cpu_gc_x86.s similarity index 94% rename from vendor/golang.org/x/sys/cpu/cpu_x86.s rename to vendor/golang.org/x/sys/cpu/cpu_gc_x86.s index 7d7ba33e..ce208ce6 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_x86.s +++ b/vendor/golang.org/x/sys/cpu/cpu_gc_x86.s @@ -18,7 +18,7 @@ TEXT ·cpuid(SB), NOSPLIT, $0-24 RET // func xgetbv() (eax, edx uint32) -TEXT ·xgetbv(SB),NOSPLIT,$0-8 +TEXT ·xgetbv(SB), NOSPLIT, $0-8 MOVL $0, CX XGETBV MOVL AX, eax+0(FP) diff --git a/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.go b/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.go index 99c60fe9..170d21dd 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.go +++ b/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.go @@ -23,9 +23,3 @@ func xgetbv() (eax, edx uint32) { gccgoXgetbv(&a, &d) return a, d } - -// gccgo doesn't build on Darwin, per: -// https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/gcc.rb#L76 -func darwinSupportsAVX512() bool { - return false -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go index a968b80f..f1caf0f7 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go +++ b/vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go @@ -35,6 +35,10 @@ const ( hwcap_SHA512 = 1 << 21 hwcap_SVE = 1 << 22 hwcap_ASIMDFHM = 1 << 23 + hwcap_DIT = 1 << 24 + + hwcap2_SVE2 = 1 << 1 + hwcap2_I8MM = 1 << 13 ) // linuxKernelCanEmulateCPUID reports whether we're running @@ -104,6 +108,11 @@ func doinit() { ARM64.HasSHA512 = isSet(hwCap, hwcap_SHA512) ARM64.HasSVE = isSet(hwCap, hwcap_SVE) ARM64.HasASIMDFHM = isSet(hwCap, hwcap_ASIMDFHM) + ARM64.HasDIT = isSet(hwCap, hwcap_DIT) + + // HWCAP2 feature bits + ARM64.HasSVE2 = isSet(hwCap2, hwcap2_SVE2) + ARM64.HasI8MM = isSet(hwCap2, hwcap2_I8MM) } func isSet(hwc uint, value uint) bool { diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_noinit.go b/vendor/golang.org/x/sys/cpu/cpu_linux_noinit.go index cd63e733..7d902b68 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_noinit.go +++ b/vendor/golang.org/x/sys/cpu/cpu_linux_noinit.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build linux && !arm && !arm64 && !mips64 && !mips64le && !ppc64 && !ppc64le && !s390x +//go:build linux && !arm && !arm64 && !mips64 && !mips64le && !ppc64 && !ppc64le && !s390x && !riscv64 package cpu diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_riscv64.go b/vendor/golang.org/x/sys/cpu/cpu_linux_riscv64.go new file mode 100644 index 00000000..cb4a0c57 --- /dev/null +++ b/vendor/golang.org/x/sys/cpu/cpu_linux_riscv64.go @@ -0,0 +1,137 @@ +// Copyright 2024 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 cpu + +import ( + "syscall" + "unsafe" +) + +// RISC-V extension discovery code for Linux. The approach here is to first try the riscv_hwprobe +// syscall falling back to HWCAP to check for the C extension if riscv_hwprobe is not available. +// +// A note on detection of the Vector extension using HWCAP. +// +// Support for the Vector extension version 1.0 was added to the Linux kernel in release 6.5. +// Support for the riscv_hwprobe syscall was added in 6.4. It follows that if the riscv_hwprobe +// syscall is not available then neither is the Vector extension (which needs kernel support). +// The riscv_hwprobe syscall should then be all we need to detect the Vector extension. +// However, some RISC-V board manufacturers ship boards with an older kernel on top of which +// they have back-ported various versions of the Vector extension patches but not the riscv_hwprobe +// patches. These kernels advertise support for the Vector extension using HWCAP. Falling +// back to HWCAP to detect the Vector extension, if riscv_hwprobe is not available, or simply not +// bothering with riscv_hwprobe at all and just using HWCAP may then seem like an attractive option. +// +// Unfortunately, simply checking the 'V' bit in AT_HWCAP will not work as this bit is used by +// RISC-V board and cloud instance providers to mean different things. The Lichee Pi 4A board +// and the Scaleway RV1 cloud instances use the 'V' bit to advertise their support for the unratified +// 0.7.1 version of the Vector Specification. The Banana Pi BPI-F3 and the CanMV-K230 board use +// it to advertise support for 1.0 of the Vector extension. Versions 0.7.1 and 1.0 of the Vector +// extension are binary incompatible. HWCAP can then not be used in isolation to populate the +// HasV field as this field indicates that the underlying CPU is compatible with RVV 1.0. +// +// There is a way at runtime to distinguish between versions 0.7.1 and 1.0 of the Vector +// specification by issuing a RVV 1.0 vsetvli instruction and checking the vill bit of the vtype +// register. This check would allow us to safely detect version 1.0 of the Vector extension +// with HWCAP, if riscv_hwprobe were not available. However, the check cannot +// be added until the assembler supports the Vector instructions. +// +// Note the riscv_hwprobe syscall does not suffer from these ambiguities by design as all of the +// extensions it advertises support for are explicitly versioned. It's also worth noting that +// the riscv_hwprobe syscall is the only way to detect multi-letter RISC-V extensions, e.g., Zba. +// These cannot be detected using HWCAP and so riscv_hwprobe must be used to detect the majority +// of RISC-V extensions. +// +// Please see https://docs.kernel.org/arch/riscv/hwprobe.html for more information. + +// golang.org/x/sys/cpu is not allowed to depend on golang.org/x/sys/unix so we must +// reproduce the constants, types and functions needed to make the riscv_hwprobe syscall +// here. + +const ( + // Copied from golang.org/x/sys/unix/ztypes_linux_riscv64.go. + riscv_HWPROBE_KEY_IMA_EXT_0 = 0x4 + riscv_HWPROBE_IMA_C = 0x2 + riscv_HWPROBE_IMA_V = 0x4 + riscv_HWPROBE_EXT_ZBA = 0x8 + riscv_HWPROBE_EXT_ZBB = 0x10 + riscv_HWPROBE_EXT_ZBS = 0x20 + riscv_HWPROBE_KEY_CPUPERF_0 = 0x5 + riscv_HWPROBE_MISALIGNED_FAST = 0x3 + riscv_HWPROBE_MISALIGNED_MASK = 0x7 +) + +const ( + // sys_RISCV_HWPROBE is copied from golang.org/x/sys/unix/zsysnum_linux_riscv64.go. + sys_RISCV_HWPROBE = 258 +) + +// riscvHWProbePairs is copied from golang.org/x/sys/unix/ztypes_linux_riscv64.go. +type riscvHWProbePairs struct { + key int64 + value uint64 +} + +const ( + // CPU features + hwcap_RISCV_ISA_C = 1 << ('C' - 'A') +) + +func doinit() { + // A slice of key/value pair structures is passed to the RISCVHWProbe syscall. The key + // field should be initialised with one of the key constants defined above, e.g., + // RISCV_HWPROBE_KEY_IMA_EXT_0. The syscall will set the value field to the appropriate value. + // If the kernel does not recognise a key it will set the key field to -1 and the value field to 0. + + pairs := []riscvHWProbePairs{ + {riscv_HWPROBE_KEY_IMA_EXT_0, 0}, + {riscv_HWPROBE_KEY_CPUPERF_0, 0}, + } + + // This call only indicates that extensions are supported if they are implemented on all cores. + if riscvHWProbe(pairs, 0) { + if pairs[0].key != -1 { + v := uint(pairs[0].value) + RISCV64.HasC = isSet(v, riscv_HWPROBE_IMA_C) + RISCV64.HasV = isSet(v, riscv_HWPROBE_IMA_V) + RISCV64.HasZba = isSet(v, riscv_HWPROBE_EXT_ZBA) + RISCV64.HasZbb = isSet(v, riscv_HWPROBE_EXT_ZBB) + RISCV64.HasZbs = isSet(v, riscv_HWPROBE_EXT_ZBS) + } + if pairs[1].key != -1 { + v := pairs[1].value & riscv_HWPROBE_MISALIGNED_MASK + RISCV64.HasFastMisaligned = v == riscv_HWPROBE_MISALIGNED_FAST + } + } + + // Let's double check with HWCAP if the C extension does not appear to be supported. + // This may happen if we're running on a kernel older than 6.4. + + if !RISCV64.HasC { + RISCV64.HasC = isSet(hwCap, hwcap_RISCV_ISA_C) + } +} + +func isSet(hwc uint, value uint) bool { + return hwc&value != 0 +} + +// riscvHWProbe is a simplified version of the generated wrapper function found in +// golang.org/x/sys/unix/zsyscall_linux_riscv64.go. We simplify it by removing the +// cpuCount and cpus parameters which we do not need. We always want to pass 0 for +// these parameters here so the kernel only reports the extensions that are present +// on all cores. +func riscvHWProbe(pairs []riscvHWProbePairs, flags uint) bool { + var _zero uintptr + var p0 unsafe.Pointer + if len(pairs) > 0 { + p0 = unsafe.Pointer(&pairs[0]) + } else { + p0 = unsafe.Pointer(&_zero) + } + + _, _, e1 := syscall.Syscall6(sys_RISCV_HWPROBE, uintptr(p0), uintptr(len(pairs)), uintptr(0), uintptr(0), uintptr(flags), 0) + return e1 == 0 +} diff --git a/vendor/golang.org/x/sys/cpu/cpu_other_x86.go b/vendor/golang.org/x/sys/cpu/cpu_other_x86.go new file mode 100644 index 00000000..a0fd7e2f --- /dev/null +++ b/vendor/golang.org/x/sys/cpu/cpu_other_x86.go @@ -0,0 +1,11 @@ +// Copyright 2024 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. + +//go:build 386 || amd64p32 || (amd64 && (!darwin || !gc)) + +package cpu + +func darwinSupportsAVX512() bool { + panic("only implemented for gc && amd64 && darwin") +} diff --git a/vendor/golang.org/x/sys/cpu/cpu_riscv64.go b/vendor/golang.org/x/sys/cpu/cpu_riscv64.go index 7f0c79c0..aca3199c 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_riscv64.go +++ b/vendor/golang.org/x/sys/cpu/cpu_riscv64.go @@ -8,4 +8,13 @@ package cpu const cacheLineSize = 64 -func initOptions() {} +func initOptions() { + options = []option{ + {Name: "fastmisaligned", Feature: &RISCV64.HasFastMisaligned}, + {Name: "c", Feature: &RISCV64.HasC}, + {Name: "v", Feature: &RISCV64.HasV}, + {Name: "zba", Feature: &RISCV64.HasZba}, + {Name: "zbb", Feature: &RISCV64.HasZbb}, + {Name: "zbs", Feature: &RISCV64.HasZbs}, + } +} diff --git a/vendor/golang.org/x/sys/cpu/cpu_x86.go b/vendor/golang.org/x/sys/cpu/cpu_x86.go index c29f5e4c..600a6807 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_x86.go +++ b/vendor/golang.org/x/sys/cpu/cpu_x86.go @@ -92,10 +92,8 @@ func archInit() { osSupportsAVX = isSet(1, eax) && isSet(2, eax) if runtime.GOOS == "darwin" { - // Darwin doesn't save/restore AVX-512 mask registers correctly across signal handlers. - // Since users can't rely on mask register contents, let's not advertise AVX-512 support. - // See issue 49233. - osSupportsAVX512 = false + // Darwin requires special AVX512 checks, see cpu_darwin_x86.go + osSupportsAVX512 = osSupportsAVX && darwinSupportsAVX512() } else { // Check if OPMASK and ZMM registers have OS support. osSupportsAVX512 = osSupportsAVX && isSet(5, eax) && isSet(6, eax) && isSet(7, eax) diff --git a/vendor/golang.org/x/sys/cpu/syscall_darwin_x86_gc.go b/vendor/golang.org/x/sys/cpu/syscall_darwin_x86_gc.go new file mode 100644 index 00000000..4d0888b0 --- /dev/null +++ b/vendor/golang.org/x/sys/cpu/syscall_darwin_x86_gc.go @@ -0,0 +1,98 @@ +// Copyright 2024 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. + +// Minimal copy of x/sys/unix so the cpu package can make a +// system call on Darwin without depending on x/sys/unix. + +//go:build darwin && amd64 && gc + +package cpu + +import ( + "syscall" + "unsafe" +) + +type _C_int int32 + +// adapted from unix.Uname() at x/sys/unix/syscall_darwin.go L419 +func darwinOSRelease(release *[256]byte) error { + // from x/sys/unix/zerrors_openbsd_amd64.go + const ( + CTL_KERN = 0x1 + KERN_OSRELEASE = 0x2 + ) + + mib := []_C_int{CTL_KERN, KERN_OSRELEASE} + n := unsafe.Sizeof(*release) + + return sysctl(mib, &release[0], &n, nil, 0) +} + +type Errno = syscall.Errno + +var _zero uintptr // Single-word zero for use when we need a valid pointer to 0 bytes. + +// from x/sys/unix/zsyscall_darwin_amd64.go L791-807 +func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) error { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + if _, _, err := syscall_syscall6( + libc_sysctl_trampoline_addr, + uintptr(_p0), + uintptr(len(mib)), + uintptr(unsafe.Pointer(old)), + uintptr(unsafe.Pointer(oldlen)), + uintptr(unsafe.Pointer(new)), + uintptr(newlen), + ); err != 0 { + return err + } + + return nil +} + +var libc_sysctl_trampoline_addr uintptr + +// adapted from internal/cpu/cpu_arm64_darwin.go +func darwinSysctlEnabled(name []byte) bool { + out := int32(0) + nout := unsafe.Sizeof(out) + if ret := sysctlbyname(&name[0], (*byte)(unsafe.Pointer(&out)), &nout, nil, 0); ret != nil { + return false + } + return out > 0 +} + +//go:cgo_import_dynamic libc_sysctl sysctl "/usr/lib/libSystem.B.dylib" + +var libc_sysctlbyname_trampoline_addr uintptr + +// adapted from runtime/sys_darwin.go in the pattern of sysctl() above, as defined in x/sys/unix +func sysctlbyname(name *byte, old *byte, oldlen *uintptr, new *byte, newlen uintptr) error { + if _, _, err := syscall_syscall6( + libc_sysctlbyname_trampoline_addr, + uintptr(unsafe.Pointer(name)), + uintptr(unsafe.Pointer(old)), + uintptr(unsafe.Pointer(oldlen)), + uintptr(unsafe.Pointer(new)), + uintptr(newlen), + 0, + ); err != 0 { + return err + } + + return nil +} + +//go:cgo_import_dynamic libc_sysctlbyname sysctlbyname "/usr/lib/libSystem.B.dylib" + +// Implemented in the runtime package (runtime/sys_darwin.go) +func syscall_syscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) + +//go:linkname syscall_syscall6 syscall.syscall6 diff --git a/vendor/golang.org/x/sys/unix/README.md b/vendor/golang.org/x/sys/unix/README.md index 7d3c060e..6e08a76a 100644 --- a/vendor/golang.org/x/sys/unix/README.md +++ b/vendor/golang.org/x/sys/unix/README.md @@ -156,7 +156,7 @@ from the generated architecture-specific files listed below, and merge these into a common file for each OS. The merge is performed in the following steps: -1. Construct the set of common code that is idential in all architecture-specific files. +1. Construct the set of common code that is identical in all architecture-specific files. 2. Write this common code to the merged file. 3. Remove the common code from all architecture-specific files. diff --git a/vendor/golang.org/x/sys/unix/aliases.go b/vendor/golang.org/x/sys/unix/aliases.go index e7d3df4b..b0e41985 100644 --- a/vendor/golang.org/x/sys/unix/aliases.go +++ b/vendor/golang.org/x/sys/unix/aliases.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build (aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos) && go1.9 +//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos package unix diff --git a/vendor/golang.org/x/sys/unix/asm_zos_s390x.s b/vendor/golang.org/x/sys/unix/asm_zos_s390x.s index 2f67ba86..813dfad7 100644 --- a/vendor/golang.org/x/sys/unix/asm_zos_s390x.s +++ b/vendor/golang.org/x/sys/unix/asm_zos_s390x.s @@ -9,9 +9,11 @@ #define PSALAA 1208(R0) #define GTAB64(x) 80(x) #define LCA64(x) 88(x) +#define SAVSTACK_ASYNC(x) 336(x) // in the LCA #define CAA(x) 8(x) -#define EDCHPXV(x) 1016(x) // in the CAA -#define SAVSTACK_ASYNC(x) 336(x) // in the LCA +#define CEECAATHDID(x) 976(x) // in the CAA +#define EDCHPXV(x) 1016(x) // in the CAA +#define GOCB(x) 1104(x) // in the CAA // SS_*, where x=SAVSTACK_ASYNC #define SS_LE(x) 0(x) @@ -19,405 +21,362 @@ #define SS_ERRNO(x) 16(x) #define SS_ERRNOJR(x) 20(x) -#define LE_CALL BYTE $0x0D; BYTE $0x76; // BL R7, R6 +// Function Descriptor Offsets +#define __errno 0x156*16 +#define __err2ad 0x16C*16 -TEXT ·clearErrno(SB),NOSPLIT,$0-0 - BL addrerrno<>(SB) - MOVD $0, 0(R3) +// Call Instructions +#define LE_CALL BYTE $0x0D; BYTE $0x76 // BL R7, R6 +#define SVC_LOAD BYTE $0x0A; BYTE $0x08 // SVC 08 LOAD +#define SVC_DELETE BYTE $0x0A; BYTE $0x09 // SVC 09 DELETE + +DATA zosLibVec<>(SB)/8, $0 +GLOBL zosLibVec<>(SB), NOPTR, $8 + +TEXT ·initZosLibVec(SB), NOSPLIT|NOFRAME, $0-0 + MOVW PSALAA, R8 + MOVD LCA64(R8), R8 + MOVD CAA(R8), R8 + MOVD EDCHPXV(R8), R8 + MOVD R8, zosLibVec<>(SB) + RET + +TEXT ·GetZosLibVec(SB), NOSPLIT|NOFRAME, $0-0 + MOVD zosLibVec<>(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·clearErrno(SB), NOSPLIT, $0-0 + BL addrerrno<>(SB) + MOVD $0, 0(R3) RET // Returns the address of errno in R3. -TEXT addrerrno<>(SB),NOSPLIT|NOFRAME,$0-0 +TEXT addrerrno<>(SB), NOSPLIT|NOFRAME, $0-0 // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 + MOVW PSALAA, R8 + MOVD LCA64(R8), R8 // Get __errno FuncDesc. - MOVD CAA(R8), R9 - MOVD EDCHPXV(R9), R9 - ADD $(0x156*16), R9 - LMG 0(R9), R5, R6 + MOVD CAA(R8), R9 + MOVD EDCHPXV(R9), R9 + ADD $(__errno), R9 + LMG 0(R9), R5, R6 // Switch to saved LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R4 - MOVD $0, 0(R9) + MOVD SAVSTACK_ASYNC(R8), R9 + MOVD 0(R9), R4 + MOVD $0, 0(R9) // Call __errno function. LE_CALL NOPH // Switch back to Go stack. - XOR R0, R0 // Restore R0 to $0. - MOVD R4, 0(R9) // Save stack pointer. + XOR R0, R0 // Restore R0 to $0. + MOVD R4, 0(R9) // Save stack pointer. RET -TEXT ·syscall_syscall(SB),NOSPLIT,$0-56 - BL runtime·entersyscall(SB) - MOVD a1+8(FP), R1 - MOVD a2+16(FP), R2 - MOVD a3+24(FP), R3 +// func svcCall(fnptr unsafe.Pointer, argv *unsafe.Pointer, dsa *uint64) +TEXT ·svcCall(SB), NOSPLIT, $0 + BL runtime·save_g(SB) // Save g and stack pointer + MOVW PSALAA, R8 + MOVD LCA64(R8), R8 + MOVD SAVSTACK_ASYNC(R8), R9 + MOVD R15, 0(R9) - // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 + MOVD argv+8(FP), R1 // Move function arguments into registers + MOVD dsa+16(FP), g + MOVD fnptr+0(FP), R15 - // Get function. - MOVD CAA(R8), R9 - MOVD EDCHPXV(R9), R9 - MOVD trap+0(FP), R5 - SLD $4, R5 - ADD R5, R9 - LMG 0(R9), R5, R6 + BYTE $0x0D // Branch to function + BYTE $0xEF - // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R4 - MOVD $0, 0(R9) + BL runtime·load_g(SB) // Restore g and stack pointer + MOVW PSALAA, R8 + MOVD LCA64(R8), R8 + MOVD SAVSTACK_ASYNC(R8), R9 + MOVD 0(R9), R15 - // Call function. - LE_CALL - NOPH - XOR R0, R0 // Restore R0 to $0. - MOVD R4, 0(R9) // Save stack pointer. - - MOVD R3, r1+32(FP) - MOVD R0, r2+40(FP) - MOVD R0, err+48(FP) - MOVW R3, R4 - CMP R4, $-1 - BNE done - BL addrerrno<>(SB) - MOVWZ 0(R3), R3 - MOVD R3, err+48(FP) -done: - BL runtime·exitsyscall(SB) RET -TEXT ·syscall_rawsyscall(SB),NOSPLIT,$0-56 - MOVD a1+8(FP), R1 - MOVD a2+16(FP), R2 - MOVD a3+24(FP), R3 - - // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - - // Get function. - MOVD CAA(R8), R9 - MOVD EDCHPXV(R9), R9 - MOVD trap+0(FP), R5 - SLD $4, R5 - ADD R5, R9 - LMG 0(R9), R5, R6 +// func svcLoad(name *byte) unsafe.Pointer +TEXT ·svcLoad(SB), NOSPLIT, $0 + MOVD R15, R2 // Save go stack pointer + MOVD name+0(FP), R0 // Move SVC args into registers + MOVD $0x80000000, R1 + MOVD $0, R15 + SVC_LOAD + MOVW R15, R3 // Save return code from SVC + MOVD R2, R15 // Restore go stack pointer + CMP R3, $0 // Check SVC return code + BNE error + + MOVD $-2, R3 // Reset last bit of entry point to zero + AND R0, R3 + MOVD R3, ret+8(FP) // Return entry point returned by SVC + CMP R0, R3 // Check if last bit of entry point was set + BNE done + + MOVD R15, R2 // Save go stack pointer + MOVD $0, R15 // Move SVC args into registers (entry point still in r0 from SVC 08) + SVC_DELETE + MOVD R2, R15 // Restore go stack pointer - // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R4 - MOVD $0, 0(R9) +error: + MOVD $0, ret+8(FP) // Return 0 on failure - // Call function. - LE_CALL - NOPH - XOR R0, R0 // Restore R0 to $0. - MOVD R4, 0(R9) // Save stack pointer. - - MOVD R3, r1+32(FP) - MOVD R0, r2+40(FP) - MOVD R0, err+48(FP) - MOVW R3, R4 - CMP R4, $-1 - BNE done - BL addrerrno<>(SB) - MOVWZ 0(R3), R3 - MOVD R3, err+48(FP) done: + XOR R0, R0 // Reset r0 to 0 RET -TEXT ·syscall_syscall6(SB),NOSPLIT,$0-80 - BL runtime·entersyscall(SB) - MOVD a1+8(FP), R1 - MOVD a2+16(FP), R2 - MOVD a3+24(FP), R3 +// func svcUnload(name *byte, fnptr unsafe.Pointer) int64 +TEXT ·svcUnload(SB), NOSPLIT, $0 + MOVD R15, R2 // Save go stack pointer + MOVD name+0(FP), R0 // Move SVC args into registers + MOVD fnptr+8(FP), R15 + SVC_DELETE + XOR R0, R0 // Reset r0 to 0 + MOVD R15, R1 // Save SVC return code + MOVD R2, R15 // Restore go stack pointer + MOVD R1, ret+16(FP) // Return SVC return code + RET +// func gettid() uint64 +TEXT ·gettid(SB), NOSPLIT, $0 // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 + MOVW PSALAA, R8 + MOVD LCA64(R8), R8 - // Get function. - MOVD CAA(R8), R9 - MOVD EDCHPXV(R9), R9 - MOVD trap+0(FP), R5 - SLD $4, R5 - ADD R5, R9 - LMG 0(R9), R5, R6 + // Get CEECAATHDID + MOVD CAA(R8), R9 + MOVD CEECAATHDID(R9), R9 + MOVD R9, ret+0(FP) - // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R4 - MOVD $0, 0(R9) - - // Fill in parameter list. - MOVD a4+32(FP), R12 - MOVD R12, (2176+24)(R4) - MOVD a5+40(FP), R12 - MOVD R12, (2176+32)(R4) - MOVD a6+48(FP), R12 - MOVD R12, (2176+40)(R4) - - // Call function. - LE_CALL - NOPH - XOR R0, R0 // Restore R0 to $0. - MOVD R4, 0(R9) // Save stack pointer. - - MOVD R3, r1+56(FP) - MOVD R0, r2+64(FP) - MOVD R0, err+72(FP) - MOVW R3, R4 - CMP R4, $-1 - BNE done - BL addrerrno<>(SB) - MOVWZ 0(R3), R3 - MOVD R3, err+72(FP) -done: - BL runtime·exitsyscall(SB) RET -TEXT ·syscall_rawsyscall6(SB),NOSPLIT,$0-80 - MOVD a1+8(FP), R1 - MOVD a2+16(FP), R2 - MOVD a3+24(FP), R3 - - // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - - // Get function. - MOVD CAA(R8), R9 - MOVD EDCHPXV(R9), R9 - MOVD trap+0(FP), R5 - SLD $4, R5 - ADD R5, R9 - LMG 0(R9), R5, R6 +// +// Call LE function, if the return is -1 +// errno and errno2 is retrieved +// +TEXT ·CallLeFuncWithErr(SB), NOSPLIT, $0 + MOVW PSALAA, R8 + MOVD LCA64(R8), R8 + MOVD CAA(R8), R9 + MOVD g, GOCB(R9) // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R4 - MOVD $0, 0(R9) - - // Fill in parameter list. - MOVD a4+32(FP), R12 - MOVD R12, (2176+24)(R4) - MOVD a5+40(FP), R12 - MOVD R12, (2176+32)(R4) - MOVD a6+48(FP), R12 - MOVD R12, (2176+40)(R4) - - // Call function. - LE_CALL + MOVD SAVSTACK_ASYNC(R8), R9 // R9-> LE stack frame saving address + MOVD 0(R9), R4 // R4-> restore previously saved stack frame pointer + + MOVD parms_base+8(FP), R7 // R7 -> argument array + MOVD parms_len+16(FP), R8 // R8 number of arguments + + // arg 1 ---> R1 + CMP R8, $0 + BEQ docall + SUB $1, R8 + MOVD 0(R7), R1 + + // arg 2 ---> R2 + CMP R8, $0 + BEQ docall + SUB $1, R8 + ADD $8, R7 + MOVD 0(R7), R2 + + // arg 3 --> R3 + CMP R8, $0 + BEQ docall + SUB $1, R8 + ADD $8, R7 + MOVD 0(R7), R3 + + CMP R8, $0 + BEQ docall + MOVD $2176+16, R6 // starting LE stack address-8 to store 4th argument + +repeat: + ADD $8, R7 + MOVD 0(R7), R0 // advance arg pointer by 8 byte + ADD $8, R6 // advance LE argument address by 8 byte + MOVD R0, (R4)(R6*1) // copy argument from go-slice to le-frame + SUB $1, R8 + CMP R8, $0 + BNE repeat + +docall: + MOVD funcdesc+0(FP), R8 // R8-> function descriptor + LMG 0(R8), R5, R6 + MOVD $0, 0(R9) // R9 address of SAVSTACK_ASYNC + LE_CALL // balr R7, R6 (return #1) + NOPH + MOVD R3, ret+32(FP) + CMP R3, $-1 // compare result to -1 + BNE done + + // retrieve errno and errno2 + MOVD zosLibVec<>(SB), R8 + ADD $(__errno), R8 + LMG 0(R8), R5, R6 + LE_CALL // balr R7, R6 __errno (return #3) NOPH - XOR R0, R0 // Restore R0 to $0. - MOVD R4, 0(R9) // Save stack pointer. - - MOVD R3, r1+56(FP) - MOVD R0, r2+64(FP) - MOVD R0, err+72(FP) - MOVW R3, R4 - CMP R4, $-1 - BNE done - BL ·rrno<>(SB) - MOVWZ 0(R3), R3 - MOVD R3, err+72(FP) + MOVWZ 0(R3), R3 + MOVD R3, err+48(FP) + MOVD zosLibVec<>(SB), R8 + ADD $(__err2ad), R8 + LMG 0(R8), R5, R6 + LE_CALL // balr R7, R6 __err2ad (return #2) + NOPH + MOVW (R3), R2 // retrieve errno2 + MOVD R2, errno2+40(FP) // store in return area + done: + MOVD R4, 0(R9) // Save stack pointer. RET -TEXT ·syscall_syscall9(SB),NOSPLIT,$0 - BL runtime·entersyscall(SB) - MOVD a1+8(FP), R1 - MOVD a2+16(FP), R2 - MOVD a3+24(FP), R3 - - // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - - // Get function. - MOVD CAA(R8), R9 - MOVD EDCHPXV(R9), R9 - MOVD trap+0(FP), R5 - SLD $4, R5 - ADD R5, R9 - LMG 0(R9), R5, R6 +// +// Call LE function, if the return is 0 +// errno and errno2 is retrieved +// +TEXT ·CallLeFuncWithPtrReturn(SB), NOSPLIT, $0 + MOVW PSALAA, R8 + MOVD LCA64(R8), R8 + MOVD CAA(R8), R9 + MOVD g, GOCB(R9) // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R4 - MOVD $0, 0(R9) - - // Fill in parameter list. - MOVD a4+32(FP), R12 - MOVD R12, (2176+24)(R4) - MOVD a5+40(FP), R12 - MOVD R12, (2176+32)(R4) - MOVD a6+48(FP), R12 - MOVD R12, (2176+40)(R4) - MOVD a7+56(FP), R12 - MOVD R12, (2176+48)(R4) - MOVD a8+64(FP), R12 - MOVD R12, (2176+56)(R4) - MOVD a9+72(FP), R12 - MOVD R12, (2176+64)(R4) - - // Call function. - LE_CALL + MOVD SAVSTACK_ASYNC(R8), R9 // R9-> LE stack frame saving address + MOVD 0(R9), R4 // R4-> restore previously saved stack frame pointer + + MOVD parms_base+8(FP), R7 // R7 -> argument array + MOVD parms_len+16(FP), R8 // R8 number of arguments + + // arg 1 ---> R1 + CMP R8, $0 + BEQ docall + SUB $1, R8 + MOVD 0(R7), R1 + + // arg 2 ---> R2 + CMP R8, $0 + BEQ docall + SUB $1, R8 + ADD $8, R7 + MOVD 0(R7), R2 + + // arg 3 --> R3 + CMP R8, $0 + BEQ docall + SUB $1, R8 + ADD $8, R7 + MOVD 0(R7), R3 + + CMP R8, $0 + BEQ docall + MOVD $2176+16, R6 // starting LE stack address-8 to store 4th argument + +repeat: + ADD $8, R7 + MOVD 0(R7), R0 // advance arg pointer by 8 byte + ADD $8, R6 // advance LE argument address by 8 byte + MOVD R0, (R4)(R6*1) // copy argument from go-slice to le-frame + SUB $1, R8 + CMP R8, $0 + BNE repeat + +docall: + MOVD funcdesc+0(FP), R8 // R8-> function descriptor + LMG 0(R8), R5, R6 + MOVD $0, 0(R9) // R9 address of SAVSTACK_ASYNC + LE_CALL // balr R7, R6 (return #1) NOPH - XOR R0, R0 // Restore R0 to $0. - MOVD R4, 0(R9) // Save stack pointer. - - MOVD R3, r1+80(FP) - MOVD R0, r2+88(FP) - MOVD R0, err+96(FP) - MOVW R3, R4 - CMP R4, $-1 - BNE done - BL addrerrno<>(SB) - MOVWZ 0(R3), R3 - MOVD R3, err+96(FP) -done: - BL runtime·exitsyscall(SB) - RET - -TEXT ·syscall_rawsyscall9(SB),NOSPLIT,$0 - MOVD a1+8(FP), R1 - MOVD a2+16(FP), R2 - MOVD a3+24(FP), R3 - - // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - - // Get function. - MOVD CAA(R8), R9 - MOVD EDCHPXV(R9), R9 - MOVD trap+0(FP), R5 - SLD $4, R5 - ADD R5, R9 - LMG 0(R9), R5, R6 - - // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R4 - MOVD $0, 0(R9) - - // Fill in parameter list. - MOVD a4+32(FP), R12 - MOVD R12, (2176+24)(R4) - MOVD a5+40(FP), R12 - MOVD R12, (2176+32)(R4) - MOVD a6+48(FP), R12 - MOVD R12, (2176+40)(R4) - MOVD a7+56(FP), R12 - MOVD R12, (2176+48)(R4) - MOVD a8+64(FP), R12 - MOVD R12, (2176+56)(R4) - MOVD a9+72(FP), R12 - MOVD R12, (2176+64)(R4) - - // Call function. - LE_CALL + MOVD R3, ret+32(FP) + CMP R3, $0 // compare result to 0 + BNE done + + // retrieve errno and errno2 + MOVD zosLibVec<>(SB), R8 + ADD $(__errno), R8 + LMG 0(R8), R5, R6 + LE_CALL // balr R7, R6 __errno (return #3) NOPH - XOR R0, R0 // Restore R0 to $0. - MOVD R4, 0(R9) // Save stack pointer. - - MOVD R3, r1+80(FP) - MOVD R0, r2+88(FP) - MOVD R0, err+96(FP) - MOVW R3, R4 - CMP R4, $-1 - BNE done - BL addrerrno<>(SB) - MOVWZ 0(R3), R3 - MOVD R3, err+96(FP) -done: - RET - -// func svcCall(fnptr unsafe.Pointer, argv *unsafe.Pointer, dsa *uint64) -TEXT ·svcCall(SB),NOSPLIT,$0 - BL runtime·save_g(SB) // Save g and stack pointer - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD R15, 0(R9) - - MOVD argv+8(FP), R1 // Move function arguments into registers - MOVD dsa+16(FP), g - MOVD fnptr+0(FP), R15 - - BYTE $0x0D // Branch to function - BYTE $0xEF - - BL runtime·load_g(SB) // Restore g and stack pointer - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R15 - - RET - -// func svcLoad(name *byte) unsafe.Pointer -TEXT ·svcLoad(SB),NOSPLIT,$0 - MOVD R15, R2 // Save go stack pointer - MOVD name+0(FP), R0 // Move SVC args into registers - MOVD $0x80000000, R1 - MOVD $0, R15 - BYTE $0x0A // SVC 08 LOAD - BYTE $0x08 - MOVW R15, R3 // Save return code from SVC - MOVD R2, R15 // Restore go stack pointer - CMP R3, $0 // Check SVC return code - BNE error - - MOVD $-2, R3 // Reset last bit of entry point to zero - AND R0, R3 - MOVD R3, addr+8(FP) // Return entry point returned by SVC - CMP R0, R3 // Check if last bit of entry point was set - BNE done - - MOVD R15, R2 // Save go stack pointer - MOVD $0, R15 // Move SVC args into registers (entry point still in r0 from SVC 08) - BYTE $0x0A // SVC 09 DELETE - BYTE $0x09 - MOVD R2, R15 // Restore go stack pointer + MOVWZ 0(R3), R3 + MOVD R3, err+48(FP) + MOVD zosLibVec<>(SB), R8 + ADD $(__err2ad), R8 + LMG 0(R8), R5, R6 + LE_CALL // balr R7, R6 __err2ad (return #2) + NOPH + MOVW (R3), R2 // retrieve errno2 + MOVD R2, errno2+40(FP) // store in return area + XOR R2, R2 + MOVWZ R2, (R3) // clear errno2 -error: - MOVD $0, addr+8(FP) // Return 0 on failure done: - XOR R0, R0 // Reset r0 to 0 + MOVD R4, 0(R9) // Save stack pointer. RET -// func svcUnload(name *byte, fnptr unsafe.Pointer) int64 -TEXT ·svcUnload(SB),NOSPLIT,$0 - MOVD R15, R2 // Save go stack pointer - MOVD name+0(FP), R0 // Move SVC args into registers - MOVD addr+8(FP), R15 - BYTE $0x0A // SVC 09 - BYTE $0x09 - XOR R0, R0 // Reset r0 to 0 - MOVD R15, R1 // Save SVC return code - MOVD R2, R15 // Restore go stack pointer - MOVD R1, rc+0(FP) // Return SVC return code +// +// function to test if a pointer can be safely dereferenced (content read) +// return 0 for succces +// +TEXT ·ptrtest(SB), NOSPLIT, $0-16 + MOVD arg+0(FP), R10 // test pointer in R10 + + // set up R2 to point to CEECAADMC + BYTE $0xE3; BYTE $0x20; BYTE $0x04; BYTE $0xB8; BYTE $0x00; BYTE $0x17 // llgt 2,1208 + BYTE $0xB9; BYTE $0x17; BYTE $0x00; BYTE $0x22 // llgtr 2,2 + BYTE $0xA5; BYTE $0x26; BYTE $0x7F; BYTE $0xFF // nilh 2,32767 + BYTE $0xE3; BYTE $0x22; BYTE $0x00; BYTE $0x58; BYTE $0x00; BYTE $0x04 // lg 2,88(2) + BYTE $0xE3; BYTE $0x22; BYTE $0x00; BYTE $0x08; BYTE $0x00; BYTE $0x04 // lg 2,8(2) + BYTE $0x41; BYTE $0x22; BYTE $0x03; BYTE $0x68 // la 2,872(2) + + // set up R5 to point to the "shunt" path which set 1 to R3 (failure) + BYTE $0xB9; BYTE $0x82; BYTE $0x00; BYTE $0x33 // xgr 3,3 + BYTE $0xA7; BYTE $0x55; BYTE $0x00; BYTE $0x04 // bras 5,lbl1 + BYTE $0xA7; BYTE $0x39; BYTE $0x00; BYTE $0x01 // lghi 3,1 + + // if r3 is not zero (failed) then branch to finish + BYTE $0xB9; BYTE $0x02; BYTE $0x00; BYTE $0x33 // lbl1 ltgr 3,3 + BYTE $0xA7; BYTE $0x74; BYTE $0x00; BYTE $0x08 // brc b'0111',lbl2 + + // stomic store shunt address in R5 into CEECAADMC + BYTE $0xE3; BYTE $0x52; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x24 // stg 5,0(2) + + // now try reading from the test pointer in R10, if it fails it branches to the "lghi" instruction above + BYTE $0xE3; BYTE $0x9A; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x04 // lg 9,0(10) + + // finish here, restore 0 into CEECAADMC + BYTE $0xB9; BYTE $0x82; BYTE $0x00; BYTE $0x99 // lbl2 xgr 9,9 + BYTE $0xE3; BYTE $0x92; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x24 // stg 9,0(2) + MOVD R3, ret+8(FP) // result in R3 RET -// func gettid() uint64 -TEXT ·gettid(SB), NOSPLIT, $0 - // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - - // Get CEECAATHDID - MOVD CAA(R8), R9 - MOVD 0x3D0(R9), R9 - MOVD R9, ret+0(FP) - +// +// function to test if a untptr can be loaded from a pointer +// return 1: the 8-byte content +// 2: 0 for success, 1 for failure +// +// func safeload(ptr uintptr) ( value uintptr, error uintptr) +TEXT ·safeload(SB), NOSPLIT, $0-24 + MOVD ptr+0(FP), R10 // test pointer in R10 + MOVD $0x0, R6 + BYTE $0xE3; BYTE $0x20; BYTE $0x04; BYTE $0xB8; BYTE $0x00; BYTE $0x17 // llgt 2,1208 + BYTE $0xB9; BYTE $0x17; BYTE $0x00; BYTE $0x22 // llgtr 2,2 + BYTE $0xA5; BYTE $0x26; BYTE $0x7F; BYTE $0xFF // nilh 2,32767 + BYTE $0xE3; BYTE $0x22; BYTE $0x00; BYTE $0x58; BYTE $0x00; BYTE $0x04 // lg 2,88(2) + BYTE $0xE3; BYTE $0x22; BYTE $0x00; BYTE $0x08; BYTE $0x00; BYTE $0x04 // lg 2,8(2) + BYTE $0x41; BYTE $0x22; BYTE $0x03; BYTE $0x68 // la 2,872(2) + BYTE $0xB9; BYTE $0x82; BYTE $0x00; BYTE $0x33 // xgr 3,3 + BYTE $0xA7; BYTE $0x55; BYTE $0x00; BYTE $0x04 // bras 5,lbl1 + BYTE $0xA7; BYTE $0x39; BYTE $0x00; BYTE $0x01 // lghi 3,1 + BYTE $0xB9; BYTE $0x02; BYTE $0x00; BYTE $0x33 // lbl1 ltgr 3,3 + BYTE $0xA7; BYTE $0x74; BYTE $0x00; BYTE $0x08 // brc b'0111',lbl2 + BYTE $0xE3; BYTE $0x52; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x24 // stg 5,0(2) + BYTE $0xE3; BYTE $0x6A; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x04 // lg 6,0(10) + BYTE $0xB9; BYTE $0x82; BYTE $0x00; BYTE $0x99 // lbl2 xgr 9,9 + BYTE $0xE3; BYTE $0x92; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x24 // stg 9,0(2) + MOVD R6, value+8(FP) // result in R6 + MOVD R3, error+16(FP) // error in R3 RET diff --git a/vendor/golang.org/x/sys/unix/bpxsvc_zos.go b/vendor/golang.org/x/sys/unix/bpxsvc_zos.go new file mode 100644 index 00000000..39d647d8 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/bpxsvc_zos.go @@ -0,0 +1,657 @@ +// Copyright 2024 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. + +//go:build zos + +package unix + +import ( + "bytes" + "fmt" + "unsafe" +) + +//go:noescape +func bpxcall(plist []unsafe.Pointer, bpx_offset int64) + +//go:noescape +func A2e([]byte) + +//go:noescape +func E2a([]byte) + +const ( + BPX4STA = 192 // stat + BPX4FST = 104 // fstat + BPX4LST = 132 // lstat + BPX4OPN = 156 // open + BPX4CLO = 72 // close + BPX4CHR = 500 // chattr + BPX4FCR = 504 // fchattr + BPX4LCR = 1180 // lchattr + BPX4CTW = 492 // cond_timed_wait + BPX4GTH = 1056 // __getthent + BPX4PTQ = 412 // pthread_quiesc + BPX4PTR = 320 // ptrace +) + +const ( + //options + //byte1 + BPX_OPNFHIGH = 0x80 + //byte2 + BPX_OPNFEXEC = 0x80 + //byte3 + BPX_O_NOLARGEFILE = 0x08 + BPX_O_LARGEFILE = 0x04 + BPX_O_ASYNCSIG = 0x02 + BPX_O_SYNC = 0x01 + //byte4 + BPX_O_CREXCL = 0xc0 + BPX_O_CREAT = 0x80 + BPX_O_EXCL = 0x40 + BPX_O_NOCTTY = 0x20 + BPX_O_TRUNC = 0x10 + BPX_O_APPEND = 0x08 + BPX_O_NONBLOCK = 0x04 + BPX_FNDELAY = 0x04 + BPX_O_RDWR = 0x03 + BPX_O_RDONLY = 0x02 + BPX_O_WRONLY = 0x01 + BPX_O_ACCMODE = 0x03 + BPX_O_GETFL = 0x0f + + //mode + // byte1 (file type) + BPX_FT_DIR = 1 + BPX_FT_CHARSPEC = 2 + BPX_FT_REGFILE = 3 + BPX_FT_FIFO = 4 + BPX_FT_SYMLINK = 5 + BPX_FT_SOCKET = 6 + //byte3 + BPX_S_ISUID = 0x08 + BPX_S_ISGID = 0x04 + BPX_S_ISVTX = 0x02 + BPX_S_IRWXU1 = 0x01 + BPX_S_IRUSR = 0x01 + //byte4 + BPX_S_IRWXU2 = 0xc0 + BPX_S_IWUSR = 0x80 + BPX_S_IXUSR = 0x40 + BPX_S_IRWXG = 0x38 + BPX_S_IRGRP = 0x20 + BPX_S_IWGRP = 0x10 + BPX_S_IXGRP = 0x08 + BPX_S_IRWXOX = 0x07 + BPX_S_IROTH = 0x04 + BPX_S_IWOTH = 0x02 + BPX_S_IXOTH = 0x01 + + CW_INTRPT = 1 + CW_CONDVAR = 32 + CW_TIMEOUT = 64 + + PGTHA_NEXT = 2 + PGTHA_CURRENT = 1 + PGTHA_FIRST = 0 + PGTHA_LAST = 3 + PGTHA_PROCESS = 0x80 + PGTHA_CONTTY = 0x40 + PGTHA_PATH = 0x20 + PGTHA_COMMAND = 0x10 + PGTHA_FILEDATA = 0x08 + PGTHA_THREAD = 0x04 + PGTHA_PTAG = 0x02 + PGTHA_COMMANDLONG = 0x01 + PGTHA_THREADFAST = 0x80 + PGTHA_FILEPATH = 0x40 + PGTHA_THDSIGMASK = 0x20 + // thread quiece mode + QUIESCE_TERM int32 = 1 + QUIESCE_FORCE int32 = 2 + QUIESCE_QUERY int32 = 3 + QUIESCE_FREEZE int32 = 4 + QUIESCE_UNFREEZE int32 = 5 + FREEZE_THIS_THREAD int32 = 6 + FREEZE_EXIT int32 = 8 + QUIESCE_SRB int32 = 9 +) + +type Pgtha struct { + Pid uint32 // 0 + Tid0 uint32 // 4 + Tid1 uint32 + Accesspid byte // C + Accesstid byte // D + Accessasid uint16 // E + Loginname [8]byte // 10 + Flag1 byte // 18 + Flag1b2 byte // 19 +} + +type Bpxystat_t struct { // DSECT BPXYSTAT + St_id [4]uint8 // 0 + St_length uint16 // 0x4 + St_version uint16 // 0x6 + St_mode uint32 // 0x8 + St_ino uint32 // 0xc + St_dev uint32 // 0x10 + St_nlink uint32 // 0x14 + St_uid uint32 // 0x18 + St_gid uint32 // 0x1c + St_size uint64 // 0x20 + St_atime uint32 // 0x28 + St_mtime uint32 // 0x2c + St_ctime uint32 // 0x30 + St_rdev uint32 // 0x34 + St_auditoraudit uint32 // 0x38 + St_useraudit uint32 // 0x3c + St_blksize uint32 // 0x40 + St_createtime uint32 // 0x44 + St_auditid [4]uint32 // 0x48 + St_res01 uint32 // 0x58 + Ft_ccsid uint16 // 0x5c + Ft_flags uint16 // 0x5e + St_res01a [2]uint32 // 0x60 + St_res02 uint32 // 0x68 + St_blocks uint32 // 0x6c + St_opaque [3]uint8 // 0x70 + St_visible uint8 // 0x73 + St_reftime uint32 // 0x74 + St_fid uint64 // 0x78 + St_filefmt uint8 // 0x80 + St_fspflag2 uint8 // 0x81 + St_res03 [2]uint8 // 0x82 + St_ctimemsec uint32 // 0x84 + St_seclabel [8]uint8 // 0x88 + St_res04 [4]uint8 // 0x90 + // end of version 1 + _ uint32 // 0x94 + St_atime64 uint64 // 0x98 + St_mtime64 uint64 // 0xa0 + St_ctime64 uint64 // 0xa8 + St_createtime64 uint64 // 0xb0 + St_reftime64 uint64 // 0xb8 + _ uint64 // 0xc0 + St_res05 [16]uint8 // 0xc8 + // end of version 2 +} + +type BpxFilestatus struct { + Oflag1 byte + Oflag2 byte + Oflag3 byte + Oflag4 byte +} + +type BpxMode struct { + Ftype byte + Mode1 byte + Mode2 byte + Mode3 byte +} + +// Thr attribute structure for extended attributes +type Bpxyatt_t struct { // DSECT BPXYATT + Att_id [4]uint8 + Att_version uint16 + Att_res01 [2]uint8 + Att_setflags1 uint8 + Att_setflags2 uint8 + Att_setflags3 uint8 + Att_setflags4 uint8 + Att_mode uint32 + Att_uid uint32 + Att_gid uint32 + Att_opaquemask [3]uint8 + Att_visblmaskres uint8 + Att_opaque [3]uint8 + Att_visibleres uint8 + Att_size_h uint32 + Att_size_l uint32 + Att_atime uint32 + Att_mtime uint32 + Att_auditoraudit uint32 + Att_useraudit uint32 + Att_ctime uint32 + Att_reftime uint32 + // end of version 1 + Att_filefmt uint8 + Att_res02 [3]uint8 + Att_filetag uint32 + Att_res03 [8]uint8 + // end of version 2 + Att_atime64 uint64 + Att_mtime64 uint64 + Att_ctime64 uint64 + Att_reftime64 uint64 + Att_seclabel [8]uint8 + Att_ver3res02 [8]uint8 + // end of version 3 +} + +func BpxOpen(name string, options *BpxFilestatus, mode *BpxMode) (rv int32, rc int32, rn int32) { + if len(name) < 1024 { + var namebuf [1024]byte + sz := int32(copy(namebuf[:], name)) + A2e(namebuf[:sz]) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(options) + parms[3] = unsafe.Pointer(mode) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4OPN) + return rv, rc, rn + } + return -1, -1, -1 +} + +func BpxClose(fd int32) (rv int32, rc int32, rn int32) { + var parms [4]unsafe.Pointer + parms[0] = unsafe.Pointer(&fd) + parms[1] = unsafe.Pointer(&rv) + parms[2] = unsafe.Pointer(&rc) + parms[3] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4CLO) + return rv, rc, rn +} + +func BpxFileFStat(fd int32, st *Bpxystat_t) (rv int32, rc int32, rn int32) { + st.St_id = [4]uint8{0xe2, 0xe3, 0xc1, 0xe3} + st.St_version = 2 + stat_sz := uint32(unsafe.Sizeof(*st)) + var parms [6]unsafe.Pointer + parms[0] = unsafe.Pointer(&fd) + parms[1] = unsafe.Pointer(&stat_sz) + parms[2] = unsafe.Pointer(st) + parms[3] = unsafe.Pointer(&rv) + parms[4] = unsafe.Pointer(&rc) + parms[5] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4FST) + return rv, rc, rn +} + +func BpxFileStat(name string, st *Bpxystat_t) (rv int32, rc int32, rn int32) { + if len(name) < 1024 { + var namebuf [1024]byte + sz := int32(copy(namebuf[:], name)) + A2e(namebuf[:sz]) + st.St_id = [4]uint8{0xe2, 0xe3, 0xc1, 0xe3} + st.St_version = 2 + stat_sz := uint32(unsafe.Sizeof(*st)) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(&stat_sz) + parms[3] = unsafe.Pointer(st) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4STA) + return rv, rc, rn + } + return -1, -1, -1 +} + +func BpxFileLStat(name string, st *Bpxystat_t) (rv int32, rc int32, rn int32) { + if len(name) < 1024 { + var namebuf [1024]byte + sz := int32(copy(namebuf[:], name)) + A2e(namebuf[:sz]) + st.St_id = [4]uint8{0xe2, 0xe3, 0xc1, 0xe3} + st.St_version = 2 + stat_sz := uint32(unsafe.Sizeof(*st)) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(&stat_sz) + parms[3] = unsafe.Pointer(st) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4LST) + return rv, rc, rn + } + return -1, -1, -1 +} + +func BpxChattr(path string, attr *Bpxyatt_t) (rv int32, rc int32, rn int32) { + if len(path) >= 1024 { + return -1, -1, -1 + } + var namebuf [1024]byte + sz := int32(copy(namebuf[:], path)) + A2e(namebuf[:sz]) + attr_sz := uint32(unsafe.Sizeof(*attr)) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(&attr_sz) + parms[3] = unsafe.Pointer(attr) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4CHR) + return rv, rc, rn +} + +func BpxLchattr(path string, attr *Bpxyatt_t) (rv int32, rc int32, rn int32) { + if len(path) >= 1024 { + return -1, -1, -1 + } + var namebuf [1024]byte + sz := int32(copy(namebuf[:], path)) + A2e(namebuf[:sz]) + attr_sz := uint32(unsafe.Sizeof(*attr)) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(&attr_sz) + parms[3] = unsafe.Pointer(attr) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4LCR) + return rv, rc, rn +} + +func BpxFchattr(fd int32, attr *Bpxyatt_t) (rv int32, rc int32, rn int32) { + attr_sz := uint32(unsafe.Sizeof(*attr)) + var parms [6]unsafe.Pointer + parms[0] = unsafe.Pointer(&fd) + parms[1] = unsafe.Pointer(&attr_sz) + parms[2] = unsafe.Pointer(attr) + parms[3] = unsafe.Pointer(&rv) + parms[4] = unsafe.Pointer(&rc) + parms[5] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4FCR) + return rv, rc, rn +} + +func BpxCondTimedWait(sec uint32, nsec uint32, events uint32, secrem *uint32, nsecrem *uint32) (rv int32, rc int32, rn int32) { + var parms [8]unsafe.Pointer + parms[0] = unsafe.Pointer(&sec) + parms[1] = unsafe.Pointer(&nsec) + parms[2] = unsafe.Pointer(&events) + parms[3] = unsafe.Pointer(secrem) + parms[4] = unsafe.Pointer(nsecrem) + parms[5] = unsafe.Pointer(&rv) + parms[6] = unsafe.Pointer(&rc) + parms[7] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4CTW) + return rv, rc, rn +} +func BpxGetthent(in *Pgtha, outlen *uint32, out unsafe.Pointer) (rv int32, rc int32, rn int32) { + var parms [7]unsafe.Pointer + inlen := uint32(26) // nothing else will work. Go says Pgtha is 28-byte because of alignment, but Pgtha is "packed" and must be 26-byte + parms[0] = unsafe.Pointer(&inlen) + parms[1] = unsafe.Pointer(&in) + parms[2] = unsafe.Pointer(outlen) + parms[3] = unsafe.Pointer(&out) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4GTH) + return rv, rc, rn +} +func ZosJobname() (jobname string, err error) { + var pgtha Pgtha + pgtha.Pid = uint32(Getpid()) + pgtha.Accesspid = PGTHA_CURRENT + pgtha.Flag1 = PGTHA_PROCESS + var out [256]byte + var outlen uint32 + outlen = 256 + rv, rc, rn := BpxGetthent(&pgtha, &outlen, unsafe.Pointer(&out[0])) + if rv == 0 { + gthc := []byte{0x87, 0xa3, 0x88, 0x83} // 'gthc' in ebcdic + ix := bytes.Index(out[:], gthc) + if ix == -1 { + err = fmt.Errorf("BPX4GTH: gthc return data not found") + return + } + jn := out[ix+80 : ix+88] // we didn't declare Pgthc, but jobname is 8-byte at offset 80 + E2a(jn) + jobname = string(bytes.TrimRight(jn, " ")) + + } else { + err = fmt.Errorf("BPX4GTH: rc=%d errno=%d reason=code=0x%x", rv, rc, rn) + } + return +} +func Bpx4ptq(code int32, data string) (rv int32, rc int32, rn int32) { + var userdata [8]byte + var parms [5]unsafe.Pointer + copy(userdata[:], data+" ") + A2e(userdata[:]) + parms[0] = unsafe.Pointer(&code) + parms[1] = unsafe.Pointer(&userdata[0]) + parms[2] = unsafe.Pointer(&rv) + parms[3] = unsafe.Pointer(&rc) + parms[4] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4PTQ) + return rv, rc, rn +} + +const ( + PT_TRACE_ME = 0 // Debug this process + PT_READ_I = 1 // Read a full word + PT_READ_D = 2 // Read a full word + PT_READ_U = 3 // Read control info + PT_WRITE_I = 4 //Write a full word + PT_WRITE_D = 5 //Write a full word + PT_CONTINUE = 7 //Continue the process + PT_KILL = 8 //Terminate the process + PT_READ_GPR = 11 // Read GPR, CR, PSW + PT_READ_FPR = 12 // Read FPR + PT_READ_VR = 13 // Read VR + PT_WRITE_GPR = 14 // Write GPR, CR, PSW + PT_WRITE_FPR = 15 // Write FPR + PT_WRITE_VR = 16 // Write VR + PT_READ_BLOCK = 17 // Read storage + PT_WRITE_BLOCK = 19 // Write storage + PT_READ_GPRH = 20 // Read GPRH + PT_WRITE_GPRH = 21 // Write GPRH + PT_REGHSET = 22 // Read all GPRHs + PT_ATTACH = 30 // Attach to a process + PT_DETACH = 31 // Detach from a process + PT_REGSET = 32 // Read all GPRs + PT_REATTACH = 33 // Reattach to a process + PT_LDINFO = 34 // Read loader info + PT_MULTI = 35 // Multi process mode + PT_LD64INFO = 36 // RMODE64 Info Area + PT_BLOCKREQ = 40 // Block request + PT_THREAD_INFO = 60 // Read thread info + PT_THREAD_MODIFY = 61 + PT_THREAD_READ_FOCUS = 62 + PT_THREAD_WRITE_FOCUS = 63 + PT_THREAD_HOLD = 64 + PT_THREAD_SIGNAL = 65 + PT_EXPLAIN = 66 + PT_EVENTS = 67 + PT_THREAD_INFO_EXTENDED = 68 + PT_REATTACH2 = 71 + PT_CAPTURE = 72 + PT_UNCAPTURE = 73 + PT_GET_THREAD_TCB = 74 + PT_GET_ALET = 75 + PT_SWAPIN = 76 + PT_EXTENDED_EVENT = 98 + PT_RECOVER = 99 // Debug a program check + PT_GPR0 = 0 // General purpose register 0 + PT_GPR1 = 1 // General purpose register 1 + PT_GPR2 = 2 // General purpose register 2 + PT_GPR3 = 3 // General purpose register 3 + PT_GPR4 = 4 // General purpose register 4 + PT_GPR5 = 5 // General purpose register 5 + PT_GPR6 = 6 // General purpose register 6 + PT_GPR7 = 7 // General purpose register 7 + PT_GPR8 = 8 // General purpose register 8 + PT_GPR9 = 9 // General purpose register 9 + PT_GPR10 = 10 // General purpose register 10 + PT_GPR11 = 11 // General purpose register 11 + PT_GPR12 = 12 // General purpose register 12 + PT_GPR13 = 13 // General purpose register 13 + PT_GPR14 = 14 // General purpose register 14 + PT_GPR15 = 15 // General purpose register 15 + PT_FPR0 = 16 // Floating point register 0 + PT_FPR1 = 17 // Floating point register 1 + PT_FPR2 = 18 // Floating point register 2 + PT_FPR3 = 19 // Floating point register 3 + PT_FPR4 = 20 // Floating point register 4 + PT_FPR5 = 21 // Floating point register 5 + PT_FPR6 = 22 // Floating point register 6 + PT_FPR7 = 23 // Floating point register 7 + PT_FPR8 = 24 // Floating point register 8 + PT_FPR9 = 25 // Floating point register 9 + PT_FPR10 = 26 // Floating point register 10 + PT_FPR11 = 27 // Floating point register 11 + PT_FPR12 = 28 // Floating point register 12 + PT_FPR13 = 29 // Floating point register 13 + PT_FPR14 = 30 // Floating point register 14 + PT_FPR15 = 31 // Floating point register 15 + PT_FPC = 32 // Floating point control register + PT_PSW = 40 // PSW + PT_PSW0 = 40 // Left half of the PSW + PT_PSW1 = 41 // Right half of the PSW + PT_CR0 = 42 // Control register 0 + PT_CR1 = 43 // Control register 1 + PT_CR2 = 44 // Control register 2 + PT_CR3 = 45 // Control register 3 + PT_CR4 = 46 // Control register 4 + PT_CR5 = 47 // Control register 5 + PT_CR6 = 48 // Control register 6 + PT_CR7 = 49 // Control register 7 + PT_CR8 = 50 // Control register 8 + PT_CR9 = 51 // Control register 9 + PT_CR10 = 52 // Control register 10 + PT_CR11 = 53 // Control register 11 + PT_CR12 = 54 // Control register 12 + PT_CR13 = 55 // Control register 13 + PT_CR14 = 56 // Control register 14 + PT_CR15 = 57 // Control register 15 + PT_GPRH0 = 58 // GP High register 0 + PT_GPRH1 = 59 // GP High register 1 + PT_GPRH2 = 60 // GP High register 2 + PT_GPRH3 = 61 // GP High register 3 + PT_GPRH4 = 62 // GP High register 4 + PT_GPRH5 = 63 // GP High register 5 + PT_GPRH6 = 64 // GP High register 6 + PT_GPRH7 = 65 // GP High register 7 + PT_GPRH8 = 66 // GP High register 8 + PT_GPRH9 = 67 // GP High register 9 + PT_GPRH10 = 68 // GP High register 10 + PT_GPRH11 = 69 // GP High register 11 + PT_GPRH12 = 70 // GP High register 12 + PT_GPRH13 = 71 // GP High register 13 + PT_GPRH14 = 72 // GP High register 14 + PT_GPRH15 = 73 // GP High register 15 + PT_VR0 = 74 // Vector register 0 + PT_VR1 = 75 // Vector register 1 + PT_VR2 = 76 // Vector register 2 + PT_VR3 = 77 // Vector register 3 + PT_VR4 = 78 // Vector register 4 + PT_VR5 = 79 // Vector register 5 + PT_VR6 = 80 // Vector register 6 + PT_VR7 = 81 // Vector register 7 + PT_VR8 = 82 // Vector register 8 + PT_VR9 = 83 // Vector register 9 + PT_VR10 = 84 // Vector register 10 + PT_VR11 = 85 // Vector register 11 + PT_VR12 = 86 // Vector register 12 + PT_VR13 = 87 // Vector register 13 + PT_VR14 = 88 // Vector register 14 + PT_VR15 = 89 // Vector register 15 + PT_VR16 = 90 // Vector register 16 + PT_VR17 = 91 // Vector register 17 + PT_VR18 = 92 // Vector register 18 + PT_VR19 = 93 // Vector register 19 + PT_VR20 = 94 // Vector register 20 + PT_VR21 = 95 // Vector register 21 + PT_VR22 = 96 // Vector register 22 + PT_VR23 = 97 // Vector register 23 + PT_VR24 = 98 // Vector register 24 + PT_VR25 = 99 // Vector register 25 + PT_VR26 = 100 // Vector register 26 + PT_VR27 = 101 // Vector register 27 + PT_VR28 = 102 // Vector register 28 + PT_VR29 = 103 // Vector register 29 + PT_VR30 = 104 // Vector register 30 + PT_VR31 = 105 // Vector register 31 + PT_PSWG = 106 // PSWG + PT_PSWG0 = 106 // Bytes 0-3 + PT_PSWG1 = 107 // Bytes 4-7 + PT_PSWG2 = 108 // Bytes 8-11 (IA high word) + PT_PSWG3 = 109 // Bytes 12-15 (IA low word) +) + +func Bpx4ptr(request int32, pid int32, addr unsafe.Pointer, data unsafe.Pointer, buffer unsafe.Pointer) (rv int32, rc int32, rn int32) { + var parms [8]unsafe.Pointer + parms[0] = unsafe.Pointer(&request) + parms[1] = unsafe.Pointer(&pid) + parms[2] = unsafe.Pointer(&addr) + parms[3] = unsafe.Pointer(&data) + parms[4] = unsafe.Pointer(&buffer) + parms[5] = unsafe.Pointer(&rv) + parms[6] = unsafe.Pointer(&rc) + parms[7] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4PTR) + return rv, rc, rn +} + +func copyU8(val uint8, dest []uint8) int { + if len(dest) < 1 { + return 0 + } + dest[0] = val + return 1 +} + +func copyU8Arr(src, dest []uint8) int { + if len(dest) < len(src) { + return 0 + } + for i, v := range src { + dest[i] = v + } + return len(src) +} + +func copyU16(val uint16, dest []uint16) int { + if len(dest) < 1 { + return 0 + } + dest[0] = val + return 1 +} + +func copyU32(val uint32, dest []uint32) int { + if len(dest) < 1 { + return 0 + } + dest[0] = val + return 1 +} + +func copyU32Arr(src, dest []uint32) int { + if len(dest) < len(src) { + return 0 + } + for i, v := range src { + dest[i] = v + } + return len(src) +} + +func copyU64(val uint64, dest []uint64) int { + if len(dest) < 1 { + return 0 + } + dest[0] = val + return 1 +} diff --git a/vendor/golang.org/x/sys/unix/bpxsvc_zos.s b/vendor/golang.org/x/sys/unix/bpxsvc_zos.s new file mode 100644 index 00000000..4bd4a179 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/bpxsvc_zos.s @@ -0,0 +1,192 @@ +// Copyright 2024 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. + +#include "go_asm.h" +#include "textflag.h" + +// function to call USS assembly language services +// +// doc: https://www.ibm.com/support/knowledgecenter/en/SSLTBW_3.1.0/com.ibm.zos.v3r1.bpxb100/bit64env.htm +// +// arg1 unsafe.Pointer array that ressembles an OS PLIST +// +// arg2 function offset as in +// doc: https://www.ibm.com/support/knowledgecenter/en/SSLTBW_3.1.0/com.ibm.zos.v3r1.bpxb100/bpx2cr_List_of_offsets.htm +// +// func bpxcall(plist []unsafe.Pointer, bpx_offset int64) + +TEXT ·bpxcall(SB), NOSPLIT|NOFRAME, $0 + MOVD plist_base+0(FP), R1 // r1 points to plist + MOVD bpx_offset+24(FP), R2 // r2 offset to BPX vector table + MOVD R14, R7 // save r14 + MOVD R15, R8 // save r15 + MOVWZ 16(R0), R9 + MOVWZ 544(R9), R9 + MOVWZ 24(R9), R9 // call vector in r9 + ADD R2, R9 // add offset to vector table + MOVWZ (R9), R9 // r9 points to entry point + BYTE $0x0D // BL R14,R9 --> basr r14,r9 + BYTE $0xE9 // clobbers 0,1,14,15 + MOVD R8, R15 // restore 15 + JMP R7 // return via saved return address + +// func A2e(arr [] byte) +// code page conversion from 819 to 1047 +TEXT ·A2e(SB), NOSPLIT|NOFRAME, $0 + MOVD arg_base+0(FP), R2 // pointer to arry of characters + MOVD arg_len+8(FP), R3 // count + XOR R0, R0 + XOR R1, R1 + BYTE $0xA7; BYTE $0x15; BYTE $0x00; BYTE $0x82 // BRAS 1,(2+(256/2)) + + // ASCII -> EBCDIC conversion table: + BYTE $0x00; BYTE $0x01; BYTE $0x02; BYTE $0x03 + BYTE $0x37; BYTE $0x2d; BYTE $0x2e; BYTE $0x2f + BYTE $0x16; BYTE $0x05; BYTE $0x15; BYTE $0x0b + BYTE $0x0c; BYTE $0x0d; BYTE $0x0e; BYTE $0x0f + BYTE $0x10; BYTE $0x11; BYTE $0x12; BYTE $0x13 + BYTE $0x3c; BYTE $0x3d; BYTE $0x32; BYTE $0x26 + BYTE $0x18; BYTE $0x19; BYTE $0x3f; BYTE $0x27 + BYTE $0x1c; BYTE $0x1d; BYTE $0x1e; BYTE $0x1f + BYTE $0x40; BYTE $0x5a; BYTE $0x7f; BYTE $0x7b + BYTE $0x5b; BYTE $0x6c; BYTE $0x50; BYTE $0x7d + BYTE $0x4d; BYTE $0x5d; BYTE $0x5c; BYTE $0x4e + BYTE $0x6b; BYTE $0x60; BYTE $0x4b; BYTE $0x61 + BYTE $0xf0; BYTE $0xf1; BYTE $0xf2; BYTE $0xf3 + BYTE $0xf4; BYTE $0xf5; BYTE $0xf6; BYTE $0xf7 + BYTE $0xf8; BYTE $0xf9; BYTE $0x7a; BYTE $0x5e + BYTE $0x4c; BYTE $0x7e; BYTE $0x6e; BYTE $0x6f + BYTE $0x7c; BYTE $0xc1; BYTE $0xc2; BYTE $0xc3 + BYTE $0xc4; BYTE $0xc5; BYTE $0xc6; BYTE $0xc7 + BYTE $0xc8; BYTE $0xc9; BYTE $0xd1; BYTE $0xd2 + BYTE $0xd3; BYTE $0xd4; BYTE $0xd5; BYTE $0xd6 + BYTE $0xd7; BYTE $0xd8; BYTE $0xd9; BYTE $0xe2 + BYTE $0xe3; BYTE $0xe4; BYTE $0xe5; BYTE $0xe6 + BYTE $0xe7; BYTE $0xe8; BYTE $0xe9; BYTE $0xad + BYTE $0xe0; BYTE $0xbd; BYTE $0x5f; BYTE $0x6d + BYTE $0x79; BYTE $0x81; BYTE $0x82; BYTE $0x83 + BYTE $0x84; BYTE $0x85; BYTE $0x86; BYTE $0x87 + BYTE $0x88; BYTE $0x89; BYTE $0x91; BYTE $0x92 + BYTE $0x93; BYTE $0x94; BYTE $0x95; BYTE $0x96 + BYTE $0x97; BYTE $0x98; BYTE $0x99; BYTE $0xa2 + BYTE $0xa3; BYTE $0xa4; BYTE $0xa5; BYTE $0xa6 + BYTE $0xa7; BYTE $0xa8; BYTE $0xa9; BYTE $0xc0 + BYTE $0x4f; BYTE $0xd0; BYTE $0xa1; BYTE $0x07 + BYTE $0x20; BYTE $0x21; BYTE $0x22; BYTE $0x23 + BYTE $0x24; BYTE $0x25; BYTE $0x06; BYTE $0x17 + BYTE $0x28; BYTE $0x29; BYTE $0x2a; BYTE $0x2b + BYTE $0x2c; BYTE $0x09; BYTE $0x0a; BYTE $0x1b + BYTE $0x30; BYTE $0x31; BYTE $0x1a; BYTE $0x33 + BYTE $0x34; BYTE $0x35; BYTE $0x36; BYTE $0x08 + BYTE $0x38; BYTE $0x39; BYTE $0x3a; BYTE $0x3b + BYTE $0x04; BYTE $0x14; BYTE $0x3e; BYTE $0xff + BYTE $0x41; BYTE $0xaa; BYTE $0x4a; BYTE $0xb1 + BYTE $0x9f; BYTE $0xb2; BYTE $0x6a; BYTE $0xb5 + BYTE $0xbb; BYTE $0xb4; BYTE $0x9a; BYTE $0x8a + BYTE $0xb0; BYTE $0xca; BYTE $0xaf; BYTE $0xbc + BYTE $0x90; BYTE $0x8f; BYTE $0xea; BYTE $0xfa + BYTE $0xbe; BYTE $0xa0; BYTE $0xb6; BYTE $0xb3 + BYTE $0x9d; BYTE $0xda; BYTE $0x9b; BYTE $0x8b + BYTE $0xb7; BYTE $0xb8; BYTE $0xb9; BYTE $0xab + BYTE $0x64; BYTE $0x65; BYTE $0x62; BYTE $0x66 + BYTE $0x63; BYTE $0x67; BYTE $0x9e; BYTE $0x68 + BYTE $0x74; BYTE $0x71; BYTE $0x72; BYTE $0x73 + BYTE $0x78; BYTE $0x75; BYTE $0x76; BYTE $0x77 + BYTE $0xac; BYTE $0x69; BYTE $0xed; BYTE $0xee + BYTE $0xeb; BYTE $0xef; BYTE $0xec; BYTE $0xbf + BYTE $0x80; BYTE $0xfd; BYTE $0xfe; BYTE $0xfb + BYTE $0xfc; BYTE $0xba; BYTE $0xae; BYTE $0x59 + BYTE $0x44; BYTE $0x45; BYTE $0x42; BYTE $0x46 + BYTE $0x43; BYTE $0x47; BYTE $0x9c; BYTE $0x48 + BYTE $0x54; BYTE $0x51; BYTE $0x52; BYTE $0x53 + BYTE $0x58; BYTE $0x55; BYTE $0x56; BYTE $0x57 + BYTE $0x8c; BYTE $0x49; BYTE $0xcd; BYTE $0xce + BYTE $0xcb; BYTE $0xcf; BYTE $0xcc; BYTE $0xe1 + BYTE $0x70; BYTE $0xdd; BYTE $0xde; BYTE $0xdb + BYTE $0xdc; BYTE $0x8d; BYTE $0x8e; BYTE $0xdf + +retry: + WORD $0xB9931022 // TROO 2,2,b'0001' + BVS retry + RET + +// func e2a(arr [] byte) +// code page conversion from 1047 to 819 +TEXT ·E2a(SB), NOSPLIT|NOFRAME, $0 + MOVD arg_base+0(FP), R2 // pointer to arry of characters + MOVD arg_len+8(FP), R3 // count + XOR R0, R0 + XOR R1, R1 + BYTE $0xA7; BYTE $0x15; BYTE $0x00; BYTE $0x82 // BRAS 1,(2+(256/2)) + + // EBCDIC -> ASCII conversion table: + BYTE $0x00; BYTE $0x01; BYTE $0x02; BYTE $0x03 + BYTE $0x9c; BYTE $0x09; BYTE $0x86; BYTE $0x7f + BYTE $0x97; BYTE $0x8d; BYTE $0x8e; BYTE $0x0b + BYTE $0x0c; BYTE $0x0d; BYTE $0x0e; BYTE $0x0f + BYTE $0x10; BYTE $0x11; BYTE $0x12; BYTE $0x13 + BYTE $0x9d; BYTE $0x0a; BYTE $0x08; BYTE $0x87 + BYTE $0x18; BYTE $0x19; BYTE $0x92; BYTE $0x8f + BYTE $0x1c; BYTE $0x1d; BYTE $0x1e; BYTE $0x1f + BYTE $0x80; BYTE $0x81; BYTE $0x82; BYTE $0x83 + BYTE $0x84; BYTE $0x85; BYTE $0x17; BYTE $0x1b + BYTE $0x88; BYTE $0x89; BYTE $0x8a; BYTE $0x8b + BYTE $0x8c; BYTE $0x05; BYTE $0x06; BYTE $0x07 + BYTE $0x90; BYTE $0x91; BYTE $0x16; BYTE $0x93 + BYTE $0x94; BYTE $0x95; BYTE $0x96; BYTE $0x04 + BYTE $0x98; BYTE $0x99; BYTE $0x9a; BYTE $0x9b + BYTE $0x14; BYTE $0x15; BYTE $0x9e; BYTE $0x1a + BYTE $0x20; BYTE $0xa0; BYTE $0xe2; BYTE $0xe4 + BYTE $0xe0; BYTE $0xe1; BYTE $0xe3; BYTE $0xe5 + BYTE $0xe7; BYTE $0xf1; BYTE $0xa2; BYTE $0x2e + BYTE $0x3c; BYTE $0x28; BYTE $0x2b; BYTE $0x7c + BYTE $0x26; BYTE $0xe9; BYTE $0xea; BYTE $0xeb + BYTE $0xe8; BYTE $0xed; BYTE $0xee; BYTE $0xef + BYTE $0xec; BYTE $0xdf; BYTE $0x21; BYTE $0x24 + BYTE $0x2a; BYTE $0x29; BYTE $0x3b; BYTE $0x5e + BYTE $0x2d; BYTE $0x2f; BYTE $0xc2; BYTE $0xc4 + BYTE $0xc0; BYTE $0xc1; BYTE $0xc3; BYTE $0xc5 + BYTE $0xc7; BYTE $0xd1; BYTE $0xa6; BYTE $0x2c + BYTE $0x25; BYTE $0x5f; BYTE $0x3e; BYTE $0x3f + BYTE $0xf8; BYTE $0xc9; BYTE $0xca; BYTE $0xcb + BYTE $0xc8; BYTE $0xcd; BYTE $0xce; BYTE $0xcf + BYTE $0xcc; BYTE $0x60; BYTE $0x3a; BYTE $0x23 + BYTE $0x40; BYTE $0x27; BYTE $0x3d; BYTE $0x22 + BYTE $0xd8; BYTE $0x61; BYTE $0x62; BYTE $0x63 + BYTE $0x64; BYTE $0x65; BYTE $0x66; BYTE $0x67 + BYTE $0x68; BYTE $0x69; BYTE $0xab; BYTE $0xbb + BYTE $0xf0; BYTE $0xfd; BYTE $0xfe; BYTE $0xb1 + BYTE $0xb0; BYTE $0x6a; BYTE $0x6b; BYTE $0x6c + BYTE $0x6d; BYTE $0x6e; BYTE $0x6f; BYTE $0x70 + BYTE $0x71; BYTE $0x72; BYTE $0xaa; BYTE $0xba + BYTE $0xe6; BYTE $0xb8; BYTE $0xc6; BYTE $0xa4 + BYTE $0xb5; BYTE $0x7e; BYTE $0x73; BYTE $0x74 + BYTE $0x75; BYTE $0x76; BYTE $0x77; BYTE $0x78 + BYTE $0x79; BYTE $0x7a; BYTE $0xa1; BYTE $0xbf + BYTE $0xd0; BYTE $0x5b; BYTE $0xde; BYTE $0xae + BYTE $0xac; BYTE $0xa3; BYTE $0xa5; BYTE $0xb7 + BYTE $0xa9; BYTE $0xa7; BYTE $0xb6; BYTE $0xbc + BYTE $0xbd; BYTE $0xbe; BYTE $0xdd; BYTE $0xa8 + BYTE $0xaf; BYTE $0x5d; BYTE $0xb4; BYTE $0xd7 + BYTE $0x7b; BYTE $0x41; BYTE $0x42; BYTE $0x43 + BYTE $0x44; BYTE $0x45; BYTE $0x46; BYTE $0x47 + BYTE $0x48; BYTE $0x49; BYTE $0xad; BYTE $0xf4 + BYTE $0xf6; BYTE $0xf2; BYTE $0xf3; BYTE $0xf5 + BYTE $0x7d; BYTE $0x4a; BYTE $0x4b; BYTE $0x4c + BYTE $0x4d; BYTE $0x4e; BYTE $0x4f; BYTE $0x50 + BYTE $0x51; BYTE $0x52; BYTE $0xb9; BYTE $0xfb + BYTE $0xfc; BYTE $0xf9; BYTE $0xfa; BYTE $0xff + BYTE $0x5c; BYTE $0xf7; BYTE $0x53; BYTE $0x54 + BYTE $0x55; BYTE $0x56; BYTE $0x57; BYTE $0x58 + BYTE $0x59; BYTE $0x5a; BYTE $0xb2; BYTE $0xd4 + BYTE $0xd6; BYTE $0xd2; BYTE $0xd3; BYTE $0xd5 + BYTE $0x30; BYTE $0x31; BYTE $0x32; BYTE $0x33 + BYTE $0x34; BYTE $0x35; BYTE $0x36; BYTE $0x37 + BYTE $0x38; BYTE $0x39; BYTE $0xb3; BYTE $0xdb + BYTE $0xdc; BYTE $0xd9; BYTE $0xda; BYTE $0x9f + +retry: + WORD $0xB9931022 // TROO 2,2,b'0001' + BVS retry + RET diff --git a/vendor/golang.org/x/sys/unix/epoll_zos.go b/vendor/golang.org/x/sys/unix/epoll_zos.go deleted file mode 100644 index 7753fdde..00000000 --- a/vendor/golang.org/x/sys/unix/epoll_zos.go +++ /dev/null @@ -1,220 +0,0 @@ -// Copyright 2020 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. - -//go:build zos && s390x - -package unix - -import ( - "sync" -) - -// This file simulates epoll on z/OS using poll. - -// Analogous to epoll_event on Linux. -// TODO(neeilan): Pad is because the Linux kernel expects a 96-bit struct. We never pass this to the kernel; remove? -type EpollEvent struct { - Events uint32 - Fd int32 - Pad int32 -} - -const ( - EPOLLERR = 0x8 - EPOLLHUP = 0x10 - EPOLLIN = 0x1 - EPOLLMSG = 0x400 - EPOLLOUT = 0x4 - EPOLLPRI = 0x2 - EPOLLRDBAND = 0x80 - EPOLLRDNORM = 0x40 - EPOLLWRBAND = 0x200 - EPOLLWRNORM = 0x100 - EPOLL_CTL_ADD = 0x1 - EPOLL_CTL_DEL = 0x2 - EPOLL_CTL_MOD = 0x3 - // The following constants are part of the epoll API, but represent - // currently unsupported functionality on z/OS. - // EPOLL_CLOEXEC = 0x80000 - // EPOLLET = 0x80000000 - // EPOLLONESHOT = 0x40000000 - // EPOLLRDHUP = 0x2000 // Typically used with edge-triggered notis - // EPOLLEXCLUSIVE = 0x10000000 // Exclusive wake-up mode - // EPOLLWAKEUP = 0x20000000 // Relies on Linux's BLOCK_SUSPEND capability -) - -// TODO(neeilan): We can eliminate these epToPoll / pToEpoll calls by using identical mask values for POLL/EPOLL -// constants where possible The lower 16 bits of epoll events (uint32) can fit any system poll event (int16). - -// epToPollEvt converts epoll event field to poll equivalent. -// In epoll, Events is a 32-bit field, while poll uses 16 bits. -func epToPollEvt(events uint32) int16 { - var ep2p = map[uint32]int16{ - EPOLLIN: POLLIN, - EPOLLOUT: POLLOUT, - EPOLLHUP: POLLHUP, - EPOLLPRI: POLLPRI, - EPOLLERR: POLLERR, - } - - var pollEvts int16 = 0 - for epEvt, pEvt := range ep2p { - if (events & epEvt) != 0 { - pollEvts |= pEvt - } - } - - return pollEvts -} - -// pToEpollEvt converts 16 bit poll event bitfields to 32-bit epoll event fields. -func pToEpollEvt(revents int16) uint32 { - var p2ep = map[int16]uint32{ - POLLIN: EPOLLIN, - POLLOUT: EPOLLOUT, - POLLHUP: EPOLLHUP, - POLLPRI: EPOLLPRI, - POLLERR: EPOLLERR, - } - - var epollEvts uint32 = 0 - for pEvt, epEvt := range p2ep { - if (revents & pEvt) != 0 { - epollEvts |= epEvt - } - } - - return epollEvts -} - -// Per-process epoll implementation. -type epollImpl struct { - mu sync.Mutex - epfd2ep map[int]*eventPoll - nextEpfd int -} - -// eventPoll holds a set of file descriptors being watched by the process. A process can have multiple epoll instances. -// On Linux, this is an in-kernel data structure accessed through a fd. -type eventPoll struct { - mu sync.Mutex - fds map[int]*EpollEvent -} - -// epoll impl for this process. -var impl epollImpl = epollImpl{ - epfd2ep: make(map[int]*eventPoll), - nextEpfd: 0, -} - -func (e *epollImpl) epollcreate(size int) (epfd int, err error) { - e.mu.Lock() - defer e.mu.Unlock() - epfd = e.nextEpfd - e.nextEpfd++ - - e.epfd2ep[epfd] = &eventPoll{ - fds: make(map[int]*EpollEvent), - } - return epfd, nil -} - -func (e *epollImpl) epollcreate1(flag int) (fd int, err error) { - return e.epollcreate(4) -} - -func (e *epollImpl) epollctl(epfd int, op int, fd int, event *EpollEvent) (err error) { - e.mu.Lock() - defer e.mu.Unlock() - - ep, ok := e.epfd2ep[epfd] - if !ok { - - return EBADF - } - - switch op { - case EPOLL_CTL_ADD: - // TODO(neeilan): When we make epfds and fds disjoint, detect epoll - // loops here (instances watching each other) and return ELOOP. - if _, ok := ep.fds[fd]; ok { - return EEXIST - } - ep.fds[fd] = event - case EPOLL_CTL_MOD: - if _, ok := ep.fds[fd]; !ok { - return ENOENT - } - ep.fds[fd] = event - case EPOLL_CTL_DEL: - if _, ok := ep.fds[fd]; !ok { - return ENOENT - } - delete(ep.fds, fd) - - } - return nil -} - -// Must be called while holding ep.mu -func (ep *eventPoll) getFds() []int { - fds := make([]int, len(ep.fds)) - for fd := range ep.fds { - fds = append(fds, fd) - } - return fds -} - -func (e *epollImpl) epollwait(epfd int, events []EpollEvent, msec int) (n int, err error) { - e.mu.Lock() // in [rare] case of concurrent epollcreate + epollwait - ep, ok := e.epfd2ep[epfd] - - if !ok { - e.mu.Unlock() - return 0, EBADF - } - - pollfds := make([]PollFd, 4) - for fd, epollevt := range ep.fds { - pollfds = append(pollfds, PollFd{Fd: int32(fd), Events: epToPollEvt(epollevt.Events)}) - } - e.mu.Unlock() - - n, err = Poll(pollfds, msec) - if err != nil { - return n, err - } - - i := 0 - for _, pFd := range pollfds { - if pFd.Revents != 0 { - events[i] = EpollEvent{Fd: pFd.Fd, Events: pToEpollEvt(pFd.Revents)} - i++ - } - - if i == n { - break - } - } - - return n, nil -} - -func EpollCreate(size int) (fd int, err error) { - return impl.epollcreate(size) -} - -func EpollCreate1(flag int) (fd int, err error) { - return impl.epollcreate1(flag) -} - -func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { - return impl.epollctl(epfd, op, fd, event) -} - -// Because EpollWait mutates events, the caller is expected to coordinate -// concurrent access if calling with the same epfd from multiple goroutines. -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - return impl.epollwait(epfd, events, msec) -} diff --git a/vendor/golang.org/x/sys/unix/fcntl.go b/vendor/golang.org/x/sys/unix/fcntl.go index 58c6bfc7..6200876f 100644 --- a/vendor/golang.org/x/sys/unix/fcntl.go +++ b/vendor/golang.org/x/sys/unix/fcntl.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build dragonfly || freebsd || linux || netbsd || openbsd +//go:build dragonfly || freebsd || linux || netbsd package unix diff --git a/vendor/golang.org/x/sys/unix/fstatfs_zos.go b/vendor/golang.org/x/sys/unix/fstatfs_zos.go deleted file mode 100644 index c8bde601..00000000 --- a/vendor/golang.org/x/sys/unix/fstatfs_zos.go +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright 2020 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. - -//go:build zos && s390x - -package unix - -import ( - "unsafe" -) - -// This file simulates fstatfs on z/OS using fstatvfs and w_getmntent. - -func Fstatfs(fd int, stat *Statfs_t) (err error) { - var stat_v Statvfs_t - err = Fstatvfs(fd, &stat_v) - if err == nil { - // populate stat - stat.Type = 0 - stat.Bsize = stat_v.Bsize - stat.Blocks = stat_v.Blocks - stat.Bfree = stat_v.Bfree - stat.Bavail = stat_v.Bavail - stat.Files = stat_v.Files - stat.Ffree = stat_v.Ffree - stat.Fsid = stat_v.Fsid - stat.Namelen = stat_v.Namemax - stat.Frsize = stat_v.Frsize - stat.Flags = stat_v.Flag - for passn := 0; passn < 5; passn++ { - switch passn { - case 0: - err = tryGetmntent64(stat) - break - case 1: - err = tryGetmntent128(stat) - break - case 2: - err = tryGetmntent256(stat) - break - case 3: - err = tryGetmntent512(stat) - break - case 4: - err = tryGetmntent1024(stat) - break - default: - break - } - //proceed to return if: err is nil (found), err is nonnil but not ERANGE (another error occurred) - if err == nil || err != nil && err != ERANGE { - break - } - } - } - return err -} - -func tryGetmntent64(stat *Statfs_t) (err error) { - var mnt_ent_buffer struct { - header W_Mnth - filesys_info [64]W_Mntent - } - var buffer_size int = int(unsafe.Sizeof(mnt_ent_buffer)) - fs_count, err := W_Getmntent((*byte)(unsafe.Pointer(&mnt_ent_buffer)), buffer_size) - if err != nil { - return err - } - err = ERANGE //return ERANGE if no match is found in this batch - for i := 0; i < fs_count; i++ { - if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { - stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) - err = nil - break - } - } - return err -} - -func tryGetmntent128(stat *Statfs_t) (err error) { - var mnt_ent_buffer struct { - header W_Mnth - filesys_info [128]W_Mntent - } - var buffer_size int = int(unsafe.Sizeof(mnt_ent_buffer)) - fs_count, err := W_Getmntent((*byte)(unsafe.Pointer(&mnt_ent_buffer)), buffer_size) - if err != nil { - return err - } - err = ERANGE //return ERANGE if no match is found in this batch - for i := 0; i < fs_count; i++ { - if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { - stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) - err = nil - break - } - } - return err -} - -func tryGetmntent256(stat *Statfs_t) (err error) { - var mnt_ent_buffer struct { - header W_Mnth - filesys_info [256]W_Mntent - } - var buffer_size int = int(unsafe.Sizeof(mnt_ent_buffer)) - fs_count, err := W_Getmntent((*byte)(unsafe.Pointer(&mnt_ent_buffer)), buffer_size) - if err != nil { - return err - } - err = ERANGE //return ERANGE if no match is found in this batch - for i := 0; i < fs_count; i++ { - if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { - stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) - err = nil - break - } - } - return err -} - -func tryGetmntent512(stat *Statfs_t) (err error) { - var mnt_ent_buffer struct { - header W_Mnth - filesys_info [512]W_Mntent - } - var buffer_size int = int(unsafe.Sizeof(mnt_ent_buffer)) - fs_count, err := W_Getmntent((*byte)(unsafe.Pointer(&mnt_ent_buffer)), buffer_size) - if err != nil { - return err - } - err = ERANGE //return ERANGE if no match is found in this batch - for i := 0; i < fs_count; i++ { - if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { - stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) - err = nil - break - } - } - return err -} - -func tryGetmntent1024(stat *Statfs_t) (err error) { - var mnt_ent_buffer struct { - header W_Mnth - filesys_info [1024]W_Mntent - } - var buffer_size int = int(unsafe.Sizeof(mnt_ent_buffer)) - fs_count, err := W_Getmntent((*byte)(unsafe.Pointer(&mnt_ent_buffer)), buffer_size) - if err != nil { - return err - } - err = ERANGE //return ERANGE if no match is found in this batch - for i := 0; i < fs_count; i++ { - if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { - stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) - err = nil - break - } - } - return err -} diff --git a/vendor/golang.org/x/sys/unix/ioctl_linux.go b/vendor/golang.org/x/sys/unix/ioctl_linux.go index 0d12c085..7ca4fa12 100644 --- a/vendor/golang.org/x/sys/unix/ioctl_linux.go +++ b/vendor/golang.org/x/sys/unix/ioctl_linux.go @@ -58,6 +58,102 @@ func IoctlGetEthtoolDrvinfo(fd int, ifname string) (*EthtoolDrvinfo, error) { return &value, err } +// IoctlGetEthtoolTsInfo fetches ethtool timestamping and PHC +// association for the network device specified by ifname. +func IoctlGetEthtoolTsInfo(fd int, ifname string) (*EthtoolTsInfo, error) { + ifr, err := NewIfreq(ifname) + if err != nil { + return nil, err + } + + value := EthtoolTsInfo{Cmd: ETHTOOL_GET_TS_INFO} + ifrd := ifr.withData(unsafe.Pointer(&value)) + + err = ioctlIfreqData(fd, SIOCETHTOOL, &ifrd) + return &value, err +} + +// IoctlGetHwTstamp retrieves the hardware timestamping configuration +// for the network device specified by ifname. +func IoctlGetHwTstamp(fd int, ifname string) (*HwTstampConfig, error) { + ifr, err := NewIfreq(ifname) + if err != nil { + return nil, err + } + + value := HwTstampConfig{} + ifrd := ifr.withData(unsafe.Pointer(&value)) + + err = ioctlIfreqData(fd, SIOCGHWTSTAMP, &ifrd) + return &value, err +} + +// IoctlSetHwTstamp updates the hardware timestamping configuration for +// the network device specified by ifname. +func IoctlSetHwTstamp(fd int, ifname string, cfg *HwTstampConfig) error { + ifr, err := NewIfreq(ifname) + if err != nil { + return err + } + ifrd := ifr.withData(unsafe.Pointer(cfg)) + return ioctlIfreqData(fd, SIOCSHWTSTAMP, &ifrd) +} + +// FdToClockID derives the clock ID from the file descriptor number +// - see clock_gettime(3), FD_TO_CLOCKID macros. The resulting ID is +// suitable for system calls like ClockGettime. +func FdToClockID(fd int) int32 { return int32((int(^fd) << 3) | 3) } + +// IoctlPtpClockGetcaps returns the description of a given PTP device. +func IoctlPtpClockGetcaps(fd int) (*PtpClockCaps, error) { + var value PtpClockCaps + err := ioctlPtr(fd, PTP_CLOCK_GETCAPS2, unsafe.Pointer(&value)) + return &value, err +} + +// IoctlPtpSysOffsetPrecise returns a description of the clock +// offset compared to the system clock. +func IoctlPtpSysOffsetPrecise(fd int) (*PtpSysOffsetPrecise, error) { + var value PtpSysOffsetPrecise + err := ioctlPtr(fd, PTP_SYS_OFFSET_PRECISE2, unsafe.Pointer(&value)) + return &value, err +} + +// IoctlPtpSysOffsetExtended returns an extended description of the +// clock offset compared to the system clock. The samples parameter +// specifies the desired number of measurements. +func IoctlPtpSysOffsetExtended(fd int, samples uint) (*PtpSysOffsetExtended, error) { + value := PtpSysOffsetExtended{Samples: uint32(samples)} + err := ioctlPtr(fd, PTP_SYS_OFFSET_EXTENDED2, unsafe.Pointer(&value)) + return &value, err +} + +// IoctlPtpPinGetfunc returns the configuration of the specified +// I/O pin on given PTP device. +func IoctlPtpPinGetfunc(fd int, index uint) (*PtpPinDesc, error) { + value := PtpPinDesc{Index: uint32(index)} + err := ioctlPtr(fd, PTP_PIN_GETFUNC2, unsafe.Pointer(&value)) + return &value, err +} + +// IoctlPtpPinSetfunc updates configuration of the specified PTP +// I/O pin. +func IoctlPtpPinSetfunc(fd int, pd *PtpPinDesc) error { + return ioctlPtr(fd, PTP_PIN_SETFUNC2, unsafe.Pointer(pd)) +} + +// IoctlPtpPeroutRequest configures the periodic output mode of the +// PTP I/O pins. +func IoctlPtpPeroutRequest(fd int, r *PtpPeroutRequest) error { + return ioctlPtr(fd, PTP_PEROUT_REQUEST2, unsafe.Pointer(r)) +} + +// IoctlPtpExttsRequest configures the external timestamping mode +// of the PTP I/O pins. +func IoctlPtpExttsRequest(fd int, r *PtpExttsRequest) error { + return ioctlPtr(fd, PTP_EXTTS_REQUEST2, unsafe.Pointer(r)) +} + // IoctlGetWatchdogInfo fetches information about a watchdog device from the // Linux watchdog API. For more information, see: // https://www.kernel.org/doc/html/latest/watchdog/watchdog-api.html. @@ -231,3 +327,8 @@ func IoctlLoopGetStatus64(fd int) (*LoopInfo64, error) { func IoctlLoopSetStatus64(fd int, value *LoopInfo64) error { return ioctlPtr(fd, LOOP_SET_STATUS64, unsafe.Pointer(value)) } + +// IoctlLoopConfigure configures all loop device parameters in a single step +func IoctlLoopConfigure(fd int, value *LoopConfig) error { + return ioctlPtr(fd, LOOP_CONFIGURE, unsafe.Pointer(value)) +} diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh index cbe24150..6ab02b6c 100644 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -58,6 +58,7 @@ includes_Darwin=' #define _DARWIN_USE_64_BIT_INODE #define __APPLE_USE_RFC_3542 #include +#include #include #include #include @@ -157,6 +158,16 @@ includes_Linux=' #endif #define _GNU_SOURCE +// See the description in unix/linux/types.go +#if defined(__ARM_EABI__) || \ + (defined(__mips__) && (_MIPS_SIM == _ABIO32)) || \ + (defined(__powerpc__) && (!defined(__powerpc64__))) +# ifdef _TIME_BITS +# undef _TIME_BITS +# endif +# define _TIME_BITS 32 +#endif + // is broken on powerpc64, as it fails to include definitions of // these structures. We just include them copied from . #if defined(__powerpc__) @@ -248,12 +259,14 @@ struct ltchars { #include #include #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -262,6 +275,7 @@ struct ltchars { #include #include #include +#include #include #include #include @@ -283,10 +297,6 @@ struct ltchars { #include #endif -#ifndef MSG_FASTOPEN -#define MSG_FASTOPEN 0x20000000 -#endif - #ifndef PTRACE_GETREGS #define PTRACE_GETREGS 0xc #endif @@ -295,14 +305,6 @@ struct ltchars { #define PTRACE_SETREGS 0xd #endif -#ifndef SOL_NETLINK -#define SOL_NETLINK 270 -#endif - -#ifndef SOL_SMC -#define SOL_SMC 286 -#endif - #ifdef SOL_BLUETOOTH // SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h // but it is already in bluetooth_linux.go @@ -319,10 +321,23 @@ struct ltchars { #undef TIPC_WAIT_FOREVER #define TIPC_WAIT_FOREVER 0xffffffff -// Copied from linux/l2tp.h -// Including linux/l2tp.h here causes conflicts between linux/in.h -// and netinet/in.h included via net/route.h above. -#define IPPROTO_L2TP 115 +// Copied from linux/netfilter/nf_nat.h +// Including linux/netfilter/nf_nat.h here causes conflicts between linux/in.h +// and netinet/in.h. +#define NF_NAT_RANGE_MAP_IPS (1 << 0) +#define NF_NAT_RANGE_PROTO_SPECIFIED (1 << 1) +#define NF_NAT_RANGE_PROTO_RANDOM (1 << 2) +#define NF_NAT_RANGE_PERSISTENT (1 << 3) +#define NF_NAT_RANGE_PROTO_RANDOM_FULLY (1 << 4) +#define NF_NAT_RANGE_PROTO_OFFSET (1 << 5) +#define NF_NAT_RANGE_NETMAP (1 << 6) +#define NF_NAT_RANGE_PROTO_RANDOM_ALL \ + (NF_NAT_RANGE_PROTO_RANDOM | NF_NAT_RANGE_PROTO_RANDOM_FULLY) +#define NF_NAT_RANGE_MASK \ + (NF_NAT_RANGE_MAP_IPS | NF_NAT_RANGE_PROTO_SPECIFIED | \ + NF_NAT_RANGE_PROTO_RANDOM | NF_NAT_RANGE_PERSISTENT | \ + NF_NAT_RANGE_PROTO_RANDOM_FULLY | NF_NAT_RANGE_PROTO_OFFSET | \ + NF_NAT_RANGE_NETMAP) // Copied from linux/hid.h. // Keep in sync with the size of the referenced fields. @@ -519,9 +534,11 @@ ccflags="$@" $2 ~ /^LOCK_(SH|EX|NB|UN)$/ || $2 ~ /^LO_(KEY|NAME)_SIZE$/ || $2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ || + $2 == "LOOP_CONFIGURE" || $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MREMAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT|UDP)_/ || $2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ || $2 ~ /^NFC_.*_(MAX)?SIZE$/ || + $2 ~ /^PTP_/ || $2 ~ /^RAW_PAYLOAD_/ || $2 ~ /^[US]F_/ || $2 ~ /^TP_STATUS_/ || @@ -546,6 +563,8 @@ ccflags="$@" $2 !~ "NLA_TYPE_MASK" && $2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ && $2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ || + $2 ~ /^SOCK_|SK_DIAG_|SKNLGRP_$/ || + $2 ~ /^(CONNECT|SAE)_/ || $2 ~ /^FIORDCHK$/ || $2 ~ /^SIOC/ || $2 ~ /^TIOC/ || @@ -560,7 +579,7 @@ ccflags="$@" $2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ || $2 ~ /^PRIO_(PROCESS|PGRP|USER)/ || $2 ~ /^CLONE_[A-Z_]+/ || - $2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ && + $2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+|BPF_F_LINK)$/ && $2 ~ /^(BPF|DLT)_/ || $2 ~ /^AUDIT_/ || $2 ~ /^(CLOCK|TIMER)_/ || @@ -581,7 +600,7 @@ ccflags="$@" $2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ || $2 ~ /^KEYCTL_/ || $2 ~ /^PERF_/ || - $2 ~ /^SECCOMP_MODE_/ || + $2 ~ /^SECCOMP_/ || $2 ~ /^SEEK_/ || $2 ~ /^SCHED_/ || $2 ~ /^SPLICE_/ || @@ -602,6 +621,9 @@ ccflags="$@" $2 ~ /^FSOPT_/ || $2 ~ /^WDIO[CFS]_/ || $2 ~ /^NFN/ || + $2 !~ /^NFT_META_IIFTYPE/ && + $2 ~ /^NFT_/ || + $2 ~ /^NF_NAT_/ || $2 ~ /^XDP_/ || $2 ~ /^RWF_/ || $2 ~ /^(HDIO|WIN|SMART)_/ || @@ -646,7 +668,7 @@ errors=$( signals=$( echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' | - grep -v 'SIGSTKSIZE\|SIGSTKSZ\|SIGRT\|SIGMAX64' | + grep -E -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' | sort ) @@ -656,7 +678,7 @@ echo '#include ' | $CC -x c - -E -dM $ccflags | sort >_error.grep echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' | - grep -v 'SIGSTKSIZE\|SIGSTKSZ\|SIGRT\|SIGMAX64' | + grep -E -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' | sort >_signal.grep echo '// mkerrors.sh' "$@" diff --git a/vendor/golang.org/x/sys/unix/mmap_nomremap.go b/vendor/golang.org/x/sys/unix/mmap_nomremap.go index 4b68e597..7f602ffd 100644 --- a/vendor/golang.org/x/sys/unix/mmap_nomremap.go +++ b/vendor/golang.org/x/sys/unix/mmap_nomremap.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build aix || darwin || dragonfly || freebsd || openbsd || solaris +//go:build aix || darwin || dragonfly || freebsd || openbsd || solaris || zos package unix diff --git a/vendor/golang.org/x/sys/unix/mremap.go b/vendor/golang.org/x/sys/unix/mremap.go index fd45fe52..3a5e776f 100644 --- a/vendor/golang.org/x/sys/unix/mremap.go +++ b/vendor/golang.org/x/sys/unix/mremap.go @@ -50,3 +50,8 @@ func (m *mremapMmapper) Mremap(oldData []byte, newLength int, flags int) (data [ func Mremap(oldData []byte, newLength int, flags int) (data []byte, err error) { return mapper.Mremap(oldData, newLength, flags) } + +func MremapPtr(oldAddr unsafe.Pointer, oldSize uintptr, newAddr unsafe.Pointer, newSize uintptr, flags int) (ret unsafe.Pointer, err error) { + xaddr, err := mapper.mremap(uintptr(oldAddr), oldSize, newSize, flags, uintptr(newAddr)) + return unsafe.Pointer(xaddr), err +} diff --git a/vendor/golang.org/x/sys/unix/pagesize_unix.go b/vendor/golang.org/x/sys/unix/pagesize_unix.go index 4d0a3430..0482408d 100644 --- a/vendor/golang.org/x/sys/unix/pagesize_unix.go +++ b/vendor/golang.org/x/sys/unix/pagesize_unix.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris +//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos // For Unix, get the pagesize from the runtime. diff --git a/vendor/golang.org/x/sys/unix/readdirent_getdirentries.go b/vendor/golang.org/x/sys/unix/readdirent_getdirentries.go index 130398b6..b903c006 100644 --- a/vendor/golang.org/x/sys/unix/readdirent_getdirentries.go +++ b/vendor/golang.org/x/sys/unix/readdirent_getdirentries.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build darwin +//go:build darwin || zos package unix diff --git a/vendor/golang.org/x/sys/unix/sockcmsg_zos.go b/vendor/golang.org/x/sys/unix/sockcmsg_zos.go new file mode 100644 index 00000000..3e53dbc0 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/sockcmsg_zos.go @@ -0,0 +1,58 @@ +// Copyright 2024 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. + +// Socket control messages + +package unix + +import "unsafe" + +// UnixCredentials encodes credentials into a socket control message +// for sending to another process. This can be used for +// authentication. +func UnixCredentials(ucred *Ucred) []byte { + b := make([]byte, CmsgSpace(SizeofUcred)) + h := (*Cmsghdr)(unsafe.Pointer(&b[0])) + h.Level = SOL_SOCKET + h.Type = SCM_CREDENTIALS + h.SetLen(CmsgLen(SizeofUcred)) + *(*Ucred)(h.data(0)) = *ucred + return b +} + +// ParseUnixCredentials decodes a socket control message that contains +// credentials in a Ucred structure. To receive such a message, the +// SO_PASSCRED option must be enabled on the socket. +func ParseUnixCredentials(m *SocketControlMessage) (*Ucred, error) { + if m.Header.Level != SOL_SOCKET { + return nil, EINVAL + } + if m.Header.Type != SCM_CREDENTIALS { + return nil, EINVAL + } + ucred := *(*Ucred)(unsafe.Pointer(&m.Data[0])) + return &ucred, nil +} + +// PktInfo4 encodes Inet4Pktinfo into a socket control message of type IP_PKTINFO. +func PktInfo4(info *Inet4Pktinfo) []byte { + b := make([]byte, CmsgSpace(SizeofInet4Pktinfo)) + h := (*Cmsghdr)(unsafe.Pointer(&b[0])) + h.Level = SOL_IP + h.Type = IP_PKTINFO + h.SetLen(CmsgLen(SizeofInet4Pktinfo)) + *(*Inet4Pktinfo)(h.data(0)) = *info + return b +} + +// PktInfo6 encodes Inet6Pktinfo into a socket control message of type IPV6_PKTINFO. +func PktInfo6(info *Inet6Pktinfo) []byte { + b := make([]byte, CmsgSpace(SizeofInet6Pktinfo)) + h := (*Cmsghdr)(unsafe.Pointer(&b[0])) + h.Level = SOL_IPV6 + h.Type = IPV6_PKTINFO + h.SetLen(CmsgLen(SizeofInet6Pktinfo)) + *(*Inet6Pktinfo)(h.data(0)) = *info + return b +} diff --git a/vendor/golang.org/x/sys/unix/symaddr_zos_s390x.s b/vendor/golang.org/x/sys/unix/symaddr_zos_s390x.s new file mode 100644 index 00000000..3c4f33cb --- /dev/null +++ b/vendor/golang.org/x/sys/unix/symaddr_zos_s390x.s @@ -0,0 +1,75 @@ +// Copyright 2024 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. + +//go:build zos && s390x && gc + +#include "textflag.h" + +// provide the address of function variable to be fixed up. + +TEXT ·getPipe2Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Pipe2(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_FlockAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Flock(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_GetxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Getxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_NanosleepAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Nanosleep(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_SetxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Setxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_Wait4Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Wait4(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_MountAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Mount(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_UnmountAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Unmount(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_UtimesNanoAtAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·UtimesNanoAt(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_UtimesNanoAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·UtimesNano(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_MkfifoatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Mkfifoat(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_ChtagAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Chtag(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_ReadlinkatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Readlinkat(SB), R8 + MOVD R8, ret+0(FP) + RET + diff --git a/vendor/golang.org/x/sys/unix/syscall_aix.go b/vendor/golang.org/x/sys/unix/syscall_aix.go index 67ce6cef..6f15ba1e 100644 --- a/vendor/golang.org/x/sys/unix/syscall_aix.go +++ b/vendor/golang.org/x/sys/unix/syscall_aix.go @@ -360,7 +360,7 @@ func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, var status _C_int var r Pid_t err = ERESTART - // AIX wait4 may return with ERESTART errno, while the processus is still + // AIX wait4 may return with ERESTART errno, while the process is still // active. for err == ERESTART { r, err = wait4(Pid_t(pid), &status, options, rusage) diff --git a/vendor/golang.org/x/sys/unix/syscall_bsd.go b/vendor/golang.org/x/sys/unix/syscall_bsd.go index 6f328e3a..a00c3e54 100644 --- a/vendor/golang.org/x/sys/unix/syscall_bsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_bsd.go @@ -316,7 +316,7 @@ func GetsockoptString(fd, level, opt int) (string, error) { if err != nil { return "", err } - return string(buf[:vallen-1]), nil + return ByteSliceToString(buf[:vallen]), nil } //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin.go b/vendor/golang.org/x/sys/unix/syscall_darwin.go index 59542a89..099867de 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin.go @@ -402,6 +402,18 @@ func IoctlSetIfreqMTU(fd int, ifreq *IfreqMTU) error { return ioctlPtr(fd, SIOCSIFMTU, unsafe.Pointer(ifreq)) } +//sys renamexNp(from string, to string, flag uint32) (err error) + +func RenamexNp(from string, to string, flag uint32) (err error) { + return renamexNp(from, to, flag) +} + +//sys renameatxNp(fromfd int, from string, tofd int, to string, flag uint32) (err error) + +func RenameatxNp(fromfd int, from string, tofd int, to string, flag uint32) (err error) { + return renameatxNp(fromfd, from, tofd, to, flag) +} + //sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS_SYSCTL func Uname(uname *Utsname) error { @@ -542,6 +554,55 @@ func SysctlKinfoProcSlice(name string, args ...int) ([]KinfoProc, error) { } } +//sys pthread_chdir_np(path string) (err error) + +func PthreadChdir(path string) (err error) { + return pthread_chdir_np(path) +} + +//sys pthread_fchdir_np(fd int) (err error) + +func PthreadFchdir(fd int) (err error) { + return pthread_fchdir_np(fd) +} + +// Connectx calls connectx(2) to initiate a connection on a socket. +// +// srcIf, srcAddr, and dstAddr are filled into a [SaEndpoints] struct and passed as the endpoints argument. +// +// - srcIf is the optional source interface index. 0 means unspecified. +// - srcAddr is the optional source address. nil means unspecified. +// - dstAddr is the destination address. +// +// On success, Connectx returns the number of bytes enqueued for transmission. +func Connectx(fd int, srcIf uint32, srcAddr, dstAddr Sockaddr, associd SaeAssocID, flags uint32, iov []Iovec, connid *SaeConnID) (n uintptr, err error) { + endpoints := SaEndpoints{ + Srcif: srcIf, + } + + if srcAddr != nil { + addrp, addrlen, err := srcAddr.sockaddr() + if err != nil { + return 0, err + } + endpoints.Srcaddr = (*RawSockaddr)(addrp) + endpoints.Srcaddrlen = uint32(addrlen) + } + + if dstAddr != nil { + addrp, addrlen, err := dstAddr.sockaddr() + if err != nil { + return 0, err + } + endpoints.Dstaddr = (*RawSockaddr)(addrp) + endpoints.Dstaddrlen = uint32(addrlen) + } + + err = connectx(fd, &endpoints, associd, flags, iov, &n, connid) + return +} + +//sys connectx(fd int, endpoints *SaEndpoints, associd SaeAssocID, flags uint32, iov []Iovec, n *uintptr, connid *SaeConnID) (err error) //sys sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error) //sys shmat(id int, addr uintptr, flag int) (ret uintptr, err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin_libSystem.go b/vendor/golang.org/x/sys/unix/syscall_darwin_libSystem.go index 16dc6993..2f0fa76e 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin_libSystem.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin_libSystem.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build darwin && go1.12 +//go:build darwin package unix diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd.go b/vendor/golang.org/x/sys/unix/syscall_freebsd.go index 64d1bb4d..2b57e0f7 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd.go @@ -13,6 +13,7 @@ package unix import ( + "errors" "sync" "unsafe" ) @@ -169,25 +170,26 @@ func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { func Uname(uname *Utsname) error { mib := []_C_int{CTL_KERN, KERN_OSTYPE} n := unsafe.Sizeof(uname.Sysname) - if err := sysctl(mib, &uname.Sysname[0], &n, nil, 0); err != nil { + // Suppress ENOMEM errors to be compatible with the C library __xuname() implementation. + if err := sysctl(mib, &uname.Sysname[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { return err } mib = []_C_int{CTL_KERN, KERN_HOSTNAME} n = unsafe.Sizeof(uname.Nodename) - if err := sysctl(mib, &uname.Nodename[0], &n, nil, 0); err != nil { + if err := sysctl(mib, &uname.Nodename[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { return err } mib = []_C_int{CTL_KERN, KERN_OSRELEASE} n = unsafe.Sizeof(uname.Release) - if err := sysctl(mib, &uname.Release[0], &n, nil, 0); err != nil { + if err := sysctl(mib, &uname.Release[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { return err } mib = []_C_int{CTL_KERN, KERN_VERSION} n = unsafe.Sizeof(uname.Version) - if err := sysctl(mib, &uname.Version[0], &n, nil, 0); err != nil { + if err := sysctl(mib, &uname.Version[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { return err } @@ -205,7 +207,7 @@ func Uname(uname *Utsname) error { mib = []_C_int{CTL_HW, HW_MACHINE} n = unsafe.Sizeof(uname.Machine) - if err := sysctl(mib, &uname.Machine[0], &n, nil, 0); err != nil { + if err := sysctl(mib, &uname.Machine[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { return err } diff --git a/vendor/golang.org/x/sys/unix/syscall_hurd.go b/vendor/golang.org/x/sys/unix/syscall_hurd.go index ba46651f..a6a2d2fc 100644 --- a/vendor/golang.org/x/sys/unix/syscall_hurd.go +++ b/vendor/golang.org/x/sys/unix/syscall_hurd.go @@ -11,6 +11,7 @@ package unix int ioctl(int, unsigned long int, uintptr_t); */ import "C" +import "unsafe" func ioctl(fd int, req uint, arg uintptr) (err error) { r0, er := C.ioctl(C.int(fd), C.ulong(req), C.uintptr_t(arg)) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index a5e1c10e..230a9454 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -61,15 +61,23 @@ func FanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname string) ( } //sys fchmodat(dirfd int, path string, mode uint32) (err error) - -func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { - // Linux fchmodat doesn't support the flags parameter. Mimick glibc's behavior - // and check the flags. Otherwise the mode would be applied to the symlink - // destination which is not what the user expects. - if flags&^AT_SYMLINK_NOFOLLOW != 0 { - return EINVAL - } else if flags&AT_SYMLINK_NOFOLLOW != 0 { - return EOPNOTSUPP +//sys fchmodat2(dirfd int, path string, mode uint32, flags int) (err error) + +func Fchmodat(dirfd int, path string, mode uint32, flags int) error { + // Linux fchmodat doesn't support the flags parameter, but fchmodat2 does. + // Try fchmodat2 if flags are specified. + if flags != 0 { + err := fchmodat2(dirfd, path, mode, flags) + if err == ENOSYS { + // fchmodat2 isn't available. If the flags are known to be valid, + // return EOPNOTSUPP to indicate that fchmodat doesn't support them. + if flags&^(AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH) != 0 { + return EINVAL + } else if flags&(AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH) != 0 { + return EOPNOTSUPP + } + } + return err } return fchmodat(dirfd, path, mode) } @@ -1287,6 +1295,48 @@ func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) { return &value, err } +// GetsockoptTCPCCVegasInfo returns algorithm specific congestion control information for a socket using the "vegas" +// algorithm. +// +// The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option: +// +// algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION) +func GetsockoptTCPCCVegasInfo(fd, level, opt int) (*TCPVegasInfo, error) { + var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment + vallen := _Socklen(SizeofTCPCCInfo) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) + out := (*TCPVegasInfo)(unsafe.Pointer(&value[0])) + return out, err +} + +// GetsockoptTCPCCDCTCPInfo returns algorithm specific congestion control information for a socket using the "dctp" +// algorithm. +// +// The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option: +// +// algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION) +func GetsockoptTCPCCDCTCPInfo(fd, level, opt int) (*TCPDCTCPInfo, error) { + var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment + vallen := _Socklen(SizeofTCPCCInfo) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) + out := (*TCPDCTCPInfo)(unsafe.Pointer(&value[0])) + return out, err +} + +// GetsockoptTCPCCBBRInfo returns algorithm specific congestion control information for a socket using the "bbr" +// algorithm. +// +// The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option: +// +// algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION) +func GetsockoptTCPCCBBRInfo(fd, level, opt int) (*TCPBBRInfo, error) { + var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment + vallen := _Socklen(SizeofTCPCCInfo) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) + out := (*TCPBBRInfo)(unsafe.Pointer(&value[0])) + return out, err +} + // GetsockoptString returns the string value of the socket option opt for the // socket associated with fd at the given socket level. func GetsockoptString(fd, level, opt int) (string, error) { @@ -1302,7 +1352,7 @@ func GetsockoptString(fd, level, opt int) (string, error) { return "", err } } - return string(buf[:vallen-1]), nil + return ByteSliceToString(buf[:vallen]), nil } func GetsockoptTpacketStats(fd, level, opt int) (*TpacketStats, error) { @@ -1810,6 +1860,7 @@ func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err e //sys ClockAdjtime(clockid int32, buf *Timex) (state int, err error) //sys ClockGetres(clockid int32, res *Timespec) (err error) //sys ClockGettime(clockid int32, time *Timespec) (err error) +//sys ClockSettime(clockid int32, time *Timespec) (err error) //sys ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error) //sys Close(fd int) (err error) //sys CloseRange(first uint, last uint, flags uint) (err error) @@ -1841,6 +1892,105 @@ func Dup2(oldfd, newfd int) error { //sys Fsmount(fd int, flags int, mountAttrs int) (fsfd int, err error) //sys Fsopen(fsName string, flags int) (fd int, err error) //sys Fspick(dirfd int, pathName string, flags int) (fd int, err error) + +//sys fsconfig(fd int, cmd uint, key *byte, value *byte, aux int) (err error) + +func fsconfigCommon(fd int, cmd uint, key string, value *byte, aux int) (err error) { + var keyp *byte + if keyp, err = BytePtrFromString(key); err != nil { + return + } + return fsconfig(fd, cmd, keyp, value, aux) +} + +// FsconfigSetFlag is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_SET_FLAG. +// +// fd is the filesystem context to act upon. +// key the parameter key to set. +func FsconfigSetFlag(fd int, key string) (err error) { + return fsconfigCommon(fd, FSCONFIG_SET_FLAG, key, nil, 0) +} + +// FsconfigSetString is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_SET_STRING. +// +// fd is the filesystem context to act upon. +// key the parameter key to set. +// value is the parameter value to set. +func FsconfigSetString(fd int, key string, value string) (err error) { + var valuep *byte + if valuep, err = BytePtrFromString(value); err != nil { + return + } + return fsconfigCommon(fd, FSCONFIG_SET_STRING, key, valuep, 0) +} + +// FsconfigSetBinary is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_SET_BINARY. +// +// fd is the filesystem context to act upon. +// key the parameter key to set. +// value is the parameter value to set. +func FsconfigSetBinary(fd int, key string, value []byte) (err error) { + if len(value) == 0 { + return EINVAL + } + return fsconfigCommon(fd, FSCONFIG_SET_BINARY, key, &value[0], len(value)) +} + +// FsconfigSetPath is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_SET_PATH. +// +// fd is the filesystem context to act upon. +// key the parameter key to set. +// path is a non-empty path for specified key. +// atfd is a file descriptor at which to start lookup from or AT_FDCWD. +func FsconfigSetPath(fd int, key string, path string, atfd int) (err error) { + var valuep *byte + if valuep, err = BytePtrFromString(path); err != nil { + return + } + return fsconfigCommon(fd, FSCONFIG_SET_PATH, key, valuep, atfd) +} + +// FsconfigSetPathEmpty is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_SET_PATH_EMPTY. The same as +// FconfigSetPath but with AT_PATH_EMPTY implied. +func FsconfigSetPathEmpty(fd int, key string, path string, atfd int) (err error) { + var valuep *byte + if valuep, err = BytePtrFromString(path); err != nil { + return + } + return fsconfigCommon(fd, FSCONFIG_SET_PATH_EMPTY, key, valuep, atfd) +} + +// FsconfigSetFd is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_SET_FD. +// +// fd is the filesystem context to act upon. +// key the parameter key to set. +// value is a file descriptor to be assigned to specified key. +func FsconfigSetFd(fd int, key string, value int) (err error) { + return fsconfigCommon(fd, FSCONFIG_SET_FD, key, nil, value) +} + +// FsconfigCreate is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_CMD_CREATE. +// +// fd is the filesystem context to act upon. +func FsconfigCreate(fd int) (err error) { + return fsconfig(fd, FSCONFIG_CMD_CREATE, nil, nil, 0) +} + +// FsconfigReconfigure is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_CMD_RECONFIGURE. +// +// fd is the filesystem context to act upon. +func FsconfigReconfigure(fd int) (err error) { + return fsconfig(fd, FSCONFIG_CMD_RECONFIGURE, nil, nil, 0) +} + //sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64 //sysnb Getpgid(pid int) (pgid int, err error) @@ -1852,7 +2002,26 @@ func Getpgrp() (pid int) { //sysnb Getpid() (pid int) //sysnb Getppid() (ppid int) //sys Getpriority(which int, who int) (prio int, err error) -//sys Getrandom(buf []byte, flags int) (n int, err error) + +func Getrandom(buf []byte, flags int) (n int, err error) { + vdsoRet, supported := vgetrandom(buf, uint32(flags)) + if supported { + if vdsoRet < 0 { + return 0, errnoErr(syscall.Errno(-vdsoRet)) + } + return vdsoRet, nil + } + var p *byte + if len(buf) > 0 { + p = &buf[0] + } + r, _, e := Syscall(SYS_GETRANDOM, uintptr(unsafe.Pointer(p)), uintptr(len(buf)), uintptr(flags)) + if e != 0 { + return 0, errnoErr(e) + } + return int(r), nil +} + //sysnb Getrusage(who int, rusage *Rusage) (err error) //sysnb Getsid(pid int) (sid int, err error) //sysnb Gettid() (tid int) @@ -2485,3 +2654,4 @@ func SchedGetAttr(pid int, flags uint) (*SchedAttr, error) { } //sys Cachestat(fd uint, crange *CachestatRange, cstat *Cachestat_t, flags uint) (err error) +//sys Mseal(b []byte, flags uint) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go index cf2ee6c7..745e5c7e 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go @@ -182,3 +182,5 @@ func KexecFileLoad(kernelFd int, initrdFd int, cmdline string, flags int) error } return kexecFileLoad(kernelFd, initrdFd, cmdlineLen, cmdline, flags) } + +const SYS_FSTATAT = SYS_NEWFSTATAT diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go b/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go index 3d0e9845..dd2262a4 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go @@ -214,3 +214,5 @@ func KexecFileLoad(kernelFd int, initrdFd int, cmdline string, flags int) error } return kexecFileLoad(kernelFd, initrdFd, cmdlineLen, cmdline, flags) } + +const SYS_FSTATAT = SYS_NEWFSTATAT diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go b/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go index 6f5a2889..8cf3670b 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go @@ -187,3 +187,5 @@ func RISCVHWProbe(pairs []RISCVHWProbePairs, set *CPUSet, flags uint) (err error } return riscvHWProbe(pairs, setSize, set, flags) } + +const SYS_FSTATAT = SYS_NEWFSTATAT diff --git a/vendor/golang.org/x/sys/unix/syscall_openbsd.go b/vendor/golang.org/x/sys/unix/syscall_openbsd.go index d2882ee0..b86ded54 100644 --- a/vendor/golang.org/x/sys/unix/syscall_openbsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_openbsd.go @@ -166,6 +166,20 @@ func Getresgid() (rgid, egid, sgid int) { //sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS___SYSCTL +//sys fcntl(fd int, cmd int, arg int) (n int, err error) +//sys fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) = SYS_FCNTL + +// FcntlInt performs a fcntl syscall on fd with the provided command and argument. +func FcntlInt(fd uintptr, cmd, arg int) (int, error) { + return fcntl(int(fd), cmd, arg) +} + +// FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. +func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { + _, err := fcntlPtr(int(fd), cmd, unsafe.Pointer(lk)) + return err +} + //sys ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { @@ -279,6 +293,7 @@ func Uname(uname *Utsname) error { //sys Mkfifoat(dirfd int, path string, mode uint32) (err error) //sys Mknod(path string, mode uint32, dev int) (err error) //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) +//sys Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys Open(path string, mode int, perm uint32) (fd int, err error) //sys Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_solaris.go b/vendor/golang.org/x/sys/unix/syscall_solaris.go index 60c8142d..21974af0 100644 --- a/vendor/golang.org/x/sys/unix/syscall_solaris.go +++ b/vendor/golang.org/x/sys/unix/syscall_solaris.go @@ -158,7 +158,7 @@ func GetsockoptString(fd, level, opt int) (string, error) { if err != nil { return "", err } - return string(buf[:vallen-1]), nil + return ByteSliceToString(buf[:vallen]), nil } const ImplementsGetwd = true diff --git a/vendor/golang.org/x/sys/unix/syscall_unix.go b/vendor/golang.org/x/sys/unix/syscall_unix.go index 77081de8..4e92e5aa 100644 --- a/vendor/golang.org/x/sys/unix/syscall_unix.go +++ b/vendor/golang.org/x/sys/unix/syscall_unix.go @@ -154,6 +154,15 @@ func Munmap(b []byte) (err error) { return mapper.Munmap(b) } +func MmapPtr(fd int, offset int64, addr unsafe.Pointer, length uintptr, prot int, flags int) (ret unsafe.Pointer, err error) { + xaddr, err := mapper.mmap(uintptr(addr), length, prot, flags, fd, offset) + return unsafe.Pointer(xaddr), err +} + +func MunmapPtr(addr unsafe.Pointer, length uintptr) (err error) { + return mapper.munmap(uintptr(addr), length) +} + func Read(fd int, p []byte) (n int, err error) { n, err = read(fd, p) if raceenabled { diff --git a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go index d99d05f1..7bf5c04b 100644 --- a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go @@ -4,11 +4,21 @@ //go:build zos && s390x +// Many of the following syscalls are not available on all versions of z/OS. +// Some missing calls have legacy implementations/simulations but others +// will be missing completely. To achieve consistent failing behaviour on +// legacy systems, we first test the function pointer via a safeloading +// mechanism to see if the function exists on a given system. Then execution +// is branched to either continue the function call, or return an error. + package unix import ( "bytes" "fmt" + "os" + "reflect" + "regexp" "runtime" "sort" "strings" @@ -17,17 +27,205 @@ import ( "unsafe" ) +//go:noescape +func initZosLibVec() + +//go:noescape +func GetZosLibVec() uintptr + +func init() { + initZosLibVec() + r0, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS_____GETENV_A<<4, uintptr(unsafe.Pointer(&([]byte("__ZOS_XSYSTRACE\x00"))[0]))) + if r0 != 0 { + n, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___ATOI_A<<4, r0) + ZosTraceLevel = int(n) + r0, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS_____GETENV_A<<4, uintptr(unsafe.Pointer(&([]byte("__ZOS_XSYSTRACEFD\x00"))[0]))) + if r0 != 0 { + fd, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___ATOI_A<<4, r0) + f := os.NewFile(fd, "zostracefile") + if f != nil { + ZosTracefile = f + } + } + + } +} + +//go:noescape +func CallLeFuncWithErr(funcdesc uintptr, parms ...uintptr) (ret, errno2 uintptr, err Errno) + +//go:noescape +func CallLeFuncWithPtrReturn(funcdesc uintptr, parms ...uintptr) (ret, errno2 uintptr, err Errno) + +// ------------------------------- +// pointer validity test +// good pointer returns 0 +// bad pointer returns 1 +// +//go:nosplit +func ptrtest(uintptr) uint64 + +// Load memory at ptr location with error handling if the location is invalid +// +//go:noescape +func safeload(ptr uintptr) (value uintptr, error uintptr) + const ( - O_CLOEXEC = 0 // Dummy value (not supported). - AF_LOCAL = AF_UNIX // AF_LOCAL is an alias for AF_UNIX + entrypointLocationOffset = 8 // From function descriptor + + xplinkEyecatcher = 0x00c300c500c500f1 // ".C.E.E.1" + eyecatcherOffset = 16 // From function entrypoint (negative) + ppa1LocationOffset = 8 // From function entrypoint (negative) + + nameLenOffset = 0x14 // From PPA1 start + nameOffset = 0x16 // From PPA1 start ) -func syscall_syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno) -func syscall_rawsyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno) -func syscall_syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) -func syscall_rawsyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) -func syscall_syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err Errno) -func syscall_rawsyscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err Errno) +func getPpaOffset(funcptr uintptr) int64 { + entrypoint, err := safeload(funcptr + entrypointLocationOffset) + if err != 0 { + return -1 + } + + // XPLink functions have ".C.E.E.1" as the first 8 bytes (EBCDIC) + val, err := safeload(entrypoint - eyecatcherOffset) + if err != 0 { + return -1 + } + if val != xplinkEyecatcher { + return -1 + } + + ppaoff, err := safeload(entrypoint - ppa1LocationOffset) + if err != 0 { + return -1 + } + + ppaoff >>= 32 + return int64(ppaoff) +} + +//------------------------------- +// function descriptor pointer validity test +// good pointer returns 0 +// bad pointer returns 1 + +// TODO: currently mksyscall_zos_s390x.go generate empty string for funcName +// have correct funcName pass to the funcptrtest function +func funcptrtest(funcptr uintptr, funcName string) uint64 { + entrypoint, err := safeload(funcptr + entrypointLocationOffset) + if err != 0 { + return 1 + } + + ppaoff := getPpaOffset(funcptr) + if ppaoff == -1 { + return 1 + } + + // PPA1 offset value is from the start of the entire function block, not the entrypoint + ppa1 := (entrypoint - eyecatcherOffset) + uintptr(ppaoff) + + nameLen, err := safeload(ppa1 + nameLenOffset) + if err != 0 { + return 1 + } + + nameLen >>= 48 + if nameLen > 128 { + return 1 + } + + // no function name input to argument end here + if funcName == "" { + return 0 + } + + var funcname [128]byte + for i := 0; i < int(nameLen); i += 8 { + v, err := safeload(ppa1 + nameOffset + uintptr(i)) + if err != 0 { + return 1 + } + funcname[i] = byte(v >> 56) + funcname[i+1] = byte(v >> 48) + funcname[i+2] = byte(v >> 40) + funcname[i+3] = byte(v >> 32) + funcname[i+4] = byte(v >> 24) + funcname[i+5] = byte(v >> 16) + funcname[i+6] = byte(v >> 8) + funcname[i+7] = byte(v) + } + + runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___E2A_L<<4, // __e2a_l + []uintptr{uintptr(unsafe.Pointer(&funcname[0])), nameLen}) + + name := string(funcname[:nameLen]) + if name != funcName { + return 1 + } + + return 0 +} + +// For detection of capabilities on a system. +// Is function descriptor f a valid function? +func isValidLeFunc(f uintptr) error { + ret := funcptrtest(f, "") + if ret != 0 { + return fmt.Errorf("Bad pointer, not an LE function ") + } + return nil +} + +// Retrieve function name from descriptor +func getLeFuncName(f uintptr) (string, error) { + // assume it has been checked, only check ppa1 validity here + entry := ((*[2]uintptr)(unsafe.Pointer(f)))[1] + preamp := ((*[4]uint32)(unsafe.Pointer(entry - eyecatcherOffset))) + + offsetPpa1 := preamp[2] + if offsetPpa1 > 0x0ffff { + return "", fmt.Errorf("PPA1 offset seems too big 0x%x\n", offsetPpa1) + } + + ppa1 := uintptr(unsafe.Pointer(preamp)) + uintptr(offsetPpa1) + res := ptrtest(ppa1) + if res != 0 { + return "", fmt.Errorf("PPA1 address not valid") + } + + size := *(*uint16)(unsafe.Pointer(ppa1 + nameLenOffset)) + if size > 128 { + return "", fmt.Errorf("Function name seems too long, length=%d\n", size) + } + + var name [128]byte + funcname := (*[128]byte)(unsafe.Pointer(ppa1 + nameOffset)) + copy(name[0:size], funcname[0:size]) + + runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___E2A_L<<4, // __e2a_l + []uintptr{uintptr(unsafe.Pointer(&name[0])), uintptr(size)}) + + return string(name[:size]), nil +} + +// Check z/OS version +func zosLeVersion() (version, release uint32) { + p1 := (*(*uintptr)(unsafe.Pointer(uintptr(1208)))) >> 32 + p1 = *(*uintptr)(unsafe.Pointer(uintptr(p1 + 88))) + p1 = *(*uintptr)(unsafe.Pointer(uintptr(p1 + 8))) + p1 = *(*uintptr)(unsafe.Pointer(uintptr(p1 + 984))) + vrm := *(*uint32)(unsafe.Pointer(p1 + 80)) + version = (vrm & 0x00ff0000) >> 16 + release = (vrm & 0x0000ff00) >> 8 + return +} + +// returns a zos C FILE * for stdio fd 0, 1, 2 +func ZosStdioFilep(fd int32) uintptr { + return uintptr(*(*uint64)(unsafe.Pointer(uintptr(*(*uint64)(unsafe.Pointer(uintptr(*(*uint64)(unsafe.Pointer(uintptr(uint64(*(*uint32)(unsafe.Pointer(uintptr(1208)))) + 80))) + uint64((fd+2)<<3)))))))) +} func copyStat(stat *Stat_t, statLE *Stat_LE_t) { stat.Dev = uint64(statLE.Dev) @@ -65,6 +263,21 @@ func (d *Dirent) NameString() string { } } +func DecodeData(dest []byte, sz int, val uint64) { + for i := 0; i < sz; i++ { + dest[sz-1-i] = byte((val >> (uint64(i * 8))) & 0xff) + } +} + +func EncodeData(data []byte) uint64 { + var value uint64 + sz := len(data) + for i := 0; i < sz; i++ { + value |= uint64(data[i]) << uint64(((sz - i - 1) * 8)) + } + return value +} + func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { if sa.Port < 0 || sa.Port > 0xFFFF { return nil, 0, EINVAL @@ -74,7 +287,9 @@ func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) - sa.raw.Addr = sa.Addr + for i := 0; i < len(sa.Addr); i++ { + sa.raw.Addr[i] = sa.Addr[i] + } return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil } @@ -88,7 +303,9 @@ func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) { p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) sa.raw.Scope_id = sa.ZoneId - sa.raw.Addr = sa.Addr + for i := 0; i < len(sa.Addr); i++ { + sa.raw.Addr[i] = sa.Addr[i] + } return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil } @@ -146,7 +363,9 @@ func anyToSockaddr(_ int, rsa *RawSockaddrAny) (Sockaddr, error) { sa := new(SockaddrInet4) p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) - sa.Addr = pp.Addr + for i := 0; i < len(sa.Addr); i++ { + sa.Addr[i] = pp.Addr[i] + } return sa, nil case AF_INET6: @@ -155,7 +374,9 @@ func anyToSockaddr(_ int, rsa *RawSockaddrAny) (Sockaddr, error) { p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) sa.ZoneId = pp.Scope_id - sa.Addr = pp.Addr + for i := 0; i < len(sa.Addr); i++ { + sa.Addr[i] = pp.Addr[i] + } return sa, nil } return nil, EAFNOSUPPORT @@ -177,6 +398,43 @@ func Accept(fd int) (nfd int, sa Sockaddr, err error) { return } +func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + nfd, err = accept4(fd, &rsa, &len, flags) + if err != nil { + return + } + if len > SizeofSockaddrAny { + panic("RawSockaddrAny too small") + } + // TODO(neeilan): Remove 0 in call + sa, err = anyToSockaddr(0, &rsa) + if err != nil { + Close(nfd) + nfd = 0 + } + return +} + +func Ctermid() (tty string, err error) { + var termdev [1025]byte + runtime.EnterSyscall() + r0, err2, err1 := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___CTERMID_A<<4, uintptr(unsafe.Pointer(&termdev[0]))) + runtime.ExitSyscall() + if r0 == 0 { + return "", fmt.Errorf("%s (errno2=0x%x)\n", err1.Error(), err2) + } + s := string(termdev[:]) + idx := strings.Index(s, string(rune(0))) + if idx == -1 { + tty = s + } else { + tty = s[:idx] + } + return +} + func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } @@ -190,10 +448,16 @@ func (cmsg *Cmsghdr) SetLen(length int) { } //sys fcntl(fd int, cmd int, arg int) (val int, err error) +//sys Flistxattr(fd int, dest []byte) (sz int, err error) = SYS___FLISTXATTR_A +//sys Fremovexattr(fd int, attr string) (err error) = SYS___FREMOVEXATTR_A //sys read(fd int, p []byte) (n int, err error) //sys write(fd int, p []byte) (n int, err error) +//sys Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) = SYS___FGETXATTR_A +//sys Fsetxattr(fd int, attr string, data []byte, flag int) (err error) = SYS___FSETXATTR_A + //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) = SYS___ACCEPT_A +//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) = SYS___ACCEPT4_A //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = SYS___BIND_A //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = SYS___CONNECT_A //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) @@ -204,6 +468,7 @@ func (cmsg *Cmsghdr) SetLen(length int) { //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = SYS___GETPEERNAME_A //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = SYS___GETSOCKNAME_A +//sys Removexattr(path string, attr string) (err error) = SYS___REMOVEXATTR_A //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) = SYS___RECVFROM_A //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) = SYS___SENDTO_A //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) = SYS___RECVMSG_A @@ -212,6 +477,10 @@ func (cmsg *Cmsghdr) SetLen(length int) { //sys munmap(addr uintptr, length uintptr) (err error) = SYS_MUNMAP //sys ioctl(fd int, req int, arg uintptr) (err error) = SYS_IOCTL //sys ioctlPtr(fd int, req int, arg unsafe.Pointer) (err error) = SYS_IOCTL +//sys shmat(id int, addr uintptr, flag int) (ret uintptr, err error) = SYS_SHMAT +//sys shmctl(id int, cmd int, buf *SysvShmDesc) (result int, err error) = SYS_SHMCTL64 +//sys shmdt(addr uintptr) (err error) = SYS_SHMDT +//sys shmget(key int, size int, flag int) (id int, err error) = SYS_SHMGET //sys Access(path string, mode uint32) (err error) = SYS___ACCESS_A //sys Chdir(path string) (err error) = SYS___CHDIR_A @@ -220,14 +489,31 @@ func (cmsg *Cmsghdr) SetLen(length int) { //sys Creat(path string, mode uint32) (fd int, err error) = SYS___CREAT_A //sys Dup(oldfd int) (fd int, err error) //sys Dup2(oldfd int, newfd int) (err error) +//sys Dup3(oldfd int, newfd int, flags int) (err error) = SYS_DUP3 +//sys Dirfd(dirp uintptr) (fd int, err error) = SYS_DIRFD +//sys EpollCreate(size int) (fd int, err error) = SYS_EPOLL_CREATE +//sys EpollCreate1(flags int) (fd int, err error) = SYS_EPOLL_CREATE1 +//sys EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) = SYS_EPOLL_CTL +//sys EpollPwait(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error) = SYS_EPOLL_PWAIT +//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_WAIT //sys Errno2() (er2 int) = SYS___ERRNO2 -//sys Err2ad() (eadd *int) = SYS___ERR2AD +//sys Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD //sys Exit(code int) +//sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) = SYS___FACCESSAT_A + +func Faccessat2(dirfd int, path string, mode uint32, flags int) (err error) { + return Faccessat(dirfd, path, mode, flags) +} + //sys Fchdir(fd int) (err error) //sys Fchmod(fd int, mode uint32) (err error) +//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) = SYS___FCHMODAT_A //sys Fchown(fd int, uid int, gid int) (err error) +//sys Fchownat(fd int, path string, uid int, gid int, flags int) (err error) = SYS___FCHOWNAT_A //sys FcntlInt(fd uintptr, cmd int, arg int) (retval int, err error) = SYS_FCNTL +//sys Fdatasync(fd int) (err error) = SYS_FDATASYNC //sys fstat(fd int, stat *Stat_LE_t) (err error) +//sys fstatat(dirfd int, path string, stat *Stat_LE_t, flags int) (err error) = SYS___FSTATAT_A func Fstat(fd int, stat *Stat_t) (err error) { var statLE Stat_LE_t @@ -236,28 +522,208 @@ func Fstat(fd int, stat *Stat_t) (err error) { return } +func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var statLE Stat_LE_t + err = fstatat(dirfd, path, &statLE, flags) + copyStat(stat, &statLE) + return +} + +func impl_Getxattr(path string, attr string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(dest) > 0 { + _p2 = unsafe.Pointer(&dest[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___GETXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest))) + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_GetxattrAddr() *(func(path string, attr string, dest []byte) (sz int, err error)) + +var Getxattr = enter_Getxattr + +func enter_Getxattr(path string, attr string, dest []byte) (sz int, err error) { + funcref := get_GetxattrAddr() + if validGetxattr() { + *funcref = impl_Getxattr + } else { + *funcref = error_Getxattr + } + return (*funcref)(path, attr, dest) +} + +func error_Getxattr(path string, attr string, dest []byte) (sz int, err error) { + return -1, ENOSYS +} + +func validGetxattr() bool { + if funcptrtest(GetZosLibVec()+SYS___GETXATTR_A<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS___GETXATTR_A<<4); err == nil { + return name == "__getxattr_a" + } + } + return false +} + +//sys Lgetxattr(link string, attr string, dest []byte) (sz int, err error) = SYS___LGETXATTR_A +//sys Lsetxattr(path string, attr string, data []byte, flags int) (err error) = SYS___LSETXATTR_A + +func impl_Setxattr(path string, attr string, data []byte, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(data) > 0 { + _p2 = unsafe.Pointer(&data[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SETXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_SetxattrAddr() *(func(path string, attr string, data []byte, flags int) (err error)) + +var Setxattr = enter_Setxattr + +func enter_Setxattr(path string, attr string, data []byte, flags int) (err error) { + funcref := get_SetxattrAddr() + if validSetxattr() { + *funcref = impl_Setxattr + } else { + *funcref = error_Setxattr + } + return (*funcref)(path, attr, data, flags) +} + +func error_Setxattr(path string, attr string, data []byte, flags int) (err error) { + return ENOSYS +} + +func validSetxattr() bool { + if funcptrtest(GetZosLibVec()+SYS___SETXATTR_A<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS___SETXATTR_A<<4); err == nil { + return name == "__setxattr_a" + } + } + return false +} + +//sys Fstatfs(fd int, buf *Statfs_t) (err error) = SYS_FSTATFS //sys Fstatvfs(fd int, stat *Statvfs_t) (err error) = SYS_FSTATVFS //sys Fsync(fd int) (err error) +//sys Futimes(fd int, tv []Timeval) (err error) = SYS_FUTIMES +//sys Futimesat(dirfd int, path string, tv []Timeval) (err error) = SYS___FUTIMESAT_A //sys Ftruncate(fd int, length int64) (err error) -//sys Getpagesize() (pgsize int) = SYS_GETPAGESIZE +//sys Getrandom(buf []byte, flags int) (n int, err error) = SYS_GETRANDOM +//sys InotifyInit() (fd int, err error) = SYS_INOTIFY_INIT +//sys InotifyInit1(flags int) (fd int, err error) = SYS_INOTIFY_INIT1 +//sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) = SYS___INOTIFY_ADD_WATCH_A +//sys InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) = SYS_INOTIFY_RM_WATCH +//sys Listxattr(path string, dest []byte) (sz int, err error) = SYS___LISTXATTR_A +//sys Llistxattr(path string, dest []byte) (sz int, err error) = SYS___LLISTXATTR_A +//sys Lremovexattr(path string, attr string) (err error) = SYS___LREMOVEXATTR_A +//sys Lutimes(path string, tv []Timeval) (err error) = SYS___LUTIMES_A //sys Mprotect(b []byte, prot int) (err error) = SYS_MPROTECT //sys Msync(b []byte, flags int) (err error) = SYS_MSYNC +//sys Console2(cmsg *ConsMsg2, modstr *byte, concmd *uint32) (err error) = SYS___CONSOLE2 + +// Pipe2 begin + +//go:nosplit +func getPipe2Addr() *(func([]int, int) error) + +var Pipe2 = pipe2Enter + +func pipe2Enter(p []int, flags int) (err error) { + if funcptrtest(GetZosLibVec()+SYS_PIPE2<<4, "") == 0 { + *getPipe2Addr() = pipe2Impl + } else { + *getPipe2Addr() = pipe2Error + } + return (*getPipe2Addr())(p, flags) +} + +func pipe2Impl(p []int, flags int) (err error) { + var pp [2]_C_int + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PIPE2<<4, uintptr(unsafe.Pointer(&pp[0])), uintptr(flags)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } else { + p[0] = int(pp[0]) + p[1] = int(pp[1]) + } + return +} +func pipe2Error(p []int, flags int) (err error) { + return fmt.Errorf("Pipe2 is not available on this system") +} + +// Pipe2 end + //sys Poll(fds []PollFd, timeout int) (n int, err error) = SYS_POLL + +func Readdir(dir uintptr) (dirent *Dirent, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___READDIR_A<<4, uintptr(dir)) + runtime.ExitSyscall() + dirent = (*Dirent)(unsafe.Pointer(r0)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//sys Readdir_r(dirp uintptr, entry *direntLE, result **direntLE) (err error) = SYS___READDIR_R_A +//sys Statfs(path string, buf *Statfs_t) (err error) = SYS___STATFS_A +//sys Syncfs(fd int) (err error) = SYS_SYNCFS //sys Times(tms *Tms) (ticks uintptr, err error) = SYS_TIMES //sys W_Getmntent(buff *byte, size int) (lastsys int, err error) = SYS_W_GETMNTENT //sys W_Getmntent_A(buff *byte, size int) (lastsys int, err error) = SYS___W_GETMNTENT_A //sys mount_LE(path string, filesystem string, fstype string, mtm uint32, parmlen int32, parm string) (err error) = SYS___MOUNT_A -//sys unmount(filesystem string, mtm int) (err error) = SYS___UMOUNT_A +//sys unmount_LE(filesystem string, mtm int) (err error) = SYS___UMOUNT_A //sys Chroot(path string) (err error) = SYS___CHROOT_A //sys Select(nmsgsfds int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (ret int, err error) = SYS_SELECT -//sysnb Uname(buf *Utsname) (err error) = SYS___UNAME_A +//sysnb Uname(buf *Utsname) (err error) = SYS_____OSNAME_A +//sys Unshare(flags int) (err error) = SYS_UNSHARE func Ptsname(fd int) (name string, err error) { - r0, _, e1 := syscall_syscall(SYS___PTSNAME_A, uintptr(fd), 0, 0) - name = u2s(unsafe.Pointer(r0)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___PTSNAME_A<<4, uintptr(fd)) + runtime.ExitSyscall() + if r0 == 0 { + err = errnoErr2(e1, e2) + } else { + name = u2s(unsafe.Pointer(r0)) } return } @@ -272,13 +738,19 @@ func u2s(cstr unsafe.Pointer) string { } func Close(fd int) (err error) { - _, _, e1 := syscall_syscall(SYS_CLOSE, uintptr(fd), 0, 0) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_CLOSE<<4, uintptr(fd)) + runtime.ExitSyscall() for i := 0; e1 == EAGAIN && i < 10; i++ { - _, _, _ = syscall_syscall(SYS_USLEEP, uintptr(10), 0, 0) - _, _, e1 = syscall_syscall(SYS_CLOSE, uintptr(fd), 0, 0) + runtime.EnterSyscall() + CallLeFuncWithErr(GetZosLibVec()+SYS_USLEEP<<4, uintptr(10)) + runtime.ExitSyscall() + runtime.EnterSyscall() + r0, e2, e1 = CallLeFuncWithErr(GetZosLibVec()+SYS_CLOSE<<4, uintptr(fd)) + runtime.ExitSyscall() } - if e1 != 0 { - err = errnoErr(e1) + if r0 != 0 { + err = errnoErr2(e1, e2) } return } @@ -288,9 +760,24 @@ func Madvise(b []byte, advice int) (err error) { return } +func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { + return mapper.Mmap(fd, offset, length, prot, flags) +} + +func Munmap(b []byte) (err error) { + return mapper.Munmap(b) +} + +func MmapPtr(fd int, offset int64, addr unsafe.Pointer, length uintptr, prot int, flags int) (ret unsafe.Pointer, err error) { + xaddr, err := mapper.mmap(uintptr(addr), length, prot, flags, fd, offset) + return unsafe.Pointer(xaddr), err +} + +func MunmapPtr(addr unsafe.Pointer, length uintptr) (err error) { + return mapper.munmap(uintptr(addr), length) +} + //sys Gethostname(buf []byte) (err error) = SYS___GETHOSTNAME_A -//sysnb Getegid() (egid int) -//sysnb Geteuid() (uid int) //sysnb Getgid() (gid int) //sysnb Getpid() (pid int) //sysnb Getpgid(pid int) (pgid int, err error) = SYS_GETPGID @@ -317,11 +804,14 @@ func Getrusage(who int, rusage *Rusage) (err error) { return } +//sys Getegid() (egid int) = SYS_GETEGID +//sys Geteuid() (euid int) = SYS_GETEUID //sysnb Getsid(pid int) (sid int, err error) = SYS_GETSID //sysnb Getuid() (uid int) //sysnb Kill(pid int, sig Signal) (err error) //sys Lchown(path string, uid int, gid int) (err error) = SYS___LCHOWN_A //sys Link(path string, link string) (err error) = SYS___LINK_A +//sys Linkat(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error) = SYS___LINKAT_A //sys Listen(s int, n int) (err error) //sys lstat(path string, stat *Stat_LE_t) (err error) = SYS___LSTAT_A @@ -332,15 +822,150 @@ func Lstat(path string, stat *Stat_t) (err error) { return } +// for checking symlinks begins with $VERSION/ $SYSNAME/ $SYSSYMR/ $SYSSYMA/ +func isSpecialPath(path []byte) (v bool) { + var special = [4][8]byte{ + {'V', 'E', 'R', 'S', 'I', 'O', 'N', '/'}, + {'S', 'Y', 'S', 'N', 'A', 'M', 'E', '/'}, + {'S', 'Y', 'S', 'S', 'Y', 'M', 'R', '/'}, + {'S', 'Y', 'S', 'S', 'Y', 'M', 'A', '/'}} + + var i, j int + for i = 0; i < len(special); i++ { + for j = 0; j < len(special[i]); j++ { + if path[j] != special[i][j] { + break + } + } + if j == len(special[i]) { + return true + } + } + return false +} + +func realpath(srcpath string, abspath []byte) (pathlen int, errno int) { + var source [1024]byte + copy(source[:], srcpath) + source[len(srcpath)] = 0 + ret := runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___REALPATH_A<<4, //__realpath_a() + []uintptr{uintptr(unsafe.Pointer(&source[0])), + uintptr(unsafe.Pointer(&abspath[0]))}) + if ret != 0 { + index := bytes.IndexByte(abspath[:], byte(0)) + if index != -1 { + return index, 0 + } + } else { + errptr := (*int)(unsafe.Pointer(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO<<4, []uintptr{}))) //__errno() + return 0, *errptr + } + return 0, 245 // EBADDATA 245 +} + +func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + n = int(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___READLINK_A<<4, + []uintptr{uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))})) + runtime.KeepAlive(unsafe.Pointer(_p0)) + if n == -1 { + value := *(*int32)(unsafe.Pointer(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO<<4, []uintptr{}))) + err = errnoErr(Errno(value)) + } else { + if buf[0] == '$' { + if isSpecialPath(buf[1:9]) { + cnt, err1 := realpath(path, buf) + if err1 == 0 { + n = cnt + } + } + } + } + return +} + +func impl_Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___READLINKAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + return n, err + } else { + if buf[0] == '$' { + if isSpecialPath(buf[1:9]) { + cnt, err1 := realpath(path, buf) + if err1 == 0 { + n = cnt + } + } + } + } + return +} + +//go:nosplit +func get_ReadlinkatAddr() *(func(dirfd int, path string, buf []byte) (n int, err error)) + +var Readlinkat = enter_Readlinkat + +func enter_Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + funcref := get_ReadlinkatAddr() + if funcptrtest(GetZosLibVec()+SYS___READLINKAT_A<<4, "") == 0 { + *funcref = impl_Readlinkat + } else { + *funcref = error_Readlinkat + } + return (*funcref)(dirfd, path, buf) +} + +func error_Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + n = -1 + err = ENOSYS + return +} + //sys Mkdir(path string, mode uint32) (err error) = SYS___MKDIR_A +//sys Mkdirat(dirfd int, path string, mode uint32) (err error) = SYS___MKDIRAT_A //sys Mkfifo(path string, mode uint32) (err error) = SYS___MKFIFO_A //sys Mknod(path string, mode uint32, dev int) (err error) = SYS___MKNOD_A +//sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) = SYS___MKNODAT_A +//sys PivotRoot(newroot string, oldroot string) (err error) = SYS___PIVOT_ROOT_A //sys Pread(fd int, p []byte, offset int64) (n int, err error) //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) -//sys Readlink(path string, buf []byte) (n int, err error) = SYS___READLINK_A +//sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) = SYS___PRCTL_A +//sysnb Prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) = SYS_PRLIMIT //sys Rename(from string, to string) (err error) = SYS___RENAME_A +//sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) = SYS___RENAMEAT_A +//sys Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) = SYS___RENAMEAT2_A //sys Rmdir(path string) (err error) = SYS___RMDIR_A //sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK +//sys Setegid(egid int) (err error) = SYS_SETEGID +//sys Seteuid(euid int) (err error) = SYS_SETEUID +//sys Sethostname(p []byte) (err error) = SYS___SETHOSTNAME_A +//sys Setns(fd int, nstype int) (err error) = SYS_SETNS //sys Setpriority(which int, who int, prio int) (err error) //sysnb Setpgid(pid int, pgid int) (err error) = SYS_SETPGID //sysnb Setrlimit(resource int, lim *Rlimit) (err error) @@ -360,32 +985,57 @@ func Stat(path string, sta *Stat_t) (err error) { } //sys Symlink(path string, link string) (err error) = SYS___SYMLINK_A +//sys Symlinkat(oldPath string, dirfd int, newPath string) (err error) = SYS___SYMLINKAT_A //sys Sync() = SYS_SYNC //sys Truncate(path string, length int64) (err error) = SYS___TRUNCATE_A //sys Tcgetattr(fildes int, termptr *Termios) (err error) = SYS_TCGETATTR //sys Tcsetattr(fildes int, when int, termptr *Termios) (err error) = SYS_TCSETATTR //sys Umask(mask int) (oldmask int) //sys Unlink(path string) (err error) = SYS___UNLINK_A +//sys Unlinkat(dirfd int, path string, flags int) (err error) = SYS___UNLINKAT_A //sys Utime(path string, utim *Utimbuf) (err error) = SYS___UTIME_A //sys open(path string, mode int, perm uint32) (fd int, err error) = SYS___OPEN_A func Open(path string, mode int, perm uint32) (fd int, err error) { + if mode&O_ACCMODE == 0 { + mode |= O_RDONLY + } return open(path, mode, perm) } -func Mkfifoat(dirfd int, path string, mode uint32) (err error) { - wd, err := Getwd() - if err != nil { - return err +//sys openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) = SYS___OPENAT_A + +func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + if flags&O_ACCMODE == 0 { + flags |= O_RDONLY } + return openat(dirfd, path, flags, mode) +} - if err := Fchdir(dirfd); err != nil { - return err +//sys openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error) = SYS___OPENAT2_A + +func Openat2(dirfd int, path string, how *OpenHow) (fd int, err error) { + if how.Flags&O_ACCMODE == 0 { + how.Flags |= O_RDONLY } - defer Chdir(wd) + return openat2(dirfd, path, how, SizeofOpenHow) +} - return Mkfifo(path, mode) +func ZosFdToPath(dirfd int) (path string, err error) { + var buffer [1024]byte + runtime.EnterSyscall() + ret, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_W_IOCTL<<4, uintptr(dirfd), 17, 1024, uintptr(unsafe.Pointer(&buffer[0]))) + runtime.ExitSyscall() + if ret == 0 { + zb := bytes.IndexByte(buffer[:], 0) + if zb == -1 { + zb = len(buffer) + } + CallLeFuncWithErr(GetZosLibVec()+SYS___E2A_L<<4, uintptr(unsafe.Pointer(&buffer[0])), uintptr(zb)) + return string(buffer[:zb]), nil + } + return "", errnoErr2(e1, e2) } //sys remove(path string) (err error) @@ -403,10 +1053,12 @@ func Getcwd(buf []byte) (n int, err error) { } else { p = unsafe.Pointer(&_zero) } - _, _, e := syscall_syscall(SYS___GETCWD_A, uintptr(p), uintptr(len(buf)), 0) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___GETCWD_A<<4, uintptr(p), uintptr(len(buf))) + runtime.ExitSyscall() n = clen(buf) + 1 - if e != 0 { - err = errnoErr(e) + if r0 == 0 { + err = errnoErr2(e1, e2) } return } @@ -520,9 +1172,41 @@ func (w WaitStatus) StopSignal() Signal { func (w WaitStatus) TrapCause() int { return -1 } +//sys waitid(idType int, id int, info *Siginfo, options int) (err error) + +func Waitid(idType int, id int, info *Siginfo, options int, rusage *Rusage) (err error) { + return waitid(idType, id, info, options) +} + //sys waitpid(pid int, wstatus *_C_int, options int) (wpid int, err error) -func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { +func impl_Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_WAIT4<<4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage))) + runtime.ExitSyscall() + wpid = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_Wait4Addr() *(func(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error)) + +var Wait4 = enter_Wait4 + +func enter_Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { + funcref := get_Wait4Addr() + if funcptrtest(GetZosLibVec()+SYS_WAIT4<<4, "") == 0 { + *funcref = impl_Wait4 + } else { + *funcref = legacyWait4 + } + return (*funcref)(pid, wstatus, options, rusage) +} + +func legacyWait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { // TODO(mundaym): z/OS doesn't have wait4. I don't think getrusage does what we want. // At the moment rusage will not be touched. var status _C_int @@ -571,23 +1255,62 @@ func Pipe(p []int) (err error) { } var pp [2]_C_int err = pipe(&pp) - if err == nil { - p[0] = int(pp[0]) - p[1] = int(pp[1]) - } + p[0] = int(pp[0]) + p[1] = int(pp[1]) return } //sys utimes(path string, timeval *[2]Timeval) (err error) = SYS___UTIMES_A func Utimes(path string, tv []Timeval) (err error) { + if tv == nil { + return utimes(path, nil) + } if len(tv) != 2 { return EINVAL } return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } -func UtimesNano(path string, ts []Timespec) error { +//sys utimensat(dirfd int, path string, ts *[2]Timespec, flags int) (err error) = SYS___UTIMENSAT_A + +func validUtimensat() bool { + if funcptrtest(GetZosLibVec()+SYS___UTIMENSAT_A<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS___UTIMENSAT_A<<4); err == nil { + return name == "__utimensat_a" + } + } + return false +} + +// Begin UtimesNano + +//go:nosplit +func get_UtimesNanoAddr() *(func(path string, ts []Timespec) (err error)) + +var UtimesNano = enter_UtimesNano + +func enter_UtimesNano(path string, ts []Timespec) (err error) { + funcref := get_UtimesNanoAddr() + if validUtimensat() { + *funcref = utimesNanoImpl + } else { + *funcref = legacyUtimesNano + } + return (*funcref)(path, ts) +} + +func utimesNanoImpl(path string, ts []Timespec) (err error) { + if ts == nil { + return utimensat(AT_FDCWD, path, nil, 0) + } + if len(ts) != 2 { + return EINVAL + } + return utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0) +} + +func legacyUtimesNano(path string, ts []Timespec) (err error) { if len(ts) != 2 { return EINVAL } @@ -600,6 +1323,70 @@ func UtimesNano(path string, ts []Timespec) error { return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } +// End UtimesNano + +// Begin UtimesNanoAt + +//go:nosplit +func get_UtimesNanoAtAddr() *(func(dirfd int, path string, ts []Timespec, flags int) (err error)) + +var UtimesNanoAt = enter_UtimesNanoAt + +func enter_UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) (err error) { + funcref := get_UtimesNanoAtAddr() + if validUtimensat() { + *funcref = utimesNanoAtImpl + } else { + *funcref = legacyUtimesNanoAt + } + return (*funcref)(dirfd, path, ts, flags) +} + +func utimesNanoAtImpl(dirfd int, path string, ts []Timespec, flags int) (err error) { + if ts == nil { + return utimensat(dirfd, path, nil, flags) + } + if len(ts) != 2 { + return EINVAL + } + return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags) +} + +func legacyUtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) (err error) { + if path[0] != '/' { + dirPath, err := ZosFdToPath(dirfd) + if err != nil { + return err + } + path = dirPath + "/" + path + } + if flags == AT_SYMLINK_NOFOLLOW { + if len(ts) != 2 { + return EINVAL + } + + if ts[0].Nsec >= 5e8 { + ts[0].Sec++ + } + ts[0].Nsec = 0 + if ts[1].Nsec >= 5e8 { + ts[1].Sec++ + } + ts[1].Nsec = 0 + + // Not as efficient as it could be because Timespec and + // Timeval have different types in the different OSes + tv := []Timeval{ + NsecToTimeval(TimespecToNsec(ts[0])), + NsecToTimeval(TimespecToNsec(ts[1])), + } + return Lutimes(path, tv) + } + return UtimesNano(path, ts) +} + +// End UtimesNanoAt + func Getsockname(fd int) (sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny @@ -1104,7 +1891,7 @@ func GetsockoptString(fd, level, opt int) (string, error) { return "", err } - return string(buf[:vallen-1]), nil + return ByteSliceToString(buf[:vallen]), nil } func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) { @@ -1191,10 +1978,13 @@ func Opendir(name string) (uintptr, error) { if err != nil { return 0, err } - dir, _, e := syscall_syscall(SYS___OPENDIR_A, uintptr(unsafe.Pointer(p)), 0, 0) + err = nil + runtime.EnterSyscall() + dir, e2, e1 := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___OPENDIR_A<<4, uintptr(unsafe.Pointer(p))) + runtime.ExitSyscall() runtime.KeepAlive(unsafe.Pointer(p)) - if e != 0 { - err = errnoErr(e) + if dir == 0 { + err = errnoErr2(e1, e2) } return dir, err } @@ -1202,51 +1992,27 @@ func Opendir(name string) (uintptr, error) { // clearsyscall.Errno resets the errno value to 0. func clearErrno() -func Readdir(dir uintptr) (*Dirent, error) { - var ent Dirent - var res uintptr - // __readdir_r_a returns errno at the end of the directory stream, rather than 0. - // Therefore to avoid false positives we clear errno before calling it. - - // TODO(neeilan): Commented this out to get sys/unix compiling on z/OS. Uncomment and fix. Error: "undefined: clearsyscall" - //clearsyscall.Errno() // TODO(mundaym): check pre-emption rules. - - e, _, _ := syscall_syscall(SYS___READDIR_R_A, dir, uintptr(unsafe.Pointer(&ent)), uintptr(unsafe.Pointer(&res))) - var err error - if e != 0 { - err = errnoErr(Errno(e)) - } - if res == 0 { - return nil, err - } - return &ent, err -} - -func readdir_r(dirp uintptr, entry *direntLE, result **direntLE) (err error) { - r0, _, e1 := syscall_syscall(SYS___READDIR_R_A, dirp, uintptr(unsafe.Pointer(entry)), uintptr(unsafe.Pointer(result))) - if int64(r0) == -1 { - err = errnoErr(Errno(e1)) - } - return -} - func Closedir(dir uintptr) error { - _, _, e := syscall_syscall(SYS_CLOSEDIR, dir, 0, 0) - if e != 0 { - return errnoErr(e) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_CLOSEDIR<<4, dir) + runtime.ExitSyscall() + if r0 != 0 { + return errnoErr2(e1, e2) } return nil } func Seekdir(dir uintptr, pos int) { - _, _, _ = syscall_syscall(SYS_SEEKDIR, dir, uintptr(pos), 0) + runtime.EnterSyscall() + CallLeFuncWithErr(GetZosLibVec()+SYS_SEEKDIR<<4, dir, uintptr(pos)) + runtime.ExitSyscall() } func Telldir(dir uintptr) (int, error) { - p, _, e := syscall_syscall(SYS_TELLDIR, dir, 0, 0) + p, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_TELLDIR<<4, dir) pos := int(p) - if pos == -1 { - return pos, errnoErr(e) + if int64(p) == -1 { + return pos, errnoErr2(e1, e2) } return pos, nil } @@ -1261,19 +2027,55 @@ func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { *(*int64)(unsafe.Pointer(&flock[4])) = lk.Start *(*int64)(unsafe.Pointer(&flock[12])) = lk.Len *(*int32)(unsafe.Pointer(&flock[20])) = lk.Pid - _, _, errno := syscall_syscall(SYS_FCNTL, fd, uintptr(cmd), uintptr(unsafe.Pointer(&flock))) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCNTL<<4, fd, uintptr(cmd), uintptr(unsafe.Pointer(&flock))) + runtime.ExitSyscall() lk.Type = *(*int16)(unsafe.Pointer(&flock[0])) lk.Whence = *(*int16)(unsafe.Pointer(&flock[2])) lk.Start = *(*int64)(unsafe.Pointer(&flock[4])) lk.Len = *(*int64)(unsafe.Pointer(&flock[12])) lk.Pid = *(*int32)(unsafe.Pointer(&flock[20])) - if errno == 0 { + if r0 == 0 { return nil } - return errno + return errnoErr2(e1, e2) +} + +func impl_Flock(fd int, how int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FLOCK<<4, uintptr(fd), uintptr(how)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return } -func Flock(fd int, how int) error { +//go:nosplit +func get_FlockAddr() *(func(fd int, how int) (err error)) + +var Flock = enter_Flock + +func validFlock(fp uintptr) bool { + if funcptrtest(GetZosLibVec()+SYS_FLOCK<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS_FLOCK<<4); err == nil { + return name == "flock" + } + } + return false +} + +func enter_Flock(fd int, how int) (err error) { + funcref := get_FlockAddr() + if validFlock(GetZosLibVec() + SYS_FLOCK<<4) { + *funcref = impl_Flock + } else { + *funcref = legacyFlock + } + return (*funcref)(fd, how) +} + +func legacyFlock(fd int, how int) error { var flock_type int16 var fcntl_cmd int @@ -1307,41 +2109,51 @@ func Flock(fd int, how int) error { } func Mlock(b []byte) (err error) { - _, _, e1 := syscall_syscall(SYS___MLOCKALL, _BPX_NONSWAP, 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_NONSWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) } return } func Mlock2(b []byte, flags int) (err error) { - _, _, e1 := syscall_syscall(SYS___MLOCKALL, _BPX_NONSWAP, 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_NONSWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) } return } func Mlockall(flags int) (err error) { - _, _, e1 := syscall_syscall(SYS___MLOCKALL, _BPX_NONSWAP, 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_NONSWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) } return } func Munlock(b []byte) (err error) { - _, _, e1 := syscall_syscall(SYS___MLOCKALL, _BPX_SWAP, 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_SWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) } return } func Munlockall() (err error) { - _, _, e1 := syscall_syscall(SYS___MLOCKALL, _BPX_SWAP, 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_SWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) } return } @@ -1367,20 +2179,109 @@ func ClockGettime(clockid int32, ts *Timespec) error { ts.Sec = int64(tm.Utime / ticks_per_sec) ts.Nsec = int64(tm.Utime) * nsec_per_sec / int64(ticks_per_sec) } else { - return EINVAL + return EINVAL + } + return nil +} + +// Chtag + +//go:nosplit +func get_ChtagAddr() *(func(path string, ccsid uint64, textbit uint64) error) + +var Chtag = enter_Chtag + +func enter_Chtag(path string, ccsid uint64, textbit uint64) error { + funcref := get_ChtagAddr() + if validSetxattr() { + *funcref = impl_Chtag + } else { + *funcref = legacy_Chtag + } + return (*funcref)(path, ccsid, textbit) +} + +func legacy_Chtag(path string, ccsid uint64, textbit uint64) error { + tag := ccsid<<16 | textbit<<15 + var tag_buff [8]byte + DecodeData(tag_buff[:], 8, tag) + return Setxattr(path, "filetag", tag_buff[:], XATTR_REPLACE) +} + +func impl_Chtag(path string, ccsid uint64, textbit uint64) error { + tag := ccsid<<16 | textbit<<15 + var tag_buff [4]byte + DecodeData(tag_buff[:], 4, tag) + return Setxattr(path, "system.filetag", tag_buff[:], XATTR_REPLACE) +} + +// End of Chtag + +// Nanosleep + +//go:nosplit +func get_NanosleepAddr() *(func(time *Timespec, leftover *Timespec) error) + +var Nanosleep = enter_Nanosleep + +func enter_Nanosleep(time *Timespec, leftover *Timespec) error { + funcref := get_NanosleepAddr() + if funcptrtest(GetZosLibVec()+SYS_NANOSLEEP<<4, "") == 0 { + *funcref = impl_Nanosleep + } else { + *funcref = legacyNanosleep + } + return (*funcref)(time, leftover) +} + +func impl_Nanosleep(time *Timespec, leftover *Timespec) error { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_NANOSLEEP<<4, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover))) + runtime.ExitSyscall() + if int64(r0) == -1 { + return errnoErr2(e1, e2) } return nil } -func Statfs(path string, stat *Statfs_t) (err error) { - fd, err := open(path, O_RDONLY, 0) - defer Close(fd) - if err != nil { - return err +func legacyNanosleep(time *Timespec, leftover *Timespec) error { + t0 := runtime.Nanotime1() + var secrem uint32 + var nsecrem uint32 + total := time.Sec*1000000000 + time.Nsec + elapsed := runtime.Nanotime1() - t0 + var rv int32 + var rc int32 + var err error + // repeatedly sleep for 1 second until less than 1 second left + for total-elapsed > 1000000000 { + rv, rc, _ = BpxCondTimedWait(uint32(1), uint32(0), uint32(CW_CONDVAR), &secrem, &nsecrem) + if rv != 0 && rc != 112 { // 112 is EAGAIN + if leftover != nil && rc == 120 { // 120 is EINTR + leftover.Sec = int64(secrem) + leftover.Nsec = int64(nsecrem) + } + err = Errno(rc) + return err + } + elapsed = runtime.Nanotime1() - t0 + } + // sleep the remainder + if total > elapsed { + rv, rc, _ = BpxCondTimedWait(uint32(0), uint32(total-elapsed), uint32(CW_CONDVAR), &secrem, &nsecrem) } - return Fstatfs(fd, stat) + if leftover != nil && rc == 120 { + leftover.Sec = int64(secrem) + leftover.Nsec = int64(nsecrem) + } + if rv != 0 && rc != 112 { + err = Errno(rc) + } + return err } +// End of Nanosleep + var ( Stdin = 0 Stdout = 1 @@ -1395,6 +2296,9 @@ var ( errENOENT error = syscall.ENOENT ) +var ZosTraceLevel int +var ZosTracefile *os.File + var ( signalNameMapOnce sync.Once signalNameMap map[string]syscall.Signal @@ -1416,6 +2320,56 @@ func errnoErr(e Errno) error { return e } +var reg *regexp.Regexp + +// enhanced with zos specific errno2 +func errnoErr2(e Errno, e2 uintptr) error { + switch e { + case 0: + return nil + case EAGAIN: + return errEAGAIN + /* + Allow the retrieval of errno2 for EINVAL and ENOENT on zos + case EINVAL: + return errEINVAL + case ENOENT: + return errENOENT + */ + } + if ZosTraceLevel > 0 { + var name string + if reg == nil { + reg = regexp.MustCompile("(^unix\\.[^/]+$|.*\\/unix\\.[^/]+$)") + } + i := 1 + pc, file, line, ok := runtime.Caller(i) + if ok { + name = runtime.FuncForPC(pc).Name() + } + for ok && reg.MatchString(runtime.FuncForPC(pc).Name()) { + i += 1 + pc, file, line, ok = runtime.Caller(i) + } + if ok { + if ZosTracefile == nil { + ZosConsolePrintf("From %s:%d\n", file, line) + ZosConsolePrintf("%s: %s (errno2=0x%x)\n", name, e.Error(), e2) + } else { + fmt.Fprintf(ZosTracefile, "From %s:%d\n", file, line) + fmt.Fprintf(ZosTracefile, "%s: %s (errno2=0x%x)\n", name, e.Error(), e2) + } + } else { + if ZosTracefile == nil { + ZosConsolePrintf("%s (errno2=0x%x)\n", e.Error(), e2) + } else { + fmt.Fprintf(ZosTracefile, "%s (errno2=0x%x)\n", e.Error(), e2) + } + } + } + return e +} + // ErrnoName returns the error name for error number e. func ErrnoName(e Errno) string { i := sort.Search(len(errorList), func(i int) bool { @@ -1474,6 +2428,9 @@ func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (d return nil, EINVAL } + // Set __MAP_64 by default + flags |= __MAP_64 + // Map the requested memory. addr, errno := m.mmap(0, uintptr(length), prot, flags, fd, offset) if errno != nil { @@ -1778,83 +2735,170 @@ func Exec(argv0 string, argv []string, envv []string) error { return syscall.Exec(argv0, argv, envv) } -func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) { +func Getag(path string) (ccsid uint16, flag uint16, err error) { + var val [8]byte + sz, err := Getxattr(path, "ccsid", val[:]) + if err != nil { + return + } + ccsid = uint16(EncodeData(val[0:sz])) + sz, err = Getxattr(path, "flags", val[:]) + if err != nil { + return + } + flag = uint16(EncodeData(val[0:sz]) >> 15) + return +} + +// Mount begin +func impl_Mount(source string, target string, fstype string, flags uintptr, data string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(source) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(target) + if err != nil { + return + } + var _p2 *byte + _p2, err = BytePtrFromString(fstype) + if err != nil { + return + } + var _p3 *byte + _p3, err = BytePtrFromString(data) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MOUNT1_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(_p3))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_MountAddr() *(func(source string, target string, fstype string, flags uintptr, data string) (err error)) + +var Mount = enter_Mount + +func enter_Mount(source string, target string, fstype string, flags uintptr, data string) (err error) { + funcref := get_MountAddr() + if validMount() { + *funcref = impl_Mount + } else { + *funcref = legacyMount + } + return (*funcref)(source, target, fstype, flags, data) +} + +func legacyMount(source string, target string, fstype string, flags uintptr, data string) (err error) { if needspace := 8 - len(fstype); needspace <= 0 { - fstype = fstype[:8] + fstype = fstype[0:8] } else { - fstype += " "[:needspace] + fstype += " "[0:needspace] } return mount_LE(target, source, fstype, uint32(flags), int32(len(data)), data) } -func Unmount(name string, mtm int) (err error) { +func validMount() bool { + if funcptrtest(GetZosLibVec()+SYS___MOUNT1_A<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS___MOUNT1_A<<4); err == nil { + return name == "__mount1_a" + } + } + return false +} + +// Mount end + +// Unmount begin +func impl_Unmount(target string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(target) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UMOUNT2_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_UnmountAddr() *(func(target string, flags int) (err error)) + +var Unmount = enter_Unmount + +func enter_Unmount(target string, flags int) (err error) { + funcref := get_UnmountAddr() + if funcptrtest(GetZosLibVec()+SYS___UMOUNT2_A<<4, "") == 0 { + *funcref = impl_Unmount + } else { + *funcref = legacyUnmount + } + return (*funcref)(target, flags) +} + +func legacyUnmount(name string, mtm int) (err error) { // mountpoint is always a full path and starts with a '/' // check if input string is not a mountpoint but a filesystem name if name[0] != '/' { - return unmount(name, mtm) + return unmount_LE(name, mtm) } // treat name as mountpoint b2s := func(arr []byte) string { - nulli := bytes.IndexByte(arr, 0) - if nulli == -1 { - return string(arr) - } else { - return string(arr[:nulli]) + var str string + for i := 0; i < len(arr); i++ { + if arr[i] == 0 { + str = string(arr[:i]) + break + } } + return str } var buffer struct { header W_Mnth fsinfo [64]W_Mntent } - fsCount, err := W_Getmntent_A((*byte)(unsafe.Pointer(&buffer)), int(unsafe.Sizeof(buffer))) - if err != nil { - return err - } - if fsCount == 0 { - return EINVAL - } - for i := 0; i < fsCount; i++ { - if b2s(buffer.fsinfo[i].Mountpoint[:]) == name { - err = unmount(b2s(buffer.fsinfo[i].Fsname[:]), mtm) - break + fs_count, err := W_Getmntent_A((*byte)(unsafe.Pointer(&buffer)), int(unsafe.Sizeof(buffer))) + if err == nil { + err = EINVAL + for i := 0; i < fs_count; i++ { + if b2s(buffer.fsinfo[i].Mountpoint[:]) == name { + err = unmount_LE(b2s(buffer.fsinfo[i].Fsname[:]), mtm) + break + } } + } else if fs_count == 0 { + err = EINVAL } return err } -func fdToPath(dirfd int) (path string, err error) { - var buffer [1024]byte - // w_ctrl() - ret := runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS_W_IOCTL<<4, - []uintptr{uintptr(dirfd), 17, 1024, uintptr(unsafe.Pointer(&buffer[0]))}) - if ret == 0 { - zb := bytes.IndexByte(buffer[:], 0) - if zb == -1 { - zb = len(buffer) - } - // __e2a_l() - runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___E2A_L<<4, - []uintptr{uintptr(unsafe.Pointer(&buffer[0])), uintptr(zb)}) - return string(buffer[:zb]), nil - } - // __errno() - errno := int(*(*int32)(unsafe.Pointer(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO<<4, - []uintptr{})))) - // __errno2() - errno2 := int(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO2<<4, - []uintptr{})) - // strerror_r() - ret = runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS_STRERROR_R<<4, - []uintptr{uintptr(errno), uintptr(unsafe.Pointer(&buffer[0])), 1024}) - if ret == 0 { - zb := bytes.IndexByte(buffer[:], 0) - if zb == -1 { - zb = len(buffer) - } - return "", fmt.Errorf("%s (errno2=0x%x)", buffer[:zb], errno2) - } else { - return "", fmt.Errorf("fdToPath errno %d (errno2=0x%x)", errno, errno2) +// Unmount end + +func direntIno(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) +} + +func direntReclen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) +} + +func direntNamlen(buf []byte) (uint64, bool) { + reclen, ok := direntReclen(buf) + if !ok { + return 0, false } + return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true } func direntLeToDirentUnix(dirent *direntLE, dir uintptr, path string) (Dirent, error) { @@ -1896,7 +2940,7 @@ func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { } // Get path from fd to avoid unavailable call (fdopendir) - path, err := fdToPath(fd) + path, err := ZosFdToPath(fd) if err != nil { return 0, err } @@ -1910,7 +2954,7 @@ func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { for { var entryLE direntLE var entrypLE *direntLE - e := readdir_r(d, &entryLE, &entrypLE) + e := Readdir_r(d, &entryLE, &entrypLE) if e != nil { return n, e } @@ -1956,23 +3000,214 @@ func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { return n, nil } -func ReadDirent(fd int, buf []byte) (n int, err error) { - var base = (*uintptr)(unsafe.Pointer(new(uint64))) - return Getdirentries(fd, buf, base) +func Err2ad() (eadd *int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS___ERR2AD<<4) + eadd = (*int)(unsafe.Pointer(r0)) + return } -func direntIno(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) +func ZosConsolePrintf(format string, v ...interface{}) (int, error) { + type __cmsg struct { + _ uint16 + _ [2]uint8 + __msg_length uint32 + __msg uintptr + _ [4]uint8 + } + msg := fmt.Sprintf(format, v...) + strptr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&msg)).Data) + len := (*reflect.StringHeader)(unsafe.Pointer(&msg)).Len + cmsg := __cmsg{__msg_length: uint32(len), __msg: uintptr(strptr)} + cmd := uint32(0) + runtime.EnterSyscall() + rc, err2, err1 := CallLeFuncWithErr(GetZosLibVec()+SYS_____CONSOLE_A<<4, uintptr(unsafe.Pointer(&cmsg)), 0, uintptr(unsafe.Pointer(&cmd))) + runtime.ExitSyscall() + if rc != 0 { + return 0, fmt.Errorf("%s (errno2=0x%x)\n", err1.Error(), err2) + } + return 0, nil +} +func ZosStringToEbcdicBytes(str string, nullterm bool) (ebcdicBytes []byte) { + if nullterm { + ebcdicBytes = []byte(str + "\x00") + } else { + ebcdicBytes = []byte(str) + } + A2e(ebcdicBytes) + return +} +func ZosEbcdicBytesToString(b []byte, trimRight bool) (str string) { + res := make([]byte, len(b)) + copy(res, b) + E2a(res) + if trimRight { + str = string(bytes.TrimRight(res, " \x00")) + } else { + str = string(res) + } + return } -func direntReclen(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) +func fdToPath(dirfd int) (path string, err error) { + var buffer [1024]byte + // w_ctrl() + ret := runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS_W_IOCTL<<4, + []uintptr{uintptr(dirfd), 17, 1024, uintptr(unsafe.Pointer(&buffer[0]))}) + if ret == 0 { + zb := bytes.IndexByte(buffer[:], 0) + if zb == -1 { + zb = len(buffer) + } + // __e2a_l() + runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___E2A_L<<4, + []uintptr{uintptr(unsafe.Pointer(&buffer[0])), uintptr(zb)}) + return string(buffer[:zb]), nil + } + // __errno() + errno := int(*(*int32)(unsafe.Pointer(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO<<4, + []uintptr{})))) + // __errno2() + errno2 := int(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO2<<4, + []uintptr{})) + // strerror_r() + ret = runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS_STRERROR_R<<4, + []uintptr{uintptr(errno), uintptr(unsafe.Pointer(&buffer[0])), 1024}) + if ret == 0 { + zb := bytes.IndexByte(buffer[:], 0) + if zb == -1 { + zb = len(buffer) + } + return "", fmt.Errorf("%s (errno2=0x%x)", buffer[:zb], errno2) + } else { + return "", fmt.Errorf("fdToPath errno %d (errno2=0x%x)", errno, errno2) + } } -func direntNamlen(buf []byte) (uint64, bool) { - reclen, ok := direntReclen(buf) - if !ok { - return 0, false +func impl_Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return } - return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKFIFOAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_MkfifoatAddr() *(func(dirfd int, path string, mode uint32) (err error)) + +var Mkfifoat = enter_Mkfifoat + +func enter_Mkfifoat(dirfd int, path string, mode uint32) (err error) { + funcref := get_MkfifoatAddr() + if funcptrtest(GetZosLibVec()+SYS___MKFIFOAT_A<<4, "") == 0 { + *funcref = impl_Mkfifoat + } else { + *funcref = legacy_Mkfifoat + } + return (*funcref)(dirfd, path, mode) +} + +func legacy_Mkfifoat(dirfd int, path string, mode uint32) (err error) { + dirname, err := ZosFdToPath(dirfd) + if err != nil { + return err + } + return Mkfifo(dirname+"/"+path, mode) +} + +//sys Posix_openpt(oflag int) (fd int, err error) = SYS_POSIX_OPENPT +//sys Grantpt(fildes int) (rc int, err error) = SYS_GRANTPT +//sys Unlockpt(fildes int) (rc int, err error) = SYS_UNLOCKPT + +func fcntlAsIs(fd uintptr, cmd int, arg uintptr) (val int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCNTL<<4, uintptr(fd), uintptr(cmd), arg) + runtime.ExitSyscall() + val = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +func Fcntl(fd uintptr, cmd int, op interface{}) (ret int, err error) { + switch op.(type) { + case *Flock_t: + err = FcntlFlock(fd, cmd, op.(*Flock_t)) + if err != nil { + ret = -1 + } + return + case int: + return FcntlInt(fd, cmd, op.(int)) + case *F_cnvrt: + return fcntlAsIs(fd, cmd, uintptr(unsafe.Pointer(op.(*F_cnvrt)))) + case unsafe.Pointer: + return fcntlAsIs(fd, cmd, uintptr(op.(unsafe.Pointer))) + default: + return -1, EINVAL + } + return +} + +func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + return sendfile(outfd, infd, offset, count) +} + +func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + // TODO: use LE call instead if the call is implemented + originalOffset, err := Seek(infd, 0, SEEK_CUR) + if err != nil { + return -1, err + } + //start reading data from in_fd + if offset != nil { + _, err := Seek(infd, *offset, SEEK_SET) + if err != nil { + return -1, err + } + } + + buf := make([]byte, count) + readBuf := make([]byte, 0) + var n int = 0 + for i := 0; i < count; i += n { + n, err := Read(infd, buf) + if n == 0 { + if err != nil { + return -1, err + } else { // EOF + break + } + } + readBuf = append(readBuf, buf...) + buf = buf[0:0] + } + + n2, err := Write(outfd, readBuf) + if err != nil { + return -1, err + } + + //When sendfile() returns, this variable will be set to the + // offset of the byte following the last byte that was read. + if offset != nil { + *offset = *offset + int64(n) + // If offset is not NULL, then sendfile() does not modify the file + // offset of in_fd + _, err := Seek(infd, originalOffset, SEEK_SET) + if err != nil { + return -1, err + } + } + return n2, nil } diff --git a/vendor/golang.org/x/sys/unix/sysvshm_unix.go b/vendor/golang.org/x/sys/unix/sysvshm_unix.go index 79a84f18..672d6b0a 100644 --- a/vendor/golang.org/x/sys/unix/sysvshm_unix.go +++ b/vendor/golang.org/x/sys/unix/sysvshm_unix.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build (darwin && !ios) || linux +//go:build (darwin && !ios) || linux || zos package unix diff --git a/vendor/golang.org/x/sys/unix/sysvshm_unix_other.go b/vendor/golang.org/x/sys/unix/sysvshm_unix_other.go index 9eb0db66..8b7977a2 100644 --- a/vendor/golang.org/x/sys/unix/sysvshm_unix_other.go +++ b/vendor/golang.org/x/sys/unix/sysvshm_unix_other.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build darwin && !ios +//go:build (darwin && !ios) || zos package unix diff --git a/vendor/golang.org/x/sys/unix/vgetrandom_linux.go b/vendor/golang.org/x/sys/unix/vgetrandom_linux.go new file mode 100644 index 00000000..07ac8e09 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/vgetrandom_linux.go @@ -0,0 +1,13 @@ +// Copyright 2024 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. + +//go:build linux && go1.24 + +package unix + +import _ "unsafe" + +//go:linkname vgetrandom runtime.vgetrandom +//go:noescape +func vgetrandom(p []byte, flags uint32) (ret int, supported bool) diff --git a/vendor/golang.org/x/sys/unix/vgetrandom_unsupported.go b/vendor/golang.org/x/sys/unix/vgetrandom_unsupported.go new file mode 100644 index 00000000..297e97bc --- /dev/null +++ b/vendor/golang.org/x/sys/unix/vgetrandom_unsupported.go @@ -0,0 +1,11 @@ +// Copyright 2024 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. + +//go:build !linux || !go1.24 + +package unix + +func vgetrandom(p []byte, flags uint32) (ret int, supported bool) { + return -1, false +} diff --git a/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go index e40fa852..d73c4652 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go @@ -237,6 +237,9 @@ const ( CLOCK_UPTIME_RAW_APPROX = 0x9 CLONE_NOFOLLOW = 0x1 CLONE_NOOWNERCOPY = 0x2 + CONNECT_DATA_AUTHENTICATED = 0x4 + CONNECT_DATA_IDEMPOTENT = 0x2 + CONNECT_RESUME_ON_READ_WRITE = 0x1 CR0 = 0x0 CR1 = 0x1000 CR2 = 0x2000 @@ -1169,6 +1172,11 @@ const ( PT_WRITE_D = 0x5 PT_WRITE_I = 0x4 PT_WRITE_U = 0x6 + RENAME_EXCL = 0x4 + RENAME_NOFOLLOW_ANY = 0x10 + RENAME_RESERVED1 = 0x8 + RENAME_SECLUDE = 0x1 + RENAME_SWAP = 0x2 RLIMIT_AS = 0x5 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 @@ -1260,6 +1268,10 @@ const ( RTV_SSTHRESH = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 + SAE_ASSOCID_ALL = 0xffffffff + SAE_ASSOCID_ANY = 0x0 + SAE_CONNID_ALL = 0xffffffff + SAE_CONNID_ANY = 0x0 SCM_CREDS = 0x3 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 diff --git a/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go index bb02aa6c..4a55a400 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go @@ -237,6 +237,9 @@ const ( CLOCK_UPTIME_RAW_APPROX = 0x9 CLONE_NOFOLLOW = 0x1 CLONE_NOOWNERCOPY = 0x2 + CONNECT_DATA_AUTHENTICATED = 0x4 + CONNECT_DATA_IDEMPOTENT = 0x2 + CONNECT_RESUME_ON_READ_WRITE = 0x1 CR0 = 0x0 CR1 = 0x1000 CR2 = 0x2000 @@ -1169,6 +1172,11 @@ const ( PT_WRITE_D = 0x5 PT_WRITE_I = 0x4 PT_WRITE_U = 0x6 + RENAME_EXCL = 0x4 + RENAME_NOFOLLOW_ANY = 0x10 + RENAME_RESERVED1 = 0x8 + RENAME_SECLUDE = 0x1 + RENAME_SWAP = 0x2 RLIMIT_AS = 0x5 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 @@ -1260,6 +1268,10 @@ const ( RTV_SSTHRESH = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 + SAE_ASSOCID_ALL = 0xffffffff + SAE_ASSOCID_ANY = 0x0 + SAE_CONNID_ALL = 0xffffffff + SAE_CONNID_ANY = 0x0 SCM_CREDS = 0x3 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux.go b/vendor/golang.org/x/sys/unix/zerrors_linux.go index 9c00cbf5..6ebc48b3 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux.go @@ -321,6 +321,9 @@ const ( AUDIT_INTEGRITY_STATUS = 0x70a AUDIT_IPC = 0x517 AUDIT_IPC_SET_PERM = 0x51f + AUDIT_IPE_ACCESS = 0x58c + AUDIT_IPE_CONFIG_CHANGE = 0x58d + AUDIT_IPE_POLICY_LOAD = 0x58e AUDIT_KERNEL = 0x7d0 AUDIT_KERNEL_OTHER = 0x524 AUDIT_KERN_MODULE = 0x532 @@ -457,6 +460,7 @@ const ( B600 = 0x8 B75 = 0x2 B9600 = 0xd + BCACHEFS_SUPER_MAGIC = 0xca451a4e BDEVFS_MAGIC = 0x62646576 BINDERFS_SUPER_MAGIC = 0x6c6f6f70 BINFMTFS_MAGIC = 0x42494e4d @@ -486,14 +490,16 @@ const ( BPF_F_ANY_ALIGNMENT = 0x2 BPF_F_BEFORE = 0x8 BPF_F_ID = 0x20 - BPF_F_LINK = 0x2000 BPF_F_NETFILTER_IP_DEFRAG = 0x1 BPF_F_QUERY_EFFECTIVE = 0x1 + BPF_F_REDIRECT_FLAGS = 0x19 BPF_F_REPLACE = 0x4 BPF_F_SLEEPABLE = 0x10 BPF_F_STRICT_ALIGNMENT = 0x1 + BPF_F_TEST_REG_INVARIANTS = 0x80 BPF_F_TEST_RND_HI32 = 0x4 BPF_F_TEST_RUN_ON_CPU = 0x1 + BPF_F_TEST_SKB_CHECKSUM_COMPLETE = 0x4 BPF_F_TEST_STATE_FREQ = 0x8 BPF_F_TEST_XDP_LIVE_FRAMES = 0x2 BPF_F_XDP_DEV_BOUND_ONLY = 0x40 @@ -502,6 +508,7 @@ const ( BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 + BPF_JCOND = 0xe0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 @@ -657,6 +664,9 @@ const ( CAN_NPROTO = 0x8 CAN_RAW = 0x1 CAN_RAW_FILTER_MAX = 0x200 + CAN_RAW_XL_VCID_RX_FILTER = 0x4 + CAN_RAW_XL_VCID_TX_PASS = 0x2 + CAN_RAW_XL_VCID_TX_SET = 0x1 CAN_RTR_FLAG = 0x40000000 CAN_SFF_ID_BITS = 0xb CAN_SFF_MASK = 0x7ff @@ -924,6 +934,7 @@ const ( EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 + EPOLL_IOC_TYPE = 0x8a EROFS_SUPER_MAGIC_V1 = 0xe0f5e1e2 ESP_V4_FLOW = 0xa ESP_V6_FLOW = 0xc @@ -937,9 +948,6 @@ const ( ETHTOOL_FEC_OFF = 0x4 ETHTOOL_FEC_RS = 0x8 ETHTOOL_FLAG_ALL = 0x7 - ETHTOOL_FLAG_COMPACT_BITSETS = 0x1 - ETHTOOL_FLAG_OMIT_REPLY = 0x2 - ETHTOOL_FLAG_STATS = 0x4 ETHTOOL_FLASHDEV = 0x33 ETHTOOL_FLASH_MAX_FILENAME = 0x80 ETHTOOL_FWVERS_LEN = 0x20 @@ -1162,6 +1170,7 @@ const ( EXTA = 0xe EXTB = 0xf F2FS_SUPER_MAGIC = 0xf2f52010 + FALLOC_FL_ALLOCATE_RANGE = 0x0 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 @@ -1339,6 +1348,7 @@ const ( F_OFD_SETLK = 0x25 F_OFD_SETLKW = 0x26 F_OK = 0x0 + F_SEAL_EXEC = 0x20 F_SEAL_FUTURE_WRITE = 0x10 F_SEAL_GROW = 0x4 F_SEAL_SEAL = 0x1 @@ -1627,6 +1637,7 @@ const ( IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 + IP_LOCAL_PORT_RANGE = 0x33 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 @@ -1653,6 +1664,7 @@ const ( IP_PMTUDISC_OMIT = 0x5 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 + IP_PROTOCOL = 0x34 IP_RECVERR = 0xb IP_RECVERR_RFC4884 = 0x1a IP_RECVFRAGSIZE = 0x19 @@ -1698,6 +1710,8 @@ const ( KEXEC_ARCH_S390 = 0x160000 KEXEC_ARCH_SH = 0x2a0000 KEXEC_ARCH_X86_64 = 0x3e0000 + KEXEC_CRASH_HOTPLUG_SUPPORT = 0x8 + KEXEC_FILE_DEBUG = 0x8 KEXEC_FILE_NO_INITRAMFS = 0x4 KEXEC_FILE_ON_CRASH = 0x2 KEXEC_FILE_UNLOAD = 0x1 @@ -1772,6 +1786,7 @@ const ( KEY_SPEC_USER_KEYRING = -0x4 KEY_SPEC_USER_SESSION_KEYRING = -0x5 LANDLOCK_ACCESS_FS_EXECUTE = 0x1 + LANDLOCK_ACCESS_FS_IOCTL_DEV = 0x8000 LANDLOCK_ACCESS_FS_MAKE_BLOCK = 0x800 LANDLOCK_ACCESS_FS_MAKE_CHAR = 0x40 LANDLOCK_ACCESS_FS_MAKE_DIR = 0x80 @@ -1786,7 +1801,11 @@ const ( LANDLOCK_ACCESS_FS_REMOVE_FILE = 0x20 LANDLOCK_ACCESS_FS_TRUNCATE = 0x4000 LANDLOCK_ACCESS_FS_WRITE_FILE = 0x2 + LANDLOCK_ACCESS_NET_BIND_TCP = 0x1 + LANDLOCK_ACCESS_NET_CONNECT_TCP = 0x2 LANDLOCK_CREATE_RULESET_VERSION = 0x1 + LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET = 0x1 + LANDLOCK_SCOPE_SIGNAL = 0x2 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 @@ -1802,6 +1821,7 @@ const ( LOCK_SH = 0x1 LOCK_UN = 0x8 LOOP_CLR_FD = 0x4c01 + LOOP_CONFIGURE = 0x4c0a LOOP_CTL_ADD = 0x4c80 LOOP_CTL_GET_FREE = 0x4c82 LOOP_CTL_REMOVE = 0x4c81 @@ -1850,6 +1870,19 @@ const ( MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_FIXED_NOREPLACE = 0x100000 + MAP_HUGE_16GB = 0x88000000 + MAP_HUGE_16KB = 0x38000000 + MAP_HUGE_16MB = 0x60000000 + MAP_HUGE_1GB = 0x78000000 + MAP_HUGE_1MB = 0x50000000 + MAP_HUGE_256MB = 0x70000000 + MAP_HUGE_2GB = 0x7c000000 + MAP_HUGE_2MB = 0x54000000 + MAP_HUGE_32MB = 0x64000000 + MAP_HUGE_512KB = 0x4c000000 + MAP_HUGE_512MB = 0x74000000 + MAP_HUGE_64KB = 0x40000000 + MAP_HUGE_8MB = 0x5c000000 MAP_HUGE_MASK = 0x3f MAP_HUGE_SHIFT = 0x1a MAP_PRIVATE = 0x2 @@ -1896,6 +1929,9 @@ const ( MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 + MNT_ID_REQ_SIZE_VER0 = 0x18 + MNT_ID_REQ_SIZE_VER1 = 0x20 + MNT_NS_INFO_SIZE_VER0 = 0x10 MODULE_INIT_COMPRESSED_FILE = 0x4 MODULE_INIT_IGNORE_MODVERSIONS = 0x1 MODULE_INIT_IGNORE_VERMAGIC = 0x2 @@ -2127,6 +2163,60 @@ const ( NFNL_SUBSYS_QUEUE = 0x3 NFNL_SUBSYS_ULOG = 0x4 NFS_SUPER_MAGIC = 0x6969 + NFT_CHAIN_FLAGS = 0x7 + NFT_CHAIN_MAXNAMELEN = 0x100 + NFT_CT_MAX = 0x17 + NFT_DATA_RESERVED_MASK = 0xffffff00 + NFT_DATA_VALUE_MAXLEN = 0x40 + NFT_EXTHDR_OP_MAX = 0x4 + NFT_FIB_RESULT_MAX = 0x3 + NFT_INNER_MASK = 0xf + NFT_LOGLEVEL_MAX = 0x8 + NFT_NAME_MAXLEN = 0x100 + NFT_NG_MAX = 0x1 + NFT_OBJECT_CONNLIMIT = 0x5 + NFT_OBJECT_COUNTER = 0x1 + NFT_OBJECT_CT_EXPECT = 0x9 + NFT_OBJECT_CT_HELPER = 0x3 + NFT_OBJECT_CT_TIMEOUT = 0x7 + NFT_OBJECT_LIMIT = 0x4 + NFT_OBJECT_MAX = 0xa + NFT_OBJECT_QUOTA = 0x2 + NFT_OBJECT_SECMARK = 0x8 + NFT_OBJECT_SYNPROXY = 0xa + NFT_OBJECT_TUNNEL = 0x6 + NFT_OBJECT_UNSPEC = 0x0 + NFT_OBJ_MAXNAMELEN = 0x100 + NFT_OSF_MAXGENRELEN = 0x10 + NFT_QUEUE_FLAG_BYPASS = 0x1 + NFT_QUEUE_FLAG_CPU_FANOUT = 0x2 + NFT_QUEUE_FLAG_MASK = 0x3 + NFT_REG32_COUNT = 0x10 + NFT_REG32_SIZE = 0x4 + NFT_REG_MAX = 0x4 + NFT_REG_SIZE = 0x10 + NFT_REJECT_ICMPX_MAX = 0x3 + NFT_RT_MAX = 0x4 + NFT_SECMARK_CTX_MAXLEN = 0x1000 + NFT_SET_MAXNAMELEN = 0x100 + NFT_SOCKET_MAX = 0x3 + NFT_TABLE_F_MASK = 0x7 + NFT_TABLE_MAXNAMELEN = 0x100 + NFT_TRACETYPE_MAX = 0x3 + NFT_TUNNEL_F_MASK = 0x7 + NFT_TUNNEL_MAX = 0x1 + NFT_TUNNEL_MODE_MAX = 0x2 + NFT_USERDATA_MAXLEN = 0x100 + NFT_XFRM_KEY_MAX = 0x6 + NF_NAT_RANGE_MAP_IPS = 0x1 + NF_NAT_RANGE_MASK = 0x7f + NF_NAT_RANGE_NETMAP = 0x40 + NF_NAT_RANGE_PERSISTENT = 0x8 + NF_NAT_RANGE_PROTO_OFFSET = 0x20 + NF_NAT_RANGE_PROTO_RANDOM = 0x4 + NF_NAT_RANGE_PROTO_RANDOM_ALL = 0x14 + NF_NAT_RANGE_PROTO_RANDOM_FULLY = 0x10 + NF_NAT_RANGE_PROTO_SPECIFIED = 0x2 NILFS_SUPER_MAGIC = 0x3434 NL0 = 0x0 NL1 = 0x100 @@ -2246,6 +2336,7 @@ const ( PERF_AUX_FLAG_PARTIAL = 0x4 PERF_AUX_FLAG_PMU_FORMAT_TYPE_MASK = 0xff00 PERF_AUX_FLAG_TRUNCATED = 0x1 + PERF_BRANCH_ENTRY_INFO_BITS_MAX = 0x21 PERF_BR_ARM64_DEBUG_DATA = 0x7 PERF_BR_ARM64_DEBUG_EXIT = 0x5 PERF_BR_ARM64_DEBUG_HALT = 0x4 @@ -2275,9 +2366,11 @@ const ( PERF_MEM_LVLNUM_IO = 0xa PERF_MEM_LVLNUM_L1 = 0x1 PERF_MEM_LVLNUM_L2 = 0x2 + PERF_MEM_LVLNUM_L2_MHB = 0x5 PERF_MEM_LVLNUM_L3 = 0x3 PERF_MEM_LVLNUM_L4 = 0x4 PERF_MEM_LVLNUM_LFB = 0xc + PERF_MEM_LVLNUM_MSC = 0x6 PERF_MEM_LVLNUM_NA = 0xf PERF_MEM_LVLNUM_PMEM = 0xe PERF_MEM_LVLNUM_RAM = 0xd @@ -2343,12 +2436,14 @@ const ( PERF_RECORD_MISC_USER = 0x2 PERF_SAMPLE_BRANCH_PLM_ALL = 0x7 PERF_SAMPLE_WEIGHT_TYPE = 0x1004000 + PID_FS_MAGIC = 0x50494446 PIPEFS_MAGIC = 0x50495045 PPPIOCGNPMODE = 0xc008744c PPPIOCNEWUNIT = 0xc004743e PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 + PROCFS_IOCTL_MAGIC = 'f' PROC_SUPER_MAGIC = 0x9fa0 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 @@ -2411,6 +2506,7 @@ const ( PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 + PR_MDWE_NO_INHERIT = 0x2 PR_MDWE_REFUSE_EXEC_GAIN = 0x1 PR_MPX_DISABLE_MANAGEMENT = 0x2c PR_MPX_ENABLE_MANAGEMENT = 0x2b @@ -2429,6 +2525,23 @@ const ( PR_PAC_GET_ENABLED_KEYS = 0x3d PR_PAC_RESET_KEYS = 0x36 PR_PAC_SET_ENABLED_KEYS = 0x3c + PR_PPC_DEXCR_CTRL_CLEAR = 0x4 + PR_PPC_DEXCR_CTRL_CLEAR_ONEXEC = 0x10 + PR_PPC_DEXCR_CTRL_EDITABLE = 0x1 + PR_PPC_DEXCR_CTRL_MASK = 0x1f + PR_PPC_DEXCR_CTRL_SET = 0x2 + PR_PPC_DEXCR_CTRL_SET_ONEXEC = 0x8 + PR_PPC_DEXCR_IBRTPD = 0x1 + PR_PPC_DEXCR_NPHIE = 0x3 + PR_PPC_DEXCR_SBHE = 0x0 + PR_PPC_DEXCR_SRAPD = 0x2 + PR_PPC_GET_DEXCR = 0x48 + PR_PPC_SET_DEXCR = 0x49 + PR_RISCV_CTX_SW_FENCEI_OFF = 0x1 + PR_RISCV_CTX_SW_FENCEI_ON = 0x0 + PR_RISCV_SCOPE_PER_PROCESS = 0x0 + PR_RISCV_SCOPE_PER_THREAD = 0x1 + PR_RISCV_SET_ICACHE_FLUSH_CTX = 0x47 PR_RISCV_V_GET_CONTROL = 0x46 PR_RISCV_V_SET_CONTROL = 0x45 PR_RISCV_V_VSTATE_CTRL_CUR_MASK = 0x3 @@ -2520,6 +2633,28 @@ const ( PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PSTOREFS_MAGIC = 0x6165676c + PTP_CLK_MAGIC = '=' + PTP_ENABLE_FEATURE = 0x1 + PTP_EXTTS_EDGES = 0x6 + PTP_EXTTS_EVENT_VALID = 0x1 + PTP_EXTTS_V1_VALID_FLAGS = 0x7 + PTP_EXTTS_VALID_FLAGS = 0x1f + PTP_EXT_OFFSET = 0x10 + PTP_FALLING_EDGE = 0x4 + PTP_MAX_SAMPLES = 0x19 + PTP_PEROUT_DUTY_CYCLE = 0x2 + PTP_PEROUT_ONE_SHOT = 0x1 + PTP_PEROUT_PHASE = 0x4 + PTP_PEROUT_V1_VALID_FLAGS = 0x0 + PTP_PEROUT_VALID_FLAGS = 0x7 + PTP_PIN_GETFUNC = 0xc0603d06 + PTP_PIN_GETFUNC2 = 0xc0603d0f + PTP_RISING_EDGE = 0x2 + PTP_STRICT_FLAGS = 0x8 + PTP_SYS_OFFSET_EXTENDED = 0xc4c03d09 + PTP_SYS_OFFSET_EXTENDED2 = 0xc4c03d12 + PTP_SYS_OFFSET_PRECISE = 0xc0403d08 + PTP_SYS_OFFSET_PRECISE2 = 0xc0403d11 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 @@ -2615,8 +2750,9 @@ const ( RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 - RTAX_FEATURE_MASK = 0xf + RTAX_FEATURE_MASK = 0x1f RTAX_FEATURE_SACK = 0x2 + RTAX_FEATURE_TCP_USEC_TS = 0x10 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb @@ -2832,14 +2968,17 @@ const ( RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 RWF_APPEND = 0x10 + RWF_ATOMIC = 0x40 RWF_DSYNC = 0x2 RWF_HIPRI = 0x1 + RWF_NOAPPEND = 0x20 RWF_NOWAIT = 0x8 - RWF_SUPPORTED = 0x1f + RWF_SUPPORTED = 0x7f RWF_SYNC = 0x4 RWF_WRITE_LIFE_NOT_SET = 0x0 SCHED_BATCH = 0x3 SCHED_DEADLINE = 0x6 + SCHED_EXT = 0x7 SCHED_FIFO = 0x1 SCHED_FLAG_ALL = 0x7f SCHED_FLAG_DL_OVERRUN = 0x4 @@ -2856,12 +2995,43 @@ const ( SCHED_RESET_ON_FORK = 0x40000000 SCHED_RR = 0x2 SCM_CREDENTIALS = 0x2 + SCM_PIDFD = 0x4 SCM_RIGHTS = 0x1 + SCM_SECURITY = 0x3 SCM_TIMESTAMP = 0x1d SC_LOG_FLUSH = 0x100000 + SECCOMP_ADDFD_FLAG_SEND = 0x2 + SECCOMP_ADDFD_FLAG_SETFD = 0x1 + SECCOMP_FILTER_FLAG_LOG = 0x2 + SECCOMP_FILTER_FLAG_NEW_LISTENER = 0x8 + SECCOMP_FILTER_FLAG_SPEC_ALLOW = 0x4 + SECCOMP_FILTER_FLAG_TSYNC = 0x1 + SECCOMP_FILTER_FLAG_TSYNC_ESRCH = 0x10 + SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV = 0x20 + SECCOMP_GET_ACTION_AVAIL = 0x2 + SECCOMP_GET_NOTIF_SIZES = 0x3 + SECCOMP_IOCTL_NOTIF_RECV = 0xc0502100 + SECCOMP_IOCTL_NOTIF_SEND = 0xc0182101 + SECCOMP_IOC_MAGIC = '!' SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 + SECCOMP_RET_ACTION = 0x7fff0000 + SECCOMP_RET_ACTION_FULL = 0xffff0000 + SECCOMP_RET_ALLOW = 0x7fff0000 + SECCOMP_RET_DATA = 0xffff + SECCOMP_RET_ERRNO = 0x50000 + SECCOMP_RET_KILL = 0x0 + SECCOMP_RET_KILL_PROCESS = 0x80000000 + SECCOMP_RET_KILL_THREAD = 0x0 + SECCOMP_RET_LOG = 0x7ffc0000 + SECCOMP_RET_TRACE = 0x7ff00000 + SECCOMP_RET_TRAP = 0x30000 + SECCOMP_RET_USER_NOTIF = 0x7fc00000 + SECCOMP_SET_MODE_FILTER = 0x1 + SECCOMP_SET_MODE_STRICT = 0x0 + SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP = 0x1 + SECCOMP_USER_NOTIF_FLAG_CONTINUE = 0x1 SECRETMEM_MAGIC = 0x5345434d SECURITYFS_MAGIC = 0x73636673 SEEK_CUR = 0x1 @@ -2960,6 +3130,8 @@ const ( SIOCSMIIREG = 0x8949 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a + SK_DIAG_BPF_STORAGE_MAX = 0x3 + SK_DIAG_BPF_STORAGE_REQ_MAX = 0x1 SMACK_MAGIC = 0x43415d53 SMART_AUTOSAVE = 0xd2 SMART_AUTO_OFFLINE = 0xdb @@ -2980,6 +3152,8 @@ const ( SOCKFS_MAGIC = 0x534f434b SOCK_BUF_LOCK_MASK = 0x3 SOCK_DCCP = 0x6 + SOCK_DESTROY = 0x15 + SOCK_DIAG_BY_FAMILY = 0x14 SOCK_IOC_TYPE = 0x89 SOCK_PACKET = 0xa SOCK_RAW = 0x3 @@ -3021,6 +3195,7 @@ const ( SOL_TIPC = 0x10f SOL_TLS = 0x11a SOL_UDP = 0x11 + SOL_VSOCK = 0x11f SOL_X25 = 0x106 SOL_XDP = 0x11b SOMAXCONN = 0x1000 @@ -3072,6 +3247,7 @@ const ( STATX_ATTR_MOUNT_ROOT = 0x2000 STATX_ATTR_NODUMP = 0x40 STATX_ATTR_VERITY = 0x100000 + STATX_ATTR_WRITE_ATOMIC = 0x400000 STATX_BASIC_STATS = 0x7ff STATX_BLOCKS = 0x400 STATX_BTIME = 0x800 @@ -3080,12 +3256,15 @@ const ( STATX_GID = 0x10 STATX_INO = 0x100 STATX_MNT_ID = 0x1000 + STATX_MNT_ID_UNIQUE = 0x4000 STATX_MODE = 0x2 STATX_MTIME = 0x40 STATX_NLINK = 0x4 STATX_SIZE = 0x200 + STATX_SUBVOL = 0x8000 STATX_TYPE = 0x1 STATX_UID = 0x8 + STATX_WRITE_ATOMIC = 0x10000 STATX__RESERVED = 0x80000000 SYNC_FILE_RANGE_WAIT_AFTER = 0x4 SYNC_FILE_RANGE_WAIT_BEFORE = 0x1 @@ -3167,6 +3346,7 @@ const ( TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_EXT = 0x20 + TCP_MD5SIG_FLAG_IFINDEX = 0x2 TCP_MD5SIG_FLAG_PREFIX = 0x1 TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 @@ -3474,12 +3654,17 @@ const ( XDP_RX_RING = 0x2 XDP_SHARED_UMEM = 0x1 XDP_STATISTICS = 0x7 + XDP_TXMD_FLAGS_CHECKSUM = 0x2 + XDP_TXMD_FLAGS_TIMESTAMP = 0x1 + XDP_TX_METADATA = 0x2 XDP_TX_RING = 0x3 XDP_UMEM_COMPLETION_RING = 0x6 XDP_UMEM_FILL_RING = 0x5 XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000 XDP_UMEM_PGOFF_FILL_RING = 0x100000000 XDP_UMEM_REG = 0x4 + XDP_UMEM_TX_METADATA_LEN = 0x4 + XDP_UMEM_TX_SW_CSUM = 0x2 XDP_UMEM_UNALIGNED_CHUNK_FLAG = 0x1 XDP_USE_NEED_WAKEUP = 0x8 XDP_USE_SG = 0x10 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go index 4920821c..c0d45e32 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -78,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x80088a02 + EPIOCSPARAMS = 0x40088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -107,6 +109,7 @@ const ( HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESC = 0x90044802 HIDIOCGRDESCSIZE = 0x80044801 + HIDIOCREVOKE = 0x4004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -118,6 +121,7 @@ const ( IXOFF = 0x1000 IXON = 0x400 MAP_32BIT = 0x40 + MAP_ABOVE4G = 0x80 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 @@ -150,9 +154,14 @@ const ( NFDBITS = 0x20 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x8008b705 NS_GET_NSTYPE = 0xb703 NS_GET_OWNER_UID = 0xb704 NS_GET_PARENT = 0xb702 + NS_GET_PID_FROM_PIDNS = 0x8004b706 + NS_GET_PID_IN_PIDNS = 0x8004b708 + NS_GET_TGID_FROM_PIDNS = 0x8004b707 + NS_GET_TGID_IN_PIDNS = 0x8004b709 NS_GET_USERNS = 0xb701 OLCUC = 0x2 ONLCR = 0x4 @@ -229,6 +238,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCXFERUNIT = 0x744e PR_SET_PTRACER_ANY = 0xffffffff + PTP_CLOCK_GETCAPS = 0x80503d01 + PTP_CLOCK_GETCAPS2 = 0x80503d0a + PTP_ENABLE_PPS = 0x40043d04 + PTP_ENABLE_PPS2 = 0x40043d0d + PTP_EXTTS_REQUEST = 0x40103d02 + PTP_EXTTS_REQUEST2 = 0x40103d0b + PTP_MASK_CLEAR_ALL = 0x3d13 + PTP_MASK_EN_SINGLE = 0x40043d14 + PTP_PEROUT_REQUEST = 0x40383d03 + PTP_PEROUT_REQUEST2 = 0x40383d0c + PTP_PIN_SETFUNC = 0x40603d07 + PTP_PIN_SETFUNC2 = 0x40603d10 + PTP_SYS_OFFSET = 0x43403d05 + PTP_SYS_OFFSET2 = 0x43403d0e PTRACE_GETFPREGS = 0xe PTRACE_GETFPXREGS = 0x12 PTRACE_GET_THREAD_AREA = 0x19 @@ -275,12 +298,17 @@ const ( RTC_WIE_ON = 0x700f RTC_WKALM_RD = 0x80287010 RTC_WKALM_SET = 0x4028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x40082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x40082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 @@ -310,6 +338,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go index a0c1e411..c731d24f 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -78,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x80088a02 + EPIOCSPARAMS = 0x40088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -107,6 +109,7 @@ const ( HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESC = 0x90044802 HIDIOCGRDESCSIZE = 0x80044801 + HIDIOCREVOKE = 0x4004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -118,6 +121,7 @@ const ( IXOFF = 0x1000 IXON = 0x400 MAP_32BIT = 0x40 + MAP_ABOVE4G = 0x80 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 @@ -150,9 +154,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x8008b705 NS_GET_NSTYPE = 0xb703 NS_GET_OWNER_UID = 0xb704 NS_GET_PARENT = 0xb702 + NS_GET_PID_FROM_PIDNS = 0x8004b706 + NS_GET_PID_IN_PIDNS = 0x8004b708 + NS_GET_TGID_FROM_PIDNS = 0x8004b707 + NS_GET_TGID_IN_PIDNS = 0x8004b709 NS_GET_USERNS = 0xb701 OLCUC = 0x2 ONLCR = 0x4 @@ -229,6 +238,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCXFERUNIT = 0x744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x80503d01 + PTP_CLOCK_GETCAPS2 = 0x80503d0a + PTP_ENABLE_PPS = 0x40043d04 + PTP_ENABLE_PPS2 = 0x40043d0d + PTP_EXTTS_REQUEST = 0x40103d02 + PTP_EXTTS_REQUEST2 = 0x40103d0b + PTP_MASK_CLEAR_ALL = 0x3d13 + PTP_MASK_EN_SINGLE = 0x40043d14 + PTP_PEROUT_REQUEST = 0x40383d03 + PTP_PEROUT_REQUEST2 = 0x40383d0c + PTP_PIN_SETFUNC = 0x40603d07 + PTP_PIN_SETFUNC2 = 0x40603d10 + PTP_SYS_OFFSET = 0x43403d05 + PTP_SYS_OFFSET2 = 0x43403d0e PTRACE_ARCH_PRCTL = 0x1e PTRACE_GETFPREGS = 0xe PTRACE_GETFPXREGS = 0x12 @@ -276,12 +299,17 @@ const ( RTC_WIE_ON = 0x700f RTC_WKALM_RD = 0x80287010 RTC_WKALM_SET = 0x4028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x40082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x40082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 @@ -311,6 +339,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go index c6398556..680018a4 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -78,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x80088a02 + EPIOCSPARAMS = 0x40088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -106,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESC = 0x90044802 HIDIOCGRDESCSIZE = 0x80044801 + HIDIOCREVOKE = 0x4004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -148,9 +151,14 @@ const ( NFDBITS = 0x20 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x8008b705 NS_GET_NSTYPE = 0xb703 NS_GET_OWNER_UID = 0xb704 NS_GET_PARENT = 0xb702 + NS_GET_PID_FROM_PIDNS = 0x8004b706 + NS_GET_PID_IN_PIDNS = 0x8004b708 + NS_GET_TGID_FROM_PIDNS = 0x8004b707 + NS_GET_TGID_IN_PIDNS = 0x8004b709 NS_GET_USERNS = 0xb701 OLCUC = 0x2 ONLCR = 0x4 @@ -227,6 +235,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCXFERUNIT = 0x744e PR_SET_PTRACER_ANY = 0xffffffff + PTP_CLOCK_GETCAPS = 0x80503d01 + PTP_CLOCK_GETCAPS2 = 0x80503d0a + PTP_ENABLE_PPS = 0x40043d04 + PTP_ENABLE_PPS2 = 0x40043d0d + PTP_EXTTS_REQUEST = 0x40103d02 + PTP_EXTTS_REQUEST2 = 0x40103d0b + PTP_MASK_CLEAR_ALL = 0x3d13 + PTP_MASK_EN_SINGLE = 0x40043d14 + PTP_PEROUT_REQUEST = 0x40383d03 + PTP_PEROUT_REQUEST2 = 0x40383d0c + PTP_PIN_SETFUNC = 0x40603d07 + PTP_PIN_SETFUNC2 = 0x40603d10 + PTP_SYS_OFFSET = 0x43403d05 + PTP_SYS_OFFSET2 = 0x43403d0e PTRACE_GETCRUNCHREGS = 0x19 PTRACE_GETFDPIC = 0x1f PTRACE_GETFDPIC_EXEC = 0x0 @@ -282,12 +304,17 @@ const ( RTC_WIE_ON = 0x700f RTC_WKALM_RD = 0x80287010 RTC_WKALM_SET = 0x4028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x40082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x40082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 @@ -317,6 +344,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go index 47cc62e2..a63909f3 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -78,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x80088a02 + EPIOCSPARAMS = 0x40088a01 EPOLL_CLOEXEC = 0x80000 ESR_MAGIC = 0x45535201 EXTPROC = 0x10000 @@ -87,6 +89,7 @@ const ( FICLONE = 0x40049409 FICLONERANGE = 0x4020940d FLUSHO = 0x1000 + FPMR_MAGIC = 0x46504d52 FPSIMD_MAGIC = 0x46508001 FS_IOC_ENABLE_VERITY = 0x40806685 FS_IOC_GETFLAGS = 0x80086601 @@ -109,6 +112,7 @@ const ( HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESC = 0x90044802 HIDIOCGRDESCSIZE = 0x80044801 + HIDIOCREVOKE = 0x4004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -151,9 +155,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x8008b705 NS_GET_NSTYPE = 0xb703 NS_GET_OWNER_UID = 0xb704 NS_GET_PARENT = 0xb702 + NS_GET_PID_FROM_PIDNS = 0x8004b706 + NS_GET_PID_IN_PIDNS = 0x8004b708 + NS_GET_TGID_FROM_PIDNS = 0x8004b707 + NS_GET_TGID_IN_PIDNS = 0x8004b709 NS_GET_USERNS = 0xb701 OLCUC = 0x2 ONLCR = 0x4 @@ -197,6 +206,7 @@ const ( PERF_EVENT_IOC_SET_BPF = 0x40042408 PERF_EVENT_IOC_SET_FILTER = 0x40082406 PERF_EVENT_IOC_SET_OUTPUT = 0x2405 + POE_MAGIC = 0x504f4530 PPPIOCATTACH = 0x4004743d PPPIOCATTCHAN = 0x40047438 PPPIOCBRIDGECHAN = 0x40047435 @@ -232,6 +242,20 @@ const ( PROT_BTI = 0x10 PROT_MTE = 0x20 PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x80503d01 + PTP_CLOCK_GETCAPS2 = 0x80503d0a + PTP_ENABLE_PPS = 0x40043d04 + PTP_ENABLE_PPS2 = 0x40043d0d + PTP_EXTTS_REQUEST = 0x40103d02 + PTP_EXTTS_REQUEST2 = 0x40103d0b + PTP_MASK_CLEAR_ALL = 0x3d13 + PTP_MASK_EN_SINGLE = 0x40043d14 + PTP_PEROUT_REQUEST = 0x40383d03 + PTP_PEROUT_REQUEST2 = 0x40383d0c + PTP_PIN_SETFUNC = 0x40603d07 + PTP_PIN_SETFUNC2 = 0x40603d10 + PTP_SYS_OFFSET = 0x43403d05 + PTP_SYS_OFFSET2 = 0x43403d0e PTRACE_PEEKMTETAGS = 0x21 PTRACE_POKEMTETAGS = 0x22 PTRACE_SYSEMU = 0x1f @@ -272,12 +296,17 @@ const ( RTC_WIE_ON = 0x700f RTC_WKALM_RD = 0x80287010 RTC_WKALM_SET = 0x4028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x40082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x40082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 @@ -307,6 +336,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go index 27ac4a09..9b0a2573 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go @@ -78,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x80088a02 + EPIOCSPARAMS = 0x40088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -107,6 +109,7 @@ const ( HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESC = 0x90044802 HIDIOCGRDESCSIZE = 0x80044801 + HIDIOCREVOKE = 0x4004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -152,9 +155,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x8008b705 NS_GET_NSTYPE = 0xb703 NS_GET_OWNER_UID = 0xb704 NS_GET_PARENT = 0xb702 + NS_GET_PID_FROM_PIDNS = 0x8004b706 + NS_GET_PID_IN_PIDNS = 0x8004b708 + NS_GET_TGID_FROM_PIDNS = 0x8004b707 + NS_GET_TGID_IN_PIDNS = 0x8004b709 NS_GET_USERNS = 0xb701 OLCUC = 0x2 ONLCR = 0x4 @@ -231,6 +239,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCXFERUNIT = 0x744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x80503d01 + PTP_CLOCK_GETCAPS2 = 0x80503d0a + PTP_ENABLE_PPS = 0x40043d04 + PTP_ENABLE_PPS2 = 0x40043d0d + PTP_EXTTS_REQUEST = 0x40103d02 + PTP_EXTTS_REQUEST2 = 0x40103d0b + PTP_MASK_CLEAR_ALL = 0x3d13 + PTP_MASK_EN_SINGLE = 0x40043d14 + PTP_PEROUT_REQUEST = 0x40383d03 + PTP_PEROUT_REQUEST2 = 0x40383d0c + PTP_PIN_SETFUNC = 0x40603d07 + PTP_PIN_SETFUNC2 = 0x40603d10 + PTP_SYS_OFFSET = 0x43403d05 + PTP_SYS_OFFSET2 = 0x43403d0e PTRACE_SYSEMU = 0x1f PTRACE_SYSEMU_SINGLESTEP = 0x20 RLIMIT_AS = 0x9 @@ -269,12 +291,17 @@ const ( RTC_WIE_ON = 0x700f RTC_WKALM_RD = 0x80287010 RTC_WKALM_SET = 0x4028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x40082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x40082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 @@ -304,6 +331,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go index 54694642..958e6e06 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -78,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -106,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x100 @@ -148,9 +151,14 @@ const ( NFDBITS = 0x20 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x2 ONLCR = 0x4 @@ -227,6 +235,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCXFERUNIT = 0x2000744e PR_SET_PTRACER_ANY = 0xffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETFPREGS = 0xe PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA_3264 = 0xc4 @@ -275,12 +297,17 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x80 SIOCATMARK = 0x40047307 @@ -310,6 +337,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go index 3adb81d7..50c7f25b 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go @@ -78,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -106,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x100 @@ -148,9 +151,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x2 ONLCR = 0x4 @@ -227,6 +235,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCXFERUNIT = 0x2000744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETFPREGS = 0xe PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA_3264 = 0xc4 @@ -275,12 +297,17 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x80 SIOCATMARK = 0x40047307 @@ -310,6 +337,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go index 2dfe98f0..ced21d66 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go @@ -78,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -106,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x100 @@ -148,9 +151,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x2 ONLCR = 0x4 @@ -227,6 +235,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCXFERUNIT = 0x2000744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETFPREGS = 0xe PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA_3264 = 0xc4 @@ -275,12 +297,17 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x80 SIOCATMARK = 0x40047307 @@ -310,6 +337,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go index f5398f84..226c0441 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -78,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -106,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x100 @@ -148,9 +151,14 @@ const ( NFDBITS = 0x20 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x2 ONLCR = 0x4 @@ -227,6 +235,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCXFERUNIT = 0x2000744e PR_SET_PTRACER_ANY = 0xffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETFPREGS = 0xe PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA_3264 = 0xc4 @@ -275,12 +297,17 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x80 SIOCATMARK = 0x40047307 @@ -310,6 +337,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go index c54f152d..3122737c 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go @@ -78,6 +78,8 @@ const ( ECHOPRT = 0x20 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000000 FF1 = 0x4000 @@ -106,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x4000 ICANON = 0x100 IEXTEN = 0x400 @@ -150,9 +153,14 @@ const ( NL3 = 0x300 NLDLY = 0x300 NOFLSH = 0x80000000 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x4 ONLCR = 0x2 @@ -230,6 +238,20 @@ const ( PPPIOCXFERUNIT = 0x2000744e PROT_SAO = 0x10 PR_SET_PTRACER_ANY = 0xffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETEVRREGS = 0x14 PTRACE_GETFPREGS = 0xe PTRACE_GETREGS64 = 0x16 @@ -330,12 +352,17 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 @@ -365,6 +392,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go index 76057dc7..eb5d3467 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -78,6 +78,8 @@ const ( ECHOPRT = 0x20 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000000 FF1 = 0x4000 @@ -106,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x4000 ICANON = 0x100 IEXTEN = 0x400 @@ -150,9 +153,14 @@ const ( NL3 = 0x300 NLDLY = 0x300 NOFLSH = 0x80000000 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x4 ONLCR = 0x2 @@ -230,6 +238,20 @@ const ( PPPIOCXFERUNIT = 0x2000744e PROT_SAO = 0x10 PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETEVRREGS = 0x14 PTRACE_GETFPREGS = 0xe PTRACE_GETREGS64 = 0x16 @@ -334,12 +356,17 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 @@ -369,6 +396,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go index e0c3725e..e921ebc6 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -78,6 +78,8 @@ const ( ECHOPRT = 0x20 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000000 FF1 = 0x4000 @@ -106,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x4000 ICANON = 0x100 IEXTEN = 0x400 @@ -150,9 +153,14 @@ const ( NL3 = 0x300 NLDLY = 0x300 NOFLSH = 0x80000000 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x4 ONLCR = 0x2 @@ -230,6 +238,20 @@ const ( PPPIOCXFERUNIT = 0x2000744e PROT_SAO = 0x10 PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETEVRREGS = 0x14 PTRACE_GETFPREGS = 0xe PTRACE_GETREGS64 = 0x16 @@ -334,12 +356,17 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 @@ -369,6 +396,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go index 18f2813e..38ba81c5 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go @@ -78,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x80088a02 + EPIOCSPARAMS = 0x40088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -106,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESC = 0x90044802 HIDIOCGRDESCSIZE = 0x80044801 + HIDIOCREVOKE = 0x4004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -148,9 +151,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x8008b705 NS_GET_NSTYPE = 0xb703 NS_GET_OWNER_UID = 0xb704 NS_GET_PARENT = 0xb702 + NS_GET_PID_FROM_PIDNS = 0x8004b706 + NS_GET_PID_IN_PIDNS = 0x8004b708 + NS_GET_TGID_FROM_PIDNS = 0x8004b707 + NS_GET_TGID_IN_PIDNS = 0x8004b709 NS_GET_USERNS = 0xb701 OLCUC = 0x2 ONLCR = 0x4 @@ -227,6 +235,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCXFERUNIT = 0x744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x80503d01 + PTP_CLOCK_GETCAPS2 = 0x80503d0a + PTP_ENABLE_PPS = 0x40043d04 + PTP_ENABLE_PPS2 = 0x40043d0d + PTP_EXTTS_REQUEST = 0x40103d02 + PTP_EXTTS_REQUEST2 = 0x40103d0b + PTP_MASK_CLEAR_ALL = 0x3d13 + PTP_MASK_EN_SINGLE = 0x40043d14 + PTP_PEROUT_REQUEST = 0x40383d03 + PTP_PEROUT_REQUEST2 = 0x40383d0c + PTP_PIN_SETFUNC = 0x40603d07 + PTP_PIN_SETFUNC2 = 0x40603d10 + PTP_SYS_OFFSET = 0x43403d05 + PTP_SYS_OFFSET2 = 0x43403d0e PTRACE_GETFDPIC = 0x21 PTRACE_GETFDPIC_EXEC = 0x0 PTRACE_GETFDPIC_INTERP = 0x1 @@ -266,12 +288,17 @@ const ( RTC_WIE_ON = 0x700f RTC_WKALM_RD = 0x80287010 RTC_WKALM_SET = 0x4028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x40082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x40082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 @@ -301,6 +328,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go index 11619d4e..71f04009 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -78,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x80088a02 + EPIOCSPARAMS = 0x40088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -106,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESC = 0x90044802 HIDIOCGRDESCSIZE = 0x80044801 + HIDIOCREVOKE = 0x4004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -148,9 +151,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x8008b705 NS_GET_NSTYPE = 0xb703 NS_GET_OWNER_UID = 0xb704 NS_GET_PARENT = 0xb702 + NS_GET_PID_FROM_PIDNS = 0x8004b706 + NS_GET_PID_IN_PIDNS = 0x8004b708 + NS_GET_TGID_FROM_PIDNS = 0x8004b707 + NS_GET_TGID_IN_PIDNS = 0x8004b709 NS_GET_USERNS = 0xb701 OLCUC = 0x2 ONLCR = 0x4 @@ -227,6 +235,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCXFERUNIT = 0x744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x80503d01 + PTP_CLOCK_GETCAPS2 = 0x80503d0a + PTP_ENABLE_PPS = 0x40043d04 + PTP_ENABLE_PPS2 = 0x40043d0d + PTP_EXTTS_REQUEST = 0x40103d02 + PTP_EXTTS_REQUEST2 = 0x40103d0b + PTP_MASK_CLEAR_ALL = 0x3d13 + PTP_MASK_EN_SINGLE = 0x40043d14 + PTP_PEROUT_REQUEST = 0x40383d03 + PTP_PEROUT_REQUEST2 = 0x40383d0c + PTP_PIN_SETFUNC = 0x40603d07 + PTP_PIN_SETFUNC2 = 0x40603d10 + PTP_SYS_OFFSET = 0x43403d05 + PTP_SYS_OFFSET2 = 0x43403d0e PTRACE_DISABLE_TE = 0x5010 PTRACE_ENABLE_TE = 0x5009 PTRACE_GET_LAST_BREAK = 0x5006 @@ -338,12 +360,17 @@ const ( RTC_WIE_ON = 0x700f RTC_WKALM_RD = 0x80287010 RTC_WKALM_SET = 0x4028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x40082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x40082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 @@ -373,6 +400,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go index 396d994d..c44a3133 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go @@ -82,6 +82,8 @@ const ( EFD_CLOEXEC = 0x400000 EFD_NONBLOCK = 0x4000 EMT_TAGOVF = 0x1 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x400000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -110,6 +112,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -153,9 +156,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x2 ONLCR = 0x4 @@ -232,6 +240,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCXFERUNIT = 0x2000744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETFPAREGS = 0x14 PTRACE_GETFPREGS = 0xe PTRACE_GETFPREGS64 = 0x19 @@ -329,12 +351,17 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x58 + SCM_DEVMEM_LINEAR = 0x57 SCM_TIMESTAMPING = 0x23 SCM_TIMESTAMPING_OPT_STATS = 0x38 SCM_TIMESTAMPING_PKTINFO = 0x3c SCM_TIMESTAMPNS = 0x21 SCM_TXTIME = 0x3f SCM_WIFI_STATUS = 0x25 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x400000 SFD_NONBLOCK = 0x4000 SF_FP = 0x38 @@ -412,6 +439,9 @@ const ( SO_CNX_ADVICE = 0x37 SO_COOKIE = 0x3b SO_DETACH_REUSEPORT_BPF = 0x47 + SO_DEVMEM_DMABUF = 0x58 + SO_DEVMEM_DONTNEED = 0x59 + SO_DEVMEM_LINEAR = 0x57 SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 diff --git a/vendor/golang.org/x/sys/unix/zerrors_zos_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_zos_s390x.go index 4dfd2e05..1ec2b140 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_zos_s390x.go @@ -10,41 +10,99 @@ package unix const ( - BRKINT = 0x0001 - CLOCK_MONOTONIC = 0x1 - CLOCK_PROCESS_CPUTIME_ID = 0x2 - CLOCK_REALTIME = 0x0 - CLOCK_THREAD_CPUTIME_ID = 0x3 - CS8 = 0x0030 - CSIZE = 0x0030 - ECHO = 0x00000008 - ECHONL = 0x00000001 - FD_CLOEXEC = 0x01 - FD_CLOFORK = 0x02 - FNDELAY = 0x04 - F_CLOSFD = 9 - F_CONTROL_CVT = 13 - F_DUPFD = 0 - F_DUPFD2 = 8 - F_GETFD = 1 - F_GETFL = 259 - F_GETLK = 5 - F_GETOWN = 10 - F_OK = 0x0 - F_RDLCK = 1 - F_SETFD = 2 - F_SETFL = 4 - F_SETLK = 6 - F_SETLKW = 7 - F_SETOWN = 11 - F_SETTAG = 12 - F_UNLCK = 3 - F_WRLCK = 2 - FSTYPE_ZFS = 0xe9 //"Z" - FSTYPE_HFS = 0xc8 //"H" - FSTYPE_NFS = 0xd5 //"N" - FSTYPE_TFS = 0xe3 //"T" - FSTYPE_AUTOMOUNT = 0xc1 //"A" + BRKINT = 0x0001 + CLOCAL = 0x1 + CLOCK_MONOTONIC = 0x1 + CLOCK_PROCESS_CPUTIME_ID = 0x2 + CLOCK_REALTIME = 0x0 + CLOCK_THREAD_CPUTIME_ID = 0x3 + CLONE_NEWIPC = 0x08000000 + CLONE_NEWNET = 0x40000000 + CLONE_NEWNS = 0x00020000 + CLONE_NEWPID = 0x20000000 + CLONE_NEWUTS = 0x04000000 + CLONE_PARENT = 0x00008000 + CS8 = 0x0030 + CSIZE = 0x0030 + ECHO = 0x00000008 + ECHONL = 0x00000001 + EFD_SEMAPHORE = 0x00002000 + EFD_CLOEXEC = 0x00001000 + EFD_NONBLOCK = 0x00000004 + EPOLL_CLOEXEC = 0x00001000 + EPOLL_CTL_ADD = 0 + EPOLL_CTL_MOD = 1 + EPOLL_CTL_DEL = 2 + EPOLLRDNORM = 0x0001 + EPOLLRDBAND = 0x0002 + EPOLLIN = 0x0003 + EPOLLOUT = 0x0004 + EPOLLWRBAND = 0x0008 + EPOLLPRI = 0x0010 + EPOLLERR = 0x0020 + EPOLLHUP = 0x0040 + EPOLLEXCLUSIVE = 0x20000000 + EPOLLONESHOT = 0x40000000 + FD_CLOEXEC = 0x01 + FD_CLOFORK = 0x02 + FD_SETSIZE = 0x800 + FNDELAY = 0x04 + F_CLOSFD = 9 + F_CONTROL_CVT = 13 + F_DUPFD = 0 + F_DUPFD2 = 8 + F_GETFD = 1 + F_GETFL = 259 + F_GETLK = 5 + F_GETOWN = 10 + F_OK = 0x0 + F_RDLCK = 1 + F_SETFD = 2 + F_SETFL = 4 + F_SETLK = 6 + F_SETLKW = 7 + F_SETOWN = 11 + F_SETTAG = 12 + F_UNLCK = 3 + F_WRLCK = 2 + FSTYPE_ZFS = 0xe9 //"Z" + FSTYPE_HFS = 0xc8 //"H" + FSTYPE_NFS = 0xd5 //"N" + FSTYPE_TFS = 0xe3 //"T" + FSTYPE_AUTOMOUNT = 0xc1 //"A" + GRND_NONBLOCK = 1 + GRND_RANDOM = 2 + HUPCL = 0x0100 // Hang up on last close + IN_CLOEXEC = 0x00001000 + IN_NONBLOCK = 0x00000004 + IN_ACCESS = 0x00000001 + IN_MODIFY = 0x00000002 + IN_ATTRIB = 0x00000004 + IN_CLOSE_WRITE = 0x00000008 + IN_CLOSE_NOWRITE = 0x00000010 + IN_OPEN = 0x00000020 + IN_MOVED_FROM = 0x00000040 + IN_MOVED_TO = 0x00000080 + IN_CREATE = 0x00000100 + IN_DELETE = 0x00000200 + IN_DELETE_SELF = 0x00000400 + IN_MOVE_SELF = 0x00000800 + IN_UNMOUNT = 0x00002000 + IN_Q_OVERFLOW = 0x00004000 + IN_IGNORED = 0x00008000 + IN_CLOSE = (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) + IN_MOVE = (IN_MOVED_FROM | IN_MOVED_TO) + IN_ALL_EVENTS = (IN_ACCESS | IN_MODIFY | IN_ATTRIB | + IN_CLOSE | IN_OPEN | IN_MOVE | + IN_CREATE | IN_DELETE | IN_DELETE_SELF | + IN_MOVE_SELF) + IN_ONLYDIR = 0x01000000 + IN_DONT_FOLLOW = 0x02000000 + IN_EXCL_UNLINK = 0x04000000 + IN_MASK_CREATE = 0x10000000 + IN_MASK_ADD = 0x20000000 + IN_ISDIR = 0x40000000 + IN_ONESHOT = 0x80000000 IP6F_MORE_FRAG = 0x0001 IP6F_OFF_MASK = 0xfff8 IP6F_RESERVED_MASK = 0x0006 @@ -152,10 +210,18 @@ const ( IP_PKTINFO = 101 IP_RECVPKTINFO = 102 IP_TOS = 2 - IP_TTL = 3 + IP_TTL = 14 IP_UNBLOCK_SOURCE = 11 + ICMP6_FILTER = 1 + MCAST_INCLUDE = 0 + MCAST_EXCLUDE = 1 + MCAST_JOIN_GROUP = 40 + MCAST_LEAVE_GROUP = 41 + MCAST_JOIN_SOURCE_GROUP = 42 + MCAST_LEAVE_SOURCE_GROUP = 43 + MCAST_BLOCK_SOURCE = 44 + MCAST_UNBLOCK_SOURCE = 46 ICANON = 0x0010 - ICMP6_FILTER = 0x26 ICRNL = 0x0002 IEXTEN = 0x0020 IGNBRK = 0x0004 @@ -165,10 +231,10 @@ const ( ISTRIP = 0x0080 IXON = 0x0200 IXOFF = 0x0100 - LOCK_SH = 0x1 // Not exist on zOS - LOCK_EX = 0x2 // Not exist on zOS - LOCK_NB = 0x4 // Not exist on zOS - LOCK_UN = 0x8 // Not exist on zOS + LOCK_SH = 0x1 + LOCK_EX = 0x2 + LOCK_NB = 0x4 + LOCK_UN = 0x8 POLLIN = 0x0003 POLLOUT = 0x0004 POLLPRI = 0x0010 @@ -182,15 +248,29 @@ const ( MAP_PRIVATE = 0x1 // changes are private MAP_SHARED = 0x2 // changes are shared MAP_FIXED = 0x4 // place exactly - MCAST_JOIN_GROUP = 40 - MCAST_LEAVE_GROUP = 41 - MCAST_JOIN_SOURCE_GROUP = 42 - MCAST_LEAVE_SOURCE_GROUP = 43 - MCAST_BLOCK_SOURCE = 44 - MCAST_UNBLOCK_SOURCE = 45 + __MAP_MEGA = 0x8 + __MAP_64 = 0x10 + MAP_ANON = 0x20 + MAP_ANONYMOUS = 0x20 MS_SYNC = 0x1 // msync - synchronous writes MS_ASYNC = 0x2 // asynchronous writes MS_INVALIDATE = 0x4 // invalidate mappings + MS_BIND = 0x00001000 + MS_MOVE = 0x00002000 + MS_NOSUID = 0x00000002 + MS_PRIVATE = 0x00040000 + MS_REC = 0x00004000 + MS_REMOUNT = 0x00008000 + MS_RDONLY = 0x00000001 + MS_UNBINDABLE = 0x00020000 + MNT_DETACH = 0x00000004 + ZOSDSFS_SUPER_MAGIC = 0x44534653 // zOS DSFS + NFS_SUPER_MAGIC = 0x6969 // NFS + NSFS_MAGIC = 0x6e736673 // PROCNS + PROC_SUPER_MAGIC = 0x9fa0 // proc FS + ZOSTFS_SUPER_MAGIC = 0x544653 // zOS TFS + ZOSUFS_SUPER_MAGIC = 0x554653 // zOS UFS + ZOSZFS_SUPER_MAGIC = 0x5A4653 // zOS ZFS MTM_RDONLY = 0x80000000 MTM_RDWR = 0x40000000 MTM_UMOUNT = 0x10000000 @@ -205,13 +285,20 @@ const ( MTM_REMOUNT = 0x00000100 MTM_NOSECURITY = 0x00000080 NFDBITS = 0x20 + ONLRET = 0x0020 // NL performs CR function O_ACCMODE = 0x03 O_APPEND = 0x08 O_ASYNCSIG = 0x0200 O_CREAT = 0x80 + O_DIRECT = 0x00002000 + O_NOFOLLOW = 0x00004000 + O_DIRECTORY = 0x00008000 + O_PATH = 0x00080000 + O_CLOEXEC = 0x00001000 O_EXCL = 0x40 O_GETFL = 0x0F O_LARGEFILE = 0x0400 + O_NDELAY = 0x4 O_NONBLOCK = 0x04 O_RDONLY = 0x02 O_RDWR = 0x03 @@ -248,6 +335,7 @@ const ( AF_IUCV = 17 AF_LAT = 14 AF_LINK = 18 + AF_LOCAL = AF_UNIX // AF_LOCAL is an alias for AF_UNIX AF_MAX = 30 AF_NBS = 7 AF_NDD = 23 @@ -285,15 +373,33 @@ const ( RLIMIT_AS = 5 RLIMIT_NOFILE = 6 RLIMIT_MEMLIMIT = 7 + RLIMIT_MEMLOCK = 0x8 RLIM_INFINITY = 2147483647 + SCHED_FIFO = 0x2 + SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x01 SF_CLOSE = 0x00000002 SF_REUSE = 0x00000001 + SHM_RND = 0x2 + SHM_RDONLY = 0x1 + SHMLBA = 0x1000 + IPC_STAT = 0x3 + IPC_SET = 0x2 + IPC_RMID = 0x1 + IPC_PRIVATE = 0x0 + IPC_CREAT = 0x1000000 + __IPC_MEGA = 0x4000000 + __IPC_SHAREAS = 0x20000000 + __IPC_BELOWBAR = 0x10000000 + IPC_EXCL = 0x2000000 + __IPC_GIGA = 0x8000000 SHUT_RD = 0 SHUT_RDWR = 2 SHUT_WR = 1 + SOCK_CLOEXEC = 0x00001000 SOCK_CONN_DGRAM = 6 SOCK_DGRAM = 2 + SOCK_NONBLOCK = 0x800 SOCK_RAW = 3 SOCK_RDM = 4 SOCK_SEQPACKET = 5 @@ -378,8 +484,6 @@ const ( S_IFMST = 0x00FF0000 TCP_KEEPALIVE = 0x8 TCP_NODELAY = 0x1 - TCP_INFO = 0xb - TCP_USER_TIMEOUT = 0x1 TIOCGWINSZ = 0x4008a368 TIOCSWINSZ = 0x8008a367 TIOCSBRK = 0x2000a77b @@ -427,7 +531,10 @@ const ( VSUSP = 9 VTIME = 10 WCONTINUED = 0x4 + WEXITED = 0x8 WNOHANG = 0x1 + WNOWAIT = 0x20 + WSTOPPED = 0x10 WUNTRACED = 0x2 _BPX_SWAP = 1 _BPX_NONSWAP = 2 @@ -452,8 +559,30 @@ const ( MADV_FREE = 15 // for Linux compatibility -- no zos semantics MADV_WIPEONFORK = 16 // for Linux compatibility -- no zos semantics MADV_KEEPONFORK = 17 // for Linux compatibility -- no zos semantics - AT_SYMLINK_NOFOLLOW = 1 // for Unix compatibility -- no zos semantics - AT_FDCWD = 2 // for Unix compatibility -- no zos semantics + AT_SYMLINK_FOLLOW = 0x400 + AT_SYMLINK_NOFOLLOW = 0x100 + XATTR_CREATE = 0x1 + XATTR_REPLACE = 0x2 + P_PID = 0 + P_PGID = 1 + P_ALL = 2 + PR_SET_NAME = 15 + PR_GET_NAME = 16 + PR_SET_NO_NEW_PRIVS = 38 + PR_GET_NO_NEW_PRIVS = 39 + PR_SET_DUMPABLE = 4 + PR_GET_DUMPABLE = 3 + PR_SET_PDEATHSIG = 1 + PR_GET_PDEATHSIG = 2 + PR_SET_CHILD_SUBREAPER = 36 + PR_GET_CHILD_SUBREAPER = 37 + AT_FDCWD = -100 + AT_EACCESS = 0x200 + AT_EMPTY_PATH = 0x1000 + AT_REMOVEDIR = 0x200 + RENAME_NOREPLACE = 1 << 0 + ST_RDONLY = 1 + ST_NOSUID = 2 ) const ( @@ -476,6 +605,7 @@ const ( EMLINK = Errno(125) ENAMETOOLONG = Errno(126) ENFILE = Errno(127) + ENOATTR = Errno(265) ENODEV = Errno(128) ENOENT = Errno(129) ENOEXEC = Errno(130) @@ -700,7 +830,7 @@ var errorList = [...]struct { {145, "EDC5145I", "The parameter list is too long, or the message to receive was too large for the buffer."}, {146, "EDC5146I", "Too many levels of symbolic links."}, {147, "EDC5147I", "Illegal byte sequence."}, - {148, "", ""}, + {148, "EDC5148I", "The named attribute or data not available."}, {149, "EDC5149I", "Value Overflow Error."}, {150, "EDC5150I", "UNIX System Services is not active."}, {151, "EDC5151I", "Dynamic allocation error."}, @@ -743,6 +873,7 @@ var errorList = [...]struct { {259, "EDC5259I", "A CUN_RS_NO_CONVERSION error was issued by Unicode Services."}, {260, "EDC5260I", "A CUN_RS_TABLE_NOT_ALIGNED error was issued by Unicode Services."}, {262, "EDC5262I", "An iconv() function encountered an unexpected error while using Unicode Services."}, + {265, "EDC5265I", "The named attribute not available."}, {1000, "EDC8000I", "A bad socket-call constant was found in the IUCV header."}, {1001, "EDC8001I", "An error was found in the IUCV header."}, {1002, "EDC8002I", "A socket descriptor is out of range."}, diff --git a/vendor/golang.org/x/sys/unix/zsymaddr_zos_s390x.s b/vendor/golang.org/x/sys/unix/zsymaddr_zos_s390x.s new file mode 100644 index 00000000..b77ff5db --- /dev/null +++ b/vendor/golang.org/x/sys/unix/zsymaddr_zos_s390x.s @@ -0,0 +1,364 @@ +// go run mksyscall_zos_s390x.go -o_sysnum zsysnum_zos_s390x.go -o_syscall zsyscall_zos_s390x.go -i_syscall syscall_zos_s390x.go -o_asm zsymaddr_zos_s390x.s +// Code generated by the command above; see README.md. DO NOT EDIT. + +//go:build zos && s390x +#include "textflag.h" + +// provide the address of function variable to be fixed up. + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FlistxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Flistxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FremovexattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Fremovexattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FgetxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Fgetxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FsetxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Fsetxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_accept4Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·accept4(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_RemovexattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Removexattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_Dup3Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Dup3(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_DirfdAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Dirfd(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_EpollCreateAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·EpollCreate(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_EpollCreate1Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·EpollCreate1(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_EpollCtlAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·EpollCtl(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_EpollPwaitAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·EpollPwait(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_EpollWaitAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·EpollWait(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_EventfdAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Eventfd(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FaccessatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Faccessat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FchmodatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Fchmodat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FchownatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Fchownat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FdatasyncAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Fdatasync(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_fstatatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·fstatat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_LgetxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Lgetxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_LsetxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Lsetxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FstatfsAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Fstatfs(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FutimesAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Futimes(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FutimesatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Futimesat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_GetrandomAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Getrandom(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_InotifyInitAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·InotifyInit(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_InotifyInit1Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·InotifyInit1(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_InotifyAddWatchAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·InotifyAddWatch(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_InotifyRmWatchAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·InotifyRmWatch(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_ListxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Listxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_LlistxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Llistxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_LremovexattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Lremovexattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_LutimesAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Lutimes(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_StatfsAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Statfs(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_SyncfsAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Syncfs(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_UnshareAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Unshare(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_LinkatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Linkat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_MkdiratAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Mkdirat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_MknodatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Mknodat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_PivotRootAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·PivotRoot(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_PrctlAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Prctl(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_PrlimitAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Prlimit(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_RenameatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Renameat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_Renameat2Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Renameat2(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_SethostnameAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Sethostname(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_SetnsAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Setns(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_SymlinkatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Symlinkat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_UnlinkatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Unlinkat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_openatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·openat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_openat2Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·openat2(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_utimensatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·utimensat(SB), R8 + MOVD R8, ret+0(FP) + RET diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go index ccb02f24..24b346e1 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go @@ -740,6 +740,54 @@ func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func renamexNp(from string, to string, flag uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_renamex_np_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flag)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_renamex_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_renamex_np renamex_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func renameatxNp(fromfd int, from string, tofd int, to string, flag uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_renameatx_np_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), uintptr(flag), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_renameatx_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_renameatx_np renameatx_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { @@ -760,6 +808,59 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func pthread_chdir_np(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_pthread_chdir_np_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pthread_chdir_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pthread_chdir_np pthread_chdir_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pthread_fchdir_np(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_pthread_fchdir_np_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pthread_fchdir_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pthread_fchdir_np pthread_fchdir_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func connectx(fd int, endpoints *SaEndpoints, associd SaeAssocID, flags uint32, iov []Iovec, n *uintptr, connid *SaeConnID) (err error) { + var _p0 unsafe.Pointer + if len(iov) > 0 { + _p0 = unsafe.Pointer(&iov[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall9(libc_connectx_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(endpoints)), uintptr(associd), uintptr(flags), uintptr(_p0), uintptr(len(iov)), uintptr(unsafe.Pointer(n)), uintptr(unsafe.Pointer(connid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_connectx_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_connectx connectx "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error) { _, _, e1 := syscall_syscall6(libc_sendfile_trampoline_addr, uintptr(infd), uintptr(outfd), uintptr(offset), uintptr(unsafe.Pointer(len)), uintptr(hdtr), uintptr(flags)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s index 8b8bb284..ebd21310 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s @@ -223,11 +223,36 @@ TEXT libc_ioctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_ioctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_ioctl_trampoline_addr(SB)/8, $libc_ioctl_trampoline<>(SB) +TEXT libc_renamex_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_renamex_np(SB) +GLOBL ·libc_renamex_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_renamex_np_trampoline_addr(SB)/8, $libc_renamex_np_trampoline<>(SB) + +TEXT libc_renameatx_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_renameatx_np(SB) +GLOBL ·libc_renameatx_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_renameatx_np_trampoline_addr(SB)/8, $libc_renameatx_np_trampoline<>(SB) + TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sysctl(SB) GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) +TEXT libc_pthread_chdir_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pthread_chdir_np(SB) +GLOBL ·libc_pthread_chdir_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pthread_chdir_np_trampoline_addr(SB)/8, $libc_pthread_chdir_np_trampoline<>(SB) + +TEXT libc_pthread_fchdir_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pthread_fchdir_np(SB) +GLOBL ·libc_pthread_fchdir_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pthread_fchdir_np_trampoline_addr(SB)/8, $libc_pthread_fchdir_np_trampoline<>(SB) + +TEXT libc_connectx_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_connectx(SB) +GLOBL ·libc_connectx_trampoline_addr(SB), RODATA, $8 +DATA ·libc_connectx_trampoline_addr(SB)/8, $libc_connectx_trampoline<>(SB) + TEXT libc_sendfile_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sendfile(SB) GLOBL ·libc_sendfile_trampoline_addr(SB), RODATA, $8 diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go index 1b40b997..824b9c2d 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go @@ -740,6 +740,54 @@ func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func renamexNp(from string, to string, flag uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_renamex_np_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flag)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_renamex_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_renamex_np renamex_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func renameatxNp(fromfd int, from string, tofd int, to string, flag uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_renameatx_np_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), uintptr(flag), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_renameatx_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_renameatx_np renameatx_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { @@ -760,6 +808,59 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func pthread_chdir_np(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_pthread_chdir_np_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pthread_chdir_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pthread_chdir_np pthread_chdir_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pthread_fchdir_np(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_pthread_fchdir_np_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pthread_fchdir_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pthread_fchdir_np pthread_fchdir_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func connectx(fd int, endpoints *SaEndpoints, associd SaeAssocID, flags uint32, iov []Iovec, n *uintptr, connid *SaeConnID) (err error) { + var _p0 unsafe.Pointer + if len(iov) > 0 { + _p0 = unsafe.Pointer(&iov[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := syscall_syscall9(libc_connectx_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(endpoints)), uintptr(associd), uintptr(flags), uintptr(_p0), uintptr(len(iov)), uintptr(unsafe.Pointer(n)), uintptr(unsafe.Pointer(connid)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_connectx_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_connectx connectx "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error) { _, _, e1 := syscall_syscall6(libc_sendfile_trampoline_addr, uintptr(infd), uintptr(outfd), uintptr(offset), uintptr(unsafe.Pointer(len)), uintptr(hdtr), uintptr(flags)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s index 08362c1a..4f178a22 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s @@ -223,11 +223,36 @@ TEXT libc_ioctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_ioctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_ioctl_trampoline_addr(SB)/8, $libc_ioctl_trampoline<>(SB) +TEXT libc_renamex_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_renamex_np(SB) +GLOBL ·libc_renamex_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_renamex_np_trampoline_addr(SB)/8, $libc_renamex_np_trampoline<>(SB) + +TEXT libc_renameatx_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_renameatx_np(SB) +GLOBL ·libc_renameatx_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_renameatx_np_trampoline_addr(SB)/8, $libc_renameatx_np_trampoline<>(SB) + TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sysctl(SB) GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) +TEXT libc_pthread_chdir_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pthread_chdir_np(SB) +GLOBL ·libc_pthread_chdir_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pthread_chdir_np_trampoline_addr(SB)/8, $libc_pthread_chdir_np_trampoline<>(SB) + +TEXT libc_pthread_fchdir_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pthread_fchdir_np(SB) +GLOBL ·libc_pthread_fchdir_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pthread_fchdir_np_trampoline_addr(SB)/8, $libc_pthread_fchdir_np_trampoline<>(SB) + +TEXT libc_connectx_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_connectx(SB) +GLOBL ·libc_connectx_trampoline_addr(SB), RODATA, $8 +DATA ·libc_connectx_trampoline_addr(SB)/8, $libc_connectx_trampoline<>(SB) + TEXT libc_sendfile_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sendfile(SB) GLOBL ·libc_sendfile_trampoline_addr(SB), RODATA, $8 diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux.go b/vendor/golang.org/x/sys/unix/zsyscall_linux.go index faca7a55..5cc1e8eb 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux.go @@ -37,6 +37,21 @@ func fchmodat(dirfd int, path string, mode uint32) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fchmodat2(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT2, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -577,6 +592,16 @@ func ClockGettime(clockid int32, time *Timespec) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func ClockSettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_SETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error) { _, _, e1 := Syscall6(SYS_CLOCK_NANOSLEEP, uintptr(clockid), uintptr(flags), uintptr(unsafe.Pointer(request)), uintptr(unsafe.Pointer(remain)), 0, 0) if e1 != 0 { @@ -891,6 +916,16 @@ func Fspick(dirfd int, pathName string, flags int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fsconfig(fd int, cmd uint, key *byte, value *byte, aux int) (err error) { + _, _, e1 := Syscall6(SYS_FSCONFIG, uintptr(fd), uintptr(cmd), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(value)), uintptr(aux), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { @@ -946,23 +981,6 @@ func Getpriority(which int, who int) (prio int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getrandom(buf []byte, flags int) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { @@ -2204,3 +2222,19 @@ func Cachestat(fd uint, crange *CachestatRange, cstat *Cachestat_t, flags uint) } return } + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mseal(b []byte, flags uint) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSEAL, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go index 88bfc288..1851df14 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go @@ -584,6 +584,32 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_fcntl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) @@ -1467,6 +1493,30 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_mount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mount mount "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { @@ -2271,5 +2321,3 @@ func unveil(path *byte, flags *byte) (err error) { var libc_unveil_trampoline_addr uintptr //go:cgo_import_dynamic libc_unveil unveil "libc.so" - - diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.s b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.s index 4cbeff17..0b43c693 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.s +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.s @@ -178,6 +178,11 @@ TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $4 DATA ·libc_sysctl_trampoline_addr(SB)/4, $libc_sysctl_trampoline<>(SB) +TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fcntl(SB) +GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fcntl_trampoline_addr(SB)/4, $libc_fcntl_trampoline<>(SB) + TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ppoll(SB) GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $4 @@ -458,6 +463,11 @@ TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $4 DATA ·libc_mknodat_trampoline_addr(SB)/4, $libc_mknodat_trampoline<>(SB) +TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mount(SB) +GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $4 +DATA ·libc_mount_trampoline_addr(SB)/4, $libc_mount_trampoline<>(SB) + TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_nanosleep(SB) GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $4 diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go index b8a67b99..e1ec0dbe 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go @@ -584,6 +584,32 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_fcntl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) @@ -1467,6 +1493,30 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_mount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mount mount "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { @@ -2271,5 +2321,3 @@ func unveil(path *byte, flags *byte) (err error) { var libc_unveil_trampoline_addr uintptr //go:cgo_import_dynamic libc_unveil unveil "libc.so" - - diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.s b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.s index 1123f275..880c6d6e 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.s +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.s @@ -178,6 +178,11 @@ TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) +TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fcntl(SB) +GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fcntl_trampoline_addr(SB)/8, $libc_fcntl_trampoline<>(SB) + TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ppoll(SB) GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $8 @@ -458,6 +463,11 @@ TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $8 DATA ·libc_mknodat_trampoline_addr(SB)/8, $libc_mknodat_trampoline<>(SB) +TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mount(SB) +GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mount_trampoline_addr(SB)/8, $libc_mount_trampoline<>(SB) + TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_nanosleep(SB) GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $8 diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go index af50a65c..7c8452a6 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go @@ -584,6 +584,32 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_fcntl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) @@ -1467,6 +1493,30 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_mount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mount mount "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { @@ -2271,5 +2321,3 @@ func unveil(path *byte, flags *byte) (err error) { var libc_unveil_trampoline_addr uintptr //go:cgo_import_dynamic libc_unveil unveil "libc.so" - - diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.s b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.s index 82badae3..b8ef95b0 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.s +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.s @@ -178,6 +178,11 @@ TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $4 DATA ·libc_sysctl_trampoline_addr(SB)/4, $libc_sysctl_trampoline<>(SB) +TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fcntl(SB) +GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fcntl_trampoline_addr(SB)/4, $libc_fcntl_trampoline<>(SB) + TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ppoll(SB) GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $4 @@ -458,6 +463,11 @@ TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $4 DATA ·libc_mknodat_trampoline_addr(SB)/4, $libc_mknodat_trampoline<>(SB) +TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mount(SB) +GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $4 +DATA ·libc_mount_trampoline_addr(SB)/4, $libc_mount_trampoline<>(SB) + TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_nanosleep(SB) GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $4 diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go index 8fb4ff36..2ffdf861 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go @@ -584,6 +584,32 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_fcntl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) @@ -1467,6 +1493,30 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_mount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mount mount "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { @@ -2271,5 +2321,3 @@ func unveil(path *byte, flags *byte) (err error) { var libc_unveil_trampoline_addr uintptr //go:cgo_import_dynamic libc_unveil unveil "libc.so" - - diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.s b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.s index 24d7eecb..2af3b5c7 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.s +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.s @@ -178,6 +178,11 @@ TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) +TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fcntl(SB) +GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fcntl_trampoline_addr(SB)/8, $libc_fcntl_trampoline<>(SB) + TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ppoll(SB) GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $8 @@ -458,6 +463,11 @@ TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $8 DATA ·libc_mknodat_trampoline_addr(SB)/8, $libc_mknodat_trampoline<>(SB) +TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mount(SB) +GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mount_trampoline_addr(SB)/8, $libc_mount_trampoline<>(SB) + TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_nanosleep(SB) GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $8 diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go index f469a83e..1da08d52 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go @@ -584,6 +584,32 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_fcntl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) @@ -1467,6 +1493,30 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_mount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mount mount "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { @@ -2271,5 +2321,3 @@ func unveil(path *byte, flags *byte) (err error) { var libc_unveil_trampoline_addr uintptr //go:cgo_import_dynamic libc_unveil unveil "libc.so" - - diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.s b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.s index 9a498a06..b7a25135 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.s +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.s @@ -178,6 +178,11 @@ TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) +TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fcntl(SB) +GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fcntl_trampoline_addr(SB)/8, $libc_fcntl_trampoline<>(SB) + TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ppoll(SB) GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $8 @@ -458,6 +463,11 @@ TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $8 DATA ·libc_mknodat_trampoline_addr(SB)/8, $libc_mknodat_trampoline<>(SB) +TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mount(SB) +GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mount_trampoline_addr(SB)/8, $libc_mount_trampoline<>(SB) + TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_nanosleep(SB) GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $8 diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go index c26ca2e1..6e85b0aa 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go @@ -584,6 +584,32 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_fcntl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) @@ -1467,6 +1493,30 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_mount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mount mount "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { @@ -2271,5 +2321,3 @@ func unveil(path *byte, flags *byte) (err error) { var libc_unveil_trampoline_addr uintptr //go:cgo_import_dynamic libc_unveil unveil "libc.so" - - diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.s b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.s index 1f224aa4..f15dadf0 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.s +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.s @@ -213,6 +213,12 @@ TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) +TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 + CALL libc_fcntl(SB) + RET +GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fcntl_trampoline_addr(SB)/8, $libc_fcntl_trampoline<>(SB) + TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 CALL libc_ppoll(SB) RET @@ -549,6 +555,12 @@ TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $8 DATA ·libc_mknodat_trampoline_addr(SB)/8, $libc_mknodat_trampoline<>(SB) +TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 + CALL libc_mount(SB) + RET +GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mount_trampoline_addr(SB)/8, $libc_mount_trampoline<>(SB) + TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 CALL libc_nanosleep(SB) RET diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go index bcc920dd..28b487df 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go @@ -584,6 +584,32 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_fcntl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) @@ -1467,6 +1493,30 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_mount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mount mount "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { @@ -2271,5 +2321,3 @@ func unveil(path *byte, flags *byte) (err error) { var libc_unveil_trampoline_addr uintptr //go:cgo_import_dynamic libc_unveil unveil "libc.so" - - diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.s b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.s index 87a79c70..1e7f321e 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.s +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.s @@ -178,6 +178,11 @@ TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) +TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fcntl(SB) +GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fcntl_trampoline_addr(SB)/8, $libc_fcntl_trampoline<>(SB) + TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ppoll(SB) GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $8 @@ -458,6 +463,11 @@ TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $8 DATA ·libc_mknodat_trampoline_addr(SB)/8, $libc_mknodat_trampoline<>(SB) +TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mount(SB) +GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mount_trampoline_addr(SB)/8, $libc_mount_trampoline<>(SB) + TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_nanosleep(SB) GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $8 diff --git a/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go b/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go index 94f01123..7ccf66b7 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go @@ -1,4 +1,4 @@ -// go run mksyscall.go -tags zos,s390x syscall_zos_s390x.go +// go run mksyscall_zos_s390x.go -o_sysnum zsysnum_zos_s390x.go -o_syscall zsyscall_zos_s390x.go -i_syscall syscall_zos_s390x.go -o_asm zsymaddr_zos_s390x.s // Code generated by the command above; see README.md. DO NOT EDIT. //go:build zos && s390x @@ -6,17 +6,100 @@ package unix import ( + "runtime" + "syscall" "unsafe" ) +var _ syscall.Errno + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := syscall_syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCNTL<<4, uintptr(fd), uintptr(cmd), uintptr(arg)) + runtime.ExitSyscall() val = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Flistxattr(fd int, dest []byte) (sz int, err error) { + var _p0 unsafe.Pointer + if len(dest) > 0 { + _p0 = unsafe.Pointer(&dest[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FLISTXATTR_A<<4, uintptr(fd), uintptr(_p0), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FlistxattrAddr() *(func(fd int, dest []byte) (sz int, err error)) + +var Flistxattr = enter_Flistxattr + +func enter_Flistxattr(fd int, dest []byte) (sz int, err error) { + funcref := get_FlistxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___FLISTXATTR_A<<4, "") == 0 { + *funcref = impl_Flistxattr + } else { + *funcref = error_Flistxattr + } + return (*funcref)(fd, dest) +} + +func error_Flistxattr(fd int, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Fremovexattr(fd int, attr string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FREMOVEXATTR_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FremovexattrAddr() *(func(fd int, attr string) (err error)) + +var Fremovexattr = enter_Fremovexattr + +func enter_Fremovexattr(fd int, attr string) (err error) { + funcref := get_FremovexattrAddr() + if funcptrtest(GetZosLibVec()+SYS___FREMOVEXATTR_A<<4, "") == 0 { + *funcref = impl_Fremovexattr + } else { + *funcref = error_Fremovexattr } + return (*funcref)(fd, attr) +} + +func error_Fremovexattr(fd int, attr string) (err error) { + err = ENOSYS return } @@ -29,10 +112,12 @@ func read(fd int, p []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := syscall_syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_READ<<4, uintptr(fd), uintptr(_p0), uintptr(len(p))) + runtime.ExitSyscall() n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -46,31 +131,159 @@ func write(fd int, p []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := syscall_syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_WRITE<<4, uintptr(fd), uintptr(_p0), uintptr(len(p))) + runtime.ExitSyscall() n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FGETXATTR_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FgetxattrAddr() *(func(fd int, attr string, dest []byte) (sz int, err error)) + +var Fgetxattr = enter_Fgetxattr + +func enter_Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { + funcref := get_FgetxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___FGETXATTR_A<<4, "") == 0 { + *funcref = impl_Fgetxattr + } else { + *funcref = error_Fgetxattr + } + return (*funcref)(fd, attr, dest) +} + +func error_Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Fsetxattr(fd int, attr string, data []byte, flag int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(data) > 0 { + _p1 = unsafe.Pointer(&data[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FSETXATTR_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(data)), uintptr(flag)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FsetxattrAddr() *(func(fd int, attr string, data []byte, flag int) (err error)) + +var Fsetxattr = enter_Fsetxattr + +func enter_Fsetxattr(fd int, attr string, data []byte, flag int) (err error) { + funcref := get_FsetxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___FSETXATTR_A<<4, "") == 0 { + *funcref = impl_Fsetxattr + } else { + *funcref = error_Fsetxattr } + return (*funcref)(fd, attr, data, flag) +} + +func error_Fsetxattr(fd int, attr string, data []byte, flag int) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := syscall_syscall(SYS___ACCEPT_A, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___ACCEPT_A<<4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___ACCEPT4_A<<4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags)) + runtime.ExitSyscall() fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_accept4Addr() *(func(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error)) + +var accept4 = enter_accept4 + +func enter_accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + funcref := get_accept4Addr() + if funcptrtest(GetZosLibVec()+SYS___ACCEPT4_A<<4, "") == 0 { + *funcref = impl_accept4 + } else { + *funcref = error_accept4 } + return (*funcref)(s, rsa, addrlen, flags) +} + +func error_accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + fd = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := syscall_syscall(SYS___BIND_A, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___BIND_A<<4, uintptr(s), uintptr(addr), uintptr(addrlen)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -78,9 +291,11 @@ func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := syscall_syscall(SYS___CONNECT_A, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CONNECT_A<<4, uintptr(s), uintptr(addr), uintptr(addrlen)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -88,10 +303,10 @@ func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { - r0, _, e1 := syscall_rawsyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETGROUPS<<4, uintptr(n), uintptr(unsafe.Pointer(list))) nn = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -99,9 +314,9 @@ func getgroups(n int, list *_Gid_t) (nn int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETGROUPS<<4, uintptr(n), uintptr(unsafe.Pointer(list))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -109,9 +324,11 @@ func setgroups(n int, list *_Gid_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := syscall_syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETSOCKOPT<<4, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -119,9 +336,11 @@ func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := syscall_syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETSOCKOPT<<4, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -129,10 +348,10 @@ func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := syscall_rawsyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SOCKET<<4, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -140,9 +359,9 @@ func socket(domain int, typ int, proto int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := syscall_rawsyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SOCKETPAIR<<4, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -150,9 +369,9 @@ func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := syscall_rawsyscall(SYS___GETPEERNAME_A, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___GETPEERNAME_A<<4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -160,10 +379,52 @@ func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := syscall_rawsyscall(SYS___GETSOCKNAME_A, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___GETSOCKNAME_A<<4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Removexattr(path string, attr string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___REMOVEXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_RemovexattrAddr() *(func(path string, attr string) (err error)) + +var Removexattr = enter_Removexattr + +func enter_Removexattr(path string, attr string) (err error) { + funcref := get_RemovexattrAddr() + if funcptrtest(GetZosLibVec()+SYS___REMOVEXATTR_A<<4, "") == 0 { + *funcref = impl_Removexattr + } else { + *funcref = error_Removexattr } + return (*funcref)(path, attr) +} + +func error_Removexattr(path string, attr string) (err error) { + err = ENOSYS return } @@ -176,10 +437,12 @@ func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Sockl } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := syscall_syscall6(SYS___RECVFROM_A, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RECVFROM_A<<4, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + runtime.ExitSyscall() n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -193,9 +456,11 @@ func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) ( } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := syscall_syscall6(SYS___SENDTO_A, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SENDTO_A<<4, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -203,10 +468,12 @@ func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := syscall_syscall(SYS___RECVMSG_A, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RECVMSG_A<<4, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + runtime.ExitSyscall() n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -214,10 +481,12 @@ func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := syscall_syscall(SYS___SENDMSG_A, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SENDMSG_A<<4, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + runtime.ExitSyscall() n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -225,10 +494,12 @@ func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { - r0, _, e1 := syscall_syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_MMAP<<4, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + runtime.ExitSyscall() ret = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -236,9 +507,11 @@ func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := syscall_syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_MUNMAP<<4, uintptr(addr), uintptr(length)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -246,9 +519,11 @@ func munmap(addr uintptr, length uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req int, arg uintptr) (err error) { - _, _, e1 := syscall_syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_IOCTL<<4, uintptr(fd), uintptr(req), uintptr(arg)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -256,9 +531,62 @@ func ioctl(fd int, req int, arg uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req int, arg unsafe.Pointer) (err error) { - _, _, e1 := syscall_syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_IOCTL<<4, uintptr(fd), uintptr(req), uintptr(arg)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func shmat(id int, addr uintptr, flag int) (ret uintptr, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHMAT<<4, uintptr(id), uintptr(addr), uintptr(flag)) + runtime.ExitSyscall() + ret = uintptr(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func shmctl(id int, cmd int, buf *SysvShmDesc) (result int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHMCTL64<<4, uintptr(id), uintptr(cmd), uintptr(unsafe.Pointer(buf))) + runtime.ExitSyscall() + result = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func shmdt(addr uintptr) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHMDT<<4, uintptr(addr)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func shmget(key int, size int, flag int) (id int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHMGET<<4, uintptr(key), uintptr(size), uintptr(flag)) + runtime.ExitSyscall() + id = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -271,9 +599,11 @@ func Access(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___ACCESS_A, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___ACCESS_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -286,9 +616,11 @@ func Chdir(path string) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___CHDIR_A, uintptr(unsafe.Pointer(_p0)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CHDIR_A<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -301,9 +633,11 @@ func Chown(path string, uid int, gid int) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___CHOWN_A, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CHOWN_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -316,9 +650,11 @@ func Chmod(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___CHMOD_A, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CHMOD_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -331,10 +667,12 @@ func Creat(path string, mode uint32) (fd int, err error) { if err != nil { return } - r0, _, e1 := syscall_syscall(SYS___CREAT_A, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CREAT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -342,10 +680,12 @@ func Creat(path string, mode uint32) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { - r0, _, e1 := syscall_syscall(SYS_DUP, uintptr(oldfd), 0, 0) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_DUP<<4, uintptr(oldfd)) + runtime.ExitSyscall() fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -353,617 +693,2216 @@ func Dup(oldfd int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { - _, _, e1 := syscall_syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_DUP2<<4, uintptr(oldfd), uintptr(newfd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Errno2() (er2 int) { - uer2, _, _ := syscall_syscall(SYS___ERRNO2, 0, 0, 0) - er2 = int(uer2) +func impl_Dup3(oldfd int, newfd int, flags int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_DUP3<<4, uintptr(oldfd), uintptr(newfd), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_Dup3Addr() *(func(oldfd int, newfd int, flags int) (err error)) -func Err2ad() (eadd *int) { - ueadd, _, _ := syscall_syscall(SYS___ERR2AD, 0, 0, 0) - eadd = (*int)(unsafe.Pointer(ueadd)) - return -} +var Dup3 = enter_Dup3 -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func enter_Dup3(oldfd int, newfd int, flags int) (err error) { + funcref := get_Dup3Addr() + if funcptrtest(GetZosLibVec()+SYS_DUP3<<4, "") == 0 { + *funcref = impl_Dup3 + } else { + *funcref = error_Dup3 + } + return (*funcref)(oldfd, newfd, flags) +} -func Exit(code int) { - syscall_syscall(SYS_EXIT, uintptr(code), 0, 0) +func error_Dup3(oldfd int, newfd int, flags int) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Fchdir(fd int) (err error) { - _, _, e1 := syscall_syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) +func impl_Dirfd(dirp uintptr) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_DIRFD<<4, uintptr(dirp)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_DirfdAddr() *(func(dirp uintptr) (fd int, err error)) -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := syscall_syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) +var Dirfd = enter_Dirfd + +func enter_Dirfd(dirp uintptr) (fd int, err error) { + funcref := get_DirfdAddr() + if funcptrtest(GetZosLibVec()+SYS_DIRFD<<4, "") == 0 { + *funcref = impl_Dirfd + } else { + *funcref = error_Dirfd } + return (*funcref)(dirp) +} + +func error_Dirfd(dirp uintptr) (fd int, err error) { + fd = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := syscall_syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) +func impl_EpollCreate(size int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_CREATE<<4, uintptr(size)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_EpollCreateAddr() *(func(size int) (fd int, err error)) -func FcntlInt(fd uintptr, cmd int, arg int) (retval int, err error) { - r0, _, e1 := syscall_syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - retval = int(r0) - if e1 != 0 { - err = errnoErr(e1) +var EpollCreate = enter_EpollCreate + +func enter_EpollCreate(size int) (fd int, err error) { + funcref := get_EpollCreateAddr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_CREATE<<4, "") == 0 { + *funcref = impl_EpollCreate + } else { + *funcref = error_EpollCreate } + return (*funcref)(size) +} + +func error_EpollCreate(size int) (fd int, err error) { + fd = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func fstat(fd int, stat *Stat_LE_t) (err error) { - _, _, e1 := syscall_syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) +func impl_EpollCreate1(flags int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_CREATE1<<4, uintptr(flags)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_EpollCreate1Addr() *(func(flags int) (fd int, err error)) -func Fstatvfs(fd int, stat *Statvfs_t) (err error) { - _, _, e1 := syscall_syscall(SYS_FSTATVFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) +var EpollCreate1 = enter_EpollCreate1 + +func enter_EpollCreate1(flags int) (fd int, err error) { + funcref := get_EpollCreate1Addr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_CREATE1<<4, "") == 0 { + *funcref = impl_EpollCreate1 + } else { + *funcref = error_EpollCreate1 } + return (*funcref)(flags) +} + +func error_EpollCreate1(flags int) (fd int, err error) { + fd = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Fsync(fd int) (err error) { - _, _, e1 := syscall_syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) +func impl_EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_CTL<<4, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_EpollCtlAddr() *(func(epfd int, op int, fd int, event *EpollEvent) (err error)) -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := syscall_syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) +var EpollCtl = enter_EpollCtl + +func enter_EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { + funcref := get_EpollCtlAddr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_CTL<<4, "") == 0 { + *funcref = impl_EpollCtl + } else { + *funcref = error_EpollCtl } - return + return (*funcref)(epfd, op, fd, event) } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpagesize() (pgsize int) { - r0, _, _ := syscall_syscall(SYS_GETPAGESIZE, 0, 0, 0) - pgsize = int(r0) +func error_EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mprotect(b []byte, prot int) (err error) { +func impl_EpollPwait(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error) { var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := syscall_syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_PWAIT<<4, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), uintptr(unsafe.Pointer(sigmask))) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_EpollPwaitAddr() *(func(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error)) -func Msync(b []byte, flags int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) +var EpollPwait = enter_EpollPwait + +func enter_EpollPwait(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error) { + funcref := get_EpollPwaitAddr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_PWAIT<<4, "") == 0 { + *funcref = impl_EpollPwait } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := syscall_syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) - if e1 != 0 { - err = errnoErr(e1) + *funcref = error_EpollPwait } + return (*funcref)(epfd, events, msec, sigmask) +} + +func error_EpollPwait(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error) { + n = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Poll(fds []PollFd, timeout int) (n int, err error) { +func impl_EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer - if len(fds) > 0 { - _p0 = unsafe.Pointer(&fds[0]) + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := syscall_syscall(SYS_POLL, uintptr(_p0), uintptr(len(fds)), uintptr(timeout)) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_WAIT<<4, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec)) + runtime.ExitSyscall() n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_EpollWaitAddr() *(func(epfd int, events []EpollEvent, msec int) (n int, err error)) -func Times(tms *Tms) (ticks uintptr, err error) { - r0, _, e1 := syscall_syscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) - ticks = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) +var EpollWait = enter_EpollWait + +func enter_EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + funcref := get_EpollWaitAddr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_WAIT<<4, "") == 0 { + *funcref = impl_EpollWait + } else { + *funcref = error_EpollWait } + return (*funcref)(epfd, events, msec) +} + +func error_EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + n = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func W_Getmntent(buff *byte, size int) (lastsys int, err error) { - r0, _, e1 := syscall_syscall(SYS_W_GETMNTENT, uintptr(unsafe.Pointer(buff)), uintptr(size), 0) - lastsys = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } +func Errno2() (er2 int) { + runtime.EnterSyscall() + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS___ERRNO2<<4) + runtime.ExitSyscall() + er2 = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func W_Getmntent_A(buff *byte, size int) (lastsys int, err error) { - r0, _, e1 := syscall_syscall(SYS___W_GETMNTENT_A, uintptr(unsafe.Pointer(buff)), uintptr(size), 0) - lastsys = int(r0) - if e1 != 0 { - err = errnoErr(e1) +func impl_Eventfd(initval uint, flags int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EVENTFD<<4, uintptr(initval), uintptr(flags)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } +//go:nosplit +func get_EventfdAddr() *(func(initval uint, flags int) (fd int, err error)) + +var Eventfd = enter_Eventfd + +func enter_Eventfd(initval uint, flags int) (fd int, err error) { + funcref := get_EventfdAddr() + if funcptrtest(GetZosLibVec()+SYS_EVENTFD<<4, "") == 0 { + *funcref = impl_Eventfd + } else { + *funcref = error_Eventfd + } + return (*funcref)(initval, flags) +} + +func error_Eventfd(initval uint, flags int) (fd int, err error) { + fd = -1 + err = ENOSYS + return +} + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func mount_LE(path string, filesystem string, fstype string, mtm uint32, parmlen int32, parm string) (err error) { +func Exit(code int) { + runtime.EnterSyscall() + CallLeFuncWithErr(GetZosLibVec()+SYS_EXIT<<4, uintptr(code)) + runtime.ExitSyscall() + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } - var _p1 *byte - _p1, err = BytePtrFromString(filesystem) - if err != nil { - return - } - var _p2 *byte - _p2, err = BytePtrFromString(fstype) - if err != nil { - return - } - var _p3 *byte - _p3, err = BytePtrFromString(parm) - if err != nil { - return - } - _, _, e1 := syscall_syscall6(SYS___MOUNT_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(mtm), uintptr(parmlen), uintptr(unsafe.Pointer(_p3))) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FACCESSAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_FaccessatAddr() *(func(dirfd int, path string, mode uint32, flags int) (err error)) -func unmount(filesystem string, mtm int) (err error) { +var Faccessat = enter_Faccessat + +func enter_Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + funcref := get_FaccessatAddr() + if funcptrtest(GetZosLibVec()+SYS___FACCESSAT_A<<4, "") == 0 { + *funcref = impl_Faccessat + } else { + *funcref = error_Faccessat + } + return (*funcref)(dirfd, path, mode, flags) +} + +func error_Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchdir(fd int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCHDIR<<4, uintptr(fd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchmod(fd int, mode uint32) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCHMOD<<4, uintptr(fd), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte - _p0, err = BytePtrFromString(filesystem) + _p0, err = BytePtrFromString(path) if err != nil { return } - _, _, e1 := syscall_syscall(SYS___UMOUNT_A, uintptr(unsafe.Pointer(_p0)), uintptr(mtm), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FCHMODAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FchmodatAddr() *(func(dirfd int, path string, mode uint32, flags int) (err error)) + +var Fchmodat = enter_Fchmodat + +func enter_Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + funcref := get_FchmodatAddr() + if funcptrtest(GetZosLibVec()+SYS___FCHMODAT_A<<4, "") == 0 { + *funcref = impl_Fchmodat + } else { + *funcref = error_Fchmodat + } + return (*funcref)(dirfd, path, mode, flags) +} + +func error_Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchown(fd int, uid int, gid int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCHOWN<<4, uintptr(fd), uintptr(uid), uintptr(gid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Chroot(path string) (err error) { +func impl_Fchownat(fd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } - _, _, e1 := syscall_syscall(SYS___CHROOT_A, uintptr(unsafe.Pointer(_p0)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FCHOWNAT_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FchownatAddr() *(func(fd int, path string, uid int, gid int, flags int) (err error)) + +var Fchownat = enter_Fchownat + +func enter_Fchownat(fd int, path string, uid int, gid int, flags int) (err error) { + funcref := get_FchownatAddr() + if funcptrtest(GetZosLibVec()+SYS___FCHOWNAT_A<<4, "") == 0 { + *funcref = impl_Fchownat + } else { + *funcref = error_Fchownat } + return (*funcref)(fd, path, uid, gid, flags) +} + +func error_Fchownat(fd int, path string, uid int, gid int, flags int) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Uname(buf *Utsname) (err error) { - _, _, e1 := syscall_rawsyscall(SYS___UNAME_A, uintptr(unsafe.Pointer(buf)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) +func FcntlInt(fd uintptr, cmd int, arg int) (retval int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCNTL<<4, uintptr(fd), uintptr(cmd), uintptr(arg)) + runtime.ExitSyscall() + retval = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Gethostname(buf []byte) (err error) { +func impl_Fdatasync(fd int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FDATASYNC<<4, uintptr(fd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FdatasyncAddr() *(func(fd int) (err error)) + +var Fdatasync = enter_Fdatasync + +func enter_Fdatasync(fd int) (err error) { + funcref := get_FdatasyncAddr() + if funcptrtest(GetZosLibVec()+SYS_FDATASYNC<<4, "") == 0 { + *funcref = impl_Fdatasync + } else { + *funcref = error_Fdatasync + } + return (*funcref)(fd) +} + +func error_Fdatasync(fd int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fstat(fd int, stat *Stat_LE_t) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FSTAT<<4, uintptr(fd), uintptr(unsafe.Pointer(stat))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_fstatat(dirfd int, path string, stat *Stat_LE_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FSTATAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_fstatatAddr() *(func(dirfd int, path string, stat *Stat_LE_t, flags int) (err error)) + +var fstatat = enter_fstatat + +func enter_fstatat(dirfd int, path string, stat *Stat_LE_t, flags int) (err error) { + funcref := get_fstatatAddr() + if funcptrtest(GetZosLibVec()+SYS___FSTATAT_A<<4, "") == 0 { + *funcref = impl_fstatat + } else { + *funcref = error_fstatat + } + return (*funcref)(dirfd, path, stat, flags) +} + +func error_fstatat(dirfd int, path string, stat *Stat_LE_t, flags int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(dest) > 0 { + _p2 = unsafe.Pointer(&dest[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LGETXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_LgetxattrAddr() *(func(link string, attr string, dest []byte) (sz int, err error)) + +var Lgetxattr = enter_Lgetxattr + +func enter_Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { + funcref := get_LgetxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LGETXATTR_A<<4, "") == 0 { + *funcref = impl_Lgetxattr + } else { + *funcref = error_Lgetxattr + } + return (*funcref)(link, attr, dest) +} + +func error_Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Lsetxattr(path string, attr string, data []byte, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(data) > 0 { + _p2 = unsafe.Pointer(&data[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LSETXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_LsetxattrAddr() *(func(path string, attr string, data []byte, flags int) (err error)) + +var Lsetxattr = enter_Lsetxattr + +func enter_Lsetxattr(path string, attr string, data []byte, flags int) (err error) { + funcref := get_LsetxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LSETXATTR_A<<4, "") == 0 { + *funcref = impl_Lsetxattr + } else { + *funcref = error_Lsetxattr + } + return (*funcref)(path, attr, data, flags) +} + +func error_Lsetxattr(path string, attr string, data []byte, flags int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Fstatfs(fd int, buf *Statfs_t) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FSTATFS<<4, uintptr(fd), uintptr(unsafe.Pointer(buf))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FstatfsAddr() *(func(fd int, buf *Statfs_t) (err error)) + +var Fstatfs = enter_Fstatfs + +func enter_Fstatfs(fd int, buf *Statfs_t) (err error) { + funcref := get_FstatfsAddr() + if funcptrtest(GetZosLibVec()+SYS_FSTATFS<<4, "") == 0 { + *funcref = impl_Fstatfs + } else { + *funcref = error_Fstatfs + } + return (*funcref)(fd, buf) +} + +func error_Fstatfs(fd int, buf *Statfs_t) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fstatvfs(fd int, stat *Statvfs_t) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FSTATVFS<<4, uintptr(fd), uintptr(unsafe.Pointer(stat))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fsync(fd int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FSYNC<<4, uintptr(fd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Futimes(fd int, tv []Timeval) (err error) { var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) + if len(tv) > 0 { + _p0 = unsafe.Pointer(&tv[0]) } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := syscall_syscall(SYS___GETHOSTNAME_A, uintptr(_p0), uintptr(len(buf)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FUTIMES<<4, uintptr(fd), uintptr(_p0), uintptr(len(tv))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_FutimesAddr() *(func(fd int, tv []Timeval) (err error)) -func Getegid() (egid int) { - r0, _, _ := syscall_rawsyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) +var Futimes = enter_Futimes + +func enter_Futimes(fd int, tv []Timeval) (err error) { + funcref := get_FutimesAddr() + if funcptrtest(GetZosLibVec()+SYS_FUTIMES<<4, "") == 0 { + *funcref = impl_Futimes + } else { + *funcref = error_Futimes + } + return (*funcref)(fd, tv) +} + +func error_Futimes(fd int, tv []Timeval) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Geteuid() (uid int) { - r0, _, _ := syscall_rawsyscall(SYS_GETEUID, 0, 0, 0) - uid = int(r0) +func impl_Futimesat(dirfd int, path string, tv []Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(tv) > 0 { + _p1 = unsafe.Pointer(&tv[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FUTIMESAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(tv))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FutimesatAddr() *(func(dirfd int, path string, tv []Timeval) (err error)) + +var Futimesat = enter_Futimesat + +func enter_Futimesat(dirfd int, path string, tv []Timeval) (err error) { + funcref := get_FutimesatAddr() + if funcptrtest(GetZosLibVec()+SYS___FUTIMESAT_A<<4, "") == 0 { + *funcref = impl_Futimesat + } else { + *funcref = error_Futimesat + } + return (*funcref)(dirfd, path, tv) +} + +func error_Futimesat(dirfd int, path string, tv []Timeval) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getgid() (gid int) { - r0, _, _ := syscall_rawsyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) +func Ftruncate(fd int, length int64) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FTRUNCATE<<4, uintptr(fd), uintptr(length)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getpid() (pid int) { - r0, _, _ := syscall_rawsyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) +func impl_Getrandom(buf []byte, flags int) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETRANDOM<<4, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_GetrandomAddr() *(func(buf []byte, flags int) (n int, err error)) + +var Getrandom = enter_Getrandom + +func enter_Getrandom(buf []byte, flags int) (n int, err error) { + funcref := get_GetrandomAddr() + if funcptrtest(GetZosLibVec()+SYS_GETRANDOM<<4, "") == 0 { + *funcref = impl_Getrandom + } else { + *funcref = error_Getrandom + } + return (*funcref)(buf, flags) +} + +func error_Getrandom(buf []byte, flags int) (n int, err error) { + n = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := syscall_rawsyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) +func impl_InotifyInit() (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec() + SYS_INOTIFY_INIT<<4) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_InotifyInitAddr() *(func() (fd int, err error)) + +var InotifyInit = enter_InotifyInit + +func enter_InotifyInit() (fd int, err error) { + funcref := get_InotifyInitAddr() + if funcptrtest(GetZosLibVec()+SYS_INOTIFY_INIT<<4, "") == 0 { + *funcref = impl_InotifyInit + } else { + *funcref = error_InotifyInit } + return (*funcref)() +} + +func error_InotifyInit() (fd int, err error) { + fd = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getppid() (pid int) { - r0, _, _ := syscall_rawsyscall(SYS_GETPPID, 0, 0, 0) - pid = int(r0) +func impl_InotifyInit1(flags int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_INOTIFY_INIT1<<4, uintptr(flags)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_InotifyInit1Addr() *(func(flags int) (fd int, err error)) + +var InotifyInit1 = enter_InotifyInit1 + +func enter_InotifyInit1(flags int) (fd int, err error) { + funcref := get_InotifyInit1Addr() + if funcptrtest(GetZosLibVec()+SYS_INOTIFY_INIT1<<4, "") == 0 { + *funcref = impl_InotifyInit1 + } else { + *funcref = error_InotifyInit1 + } + return (*funcref)(flags) +} + +func error_InotifyInit1(flags int) (fd int, err error) { + fd = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(pathname) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___INOTIFY_ADD_WATCH_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) + runtime.ExitSyscall() + watchdesc = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_InotifyAddWatchAddr() *(func(fd int, pathname string, mask uint32) (watchdesc int, err error)) + +var InotifyAddWatch = enter_InotifyAddWatch + +func enter_InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { + funcref := get_InotifyAddWatchAddr() + if funcptrtest(GetZosLibVec()+SYS___INOTIFY_ADD_WATCH_A<<4, "") == 0 { + *funcref = impl_InotifyAddWatch + } else { + *funcref = error_InotifyAddWatch + } + return (*funcref)(fd, pathname, mask) +} + +func error_InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { + watchdesc = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_INOTIFY_RM_WATCH<<4, uintptr(fd), uintptr(watchdesc)) + runtime.ExitSyscall() + success = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_InotifyRmWatchAddr() *(func(fd int, watchdesc uint32) (success int, err error)) + +var InotifyRmWatch = enter_InotifyRmWatch + +func enter_InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { + funcref := get_InotifyRmWatchAddr() + if funcptrtest(GetZosLibVec()+SYS_INOTIFY_RM_WATCH<<4, "") == 0 { + *funcref = impl_InotifyRmWatch + } else { + *funcref = error_InotifyRmWatch + } + return (*funcref)(fd, watchdesc) +} + +func error_InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { + success = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Listxattr(path string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LISTXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_ListxattrAddr() *(func(path string, dest []byte) (sz int, err error)) + +var Listxattr = enter_Listxattr + +func enter_Listxattr(path string, dest []byte) (sz int, err error) { + funcref := get_ListxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LISTXATTR_A<<4, "") == 0 { + *funcref = impl_Listxattr + } else { + *funcref = error_Listxattr + } + return (*funcref)(path, dest) +} + +func error_Listxattr(path string, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Llistxattr(path string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LLISTXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_LlistxattrAddr() *(func(path string, dest []byte) (sz int, err error)) + +var Llistxattr = enter_Llistxattr + +func enter_Llistxattr(path string, dest []byte) (sz int, err error) { + funcref := get_LlistxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LLISTXATTR_A<<4, "") == 0 { + *funcref = impl_Llistxattr + } else { + *funcref = error_Llistxattr + } + return (*funcref)(path, dest) +} + +func error_Llistxattr(path string, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Lremovexattr(path string, attr string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LREMOVEXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_LremovexattrAddr() *(func(path string, attr string) (err error)) + +var Lremovexattr = enter_Lremovexattr + +func enter_Lremovexattr(path string, attr string) (err error) { + funcref := get_LremovexattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LREMOVEXATTR_A<<4, "") == 0 { + *funcref = impl_Lremovexattr + } else { + *funcref = error_Lremovexattr + } + return (*funcref)(path, attr) +} + +func error_Lremovexattr(path string, attr string) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Lutimes(path string, tv []Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(tv) > 0 { + _p1 = unsafe.Pointer(&tv[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LUTIMES_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(tv))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_LutimesAddr() *(func(path string, tv []Timeval) (err error)) + +var Lutimes = enter_Lutimes + +func enter_Lutimes(path string, tv []Timeval) (err error) { + funcref := get_LutimesAddr() + if funcptrtest(GetZosLibVec()+SYS___LUTIMES_A<<4, "") == 0 { + *funcref = impl_Lutimes + } else { + *funcref = error_Lutimes + } + return (*funcref)(path, tv) +} + +func error_Lutimes(path string, tv []Timeval) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_MPROTECT<<4, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_MSYNC<<4, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Console2(cmsg *ConsMsg2, modstr *byte, concmd *uint32) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CONSOLE2<<4, uintptr(unsafe.Pointer(cmsg)), uintptr(unsafe.Pointer(modstr)), uintptr(unsafe.Pointer(concmd))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Poll(fds []PollFd, timeout int) (n int, err error) { + var _p0 unsafe.Pointer + if len(fds) > 0 { + _p0 = unsafe.Pointer(&fds[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_POLL<<4, uintptr(_p0), uintptr(len(fds)), uintptr(timeout)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Readdir_r(dirp uintptr, entry *direntLE, result **direntLE) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___READDIR_R_A<<4, uintptr(dirp), uintptr(unsafe.Pointer(entry)), uintptr(unsafe.Pointer(result))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Statfs(path string, buf *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___STATFS_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_StatfsAddr() *(func(path string, buf *Statfs_t) (err error)) + +var Statfs = enter_Statfs + +func enter_Statfs(path string, buf *Statfs_t) (err error) { + funcref := get_StatfsAddr() + if funcptrtest(GetZosLibVec()+SYS___STATFS_A<<4, "") == 0 { + *funcref = impl_Statfs + } else { + *funcref = error_Statfs + } + return (*funcref)(path, buf) +} + +func error_Statfs(path string, buf *Statfs_t) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Syncfs(fd int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SYNCFS<<4, uintptr(fd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_SyncfsAddr() *(func(fd int) (err error)) + +var Syncfs = enter_Syncfs + +func enter_Syncfs(fd int) (err error) { + funcref := get_SyncfsAddr() + if funcptrtest(GetZosLibVec()+SYS_SYNCFS<<4, "") == 0 { + *funcref = impl_Syncfs + } else { + *funcref = error_Syncfs + } + return (*funcref)(fd) +} + +func error_Syncfs(fd int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Times(tms *Tms) (ticks uintptr, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_TIMES<<4, uintptr(unsafe.Pointer(tms))) + runtime.ExitSyscall() + ticks = uintptr(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func W_Getmntent(buff *byte, size int) (lastsys int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_W_GETMNTENT<<4, uintptr(unsafe.Pointer(buff)), uintptr(size)) + runtime.ExitSyscall() + lastsys = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func W_Getmntent_A(buff *byte, size int) (lastsys int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___W_GETMNTENT_A<<4, uintptr(unsafe.Pointer(buff)), uintptr(size)) + runtime.ExitSyscall() + lastsys = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func mount_LE(path string, filesystem string, fstype string, mtm uint32, parmlen int32, parm string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(filesystem) + if err != nil { + return + } + var _p2 *byte + _p2, err = BytePtrFromString(fstype) + if err != nil { + return + } + var _p3 *byte + _p3, err = BytePtrFromString(parm) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MOUNT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(mtm), uintptr(parmlen), uintptr(unsafe.Pointer(_p3))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func unmount_LE(filesystem string, mtm int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(filesystem) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UMOUNT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mtm)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CHROOT_A<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Select(nmsgsfds int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (ret int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SELECT<<4, uintptr(nmsgsfds), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout))) + runtime.ExitSyscall() + ret = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Uname(buf *Utsname) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_____OSNAME_A<<4, uintptr(unsafe.Pointer(buf))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Unshare(flags int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_UNSHARE<<4, uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_UnshareAddr() *(func(flags int) (err error)) + +var Unshare = enter_Unshare + +func enter_Unshare(flags int) (err error) { + funcref := get_UnshareAddr() + if funcptrtest(GetZosLibVec()+SYS_UNSHARE<<4, "") == 0 { + *funcref = impl_Unshare + } else { + *funcref = error_Unshare + } + return (*funcref)(flags) +} + +func error_Unshare(flags int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Gethostname(buf []byte) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___GETHOSTNAME_A<<4, uintptr(_p0), uintptr(len(buf))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getgid() (gid int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETGID<<4) + gid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getpid() (pid int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETPID<<4) + pid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getpgid(pid int) (pgid int, err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETPGID<<4, uintptr(pid)) + pgid = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getppid() (pid int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETPPID<<4) + pid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getpriority(which int, who int) (prio int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETPRIORITY<<4, uintptr(which), uintptr(who)) + runtime.ExitSyscall() + prio = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getrlimit(resource int, rlim *Rlimit) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETRLIMIT<<4, uintptr(resource), uintptr(unsafe.Pointer(rlim))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func getrusage(who int, rusage *rusage_zos) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETRUSAGE<<4, uintptr(who), uintptr(unsafe.Pointer(rusage))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getegid() (egid int) { + runtime.EnterSyscall() + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETEGID<<4) + runtime.ExitSyscall() + egid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Geteuid() (euid int) { + runtime.EnterSyscall() + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETEUID<<4) + runtime.ExitSyscall() + euid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getsid(pid int) (sid int, err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETSID<<4, uintptr(pid)) + sid = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getuid() (uid int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETUID<<4) + uid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Kill(pid int, sig Signal) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_KILL<<4, uintptr(pid), uintptr(sig)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LCHOWN_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LINK_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Linkat(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldPath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newPath) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LINKAT_A<<4, uintptr(oldDirFd), uintptr(unsafe.Pointer(_p0)), uintptr(newDirFd), uintptr(unsafe.Pointer(_p1)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_LinkatAddr() *(func(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error)) + +var Linkat = enter_Linkat + +func enter_Linkat(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error) { + funcref := get_LinkatAddr() + if funcptrtest(GetZosLibVec()+SYS___LINKAT_A<<4, "") == 0 { + *funcref = impl_Linkat + } else { + *funcref = error_Linkat + } + return (*funcref)(oldDirFd, oldPath, newDirFd, newPath, flags) +} + +func error_Linkat(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Listen(s int, n int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_LISTEN<<4, uintptr(s), uintptr(n)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func lstat(path string, stat *Stat_LE_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LSTAT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKDIR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKDIRAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_MkdiratAddr() *(func(dirfd int, path string, mode uint32) (err error)) + +var Mkdirat = enter_Mkdirat + +func enter_Mkdirat(dirfd int, path string, mode uint32) (err error) { + funcref := get_MkdiratAddr() + if funcptrtest(GetZosLibVec()+SYS___MKDIRAT_A<<4, "") == 0 { + *funcref = impl_Mkdirat + } else { + *funcref = error_Mkdirat + } + return (*funcref)(dirfd, path, mode) +} + +func error_Mkdirat(dirfd int, path string, mode uint32) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKFIFO_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKNOD_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKNODAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_MknodatAddr() *(func(dirfd int, path string, mode uint32, dev int) (err error)) + +var Mknodat = enter_Mknodat + +func enter_Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + funcref := get_MknodatAddr() + if funcptrtest(GetZosLibVec()+SYS___MKNODAT_A<<4, "") == 0 { + *funcref = impl_Mknodat + } else { + *funcref = error_Mknodat + } + return (*funcref)(dirfd, path, mode, dev) +} + +func error_Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_PivotRoot(newroot string, oldroot string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(newroot) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(oldroot) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___PIVOT_ROOT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_PivotRootAddr() *(func(newroot string, oldroot string) (err error)) + +var PivotRoot = enter_PivotRoot + +func enter_PivotRoot(newroot string, oldroot string) (err error) { + funcref := get_PivotRootAddr() + if funcptrtest(GetZosLibVec()+SYS___PIVOT_ROOT_A<<4, "") == 0 { + *funcref = impl_PivotRoot + } else { + *funcref = error_PivotRoot + } + return (*funcref)(newroot, oldroot) +} + +func error_PivotRoot(newroot string, oldroot string) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PREAD<<4, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := syscall_syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) +func Pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PWRITE<<4, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getrlimit(resource int, rlim *Rlimit) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) - if e1 != 0 { - err = errnoErr(e1) +func impl_Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___PRCTL_A<<4, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_PrctlAddr() *(func(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error)) -func getrusage(who int, rusage *rusage_zos) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) +var Prctl = enter_Prctl + +func enter_Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { + funcref := get_PrctlAddr() + if funcptrtest(GetZosLibVec()+SYS___PRCTL_A<<4, "") == 0 { + *funcref = impl_Prctl + } else { + *funcref = error_Prctl } - return + return (*funcref)(option, arg2, arg3, arg4, arg5) } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getsid(pid int) (sid int, err error) { - r0, _, e1 := syscall_rawsyscall(SYS_GETSID, uintptr(pid), 0, 0) - sid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } +func error_Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getuid() (uid int) { - r0, _, _ := syscall_rawsyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) +func impl_Prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PRLIMIT<<4, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_PrlimitAddr() *(func(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error)) -func Kill(pid int, sig Signal) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) - if e1 != 0 { - err = errnoErr(e1) +var Prlimit = enter_Prlimit + +func enter_Prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + funcref := get_PrlimitAddr() + if funcptrtest(GetZosLibVec()+SYS_PRLIMIT<<4, "") == 0 { + *funcref = impl_Prlimit + } else { + *funcref = error_Prlimit } + return (*funcref)(pid, resource, newlimit, old) +} + +func error_Prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Lchown(path string, uid int, gid int) (err error) { +func Rename(from string, to string) (err error) { var _p0 *byte - _p0, err = BytePtrFromString(path) + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) if err != nil { return } - _, _, e1 := syscall_syscall(SYS___LCHOWN_A, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RENAME_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Link(path string, link string) (err error) { +func impl_Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte - _p0, err = BytePtrFromString(path) + _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte - _p1, err = BytePtrFromString(link) + _p1, err = BytePtrFromString(newpath) if err != nil { return } - _, _, e1 := syscall_syscall(SYS___LINK_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RENAMEAT_A<<4, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_RenameatAddr() *(func(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)) -func Listen(s int, n int) (err error) { - _, _, e1 := syscall_syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) - if e1 != 0 { - err = errnoErr(e1) +var Renameat = enter_Renameat + +func enter_Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + funcref := get_RenameatAddr() + if funcptrtest(GetZosLibVec()+SYS___RENAMEAT_A<<4, "") == 0 { + *funcref = impl_Renameat + } else { + *funcref = error_Renameat } + return (*funcref)(olddirfd, oldpath, newdirfd, newpath) +} + +func error_Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func lstat(path string, stat *Stat_LE_t) (err error) { +func impl_Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) { var _p0 *byte - _p0, err = BytePtrFromString(path) + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) if err != nil { return } - _, _, e1 := syscall_syscall(SYS___LSTAT_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RENAMEAT2_A<<4, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_Renameat2Addr() *(func(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error)) -func Mkdir(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := syscall_syscall(SYS___MKDIR_A, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) +var Renameat2 = enter_Renameat2 + +func enter_Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) { + funcref := get_Renameat2Addr() + if funcptrtest(GetZosLibVec()+SYS___RENAMEAT2_A<<4, "") == 0 { + *funcref = impl_Renameat2 + } else { + *funcref = error_Renameat2 } + return (*funcref)(olddirfd, oldpath, newdirfd, newpath, flags) +} + +func error_Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mkfifo(path string, mode uint32) (err error) { +func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } - _, _, e1 := syscall_syscall(SYS___MKFIFO_A, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RMDIR_A<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mknod(path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := syscall_syscall(SYS___MKNOD_A, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) - if e1 != 0 { - err = errnoErr(e1) +func Seek(fd int, offset int64, whence int) (off int64, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_LSEEK<<4, uintptr(fd), uintptr(offset), uintptr(whence)) + runtime.ExitSyscall() + off = int64(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) +func Setegid(egid int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETEGID<<4, uintptr(egid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } - r0, _, e1 := syscall_syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Seteuid(euid int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETEUID<<4, uintptr(euid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { +func impl_Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := syscall_syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SETHOSTNAME_A<<4, uintptr(_p0), uintptr(len(p))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_SethostnameAddr() *(func(p []byte) (err error)) -func Readlink(path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) +var Sethostname = enter_Sethostname + +func enter_Sethostname(p []byte) (err error) { + funcref := get_SethostnameAddr() + if funcptrtest(GetZosLibVec()+SYS___SETHOSTNAME_A<<4, "") == 0 { + *funcref = impl_Sethostname } else { - _p1 = unsafe.Pointer(&_zero) + *funcref = error_Sethostname } - r0, _, e1 := syscall_syscall(SYS___READLINK_A, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return + return (*funcref)(p) } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rename(from string, to string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(from) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(to) - if err != nil { - return - } - _, _, e1 := syscall_syscall(SYS___RENAME_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - if e1 != 0 { - err = errnoErr(e1) - } +func error_Sethostname(p []byte) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Rmdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := syscall_syscall(SYS___RMDIR_A, uintptr(unsafe.Pointer(_p0)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) +func impl_Setns(fd int, nstype int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETNS<<4, uintptr(fd), uintptr(nstype)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_SetnsAddr() *(func(fd int, nstype int) (err error)) -func Seek(fd int, offset int64, whence int) (off int64, err error) { - r0, _, e1 := syscall_syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) - off = int64(r0) - if e1 != 0 { - err = errnoErr(e1) +var Setns = enter_Setns + +func enter_Setns(fd int, nstype int) (err error) { + funcref := get_SetnsAddr() + if funcptrtest(GetZosLibVec()+SYS_SETNS<<4, "") == 0 { + *funcref = impl_Setns + } else { + *funcref = error_Setns } + return (*funcref)(fd, nstype) +} + +func error_Setns(fd int, nstype int) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := syscall_syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETPRIORITY<<4, uintptr(which), uintptr(who), uintptr(prio)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -971,9 +2910,9 @@ func Setpriority(which int, who int, prio int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETPGID<<4, uintptr(pid), uintptr(pgid)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -981,9 +2920,9 @@ func Setpgid(pid int, pgid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(resource int, lim *Rlimit) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETRLIMIT<<4, uintptr(resource), uintptr(unsafe.Pointer(lim))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -991,9 +2930,9 @@ func Setrlimit(resource int, lim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETREGID<<4, uintptr(rgid), uintptr(egid)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1001,9 +2940,9 @@ func Setregid(rgid int, egid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETREUID<<4, uintptr(ruid), uintptr(euid)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1011,10 +2950,10 @@ func Setreuid(ruid int, euid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { - r0, _, e1 := syscall_rawsyscall(SYS_SETSID, 0, 0, 0) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec() + SYS_SETSID<<4) pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1022,9 +2961,11 @@ func Setsid() (pid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { - _, _, e1 := syscall_syscall(SYS_SETUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETUID<<4, uintptr(uid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1032,9 +2973,11 @@ func Setuid(uid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(uid int) (err error) { - _, _, e1 := syscall_syscall(SYS_SETGID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETGID<<4, uintptr(uid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1042,9 +2985,11 @@ func Setgid(uid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { - _, _, e1 := syscall_syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHUTDOWN<<4, uintptr(fd), uintptr(how)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1057,9 +3002,11 @@ func stat(path string, statLE *Stat_LE_t) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___STAT_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(statLE)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___STAT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(statLE))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1077,17 +3024,63 @@ func Symlink(path string, link string) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___SYMLINK_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SYMLINK_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Symlinkat(oldPath string, dirfd int, newPath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldPath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newPath) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SYMLINKAT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(dirfd), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } +//go:nosplit +func get_SymlinkatAddr() *(func(oldPath string, dirfd int, newPath string) (err error)) + +var Symlinkat = enter_Symlinkat + +func enter_Symlinkat(oldPath string, dirfd int, newPath string) (err error) { + funcref := get_SymlinkatAddr() + if funcptrtest(GetZosLibVec()+SYS___SYMLINKAT_A<<4, "") == 0 { + *funcref = impl_Symlinkat + } else { + *funcref = error_Symlinkat + } + return (*funcref)(oldPath, dirfd, newPath) +} + +func error_Symlinkat(oldPath string, dirfd int, newPath string) (err error) { + err = ENOSYS + return +} + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { - syscall_syscall(SYS_SYNC, 0, 0, 0) + runtime.EnterSyscall() + CallLeFuncWithErr(GetZosLibVec() + SYS_SYNC<<4) + runtime.ExitSyscall() return } @@ -1099,9 +3092,11 @@ func Truncate(path string, length int64) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___TRUNCATE_A, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___TRUNCATE_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(length)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1109,9 +3104,11 @@ func Truncate(path string, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tcgetattr(fildes int, termptr *Termios) (err error) { - _, _, e1 := syscall_syscall(SYS_TCGETATTR, uintptr(fildes), uintptr(unsafe.Pointer(termptr)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_TCGETATTR<<4, uintptr(fildes), uintptr(unsafe.Pointer(termptr))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1119,9 +3116,11 @@ func Tcgetattr(fildes int, termptr *Termios) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tcsetattr(fildes int, when int, termptr *Termios) (err error) { - _, _, e1 := syscall_syscall(SYS_TCSETATTR, uintptr(fildes), uintptr(when), uintptr(unsafe.Pointer(termptr))) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_TCSETATTR<<4, uintptr(fildes), uintptr(when), uintptr(unsafe.Pointer(termptr))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1129,7 +3128,9 @@ func Tcsetattr(fildes int, when int, termptr *Termios) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { - r0, _, _ := syscall_syscall(SYS_UMASK, uintptr(mask), 0, 0) + runtime.EnterSyscall() + r0, _, _ := CallLeFuncWithErr(GetZosLibVec()+SYS_UMASK<<4, uintptr(mask)) + runtime.ExitSyscall() oldmask = int(r0) return } @@ -1142,10 +3143,49 @@ func Unlink(path string) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___UNLINK_A, uintptr(unsafe.Pointer(_p0)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UNLINK_A<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UNLINKAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_UnlinkatAddr() *(func(dirfd int, path string, flags int) (err error)) + +var Unlinkat = enter_Unlinkat + +func enter_Unlinkat(dirfd int, path string, flags int) (err error) { + funcref := get_UnlinkatAddr() + if funcptrtest(GetZosLibVec()+SYS___UNLINKAT_A<<4, "") == 0 { + *funcref = impl_Unlinkat + } else { + *funcref = error_Unlinkat } + return (*funcref)(dirfd, path, flags) +} + +func error_Unlinkat(dirfd int, path string, flags int) (err error) { + err = ENOSYS return } @@ -1157,9 +3197,11 @@ func Utime(path string, utim *Utimbuf) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___UTIME_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(utim)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UTIME_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(utim))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1172,11 +3214,91 @@ func open(path string, mode int, perm uint32) (fd int, err error) { if err != nil { return } - r0, _, e1 := syscall_syscall(SYS___OPEN_A, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___OPEN_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___OPENAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_openatAddr() *(func(dirfd int, path string, flags int, mode uint32) (fd int, err error)) + +var openat = enter_openat + +func enter_openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + funcref := get_openatAddr() + if funcptrtest(GetZosLibVec()+SYS___OPENAT_A<<4, "") == 0 { + *funcref = impl_openat + } else { + *funcref = error_openat + } + return (*funcref)(dirfd, path, flags, mode) +} + +func error_openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + fd = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___OPENAT2_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(open_how)), uintptr(size)) + runtime.ExitSyscall() fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_openat2Addr() *(func(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error)) + +var openat2 = enter_openat2 + +func enter_openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error) { + funcref := get_openat2Addr() + if funcptrtest(GetZosLibVec()+SYS___OPENAT2_A<<4, "") == 0 { + *funcref = impl_openat2 + } else { + *funcref = error_openat2 } + return (*funcref)(dirfd, path, open_how, size) +} + +func error_openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error) { + fd = -1 + err = ENOSYS return } @@ -1188,9 +3310,23 @@ func remove(path string) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS_REMOVE, uintptr(unsafe.Pointer(_p0)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_REMOVE<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func waitid(idType int, id int, info *Siginfo, options int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_WAITID<<4, uintptr(idType), uintptr(id), uintptr(unsafe.Pointer(info)), uintptr(options)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1198,10 +3334,12 @@ func remove(path string) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func waitpid(pid int, wstatus *_C_int, options int) (wpid int, err error) { - r0, _, e1 := syscall_syscall(SYS_WAITPID, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options)) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_WAITPID<<4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options)) + runtime.ExitSyscall() wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1209,9 +3347,9 @@ func waitpid(pid int, wstatus *_C_int, options int) (wpid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func gettimeofday(tv *timeval_zos) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETTIMEOFDAY<<4, uintptr(unsafe.Pointer(tv))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1219,9 +3357,9 @@ func gettimeofday(tv *timeval_zos) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PIPE<<4, uintptr(unsafe.Pointer(p))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1234,20 +3372,87 @@ func utimes(path string, timeval *[2]Timeval) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___UTIMES_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UTIMES_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Select(nmsgsfds int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (ret int, err error) { - r0, _, e1 := syscall_syscall6(SYS_SELECT, uintptr(nmsgsfds), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - ret = int(r0) - if e1 != 0 { - err = errnoErr(e1) +func impl_utimensat(dirfd int, path string, ts *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UTIMENSAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(ts)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_utimensatAddr() *(func(dirfd int, path string, ts *[2]Timespec, flags int) (err error)) + +var utimensat = enter_utimensat + +func enter_utimensat(dirfd int, path string, ts *[2]Timespec, flags int) (err error) { + funcref := get_utimensatAddr() + if funcptrtest(GetZosLibVec()+SYS___UTIMENSAT_A<<4, "") == 0 { + *funcref = impl_utimensat + } else { + *funcref = error_utimensat + } + return (*funcref)(dirfd, path, ts, flags) +} + +func error_utimensat(dirfd int, path string, ts *[2]Timespec, flags int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Posix_openpt(oflag int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_POSIX_OPENPT<<4, uintptr(oflag)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Grantpt(fildes int) (rc int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GRANTPT<<4, uintptr(fildes)) + runtime.ExitSyscall() + rc = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Unlockpt(fildes int) (rc int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_UNLOCKPT<<4, uintptr(fildes)) + runtime.ExitSyscall() + rc = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go index fcf3ecbd..524b0820 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go @@ -448,4 +448,14 @@ const ( SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go index f56dc250..f485dbf4 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go @@ -341,6 +341,7 @@ const ( SYS_STATX = 332 SYS_IO_PGETEVENTS = 333 SYS_RSEQ = 334 + SYS_URETPROBE = 335 SYS_PIDFD_SEND_SIGNAL = 424 SYS_IO_URING_SETUP = 425 SYS_IO_URING_ENTER = 426 @@ -371,4 +372,13 @@ const ( SYS_CACHESTAT = 451 SYS_FCHMODAT2 = 452 SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go index 974bf246..70b35bf3 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go @@ -412,4 +412,14 @@ const ( SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go index 39a2739e..1893e2fe 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go @@ -85,7 +85,7 @@ const ( SYS_SPLICE = 76 SYS_TEE = 77 SYS_READLINKAT = 78 - SYS_FSTATAT = 79 + SYS_NEWFSTATAT = 79 SYS_FSTAT = 80 SYS_SYNC = 81 SYS_FSYNC = 82 @@ -315,4 +315,14 @@ const ( SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go index cf9c9d77..16a4017d 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go @@ -84,6 +84,8 @@ const ( SYS_SPLICE = 76 SYS_TEE = 77 SYS_READLINKAT = 78 + SYS_NEWFSTATAT = 79 + SYS_FSTAT = 80 SYS_SYNC = 81 SYS_FSYNC = 82 SYS_FDATASYNC = 83 @@ -309,4 +311,14 @@ const ( SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go index 10b7362e..7e567f1e 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go @@ -432,4 +432,14 @@ const ( SYS_SET_MEMPOLICY_HOME_NODE = 4450 SYS_CACHESTAT = 4451 SYS_FCHMODAT2 = 4452 + SYS_MAP_SHADOW_STACK = 4453 + SYS_FUTEX_WAKE = 4454 + SYS_FUTEX_WAIT = 4455 + SYS_FUTEX_REQUEUE = 4456 + SYS_STATMOUNT = 4457 + SYS_LISTMOUNT = 4458 + SYS_LSM_GET_SELF_ATTR = 4459 + SYS_LSM_SET_SELF_ATTR = 4460 + SYS_LSM_LIST_MODULES = 4461 + SYS_MSEAL = 4462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go index cd4d8b4f..38ae55e5 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go @@ -362,4 +362,14 @@ const ( SYS_SET_MEMPOLICY_HOME_NODE = 5450 SYS_CACHESTAT = 5451 SYS_FCHMODAT2 = 5452 + SYS_MAP_SHADOW_STACK = 5453 + SYS_FUTEX_WAKE = 5454 + SYS_FUTEX_WAIT = 5455 + SYS_FUTEX_REQUEUE = 5456 + SYS_STATMOUNT = 5457 + SYS_LISTMOUNT = 5458 + SYS_LSM_GET_SELF_ATTR = 5459 + SYS_LSM_SET_SELF_ATTR = 5460 + SYS_LSM_LIST_MODULES = 5461 + SYS_MSEAL = 5462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go index 2c0efca8..55e92e60 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go @@ -362,4 +362,14 @@ const ( SYS_SET_MEMPOLICY_HOME_NODE = 5450 SYS_CACHESTAT = 5451 SYS_FCHMODAT2 = 5452 + SYS_MAP_SHADOW_STACK = 5453 + SYS_FUTEX_WAKE = 5454 + SYS_FUTEX_WAIT = 5455 + SYS_FUTEX_REQUEUE = 5456 + SYS_STATMOUNT = 5457 + SYS_LISTMOUNT = 5458 + SYS_LSM_GET_SELF_ATTR = 5459 + SYS_LSM_SET_SELF_ATTR = 5460 + SYS_LSM_LIST_MODULES = 5461 + SYS_MSEAL = 5462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go index a72e31d3..60658d6a 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go @@ -432,4 +432,14 @@ const ( SYS_SET_MEMPOLICY_HOME_NODE = 4450 SYS_CACHESTAT = 4451 SYS_FCHMODAT2 = 4452 + SYS_MAP_SHADOW_STACK = 4453 + SYS_FUTEX_WAKE = 4454 + SYS_FUTEX_WAIT = 4455 + SYS_FUTEX_REQUEUE = 4456 + SYS_STATMOUNT = 4457 + SYS_LISTMOUNT = 4458 + SYS_LSM_GET_SELF_ATTR = 4459 + SYS_LSM_SET_SELF_ATTR = 4460 + SYS_LSM_LIST_MODULES = 4461 + SYS_MSEAL = 4462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go index c7d1e374..e203e8a7 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go @@ -439,4 +439,14 @@ const ( SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go index f4d4838c..5944b97d 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go @@ -411,4 +411,14 @@ const ( SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go index b64f0e59..c66d416d 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go @@ -411,4 +411,14 @@ const ( SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go index 95711195..a5459e76 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go @@ -84,7 +84,7 @@ const ( SYS_SPLICE = 76 SYS_TEE = 77 SYS_READLINKAT = 78 - SYS_FSTATAT = 79 + SYS_NEWFSTATAT = 79 SYS_FSTAT = 80 SYS_SYNC = 81 SYS_FSYNC = 82 @@ -316,4 +316,14 @@ const ( SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go index f94e943b..01d86825 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go @@ -377,4 +377,14 @@ const ( SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go index ba0c2bc5..7b703e77 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go @@ -390,4 +390,14 @@ const ( SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go b/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go index b2e30858..5e8c263c 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go @@ -1,2669 +1,2852 @@ -// Copyright 2020 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. +// go run mksyscall_zos_s390x.go -o_sysnum zsysnum_zos_s390x.go -o_syscall zsyscall_zos_s390x.go -i_syscall syscall_zos_s390x.go -o_asm zsymaddr_zos_s390x.s +// Code generated by the command above; see README.md. DO NOT EDIT. //go:build zos && s390x package unix -// TODO: auto-generate. - const ( - SYS_ACOSD128 = 0xB80 - SYS_ACOSD32 = 0xB7E - SYS_ACOSD64 = 0xB7F - SYS_ACOSHD128 = 0xB83 - SYS_ACOSHD32 = 0xB81 - SYS_ACOSHD64 = 0xB82 - SYS_AIO_FSYNC = 0xC69 - SYS_ASCTIME = 0x0AE - SYS_ASCTIME64 = 0xCD7 - SYS_ASCTIME64_R = 0xCD8 - SYS_ASIND128 = 0xB86 - SYS_ASIND32 = 0xB84 - SYS_ASIND64 = 0xB85 - SYS_ASINHD128 = 0xB89 - SYS_ASINHD32 = 0xB87 - SYS_ASINHD64 = 0xB88 - SYS_ATAN2D128 = 0xB8F - SYS_ATAN2D32 = 0xB8D - SYS_ATAN2D64 = 0xB8E - SYS_ATAND128 = 0xB8C - SYS_ATAND32 = 0xB8A - SYS_ATAND64 = 0xB8B - SYS_ATANHD128 = 0xB92 - SYS_ATANHD32 = 0xB90 - SYS_ATANHD64 = 0xB91 - SYS_BIND2ADDRSEL = 0xD59 - SYS_C16RTOMB = 0xD40 - SYS_C32RTOMB = 0xD41 - SYS_CBRTD128 = 0xB95 - SYS_CBRTD32 = 0xB93 - SYS_CBRTD64 = 0xB94 - SYS_CEILD128 = 0xB98 - SYS_CEILD32 = 0xB96 - SYS_CEILD64 = 0xB97 - SYS_CLEARENV = 0x0C9 - SYS_CLEARERR_UNLOCKED = 0xCA1 - SYS_CLOCK = 0x0AA - SYS_CLOGL = 0xA00 - SYS_CLRMEMF = 0x0BD - SYS_CONJ = 0xA03 - SYS_CONJF = 0xA06 - SYS_CONJL = 0xA09 - SYS_COPYSIGND128 = 0xB9E - SYS_COPYSIGND32 = 0xB9C - SYS_COPYSIGND64 = 0xB9D - SYS_COSD128 = 0xBA1 - SYS_COSD32 = 0xB9F - SYS_COSD64 = 0xBA0 - SYS_COSHD128 = 0xBA4 - SYS_COSHD32 = 0xBA2 - SYS_COSHD64 = 0xBA3 - SYS_CPOW = 0xA0C - SYS_CPOWF = 0xA0F - SYS_CPOWL = 0xA12 - SYS_CPROJ = 0xA15 - SYS_CPROJF = 0xA18 - SYS_CPROJL = 0xA1B - SYS_CREAL = 0xA1E - SYS_CREALF = 0xA21 - SYS_CREALL = 0xA24 - SYS_CSIN = 0xA27 - SYS_CSINF = 0xA2A - SYS_CSINH = 0xA30 - SYS_CSINHF = 0xA33 - SYS_CSINHL = 0xA36 - SYS_CSINL = 0xA2D - SYS_CSNAP = 0x0C5 - SYS_CSQRT = 0xA39 - SYS_CSQRTF = 0xA3C - SYS_CSQRTL = 0xA3F - SYS_CTAN = 0xA42 - SYS_CTANF = 0xA45 - SYS_CTANH = 0xA4B - SYS_CTANHF = 0xA4E - SYS_CTANHL = 0xA51 - SYS_CTANL = 0xA48 - SYS_CTIME = 0x0AB - SYS_CTIME64 = 0xCD9 - SYS_CTIME64_R = 0xCDA - SYS_CTRACE = 0x0C6 - SYS_DIFFTIME = 0x0A7 - SYS_DIFFTIME64 = 0xCDB - SYS_DLADDR = 0xC82 - SYS_DYNALLOC = 0x0C3 - SYS_DYNFREE = 0x0C2 - SYS_ERFCD128 = 0xBAA - SYS_ERFCD32 = 0xBA8 - SYS_ERFCD64 = 0xBA9 - SYS_ERFD128 = 0xBA7 - SYS_ERFD32 = 0xBA5 - SYS_ERFD64 = 0xBA6 - SYS_EXP2D128 = 0xBB0 - SYS_EXP2D32 = 0xBAE - SYS_EXP2D64 = 0xBAF - SYS_EXPD128 = 0xBAD - SYS_EXPD32 = 0xBAB - SYS_EXPD64 = 0xBAC - SYS_EXPM1D128 = 0xBB3 - SYS_EXPM1D32 = 0xBB1 - SYS_EXPM1D64 = 0xBB2 - SYS_FABSD128 = 0xBB6 - SYS_FABSD32 = 0xBB4 - SYS_FABSD64 = 0xBB5 - SYS_FDELREC_UNLOCKED = 0xCA2 - SYS_FDIMD128 = 0xBB9 - SYS_FDIMD32 = 0xBB7 - SYS_FDIMD64 = 0xBB8 - SYS_FDOPEN_UNLOCKED = 0xCFC - SYS_FECLEAREXCEPT = 0xAEA - SYS_FEGETENV = 0xAEB - SYS_FEGETEXCEPTFLAG = 0xAEC - SYS_FEGETROUND = 0xAED - SYS_FEHOLDEXCEPT = 0xAEE - SYS_FEOF_UNLOCKED = 0xCA3 - SYS_FERAISEEXCEPT = 0xAEF - SYS_FERROR_UNLOCKED = 0xCA4 - SYS_FESETENV = 0xAF0 - SYS_FESETEXCEPTFLAG = 0xAF1 - SYS_FESETROUND = 0xAF2 - SYS_FETCHEP = 0x0BF - SYS_FETESTEXCEPT = 0xAF3 - SYS_FEUPDATEENV = 0xAF4 - SYS_FE_DEC_GETROUND = 0xBBA - SYS_FE_DEC_SETROUND = 0xBBB - SYS_FFLUSH_UNLOCKED = 0xCA5 - SYS_FGETC_UNLOCKED = 0xC80 - SYS_FGETPOS64 = 0xCEE - SYS_FGETPOS64_UNLOCKED = 0xCF4 - SYS_FGETPOS_UNLOCKED = 0xCA6 - SYS_FGETS_UNLOCKED = 0xC7C - SYS_FGETWC_UNLOCKED = 0xCA7 - SYS_FGETWS_UNLOCKED = 0xCA8 - SYS_FILENO_UNLOCKED = 0xCA9 - SYS_FLDATA = 0x0C1 - SYS_FLDATA_UNLOCKED = 0xCAA - SYS_FLOCATE_UNLOCKED = 0xCAB - SYS_FLOORD128 = 0xBBE - SYS_FLOORD32 = 0xBBC - SYS_FLOORD64 = 0xBBD - SYS_FMA = 0xA63 - SYS_FMAD128 = 0xBC1 - SYS_FMAD32 = 0xBBF - SYS_FMAD64 = 0xBC0 - SYS_FMAF = 0xA66 - SYS_FMAL = 0xA69 - SYS_FMAX = 0xA6C - SYS_FMAXD128 = 0xBC4 - SYS_FMAXD32 = 0xBC2 - SYS_FMAXD64 = 0xBC3 - SYS_FMAXF = 0xA6F - SYS_FMAXL = 0xA72 - SYS_FMIN = 0xA75 - SYS_FMIND128 = 0xBC7 - SYS_FMIND32 = 0xBC5 - SYS_FMIND64 = 0xBC6 - SYS_FMINF = 0xA78 - SYS_FMINL = 0xA7B - SYS_FMODD128 = 0xBCA - SYS_FMODD32 = 0xBC8 - SYS_FMODD64 = 0xBC9 - SYS_FOPEN64 = 0xD49 - SYS_FOPEN64_UNLOCKED = 0xD4A - SYS_FOPEN_UNLOCKED = 0xCFA - SYS_FPRINTF_UNLOCKED = 0xCAC - SYS_FPUTC_UNLOCKED = 0xC81 - SYS_FPUTS_UNLOCKED = 0xC7E - SYS_FPUTWC_UNLOCKED = 0xCAD - SYS_FPUTWS_UNLOCKED = 0xCAE - SYS_FREAD_NOUPDATE = 0xCEC - SYS_FREAD_NOUPDATE_UNLOCKED = 0xCED - SYS_FREAD_UNLOCKED = 0xC7B - SYS_FREEIFADDRS = 0xCE6 - SYS_FREOPEN64 = 0xD4B - SYS_FREOPEN64_UNLOCKED = 0xD4C - SYS_FREOPEN_UNLOCKED = 0xCFB - SYS_FREXPD128 = 0xBCE - SYS_FREXPD32 = 0xBCC - SYS_FREXPD64 = 0xBCD - SYS_FSCANF_UNLOCKED = 0xCAF - SYS_FSEEK64 = 0xCEF - SYS_FSEEK64_UNLOCKED = 0xCF5 - SYS_FSEEKO64 = 0xCF0 - SYS_FSEEKO64_UNLOCKED = 0xCF6 - SYS_FSEEKO_UNLOCKED = 0xCB1 - SYS_FSEEK_UNLOCKED = 0xCB0 - SYS_FSETPOS64 = 0xCF1 - SYS_FSETPOS64_UNLOCKED = 0xCF7 - SYS_FSETPOS_UNLOCKED = 0xCB3 - SYS_FTELL64 = 0xCF2 - SYS_FTELL64_UNLOCKED = 0xCF8 - SYS_FTELLO64 = 0xCF3 - SYS_FTELLO64_UNLOCKED = 0xCF9 - SYS_FTELLO_UNLOCKED = 0xCB5 - SYS_FTELL_UNLOCKED = 0xCB4 - SYS_FUPDATE = 0x0B5 - SYS_FUPDATE_UNLOCKED = 0xCB7 - SYS_FWIDE_UNLOCKED = 0xCB8 - SYS_FWPRINTF_UNLOCKED = 0xCB9 - SYS_FWRITE_UNLOCKED = 0xC7A - SYS_FWSCANF_UNLOCKED = 0xCBA - SYS_GETDATE64 = 0xD4F - SYS_GETIFADDRS = 0xCE7 - SYS_GETIPV4SOURCEFILTER = 0xC77 - SYS_GETSOURCEFILTER = 0xC79 - SYS_GETSYNTX = 0x0FD - SYS_GETS_UNLOCKED = 0xC7D - SYS_GETTIMEOFDAY64 = 0xD50 - SYS_GETWCHAR_UNLOCKED = 0xCBC - SYS_GETWC_UNLOCKED = 0xCBB - SYS_GMTIME = 0x0B0 - SYS_GMTIME64 = 0xCDC - SYS_GMTIME64_R = 0xCDD - SYS_HYPOTD128 = 0xBD1 - SYS_HYPOTD32 = 0xBCF - SYS_HYPOTD64 = 0xBD0 - SYS_ILOGBD128 = 0xBD4 - SYS_ILOGBD32 = 0xBD2 - SYS_ILOGBD64 = 0xBD3 - SYS_ILOGBF = 0xA7E - SYS_ILOGBL = 0xA81 - SYS_INET6_IS_SRCADDR = 0xD5A - SYS_ISBLANK = 0x0FE - SYS_ISWALNUM = 0x0FF - SYS_LDEXPD128 = 0xBD7 - SYS_LDEXPD32 = 0xBD5 - SYS_LDEXPD64 = 0xBD6 - SYS_LGAMMAD128 = 0xBDA - SYS_LGAMMAD32 = 0xBD8 - SYS_LGAMMAD64 = 0xBD9 - SYS_LIO_LISTIO = 0xC6A - SYS_LLRINT = 0xA84 - SYS_LLRINTD128 = 0xBDD - SYS_LLRINTD32 = 0xBDB - SYS_LLRINTD64 = 0xBDC - SYS_LLRINTF = 0xA87 - SYS_LLRINTL = 0xA8A - SYS_LLROUND = 0xA8D - SYS_LLROUNDD128 = 0xBE0 - SYS_LLROUNDD32 = 0xBDE - SYS_LLROUNDD64 = 0xBDF - SYS_LLROUNDF = 0xA90 - SYS_LLROUNDL = 0xA93 - SYS_LOCALTIM = 0x0B1 - SYS_LOCALTIME = 0x0B1 - SYS_LOCALTIME64 = 0xCDE - SYS_LOCALTIME64_R = 0xCDF - SYS_LOG10D128 = 0xBE6 - SYS_LOG10D32 = 0xBE4 - SYS_LOG10D64 = 0xBE5 - SYS_LOG1PD128 = 0xBE9 - SYS_LOG1PD32 = 0xBE7 - SYS_LOG1PD64 = 0xBE8 - SYS_LOG2D128 = 0xBEC - SYS_LOG2D32 = 0xBEA - SYS_LOG2D64 = 0xBEB - SYS_LOGBD128 = 0xBEF - SYS_LOGBD32 = 0xBED - SYS_LOGBD64 = 0xBEE - SYS_LOGBF = 0xA96 - SYS_LOGBL = 0xA99 - SYS_LOGD128 = 0xBE3 - SYS_LOGD32 = 0xBE1 - SYS_LOGD64 = 0xBE2 - SYS_LRINT = 0xA9C - SYS_LRINTD128 = 0xBF2 - SYS_LRINTD32 = 0xBF0 - SYS_LRINTD64 = 0xBF1 - SYS_LRINTF = 0xA9F - SYS_LRINTL = 0xAA2 - SYS_LROUNDD128 = 0xBF5 - SYS_LROUNDD32 = 0xBF3 - SYS_LROUNDD64 = 0xBF4 - SYS_LROUNDL = 0xAA5 - SYS_MBLEN = 0x0AF - SYS_MBRTOC16 = 0xD42 - SYS_MBRTOC32 = 0xD43 - SYS_MEMSET = 0x0A3 - SYS_MKTIME = 0x0AC - SYS_MKTIME64 = 0xCE0 - SYS_MODFD128 = 0xBF8 - SYS_MODFD32 = 0xBF6 - SYS_MODFD64 = 0xBF7 - SYS_NAN = 0xAA8 - SYS_NAND128 = 0xBFB - SYS_NAND32 = 0xBF9 - SYS_NAND64 = 0xBFA - SYS_NANF = 0xAAA - SYS_NANL = 0xAAC - SYS_NEARBYINT = 0xAAE - SYS_NEARBYINTD128 = 0xBFE - SYS_NEARBYINTD32 = 0xBFC - SYS_NEARBYINTD64 = 0xBFD - SYS_NEARBYINTF = 0xAB1 - SYS_NEARBYINTL = 0xAB4 - SYS_NEXTAFTERD128 = 0xC01 - SYS_NEXTAFTERD32 = 0xBFF - SYS_NEXTAFTERD64 = 0xC00 - SYS_NEXTAFTERF = 0xAB7 - SYS_NEXTAFTERL = 0xABA - SYS_NEXTTOWARD = 0xABD - SYS_NEXTTOWARDD128 = 0xC04 - SYS_NEXTTOWARDD32 = 0xC02 - SYS_NEXTTOWARDD64 = 0xC03 - SYS_NEXTTOWARDF = 0xAC0 - SYS_NEXTTOWARDL = 0xAC3 - SYS_NL_LANGINFO = 0x0FC - SYS_PERROR_UNLOCKED = 0xCBD - SYS_POSIX_FALLOCATE = 0xCE8 - SYS_POSIX_MEMALIGN = 0xCE9 - SYS_POSIX_OPENPT = 0xC66 - SYS_POWD128 = 0xC07 - SYS_POWD32 = 0xC05 - SYS_POWD64 = 0xC06 - SYS_PRINTF_UNLOCKED = 0xCBE - SYS_PSELECT = 0xC67 - SYS_PTHREAD_ATTR_GETSTACK = 0xB3E - SYS_PTHREAD_ATTR_SETSTACK = 0xB3F - SYS_PTHREAD_SECURITY_APPLID_NP = 0xCE4 - SYS_PUTS_UNLOCKED = 0xC7F - SYS_PUTWCHAR_UNLOCKED = 0xCC0 - SYS_PUTWC_UNLOCKED = 0xCBF - SYS_QUANTEXPD128 = 0xD46 - SYS_QUANTEXPD32 = 0xD44 - SYS_QUANTEXPD64 = 0xD45 - SYS_QUANTIZED128 = 0xC0A - SYS_QUANTIZED32 = 0xC08 - SYS_QUANTIZED64 = 0xC09 - SYS_REMAINDERD128 = 0xC0D - SYS_REMAINDERD32 = 0xC0B - SYS_REMAINDERD64 = 0xC0C - SYS_RESIZE_ALLOC = 0xCEB - SYS_REWIND_UNLOCKED = 0xCC1 - SYS_RINTD128 = 0xC13 - SYS_RINTD32 = 0xC11 - SYS_RINTD64 = 0xC12 - SYS_RINTF = 0xACB - SYS_RINTL = 0xACD - SYS_ROUND = 0xACF - SYS_ROUNDD128 = 0xC16 - SYS_ROUNDD32 = 0xC14 - SYS_ROUNDD64 = 0xC15 - SYS_ROUNDF = 0xAD2 - SYS_ROUNDL = 0xAD5 - SYS_SAMEQUANTUMD128 = 0xC19 - SYS_SAMEQUANTUMD32 = 0xC17 - SYS_SAMEQUANTUMD64 = 0xC18 - SYS_SCALBLN = 0xAD8 - SYS_SCALBLND128 = 0xC1C - SYS_SCALBLND32 = 0xC1A - SYS_SCALBLND64 = 0xC1B - SYS_SCALBLNF = 0xADB - SYS_SCALBLNL = 0xADE - SYS_SCALBND128 = 0xC1F - SYS_SCALBND32 = 0xC1D - SYS_SCALBND64 = 0xC1E - SYS_SCALBNF = 0xAE3 - SYS_SCALBNL = 0xAE6 - SYS_SCANF_UNLOCKED = 0xCC2 - SYS_SCHED_YIELD = 0xB32 - SYS_SETENV = 0x0C8 - SYS_SETIPV4SOURCEFILTER = 0xC76 - SYS_SETSOURCEFILTER = 0xC78 - SYS_SHM_OPEN = 0xC8C - SYS_SHM_UNLINK = 0xC8D - SYS_SIND128 = 0xC22 - SYS_SIND32 = 0xC20 - SYS_SIND64 = 0xC21 - SYS_SINHD128 = 0xC25 - SYS_SINHD32 = 0xC23 - SYS_SINHD64 = 0xC24 - SYS_SIZEOF_ALLOC = 0xCEA - SYS_SOCKATMARK = 0xC68 - SYS_SQRTD128 = 0xC28 - SYS_SQRTD32 = 0xC26 - SYS_SQRTD64 = 0xC27 - SYS_STRCHR = 0x0A0 - SYS_STRCSPN = 0x0A1 - SYS_STRERROR = 0x0A8 - SYS_STRERROR_R = 0xB33 - SYS_STRFTIME = 0x0B2 - SYS_STRLEN = 0x0A9 - SYS_STRPBRK = 0x0A2 - SYS_STRSPN = 0x0A4 - SYS_STRSTR = 0x0A5 - SYS_STRTOD128 = 0xC2B - SYS_STRTOD32 = 0xC29 - SYS_STRTOD64 = 0xC2A - SYS_STRTOK = 0x0A6 - SYS_TAND128 = 0xC2E - SYS_TAND32 = 0xC2C - SYS_TAND64 = 0xC2D - SYS_TANHD128 = 0xC31 - SYS_TANHD32 = 0xC2F - SYS_TANHD64 = 0xC30 - SYS_TGAMMAD128 = 0xC34 - SYS_TGAMMAD32 = 0xC32 - SYS_TGAMMAD64 = 0xC33 - SYS_TIME = 0x0AD - SYS_TIME64 = 0xCE1 - SYS_TMPFILE64 = 0xD4D - SYS_TMPFILE64_UNLOCKED = 0xD4E - SYS_TMPFILE_UNLOCKED = 0xCFD - SYS_TRUNCD128 = 0xC40 - SYS_TRUNCD32 = 0xC3E - SYS_TRUNCD64 = 0xC3F - SYS_UNGETC_UNLOCKED = 0xCC3 - SYS_UNGETWC_UNLOCKED = 0xCC4 - SYS_UNSETENV = 0xB34 - SYS_VFPRINTF_UNLOCKED = 0xCC5 - SYS_VFSCANF_UNLOCKED = 0xCC7 - SYS_VFWPRINTF_UNLOCKED = 0xCC9 - SYS_VFWSCANF_UNLOCKED = 0xCCB - SYS_VPRINTF_UNLOCKED = 0xCCD - SYS_VSCANF_UNLOCKED = 0xCCF - SYS_VWPRINTF_UNLOCKED = 0xCD1 - SYS_VWSCANF_UNLOCKED = 0xCD3 - SYS_WCSTOD128 = 0xC43 - SYS_WCSTOD32 = 0xC41 - SYS_WCSTOD64 = 0xC42 - SYS_WPRINTF_UNLOCKED = 0xCD5 - SYS_WSCANF_UNLOCKED = 0xCD6 - SYS__FLUSHLBF = 0xD68 - SYS__FLUSHLBF_UNLOCKED = 0xD6F - SYS___ACOSHF_H = 0xA54 - SYS___ACOSHL_H = 0xA55 - SYS___ASINHF_H = 0xA56 - SYS___ASINHL_H = 0xA57 - SYS___ATANPID128 = 0xC6D - SYS___ATANPID32 = 0xC6B - SYS___ATANPID64 = 0xC6C - SYS___CBRTF_H = 0xA58 - SYS___CBRTL_H = 0xA59 - SYS___CDUMP = 0x0C4 - SYS___CLASS = 0xAFA - SYS___CLASS2 = 0xB99 - SYS___CLASS2D128 = 0xC99 - SYS___CLASS2D32 = 0xC97 - SYS___CLASS2D64 = 0xC98 - SYS___CLASS2F = 0xC91 - SYS___CLASS2F_B = 0xC93 - SYS___CLASS2F_H = 0xC94 - SYS___CLASS2L = 0xC92 - SYS___CLASS2L_B = 0xC95 - SYS___CLASS2L_H = 0xC96 - SYS___CLASS2_B = 0xB9A - SYS___CLASS2_H = 0xB9B - SYS___CLASS_B = 0xAFB - SYS___CLASS_H = 0xAFC - SYS___CLOGL_B = 0xA01 - SYS___CLOGL_H = 0xA02 - SYS___CLRENV = 0x0C9 - SYS___CLRMF = 0x0BD - SYS___CODEPAGE_INFO = 0xC64 - SYS___CONJF_B = 0xA07 - SYS___CONJF_H = 0xA08 - SYS___CONJL_B = 0xA0A - SYS___CONJL_H = 0xA0B - SYS___CONJ_B = 0xA04 - SYS___CONJ_H = 0xA05 - SYS___COPYSIGN_B = 0xA5A - SYS___COPYSIGN_H = 0xAF5 - SYS___COSPID128 = 0xC70 - SYS___COSPID32 = 0xC6E - SYS___COSPID64 = 0xC6F - SYS___CPOWF_B = 0xA10 - SYS___CPOWF_H = 0xA11 - SYS___CPOWL_B = 0xA13 - SYS___CPOWL_H = 0xA14 - SYS___CPOW_B = 0xA0D - SYS___CPOW_H = 0xA0E - SYS___CPROJF_B = 0xA19 - SYS___CPROJF_H = 0xA1A - SYS___CPROJL_B = 0xA1C - SYS___CPROJL_H = 0xA1D - SYS___CPROJ_B = 0xA16 - SYS___CPROJ_H = 0xA17 - SYS___CREALF_B = 0xA22 - SYS___CREALF_H = 0xA23 - SYS___CREALL_B = 0xA25 - SYS___CREALL_H = 0xA26 - SYS___CREAL_B = 0xA1F - SYS___CREAL_H = 0xA20 - SYS___CSINF_B = 0xA2B - SYS___CSINF_H = 0xA2C - SYS___CSINHF_B = 0xA34 - SYS___CSINHF_H = 0xA35 - SYS___CSINHL_B = 0xA37 - SYS___CSINHL_H = 0xA38 - SYS___CSINH_B = 0xA31 - SYS___CSINH_H = 0xA32 - SYS___CSINL_B = 0xA2E - SYS___CSINL_H = 0xA2F - SYS___CSIN_B = 0xA28 - SYS___CSIN_H = 0xA29 - SYS___CSNAP = 0x0C5 - SYS___CSQRTF_B = 0xA3D - SYS___CSQRTF_H = 0xA3E - SYS___CSQRTL_B = 0xA40 - SYS___CSQRTL_H = 0xA41 - SYS___CSQRT_B = 0xA3A - SYS___CSQRT_H = 0xA3B - SYS___CTANF_B = 0xA46 - SYS___CTANF_H = 0xA47 - SYS___CTANHF_B = 0xA4F - SYS___CTANHF_H = 0xA50 - SYS___CTANHL_B = 0xA52 - SYS___CTANHL_H = 0xA53 - SYS___CTANH_B = 0xA4C - SYS___CTANH_H = 0xA4D - SYS___CTANL_B = 0xA49 - SYS___CTANL_H = 0xA4A - SYS___CTAN_B = 0xA43 - SYS___CTAN_H = 0xA44 - SYS___CTEST = 0x0C7 - SYS___CTRACE = 0x0C6 - SYS___D1TOP = 0xC9B - SYS___D2TOP = 0xC9C - SYS___D4TOP = 0xC9D - SYS___DYNALL = 0x0C3 - SYS___DYNFRE = 0x0C2 - SYS___EXP2F_H = 0xA5E - SYS___EXP2L_H = 0xA5F - SYS___EXP2_H = 0xA5D - SYS___EXPM1F_H = 0xA5B - SYS___EXPM1L_H = 0xA5C - SYS___FBUFSIZE = 0xD60 - SYS___FLBF = 0xD62 - SYS___FLDATA = 0x0C1 - SYS___FMAF_B = 0xA67 - SYS___FMAF_H = 0xA68 - SYS___FMAL_B = 0xA6A - SYS___FMAL_H = 0xA6B - SYS___FMAXF_B = 0xA70 - SYS___FMAXF_H = 0xA71 - SYS___FMAXL_B = 0xA73 - SYS___FMAXL_H = 0xA74 - SYS___FMAX_B = 0xA6D - SYS___FMAX_H = 0xA6E - SYS___FMA_B = 0xA64 - SYS___FMA_H = 0xA65 - SYS___FMINF_B = 0xA79 - SYS___FMINF_H = 0xA7A - SYS___FMINL_B = 0xA7C - SYS___FMINL_H = 0xA7D - SYS___FMIN_B = 0xA76 - SYS___FMIN_H = 0xA77 - SYS___FPENDING = 0xD61 - SYS___FPENDING_UNLOCKED = 0xD6C - SYS___FPURGE = 0xD69 - SYS___FPURGE_UNLOCKED = 0xD70 - SYS___FP_CAST_D = 0xBCB - SYS___FREADABLE = 0xD63 - SYS___FREADAHEAD = 0xD6A - SYS___FREADAHEAD_UNLOCKED = 0xD71 - SYS___FREADING = 0xD65 - SYS___FREADING_UNLOCKED = 0xD6D - SYS___FSEEK2 = 0xB3C - SYS___FSETERR = 0xD6B - SYS___FSETLOCKING = 0xD67 - SYS___FTCHEP = 0x0BF - SYS___FTELL2 = 0xB3B - SYS___FUPDT = 0x0B5 - SYS___FWRITABLE = 0xD64 - SYS___FWRITING = 0xD66 - SYS___FWRITING_UNLOCKED = 0xD6E - SYS___GETCB = 0x0B4 - SYS___GETGRGID1 = 0xD5B - SYS___GETGRNAM1 = 0xD5C - SYS___GETTHENT = 0xCE5 - SYS___GETTOD = 0xD3E - SYS___HYPOTF_H = 0xAF6 - SYS___HYPOTL_H = 0xAF7 - SYS___ILOGBF_B = 0xA7F - SYS___ILOGBF_H = 0xA80 - SYS___ILOGBL_B = 0xA82 - SYS___ILOGBL_H = 0xA83 - SYS___ISBLANK_A = 0xB2E - SYS___ISBLNK = 0x0FE - SYS___ISWBLANK_A = 0xB2F - SYS___LE_CEEGTJS = 0xD72 - SYS___LE_TRACEBACK = 0xB7A - SYS___LGAMMAL_H = 0xA62 - SYS___LGAMMA_B_C99 = 0xB39 - SYS___LGAMMA_H_C99 = 0xB38 - SYS___LGAMMA_R_C99 = 0xB3A - SYS___LLRINTF_B = 0xA88 - SYS___LLRINTF_H = 0xA89 - SYS___LLRINTL_B = 0xA8B - SYS___LLRINTL_H = 0xA8C - SYS___LLRINT_B = 0xA85 - SYS___LLRINT_H = 0xA86 - SYS___LLROUNDF_B = 0xA91 - SYS___LLROUNDF_H = 0xA92 - SYS___LLROUNDL_B = 0xA94 - SYS___LLROUNDL_H = 0xA95 - SYS___LLROUND_B = 0xA8E - SYS___LLROUND_H = 0xA8F - SYS___LOCALE_CTL = 0xD47 - SYS___LOG1PF_H = 0xA60 - SYS___LOG1PL_H = 0xA61 - SYS___LOGBF_B = 0xA97 - SYS___LOGBF_H = 0xA98 - SYS___LOGBL_B = 0xA9A - SYS___LOGBL_H = 0xA9B - SYS___LOGIN_APPLID = 0xCE2 - SYS___LRINTF_B = 0xAA0 - SYS___LRINTF_H = 0xAA1 - SYS___LRINTL_B = 0xAA3 - SYS___LRINTL_H = 0xAA4 - SYS___LRINT_B = 0xA9D - SYS___LRINT_H = 0xA9E - SYS___LROUNDF_FIXUP = 0xB31 - SYS___LROUNDL_B = 0xAA6 - SYS___LROUNDL_H = 0xAA7 - SYS___LROUND_FIXUP = 0xB30 - SYS___MOSERVICES = 0xD3D - SYS___MUST_STAY_CLEAN = 0xB7C - SYS___NANF_B = 0xAAB - SYS___NANL_B = 0xAAD - SYS___NAN_B = 0xAA9 - SYS___NEARBYINTF_B = 0xAB2 - SYS___NEARBYINTF_H = 0xAB3 - SYS___NEARBYINTL_B = 0xAB5 - SYS___NEARBYINTL_H = 0xAB6 - SYS___NEARBYINT_B = 0xAAF - SYS___NEARBYINT_H = 0xAB0 - SYS___NEXTAFTERF_B = 0xAB8 - SYS___NEXTAFTERF_H = 0xAB9 - SYS___NEXTAFTERL_B = 0xABB - SYS___NEXTAFTERL_H = 0xABC - SYS___NEXTTOWARDF_B = 0xAC1 - SYS___NEXTTOWARDF_H = 0xAC2 - SYS___NEXTTOWARDL_B = 0xAC4 - SYS___NEXTTOWARDL_H = 0xAC5 - SYS___NEXTTOWARD_B = 0xABE - SYS___NEXTTOWARD_H = 0xABF - SYS___O_ENV = 0xB7D - SYS___PASSWD_APPLID = 0xCE3 - SYS___PTOD1 = 0xC9E - SYS___PTOD2 = 0xC9F - SYS___PTOD4 = 0xCA0 - SYS___REGCOMP_STD = 0x0EA - SYS___REMAINDERF_H = 0xAC6 - SYS___REMAINDERL_H = 0xAC7 - SYS___REMQUOD128 = 0xC10 - SYS___REMQUOD32 = 0xC0E - SYS___REMQUOD64 = 0xC0F - SYS___REMQUOF_H = 0xAC9 - SYS___REMQUOL_H = 0xACA - SYS___REMQUO_H = 0xAC8 - SYS___RINTF_B = 0xACC - SYS___RINTL_B = 0xACE - SYS___ROUNDF_B = 0xAD3 - SYS___ROUNDF_H = 0xAD4 - SYS___ROUNDL_B = 0xAD6 - SYS___ROUNDL_H = 0xAD7 - SYS___ROUND_B = 0xAD0 - SYS___ROUND_H = 0xAD1 - SYS___SCALBLNF_B = 0xADC - SYS___SCALBLNF_H = 0xADD - SYS___SCALBLNL_B = 0xADF - SYS___SCALBLNL_H = 0xAE0 - SYS___SCALBLN_B = 0xAD9 - SYS___SCALBLN_H = 0xADA - SYS___SCALBNF_B = 0xAE4 - SYS___SCALBNF_H = 0xAE5 - SYS___SCALBNL_B = 0xAE7 - SYS___SCALBNL_H = 0xAE8 - SYS___SCALBN_B = 0xAE1 - SYS___SCALBN_H = 0xAE2 - SYS___SETENV = 0x0C8 - SYS___SINPID128 = 0xC73 - SYS___SINPID32 = 0xC71 - SYS___SINPID64 = 0xC72 - SYS___SMF_RECORD2 = 0xD48 - SYS___STATIC_REINIT = 0xB3D - SYS___TGAMMAF_H_C99 = 0xB79 - SYS___TGAMMAL_H = 0xAE9 - SYS___TGAMMA_H_C99 = 0xB78 - SYS___TOCSNAME2 = 0xC9A - SYS_CEIL = 0x01F - SYS_CHAUDIT = 0x1E0 - SYS_EXP = 0x01A - SYS_FCHAUDIT = 0x1E1 - SYS_FREXP = 0x01D - SYS_GETGROUPSBYNAME = 0x1E2 - SYS_GETPWUID = 0x1A0 - SYS_GETUID = 0x1A1 - SYS_ISATTY = 0x1A3 - SYS_KILL = 0x1A4 - SYS_LDEXP = 0x01E - SYS_LINK = 0x1A5 - SYS_LOG10 = 0x01C - SYS_LSEEK = 0x1A6 - SYS_LSTAT = 0x1A7 - SYS_MKDIR = 0x1A8 - SYS_MKFIFO = 0x1A9 - SYS_MKNOD = 0x1AA - SYS_MODF = 0x01B - SYS_MOUNT = 0x1AB - SYS_OPEN = 0x1AC - SYS_OPENDIR = 0x1AD - SYS_PATHCONF = 0x1AE - SYS_PAUSE = 0x1AF - SYS_PIPE = 0x1B0 - SYS_PTHREAD_ATTR_DESTROY = 0x1E7 - SYS_PTHREAD_ATTR_GETDETACHSTATE = 0x1EB - SYS_PTHREAD_ATTR_GETSTACKSIZE = 0x1E9 - SYS_PTHREAD_ATTR_GETWEIGHT_NP = 0x1ED - SYS_PTHREAD_ATTR_INIT = 0x1E6 - SYS_PTHREAD_ATTR_SETDETACHSTATE = 0x1EA - SYS_PTHREAD_ATTR_SETSTACKSIZE = 0x1E8 - SYS_PTHREAD_ATTR_SETWEIGHT_NP = 0x1EC - SYS_PTHREAD_CANCEL = 0x1EE - SYS_PTHREAD_CLEANUP_POP = 0x1F0 - SYS_PTHREAD_CLEANUP_PUSH = 0x1EF - SYS_PTHREAD_CONDATTR_DESTROY = 0x1F2 - SYS_PTHREAD_CONDATTR_INIT = 0x1F1 - SYS_PTHREAD_COND_BROADCAST = 0x1F6 - SYS_PTHREAD_COND_DESTROY = 0x1F4 - SYS_PTHREAD_COND_INIT = 0x1F3 - SYS_PTHREAD_COND_SIGNAL = 0x1F5 - SYS_PTHREAD_COND_TIMEDWAIT = 0x1F8 - SYS_PTHREAD_COND_WAIT = 0x1F7 - SYS_PTHREAD_CREATE = 0x1F9 - SYS_PTHREAD_DETACH = 0x1FA - SYS_PTHREAD_EQUAL = 0x1FB - SYS_PTHREAD_EXIT = 0x1E4 - SYS_PTHREAD_GETSPECIFIC = 0x1FC - SYS_PTHREAD_JOIN = 0x1FD - SYS_PTHREAD_KEY_CREATE = 0x1FE - SYS_PTHREAD_KILL = 0x1E5 - SYS_PTHREAD_MUTEXATTR_INIT = 0x1FF - SYS_READ = 0x1B2 - SYS_READDIR = 0x1B3 - SYS_READLINK = 0x1B4 - SYS_REWINDDIR = 0x1B5 - SYS_RMDIR = 0x1B6 - SYS_SETEGID = 0x1B7 - SYS_SETEUID = 0x1B8 - SYS_SETGID = 0x1B9 - SYS_SETPGID = 0x1BA - SYS_SETSID = 0x1BB - SYS_SETUID = 0x1BC - SYS_SIGACTION = 0x1BD - SYS_SIGADDSET = 0x1BE - SYS_SIGDELSET = 0x1BF - SYS_SIGEMPTYSET = 0x1C0 - SYS_SIGFILLSET = 0x1C1 - SYS_SIGISMEMBER = 0x1C2 - SYS_SIGLONGJMP = 0x1C3 - SYS_SIGPENDING = 0x1C4 - SYS_SIGPROCMASK = 0x1C5 - SYS_SIGSETJMP = 0x1C6 - SYS_SIGSUSPEND = 0x1C7 - SYS_SIGWAIT = 0x1E3 - SYS_SLEEP = 0x1C8 - SYS_STAT = 0x1C9 - SYS_SYMLINK = 0x1CB - SYS_SYSCONF = 0x1CC - SYS_TCDRAIN = 0x1CD - SYS_TCFLOW = 0x1CE - SYS_TCFLUSH = 0x1CF - SYS_TCGETATTR = 0x1D0 - SYS_TCGETPGRP = 0x1D1 - SYS_TCSENDBREAK = 0x1D2 - SYS_TCSETATTR = 0x1D3 - SYS_TCSETPGRP = 0x1D4 - SYS_TIMES = 0x1D5 - SYS_TTYNAME = 0x1D6 - SYS_TZSET = 0x1D7 - SYS_UMASK = 0x1D8 - SYS_UMOUNT = 0x1D9 - SYS_UNAME = 0x1DA - SYS_UNLINK = 0x1DB - SYS_UTIME = 0x1DC - SYS_WAIT = 0x1DD - SYS_WAITPID = 0x1DE - SYS_WRITE = 0x1DF - SYS_W_GETPSENT = 0x1B1 - SYS_W_IOCTL = 0x1A2 - SYS_W_STATFS = 0x1CA - SYS_A64L = 0x2EF - SYS_BCMP = 0x2B9 - SYS_BCOPY = 0x2BA - SYS_BZERO = 0x2BB - SYS_CATCLOSE = 0x2B6 - SYS_CATGETS = 0x2B7 - SYS_CATOPEN = 0x2B8 - SYS_CRYPT = 0x2AC - SYS_DBM_CLEARERR = 0x2F7 - SYS_DBM_CLOSE = 0x2F8 - SYS_DBM_DELETE = 0x2F9 - SYS_DBM_ERROR = 0x2FA - SYS_DBM_FETCH = 0x2FB - SYS_DBM_FIRSTKEY = 0x2FC - SYS_DBM_NEXTKEY = 0x2FD - SYS_DBM_OPEN = 0x2FE - SYS_DBM_STORE = 0x2FF - SYS_DRAND48 = 0x2B2 - SYS_ENCRYPT = 0x2AD - SYS_ENDUTXENT = 0x2E1 - SYS_ERAND48 = 0x2B3 - SYS_ERF = 0x02C - SYS_ERFC = 0x02D - SYS_FCHDIR = 0x2D9 - SYS_FFS = 0x2BC - SYS_FMTMSG = 0x2E5 - SYS_FSTATVFS = 0x2B4 - SYS_FTIME = 0x2F5 - SYS_GAMMA = 0x02E - SYS_GETDATE = 0x2A6 - SYS_GETPAGESIZE = 0x2D8 - SYS_GETTIMEOFDAY = 0x2F6 - SYS_GETUTXENT = 0x2E0 - SYS_GETUTXID = 0x2E2 - SYS_GETUTXLINE = 0x2E3 - SYS_HCREATE = 0x2C6 - SYS_HDESTROY = 0x2C7 - SYS_HSEARCH = 0x2C8 - SYS_HYPOT = 0x02B - SYS_INDEX = 0x2BD - SYS_INITSTATE = 0x2C2 - SYS_INSQUE = 0x2CF - SYS_ISASCII = 0x2ED - SYS_JRAND48 = 0x2E6 - SYS_L64A = 0x2F0 - SYS_LCONG48 = 0x2EA - SYS_LFIND = 0x2C9 - SYS_LRAND48 = 0x2E7 - SYS_LSEARCH = 0x2CA - SYS_MEMCCPY = 0x2D4 - SYS_MRAND48 = 0x2E8 - SYS_NRAND48 = 0x2E9 - SYS_PCLOSE = 0x2D2 - SYS_POPEN = 0x2D1 - SYS_PUTUTXLINE = 0x2E4 - SYS_RANDOM = 0x2C4 - SYS_REMQUE = 0x2D0 - SYS_RINDEX = 0x2BE - SYS_SEED48 = 0x2EC - SYS_SETKEY = 0x2AE - SYS_SETSTATE = 0x2C3 - SYS_SETUTXENT = 0x2DF - SYS_SRAND48 = 0x2EB - SYS_SRANDOM = 0x2C5 - SYS_STATVFS = 0x2B5 - SYS_STRCASECMP = 0x2BF - SYS_STRDUP = 0x2C0 - SYS_STRNCASECMP = 0x2C1 - SYS_SWAB = 0x2D3 - SYS_TDELETE = 0x2CB - SYS_TFIND = 0x2CC - SYS_TOASCII = 0x2EE - SYS_TSEARCH = 0x2CD - SYS_TWALK = 0x2CE - SYS_UALARM = 0x2F1 - SYS_USLEEP = 0x2F2 - SYS_WAIT3 = 0x2A7 - SYS_WAITID = 0x2A8 - SYS_Y1 = 0x02A - SYS___ATOE = 0x2DB - SYS___ATOE_L = 0x2DC - SYS___CATTRM = 0x2A9 - SYS___CNVBLK = 0x2AF - SYS___CRYTRM = 0x2B0 - SYS___DLGHT = 0x2A1 - SYS___ECRTRM = 0x2B1 - SYS___ETOA = 0x2DD - SYS___ETOA_L = 0x2DE - SYS___GDTRM = 0x2AA - SYS___OCLCK = 0x2DA - SYS___OPARGF = 0x2A2 - SYS___OPERRF = 0x2A5 - SYS___OPINDF = 0x2A4 - SYS___OPOPTF = 0x2A3 - SYS___RNDTRM = 0x2AB - SYS___SRCTRM = 0x2F4 - SYS___TZONE = 0x2A0 - SYS___UTXTRM = 0x2F3 - SYS_ASIN = 0x03E - SYS_ISXDIGIT = 0x03B - SYS_SETLOCAL = 0x03A - SYS_SETLOCALE = 0x03A - SYS_SIN = 0x03F - SYS_TOLOWER = 0x03C - SYS_TOUPPER = 0x03D - SYS_ACCEPT_AND_RECV = 0x4F7 - SYS_ATOL = 0x04E - SYS_CHECKSCH = 0x4BC - SYS_CHECKSCHENV = 0x4BC - SYS_CLEARERR = 0x04C - SYS_CONNECTS = 0x4B5 - SYS_CONNECTSERVER = 0x4B5 - SYS_CONNECTW = 0x4B4 - SYS_CONNECTWORKMGR = 0x4B4 - SYS_CONTINUE = 0x4B3 - SYS_CONTINUEWORKUNIT = 0x4B3 - SYS_COPYSIGN = 0x4C2 - SYS_CREATEWO = 0x4B2 - SYS_CREATEWORKUNIT = 0x4B2 - SYS_DELETEWO = 0x4B9 - SYS_DELETEWORKUNIT = 0x4B9 - SYS_DISCONNE = 0x4B6 - SYS_DISCONNECTSERVER = 0x4B6 - SYS_FEOF = 0x04D - SYS_FERROR = 0x04A - SYS_FINITE = 0x4C8 - SYS_GAMMA_R = 0x4E2 - SYS_JOINWORK = 0x4B7 - SYS_JOINWORKUNIT = 0x4B7 - SYS_LEAVEWOR = 0x4B8 - SYS_LEAVEWORKUNIT = 0x4B8 - SYS_LGAMMA_R = 0x4EB - SYS_MATHERR = 0x4D0 - SYS_PERROR = 0x04F - SYS_QUERYMET = 0x4BA - SYS_QUERYMETRICS = 0x4BA - SYS_QUERYSCH = 0x4BB - SYS_QUERYSCHENV = 0x4BB - SYS_REWIND = 0x04B - SYS_SCALBN = 0x4D4 - SYS_SIGNIFIC = 0x4D5 - SYS_SIGNIFICAND = 0x4D5 - SYS___ACOSH_B = 0x4DA - SYS___ACOS_B = 0x4D9 - SYS___ASINH_B = 0x4BE - SYS___ASIN_B = 0x4DB - SYS___ATAN2_B = 0x4DC - SYS___ATANH_B = 0x4DD - SYS___ATAN_B = 0x4BF - SYS___CBRT_B = 0x4C0 - SYS___CEIL_B = 0x4C1 - SYS___COSH_B = 0x4DE - SYS___COS_B = 0x4C3 - SYS___DGHT = 0x4A8 - SYS___ENVN = 0x4B0 - SYS___ERFC_B = 0x4C5 - SYS___ERF_B = 0x4C4 - SYS___EXPM1_B = 0x4C6 - SYS___EXP_B = 0x4DF - SYS___FABS_B = 0x4C7 - SYS___FLOOR_B = 0x4C9 - SYS___FMOD_B = 0x4E0 - SYS___FP_SETMODE = 0x4F8 - SYS___FREXP_B = 0x4CA - SYS___GAMMA_B = 0x4E1 - SYS___GDRR = 0x4A1 - SYS___HRRNO = 0x4A2 - SYS___HYPOT_B = 0x4E3 - SYS___ILOGB_B = 0x4CB - SYS___ISNAN_B = 0x4CC - SYS___J0_B = 0x4E4 - SYS___J1_B = 0x4E6 - SYS___JN_B = 0x4E8 - SYS___LDEXP_B = 0x4CD - SYS___LGAMMA_B = 0x4EA - SYS___LOG10_B = 0x4ED - SYS___LOG1P_B = 0x4CE - SYS___LOGB_B = 0x4CF - SYS___LOGIN = 0x4F5 - SYS___LOG_B = 0x4EC - SYS___MLOCKALL = 0x4B1 - SYS___MODF_B = 0x4D1 - SYS___NEXTAFTER_B = 0x4D2 - SYS___OPENDIR2 = 0x4F3 - SYS___OPEN_STAT = 0x4F6 - SYS___OPND = 0x4A5 - SYS___OPPT = 0x4A6 - SYS___OPRG = 0x4A3 - SYS___OPRR = 0x4A4 - SYS___PID_AFFINITY = 0x4BD - SYS___POW_B = 0x4EE - SYS___READDIR2 = 0x4F4 - SYS___REMAINDER_B = 0x4EF - SYS___RINT_B = 0x4D3 - SYS___SCALB_B = 0x4F0 - SYS___SIGACTIONSET = 0x4FB - SYS___SIGGM = 0x4A7 - SYS___SINH_B = 0x4F1 - SYS___SIN_B = 0x4D6 - SYS___SQRT_B = 0x4F2 - SYS___TANH_B = 0x4D8 - SYS___TAN_B = 0x4D7 - SYS___TRRNO = 0x4AF - SYS___TZNE = 0x4A9 - SYS___TZZN = 0x4AA - SYS___UCREATE = 0x4FC - SYS___UFREE = 0x4FE - SYS___UHEAPREPORT = 0x4FF - SYS___UMALLOC = 0x4FD - SYS___Y0_B = 0x4E5 - SYS___Y1_B = 0x4E7 - SYS___YN_B = 0x4E9 - SYS_ABORT = 0x05C - SYS_ASCTIME_R = 0x5E0 - SYS_ATEXIT = 0x05D - SYS_CONNECTE = 0x5AE - SYS_CONNECTEXPORTIMPORT = 0x5AE - SYS_CTIME_R = 0x5E1 - SYS_DN_COMP = 0x5DF - SYS_DN_EXPAND = 0x5DD - SYS_DN_SKIPNAME = 0x5DE - SYS_EXIT = 0x05A - SYS_EXPORTWO = 0x5A1 - SYS_EXPORTWORKUNIT = 0x5A1 - SYS_EXTRACTW = 0x5A5 - SYS_EXTRACTWORKUNIT = 0x5A5 - SYS_FSEEKO = 0x5C9 - SYS_FTELLO = 0x5C8 - SYS_GETGRGID_R = 0x5E7 - SYS_GETGRNAM_R = 0x5E8 - SYS_GETLOGIN_R = 0x5E9 - SYS_GETPWNAM_R = 0x5EA - SYS_GETPWUID_R = 0x5EB - SYS_GMTIME_R = 0x5E2 - SYS_IMPORTWO = 0x5A3 - SYS_IMPORTWORKUNIT = 0x5A3 - SYS_INET_NTOP = 0x5D3 - SYS_INET_PTON = 0x5D4 - SYS_LLABS = 0x5CE - SYS_LLDIV = 0x5CB - SYS_LOCALTIME_R = 0x5E3 - SYS_PTHREAD_ATFORK = 0x5ED - SYS_PTHREAD_ATTR_GETDETACHSTATE_U98 = 0x5FB - SYS_PTHREAD_ATTR_GETGUARDSIZE = 0x5EE - SYS_PTHREAD_ATTR_GETSCHEDPARAM = 0x5F9 - SYS_PTHREAD_ATTR_GETSTACKADDR = 0x5EF - SYS_PTHREAD_ATTR_SETDETACHSTATE_U98 = 0x5FC - SYS_PTHREAD_ATTR_SETGUARDSIZE = 0x5F0 - SYS_PTHREAD_ATTR_SETSCHEDPARAM = 0x5FA - SYS_PTHREAD_ATTR_SETSTACKADDR = 0x5F1 - SYS_PTHREAD_CONDATTR_GETPSHARED = 0x5F2 - SYS_PTHREAD_CONDATTR_SETPSHARED = 0x5F3 - SYS_PTHREAD_DETACH_U98 = 0x5FD - SYS_PTHREAD_GETCONCURRENCY = 0x5F4 - SYS_PTHREAD_GETSPECIFIC_U98 = 0x5FE - SYS_PTHREAD_KEY_DELETE = 0x5F5 - SYS_PTHREAD_SETCANCELSTATE = 0x5FF - SYS_PTHREAD_SETCONCURRENCY = 0x5F6 - SYS_PTHREAD_SIGMASK = 0x5F7 - SYS_QUERYENC = 0x5AD - SYS_QUERYWORKUNITCLASSIFICATION = 0x5AD - SYS_RAISE = 0x05E - SYS_RAND_R = 0x5E4 - SYS_READDIR_R = 0x5E6 - SYS_REALLOC = 0x05B - SYS_RES_INIT = 0x5D8 - SYS_RES_MKQUERY = 0x5D7 - SYS_RES_QUERY = 0x5D9 - SYS_RES_QUERYDOMAIN = 0x5DC - SYS_RES_SEARCH = 0x5DA - SYS_RES_SEND = 0x5DB - SYS_SETJMP = 0x05F - SYS_SIGQUEUE = 0x5A9 - SYS_STRTOK_R = 0x5E5 - SYS_STRTOLL = 0x5B0 - SYS_STRTOULL = 0x5B1 - SYS_TTYNAME_R = 0x5EC - SYS_UNDOEXPO = 0x5A2 - SYS_UNDOEXPORTWORKUNIT = 0x5A2 - SYS_UNDOIMPO = 0x5A4 - SYS_UNDOIMPORTWORKUNIT = 0x5A4 - SYS_WCSTOLL = 0x5CC - SYS_WCSTOULL = 0x5CD - SYS___ABORT = 0x05C - SYS___CONSOLE2 = 0x5D2 - SYS___CPL = 0x5A6 - SYS___DISCARDDATA = 0x5F8 - SYS___DSA_PREV = 0x5B2 - SYS___EP_FIND = 0x5B3 - SYS___FP_SWAPMODE = 0x5AF - SYS___GETUSERID = 0x5AB - SYS___GET_CPUID = 0x5B9 - SYS___GET_SYSTEM_SETTINGS = 0x5BA - SYS___IPDOMAINNAME = 0x5AC - SYS___MAP_INIT = 0x5A7 - SYS___MAP_SERVICE = 0x5A8 - SYS___MOUNT = 0x5AA - SYS___MSGRCV_TIMED = 0x5B7 - SYS___RES = 0x5D6 - SYS___SEMOP_TIMED = 0x5B8 - SYS___SERVER_THREADS_QUERY = 0x5B4 - SYS_FPRINTF = 0x06D - SYS_FSCANF = 0x06A - SYS_PRINTF = 0x06F - SYS_SETBUF = 0x06B - SYS_SETVBUF = 0x06C - SYS_SSCANF = 0x06E - SYS___CATGETS_A = 0x6C0 - SYS___CHAUDIT_A = 0x6F4 - SYS___CHMOD_A = 0x6E8 - SYS___COLLATE_INIT_A = 0x6AC - SYS___CREAT_A = 0x6F6 - SYS___CTYPE_INIT_A = 0x6AF - SYS___DLLLOAD_A = 0x6DF - SYS___DLLQUERYFN_A = 0x6E0 - SYS___DLLQUERYVAR_A = 0x6E1 - SYS___E2A_L = 0x6E3 - SYS___EXECLE_A = 0x6A0 - SYS___EXECLP_A = 0x6A4 - SYS___EXECVE_A = 0x6C1 - SYS___EXECVP_A = 0x6C2 - SYS___EXECV_A = 0x6B1 - SYS___FPRINTF_A = 0x6FA - SYS___GETADDRINFO_A = 0x6BF - SYS___GETNAMEINFO_A = 0x6C4 - SYS___GET_WCTYPE_STD_A = 0x6AE - SYS___ICONV_OPEN_A = 0x6DE - SYS___IF_INDEXTONAME_A = 0x6DC - SYS___IF_NAMETOINDEX_A = 0x6DB - SYS___ISWCTYPE_A = 0x6B0 - SYS___IS_WCTYPE_STD_A = 0x6B2 - SYS___LOCALECONV_A = 0x6B8 - SYS___LOCALECONV_STD_A = 0x6B9 - SYS___LOCALE_INIT_A = 0x6B7 - SYS___LSTAT_A = 0x6EE - SYS___LSTAT_O_A = 0x6EF - SYS___MKDIR_A = 0x6E9 - SYS___MKFIFO_A = 0x6EC - SYS___MKNOD_A = 0x6F0 - SYS___MONETARY_INIT_A = 0x6BC - SYS___MOUNT_A = 0x6F1 - SYS___NL_CSINFO_A = 0x6D6 - SYS___NL_LANGINFO_A = 0x6BA - SYS___NL_LNAGINFO_STD_A = 0x6BB - SYS___NL_MONINFO_A = 0x6D7 - SYS___NL_NUMINFO_A = 0x6D8 - SYS___NL_RESPINFO_A = 0x6D9 - SYS___NL_TIMINFO_A = 0x6DA - SYS___NUMERIC_INIT_A = 0x6C6 - SYS___OPEN_A = 0x6F7 - SYS___PRINTF_A = 0x6DD - SYS___RESP_INIT_A = 0x6C7 - SYS___RPMATCH_A = 0x6C8 - SYS___RPMATCH_C_A = 0x6C9 - SYS___RPMATCH_STD_A = 0x6CA - SYS___SETLOCALE_A = 0x6F9 - SYS___SPAWNP_A = 0x6C5 - SYS___SPAWN_A = 0x6C3 - SYS___SPRINTF_A = 0x6FB - SYS___STAT_A = 0x6EA - SYS___STAT_O_A = 0x6EB - SYS___STRCOLL_STD_A = 0x6A1 - SYS___STRFMON_A = 0x6BD - SYS___STRFMON_STD_A = 0x6BE - SYS___STRFTIME_A = 0x6CC - SYS___STRFTIME_STD_A = 0x6CD - SYS___STRPTIME_A = 0x6CE - SYS___STRPTIME_STD_A = 0x6CF - SYS___STRXFRM_A = 0x6A2 - SYS___STRXFRM_C_A = 0x6A3 - SYS___STRXFRM_STD_A = 0x6A5 - SYS___SYNTAX_INIT_A = 0x6D4 - SYS___TIME_INIT_A = 0x6CB - SYS___TOD_INIT_A = 0x6D5 - SYS___TOWLOWER_A = 0x6B3 - SYS___TOWLOWER_STD_A = 0x6B4 - SYS___TOWUPPER_A = 0x6B5 - SYS___TOWUPPER_STD_A = 0x6B6 - SYS___UMOUNT_A = 0x6F2 - SYS___VFPRINTF_A = 0x6FC - SYS___VPRINTF_A = 0x6FD - SYS___VSPRINTF_A = 0x6FE - SYS___VSWPRINTF_A = 0x6FF - SYS___WCSCOLL_A = 0x6A6 - SYS___WCSCOLL_C_A = 0x6A7 - SYS___WCSCOLL_STD_A = 0x6A8 - SYS___WCSFTIME_A = 0x6D0 - SYS___WCSFTIME_STD_A = 0x6D1 - SYS___WCSXFRM_A = 0x6A9 - SYS___WCSXFRM_C_A = 0x6AA - SYS___WCSXFRM_STD_A = 0x6AB - SYS___WCTYPE_A = 0x6AD - SYS___W_GETMNTENT_A = 0x6F5 - SYS_____CCSIDTYPE_A = 0x6E6 - SYS_____CHATTR_A = 0x6E2 - SYS_____CSNAMETYPE_A = 0x6E7 - SYS_____OPEN_STAT_A = 0x6ED - SYS_____SPAWN2_A = 0x6D2 - SYS_____SPAWNP2_A = 0x6D3 - SYS_____TOCCSID_A = 0x6E4 - SYS_____TOCSNAME_A = 0x6E5 - SYS_ACL_FREE = 0x7FF - SYS_ACL_INIT = 0x7FE - SYS_FWIDE = 0x7DF - SYS_FWPRINTF = 0x7D1 - SYS_FWRITE = 0x07E - SYS_FWSCANF = 0x7D5 - SYS_GETCHAR = 0x07B - SYS_GETS = 0x07C - SYS_M_CREATE_LAYOUT = 0x7C9 - SYS_M_DESTROY_LAYOUT = 0x7CA - SYS_M_GETVALUES_LAYOUT = 0x7CB - SYS_M_SETVALUES_LAYOUT = 0x7CC - SYS_M_TRANSFORM_LAYOUT = 0x7CD - SYS_M_WTRANSFORM_LAYOUT = 0x7CE - SYS_PREAD = 0x7C7 - SYS_PUTC = 0x07D - SYS_PUTCHAR = 0x07A - SYS_PUTS = 0x07F - SYS_PWRITE = 0x7C8 - SYS_TOWCTRAN = 0x7D8 - SYS_TOWCTRANS = 0x7D8 - SYS_UNATEXIT = 0x7B5 - SYS_VFWPRINT = 0x7D3 - SYS_VFWPRINTF = 0x7D3 - SYS_VWPRINTF = 0x7D4 - SYS_WCTRANS = 0x7D7 - SYS_WPRINTF = 0x7D2 - SYS_WSCANF = 0x7D6 - SYS___ASCTIME_R_A = 0x7A1 - SYS___BASENAME_A = 0x7DC - SYS___BTOWC_A = 0x7E4 - SYS___CDUMP_A = 0x7B7 - SYS___CEE3DMP_A = 0x7B6 - SYS___CEILF_H = 0x7F4 - SYS___CEILL_H = 0x7F5 - SYS___CEIL_H = 0x7EA - SYS___CRYPT_A = 0x7BE - SYS___CSNAP_A = 0x7B8 - SYS___CTEST_A = 0x7B9 - SYS___CTIME_R_A = 0x7A2 - SYS___CTRACE_A = 0x7BA - SYS___DBM_OPEN_A = 0x7E6 - SYS___DIRNAME_A = 0x7DD - SYS___FABSF_H = 0x7FA - SYS___FABSL_H = 0x7FB - SYS___FABS_H = 0x7ED - SYS___FGETWC_A = 0x7AA - SYS___FGETWS_A = 0x7AD - SYS___FLOORF_H = 0x7F6 - SYS___FLOORL_H = 0x7F7 - SYS___FLOOR_H = 0x7EB - SYS___FPUTWC_A = 0x7A5 - SYS___FPUTWS_A = 0x7A8 - SYS___GETTIMEOFDAY_A = 0x7AE - SYS___GETWCHAR_A = 0x7AC - SYS___GETWC_A = 0x7AB - SYS___GLOB_A = 0x7DE - SYS___GMTIME_A = 0x7AF - SYS___GMTIME_R_A = 0x7B0 - SYS___INET_PTON_A = 0x7BC - SYS___J0_H = 0x7EE - SYS___J1_H = 0x7EF - SYS___JN_H = 0x7F0 - SYS___LOCALTIME_A = 0x7B1 - SYS___LOCALTIME_R_A = 0x7B2 - SYS___MALLOC24 = 0x7FC - SYS___MALLOC31 = 0x7FD - SYS___MKTIME_A = 0x7B3 - SYS___MODFF_H = 0x7F8 - SYS___MODFL_H = 0x7F9 - SYS___MODF_H = 0x7EC - SYS___OPENDIR_A = 0x7C2 - SYS___OSNAME = 0x7E0 - SYS___PUTWCHAR_A = 0x7A7 - SYS___PUTWC_A = 0x7A6 - SYS___READDIR_A = 0x7C3 - SYS___STRTOLL_A = 0x7A3 - SYS___STRTOULL_A = 0x7A4 - SYS___SYSLOG_A = 0x7BD - SYS___TZZNA = 0x7B4 - SYS___UNGETWC_A = 0x7A9 - SYS___UTIME_A = 0x7A0 - SYS___VFPRINTF2_A = 0x7E7 - SYS___VPRINTF2_A = 0x7E8 - SYS___VSPRINTF2_A = 0x7E9 - SYS___VSWPRNTF2_A = 0x7BB - SYS___WCSTOD_A = 0x7D9 - SYS___WCSTOL_A = 0x7DA - SYS___WCSTOUL_A = 0x7DB - SYS___WCTOB_A = 0x7E5 - SYS___Y0_H = 0x7F1 - SYS___Y1_H = 0x7F2 - SYS___YN_H = 0x7F3 - SYS_____OPENDIR2_A = 0x7BF - SYS_____OSNAME_A = 0x7E1 - SYS_____READDIR2_A = 0x7C0 - SYS_DLCLOSE = 0x8DF - SYS_DLERROR = 0x8E0 - SYS_DLOPEN = 0x8DD - SYS_DLSYM = 0x8DE - SYS_FLOCKFILE = 0x8D3 - SYS_FTRYLOCKFILE = 0x8D4 - SYS_FUNLOCKFILE = 0x8D5 - SYS_GETCHAR_UNLOCKED = 0x8D7 - SYS_GETC_UNLOCKED = 0x8D6 - SYS_PUTCHAR_UNLOCKED = 0x8D9 - SYS_PUTC_UNLOCKED = 0x8D8 - SYS_SNPRINTF = 0x8DA - SYS_VSNPRINTF = 0x8DB - SYS_WCSCSPN = 0x08B - SYS_WCSLEN = 0x08C - SYS_WCSNCAT = 0x08D - SYS_WCSNCMP = 0x08A - SYS_WCSNCPY = 0x08F - SYS_WCSSPN = 0x08E - SYS___ABSF_H = 0x8E7 - SYS___ABSL_H = 0x8E8 - SYS___ABS_H = 0x8E6 - SYS___ACOSF_H = 0x8EA - SYS___ACOSH_H = 0x8EC - SYS___ACOSL_H = 0x8EB - SYS___ACOS_H = 0x8E9 - SYS___ASINF_H = 0x8EE - SYS___ASINH_H = 0x8F0 - SYS___ASINL_H = 0x8EF - SYS___ASIN_H = 0x8ED - SYS___ATAN2F_H = 0x8F8 - SYS___ATAN2L_H = 0x8F9 - SYS___ATAN2_H = 0x8F7 - SYS___ATANF_H = 0x8F2 - SYS___ATANHF_H = 0x8F5 - SYS___ATANHL_H = 0x8F6 - SYS___ATANH_H = 0x8F4 - SYS___ATANL_H = 0x8F3 - SYS___ATAN_H = 0x8F1 - SYS___CBRT_H = 0x8FA - SYS___COPYSIGNF_H = 0x8FB - SYS___COPYSIGNL_H = 0x8FC - SYS___COSF_H = 0x8FE - SYS___COSL_H = 0x8FF - SYS___COS_H = 0x8FD - SYS___DLERROR_A = 0x8D2 - SYS___DLOPEN_A = 0x8D0 - SYS___DLSYM_A = 0x8D1 - SYS___GETUTXENT_A = 0x8C6 - SYS___GETUTXID_A = 0x8C7 - SYS___GETUTXLINE_A = 0x8C8 - SYS___ITOA = 0x8AA - SYS___ITOA_A = 0x8B0 - SYS___LE_CONDITION_TOKEN_BUILD = 0x8A5 - SYS___LE_MSG_ADD_INSERT = 0x8A6 - SYS___LE_MSG_GET = 0x8A7 - SYS___LE_MSG_GET_AND_WRITE = 0x8A8 - SYS___LE_MSG_WRITE = 0x8A9 - SYS___LLTOA = 0x8AE - SYS___LLTOA_A = 0x8B4 - SYS___LTOA = 0x8AC - SYS___LTOA_A = 0x8B2 - SYS___PUTCHAR_UNLOCKED_A = 0x8CC - SYS___PUTC_UNLOCKED_A = 0x8CB - SYS___PUTUTXLINE_A = 0x8C9 - SYS___RESET_EXCEPTION_HANDLER = 0x8E3 - SYS___REXEC_A = 0x8C4 - SYS___REXEC_AF_A = 0x8C5 - SYS___SET_EXCEPTION_HANDLER = 0x8E2 - SYS___SNPRINTF_A = 0x8CD - SYS___SUPERKILL = 0x8A4 - SYS___TCGETATTR_A = 0x8A1 - SYS___TCSETATTR_A = 0x8A2 - SYS___ULLTOA = 0x8AF - SYS___ULLTOA_A = 0x8B5 - SYS___ULTOA = 0x8AD - SYS___ULTOA_A = 0x8B3 - SYS___UTOA = 0x8AB - SYS___UTOA_A = 0x8B1 - SYS___VHM_EVENT = 0x8E4 - SYS___VSNPRINTF_A = 0x8CE - SYS_____GETENV_A = 0x8C3 - SYS_____UTMPXNAME_A = 0x8CA - SYS_CACOSH = 0x9A0 - SYS_CACOSHF = 0x9A3 - SYS_CACOSHL = 0x9A6 - SYS_CARG = 0x9A9 - SYS_CARGF = 0x9AC - SYS_CARGL = 0x9AF - SYS_CASIN = 0x9B2 - SYS_CASINF = 0x9B5 - SYS_CASINH = 0x9BB - SYS_CASINHF = 0x9BE - SYS_CASINHL = 0x9C1 - SYS_CASINL = 0x9B8 - SYS_CATAN = 0x9C4 - SYS_CATANF = 0x9C7 - SYS_CATANH = 0x9CD - SYS_CATANHF = 0x9D0 - SYS_CATANHL = 0x9D3 - SYS_CATANL = 0x9CA - SYS_CCOS = 0x9D6 - SYS_CCOSF = 0x9D9 - SYS_CCOSH = 0x9DF - SYS_CCOSHF = 0x9E2 - SYS_CCOSHL = 0x9E5 - SYS_CCOSL = 0x9DC - SYS_CEXP = 0x9E8 - SYS_CEXPF = 0x9EB - SYS_CEXPL = 0x9EE - SYS_CIMAG = 0x9F1 - SYS_CIMAGF = 0x9F4 - SYS_CIMAGL = 0x9F7 - SYS_CLOGF = 0x9FD - SYS_MEMCHR = 0x09B - SYS_MEMCMP = 0x09A - SYS_STRCOLL = 0x09C - SYS_STRNCMP = 0x09D - SYS_STRRCHR = 0x09F - SYS_STRXFRM = 0x09E - SYS___CACOSHF_B = 0x9A4 - SYS___CACOSHF_H = 0x9A5 - SYS___CACOSHL_B = 0x9A7 - SYS___CACOSHL_H = 0x9A8 - SYS___CACOSH_B = 0x9A1 - SYS___CACOSH_H = 0x9A2 - SYS___CARGF_B = 0x9AD - SYS___CARGF_H = 0x9AE - SYS___CARGL_B = 0x9B0 - SYS___CARGL_H = 0x9B1 - SYS___CARG_B = 0x9AA - SYS___CARG_H = 0x9AB - SYS___CASINF_B = 0x9B6 - SYS___CASINF_H = 0x9B7 - SYS___CASINHF_B = 0x9BF - SYS___CASINHF_H = 0x9C0 - SYS___CASINHL_B = 0x9C2 - SYS___CASINHL_H = 0x9C3 - SYS___CASINH_B = 0x9BC - SYS___CASINH_H = 0x9BD - SYS___CASINL_B = 0x9B9 - SYS___CASINL_H = 0x9BA - SYS___CASIN_B = 0x9B3 - SYS___CASIN_H = 0x9B4 - SYS___CATANF_B = 0x9C8 - SYS___CATANF_H = 0x9C9 - SYS___CATANHF_B = 0x9D1 - SYS___CATANHF_H = 0x9D2 - SYS___CATANHL_B = 0x9D4 - SYS___CATANHL_H = 0x9D5 - SYS___CATANH_B = 0x9CE - SYS___CATANH_H = 0x9CF - SYS___CATANL_B = 0x9CB - SYS___CATANL_H = 0x9CC - SYS___CATAN_B = 0x9C5 - SYS___CATAN_H = 0x9C6 - SYS___CCOSF_B = 0x9DA - SYS___CCOSF_H = 0x9DB - SYS___CCOSHF_B = 0x9E3 - SYS___CCOSHF_H = 0x9E4 - SYS___CCOSHL_B = 0x9E6 - SYS___CCOSHL_H = 0x9E7 - SYS___CCOSH_B = 0x9E0 - SYS___CCOSH_H = 0x9E1 - SYS___CCOSL_B = 0x9DD - SYS___CCOSL_H = 0x9DE - SYS___CCOS_B = 0x9D7 - SYS___CCOS_H = 0x9D8 - SYS___CEXPF_B = 0x9EC - SYS___CEXPF_H = 0x9ED - SYS___CEXPL_B = 0x9EF - SYS___CEXPL_H = 0x9F0 - SYS___CEXP_B = 0x9E9 - SYS___CEXP_H = 0x9EA - SYS___CIMAGF_B = 0x9F5 - SYS___CIMAGF_H = 0x9F6 - SYS___CIMAGL_B = 0x9F8 - SYS___CIMAGL_H = 0x9F9 - SYS___CIMAG_B = 0x9F2 - SYS___CIMAG_H = 0x9F3 - SYS___CLOG = 0x9FA - SYS___CLOGF_B = 0x9FE - SYS___CLOGF_H = 0x9FF - SYS___CLOG_B = 0x9FB - SYS___CLOG_H = 0x9FC - SYS_ISWCTYPE = 0x10C - SYS_ISWXDIGI = 0x10A - SYS_ISWXDIGIT = 0x10A - SYS_MBSINIT = 0x10F - SYS_TOWLOWER = 0x10D - SYS_TOWUPPER = 0x10E - SYS_WCTYPE = 0x10B - SYS_WCSSTR = 0x11B - SYS___RPMTCH = 0x11A - SYS_WCSTOD = 0x12E - SYS_WCSTOK = 0x12C - SYS_WCSTOL = 0x12D - SYS_WCSTOUL = 0x12F - SYS_FGETWC = 0x13C - SYS_FGETWS = 0x13D - SYS_FPUTWC = 0x13E - SYS_FPUTWS = 0x13F - SYS_REGERROR = 0x13B - SYS_REGFREE = 0x13A - SYS_COLLEQUIV = 0x14F - SYS_COLLTOSTR = 0x14E - SYS_ISMCCOLLEL = 0x14C - SYS_STRTOCOLL = 0x14D - SYS_DLLFREE = 0x16F - SYS_DLLQUERYFN = 0x16D - SYS_DLLQUERYVAR = 0x16E - SYS_GETMCCOLL = 0x16A - SYS_GETWMCCOLL = 0x16B - SYS___ERR2AD = 0x16C - SYS_CFSETOSPEED = 0x17A - SYS_CHDIR = 0x17B - SYS_CHMOD = 0x17C - SYS_CHOWN = 0x17D - SYS_CLOSE = 0x17E - SYS_CLOSEDIR = 0x17F - SYS_LOG = 0x017 - SYS_COSH = 0x018 - SYS_FCHMOD = 0x18A - SYS_FCHOWN = 0x18B - SYS_FCNTL = 0x18C - SYS_FILENO = 0x18D - SYS_FORK = 0x18E - SYS_FPATHCONF = 0x18F - SYS_GETLOGIN = 0x19A - SYS_GETPGRP = 0x19C - SYS_GETPID = 0x19D - SYS_GETPPID = 0x19E - SYS_GETPWNAM = 0x19F - SYS_TANH = 0x019 - SYS_W_GETMNTENT = 0x19B - SYS_POW = 0x020 - SYS_PTHREAD_SELF = 0x20A - SYS_PTHREAD_SETINTR = 0x20B - SYS_PTHREAD_SETINTRTYPE = 0x20C - SYS_PTHREAD_SETSPECIFIC = 0x20D - SYS_PTHREAD_TESTINTR = 0x20E - SYS_PTHREAD_YIELD = 0x20F - SYS_SQRT = 0x021 - SYS_FLOOR = 0x022 - SYS_J1 = 0x023 - SYS_WCSPBRK = 0x23F - SYS_BSEARCH = 0x24C - SYS_FABS = 0x024 - SYS_GETENV = 0x24A - SYS_LDIV = 0x24D - SYS_SYSTEM = 0x24B - SYS_FMOD = 0x025 - SYS___RETHROW = 0x25F - SYS___THROW = 0x25E - SYS_J0 = 0x026 - SYS_PUTENV = 0x26A - SYS___GETENV = 0x26F - SYS_SEMCTL = 0x27A - SYS_SEMGET = 0x27B - SYS_SEMOP = 0x27C - SYS_SHMAT = 0x27D - SYS_SHMCTL = 0x27E - SYS_SHMDT = 0x27F - SYS_YN = 0x027 - SYS_JN = 0x028 - SYS_SIGALTSTACK = 0x28A - SYS_SIGHOLD = 0x28B - SYS_SIGIGNORE = 0x28C - SYS_SIGINTERRUPT = 0x28D - SYS_SIGPAUSE = 0x28E - SYS_SIGRELSE = 0x28F - SYS_GETOPT = 0x29A - SYS_GETSUBOPT = 0x29D - SYS_LCHOWN = 0x29B - SYS_SETPGRP = 0x29E - SYS_TRUNCATE = 0x29C - SYS_Y0 = 0x029 - SYS___GDERR = 0x29F - SYS_ISALPHA = 0x030 - SYS_VFORK = 0x30F - SYS__LONGJMP = 0x30D - SYS__SETJMP = 0x30E - SYS_GLOB = 0x31A - SYS_GLOBFREE = 0x31B - SYS_ISALNUM = 0x031 - SYS_PUTW = 0x31C - SYS_SEEKDIR = 0x31D - SYS_TELLDIR = 0x31E - SYS_TEMPNAM = 0x31F - SYS_GETTIMEOFDAY_R = 0x32E - SYS_ISLOWER = 0x032 - SYS_LGAMMA = 0x32C - SYS_REMAINDER = 0x32A - SYS_SCALB = 0x32B - SYS_SYNC = 0x32F - SYS_TTYSLOT = 0x32D - SYS_ENDPROTOENT = 0x33A - SYS_ENDSERVENT = 0x33B - SYS_GETHOSTBYADDR = 0x33D - SYS_GETHOSTBYADDR_R = 0x33C - SYS_GETHOSTBYNAME = 0x33F - SYS_GETHOSTBYNAME_R = 0x33E - SYS_ISCNTRL = 0x033 - SYS_GETSERVBYNAME = 0x34A - SYS_GETSERVBYPORT = 0x34B - SYS_GETSERVENT = 0x34C - SYS_GETSOCKNAME = 0x34D - SYS_GETSOCKOPT = 0x34E - SYS_INET_ADDR = 0x34F - SYS_ISDIGIT = 0x034 - SYS_ISGRAPH = 0x035 - SYS_SELECT = 0x35B - SYS_SELECTEX = 0x35C - SYS_SEND = 0x35D - SYS_SENDTO = 0x35F - SYS_CHROOT = 0x36A - SYS_ISNAN = 0x36D - SYS_ISUPPER = 0x036 - SYS_ULIMIT = 0x36C - SYS_UTIMES = 0x36E - SYS_W_STATVFS = 0x36B - SYS___H_ERRNO = 0x36F - SYS_GRANTPT = 0x37A - SYS_ISPRINT = 0x037 - SYS_TCGETSID = 0x37C - SYS_UNLOCKPT = 0x37B - SYS___TCGETCP = 0x37D - SYS___TCSETCP = 0x37E - SYS___TCSETTABLES = 0x37F - SYS_ISPUNCT = 0x038 - SYS_NLIST = 0x38C - SYS___IPDBCS = 0x38D - SYS___IPDSPX = 0x38E - SYS___IPMSGC = 0x38F - SYS___STHOSTENT = 0x38B - SYS___STSERVENT = 0x38A - SYS_ISSPACE = 0x039 - SYS_COS = 0x040 - SYS_T_ALLOC = 0x40A - SYS_T_BIND = 0x40B - SYS_T_CLOSE = 0x40C - SYS_T_CONNECT = 0x40D - SYS_T_ERROR = 0x40E - SYS_T_FREE = 0x40F - SYS_TAN = 0x041 - SYS_T_RCVREL = 0x41A - SYS_T_RCVUDATA = 0x41B - SYS_T_RCVUDERR = 0x41C - SYS_T_SND = 0x41D - SYS_T_SNDDIS = 0x41E - SYS_T_SNDREL = 0x41F - SYS_GETPMSG = 0x42A - SYS_ISASTREAM = 0x42B - SYS_PUTMSG = 0x42C - SYS_PUTPMSG = 0x42D - SYS_SINH = 0x042 - SYS___ISPOSIXON = 0x42E - SYS___OPENMVSREL = 0x42F - SYS_ACOS = 0x043 - SYS_ATAN = 0x044 - SYS_ATAN2 = 0x045 - SYS_FTELL = 0x046 - SYS_FGETPOS = 0x047 - SYS_SOCK_DEBUG = 0x47A - SYS_SOCK_DO_TESTSTOR = 0x47D - SYS_TAKESOCKET = 0x47E - SYS___SERVER_INIT = 0x47F - SYS_FSEEK = 0x048 - SYS___IPHOST = 0x48B - SYS___IPNODE = 0x48C - SYS___SERVER_CLASSIFY_CREATE = 0x48D - SYS___SERVER_CLASSIFY_DESTROY = 0x48E - SYS___SERVER_CLASSIFY_RESET = 0x48F - SYS___SMF_RECORD = 0x48A - SYS_FSETPOS = 0x049 - SYS___FNWSA = 0x49B - SYS___SPAWN2 = 0x49D - SYS___SPAWNP2 = 0x49E - SYS_ATOF = 0x050 - SYS_PTHREAD_MUTEXATTR_GETPSHARED = 0x50A - SYS_PTHREAD_MUTEXATTR_SETPSHARED = 0x50B - SYS_PTHREAD_RWLOCK_DESTROY = 0x50C - SYS_PTHREAD_RWLOCK_INIT = 0x50D - SYS_PTHREAD_RWLOCK_RDLOCK = 0x50E - SYS_PTHREAD_RWLOCK_TRYRDLOCK = 0x50F - SYS_ATOI = 0x051 - SYS___FP_CLASS = 0x51D - SYS___FP_CLR_FLAG = 0x51A - SYS___FP_FINITE = 0x51E - SYS___FP_ISNAN = 0x51F - SYS___FP_RAISE_XCP = 0x51C - SYS___FP_READ_FLAG = 0x51B - SYS_RAND = 0x052 - SYS_SIGTIMEDWAIT = 0x52D - SYS_SIGWAITINFO = 0x52E - SYS___CHKBFP = 0x52F - SYS___FPC_RS = 0x52C - SYS___FPC_RW = 0x52A - SYS___FPC_SM = 0x52B - SYS_STRTOD = 0x053 - SYS_STRTOL = 0x054 - SYS_STRTOUL = 0x055 - SYS_MALLOC = 0x056 - SYS_SRAND = 0x057 - SYS_CALLOC = 0x058 - SYS_FREE = 0x059 - SYS___OSENV = 0x59F - SYS___W_PIOCTL = 0x59E - SYS_LONGJMP = 0x060 - SYS___FLOORF_B = 0x60A - SYS___FLOORL_B = 0x60B - SYS___FREXPF_B = 0x60C - SYS___FREXPL_B = 0x60D - SYS___LDEXPF_B = 0x60E - SYS___LDEXPL_B = 0x60F - SYS_SIGNAL = 0x061 - SYS___ATAN2F_B = 0x61A - SYS___ATAN2L_B = 0x61B - SYS___COSHF_B = 0x61C - SYS___COSHL_B = 0x61D - SYS___EXPF_B = 0x61E - SYS___EXPL_B = 0x61F - SYS_TMPNAM = 0x062 - SYS___ABSF_B = 0x62A - SYS___ABSL_B = 0x62C - SYS___ABS_B = 0x62B - SYS___FMODF_B = 0x62D - SYS___FMODL_B = 0x62E - SYS___MODFF_B = 0x62F - SYS_ATANL = 0x63A - SYS_CEILF = 0x63B - SYS_CEILL = 0x63C - SYS_COSF = 0x63D - SYS_COSHF = 0x63F - SYS_COSL = 0x63E - SYS_REMOVE = 0x063 - SYS_POWL = 0x64A - SYS_RENAME = 0x064 - SYS_SINF = 0x64B - SYS_SINHF = 0x64F - SYS_SINL = 0x64C - SYS_SQRTF = 0x64D - SYS_SQRTL = 0x64E - SYS_BTOWC = 0x65F - SYS_FREXPL = 0x65A - SYS_LDEXPF = 0x65B - SYS_LDEXPL = 0x65C - SYS_MODFF = 0x65D - SYS_MODFL = 0x65E - SYS_TMPFILE = 0x065 - SYS_FREOPEN = 0x066 - SYS___CHARMAP_INIT_A = 0x66E - SYS___GETHOSTBYADDR_R_A = 0x66C - SYS___GETHOSTBYNAME_A = 0x66A - SYS___GETHOSTBYNAME_R_A = 0x66D - SYS___MBLEN_A = 0x66F - SYS___RES_INIT_A = 0x66B - SYS_FCLOSE = 0x067 - SYS___GETGRGID_R_A = 0x67D - SYS___WCSTOMBS_A = 0x67A - SYS___WCSTOMBS_STD_A = 0x67B - SYS___WCSWIDTH_A = 0x67C - SYS___WCSWIDTH_ASIA = 0x67F - SYS___WCSWIDTH_STD_A = 0x67E - SYS_FFLUSH = 0x068 - SYS___GETLOGIN_R_A = 0x68E - SYS___GETPWNAM_R_A = 0x68C - SYS___GETPWUID_R_A = 0x68D - SYS___TTYNAME_R_A = 0x68F - SYS___WCWIDTH_ASIA = 0x68B - SYS___WCWIDTH_STD_A = 0x68A - SYS_FOPEN = 0x069 - SYS___REGEXEC_A = 0x69A - SYS___REGEXEC_STD_A = 0x69B - SYS___REGFREE_A = 0x69C - SYS___REGFREE_STD_A = 0x69D - SYS___STRCOLL_A = 0x69E - SYS___STRCOLL_C_A = 0x69F - SYS_SCANF = 0x070 - SYS___A64L_A = 0x70C - SYS___ECVT_A = 0x70D - SYS___FCVT_A = 0x70E - SYS___GCVT_A = 0x70F - SYS___STRTOUL_A = 0x70A - SYS_____AE_CORRESTBL_QUERY_A = 0x70B - SYS_SPRINTF = 0x071 - SYS___ACCESS_A = 0x71F - SYS___CATOPEN_A = 0x71E - SYS___GETOPT_A = 0x71D - SYS___REALPATH_A = 0x71A - SYS___SETENV_A = 0x71B - SYS___SYSTEM_A = 0x71C - SYS_FGETC = 0x072 - SYS___GAI_STRERROR_A = 0x72F - SYS___RMDIR_A = 0x72A - SYS___STATVFS_A = 0x72B - SYS___SYMLINK_A = 0x72C - SYS___TRUNCATE_A = 0x72D - SYS___UNLINK_A = 0x72E - SYS_VFPRINTF = 0x073 - SYS___ISSPACE_A = 0x73A - SYS___ISUPPER_A = 0x73B - SYS___ISWALNUM_A = 0x73F - SYS___ISXDIGIT_A = 0x73C - SYS___TOLOWER_A = 0x73D - SYS___TOUPPER_A = 0x73E - SYS_VPRINTF = 0x074 - SYS___CONFSTR_A = 0x74B - SYS___FDOPEN_A = 0x74E - SYS___FLDATA_A = 0x74F - SYS___FTOK_A = 0x74C - SYS___ISWXDIGIT_A = 0x74A - SYS___MKTEMP_A = 0x74D - SYS_VSPRINTF = 0x075 - SYS___GETGRGID_A = 0x75A - SYS___GETGRNAM_A = 0x75B - SYS___GETGROUPSBYNAME_A = 0x75C - SYS___GETHOSTENT_A = 0x75D - SYS___GETHOSTNAME_A = 0x75E - SYS___GETLOGIN_A = 0x75F - SYS_GETC = 0x076 - SYS___CREATEWORKUNIT_A = 0x76A - SYS___CTERMID_A = 0x76B - SYS___FMTMSG_A = 0x76C - SYS___INITGROUPS_A = 0x76D - SYS___MSGRCV_A = 0x76F - SYS_____LOGIN_A = 0x76E - SYS_FGETS = 0x077 - SYS___STRCASECMP_A = 0x77B - SYS___STRNCASECMP_A = 0x77C - SYS___TTYNAME_A = 0x77D - SYS___UNAME_A = 0x77E - SYS___UTIMES_A = 0x77F - SYS_____SERVER_PWU_A = 0x77A - SYS_FPUTC = 0x078 - SYS___CREAT_O_A = 0x78E - SYS___ENVNA = 0x78F - SYS___FREAD_A = 0x78A - SYS___FWRITE_A = 0x78B - SYS___ISASCII = 0x78D - SYS___OPEN_O_A = 0x78C - SYS_FPUTS = 0x079 - SYS___ASCTIME_A = 0x79C - SYS___CTIME_A = 0x79D - SYS___GETDATE_A = 0x79E - SYS___GETSERVBYPORT_A = 0x79A - SYS___GETSERVENT_A = 0x79B - SYS___TZSET_A = 0x79F - SYS_ACL_FROM_TEXT = 0x80C - SYS_ACL_SET_FD = 0x80A - SYS_ACL_SET_FILE = 0x80B - SYS_ACL_SORT = 0x80E - SYS_ACL_TO_TEXT = 0x80D - SYS_UNGETC = 0x080 - SYS___SHUTDOWN_REGISTRATION = 0x80F - SYS_FREAD = 0x081 - SYS_FREEADDRINFO = 0x81A - SYS_GAI_STRERROR = 0x81B - SYS_REXEC_AF = 0x81C - SYS___DYNALLOC_A = 0x81F - SYS___POE = 0x81D - SYS_WCSTOMBS = 0x082 - SYS___INET_ADDR_A = 0x82F - SYS___NLIST_A = 0x82A - SYS_____TCGETCP_A = 0x82B - SYS_____TCSETCP_A = 0x82C - SYS_____W_PIOCTL_A = 0x82E - SYS_MBTOWC = 0x083 - SYS___CABEND = 0x83D - SYS___LE_CIB_GET = 0x83E - SYS___RECVMSG_A = 0x83B - SYS___SENDMSG_A = 0x83A - SYS___SET_LAA_FOR_JIT = 0x83F - SYS_____LCHATTR_A = 0x83C - SYS_WCTOMB = 0x084 - SYS___CBRTL_B = 0x84A - SYS___COPYSIGNF_B = 0x84B - SYS___COPYSIGNL_B = 0x84C - SYS___COTANF_B = 0x84D - SYS___COTANL_B = 0x84F - SYS___COTAN_B = 0x84E - SYS_MBSTOWCS = 0x085 - SYS___LOG1PL_B = 0x85A - SYS___LOG2F_B = 0x85B - SYS___LOG2L_B = 0x85D - SYS___LOG2_B = 0x85C - SYS___REMAINDERF_B = 0x85E - SYS___REMAINDERL_B = 0x85F - SYS_ACOSHF = 0x86E - SYS_ACOSHL = 0x86F - SYS_WCSCPY = 0x086 - SYS___ERFCF_B = 0x86D - SYS___ERFF_B = 0x86C - SYS___LROUNDF_B = 0x86A - SYS___LROUND_B = 0x86B - SYS_COTANL = 0x87A - SYS_EXP2F = 0x87B - SYS_EXP2L = 0x87C - SYS_EXPM1F = 0x87D - SYS_EXPM1L = 0x87E - SYS_FDIMF = 0x87F - SYS_WCSCAT = 0x087 - SYS___COTANL = 0x87A - SYS_REMAINDERF = 0x88A - SYS_REMAINDERL = 0x88B - SYS_REMAINDF = 0x88A - SYS_REMAINDL = 0x88B - SYS_REMQUO = 0x88D - SYS_REMQUOF = 0x88C - SYS_REMQUOL = 0x88E - SYS_TGAMMAF = 0x88F - SYS_WCSCHR = 0x088 - SYS_ERFCF = 0x89B - SYS_ERFCL = 0x89C - SYS_ERFL = 0x89A - SYS_EXP2 = 0x89E - SYS_WCSCMP = 0x089 - SYS___EXP2_B = 0x89D - SYS___FAR_JUMP = 0x89F - SYS_ABS = 0x090 - SYS___ERFCL_H = 0x90A - SYS___EXPF_H = 0x90C - SYS___EXPL_H = 0x90D - SYS___EXPM1_H = 0x90E - SYS___EXP_H = 0x90B - SYS___FDIM_H = 0x90F - SYS_DIV = 0x091 - SYS___LOG2F_H = 0x91F - SYS___LOG2_H = 0x91E - SYS___LOGB_H = 0x91D - SYS___LOGF_H = 0x91B - SYS___LOGL_H = 0x91C - SYS___LOG_H = 0x91A - SYS_LABS = 0x092 - SYS___POWL_H = 0x92A - SYS___REMAINDER_H = 0x92B - SYS___RINT_H = 0x92C - SYS___SCALB_H = 0x92D - SYS___SINF_H = 0x92F - SYS___SIN_H = 0x92E - SYS_STRNCPY = 0x093 - SYS___TANHF_H = 0x93B - SYS___TANHL_H = 0x93C - SYS___TANH_H = 0x93A - SYS___TGAMMAF_H = 0x93E - SYS___TGAMMA_H = 0x93D - SYS___TRUNC_H = 0x93F - SYS_MEMCPY = 0x094 - SYS_VFWSCANF = 0x94A - SYS_VSWSCANF = 0x94E - SYS_VWSCANF = 0x94C - SYS_INET6_RTH_ADD = 0x95D - SYS_INET6_RTH_INIT = 0x95C - SYS_INET6_RTH_REVERSE = 0x95E - SYS_INET6_RTH_SEGMENTS = 0x95F - SYS_INET6_RTH_SPACE = 0x95B - SYS_MEMMOVE = 0x095 - SYS_WCSTOLD = 0x95A - SYS_STRCPY = 0x096 - SYS_STRCMP = 0x097 - SYS_CABS = 0x98E - SYS_STRCAT = 0x098 - SYS___CABS_B = 0x98F - SYS___POW_II = 0x98A - SYS___POW_II_B = 0x98B - SYS___POW_II_H = 0x98C - SYS_CACOSF = 0x99A - SYS_CACOSL = 0x99D - SYS_STRNCAT = 0x099 - SYS___CACOSF_B = 0x99B - SYS___CACOSF_H = 0x99C - SYS___CACOSL_B = 0x99E - SYS___CACOSL_H = 0x99F - SYS_ISWALPHA = 0x100 - SYS_ISWBLANK = 0x101 - SYS___ISWBLK = 0x101 - SYS_ISWCNTRL = 0x102 - SYS_ISWDIGIT = 0x103 - SYS_ISWGRAPH = 0x104 - SYS_ISWLOWER = 0x105 - SYS_ISWPRINT = 0x106 - SYS_ISWPUNCT = 0x107 - SYS_ISWSPACE = 0x108 - SYS_ISWUPPER = 0x109 - SYS_WCTOB = 0x110 - SYS_MBRLEN = 0x111 - SYS_MBRTOWC = 0x112 - SYS_MBSRTOWC = 0x113 - SYS_MBSRTOWCS = 0x113 - SYS_WCRTOMB = 0x114 - SYS_WCSRTOMB = 0x115 - SYS_WCSRTOMBS = 0x115 - SYS___CSID = 0x116 - SYS___WCSID = 0x117 - SYS_STRPTIME = 0x118 - SYS___STRPTM = 0x118 - SYS_STRFMON = 0x119 - SYS_WCSCOLL = 0x130 - SYS_WCSXFRM = 0x131 - SYS_WCSWIDTH = 0x132 - SYS_WCWIDTH = 0x133 - SYS_WCSFTIME = 0x134 - SYS_SWPRINTF = 0x135 - SYS_VSWPRINT = 0x136 - SYS_VSWPRINTF = 0x136 - SYS_SWSCANF = 0x137 - SYS_REGCOMP = 0x138 - SYS_REGEXEC = 0x139 - SYS_GETWC = 0x140 - SYS_GETWCHAR = 0x141 - SYS_PUTWC = 0x142 - SYS_PUTWCHAR = 0x143 - SYS_UNGETWC = 0x144 - SYS_ICONV_OPEN = 0x145 - SYS_ICONV = 0x146 - SYS_ICONV_CLOSE = 0x147 - SYS_COLLRANGE = 0x150 - SYS_CCLASS = 0x151 - SYS_COLLORDER = 0x152 - SYS___DEMANGLE = 0x154 - SYS_FDOPEN = 0x155 - SYS___ERRNO = 0x156 - SYS___ERRNO2 = 0x157 - SYS___TERROR = 0x158 - SYS_MAXCOLL = 0x169 - SYS_DLLLOAD = 0x170 - SYS__EXIT = 0x174 - SYS_ACCESS = 0x175 - SYS_ALARM = 0x176 - SYS_CFGETISPEED = 0x177 - SYS_CFGETOSPEED = 0x178 - SYS_CFSETISPEED = 0x179 - SYS_CREAT = 0x180 - SYS_CTERMID = 0x181 - SYS_DUP = 0x182 - SYS_DUP2 = 0x183 - SYS_EXECL = 0x184 - SYS_EXECLE = 0x185 - SYS_EXECLP = 0x186 - SYS_EXECV = 0x187 - SYS_EXECVE = 0x188 - SYS_EXECVP = 0x189 - SYS_FSTAT = 0x190 - SYS_FSYNC = 0x191 - SYS_FTRUNCATE = 0x192 - SYS_GETCWD = 0x193 - SYS_GETEGID = 0x194 - SYS_GETEUID = 0x195 - SYS_GETGID = 0x196 - SYS_GETGRGID = 0x197 - SYS_GETGRNAM = 0x198 - SYS_GETGROUPS = 0x199 - SYS_PTHREAD_MUTEXATTR_DESTROY = 0x200 - SYS_PTHREAD_MUTEXATTR_SETKIND_NP = 0x201 - SYS_PTHREAD_MUTEXATTR_GETKIND_NP = 0x202 - SYS_PTHREAD_MUTEX_INIT = 0x203 - SYS_PTHREAD_MUTEX_DESTROY = 0x204 - SYS_PTHREAD_MUTEX_LOCK = 0x205 - SYS_PTHREAD_MUTEX_TRYLOCK = 0x206 - SYS_PTHREAD_MUTEX_UNLOCK = 0x207 - SYS_PTHREAD_ONCE = 0x209 - SYS_TW_OPEN = 0x210 - SYS_TW_FCNTL = 0x211 - SYS_PTHREAD_JOIN_D4_NP = 0x212 - SYS_PTHREAD_CONDATTR_SETKIND_NP = 0x213 - SYS_PTHREAD_CONDATTR_GETKIND_NP = 0x214 - SYS_EXTLINK_NP = 0x215 - SYS___PASSWD = 0x216 - SYS_SETGROUPS = 0x217 - SYS_INITGROUPS = 0x218 - SYS_WCSRCHR = 0x240 - SYS_SVC99 = 0x241 - SYS___SVC99 = 0x241 - SYS_WCSWCS = 0x242 - SYS_LOCALECO = 0x243 - SYS_LOCALECONV = 0x243 - SYS___LIBREL = 0x244 - SYS_RELEASE = 0x245 - SYS___RLSE = 0x245 - SYS_FLOCATE = 0x246 - SYS___FLOCT = 0x246 - SYS_FDELREC = 0x247 - SYS___FDLREC = 0x247 - SYS_FETCH = 0x248 - SYS___FETCH = 0x248 - SYS_QSORT = 0x249 - SYS___CLEANUPCATCH = 0x260 - SYS___CATCHMATCH = 0x261 - SYS___CLEAN2UPCATCH = 0x262 - SYS_GETPRIORITY = 0x270 - SYS_NICE = 0x271 - SYS_SETPRIORITY = 0x272 - SYS_GETITIMER = 0x273 - SYS_SETITIMER = 0x274 - SYS_MSGCTL = 0x275 - SYS_MSGGET = 0x276 - SYS_MSGRCV = 0x277 - SYS_MSGSND = 0x278 - SYS_MSGXRCV = 0x279 - SYS___MSGXR = 0x279 - SYS_SHMGET = 0x280 - SYS___GETIPC = 0x281 - SYS_SETGRENT = 0x282 - SYS_GETGRENT = 0x283 - SYS_ENDGRENT = 0x284 - SYS_SETPWENT = 0x285 - SYS_GETPWENT = 0x286 - SYS_ENDPWENT = 0x287 - SYS_BSD_SIGNAL = 0x288 - SYS_KILLPG = 0x289 - SYS_SIGSET = 0x290 - SYS_SIGSTACK = 0x291 - SYS_GETRLIMIT = 0x292 - SYS_SETRLIMIT = 0x293 - SYS_GETRUSAGE = 0x294 - SYS_MMAP = 0x295 - SYS_MPROTECT = 0x296 - SYS_MSYNC = 0x297 - SYS_MUNMAP = 0x298 - SYS_CONFSTR = 0x299 - SYS___NDMTRM = 0x300 - SYS_FTOK = 0x301 - SYS_BASENAME = 0x302 - SYS_DIRNAME = 0x303 - SYS_GETDTABLESIZE = 0x304 - SYS_MKSTEMP = 0x305 - SYS_MKTEMP = 0x306 - SYS_NFTW = 0x307 - SYS_GETWD = 0x308 - SYS_LOCKF = 0x309 - SYS_WORDEXP = 0x310 - SYS_WORDFREE = 0x311 - SYS_GETPGID = 0x312 - SYS_GETSID = 0x313 - SYS___UTMPXNAME = 0x314 - SYS_CUSERID = 0x315 - SYS_GETPASS = 0x316 - SYS_FNMATCH = 0x317 - SYS_FTW = 0x318 - SYS_GETW = 0x319 - SYS_ACOSH = 0x320 - SYS_ASINH = 0x321 - SYS_ATANH = 0x322 - SYS_CBRT = 0x323 - SYS_EXPM1 = 0x324 - SYS_ILOGB = 0x325 - SYS_LOGB = 0x326 - SYS_LOG1P = 0x327 - SYS_NEXTAFTER = 0x328 - SYS_RINT = 0x329 - SYS_SPAWN = 0x330 - SYS_SPAWNP = 0x331 - SYS_GETLOGIN_UU = 0x332 - SYS_ECVT = 0x333 - SYS_FCVT = 0x334 - SYS_GCVT = 0x335 - SYS_ACCEPT = 0x336 - SYS_BIND = 0x337 - SYS_CONNECT = 0x338 - SYS_ENDHOSTENT = 0x339 - SYS_GETHOSTENT = 0x340 - SYS_GETHOSTID = 0x341 - SYS_GETHOSTNAME = 0x342 - SYS_GETNETBYADDR = 0x343 - SYS_GETNETBYNAME = 0x344 - SYS_GETNETENT = 0x345 - SYS_GETPEERNAME = 0x346 - SYS_GETPROTOBYNAME = 0x347 - SYS_GETPROTOBYNUMBER = 0x348 - SYS_GETPROTOENT = 0x349 - SYS_INET_LNAOF = 0x350 - SYS_INET_MAKEADDR = 0x351 - SYS_INET_NETOF = 0x352 - SYS_INET_NETWORK = 0x353 - SYS_INET_NTOA = 0x354 - SYS_IOCTL = 0x355 - SYS_LISTEN = 0x356 - SYS_READV = 0x357 - SYS_RECV = 0x358 - SYS_RECVFROM = 0x359 - SYS_SETHOSTENT = 0x360 - SYS_SETNETENT = 0x361 - SYS_SETPEER = 0x362 - SYS_SETPROTOENT = 0x363 - SYS_SETSERVENT = 0x364 - SYS_SETSOCKOPT = 0x365 - SYS_SHUTDOWN = 0x366 - SYS_SOCKET = 0x367 - SYS_SOCKETPAIR = 0x368 - SYS_WRITEV = 0x369 - SYS_ENDNETENT = 0x370 - SYS_CLOSELOG = 0x371 - SYS_OPENLOG = 0x372 - SYS_SETLOGMASK = 0x373 - SYS_SYSLOG = 0x374 - SYS_PTSNAME = 0x375 - SYS_SETREUID = 0x376 - SYS_SETREGID = 0x377 - SYS_REALPATH = 0x378 - SYS___SIGNGAM = 0x379 - SYS_POLL = 0x380 - SYS_REXEC = 0x381 - SYS___ISASCII2 = 0x382 - SYS___TOASCII2 = 0x383 - SYS_CHPRIORITY = 0x384 - SYS_PTHREAD_ATTR_SETSYNCTYPE_NP = 0x385 - SYS_PTHREAD_ATTR_GETSYNCTYPE_NP = 0x386 - SYS_PTHREAD_SET_LIMIT_NP = 0x387 - SYS___STNETENT = 0x388 - SYS___STPROTOENT = 0x389 - SYS___SELECT1 = 0x390 - SYS_PTHREAD_SECURITY_NP = 0x391 - SYS___CHECK_RESOURCE_AUTH_NP = 0x392 - SYS___CONVERT_ID_NP = 0x393 - SYS___OPENVMREL = 0x394 - SYS_WMEMCHR = 0x395 - SYS_WMEMCMP = 0x396 - SYS_WMEMCPY = 0x397 - SYS_WMEMMOVE = 0x398 - SYS_WMEMSET = 0x399 - SYS___FPUTWC = 0x400 - SYS___PUTWC = 0x401 - SYS___PWCHAR = 0x402 - SYS___WCSFTM = 0x403 - SYS___WCSTOK = 0x404 - SYS___WCWDTH = 0x405 - SYS_T_ACCEPT = 0x409 - SYS_T_GETINFO = 0x410 - SYS_T_GETPROTADDR = 0x411 - SYS_T_GETSTATE = 0x412 - SYS_T_LISTEN = 0x413 - SYS_T_LOOK = 0x414 - SYS_T_OPEN = 0x415 - SYS_T_OPTMGMT = 0x416 - SYS_T_RCV = 0x417 - SYS_T_RCVCONNECT = 0x418 - SYS_T_RCVDIS = 0x419 - SYS_T_SNDUDATA = 0x420 - SYS_T_STRERROR = 0x421 - SYS_T_SYNC = 0x422 - SYS_T_UNBIND = 0x423 - SYS___T_ERRNO = 0x424 - SYS___RECVMSG2 = 0x425 - SYS___SENDMSG2 = 0x426 - SYS_FATTACH = 0x427 - SYS_FDETACH = 0x428 - SYS_GETMSG = 0x429 - SYS_GETCONTEXT = 0x430 - SYS_SETCONTEXT = 0x431 - SYS_MAKECONTEXT = 0x432 - SYS_SWAPCONTEXT = 0x433 - SYS_PTHREAD_GETSPECIFIC_D8_NP = 0x434 - SYS_GETCLIENTID = 0x470 - SYS___GETCLIENTID = 0x471 - SYS_GETSTABLESIZE = 0x472 - SYS_GETIBMOPT = 0x473 - SYS_GETIBMSOCKOPT = 0x474 - SYS_GIVESOCKET = 0x475 - SYS_IBMSFLUSH = 0x476 - SYS_MAXDESC = 0x477 - SYS_SETIBMOPT = 0x478 - SYS_SETIBMSOCKOPT = 0x479 - SYS___SERVER_PWU = 0x480 - SYS_PTHREAD_TAG_NP = 0x481 - SYS___CONSOLE = 0x482 - SYS___WSINIT = 0x483 - SYS___IPTCPN = 0x489 - SYS___SERVER_CLASSIFY = 0x490 - SYS___HEAPRPT = 0x496 - SYS___ISBFP = 0x500 - SYS___FP_CAST = 0x501 - SYS___CERTIFICATE = 0x502 - SYS_SEND_FILE = 0x503 - SYS_AIO_CANCEL = 0x504 - SYS_AIO_ERROR = 0x505 - SYS_AIO_READ = 0x506 - SYS_AIO_RETURN = 0x507 - SYS_AIO_SUSPEND = 0x508 - SYS_AIO_WRITE = 0x509 - SYS_PTHREAD_RWLOCK_TRYWRLOCK = 0x510 - SYS_PTHREAD_RWLOCK_UNLOCK = 0x511 - SYS_PTHREAD_RWLOCK_WRLOCK = 0x512 - SYS_PTHREAD_RWLOCKATTR_GETPSHARED = 0x513 - SYS_PTHREAD_RWLOCKATTR_SETPSHARED = 0x514 - SYS_PTHREAD_RWLOCKATTR_INIT = 0x515 - SYS_PTHREAD_RWLOCKATTR_DESTROY = 0x516 - SYS___CTTBL = 0x517 - SYS_PTHREAD_MUTEXATTR_SETTYPE = 0x518 - SYS_PTHREAD_MUTEXATTR_GETTYPE = 0x519 - SYS___FP_UNORDERED = 0x520 - SYS___FP_READ_RND = 0x521 - SYS___FP_READ_RND_B = 0x522 - SYS___FP_SWAP_RND = 0x523 - SYS___FP_SWAP_RND_B = 0x524 - SYS___FP_LEVEL = 0x525 - SYS___FP_BTOH = 0x526 - SYS___FP_HTOB = 0x527 - SYS___FPC_RD = 0x528 - SYS___FPC_WR = 0x529 - SYS_PTHREAD_SETCANCELTYPE = 0x600 - SYS_PTHREAD_TESTCANCEL = 0x601 - SYS___ATANF_B = 0x602 - SYS___ATANL_B = 0x603 - SYS___CEILF_B = 0x604 - SYS___CEILL_B = 0x605 - SYS___COSF_B = 0x606 - SYS___COSL_B = 0x607 - SYS___FABSF_B = 0x608 - SYS___FABSL_B = 0x609 - SYS___SINF_B = 0x610 - SYS___SINL_B = 0x611 - SYS___TANF_B = 0x612 - SYS___TANL_B = 0x613 - SYS___TANHF_B = 0x614 - SYS___TANHL_B = 0x615 - SYS___ACOSF_B = 0x616 - SYS___ACOSL_B = 0x617 - SYS___ASINF_B = 0x618 - SYS___ASINL_B = 0x619 - SYS___LOGF_B = 0x620 - SYS___LOGL_B = 0x621 - SYS___LOG10F_B = 0x622 - SYS___LOG10L_B = 0x623 - SYS___POWF_B = 0x624 - SYS___POWL_B = 0x625 - SYS___SINHF_B = 0x626 - SYS___SINHL_B = 0x627 - SYS___SQRTF_B = 0x628 - SYS___SQRTL_B = 0x629 - SYS___MODFL_B = 0x630 - SYS_ABSF = 0x631 - SYS_ABSL = 0x632 - SYS_ACOSF = 0x633 - SYS_ACOSL = 0x634 - SYS_ASINF = 0x635 - SYS_ASINL = 0x636 - SYS_ATAN2F = 0x637 - SYS_ATAN2L = 0x638 - SYS_ATANF = 0x639 - SYS_COSHL = 0x640 - SYS_EXPF = 0x641 - SYS_EXPL = 0x642 - SYS_TANHF = 0x643 - SYS_TANHL = 0x644 - SYS_LOG10F = 0x645 - SYS_LOG10L = 0x646 - SYS_LOGF = 0x647 - SYS_LOGL = 0x648 - SYS_POWF = 0x649 - SYS_SINHL = 0x650 - SYS_TANF = 0x651 - SYS_TANL = 0x652 - SYS_FABSF = 0x653 - SYS_FABSL = 0x654 - SYS_FLOORF = 0x655 - SYS_FLOORL = 0x656 - SYS_FMODF = 0x657 - SYS_FMODL = 0x658 - SYS_FREXPF = 0x659 - SYS___CHATTR = 0x660 - SYS___FCHATTR = 0x661 - SYS___TOCCSID = 0x662 - SYS___CSNAMETYPE = 0x663 - SYS___TOCSNAME = 0x664 - SYS___CCSIDTYPE = 0x665 - SYS___AE_CORRESTBL_QUERY = 0x666 - SYS___AE_AUTOCONVERT_STATE = 0x667 - SYS_DN_FIND = 0x668 - SYS___GETHOSTBYADDR_A = 0x669 - SYS___MBLEN_SB_A = 0x670 - SYS___MBLEN_STD_A = 0x671 - SYS___MBLEN_UTF = 0x672 - SYS___MBSTOWCS_A = 0x673 - SYS___MBSTOWCS_STD_A = 0x674 - SYS___MBTOWC_A = 0x675 - SYS___MBTOWC_ISO1 = 0x676 - SYS___MBTOWC_SBCS = 0x677 - SYS___MBTOWC_MBCS = 0x678 - SYS___MBTOWC_UTF = 0x679 - SYS___CSID_A = 0x680 - SYS___CSID_STD_A = 0x681 - SYS___WCSID_A = 0x682 - SYS___WCSID_STD_A = 0x683 - SYS___WCTOMB_A = 0x684 - SYS___WCTOMB_ISO1 = 0x685 - SYS___WCTOMB_STD_A = 0x686 - SYS___WCTOMB_UTF = 0x687 - SYS___WCWIDTH_A = 0x688 - SYS___GETGRNAM_R_A = 0x689 - SYS___READDIR_R_A = 0x690 - SYS___E2A_S = 0x691 - SYS___FNMATCH_A = 0x692 - SYS___FNMATCH_C_A = 0x693 - SYS___EXECL_A = 0x694 - SYS___FNMATCH_STD_A = 0x695 - SYS___REGCOMP_A = 0x696 - SYS___REGCOMP_STD_A = 0x697 - SYS___REGERROR_A = 0x698 - SYS___REGERROR_STD_A = 0x699 - SYS___SWPRINTF_A = 0x700 - SYS___FSCANF_A = 0x701 - SYS___SCANF_A = 0x702 - SYS___SSCANF_A = 0x703 - SYS___SWSCANF_A = 0x704 - SYS___ATOF_A = 0x705 - SYS___ATOI_A = 0x706 - SYS___ATOL_A = 0x707 - SYS___STRTOD_A = 0x708 - SYS___STRTOL_A = 0x709 - SYS___L64A_A = 0x710 - SYS___STRERROR_A = 0x711 - SYS___PERROR_A = 0x712 - SYS___FETCH_A = 0x713 - SYS___GETENV_A = 0x714 - SYS___MKSTEMP_A = 0x717 - SYS___PTSNAME_A = 0x718 - SYS___PUTENV_A = 0x719 - SYS___CHDIR_A = 0x720 - SYS___CHOWN_A = 0x721 - SYS___CHROOT_A = 0x722 - SYS___GETCWD_A = 0x723 - SYS___GETWD_A = 0x724 - SYS___LCHOWN_A = 0x725 - SYS___LINK_A = 0x726 - SYS___PATHCONF_A = 0x727 - SYS___IF_NAMEINDEX_A = 0x728 - SYS___READLINK_A = 0x729 - SYS___EXTLINK_NP_A = 0x730 - SYS___ISALNUM_A = 0x731 - SYS___ISALPHA_A = 0x732 - SYS___A2E_S = 0x733 - SYS___ISCNTRL_A = 0x734 - SYS___ISDIGIT_A = 0x735 - SYS___ISGRAPH_A = 0x736 - SYS___ISLOWER_A = 0x737 - SYS___ISPRINT_A = 0x738 - SYS___ISPUNCT_A = 0x739 - SYS___ISWALPHA_A = 0x740 - SYS___A2E_L = 0x741 - SYS___ISWCNTRL_A = 0x742 - SYS___ISWDIGIT_A = 0x743 - SYS___ISWGRAPH_A = 0x744 - SYS___ISWLOWER_A = 0x745 - SYS___ISWPRINT_A = 0x746 - SYS___ISWPUNCT_A = 0x747 - SYS___ISWSPACE_A = 0x748 - SYS___ISWUPPER_A = 0x749 - SYS___REMOVE_A = 0x750 - SYS___RENAME_A = 0x751 - SYS___TMPNAM_A = 0x752 - SYS___FOPEN_A = 0x753 - SYS___FREOPEN_A = 0x754 - SYS___CUSERID_A = 0x755 - SYS___POPEN_A = 0x756 - SYS___TEMPNAM_A = 0x757 - SYS___FTW_A = 0x758 - SYS___GETGRENT_A = 0x759 - SYS___INET_NTOP_A = 0x760 - SYS___GETPASS_A = 0x761 - SYS___GETPWENT_A = 0x762 - SYS___GETPWNAM_A = 0x763 - SYS___GETPWUID_A = 0x764 - SYS_____CHECK_RESOURCE_AUTH_NP_A = 0x765 - SYS___CHECKSCHENV_A = 0x766 - SYS___CONNECTSERVER_A = 0x767 - SYS___CONNECTWORKMGR_A = 0x768 - SYS_____CONSOLE_A = 0x769 - SYS___MSGSND_A = 0x770 - SYS___MSGXRCV_A = 0x771 - SYS___NFTW_A = 0x772 - SYS_____PASSWD_A = 0x773 - SYS___PTHREAD_SECURITY_NP_A = 0x774 - SYS___QUERYMETRICS_A = 0x775 - SYS___QUERYSCHENV = 0x776 - SYS___READV_A = 0x777 - SYS_____SERVER_CLASSIFY_A = 0x778 - SYS_____SERVER_INIT_A = 0x779 - SYS___W_GETPSENT_A = 0x780 - SYS___WRITEV_A = 0x781 - SYS___W_STATFS_A = 0x782 - SYS___W_STATVFS_A = 0x783 - SYS___FPUTC_A = 0x784 - SYS___PUTCHAR_A = 0x785 - SYS___PUTS_A = 0x786 - SYS___FGETS_A = 0x787 - SYS___GETS_A = 0x788 - SYS___FPUTS_A = 0x789 - SYS___PUTC_A = 0x790 - SYS___AE_THREAD_SETMODE = 0x791 - SYS___AE_THREAD_SWAPMODE = 0x792 - SYS___GETNETBYADDR_A = 0x793 - SYS___GETNETBYNAME_A = 0x794 - SYS___GETNETENT_A = 0x795 - SYS___GETPROTOBYNAME_A = 0x796 - SYS___GETPROTOBYNUMBER_A = 0x797 - SYS___GETPROTOENT_A = 0x798 - SYS___GETSERVBYNAME_A = 0x799 - SYS_ACL_FIRST_ENTRY = 0x800 - SYS_ACL_GET_ENTRY = 0x801 - SYS_ACL_VALID = 0x802 - SYS_ACL_CREATE_ENTRY = 0x803 - SYS_ACL_DELETE_ENTRY = 0x804 - SYS_ACL_UPDATE_ENTRY = 0x805 - SYS_ACL_DELETE_FD = 0x806 - SYS_ACL_DELETE_FILE = 0x807 - SYS_ACL_GET_FD = 0x808 - SYS_ACL_GET_FILE = 0x809 - SYS___ERFL_B = 0x810 - SYS___ERFCL_B = 0x811 - SYS___LGAMMAL_B = 0x812 - SYS___SETHOOKEVENTS = 0x813 - SYS_IF_NAMETOINDEX = 0x814 - SYS_IF_INDEXTONAME = 0x815 - SYS_IF_NAMEINDEX = 0x816 - SYS_IF_FREENAMEINDEX = 0x817 - SYS_GETADDRINFO = 0x818 - SYS_GETNAMEINFO = 0x819 - SYS___DYNFREE_A = 0x820 - SYS___RES_QUERY_A = 0x821 - SYS___RES_SEARCH_A = 0x822 - SYS___RES_QUERYDOMAIN_A = 0x823 - SYS___RES_MKQUERY_A = 0x824 - SYS___RES_SEND_A = 0x825 - SYS___DN_EXPAND_A = 0x826 - SYS___DN_SKIPNAME_A = 0x827 - SYS___DN_COMP_A = 0x828 - SYS___DN_FIND_A = 0x829 - SYS___INET_NTOA_A = 0x830 - SYS___INET_NETWORK_A = 0x831 - SYS___ACCEPT_A = 0x832 - SYS___ACCEPT_AND_RECV_A = 0x833 - SYS___BIND_A = 0x834 - SYS___CONNECT_A = 0x835 - SYS___GETPEERNAME_A = 0x836 - SYS___GETSOCKNAME_A = 0x837 - SYS___RECVFROM_A = 0x838 - SYS___SENDTO_A = 0x839 - SYS___LCHATTR = 0x840 - SYS___WRITEDOWN = 0x841 - SYS_PTHREAD_MUTEX_INIT2 = 0x842 - SYS___ACOSHF_B = 0x843 - SYS___ACOSHL_B = 0x844 - SYS___ASINHF_B = 0x845 - SYS___ASINHL_B = 0x846 - SYS___ATANHF_B = 0x847 - SYS___ATANHL_B = 0x848 - SYS___CBRTF_B = 0x849 - SYS___EXP2F_B = 0x850 - SYS___EXP2L_B = 0x851 - SYS___EXPM1F_B = 0x852 - SYS___EXPM1L_B = 0x853 - SYS___FDIMF_B = 0x854 - SYS___FDIM_B = 0x855 - SYS___FDIML_B = 0x856 - SYS___HYPOTF_B = 0x857 - SYS___HYPOTL_B = 0x858 - SYS___LOG1PF_B = 0x859 - SYS___REMQUOF_B = 0x860 - SYS___REMQUO_B = 0x861 - SYS___REMQUOL_B = 0x862 - SYS___TGAMMAF_B = 0x863 - SYS___TGAMMA_B = 0x864 - SYS___TGAMMAL_B = 0x865 - SYS___TRUNCF_B = 0x866 - SYS___TRUNC_B = 0x867 - SYS___TRUNCL_B = 0x868 - SYS___LGAMMAF_B = 0x869 - SYS_ASINHF = 0x870 - SYS_ASINHL = 0x871 - SYS_ATANHF = 0x872 - SYS_ATANHL = 0x873 - SYS_CBRTF = 0x874 - SYS_CBRTL = 0x875 - SYS_COPYSIGNF = 0x876 - SYS_CPYSIGNF = 0x876 - SYS_COPYSIGNL = 0x877 - SYS_CPYSIGNL = 0x877 - SYS_COTANF = 0x878 - SYS___COTANF = 0x878 - SYS_COTAN = 0x879 - SYS___COTAN = 0x879 - SYS_FDIM = 0x881 - SYS_FDIML = 0x882 - SYS_HYPOTF = 0x883 - SYS_HYPOTL = 0x884 - SYS_LOG1PF = 0x885 - SYS_LOG1PL = 0x886 - SYS_LOG2F = 0x887 - SYS_LOG2 = 0x888 - SYS_LOG2L = 0x889 - SYS_TGAMMA = 0x890 - SYS_TGAMMAL = 0x891 - SYS_TRUNCF = 0x892 - SYS_TRUNC = 0x893 - SYS_TRUNCL = 0x894 - SYS_LGAMMAF = 0x895 - SYS_LGAMMAL = 0x896 - SYS_LROUNDF = 0x897 - SYS_LROUND = 0x898 - SYS_ERFF = 0x899 - SYS___COSHF_H = 0x900 - SYS___COSHL_H = 0x901 - SYS___COTAN_H = 0x902 - SYS___COTANF_H = 0x903 - SYS___COTANL_H = 0x904 - SYS___ERF_H = 0x905 - SYS___ERFF_H = 0x906 - SYS___ERFL_H = 0x907 - SYS___ERFC_H = 0x908 - SYS___ERFCF_H = 0x909 - SYS___FDIMF_H = 0x910 - SYS___FDIML_H = 0x911 - SYS___FMOD_H = 0x912 - SYS___FMODF_H = 0x913 - SYS___FMODL_H = 0x914 - SYS___GAMMA_H = 0x915 - SYS___HYPOT_H = 0x916 - SYS___ILOGB_H = 0x917 - SYS___LGAMMA_H = 0x918 - SYS___LGAMMAF_H = 0x919 - SYS___LOG2L_H = 0x920 - SYS___LOG1P_H = 0x921 - SYS___LOG10_H = 0x922 - SYS___LOG10F_H = 0x923 - SYS___LOG10L_H = 0x924 - SYS___LROUND_H = 0x925 - SYS___LROUNDF_H = 0x926 - SYS___NEXTAFTER_H = 0x927 - SYS___POW_H = 0x928 - SYS___POWF_H = 0x929 - SYS___SINL_H = 0x930 - SYS___SINH_H = 0x931 - SYS___SINHF_H = 0x932 - SYS___SINHL_H = 0x933 - SYS___SQRT_H = 0x934 - SYS___SQRTF_H = 0x935 - SYS___SQRTL_H = 0x936 - SYS___TAN_H = 0x937 - SYS___TANF_H = 0x938 - SYS___TANL_H = 0x939 - SYS___TRUNCF_H = 0x940 - SYS___TRUNCL_H = 0x941 - SYS___COSH_H = 0x942 - SYS___LE_DEBUG_SET_RESUME_MCH = 0x943 - SYS_VFSCANF = 0x944 - SYS_VSCANF = 0x946 - SYS_VSSCANF = 0x948 - SYS_IMAXABS = 0x950 - SYS_IMAXDIV = 0x951 - SYS_STRTOIMAX = 0x952 - SYS_STRTOUMAX = 0x953 - SYS_WCSTOIMAX = 0x954 - SYS_WCSTOUMAX = 0x955 - SYS_ATOLL = 0x956 - SYS_STRTOF = 0x957 - SYS_STRTOLD = 0x958 - SYS_WCSTOF = 0x959 - SYS_INET6_RTH_GETADDR = 0x960 - SYS_INET6_OPT_INIT = 0x961 - SYS_INET6_OPT_APPEND = 0x962 - SYS_INET6_OPT_FINISH = 0x963 - SYS_INET6_OPT_SET_VAL = 0x964 - SYS_INET6_OPT_NEXT = 0x965 - SYS_INET6_OPT_FIND = 0x966 - SYS_INET6_OPT_GET_VAL = 0x967 - SYS___POW_I = 0x987 - SYS___POW_I_B = 0x988 - SYS___POW_I_H = 0x989 - SYS___CABS_H = 0x990 - SYS_CABSF = 0x991 - SYS___CABSF_B = 0x992 - SYS___CABSF_H = 0x993 - SYS_CABSL = 0x994 - SYS___CABSL_B = 0x995 - SYS___CABSL_H = 0x996 - SYS_CACOS = 0x997 - SYS___CACOS_B = 0x998 - SYS___CACOS_H = 0x999 + SYS_LOG = 0x17 // 23 + SYS_COSH = 0x18 // 24 + SYS_TANH = 0x19 // 25 + SYS_EXP = 0x1A // 26 + SYS_MODF = 0x1B // 27 + SYS_LOG10 = 0x1C // 28 + SYS_FREXP = 0x1D // 29 + SYS_LDEXP = 0x1E // 30 + SYS_CEIL = 0x1F // 31 + SYS_POW = 0x20 // 32 + SYS_SQRT = 0x21 // 33 + SYS_FLOOR = 0x22 // 34 + SYS_J1 = 0x23 // 35 + SYS_FABS = 0x24 // 36 + SYS_FMOD = 0x25 // 37 + SYS_J0 = 0x26 // 38 + SYS_YN = 0x27 // 39 + SYS_JN = 0x28 // 40 + SYS_Y0 = 0x29 // 41 + SYS_Y1 = 0x2A // 42 + SYS_HYPOT = 0x2B // 43 + SYS_ERF = 0x2C // 44 + SYS_ERFC = 0x2D // 45 + SYS_GAMMA = 0x2E // 46 + SYS_ISALPHA = 0x30 // 48 + SYS_ISALNUM = 0x31 // 49 + SYS_ISLOWER = 0x32 // 50 + SYS_ISCNTRL = 0x33 // 51 + SYS_ISDIGIT = 0x34 // 52 + SYS_ISGRAPH = 0x35 // 53 + SYS_ISUPPER = 0x36 // 54 + SYS_ISPRINT = 0x37 // 55 + SYS_ISPUNCT = 0x38 // 56 + SYS_ISSPACE = 0x39 // 57 + SYS_SETLOCAL = 0x3A // 58 + SYS_SETLOCALE = 0x3A // 58 + SYS_ISXDIGIT = 0x3B // 59 + SYS_TOLOWER = 0x3C // 60 + SYS_TOUPPER = 0x3D // 61 + SYS_ASIN = 0x3E // 62 + SYS_SIN = 0x3F // 63 + SYS_COS = 0x40 // 64 + SYS_TAN = 0x41 // 65 + SYS_SINH = 0x42 // 66 + SYS_ACOS = 0x43 // 67 + SYS_ATAN = 0x44 // 68 + SYS_ATAN2 = 0x45 // 69 + SYS_FTELL = 0x46 // 70 + SYS_FGETPOS = 0x47 // 71 + SYS_FSEEK = 0x48 // 72 + SYS_FSETPOS = 0x49 // 73 + SYS_FERROR = 0x4A // 74 + SYS_REWIND = 0x4B // 75 + SYS_CLEARERR = 0x4C // 76 + SYS_FEOF = 0x4D // 77 + SYS_ATOL = 0x4E // 78 + SYS_PERROR = 0x4F // 79 + SYS_ATOF = 0x50 // 80 + SYS_ATOI = 0x51 // 81 + SYS_RAND = 0x52 // 82 + SYS_STRTOD = 0x53 // 83 + SYS_STRTOL = 0x54 // 84 + SYS_STRTOUL = 0x55 // 85 + SYS_MALLOC = 0x56 // 86 + SYS_SRAND = 0x57 // 87 + SYS_CALLOC = 0x58 // 88 + SYS_FREE = 0x59 // 89 + SYS_EXIT = 0x5A // 90 + SYS_REALLOC = 0x5B // 91 + SYS_ABORT = 0x5C // 92 + SYS___ABORT = 0x5C // 92 + SYS_ATEXIT = 0x5D // 93 + SYS_RAISE = 0x5E // 94 + SYS_SETJMP = 0x5F // 95 + SYS_LONGJMP = 0x60 // 96 + SYS_SIGNAL = 0x61 // 97 + SYS_TMPNAM = 0x62 // 98 + SYS_REMOVE = 0x63 // 99 + SYS_RENAME = 0x64 // 100 + SYS_TMPFILE = 0x65 // 101 + SYS_FREOPEN = 0x66 // 102 + SYS_FCLOSE = 0x67 // 103 + SYS_FFLUSH = 0x68 // 104 + SYS_FOPEN = 0x69 // 105 + SYS_FSCANF = 0x6A // 106 + SYS_SETBUF = 0x6B // 107 + SYS_SETVBUF = 0x6C // 108 + SYS_FPRINTF = 0x6D // 109 + SYS_SSCANF = 0x6E // 110 + SYS_PRINTF = 0x6F // 111 + SYS_SCANF = 0x70 // 112 + SYS_SPRINTF = 0x71 // 113 + SYS_FGETC = 0x72 // 114 + SYS_VFPRINTF = 0x73 // 115 + SYS_VPRINTF = 0x74 // 116 + SYS_VSPRINTF = 0x75 // 117 + SYS_GETC = 0x76 // 118 + SYS_FGETS = 0x77 // 119 + SYS_FPUTC = 0x78 // 120 + SYS_FPUTS = 0x79 // 121 + SYS_PUTCHAR = 0x7A // 122 + SYS_GETCHAR = 0x7B // 123 + SYS_GETS = 0x7C // 124 + SYS_PUTC = 0x7D // 125 + SYS_FWRITE = 0x7E // 126 + SYS_PUTS = 0x7F // 127 + SYS_UNGETC = 0x80 // 128 + SYS_FREAD = 0x81 // 129 + SYS_WCSTOMBS = 0x82 // 130 + SYS_MBTOWC = 0x83 // 131 + SYS_WCTOMB = 0x84 // 132 + SYS_MBSTOWCS = 0x85 // 133 + SYS_WCSCPY = 0x86 // 134 + SYS_WCSCAT = 0x87 // 135 + SYS_WCSCHR = 0x88 // 136 + SYS_WCSCMP = 0x89 // 137 + SYS_WCSNCMP = 0x8A // 138 + SYS_WCSCSPN = 0x8B // 139 + SYS_WCSLEN = 0x8C // 140 + SYS_WCSNCAT = 0x8D // 141 + SYS_WCSSPN = 0x8E // 142 + SYS_WCSNCPY = 0x8F // 143 + SYS_ABS = 0x90 // 144 + SYS_DIV = 0x91 // 145 + SYS_LABS = 0x92 // 146 + SYS_STRNCPY = 0x93 // 147 + SYS_MEMCPY = 0x94 // 148 + SYS_MEMMOVE = 0x95 // 149 + SYS_STRCPY = 0x96 // 150 + SYS_STRCMP = 0x97 // 151 + SYS_STRCAT = 0x98 // 152 + SYS_STRNCAT = 0x99 // 153 + SYS_MEMCMP = 0x9A // 154 + SYS_MEMCHR = 0x9B // 155 + SYS_STRCOLL = 0x9C // 156 + SYS_STRNCMP = 0x9D // 157 + SYS_STRXFRM = 0x9E // 158 + SYS_STRRCHR = 0x9F // 159 + SYS_STRCHR = 0xA0 // 160 + SYS_STRCSPN = 0xA1 // 161 + SYS_STRPBRK = 0xA2 // 162 + SYS_MEMSET = 0xA3 // 163 + SYS_STRSPN = 0xA4 // 164 + SYS_STRSTR = 0xA5 // 165 + SYS_STRTOK = 0xA6 // 166 + SYS_DIFFTIME = 0xA7 // 167 + SYS_STRERROR = 0xA8 // 168 + SYS_STRLEN = 0xA9 // 169 + SYS_CLOCK = 0xAA // 170 + SYS_CTIME = 0xAB // 171 + SYS_MKTIME = 0xAC // 172 + SYS_TIME = 0xAD // 173 + SYS_ASCTIME = 0xAE // 174 + SYS_MBLEN = 0xAF // 175 + SYS_GMTIME = 0xB0 // 176 + SYS_LOCALTIM = 0xB1 // 177 + SYS_LOCALTIME = 0xB1 // 177 + SYS_STRFTIME = 0xB2 // 178 + SYS___GETCB = 0xB4 // 180 + SYS_FUPDATE = 0xB5 // 181 + SYS___FUPDT = 0xB5 // 181 + SYS_CLRMEMF = 0xBD // 189 + SYS___CLRMF = 0xBD // 189 + SYS_FETCHEP = 0xBF // 191 + SYS___FTCHEP = 0xBF // 191 + SYS_FLDATA = 0xC1 // 193 + SYS___FLDATA = 0xC1 // 193 + SYS_DYNFREE = 0xC2 // 194 + SYS___DYNFRE = 0xC2 // 194 + SYS_DYNALLOC = 0xC3 // 195 + SYS___DYNALL = 0xC3 // 195 + SYS___CDUMP = 0xC4 // 196 + SYS_CSNAP = 0xC5 // 197 + SYS___CSNAP = 0xC5 // 197 + SYS_CTRACE = 0xC6 // 198 + SYS___CTRACE = 0xC6 // 198 + SYS___CTEST = 0xC7 // 199 + SYS_SETENV = 0xC8 // 200 + SYS___SETENV = 0xC8 // 200 + SYS_CLEARENV = 0xC9 // 201 + SYS___CLRENV = 0xC9 // 201 + SYS___REGCOMP_STD = 0xEA // 234 + SYS_NL_LANGINFO = 0xFC // 252 + SYS_GETSYNTX = 0xFD // 253 + SYS_ISBLANK = 0xFE // 254 + SYS___ISBLNK = 0xFE // 254 + SYS_ISWALNUM = 0xFF // 255 + SYS_ISWALPHA = 0x100 // 256 + SYS_ISWBLANK = 0x101 // 257 + SYS___ISWBLK = 0x101 // 257 + SYS_ISWCNTRL = 0x102 // 258 + SYS_ISWDIGIT = 0x103 // 259 + SYS_ISWGRAPH = 0x104 // 260 + SYS_ISWLOWER = 0x105 // 261 + SYS_ISWPRINT = 0x106 // 262 + SYS_ISWPUNCT = 0x107 // 263 + SYS_ISWSPACE = 0x108 // 264 + SYS_ISWUPPER = 0x109 // 265 + SYS_ISWXDIGI = 0x10A // 266 + SYS_ISWXDIGIT = 0x10A // 266 + SYS_WCTYPE = 0x10B // 267 + SYS_ISWCTYPE = 0x10C // 268 + SYS_TOWLOWER = 0x10D // 269 + SYS_TOWUPPER = 0x10E // 270 + SYS_MBSINIT = 0x10F // 271 + SYS_WCTOB = 0x110 // 272 + SYS_MBRLEN = 0x111 // 273 + SYS_MBRTOWC = 0x112 // 274 + SYS_MBSRTOWC = 0x113 // 275 + SYS_MBSRTOWCS = 0x113 // 275 + SYS_WCRTOMB = 0x114 // 276 + SYS_WCSRTOMB = 0x115 // 277 + SYS_WCSRTOMBS = 0x115 // 277 + SYS___CSID = 0x116 // 278 + SYS___WCSID = 0x117 // 279 + SYS_STRPTIME = 0x118 // 280 + SYS___STRPTM = 0x118 // 280 + SYS_STRFMON = 0x119 // 281 + SYS___RPMTCH = 0x11A // 282 + SYS_WCSSTR = 0x11B // 283 + SYS_WCSTOK = 0x12C // 300 + SYS_WCSTOL = 0x12D // 301 + SYS_WCSTOD = 0x12E // 302 + SYS_WCSTOUL = 0x12F // 303 + SYS_WCSCOLL = 0x130 // 304 + SYS_WCSXFRM = 0x131 // 305 + SYS_WCSWIDTH = 0x132 // 306 + SYS_WCWIDTH = 0x133 // 307 + SYS_WCSFTIME = 0x134 // 308 + SYS_SWPRINTF = 0x135 // 309 + SYS_VSWPRINT = 0x136 // 310 + SYS_VSWPRINTF = 0x136 // 310 + SYS_SWSCANF = 0x137 // 311 + SYS_REGCOMP = 0x138 // 312 + SYS_REGEXEC = 0x139 // 313 + SYS_REGFREE = 0x13A // 314 + SYS_REGERROR = 0x13B // 315 + SYS_FGETWC = 0x13C // 316 + SYS_FGETWS = 0x13D // 317 + SYS_FPUTWC = 0x13E // 318 + SYS_FPUTWS = 0x13F // 319 + SYS_GETWC = 0x140 // 320 + SYS_GETWCHAR = 0x141 // 321 + SYS_PUTWC = 0x142 // 322 + SYS_PUTWCHAR = 0x143 // 323 + SYS_UNGETWC = 0x144 // 324 + SYS_ICONV_OPEN = 0x145 // 325 + SYS_ICONV = 0x146 // 326 + SYS_ICONV_CLOSE = 0x147 // 327 + SYS_ISMCCOLLEL = 0x14C // 332 + SYS_STRTOCOLL = 0x14D // 333 + SYS_COLLTOSTR = 0x14E // 334 + SYS_COLLEQUIV = 0x14F // 335 + SYS_COLLRANGE = 0x150 // 336 + SYS_CCLASS = 0x151 // 337 + SYS_COLLORDER = 0x152 // 338 + SYS___DEMANGLE = 0x154 // 340 + SYS_FDOPEN = 0x155 // 341 + SYS___ERRNO = 0x156 // 342 + SYS___ERRNO2 = 0x157 // 343 + SYS___TERROR = 0x158 // 344 + SYS_MAXCOLL = 0x169 // 361 + SYS_GETMCCOLL = 0x16A // 362 + SYS_GETWMCCOLL = 0x16B // 363 + SYS___ERR2AD = 0x16C // 364 + SYS_DLLQUERYFN = 0x16D // 365 + SYS_DLLQUERYVAR = 0x16E // 366 + SYS_DLLFREE = 0x16F // 367 + SYS_DLLLOAD = 0x170 // 368 + SYS__EXIT = 0x174 // 372 + SYS_ACCESS = 0x175 // 373 + SYS_ALARM = 0x176 // 374 + SYS_CFGETISPEED = 0x177 // 375 + SYS_CFGETOSPEED = 0x178 // 376 + SYS_CFSETISPEED = 0x179 // 377 + SYS_CFSETOSPEED = 0x17A // 378 + SYS_CHDIR = 0x17B // 379 + SYS_CHMOD = 0x17C // 380 + SYS_CHOWN = 0x17D // 381 + SYS_CLOSE = 0x17E // 382 + SYS_CLOSEDIR = 0x17F // 383 + SYS_CREAT = 0x180 // 384 + SYS_CTERMID = 0x181 // 385 + SYS_DUP = 0x182 // 386 + SYS_DUP2 = 0x183 // 387 + SYS_EXECL = 0x184 // 388 + SYS_EXECLE = 0x185 // 389 + SYS_EXECLP = 0x186 // 390 + SYS_EXECV = 0x187 // 391 + SYS_EXECVE = 0x188 // 392 + SYS_EXECVP = 0x189 // 393 + SYS_FCHMOD = 0x18A // 394 + SYS_FCHOWN = 0x18B // 395 + SYS_FCNTL = 0x18C // 396 + SYS_FILENO = 0x18D // 397 + SYS_FORK = 0x18E // 398 + SYS_FPATHCONF = 0x18F // 399 + SYS_FSTAT = 0x190 // 400 + SYS_FSYNC = 0x191 // 401 + SYS_FTRUNCATE = 0x192 // 402 + SYS_GETCWD = 0x193 // 403 + SYS_GETEGID = 0x194 // 404 + SYS_GETEUID = 0x195 // 405 + SYS_GETGID = 0x196 // 406 + SYS_GETGRGID = 0x197 // 407 + SYS_GETGRNAM = 0x198 // 408 + SYS_GETGROUPS = 0x199 // 409 + SYS_GETLOGIN = 0x19A // 410 + SYS_W_GETMNTENT = 0x19B // 411 + SYS_GETPGRP = 0x19C // 412 + SYS_GETPID = 0x19D // 413 + SYS_GETPPID = 0x19E // 414 + SYS_GETPWNAM = 0x19F // 415 + SYS_GETPWUID = 0x1A0 // 416 + SYS_GETUID = 0x1A1 // 417 + SYS_W_IOCTL = 0x1A2 // 418 + SYS_ISATTY = 0x1A3 // 419 + SYS_KILL = 0x1A4 // 420 + SYS_LINK = 0x1A5 // 421 + SYS_LSEEK = 0x1A6 // 422 + SYS_LSTAT = 0x1A7 // 423 + SYS_MKDIR = 0x1A8 // 424 + SYS_MKFIFO = 0x1A9 // 425 + SYS_MKNOD = 0x1AA // 426 + SYS_MOUNT = 0x1AB // 427 + SYS_OPEN = 0x1AC // 428 + SYS_OPENDIR = 0x1AD // 429 + SYS_PATHCONF = 0x1AE // 430 + SYS_PAUSE = 0x1AF // 431 + SYS_PIPE = 0x1B0 // 432 + SYS_W_GETPSENT = 0x1B1 // 433 + SYS_READ = 0x1B2 // 434 + SYS_READDIR = 0x1B3 // 435 + SYS_READLINK = 0x1B4 // 436 + SYS_REWINDDIR = 0x1B5 // 437 + SYS_RMDIR = 0x1B6 // 438 + SYS_SETEGID = 0x1B7 // 439 + SYS_SETEUID = 0x1B8 // 440 + SYS_SETGID = 0x1B9 // 441 + SYS_SETPGID = 0x1BA // 442 + SYS_SETSID = 0x1BB // 443 + SYS_SETUID = 0x1BC // 444 + SYS_SIGACTION = 0x1BD // 445 + SYS_SIGADDSET = 0x1BE // 446 + SYS_SIGDELSET = 0x1BF // 447 + SYS_SIGEMPTYSET = 0x1C0 // 448 + SYS_SIGFILLSET = 0x1C1 // 449 + SYS_SIGISMEMBER = 0x1C2 // 450 + SYS_SIGLONGJMP = 0x1C3 // 451 + SYS_SIGPENDING = 0x1C4 // 452 + SYS_SIGPROCMASK = 0x1C5 // 453 + SYS_SIGSETJMP = 0x1C6 // 454 + SYS_SIGSUSPEND = 0x1C7 // 455 + SYS_SLEEP = 0x1C8 // 456 + SYS_STAT = 0x1C9 // 457 + SYS_W_STATFS = 0x1CA // 458 + SYS_SYMLINK = 0x1CB // 459 + SYS_SYSCONF = 0x1CC // 460 + SYS_TCDRAIN = 0x1CD // 461 + SYS_TCFLOW = 0x1CE // 462 + SYS_TCFLUSH = 0x1CF // 463 + SYS_TCGETATTR = 0x1D0 // 464 + SYS_TCGETPGRP = 0x1D1 // 465 + SYS_TCSENDBREAK = 0x1D2 // 466 + SYS_TCSETATTR = 0x1D3 // 467 + SYS_TCSETPGRP = 0x1D4 // 468 + SYS_TIMES = 0x1D5 // 469 + SYS_TTYNAME = 0x1D6 // 470 + SYS_TZSET = 0x1D7 // 471 + SYS_UMASK = 0x1D8 // 472 + SYS_UMOUNT = 0x1D9 // 473 + SYS_UNAME = 0x1DA // 474 + SYS_UNLINK = 0x1DB // 475 + SYS_UTIME = 0x1DC // 476 + SYS_WAIT = 0x1DD // 477 + SYS_WAITPID = 0x1DE // 478 + SYS_WRITE = 0x1DF // 479 + SYS_CHAUDIT = 0x1E0 // 480 + SYS_FCHAUDIT = 0x1E1 // 481 + SYS_GETGROUPSBYNAME = 0x1E2 // 482 + SYS_SIGWAIT = 0x1E3 // 483 + SYS_PTHREAD_EXIT = 0x1E4 // 484 + SYS_PTHREAD_KILL = 0x1E5 // 485 + SYS_PTHREAD_ATTR_INIT = 0x1E6 // 486 + SYS_PTHREAD_ATTR_DESTROY = 0x1E7 // 487 + SYS_PTHREAD_ATTR_SETSTACKSIZE = 0x1E8 // 488 + SYS_PTHREAD_ATTR_GETSTACKSIZE = 0x1E9 // 489 + SYS_PTHREAD_ATTR_SETDETACHSTATE = 0x1EA // 490 + SYS_PTHREAD_ATTR_GETDETACHSTATE = 0x1EB // 491 + SYS_PTHREAD_ATTR_SETWEIGHT_NP = 0x1EC // 492 + SYS_PTHREAD_ATTR_GETWEIGHT_NP = 0x1ED // 493 + SYS_PTHREAD_CANCEL = 0x1EE // 494 + SYS_PTHREAD_CLEANUP_PUSH = 0x1EF // 495 + SYS_PTHREAD_CLEANUP_POP = 0x1F0 // 496 + SYS_PTHREAD_CONDATTR_INIT = 0x1F1 // 497 + SYS_PTHREAD_CONDATTR_DESTROY = 0x1F2 // 498 + SYS_PTHREAD_COND_INIT = 0x1F3 // 499 + SYS_PTHREAD_COND_DESTROY = 0x1F4 // 500 + SYS_PTHREAD_COND_SIGNAL = 0x1F5 // 501 + SYS_PTHREAD_COND_BROADCAST = 0x1F6 // 502 + SYS_PTHREAD_COND_WAIT = 0x1F7 // 503 + SYS_PTHREAD_COND_TIMEDWAIT = 0x1F8 // 504 + SYS_PTHREAD_CREATE = 0x1F9 // 505 + SYS_PTHREAD_DETACH = 0x1FA // 506 + SYS_PTHREAD_EQUAL = 0x1FB // 507 + SYS_PTHREAD_GETSPECIFIC = 0x1FC // 508 + SYS_PTHREAD_JOIN = 0x1FD // 509 + SYS_PTHREAD_KEY_CREATE = 0x1FE // 510 + SYS_PTHREAD_MUTEXATTR_INIT = 0x1FF // 511 + SYS_PTHREAD_MUTEXATTR_DESTROY = 0x200 // 512 + SYS_PTHREAD_MUTEXATTR_SETKIND_NP = 0x201 // 513 + SYS_PTHREAD_MUTEXATTR_GETKIND_NP = 0x202 // 514 + SYS_PTHREAD_MUTEX_INIT = 0x203 // 515 + SYS_PTHREAD_MUTEX_DESTROY = 0x204 // 516 + SYS_PTHREAD_MUTEX_LOCK = 0x205 // 517 + SYS_PTHREAD_MUTEX_TRYLOCK = 0x206 // 518 + SYS_PTHREAD_MUTEX_UNLOCK = 0x207 // 519 + SYS_PTHREAD_ONCE = 0x209 // 521 + SYS_PTHREAD_SELF = 0x20A // 522 + SYS_PTHREAD_SETINTR = 0x20B // 523 + SYS_PTHREAD_SETINTRTYPE = 0x20C // 524 + SYS_PTHREAD_SETSPECIFIC = 0x20D // 525 + SYS_PTHREAD_TESTINTR = 0x20E // 526 + SYS_PTHREAD_YIELD = 0x20F // 527 + SYS_TW_OPEN = 0x210 // 528 + SYS_TW_FCNTL = 0x211 // 529 + SYS_PTHREAD_JOIN_D4_NP = 0x212 // 530 + SYS_PTHREAD_CONDATTR_SETKIND_NP = 0x213 // 531 + SYS_PTHREAD_CONDATTR_GETKIND_NP = 0x214 // 532 + SYS_EXTLINK_NP = 0x215 // 533 + SYS___PASSWD = 0x216 // 534 + SYS_SETGROUPS = 0x217 // 535 + SYS_INITGROUPS = 0x218 // 536 + SYS_WCSPBRK = 0x23F // 575 + SYS_WCSRCHR = 0x240 // 576 + SYS_SVC99 = 0x241 // 577 + SYS___SVC99 = 0x241 // 577 + SYS_WCSWCS = 0x242 // 578 + SYS_LOCALECO = 0x243 // 579 + SYS_LOCALECONV = 0x243 // 579 + SYS___LIBREL = 0x244 // 580 + SYS_RELEASE = 0x245 // 581 + SYS___RLSE = 0x245 // 581 + SYS_FLOCATE = 0x246 // 582 + SYS___FLOCT = 0x246 // 582 + SYS_FDELREC = 0x247 // 583 + SYS___FDLREC = 0x247 // 583 + SYS_FETCH = 0x248 // 584 + SYS___FETCH = 0x248 // 584 + SYS_QSORT = 0x249 // 585 + SYS_GETENV = 0x24A // 586 + SYS_SYSTEM = 0x24B // 587 + SYS_BSEARCH = 0x24C // 588 + SYS_LDIV = 0x24D // 589 + SYS___THROW = 0x25E // 606 + SYS___RETHROW = 0x25F // 607 + SYS___CLEANUPCATCH = 0x260 // 608 + SYS___CATCHMATCH = 0x261 // 609 + SYS___CLEAN2UPCATCH = 0x262 // 610 + SYS_PUTENV = 0x26A // 618 + SYS___GETENV = 0x26F // 623 + SYS_GETPRIORITY = 0x270 // 624 + SYS_NICE = 0x271 // 625 + SYS_SETPRIORITY = 0x272 // 626 + SYS_GETITIMER = 0x273 // 627 + SYS_SETITIMER = 0x274 // 628 + SYS_MSGCTL = 0x275 // 629 + SYS_MSGGET = 0x276 // 630 + SYS_MSGRCV = 0x277 // 631 + SYS_MSGSND = 0x278 // 632 + SYS_MSGXRCV = 0x279 // 633 + SYS___MSGXR = 0x279 // 633 + SYS_SEMCTL = 0x27A // 634 + SYS_SEMGET = 0x27B // 635 + SYS_SEMOP = 0x27C // 636 + SYS_SHMAT = 0x27D // 637 + SYS_SHMCTL = 0x27E // 638 + SYS_SHMDT = 0x27F // 639 + SYS_SHMGET = 0x280 // 640 + SYS___GETIPC = 0x281 // 641 + SYS_SETGRENT = 0x282 // 642 + SYS_GETGRENT = 0x283 // 643 + SYS_ENDGRENT = 0x284 // 644 + SYS_SETPWENT = 0x285 // 645 + SYS_GETPWENT = 0x286 // 646 + SYS_ENDPWENT = 0x287 // 647 + SYS_BSD_SIGNAL = 0x288 // 648 + SYS_KILLPG = 0x289 // 649 + SYS_SIGALTSTACK = 0x28A // 650 + SYS_SIGHOLD = 0x28B // 651 + SYS_SIGIGNORE = 0x28C // 652 + SYS_SIGINTERRUPT = 0x28D // 653 + SYS_SIGPAUSE = 0x28E // 654 + SYS_SIGRELSE = 0x28F // 655 + SYS_SIGSET = 0x290 // 656 + SYS_SIGSTACK = 0x291 // 657 + SYS_GETRLIMIT = 0x292 // 658 + SYS_SETRLIMIT = 0x293 // 659 + SYS_GETRUSAGE = 0x294 // 660 + SYS_MMAP = 0x295 // 661 + SYS_MPROTECT = 0x296 // 662 + SYS_MSYNC = 0x297 // 663 + SYS_MUNMAP = 0x298 // 664 + SYS_CONFSTR = 0x299 // 665 + SYS_GETOPT = 0x29A // 666 + SYS_LCHOWN = 0x29B // 667 + SYS_TRUNCATE = 0x29C // 668 + SYS_GETSUBOPT = 0x29D // 669 + SYS_SETPGRP = 0x29E // 670 + SYS___GDERR = 0x29F // 671 + SYS___TZONE = 0x2A0 // 672 + SYS___DLGHT = 0x2A1 // 673 + SYS___OPARGF = 0x2A2 // 674 + SYS___OPOPTF = 0x2A3 // 675 + SYS___OPINDF = 0x2A4 // 676 + SYS___OPERRF = 0x2A5 // 677 + SYS_GETDATE = 0x2A6 // 678 + SYS_WAIT3 = 0x2A7 // 679 + SYS_WAITID = 0x2A8 // 680 + SYS___CATTRM = 0x2A9 // 681 + SYS___GDTRM = 0x2AA // 682 + SYS___RNDTRM = 0x2AB // 683 + SYS_CRYPT = 0x2AC // 684 + SYS_ENCRYPT = 0x2AD // 685 + SYS_SETKEY = 0x2AE // 686 + SYS___CNVBLK = 0x2AF // 687 + SYS___CRYTRM = 0x2B0 // 688 + SYS___ECRTRM = 0x2B1 // 689 + SYS_DRAND48 = 0x2B2 // 690 + SYS_ERAND48 = 0x2B3 // 691 + SYS_FSTATVFS = 0x2B4 // 692 + SYS_STATVFS = 0x2B5 // 693 + SYS_CATCLOSE = 0x2B6 // 694 + SYS_CATGETS = 0x2B7 // 695 + SYS_CATOPEN = 0x2B8 // 696 + SYS_BCMP = 0x2B9 // 697 + SYS_BCOPY = 0x2BA // 698 + SYS_BZERO = 0x2BB // 699 + SYS_FFS = 0x2BC // 700 + SYS_INDEX = 0x2BD // 701 + SYS_RINDEX = 0x2BE // 702 + SYS_STRCASECMP = 0x2BF // 703 + SYS_STRDUP = 0x2C0 // 704 + SYS_STRNCASECMP = 0x2C1 // 705 + SYS_INITSTATE = 0x2C2 // 706 + SYS_SETSTATE = 0x2C3 // 707 + SYS_RANDOM = 0x2C4 // 708 + SYS_SRANDOM = 0x2C5 // 709 + SYS_HCREATE = 0x2C6 // 710 + SYS_HDESTROY = 0x2C7 // 711 + SYS_HSEARCH = 0x2C8 // 712 + SYS_LFIND = 0x2C9 // 713 + SYS_LSEARCH = 0x2CA // 714 + SYS_TDELETE = 0x2CB // 715 + SYS_TFIND = 0x2CC // 716 + SYS_TSEARCH = 0x2CD // 717 + SYS_TWALK = 0x2CE // 718 + SYS_INSQUE = 0x2CF // 719 + SYS_REMQUE = 0x2D0 // 720 + SYS_POPEN = 0x2D1 // 721 + SYS_PCLOSE = 0x2D2 // 722 + SYS_SWAB = 0x2D3 // 723 + SYS_MEMCCPY = 0x2D4 // 724 + SYS_GETPAGESIZE = 0x2D8 // 728 + SYS_FCHDIR = 0x2D9 // 729 + SYS___OCLCK = 0x2DA // 730 + SYS___ATOE = 0x2DB // 731 + SYS___ATOE_L = 0x2DC // 732 + SYS___ETOA = 0x2DD // 733 + SYS___ETOA_L = 0x2DE // 734 + SYS_SETUTXENT = 0x2DF // 735 + SYS_GETUTXENT = 0x2E0 // 736 + SYS_ENDUTXENT = 0x2E1 // 737 + SYS_GETUTXID = 0x2E2 // 738 + SYS_GETUTXLINE = 0x2E3 // 739 + SYS_PUTUTXLINE = 0x2E4 // 740 + SYS_FMTMSG = 0x2E5 // 741 + SYS_JRAND48 = 0x2E6 // 742 + SYS_LRAND48 = 0x2E7 // 743 + SYS_MRAND48 = 0x2E8 // 744 + SYS_NRAND48 = 0x2E9 // 745 + SYS_LCONG48 = 0x2EA // 746 + SYS_SRAND48 = 0x2EB // 747 + SYS_SEED48 = 0x2EC // 748 + SYS_ISASCII = 0x2ED // 749 + SYS_TOASCII = 0x2EE // 750 + SYS_A64L = 0x2EF // 751 + SYS_L64A = 0x2F0 // 752 + SYS_UALARM = 0x2F1 // 753 + SYS_USLEEP = 0x2F2 // 754 + SYS___UTXTRM = 0x2F3 // 755 + SYS___SRCTRM = 0x2F4 // 756 + SYS_FTIME = 0x2F5 // 757 + SYS_GETTIMEOFDAY = 0x2F6 // 758 + SYS_DBM_CLEARERR = 0x2F7 // 759 + SYS_DBM_CLOSE = 0x2F8 // 760 + SYS_DBM_DELETE = 0x2F9 // 761 + SYS_DBM_ERROR = 0x2FA // 762 + SYS_DBM_FETCH = 0x2FB // 763 + SYS_DBM_FIRSTKEY = 0x2FC // 764 + SYS_DBM_NEXTKEY = 0x2FD // 765 + SYS_DBM_OPEN = 0x2FE // 766 + SYS_DBM_STORE = 0x2FF // 767 + SYS___NDMTRM = 0x300 // 768 + SYS_FTOK = 0x301 // 769 + SYS_BASENAME = 0x302 // 770 + SYS_DIRNAME = 0x303 // 771 + SYS_GETDTABLESIZE = 0x304 // 772 + SYS_MKSTEMP = 0x305 // 773 + SYS_MKTEMP = 0x306 // 774 + SYS_NFTW = 0x307 // 775 + SYS_GETWD = 0x308 // 776 + SYS_LOCKF = 0x309 // 777 + SYS__LONGJMP = 0x30D // 781 + SYS__SETJMP = 0x30E // 782 + SYS_VFORK = 0x30F // 783 + SYS_WORDEXP = 0x310 // 784 + SYS_WORDFREE = 0x311 // 785 + SYS_GETPGID = 0x312 // 786 + SYS_GETSID = 0x313 // 787 + SYS___UTMPXNAME = 0x314 // 788 + SYS_CUSERID = 0x315 // 789 + SYS_GETPASS = 0x316 // 790 + SYS_FNMATCH = 0x317 // 791 + SYS_FTW = 0x318 // 792 + SYS_GETW = 0x319 // 793 + SYS_GLOB = 0x31A // 794 + SYS_GLOBFREE = 0x31B // 795 + SYS_PUTW = 0x31C // 796 + SYS_SEEKDIR = 0x31D // 797 + SYS_TELLDIR = 0x31E // 798 + SYS_TEMPNAM = 0x31F // 799 + SYS_ACOSH = 0x320 // 800 + SYS_ASINH = 0x321 // 801 + SYS_ATANH = 0x322 // 802 + SYS_CBRT = 0x323 // 803 + SYS_EXPM1 = 0x324 // 804 + SYS_ILOGB = 0x325 // 805 + SYS_LOGB = 0x326 // 806 + SYS_LOG1P = 0x327 // 807 + SYS_NEXTAFTER = 0x328 // 808 + SYS_RINT = 0x329 // 809 + SYS_REMAINDER = 0x32A // 810 + SYS_SCALB = 0x32B // 811 + SYS_LGAMMA = 0x32C // 812 + SYS_TTYSLOT = 0x32D // 813 + SYS_GETTIMEOFDAY_R = 0x32E // 814 + SYS_SYNC = 0x32F // 815 + SYS_SPAWN = 0x330 // 816 + SYS_SPAWNP = 0x331 // 817 + SYS_GETLOGIN_UU = 0x332 // 818 + SYS_ECVT = 0x333 // 819 + SYS_FCVT = 0x334 // 820 + SYS_GCVT = 0x335 // 821 + SYS_ACCEPT = 0x336 // 822 + SYS_BIND = 0x337 // 823 + SYS_CONNECT = 0x338 // 824 + SYS_ENDHOSTENT = 0x339 // 825 + SYS_ENDPROTOENT = 0x33A // 826 + SYS_ENDSERVENT = 0x33B // 827 + SYS_GETHOSTBYADDR_R = 0x33C // 828 + SYS_GETHOSTBYADDR = 0x33D // 829 + SYS_GETHOSTBYNAME_R = 0x33E // 830 + SYS_GETHOSTBYNAME = 0x33F // 831 + SYS_GETHOSTENT = 0x340 // 832 + SYS_GETHOSTID = 0x341 // 833 + SYS_GETHOSTNAME = 0x342 // 834 + SYS_GETNETBYADDR = 0x343 // 835 + SYS_GETNETBYNAME = 0x344 // 836 + SYS_GETNETENT = 0x345 // 837 + SYS_GETPEERNAME = 0x346 // 838 + SYS_GETPROTOBYNAME = 0x347 // 839 + SYS_GETPROTOBYNUMBER = 0x348 // 840 + SYS_GETPROTOENT = 0x349 // 841 + SYS_GETSERVBYNAME = 0x34A // 842 + SYS_GETSERVBYPORT = 0x34B // 843 + SYS_GETSERVENT = 0x34C // 844 + SYS_GETSOCKNAME = 0x34D // 845 + SYS_GETSOCKOPT = 0x34E // 846 + SYS_INET_ADDR = 0x34F // 847 + SYS_INET_LNAOF = 0x350 // 848 + SYS_INET_MAKEADDR = 0x351 // 849 + SYS_INET_NETOF = 0x352 // 850 + SYS_INET_NETWORK = 0x353 // 851 + SYS_INET_NTOA = 0x354 // 852 + SYS_IOCTL = 0x355 // 853 + SYS_LISTEN = 0x356 // 854 + SYS_READV = 0x357 // 855 + SYS_RECV = 0x358 // 856 + SYS_RECVFROM = 0x359 // 857 + SYS_SELECT = 0x35B // 859 + SYS_SELECTEX = 0x35C // 860 + SYS_SEND = 0x35D // 861 + SYS_SENDTO = 0x35F // 863 + SYS_SETHOSTENT = 0x360 // 864 + SYS_SETNETENT = 0x361 // 865 + SYS_SETPEER = 0x362 // 866 + SYS_SETPROTOENT = 0x363 // 867 + SYS_SETSERVENT = 0x364 // 868 + SYS_SETSOCKOPT = 0x365 // 869 + SYS_SHUTDOWN = 0x366 // 870 + SYS_SOCKET = 0x367 // 871 + SYS_SOCKETPAIR = 0x368 // 872 + SYS_WRITEV = 0x369 // 873 + SYS_CHROOT = 0x36A // 874 + SYS_W_STATVFS = 0x36B // 875 + SYS_ULIMIT = 0x36C // 876 + SYS_ISNAN = 0x36D // 877 + SYS_UTIMES = 0x36E // 878 + SYS___H_ERRNO = 0x36F // 879 + SYS_ENDNETENT = 0x370 // 880 + SYS_CLOSELOG = 0x371 // 881 + SYS_OPENLOG = 0x372 // 882 + SYS_SETLOGMASK = 0x373 // 883 + SYS_SYSLOG = 0x374 // 884 + SYS_PTSNAME = 0x375 // 885 + SYS_SETREUID = 0x376 // 886 + SYS_SETREGID = 0x377 // 887 + SYS_REALPATH = 0x378 // 888 + SYS___SIGNGAM = 0x379 // 889 + SYS_GRANTPT = 0x37A // 890 + SYS_UNLOCKPT = 0x37B // 891 + SYS_TCGETSID = 0x37C // 892 + SYS___TCGETCP = 0x37D // 893 + SYS___TCSETCP = 0x37E // 894 + SYS___TCSETTABLES = 0x37F // 895 + SYS_POLL = 0x380 // 896 + SYS_REXEC = 0x381 // 897 + SYS___ISASCII2 = 0x382 // 898 + SYS___TOASCII2 = 0x383 // 899 + SYS_CHPRIORITY = 0x384 // 900 + SYS_PTHREAD_ATTR_SETSYNCTYPE_NP = 0x385 // 901 + SYS_PTHREAD_ATTR_GETSYNCTYPE_NP = 0x386 // 902 + SYS_PTHREAD_SET_LIMIT_NP = 0x387 // 903 + SYS___STNETENT = 0x388 // 904 + SYS___STPROTOENT = 0x389 // 905 + SYS___STSERVENT = 0x38A // 906 + SYS___STHOSTENT = 0x38B // 907 + SYS_NLIST = 0x38C // 908 + SYS___IPDBCS = 0x38D // 909 + SYS___IPDSPX = 0x38E // 910 + SYS___IPMSGC = 0x38F // 911 + SYS___SELECT1 = 0x390 // 912 + SYS_PTHREAD_SECURITY_NP = 0x391 // 913 + SYS___CHECK_RESOURCE_AUTH_NP = 0x392 // 914 + SYS___CONVERT_ID_NP = 0x393 // 915 + SYS___OPENVMREL = 0x394 // 916 + SYS_WMEMCHR = 0x395 // 917 + SYS_WMEMCMP = 0x396 // 918 + SYS_WMEMCPY = 0x397 // 919 + SYS_WMEMMOVE = 0x398 // 920 + SYS_WMEMSET = 0x399 // 921 + SYS___FPUTWC = 0x400 // 1024 + SYS___PUTWC = 0x401 // 1025 + SYS___PWCHAR = 0x402 // 1026 + SYS___WCSFTM = 0x403 // 1027 + SYS___WCSTOK = 0x404 // 1028 + SYS___WCWDTH = 0x405 // 1029 + SYS_T_ACCEPT = 0x409 // 1033 + SYS_T_ALLOC = 0x40A // 1034 + SYS_T_BIND = 0x40B // 1035 + SYS_T_CLOSE = 0x40C // 1036 + SYS_T_CONNECT = 0x40D // 1037 + SYS_T_ERROR = 0x40E // 1038 + SYS_T_FREE = 0x40F // 1039 + SYS_T_GETINFO = 0x410 // 1040 + SYS_T_GETPROTADDR = 0x411 // 1041 + SYS_T_GETSTATE = 0x412 // 1042 + SYS_T_LISTEN = 0x413 // 1043 + SYS_T_LOOK = 0x414 // 1044 + SYS_T_OPEN = 0x415 // 1045 + SYS_T_OPTMGMT = 0x416 // 1046 + SYS_T_RCV = 0x417 // 1047 + SYS_T_RCVCONNECT = 0x418 // 1048 + SYS_T_RCVDIS = 0x419 // 1049 + SYS_T_RCVREL = 0x41A // 1050 + SYS_T_RCVUDATA = 0x41B // 1051 + SYS_T_RCVUDERR = 0x41C // 1052 + SYS_T_SND = 0x41D // 1053 + SYS_T_SNDDIS = 0x41E // 1054 + SYS_T_SNDREL = 0x41F // 1055 + SYS_T_SNDUDATA = 0x420 // 1056 + SYS_T_STRERROR = 0x421 // 1057 + SYS_T_SYNC = 0x422 // 1058 + SYS_T_UNBIND = 0x423 // 1059 + SYS___T_ERRNO = 0x424 // 1060 + SYS___RECVMSG2 = 0x425 // 1061 + SYS___SENDMSG2 = 0x426 // 1062 + SYS_FATTACH = 0x427 // 1063 + SYS_FDETACH = 0x428 // 1064 + SYS_GETMSG = 0x429 // 1065 + SYS_GETPMSG = 0x42A // 1066 + SYS_ISASTREAM = 0x42B // 1067 + SYS_PUTMSG = 0x42C // 1068 + SYS_PUTPMSG = 0x42D // 1069 + SYS___ISPOSIXON = 0x42E // 1070 + SYS___OPENMVSREL = 0x42F // 1071 + SYS_GETCONTEXT = 0x430 // 1072 + SYS_SETCONTEXT = 0x431 // 1073 + SYS_MAKECONTEXT = 0x432 // 1074 + SYS_SWAPCONTEXT = 0x433 // 1075 + SYS_PTHREAD_GETSPECIFIC_D8_NP = 0x434 // 1076 + SYS_GETCLIENTID = 0x470 // 1136 + SYS___GETCLIENTID = 0x471 // 1137 + SYS_GETSTABLESIZE = 0x472 // 1138 + SYS_GETIBMOPT = 0x473 // 1139 + SYS_GETIBMSOCKOPT = 0x474 // 1140 + SYS_GIVESOCKET = 0x475 // 1141 + SYS_IBMSFLUSH = 0x476 // 1142 + SYS_MAXDESC = 0x477 // 1143 + SYS_SETIBMOPT = 0x478 // 1144 + SYS_SETIBMSOCKOPT = 0x479 // 1145 + SYS_SOCK_DEBUG = 0x47A // 1146 + SYS_SOCK_DO_TESTSTOR = 0x47D // 1149 + SYS_TAKESOCKET = 0x47E // 1150 + SYS___SERVER_INIT = 0x47F // 1151 + SYS___SERVER_PWU = 0x480 // 1152 + SYS_PTHREAD_TAG_NP = 0x481 // 1153 + SYS___CONSOLE = 0x482 // 1154 + SYS___WSINIT = 0x483 // 1155 + SYS___IPTCPN = 0x489 // 1161 + SYS___SMF_RECORD = 0x48A // 1162 + SYS___IPHOST = 0x48B // 1163 + SYS___IPNODE = 0x48C // 1164 + SYS___SERVER_CLASSIFY_CREATE = 0x48D // 1165 + SYS___SERVER_CLASSIFY_DESTROY = 0x48E // 1166 + SYS___SERVER_CLASSIFY_RESET = 0x48F // 1167 + SYS___SERVER_CLASSIFY = 0x490 // 1168 + SYS___HEAPRPT = 0x496 // 1174 + SYS___FNWSA = 0x49B // 1179 + SYS___SPAWN2 = 0x49D // 1181 + SYS___SPAWNP2 = 0x49E // 1182 + SYS___GDRR = 0x4A1 // 1185 + SYS___HRRNO = 0x4A2 // 1186 + SYS___OPRG = 0x4A3 // 1187 + SYS___OPRR = 0x4A4 // 1188 + SYS___OPND = 0x4A5 // 1189 + SYS___OPPT = 0x4A6 // 1190 + SYS___SIGGM = 0x4A7 // 1191 + SYS___DGHT = 0x4A8 // 1192 + SYS___TZNE = 0x4A9 // 1193 + SYS___TZZN = 0x4AA // 1194 + SYS___TRRNO = 0x4AF // 1199 + SYS___ENVN = 0x4B0 // 1200 + SYS___MLOCKALL = 0x4B1 // 1201 + SYS_CREATEWO = 0x4B2 // 1202 + SYS_CREATEWORKUNIT = 0x4B2 // 1202 + SYS_CONTINUE = 0x4B3 // 1203 + SYS_CONTINUEWORKUNIT = 0x4B3 // 1203 + SYS_CONNECTW = 0x4B4 // 1204 + SYS_CONNECTWORKMGR = 0x4B4 // 1204 + SYS_CONNECTS = 0x4B5 // 1205 + SYS_CONNECTSERVER = 0x4B5 // 1205 + SYS_DISCONNE = 0x4B6 // 1206 + SYS_DISCONNECTSERVER = 0x4B6 // 1206 + SYS_JOINWORK = 0x4B7 // 1207 + SYS_JOINWORKUNIT = 0x4B7 // 1207 + SYS_LEAVEWOR = 0x4B8 // 1208 + SYS_LEAVEWORKUNIT = 0x4B8 // 1208 + SYS_DELETEWO = 0x4B9 // 1209 + SYS_DELETEWORKUNIT = 0x4B9 // 1209 + SYS_QUERYMET = 0x4BA // 1210 + SYS_QUERYMETRICS = 0x4BA // 1210 + SYS_QUERYSCH = 0x4BB // 1211 + SYS_QUERYSCHENV = 0x4BB // 1211 + SYS_CHECKSCH = 0x4BC // 1212 + SYS_CHECKSCHENV = 0x4BC // 1212 + SYS___PID_AFFINITY = 0x4BD // 1213 + SYS___ASINH_B = 0x4BE // 1214 + SYS___ATAN_B = 0x4BF // 1215 + SYS___CBRT_B = 0x4C0 // 1216 + SYS___CEIL_B = 0x4C1 // 1217 + SYS_COPYSIGN = 0x4C2 // 1218 + SYS___COS_B = 0x4C3 // 1219 + SYS___ERF_B = 0x4C4 // 1220 + SYS___ERFC_B = 0x4C5 // 1221 + SYS___EXPM1_B = 0x4C6 // 1222 + SYS___FABS_B = 0x4C7 // 1223 + SYS_FINITE = 0x4C8 // 1224 + SYS___FLOOR_B = 0x4C9 // 1225 + SYS___FREXP_B = 0x4CA // 1226 + SYS___ILOGB_B = 0x4CB // 1227 + SYS___ISNAN_B = 0x4CC // 1228 + SYS___LDEXP_B = 0x4CD // 1229 + SYS___LOG1P_B = 0x4CE // 1230 + SYS___LOGB_B = 0x4CF // 1231 + SYS_MATHERR = 0x4D0 // 1232 + SYS___MODF_B = 0x4D1 // 1233 + SYS___NEXTAFTER_B = 0x4D2 // 1234 + SYS___RINT_B = 0x4D3 // 1235 + SYS_SCALBN = 0x4D4 // 1236 + SYS_SIGNIFIC = 0x4D5 // 1237 + SYS_SIGNIFICAND = 0x4D5 // 1237 + SYS___SIN_B = 0x4D6 // 1238 + SYS___TAN_B = 0x4D7 // 1239 + SYS___TANH_B = 0x4D8 // 1240 + SYS___ACOS_B = 0x4D9 // 1241 + SYS___ACOSH_B = 0x4DA // 1242 + SYS___ASIN_B = 0x4DB // 1243 + SYS___ATAN2_B = 0x4DC // 1244 + SYS___ATANH_B = 0x4DD // 1245 + SYS___COSH_B = 0x4DE // 1246 + SYS___EXP_B = 0x4DF // 1247 + SYS___FMOD_B = 0x4E0 // 1248 + SYS___GAMMA_B = 0x4E1 // 1249 + SYS_GAMMA_R = 0x4E2 // 1250 + SYS___HYPOT_B = 0x4E3 // 1251 + SYS___J0_B = 0x4E4 // 1252 + SYS___Y0_B = 0x4E5 // 1253 + SYS___J1_B = 0x4E6 // 1254 + SYS___Y1_B = 0x4E7 // 1255 + SYS___JN_B = 0x4E8 // 1256 + SYS___YN_B = 0x4E9 // 1257 + SYS___LGAMMA_B = 0x4EA // 1258 + SYS_LGAMMA_R = 0x4EB // 1259 + SYS___LOG_B = 0x4EC // 1260 + SYS___LOG10_B = 0x4ED // 1261 + SYS___POW_B = 0x4EE // 1262 + SYS___REMAINDER_B = 0x4EF // 1263 + SYS___SCALB_B = 0x4F0 // 1264 + SYS___SINH_B = 0x4F1 // 1265 + SYS___SQRT_B = 0x4F2 // 1266 + SYS___OPENDIR2 = 0x4F3 // 1267 + SYS___READDIR2 = 0x4F4 // 1268 + SYS___LOGIN = 0x4F5 // 1269 + SYS___OPEN_STAT = 0x4F6 // 1270 + SYS_ACCEPT_AND_RECV = 0x4F7 // 1271 + SYS___FP_SETMODE = 0x4F8 // 1272 + SYS___SIGACTIONSET = 0x4FB // 1275 + SYS___UCREATE = 0x4FC // 1276 + SYS___UMALLOC = 0x4FD // 1277 + SYS___UFREE = 0x4FE // 1278 + SYS___UHEAPREPORT = 0x4FF // 1279 + SYS___ISBFP = 0x500 // 1280 + SYS___FP_CAST = 0x501 // 1281 + SYS___CERTIFICATE = 0x502 // 1282 + SYS_SEND_FILE = 0x503 // 1283 + SYS_AIO_CANCEL = 0x504 // 1284 + SYS_AIO_ERROR = 0x505 // 1285 + SYS_AIO_READ = 0x506 // 1286 + SYS_AIO_RETURN = 0x507 // 1287 + SYS_AIO_SUSPEND = 0x508 // 1288 + SYS_AIO_WRITE = 0x509 // 1289 + SYS_PTHREAD_MUTEXATTR_GETPSHARED = 0x50A // 1290 + SYS_PTHREAD_MUTEXATTR_SETPSHARED = 0x50B // 1291 + SYS_PTHREAD_RWLOCK_DESTROY = 0x50C // 1292 + SYS_PTHREAD_RWLOCK_INIT = 0x50D // 1293 + SYS_PTHREAD_RWLOCK_RDLOCK = 0x50E // 1294 + SYS_PTHREAD_RWLOCK_TRYRDLOCK = 0x50F // 1295 + SYS_PTHREAD_RWLOCK_TRYWRLOCK = 0x510 // 1296 + SYS_PTHREAD_RWLOCK_UNLOCK = 0x511 // 1297 + SYS_PTHREAD_RWLOCK_WRLOCK = 0x512 // 1298 + SYS_PTHREAD_RWLOCKATTR_GETPSHARED = 0x513 // 1299 + SYS_PTHREAD_RWLOCKATTR_SETPSHARED = 0x514 // 1300 + SYS_PTHREAD_RWLOCKATTR_INIT = 0x515 // 1301 + SYS_PTHREAD_RWLOCKATTR_DESTROY = 0x516 // 1302 + SYS___CTTBL = 0x517 // 1303 + SYS_PTHREAD_MUTEXATTR_SETTYPE = 0x518 // 1304 + SYS_PTHREAD_MUTEXATTR_GETTYPE = 0x519 // 1305 + SYS___FP_CLR_FLAG = 0x51A // 1306 + SYS___FP_READ_FLAG = 0x51B // 1307 + SYS___FP_RAISE_XCP = 0x51C // 1308 + SYS___FP_CLASS = 0x51D // 1309 + SYS___FP_FINITE = 0x51E // 1310 + SYS___FP_ISNAN = 0x51F // 1311 + SYS___FP_UNORDERED = 0x520 // 1312 + SYS___FP_READ_RND = 0x521 // 1313 + SYS___FP_READ_RND_B = 0x522 // 1314 + SYS___FP_SWAP_RND = 0x523 // 1315 + SYS___FP_SWAP_RND_B = 0x524 // 1316 + SYS___FP_LEVEL = 0x525 // 1317 + SYS___FP_BTOH = 0x526 // 1318 + SYS___FP_HTOB = 0x527 // 1319 + SYS___FPC_RD = 0x528 // 1320 + SYS___FPC_WR = 0x529 // 1321 + SYS___FPC_RW = 0x52A // 1322 + SYS___FPC_SM = 0x52B // 1323 + SYS___FPC_RS = 0x52C // 1324 + SYS_SIGTIMEDWAIT = 0x52D // 1325 + SYS_SIGWAITINFO = 0x52E // 1326 + SYS___CHKBFP = 0x52F // 1327 + SYS___W_PIOCTL = 0x59E // 1438 + SYS___OSENV = 0x59F // 1439 + SYS_EXPORTWO = 0x5A1 // 1441 + SYS_EXPORTWORKUNIT = 0x5A1 // 1441 + SYS_UNDOEXPO = 0x5A2 // 1442 + SYS_UNDOEXPORTWORKUNIT = 0x5A2 // 1442 + SYS_IMPORTWO = 0x5A3 // 1443 + SYS_IMPORTWORKUNIT = 0x5A3 // 1443 + SYS_UNDOIMPO = 0x5A4 // 1444 + SYS_UNDOIMPORTWORKUNIT = 0x5A4 // 1444 + SYS_EXTRACTW = 0x5A5 // 1445 + SYS_EXTRACTWORKUNIT = 0x5A5 // 1445 + SYS___CPL = 0x5A6 // 1446 + SYS___MAP_INIT = 0x5A7 // 1447 + SYS___MAP_SERVICE = 0x5A8 // 1448 + SYS_SIGQUEUE = 0x5A9 // 1449 + SYS___MOUNT = 0x5AA // 1450 + SYS___GETUSERID = 0x5AB // 1451 + SYS___IPDOMAINNAME = 0x5AC // 1452 + SYS_QUERYENC = 0x5AD // 1453 + SYS_QUERYWORKUNITCLASSIFICATION = 0x5AD // 1453 + SYS_CONNECTE = 0x5AE // 1454 + SYS_CONNECTEXPORTIMPORT = 0x5AE // 1454 + SYS___FP_SWAPMODE = 0x5AF // 1455 + SYS_STRTOLL = 0x5B0 // 1456 + SYS_STRTOULL = 0x5B1 // 1457 + SYS___DSA_PREV = 0x5B2 // 1458 + SYS___EP_FIND = 0x5B3 // 1459 + SYS___SERVER_THREADS_QUERY = 0x5B4 // 1460 + SYS___MSGRCV_TIMED = 0x5B7 // 1463 + SYS___SEMOP_TIMED = 0x5B8 // 1464 + SYS___GET_CPUID = 0x5B9 // 1465 + SYS___GET_SYSTEM_SETTINGS = 0x5BA // 1466 + SYS_FTELLO = 0x5C8 // 1480 + SYS_FSEEKO = 0x5C9 // 1481 + SYS_LLDIV = 0x5CB // 1483 + SYS_WCSTOLL = 0x5CC // 1484 + SYS_WCSTOULL = 0x5CD // 1485 + SYS_LLABS = 0x5CE // 1486 + SYS___CONSOLE2 = 0x5D2 // 1490 + SYS_INET_NTOP = 0x5D3 // 1491 + SYS_INET_PTON = 0x5D4 // 1492 + SYS___RES = 0x5D6 // 1494 + SYS_RES_MKQUERY = 0x5D7 // 1495 + SYS_RES_INIT = 0x5D8 // 1496 + SYS_RES_QUERY = 0x5D9 // 1497 + SYS_RES_SEARCH = 0x5DA // 1498 + SYS_RES_SEND = 0x5DB // 1499 + SYS_RES_QUERYDOMAIN = 0x5DC // 1500 + SYS_DN_EXPAND = 0x5DD // 1501 + SYS_DN_SKIPNAME = 0x5DE // 1502 + SYS_DN_COMP = 0x5DF // 1503 + SYS_ASCTIME_R = 0x5E0 // 1504 + SYS_CTIME_R = 0x5E1 // 1505 + SYS_GMTIME_R = 0x5E2 // 1506 + SYS_LOCALTIME_R = 0x5E3 // 1507 + SYS_RAND_R = 0x5E4 // 1508 + SYS_STRTOK_R = 0x5E5 // 1509 + SYS_READDIR_R = 0x5E6 // 1510 + SYS_GETGRGID_R = 0x5E7 // 1511 + SYS_GETGRNAM_R = 0x5E8 // 1512 + SYS_GETLOGIN_R = 0x5E9 // 1513 + SYS_GETPWNAM_R = 0x5EA // 1514 + SYS_GETPWUID_R = 0x5EB // 1515 + SYS_TTYNAME_R = 0x5EC // 1516 + SYS_PTHREAD_ATFORK = 0x5ED // 1517 + SYS_PTHREAD_ATTR_GETGUARDSIZE = 0x5EE // 1518 + SYS_PTHREAD_ATTR_GETSTACKADDR = 0x5EF // 1519 + SYS_PTHREAD_ATTR_SETGUARDSIZE = 0x5F0 // 1520 + SYS_PTHREAD_ATTR_SETSTACKADDR = 0x5F1 // 1521 + SYS_PTHREAD_CONDATTR_GETPSHARED = 0x5F2 // 1522 + SYS_PTHREAD_CONDATTR_SETPSHARED = 0x5F3 // 1523 + SYS_PTHREAD_GETCONCURRENCY = 0x5F4 // 1524 + SYS_PTHREAD_KEY_DELETE = 0x5F5 // 1525 + SYS_PTHREAD_SETCONCURRENCY = 0x5F6 // 1526 + SYS_PTHREAD_SIGMASK = 0x5F7 // 1527 + SYS___DISCARDDATA = 0x5F8 // 1528 + SYS_PTHREAD_ATTR_GETSCHEDPARAM = 0x5F9 // 1529 + SYS_PTHREAD_ATTR_SETSCHEDPARAM = 0x5FA // 1530 + SYS_PTHREAD_ATTR_GETDETACHSTATE_U98 = 0x5FB // 1531 + SYS_PTHREAD_ATTR_SETDETACHSTATE_U98 = 0x5FC // 1532 + SYS_PTHREAD_DETACH_U98 = 0x5FD // 1533 + SYS_PTHREAD_GETSPECIFIC_U98 = 0x5FE // 1534 + SYS_PTHREAD_SETCANCELSTATE = 0x5FF // 1535 + SYS_PTHREAD_SETCANCELTYPE = 0x600 // 1536 + SYS_PTHREAD_TESTCANCEL = 0x601 // 1537 + SYS___ATANF_B = 0x602 // 1538 + SYS___ATANL_B = 0x603 // 1539 + SYS___CEILF_B = 0x604 // 1540 + SYS___CEILL_B = 0x605 // 1541 + SYS___COSF_B = 0x606 // 1542 + SYS___COSL_B = 0x607 // 1543 + SYS___FABSF_B = 0x608 // 1544 + SYS___FABSL_B = 0x609 // 1545 + SYS___FLOORF_B = 0x60A // 1546 + SYS___FLOORL_B = 0x60B // 1547 + SYS___FREXPF_B = 0x60C // 1548 + SYS___FREXPL_B = 0x60D // 1549 + SYS___LDEXPF_B = 0x60E // 1550 + SYS___LDEXPL_B = 0x60F // 1551 + SYS___SINF_B = 0x610 // 1552 + SYS___SINL_B = 0x611 // 1553 + SYS___TANF_B = 0x612 // 1554 + SYS___TANL_B = 0x613 // 1555 + SYS___TANHF_B = 0x614 // 1556 + SYS___TANHL_B = 0x615 // 1557 + SYS___ACOSF_B = 0x616 // 1558 + SYS___ACOSL_B = 0x617 // 1559 + SYS___ASINF_B = 0x618 // 1560 + SYS___ASINL_B = 0x619 // 1561 + SYS___ATAN2F_B = 0x61A // 1562 + SYS___ATAN2L_B = 0x61B // 1563 + SYS___COSHF_B = 0x61C // 1564 + SYS___COSHL_B = 0x61D // 1565 + SYS___EXPF_B = 0x61E // 1566 + SYS___EXPL_B = 0x61F // 1567 + SYS___LOGF_B = 0x620 // 1568 + SYS___LOGL_B = 0x621 // 1569 + SYS___LOG10F_B = 0x622 // 1570 + SYS___LOG10L_B = 0x623 // 1571 + SYS___POWF_B = 0x624 // 1572 + SYS___POWL_B = 0x625 // 1573 + SYS___SINHF_B = 0x626 // 1574 + SYS___SINHL_B = 0x627 // 1575 + SYS___SQRTF_B = 0x628 // 1576 + SYS___SQRTL_B = 0x629 // 1577 + SYS___ABSF_B = 0x62A // 1578 + SYS___ABS_B = 0x62B // 1579 + SYS___ABSL_B = 0x62C // 1580 + SYS___FMODF_B = 0x62D // 1581 + SYS___FMODL_B = 0x62E // 1582 + SYS___MODFF_B = 0x62F // 1583 + SYS___MODFL_B = 0x630 // 1584 + SYS_ABSF = 0x631 // 1585 + SYS_ABSL = 0x632 // 1586 + SYS_ACOSF = 0x633 // 1587 + SYS_ACOSL = 0x634 // 1588 + SYS_ASINF = 0x635 // 1589 + SYS_ASINL = 0x636 // 1590 + SYS_ATAN2F = 0x637 // 1591 + SYS_ATAN2L = 0x638 // 1592 + SYS_ATANF = 0x639 // 1593 + SYS_ATANL = 0x63A // 1594 + SYS_CEILF = 0x63B // 1595 + SYS_CEILL = 0x63C // 1596 + SYS_COSF = 0x63D // 1597 + SYS_COSL = 0x63E // 1598 + SYS_COSHF = 0x63F // 1599 + SYS_COSHL = 0x640 // 1600 + SYS_EXPF = 0x641 // 1601 + SYS_EXPL = 0x642 // 1602 + SYS_TANHF = 0x643 // 1603 + SYS_TANHL = 0x644 // 1604 + SYS_LOG10F = 0x645 // 1605 + SYS_LOG10L = 0x646 // 1606 + SYS_LOGF = 0x647 // 1607 + SYS_LOGL = 0x648 // 1608 + SYS_POWF = 0x649 // 1609 + SYS_POWL = 0x64A // 1610 + SYS_SINF = 0x64B // 1611 + SYS_SINL = 0x64C // 1612 + SYS_SQRTF = 0x64D // 1613 + SYS_SQRTL = 0x64E // 1614 + SYS_SINHF = 0x64F // 1615 + SYS_SINHL = 0x650 // 1616 + SYS_TANF = 0x651 // 1617 + SYS_TANL = 0x652 // 1618 + SYS_FABSF = 0x653 // 1619 + SYS_FABSL = 0x654 // 1620 + SYS_FLOORF = 0x655 // 1621 + SYS_FLOORL = 0x656 // 1622 + SYS_FMODF = 0x657 // 1623 + SYS_FMODL = 0x658 // 1624 + SYS_FREXPF = 0x659 // 1625 + SYS_FREXPL = 0x65A // 1626 + SYS_LDEXPF = 0x65B // 1627 + SYS_LDEXPL = 0x65C // 1628 + SYS_MODFF = 0x65D // 1629 + SYS_MODFL = 0x65E // 1630 + SYS_BTOWC = 0x65F // 1631 + SYS___CHATTR = 0x660 // 1632 + SYS___FCHATTR = 0x661 // 1633 + SYS___TOCCSID = 0x662 // 1634 + SYS___CSNAMETYPE = 0x663 // 1635 + SYS___TOCSNAME = 0x664 // 1636 + SYS___CCSIDTYPE = 0x665 // 1637 + SYS___AE_CORRESTBL_QUERY = 0x666 // 1638 + SYS___AE_AUTOCONVERT_STATE = 0x667 // 1639 + SYS_DN_FIND = 0x668 // 1640 + SYS___GETHOSTBYADDR_A = 0x669 // 1641 + SYS___GETHOSTBYNAME_A = 0x66A // 1642 + SYS___RES_INIT_A = 0x66B // 1643 + SYS___GETHOSTBYADDR_R_A = 0x66C // 1644 + SYS___GETHOSTBYNAME_R_A = 0x66D // 1645 + SYS___CHARMAP_INIT_A = 0x66E // 1646 + SYS___MBLEN_A = 0x66F // 1647 + SYS___MBLEN_SB_A = 0x670 // 1648 + SYS___MBLEN_STD_A = 0x671 // 1649 + SYS___MBLEN_UTF = 0x672 // 1650 + SYS___MBSTOWCS_A = 0x673 // 1651 + SYS___MBSTOWCS_STD_A = 0x674 // 1652 + SYS___MBTOWC_A = 0x675 // 1653 + SYS___MBTOWC_ISO1 = 0x676 // 1654 + SYS___MBTOWC_SBCS = 0x677 // 1655 + SYS___MBTOWC_MBCS = 0x678 // 1656 + SYS___MBTOWC_UTF = 0x679 // 1657 + SYS___WCSTOMBS_A = 0x67A // 1658 + SYS___WCSTOMBS_STD_A = 0x67B // 1659 + SYS___WCSWIDTH_A = 0x67C // 1660 + SYS___GETGRGID_R_A = 0x67D // 1661 + SYS___WCSWIDTH_STD_A = 0x67E // 1662 + SYS___WCSWIDTH_ASIA = 0x67F // 1663 + SYS___CSID_A = 0x680 // 1664 + SYS___CSID_STD_A = 0x681 // 1665 + SYS___WCSID_A = 0x682 // 1666 + SYS___WCSID_STD_A = 0x683 // 1667 + SYS___WCTOMB_A = 0x684 // 1668 + SYS___WCTOMB_ISO1 = 0x685 // 1669 + SYS___WCTOMB_STD_A = 0x686 // 1670 + SYS___WCTOMB_UTF = 0x687 // 1671 + SYS___WCWIDTH_A = 0x688 // 1672 + SYS___GETGRNAM_R_A = 0x689 // 1673 + SYS___WCWIDTH_STD_A = 0x68A // 1674 + SYS___WCWIDTH_ASIA = 0x68B // 1675 + SYS___GETPWNAM_R_A = 0x68C // 1676 + SYS___GETPWUID_R_A = 0x68D // 1677 + SYS___GETLOGIN_R_A = 0x68E // 1678 + SYS___TTYNAME_R_A = 0x68F // 1679 + SYS___READDIR_R_A = 0x690 // 1680 + SYS___E2A_S = 0x691 // 1681 + SYS___FNMATCH_A = 0x692 // 1682 + SYS___FNMATCH_C_A = 0x693 // 1683 + SYS___EXECL_A = 0x694 // 1684 + SYS___FNMATCH_STD_A = 0x695 // 1685 + SYS___REGCOMP_A = 0x696 // 1686 + SYS___REGCOMP_STD_A = 0x697 // 1687 + SYS___REGERROR_A = 0x698 // 1688 + SYS___REGERROR_STD_A = 0x699 // 1689 + SYS___REGEXEC_A = 0x69A // 1690 + SYS___REGEXEC_STD_A = 0x69B // 1691 + SYS___REGFREE_A = 0x69C // 1692 + SYS___REGFREE_STD_A = 0x69D // 1693 + SYS___STRCOLL_A = 0x69E // 1694 + SYS___STRCOLL_C_A = 0x69F // 1695 + SYS___EXECLE_A = 0x6A0 // 1696 + SYS___STRCOLL_STD_A = 0x6A1 // 1697 + SYS___STRXFRM_A = 0x6A2 // 1698 + SYS___STRXFRM_C_A = 0x6A3 // 1699 + SYS___EXECLP_A = 0x6A4 // 1700 + SYS___STRXFRM_STD_A = 0x6A5 // 1701 + SYS___WCSCOLL_A = 0x6A6 // 1702 + SYS___WCSCOLL_C_A = 0x6A7 // 1703 + SYS___WCSCOLL_STD_A = 0x6A8 // 1704 + SYS___WCSXFRM_A = 0x6A9 // 1705 + SYS___WCSXFRM_C_A = 0x6AA // 1706 + SYS___WCSXFRM_STD_A = 0x6AB // 1707 + SYS___COLLATE_INIT_A = 0x6AC // 1708 + SYS___WCTYPE_A = 0x6AD // 1709 + SYS___GET_WCTYPE_STD_A = 0x6AE // 1710 + SYS___CTYPE_INIT_A = 0x6AF // 1711 + SYS___ISWCTYPE_A = 0x6B0 // 1712 + SYS___EXECV_A = 0x6B1 // 1713 + SYS___IS_WCTYPE_STD_A = 0x6B2 // 1714 + SYS___TOWLOWER_A = 0x6B3 // 1715 + SYS___TOWLOWER_STD_A = 0x6B4 // 1716 + SYS___TOWUPPER_A = 0x6B5 // 1717 + SYS___TOWUPPER_STD_A = 0x6B6 // 1718 + SYS___LOCALE_INIT_A = 0x6B7 // 1719 + SYS___LOCALECONV_A = 0x6B8 // 1720 + SYS___LOCALECONV_STD_A = 0x6B9 // 1721 + SYS___NL_LANGINFO_A = 0x6BA // 1722 + SYS___NL_LNAGINFO_STD_A = 0x6BB // 1723 + SYS___MONETARY_INIT_A = 0x6BC // 1724 + SYS___STRFMON_A = 0x6BD // 1725 + SYS___STRFMON_STD_A = 0x6BE // 1726 + SYS___GETADDRINFO_A = 0x6BF // 1727 + SYS___CATGETS_A = 0x6C0 // 1728 + SYS___EXECVE_A = 0x6C1 // 1729 + SYS___EXECVP_A = 0x6C2 // 1730 + SYS___SPAWN_A = 0x6C3 // 1731 + SYS___GETNAMEINFO_A = 0x6C4 // 1732 + SYS___SPAWNP_A = 0x6C5 // 1733 + SYS___NUMERIC_INIT_A = 0x6C6 // 1734 + SYS___RESP_INIT_A = 0x6C7 // 1735 + SYS___RPMATCH_A = 0x6C8 // 1736 + SYS___RPMATCH_C_A = 0x6C9 // 1737 + SYS___RPMATCH_STD_A = 0x6CA // 1738 + SYS___TIME_INIT_A = 0x6CB // 1739 + SYS___STRFTIME_A = 0x6CC // 1740 + SYS___STRFTIME_STD_A = 0x6CD // 1741 + SYS___STRPTIME_A = 0x6CE // 1742 + SYS___STRPTIME_STD_A = 0x6CF // 1743 + SYS___WCSFTIME_A = 0x6D0 // 1744 + SYS___WCSFTIME_STD_A = 0x6D1 // 1745 + SYS_____SPAWN2_A = 0x6D2 // 1746 + SYS_____SPAWNP2_A = 0x6D3 // 1747 + SYS___SYNTAX_INIT_A = 0x6D4 // 1748 + SYS___TOD_INIT_A = 0x6D5 // 1749 + SYS___NL_CSINFO_A = 0x6D6 // 1750 + SYS___NL_MONINFO_A = 0x6D7 // 1751 + SYS___NL_NUMINFO_A = 0x6D8 // 1752 + SYS___NL_RESPINFO_A = 0x6D9 // 1753 + SYS___NL_TIMINFO_A = 0x6DA // 1754 + SYS___IF_NAMETOINDEX_A = 0x6DB // 1755 + SYS___IF_INDEXTONAME_A = 0x6DC // 1756 + SYS___PRINTF_A = 0x6DD // 1757 + SYS___ICONV_OPEN_A = 0x6DE // 1758 + SYS___DLLLOAD_A = 0x6DF // 1759 + SYS___DLLQUERYFN_A = 0x6E0 // 1760 + SYS___DLLQUERYVAR_A = 0x6E1 // 1761 + SYS_____CHATTR_A = 0x6E2 // 1762 + SYS___E2A_L = 0x6E3 // 1763 + SYS_____TOCCSID_A = 0x6E4 // 1764 + SYS_____TOCSNAME_A = 0x6E5 // 1765 + SYS_____CCSIDTYPE_A = 0x6E6 // 1766 + SYS_____CSNAMETYPE_A = 0x6E7 // 1767 + SYS___CHMOD_A = 0x6E8 // 1768 + SYS___MKDIR_A = 0x6E9 // 1769 + SYS___STAT_A = 0x6EA // 1770 + SYS___STAT_O_A = 0x6EB // 1771 + SYS___MKFIFO_A = 0x6EC // 1772 + SYS_____OPEN_STAT_A = 0x6ED // 1773 + SYS___LSTAT_A = 0x6EE // 1774 + SYS___LSTAT_O_A = 0x6EF // 1775 + SYS___MKNOD_A = 0x6F0 // 1776 + SYS___MOUNT_A = 0x6F1 // 1777 + SYS___UMOUNT_A = 0x6F2 // 1778 + SYS___CHAUDIT_A = 0x6F4 // 1780 + SYS___W_GETMNTENT_A = 0x6F5 // 1781 + SYS___CREAT_A = 0x6F6 // 1782 + SYS___OPEN_A = 0x6F7 // 1783 + SYS___SETLOCALE_A = 0x6F9 // 1785 + SYS___FPRINTF_A = 0x6FA // 1786 + SYS___SPRINTF_A = 0x6FB // 1787 + SYS___VFPRINTF_A = 0x6FC // 1788 + SYS___VPRINTF_A = 0x6FD // 1789 + SYS___VSPRINTF_A = 0x6FE // 1790 + SYS___VSWPRINTF_A = 0x6FF // 1791 + SYS___SWPRINTF_A = 0x700 // 1792 + SYS___FSCANF_A = 0x701 // 1793 + SYS___SCANF_A = 0x702 // 1794 + SYS___SSCANF_A = 0x703 // 1795 + SYS___SWSCANF_A = 0x704 // 1796 + SYS___ATOF_A = 0x705 // 1797 + SYS___ATOI_A = 0x706 // 1798 + SYS___ATOL_A = 0x707 // 1799 + SYS___STRTOD_A = 0x708 // 1800 + SYS___STRTOL_A = 0x709 // 1801 + SYS___STRTOUL_A = 0x70A // 1802 + SYS_____AE_CORRESTBL_QUERY_A = 0x70B // 1803 + SYS___A64L_A = 0x70C // 1804 + SYS___ECVT_A = 0x70D // 1805 + SYS___FCVT_A = 0x70E // 1806 + SYS___GCVT_A = 0x70F // 1807 + SYS___L64A_A = 0x710 // 1808 + SYS___STRERROR_A = 0x711 // 1809 + SYS___PERROR_A = 0x712 // 1810 + SYS___FETCH_A = 0x713 // 1811 + SYS___GETENV_A = 0x714 // 1812 + SYS___MKSTEMP_A = 0x717 // 1815 + SYS___PTSNAME_A = 0x718 // 1816 + SYS___PUTENV_A = 0x719 // 1817 + SYS___REALPATH_A = 0x71A // 1818 + SYS___SETENV_A = 0x71B // 1819 + SYS___SYSTEM_A = 0x71C // 1820 + SYS___GETOPT_A = 0x71D // 1821 + SYS___CATOPEN_A = 0x71E // 1822 + SYS___ACCESS_A = 0x71F // 1823 + SYS___CHDIR_A = 0x720 // 1824 + SYS___CHOWN_A = 0x721 // 1825 + SYS___CHROOT_A = 0x722 // 1826 + SYS___GETCWD_A = 0x723 // 1827 + SYS___GETWD_A = 0x724 // 1828 + SYS___LCHOWN_A = 0x725 // 1829 + SYS___LINK_A = 0x726 // 1830 + SYS___PATHCONF_A = 0x727 // 1831 + SYS___IF_NAMEINDEX_A = 0x728 // 1832 + SYS___READLINK_A = 0x729 // 1833 + SYS___RMDIR_A = 0x72A // 1834 + SYS___STATVFS_A = 0x72B // 1835 + SYS___SYMLINK_A = 0x72C // 1836 + SYS___TRUNCATE_A = 0x72D // 1837 + SYS___UNLINK_A = 0x72E // 1838 + SYS___GAI_STRERROR_A = 0x72F // 1839 + SYS___EXTLINK_NP_A = 0x730 // 1840 + SYS___ISALNUM_A = 0x731 // 1841 + SYS___ISALPHA_A = 0x732 // 1842 + SYS___A2E_S = 0x733 // 1843 + SYS___ISCNTRL_A = 0x734 // 1844 + SYS___ISDIGIT_A = 0x735 // 1845 + SYS___ISGRAPH_A = 0x736 // 1846 + SYS___ISLOWER_A = 0x737 // 1847 + SYS___ISPRINT_A = 0x738 // 1848 + SYS___ISPUNCT_A = 0x739 // 1849 + SYS___ISSPACE_A = 0x73A // 1850 + SYS___ISUPPER_A = 0x73B // 1851 + SYS___ISXDIGIT_A = 0x73C // 1852 + SYS___TOLOWER_A = 0x73D // 1853 + SYS___TOUPPER_A = 0x73E // 1854 + SYS___ISWALNUM_A = 0x73F // 1855 + SYS___ISWALPHA_A = 0x740 // 1856 + SYS___A2E_L = 0x741 // 1857 + SYS___ISWCNTRL_A = 0x742 // 1858 + SYS___ISWDIGIT_A = 0x743 // 1859 + SYS___ISWGRAPH_A = 0x744 // 1860 + SYS___ISWLOWER_A = 0x745 // 1861 + SYS___ISWPRINT_A = 0x746 // 1862 + SYS___ISWPUNCT_A = 0x747 // 1863 + SYS___ISWSPACE_A = 0x748 // 1864 + SYS___ISWUPPER_A = 0x749 // 1865 + SYS___ISWXDIGIT_A = 0x74A // 1866 + SYS___CONFSTR_A = 0x74B // 1867 + SYS___FTOK_A = 0x74C // 1868 + SYS___MKTEMP_A = 0x74D // 1869 + SYS___FDOPEN_A = 0x74E // 1870 + SYS___FLDATA_A = 0x74F // 1871 + SYS___REMOVE_A = 0x750 // 1872 + SYS___RENAME_A = 0x751 // 1873 + SYS___TMPNAM_A = 0x752 // 1874 + SYS___FOPEN_A = 0x753 // 1875 + SYS___FREOPEN_A = 0x754 // 1876 + SYS___CUSERID_A = 0x755 // 1877 + SYS___POPEN_A = 0x756 // 1878 + SYS___TEMPNAM_A = 0x757 // 1879 + SYS___FTW_A = 0x758 // 1880 + SYS___GETGRENT_A = 0x759 // 1881 + SYS___GETGRGID_A = 0x75A // 1882 + SYS___GETGRNAM_A = 0x75B // 1883 + SYS___GETGROUPSBYNAME_A = 0x75C // 1884 + SYS___GETHOSTENT_A = 0x75D // 1885 + SYS___GETHOSTNAME_A = 0x75E // 1886 + SYS___GETLOGIN_A = 0x75F // 1887 + SYS___INET_NTOP_A = 0x760 // 1888 + SYS___GETPASS_A = 0x761 // 1889 + SYS___GETPWENT_A = 0x762 // 1890 + SYS___GETPWNAM_A = 0x763 // 1891 + SYS___GETPWUID_A = 0x764 // 1892 + SYS_____CHECK_RESOURCE_AUTH_NP_A = 0x765 // 1893 + SYS___CHECKSCHENV_A = 0x766 // 1894 + SYS___CONNECTSERVER_A = 0x767 // 1895 + SYS___CONNECTWORKMGR_A = 0x768 // 1896 + SYS_____CONSOLE_A = 0x769 // 1897 + SYS___CREATEWORKUNIT_A = 0x76A // 1898 + SYS___CTERMID_A = 0x76B // 1899 + SYS___FMTMSG_A = 0x76C // 1900 + SYS___INITGROUPS_A = 0x76D // 1901 + SYS_____LOGIN_A = 0x76E // 1902 + SYS___MSGRCV_A = 0x76F // 1903 + SYS___MSGSND_A = 0x770 // 1904 + SYS___MSGXRCV_A = 0x771 // 1905 + SYS___NFTW_A = 0x772 // 1906 + SYS_____PASSWD_A = 0x773 // 1907 + SYS___PTHREAD_SECURITY_NP_A = 0x774 // 1908 + SYS___QUERYMETRICS_A = 0x775 // 1909 + SYS___QUERYSCHENV = 0x776 // 1910 + SYS___READV_A = 0x777 // 1911 + SYS_____SERVER_CLASSIFY_A = 0x778 // 1912 + SYS_____SERVER_INIT_A = 0x779 // 1913 + SYS_____SERVER_PWU_A = 0x77A // 1914 + SYS___STRCASECMP_A = 0x77B // 1915 + SYS___STRNCASECMP_A = 0x77C // 1916 + SYS___TTYNAME_A = 0x77D // 1917 + SYS___UNAME_A = 0x77E // 1918 + SYS___UTIMES_A = 0x77F // 1919 + SYS___W_GETPSENT_A = 0x780 // 1920 + SYS___WRITEV_A = 0x781 // 1921 + SYS___W_STATFS_A = 0x782 // 1922 + SYS___W_STATVFS_A = 0x783 // 1923 + SYS___FPUTC_A = 0x784 // 1924 + SYS___PUTCHAR_A = 0x785 // 1925 + SYS___PUTS_A = 0x786 // 1926 + SYS___FGETS_A = 0x787 // 1927 + SYS___GETS_A = 0x788 // 1928 + SYS___FPUTS_A = 0x789 // 1929 + SYS___FREAD_A = 0x78A // 1930 + SYS___FWRITE_A = 0x78B // 1931 + SYS___OPEN_O_A = 0x78C // 1932 + SYS___ISASCII = 0x78D // 1933 + SYS___CREAT_O_A = 0x78E // 1934 + SYS___ENVNA = 0x78F // 1935 + SYS___PUTC_A = 0x790 // 1936 + SYS___AE_THREAD_SETMODE = 0x791 // 1937 + SYS___AE_THREAD_SWAPMODE = 0x792 // 1938 + SYS___GETNETBYADDR_A = 0x793 // 1939 + SYS___GETNETBYNAME_A = 0x794 // 1940 + SYS___GETNETENT_A = 0x795 // 1941 + SYS___GETPROTOBYNAME_A = 0x796 // 1942 + SYS___GETPROTOBYNUMBER_A = 0x797 // 1943 + SYS___GETPROTOENT_A = 0x798 // 1944 + SYS___GETSERVBYNAME_A = 0x799 // 1945 + SYS___GETSERVBYPORT_A = 0x79A // 1946 + SYS___GETSERVENT_A = 0x79B // 1947 + SYS___ASCTIME_A = 0x79C // 1948 + SYS___CTIME_A = 0x79D // 1949 + SYS___GETDATE_A = 0x79E // 1950 + SYS___TZSET_A = 0x79F // 1951 + SYS___UTIME_A = 0x7A0 // 1952 + SYS___ASCTIME_R_A = 0x7A1 // 1953 + SYS___CTIME_R_A = 0x7A2 // 1954 + SYS___STRTOLL_A = 0x7A3 // 1955 + SYS___STRTOULL_A = 0x7A4 // 1956 + SYS___FPUTWC_A = 0x7A5 // 1957 + SYS___PUTWC_A = 0x7A6 // 1958 + SYS___PUTWCHAR_A = 0x7A7 // 1959 + SYS___FPUTWS_A = 0x7A8 // 1960 + SYS___UNGETWC_A = 0x7A9 // 1961 + SYS___FGETWC_A = 0x7AA // 1962 + SYS___GETWC_A = 0x7AB // 1963 + SYS___GETWCHAR_A = 0x7AC // 1964 + SYS___FGETWS_A = 0x7AD // 1965 + SYS___GETTIMEOFDAY_A = 0x7AE // 1966 + SYS___GMTIME_A = 0x7AF // 1967 + SYS___GMTIME_R_A = 0x7B0 // 1968 + SYS___LOCALTIME_A = 0x7B1 // 1969 + SYS___LOCALTIME_R_A = 0x7B2 // 1970 + SYS___MKTIME_A = 0x7B3 // 1971 + SYS___TZZNA = 0x7B4 // 1972 + SYS_UNATEXIT = 0x7B5 // 1973 + SYS___CEE3DMP_A = 0x7B6 // 1974 + SYS___CDUMP_A = 0x7B7 // 1975 + SYS___CSNAP_A = 0x7B8 // 1976 + SYS___CTEST_A = 0x7B9 // 1977 + SYS___CTRACE_A = 0x7BA // 1978 + SYS___VSWPRNTF2_A = 0x7BB // 1979 + SYS___INET_PTON_A = 0x7BC // 1980 + SYS___SYSLOG_A = 0x7BD // 1981 + SYS___CRYPT_A = 0x7BE // 1982 + SYS_____OPENDIR2_A = 0x7BF // 1983 + SYS_____READDIR2_A = 0x7C0 // 1984 + SYS___OPENDIR_A = 0x7C2 // 1986 + SYS___READDIR_A = 0x7C3 // 1987 + SYS_PREAD = 0x7C7 // 1991 + SYS_PWRITE = 0x7C8 // 1992 + SYS_M_CREATE_LAYOUT = 0x7C9 // 1993 + SYS_M_DESTROY_LAYOUT = 0x7CA // 1994 + SYS_M_GETVALUES_LAYOUT = 0x7CB // 1995 + SYS_M_SETVALUES_LAYOUT = 0x7CC // 1996 + SYS_M_TRANSFORM_LAYOUT = 0x7CD // 1997 + SYS_M_WTRANSFORM_LAYOUT = 0x7CE // 1998 + SYS_FWPRINTF = 0x7D1 // 2001 + SYS_WPRINTF = 0x7D2 // 2002 + SYS_VFWPRINT = 0x7D3 // 2003 + SYS_VFWPRINTF = 0x7D3 // 2003 + SYS_VWPRINTF = 0x7D4 // 2004 + SYS_FWSCANF = 0x7D5 // 2005 + SYS_WSCANF = 0x7D6 // 2006 + SYS_WCTRANS = 0x7D7 // 2007 + SYS_TOWCTRAN = 0x7D8 // 2008 + SYS_TOWCTRANS = 0x7D8 // 2008 + SYS___WCSTOD_A = 0x7D9 // 2009 + SYS___WCSTOL_A = 0x7DA // 2010 + SYS___WCSTOUL_A = 0x7DB // 2011 + SYS___BASENAME_A = 0x7DC // 2012 + SYS___DIRNAME_A = 0x7DD // 2013 + SYS___GLOB_A = 0x7DE // 2014 + SYS_FWIDE = 0x7DF // 2015 + SYS___OSNAME = 0x7E0 // 2016 + SYS_____OSNAME_A = 0x7E1 // 2017 + SYS___BTOWC_A = 0x7E4 // 2020 + SYS___WCTOB_A = 0x7E5 // 2021 + SYS___DBM_OPEN_A = 0x7E6 // 2022 + SYS___VFPRINTF2_A = 0x7E7 // 2023 + SYS___VPRINTF2_A = 0x7E8 // 2024 + SYS___VSPRINTF2_A = 0x7E9 // 2025 + SYS___CEIL_H = 0x7EA // 2026 + SYS___FLOOR_H = 0x7EB // 2027 + SYS___MODF_H = 0x7EC // 2028 + SYS___FABS_H = 0x7ED // 2029 + SYS___J0_H = 0x7EE // 2030 + SYS___J1_H = 0x7EF // 2031 + SYS___JN_H = 0x7F0 // 2032 + SYS___Y0_H = 0x7F1 // 2033 + SYS___Y1_H = 0x7F2 // 2034 + SYS___YN_H = 0x7F3 // 2035 + SYS___CEILF_H = 0x7F4 // 2036 + SYS___CEILL_H = 0x7F5 // 2037 + SYS___FLOORF_H = 0x7F6 // 2038 + SYS___FLOORL_H = 0x7F7 // 2039 + SYS___MODFF_H = 0x7F8 // 2040 + SYS___MODFL_H = 0x7F9 // 2041 + SYS___FABSF_H = 0x7FA // 2042 + SYS___FABSL_H = 0x7FB // 2043 + SYS___MALLOC24 = 0x7FC // 2044 + SYS___MALLOC31 = 0x7FD // 2045 + SYS_ACL_INIT = 0x7FE // 2046 + SYS_ACL_FREE = 0x7FF // 2047 + SYS_ACL_FIRST_ENTRY = 0x800 // 2048 + SYS_ACL_GET_ENTRY = 0x801 // 2049 + SYS_ACL_VALID = 0x802 // 2050 + SYS_ACL_CREATE_ENTRY = 0x803 // 2051 + SYS_ACL_DELETE_ENTRY = 0x804 // 2052 + SYS_ACL_UPDATE_ENTRY = 0x805 // 2053 + SYS_ACL_DELETE_FD = 0x806 // 2054 + SYS_ACL_DELETE_FILE = 0x807 // 2055 + SYS_ACL_GET_FD = 0x808 // 2056 + SYS_ACL_GET_FILE = 0x809 // 2057 + SYS_ACL_SET_FD = 0x80A // 2058 + SYS_ACL_SET_FILE = 0x80B // 2059 + SYS_ACL_FROM_TEXT = 0x80C // 2060 + SYS_ACL_TO_TEXT = 0x80D // 2061 + SYS_ACL_SORT = 0x80E // 2062 + SYS___SHUTDOWN_REGISTRATION = 0x80F // 2063 + SYS___ERFL_B = 0x810 // 2064 + SYS___ERFCL_B = 0x811 // 2065 + SYS___LGAMMAL_B = 0x812 // 2066 + SYS___SETHOOKEVENTS = 0x813 // 2067 + SYS_IF_NAMETOINDEX = 0x814 // 2068 + SYS_IF_INDEXTONAME = 0x815 // 2069 + SYS_IF_NAMEINDEX = 0x816 // 2070 + SYS_IF_FREENAMEINDEX = 0x817 // 2071 + SYS_GETADDRINFO = 0x818 // 2072 + SYS_GETNAMEINFO = 0x819 // 2073 + SYS_FREEADDRINFO = 0x81A // 2074 + SYS_GAI_STRERROR = 0x81B // 2075 + SYS_REXEC_AF = 0x81C // 2076 + SYS___POE = 0x81D // 2077 + SYS___DYNALLOC_A = 0x81F // 2079 + SYS___DYNFREE_A = 0x820 // 2080 + SYS___RES_QUERY_A = 0x821 // 2081 + SYS___RES_SEARCH_A = 0x822 // 2082 + SYS___RES_QUERYDOMAIN_A = 0x823 // 2083 + SYS___RES_MKQUERY_A = 0x824 // 2084 + SYS___RES_SEND_A = 0x825 // 2085 + SYS___DN_EXPAND_A = 0x826 // 2086 + SYS___DN_SKIPNAME_A = 0x827 // 2087 + SYS___DN_COMP_A = 0x828 // 2088 + SYS___DN_FIND_A = 0x829 // 2089 + SYS___NLIST_A = 0x82A // 2090 + SYS_____TCGETCP_A = 0x82B // 2091 + SYS_____TCSETCP_A = 0x82C // 2092 + SYS_____W_PIOCTL_A = 0x82E // 2094 + SYS___INET_ADDR_A = 0x82F // 2095 + SYS___INET_NTOA_A = 0x830 // 2096 + SYS___INET_NETWORK_A = 0x831 // 2097 + SYS___ACCEPT_A = 0x832 // 2098 + SYS___ACCEPT_AND_RECV_A = 0x833 // 2099 + SYS___BIND_A = 0x834 // 2100 + SYS___CONNECT_A = 0x835 // 2101 + SYS___GETPEERNAME_A = 0x836 // 2102 + SYS___GETSOCKNAME_A = 0x837 // 2103 + SYS___RECVFROM_A = 0x838 // 2104 + SYS___SENDTO_A = 0x839 // 2105 + SYS___SENDMSG_A = 0x83A // 2106 + SYS___RECVMSG_A = 0x83B // 2107 + SYS_____LCHATTR_A = 0x83C // 2108 + SYS___CABEND = 0x83D // 2109 + SYS___LE_CIB_GET = 0x83E // 2110 + SYS___SET_LAA_FOR_JIT = 0x83F // 2111 + SYS___LCHATTR = 0x840 // 2112 + SYS___WRITEDOWN = 0x841 // 2113 + SYS_PTHREAD_MUTEX_INIT2 = 0x842 // 2114 + SYS___ACOSHF_B = 0x843 // 2115 + SYS___ACOSHL_B = 0x844 // 2116 + SYS___ASINHF_B = 0x845 // 2117 + SYS___ASINHL_B = 0x846 // 2118 + SYS___ATANHF_B = 0x847 // 2119 + SYS___ATANHL_B = 0x848 // 2120 + SYS___CBRTF_B = 0x849 // 2121 + SYS___CBRTL_B = 0x84A // 2122 + SYS___COPYSIGNF_B = 0x84B // 2123 + SYS___COPYSIGNL_B = 0x84C // 2124 + SYS___COTANF_B = 0x84D // 2125 + SYS___COTAN_B = 0x84E // 2126 + SYS___COTANL_B = 0x84F // 2127 + SYS___EXP2F_B = 0x850 // 2128 + SYS___EXP2L_B = 0x851 // 2129 + SYS___EXPM1F_B = 0x852 // 2130 + SYS___EXPM1L_B = 0x853 // 2131 + SYS___FDIMF_B = 0x854 // 2132 + SYS___FDIM_B = 0x855 // 2133 + SYS___FDIML_B = 0x856 // 2134 + SYS___HYPOTF_B = 0x857 // 2135 + SYS___HYPOTL_B = 0x858 // 2136 + SYS___LOG1PF_B = 0x859 // 2137 + SYS___LOG1PL_B = 0x85A // 2138 + SYS___LOG2F_B = 0x85B // 2139 + SYS___LOG2_B = 0x85C // 2140 + SYS___LOG2L_B = 0x85D // 2141 + SYS___REMAINDERF_B = 0x85E // 2142 + SYS___REMAINDERL_B = 0x85F // 2143 + SYS___REMQUOF_B = 0x860 // 2144 + SYS___REMQUO_B = 0x861 // 2145 + SYS___REMQUOL_B = 0x862 // 2146 + SYS___TGAMMAF_B = 0x863 // 2147 + SYS___TGAMMA_B = 0x864 // 2148 + SYS___TGAMMAL_B = 0x865 // 2149 + SYS___TRUNCF_B = 0x866 // 2150 + SYS___TRUNC_B = 0x867 // 2151 + SYS___TRUNCL_B = 0x868 // 2152 + SYS___LGAMMAF_B = 0x869 // 2153 + SYS___LROUNDF_B = 0x86A // 2154 + SYS___LROUND_B = 0x86B // 2155 + SYS___ERFF_B = 0x86C // 2156 + SYS___ERFCF_B = 0x86D // 2157 + SYS_ACOSHF = 0x86E // 2158 + SYS_ACOSHL = 0x86F // 2159 + SYS_ASINHF = 0x870 // 2160 + SYS_ASINHL = 0x871 // 2161 + SYS_ATANHF = 0x872 // 2162 + SYS_ATANHL = 0x873 // 2163 + SYS_CBRTF = 0x874 // 2164 + SYS_CBRTL = 0x875 // 2165 + SYS_COPYSIGNF = 0x876 // 2166 + SYS_CPYSIGNF = 0x876 // 2166 + SYS_COPYSIGNL = 0x877 // 2167 + SYS_CPYSIGNL = 0x877 // 2167 + SYS_COTANF = 0x878 // 2168 + SYS___COTANF = 0x878 // 2168 + SYS_COTAN = 0x879 // 2169 + SYS___COTAN = 0x879 // 2169 + SYS_COTANL = 0x87A // 2170 + SYS___COTANL = 0x87A // 2170 + SYS_EXP2F = 0x87B // 2171 + SYS_EXP2L = 0x87C // 2172 + SYS_EXPM1F = 0x87D // 2173 + SYS_EXPM1L = 0x87E // 2174 + SYS_FDIMF = 0x87F // 2175 + SYS_FDIM = 0x881 // 2177 + SYS_FDIML = 0x882 // 2178 + SYS_HYPOTF = 0x883 // 2179 + SYS_HYPOTL = 0x884 // 2180 + SYS_LOG1PF = 0x885 // 2181 + SYS_LOG1PL = 0x886 // 2182 + SYS_LOG2F = 0x887 // 2183 + SYS_LOG2 = 0x888 // 2184 + SYS_LOG2L = 0x889 // 2185 + SYS_REMAINDERF = 0x88A // 2186 + SYS_REMAINDF = 0x88A // 2186 + SYS_REMAINDERL = 0x88B // 2187 + SYS_REMAINDL = 0x88B // 2187 + SYS_REMQUOF = 0x88C // 2188 + SYS_REMQUO = 0x88D // 2189 + SYS_REMQUOL = 0x88E // 2190 + SYS_TGAMMAF = 0x88F // 2191 + SYS_TGAMMA = 0x890 // 2192 + SYS_TGAMMAL = 0x891 // 2193 + SYS_TRUNCF = 0x892 // 2194 + SYS_TRUNC = 0x893 // 2195 + SYS_TRUNCL = 0x894 // 2196 + SYS_LGAMMAF = 0x895 // 2197 + SYS_LGAMMAL = 0x896 // 2198 + SYS_LROUNDF = 0x897 // 2199 + SYS_LROUND = 0x898 // 2200 + SYS_ERFF = 0x899 // 2201 + SYS_ERFL = 0x89A // 2202 + SYS_ERFCF = 0x89B // 2203 + SYS_ERFCL = 0x89C // 2204 + SYS___EXP2_B = 0x89D // 2205 + SYS_EXP2 = 0x89E // 2206 + SYS___FAR_JUMP = 0x89F // 2207 + SYS___TCGETATTR_A = 0x8A1 // 2209 + SYS___TCSETATTR_A = 0x8A2 // 2210 + SYS___SUPERKILL = 0x8A4 // 2212 + SYS___LE_CONDITION_TOKEN_BUILD = 0x8A5 // 2213 + SYS___LE_MSG_ADD_INSERT = 0x8A6 // 2214 + SYS___LE_MSG_GET = 0x8A7 // 2215 + SYS___LE_MSG_GET_AND_WRITE = 0x8A8 // 2216 + SYS___LE_MSG_WRITE = 0x8A9 // 2217 + SYS___ITOA = 0x8AA // 2218 + SYS___UTOA = 0x8AB // 2219 + SYS___LTOA = 0x8AC // 2220 + SYS___ULTOA = 0x8AD // 2221 + SYS___LLTOA = 0x8AE // 2222 + SYS___ULLTOA = 0x8AF // 2223 + SYS___ITOA_A = 0x8B0 // 2224 + SYS___UTOA_A = 0x8B1 // 2225 + SYS___LTOA_A = 0x8B2 // 2226 + SYS___ULTOA_A = 0x8B3 // 2227 + SYS___LLTOA_A = 0x8B4 // 2228 + SYS___ULLTOA_A = 0x8B5 // 2229 + SYS_____GETENV_A = 0x8C3 // 2243 + SYS___REXEC_A = 0x8C4 // 2244 + SYS___REXEC_AF_A = 0x8C5 // 2245 + SYS___GETUTXENT_A = 0x8C6 // 2246 + SYS___GETUTXID_A = 0x8C7 // 2247 + SYS___GETUTXLINE_A = 0x8C8 // 2248 + SYS___PUTUTXLINE_A = 0x8C9 // 2249 + SYS_____UTMPXNAME_A = 0x8CA // 2250 + SYS___PUTC_UNLOCKED_A = 0x8CB // 2251 + SYS___PUTCHAR_UNLOCKED_A = 0x8CC // 2252 + SYS___SNPRINTF_A = 0x8CD // 2253 + SYS___VSNPRINTF_A = 0x8CE // 2254 + SYS___DLOPEN_A = 0x8D0 // 2256 + SYS___DLSYM_A = 0x8D1 // 2257 + SYS___DLERROR_A = 0x8D2 // 2258 + SYS_FLOCKFILE = 0x8D3 // 2259 + SYS_FTRYLOCKFILE = 0x8D4 // 2260 + SYS_FUNLOCKFILE = 0x8D5 // 2261 + SYS_GETC_UNLOCKED = 0x8D6 // 2262 + SYS_GETCHAR_UNLOCKED = 0x8D7 // 2263 + SYS_PUTC_UNLOCKED = 0x8D8 // 2264 + SYS_PUTCHAR_UNLOCKED = 0x8D9 // 2265 + SYS_SNPRINTF = 0x8DA // 2266 + SYS_VSNPRINTF = 0x8DB // 2267 + SYS_DLOPEN = 0x8DD // 2269 + SYS_DLSYM = 0x8DE // 2270 + SYS_DLCLOSE = 0x8DF // 2271 + SYS_DLERROR = 0x8E0 // 2272 + SYS___SET_EXCEPTION_HANDLER = 0x8E2 // 2274 + SYS___RESET_EXCEPTION_HANDLER = 0x8E3 // 2275 + SYS___VHM_EVENT = 0x8E4 // 2276 + SYS___ABS_H = 0x8E6 // 2278 + SYS___ABSF_H = 0x8E7 // 2279 + SYS___ABSL_H = 0x8E8 // 2280 + SYS___ACOS_H = 0x8E9 // 2281 + SYS___ACOSF_H = 0x8EA // 2282 + SYS___ACOSL_H = 0x8EB // 2283 + SYS___ACOSH_H = 0x8EC // 2284 + SYS___ASIN_H = 0x8ED // 2285 + SYS___ASINF_H = 0x8EE // 2286 + SYS___ASINL_H = 0x8EF // 2287 + SYS___ASINH_H = 0x8F0 // 2288 + SYS___ATAN_H = 0x8F1 // 2289 + SYS___ATANF_H = 0x8F2 // 2290 + SYS___ATANL_H = 0x8F3 // 2291 + SYS___ATANH_H = 0x8F4 // 2292 + SYS___ATANHF_H = 0x8F5 // 2293 + SYS___ATANHL_H = 0x8F6 // 2294 + SYS___ATAN2_H = 0x8F7 // 2295 + SYS___ATAN2F_H = 0x8F8 // 2296 + SYS___ATAN2L_H = 0x8F9 // 2297 + SYS___CBRT_H = 0x8FA // 2298 + SYS___COPYSIGNF_H = 0x8FB // 2299 + SYS___COPYSIGNL_H = 0x8FC // 2300 + SYS___COS_H = 0x8FD // 2301 + SYS___COSF_H = 0x8FE // 2302 + SYS___COSL_H = 0x8FF // 2303 + SYS___COSHF_H = 0x900 // 2304 + SYS___COSHL_H = 0x901 // 2305 + SYS___COTAN_H = 0x902 // 2306 + SYS___COTANF_H = 0x903 // 2307 + SYS___COTANL_H = 0x904 // 2308 + SYS___ERF_H = 0x905 // 2309 + SYS___ERFF_H = 0x906 // 2310 + SYS___ERFL_H = 0x907 // 2311 + SYS___ERFC_H = 0x908 // 2312 + SYS___ERFCF_H = 0x909 // 2313 + SYS___ERFCL_H = 0x90A // 2314 + SYS___EXP_H = 0x90B // 2315 + SYS___EXPF_H = 0x90C // 2316 + SYS___EXPL_H = 0x90D // 2317 + SYS___EXPM1_H = 0x90E // 2318 + SYS___FDIM_H = 0x90F // 2319 + SYS___FDIMF_H = 0x910 // 2320 + SYS___FDIML_H = 0x911 // 2321 + SYS___FMOD_H = 0x912 // 2322 + SYS___FMODF_H = 0x913 // 2323 + SYS___FMODL_H = 0x914 // 2324 + SYS___GAMMA_H = 0x915 // 2325 + SYS___HYPOT_H = 0x916 // 2326 + SYS___ILOGB_H = 0x917 // 2327 + SYS___LGAMMA_H = 0x918 // 2328 + SYS___LGAMMAF_H = 0x919 // 2329 + SYS___LOG_H = 0x91A // 2330 + SYS___LOGF_H = 0x91B // 2331 + SYS___LOGL_H = 0x91C // 2332 + SYS___LOGB_H = 0x91D // 2333 + SYS___LOG2_H = 0x91E // 2334 + SYS___LOG2F_H = 0x91F // 2335 + SYS___LOG2L_H = 0x920 // 2336 + SYS___LOG1P_H = 0x921 // 2337 + SYS___LOG10_H = 0x922 // 2338 + SYS___LOG10F_H = 0x923 // 2339 + SYS___LOG10L_H = 0x924 // 2340 + SYS___LROUND_H = 0x925 // 2341 + SYS___LROUNDF_H = 0x926 // 2342 + SYS___NEXTAFTER_H = 0x927 // 2343 + SYS___POW_H = 0x928 // 2344 + SYS___POWF_H = 0x929 // 2345 + SYS___POWL_H = 0x92A // 2346 + SYS___REMAINDER_H = 0x92B // 2347 + SYS___RINT_H = 0x92C // 2348 + SYS___SCALB_H = 0x92D // 2349 + SYS___SIN_H = 0x92E // 2350 + SYS___SINF_H = 0x92F // 2351 + SYS___SINL_H = 0x930 // 2352 + SYS___SINH_H = 0x931 // 2353 + SYS___SINHF_H = 0x932 // 2354 + SYS___SINHL_H = 0x933 // 2355 + SYS___SQRT_H = 0x934 // 2356 + SYS___SQRTF_H = 0x935 // 2357 + SYS___SQRTL_H = 0x936 // 2358 + SYS___TAN_H = 0x937 // 2359 + SYS___TANF_H = 0x938 // 2360 + SYS___TANL_H = 0x939 // 2361 + SYS___TANH_H = 0x93A // 2362 + SYS___TANHF_H = 0x93B // 2363 + SYS___TANHL_H = 0x93C // 2364 + SYS___TGAMMA_H = 0x93D // 2365 + SYS___TGAMMAF_H = 0x93E // 2366 + SYS___TRUNC_H = 0x93F // 2367 + SYS___TRUNCF_H = 0x940 // 2368 + SYS___TRUNCL_H = 0x941 // 2369 + SYS___COSH_H = 0x942 // 2370 + SYS___LE_DEBUG_SET_RESUME_MCH = 0x943 // 2371 + SYS_VFSCANF = 0x944 // 2372 + SYS_VSCANF = 0x946 // 2374 + SYS_VSSCANF = 0x948 // 2376 + SYS_VFWSCANF = 0x94A // 2378 + SYS_VWSCANF = 0x94C // 2380 + SYS_VSWSCANF = 0x94E // 2382 + SYS_IMAXABS = 0x950 // 2384 + SYS_IMAXDIV = 0x951 // 2385 + SYS_STRTOIMAX = 0x952 // 2386 + SYS_STRTOUMAX = 0x953 // 2387 + SYS_WCSTOIMAX = 0x954 // 2388 + SYS_WCSTOUMAX = 0x955 // 2389 + SYS_ATOLL = 0x956 // 2390 + SYS_STRTOF = 0x957 // 2391 + SYS_STRTOLD = 0x958 // 2392 + SYS_WCSTOF = 0x959 // 2393 + SYS_WCSTOLD = 0x95A // 2394 + SYS_INET6_RTH_SPACE = 0x95B // 2395 + SYS_INET6_RTH_INIT = 0x95C // 2396 + SYS_INET6_RTH_ADD = 0x95D // 2397 + SYS_INET6_RTH_REVERSE = 0x95E // 2398 + SYS_INET6_RTH_SEGMENTS = 0x95F // 2399 + SYS_INET6_RTH_GETADDR = 0x960 // 2400 + SYS_INET6_OPT_INIT = 0x961 // 2401 + SYS_INET6_OPT_APPEND = 0x962 // 2402 + SYS_INET6_OPT_FINISH = 0x963 // 2403 + SYS_INET6_OPT_SET_VAL = 0x964 // 2404 + SYS_INET6_OPT_NEXT = 0x965 // 2405 + SYS_INET6_OPT_FIND = 0x966 // 2406 + SYS_INET6_OPT_GET_VAL = 0x967 // 2407 + SYS___POW_I = 0x987 // 2439 + SYS___POW_I_B = 0x988 // 2440 + SYS___POW_I_H = 0x989 // 2441 + SYS___POW_II = 0x98A // 2442 + SYS___POW_II_B = 0x98B // 2443 + SYS___POW_II_H = 0x98C // 2444 + SYS_CABS = 0x98E // 2446 + SYS___CABS_B = 0x98F // 2447 + SYS___CABS_H = 0x990 // 2448 + SYS_CABSF = 0x991 // 2449 + SYS___CABSF_B = 0x992 // 2450 + SYS___CABSF_H = 0x993 // 2451 + SYS_CABSL = 0x994 // 2452 + SYS___CABSL_B = 0x995 // 2453 + SYS___CABSL_H = 0x996 // 2454 + SYS_CACOS = 0x997 // 2455 + SYS___CACOS_B = 0x998 // 2456 + SYS___CACOS_H = 0x999 // 2457 + SYS_CACOSF = 0x99A // 2458 + SYS___CACOSF_B = 0x99B // 2459 + SYS___CACOSF_H = 0x99C // 2460 + SYS_CACOSL = 0x99D // 2461 + SYS___CACOSL_B = 0x99E // 2462 + SYS___CACOSL_H = 0x99F // 2463 + SYS_CACOSH = 0x9A0 // 2464 + SYS___CACOSH_B = 0x9A1 // 2465 + SYS___CACOSH_H = 0x9A2 // 2466 + SYS_CACOSHF = 0x9A3 // 2467 + SYS___CACOSHF_B = 0x9A4 // 2468 + SYS___CACOSHF_H = 0x9A5 // 2469 + SYS_CACOSHL = 0x9A6 // 2470 + SYS___CACOSHL_B = 0x9A7 // 2471 + SYS___CACOSHL_H = 0x9A8 // 2472 + SYS_CARG = 0x9A9 // 2473 + SYS___CARG_B = 0x9AA // 2474 + SYS___CARG_H = 0x9AB // 2475 + SYS_CARGF = 0x9AC // 2476 + SYS___CARGF_B = 0x9AD // 2477 + SYS___CARGF_H = 0x9AE // 2478 + SYS_CARGL = 0x9AF // 2479 + SYS___CARGL_B = 0x9B0 // 2480 + SYS___CARGL_H = 0x9B1 // 2481 + SYS_CASIN = 0x9B2 // 2482 + SYS___CASIN_B = 0x9B3 // 2483 + SYS___CASIN_H = 0x9B4 // 2484 + SYS_CASINF = 0x9B5 // 2485 + SYS___CASINF_B = 0x9B6 // 2486 + SYS___CASINF_H = 0x9B7 // 2487 + SYS_CASINL = 0x9B8 // 2488 + SYS___CASINL_B = 0x9B9 // 2489 + SYS___CASINL_H = 0x9BA // 2490 + SYS_CASINH = 0x9BB // 2491 + SYS___CASINH_B = 0x9BC // 2492 + SYS___CASINH_H = 0x9BD // 2493 + SYS_CASINHF = 0x9BE // 2494 + SYS___CASINHF_B = 0x9BF // 2495 + SYS___CASINHF_H = 0x9C0 // 2496 + SYS_CASINHL = 0x9C1 // 2497 + SYS___CASINHL_B = 0x9C2 // 2498 + SYS___CASINHL_H = 0x9C3 // 2499 + SYS_CATAN = 0x9C4 // 2500 + SYS___CATAN_B = 0x9C5 // 2501 + SYS___CATAN_H = 0x9C6 // 2502 + SYS_CATANF = 0x9C7 // 2503 + SYS___CATANF_B = 0x9C8 // 2504 + SYS___CATANF_H = 0x9C9 // 2505 + SYS_CATANL = 0x9CA // 2506 + SYS___CATANL_B = 0x9CB // 2507 + SYS___CATANL_H = 0x9CC // 2508 + SYS_CATANH = 0x9CD // 2509 + SYS___CATANH_B = 0x9CE // 2510 + SYS___CATANH_H = 0x9CF // 2511 + SYS_CATANHF = 0x9D0 // 2512 + SYS___CATANHF_B = 0x9D1 // 2513 + SYS___CATANHF_H = 0x9D2 // 2514 + SYS_CATANHL = 0x9D3 // 2515 + SYS___CATANHL_B = 0x9D4 // 2516 + SYS___CATANHL_H = 0x9D5 // 2517 + SYS_CCOS = 0x9D6 // 2518 + SYS___CCOS_B = 0x9D7 // 2519 + SYS___CCOS_H = 0x9D8 // 2520 + SYS_CCOSF = 0x9D9 // 2521 + SYS___CCOSF_B = 0x9DA // 2522 + SYS___CCOSF_H = 0x9DB // 2523 + SYS_CCOSL = 0x9DC // 2524 + SYS___CCOSL_B = 0x9DD // 2525 + SYS___CCOSL_H = 0x9DE // 2526 + SYS_CCOSH = 0x9DF // 2527 + SYS___CCOSH_B = 0x9E0 // 2528 + SYS___CCOSH_H = 0x9E1 // 2529 + SYS_CCOSHF = 0x9E2 // 2530 + SYS___CCOSHF_B = 0x9E3 // 2531 + SYS___CCOSHF_H = 0x9E4 // 2532 + SYS_CCOSHL = 0x9E5 // 2533 + SYS___CCOSHL_B = 0x9E6 // 2534 + SYS___CCOSHL_H = 0x9E7 // 2535 + SYS_CEXP = 0x9E8 // 2536 + SYS___CEXP_B = 0x9E9 // 2537 + SYS___CEXP_H = 0x9EA // 2538 + SYS_CEXPF = 0x9EB // 2539 + SYS___CEXPF_B = 0x9EC // 2540 + SYS___CEXPF_H = 0x9ED // 2541 + SYS_CEXPL = 0x9EE // 2542 + SYS___CEXPL_B = 0x9EF // 2543 + SYS___CEXPL_H = 0x9F0 // 2544 + SYS_CIMAG = 0x9F1 // 2545 + SYS___CIMAG_B = 0x9F2 // 2546 + SYS___CIMAG_H = 0x9F3 // 2547 + SYS_CIMAGF = 0x9F4 // 2548 + SYS___CIMAGF_B = 0x9F5 // 2549 + SYS___CIMAGF_H = 0x9F6 // 2550 + SYS_CIMAGL = 0x9F7 // 2551 + SYS___CIMAGL_B = 0x9F8 // 2552 + SYS___CIMAGL_H = 0x9F9 // 2553 + SYS___CLOG = 0x9FA // 2554 + SYS___CLOG_B = 0x9FB // 2555 + SYS___CLOG_H = 0x9FC // 2556 + SYS_CLOGF = 0x9FD // 2557 + SYS___CLOGF_B = 0x9FE // 2558 + SYS___CLOGF_H = 0x9FF // 2559 + SYS_CLOGL = 0xA00 // 2560 + SYS___CLOGL_B = 0xA01 // 2561 + SYS___CLOGL_H = 0xA02 // 2562 + SYS_CONJ = 0xA03 // 2563 + SYS___CONJ_B = 0xA04 // 2564 + SYS___CONJ_H = 0xA05 // 2565 + SYS_CONJF = 0xA06 // 2566 + SYS___CONJF_B = 0xA07 // 2567 + SYS___CONJF_H = 0xA08 // 2568 + SYS_CONJL = 0xA09 // 2569 + SYS___CONJL_B = 0xA0A // 2570 + SYS___CONJL_H = 0xA0B // 2571 + SYS_CPOW = 0xA0C // 2572 + SYS___CPOW_B = 0xA0D // 2573 + SYS___CPOW_H = 0xA0E // 2574 + SYS_CPOWF = 0xA0F // 2575 + SYS___CPOWF_B = 0xA10 // 2576 + SYS___CPOWF_H = 0xA11 // 2577 + SYS_CPOWL = 0xA12 // 2578 + SYS___CPOWL_B = 0xA13 // 2579 + SYS___CPOWL_H = 0xA14 // 2580 + SYS_CPROJ = 0xA15 // 2581 + SYS___CPROJ_B = 0xA16 // 2582 + SYS___CPROJ_H = 0xA17 // 2583 + SYS_CPROJF = 0xA18 // 2584 + SYS___CPROJF_B = 0xA19 // 2585 + SYS___CPROJF_H = 0xA1A // 2586 + SYS_CPROJL = 0xA1B // 2587 + SYS___CPROJL_B = 0xA1C // 2588 + SYS___CPROJL_H = 0xA1D // 2589 + SYS_CREAL = 0xA1E // 2590 + SYS___CREAL_B = 0xA1F // 2591 + SYS___CREAL_H = 0xA20 // 2592 + SYS_CREALF = 0xA21 // 2593 + SYS___CREALF_B = 0xA22 // 2594 + SYS___CREALF_H = 0xA23 // 2595 + SYS_CREALL = 0xA24 // 2596 + SYS___CREALL_B = 0xA25 // 2597 + SYS___CREALL_H = 0xA26 // 2598 + SYS_CSIN = 0xA27 // 2599 + SYS___CSIN_B = 0xA28 // 2600 + SYS___CSIN_H = 0xA29 // 2601 + SYS_CSINF = 0xA2A // 2602 + SYS___CSINF_B = 0xA2B // 2603 + SYS___CSINF_H = 0xA2C // 2604 + SYS_CSINL = 0xA2D // 2605 + SYS___CSINL_B = 0xA2E // 2606 + SYS___CSINL_H = 0xA2F // 2607 + SYS_CSINH = 0xA30 // 2608 + SYS___CSINH_B = 0xA31 // 2609 + SYS___CSINH_H = 0xA32 // 2610 + SYS_CSINHF = 0xA33 // 2611 + SYS___CSINHF_B = 0xA34 // 2612 + SYS___CSINHF_H = 0xA35 // 2613 + SYS_CSINHL = 0xA36 // 2614 + SYS___CSINHL_B = 0xA37 // 2615 + SYS___CSINHL_H = 0xA38 // 2616 + SYS_CSQRT = 0xA39 // 2617 + SYS___CSQRT_B = 0xA3A // 2618 + SYS___CSQRT_H = 0xA3B // 2619 + SYS_CSQRTF = 0xA3C // 2620 + SYS___CSQRTF_B = 0xA3D // 2621 + SYS___CSQRTF_H = 0xA3E // 2622 + SYS_CSQRTL = 0xA3F // 2623 + SYS___CSQRTL_B = 0xA40 // 2624 + SYS___CSQRTL_H = 0xA41 // 2625 + SYS_CTAN = 0xA42 // 2626 + SYS___CTAN_B = 0xA43 // 2627 + SYS___CTAN_H = 0xA44 // 2628 + SYS_CTANF = 0xA45 // 2629 + SYS___CTANF_B = 0xA46 // 2630 + SYS___CTANF_H = 0xA47 // 2631 + SYS_CTANL = 0xA48 // 2632 + SYS___CTANL_B = 0xA49 // 2633 + SYS___CTANL_H = 0xA4A // 2634 + SYS_CTANH = 0xA4B // 2635 + SYS___CTANH_B = 0xA4C // 2636 + SYS___CTANH_H = 0xA4D // 2637 + SYS_CTANHF = 0xA4E // 2638 + SYS___CTANHF_B = 0xA4F // 2639 + SYS___CTANHF_H = 0xA50 // 2640 + SYS_CTANHL = 0xA51 // 2641 + SYS___CTANHL_B = 0xA52 // 2642 + SYS___CTANHL_H = 0xA53 // 2643 + SYS___ACOSHF_H = 0xA54 // 2644 + SYS___ACOSHL_H = 0xA55 // 2645 + SYS___ASINHF_H = 0xA56 // 2646 + SYS___ASINHL_H = 0xA57 // 2647 + SYS___CBRTF_H = 0xA58 // 2648 + SYS___CBRTL_H = 0xA59 // 2649 + SYS___COPYSIGN_B = 0xA5A // 2650 + SYS___EXPM1F_H = 0xA5B // 2651 + SYS___EXPM1L_H = 0xA5C // 2652 + SYS___EXP2_H = 0xA5D // 2653 + SYS___EXP2F_H = 0xA5E // 2654 + SYS___EXP2L_H = 0xA5F // 2655 + SYS___LOG1PF_H = 0xA60 // 2656 + SYS___LOG1PL_H = 0xA61 // 2657 + SYS___LGAMMAL_H = 0xA62 // 2658 + SYS_FMA = 0xA63 // 2659 + SYS___FMA_B = 0xA64 // 2660 + SYS___FMA_H = 0xA65 // 2661 + SYS_FMAF = 0xA66 // 2662 + SYS___FMAF_B = 0xA67 // 2663 + SYS___FMAF_H = 0xA68 // 2664 + SYS_FMAL = 0xA69 // 2665 + SYS___FMAL_B = 0xA6A // 2666 + SYS___FMAL_H = 0xA6B // 2667 + SYS_FMAX = 0xA6C // 2668 + SYS___FMAX_B = 0xA6D // 2669 + SYS___FMAX_H = 0xA6E // 2670 + SYS_FMAXF = 0xA6F // 2671 + SYS___FMAXF_B = 0xA70 // 2672 + SYS___FMAXF_H = 0xA71 // 2673 + SYS_FMAXL = 0xA72 // 2674 + SYS___FMAXL_B = 0xA73 // 2675 + SYS___FMAXL_H = 0xA74 // 2676 + SYS_FMIN = 0xA75 // 2677 + SYS___FMIN_B = 0xA76 // 2678 + SYS___FMIN_H = 0xA77 // 2679 + SYS_FMINF = 0xA78 // 2680 + SYS___FMINF_B = 0xA79 // 2681 + SYS___FMINF_H = 0xA7A // 2682 + SYS_FMINL = 0xA7B // 2683 + SYS___FMINL_B = 0xA7C // 2684 + SYS___FMINL_H = 0xA7D // 2685 + SYS_ILOGBF = 0xA7E // 2686 + SYS___ILOGBF_B = 0xA7F // 2687 + SYS___ILOGBF_H = 0xA80 // 2688 + SYS_ILOGBL = 0xA81 // 2689 + SYS___ILOGBL_B = 0xA82 // 2690 + SYS___ILOGBL_H = 0xA83 // 2691 + SYS_LLRINT = 0xA84 // 2692 + SYS___LLRINT_B = 0xA85 // 2693 + SYS___LLRINT_H = 0xA86 // 2694 + SYS_LLRINTF = 0xA87 // 2695 + SYS___LLRINTF_B = 0xA88 // 2696 + SYS___LLRINTF_H = 0xA89 // 2697 + SYS_LLRINTL = 0xA8A // 2698 + SYS___LLRINTL_B = 0xA8B // 2699 + SYS___LLRINTL_H = 0xA8C // 2700 + SYS_LLROUND = 0xA8D // 2701 + SYS___LLROUND_B = 0xA8E // 2702 + SYS___LLROUND_H = 0xA8F // 2703 + SYS_LLROUNDF = 0xA90 // 2704 + SYS___LLROUNDF_B = 0xA91 // 2705 + SYS___LLROUNDF_H = 0xA92 // 2706 + SYS_LLROUNDL = 0xA93 // 2707 + SYS___LLROUNDL_B = 0xA94 // 2708 + SYS___LLROUNDL_H = 0xA95 // 2709 + SYS_LOGBF = 0xA96 // 2710 + SYS___LOGBF_B = 0xA97 // 2711 + SYS___LOGBF_H = 0xA98 // 2712 + SYS_LOGBL = 0xA99 // 2713 + SYS___LOGBL_B = 0xA9A // 2714 + SYS___LOGBL_H = 0xA9B // 2715 + SYS_LRINT = 0xA9C // 2716 + SYS___LRINT_B = 0xA9D // 2717 + SYS___LRINT_H = 0xA9E // 2718 + SYS_LRINTF = 0xA9F // 2719 + SYS___LRINTF_B = 0xAA0 // 2720 + SYS___LRINTF_H = 0xAA1 // 2721 + SYS_LRINTL = 0xAA2 // 2722 + SYS___LRINTL_B = 0xAA3 // 2723 + SYS___LRINTL_H = 0xAA4 // 2724 + SYS_LROUNDL = 0xAA5 // 2725 + SYS___LROUNDL_B = 0xAA6 // 2726 + SYS___LROUNDL_H = 0xAA7 // 2727 + SYS_NAN = 0xAA8 // 2728 + SYS___NAN_B = 0xAA9 // 2729 + SYS_NANF = 0xAAA // 2730 + SYS___NANF_B = 0xAAB // 2731 + SYS_NANL = 0xAAC // 2732 + SYS___NANL_B = 0xAAD // 2733 + SYS_NEARBYINT = 0xAAE // 2734 + SYS___NEARBYINT_B = 0xAAF // 2735 + SYS___NEARBYINT_H = 0xAB0 // 2736 + SYS_NEARBYINTF = 0xAB1 // 2737 + SYS___NEARBYINTF_B = 0xAB2 // 2738 + SYS___NEARBYINTF_H = 0xAB3 // 2739 + SYS_NEARBYINTL = 0xAB4 // 2740 + SYS___NEARBYINTL_B = 0xAB5 // 2741 + SYS___NEARBYINTL_H = 0xAB6 // 2742 + SYS_NEXTAFTERF = 0xAB7 // 2743 + SYS___NEXTAFTERF_B = 0xAB8 // 2744 + SYS___NEXTAFTERF_H = 0xAB9 // 2745 + SYS_NEXTAFTERL = 0xABA // 2746 + SYS___NEXTAFTERL_B = 0xABB // 2747 + SYS___NEXTAFTERL_H = 0xABC // 2748 + SYS_NEXTTOWARD = 0xABD // 2749 + SYS___NEXTTOWARD_B = 0xABE // 2750 + SYS___NEXTTOWARD_H = 0xABF // 2751 + SYS_NEXTTOWARDF = 0xAC0 // 2752 + SYS___NEXTTOWARDF_B = 0xAC1 // 2753 + SYS___NEXTTOWARDF_H = 0xAC2 // 2754 + SYS_NEXTTOWARDL = 0xAC3 // 2755 + SYS___NEXTTOWARDL_B = 0xAC4 // 2756 + SYS___NEXTTOWARDL_H = 0xAC5 // 2757 + SYS___REMAINDERF_H = 0xAC6 // 2758 + SYS___REMAINDERL_H = 0xAC7 // 2759 + SYS___REMQUO_H = 0xAC8 // 2760 + SYS___REMQUOF_H = 0xAC9 // 2761 + SYS___REMQUOL_H = 0xACA // 2762 + SYS_RINTF = 0xACB // 2763 + SYS___RINTF_B = 0xACC // 2764 + SYS_RINTL = 0xACD // 2765 + SYS___RINTL_B = 0xACE // 2766 + SYS_ROUND = 0xACF // 2767 + SYS___ROUND_B = 0xAD0 // 2768 + SYS___ROUND_H = 0xAD1 // 2769 + SYS_ROUNDF = 0xAD2 // 2770 + SYS___ROUNDF_B = 0xAD3 // 2771 + SYS___ROUNDF_H = 0xAD4 // 2772 + SYS_ROUNDL = 0xAD5 // 2773 + SYS___ROUNDL_B = 0xAD6 // 2774 + SYS___ROUNDL_H = 0xAD7 // 2775 + SYS_SCALBLN = 0xAD8 // 2776 + SYS___SCALBLN_B = 0xAD9 // 2777 + SYS___SCALBLN_H = 0xADA // 2778 + SYS_SCALBLNF = 0xADB // 2779 + SYS___SCALBLNF_B = 0xADC // 2780 + SYS___SCALBLNF_H = 0xADD // 2781 + SYS_SCALBLNL = 0xADE // 2782 + SYS___SCALBLNL_B = 0xADF // 2783 + SYS___SCALBLNL_H = 0xAE0 // 2784 + SYS___SCALBN_B = 0xAE1 // 2785 + SYS___SCALBN_H = 0xAE2 // 2786 + SYS_SCALBNF = 0xAE3 // 2787 + SYS___SCALBNF_B = 0xAE4 // 2788 + SYS___SCALBNF_H = 0xAE5 // 2789 + SYS_SCALBNL = 0xAE6 // 2790 + SYS___SCALBNL_B = 0xAE7 // 2791 + SYS___SCALBNL_H = 0xAE8 // 2792 + SYS___TGAMMAL_H = 0xAE9 // 2793 + SYS_FECLEAREXCEPT = 0xAEA // 2794 + SYS_FEGETENV = 0xAEB // 2795 + SYS_FEGETEXCEPTFLAG = 0xAEC // 2796 + SYS_FEGETROUND = 0xAED // 2797 + SYS_FEHOLDEXCEPT = 0xAEE // 2798 + SYS_FERAISEEXCEPT = 0xAEF // 2799 + SYS_FESETENV = 0xAF0 // 2800 + SYS_FESETEXCEPTFLAG = 0xAF1 // 2801 + SYS_FESETROUND = 0xAF2 // 2802 + SYS_FETESTEXCEPT = 0xAF3 // 2803 + SYS_FEUPDATEENV = 0xAF4 // 2804 + SYS___COPYSIGN_H = 0xAF5 // 2805 + SYS___HYPOTF_H = 0xAF6 // 2806 + SYS___HYPOTL_H = 0xAF7 // 2807 + SYS___CLASS = 0xAFA // 2810 + SYS___CLASS_B = 0xAFB // 2811 + SYS___CLASS_H = 0xAFC // 2812 + SYS___ISBLANK_A = 0xB2E // 2862 + SYS___ISWBLANK_A = 0xB2F // 2863 + SYS___LROUND_FIXUP = 0xB30 // 2864 + SYS___LROUNDF_FIXUP = 0xB31 // 2865 + SYS_SCHED_YIELD = 0xB32 // 2866 + SYS_STRERROR_R = 0xB33 // 2867 + SYS_UNSETENV = 0xB34 // 2868 + SYS___LGAMMA_H_C99 = 0xB38 // 2872 + SYS___LGAMMA_B_C99 = 0xB39 // 2873 + SYS___LGAMMA_R_C99 = 0xB3A // 2874 + SYS___FTELL2 = 0xB3B // 2875 + SYS___FSEEK2 = 0xB3C // 2876 + SYS___STATIC_REINIT = 0xB3D // 2877 + SYS_PTHREAD_ATTR_GETSTACK = 0xB3E // 2878 + SYS_PTHREAD_ATTR_SETSTACK = 0xB3F // 2879 + SYS___TGAMMA_H_C99 = 0xB78 // 2936 + SYS___TGAMMAF_H_C99 = 0xB79 // 2937 + SYS___LE_TRACEBACK = 0xB7A // 2938 + SYS___MUST_STAY_CLEAN = 0xB7C // 2940 + SYS___O_ENV = 0xB7D // 2941 + SYS_ACOSD32 = 0xB7E // 2942 + SYS_ACOSD64 = 0xB7F // 2943 + SYS_ACOSD128 = 0xB80 // 2944 + SYS_ACOSHD32 = 0xB81 // 2945 + SYS_ACOSHD64 = 0xB82 // 2946 + SYS_ACOSHD128 = 0xB83 // 2947 + SYS_ASIND32 = 0xB84 // 2948 + SYS_ASIND64 = 0xB85 // 2949 + SYS_ASIND128 = 0xB86 // 2950 + SYS_ASINHD32 = 0xB87 // 2951 + SYS_ASINHD64 = 0xB88 // 2952 + SYS_ASINHD128 = 0xB89 // 2953 + SYS_ATAND32 = 0xB8A // 2954 + SYS_ATAND64 = 0xB8B // 2955 + SYS_ATAND128 = 0xB8C // 2956 + SYS_ATAN2D32 = 0xB8D // 2957 + SYS_ATAN2D64 = 0xB8E // 2958 + SYS_ATAN2D128 = 0xB8F // 2959 + SYS_ATANHD32 = 0xB90 // 2960 + SYS_ATANHD64 = 0xB91 // 2961 + SYS_ATANHD128 = 0xB92 // 2962 + SYS_CBRTD32 = 0xB93 // 2963 + SYS_CBRTD64 = 0xB94 // 2964 + SYS_CBRTD128 = 0xB95 // 2965 + SYS_CEILD32 = 0xB96 // 2966 + SYS_CEILD64 = 0xB97 // 2967 + SYS_CEILD128 = 0xB98 // 2968 + SYS___CLASS2 = 0xB99 // 2969 + SYS___CLASS2_B = 0xB9A // 2970 + SYS___CLASS2_H = 0xB9B // 2971 + SYS_COPYSIGND32 = 0xB9C // 2972 + SYS_COPYSIGND64 = 0xB9D // 2973 + SYS_COPYSIGND128 = 0xB9E // 2974 + SYS_COSD32 = 0xB9F // 2975 + SYS_COSD64 = 0xBA0 // 2976 + SYS_COSD128 = 0xBA1 // 2977 + SYS_COSHD32 = 0xBA2 // 2978 + SYS_COSHD64 = 0xBA3 // 2979 + SYS_COSHD128 = 0xBA4 // 2980 + SYS_ERFD32 = 0xBA5 // 2981 + SYS_ERFD64 = 0xBA6 // 2982 + SYS_ERFD128 = 0xBA7 // 2983 + SYS_ERFCD32 = 0xBA8 // 2984 + SYS_ERFCD64 = 0xBA9 // 2985 + SYS_ERFCD128 = 0xBAA // 2986 + SYS_EXPD32 = 0xBAB // 2987 + SYS_EXPD64 = 0xBAC // 2988 + SYS_EXPD128 = 0xBAD // 2989 + SYS_EXP2D32 = 0xBAE // 2990 + SYS_EXP2D64 = 0xBAF // 2991 + SYS_EXP2D128 = 0xBB0 // 2992 + SYS_EXPM1D32 = 0xBB1 // 2993 + SYS_EXPM1D64 = 0xBB2 // 2994 + SYS_EXPM1D128 = 0xBB3 // 2995 + SYS_FABSD32 = 0xBB4 // 2996 + SYS_FABSD64 = 0xBB5 // 2997 + SYS_FABSD128 = 0xBB6 // 2998 + SYS_FDIMD32 = 0xBB7 // 2999 + SYS_FDIMD64 = 0xBB8 // 3000 + SYS_FDIMD128 = 0xBB9 // 3001 + SYS_FE_DEC_GETROUND = 0xBBA // 3002 + SYS_FE_DEC_SETROUND = 0xBBB // 3003 + SYS_FLOORD32 = 0xBBC // 3004 + SYS_FLOORD64 = 0xBBD // 3005 + SYS_FLOORD128 = 0xBBE // 3006 + SYS_FMAD32 = 0xBBF // 3007 + SYS_FMAD64 = 0xBC0 // 3008 + SYS_FMAD128 = 0xBC1 // 3009 + SYS_FMAXD32 = 0xBC2 // 3010 + SYS_FMAXD64 = 0xBC3 // 3011 + SYS_FMAXD128 = 0xBC4 // 3012 + SYS_FMIND32 = 0xBC5 // 3013 + SYS_FMIND64 = 0xBC6 // 3014 + SYS_FMIND128 = 0xBC7 // 3015 + SYS_FMODD32 = 0xBC8 // 3016 + SYS_FMODD64 = 0xBC9 // 3017 + SYS_FMODD128 = 0xBCA // 3018 + SYS___FP_CAST_D = 0xBCB // 3019 + SYS_FREXPD32 = 0xBCC // 3020 + SYS_FREXPD64 = 0xBCD // 3021 + SYS_FREXPD128 = 0xBCE // 3022 + SYS_HYPOTD32 = 0xBCF // 3023 + SYS_HYPOTD64 = 0xBD0 // 3024 + SYS_HYPOTD128 = 0xBD1 // 3025 + SYS_ILOGBD32 = 0xBD2 // 3026 + SYS_ILOGBD64 = 0xBD3 // 3027 + SYS_ILOGBD128 = 0xBD4 // 3028 + SYS_LDEXPD32 = 0xBD5 // 3029 + SYS_LDEXPD64 = 0xBD6 // 3030 + SYS_LDEXPD128 = 0xBD7 // 3031 + SYS_LGAMMAD32 = 0xBD8 // 3032 + SYS_LGAMMAD64 = 0xBD9 // 3033 + SYS_LGAMMAD128 = 0xBDA // 3034 + SYS_LLRINTD32 = 0xBDB // 3035 + SYS_LLRINTD64 = 0xBDC // 3036 + SYS_LLRINTD128 = 0xBDD // 3037 + SYS_LLROUNDD32 = 0xBDE // 3038 + SYS_LLROUNDD64 = 0xBDF // 3039 + SYS_LLROUNDD128 = 0xBE0 // 3040 + SYS_LOGD32 = 0xBE1 // 3041 + SYS_LOGD64 = 0xBE2 // 3042 + SYS_LOGD128 = 0xBE3 // 3043 + SYS_LOG10D32 = 0xBE4 // 3044 + SYS_LOG10D64 = 0xBE5 // 3045 + SYS_LOG10D128 = 0xBE6 // 3046 + SYS_LOG1PD32 = 0xBE7 // 3047 + SYS_LOG1PD64 = 0xBE8 // 3048 + SYS_LOG1PD128 = 0xBE9 // 3049 + SYS_LOG2D32 = 0xBEA // 3050 + SYS_LOG2D64 = 0xBEB // 3051 + SYS_LOG2D128 = 0xBEC // 3052 + SYS_LOGBD32 = 0xBED // 3053 + SYS_LOGBD64 = 0xBEE // 3054 + SYS_LOGBD128 = 0xBEF // 3055 + SYS_LRINTD32 = 0xBF0 // 3056 + SYS_LRINTD64 = 0xBF1 // 3057 + SYS_LRINTD128 = 0xBF2 // 3058 + SYS_LROUNDD32 = 0xBF3 // 3059 + SYS_LROUNDD64 = 0xBF4 // 3060 + SYS_LROUNDD128 = 0xBF5 // 3061 + SYS_MODFD32 = 0xBF6 // 3062 + SYS_MODFD64 = 0xBF7 // 3063 + SYS_MODFD128 = 0xBF8 // 3064 + SYS_NAND32 = 0xBF9 // 3065 + SYS_NAND64 = 0xBFA // 3066 + SYS_NAND128 = 0xBFB // 3067 + SYS_NEARBYINTD32 = 0xBFC // 3068 + SYS_NEARBYINTD64 = 0xBFD // 3069 + SYS_NEARBYINTD128 = 0xBFE // 3070 + SYS_NEXTAFTERD32 = 0xBFF // 3071 + SYS_NEXTAFTERD64 = 0xC00 // 3072 + SYS_NEXTAFTERD128 = 0xC01 // 3073 + SYS_NEXTTOWARDD32 = 0xC02 // 3074 + SYS_NEXTTOWARDD64 = 0xC03 // 3075 + SYS_NEXTTOWARDD128 = 0xC04 // 3076 + SYS_POWD32 = 0xC05 // 3077 + SYS_POWD64 = 0xC06 // 3078 + SYS_POWD128 = 0xC07 // 3079 + SYS_QUANTIZED32 = 0xC08 // 3080 + SYS_QUANTIZED64 = 0xC09 // 3081 + SYS_QUANTIZED128 = 0xC0A // 3082 + SYS_REMAINDERD32 = 0xC0B // 3083 + SYS_REMAINDERD64 = 0xC0C // 3084 + SYS_REMAINDERD128 = 0xC0D // 3085 + SYS___REMQUOD32 = 0xC0E // 3086 + SYS___REMQUOD64 = 0xC0F // 3087 + SYS___REMQUOD128 = 0xC10 // 3088 + SYS_RINTD32 = 0xC11 // 3089 + SYS_RINTD64 = 0xC12 // 3090 + SYS_RINTD128 = 0xC13 // 3091 + SYS_ROUNDD32 = 0xC14 // 3092 + SYS_ROUNDD64 = 0xC15 // 3093 + SYS_ROUNDD128 = 0xC16 // 3094 + SYS_SAMEQUANTUMD32 = 0xC17 // 3095 + SYS_SAMEQUANTUMD64 = 0xC18 // 3096 + SYS_SAMEQUANTUMD128 = 0xC19 // 3097 + SYS_SCALBLND32 = 0xC1A // 3098 + SYS_SCALBLND64 = 0xC1B // 3099 + SYS_SCALBLND128 = 0xC1C // 3100 + SYS_SCALBND32 = 0xC1D // 3101 + SYS_SCALBND64 = 0xC1E // 3102 + SYS_SCALBND128 = 0xC1F // 3103 + SYS_SIND32 = 0xC20 // 3104 + SYS_SIND64 = 0xC21 // 3105 + SYS_SIND128 = 0xC22 // 3106 + SYS_SINHD32 = 0xC23 // 3107 + SYS_SINHD64 = 0xC24 // 3108 + SYS_SINHD128 = 0xC25 // 3109 + SYS_SQRTD32 = 0xC26 // 3110 + SYS_SQRTD64 = 0xC27 // 3111 + SYS_SQRTD128 = 0xC28 // 3112 + SYS_STRTOD32 = 0xC29 // 3113 + SYS_STRTOD64 = 0xC2A // 3114 + SYS_STRTOD128 = 0xC2B // 3115 + SYS_TAND32 = 0xC2C // 3116 + SYS_TAND64 = 0xC2D // 3117 + SYS_TAND128 = 0xC2E // 3118 + SYS_TANHD32 = 0xC2F // 3119 + SYS_TANHD64 = 0xC30 // 3120 + SYS_TANHD128 = 0xC31 // 3121 + SYS_TGAMMAD32 = 0xC32 // 3122 + SYS_TGAMMAD64 = 0xC33 // 3123 + SYS_TGAMMAD128 = 0xC34 // 3124 + SYS_TRUNCD32 = 0xC3E // 3134 + SYS_TRUNCD64 = 0xC3F // 3135 + SYS_TRUNCD128 = 0xC40 // 3136 + SYS_WCSTOD32 = 0xC41 // 3137 + SYS_WCSTOD64 = 0xC42 // 3138 + SYS_WCSTOD128 = 0xC43 // 3139 + SYS___CODEPAGE_INFO = 0xC64 // 3172 + SYS_POSIX_OPENPT = 0xC66 // 3174 + SYS_PSELECT = 0xC67 // 3175 + SYS_SOCKATMARK = 0xC68 // 3176 + SYS_AIO_FSYNC = 0xC69 // 3177 + SYS_LIO_LISTIO = 0xC6A // 3178 + SYS___ATANPID32 = 0xC6B // 3179 + SYS___ATANPID64 = 0xC6C // 3180 + SYS___ATANPID128 = 0xC6D // 3181 + SYS___COSPID32 = 0xC6E // 3182 + SYS___COSPID64 = 0xC6F // 3183 + SYS___COSPID128 = 0xC70 // 3184 + SYS___SINPID32 = 0xC71 // 3185 + SYS___SINPID64 = 0xC72 // 3186 + SYS___SINPID128 = 0xC73 // 3187 + SYS_SETIPV4SOURCEFILTER = 0xC76 // 3190 + SYS_GETIPV4SOURCEFILTER = 0xC77 // 3191 + SYS_SETSOURCEFILTER = 0xC78 // 3192 + SYS_GETSOURCEFILTER = 0xC79 // 3193 + SYS_FWRITE_UNLOCKED = 0xC7A // 3194 + SYS_FREAD_UNLOCKED = 0xC7B // 3195 + SYS_FGETS_UNLOCKED = 0xC7C // 3196 + SYS_GETS_UNLOCKED = 0xC7D // 3197 + SYS_FPUTS_UNLOCKED = 0xC7E // 3198 + SYS_PUTS_UNLOCKED = 0xC7F // 3199 + SYS_FGETC_UNLOCKED = 0xC80 // 3200 + SYS_FPUTC_UNLOCKED = 0xC81 // 3201 + SYS_DLADDR = 0xC82 // 3202 + SYS_SHM_OPEN = 0xC8C // 3212 + SYS_SHM_UNLINK = 0xC8D // 3213 + SYS___CLASS2F = 0xC91 // 3217 + SYS___CLASS2L = 0xC92 // 3218 + SYS___CLASS2F_B = 0xC93 // 3219 + SYS___CLASS2F_H = 0xC94 // 3220 + SYS___CLASS2L_B = 0xC95 // 3221 + SYS___CLASS2L_H = 0xC96 // 3222 + SYS___CLASS2D32 = 0xC97 // 3223 + SYS___CLASS2D64 = 0xC98 // 3224 + SYS___CLASS2D128 = 0xC99 // 3225 + SYS___TOCSNAME2 = 0xC9A // 3226 + SYS___D1TOP = 0xC9B // 3227 + SYS___D2TOP = 0xC9C // 3228 + SYS___D4TOP = 0xC9D // 3229 + SYS___PTOD1 = 0xC9E // 3230 + SYS___PTOD2 = 0xC9F // 3231 + SYS___PTOD4 = 0xCA0 // 3232 + SYS_CLEARERR_UNLOCKED = 0xCA1 // 3233 + SYS_FDELREC_UNLOCKED = 0xCA2 // 3234 + SYS_FEOF_UNLOCKED = 0xCA3 // 3235 + SYS_FERROR_UNLOCKED = 0xCA4 // 3236 + SYS_FFLUSH_UNLOCKED = 0xCA5 // 3237 + SYS_FGETPOS_UNLOCKED = 0xCA6 // 3238 + SYS_FGETWC_UNLOCKED = 0xCA7 // 3239 + SYS_FGETWS_UNLOCKED = 0xCA8 // 3240 + SYS_FILENO_UNLOCKED = 0xCA9 // 3241 + SYS_FLDATA_UNLOCKED = 0xCAA // 3242 + SYS_FLOCATE_UNLOCKED = 0xCAB // 3243 + SYS_FPRINTF_UNLOCKED = 0xCAC // 3244 + SYS_FPUTWC_UNLOCKED = 0xCAD // 3245 + SYS_FPUTWS_UNLOCKED = 0xCAE // 3246 + SYS_FSCANF_UNLOCKED = 0xCAF // 3247 + SYS_FSEEK_UNLOCKED = 0xCB0 // 3248 + SYS_FSEEKO_UNLOCKED = 0xCB1 // 3249 + SYS_FSETPOS_UNLOCKED = 0xCB3 // 3251 + SYS_FTELL_UNLOCKED = 0xCB4 // 3252 + SYS_FTELLO_UNLOCKED = 0xCB5 // 3253 + SYS_FUPDATE_UNLOCKED = 0xCB7 // 3255 + SYS_FWIDE_UNLOCKED = 0xCB8 // 3256 + SYS_FWPRINTF_UNLOCKED = 0xCB9 // 3257 + SYS_FWSCANF_UNLOCKED = 0xCBA // 3258 + SYS_GETWC_UNLOCKED = 0xCBB // 3259 + SYS_GETWCHAR_UNLOCKED = 0xCBC // 3260 + SYS_PERROR_UNLOCKED = 0xCBD // 3261 + SYS_PRINTF_UNLOCKED = 0xCBE // 3262 + SYS_PUTWC_UNLOCKED = 0xCBF // 3263 + SYS_PUTWCHAR_UNLOCKED = 0xCC0 // 3264 + SYS_REWIND_UNLOCKED = 0xCC1 // 3265 + SYS_SCANF_UNLOCKED = 0xCC2 // 3266 + SYS_UNGETC_UNLOCKED = 0xCC3 // 3267 + SYS_UNGETWC_UNLOCKED = 0xCC4 // 3268 + SYS_VFPRINTF_UNLOCKED = 0xCC5 // 3269 + SYS_VFSCANF_UNLOCKED = 0xCC7 // 3271 + SYS_VFWPRINTF_UNLOCKED = 0xCC9 // 3273 + SYS_VFWSCANF_UNLOCKED = 0xCCB // 3275 + SYS_VPRINTF_UNLOCKED = 0xCCD // 3277 + SYS_VSCANF_UNLOCKED = 0xCCF // 3279 + SYS_VWPRINTF_UNLOCKED = 0xCD1 // 3281 + SYS_VWSCANF_UNLOCKED = 0xCD3 // 3283 + SYS_WPRINTF_UNLOCKED = 0xCD5 // 3285 + SYS_WSCANF_UNLOCKED = 0xCD6 // 3286 + SYS_ASCTIME64 = 0xCD7 // 3287 + SYS_ASCTIME64_R = 0xCD8 // 3288 + SYS_CTIME64 = 0xCD9 // 3289 + SYS_CTIME64_R = 0xCDA // 3290 + SYS_DIFFTIME64 = 0xCDB // 3291 + SYS_GMTIME64 = 0xCDC // 3292 + SYS_GMTIME64_R = 0xCDD // 3293 + SYS_LOCALTIME64 = 0xCDE // 3294 + SYS_LOCALTIME64_R = 0xCDF // 3295 + SYS_MKTIME64 = 0xCE0 // 3296 + SYS_TIME64 = 0xCE1 // 3297 + SYS___LOGIN_APPLID = 0xCE2 // 3298 + SYS___PASSWD_APPLID = 0xCE3 // 3299 + SYS_PTHREAD_SECURITY_APPLID_NP = 0xCE4 // 3300 + SYS___GETTHENT = 0xCE5 // 3301 + SYS_FREEIFADDRS = 0xCE6 // 3302 + SYS_GETIFADDRS = 0xCE7 // 3303 + SYS_POSIX_FALLOCATE = 0xCE8 // 3304 + SYS_POSIX_MEMALIGN = 0xCE9 // 3305 + SYS_SIZEOF_ALLOC = 0xCEA // 3306 + SYS_RESIZE_ALLOC = 0xCEB // 3307 + SYS_FREAD_NOUPDATE = 0xCEC // 3308 + SYS_FREAD_NOUPDATE_UNLOCKED = 0xCED // 3309 + SYS_FGETPOS64 = 0xCEE // 3310 + SYS_FSEEK64 = 0xCEF // 3311 + SYS_FSEEKO64 = 0xCF0 // 3312 + SYS_FSETPOS64 = 0xCF1 // 3313 + SYS_FTELL64 = 0xCF2 // 3314 + SYS_FTELLO64 = 0xCF3 // 3315 + SYS_FGETPOS64_UNLOCKED = 0xCF4 // 3316 + SYS_FSEEK64_UNLOCKED = 0xCF5 // 3317 + SYS_FSEEKO64_UNLOCKED = 0xCF6 // 3318 + SYS_FSETPOS64_UNLOCKED = 0xCF7 // 3319 + SYS_FTELL64_UNLOCKED = 0xCF8 // 3320 + SYS_FTELLO64_UNLOCKED = 0xCF9 // 3321 + SYS_FOPEN_UNLOCKED = 0xCFA // 3322 + SYS_FREOPEN_UNLOCKED = 0xCFB // 3323 + SYS_FDOPEN_UNLOCKED = 0xCFC // 3324 + SYS_TMPFILE_UNLOCKED = 0xCFD // 3325 + SYS___MOSERVICES = 0xD3D // 3389 + SYS___GETTOD = 0xD3E // 3390 + SYS_C16RTOMB = 0xD40 // 3392 + SYS_C32RTOMB = 0xD41 // 3393 + SYS_MBRTOC16 = 0xD42 // 3394 + SYS_MBRTOC32 = 0xD43 // 3395 + SYS_QUANTEXPD32 = 0xD44 // 3396 + SYS_QUANTEXPD64 = 0xD45 // 3397 + SYS_QUANTEXPD128 = 0xD46 // 3398 + SYS___LOCALE_CTL = 0xD47 // 3399 + SYS___SMF_RECORD2 = 0xD48 // 3400 + SYS_FOPEN64 = 0xD49 // 3401 + SYS_FOPEN64_UNLOCKED = 0xD4A // 3402 + SYS_FREOPEN64 = 0xD4B // 3403 + SYS_FREOPEN64_UNLOCKED = 0xD4C // 3404 + SYS_TMPFILE64 = 0xD4D // 3405 + SYS_TMPFILE64_UNLOCKED = 0xD4E // 3406 + SYS_GETDATE64 = 0xD4F // 3407 + SYS_GETTIMEOFDAY64 = 0xD50 // 3408 + SYS_BIND2ADDRSEL = 0xD59 // 3417 + SYS_INET6_IS_SRCADDR = 0xD5A // 3418 + SYS___GETGRGID1 = 0xD5B // 3419 + SYS___GETGRNAM1 = 0xD5C // 3420 + SYS___FBUFSIZE = 0xD60 // 3424 + SYS___FPENDING = 0xD61 // 3425 + SYS___FLBF = 0xD62 // 3426 + SYS___FREADABLE = 0xD63 // 3427 + SYS___FWRITABLE = 0xD64 // 3428 + SYS___FREADING = 0xD65 // 3429 + SYS___FWRITING = 0xD66 // 3430 + SYS___FSETLOCKING = 0xD67 // 3431 + SYS__FLUSHLBF = 0xD68 // 3432 + SYS___FPURGE = 0xD69 // 3433 + SYS___FREADAHEAD = 0xD6A // 3434 + SYS___FSETERR = 0xD6B // 3435 + SYS___FPENDING_UNLOCKED = 0xD6C // 3436 + SYS___FREADING_UNLOCKED = 0xD6D // 3437 + SYS___FWRITING_UNLOCKED = 0xD6E // 3438 + SYS__FLUSHLBF_UNLOCKED = 0xD6F // 3439 + SYS___FPURGE_UNLOCKED = 0xD70 // 3440 + SYS___FREADAHEAD_UNLOCKED = 0xD71 // 3441 + SYS___LE_CEEGTJS = 0xD72 // 3442 + SYS___LE_RECORD_DUMP = 0xD73 // 3443 + SYS_FSTAT64 = 0xD74 // 3444 + SYS_LSTAT64 = 0xD75 // 3445 + SYS_STAT64 = 0xD76 // 3446 + SYS___READDIR2_64 = 0xD77 // 3447 + SYS___OPEN_STAT64 = 0xD78 // 3448 + SYS_FTW64 = 0xD79 // 3449 + SYS_NFTW64 = 0xD7A // 3450 + SYS_UTIME64 = 0xD7B // 3451 + SYS_UTIMES64 = 0xD7C // 3452 + SYS___GETIPC64 = 0xD7D // 3453 + SYS_MSGCTL64 = 0xD7E // 3454 + SYS_SEMCTL64 = 0xD7F // 3455 + SYS_SHMCTL64 = 0xD80 // 3456 + SYS_MSGXRCV64 = 0xD81 // 3457 + SYS___MGXR64 = 0xD81 // 3457 + SYS_W_GETPSENT64 = 0xD82 // 3458 + SYS_PTHREAD_COND_TIMEDWAIT64 = 0xD83 // 3459 + SYS_FTIME64 = 0xD85 // 3461 + SYS_GETUTXENT64 = 0xD86 // 3462 + SYS_GETUTXID64 = 0xD87 // 3463 + SYS_GETUTXLINE64 = 0xD88 // 3464 + SYS_PUTUTXLINE64 = 0xD89 // 3465 + SYS_NEWLOCALE = 0xD8A // 3466 + SYS_FREELOCALE = 0xD8B // 3467 + SYS_USELOCALE = 0xD8C // 3468 + SYS_DUPLOCALE = 0xD8D // 3469 + SYS___CHATTR64 = 0xD9C // 3484 + SYS___LCHATTR64 = 0xD9D // 3485 + SYS___FCHATTR64 = 0xD9E // 3486 + SYS_____CHATTR64_A = 0xD9F // 3487 + SYS_____LCHATTR64_A = 0xDA0 // 3488 + SYS___LE_CEEUSGD = 0xDA1 // 3489 + SYS___LE_IFAM_CON = 0xDA2 // 3490 + SYS___LE_IFAM_DSC = 0xDA3 // 3491 + SYS___LE_IFAM_GET = 0xDA4 // 3492 + SYS___LE_IFAM_QRY = 0xDA5 // 3493 + SYS_ALIGNED_ALLOC = 0xDA6 // 3494 + SYS_ACCEPT4 = 0xDA7 // 3495 + SYS___ACCEPT4_A = 0xDA8 // 3496 + SYS_COPYFILERANGE = 0xDA9 // 3497 + SYS_GETLINE = 0xDAA // 3498 + SYS___GETLINE_A = 0xDAB // 3499 + SYS_DIRFD = 0xDAC // 3500 + SYS_CLOCK_GETTIME = 0xDAD // 3501 + SYS_DUP3 = 0xDAE // 3502 + SYS_EPOLL_CREATE = 0xDAF // 3503 + SYS_EPOLL_CREATE1 = 0xDB0 // 3504 + SYS_EPOLL_CTL = 0xDB1 // 3505 + SYS_EPOLL_WAIT = 0xDB2 // 3506 + SYS_EPOLL_PWAIT = 0xDB3 // 3507 + SYS_EVENTFD = 0xDB4 // 3508 + SYS_STATFS = 0xDB5 // 3509 + SYS___STATFS_A = 0xDB6 // 3510 + SYS_FSTATFS = 0xDB7 // 3511 + SYS_INOTIFY_INIT = 0xDB8 // 3512 + SYS_INOTIFY_INIT1 = 0xDB9 // 3513 + SYS_INOTIFY_ADD_WATCH = 0xDBA // 3514 + SYS___INOTIFY_ADD_WATCH_A = 0xDBB // 3515 + SYS_INOTIFY_RM_WATCH = 0xDBC // 3516 + SYS_PIPE2 = 0xDBD // 3517 + SYS_PIVOT_ROOT = 0xDBE // 3518 + SYS___PIVOT_ROOT_A = 0xDBF // 3519 + SYS_PRCTL = 0xDC0 // 3520 + SYS_PRLIMIT = 0xDC1 // 3521 + SYS_SETHOSTNAME = 0xDC2 // 3522 + SYS___SETHOSTNAME_A = 0xDC3 // 3523 + SYS_SETRESUID = 0xDC4 // 3524 + SYS_SETRESGID = 0xDC5 // 3525 + SYS_PTHREAD_CONDATTR_GETCLOCK = 0xDC6 // 3526 + SYS_FLOCK = 0xDC7 // 3527 + SYS_FGETXATTR = 0xDC8 // 3528 + SYS___FGETXATTR_A = 0xDC9 // 3529 + SYS_FLISTXATTR = 0xDCA // 3530 + SYS___FLISTXATTR_A = 0xDCB // 3531 + SYS_FREMOVEXATTR = 0xDCC // 3532 + SYS___FREMOVEXATTR_A = 0xDCD // 3533 + SYS_FSETXATTR = 0xDCE // 3534 + SYS___FSETXATTR_A = 0xDCF // 3535 + SYS_GETXATTR = 0xDD0 // 3536 + SYS___GETXATTR_A = 0xDD1 // 3537 + SYS_LGETXATTR = 0xDD2 // 3538 + SYS___LGETXATTR_A = 0xDD3 // 3539 + SYS_LISTXATTR = 0xDD4 // 3540 + SYS___LISTXATTR_A = 0xDD5 // 3541 + SYS_LLISTXATTR = 0xDD6 // 3542 + SYS___LLISTXATTR_A = 0xDD7 // 3543 + SYS_LREMOVEXATTR = 0xDD8 // 3544 + SYS___LREMOVEXATTR_A = 0xDD9 // 3545 + SYS_LSETXATTR = 0xDDA // 3546 + SYS___LSETXATTR_A = 0xDDB // 3547 + SYS_REMOVEXATTR = 0xDDC // 3548 + SYS___REMOVEXATTR_A = 0xDDD // 3549 + SYS_SETXATTR = 0xDDE // 3550 + SYS___SETXATTR_A = 0xDDF // 3551 + SYS_FDATASYNC = 0xDE0 // 3552 + SYS_SYNCFS = 0xDE1 // 3553 + SYS_FUTIMES = 0xDE2 // 3554 + SYS_FUTIMESAT = 0xDE3 // 3555 + SYS___FUTIMESAT_A = 0xDE4 // 3556 + SYS_LUTIMES = 0xDE5 // 3557 + SYS___LUTIMES_A = 0xDE6 // 3558 + SYS_INET_ATON = 0xDE7 // 3559 + SYS_GETRANDOM = 0xDE8 // 3560 + SYS_GETTID = 0xDE9 // 3561 + SYS_MEMFD_CREATE = 0xDEA // 3562 + SYS___MEMFD_CREATE_A = 0xDEB // 3563 + SYS_FACCESSAT = 0xDEC // 3564 + SYS___FACCESSAT_A = 0xDED // 3565 + SYS_FCHMODAT = 0xDEE // 3566 + SYS___FCHMODAT_A = 0xDEF // 3567 + SYS_FCHOWNAT = 0xDF0 // 3568 + SYS___FCHOWNAT_A = 0xDF1 // 3569 + SYS_FSTATAT = 0xDF2 // 3570 + SYS___FSTATAT_A = 0xDF3 // 3571 + SYS_LINKAT = 0xDF4 // 3572 + SYS___LINKAT_A = 0xDF5 // 3573 + SYS_MKDIRAT = 0xDF6 // 3574 + SYS___MKDIRAT_A = 0xDF7 // 3575 + SYS_MKFIFOAT = 0xDF8 // 3576 + SYS___MKFIFOAT_A = 0xDF9 // 3577 + SYS_MKNODAT = 0xDFA // 3578 + SYS___MKNODAT_A = 0xDFB // 3579 + SYS_OPENAT = 0xDFC // 3580 + SYS___OPENAT_A = 0xDFD // 3581 + SYS_READLINKAT = 0xDFE // 3582 + SYS___READLINKAT_A = 0xDFF // 3583 + SYS_RENAMEAT = 0xE00 // 3584 + SYS___RENAMEAT_A = 0xE01 // 3585 + SYS_RENAMEAT2 = 0xE02 // 3586 + SYS___RENAMEAT2_A = 0xE03 // 3587 + SYS_SYMLINKAT = 0xE04 // 3588 + SYS___SYMLINKAT_A = 0xE05 // 3589 + SYS_UNLINKAT = 0xE06 // 3590 + SYS___UNLINKAT_A = 0xE07 // 3591 + SYS_SYSINFO = 0xE08 // 3592 + SYS_WAIT4 = 0xE0A // 3594 + SYS_CLONE = 0xE0B // 3595 + SYS_UNSHARE = 0xE0C // 3596 + SYS_SETNS = 0xE0D // 3597 + SYS_CAPGET = 0xE0E // 3598 + SYS_CAPSET = 0xE0F // 3599 + SYS_STRCHRNUL = 0xE10 // 3600 + SYS_PTHREAD_CONDATTR_SETCLOCK = 0xE12 // 3602 + SYS_OPEN_BY_HANDLE_AT = 0xE13 // 3603 + SYS___OPEN_BY_HANDLE_AT_A = 0xE14 // 3604 + SYS___INET_ATON_A = 0xE15 // 3605 + SYS_MOUNT1 = 0xE16 // 3606 + SYS___MOUNT1_A = 0xE17 // 3607 + SYS_UMOUNT1 = 0xE18 // 3608 + SYS___UMOUNT1_A = 0xE19 // 3609 + SYS_UMOUNT2 = 0xE1A // 3610 + SYS___UMOUNT2_A = 0xE1B // 3611 + SYS___PRCTL_A = 0xE1C // 3612 + SYS_LOCALTIME_R2 = 0xE1D // 3613 + SYS___LOCALTIME_R2_A = 0xE1E // 3614 + SYS_OPENAT2 = 0xE1F // 3615 + SYS___OPENAT2_A = 0xE20 // 3616 + SYS___LE_CEEMICT = 0xE21 // 3617 + SYS_GETENTROPY = 0xE22 // 3618 + SYS_NANOSLEEP = 0xE23 // 3619 + SYS_UTIMENSAT = 0xE24 // 3620 + SYS___UTIMENSAT_A = 0xE25 // 3621 + SYS_ASPRINTF = 0xE26 // 3622 + SYS___ASPRINTF_A = 0xE27 // 3623 + SYS_VASPRINTF = 0xE28 // 3624 + SYS___VASPRINTF_A = 0xE29 // 3625 + SYS_DPRINTF = 0xE2A // 3626 + SYS___DPRINTF_A = 0xE2B // 3627 + SYS_GETOPT_LONG = 0xE2C // 3628 + SYS___GETOPT_LONG_A = 0xE2D // 3629 + SYS_PSIGNAL = 0xE2E // 3630 + SYS___PSIGNAL_A = 0xE2F // 3631 + SYS_PSIGNAL_UNLOCKED = 0xE30 // 3632 + SYS___PSIGNAL_UNLOCKED_A = 0xE31 // 3633 + SYS_FSTATAT_O = 0xE32 // 3634 + SYS___FSTATAT_O_A = 0xE33 // 3635 + SYS_FSTATAT64 = 0xE34 // 3636 + SYS___FSTATAT64_A = 0xE35 // 3637 + SYS___CHATTRAT = 0xE36 // 3638 + SYS_____CHATTRAT_A = 0xE37 // 3639 + SYS___CHATTRAT64 = 0xE38 // 3640 + SYS_____CHATTRAT64_A = 0xE39 // 3641 + SYS_MADVISE = 0xE3A // 3642 + SYS___AUTHENTICATE = 0xE3B // 3643 + ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go index 091d107f..17c53bd9 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go @@ -306,6 +306,19 @@ type XVSockPgen struct { type _Socklen uint32 +type SaeAssocID uint32 + +type SaeConnID uint32 + +type SaEndpoints struct { + Srcif uint32 + Srcaddr *RawSockaddr + Srcaddrlen uint32 + Dstaddr *RawSockaddr + Dstaddrlen uint32 + _ [4]byte +} + type Xucred struct { Version uint32 Uid uint32 @@ -449,11 +462,14 @@ type FdSet struct { const ( SizeofIfMsghdr = 0x70 + SizeofIfMsghdr2 = 0xa0 SizeofIfData = 0x60 + SizeofIfData64 = 0x80 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfmaMsghdr2 = 0x14 SizeofRtMsghdr = 0x5c + SizeofRtMsghdr2 = 0x5c SizeofRtMetrics = 0x38 ) @@ -467,6 +483,20 @@ type IfMsghdr struct { Data IfData } +type IfMsghdr2 struct { + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + Snd_len int32 + Snd_maxlen int32 + Snd_drops int32 + Timer int32 + Data IfData64 +} + type IfData struct { Type uint8 Typelen uint8 @@ -499,6 +529,34 @@ type IfData struct { Reserved2 uint32 } +type IfData64 struct { + Type uint8 + Typelen uint8 + Physical uint8 + Addrlen uint8 + Hdrlen uint8 + Recvquota uint8 + Xmitquota uint8 + Unused1 uint8 + Mtu uint32 + Metric uint32 + Baudrate uint64 + Ipackets uint64 + Ierrors uint64 + Opackets uint64 + Oerrors uint64 + Collisions uint64 + Ibytes uint64 + Obytes uint64 + Imcasts uint64 + Omcasts uint64 + Iqdrops uint64 + Noproto uint64 + Recvtiming uint32 + Xmittiming uint32 + Lastchange Timeval32 +} + type IfaMsghdr struct { Msglen uint16 Version uint8 @@ -544,6 +602,21 @@ type RtMsghdr struct { Rmx RtMetrics } +type RtMsghdr2 struct { + Msglen uint16 + Version uint8 + Type uint8 + Index uint16 + Flags int32 + Addrs int32 + Refcnt int32 + Parentflags int32 + Reserved int32 + Use int32 + Inits uint32 + Rmx RtMetrics +} + type RtMetrics struct { Locks uint32 Mtu uint32 diff --git a/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go index 28ff4ef7..2392226a 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go @@ -306,6 +306,19 @@ type XVSockPgen struct { type _Socklen uint32 +type SaeAssocID uint32 + +type SaeConnID uint32 + +type SaEndpoints struct { + Srcif uint32 + Srcaddr *RawSockaddr + Srcaddrlen uint32 + Dstaddr *RawSockaddr + Dstaddrlen uint32 + _ [4]byte +} + type Xucred struct { Version uint32 Uid uint32 @@ -449,11 +462,14 @@ type FdSet struct { const ( SizeofIfMsghdr = 0x70 + SizeofIfMsghdr2 = 0xa0 SizeofIfData = 0x60 + SizeofIfData64 = 0x80 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfmaMsghdr2 = 0x14 SizeofRtMsghdr = 0x5c + SizeofRtMsghdr2 = 0x5c SizeofRtMetrics = 0x38 ) @@ -467,6 +483,20 @@ type IfMsghdr struct { Data IfData } +type IfMsghdr2 struct { + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + Snd_len int32 + Snd_maxlen int32 + Snd_drops int32 + Timer int32 + Data IfData64 +} + type IfData struct { Type uint8 Typelen uint8 @@ -499,6 +529,34 @@ type IfData struct { Reserved2 uint32 } +type IfData64 struct { + Type uint8 + Typelen uint8 + Physical uint8 + Addrlen uint8 + Hdrlen uint8 + Recvquota uint8 + Xmitquota uint8 + Unused1 uint8 + Mtu uint32 + Metric uint32 + Baudrate uint64 + Ipackets uint64 + Ierrors uint64 + Opackets uint64 + Oerrors uint64 + Collisions uint64 + Ibytes uint64 + Obytes uint64 + Imcasts uint64 + Omcasts uint64 + Iqdrops uint64 + Noproto uint64 + Recvtiming uint32 + Xmittiming uint32 + Lastchange Timeval32 +} + type IfaMsghdr struct { Msglen uint16 Version uint8 @@ -544,6 +602,21 @@ type RtMsghdr struct { Rmx RtMetrics } +type RtMsghdr2 struct { + Msglen uint16 + Version uint8 + Type uint8 + Index uint16 + Flags int32 + Addrs int32 + Refcnt int32 + Parentflags int32 + Reserved int32 + Use int32 + Inits uint32 + Rmx RtMetrics +} + type RtMetrics struct { Locks uint32 Mtu uint32 diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go index 6cbd094a..51e13eb0 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go @@ -625,6 +625,7 @@ const ( POLLRDNORM = 0x40 POLLWRBAND = 0x100 POLLWRNORM = 0x4 + POLLRDHUP = 0x4000 ) type CapRights struct { diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go index 7c03b6ee..d002d8ef 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go @@ -630,6 +630,7 @@ const ( POLLRDNORM = 0x40 POLLWRBAND = 0x100 POLLWRNORM = 0x4 + POLLRDHUP = 0x4000 ) type CapRights struct { diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go index 422107ee..3f863d89 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go @@ -616,6 +616,7 @@ const ( POLLRDNORM = 0x40 POLLWRBAND = 0x100 POLLWRNORM = 0x4 + POLLRDHUP = 0x4000 ) type CapRights struct { diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go index 505a12ac..61c72931 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go @@ -610,6 +610,7 @@ const ( POLLRDNORM = 0x40 POLLWRBAND = 0x100 POLLWRNORM = 0x4 + POLLRDHUP = 0x4000 ) type CapRights struct { diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_riscv64.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_riscv64.go index cc986c79..b5d17414 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_freebsd_riscv64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_riscv64.go @@ -612,6 +612,7 @@ const ( POLLRDNORM = 0x40 POLLWRBAND = 0x100 POLLWRNORM = 0x4 + POLLRDHUP = 0x4000 ) type CapRights struct { diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux.go b/vendor/golang.org/x/sys/unix/ztypes_linux.go index 997bcd55..5537148d 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux.go @@ -87,30 +87,35 @@ type StatxTimestamp struct { } type Statx_t struct { - Mask uint32 - Blksize uint32 - Attributes uint64 - Nlink uint32 - Uid uint32 - Gid uint32 - Mode uint16 - _ [1]uint16 - Ino uint64 - Size uint64 - Blocks uint64 - Attributes_mask uint64 - Atime StatxTimestamp - Btime StatxTimestamp - Ctime StatxTimestamp - Mtime StatxTimestamp - Rdev_major uint32 - Rdev_minor uint32 - Dev_major uint32 - Dev_minor uint32 - Mnt_id uint64 - Dio_mem_align uint32 - Dio_offset_align uint32 - _ [12]uint64 + Mask uint32 + Blksize uint32 + Attributes uint64 + Nlink uint32 + Uid uint32 + Gid uint32 + Mode uint16 + _ [1]uint16 + Ino uint64 + Size uint64 + Blocks uint64 + Attributes_mask uint64 + Atime StatxTimestamp + Btime StatxTimestamp + Ctime StatxTimestamp + Mtime StatxTimestamp + Rdev_major uint32 + Rdev_minor uint32 + Dev_major uint32 + Dev_minor uint32 + Mnt_id uint64 + Dio_mem_align uint32 + Dio_offset_align uint32 + Subvol uint64 + Atomic_write_unit_min uint32 + Atomic_write_unit_max uint32 + Atomic_write_segments_max uint32 + _ [1]uint32 + _ [9]uint64 } type Fsid struct { @@ -174,7 +179,8 @@ type FscryptPolicyV2 struct { Contents_encryption_mode uint8 Filenames_encryption_mode uint8 Flags uint8 - _ [4]uint8 + Log2_data_unit_size uint8 + _ [3]uint8 Master_key_identifier [16]uint8 } @@ -455,60 +461,86 @@ type Ucred struct { } type TCPInfo struct { - State uint8 - Ca_state uint8 - Retransmits uint8 - Probes uint8 - Backoff uint8 - Options uint8 - Rto uint32 - Ato uint32 - Snd_mss uint32 - Rcv_mss uint32 - Unacked uint32 - Sacked uint32 - Lost uint32 - Retrans uint32 - Fackets uint32 - Last_data_sent uint32 - Last_ack_sent uint32 - Last_data_recv uint32 - Last_ack_recv uint32 - Pmtu uint32 - Rcv_ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Snd_ssthresh uint32 - Snd_cwnd uint32 - Advmss uint32 - Reordering uint32 - Rcv_rtt uint32 - Rcv_space uint32 - Total_retrans uint32 - Pacing_rate uint64 - Max_pacing_rate uint64 - Bytes_acked uint64 - Bytes_received uint64 - Segs_out uint32 - Segs_in uint32 - Notsent_bytes uint32 - Min_rtt uint32 - Data_segs_in uint32 - Data_segs_out uint32 - Delivery_rate uint64 - Busy_time uint64 - Rwnd_limited uint64 - Sndbuf_limited uint64 - Delivered uint32 - Delivered_ce uint32 - Bytes_sent uint64 - Bytes_retrans uint64 - Dsack_dups uint32 - Reord_seen uint32 - Rcv_ooopack uint32 - Snd_wnd uint32 - Rcv_wnd uint32 - Rehash uint32 + State uint8 + Ca_state uint8 + Retransmits uint8 + Probes uint8 + Backoff uint8 + Options uint8 + Rto uint32 + Ato uint32 + Snd_mss uint32 + Rcv_mss uint32 + Unacked uint32 + Sacked uint32 + Lost uint32 + Retrans uint32 + Fackets uint32 + Last_data_sent uint32 + Last_ack_sent uint32 + Last_data_recv uint32 + Last_ack_recv uint32 + Pmtu uint32 + Rcv_ssthresh uint32 + Rtt uint32 + Rttvar uint32 + Snd_ssthresh uint32 + Snd_cwnd uint32 + Advmss uint32 + Reordering uint32 + Rcv_rtt uint32 + Rcv_space uint32 + Total_retrans uint32 + Pacing_rate uint64 + Max_pacing_rate uint64 + Bytes_acked uint64 + Bytes_received uint64 + Segs_out uint32 + Segs_in uint32 + Notsent_bytes uint32 + Min_rtt uint32 + Data_segs_in uint32 + Data_segs_out uint32 + Delivery_rate uint64 + Busy_time uint64 + Rwnd_limited uint64 + Sndbuf_limited uint64 + Delivered uint32 + Delivered_ce uint32 + Bytes_sent uint64 + Bytes_retrans uint64 + Dsack_dups uint32 + Reord_seen uint32 + Rcv_ooopack uint32 + Snd_wnd uint32 + Rcv_wnd uint32 + Rehash uint32 + Total_rto uint16 + Total_rto_recoveries uint16 + Total_rto_time uint32 +} + +type TCPVegasInfo struct { + Enabled uint32 + Rttcnt uint32 + Rtt uint32 + Minrtt uint32 +} + +type TCPDCTCPInfo struct { + Enabled uint16 + Ce_state uint16 + Alpha uint32 + Ab_ecn uint32 + Ab_tot uint32 +} + +type TCPBBRInfo struct { + Bw_lo uint32 + Bw_hi uint32 + Min_rtt uint32 + Pacing_gain uint32 + Cwnd_gain uint32 } type CanFilter struct { @@ -551,7 +583,8 @@ const ( SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc - SizeofTCPInfo = 0xf0 + SizeofTCPInfo = 0xf8 + SizeofTCPCCInfo = 0x14 SizeofCanFilter = 0x8 SizeofTCPRepairOpt = 0x8 ) @@ -832,6 +865,15 @@ const ( FSPICK_EMPTY_PATH = 0x8 FSMOUNT_CLOEXEC = 0x1 + + FSCONFIG_SET_FLAG = 0x0 + FSCONFIG_SET_STRING = 0x1 + FSCONFIG_SET_BINARY = 0x2 + FSCONFIG_SET_PATH = 0x3 + FSCONFIG_SET_PATH_EMPTY = 0x4 + FSCONFIG_SET_FD = 0x5 + FSCONFIG_CMD_CREATE = 0x6 + FSCONFIG_CMD_RECONFIGURE = 0x7 ) type OpenHow struct { @@ -1165,7 +1207,8 @@ const ( PERF_SAMPLE_BRANCH_TYPE_SAVE_SHIFT = 0x10 PERF_SAMPLE_BRANCH_HW_INDEX_SHIFT = 0x11 PERF_SAMPLE_BRANCH_PRIV_SAVE_SHIFT = 0x12 - PERF_SAMPLE_BRANCH_MAX_SHIFT = 0x13 + PERF_SAMPLE_BRANCH_COUNTERS = 0x80000 + PERF_SAMPLE_BRANCH_MAX_SHIFT = 0x14 PERF_SAMPLE_BRANCH_USER = 0x1 PERF_SAMPLE_BRANCH_KERNEL = 0x2 PERF_SAMPLE_BRANCH_HV = 0x4 @@ -1185,7 +1228,7 @@ const ( PERF_SAMPLE_BRANCH_TYPE_SAVE = 0x10000 PERF_SAMPLE_BRANCH_HW_INDEX = 0x20000 PERF_SAMPLE_BRANCH_PRIV_SAVE = 0x40000 - PERF_SAMPLE_BRANCH_MAX = 0x80000 + PERF_SAMPLE_BRANCH_MAX = 0x100000 PERF_BR_UNKNOWN = 0x0 PERF_BR_COND = 0x1 PERF_BR_UNCOND = 0x2 @@ -1546,6 +1589,7 @@ const ( IFLA_DEVLINK_PORT = 0x3e IFLA_GSO_IPV4_MAX_SIZE = 0x3f IFLA_GRO_IPV4_MAX_SIZE = 0x40 + IFLA_DPLL_PIN = 0x41 IFLA_PROTO_DOWN_REASON_UNSPEC = 0x0 IFLA_PROTO_DOWN_REASON_MASK = 0x1 IFLA_PROTO_DOWN_REASON_VALUE = 0x2 @@ -1561,6 +1605,7 @@ const ( IFLA_INET6_ICMP6STATS = 0x6 IFLA_INET6_TOKEN = 0x7 IFLA_INET6_ADDR_GEN_MODE = 0x8 + IFLA_INET6_RA_MTU = 0x9 IFLA_BR_UNSPEC = 0x0 IFLA_BR_FORWARD_DELAY = 0x1 IFLA_BR_HELLO_TIME = 0x2 @@ -1608,6 +1653,9 @@ const ( IFLA_BR_MCAST_MLD_VERSION = 0x2c IFLA_BR_VLAN_STATS_PER_PORT = 0x2d IFLA_BR_MULTI_BOOLOPT = 0x2e + IFLA_BR_MCAST_QUERIER_STATE = 0x2f + IFLA_BR_FDB_N_LEARNED = 0x30 + IFLA_BR_FDB_MAX_LEARNED = 0x31 IFLA_BRPORT_UNSPEC = 0x0 IFLA_BRPORT_STATE = 0x1 IFLA_BRPORT_PRIORITY = 0x2 @@ -1645,6 +1693,14 @@ const ( IFLA_BRPORT_BACKUP_PORT = 0x22 IFLA_BRPORT_MRP_RING_OPEN = 0x23 IFLA_BRPORT_MRP_IN_OPEN = 0x24 + IFLA_BRPORT_MCAST_EHT_HOSTS_LIMIT = 0x25 + IFLA_BRPORT_MCAST_EHT_HOSTS_CNT = 0x26 + IFLA_BRPORT_LOCKED = 0x27 + IFLA_BRPORT_MAB = 0x28 + IFLA_BRPORT_MCAST_N_GROUPS = 0x29 + IFLA_BRPORT_MCAST_MAX_GROUPS = 0x2a + IFLA_BRPORT_NEIGH_VLAN_SUPPRESS = 0x2b + IFLA_BRPORT_BACKUP_NHID = 0x2c IFLA_INFO_UNSPEC = 0x0 IFLA_INFO_KIND = 0x1 IFLA_INFO_DATA = 0x2 @@ -1666,6 +1722,9 @@ const ( IFLA_MACVLAN_MACADDR = 0x4 IFLA_MACVLAN_MACADDR_DATA = 0x5 IFLA_MACVLAN_MACADDR_COUNT = 0x6 + IFLA_MACVLAN_BC_QUEUE_LEN = 0x7 + IFLA_MACVLAN_BC_QUEUE_LEN_USED = 0x8 + IFLA_MACVLAN_BC_CUTOFF = 0x9 IFLA_VRF_UNSPEC = 0x0 IFLA_VRF_TABLE = 0x1 IFLA_VRF_PORT_UNSPEC = 0x0 @@ -1689,9 +1748,16 @@ const ( IFLA_XFRM_UNSPEC = 0x0 IFLA_XFRM_LINK = 0x1 IFLA_XFRM_IF_ID = 0x2 + IFLA_XFRM_COLLECT_METADATA = 0x3 IFLA_IPVLAN_UNSPEC = 0x0 IFLA_IPVLAN_MODE = 0x1 IFLA_IPVLAN_FLAGS = 0x2 + IFLA_NETKIT_UNSPEC = 0x0 + IFLA_NETKIT_PEER_INFO = 0x1 + IFLA_NETKIT_PRIMARY = 0x2 + IFLA_NETKIT_POLICY = 0x3 + IFLA_NETKIT_PEER_POLICY = 0x4 + IFLA_NETKIT_MODE = 0x5 IFLA_VXLAN_UNSPEC = 0x0 IFLA_VXLAN_ID = 0x1 IFLA_VXLAN_GROUP = 0x2 @@ -1722,6 +1788,9 @@ const ( IFLA_VXLAN_GPE = 0x1b IFLA_VXLAN_TTL_INHERIT = 0x1c IFLA_VXLAN_DF = 0x1d + IFLA_VXLAN_VNIFILTER = 0x1e + IFLA_VXLAN_LOCALBYPASS = 0x1f + IFLA_VXLAN_LABEL_POLICY = 0x20 IFLA_GENEVE_UNSPEC = 0x0 IFLA_GENEVE_ID = 0x1 IFLA_GENEVE_REMOTE = 0x2 @@ -1736,6 +1805,7 @@ const ( IFLA_GENEVE_LABEL = 0xb IFLA_GENEVE_TTL_INHERIT = 0xc IFLA_GENEVE_DF = 0xd + IFLA_GENEVE_INNER_PROTO_INHERIT = 0xe IFLA_BAREUDP_UNSPEC = 0x0 IFLA_BAREUDP_PORT = 0x1 IFLA_BAREUDP_ETHERTYPE = 0x2 @@ -1748,6 +1818,10 @@ const ( IFLA_GTP_FD1 = 0x2 IFLA_GTP_PDP_HASHSIZE = 0x3 IFLA_GTP_ROLE = 0x4 + IFLA_GTP_CREATE_SOCKETS = 0x5 + IFLA_GTP_RESTART_COUNT = 0x6 + IFLA_GTP_LOCAL = 0x7 + IFLA_GTP_LOCAL6 = 0x8 IFLA_BOND_UNSPEC = 0x0 IFLA_BOND_MODE = 0x1 IFLA_BOND_ACTIVE_SLAVE = 0x2 @@ -1777,6 +1851,10 @@ const ( IFLA_BOND_AD_ACTOR_SYSTEM = 0x1a IFLA_BOND_TLB_DYNAMIC_LB = 0x1b IFLA_BOND_PEER_NOTIF_DELAY = 0x1c + IFLA_BOND_AD_LACP_ACTIVE = 0x1d + IFLA_BOND_MISSED_MAX = 0x1e + IFLA_BOND_NS_IP6_TARGET = 0x1f + IFLA_BOND_COUPLED_CONTROL = 0x20 IFLA_BOND_AD_INFO_UNSPEC = 0x0 IFLA_BOND_AD_INFO_AGGREGATOR = 0x1 IFLA_BOND_AD_INFO_NUM_PORTS = 0x2 @@ -1792,6 +1870,7 @@ const ( IFLA_BOND_SLAVE_AD_AGGREGATOR_ID = 0x6 IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE = 0x7 IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE = 0x8 + IFLA_BOND_SLAVE_PRIO = 0x9 IFLA_VF_INFO_UNSPEC = 0x0 IFLA_VF_INFO = 0x1 IFLA_VF_UNSPEC = 0x0 @@ -1844,14 +1923,23 @@ const ( IFLA_HSR_SEQ_NR = 0x5 IFLA_HSR_VERSION = 0x6 IFLA_HSR_PROTOCOL = 0x7 + IFLA_HSR_INTERLINK = 0x8 IFLA_STATS_UNSPEC = 0x0 IFLA_STATS_LINK_64 = 0x1 IFLA_STATS_LINK_XSTATS = 0x2 IFLA_STATS_LINK_XSTATS_SLAVE = 0x3 IFLA_STATS_LINK_OFFLOAD_XSTATS = 0x4 IFLA_STATS_AF_SPEC = 0x5 + IFLA_STATS_GETSET_UNSPEC = 0x0 + IFLA_STATS_GET_FILTERS = 0x1 + IFLA_STATS_SET_OFFLOAD_XSTATS_L3_STATS = 0x2 IFLA_OFFLOAD_XSTATS_UNSPEC = 0x0 IFLA_OFFLOAD_XSTATS_CPU_HIT = 0x1 + IFLA_OFFLOAD_XSTATS_HW_S_INFO = 0x2 + IFLA_OFFLOAD_XSTATS_L3_STATS = 0x3 + IFLA_OFFLOAD_XSTATS_HW_S_INFO_UNSPEC = 0x0 + IFLA_OFFLOAD_XSTATS_HW_S_INFO_REQUEST = 0x1 + IFLA_OFFLOAD_XSTATS_HW_S_INFO_USED = 0x2 IFLA_XDP_UNSPEC = 0x0 IFLA_XDP_FD = 0x1 IFLA_XDP_ATTACHED = 0x2 @@ -1881,6 +1969,20 @@ const ( IFLA_RMNET_UNSPEC = 0x0 IFLA_RMNET_MUX_ID = 0x1 IFLA_RMNET_FLAGS = 0x2 + IFLA_MCTP_UNSPEC = 0x0 + IFLA_MCTP_NET = 0x1 + IFLA_DSA_UNSPEC = 0x0 + IFLA_DSA_CONDUIT = 0x1 + IFLA_DSA_MASTER = 0x1 +) + +const ( + NETKIT_NEXT = -0x1 + NETKIT_PASS = 0x0 + NETKIT_DROP = 0x2 + NETKIT_REDIRECT = 0x7 + NETKIT_L2 = 0x0 + NETKIT_L3 = 0x1 ) const ( @@ -2417,6 +2519,15 @@ type XDPMmapOffsets struct { Cr XDPRingOffset } +type XDPUmemReg struct { + Addr uint64 + Len uint64 + Size uint32 + Headroom uint32 + Flags uint32 + Tx_metadata_len uint32 +} + type XDPStatistics struct { Rx_dropped uint64 Rx_invalid_descs uint64 @@ -2483,8 +2594,8 @@ const ( SOF_TIMESTAMPING_BIND_PHC = 0x8000 SOF_TIMESTAMPING_OPT_ID_TCP = 0x10000 - SOF_TIMESTAMPING_LAST = 0x10000 - SOF_TIMESTAMPING_MASK = 0x1ffff + SOF_TIMESTAMPING_LAST = 0x20000 + SOF_TIMESTAMPING_MASK = 0x3ffff SCM_TSTAMP_SND = 0x0 SCM_TSTAMP_SCHED = 0x1 @@ -2671,6 +2782,7 @@ const ( BPF_PROG_TYPE_LSM = 0x1d BPF_PROG_TYPE_SK_LOOKUP = 0x1e BPF_PROG_TYPE_SYSCALL = 0x1f + BPF_PROG_TYPE_NETFILTER = 0x20 BPF_CGROUP_INET_INGRESS = 0x0 BPF_CGROUP_INET_EGRESS = 0x1 BPF_CGROUP_INET_SOCK_CREATE = 0x2 @@ -2715,6 +2827,11 @@ const ( BPF_PERF_EVENT = 0x29 BPF_TRACE_KPROBE_MULTI = 0x2a BPF_LSM_CGROUP = 0x2b + BPF_STRUCT_OPS = 0x2c + BPF_NETFILTER = 0x2d + BPF_TCX_INGRESS = 0x2e + BPF_TCX_EGRESS = 0x2f + BPF_TRACE_UPROBE_MULTI = 0x30 BPF_LINK_TYPE_UNSPEC = 0x0 BPF_LINK_TYPE_RAW_TRACEPOINT = 0x1 BPF_LINK_TYPE_TRACING = 0x2 @@ -2725,6 +2842,18 @@ const ( BPF_LINK_TYPE_PERF_EVENT = 0x7 BPF_LINK_TYPE_KPROBE_MULTI = 0x8 BPF_LINK_TYPE_STRUCT_OPS = 0x9 + BPF_LINK_TYPE_NETFILTER = 0xa + BPF_LINK_TYPE_TCX = 0xb + BPF_LINK_TYPE_UPROBE_MULTI = 0xc + BPF_PERF_EVENT_UNSPEC = 0x0 + BPF_PERF_EVENT_UPROBE = 0x1 + BPF_PERF_EVENT_URETPROBE = 0x2 + BPF_PERF_EVENT_KPROBE = 0x3 + BPF_PERF_EVENT_KRETPROBE = 0x4 + BPF_PERF_EVENT_TRACEPOINT = 0x5 + BPF_PERF_EVENT_EVENT = 0x6 + BPF_F_KPROBE_MULTI_RETURN = 0x1 + BPF_F_UPROBE_MULTI_RETURN = 0x1 BPF_ANY = 0x0 BPF_NOEXIST = 0x1 BPF_EXIST = 0x2 @@ -2742,6 +2871,8 @@ const ( BPF_F_MMAPABLE = 0x400 BPF_F_PRESERVE_ELEMS = 0x800 BPF_F_INNER_MAP = 0x1000 + BPF_F_LINK = 0x2000 + BPF_F_PATH_FD = 0x4000 BPF_STATS_RUN_TIME = 0x0 BPF_STACK_BUILD_ID_EMPTY = 0x0 BPF_STACK_BUILD_ID_VALID = 0x1 @@ -2762,6 +2893,7 @@ const ( BPF_F_ZERO_CSUM_TX = 0x2 BPF_F_DONT_FRAGMENT = 0x4 BPF_F_SEQ_NUMBER = 0x8 + BPF_F_NO_TUNNEL_KEY = 0x10 BPF_F_TUNINFO_FLAGS = 0x10 BPF_F_INDEX_MASK = 0xffffffff BPF_F_CURRENT_CPU = 0xffffffff @@ -2778,6 +2910,8 @@ const ( BPF_F_ADJ_ROOM_ENCAP_L4_UDP = 0x10 BPF_F_ADJ_ROOM_NO_CSUM_RESET = 0x20 BPF_F_ADJ_ROOM_ENCAP_L2_ETH = 0x40 + BPF_F_ADJ_ROOM_DECAP_L3_IPV4 = 0x80 + BPF_F_ADJ_ROOM_DECAP_L3_IPV6 = 0x100 BPF_ADJ_ROOM_ENCAP_L2_MASK = 0xff BPF_ADJ_ROOM_ENCAP_L2_SHIFT = 0x38 BPF_F_SYSCTL_BASE_NAME = 0x1 @@ -2848,7 +2982,7 @@ const ( BPF_TCP_LISTEN = 0xa BPF_TCP_CLOSING = 0xb BPF_TCP_NEW_SYN_RECV = 0xc - BPF_TCP_MAX_STATES = 0xd + BPF_TCP_MAX_STATES = 0xe TCP_BPF_IW = 0x3e9 TCP_BPF_SNDCWND_CLAMP = 0x3ea TCP_BPF_DELACK_MAX = 0x3eb @@ -2866,6 +3000,8 @@ const ( BPF_DEVCG_DEV_CHAR = 0x2 BPF_FIB_LOOKUP_DIRECT = 0x1 BPF_FIB_LOOKUP_OUTPUT = 0x2 + BPF_FIB_LOOKUP_SKIP_NEIGH = 0x4 + BPF_FIB_LOOKUP_TBID = 0x8 BPF_FIB_LKUP_RET_SUCCESS = 0x0 BPF_FIB_LKUP_RET_BLACKHOLE = 0x1 BPF_FIB_LKUP_RET_UNREACHABLE = 0x2 @@ -2901,6 +3037,7 @@ const ( BPF_CORE_ENUMVAL_EXISTS = 0xa BPF_CORE_ENUMVAL_VALUE = 0xb BPF_CORE_TYPE_MATCHES = 0xc + BPF_F_TIMER_ABS = 0x1 ) const ( @@ -2979,6 +3116,12 @@ type LoopInfo64 struct { Encrypt_key [32]uint8 Init [2]uint64 } +type LoopConfig struct { + Fd uint32 + Size uint32 + Info LoopInfo64 + _ [8]uint64 +} type TIPCSocketAddr struct { Ref uint32 @@ -3115,7 +3258,7 @@ const ( DEVLINK_CMD_LINECARD_NEW = 0x50 DEVLINK_CMD_LINECARD_DEL = 0x51 DEVLINK_CMD_SELFTESTS_GET = 0x52 - DEVLINK_CMD_MAX = 0x53 + DEVLINK_CMD_MAX = 0x54 DEVLINK_PORT_TYPE_NOTSET = 0x0 DEVLINK_PORT_TYPE_AUTO = 0x1 DEVLINK_PORT_TYPE_ETH = 0x2 @@ -3367,7 +3510,7 @@ const ( DEVLINK_PORT_FN_ATTR_STATE = 0x2 DEVLINK_PORT_FN_ATTR_OPSTATE = 0x3 DEVLINK_PORT_FN_ATTR_CAPS = 0x4 - DEVLINK_PORT_FUNCTION_ATTR_MAX = 0x4 + DEVLINK_PORT_FUNCTION_ATTR_MAX = 0x6 ) type FsverityDigest struct { @@ -3398,7 +3541,7 @@ type Nhmsg struct { type NexthopGrp struct { Id uint32 Weight uint8 - Resvd1 uint8 + High uint8 Resvd2 uint16 } @@ -3659,7 +3802,7 @@ const ( ETHTOOL_MSG_PSE_GET = 0x24 ETHTOOL_MSG_PSE_SET = 0x25 ETHTOOL_MSG_RSS_GET = 0x26 - ETHTOOL_MSG_USER_MAX = 0x2b + ETHTOOL_MSG_USER_MAX = 0x2d ETHTOOL_MSG_KERNEL_NONE = 0x0 ETHTOOL_MSG_STRSET_GET_REPLY = 0x1 ETHTOOL_MSG_LINKINFO_GET_REPLY = 0x2 @@ -3699,12 +3842,15 @@ const ( ETHTOOL_MSG_MODULE_NTF = 0x24 ETHTOOL_MSG_PSE_GET_REPLY = 0x25 ETHTOOL_MSG_RSS_GET_REPLY = 0x26 - ETHTOOL_MSG_KERNEL_MAX = 0x2b + ETHTOOL_MSG_KERNEL_MAX = 0x2e + ETHTOOL_FLAG_COMPACT_BITSETS = 0x1 + ETHTOOL_FLAG_OMIT_REPLY = 0x2 + ETHTOOL_FLAG_STATS = 0x4 ETHTOOL_A_HEADER_UNSPEC = 0x0 ETHTOOL_A_HEADER_DEV_INDEX = 0x1 ETHTOOL_A_HEADER_DEV_NAME = 0x2 ETHTOOL_A_HEADER_FLAGS = 0x3 - ETHTOOL_A_HEADER_MAX = 0x3 + ETHTOOL_A_HEADER_MAX = 0x4 ETHTOOL_A_BITSET_BIT_UNSPEC = 0x0 ETHTOOL_A_BITSET_BIT_INDEX = 0x1 ETHTOOL_A_BITSET_BIT_NAME = 0x2 @@ -3841,7 +3987,7 @@ const ( ETHTOOL_A_COALESCE_RATE_SAMPLE_INTERVAL = 0x17 ETHTOOL_A_COALESCE_USE_CQE_MODE_TX = 0x18 ETHTOOL_A_COALESCE_USE_CQE_MODE_RX = 0x19 - ETHTOOL_A_COALESCE_MAX = 0x1c + ETHTOOL_A_COALESCE_MAX = 0x1e ETHTOOL_A_PAUSE_UNSPEC = 0x0 ETHTOOL_A_PAUSE_HEADER = 0x1 ETHTOOL_A_PAUSE_AUTONEG = 0x2 @@ -3869,7 +4015,7 @@ const ( ETHTOOL_A_TSINFO_TX_TYPES = 0x3 ETHTOOL_A_TSINFO_RX_FILTERS = 0x4 ETHTOOL_A_TSINFO_PHC_INDEX = 0x5 - ETHTOOL_A_TSINFO_MAX = 0x5 + ETHTOOL_A_TSINFO_MAX = 0x6 ETHTOOL_A_CABLE_TEST_UNSPEC = 0x0 ETHTOOL_A_CABLE_TEST_HEADER = 0x1 ETHTOOL_A_CABLE_TEST_MAX = 0x1 @@ -3885,11 +4031,11 @@ const ( ETHTOOL_A_CABLE_RESULT_UNSPEC = 0x0 ETHTOOL_A_CABLE_RESULT_PAIR = 0x1 ETHTOOL_A_CABLE_RESULT_CODE = 0x2 - ETHTOOL_A_CABLE_RESULT_MAX = 0x2 + ETHTOOL_A_CABLE_RESULT_MAX = 0x3 ETHTOOL_A_CABLE_FAULT_LENGTH_UNSPEC = 0x0 ETHTOOL_A_CABLE_FAULT_LENGTH_PAIR = 0x1 ETHTOOL_A_CABLE_FAULT_LENGTH_CM = 0x2 - ETHTOOL_A_CABLE_FAULT_LENGTH_MAX = 0x2 + ETHTOOL_A_CABLE_FAULT_LENGTH_MAX = 0x3 ETHTOOL_A_CABLE_TEST_NTF_STATUS_UNSPEC = 0x0 ETHTOOL_A_CABLE_TEST_NTF_STATUS_STARTED = 0x1 ETHTOOL_A_CABLE_TEST_NTF_STATUS_COMPLETED = 0x2 @@ -3972,6 +4118,107 @@ type EthtoolDrvinfo struct { Regdump_len uint32 } +type EthtoolTsInfo struct { + Cmd uint32 + So_timestamping uint32 + Phc_index int32 + Tx_types uint32 + Tx_reserved [3]uint32 + Rx_filters uint32 + Rx_reserved [3]uint32 +} + +type HwTstampConfig struct { + Flags int32 + Tx_type int32 + Rx_filter int32 +} + +const ( + HWTSTAMP_FILTER_NONE = 0x0 + HWTSTAMP_FILTER_ALL = 0x1 + HWTSTAMP_FILTER_SOME = 0x2 + HWTSTAMP_FILTER_PTP_V1_L4_EVENT = 0x3 + HWTSTAMP_FILTER_PTP_V2_L4_EVENT = 0x6 + HWTSTAMP_FILTER_PTP_V2_L2_EVENT = 0x9 + HWTSTAMP_FILTER_PTP_V2_EVENT = 0xc +) + +const ( + HWTSTAMP_TX_OFF = 0x0 + HWTSTAMP_TX_ON = 0x1 + HWTSTAMP_TX_ONESTEP_SYNC = 0x2 +) + +type ( + PtpClockCaps struct { + Max_adj int32 + N_alarm int32 + N_ext_ts int32 + N_per_out int32 + Pps int32 + N_pins int32 + Cross_timestamping int32 + Adjust_phase int32 + Max_phase_adj int32 + Rsv [11]int32 + } + PtpClockTime struct { + Sec int64 + Nsec uint32 + Reserved uint32 + } + PtpExttsEvent struct { + T PtpClockTime + Index uint32 + Flags uint32 + Rsv [2]uint32 + } + PtpExttsRequest struct { + Index uint32 + Flags uint32 + Rsv [2]uint32 + } + PtpPeroutRequest struct { + StartOrPhase PtpClockTime + Period PtpClockTime + Index uint32 + Flags uint32 + On PtpClockTime + } + PtpPinDesc struct { + Name [64]byte + Index uint32 + Func uint32 + Chan uint32 + Rsv [5]uint32 + } + PtpSysOffset struct { + Samples uint32 + Rsv [3]uint32 + Ts [51]PtpClockTime + } + PtpSysOffsetExtended struct { + Samples uint32 + Clockid int32 + Rsv [2]uint32 + Ts [25][3]PtpClockTime + } + PtpSysOffsetPrecise struct { + Device PtpClockTime + Realtime PtpClockTime + Monoraw PtpClockTime + Rsv [4]uint32 + } +) + +const ( + PTP_PF_NONE = 0x0 + PTP_PF_EXTTS = 0x1 + PTP_PF_PEROUT = 0x2 + PTP_PF_PHYSYNC = 0x3 +) + type ( HIDRawReportDescriptor struct { Size uint32 @@ -4151,7 +4398,9 @@ const ( ) type LandlockRulesetAttr struct { - Access_fs uint64 + Access_fs uint64 + Access_net uint64 + Scoped uint64 } type LandlockPathBeneathAttr struct { @@ -4498,7 +4747,7 @@ const ( NL80211_ATTR_MAC_HINT = 0xc8 NL80211_ATTR_MAC_MASK = 0xd7 NL80211_ATTR_MAX_AP_ASSOC_STA = 0xca - NL80211_ATTR_MAX = 0x146 + NL80211_ATTR_MAX = 0x14c NL80211_ATTR_MAX_CRIT_PROT_DURATION = 0xb4 NL80211_ATTR_MAX_CSA_COUNTERS = 0xce NL80211_ATTR_MAX_MATCH_SETS = 0x85 @@ -4764,7 +5013,7 @@ const ( NL80211_BSS_FREQUENCY_OFFSET = 0x14 NL80211_BSS_INFORMATION_ELEMENTS = 0x6 NL80211_BSS_LAST_SEEN_BOOTTIME = 0xf - NL80211_BSS_MAX = 0x16 + NL80211_BSS_MAX = 0x18 NL80211_BSS_MLD_ADDR = 0x16 NL80211_BSS_MLO_LINK_ID = 0x15 NL80211_BSS_PAD = 0x10 @@ -4868,7 +5117,7 @@ const ( NL80211_CMD_LEAVE_IBSS = 0x2c NL80211_CMD_LEAVE_MESH = 0x45 NL80211_CMD_LEAVE_OCB = 0x6d - NL80211_CMD_MAX = 0x9a + NL80211_CMD_MAX = 0x9b NL80211_CMD_MICHAEL_MIC_FAILURE = 0x29 NL80211_CMD_MODIFY_LINK_STA = 0x97 NL80211_CMD_NAN_MATCH = 0x78 @@ -5102,7 +5351,7 @@ const ( NL80211_FREQUENCY_ATTR_GO_CONCURRENT = 0xf NL80211_FREQUENCY_ATTR_INDOOR_ONLY = 0xe NL80211_FREQUENCY_ATTR_IR_CONCURRENT = 0xf - NL80211_FREQUENCY_ATTR_MAX = 0x1b + NL80211_FREQUENCY_ATTR_MAX = 0x21 NL80211_FREQUENCY_ATTR_MAX_TX_POWER = 0x6 NL80211_FREQUENCY_ATTR_NO_10MHZ = 0x11 NL80211_FREQUENCY_ATTR_NO_160MHZ = 0xc @@ -5515,7 +5764,7 @@ const ( NL80211_REGDOM_TYPE_CUSTOM_WORLD = 0x2 NL80211_REGDOM_TYPE_INTERSECTION = 0x3 NL80211_REGDOM_TYPE_WORLD = 0x1 - NL80211_REG_RULE_ATTR_MAX = 0x7 + NL80211_REG_RULE_ATTR_MAX = 0x8 NL80211_REKEY_DATA_AKM = 0x4 NL80211_REKEY_DATA_KCK = 0x2 NL80211_REKEY_DATA_KEK = 0x1 @@ -5596,7 +5845,7 @@ const ( NL80211_STA_FLAG_ASSOCIATED = 0x7 NL80211_STA_FLAG_AUTHENTICATED = 0x5 NL80211_STA_FLAG_AUTHORIZED = 0x1 - NL80211_STA_FLAG_MAX = 0x7 + NL80211_STA_FLAG_MAX = 0x8 NL80211_STA_FLAG_MAX_OLD_API = 0x6 NL80211_STA_FLAG_MFP = 0x4 NL80211_STA_FLAG_SHORT_PREAMBLE = 0x2 @@ -5894,3 +6143,34 @@ type CachestatRange struct { Off uint64 Len uint64 } + +const ( + SK_MEMINFO_RMEM_ALLOC = 0x0 + SK_MEMINFO_RCVBUF = 0x1 + SK_MEMINFO_WMEM_ALLOC = 0x2 + SK_MEMINFO_SNDBUF = 0x3 + SK_MEMINFO_FWD_ALLOC = 0x4 + SK_MEMINFO_WMEM_QUEUED = 0x5 + SK_MEMINFO_OPTMEM = 0x6 + SK_MEMINFO_BACKLOG = 0x7 + SK_MEMINFO_DROPS = 0x8 + SK_MEMINFO_VARS = 0x9 + SKNLGRP_NONE = 0x0 + SKNLGRP_INET_TCP_DESTROY = 0x1 + SKNLGRP_INET_UDP_DESTROY = 0x2 + SKNLGRP_INET6_TCP_DESTROY = 0x3 + SKNLGRP_INET6_UDP_DESTROY = 0x4 + SK_DIAG_BPF_STORAGE_REQ_NONE = 0x0 + SK_DIAG_BPF_STORAGE_REQ_MAP_FD = 0x1 + SK_DIAG_BPF_STORAGE_REP_NONE = 0x0 + SK_DIAG_BPF_STORAGE = 0x1 + SK_DIAG_BPF_STORAGE_NONE = 0x0 + SK_DIAG_BPF_STORAGE_PAD = 0x1 + SK_DIAG_BPF_STORAGE_MAP_ID = 0x2 + SK_DIAG_BPF_STORAGE_MAP_VALUE = 0x3 +) + +type SockDiagReq struct { + Family uint8 + Protocol uint8 +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go index 438a30af..fd402da4 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go @@ -477,14 +477,6 @@ const ( BLKPG = 0x1269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go index adceca35..eb7a5e18 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go @@ -492,15 +492,6 @@ const ( BLKPG = 0x1269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go index eeaa00a3..d78ac108 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go @@ -470,15 +470,6 @@ const ( BLKPG = 0x1269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]uint8 Driver_name [64]uint8 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go index 6739aa91..cd06d47f 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go @@ -471,15 +471,6 @@ const ( BLKPG = 0x1269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go index 9920ef63..2f28fe26 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go @@ -472,15 +472,6 @@ const ( BLKPG = 0x1269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go index 2923b799..71d6cac2 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go @@ -476,15 +476,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go index ce2750ee..8596d453 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go @@ -474,15 +474,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go index 3038811d..cd60ea18 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go @@ -474,15 +474,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go index efc6fed1..b0ae420c 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go @@ -476,15 +476,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go index 9a654b75..83597287 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go @@ -482,15 +482,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]uint8 Driver_name [64]uint8 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go index 40d358e3..69eb6a5c 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go @@ -481,15 +481,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]uint8 Driver_name [64]uint8 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go index 148c6ceb..5f583cb6 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go @@ -481,15 +481,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]uint8 Driver_name [64]uint8 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go index 72ba8154..ad05b51a 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go @@ -499,15 +499,6 @@ const ( BLKPG = 0x1269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]uint8 Driver_name [64]uint8 @@ -736,6 +727,37 @@ const ( RISCV_HWPROBE_EXT_ZBA = 0x8 RISCV_HWPROBE_EXT_ZBB = 0x10 RISCV_HWPROBE_EXT_ZBS = 0x20 + RISCV_HWPROBE_EXT_ZICBOZ = 0x40 + RISCV_HWPROBE_EXT_ZBC = 0x80 + RISCV_HWPROBE_EXT_ZBKB = 0x100 + RISCV_HWPROBE_EXT_ZBKC = 0x200 + RISCV_HWPROBE_EXT_ZBKX = 0x400 + RISCV_HWPROBE_EXT_ZKND = 0x800 + RISCV_HWPROBE_EXT_ZKNE = 0x1000 + RISCV_HWPROBE_EXT_ZKNH = 0x2000 + RISCV_HWPROBE_EXT_ZKSED = 0x4000 + RISCV_HWPROBE_EXT_ZKSH = 0x8000 + RISCV_HWPROBE_EXT_ZKT = 0x10000 + RISCV_HWPROBE_EXT_ZVBB = 0x20000 + RISCV_HWPROBE_EXT_ZVBC = 0x40000 + RISCV_HWPROBE_EXT_ZVKB = 0x80000 + RISCV_HWPROBE_EXT_ZVKG = 0x100000 + RISCV_HWPROBE_EXT_ZVKNED = 0x200000 + RISCV_HWPROBE_EXT_ZVKNHA = 0x400000 + RISCV_HWPROBE_EXT_ZVKNHB = 0x800000 + RISCV_HWPROBE_EXT_ZVKSED = 0x1000000 + RISCV_HWPROBE_EXT_ZVKSH = 0x2000000 + RISCV_HWPROBE_EXT_ZVKT = 0x4000000 + RISCV_HWPROBE_EXT_ZFH = 0x8000000 + RISCV_HWPROBE_EXT_ZFHMIN = 0x10000000 + RISCV_HWPROBE_EXT_ZIHINTNTL = 0x20000000 + RISCV_HWPROBE_EXT_ZVFH = 0x40000000 + RISCV_HWPROBE_EXT_ZVFHMIN = 0x80000000 + RISCV_HWPROBE_EXT_ZFA = 0x100000000 + RISCV_HWPROBE_EXT_ZTSO = 0x200000000 + RISCV_HWPROBE_EXT_ZACAS = 0x400000000 + RISCV_HWPROBE_EXT_ZICOND = 0x800000000 + RISCV_HWPROBE_EXT_ZIHINTPAUSE = 0x1000000000 RISCV_HWPROBE_KEY_CPUPERF_0 = 0x5 RISCV_HWPROBE_MISALIGNED_UNKNOWN = 0x0 RISCV_HWPROBE_MISALIGNED_EMULATED = 0x1 @@ -743,4 +765,6 @@ const ( RISCV_HWPROBE_MISALIGNED_FAST = 0x3 RISCV_HWPROBE_MISALIGNED_UNSUPPORTED = 0x4 RISCV_HWPROBE_MISALIGNED_MASK = 0x7 + RISCV_HWPROBE_KEY_ZICBOZ_BLOCK_SIZE = 0x6 + RISCV_HWPROBE_WHICH_CPUS = 0x1 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go index 71e76550..cf3ce900 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go @@ -495,15 +495,6 @@ const ( BLKPG = 0x1269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go index 4abbdb9d..590b5673 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go @@ -476,15 +476,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go b/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go index 54f31be6..2e5d5a44 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go @@ -25,10 +25,13 @@ const ( SizeofIPv6Mreq = 20 SizeofICMPv6Filter = 32 SizeofIPv6MTUInfo = 32 + SizeofInet4Pktinfo = 8 + SizeofInet6Pktinfo = 20 SizeofLinger = 8 SizeofSockaddrInet4 = 16 SizeofSockaddrInet6 = 28 SizeofTCPInfo = 0x68 + SizeofUcred = 12 ) type ( @@ -69,12 +72,17 @@ type Utimbuf struct { } type Utsname struct { - Sysname [65]byte - Nodename [65]byte - Release [65]byte - Version [65]byte - Machine [65]byte - Domainname [65]byte + Sysname [16]byte + Nodename [32]byte + Release [8]byte + Version [8]byte + Machine [16]byte +} + +type Ucred struct { + Pid int32 + Uid uint32 + Gid uint32 } type RawSockaddrInet4 struct { @@ -325,7 +333,7 @@ type Statvfs_t struct { } type Statfs_t struct { - Type uint32 + Type uint64 Bsize uint64 Blocks uint64 Bfree uint64 @@ -336,6 +344,7 @@ type Statfs_t struct { Namelen uint64 Frsize uint64 Flags uint64 + _ [4]uint64 } type direntLE struct { @@ -368,6 +377,12 @@ type Flock_t struct { Pid int32 } +type F_cnvrt struct { + Cvtcmd int32 + Pccsid int16 + Fccsid int16 +} + type Termios struct { Cflag uint32 Iflag uint32 @@ -412,3 +427,126 @@ type W_Mntent struct { Quiesceowner [8]byte _ [38]byte } + +type EpollEvent struct { + Events uint32 + _ int32 + Fd int32 + Pad int32 +} + +type InotifyEvent struct { + Wd int32 + Mask uint32 + Cookie uint32 + Len uint32 + Name string +} + +const ( + SizeofInotifyEvent = 0x10 +) + +type ConsMsg2 struct { + Cm2Format uint16 + Cm2R1 uint16 + Cm2Msglength uint32 + Cm2Msg *byte + Cm2R2 [4]byte + Cm2R3 [4]byte + Cm2Routcde *uint32 + Cm2Descr *uint32 + Cm2Msgflag uint32 + Cm2Token uint32 + Cm2Msgid *uint32 + Cm2R4 [4]byte + Cm2DomToken uint32 + Cm2DomMsgid *uint32 + Cm2ModCartptr *byte + Cm2ModConsidptr *byte + Cm2MsgCart [8]byte + Cm2MsgConsid [4]byte + Cm2R5 [12]byte +} + +const ( + CC_modify = 1 + CC_stop = 2 + CONSOLE_FORMAT_2 = 2 + CONSOLE_FORMAT_3 = 3 + CONSOLE_HRDCPY = 0x80000000 +) + +type OpenHow struct { + Flags uint64 + Mode uint64 + Resolve uint64 +} + +const SizeofOpenHow = 0x18 + +const ( + RESOLVE_CACHED = 0x20 + RESOLVE_BENEATH = 0x8 + RESOLVE_IN_ROOT = 0x10 + RESOLVE_NO_MAGICLINKS = 0x2 + RESOLVE_NO_SYMLINKS = 0x4 + RESOLVE_NO_XDEV = 0x1 +) + +type Siginfo struct { + Signo int32 + Errno int32 + Code int32 + Pid int32 + Uid uint32 + _ [44]byte +} + +type SysvIpcPerm struct { + Uid uint32 + Gid uint32 + Cuid uint32 + Cgid uint32 + Mode int32 +} + +type SysvShmDesc struct { + Perm SysvIpcPerm + _ [4]byte + Lpid int32 + Cpid int32 + Nattch uint32 + _ [4]byte + _ [4]byte + _ [4]byte + _ int32 + _ uint8 + _ uint8 + _ uint16 + _ *byte + Segsz uint64 + Atime Time_t + Dtime Time_t + Ctime Time_t +} + +type SysvShmDesc64 struct { + Perm SysvIpcPerm + _ [4]byte + Lpid int32 + Cpid int32 + Nattch uint32 + _ [4]byte + _ [4]byte + _ [4]byte + _ int32 + _ byte + _ uint8 + _ uint16 + _ *byte + Segsz uint64 + Atime int64 + Dtime int64 + Ctime int64 +} diff --git a/vendor/golang.org/x/sys/windows/aliases.go b/vendor/golang.org/x/sys/windows/aliases.go index ce2d713d..16f90560 100644 --- a/vendor/golang.org/x/sys/windows/aliases.go +++ b/vendor/golang.org/x/sys/windows/aliases.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build windows && go1.9 +//go:build windows package windows diff --git a/vendor/golang.org/x/sys/windows/dll_windows.go b/vendor/golang.org/x/sys/windows/dll_windows.go index 115341fb..4e613cf6 100644 --- a/vendor/golang.org/x/sys/windows/dll_windows.go +++ b/vendor/golang.org/x/sys/windows/dll_windows.go @@ -65,7 +65,7 @@ func LoadDLL(name string) (dll *DLL, err error) { return d, nil } -// MustLoadDLL is like LoadDLL but panics if load operation failes. +// MustLoadDLL is like LoadDLL but panics if load operation fails. func MustLoadDLL(name string) *DLL { d, e := LoadDLL(name) if e != nil { diff --git a/vendor/golang.org/x/sys/windows/empty.s b/vendor/golang.org/x/sys/windows/empty.s deleted file mode 100644 index ba64caca..00000000 --- a/vendor/golang.org/x/sys/windows/empty.s +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright 2019 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. - -//go:build !go1.12 - -// This file is here to allow bodyless functions with go:linkname for Go 1.11 -// and earlier (see https://golang.org/issue/23311). diff --git a/vendor/golang.org/x/sys/windows/env_windows.go b/vendor/golang.org/x/sys/windows/env_windows.go index b8ad1925..d4577a42 100644 --- a/vendor/golang.org/x/sys/windows/env_windows.go +++ b/vendor/golang.org/x/sys/windows/env_windows.go @@ -37,14 +37,17 @@ func (token Token) Environ(inheritExisting bool) (env []string, err error) { return nil, err } defer DestroyEnvironmentBlock(block) - blockp := unsafe.Pointer(block) - for { - entry := UTF16PtrToString((*uint16)(blockp)) - if len(entry) == 0 { - break + size := unsafe.Sizeof(*block) + for *block != 0 { + // find NUL terminator + end := unsafe.Pointer(block) + for *(*uint16)(end) != 0 { + end = unsafe.Add(end, size) } - env = append(env, entry) - blockp = unsafe.Add(blockp, 2*(len(entry)+1)) + + entry := unsafe.Slice(block, (uintptr(end)-uintptr(unsafe.Pointer(block)))/size) + env = append(env, UTF16ToString(entry)) + block = (*uint16)(unsafe.Add(end, size)) } return env, nil } diff --git a/vendor/golang.org/x/sys/windows/security_windows.go b/vendor/golang.org/x/sys/windows/security_windows.go index 26be94a8..b6e1ab76 100644 --- a/vendor/golang.org/x/sys/windows/security_windows.go +++ b/vendor/golang.org/x/sys/windows/security_windows.go @@ -68,6 +68,7 @@ type UserInfo10 struct { //sys NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) = netapi32.NetUserGetInfo //sys NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error) = netapi32.NetGetJoinInformation //sys NetApiBufferFree(buf *byte) (neterr error) = netapi32.NetApiBufferFree +//sys NetUserEnum(serverName *uint16, level uint32, filter uint32, buf **byte, prefMaxLen uint32, entriesRead *uint32, totalEntries *uint32, resumeHandle *uint32) (neterr error) = netapi32.NetUserEnum const ( // do not reorder @@ -893,7 +894,7 @@ type ACL struct { aclRevision byte sbz1 byte aclSize uint16 - aceCount uint16 + AceCount uint16 sbz2 uint16 } @@ -1086,6 +1087,27 @@ type EXPLICIT_ACCESS struct { Trustee TRUSTEE } +// https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-ace_header +type ACE_HEADER struct { + AceType uint8 + AceFlags uint8 + AceSize uint16 +} + +// https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-access_allowed_ace +type ACCESS_ALLOWED_ACE struct { + Header ACE_HEADER + Mask ACCESS_MASK + SidStart uint32 +} + +const ( + // Constants for AceType + // https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-ace_header + ACCESS_ALLOWED_ACE_TYPE = 0 + ACCESS_DENIED_ACE_TYPE = 1 +) + // This type is the union inside of TRUSTEE and must be created using one of the TrusteeValueFrom* functions. type TrusteeValue uintptr @@ -1157,6 +1179,7 @@ type OBJECTS_AND_NAME struct { //sys makeSelfRelativeSD(absoluteSD *SECURITY_DESCRIPTOR, selfRelativeSD *SECURITY_DESCRIPTOR, selfRelativeSDSize *uint32) (err error) = advapi32.MakeSelfRelativeSD //sys setEntriesInAcl(countExplicitEntries uint32, explicitEntries *EXPLICIT_ACCESS, oldACL *ACL, newACL **ACL) (ret error) = advapi32.SetEntriesInAclW +//sys GetAce(acl *ACL, aceIndex uint32, pAce **ACCESS_ALLOWED_ACE) (err error) = advapi32.GetAce // Control returns the security descriptor control bits. func (sd *SECURITY_DESCRIPTOR) Control() (control SECURITY_DESCRIPTOR_CONTROL, revision uint32, err error) { diff --git a/vendor/golang.org/x/sys/windows/syscall_windows.go b/vendor/golang.org/x/sys/windows/syscall_windows.go index fb6cfd04..4a325438 100644 --- a/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -17,8 +17,10 @@ import ( "unsafe" ) -type Handle uintptr -type HWND uintptr +type ( + Handle uintptr + HWND uintptr +) const ( InvalidHandle = ^Handle(0) @@ -125,8 +127,7 @@ func UTF16PtrToString(p *uint16) string { for ptr := unsafe.Pointer(p); *(*uint16)(ptr) != 0; n++ { ptr = unsafe.Pointer(uintptr(ptr) + unsafe.Sizeof(*p)) } - - return string(utf16.Decode(unsafe.Slice(p, n))) + return UTF16ToString(unsafe.Slice(p, n)) } func Getpagesize() int { return 4096 } @@ -155,6 +156,8 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys GetModuleFileName(module Handle, filename *uint16, size uint32) (n uint32, err error) = kernel32.GetModuleFileNameW //sys GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err error) = kernel32.GetModuleHandleExW //sys SetDefaultDllDirectories(directoryFlags uint32) (err error) +//sys AddDllDirectory(path *uint16) (cookie uintptr, err error) = kernel32.AddDllDirectory +//sys RemoveDllDirectory(cookie uintptr) (err error) = kernel32.RemoveDllDirectory //sys SetDllDirectory(path string) (err error) = kernel32.SetDllDirectoryW //sys GetVersion() (ver uint32, err error) //sys FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW @@ -164,6 +167,9 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile Handle) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW //sys CreateNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *SecurityAttributes) (handle Handle, err error) [failretval==InvalidHandle] = CreateNamedPipeW //sys ConnectNamedPipe(pipe Handle, overlapped *Overlapped) (err error) +//sys DisconnectNamedPipe(pipe Handle) (err error) +//sys GetNamedPipeClientProcessId(pipe Handle, clientProcessID *uint32) (err error) +//sys GetNamedPipeServerProcessId(pipe Handle, serverProcessID *uint32) (err error) //sys GetNamedPipeInfo(pipe Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) //sys GetNamedPipeHandleState(pipe Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW //sys SetNamedPipeHandleState(pipe Handle, state *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32) (err error) = SetNamedPipeHandleState @@ -192,6 +198,7 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW //sys GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW //sys SetEndOfFile(handle Handle) (err error) +//sys SetFileValidData(handle Handle, validDataLength int64) (err error) //sys GetSystemTimeAsFileTime(time *Filetime) //sys GetSystemTimePreciseAsFileTime(time *Filetime) //sys GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) [failretval==0xffffffff] @@ -208,6 +215,10 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys OpenProcess(desiredAccess uint32, inheritHandle bool, processId uint32) (handle Handle, err error) //sys ShellExecute(hwnd Handle, verb *uint16, file *uint16, args *uint16, cwd *uint16, showCmd int32) (err error) [failretval<=32] = shell32.ShellExecuteW //sys GetWindowThreadProcessId(hwnd HWND, pid *uint32) (tid uint32, err error) = user32.GetWindowThreadProcessId +//sys LoadKeyboardLayout(name *uint16, flags uint32) (hkl Handle, err error) [failretval==0] = user32.LoadKeyboardLayoutW +//sys UnloadKeyboardLayout(hkl Handle) (err error) = user32.UnloadKeyboardLayout +//sys GetKeyboardLayout(tid uint32) (hkl Handle) = user32.GetKeyboardLayout +//sys ToUnicodeEx(vkey uint32, scancode uint32, keystate *byte, pwszBuff *uint16, cchBuff int32, flags uint32, hkl Handle) (ret int32) = user32.ToUnicodeEx //sys GetShellWindow() (shellWindow HWND) = user32.GetShellWindow //sys MessageBox(hwnd HWND, text *uint16, caption *uint16, boxtype uint32) (ret int32, err error) [failretval==0] = user32.MessageBoxW //sys ExitWindowsEx(flags uint32, reason uint32) (err error) = user32.ExitWindowsEx @@ -304,6 +315,10 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys SetConsoleMode(console Handle, mode uint32) (err error) = kernel32.SetConsoleMode //sys GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) = kernel32.GetConsoleScreenBufferInfo //sys setConsoleCursorPosition(console Handle, position uint32) (err error) = kernel32.SetConsoleCursorPosition +//sys GetConsoleCP() (cp uint32, err error) = kernel32.GetConsoleCP +//sys GetConsoleOutputCP() (cp uint32, err error) = kernel32.GetConsoleOutputCP +//sys SetConsoleCP(cp uint32) (err error) = kernel32.SetConsoleCP +//sys SetConsoleOutputCP(cp uint32) (err error) = kernel32.SetConsoleOutputCP //sys WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW //sys ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW //sys resizePseudoConsole(pconsole Handle, size uint32) (hr error) = kernel32.ResizePseudoConsole @@ -346,8 +361,19 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys SetProcessPriorityBoost(process Handle, disable bool) (err error) = kernel32.SetProcessPriorityBoost //sys GetProcessWorkingSetSizeEx(hProcess Handle, lpMinimumWorkingSetSize *uintptr, lpMaximumWorkingSetSize *uintptr, flags *uint32) //sys SetProcessWorkingSetSizeEx(hProcess Handle, dwMinimumWorkingSetSize uintptr, dwMaximumWorkingSetSize uintptr, flags uint32) (err error) +//sys ClearCommBreak(handle Handle) (err error) +//sys ClearCommError(handle Handle, lpErrors *uint32, lpStat *ComStat) (err error) +//sys EscapeCommFunction(handle Handle, dwFunc uint32) (err error) +//sys GetCommState(handle Handle, lpDCB *DCB) (err error) +//sys GetCommModemStatus(handle Handle, lpModemStat *uint32) (err error) //sys GetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) +//sys PurgeComm(handle Handle, dwFlags uint32) (err error) +//sys SetCommBreak(handle Handle) (err error) +//sys SetCommMask(handle Handle, dwEvtMask uint32) (err error) +//sys SetCommState(handle Handle, lpDCB *DCB) (err error) //sys SetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) +//sys SetupComm(handle Handle, dwInQueue uint32, dwOutQueue uint32) (err error) +//sys WaitCommEvent(handle Handle, lpEvtMask *uint32, lpOverlapped *Overlapped) (err error) //sys GetActiveProcessorCount(groupNumber uint16) (ret uint32) //sys GetMaximumProcessorCount(groupNumber uint16) (ret uint32) //sys EnumWindows(enumFunc uintptr, param unsafe.Pointer) (err error) = user32.EnumWindows @@ -701,20 +727,12 @@ func DurationSinceBoot() time.Duration { } func Ftruncate(fd Handle, length int64) (err error) { - curoffset, e := Seek(fd, 0, 1) - if e != nil { - return e - } - defer Seek(fd, curoffset, 0) - _, e = Seek(fd, length, 0) - if e != nil { - return e + type _FILE_END_OF_FILE_INFO struct { + EndOfFile int64 } - e = SetEndOfFile(fd) - if e != nil { - return e - } - return nil + var info _FILE_END_OF_FILE_INFO + info.EndOfFile = length + return SetFileInformationByHandle(fd, FileEndOfFileInfo, (*byte)(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info))) } func Gettimeofday(tv *Timeval) (err error) { @@ -870,6 +888,11 @@ const socket_error = uintptr(^uint32(0)) //sys GetACP() (acp uint32) = kernel32.GetACP //sys MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) = kernel32.MultiByteToWideChar //sys getBestInterfaceEx(sockaddr unsafe.Pointer, pdwBestIfIndex *uint32) (errcode error) = iphlpapi.GetBestInterfaceEx +//sys GetIfEntry2Ex(level uint32, row *MibIfRow2) (errcode error) = iphlpapi.GetIfEntry2Ex +//sys GetUnicastIpAddressEntry(row *MibUnicastIpAddressRow) (errcode error) = iphlpapi.GetUnicastIpAddressEntry +//sys NotifyIpInterfaceChange(family uint16, callback uintptr, callerContext unsafe.Pointer, initialNotification bool, notificationHandle *Handle) (errcode error) = iphlpapi.NotifyIpInterfaceChange +//sys NotifyUnicastIpAddressChange(family uint16, callback uintptr, callerContext unsafe.Pointer, initialNotification bool, notificationHandle *Handle) (errcode error) = iphlpapi.NotifyUnicastIpAddressChange +//sys CancelMibChangeNotify2(notificationHandle Handle) (errcode error) = iphlpapi.CancelMibChangeNotify2 // For testing: clients can set this flag to force // creation of IPv6 sockets to return EAFNOSUPPORT. @@ -1354,9 +1377,11 @@ func SetsockoptLinger(fd Handle, level, opt int, l *Linger) (err error) { func SetsockoptInet4Addr(fd Handle, level, opt int, value [4]byte) (err error) { return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&value[0])), 4) } + func SetsockoptIPMreq(fd Handle, level, opt int, mreq *IPMreq) (err error) { return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(mreq)), int32(unsafe.Sizeof(*mreq))) } + func SetsockoptIPv6Mreq(fd Handle, level, opt int, mreq *IPv6Mreq) (err error) { return syscall.EWINDOWS } @@ -1659,13 +1684,16 @@ func (s NTStatus) Error() string { // do not use NTUnicodeString, and instead UTF16PtrFromString should be used for // the more common *uint16 string type. func NewNTUnicodeString(s string) (*NTUnicodeString, error) { - var u NTUnicodeString - s16, err := UTF16PtrFromString(s) + s16, err := UTF16FromString(s) if err != nil { return nil, err } - RtlInitUnicodeString(&u, s16) - return &u, nil + n := uint16(len(s16) * 2) + return &NTUnicodeString{ + Length: n - 2, // subtract 2 bytes for the NULL terminator + MaximumLength: n, + Buffer: &s16[0], + }, nil } // Slice returns a uint16 slice that aliases the data in the NTUnicodeString. @@ -1832,3 +1860,73 @@ func ResizePseudoConsole(pconsole Handle, size Coord) error { // accept arguments that can be casted to uintptr, and Coord can't. return resizePseudoConsole(pconsole, *((*uint32)(unsafe.Pointer(&size)))) } + +// DCB constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-dcb. +const ( + CBR_110 = 110 + CBR_300 = 300 + CBR_600 = 600 + CBR_1200 = 1200 + CBR_2400 = 2400 + CBR_4800 = 4800 + CBR_9600 = 9600 + CBR_14400 = 14400 + CBR_19200 = 19200 + CBR_38400 = 38400 + CBR_57600 = 57600 + CBR_115200 = 115200 + CBR_128000 = 128000 + CBR_256000 = 256000 + + DTR_CONTROL_DISABLE = 0x00000000 + DTR_CONTROL_ENABLE = 0x00000010 + DTR_CONTROL_HANDSHAKE = 0x00000020 + + RTS_CONTROL_DISABLE = 0x00000000 + RTS_CONTROL_ENABLE = 0x00001000 + RTS_CONTROL_HANDSHAKE = 0x00002000 + RTS_CONTROL_TOGGLE = 0x00003000 + + NOPARITY = 0 + ODDPARITY = 1 + EVENPARITY = 2 + MARKPARITY = 3 + SPACEPARITY = 4 + + ONESTOPBIT = 0 + ONE5STOPBITS = 1 + TWOSTOPBITS = 2 +) + +// EscapeCommFunction constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-escapecommfunction. +const ( + SETXOFF = 1 + SETXON = 2 + SETRTS = 3 + CLRRTS = 4 + SETDTR = 5 + CLRDTR = 6 + SETBREAK = 8 + CLRBREAK = 9 +) + +// PurgeComm constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-purgecomm. +const ( + PURGE_TXABORT = 0x0001 + PURGE_RXABORT = 0x0002 + PURGE_TXCLEAR = 0x0004 + PURGE_RXCLEAR = 0x0008 +) + +// SetCommMask constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setcommmask. +const ( + EV_RXCHAR = 0x0001 + EV_RXFLAG = 0x0002 + EV_TXEMPTY = 0x0004 + EV_CTS = 0x0008 + EV_DSR = 0x0010 + EV_RLSD = 0x0020 + EV_BREAK = 0x0040 + EV_ERR = 0x0080 + EV_RING = 0x0100 +) diff --git a/vendor/golang.org/x/sys/windows/types_windows.go b/vendor/golang.org/x/sys/windows/types_windows.go index 359780f6..9d138de5 100644 --- a/vendor/golang.org/x/sys/windows/types_windows.go +++ b/vendor/golang.org/x/sys/windows/types_windows.go @@ -176,6 +176,7 @@ const ( WAIT_FAILED = 0xFFFFFFFF // Access rights for process. + PROCESS_ALL_ACCESS = 0xFFFF PROCESS_CREATE_PROCESS = 0x0080 PROCESS_CREATE_THREAD = 0x0002 PROCESS_DUP_HANDLE = 0x0040 @@ -1060,6 +1061,7 @@ const ( SIO_GET_EXTENSION_FUNCTION_POINTER = IOC_INOUT | IOC_WS2 | 6 SIO_KEEPALIVE_VALS = IOC_IN | IOC_VENDOR | 4 SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12 + SIO_UDP_NETRESET = IOC_IN | IOC_VENDOR | 15 // cf. http://support.microsoft.com/default.aspx?scid=kb;en-us;257460 @@ -2003,7 +2005,21 @@ const ( MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x20 ) -const GAA_FLAG_INCLUDE_PREFIX = 0x00000010 +// Flags for GetAdaptersAddresses, see +// https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getadaptersaddresses. +const ( + GAA_FLAG_SKIP_UNICAST = 0x1 + GAA_FLAG_SKIP_ANYCAST = 0x2 + GAA_FLAG_SKIP_MULTICAST = 0x4 + GAA_FLAG_SKIP_DNS_SERVER = 0x8 + GAA_FLAG_INCLUDE_PREFIX = 0x10 + GAA_FLAG_SKIP_FRIENDLY_NAME = 0x20 + GAA_FLAG_INCLUDE_WINS_INFO = 0x40 + GAA_FLAG_INCLUDE_GATEWAYS = 0x80 + GAA_FLAG_INCLUDE_ALL_INTERFACES = 0x100 + GAA_FLAG_INCLUDE_ALL_COMPARTMENTS = 0x200 + GAA_FLAG_INCLUDE_TUNNEL_BINDINGORDER = 0x400 +) const ( IF_TYPE_OTHER = 1 @@ -2017,6 +2033,50 @@ const ( IF_TYPE_IEEE1394 = 144 ) +// Enum NL_PREFIX_ORIGIN for [IpAdapterUnicastAddress], see +// https://learn.microsoft.com/en-us/windows/win32/api/nldef/ne-nldef-nl_prefix_origin +const ( + IpPrefixOriginOther = 0 + IpPrefixOriginManual = 1 + IpPrefixOriginWellKnown = 2 + IpPrefixOriginDhcp = 3 + IpPrefixOriginRouterAdvertisement = 4 + IpPrefixOriginUnchanged = 1 << 4 +) + +// Enum NL_SUFFIX_ORIGIN for [IpAdapterUnicastAddress], see +// https://learn.microsoft.com/en-us/windows/win32/api/nldef/ne-nldef-nl_suffix_origin +const ( + NlsoOther = 0 + NlsoManual = 1 + NlsoWellKnown = 2 + NlsoDhcp = 3 + NlsoLinkLayerAddress = 4 + NlsoRandom = 5 + IpSuffixOriginOther = 0 + IpSuffixOriginManual = 1 + IpSuffixOriginWellKnown = 2 + IpSuffixOriginDhcp = 3 + IpSuffixOriginLinkLayerAddress = 4 + IpSuffixOriginRandom = 5 + IpSuffixOriginUnchanged = 1 << 4 +) + +// Enum NL_DAD_STATE for [IpAdapterUnicastAddress], see +// https://learn.microsoft.com/en-us/windows/win32/api/nldef/ne-nldef-nl_dad_state +const ( + NldsInvalid = 0 + NldsTentative = 1 + NldsDuplicate = 2 + NldsDeprecated = 3 + NldsPreferred = 4 + IpDadStateInvalid = 0 + IpDadStateTentative = 1 + IpDadStateDuplicate = 2 + IpDadStateDeprecated = 3 + IpDadStatePreferred = 4 +) + type SocketAddress struct { Sockaddr *syscall.RawSockaddrAny SockaddrLength int32 @@ -2144,6 +2204,132 @@ const ( IfOperStatusLowerLayerDown = 7 ) +const ( + IF_MAX_PHYS_ADDRESS_LENGTH = 32 + IF_MAX_STRING_SIZE = 256 +) + +// MIB_IF_ENTRY_LEVEL enumeration from netioapi.h or +// https://learn.microsoft.com/en-us/windows/win32/api/netioapi/nf-netioapi-getifentry2ex. +const ( + MibIfEntryNormal = 0 + MibIfEntryNormalWithoutStatistics = 2 +) + +// MIB_NOTIFICATION_TYPE enumeration from netioapi.h or +// https://learn.microsoft.com/en-us/windows/win32/api/netioapi/ne-netioapi-mib_notification_type. +const ( + MibParameterNotification = 0 + MibAddInstance = 1 + MibDeleteInstance = 2 + MibInitialNotification = 3 +) + +// MibIfRow2 stores information about a particular interface. See +// https://learn.microsoft.com/en-us/windows/win32/api/netioapi/ns-netioapi-mib_if_row2. +type MibIfRow2 struct { + InterfaceLuid uint64 + InterfaceIndex uint32 + InterfaceGuid GUID + Alias [IF_MAX_STRING_SIZE + 1]uint16 + Description [IF_MAX_STRING_SIZE + 1]uint16 + PhysicalAddressLength uint32 + PhysicalAddress [IF_MAX_PHYS_ADDRESS_LENGTH]uint8 + PermanentPhysicalAddress [IF_MAX_PHYS_ADDRESS_LENGTH]uint8 + Mtu uint32 + Type uint32 + TunnelType uint32 + MediaType uint32 + PhysicalMediumType uint32 + AccessType uint32 + DirectionType uint32 + InterfaceAndOperStatusFlags uint8 + OperStatus uint32 + AdminStatus uint32 + MediaConnectState uint32 + NetworkGuid GUID + ConnectionType uint32 + TransmitLinkSpeed uint64 + ReceiveLinkSpeed uint64 + InOctets uint64 + InUcastPkts uint64 + InNUcastPkts uint64 + InDiscards uint64 + InErrors uint64 + InUnknownProtos uint64 + InUcastOctets uint64 + InMulticastOctets uint64 + InBroadcastOctets uint64 + OutOctets uint64 + OutUcastPkts uint64 + OutNUcastPkts uint64 + OutDiscards uint64 + OutErrors uint64 + OutUcastOctets uint64 + OutMulticastOctets uint64 + OutBroadcastOctets uint64 + OutQLen uint64 +} + +// MIB_UNICASTIPADDRESS_ROW stores information about a unicast IP address. See +// https://learn.microsoft.com/en-us/windows/win32/api/netioapi/ns-netioapi-mib_unicastipaddress_row. +type MibUnicastIpAddressRow struct { + Address RawSockaddrInet6 // SOCKADDR_INET union + InterfaceLuid uint64 + InterfaceIndex uint32 + PrefixOrigin uint32 + SuffixOrigin uint32 + ValidLifetime uint32 + PreferredLifetime uint32 + OnLinkPrefixLength uint8 + SkipAsSource uint8 + DadState uint32 + ScopeId uint32 + CreationTimeStamp Filetime +} + +const ScopeLevelCount = 16 + +// MIB_IPINTERFACE_ROW stores interface management information for a particular IP address family on a network interface. +// See https://learn.microsoft.com/en-us/windows/win32/api/netioapi/ns-netioapi-mib_ipinterface_row. +type MibIpInterfaceRow struct { + Family uint16 + InterfaceLuid uint64 + InterfaceIndex uint32 + MaxReassemblySize uint32 + InterfaceIdentifier uint64 + MinRouterAdvertisementInterval uint32 + MaxRouterAdvertisementInterval uint32 + AdvertisingEnabled uint8 + ForwardingEnabled uint8 + WeakHostSend uint8 + WeakHostReceive uint8 + UseAutomaticMetric uint8 + UseNeighborUnreachabilityDetection uint8 + ManagedAddressConfigurationSupported uint8 + OtherStatefulConfigurationSupported uint8 + AdvertiseDefaultRoute uint8 + RouterDiscoveryBehavior uint32 + DadTransmits uint32 + BaseReachableTime uint32 + RetransmitTime uint32 + PathMtuDiscoveryTimeout uint32 + LinkLocalAddressBehavior uint32 + LinkLocalAddressTimeout uint32 + ZoneIndices [ScopeLevelCount]uint32 + SitePrefixLength uint32 + Metric uint32 + NlMtu uint32 + Connected uint8 + SupportsWakeUpPatterns uint8 + SupportsNeighborDiscovery uint8 + SupportsRouterDiscovery uint8 + ReachableTime uint32 + TransmitOffload uint32 + ReceiveOffload uint32 + DisableDefaultRoutes uint8 +} + // Console related constants used for the mode parameter to SetConsoleMode. See // https://docs.microsoft.com/en-us/windows/console/setconsolemode for details. @@ -3380,3 +3566,38 @@ type BLOB struct { Size uint32 BlobData *byte } + +type ComStat struct { + Flags uint32 + CBInQue uint32 + CBOutQue uint32 +} + +type DCB struct { + DCBlength uint32 + BaudRate uint32 + Flags uint32 + wReserved uint16 + XonLim uint16 + XoffLim uint16 + ByteSize uint8 + Parity uint8 + StopBits uint8 + XonChar byte + XoffChar byte + ErrorChar byte + EofChar byte + EvtChar byte + wReserved1 uint16 +} + +// Keyboard Layout Flags. +// See https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-loadkeyboardlayoutw +const ( + KLF_ACTIVATE = 0x00000001 + KLF_SUBSTITUTE_OK = 0x00000002 + KLF_REORDER = 0x00000008 + KLF_REPLACELANG = 0x00000010 + KLF_NOTELLSHELL = 0x00000080 + KLF_SETFORPROCESS = 0x00000100 +) diff --git a/vendor/golang.org/x/sys/windows/zsyscall_windows.go b/vendor/golang.org/x/sys/windows/zsyscall_windows.go index db6282e0..01c0716c 100644 --- a/vendor/golang.org/x/sys/windows/zsyscall_windows.go +++ b/vendor/golang.org/x/sys/windows/zsyscall_windows.go @@ -91,6 +91,7 @@ var ( procEnumServicesStatusExW = modadvapi32.NewProc("EnumServicesStatusExW") procEqualSid = modadvapi32.NewProc("EqualSid") procFreeSid = modadvapi32.NewProc("FreeSid") + procGetAce = modadvapi32.NewProc("GetAce") procGetLengthSid = modadvapi32.NewProc("GetLengthSid") procGetNamedSecurityInfoW = modadvapi32.NewProc("GetNamedSecurityInfoW") procGetSecurityDescriptorControl = modadvapi32.NewProc("GetSecurityDescriptorControl") @@ -180,13 +181,21 @@ var ( procDnsRecordListFree = moddnsapi.NewProc("DnsRecordListFree") procDwmGetWindowAttribute = moddwmapi.NewProc("DwmGetWindowAttribute") procDwmSetWindowAttribute = moddwmapi.NewProc("DwmSetWindowAttribute") + procCancelMibChangeNotify2 = modiphlpapi.NewProc("CancelMibChangeNotify2") procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses") procGetAdaptersInfo = modiphlpapi.NewProc("GetAdaptersInfo") procGetBestInterfaceEx = modiphlpapi.NewProc("GetBestInterfaceEx") procGetIfEntry = modiphlpapi.NewProc("GetIfEntry") + procGetIfEntry2Ex = modiphlpapi.NewProc("GetIfEntry2Ex") + procGetUnicastIpAddressEntry = modiphlpapi.NewProc("GetUnicastIpAddressEntry") + procNotifyIpInterfaceChange = modiphlpapi.NewProc("NotifyIpInterfaceChange") + procNotifyUnicastIpAddressChange = modiphlpapi.NewProc("NotifyUnicastIpAddressChange") + procAddDllDirectory = modkernel32.NewProc("AddDllDirectory") procAssignProcessToJobObject = modkernel32.NewProc("AssignProcessToJobObject") procCancelIo = modkernel32.NewProc("CancelIo") procCancelIoEx = modkernel32.NewProc("CancelIoEx") + procClearCommBreak = modkernel32.NewProc("ClearCommBreak") + procClearCommError = modkernel32.NewProc("ClearCommError") procCloseHandle = modkernel32.NewProc("CloseHandle") procClosePseudoConsole = modkernel32.NewProc("ClosePseudoConsole") procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe") @@ -211,7 +220,9 @@ var ( procDeleteProcThreadAttributeList = modkernel32.NewProc("DeleteProcThreadAttributeList") procDeleteVolumeMountPointW = modkernel32.NewProc("DeleteVolumeMountPointW") procDeviceIoControl = modkernel32.NewProc("DeviceIoControl") + procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe") procDuplicateHandle = modkernel32.NewProc("DuplicateHandle") + procEscapeCommFunction = modkernel32.NewProc("EscapeCommFunction") procExitProcess = modkernel32.NewProc("ExitProcess") procExpandEnvironmentStringsW = modkernel32.NewProc("ExpandEnvironmentStringsW") procFindClose = modkernel32.NewProc("FindClose") @@ -235,11 +246,15 @@ var ( procGenerateConsoleCtrlEvent = modkernel32.NewProc("GenerateConsoleCtrlEvent") procGetACP = modkernel32.NewProc("GetACP") procGetActiveProcessorCount = modkernel32.NewProc("GetActiveProcessorCount") + procGetCommModemStatus = modkernel32.NewProc("GetCommModemStatus") + procGetCommState = modkernel32.NewProc("GetCommState") procGetCommTimeouts = modkernel32.NewProc("GetCommTimeouts") procGetCommandLineW = modkernel32.NewProc("GetCommandLineW") procGetComputerNameExW = modkernel32.NewProc("GetComputerNameExW") procGetComputerNameW = modkernel32.NewProc("GetComputerNameW") + procGetConsoleCP = modkernel32.NewProc("GetConsoleCP") procGetConsoleMode = modkernel32.NewProc("GetConsoleMode") + procGetConsoleOutputCP = modkernel32.NewProc("GetConsoleOutputCP") procGetConsoleScreenBufferInfo = modkernel32.NewProc("GetConsoleScreenBufferInfo") procGetCurrentDirectoryW = modkernel32.NewProc("GetCurrentDirectoryW") procGetCurrentProcessId = modkernel32.NewProc("GetCurrentProcessId") @@ -265,8 +280,10 @@ var ( procGetMaximumProcessorCount = modkernel32.NewProc("GetMaximumProcessorCount") procGetModuleFileNameW = modkernel32.NewProc("GetModuleFileNameW") procGetModuleHandleExW = modkernel32.NewProc("GetModuleHandleExW") + procGetNamedPipeClientProcessId = modkernel32.NewProc("GetNamedPipeClientProcessId") procGetNamedPipeHandleStateW = modkernel32.NewProc("GetNamedPipeHandleStateW") procGetNamedPipeInfo = modkernel32.NewProc("GetNamedPipeInfo") + procGetNamedPipeServerProcessId = modkernel32.NewProc("GetNamedPipeServerProcessId") procGetOverlappedResult = modkernel32.NewProc("GetOverlappedResult") procGetPriorityClass = modkernel32.NewProc("GetPriorityClass") procGetProcAddress = modkernel32.NewProc("GetProcAddress") @@ -321,6 +338,7 @@ var ( procProcess32NextW = modkernel32.NewProc("Process32NextW") procProcessIdToSessionId = modkernel32.NewProc("ProcessIdToSessionId") procPulseEvent = modkernel32.NewProc("PulseEvent") + procPurgeComm = modkernel32.NewProc("PurgeComm") procQueryDosDeviceW = modkernel32.NewProc("QueryDosDeviceW") procQueryFullProcessImageNameW = modkernel32.NewProc("QueryFullProcessImageNameW") procQueryInformationJobObject = modkernel32.NewProc("QueryInformationJobObject") @@ -330,12 +348,18 @@ var ( procReadProcessMemory = modkernel32.NewProc("ReadProcessMemory") procReleaseMutex = modkernel32.NewProc("ReleaseMutex") procRemoveDirectoryW = modkernel32.NewProc("RemoveDirectoryW") + procRemoveDllDirectory = modkernel32.NewProc("RemoveDllDirectory") procResetEvent = modkernel32.NewProc("ResetEvent") procResizePseudoConsole = modkernel32.NewProc("ResizePseudoConsole") procResumeThread = modkernel32.NewProc("ResumeThread") + procSetCommBreak = modkernel32.NewProc("SetCommBreak") + procSetCommMask = modkernel32.NewProc("SetCommMask") + procSetCommState = modkernel32.NewProc("SetCommState") procSetCommTimeouts = modkernel32.NewProc("SetCommTimeouts") + procSetConsoleCP = modkernel32.NewProc("SetConsoleCP") procSetConsoleCursorPosition = modkernel32.NewProc("SetConsoleCursorPosition") procSetConsoleMode = modkernel32.NewProc("SetConsoleMode") + procSetConsoleOutputCP = modkernel32.NewProc("SetConsoleOutputCP") procSetCurrentDirectoryW = modkernel32.NewProc("SetCurrentDirectoryW") procSetDefaultDllDirectories = modkernel32.NewProc("SetDefaultDllDirectories") procSetDllDirectoryW = modkernel32.NewProc("SetDllDirectoryW") @@ -348,6 +372,7 @@ var ( procSetFileInformationByHandle = modkernel32.NewProc("SetFileInformationByHandle") procSetFilePointer = modkernel32.NewProc("SetFilePointer") procSetFileTime = modkernel32.NewProc("SetFileTime") + procSetFileValidData = modkernel32.NewProc("SetFileValidData") procSetHandleInformation = modkernel32.NewProc("SetHandleInformation") procSetInformationJobObject = modkernel32.NewProc("SetInformationJobObject") procSetNamedPipeHandleState = modkernel32.NewProc("SetNamedPipeHandleState") @@ -358,6 +383,7 @@ var ( procSetStdHandle = modkernel32.NewProc("SetStdHandle") procSetVolumeLabelW = modkernel32.NewProc("SetVolumeLabelW") procSetVolumeMountPointW = modkernel32.NewProc("SetVolumeMountPointW") + procSetupComm = modkernel32.NewProc("SetupComm") procSizeofResource = modkernel32.NewProc("SizeofResource") procSleepEx = modkernel32.NewProc("SleepEx") procTerminateJobObject = modkernel32.NewProc("TerminateJobObject") @@ -376,6 +402,7 @@ var ( procVirtualQueryEx = modkernel32.NewProc("VirtualQueryEx") procVirtualUnlock = modkernel32.NewProc("VirtualUnlock") procWTSGetActiveConsoleSessionId = modkernel32.NewProc("WTSGetActiveConsoleSessionId") + procWaitCommEvent = modkernel32.NewProc("WaitCommEvent") procWaitForMultipleObjects = modkernel32.NewProc("WaitForMultipleObjects") procWaitForSingleObject = modkernel32.NewProc("WaitForSingleObject") procWriteConsoleW = modkernel32.NewProc("WriteConsoleW") @@ -386,6 +413,7 @@ var ( procTransmitFile = modmswsock.NewProc("TransmitFile") procNetApiBufferFree = modnetapi32.NewProc("NetApiBufferFree") procNetGetJoinInformation = modnetapi32.NewProc("NetGetJoinInformation") + procNetUserEnum = modnetapi32.NewProc("NetUserEnum") procNetUserGetInfo = modnetapi32.NewProc("NetUserGetInfo") procNtCreateFile = modntdll.NewProc("NtCreateFile") procNtCreateNamedPipeFile = modntdll.NewProc("NtCreateNamedPipeFile") @@ -461,12 +489,16 @@ var ( procGetDesktopWindow = moduser32.NewProc("GetDesktopWindow") procGetForegroundWindow = moduser32.NewProc("GetForegroundWindow") procGetGUIThreadInfo = moduser32.NewProc("GetGUIThreadInfo") + procGetKeyboardLayout = moduser32.NewProc("GetKeyboardLayout") procGetShellWindow = moduser32.NewProc("GetShellWindow") procGetWindowThreadProcessId = moduser32.NewProc("GetWindowThreadProcessId") procIsWindow = moduser32.NewProc("IsWindow") procIsWindowUnicode = moduser32.NewProc("IsWindowUnicode") procIsWindowVisible = moduser32.NewProc("IsWindowVisible") + procLoadKeyboardLayoutW = moduser32.NewProc("LoadKeyboardLayoutW") procMessageBoxW = moduser32.NewProc("MessageBoxW") + procToUnicodeEx = moduser32.NewProc("ToUnicodeEx") + procUnloadKeyboardLayout = moduser32.NewProc("UnloadKeyboardLayout") procCreateEnvironmentBlock = moduserenv.NewProc("CreateEnvironmentBlock") procDestroyEnvironmentBlock = moduserenv.NewProc("DestroyEnvironmentBlock") procGetUserProfileDirectoryW = moduserenv.NewProc("GetUserProfileDirectoryW") @@ -772,6 +804,14 @@ func FreeSid(sid *SID) (err error) { return } +func GetAce(acl *ACL, aceIndex uint32, pAce **ACCESS_ALLOWED_ACE) (err error) { + r1, _, e1 := syscall.Syscall(procGetAce.Addr(), 3, uintptr(unsafe.Pointer(acl)), uintptr(aceIndex), uintptr(unsafe.Pointer(pAce))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func GetLengthSid(sid *SID) (len uint32) { r0, _, _ := syscall.Syscall(procGetLengthSid.Addr(), 1, uintptr(unsafe.Pointer(sid)), 0, 0) len = uint32(r0) @@ -1573,6 +1613,14 @@ func DwmSetWindowAttribute(hwnd HWND, attribute uint32, value unsafe.Pointer, si return } +func CancelMibChangeNotify2(notificationHandle Handle) (errcode error) { + r0, _, _ := syscall.Syscall(procCancelMibChangeNotify2.Addr(), 1, uintptr(notificationHandle), 0, 0) + if r0 != 0 { + errcode = syscall.Errno(r0) + } + return +} + func GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) { r0, _, _ := syscall.Syscall6(procGetAdaptersAddresses.Addr(), 5, uintptr(family), uintptr(flags), uintptr(reserved), uintptr(unsafe.Pointer(adapterAddresses)), uintptr(unsafe.Pointer(sizePointer)), 0) if r0 != 0 { @@ -1605,6 +1653,55 @@ func GetIfEntry(pIfRow *MibIfRow) (errcode error) { return } +func GetIfEntry2Ex(level uint32, row *MibIfRow2) (errcode error) { + r0, _, _ := syscall.Syscall(procGetIfEntry2Ex.Addr(), 2, uintptr(level), uintptr(unsafe.Pointer(row)), 0) + if r0 != 0 { + errcode = syscall.Errno(r0) + } + return +} + +func GetUnicastIpAddressEntry(row *MibUnicastIpAddressRow) (errcode error) { + r0, _, _ := syscall.Syscall(procGetUnicastIpAddressEntry.Addr(), 1, uintptr(unsafe.Pointer(row)), 0, 0) + if r0 != 0 { + errcode = syscall.Errno(r0) + } + return +} + +func NotifyIpInterfaceChange(family uint16, callback uintptr, callerContext unsafe.Pointer, initialNotification bool, notificationHandle *Handle) (errcode error) { + var _p0 uint32 + if initialNotification { + _p0 = 1 + } + r0, _, _ := syscall.Syscall6(procNotifyIpInterfaceChange.Addr(), 5, uintptr(family), uintptr(callback), uintptr(callerContext), uintptr(_p0), uintptr(unsafe.Pointer(notificationHandle)), 0) + if r0 != 0 { + errcode = syscall.Errno(r0) + } + return +} + +func NotifyUnicastIpAddressChange(family uint16, callback uintptr, callerContext unsafe.Pointer, initialNotification bool, notificationHandle *Handle) (errcode error) { + var _p0 uint32 + if initialNotification { + _p0 = 1 + } + r0, _, _ := syscall.Syscall6(procNotifyUnicastIpAddressChange.Addr(), 5, uintptr(family), uintptr(callback), uintptr(callerContext), uintptr(_p0), uintptr(unsafe.Pointer(notificationHandle)), 0) + if r0 != 0 { + errcode = syscall.Errno(r0) + } + return +} + +func AddDllDirectory(path *uint16) (cookie uintptr, err error) { + r0, _, e1 := syscall.Syscall(procAddDllDirectory.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) + cookie = uintptr(r0) + if cookie == 0 { + err = errnoErr(e1) + } + return +} + func AssignProcessToJobObject(job Handle, process Handle) (err error) { r1, _, e1 := syscall.Syscall(procAssignProcessToJobObject.Addr(), 2, uintptr(job), uintptr(process), 0) if r1 == 0 { @@ -1629,6 +1726,22 @@ func CancelIoEx(s Handle, o *Overlapped) (err error) { return } +func ClearCommBreak(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procClearCommBreak.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func ClearCommError(handle Handle, lpErrors *uint32, lpStat *ComStat) (err error) { + r1, _, e1 := syscall.Syscall(procClearCommError.Addr(), 3, uintptr(handle), uintptr(unsafe.Pointer(lpErrors)), uintptr(unsafe.Pointer(lpStat))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func CloseHandle(handle Handle) (err error) { r1, _, e1 := syscall.Syscall(procCloseHandle.Addr(), 1, uintptr(handle), 0, 0) if r1 == 0 { @@ -1833,6 +1946,14 @@ func DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBuff return } +func DisconnectNamedPipe(pipe Handle) (err error) { + r1, _, e1 := syscall.Syscall(procDisconnectNamedPipe.Addr(), 1, uintptr(pipe), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error) { var _p0 uint32 if bInheritHandle { @@ -1845,6 +1966,14 @@ func DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetP return } +func EscapeCommFunction(handle Handle, dwFunc uint32) (err error) { + r1, _, e1 := syscall.Syscall(procEscapeCommFunction.Addr(), 2, uintptr(handle), uintptr(dwFunc), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func ExitProcess(exitcode uint32) { syscall.Syscall(procExitProcess.Addr(), 1, uintptr(exitcode), 0, 0) return @@ -2046,6 +2175,22 @@ func GetActiveProcessorCount(groupNumber uint16) (ret uint32) { return } +func GetCommModemStatus(handle Handle, lpModemStat *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetCommModemStatus.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(lpModemStat)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func GetCommState(handle Handle, lpDCB *DCB) (err error) { + r1, _, e1 := syscall.Syscall(procGetCommState.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(lpDCB)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func GetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) { r1, _, e1 := syscall.Syscall(procGetCommTimeouts.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(timeouts)), 0) if r1 == 0 { @@ -2076,6 +2221,15 @@ func GetComputerName(buf *uint16, n *uint32) (err error) { return } +func GetConsoleCP() (cp uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetConsoleCP.Addr(), 0, 0, 0, 0) + cp = uint32(r0) + if cp == 0 { + err = errnoErr(e1) + } + return +} + func GetConsoleMode(console Handle, mode *uint32) (err error) { r1, _, e1 := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(console), uintptr(unsafe.Pointer(mode)), 0) if r1 == 0 { @@ -2084,6 +2238,15 @@ func GetConsoleMode(console Handle, mode *uint32) (err error) { return } +func GetConsoleOutputCP() (cp uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetConsoleOutputCP.Addr(), 0, 0, 0, 0) + cp = uint32(r0) + if cp == 0 { + err = errnoErr(e1) + } + return +} + func GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) { r1, _, e1 := syscall.Syscall(procGetConsoleScreenBufferInfo.Addr(), 2, uintptr(console), uintptr(unsafe.Pointer(info)), 0) if r1 == 0 { @@ -2285,6 +2448,14 @@ func GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err er return } +func GetNamedPipeClientProcessId(pipe Handle, clientProcessID *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetNamedPipeClientProcessId.Addr(), 2, uintptr(pipe), uintptr(unsafe.Pointer(clientProcessID)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func GetNamedPipeHandleState(pipe Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) { r1, _, e1 := syscall.Syscall9(procGetNamedPipeHandleStateW.Addr(), 7, uintptr(pipe), uintptr(unsafe.Pointer(state)), uintptr(unsafe.Pointer(curInstances)), uintptr(unsafe.Pointer(maxCollectionCount)), uintptr(unsafe.Pointer(collectDataTimeout)), uintptr(unsafe.Pointer(userName)), uintptr(maxUserNameSize), 0, 0) if r1 == 0 { @@ -2301,6 +2472,14 @@ func GetNamedPipeInfo(pipe Handle, flags *uint32, outSize *uint32, inSize *uint3 return } +func GetNamedPipeServerProcessId(pipe Handle, serverProcessID *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetNamedPipeServerProcessId.Addr(), 2, uintptr(pipe), uintptr(unsafe.Pointer(serverProcessID)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func GetOverlappedResult(handle Handle, overlapped *Overlapped, done *uint32, wait bool) (err error) { var _p0 uint32 if wait { @@ -2798,6 +2977,14 @@ func PulseEvent(event Handle) (err error) { return } +func PurgeComm(handle Handle, dwFlags uint32) (err error) { + r1, _, e1 := syscall.Syscall(procPurgeComm.Addr(), 2, uintptr(handle), uintptr(dwFlags), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func QueryDosDevice(deviceName *uint16, targetPath *uint16, max uint32) (n uint32, err error) { r0, _, e1 := syscall.Syscall(procQueryDosDeviceW.Addr(), 3, uintptr(unsafe.Pointer(deviceName)), uintptr(unsafe.Pointer(targetPath)), uintptr(max)) n = uint32(r0) @@ -2879,6 +3066,14 @@ func RemoveDirectory(path *uint16) (err error) { return } +func RemoveDllDirectory(cookie uintptr) (err error) { + r1, _, e1 := syscall.Syscall(procRemoveDllDirectory.Addr(), 1, uintptr(cookie), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func ResetEvent(event Handle) (err error) { r1, _, e1 := syscall.Syscall(procResetEvent.Addr(), 1, uintptr(event), 0, 0) if r1 == 0 { @@ -2904,6 +3099,30 @@ func ResumeThread(thread Handle) (ret uint32, err error) { return } +func SetCommBreak(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procSetCommBreak.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func SetCommMask(handle Handle, dwEvtMask uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetCommMask.Addr(), 2, uintptr(handle), uintptr(dwEvtMask), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func SetCommState(handle Handle, lpDCB *DCB) (err error) { + r1, _, e1 := syscall.Syscall(procSetCommState.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(lpDCB)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func SetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) { r1, _, e1 := syscall.Syscall(procSetCommTimeouts.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(timeouts)), 0) if r1 == 0 { @@ -2912,6 +3131,14 @@ func SetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) { return } +func SetConsoleCP(cp uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetConsoleCP.Addr(), 1, uintptr(cp), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func setConsoleCursorPosition(console Handle, position uint32) (err error) { r1, _, e1 := syscall.Syscall(procSetConsoleCursorPosition.Addr(), 2, uintptr(console), uintptr(position), 0) if r1 == 0 { @@ -2928,6 +3155,14 @@ func SetConsoleMode(console Handle, mode uint32) (err error) { return } +func SetConsoleOutputCP(cp uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetConsoleOutputCP.Addr(), 1, uintptr(cp), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func SetCurrentDirectory(path *uint16) (err error) { r1, _, e1 := syscall.Syscall(procSetCurrentDirectoryW.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) if r1 == 0 { @@ -3032,6 +3267,14 @@ func SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetim return } +func SetFileValidData(handle Handle, validDataLength int64) (err error) { + r1, _, e1 := syscall.Syscall(procSetFileValidData.Addr(), 2, uintptr(handle), uintptr(validDataLength), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error) { r1, _, e1 := syscall.Syscall(procSetHandleInformation.Addr(), 3, uintptr(handle), uintptr(mask), uintptr(flags)) if r1 == 0 { @@ -3117,6 +3360,14 @@ func SetVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16) (err erro return } +func SetupComm(handle Handle, dwInQueue uint32, dwOutQueue uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetupComm.Addr(), 3, uintptr(handle), uintptr(dwInQueue), uintptr(dwOutQueue)) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func SizeofResource(module Handle, resInfo Handle) (size uint32, err error) { r0, _, e1 := syscall.Syscall(procSizeofResource.Addr(), 2, uintptr(module), uintptr(resInfo), 0) size = uint32(r0) @@ -3263,6 +3514,14 @@ func WTSGetActiveConsoleSessionId() (sessionID uint32) { return } +func WaitCommEvent(handle Handle, lpEvtMask *uint32, lpOverlapped *Overlapped) (err error) { + r1, _, e1 := syscall.Syscall(procWaitCommEvent.Addr(), 3, uintptr(handle), uintptr(unsafe.Pointer(lpEvtMask)), uintptr(unsafe.Pointer(lpOverlapped))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func waitForMultipleObjects(count uint32, handles uintptr, waitAll bool, waitMilliseconds uint32) (event uint32, err error) { var _p0 uint32 if waitAll { @@ -3350,6 +3609,14 @@ func NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (nete return } +func NetUserEnum(serverName *uint16, level uint32, filter uint32, buf **byte, prefMaxLen uint32, entriesRead *uint32, totalEntries *uint32, resumeHandle *uint32) (neterr error) { + r0, _, _ := syscall.Syscall9(procNetUserEnum.Addr(), 8, uintptr(unsafe.Pointer(serverName)), uintptr(level), uintptr(filter), uintptr(unsafe.Pointer(buf)), uintptr(prefMaxLen), uintptr(unsafe.Pointer(entriesRead)), uintptr(unsafe.Pointer(totalEntries)), uintptr(unsafe.Pointer(resumeHandle)), 0) + if r0 != 0 { + neterr = syscall.Errno(r0) + } + return +} + func NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) { r0, _, _ := syscall.Syscall6(procNetUserGetInfo.Addr(), 4, uintptr(unsafe.Pointer(serverName)), uintptr(unsafe.Pointer(userName)), uintptr(level), uintptr(unsafe.Pointer(buf)), 0, 0) if r0 != 0 { @@ -3928,6 +4195,12 @@ func GetGUIThreadInfo(thread uint32, info *GUIThreadInfo) (err error) { return } +func GetKeyboardLayout(tid uint32) (hkl Handle) { + r0, _, _ := syscall.Syscall(procGetKeyboardLayout.Addr(), 1, uintptr(tid), 0, 0) + hkl = Handle(r0) + return +} + func GetShellWindow() (shellWindow HWND) { r0, _, _ := syscall.Syscall(procGetShellWindow.Addr(), 0, 0, 0, 0) shellWindow = HWND(r0) @@ -3961,6 +4234,15 @@ func IsWindowVisible(hwnd HWND) (isVisible bool) { return } +func LoadKeyboardLayout(name *uint16, flags uint32) (hkl Handle, err error) { + r0, _, e1 := syscall.Syscall(procLoadKeyboardLayoutW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(flags), 0) + hkl = Handle(r0) + if hkl == 0 { + err = errnoErr(e1) + } + return +} + func MessageBox(hwnd HWND, text *uint16, caption *uint16, boxtype uint32) (ret int32, err error) { r0, _, e1 := syscall.Syscall6(procMessageBoxW.Addr(), 4, uintptr(hwnd), uintptr(unsafe.Pointer(text)), uintptr(unsafe.Pointer(caption)), uintptr(boxtype), 0, 0) ret = int32(r0) @@ -3970,6 +4252,20 @@ func MessageBox(hwnd HWND, text *uint16, caption *uint16, boxtype uint32) (ret i return } +func ToUnicodeEx(vkey uint32, scancode uint32, keystate *byte, pwszBuff *uint16, cchBuff int32, flags uint32, hkl Handle) (ret int32) { + r0, _, _ := syscall.Syscall9(procToUnicodeEx.Addr(), 7, uintptr(vkey), uintptr(scancode), uintptr(unsafe.Pointer(keystate)), uintptr(unsafe.Pointer(pwszBuff)), uintptr(cchBuff), uintptr(flags), uintptr(hkl), 0, 0) + ret = int32(r0) + return +} + +func UnloadKeyboardLayout(hkl Handle) (err error) { + r1, _, e1 := syscall.Syscall(procUnloadKeyboardLayout.Addr(), 1, uintptr(hkl), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func CreateEnvironmentBlock(block **uint16, token Token, inheritExisting bool) (err error) { var _p0 uint32 if inheritExisting { diff --git a/vendor/golang.org/x/text/feature/plural/common.go b/vendor/golang.org/x/text/feature/plural/common.go new file mode 100644 index 00000000..fdcb373f --- /dev/null +++ b/vendor/golang.org/x/text/feature/plural/common.go @@ -0,0 +1,70 @@ +// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. + +package plural + +// Form defines a plural form. +// +// Not all languages support all forms. Also, the meaning of each form varies +// per language. It is important to note that the name of a form does not +// necessarily correspond one-to-one with the set of numbers. For instance, +// for Croation, One matches not only 1, but also 11, 21, etc. +// +// Each language must at least support the form "other". +type Form byte + +const ( + Other Form = iota + Zero + One + Two + Few + Many +) + +var countMap = map[string]Form{ + "other": Other, + "zero": Zero, + "one": One, + "two": Two, + "few": Few, + "many": Many, +} + +type pluralCheck struct { + // category: + // 3..7: opID + // 0..2: category + cat byte + setID byte +} + +// opID identifies the type of operand in the plural rule, being i, n or f. +// (v, w, and t are treated as filters in our implementation.) +type opID byte + +const ( + opMod opID = 0x1 // is '%' used? + opNotEqual opID = 0x2 // using "!=" to compare + opI opID = 0 << 2 // integers after taking the absolute value + opN opID = 1 << 2 // full number (must be integer) + opF opID = 2 << 2 // fraction + opV opID = 3 << 2 // number of visible digits + opW opID = 4 << 2 // number of visible digits without trailing zeros + opBretonM opID = 5 << 2 // hard-wired rule for Breton + opItalian800 opID = 6 << 2 // hard-wired rule for Italian + opAzerbaijan00s opID = 7 << 2 // hard-wired rule for Azerbaijan +) +const ( + // Use this plural form to indicate the next rule needs to match as well. + // The last condition in the list will have the correct plural form. + andNext = 0x7 + formMask = 0x7 + + opShift = 3 + + // numN indicates the maximum integer, or maximum mod value, for which we + // have inclusion masks. + numN = 100 + // The common denominator of the modulo that is taken. + maxMod = 100 +) diff --git a/vendor/golang.org/x/text/feature/plural/message.go b/vendor/golang.org/x/text/feature/plural/message.go new file mode 100644 index 00000000..56d518cc --- /dev/null +++ b/vendor/golang.org/x/text/feature/plural/message.go @@ -0,0 +1,244 @@ +// Copyright 2017 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 plural + +import ( + "fmt" + "io" + "reflect" + "strconv" + + "golang.org/x/text/internal/catmsg" + "golang.org/x/text/internal/number" + "golang.org/x/text/language" + "golang.org/x/text/message/catalog" +) + +// TODO: consider deleting this interface. Maybe VisibleDigits is always +// sufficient and practical. + +// Interface is used for types that can determine their own plural form. +type Interface interface { + // PluralForm reports the plural form for the given language of the + // underlying value. It also returns the integer value. If the integer value + // is larger than fits in n, PluralForm may return a value modulo + // 10,000,000. + PluralForm(t language.Tag, scale int) (f Form, n int) +} + +// Selectf returns the first case for which its selector is a match for the +// arg-th substitution argument to a formatting call, formatting it as indicated +// by format. +// +// The cases argument are pairs of selectors and messages. Selectors are of type +// string or Form. Messages are of type string or catalog.Message. A selector +// matches an argument if: +// - it is "other" or Other +// - it matches the plural form of the argument: "zero", "one", "two", "few", +// or "many", or the equivalent Form +// - it is of the form "=x" where x is an integer that matches the value of +// the argument. +// - it is of the form " kindDefault { + e.EncodeUint(uint64(m.scale)) + } + + forms := validForms(cardinal, e.Language()) + + for i := 0; i < len(m.cases); { + if err := compileSelector(e, forms, m.cases[i]); err != nil { + return err + } + if i++; i >= len(m.cases) { + return fmt.Errorf("plural: no message defined for selector %v", m.cases[i-1]) + } + var msg catalog.Message + switch x := m.cases[i].(type) { + case string: + msg = catalog.String(x) + case catalog.Message: + msg = x + default: + return fmt.Errorf("plural: message of type %T; must be string or catalog.Message", x) + } + if err := e.EncodeMessage(msg); err != nil { + return err + } + i++ + } + return nil +} + +func compileSelector(e *catmsg.Encoder, valid []Form, selector interface{}) error { + form := Other + switch x := selector.(type) { + case string: + if x == "" { + return fmt.Errorf("plural: empty selector") + } + if c := x[0]; c == '=' || c == '<' { + val, err := strconv.ParseUint(x[1:], 10, 16) + if err != nil { + return fmt.Errorf("plural: invalid number in selector %q: %v", selector, err) + } + e.EncodeUint(uint64(c)) + e.EncodeUint(val) + return nil + } + var ok bool + form, ok = countMap[x] + if !ok { + return fmt.Errorf("plural: invalid plural form %q", selector) + } + case Form: + form = x + default: + return fmt.Errorf("plural: selector of type %T; want string or Form", selector) + } + + ok := false + for _, f := range valid { + if f == form { + ok = true + break + } + } + if !ok { + return fmt.Errorf("plural: form %q not supported for language %q", selector, e.Language()) + } + e.EncodeUint(uint64(form)) + return nil +} + +func execute(d *catmsg.Decoder) bool { + lang := d.Language() + argN := int(d.DecodeUint()) + kind := int(d.DecodeUint()) + scale := -1 // default + if kind > kindDefault { + scale = int(d.DecodeUint()) + } + form := Other + n := -1 + if arg := d.Arg(argN); arg == nil { + // Default to Other. + } else if x, ok := arg.(number.VisibleDigits); ok { + d := x.Digits(nil, lang, scale) + form, n = cardinal.matchDisplayDigits(lang, &d) + } else if x, ok := arg.(Interface); ok { + // This covers lists and formatters from the number package. + form, n = x.PluralForm(lang, scale) + } else { + var f number.Formatter + switch kind { + case kindScale: + f.InitDecimal(lang) + f.SetScale(scale) + case kindScientific: + f.InitScientific(lang) + f.SetScale(scale) + case kindPrecision: + f.InitDecimal(lang) + f.SetPrecision(scale) + case kindDefault: + // sensible default + f.InitDecimal(lang) + if k := reflect.TypeOf(arg).Kind(); reflect.Int <= k && k <= reflect.Uintptr { + f.SetScale(0) + } else { + f.SetScale(2) + } + } + var dec number.Decimal // TODO: buffer in Printer + dec.Convert(f.RoundingContext, arg) + v := number.FormatDigits(&dec, f.RoundingContext) + if !v.NaN && !v.Inf { + form, n = cardinal.matchDisplayDigits(d.Language(), &v) + } + } + for !d.Done() { + f := d.DecodeUint() + if (f == '=' && n == int(d.DecodeUint())) || + (f == '<' && 0 <= n && n < int(d.DecodeUint())) || + form == Form(f) || + Other == Form(f) { + return d.ExecuteMessage() + } + d.SkipMessage() + } + return false +} diff --git a/vendor/golang.org/x/text/feature/plural/plural.go b/vendor/golang.org/x/text/feature/plural/plural.go new file mode 100644 index 00000000..e9f2d42e --- /dev/null +++ b/vendor/golang.org/x/text/feature/plural/plural.go @@ -0,0 +1,262 @@ +// Copyright 2016 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. + +//go:generate go run gen.go gen_common.go + +// Package plural provides utilities for handling linguistic plurals in text. +// +// The definitions in this package are based on the plural rule handling defined +// in CLDR. See +// https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules for +// details. +package plural + +import ( + "golang.org/x/text/internal/language/compact" + "golang.org/x/text/internal/number" + "golang.org/x/text/language" +) + +// Rules defines the plural rules for all languages for a certain plural type. +// +// This package is UNDER CONSTRUCTION and its API may change. +type Rules struct { + rules []pluralCheck + index []byte + langToIndex []byte + inclusionMasks []uint64 +} + +var ( + // Cardinal defines the plural rules for numbers indicating quantities. + Cardinal *Rules = cardinal + + // Ordinal defines the plural rules for numbers indicating position + // (first, second, etc.). + Ordinal *Rules = ordinal + + ordinal = &Rules{ + ordinalRules, + ordinalIndex, + ordinalLangToIndex, + ordinalInclusionMasks[:], + } + + cardinal = &Rules{ + cardinalRules, + cardinalIndex, + cardinalLangToIndex, + cardinalInclusionMasks[:], + } +) + +// getIntApprox converts the digits in slice digits[start:end] to an integer +// according to the following rules: +// - Let i be asInt(digits[start:end]), where out-of-range digits are assumed +// to be zero. +// - Result n is big if i / 10^nMod > 1. +// - Otherwise the result is i % 10^nMod. +// +// For example, if digits is {1, 2, 3} and start:end is 0:5, then the result +// for various values of nMod is: +// - when nMod == 2, n == big +// - when nMod == 3, n == big +// - when nMod == 4, n == big +// - when nMod == 5, n == 12300 +// - when nMod == 6, n == 12300 +// - when nMod == 7, n == 12300 +func getIntApprox(digits []byte, start, end, nMod, big int) (n int) { + // Leading 0 digits just result in 0. + p := start + if p < 0 { + p = 0 + } + // Range only over the part for which we have digits. + mid := end + if mid >= len(digits) { + mid = len(digits) + } + // Check digits more significant that nMod. + if q := end - nMod; q > 0 { + if q > mid { + q = mid + } + for ; p < q; p++ { + if digits[p] != 0 { + return big + } + } + } + for ; p < mid; p++ { + n = 10*n + int(digits[p]) + } + // Multiply for trailing zeros. + for ; p < end; p++ { + n *= 10 + } + return n +} + +// MatchDigits computes the plural form for the given language and the given +// decimal floating point digits. The digits are stored in big-endian order and +// are of value byte(0) - byte(9). The floating point position is indicated by +// exp and the number of visible decimals is scale. All leading and trailing +// zeros may be omitted from digits. +// +// The following table contains examples of possible arguments to represent +// the given numbers. +// +// decimal digits exp scale +// 123 []byte{1, 2, 3} 3 0 +// 123.4 []byte{1, 2, 3, 4} 3 1 +// 123.40 []byte{1, 2, 3, 4} 3 2 +// 100000 []byte{1} 6 0 +// 100000.00 []byte{1} 6 3 +func (p *Rules) MatchDigits(t language.Tag, digits []byte, exp, scale int) Form { + index := tagToID(t) + + // Differentiate up to including mod 1000000 for the integer part. + n := getIntApprox(digits, 0, exp, 6, 1000000) + + // Differentiate up to including mod 100 for the fractional part. + f := getIntApprox(digits, exp, exp+scale, 2, 100) + + return matchPlural(p, index, n, f, scale) +} + +func (p *Rules) matchDisplayDigits(t language.Tag, d *number.Digits) (Form, int) { + n := getIntApprox(d.Digits, 0, int(d.Exp), 6, 1000000) + return p.MatchDigits(t, d.Digits, int(d.Exp), d.NumFracDigits()), n +} + +func validForms(p *Rules, t language.Tag) (forms []Form) { + offset := p.langToIndex[tagToID(t)] + rules := p.rules[p.index[offset]:p.index[offset+1]] + + forms = append(forms, Other) + last := Other + for _, r := range rules { + if cat := Form(r.cat & formMask); cat != andNext && last != cat { + forms = append(forms, cat) + last = cat + } + } + return forms +} + +func (p *Rules) matchComponents(t language.Tag, n, f, scale int) Form { + return matchPlural(p, tagToID(t), n, f, scale) +} + +// MatchPlural returns the plural form for the given language and plural +// operands (as defined in +// https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules): +// +// where +// n absolute value of the source number (integer and decimals) +// input +// i integer digits of n. +// v number of visible fraction digits in n, with trailing zeros. +// w number of visible fraction digits in n, without trailing zeros. +// f visible fractional digits in n, with trailing zeros (f = t * 10^(v-w)) +// t visible fractional digits in n, without trailing zeros. +// +// If any of the operand values is too large to fit in an int, it is okay to +// pass the value modulo 10,000,000. +func (p *Rules) MatchPlural(lang language.Tag, i, v, w, f, t int) Form { + return matchPlural(p, tagToID(lang), i, f, v) +} + +func matchPlural(p *Rules, index compact.ID, n, f, v int) Form { + nMask := p.inclusionMasks[n%maxMod] + // Compute the fMask inline in the rules below, as it is relatively rare. + // fMask := p.inclusionMasks[f%maxMod] + vMask := p.inclusionMasks[v%maxMod] + + // Do the matching + offset := p.langToIndex[index] + rules := p.rules[p.index[offset]:p.index[offset+1]] + for i := 0; i < len(rules); i++ { + rule := rules[i] + setBit := uint64(1 << rule.setID) + var skip bool + switch op := opID(rule.cat >> opShift); op { + case opI: // i = x + skip = n >= numN || nMask&setBit == 0 + + case opI | opNotEqual: // i != x + skip = n < numN && nMask&setBit != 0 + + case opI | opMod: // i % m = x + skip = nMask&setBit == 0 + + case opI | opMod | opNotEqual: // i % m != x + skip = nMask&setBit != 0 + + case opN: // n = x + skip = f != 0 || n >= numN || nMask&setBit == 0 + + case opN | opNotEqual: // n != x + skip = f == 0 && n < numN && nMask&setBit != 0 + + case opN | opMod: // n % m = x + skip = f != 0 || nMask&setBit == 0 + + case opN | opMod | opNotEqual: // n % m != x + skip = f == 0 && nMask&setBit != 0 + + case opF: // f = x + skip = f >= numN || p.inclusionMasks[f%maxMod]&setBit == 0 + + case opF | opNotEqual: // f != x + skip = f < numN && p.inclusionMasks[f%maxMod]&setBit != 0 + + case opF | opMod: // f % m = x + skip = p.inclusionMasks[f%maxMod]&setBit == 0 + + case opF | opMod | opNotEqual: // f % m != x + skip = p.inclusionMasks[f%maxMod]&setBit != 0 + + case opV: // v = x + skip = v < numN && vMask&setBit == 0 + + case opV | opNotEqual: // v != x + skip = v < numN && vMask&setBit != 0 + + case opW: // w == 0 + skip = f != 0 + + case opW | opNotEqual: // w != 0 + skip = f == 0 + + // Hard-wired rules that cannot be handled by our algorithm. + + case opBretonM: + skip = f != 0 || n == 0 || n%1000000 != 0 + + case opAzerbaijan00s: + // 100,200,300,400,500,600,700,800,900 + skip = n == 0 || n >= 1000 || n%100 != 0 + + case opItalian800: + skip = (f != 0 || n >= numN || nMask&setBit == 0) && n != 800 + } + if skip { + // advance over AND entries. + for ; i < len(rules) && rules[i].cat&formMask == andNext; i++ { + } + continue + } + // return if we have a final entry. + if cat := rule.cat & formMask; cat != andNext { + return Form(cat) + } + } + return Other +} + +func tagToID(t language.Tag) compact.ID { + id, _ := compact.RegionalID(compact.Tag(t)) + return id +} diff --git a/vendor/golang.org/x/text/feature/plural/tables.go b/vendor/golang.org/x/text/feature/plural/tables.go new file mode 100644 index 00000000..b06b9cb4 --- /dev/null +++ b/vendor/golang.org/x/text/feature/plural/tables.go @@ -0,0 +1,552 @@ +// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. + +package plural + +// CLDRVersion is the CLDR version from which the tables in this package are derived. +const CLDRVersion = "32" + +var ordinalRules = []pluralCheck{ // 64 elements + 0: {cat: 0x2f, setID: 0x4}, + 1: {cat: 0x3a, setID: 0x5}, + 2: {cat: 0x22, setID: 0x1}, + 3: {cat: 0x22, setID: 0x6}, + 4: {cat: 0x22, setID: 0x7}, + 5: {cat: 0x2f, setID: 0x8}, + 6: {cat: 0x3c, setID: 0x9}, + 7: {cat: 0x2f, setID: 0xa}, + 8: {cat: 0x3c, setID: 0xb}, + 9: {cat: 0x2c, setID: 0xc}, + 10: {cat: 0x24, setID: 0xd}, + 11: {cat: 0x2d, setID: 0xe}, + 12: {cat: 0x2d, setID: 0xf}, + 13: {cat: 0x2f, setID: 0x10}, + 14: {cat: 0x35, setID: 0x3}, + 15: {cat: 0xc5, setID: 0x11}, + 16: {cat: 0x2, setID: 0x1}, + 17: {cat: 0x5, setID: 0x3}, + 18: {cat: 0xd, setID: 0x12}, + 19: {cat: 0x22, setID: 0x1}, + 20: {cat: 0x2f, setID: 0x13}, + 21: {cat: 0x3d, setID: 0x14}, + 22: {cat: 0x2f, setID: 0x15}, + 23: {cat: 0x3a, setID: 0x16}, + 24: {cat: 0x2f, setID: 0x17}, + 25: {cat: 0x3b, setID: 0x18}, + 26: {cat: 0x2f, setID: 0xa}, + 27: {cat: 0x3c, setID: 0xb}, + 28: {cat: 0x22, setID: 0x1}, + 29: {cat: 0x23, setID: 0x19}, + 30: {cat: 0x24, setID: 0x1a}, + 31: {cat: 0x22, setID: 0x1b}, + 32: {cat: 0x23, setID: 0x2}, + 33: {cat: 0x24, setID: 0x1a}, + 34: {cat: 0xf, setID: 0x15}, + 35: {cat: 0x1a, setID: 0x16}, + 36: {cat: 0xf, setID: 0x17}, + 37: {cat: 0x1b, setID: 0x18}, + 38: {cat: 0xf, setID: 0x1c}, + 39: {cat: 0x1d, setID: 0x1d}, + 40: {cat: 0xa, setID: 0x1e}, + 41: {cat: 0xa, setID: 0x1f}, + 42: {cat: 0xc, setID: 0x20}, + 43: {cat: 0xe4, setID: 0x0}, + 44: {cat: 0x5, setID: 0x3}, + 45: {cat: 0xd, setID: 0xe}, + 46: {cat: 0xd, setID: 0x21}, + 47: {cat: 0x22, setID: 0x1}, + 48: {cat: 0x23, setID: 0x19}, + 49: {cat: 0x24, setID: 0x1a}, + 50: {cat: 0x25, setID: 0x22}, + 51: {cat: 0x22, setID: 0x23}, + 52: {cat: 0x23, setID: 0x19}, + 53: {cat: 0x24, setID: 0x1a}, + 54: {cat: 0x25, setID: 0x22}, + 55: {cat: 0x22, setID: 0x24}, + 56: {cat: 0x23, setID: 0x19}, + 57: {cat: 0x24, setID: 0x1a}, + 58: {cat: 0x25, setID: 0x22}, + 59: {cat: 0x21, setID: 0x25}, + 60: {cat: 0x22, setID: 0x1}, + 61: {cat: 0x23, setID: 0x2}, + 62: {cat: 0x24, setID: 0x26}, + 63: {cat: 0x25, setID: 0x27}, +} // Size: 152 bytes + +var ordinalIndex = []uint8{ // 22 elements + 0x00, 0x00, 0x02, 0x03, 0x04, 0x05, 0x07, 0x09, + 0x0b, 0x0f, 0x10, 0x13, 0x16, 0x1c, 0x1f, 0x22, + 0x28, 0x2f, 0x33, 0x37, 0x3b, 0x40, +} // Size: 46 bytes + +var ordinalLangToIndex = []uint8{ // 775 elements + // Entry 0 - 3F + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x12, 0x12, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, + 0x10, 0x10, 0x10, 0x00, 0x00, 0x05, 0x05, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Entry 40 - 7F + 0x12, 0x12, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, + 0x0e, 0x0e, 0x0e, 0x0e, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x14, 0x14, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Entry 80 - BF + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x0c, + 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, + 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, + 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, + 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, + 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, + 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, + 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, + // Entry C0 - FF + 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, + 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, + 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, + 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, + 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, + 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Entry 100 - 13F + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, + 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + // Entry 140 - 17F + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x11, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, + 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, + 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Entry 180 - 1BF + 0x00, 0x00, 0x00, 0x00, 0x09, 0x09, 0x09, 0x09, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x0a, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x08, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Entry 1C0 - 1FF + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0f, 0x0f, 0x00, 0x00, + 0x00, 0x00, 0x02, 0x0d, 0x0d, 0x02, 0x02, 0x02, + 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Entry 200 - 23F + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x13, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Entry 240 - 27F + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, + 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Entry 280 - 2BF + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x0b, 0x0b, 0x0b, 0x0b, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x07, 0x07, 0x02, 0x00, 0x00, 0x00, 0x00, + // Entry 2C0 - 2FF + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x06, 0x06, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Entry 300 - 33F + 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x0c, +} // Size: 799 bytes + +var ordinalInclusionMasks = []uint64{ // 100 elements + // Entry 0 - 1F + 0x0000002000010009, 0x00000018482000d3, 0x0000000042840195, 0x000000410a040581, + 0x00000041040c0081, 0x0000009840040041, 0x0000008400045001, 0x0000003850040001, + 0x0000003850060001, 0x0000003800049001, 0x0000000800052001, 0x0000000040660031, + 0x0000000041840331, 0x0000000100040f01, 0x00000001001c0001, 0x0000000040040001, + 0x0000000000045001, 0x0000000070040001, 0x0000000070040001, 0x0000000000049001, + 0x0000000080050001, 0x0000000040200011, 0x0000000040800111, 0x0000000100000501, + 0x0000000100080001, 0x0000000040000001, 0x0000000000005001, 0x0000000050000001, + 0x0000000050000001, 0x0000000000009001, 0x0000000000010001, 0x0000000040200011, + // Entry 20 - 3F + 0x0000000040800111, 0x0000000100000501, 0x0000000100080001, 0x0000000040000001, + 0x0000000000005001, 0x0000000050000001, 0x0000000050000001, 0x0000000000009001, + 0x0000000200050001, 0x0000000040200011, 0x0000000040800111, 0x0000000100000501, + 0x0000000100080001, 0x0000000040000001, 0x0000000000005001, 0x0000000050000001, + 0x0000000050000001, 0x0000000000009001, 0x0000000080010001, 0x0000000040200011, + 0x0000000040800111, 0x0000000100000501, 0x0000000100080001, 0x0000000040000001, + 0x0000000000005001, 0x0000000050000001, 0x0000000050000001, 0x0000000000009001, + 0x0000000200050001, 0x0000000040200011, 0x0000000040800111, 0x0000000100000501, + // Entry 40 - 5F + 0x0000000100080001, 0x0000000040000001, 0x0000000000005001, 0x0000000050000001, + 0x0000000050000001, 0x0000000000009001, 0x0000000080010001, 0x0000000040200011, + 0x0000000040800111, 0x0000000100000501, 0x0000000100080001, 0x0000000040000001, + 0x0000000000005001, 0x0000000050000001, 0x0000000050000001, 0x0000000000009001, + 0x0000000080070001, 0x0000000040200011, 0x0000000040800111, 0x0000000100000501, + 0x0000000100080001, 0x0000000040000001, 0x0000000000005001, 0x0000000050000001, + 0x0000000050000001, 0x0000000000009001, 0x0000000200010001, 0x0000000040200011, + 0x0000000040800111, 0x0000000100000501, 0x0000000100080001, 0x0000000040000001, + // Entry 60 - 7F + 0x0000000000005001, 0x0000000050000001, 0x0000000050000001, 0x0000000000009001, +} // Size: 824 bytes + +// Slots used for ordinal: 40 of 0xFF rules; 16 of 0xFF indexes; 40 of 64 sets + +var cardinalRules = []pluralCheck{ // 166 elements + 0: {cat: 0x2, setID: 0x3}, + 1: {cat: 0x22, setID: 0x1}, + 2: {cat: 0x2, setID: 0x4}, + 3: {cat: 0x2, setID: 0x4}, + 4: {cat: 0x7, setID: 0x1}, + 5: {cat: 0x62, setID: 0x3}, + 6: {cat: 0x22, setID: 0x4}, + 7: {cat: 0x7, setID: 0x3}, + 8: {cat: 0x42, setID: 0x1}, + 9: {cat: 0x22, setID: 0x4}, + 10: {cat: 0x22, setID: 0x4}, + 11: {cat: 0x22, setID: 0x5}, + 12: {cat: 0x22, setID: 0x1}, + 13: {cat: 0x22, setID: 0x1}, + 14: {cat: 0x7, setID: 0x4}, + 15: {cat: 0x92, setID: 0x3}, + 16: {cat: 0xf, setID: 0x6}, + 17: {cat: 0x1f, setID: 0x7}, + 18: {cat: 0x82, setID: 0x3}, + 19: {cat: 0x92, setID: 0x3}, + 20: {cat: 0xf, setID: 0x6}, + 21: {cat: 0x62, setID: 0x3}, + 22: {cat: 0x4a, setID: 0x6}, + 23: {cat: 0x7, setID: 0x8}, + 24: {cat: 0x62, setID: 0x3}, + 25: {cat: 0x1f, setID: 0x9}, + 26: {cat: 0x62, setID: 0x3}, + 27: {cat: 0x5f, setID: 0x9}, + 28: {cat: 0x72, setID: 0x3}, + 29: {cat: 0x29, setID: 0xa}, + 30: {cat: 0x29, setID: 0xb}, + 31: {cat: 0x4f, setID: 0xb}, + 32: {cat: 0x61, setID: 0x2}, + 33: {cat: 0x2f, setID: 0x6}, + 34: {cat: 0x3a, setID: 0x7}, + 35: {cat: 0x4f, setID: 0x6}, + 36: {cat: 0x5f, setID: 0x7}, + 37: {cat: 0x62, setID: 0x2}, + 38: {cat: 0x4f, setID: 0x6}, + 39: {cat: 0x72, setID: 0x2}, + 40: {cat: 0x21, setID: 0x3}, + 41: {cat: 0x7, setID: 0x4}, + 42: {cat: 0x32, setID: 0x3}, + 43: {cat: 0x21, setID: 0x3}, + 44: {cat: 0x22, setID: 0x1}, + 45: {cat: 0x22, setID: 0x1}, + 46: {cat: 0x23, setID: 0x2}, + 47: {cat: 0x2, setID: 0x3}, + 48: {cat: 0x22, setID: 0x1}, + 49: {cat: 0x24, setID: 0xc}, + 50: {cat: 0x7, setID: 0x1}, + 51: {cat: 0x62, setID: 0x3}, + 52: {cat: 0x74, setID: 0x3}, + 53: {cat: 0x24, setID: 0x3}, + 54: {cat: 0x2f, setID: 0xd}, + 55: {cat: 0x34, setID: 0x1}, + 56: {cat: 0xf, setID: 0x6}, + 57: {cat: 0x1f, setID: 0x7}, + 58: {cat: 0x62, setID: 0x3}, + 59: {cat: 0x4f, setID: 0x6}, + 60: {cat: 0x5a, setID: 0x7}, + 61: {cat: 0xf, setID: 0xe}, + 62: {cat: 0x1f, setID: 0xf}, + 63: {cat: 0x64, setID: 0x3}, + 64: {cat: 0x4f, setID: 0xe}, + 65: {cat: 0x5c, setID: 0xf}, + 66: {cat: 0x22, setID: 0x10}, + 67: {cat: 0x23, setID: 0x11}, + 68: {cat: 0x24, setID: 0x12}, + 69: {cat: 0xf, setID: 0x1}, + 70: {cat: 0x62, setID: 0x3}, + 71: {cat: 0xf, setID: 0x2}, + 72: {cat: 0x63, setID: 0x3}, + 73: {cat: 0xf, setID: 0x13}, + 74: {cat: 0x64, setID: 0x3}, + 75: {cat: 0x74, setID: 0x3}, + 76: {cat: 0xf, setID: 0x1}, + 77: {cat: 0x62, setID: 0x3}, + 78: {cat: 0x4a, setID: 0x1}, + 79: {cat: 0xf, setID: 0x2}, + 80: {cat: 0x63, setID: 0x3}, + 81: {cat: 0x4b, setID: 0x2}, + 82: {cat: 0xf, setID: 0x13}, + 83: {cat: 0x64, setID: 0x3}, + 84: {cat: 0x4c, setID: 0x13}, + 85: {cat: 0x7, setID: 0x1}, + 86: {cat: 0x62, setID: 0x3}, + 87: {cat: 0x7, setID: 0x2}, + 88: {cat: 0x63, setID: 0x3}, + 89: {cat: 0x2f, setID: 0xa}, + 90: {cat: 0x37, setID: 0x14}, + 91: {cat: 0x65, setID: 0x3}, + 92: {cat: 0x7, setID: 0x1}, + 93: {cat: 0x62, setID: 0x3}, + 94: {cat: 0x7, setID: 0x15}, + 95: {cat: 0x64, setID: 0x3}, + 96: {cat: 0x75, setID: 0x3}, + 97: {cat: 0x7, setID: 0x1}, + 98: {cat: 0x62, setID: 0x3}, + 99: {cat: 0xf, setID: 0xe}, + 100: {cat: 0x1f, setID: 0xf}, + 101: {cat: 0x64, setID: 0x3}, + 102: {cat: 0xf, setID: 0x16}, + 103: {cat: 0x17, setID: 0x1}, + 104: {cat: 0x65, setID: 0x3}, + 105: {cat: 0xf, setID: 0x17}, + 106: {cat: 0x65, setID: 0x3}, + 107: {cat: 0xf, setID: 0xf}, + 108: {cat: 0x65, setID: 0x3}, + 109: {cat: 0x2f, setID: 0x6}, + 110: {cat: 0x3a, setID: 0x7}, + 111: {cat: 0x2f, setID: 0xe}, + 112: {cat: 0x3c, setID: 0xf}, + 113: {cat: 0x2d, setID: 0xa}, + 114: {cat: 0x2d, setID: 0x17}, + 115: {cat: 0x2d, setID: 0x18}, + 116: {cat: 0x2f, setID: 0x6}, + 117: {cat: 0x3a, setID: 0xb}, + 118: {cat: 0x2f, setID: 0x19}, + 119: {cat: 0x3c, setID: 0xb}, + 120: {cat: 0x55, setID: 0x3}, + 121: {cat: 0x22, setID: 0x1}, + 122: {cat: 0x24, setID: 0x3}, + 123: {cat: 0x2c, setID: 0xc}, + 124: {cat: 0x2d, setID: 0xb}, + 125: {cat: 0xf, setID: 0x6}, + 126: {cat: 0x1f, setID: 0x7}, + 127: {cat: 0x62, setID: 0x3}, + 128: {cat: 0xf, setID: 0xe}, + 129: {cat: 0x1f, setID: 0xf}, + 130: {cat: 0x64, setID: 0x3}, + 131: {cat: 0xf, setID: 0xa}, + 132: {cat: 0x65, setID: 0x3}, + 133: {cat: 0xf, setID: 0x17}, + 134: {cat: 0x65, setID: 0x3}, + 135: {cat: 0xf, setID: 0x18}, + 136: {cat: 0x65, setID: 0x3}, + 137: {cat: 0x2f, setID: 0x6}, + 138: {cat: 0x3a, setID: 0x1a}, + 139: {cat: 0x2f, setID: 0x1b}, + 140: {cat: 0x3b, setID: 0x1c}, + 141: {cat: 0x2f, setID: 0x1d}, + 142: {cat: 0x3c, setID: 0x1e}, + 143: {cat: 0x37, setID: 0x3}, + 144: {cat: 0xa5, setID: 0x0}, + 145: {cat: 0x22, setID: 0x1}, + 146: {cat: 0x23, setID: 0x2}, + 147: {cat: 0x24, setID: 0x1f}, + 148: {cat: 0x25, setID: 0x20}, + 149: {cat: 0xf, setID: 0x6}, + 150: {cat: 0x62, setID: 0x3}, + 151: {cat: 0xf, setID: 0x1b}, + 152: {cat: 0x63, setID: 0x3}, + 153: {cat: 0xf, setID: 0x21}, + 154: {cat: 0x64, setID: 0x3}, + 155: {cat: 0x75, setID: 0x3}, + 156: {cat: 0x21, setID: 0x3}, + 157: {cat: 0x22, setID: 0x1}, + 158: {cat: 0x23, setID: 0x2}, + 159: {cat: 0x2c, setID: 0x22}, + 160: {cat: 0x2d, setID: 0x5}, + 161: {cat: 0x21, setID: 0x3}, + 162: {cat: 0x22, setID: 0x1}, + 163: {cat: 0x23, setID: 0x2}, + 164: {cat: 0x24, setID: 0x23}, + 165: {cat: 0x25, setID: 0x24}, +} // Size: 356 bytes + +var cardinalIndex = []uint8{ // 36 elements + 0x00, 0x00, 0x02, 0x03, 0x04, 0x06, 0x09, 0x0a, + 0x0c, 0x0d, 0x10, 0x14, 0x17, 0x1d, 0x28, 0x2b, + 0x2d, 0x2f, 0x32, 0x38, 0x42, 0x45, 0x4c, 0x55, + 0x5c, 0x61, 0x6d, 0x74, 0x79, 0x7d, 0x89, 0x91, + 0x95, 0x9c, 0xa1, 0xa6, +} // Size: 60 bytes + +var cardinalLangToIndex = []uint8{ // 775 elements + // Entry 0 - 3F + 0x00, 0x08, 0x08, 0x08, 0x00, 0x00, 0x06, 0x06, + 0x01, 0x01, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, + 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, + 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, + 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, + 0x01, 0x01, 0x08, 0x08, 0x04, 0x04, 0x08, 0x08, + 0x08, 0x08, 0x08, 0x00, 0x00, 0x1a, 0x1a, 0x08, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x06, 0x00, 0x00, + // Entry 40 - 7F + 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x1e, 0x1e, + 0x08, 0x08, 0x13, 0x13, 0x13, 0x13, 0x13, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x00, 0x00, 0x00, 0x08, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, + 0x18, 0x18, 0x00, 0x00, 0x22, 0x22, 0x09, 0x09, + 0x09, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x00, 0x00, 0x16, 0x16, 0x00, + 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Entry 80 - BF + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + // Entry C0 - FF + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x08, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, + // Entry 100 - 13F + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, + 0x08, 0x08, 0x00, 0x00, 0x01, 0x01, 0x01, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x04, 0x04, 0x0c, 0x0c, + 0x08, 0x08, 0x08, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + // Entry 140 - 17F + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x08, 0x08, 0x04, 0x04, 0x1f, 0x1f, + 0x14, 0x14, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, + 0x01, 0x01, 0x06, 0x00, 0x00, 0x20, 0x20, 0x08, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x17, 0x17, 0x01, + 0x01, 0x13, 0x13, 0x13, 0x16, 0x16, 0x08, 0x08, + 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Entry 180 - 1BF + 0x00, 0x04, 0x0a, 0x0a, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x10, 0x17, 0x00, 0x00, 0x00, 0x08, 0x08, + 0x04, 0x08, 0x08, 0x00, 0x00, 0x08, 0x08, 0x02, + 0x02, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x08, 0x08, + 0x08, 0x08, 0x08, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x08, + 0x08, 0x08, 0x00, 0x00, 0x0f, 0x0f, 0x08, 0x10, + // Entry 1C0 - 1FF + 0x10, 0x08, 0x08, 0x0e, 0x0e, 0x08, 0x08, 0x08, + 0x08, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x1b, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x0d, 0x08, + 0x08, 0x08, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, + 0x00, 0x00, 0x08, 0x08, 0x0b, 0x0b, 0x08, 0x08, + 0x08, 0x08, 0x12, 0x01, 0x01, 0x00, 0x00, 0x00, + 0x00, 0x1c, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, + // Entry 200 - 23F + 0x00, 0x08, 0x10, 0x10, 0x08, 0x08, 0x08, 0x08, + 0x08, 0x00, 0x00, 0x00, 0x08, 0x08, 0x08, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x00, + 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x08, + 0x06, 0x00, 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x08, 0x19, 0x19, 0x0d, 0x0d, + 0x08, 0x08, 0x03, 0x04, 0x03, 0x04, 0x04, 0x04, + // Entry 240 - 27F + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x00, + 0x00, 0x00, 0x00, 0x08, 0x08, 0x00, 0x00, 0x12, + 0x12, 0x12, 0x08, 0x08, 0x1d, 0x1d, 0x1d, 0x1d, + 0x1d, 0x1d, 0x1d, 0x00, 0x00, 0x08, 0x08, 0x00, + 0x00, 0x08, 0x08, 0x00, 0x00, 0x08, 0x08, 0x08, + 0x10, 0x10, 0x10, 0x10, 0x08, 0x08, 0x00, 0x00, + 0x00, 0x00, 0x13, 0x11, 0x11, 0x11, 0x11, 0x11, + 0x05, 0x05, 0x18, 0x18, 0x15, 0x15, 0x10, 0x10, + // Entry 280 - 2BF + 0x10, 0x10, 0x10, 0x10, 0x08, 0x08, 0x08, 0x08, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x13, + 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, + 0x13, 0x13, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, + 0x08, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x06, + 0x08, 0x08, 0x08, 0x0c, 0x08, 0x00, 0x00, 0x08, + // Entry 2C0 - 2FF + 0x08, 0x08, 0x08, 0x00, 0x00, 0x00, 0x00, 0x07, + 0x07, 0x08, 0x08, 0x1d, 0x1d, 0x04, 0x04, 0x04, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, + 0x08, 0x08, 0x08, 0x06, 0x08, 0x08, 0x00, 0x00, + 0x08, 0x08, 0x08, 0x00, 0x00, 0x04, 0x04, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Entry 300 - 33F + 0x00, 0x00, 0x00, 0x01, 0x01, 0x04, 0x04, +} // Size: 799 bytes + +var cardinalInclusionMasks = []uint64{ // 100 elements + // Entry 0 - 1F + 0x0000000200500419, 0x0000000000512153, 0x000000000a327105, 0x0000000ca23c7101, + 0x00000004a23c7201, 0x0000000482943001, 0x0000001482943201, 0x0000000502943001, + 0x0000000502943001, 0x0000000522943201, 0x0000000540543401, 0x00000000454128e1, + 0x000000005b02e821, 0x000000006304e821, 0x000000006304ea21, 0x0000000042842821, + 0x0000000042842a21, 0x0000000042842821, 0x0000000042842821, 0x0000000062842a21, + 0x0000000200400421, 0x0000000000400061, 0x000000000a004021, 0x0000000022004021, + 0x0000000022004221, 0x0000000002800021, 0x0000000002800221, 0x0000000002800021, + 0x0000000002800021, 0x0000000022800221, 0x0000000000400421, 0x0000000000400061, + // Entry 20 - 3F + 0x000000000a004021, 0x0000000022004021, 0x0000000022004221, 0x0000000002800021, + 0x0000000002800221, 0x0000000002800021, 0x0000000002800021, 0x0000000022800221, + 0x0000000200400421, 0x0000000000400061, 0x000000000a004021, 0x0000000022004021, + 0x0000000022004221, 0x0000000002800021, 0x0000000002800221, 0x0000000002800021, + 0x0000000002800021, 0x0000000022800221, 0x0000000000400421, 0x0000000000400061, + 0x000000000a004021, 0x0000000022004021, 0x0000000022004221, 0x0000000002800021, + 0x0000000002800221, 0x0000000002800021, 0x0000000002800021, 0x0000000022800221, + 0x0000000200400421, 0x0000000000400061, 0x000000000a004021, 0x0000000022004021, + // Entry 40 - 5F + 0x0000000022004221, 0x0000000002800021, 0x0000000002800221, 0x0000000002800021, + 0x0000000002800021, 0x0000000022800221, 0x0000000040400421, 0x0000000044400061, + 0x000000005a004021, 0x0000000062004021, 0x0000000062004221, 0x0000000042800021, + 0x0000000042800221, 0x0000000042800021, 0x0000000042800021, 0x0000000062800221, + 0x0000000200400421, 0x0000000000400061, 0x000000000a004021, 0x0000000022004021, + 0x0000000022004221, 0x0000000002800021, 0x0000000002800221, 0x0000000002800021, + 0x0000000002800021, 0x0000000022800221, 0x0000000040400421, 0x0000000044400061, + 0x000000005a004021, 0x0000000062004021, 0x0000000062004221, 0x0000000042800021, + // Entry 60 - 7F + 0x0000000042800221, 0x0000000042800021, 0x0000000042800021, 0x0000000062800221, +} // Size: 824 bytes + +// Slots used for cardinal: A6 of 0xFF rules; 24 of 0xFF indexes; 37 of 64 sets + +// Total table size 3860 bytes (3KiB); checksum: AAFBF21 diff --git a/vendor/golang.org/x/text/internal/catmsg/catmsg.go b/vendor/golang.org/x/text/internal/catmsg/catmsg.go new file mode 100644 index 00000000..1b257a7b --- /dev/null +++ b/vendor/golang.org/x/text/internal/catmsg/catmsg.go @@ -0,0 +1,417 @@ +// Copyright 2017 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 catmsg contains support types for package x/text/message/catalog. +// +// This package contains the low-level implementations of Message used by the +// catalog package and provides primitives for other packages to implement their +// own. For instance, the plural package provides functionality for selecting +// translation strings based on the plural category of substitution arguments. +// +// # Encoding and Decoding +// +// Catalogs store Messages encoded as a single string. Compiling a message into +// a string both results in compacter representation and speeds up evaluation. +// +// A Message must implement a Compile method to convert its arbitrary +// representation to a string. The Compile method takes an Encoder which +// facilitates serializing the message. Encoders also provide more context of +// the messages's creation (such as for which language the message is intended), +// which may not be known at the time of the creation of the message. +// +// Each message type must also have an accompanying decoder registered to decode +// the message. This decoder takes a Decoder argument which provides the +// counterparts for the decoding. +// +// # Renderers +// +// A Decoder must be initialized with a Renderer implementation. These +// implementations must be provided by packages that use Catalogs, typically +// formatting packages such as x/text/message. A typical user will not need to +// worry about this type; it is only relevant to packages that do string +// formatting and want to use the catalog package to handle localized strings. +// +// A package that uses catalogs for selecting strings receives selection results +// as sequence of substrings passed to the Renderer. The following snippet shows +// how to express the above example using the message package. +// +// message.Set(language.English, "You are %d minute(s) late.", +// catalog.Var("minutes", plural.Select(1, "one", "minute")), +// catalog.String("You are %[1]d ${minutes} late.")) +// +// p := message.NewPrinter(language.English) +// p.Printf("You are %d minute(s) late.", 5) // always 5 minutes late. +// +// To evaluate the Printf, package message wraps the arguments in a Renderer +// that is passed to the catalog for message decoding. The call sequence that +// results from evaluating the above message, assuming the person is rather +// tardy, is: +// +// Render("You are %[1]d ") +// Arg(1) +// Render("minutes") +// Render(" late.") +// +// The calls to Arg is caused by the plural.Select execution, which evaluates +// the argument to determine whether the singular or plural message form should +// be selected. The calls to Render reports the partial results to the message +// package for further evaluation. +package catmsg + +import ( + "errors" + "fmt" + "strconv" + "strings" + "sync" + + "golang.org/x/text/language" +) + +// A Handle refers to a registered message type. +type Handle int + +// A Handler decodes and evaluates data compiled by a Message and sends the +// result to the Decoder. The output may depend on the value of the substitution +// arguments, accessible by the Decoder's Arg method. The Handler returns false +// if there is no translation for the given substitution arguments. +type Handler func(d *Decoder) bool + +// Register records the existence of a message type and returns a Handle that +// can be used in the Encoder's EncodeMessageType method to create such +// messages. The prefix of the name should be the package path followed by +// an optional disambiguating string. +// Register will panic if a handle for the same name was already registered. +func Register(name string, handler Handler) Handle { + mutex.Lock() + defer mutex.Unlock() + + if _, ok := names[name]; ok { + panic(fmt.Errorf("catmsg: handler for %q already exists", name)) + } + h := Handle(len(handlers)) + names[name] = h + handlers = append(handlers, handler) + return h +} + +// These handlers require fixed positions in the handlers slice. +const ( + msgVars Handle = iota + msgFirst + msgRaw + msgString + msgAffix + // Leave some arbitrary room for future expansion: 20 should suffice. + numInternal = 20 +) + +const prefix = "golang.org/x/text/internal/catmsg." + +var ( + // TODO: find a more stable way to link handles to message types. + mutex sync.Mutex + names = map[string]Handle{ + prefix + "Vars": msgVars, + prefix + "First": msgFirst, + prefix + "Raw": msgRaw, + prefix + "String": msgString, + prefix + "Affix": msgAffix, + } + handlers = make([]Handler, numInternal) +) + +func init() { + // This handler is a message type wrapper that initializes a decoder + // with a variable block. This message type, if present, is always at the + // start of an encoded message. + handlers[msgVars] = func(d *Decoder) bool { + blockSize := int(d.DecodeUint()) + d.vars = d.data[:blockSize] + d.data = d.data[blockSize:] + return d.executeMessage() + } + + // First takes the first message in a sequence that results in a match for + // the given substitution arguments. + handlers[msgFirst] = func(d *Decoder) bool { + for !d.Done() { + if d.ExecuteMessage() { + return true + } + } + return false + } + + handlers[msgRaw] = func(d *Decoder) bool { + d.Render(d.data) + return true + } + + // A String message alternates between a string constant and a variable + // substitution. + handlers[msgString] = func(d *Decoder) bool { + for !d.Done() { + if str := d.DecodeString(); str != "" { + d.Render(str) + } + if d.Done() { + break + } + d.ExecuteSubstitution() + } + return true + } + + handlers[msgAffix] = func(d *Decoder) bool { + // TODO: use an alternative method for common cases. + prefix := d.DecodeString() + suffix := d.DecodeString() + if prefix != "" { + d.Render(prefix) + } + ret := d.ExecuteMessage() + if suffix != "" { + d.Render(suffix) + } + return ret + } +} + +var ( + // ErrIncomplete indicates a compiled message does not define translations + // for all possible argument values. If this message is returned, evaluating + // a message may result in the ErrNoMatch error. + ErrIncomplete = errors.New("catmsg: incomplete message; may not give result for all inputs") + + // ErrNoMatch indicates no translation message matched the given input + // parameters when evaluating a message. + ErrNoMatch = errors.New("catmsg: no translation for inputs") +) + +// A Message holds a collection of translations for the same phrase that may +// vary based on the values of substitution arguments. +type Message interface { + // Compile encodes the format string(s) of the message as a string for later + // evaluation. + // + // The first call Compile makes on the encoder must be EncodeMessageType. + // The handle passed to this call may either be a handle returned by + // Register to encode a single custom message, or HandleFirst followed by + // a sequence of calls to EncodeMessage. + // + // Compile must return ErrIncomplete if it is possible for evaluation to + // not match any translation for a given set of formatting parameters. + // For example, selecting a translation based on plural form may not yield + // a match if the form "Other" is not one of the selectors. + // + // Compile may return any other application-specific error. For backwards + // compatibility with package like fmt, which often do not do sanity + // checking of format strings ahead of time, Compile should still make an + // effort to have some sensible fallback in case of an error. + Compile(e *Encoder) error +} + +// Compile converts a Message to a data string that can be stored in a Catalog. +// The resulting string can subsequently be decoded by passing to the Execute +// method of a Decoder. +func Compile(tag language.Tag, macros Dictionary, m Message) (data string, err error) { + // TODO: pass macros so they can be used for validation. + v := &Encoder{inBody: true} // encoder for variables + v.root = v + e := &Encoder{root: v, parent: v, tag: tag} // encoder for messages + err = m.Compile(e) + // This package serves te message package, which in turn is meant to be a + // drop-in replacement for fmt. With the fmt package, format strings are + // evaluated lazily and errors are handled by substituting strings in the + // result, rather then returning an error. Dealing with multiple languages + // makes it more important to check errors ahead of time. We chose to be + // consistent and compatible and allow graceful degradation in case of + // errors. + buf := e.buf[stripPrefix(e.buf):] + if len(v.buf) > 0 { + // Prepend variable block. + b := make([]byte, 1+maxVarintBytes+len(v.buf)+len(buf)) + b[0] = byte(msgVars) + b = b[:1+encodeUint(b[1:], uint64(len(v.buf)))] + b = append(b, v.buf...) + b = append(b, buf...) + buf = b + } + if err == nil { + err = v.err + } + return string(buf), err +} + +// FirstOf is a message type that prints the first message in the sequence that +// resolves to a match for the given substitution arguments. +type FirstOf []Message + +// Compile implements Message. +func (s FirstOf) Compile(e *Encoder) error { + e.EncodeMessageType(msgFirst) + err := ErrIncomplete + for i, m := range s { + if err == nil { + return fmt.Errorf("catalog: message argument %d is complete and blocks subsequent messages", i-1) + } + err = e.EncodeMessage(m) + } + return err +} + +// Var defines a message that can be substituted for a placeholder of the same +// name. If an expression does not result in a string after evaluation, Name is +// used as the substitution. For example: +// +// Var{ +// Name: "minutes", +// Message: plural.Select(1, "one", "minute"), +// } +// +// will resolve to minute for singular and minutes for plural forms. +type Var struct { + Name string + Message Message +} + +var errIsVar = errors.New("catmsg: variable used as message") + +// Compile implements Message. +// +// Note that this method merely registers a variable; it does not create an +// encoded message. +func (v *Var) Compile(e *Encoder) error { + if err := e.addVar(v.Name, v.Message); err != nil { + return err + } + // Using a Var by itself is an error. If it is in a sequence followed by + // other messages referring to it, this error will be ignored. + return errIsVar +} + +// Raw is a message consisting of a single format string that is passed as is +// to the Renderer. +// +// Note that a Renderer may still do its own variable substitution. +type Raw string + +// Compile implements Message. +func (r Raw) Compile(e *Encoder) (err error) { + e.EncodeMessageType(msgRaw) + // Special case: raw strings don't have a size encoding and so don't use + // EncodeString. + e.buf = append(e.buf, r...) + return nil +} + +// String is a message consisting of a single format string which contains +// placeholders that may be substituted with variables. +// +// Variable substitutions are marked with placeholders and a variable name of +// the form ${name}. Any other substitutions such as Go templates or +// printf-style substitutions are left to be done by the Renderer. +// +// When evaluation a string interpolation, a Renderer will receive separate +// calls for each placeholder and interstitial string. For example, for the +// message: "%[1]v ${invites} %[2]v to ${their} party." The sequence of calls +// is: +// +// d.Render("%[1]v ") +// d.Arg(1) +// d.Render(resultOfInvites) +// d.Render(" %[2]v to ") +// d.Arg(2) +// d.Render(resultOfTheir) +// d.Render(" party.") +// +// where the messages for "invites" and "their" both use a plural.Select +// referring to the first argument. +// +// Strings may also invoke macros. Macros are essentially variables that can be +// reused. Macros may, for instance, be used to make selections between +// different conjugations of a verb. See the catalog package description for an +// overview of macros. +type String string + +// Compile implements Message. It parses the placeholder formats and returns +// any error. +func (s String) Compile(e *Encoder) (err error) { + msg := string(s) + const subStart = "${" + hasHeader := false + p := 0 + b := []byte{} + for { + i := strings.Index(msg[p:], subStart) + if i == -1 { + break + } + b = append(b, msg[p:p+i]...) + p += i + len(subStart) + if i = strings.IndexByte(msg[p:], '}'); i == -1 { + b = append(b, "$!(MISSINGBRACE)"...) + err = fmt.Errorf("catmsg: missing '}'") + p = len(msg) + break + } + name := strings.TrimSpace(msg[p : p+i]) + if q := strings.IndexByte(name, '('); q == -1 { + if !hasHeader { + hasHeader = true + e.EncodeMessageType(msgString) + } + e.EncodeString(string(b)) + e.EncodeSubstitution(name) + b = b[:0] + } else if j := strings.IndexByte(name[q:], ')'); j == -1 { + // TODO: what should the error be? + b = append(b, "$!(MISSINGPAREN)"...) + err = fmt.Errorf("catmsg: missing ')'") + } else if x, sErr := strconv.ParseUint(strings.TrimSpace(name[q+1:q+j]), 10, 32); sErr != nil { + // TODO: handle more than one argument + b = append(b, "$!(BADNUM)"...) + err = fmt.Errorf("catmsg: invalid number %q", strings.TrimSpace(name[q+1:q+j])) + } else { + if !hasHeader { + hasHeader = true + e.EncodeMessageType(msgString) + } + e.EncodeString(string(b)) + e.EncodeSubstitution(name[:q], int(x)) + b = b[:0] + } + p += i + 1 + } + b = append(b, msg[p:]...) + if !hasHeader { + // Simplify string to a raw string. + Raw(string(b)).Compile(e) + } else if len(b) > 0 { + e.EncodeString(string(b)) + } + return err +} + +// Affix is a message that adds a prefix and suffix to another message. +// This is mostly used add back whitespace to a translation that was stripped +// before sending it out. +type Affix struct { + Message Message + Prefix string + Suffix string +} + +// Compile implements Message. +func (a Affix) Compile(e *Encoder) (err error) { + // TODO: consider adding a special message type that just adds a single + // return. This is probably common enough to handle the majority of cases. + // Get some stats first, though. + e.EncodeMessageType(msgAffix) + e.EncodeString(a.Prefix) + e.EncodeString(a.Suffix) + e.EncodeMessage(a.Message) + return nil +} diff --git a/vendor/golang.org/x/text/internal/catmsg/codec.go b/vendor/golang.org/x/text/internal/catmsg/codec.go new file mode 100644 index 00000000..49c9fc97 --- /dev/null +++ b/vendor/golang.org/x/text/internal/catmsg/codec.go @@ -0,0 +1,407 @@ +// Copyright 2017 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 catmsg + +import ( + "errors" + "fmt" + + "golang.org/x/text/language" +) + +// A Renderer renders a Message. +type Renderer interface { + // Render renders the given string. The given string may be interpreted as a + // format string, such as the one used by the fmt package or a template. + Render(s string) + + // Arg returns the i-th argument passed to format a message. This method + // should return nil if there is no such argument. Messages need access to + // arguments to allow selecting a message based on linguistic features of + // those arguments. + Arg(i int) interface{} +} + +// A Dictionary specifies a source of messages, including variables or macros. +type Dictionary interface { + // Lookup returns the message for the given key. It returns false for ok if + // such a message could not be found. + Lookup(key string) (data string, ok bool) + + // TODO: consider returning an interface, instead of a string. This will + // allow implementations to do their own message type decoding. +} + +// An Encoder serializes a Message to a string. +type Encoder struct { + // The root encoder is used for storing encoded variables. + root *Encoder + // The parent encoder provides the surrounding scopes for resolving variable + // names. + parent *Encoder + + tag language.Tag + + // buf holds the encoded message so far. After a message completes encoding, + // the contents of buf, prefixed by the encoded length, are flushed to the + // parent buffer. + buf []byte + + // vars is the lookup table of variables in the current scope. + vars []keyVal + + err error + inBody bool // if false next call must be EncodeMessageType +} + +type keyVal struct { + key string + offset int +} + +// Language reports the language for which the encoded message will be stored +// in the Catalog. +func (e *Encoder) Language() language.Tag { return e.tag } + +func (e *Encoder) setError(err error) { + if e.root.err == nil { + e.root.err = err + } +} + +// EncodeUint encodes x. +func (e *Encoder) EncodeUint(x uint64) { + e.checkInBody() + var buf [maxVarintBytes]byte + n := encodeUint(buf[:], x) + e.buf = append(e.buf, buf[:n]...) +} + +// EncodeString encodes s. +func (e *Encoder) EncodeString(s string) { + e.checkInBody() + e.EncodeUint(uint64(len(s))) + e.buf = append(e.buf, s...) +} + +// EncodeMessageType marks the current message to be of type h. +// +// It must be the first call of a Message's Compile method. +func (e *Encoder) EncodeMessageType(h Handle) { + if e.inBody { + panic("catmsg: EncodeMessageType not the first method called") + } + e.inBody = true + e.EncodeUint(uint64(h)) +} + +// EncodeMessage serializes the given message inline at the current position. +func (e *Encoder) EncodeMessage(m Message) error { + e = &Encoder{root: e.root, parent: e, tag: e.tag} + err := m.Compile(e) + if _, ok := m.(*Var); !ok { + e.flushTo(e.parent) + } + return err +} + +func (e *Encoder) checkInBody() { + if !e.inBody { + panic("catmsg: expected prior call to EncodeMessageType") + } +} + +// stripPrefix indicates the number of prefix bytes that must be stripped to +// turn a single-element sequence into a message that is just this single member +// without its size prefix. If the message can be stripped, b[1:n] contains the +// size prefix. +func stripPrefix(b []byte) (n int) { + if len(b) > 0 && Handle(b[0]) == msgFirst { + x, n, _ := decodeUint(b[1:]) + if 1+n+int(x) == len(b) { + return 1 + n + } + } + return 0 +} + +func (e *Encoder) flushTo(dst *Encoder) { + data := e.buf + p := stripPrefix(data) + if p > 0 { + data = data[1:] + } else { + // Prefix the size. + dst.EncodeUint(uint64(len(data))) + } + dst.buf = append(dst.buf, data...) +} + +func (e *Encoder) addVar(key string, m Message) error { + for _, v := range e.parent.vars { + if v.key == key { + err := fmt.Errorf("catmsg: duplicate variable %q", key) + e.setError(err) + return err + } + } + scope := e.parent + // If a variable message is Incomplete, and does not evaluate to a message + // during execution, we fall back to the variable name. We encode this by + // appending the variable name if the message reports it's incomplete. + + err := m.Compile(e) + if err != ErrIncomplete { + e.setError(err) + } + switch { + case len(e.buf) == 1 && Handle(e.buf[0]) == msgFirst: // empty sequence + e.buf = e.buf[:0] + e.inBody = false + fallthrough + case len(e.buf) == 0: + // Empty message. + if err := String(key).Compile(e); err != nil { + e.setError(err) + } + case err == ErrIncomplete: + if Handle(e.buf[0]) != msgFirst { + seq := &Encoder{root: e.root, parent: e} + seq.EncodeMessageType(msgFirst) + e.flushTo(seq) + e = seq + } + // e contains a sequence; append the fallback string. + e.EncodeMessage(String(key)) + } + + // Flush result to variable heap. + offset := len(e.root.buf) + e.flushTo(e.root) + e.buf = e.buf[:0] + + // Record variable offset in current scope. + scope.vars = append(scope.vars, keyVal{key: key, offset: offset}) + return err +} + +const ( + substituteVar = iota + substituteMacro + substituteError +) + +// EncodeSubstitution inserts a resolved reference to a variable or macro. +// +// This call must be matched with a call to ExecuteSubstitution at decoding +// time. +func (e *Encoder) EncodeSubstitution(name string, arguments ...int) { + if arity := len(arguments); arity > 0 { + // TODO: also resolve macros. + e.EncodeUint(substituteMacro) + e.EncodeString(name) + for _, a := range arguments { + e.EncodeUint(uint64(a)) + } + return + } + for scope := e; scope != nil; scope = scope.parent { + for _, v := range scope.vars { + if v.key != name { + continue + } + e.EncodeUint(substituteVar) // TODO: support arity > 0 + e.EncodeUint(uint64(v.offset)) + return + } + } + // TODO: refer to dictionary-wide scoped variables. + e.EncodeUint(substituteError) + e.EncodeString(name) + e.setError(fmt.Errorf("catmsg: unknown var %q", name)) +} + +// A Decoder deserializes and evaluates messages that are encoded by an encoder. +type Decoder struct { + tag language.Tag + dst Renderer + macros Dictionary + + err error + vars string + data string + + macroArg int // TODO: allow more than one argument +} + +// NewDecoder returns a new Decoder. +// +// Decoders are designed to be reused for multiple invocations of Execute. +// Only one goroutine may call Execute concurrently. +func NewDecoder(tag language.Tag, r Renderer, macros Dictionary) *Decoder { + return &Decoder{ + tag: tag, + dst: r, + macros: macros, + } +} + +func (d *Decoder) setError(err error) { + if d.err == nil { + d.err = err + } +} + +// Language returns the language in which the message is being rendered. +// +// The destination language may be a child language of the language used for +// encoding. For instance, a decoding language of "pt-PT"" is consistent with an +// encoding language of "pt". +func (d *Decoder) Language() language.Tag { return d.tag } + +// Done reports whether there are more bytes to process in this message. +func (d *Decoder) Done() bool { return len(d.data) == 0 } + +// Render implements Renderer. +func (d *Decoder) Render(s string) { d.dst.Render(s) } + +// Arg implements Renderer. +// +// During evaluation of macros, the argument positions may be mapped to +// arguments that differ from the original call. +func (d *Decoder) Arg(i int) interface{} { + if d.macroArg != 0 { + if i != 1 { + panic("catmsg: only macros with single argument supported") + } + i = d.macroArg + } + return d.dst.Arg(i) +} + +// DecodeUint decodes a number that was encoded with EncodeUint and advances the +// position. +func (d *Decoder) DecodeUint() uint64 { + x, n, err := decodeUintString(d.data) + d.data = d.data[n:] + if err != nil { + d.setError(err) + } + return x +} + +// DecodeString decodes a string that was encoded with EncodeString and advances +// the position. +func (d *Decoder) DecodeString() string { + size := d.DecodeUint() + s := d.data[:size] + d.data = d.data[size:] + return s +} + +// SkipMessage skips the message at the current location and advances the +// position. +func (d *Decoder) SkipMessage() { + n := int(d.DecodeUint()) + d.data = d.data[n:] +} + +// Execute decodes and evaluates msg. +// +// Only one goroutine may call execute. +func (d *Decoder) Execute(msg string) error { + d.err = nil + if !d.execute(msg) { + return ErrNoMatch + } + return d.err +} + +func (d *Decoder) execute(msg string) bool { + saved := d.data + d.data = msg + ok := d.executeMessage() + d.data = saved + return ok +} + +// executeMessageFromData is like execute, but also decodes a leading message +// size and clips the given string accordingly. +// +// It reports the number of bytes consumed and whether a message was selected. +func (d *Decoder) executeMessageFromData(s string) (n int, ok bool) { + saved := d.data + d.data = s + size := int(d.DecodeUint()) + n = len(s) - len(d.data) + // Sanitize the setting. This allows skipping a size argument for + // RawString and method Done. + d.data = d.data[:size] + ok = d.executeMessage() + n += size - len(d.data) + d.data = saved + return n, ok +} + +var errUnknownHandler = errors.New("catmsg: string contains unsupported handler") + +// executeMessage reads the handle id, initializes the decoder and executes the +// message. It is assumed that all of d.data[d.p:] is the single message. +func (d *Decoder) executeMessage() bool { + if d.Done() { + // We interpret no data as a valid empty message. + return true + } + handle := d.DecodeUint() + + var fn Handler + mutex.Lock() + if int(handle) < len(handlers) { + fn = handlers[handle] + } + mutex.Unlock() + if fn == nil { + d.setError(errUnknownHandler) + d.execute(fmt.Sprintf("\x02$!(UNKNOWNMSGHANDLER=%#x)", handle)) + return true + } + return fn(d) +} + +// ExecuteMessage decodes and executes the message at the current position. +func (d *Decoder) ExecuteMessage() bool { + n, ok := d.executeMessageFromData(d.data) + d.data = d.data[n:] + return ok +} + +// ExecuteSubstitution executes the message corresponding to the substitution +// as encoded by EncodeSubstitution. +func (d *Decoder) ExecuteSubstitution() { + switch x := d.DecodeUint(); x { + case substituteVar: + offset := d.DecodeUint() + d.executeMessageFromData(d.vars[offset:]) + case substituteMacro: + name := d.DecodeString() + data, ok := d.macros.Lookup(name) + old := d.macroArg + // TODO: support macros of arity other than 1. + d.macroArg = int(d.DecodeUint()) + switch { + case !ok: + // TODO: detect this at creation time. + d.setError(fmt.Errorf("catmsg: undefined macro %q", name)) + fallthrough + case !d.execute(data): + d.dst.Render(name) // fall back to macro name. + } + d.macroArg = old + case substituteError: + d.dst.Render(d.DecodeString()) + default: + panic("catmsg: unreachable") + } +} diff --git a/vendor/golang.org/x/text/internal/catmsg/varint.go b/vendor/golang.org/x/text/internal/catmsg/varint.go new file mode 100644 index 00000000..a2cee2cf --- /dev/null +++ b/vendor/golang.org/x/text/internal/catmsg/varint.go @@ -0,0 +1,62 @@ +// Copyright 2017 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 catmsg + +// This file implements varint encoding analogous to the one in encoding/binary. +// We need a string version of this function, so we add that here and then add +// the rest for consistency. + +import "errors" + +var ( + errIllegalVarint = errors.New("catmsg: illegal varint") + errVarintTooLarge = errors.New("catmsg: varint too large for uint64") +) + +const maxVarintBytes = 10 // maximum length of a varint + +// encodeUint encodes x as a variable-sized integer into buf and returns the +// number of bytes written. buf must be at least maxVarintBytes long +func encodeUint(buf []byte, x uint64) (n int) { + for ; x > 127; n++ { + buf[n] = 0x80 | uint8(x&0x7F) + x >>= 7 + } + buf[n] = uint8(x) + n++ + return n +} + +func decodeUintString(s string) (x uint64, size int, err error) { + i := 0 + for shift := uint(0); shift < 64; shift += 7 { + if i >= len(s) { + return 0, i, errIllegalVarint + } + b := uint64(s[i]) + i++ + x |= (b & 0x7F) << shift + if b&0x80 == 0 { + return x, i, nil + } + } + return 0, i, errVarintTooLarge +} + +func decodeUint(b []byte) (x uint64, size int, err error) { + i := 0 + for shift := uint(0); shift < 64; shift += 7 { + if i >= len(b) { + return 0, i, errIllegalVarint + } + c := uint64(b[i]) + i++ + x |= (c & 0x7F) << shift + if c&0x80 == 0 { + return x, i, nil + } + } + return 0, i, errVarintTooLarge +} diff --git a/vendor/golang.org/x/text/internal/format/format.go b/vendor/golang.org/x/text/internal/format/format.go new file mode 100644 index 00000000..ee1c57a3 --- /dev/null +++ b/vendor/golang.org/x/text/internal/format/format.go @@ -0,0 +1,41 @@ +// Copyright 2015 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 format contains types for defining language-specific formatting of +// values. +// +// This package is internal now, but will eventually be exposed after the API +// settles. +package format // import "golang.org/x/text/internal/format" + +import ( + "fmt" + + "golang.org/x/text/language" +) + +// State represents the printer state passed to custom formatters. It provides +// access to the fmt.State interface and the sentence and language-related +// context. +type State interface { + fmt.State + + // Language reports the requested language in which to render a message. + Language() language.Tag + + // TODO: consider this and removing rune from the Format method in the + // Formatter interface. + // + // Verb returns the format variant to render, analogous to the types used + // in fmt. Use 'v' for the default or only variant. + // Verb() rune + + // TODO: more info: + // - sentence context such as linguistic features passed by the translator. +} + +// Formatter is analogous to fmt.Formatter. +type Formatter interface { + Format(state State, verb rune) +} diff --git a/vendor/golang.org/x/text/internal/format/parser.go b/vendor/golang.org/x/text/internal/format/parser.go new file mode 100644 index 00000000..855aed71 --- /dev/null +++ b/vendor/golang.org/x/text/internal/format/parser.go @@ -0,0 +1,358 @@ +// Copyright 2017 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 format + +import ( + "reflect" + "unicode/utf8" +) + +// A Parser parses a format string. The result from the parse are set in the +// struct fields. +type Parser struct { + Verb rune + + WidthPresent bool + PrecPresent bool + Minus bool + Plus bool + Sharp bool + Space bool + Zero bool + + // For the formats %+v %#v, we set the plusV/sharpV flags + // and clear the plus/sharp flags since %+v and %#v are in effect + // different, flagless formats set at the top level. + PlusV bool + SharpV bool + + HasIndex bool + + Width int + Prec int // precision + + // retain arguments across calls. + Args []interface{} + // retain current argument number across calls + ArgNum int + + // reordered records whether the format string used argument reordering. + Reordered bool + // goodArgNum records whether the most recent reordering directive was valid. + goodArgNum bool + + // position info + format string + startPos int + endPos int + Status Status +} + +// Reset initializes a parser to scan format strings for the given args. +func (p *Parser) Reset(args []interface{}) { + p.Args = args + p.ArgNum = 0 + p.startPos = 0 + p.Reordered = false +} + +// Text returns the part of the format string that was parsed by the last call +// to Scan. It returns the original substitution clause if the current scan +// parsed a substitution. +func (p *Parser) Text() string { return p.format[p.startPos:p.endPos] } + +// SetFormat sets a new format string to parse. It does not reset the argument +// count. +func (p *Parser) SetFormat(format string) { + p.format = format + p.startPos = 0 + p.endPos = 0 +} + +// Status indicates the result type of a call to Scan. +type Status int + +const ( + StatusText Status = iota + StatusSubstitution + StatusBadWidthSubstitution + StatusBadPrecSubstitution + StatusNoVerb + StatusBadArgNum + StatusMissingArg +) + +// ClearFlags reset the parser to default behavior. +func (p *Parser) ClearFlags() { + p.WidthPresent = false + p.PrecPresent = false + p.Minus = false + p.Plus = false + p.Sharp = false + p.Space = false + p.Zero = false + + p.PlusV = false + p.SharpV = false + + p.HasIndex = false +} + +// Scan scans the next part of the format string and sets the status to +// indicate whether it scanned a string literal, substitution or error. +func (p *Parser) Scan() bool { + p.Status = StatusText + format := p.format + end := len(format) + if p.endPos >= end { + return false + } + afterIndex := false // previous item in format was an index like [3]. + + p.startPos = p.endPos + p.goodArgNum = true + i := p.startPos + for i < end && format[i] != '%' { + i++ + } + if i > p.startPos { + p.endPos = i + return true + } + // Process one verb + i++ + + p.Status = StatusSubstitution + + // Do we have flags? + p.ClearFlags() + +simpleFormat: + for ; i < end; i++ { + c := p.format[i] + switch c { + case '#': + p.Sharp = true + case '0': + p.Zero = !p.Minus // Only allow zero padding to the left. + case '+': + p.Plus = true + case '-': + p.Minus = true + p.Zero = false // Do not pad with zeros to the right. + case ' ': + p.Space = true + default: + // Fast path for common case of ascii lower case simple verbs + // without precision or width or argument indices. + if 'a' <= c && c <= 'z' && p.ArgNum < len(p.Args) { + if c == 'v' { + // Go syntax + p.SharpV = p.Sharp + p.Sharp = false + // Struct-field syntax + p.PlusV = p.Plus + p.Plus = false + } + p.Verb = rune(c) + p.ArgNum++ + p.endPos = i + 1 + return true + } + // Format is more complex than simple flags and a verb or is malformed. + break simpleFormat + } + } + + // Do we have an explicit argument index? + i, afterIndex = p.updateArgNumber(format, i) + + // Do we have width? + if i < end && format[i] == '*' { + i++ + p.Width, p.WidthPresent = p.intFromArg() + + if !p.WidthPresent { + p.Status = StatusBadWidthSubstitution + } + + // We have a negative width, so take its value and ensure + // that the minus flag is set + if p.Width < 0 { + p.Width = -p.Width + p.Minus = true + p.Zero = false // Do not pad with zeros to the right. + } + afterIndex = false + } else { + p.Width, p.WidthPresent, i = parsenum(format, i, end) + if afterIndex && p.WidthPresent { // "%[3]2d" + p.goodArgNum = false + } + } + + // Do we have precision? + if i+1 < end && format[i] == '.' { + i++ + if afterIndex { // "%[3].2d" + p.goodArgNum = false + } + i, afterIndex = p.updateArgNumber(format, i) + if i < end && format[i] == '*' { + i++ + p.Prec, p.PrecPresent = p.intFromArg() + // Negative precision arguments don't make sense + if p.Prec < 0 { + p.Prec = 0 + p.PrecPresent = false + } + if !p.PrecPresent { + p.Status = StatusBadPrecSubstitution + } + afterIndex = false + } else { + p.Prec, p.PrecPresent, i = parsenum(format, i, end) + if !p.PrecPresent { + p.Prec = 0 + p.PrecPresent = true + } + } + } + + if !afterIndex { + i, afterIndex = p.updateArgNumber(format, i) + } + p.HasIndex = afterIndex + + if i >= end { + p.endPos = i + p.Status = StatusNoVerb + return true + } + + verb, w := utf8.DecodeRuneInString(format[i:]) + p.endPos = i + w + p.Verb = verb + + switch { + case verb == '%': // Percent does not absorb operands and ignores f.wid and f.prec. + p.startPos = p.endPos - 1 + p.Status = StatusText + case !p.goodArgNum: + p.Status = StatusBadArgNum + case p.ArgNum >= len(p.Args): // No argument left over to print for the current verb. + p.Status = StatusMissingArg + p.ArgNum++ + case verb == 'v': + // Go syntax + p.SharpV = p.Sharp + p.Sharp = false + // Struct-field syntax + p.PlusV = p.Plus + p.Plus = false + fallthrough + default: + p.ArgNum++ + } + return true +} + +// intFromArg gets the ArgNumth element of Args. On return, isInt reports +// whether the argument has integer type. +func (p *Parser) intFromArg() (num int, isInt bool) { + if p.ArgNum < len(p.Args) { + arg := p.Args[p.ArgNum] + num, isInt = arg.(int) // Almost always OK. + if !isInt { + // Work harder. + switch v := reflect.ValueOf(arg); v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + n := v.Int() + if int64(int(n)) == n { + num = int(n) + isInt = true + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + n := v.Uint() + if int64(n) >= 0 && uint64(int(n)) == n { + num = int(n) + isInt = true + } + default: + // Already 0, false. + } + } + p.ArgNum++ + if tooLarge(num) { + num = 0 + isInt = false + } + } + return +} + +// parseArgNumber returns the value of the bracketed number, minus 1 +// (explicit argument numbers are one-indexed but we want zero-indexed). +// The opening bracket is known to be present at format[0]. +// The returned values are the index, the number of bytes to consume +// up to the closing paren, if present, and whether the number parsed +// ok. The bytes to consume will be 1 if no closing paren is present. +func parseArgNumber(format string) (index int, wid int, ok bool) { + // There must be at least 3 bytes: [n]. + if len(format) < 3 { + return 0, 1, false + } + + // Find closing bracket. + for i := 1; i < len(format); i++ { + if format[i] == ']' { + width, ok, newi := parsenum(format, 1, i) + if !ok || newi != i { + return 0, i + 1, false + } + return width - 1, i + 1, true // arg numbers are one-indexed and skip paren. + } + } + return 0, 1, false +} + +// updateArgNumber returns the next argument to evaluate, which is either the value of the passed-in +// argNum or the value of the bracketed integer that begins format[i:]. It also returns +// the new value of i, that is, the index of the next byte of the format to process. +func (p *Parser) updateArgNumber(format string, i int) (newi int, found bool) { + if len(format) <= i || format[i] != '[' { + return i, false + } + p.Reordered = true + index, wid, ok := parseArgNumber(format[i:]) + if ok && 0 <= index && index < len(p.Args) { + p.ArgNum = index + return i + wid, true + } + p.goodArgNum = false + return i + wid, ok +} + +// tooLarge reports whether the magnitude of the integer is +// too large to be used as a formatting width or precision. +func tooLarge(x int) bool { + const max int = 1e6 + return x > max || x < -max +} + +// parsenum converts ASCII to integer. num is 0 (and isnum is false) if no number present. +func parsenum(s string, start, end int) (num int, isnum bool, newi int) { + if start >= end { + return 0, false, end + } + for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ { + if tooLarge(num) { + return 0, false, end // Overflow; crazy long number most likely. + } + num = num*10 + int(s[newi]-'0') + isnum = true + } + return +} diff --git a/vendor/golang.org/x/text/internal/number/common.go b/vendor/golang.org/x/text/internal/number/common.go new file mode 100644 index 00000000..a6e9c8e0 --- /dev/null +++ b/vendor/golang.org/x/text/internal/number/common.go @@ -0,0 +1,55 @@ +// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. + +package number + +import ( + "unicode/utf8" + + "golang.org/x/text/internal/language/compact" +) + +// A system identifies a CLDR numbering system. +type system byte + +type systemData struct { + id system + digitSize byte // number of UTF-8 bytes per digit + zero [utf8.UTFMax]byte // UTF-8 sequence of zero digit. +} + +// A SymbolType identifies a symbol of a specific kind. +type SymbolType int + +const ( + SymDecimal SymbolType = iota + SymGroup + SymList + SymPercentSign + SymPlusSign + SymMinusSign + SymExponential + SymSuperscriptingExponent + SymPerMille + SymInfinity + SymNan + SymTimeSeparator + + NumSymbolTypes +) + +const hasNonLatnMask = 0x8000 + +// symOffset is an offset into altSymData if the bit indicated by hasNonLatnMask +// is not 0 (with this bit masked out), and an offset into symIndex otherwise. +// +// TODO: this type can be a byte again if we use an indirection into altsymData +// and introduce an alt -> offset slice (the length of this will be number of +// alternatives plus 1). This also allows getting rid of the compactTag field +// in altSymData. In total this will save about 1K. +type symOffset uint16 + +type altSymData struct { + compactTag compact.ID + symIndex symOffset + system system +} diff --git a/vendor/golang.org/x/text/internal/number/decimal.go b/vendor/golang.org/x/text/internal/number/decimal.go new file mode 100644 index 00000000..e128cf34 --- /dev/null +++ b/vendor/golang.org/x/text/internal/number/decimal.go @@ -0,0 +1,500 @@ +// Copyright 2017 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. + +//go:generate stringer -type RoundingMode + +package number + +import ( + "math" + "strconv" +) + +// RoundingMode determines how a number is rounded to the desired precision. +type RoundingMode byte + +const ( + ToNearestEven RoundingMode = iota // towards the nearest integer, or towards an even number if equidistant. + ToNearestZero // towards the nearest integer, or towards zero if equidistant. + ToNearestAway // towards the nearest integer, or away from zero if equidistant. + ToPositiveInf // towards infinity + ToNegativeInf // towards negative infinity + ToZero // towards zero + AwayFromZero // away from zero + numModes +) + +const maxIntDigits = 20 + +// A Decimal represents a floating point number in decimal format. +// Digits represents a number [0, 1.0), and the absolute value represented by +// Decimal is Digits * 10^Exp. Leading and trailing zeros may be omitted and Exp +// may point outside a valid position in Digits. +// +// Examples: +// +// Number Decimal +// 12345 Digits: [1, 2, 3, 4, 5], Exp: 5 +// 12.345 Digits: [1, 2, 3, 4, 5], Exp: 2 +// 12000 Digits: [1, 2], Exp: 5 +// 12000.00 Digits: [1, 2], Exp: 5 +// 0.00123 Digits: [1, 2, 3], Exp: -2 +// 0 Digits: [], Exp: 0 +type Decimal struct { + digits + + buf [maxIntDigits]byte +} + +type digits struct { + Digits []byte // mantissa digits, big-endian + Exp int32 // exponent + Neg bool + Inf bool // Takes precedence over Digits and Exp. + NaN bool // Takes precedence over Inf. +} + +// Digits represents a floating point number represented in digits of the +// base in which a number is to be displayed. It is similar to Decimal, but +// keeps track of trailing fraction zeros and the comma placement for +// engineering notation. Digits must have at least one digit. +// +// Examples: +// +// Number Decimal +// decimal +// 12345 Digits: [1, 2, 3, 4, 5], Exp: 5 End: 5 +// 12.345 Digits: [1, 2, 3, 4, 5], Exp: 2 End: 5 +// 12000 Digits: [1, 2], Exp: 5 End: 5 +// 12000.00 Digits: [1, 2], Exp: 5 End: 7 +// 0.00123 Digits: [1, 2, 3], Exp: -2 End: 3 +// 0 Digits: [], Exp: 0 End: 1 +// scientific (actual exp is Exp - Comma) +// 0e0 Digits: [0], Exp: 1, End: 1, Comma: 1 +// .0e0 Digits: [0], Exp: 0, End: 1, Comma: 0 +// 0.0e0 Digits: [0], Exp: 1, End: 2, Comma: 1 +// 1.23e4 Digits: [1, 2, 3], Exp: 5, End: 3, Comma: 1 +// .123e5 Digits: [1, 2, 3], Exp: 5, End: 3, Comma: 0 +// engineering +// 12.3e3 Digits: [1, 2, 3], Exp: 5, End: 3, Comma: 2 +type Digits struct { + digits + // End indicates the end position of the number. + End int32 // For decimals Exp <= End. For scientific len(Digits) <= End. + // Comma is used for the comma position for scientific (always 0 or 1) and + // engineering notation (always 0, 1, 2, or 3). + Comma uint8 + // IsScientific indicates whether this number is to be rendered as a + // scientific number. + IsScientific bool +} + +func (d *Digits) NumFracDigits() int { + if d.Exp >= d.End { + return 0 + } + return int(d.End - d.Exp) +} + +// normalize returns a new Decimal with leading and trailing zeros removed. +func (d *Decimal) normalize() (n Decimal) { + n = *d + b := n.Digits + // Strip leading zeros. Resulting number of digits is significant digits. + for len(b) > 0 && b[0] == 0 { + b = b[1:] + n.Exp-- + } + // Strip trailing zeros + for len(b) > 0 && b[len(b)-1] == 0 { + b = b[:len(b)-1] + } + if len(b) == 0 { + n.Exp = 0 + } + n.Digits = b + return n +} + +func (d *Decimal) clear() { + b := d.Digits + if b == nil { + b = d.buf[:0] + } + *d = Decimal{} + d.Digits = b[:0] +} + +func (x *Decimal) String() string { + if x.NaN { + return "NaN" + } + var buf []byte + if x.Neg { + buf = append(buf, '-') + } + if x.Inf { + buf = append(buf, "Inf"...) + return string(buf) + } + switch { + case len(x.Digits) == 0: + buf = append(buf, '0') + case x.Exp <= 0: + // 0.00ddd + buf = append(buf, "0."...) + buf = appendZeros(buf, -int(x.Exp)) + buf = appendDigits(buf, x.Digits) + + case /* 0 < */ int(x.Exp) < len(x.Digits): + // dd.ddd + buf = appendDigits(buf, x.Digits[:x.Exp]) + buf = append(buf, '.') + buf = appendDigits(buf, x.Digits[x.Exp:]) + + default: // len(x.Digits) <= x.Exp + // ddd00 + buf = appendDigits(buf, x.Digits) + buf = appendZeros(buf, int(x.Exp)-len(x.Digits)) + } + return string(buf) +} + +func appendDigits(buf []byte, digits []byte) []byte { + for _, c := range digits { + buf = append(buf, c+'0') + } + return buf +} + +// appendZeros appends n 0 digits to buf and returns buf. +func appendZeros(buf []byte, n int) []byte { + for ; n > 0; n-- { + buf = append(buf, '0') + } + return buf +} + +func (d *digits) round(mode RoundingMode, n int) { + if n >= len(d.Digits) { + return + } + // Make rounding decision: The result mantissa is truncated ("rounded down") + // by default. Decide if we need to increment, or "round up", the (unsigned) + // mantissa. + inc := false + switch mode { + case ToNegativeInf: + inc = d.Neg + case ToPositiveInf: + inc = !d.Neg + case ToZero: + // nothing to do + case AwayFromZero: + inc = true + case ToNearestEven: + inc = d.Digits[n] > 5 || d.Digits[n] == 5 && + (len(d.Digits) > n+1 || n == 0 || d.Digits[n-1]&1 != 0) + case ToNearestAway: + inc = d.Digits[n] >= 5 + case ToNearestZero: + inc = d.Digits[n] > 5 || d.Digits[n] == 5 && len(d.Digits) > n+1 + default: + panic("unreachable") + } + if inc { + d.roundUp(n) + } else { + d.roundDown(n) + } +} + +// roundFloat rounds a floating point number. +func (r RoundingMode) roundFloat(x float64) float64 { + // Make rounding decision: The result mantissa is truncated ("rounded down") + // by default. Decide if we need to increment, or "round up", the (unsigned) + // mantissa. + abs := x + if x < 0 { + abs = -x + } + i, f := math.Modf(abs) + if f == 0.0 { + return x + } + inc := false + switch r { + case ToNegativeInf: + inc = x < 0 + case ToPositiveInf: + inc = x >= 0 + case ToZero: + // nothing to do + case AwayFromZero: + inc = true + case ToNearestEven: + // TODO: check overflow + inc = f > 0.5 || f == 0.5 && int64(i)&1 != 0 + case ToNearestAway: + inc = f >= 0.5 + case ToNearestZero: + inc = f > 0.5 + default: + panic("unreachable") + } + if inc { + i += 1 + } + if abs != x { + i = -i + } + return i +} + +func (x *digits) roundUp(n int) { + if n < 0 || n >= len(x.Digits) { + return // nothing to do + } + // find first digit < 9 + for n > 0 && x.Digits[n-1] >= 9 { + n-- + } + + if n == 0 { + // all digits are 9s => round up to 1 and update exponent + x.Digits[0] = 1 // ok since len(x.Digits) > n + x.Digits = x.Digits[:1] + x.Exp++ + return + } + x.Digits[n-1]++ + x.Digits = x.Digits[:n] + // x already trimmed +} + +func (x *digits) roundDown(n int) { + if n < 0 || n >= len(x.Digits) { + return // nothing to do + } + x.Digits = x.Digits[:n] + trim(x) +} + +// trim cuts off any trailing zeros from x's mantissa; +// they are meaningless for the value of x. +func trim(x *digits) { + i := len(x.Digits) + for i > 0 && x.Digits[i-1] == 0 { + i-- + } + x.Digits = x.Digits[:i] + if i == 0 { + x.Exp = 0 + } +} + +// A Converter converts a number into decimals according to the given rounding +// criteria. +type Converter interface { + Convert(d *Decimal, r RoundingContext) +} + +const ( + signed = true + unsigned = false +) + +// Convert converts the given number to the decimal representation using the +// supplied RoundingContext. +func (d *Decimal) Convert(r RoundingContext, number interface{}) { + switch f := number.(type) { + case Converter: + d.clear() + f.Convert(d, r) + case float32: + d.ConvertFloat(r, float64(f), 32) + case float64: + d.ConvertFloat(r, f, 64) + case int: + d.ConvertInt(r, signed, uint64(f)) + case int8: + d.ConvertInt(r, signed, uint64(f)) + case int16: + d.ConvertInt(r, signed, uint64(f)) + case int32: + d.ConvertInt(r, signed, uint64(f)) + case int64: + d.ConvertInt(r, signed, uint64(f)) + case uint: + d.ConvertInt(r, unsigned, uint64(f)) + case uint8: + d.ConvertInt(r, unsigned, uint64(f)) + case uint16: + d.ConvertInt(r, unsigned, uint64(f)) + case uint32: + d.ConvertInt(r, unsigned, uint64(f)) + case uint64: + d.ConvertInt(r, unsigned, f) + + default: + d.NaN = true + // TODO: + // case string: if produced by strconv, allows for easy arbitrary pos. + // case reflect.Value: + // case big.Float + // case big.Int + // case big.Rat? + // catch underlyings using reflect or will this already be done by the + // message package? + } +} + +// ConvertInt converts an integer to decimals. +func (d *Decimal) ConvertInt(r RoundingContext, signed bool, x uint64) { + if r.Increment > 0 { + // TODO: if uint64 is too large, fall back to float64 + if signed { + d.ConvertFloat(r, float64(int64(x)), 64) + } else { + d.ConvertFloat(r, float64(x), 64) + } + return + } + d.clear() + if signed && int64(x) < 0 { + x = uint64(-int64(x)) + d.Neg = true + } + d.fillIntDigits(x) + d.Exp = int32(len(d.Digits)) +} + +// ConvertFloat converts a floating point number to decimals. +func (d *Decimal) ConvertFloat(r RoundingContext, x float64, size int) { + d.clear() + if math.IsNaN(x) { + d.NaN = true + return + } + // Simple case: decimal notation + if r.Increment > 0 { + scale := int(r.IncrementScale) + mult := 1.0 + if scale >= len(scales) { + mult = math.Pow(10, float64(scale)) + } else { + mult = scales[scale] + } + // We multiply x instead of dividing inc as it gives less rounding + // issues. + x *= mult + x /= float64(r.Increment) + x = r.Mode.roundFloat(x) + x *= float64(r.Increment) + x /= mult + } + + abs := x + if x < 0 { + d.Neg = true + abs = -x + } + if math.IsInf(abs, 1) { + d.Inf = true + return + } + + // By default we get the exact decimal representation. + verb := byte('g') + prec := -1 + // As the strconv API does not return the rounding accuracy, we can only + // round using ToNearestEven. + if r.Mode == ToNearestEven { + if n := r.RoundSignificantDigits(); n >= 0 { + prec = n + } else if n = r.RoundFractionDigits(); n >= 0 { + prec = n + verb = 'f' + } + } else { + // TODO: At this point strconv's rounding is imprecise to the point that + // it is not usable for this purpose. + // See https://github.com/golang/go/issues/21714 + // If rounding is requested, we ask for a large number of digits and + // round from there to simulate rounding only once. + // Ideally we would have strconv export an AppendDigits that would take + // a rounding mode and/or return an accuracy. Something like this would + // work: + // AppendDigits(dst []byte, x float64, base, size, prec int) (digits []byte, exp, accuracy int) + hasPrec := r.RoundSignificantDigits() >= 0 + hasScale := r.RoundFractionDigits() >= 0 + if hasPrec || hasScale { + // prec is the number of mantissa bits plus some extra for safety. + // We need at least the number of mantissa bits as decimals to + // accurately represent the floating point without rounding, as each + // bit requires one more decimal to represent: 0.5, 0.25, 0.125, ... + prec = 60 + } + } + + b := strconv.AppendFloat(d.Digits[:0], abs, verb, prec, size) + i := 0 + k := 0 + beforeDot := 1 + for i < len(b) { + if c := b[i]; '0' <= c && c <= '9' { + b[k] = c - '0' + k++ + d.Exp += int32(beforeDot) + } else if c == '.' { + beforeDot = 0 + d.Exp = int32(k) + } else { + break + } + i++ + } + d.Digits = b[:k] + if i != len(b) { + i += len("e") + pSign := i + exp := 0 + for i++; i < len(b); i++ { + exp *= 10 + exp += int(b[i] - '0') + } + if b[pSign] == '-' { + exp = -exp + } + d.Exp = int32(exp) + 1 + } +} + +func (d *Decimal) fillIntDigits(x uint64) { + if cap(d.Digits) < maxIntDigits { + d.Digits = d.buf[:] + } else { + d.Digits = d.buf[:maxIntDigits] + } + i := 0 + for ; x > 0; x /= 10 { + d.Digits[i] = byte(x % 10) + i++ + } + d.Digits = d.Digits[:i] + for p := 0; p < i; p++ { + i-- + d.Digits[p], d.Digits[i] = d.Digits[i], d.Digits[p] + } +} + +var scales [70]float64 + +func init() { + x := 1.0 + for i := range scales { + scales[i] = x + x *= 10 + } +} diff --git a/vendor/golang.org/x/text/internal/number/format.go b/vendor/golang.org/x/text/internal/number/format.go new file mode 100644 index 00000000..cd94c5dc --- /dev/null +++ b/vendor/golang.org/x/text/internal/number/format.go @@ -0,0 +1,535 @@ +// Copyright 2017 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 number + +import ( + "strconv" + "unicode/utf8" + + "golang.org/x/text/language" +) + +// TODO: +// - grouping of fractions +// - allow user-defined superscript notation (such as 4) +// - same for non-breaking spaces, like   + +// A VisibleDigits computes digits, comma placement and trailing zeros as they +// will be shown to the user. +type VisibleDigits interface { + Digits(buf []byte, t language.Tag, scale int) Digits + // TODO: Do we also need to add the verb or pass a format.State? +} + +// Formatting proceeds along the following lines: +// 0) Compose rounding information from format and context. +// 1) Convert a number into a Decimal. +// 2) Sanitize Decimal by adding trailing zeros, removing leading digits, and +// (non-increment) rounding. The Decimal that results from this is suitable +// for determining the plural form. +// 3) Render the Decimal in the localized form. + +// Formatter contains all the information needed to render a number. +type Formatter struct { + Pattern + Info +} + +func (f *Formatter) init(t language.Tag, index []uint8) { + f.Info = InfoFromTag(t) + f.Pattern = formats[index[tagToID(t)]] +} + +// InitPattern initializes a Formatter for the given Pattern. +func (f *Formatter) InitPattern(t language.Tag, pat *Pattern) { + f.Info = InfoFromTag(t) + f.Pattern = *pat +} + +// InitDecimal initializes a Formatter using the default Pattern for the given +// language. +func (f *Formatter) InitDecimal(t language.Tag) { + f.init(t, tagToDecimal) +} + +// InitScientific initializes a Formatter using the default Pattern for the +// given language. +func (f *Formatter) InitScientific(t language.Tag) { + f.init(t, tagToScientific) + f.Pattern.MinFractionDigits = 0 + f.Pattern.MaxFractionDigits = -1 +} + +// InitEngineering initializes a Formatter using the default Pattern for the +// given language. +func (f *Formatter) InitEngineering(t language.Tag) { + f.init(t, tagToScientific) + f.Pattern.MinFractionDigits = 0 + f.Pattern.MaxFractionDigits = -1 + f.Pattern.MaxIntegerDigits = 3 + f.Pattern.MinIntegerDigits = 1 +} + +// InitPercent initializes a Formatter using the default Pattern for the given +// language. +func (f *Formatter) InitPercent(t language.Tag) { + f.init(t, tagToPercent) +} + +// InitPerMille initializes a Formatter using the default Pattern for the given +// language. +func (f *Formatter) InitPerMille(t language.Tag) { + f.init(t, tagToPercent) + f.Pattern.DigitShift = 3 +} + +func (f *Formatter) Append(dst []byte, x interface{}) []byte { + var d Decimal + r := f.RoundingContext + d.Convert(r, x) + return f.Render(dst, FormatDigits(&d, r)) +} + +func FormatDigits(d *Decimal, r RoundingContext) Digits { + if r.isScientific() { + return scientificVisibleDigits(r, d) + } + return decimalVisibleDigits(r, d) +} + +func (f *Formatter) Format(dst []byte, d *Decimal) []byte { + return f.Render(dst, FormatDigits(d, f.RoundingContext)) +} + +func (f *Formatter) Render(dst []byte, d Digits) []byte { + var result []byte + var postPrefix, preSuffix int + if d.IsScientific { + result, postPrefix, preSuffix = appendScientific(dst, f, &d) + } else { + result, postPrefix, preSuffix = appendDecimal(dst, f, &d) + } + if f.PadRune == 0 { + return result + } + width := int(f.FormatWidth) + if count := utf8.RuneCount(result); count < width { + insertPos := 0 + switch f.Flags & PadMask { + case PadAfterPrefix: + insertPos = postPrefix + case PadBeforeSuffix: + insertPos = preSuffix + case PadAfterSuffix: + insertPos = len(result) + } + num := width - count + pad := [utf8.UTFMax]byte{' '} + sz := 1 + if r := f.PadRune; r != 0 { + sz = utf8.EncodeRune(pad[:], r) + } + extra := sz * num + if n := len(result) + extra; n < cap(result) { + result = result[:n] + copy(result[insertPos+extra:], result[insertPos:]) + } else { + buf := make([]byte, n) + copy(buf, result[:insertPos]) + copy(buf[insertPos+extra:], result[insertPos:]) + result = buf + } + for ; num > 0; num-- { + insertPos += copy(result[insertPos:], pad[:sz]) + } + } + return result +} + +// decimalVisibleDigits converts d according to the RoundingContext. Note that +// the exponent may change as a result of this operation. +func decimalVisibleDigits(r RoundingContext, d *Decimal) Digits { + if d.NaN || d.Inf { + return Digits{digits: digits{Neg: d.Neg, NaN: d.NaN, Inf: d.Inf}} + } + n := Digits{digits: d.normalize().digits} + + exp := n.Exp + exp += int32(r.DigitShift) + + // Cap integer digits. Remove *most-significant* digits. + if r.MaxIntegerDigits > 0 { + if p := int(exp) - int(r.MaxIntegerDigits); p > 0 { + if p > len(n.Digits) { + p = len(n.Digits) + } + if n.Digits = n.Digits[p:]; len(n.Digits) == 0 { + exp = 0 + } else { + exp -= int32(p) + } + // Strip leading zeros. + for len(n.Digits) > 0 && n.Digits[0] == 0 { + n.Digits = n.Digits[1:] + exp-- + } + } + } + + // Rounding if not already done by Convert. + p := len(n.Digits) + if maxSig := int(r.MaxSignificantDigits); maxSig > 0 { + p = maxSig + } + if maxFrac := int(r.MaxFractionDigits); maxFrac >= 0 { + if cap := int(exp) + maxFrac; cap < p { + p = int(exp) + maxFrac + } + if p < 0 { + p = 0 + } + } + n.round(r.Mode, p) + + // set End (trailing zeros) + n.End = int32(len(n.Digits)) + if n.End == 0 { + exp = 0 + if r.MinFractionDigits > 0 { + n.End = int32(r.MinFractionDigits) + } + if p := int32(r.MinSignificantDigits) - 1; p > n.End { + n.End = p + } + } else { + if end := exp + int32(r.MinFractionDigits); end > n.End { + n.End = end + } + if n.End < int32(r.MinSignificantDigits) { + n.End = int32(r.MinSignificantDigits) + } + } + n.Exp = exp + return n +} + +// appendDecimal appends a formatted number to dst. It returns two possible +// insertion points for padding. +func appendDecimal(dst []byte, f *Formatter, n *Digits) (b []byte, postPre, preSuf int) { + if dst, ok := f.renderSpecial(dst, n); ok { + return dst, 0, len(dst) + } + digits := n.Digits + exp := n.Exp + + // Split in integer and fraction part. + var intDigits, fracDigits []byte + numInt := 0 + numFrac := int(n.End - n.Exp) + if exp > 0 { + numInt = int(exp) + if int(exp) >= len(digits) { // ddddd | ddddd00 + intDigits = digits + } else { // ddd.dd + intDigits = digits[:exp] + fracDigits = digits[exp:] + } + } else { + fracDigits = digits + } + + neg := n.Neg + affix, suffix := f.getAffixes(neg) + dst = appendAffix(dst, f, affix, neg) + savedLen := len(dst) + + minInt := int(f.MinIntegerDigits) + if minInt == 0 && f.MinSignificantDigits > 0 { + minInt = 1 + } + // add leading zeros + for i := minInt; i > numInt; i-- { + dst = f.AppendDigit(dst, 0) + if f.needsSep(i) { + dst = append(dst, f.Symbol(SymGroup)...) + } + } + i := 0 + for ; i < len(intDigits); i++ { + dst = f.AppendDigit(dst, intDigits[i]) + if f.needsSep(numInt - i) { + dst = append(dst, f.Symbol(SymGroup)...) + } + } + for ; i < numInt; i++ { + dst = f.AppendDigit(dst, 0) + if f.needsSep(numInt - i) { + dst = append(dst, f.Symbol(SymGroup)...) + } + } + + if numFrac > 0 || f.Flags&AlwaysDecimalSeparator != 0 { + dst = append(dst, f.Symbol(SymDecimal)...) + } + // Add trailing zeros + i = 0 + for n := -int(n.Exp); i < n; i++ { + dst = f.AppendDigit(dst, 0) + } + for _, d := range fracDigits { + i++ + dst = f.AppendDigit(dst, d) + } + for ; i < numFrac; i++ { + dst = f.AppendDigit(dst, 0) + } + return appendAffix(dst, f, suffix, neg), savedLen, len(dst) +} + +func scientificVisibleDigits(r RoundingContext, d *Decimal) Digits { + if d.NaN || d.Inf { + return Digits{digits: digits{Neg: d.Neg, NaN: d.NaN, Inf: d.Inf}} + } + n := Digits{digits: d.normalize().digits, IsScientific: true} + + // Normalize to have at least one digit. This simplifies engineering + // notation. + if len(n.Digits) == 0 { + n.Digits = append(n.Digits, 0) + n.Exp = 1 + } + + // Significant digits are transformed by the parser for scientific notation + // and do not need to be handled here. + maxInt, numInt := int(r.MaxIntegerDigits), int(r.MinIntegerDigits) + if numInt == 0 { + numInt = 1 + } + + // If a maximum number of integers is specified, the minimum must be 1 + // and the exponent is grouped by this number (e.g. for engineering) + if maxInt > numInt { + // Correct the exponent to reflect a single integer digit. + numInt = 1 + // engineering + // 0.01234 ([12345]e-1) -> 1.2345e-2 12.345e-3 + // 12345 ([12345]e+5) -> 1.2345e4 12.345e3 + d := int(n.Exp-1) % maxInt + if d < 0 { + d += maxInt + } + numInt += d + } + + p := len(n.Digits) + if maxSig := int(r.MaxSignificantDigits); maxSig > 0 { + p = maxSig + } + if maxFrac := int(r.MaxFractionDigits); maxFrac >= 0 && numInt+maxFrac < p { + p = numInt + maxFrac + } + n.round(r.Mode, p) + + n.Comma = uint8(numInt) + n.End = int32(len(n.Digits)) + if minSig := int32(r.MinFractionDigits) + int32(numInt); n.End < minSig { + n.End = minSig + } + return n +} + +// appendScientific appends a formatted number to dst. It returns two possible +// insertion points for padding. +func appendScientific(dst []byte, f *Formatter, n *Digits) (b []byte, postPre, preSuf int) { + if dst, ok := f.renderSpecial(dst, n); ok { + return dst, 0, 0 + } + digits := n.Digits + numInt := int(n.Comma) + numFrac := int(n.End) - int(n.Comma) + + var intDigits, fracDigits []byte + if numInt <= len(digits) { + intDigits = digits[:numInt] + fracDigits = digits[numInt:] + } else { + intDigits = digits + } + neg := n.Neg + affix, suffix := f.getAffixes(neg) + dst = appendAffix(dst, f, affix, neg) + savedLen := len(dst) + + i := 0 + for ; i < len(intDigits); i++ { + dst = f.AppendDigit(dst, intDigits[i]) + if f.needsSep(numInt - i) { + dst = append(dst, f.Symbol(SymGroup)...) + } + } + for ; i < numInt; i++ { + dst = f.AppendDigit(dst, 0) + if f.needsSep(numInt - i) { + dst = append(dst, f.Symbol(SymGroup)...) + } + } + + if numFrac > 0 || f.Flags&AlwaysDecimalSeparator != 0 { + dst = append(dst, f.Symbol(SymDecimal)...) + } + i = 0 + for ; i < len(fracDigits); i++ { + dst = f.AppendDigit(dst, fracDigits[i]) + } + for ; i < numFrac; i++ { + dst = f.AppendDigit(dst, 0) + } + + // exp + buf := [12]byte{} + // TODO: use exponential if superscripting is not available (no Latin + // numbers or no tags) and use exponential in all other cases. + exp := n.Exp - int32(n.Comma) + exponential := f.Symbol(SymExponential) + if exponential == "E" { + dst = append(dst, "\u202f"...) // NARROW NO-BREAK SPACE + dst = append(dst, f.Symbol(SymSuperscriptingExponent)...) + dst = append(dst, "\u202f"...) // NARROW NO-BREAK SPACE + dst = f.AppendDigit(dst, 1) + dst = f.AppendDigit(dst, 0) + switch { + case exp < 0: + dst = append(dst, superMinus...) + exp = -exp + case f.Flags&AlwaysExpSign != 0: + dst = append(dst, superPlus...) + } + b = strconv.AppendUint(buf[:0], uint64(exp), 10) + for i := len(b); i < int(f.MinExponentDigits); i++ { + dst = append(dst, superDigits[0]...) + } + for _, c := range b { + dst = append(dst, superDigits[c-'0']...) + } + } else { + dst = append(dst, exponential...) + switch { + case exp < 0: + dst = append(dst, f.Symbol(SymMinusSign)...) + exp = -exp + case f.Flags&AlwaysExpSign != 0: + dst = append(dst, f.Symbol(SymPlusSign)...) + } + b = strconv.AppendUint(buf[:0], uint64(exp), 10) + for i := len(b); i < int(f.MinExponentDigits); i++ { + dst = f.AppendDigit(dst, 0) + } + for _, c := range b { + dst = f.AppendDigit(dst, c-'0') + } + } + return appendAffix(dst, f, suffix, neg), savedLen, len(dst) +} + +const ( + superMinus = "\u207B" // SUPERSCRIPT HYPHEN-MINUS + superPlus = "\u207A" // SUPERSCRIPT PLUS SIGN +) + +var ( + // Note: the digits are not sequential!!! + superDigits = []string{ + "\u2070", // SUPERSCRIPT DIGIT ZERO + "\u00B9", // SUPERSCRIPT DIGIT ONE + "\u00B2", // SUPERSCRIPT DIGIT TWO + "\u00B3", // SUPERSCRIPT DIGIT THREE + "\u2074", // SUPERSCRIPT DIGIT FOUR + "\u2075", // SUPERSCRIPT DIGIT FIVE + "\u2076", // SUPERSCRIPT DIGIT SIX + "\u2077", // SUPERSCRIPT DIGIT SEVEN + "\u2078", // SUPERSCRIPT DIGIT EIGHT + "\u2079", // SUPERSCRIPT DIGIT NINE + } +) + +func (f *Formatter) getAffixes(neg bool) (affix, suffix string) { + str := f.Affix + if str != "" { + if f.NegOffset > 0 { + if neg { + str = str[f.NegOffset:] + } else { + str = str[:f.NegOffset] + } + } + sufStart := 1 + str[0] + affix = str[1:sufStart] + suffix = str[sufStart+1:] + } + // TODO: introduce a NeedNeg sign to indicate if the left pattern already + // has a sign marked? + if f.NegOffset == 0 && (neg || f.Flags&AlwaysSign != 0) { + affix = "-" + affix + } + return affix, suffix +} + +func (f *Formatter) renderSpecial(dst []byte, d *Digits) (b []byte, ok bool) { + if d.NaN { + return fmtNaN(dst, f), true + } + if d.Inf { + return fmtInfinite(dst, f, d), true + } + return dst, false +} + +func fmtNaN(dst []byte, f *Formatter) []byte { + return append(dst, f.Symbol(SymNan)...) +} + +func fmtInfinite(dst []byte, f *Formatter, d *Digits) []byte { + affix, suffix := f.getAffixes(d.Neg) + dst = appendAffix(dst, f, affix, d.Neg) + dst = append(dst, f.Symbol(SymInfinity)...) + dst = appendAffix(dst, f, suffix, d.Neg) + return dst +} + +func appendAffix(dst []byte, f *Formatter, affix string, neg bool) []byte { + quoting := false + escaping := false + for _, r := range affix { + switch { + case escaping: + // escaping occurs both inside and outside of quotes + dst = append(dst, string(r)...) + escaping = false + case r == '\\': + escaping = true + case r == '\'': + quoting = !quoting + case quoting: + dst = append(dst, string(r)...) + case r == '%': + if f.DigitShift == 3 { + dst = append(dst, f.Symbol(SymPerMille)...) + } else { + dst = append(dst, f.Symbol(SymPercentSign)...) + } + case r == '-' || r == '+': + if neg { + dst = append(dst, f.Symbol(SymMinusSign)...) + } else if f.Flags&ElideSign == 0 { + dst = append(dst, f.Symbol(SymPlusSign)...) + } else { + dst = append(dst, ' ') + } + default: + dst = append(dst, string(r)...) + } + } + return dst +} diff --git a/vendor/golang.org/x/text/internal/number/number.go b/vendor/golang.org/x/text/internal/number/number.go new file mode 100644 index 00000000..e1d933c3 --- /dev/null +++ b/vendor/golang.org/x/text/internal/number/number.go @@ -0,0 +1,152 @@ +// Copyright 2016 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. + +//go:generate go run gen.go gen_common.go + +// Package number contains tools and data for formatting numbers. +package number + +import ( + "unicode/utf8" + + "golang.org/x/text/internal/language/compact" + "golang.org/x/text/language" +) + +// Info holds number formatting configuration data. +type Info struct { + system systemData // numbering system information + symIndex symOffset // index to symbols +} + +// InfoFromLangID returns a Info for the given compact language identifier and +// numbering system identifier. If system is the empty string, the default +// numbering system will be taken for that language. +func InfoFromLangID(compactIndex compact.ID, numberSystem string) Info { + p := langToDefaults[compactIndex] + // Lookup the entry for the language. + pSymIndex := symOffset(0) // Default: Latin, default symbols + system, ok := systemMap[numberSystem] + if !ok { + // Take the value for the default numbering system. This is by far the + // most common case as an alternative numbering system is hardly used. + if p&hasNonLatnMask == 0 { // Latn digits. + pSymIndex = p + } else { // Non-Latn or multiple numbering systems. + // Take the first entry from the alternatives list. + data := langToAlt[p&^hasNonLatnMask] + pSymIndex = data.symIndex + system = data.system + } + } else { + langIndex := compactIndex + ns := system + outerLoop: + for ; ; p = langToDefaults[langIndex] { + if p&hasNonLatnMask == 0 { + if ns == 0 { + // The index directly points to the symbol data. + pSymIndex = p + break + } + // Move to the parent and retry. + langIndex = langIndex.Parent() + } else { + // The index points to a list of symbol data indexes. + for _, e := range langToAlt[p&^hasNonLatnMask:] { + if e.compactTag != langIndex { + if langIndex == 0 { + // The CLDR root defines full symbol information for + // all numbering systems (even though mostly by + // means of aliases). Fall back to the default entry + // for Latn if there is no data for the numbering + // system of this language. + if ns == 0 { + break + } + // Fall back to Latin and start from the original + // language. See + // https://unicode.org/reports/tr35/#Locale_Inheritance. + ns = numLatn + langIndex = compactIndex + continue outerLoop + } + // Fall back to parent. + langIndex = langIndex.Parent() + } else if e.system == ns { + pSymIndex = e.symIndex + break outerLoop + } + } + } + } + } + if int(system) >= len(numSysData) { // algorithmic + // Will generate ASCII digits in case the user inadvertently calls + // WriteDigit or Digit on it. + d := numSysData[0] + d.id = system + return Info{ + system: d, + symIndex: pSymIndex, + } + } + return Info{ + system: numSysData[system], + symIndex: pSymIndex, + } +} + +// InfoFromTag returns a Info for the given language tag. +func InfoFromTag(t language.Tag) Info { + return InfoFromLangID(tagToID(t), t.TypeForKey("nu")) +} + +// IsDecimal reports if the numbering system can convert decimal to native +// symbols one-to-one. +func (n Info) IsDecimal() bool { + return int(n.system.id) < len(numSysData) +} + +// WriteDigit writes the UTF-8 sequence for n corresponding to the given ASCII +// digit to dst and reports the number of bytes written. dst must be large +// enough to hold the rune (can be up to utf8.UTFMax bytes). +func (n Info) WriteDigit(dst []byte, asciiDigit rune) int { + copy(dst, n.system.zero[:n.system.digitSize]) + dst[n.system.digitSize-1] += byte(asciiDigit - '0') + return int(n.system.digitSize) +} + +// AppendDigit appends the UTF-8 sequence for n corresponding to the given digit +// to dst and reports the number of bytes written. dst must be large enough to +// hold the rune (can be up to utf8.UTFMax bytes). +func (n Info) AppendDigit(dst []byte, digit byte) []byte { + dst = append(dst, n.system.zero[:n.system.digitSize]...) + dst[len(dst)-1] += digit + return dst +} + +// Digit returns the digit for the numbering system for the corresponding ASCII +// value. For example, ni.Digit('3') could return '三'. Note that the argument +// is the rune constant '3', which equals 51, not the integer constant 3. +func (n Info) Digit(asciiDigit rune) rune { + var x [utf8.UTFMax]byte + n.WriteDigit(x[:], asciiDigit) + r, _ := utf8.DecodeRune(x[:]) + return r +} + +// Symbol returns the string for the given symbol type. +func (n Info) Symbol(t SymbolType) string { + return symData.Elem(int(symIndex[n.symIndex][t])) +} + +func formatForLang(t language.Tag, index []byte) *Pattern { + return &formats[index[tagToID(t)]] +} + +func tagToID(t language.Tag) compact.ID { + id, _ := compact.RegionalID(compact.Tag(t)) + return id +} diff --git a/vendor/golang.org/x/text/internal/number/pattern.go b/vendor/golang.org/x/text/internal/number/pattern.go new file mode 100644 index 00000000..06e59559 --- /dev/null +++ b/vendor/golang.org/x/text/internal/number/pattern.go @@ -0,0 +1,485 @@ +// Copyright 2015 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 number + +import ( + "errors" + "unicode/utf8" +) + +// This file contains a parser for the CLDR number patterns as described in +// https://unicode.org/reports/tr35/tr35-numbers.html#Number_Format_Patterns. +// +// The following BNF is derived from this standard. +// +// pattern := subpattern (';' subpattern)? +// subpattern := affix? number exponent? affix? +// number := decimal | sigDigits +// decimal := '#'* '0'* ('.' fraction)? | '#' | '0' +// fraction := '0'* '#'* +// sigDigits := '#'* '@' '@'* '#'* +// exponent := 'E' '+'? '0'* '0' +// padSpec := '*' \L +// +// Notes: +// - An affix pattern may contain any runes, but runes with special meaning +// should be escaped. +// - Sequences of digits, '#', and '@' in decimal and sigDigits may have +// interstitial commas. + +// TODO: replace special characters in affixes (-, +, ¤) with control codes. + +// Pattern holds information for formatting numbers. It is designed to hold +// information from CLDR number patterns. +// +// This pattern is precompiled for all patterns for all languages. Even though +// the number of patterns is not very large, we want to keep this small. +// +// This type is only intended for internal use. +type Pattern struct { + RoundingContext + + Affix string // includes prefix and suffix. First byte is prefix length. + Offset uint16 // Offset into Affix for prefix and suffix + NegOffset uint16 // Offset into Affix for negative prefix and suffix or 0. + PadRune rune + FormatWidth uint16 + + GroupingSize [2]uint8 + Flags PatternFlag +} + +// A RoundingContext indicates how a number should be converted to digits. +// It contains all information needed to determine the "visible digits" as +// required by the pluralization rules. +type RoundingContext struct { + // TODO: unify these two fields so that there is a more unambiguous meaning + // of how precision is handled. + MaxSignificantDigits int16 // -1 is unlimited + MaxFractionDigits int16 // -1 is unlimited + + Increment uint32 + IncrementScale uint8 // May differ from printed scale. + + Mode RoundingMode + + DigitShift uint8 // Number of decimals to shift. Used for % and ‰. + + // Number of digits. + MinIntegerDigits uint8 + + MaxIntegerDigits uint8 + MinFractionDigits uint8 + MinSignificantDigits uint8 + + MinExponentDigits uint8 +} + +// RoundSignificantDigits returns the number of significant digits an +// implementation of Convert may round to or n < 0 if there is no maximum or +// a maximum is not recommended. +func (r *RoundingContext) RoundSignificantDigits() (n int) { + if r.MaxFractionDigits == 0 && r.MaxSignificantDigits > 0 { + return int(r.MaxSignificantDigits) + } else if r.isScientific() && r.MaxIntegerDigits == 1 { + if r.MaxSignificantDigits == 0 || + int(r.MaxFractionDigits+1) == int(r.MaxSignificantDigits) { + // Note: don't add DigitShift: it is only used for decimals. + return int(r.MaxFractionDigits) + 1 + } + } + return -1 +} + +// RoundFractionDigits returns the number of fraction digits an implementation +// of Convert may round to or n < 0 if there is no maximum or a maximum is not +// recommended. +func (r *RoundingContext) RoundFractionDigits() (n int) { + if r.MinExponentDigits == 0 && + r.MaxSignificantDigits == 0 && + r.MaxFractionDigits >= 0 { + return int(r.MaxFractionDigits) + int(r.DigitShift) + } + return -1 +} + +// SetScale fixes the RoundingContext to a fixed number of fraction digits. +func (r *RoundingContext) SetScale(scale int) { + r.MinFractionDigits = uint8(scale) + r.MaxFractionDigits = int16(scale) +} + +func (r *RoundingContext) SetPrecision(prec int) { + r.MaxSignificantDigits = int16(prec) +} + +func (r *RoundingContext) isScientific() bool { + return r.MinExponentDigits > 0 +} + +func (f *Pattern) needsSep(pos int) bool { + p := pos - 1 + size := int(f.GroupingSize[0]) + if size == 0 || p == 0 { + return false + } + if p == size { + return true + } + if p -= size; p < 0 { + return false + } + // TODO: make second groupingsize the same as first if 0 so that we can + // avoid this check. + if x := int(f.GroupingSize[1]); x != 0 { + size = x + } + return p%size == 0 +} + +// A PatternFlag is a bit mask for the flag field of a Pattern. +type PatternFlag uint8 + +const ( + AlwaysSign PatternFlag = 1 << iota + ElideSign // Use space instead of plus sign. AlwaysSign must be true. + AlwaysExpSign + AlwaysDecimalSeparator + ParenthesisForNegative // Common pattern. Saves space. + + PadAfterNumber + PadAfterAffix + + PadBeforePrefix = 0 // Default + PadAfterPrefix = PadAfterAffix + PadBeforeSuffix = PadAfterNumber + PadAfterSuffix = PadAfterNumber | PadAfterAffix + PadMask = PadAfterNumber | PadAfterAffix +) + +type parser struct { + *Pattern + + leadingSharps int + + pos int + err error + doNotTerminate bool + groupingCount uint + hasGroup bool + buf []byte +} + +func (p *parser) setError(err error) { + if p.err == nil { + p.err = err + } +} + +func (p *parser) updateGrouping() { + if p.hasGroup && + 0 < p.groupingCount && p.groupingCount < 255 { + p.GroupingSize[1] = p.GroupingSize[0] + p.GroupingSize[0] = uint8(p.groupingCount) + } + p.groupingCount = 0 + p.hasGroup = true +} + +var ( + // TODO: more sensible and localizeable error messages. + errMultiplePadSpecifiers = errors.New("format: pattern has multiple pad specifiers") + errInvalidPadSpecifier = errors.New("format: invalid pad specifier") + errInvalidQuote = errors.New("format: invalid quote") + errAffixTooLarge = errors.New("format: prefix or suffix exceeds maximum UTF-8 length of 256 bytes") + errDuplicatePercentSign = errors.New("format: duplicate percent sign") + errDuplicatePermilleSign = errors.New("format: duplicate permille sign") + errUnexpectedEnd = errors.New("format: unexpected end of pattern") +) + +// ParsePattern extracts formatting information from a CLDR number pattern. +// +// See https://unicode.org/reports/tr35/tr35-numbers.html#Number_Format_Patterns. +func ParsePattern(s string) (f *Pattern, err error) { + p := parser{Pattern: &Pattern{}} + + s = p.parseSubPattern(s) + + if s != "" { + // Parse negative sub pattern. + if s[0] != ';' { + p.setError(errors.New("format: error parsing first sub pattern")) + return nil, p.err + } + neg := parser{Pattern: &Pattern{}} // just for extracting the affixes. + s = neg.parseSubPattern(s[len(";"):]) + p.NegOffset = uint16(len(p.buf)) + p.buf = append(p.buf, neg.buf...) + } + if s != "" { + p.setError(errors.New("format: spurious characters at end of pattern")) + } + if p.err != nil { + return nil, p.err + } + if affix := string(p.buf); affix == "\x00\x00" || affix == "\x00\x00\x00\x00" { + // No prefix or suffixes. + p.NegOffset = 0 + } else { + p.Affix = affix + } + if p.Increment == 0 { + p.IncrementScale = 0 + } + return p.Pattern, nil +} + +func (p *parser) parseSubPattern(s string) string { + s = p.parsePad(s, PadBeforePrefix) + s = p.parseAffix(s) + s = p.parsePad(s, PadAfterPrefix) + + s = p.parse(p.number, s) + p.updateGrouping() + + s = p.parsePad(s, PadBeforeSuffix) + s = p.parseAffix(s) + s = p.parsePad(s, PadAfterSuffix) + return s +} + +func (p *parser) parsePad(s string, f PatternFlag) (tail string) { + if len(s) >= 2 && s[0] == '*' { + r, sz := utf8.DecodeRuneInString(s[1:]) + if p.PadRune != 0 { + p.err = errMultiplePadSpecifiers + } else { + p.Flags |= f + p.PadRune = r + } + return s[1+sz:] + } + return s +} + +func (p *parser) parseAffix(s string) string { + x := len(p.buf) + p.buf = append(p.buf, 0) // placeholder for affix length + + s = p.parse(p.affix, s) + + n := len(p.buf) - x - 1 + if n > 0xFF { + p.setError(errAffixTooLarge) + } + p.buf[x] = uint8(n) + return s +} + +// state implements a state transition. It returns the new state. A state +// function may set an error on the parser or may simply return on an incorrect +// token and let the next phase fail. +type state func(r rune) state + +// parse repeatedly applies a state function on the given string until a +// termination condition is reached. +func (p *parser) parse(fn state, s string) (tail string) { + for i, r := range s { + p.doNotTerminate = false + if fn = fn(r); fn == nil || p.err != nil { + return s[i:] + } + p.FormatWidth++ + } + if p.doNotTerminate { + p.setError(errUnexpectedEnd) + } + return "" +} + +func (p *parser) affix(r rune) state { + switch r { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '#', '@', '.', '*', ',', ';': + return nil + case '\'': + p.FormatWidth-- + return p.escapeFirst + case '%': + if p.DigitShift != 0 { + p.setError(errDuplicatePercentSign) + } + p.DigitShift = 2 + case '\u2030': // ‰ Per mille + if p.DigitShift != 0 { + p.setError(errDuplicatePermilleSign) + } + p.DigitShift = 3 + // TODO: handle currency somehow: ¤, ¤¤, ¤¤¤, ¤¤¤¤ + } + p.buf = append(p.buf, string(r)...) + return p.affix +} + +func (p *parser) escapeFirst(r rune) state { + switch r { + case '\'': + p.buf = append(p.buf, "\\'"...) + return p.affix + default: + p.buf = append(p.buf, '\'') + p.buf = append(p.buf, string(r)...) + } + return p.escape +} + +func (p *parser) escape(r rune) state { + switch r { + case '\'': + p.FormatWidth-- + p.buf = append(p.buf, '\'') + return p.affix + default: + p.buf = append(p.buf, string(r)...) + } + return p.escape +} + +// number parses a number. The BNF says the integer part should always have +// a '0', but that does not appear to be the case according to the rest of the +// documentation. We will allow having only '#' numbers. +func (p *parser) number(r rune) state { + switch r { + case '#': + p.groupingCount++ + p.leadingSharps++ + case '@': + p.groupingCount++ + p.leadingSharps = 0 + p.MaxFractionDigits = -1 + return p.sigDigits(r) + case ',': + if p.leadingSharps == 0 { // no leading commas + return nil + } + p.updateGrouping() + case 'E': + p.MaxIntegerDigits = uint8(p.leadingSharps) + return p.exponent + case '.': // allow ".##" etc. + p.updateGrouping() + return p.fraction + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return p.integer(r) + default: + return nil + } + return p.number +} + +func (p *parser) integer(r rune) state { + if !('0' <= r && r <= '9') { + var next state + switch r { + case 'E': + if p.leadingSharps > 0 { + p.MaxIntegerDigits = uint8(p.leadingSharps) + p.MinIntegerDigits + } + next = p.exponent + case '.': + next = p.fraction + case ',': + next = p.integer + } + p.updateGrouping() + return next + } + p.Increment = p.Increment*10 + uint32(r-'0') + p.groupingCount++ + p.MinIntegerDigits++ + return p.integer +} + +func (p *parser) sigDigits(r rune) state { + switch r { + case '@': + p.groupingCount++ + p.MaxSignificantDigits++ + p.MinSignificantDigits++ + case '#': + return p.sigDigitsFinal(r) + case 'E': + p.updateGrouping() + return p.normalizeSigDigitsWithExponent() + default: + p.updateGrouping() + return nil + } + return p.sigDigits +} + +func (p *parser) sigDigitsFinal(r rune) state { + switch r { + case '#': + p.groupingCount++ + p.MaxSignificantDigits++ + case 'E': + p.updateGrouping() + return p.normalizeSigDigitsWithExponent() + default: + p.updateGrouping() + return nil + } + return p.sigDigitsFinal +} + +func (p *parser) normalizeSigDigitsWithExponent() state { + p.MinIntegerDigits, p.MaxIntegerDigits = 1, 1 + p.MinFractionDigits = p.MinSignificantDigits - 1 + p.MaxFractionDigits = p.MaxSignificantDigits - 1 + p.MinSignificantDigits, p.MaxSignificantDigits = 0, 0 + return p.exponent +} + +func (p *parser) fraction(r rune) state { + switch r { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + p.Increment = p.Increment*10 + uint32(r-'0') + p.IncrementScale++ + p.MinFractionDigits++ + p.MaxFractionDigits++ + case '#': + p.MaxFractionDigits++ + case 'E': + if p.leadingSharps > 0 { + p.MaxIntegerDigits = uint8(p.leadingSharps) + p.MinIntegerDigits + } + return p.exponent + default: + return nil + } + return p.fraction +} + +func (p *parser) exponent(r rune) state { + switch r { + case '+': + // Set mode and check it wasn't already set. + if p.Flags&AlwaysExpSign != 0 || p.MinExponentDigits > 0 { + break + } + p.Flags |= AlwaysExpSign + p.doNotTerminate = true + return p.exponent + case '0': + p.MinExponentDigits++ + return p.exponent + } + // termination condition + if p.MinExponentDigits == 0 { + p.setError(errors.New("format: need at least one digit")) + } + return nil +} diff --git a/vendor/golang.org/x/text/internal/number/roundingmode_string.go b/vendor/golang.org/x/text/internal/number/roundingmode_string.go new file mode 100644 index 00000000..bcc22471 --- /dev/null +++ b/vendor/golang.org/x/text/internal/number/roundingmode_string.go @@ -0,0 +1,30 @@ +// Code generated by "stringer -type RoundingMode"; DO NOT EDIT. + +package number + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[ToNearestEven-0] + _ = x[ToNearestZero-1] + _ = x[ToNearestAway-2] + _ = x[ToPositiveInf-3] + _ = x[ToNegativeInf-4] + _ = x[ToZero-5] + _ = x[AwayFromZero-6] + _ = x[numModes-7] +} + +const _RoundingMode_name = "ToNearestEvenToNearestZeroToNearestAwayToPositiveInfToNegativeInfToZeroAwayFromZeronumModes" + +var _RoundingMode_index = [...]uint8{0, 13, 26, 39, 52, 65, 71, 83, 91} + +func (i RoundingMode) String() string { + if i >= RoundingMode(len(_RoundingMode_index)-1) { + return "RoundingMode(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _RoundingMode_name[_RoundingMode_index[i]:_RoundingMode_index[i+1]] +} diff --git a/vendor/golang.org/x/text/internal/number/tables.go b/vendor/golang.org/x/text/internal/number/tables.go new file mode 100644 index 00000000..8efce81b --- /dev/null +++ b/vendor/golang.org/x/text/internal/number/tables.go @@ -0,0 +1,1219 @@ +// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. + +package number + +import "golang.org/x/text/internal/stringset" + +// CLDRVersion is the CLDR version from which the tables in this package are derived. +const CLDRVersion = "32" + +var numSysData = []systemData{ // 59 elements + 0: {id: 0x0, digitSize: 0x1, zero: [4]uint8{0x30, 0x0, 0x0, 0x0}}, + 1: {id: 0x1, digitSize: 0x4, zero: [4]uint8{0xf0, 0x9e, 0xa5, 0x90}}, + 2: {id: 0x2, digitSize: 0x4, zero: [4]uint8{0xf0, 0x91, 0x9c, 0xb0}}, + 3: {id: 0x3, digitSize: 0x2, zero: [4]uint8{0xd9, 0xa0, 0x0, 0x0}}, + 4: {id: 0x4, digitSize: 0x2, zero: [4]uint8{0xdb, 0xb0, 0x0, 0x0}}, + 5: {id: 0x5, digitSize: 0x3, zero: [4]uint8{0xe1, 0xad, 0x90, 0x0}}, + 6: {id: 0x6, digitSize: 0x3, zero: [4]uint8{0xe0, 0xa7, 0xa6, 0x0}}, + 7: {id: 0x7, digitSize: 0x4, zero: [4]uint8{0xf0, 0x91, 0xb1, 0x90}}, + 8: {id: 0x8, digitSize: 0x4, zero: [4]uint8{0xf0, 0x91, 0x81, 0xa6}}, + 9: {id: 0x9, digitSize: 0x4, zero: [4]uint8{0xf0, 0x91, 0x84, 0xb6}}, + 10: {id: 0xa, digitSize: 0x3, zero: [4]uint8{0xea, 0xa9, 0x90, 0x0}}, + 11: {id: 0xb, digitSize: 0x3, zero: [4]uint8{0xe0, 0xa5, 0xa6, 0x0}}, + 12: {id: 0xc, digitSize: 0x3, zero: [4]uint8{0xef, 0xbc, 0x90, 0x0}}, + 13: {id: 0xd, digitSize: 0x4, zero: [4]uint8{0xf0, 0x91, 0xb5, 0x90}}, + 14: {id: 0xe, digitSize: 0x3, zero: [4]uint8{0xe0, 0xab, 0xa6, 0x0}}, + 15: {id: 0xf, digitSize: 0x3, zero: [4]uint8{0xe0, 0xa9, 0xa6, 0x0}}, + 16: {id: 0x10, digitSize: 0x4, zero: [4]uint8{0xf0, 0x96, 0xad, 0x90}}, + 17: {id: 0x11, digitSize: 0x3, zero: [4]uint8{0xea, 0xa7, 0x90, 0x0}}, + 18: {id: 0x12, digitSize: 0x3, zero: [4]uint8{0xea, 0xa4, 0x80, 0x0}}, + 19: {id: 0x13, digitSize: 0x3, zero: [4]uint8{0xe1, 0x9f, 0xa0, 0x0}}, + 20: {id: 0x14, digitSize: 0x3, zero: [4]uint8{0xe0, 0xb3, 0xa6, 0x0}}, + 21: {id: 0x15, digitSize: 0x3, zero: [4]uint8{0xe1, 0xaa, 0x80, 0x0}}, + 22: {id: 0x16, digitSize: 0x3, zero: [4]uint8{0xe1, 0xaa, 0x90, 0x0}}, + 23: {id: 0x17, digitSize: 0x3, zero: [4]uint8{0xe0, 0xbb, 0x90, 0x0}}, + 24: {id: 0x18, digitSize: 0x3, zero: [4]uint8{0xe1, 0xb1, 0x80, 0x0}}, + 25: {id: 0x19, digitSize: 0x3, zero: [4]uint8{0xe1, 0xa5, 0x86, 0x0}}, + 26: {id: 0x1a, digitSize: 0x4, zero: [4]uint8{0xf0, 0x9d, 0x9f, 0x8e}}, + 27: {id: 0x1b, digitSize: 0x4, zero: [4]uint8{0xf0, 0x9d, 0x9f, 0x98}}, + 28: {id: 0x1c, digitSize: 0x4, zero: [4]uint8{0xf0, 0x9d, 0x9f, 0xb6}}, + 29: {id: 0x1d, digitSize: 0x4, zero: [4]uint8{0xf0, 0x9d, 0x9f, 0xac}}, + 30: {id: 0x1e, digitSize: 0x4, zero: [4]uint8{0xf0, 0x9d, 0x9f, 0xa2}}, + 31: {id: 0x1f, digitSize: 0x3, zero: [4]uint8{0xe0, 0xb5, 0xa6, 0x0}}, + 32: {id: 0x20, digitSize: 0x4, zero: [4]uint8{0xf0, 0x91, 0x99, 0x90}}, + 33: {id: 0x21, digitSize: 0x3, zero: [4]uint8{0xe1, 0xa0, 0x90, 0x0}}, + 34: {id: 0x22, digitSize: 0x4, zero: [4]uint8{0xf0, 0x96, 0xa9, 0xa0}}, + 35: {id: 0x23, digitSize: 0x3, zero: [4]uint8{0xea, 0xaf, 0xb0, 0x0}}, + 36: {id: 0x24, digitSize: 0x3, zero: [4]uint8{0xe1, 0x81, 0x80, 0x0}}, + 37: {id: 0x25, digitSize: 0x3, zero: [4]uint8{0xe1, 0x82, 0x90, 0x0}}, + 38: {id: 0x26, digitSize: 0x3, zero: [4]uint8{0xea, 0xa7, 0xb0, 0x0}}, + 39: {id: 0x27, digitSize: 0x4, zero: [4]uint8{0xf0, 0x91, 0x91, 0x90}}, + 40: {id: 0x28, digitSize: 0x2, zero: [4]uint8{0xdf, 0x80, 0x0, 0x0}}, + 41: {id: 0x29, digitSize: 0x3, zero: [4]uint8{0xe1, 0xb1, 0x90, 0x0}}, + 42: {id: 0x2a, digitSize: 0x3, zero: [4]uint8{0xe0, 0xad, 0xa6, 0x0}}, + 43: {id: 0x2b, digitSize: 0x4, zero: [4]uint8{0xf0, 0x90, 0x92, 0xa0}}, + 44: {id: 0x2c, digitSize: 0x3, zero: [4]uint8{0xea, 0xa3, 0x90, 0x0}}, + 45: {id: 0x2d, digitSize: 0x4, zero: [4]uint8{0xf0, 0x91, 0x87, 0x90}}, + 46: {id: 0x2e, digitSize: 0x4, zero: [4]uint8{0xf0, 0x91, 0x8b, 0xb0}}, + 47: {id: 0x2f, digitSize: 0x3, zero: [4]uint8{0xe0, 0xb7, 0xa6, 0x0}}, + 48: {id: 0x30, digitSize: 0x4, zero: [4]uint8{0xf0, 0x91, 0x83, 0xb0}}, + 49: {id: 0x31, digitSize: 0x3, zero: [4]uint8{0xe1, 0xae, 0xb0, 0x0}}, + 50: {id: 0x32, digitSize: 0x4, zero: [4]uint8{0xf0, 0x91, 0x9b, 0x80}}, + 51: {id: 0x33, digitSize: 0x3, zero: [4]uint8{0xe1, 0xa7, 0x90, 0x0}}, + 52: {id: 0x34, digitSize: 0x3, zero: [4]uint8{0xe0, 0xaf, 0xa6, 0x0}}, + 53: {id: 0x35, digitSize: 0x3, zero: [4]uint8{0xe0, 0xb1, 0xa6, 0x0}}, + 54: {id: 0x36, digitSize: 0x3, zero: [4]uint8{0xe0, 0xb9, 0x90, 0x0}}, + 55: {id: 0x37, digitSize: 0x3, zero: [4]uint8{0xe0, 0xbc, 0xa0, 0x0}}, + 56: {id: 0x38, digitSize: 0x4, zero: [4]uint8{0xf0, 0x91, 0x93, 0x90}}, + 57: {id: 0x39, digitSize: 0x3, zero: [4]uint8{0xea, 0x98, 0xa0, 0x0}}, + 58: {id: 0x3a, digitSize: 0x4, zero: [4]uint8{0xf0, 0x91, 0xa3, 0xa0}}, +} // Size: 378 bytes + +const ( + numAdlm = 0x1 + numAhom = 0x2 + numArab = 0x3 + numArabext = 0x4 + numArmn = 0x3b + numArmnlow = 0x3c + numBali = 0x5 + numBeng = 0x6 + numBhks = 0x7 + numBrah = 0x8 + numCakm = 0x9 + numCham = 0xa + numCyrl = 0x3d + numDeva = 0xb + numEthi = 0x3e + numFullwide = 0xc + numGeor = 0x3f + numGonm = 0xd + numGrek = 0x40 + numGreklow = 0x41 + numGujr = 0xe + numGuru = 0xf + numHanidays = 0x42 + numHanidec = 0x43 + numHans = 0x44 + numHansfin = 0x45 + numHant = 0x46 + numHantfin = 0x47 + numHebr = 0x48 + numHmng = 0x10 + numJava = 0x11 + numJpan = 0x49 + numJpanfin = 0x4a + numKali = 0x12 + numKhmr = 0x13 + numKnda = 0x14 + numLana = 0x15 + numLanatham = 0x16 + numLaoo = 0x17 + numLatn = 0x0 + numLepc = 0x18 + numLimb = 0x19 + numMathbold = 0x1a + numMathdbl = 0x1b + numMathmono = 0x1c + numMathsanb = 0x1d + numMathsans = 0x1e + numMlym = 0x1f + numModi = 0x20 + numMong = 0x21 + numMroo = 0x22 + numMtei = 0x23 + numMymr = 0x24 + numMymrshan = 0x25 + numMymrtlng = 0x26 + numNewa = 0x27 + numNkoo = 0x28 + numOlck = 0x29 + numOrya = 0x2a + numOsma = 0x2b + numRoman = 0x4b + numRomanlow = 0x4c + numSaur = 0x2c + numShrd = 0x2d + numSind = 0x2e + numSinh = 0x2f + numSora = 0x30 + numSund = 0x31 + numTakr = 0x32 + numTalu = 0x33 + numTaml = 0x4d + numTamldec = 0x34 + numTelu = 0x35 + numThai = 0x36 + numTibt = 0x37 + numTirh = 0x38 + numVaii = 0x39 + numWara = 0x3a + numNumberSystems +) + +var systemMap = map[string]system{ + "adlm": numAdlm, + "ahom": numAhom, + "arab": numArab, + "arabext": numArabext, + "armn": numArmn, + "armnlow": numArmnlow, + "bali": numBali, + "beng": numBeng, + "bhks": numBhks, + "brah": numBrah, + "cakm": numCakm, + "cham": numCham, + "cyrl": numCyrl, + "deva": numDeva, + "ethi": numEthi, + "fullwide": numFullwide, + "geor": numGeor, + "gonm": numGonm, + "grek": numGrek, + "greklow": numGreklow, + "gujr": numGujr, + "guru": numGuru, + "hanidays": numHanidays, + "hanidec": numHanidec, + "hans": numHans, + "hansfin": numHansfin, + "hant": numHant, + "hantfin": numHantfin, + "hebr": numHebr, + "hmng": numHmng, + "java": numJava, + "jpan": numJpan, + "jpanfin": numJpanfin, + "kali": numKali, + "khmr": numKhmr, + "knda": numKnda, + "lana": numLana, + "lanatham": numLanatham, + "laoo": numLaoo, + "latn": numLatn, + "lepc": numLepc, + "limb": numLimb, + "mathbold": numMathbold, + "mathdbl": numMathdbl, + "mathmono": numMathmono, + "mathsanb": numMathsanb, + "mathsans": numMathsans, + "mlym": numMlym, + "modi": numModi, + "mong": numMong, + "mroo": numMroo, + "mtei": numMtei, + "mymr": numMymr, + "mymrshan": numMymrshan, + "mymrtlng": numMymrtlng, + "newa": numNewa, + "nkoo": numNkoo, + "olck": numOlck, + "orya": numOrya, + "osma": numOsma, + "roman": numRoman, + "romanlow": numRomanlow, + "saur": numSaur, + "shrd": numShrd, + "sind": numSind, + "sinh": numSinh, + "sora": numSora, + "sund": numSund, + "takr": numTakr, + "talu": numTalu, + "taml": numTaml, + "tamldec": numTamldec, + "telu": numTelu, + "thai": numThai, + "tibt": numTibt, + "tirh": numTirh, + "vaii": numVaii, + "wara": numWara, +} + +var symIndex = [][12]uint8{ // 81 elements + 0: [12]uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb}, + 1: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb}, + 2: [12]uint8{0x0, 0x1, 0x2, 0xd, 0xe, 0xf, 0x6, 0x7, 0x8, 0x9, 0x10, 0xb}, + 3: [12]uint8{0x1, 0x0, 0x2, 0xd, 0xe, 0xf, 0x6, 0x7, 0x8, 0x9, 0x10, 0xb}, + 4: [12]uint8{0x0, 0x1, 0x2, 0x11, 0xe, 0xf, 0x6, 0x7, 0x8, 0x9, 0x10, 0xb}, + 5: [12]uint8{0x1, 0x0, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x12, 0xb}, + 6: [12]uint8{0x1, 0x0, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb}, + 7: [12]uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x13, 0xb}, + 8: [12]uint8{0x0, 0x1, 0x2, 0x3, 0xe, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb}, + 9: [12]uint8{0x1, 0x0, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0x0}, + 10: [12]uint8{0x1, 0x0, 0x2, 0x3, 0x4, 0x5, 0x6, 0x14, 0x8, 0x9, 0xa, 0xb}, + 11: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x14, 0x8, 0x9, 0xa, 0xb}, + 12: [12]uint8{0x0, 0x15, 0x2, 0x3, 0x4, 0x5, 0x6, 0x14, 0x8, 0x9, 0xa, 0xb}, + 13: [12]uint8{0x0, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb}, + 14: [12]uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x16, 0xb}, + 15: [12]uint8{0x1, 0x0, 0x2, 0x3, 0x4, 0x5, 0x17, 0x7, 0x8, 0x9, 0xa, 0xb}, + 16: [12]uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x17, 0x7, 0x8, 0x9, 0xa, 0x0}, + 17: [12]uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x17, 0x7, 0x8, 0x9, 0xa, 0xb}, + 18: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0x0}, + 19: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x18, 0x7, 0x8, 0x9, 0xa, 0xb}, + 20: [12]uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x19, 0x1a, 0xa, 0xb}, + 21: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x1b, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb}, + 22: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x1b, 0x18, 0x7, 0x8, 0x9, 0xa, 0xb}, + 23: [12]uint8{0x1, 0x0, 0x2, 0x3, 0x4, 0x1b, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb}, + 24: [12]uint8{0x0, 0x1, 0x2, 0x3, 0xe, 0x1c, 0x6, 0x7, 0x8, 0x9, 0x1d, 0xb}, + 25: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x1b, 0x6, 0x7, 0x8, 0x9, 0x1e, 0x0}, + 26: [12]uint8{0x0, 0x15, 0x2, 0x3, 0x4, 0x1b, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb}, + 27: [12]uint8{0x0, 0x1, 0x2, 0x3, 0xe, 0xf, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb}, + 28: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x1f, 0xb}, + 29: [12]uint8{0x0, 0x15, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb}, + 30: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x20, 0xb}, + 31: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x21, 0x7, 0x8, 0x9, 0x22, 0xb}, + 32: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x23, 0xb}, + 33: [12]uint8{0x1, 0x0, 0x2, 0x3, 0x4, 0x1b, 0x18, 0x14, 0x8, 0x9, 0x24, 0xb}, + 34: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x1b, 0x18, 0x7, 0x8, 0x9, 0x24, 0xb}, + 35: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x25, 0xb}, + 36: [12]uint8{0x1, 0x0, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x26, 0xb}, + 37: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x27, 0xb}, + 38: [12]uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x28, 0xb}, + 39: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x29, 0xb}, + 40: [12]uint8{0x1, 0x0, 0x2, 0x3, 0xe, 0x1c, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb}, + 41: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x2a, 0xb}, + 42: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x2b, 0xb}, + 43: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x1b, 0x2c, 0x14, 0x8, 0x9, 0x24, 0xb}, + 44: [12]uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0x0}, + 45: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x17, 0x7, 0x8, 0x9, 0xa, 0xb}, + 46: [12]uint8{0x1, 0x0, 0x2, 0x3, 0x4, 0x1b, 0x17, 0x7, 0x8, 0x9, 0xa, 0xb}, + 47: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x2d, 0x0}, + 48: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x2e, 0xb}, + 49: [12]uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x2f, 0xb}, + 50: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x30, 0x7, 0x8, 0x9, 0xa, 0xb}, + 51: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x31, 0xb}, + 52: [12]uint8{0x1, 0xc, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x32, 0xb}, + 53: [12]uint8{0x1, 0x15, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb}, + 54: [12]uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x33, 0xb}, + 55: [12]uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x34, 0xb}, + 56: [12]uint8{0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x7, 0x3c, 0x9, 0xa, 0xb}, + 57: [12]uint8{0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x7, 0x3c, 0x9, 0x3d, 0xb}, + 58: [12]uint8{0x35, 0x36, 0x37, 0x11, 0x3e, 0x3f, 0x3b, 0x7, 0x3c, 0x9, 0xa, 0xb}, + 59: [12]uint8{0x35, 0x36, 0x37, 0x11, 0x39, 0x3a, 0x3b, 0x7, 0x3c, 0x9, 0xa, 0xb}, + 60: [12]uint8{0x35, 0x36, 0x37, 0x11, 0x39, 0x40, 0x3b, 0x7, 0x3c, 0x9, 0xa, 0xb}, + 61: [12]uint8{0x35, 0x36, 0x37, 0x41, 0x3e, 0x3f, 0x3b, 0x7, 0x3c, 0x9, 0xa, 0xb}, + 62: [12]uint8{0x35, 0x36, 0x37, 0x38, 0x3e, 0x3f, 0x3b, 0x7, 0x3c, 0x9, 0xa, 0xb}, + 63: [12]uint8{0x35, 0xc, 0x37, 0x38, 0x39, 0x42, 0x3b, 0x7, 0x3c, 0x9, 0xa, 0x0}, + 64: [12]uint8{0x35, 0xc, 0x37, 0x38, 0x39, 0x42, 0x43, 0x7, 0x44, 0x9, 0x24, 0xb}, + 65: [12]uint8{0x35, 0x36, 0x37, 0x38, 0x39, 0x5, 0x3b, 0x7, 0x3c, 0x9, 0x33, 0xb}, + 66: [12]uint8{0x35, 0x36, 0x37, 0x11, 0x45, 0x46, 0x43, 0x7, 0x3c, 0x9, 0xa, 0x35}, + 67: [12]uint8{0x35, 0x36, 0x37, 0x11, 0xe, 0x1c, 0x43, 0x7, 0x3c, 0x9, 0x1d, 0xb}, + 68: [12]uint8{0x35, 0x36, 0x37, 0x11, 0xe, 0x1c, 0x43, 0x7, 0x3c, 0x9, 0xa, 0x35}, + 69: [12]uint8{0x35, 0x36, 0x37, 0x11, 0x45, 0x5, 0x43, 0x7, 0x3c, 0x9, 0xa, 0x35}, + 70: [12]uint8{0x1, 0xc, 0x37, 0x11, 0x45, 0x47, 0x43, 0x7, 0x3c, 0x9, 0xa, 0x0}, + 71: [12]uint8{0x35, 0x1, 0x37, 0x11, 0x4, 0x5, 0x43, 0x7, 0x3c, 0x9, 0xa, 0x35}, + 72: [12]uint8{0x1, 0xc, 0x37, 0x11, 0x45, 0x47, 0x43, 0x7, 0x3c, 0x9, 0x24, 0xb}, + 73: [12]uint8{0x35, 0x36, 0x2, 0x3, 0x45, 0x46, 0x43, 0x7, 0x8, 0x9, 0xa, 0x35}, + 74: [12]uint8{0x35, 0x36, 0x37, 0x11, 0x4, 0x5, 0x43, 0x7, 0x3c, 0x9, 0x31, 0x35}, + 75: [12]uint8{0x35, 0x36, 0x37, 0x11, 0x4, 0x5, 0x43, 0x7, 0x3c, 0x9, 0x32, 0x35}, + 76: [12]uint8{0x35, 0x36, 0x37, 0x11, 0x48, 0x46, 0x43, 0x7, 0x3c, 0x9, 0x33, 0x35}, + 77: [12]uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0x49}, + 78: [12]uint8{0x0, 0x1, 0x4a, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x28, 0xb}, + 79: [12]uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x4b, 0xb}, + 80: [12]uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x4c, 0x4d, 0xb}, +} // Size: 996 bytes + +var symData = stringset.Set{ + Data: "" + // Size: 599 bytes + ".,;%+-E׉∞NaN:\u00a0\u200e%\u200e\u200e+\u200e-ليس\u00a0رقمًا٪NDТерхьаш" + + "\u00a0дац·’mnne×10^0/00INF−\u200e−ناعددepälukuՈչԹარ\u00a0არის\u00a0რიცხვ" + + "იZMdMсан\u00a0емес¤¤¤сан\u00a0эмесບໍ່\u200bແມ່ນ\u200bໂຕ\u200bເລກNSဂဏန်" + + "းမဟုတ်သောННне\u00a0числочыыһыла\u00a0буотах·10^epilohosan\u00a0dälTFЕs" + + "on\u00a0emasҳақиқий\u00a0сон\u00a0эмас非數值非数值٫٬؛٪\u061c\u061c+\u061c-اس؉ل" + + "يس\u00a0رقم\u200f+\u200f-\u200f−٪\u200f\u061c−×۱۰^؉\u200f\u200e+\u200e" + + "\u200e-\u200e\u200e−\u200e+\u200e:၊ཨང་མེན་གྲངས་མེདཨང་མད", + Index: []uint16{ // 79 elements + // Entry 0 - 3F + 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, + 0x0009, 0x000c, 0x000f, 0x0012, 0x0013, 0x0015, 0x001c, 0x0020, + 0x0024, 0x0036, 0x0038, 0x003a, 0x0050, 0x0052, 0x0055, 0x0058, + 0x0059, 0x005e, 0x0062, 0x0065, 0x0068, 0x006e, 0x0078, 0x0080, + 0x0086, 0x00ae, 0x00af, 0x00b2, 0x00c2, 0x00c8, 0x00d8, 0x0105, + 0x0107, 0x012e, 0x0132, 0x0142, 0x015e, 0x0163, 0x016a, 0x0173, + 0x0175, 0x0177, 0x0180, 0x01a0, 0x01a9, 0x01b2, 0x01b4, 0x01b6, + 0x01b8, 0x01bc, 0x01bf, 0x01c2, 0x01c6, 0x01c8, 0x01d6, 0x01da, + // Entry 40 - 7F + 0x01de, 0x01e4, 0x01e9, 0x01ee, 0x01f5, 0x01fa, 0x0201, 0x0208, + 0x0211, 0x0215, 0x0218, 0x021b, 0x0230, 0x0248, 0x0257, + }, +} // Size: 797 bytes + +// langToDefaults maps a compact language index to the default numbering system +// and default symbol set +var langToDefaults = [775]symOffset{ + // Entry 0 - 3F + 0x8000, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, 0x0000, + 0x0000, 0x0000, 0x8003, 0x0002, 0x0002, 0x0002, 0x0002, 0x0003, + 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, + 0x0003, 0x0003, 0x0003, 0x0003, 0x0002, 0x0002, 0x0002, 0x0004, + 0x0002, 0x0004, 0x0002, 0x0002, 0x0002, 0x0003, 0x0002, 0x0000, + 0x8005, 0x0000, 0x0000, 0x0000, 0x8006, 0x0005, 0x0006, 0x0006, + 0x0006, 0x0006, 0x0006, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, + // Entry 40 - 7F + 0x8009, 0x0000, 0x0000, 0x800a, 0x0000, 0x0000, 0x800c, 0x0001, + 0x0000, 0x0000, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, + 0x0006, 0x0006, 0x0006, 0x0006, 0x800e, 0x0000, 0x0000, 0x0007, + 0x0007, 0x0000, 0x0000, 0x0000, 0x0000, 0x800f, 0x0008, 0x0008, + 0x8011, 0x0001, 0x0001, 0x0001, 0x803c, 0x0000, 0x0009, 0x0009, + 0x0009, 0x0000, 0x0000, 0x000a, 0x000b, 0x000a, 0x000c, 0x000a, + 0x000a, 0x000c, 0x000a, 0x000d, 0x000d, 0x000a, 0x000a, 0x0001, + 0x0001, 0x0000, 0x0001, 0x0001, 0x803f, 0x0000, 0x0000, 0x0000, + // Entry 80 - BF + 0x000e, 0x000e, 0x000e, 0x000f, 0x000f, 0x000f, 0x0000, 0x0000, + 0x0006, 0x0000, 0x0000, 0x0000, 0x000a, 0x0010, 0x0000, 0x0006, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0011, 0x0000, 0x000a, + 0x0000, 0x0000, 0x0000, 0x0000, 0x000a, 0x0000, 0x0009, 0x0000, + 0x0000, 0x0012, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + // Entry C0 - FF + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0006, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0013, 0x0000, + 0x0000, 0x000f, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x0000, 0x0015, + 0x0015, 0x0006, 0x0000, 0x0006, 0x0006, 0x0000, 0x0000, 0x0006, + 0x0006, 0x0001, 0x0000, 0x0000, 0x0006, 0x0006, 0x0006, 0x0006, + // Entry 100 - 13F + 0x0000, 0x0000, 0x0006, 0x0000, 0x0000, 0x0000, 0x0000, 0x0006, + 0x0000, 0x0006, 0x0000, 0x0000, 0x0006, 0x0006, 0x0016, 0x0016, + 0x0017, 0x0017, 0x0001, 0x0001, 0x8041, 0x0018, 0x0018, 0x0001, + 0x0001, 0x0001, 0x0001, 0x0001, 0x0019, 0x0019, 0x0000, 0x0000, + 0x0017, 0x0017, 0x0017, 0x8044, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0006, 0x0006, 0x0001, 0x0001, 0x0001, 0x0001, + // Entry 140 - 17F + 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0006, 0x0006, 0x0006, 0x0006, 0x0000, 0x0000, + 0x8047, 0x0000, 0x0006, 0x0006, 0x001a, 0x001a, 0x001a, 0x001a, + 0x804a, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x804c, 0x001b, 0x0000, + 0x0000, 0x0006, 0x0006, 0x0006, 0x000a, 0x000a, 0x0001, 0x0001, + 0x001c, 0x001c, 0x0009, 0x0009, 0x804f, 0x0000, 0x0000, 0x0000, + // Entry 180 - 1BF + 0x0000, 0x0000, 0x8052, 0x0006, 0x0006, 0x001d, 0x0006, 0x0006, + 0x0006, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0006, 0x0006, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x001e, 0x001e, 0x001f, + 0x001f, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, + 0x0001, 0x000d, 0x000d, 0x0000, 0x0000, 0x0020, 0x0020, 0x0006, + 0x0006, 0x0021, 0x0021, 0x0000, 0x0000, 0x0006, 0x0006, 0x0000, + 0x0000, 0x8054, 0x0000, 0x0000, 0x0000, 0x0000, 0x8056, 0x001b, + 0x0000, 0x0000, 0x0001, 0x0001, 0x0022, 0x0022, 0x0000, 0x0000, + // Entry 1C0 - 1FF + 0x0000, 0x0023, 0x0023, 0x0000, 0x0000, 0x0006, 0x0006, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, + 0x0024, 0x0024, 0x8058, 0x0000, 0x0000, 0x0016, 0x0016, 0x0006, + 0x0006, 0x0000, 0x0000, 0x0000, 0x0000, 0x0025, 0x0025, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x000d, 0x000d, 0x0000, 0x0000, + 0x0006, 0x0006, 0x0000, 0x0000, 0x0006, 0x0006, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x805a, 0x0000, 0x0000, 0x0006, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0006, 0x0006, 0x805b, 0x0026, 0x805d, + // Entry 200 - 23F + 0x0000, 0x0000, 0x0000, 0x0000, 0x805e, 0x0015, 0x0015, 0x0000, + 0x0000, 0x0006, 0x0006, 0x0006, 0x8061, 0x0000, 0x0000, 0x8062, + 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0001, + 0x0001, 0x0015, 0x0015, 0x0006, 0x0006, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0027, 0x0027, 0x0027, 0x8065, 0x8067, + 0x001b, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001, 0x0001, 0x0001, + 0x8069, 0x0028, 0x0006, 0x0001, 0x0006, 0x0001, 0x0001, 0x0001, + // Entry 240 - 27F + 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, + 0x0006, 0x0000, 0x0000, 0x001a, 0x001a, 0x0006, 0x0006, 0x0006, + 0x0006, 0x0006, 0x0000, 0x0000, 0x0029, 0x0029, 0x0029, 0x0029, + 0x0029, 0x0029, 0x0029, 0x0006, 0x0006, 0x0000, 0x0000, 0x002a, + 0x002a, 0x0000, 0x0000, 0x0000, 0x0000, 0x806b, 0x0000, 0x0000, + 0x002b, 0x002b, 0x002b, 0x002b, 0x0006, 0x0006, 0x000d, 0x000d, + 0x0006, 0x0006, 0x0000, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x002c, 0x002c, 0x002d, 0x002d, 0x002e, 0x002e, 0x0000, 0x0000, + // Entry 280 - 2BF + 0x0000, 0x002f, 0x002f, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0001, 0x0001, 0x0001, 0x0001, 0x0006, + 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, + 0x0006, 0x0006, 0x0000, 0x0000, 0x0000, 0x806d, 0x0022, 0x0022, + 0x0022, 0x0000, 0x0006, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0030, 0x0030, 0x0000, 0x0000, 0x8071, 0x0031, 0x0006, + // Entry 2C0 - 2FF + 0x0006, 0x0006, 0x0000, 0x0001, 0x0001, 0x000d, 0x000d, 0x0001, + 0x0001, 0x0000, 0x0000, 0x0032, 0x0032, 0x8074, 0x8076, 0x001b, + 0x8077, 0x8079, 0x0028, 0x807b, 0x0034, 0x0033, 0x0033, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0006, 0x0006, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0035, 0x0035, 0x0006, 0x0006, + 0x0000, 0x0000, 0x0000, 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0036, 0x0037, 0x0037, 0x0036, 0x0036, 0x0001, + 0x0001, 0x807d, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x8080, + // Entry 300 - 33F + 0x0036, 0x0036, 0x0036, 0x0000, 0x0000, 0x0006, 0x0014, +} // Size: 1550 bytes + +// langToAlt is a list of numbering system and symbol set pairs, sorted and +// marked by compact language index. +var langToAlt = []altSymData{ // 131 elements + 1: {compactTag: 0x0, symIndex: 0x38, system: 0x3}, + 2: {compactTag: 0x0, symIndex: 0x42, system: 0x4}, + 3: {compactTag: 0xa, symIndex: 0x39, system: 0x3}, + 4: {compactTag: 0xa, symIndex: 0x2, system: 0x0}, + 5: {compactTag: 0x28, symIndex: 0x0, system: 0x6}, + 6: {compactTag: 0x2c, symIndex: 0x5, system: 0x0}, + 7: {compactTag: 0x2c, symIndex: 0x3a, system: 0x3}, + 8: {compactTag: 0x2c, symIndex: 0x42, system: 0x4}, + 9: {compactTag: 0x40, symIndex: 0x0, system: 0x6}, + 10: {compactTag: 0x43, symIndex: 0x0, system: 0x0}, + 11: {compactTag: 0x43, symIndex: 0x4f, system: 0x37}, + 12: {compactTag: 0x46, symIndex: 0x1, system: 0x0}, + 13: {compactTag: 0x46, symIndex: 0x38, system: 0x3}, + 14: {compactTag: 0x54, symIndex: 0x0, system: 0x9}, + 15: {compactTag: 0x5d, symIndex: 0x3a, system: 0x3}, + 16: {compactTag: 0x5d, symIndex: 0x8, system: 0x0}, + 17: {compactTag: 0x60, symIndex: 0x1, system: 0x0}, + 18: {compactTag: 0x60, symIndex: 0x38, system: 0x3}, + 19: {compactTag: 0x60, symIndex: 0x42, system: 0x4}, + 20: {compactTag: 0x60, symIndex: 0x0, system: 0x5}, + 21: {compactTag: 0x60, symIndex: 0x0, system: 0x6}, + 22: {compactTag: 0x60, symIndex: 0x0, system: 0x8}, + 23: {compactTag: 0x60, symIndex: 0x0, system: 0x9}, + 24: {compactTag: 0x60, symIndex: 0x0, system: 0xa}, + 25: {compactTag: 0x60, symIndex: 0x0, system: 0xb}, + 26: {compactTag: 0x60, symIndex: 0x0, system: 0xc}, + 27: {compactTag: 0x60, symIndex: 0x0, system: 0xd}, + 28: {compactTag: 0x60, symIndex: 0x0, system: 0xe}, + 29: {compactTag: 0x60, symIndex: 0x0, system: 0xf}, + 30: {compactTag: 0x60, symIndex: 0x0, system: 0x11}, + 31: {compactTag: 0x60, symIndex: 0x0, system: 0x12}, + 32: {compactTag: 0x60, symIndex: 0x0, system: 0x13}, + 33: {compactTag: 0x60, symIndex: 0x0, system: 0x14}, + 34: {compactTag: 0x60, symIndex: 0x0, system: 0x15}, + 35: {compactTag: 0x60, symIndex: 0x0, system: 0x16}, + 36: {compactTag: 0x60, symIndex: 0x0, system: 0x17}, + 37: {compactTag: 0x60, symIndex: 0x0, system: 0x18}, + 38: {compactTag: 0x60, symIndex: 0x0, system: 0x19}, + 39: {compactTag: 0x60, symIndex: 0x0, system: 0x1f}, + 40: {compactTag: 0x60, symIndex: 0x0, system: 0x21}, + 41: {compactTag: 0x60, symIndex: 0x0, system: 0x23}, + 42: {compactTag: 0x60, symIndex: 0x0, system: 0x24}, + 43: {compactTag: 0x60, symIndex: 0x0, system: 0x25}, + 44: {compactTag: 0x60, symIndex: 0x0, system: 0x28}, + 45: {compactTag: 0x60, symIndex: 0x0, system: 0x29}, + 46: {compactTag: 0x60, symIndex: 0x0, system: 0x2a}, + 47: {compactTag: 0x60, symIndex: 0x0, system: 0x2b}, + 48: {compactTag: 0x60, symIndex: 0x0, system: 0x2c}, + 49: {compactTag: 0x60, symIndex: 0x0, system: 0x2d}, + 50: {compactTag: 0x60, symIndex: 0x0, system: 0x30}, + 51: {compactTag: 0x60, symIndex: 0x0, system: 0x31}, + 52: {compactTag: 0x60, symIndex: 0x0, system: 0x32}, + 53: {compactTag: 0x60, symIndex: 0x0, system: 0x33}, + 54: {compactTag: 0x60, symIndex: 0x0, system: 0x34}, + 55: {compactTag: 0x60, symIndex: 0x0, system: 0x35}, + 56: {compactTag: 0x60, symIndex: 0x0, system: 0x36}, + 57: {compactTag: 0x60, symIndex: 0x0, system: 0x37}, + 58: {compactTag: 0x60, symIndex: 0x0, system: 0x39}, + 59: {compactTag: 0x60, symIndex: 0x0, system: 0x43}, + 60: {compactTag: 0x64, symIndex: 0x0, system: 0x0}, + 61: {compactTag: 0x64, symIndex: 0x38, system: 0x3}, + 62: {compactTag: 0x64, symIndex: 0x42, system: 0x4}, + 63: {compactTag: 0x7c, symIndex: 0x50, system: 0x37}, + 64: {compactTag: 0x7c, symIndex: 0x0, system: 0x0}, + 65: {compactTag: 0x114, symIndex: 0x43, system: 0x4}, + 66: {compactTag: 0x114, symIndex: 0x18, system: 0x0}, + 67: {compactTag: 0x114, symIndex: 0x3b, system: 0x3}, + 68: {compactTag: 0x123, symIndex: 0x1, system: 0x0}, + 69: {compactTag: 0x123, symIndex: 0x3c, system: 0x3}, + 70: {compactTag: 0x123, symIndex: 0x44, system: 0x4}, + 71: {compactTag: 0x158, symIndex: 0x0, system: 0x0}, + 72: {compactTag: 0x158, symIndex: 0x3b, system: 0x3}, + 73: {compactTag: 0x158, symIndex: 0x45, system: 0x4}, + 74: {compactTag: 0x160, symIndex: 0x0, system: 0x0}, + 75: {compactTag: 0x160, symIndex: 0x38, system: 0x3}, + 76: {compactTag: 0x16d, symIndex: 0x1b, system: 0x0}, + 77: {compactTag: 0x16d, symIndex: 0x0, system: 0x9}, + 78: {compactTag: 0x16d, symIndex: 0x0, system: 0xa}, + 79: {compactTag: 0x17c, symIndex: 0x0, system: 0x0}, + 80: {compactTag: 0x17c, symIndex: 0x3d, system: 0x3}, + 81: {compactTag: 0x17c, symIndex: 0x42, system: 0x4}, + 82: {compactTag: 0x182, symIndex: 0x6, system: 0x0}, + 83: {compactTag: 0x182, symIndex: 0x38, system: 0x3}, + 84: {compactTag: 0x1b1, symIndex: 0x0, system: 0x0}, + 85: {compactTag: 0x1b1, symIndex: 0x3e, system: 0x3}, + 86: {compactTag: 0x1b6, symIndex: 0x42, system: 0x4}, + 87: {compactTag: 0x1b6, symIndex: 0x1b, system: 0x0}, + 88: {compactTag: 0x1d2, symIndex: 0x42, system: 0x4}, + 89: {compactTag: 0x1d2, symIndex: 0x0, system: 0x0}, + 90: {compactTag: 0x1f3, symIndex: 0x0, system: 0xb}, + 91: {compactTag: 0x1fd, symIndex: 0x4e, system: 0x24}, + 92: {compactTag: 0x1fd, symIndex: 0x26, system: 0x0}, + 93: {compactTag: 0x1ff, symIndex: 0x42, system: 0x4}, + 94: {compactTag: 0x204, symIndex: 0x15, system: 0x0}, + 95: {compactTag: 0x204, symIndex: 0x3f, system: 0x3}, + 96: {compactTag: 0x204, symIndex: 0x46, system: 0x4}, + 97: {compactTag: 0x20c, symIndex: 0x0, system: 0xb}, + 98: {compactTag: 0x20f, symIndex: 0x6, system: 0x0}, + 99: {compactTag: 0x20f, symIndex: 0x38, system: 0x3}, + 100: {compactTag: 0x20f, symIndex: 0x42, system: 0x4}, + 101: {compactTag: 0x22e, symIndex: 0x0, system: 0x0}, + 102: {compactTag: 0x22e, symIndex: 0x47, system: 0x4}, + 103: {compactTag: 0x22f, symIndex: 0x42, system: 0x4}, + 104: {compactTag: 0x22f, symIndex: 0x1b, system: 0x0}, + 105: {compactTag: 0x238, symIndex: 0x42, system: 0x4}, + 106: {compactTag: 0x238, symIndex: 0x28, system: 0x0}, + 107: {compactTag: 0x265, symIndex: 0x38, system: 0x3}, + 108: {compactTag: 0x265, symIndex: 0x0, system: 0x0}, + 109: {compactTag: 0x29d, symIndex: 0x22, system: 0x0}, + 110: {compactTag: 0x29d, symIndex: 0x40, system: 0x3}, + 111: {compactTag: 0x29d, symIndex: 0x48, system: 0x4}, + 112: {compactTag: 0x29d, symIndex: 0x4d, system: 0xc}, + 113: {compactTag: 0x2bd, symIndex: 0x31, system: 0x0}, + 114: {compactTag: 0x2bd, symIndex: 0x3e, system: 0x3}, + 115: {compactTag: 0x2bd, symIndex: 0x42, system: 0x4}, + 116: {compactTag: 0x2cd, symIndex: 0x1b, system: 0x0}, + 117: {compactTag: 0x2cd, symIndex: 0x49, system: 0x4}, + 118: {compactTag: 0x2ce, symIndex: 0x49, system: 0x4}, + 119: {compactTag: 0x2d0, symIndex: 0x33, system: 0x0}, + 120: {compactTag: 0x2d0, symIndex: 0x4a, system: 0x4}, + 121: {compactTag: 0x2d1, symIndex: 0x42, system: 0x4}, + 122: {compactTag: 0x2d1, symIndex: 0x28, system: 0x0}, + 123: {compactTag: 0x2d3, symIndex: 0x34, system: 0x0}, + 124: {compactTag: 0x2d3, symIndex: 0x4b, system: 0x4}, + 125: {compactTag: 0x2f9, symIndex: 0x0, system: 0x0}, + 126: {compactTag: 0x2f9, symIndex: 0x38, system: 0x3}, + 127: {compactTag: 0x2f9, symIndex: 0x42, system: 0x4}, + 128: {compactTag: 0x2ff, symIndex: 0x36, system: 0x0}, + 129: {compactTag: 0x2ff, symIndex: 0x41, system: 0x3}, + 130: {compactTag: 0x2ff, symIndex: 0x4c, system: 0x4}, +} // Size: 810 bytes + +var tagToDecimal = []uint8{ // 775 elements + // Entry 0 - 3F + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x05, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + // Entry 40 - 7F + 0x05, 0x05, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x05, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x05, 0x05, 0x05, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x05, 0x05, 0x01, 0x01, + // Entry 80 - BF + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + // Entry C0 - FF + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + // Entry 100 - 13F + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + // Entry 140 - 17F + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x05, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x05, + 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + // Entry 180 - 1BF + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x05, 0x05, 0x05, 0x05, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + // Entry 1C0 - 1FF + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x05, 0x05, + 0x01, 0x01, 0x01, 0x05, 0x05, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + // Entry 200 - 23F + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x05, 0x05, 0x01, 0x01, 0x01, 0x05, 0x01, + 0x01, 0x05, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + // Entry 240 - 27F + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + // Entry 280 - 2BF + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x05, + 0x05, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + // Entry 2C0 - 2FF + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + // Entry 300 - 33F + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, +} // Size: 799 bytes + +var tagToScientific = []uint8{ // 775 elements + // Entry 0 - 3F + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + // Entry 40 - 7F + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + // Entry 80 - BF + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + // Entry C0 - FF + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + // Entry 100 - 13F + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + // Entry 140 - 17F + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x0c, 0x0c, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x0c, + 0x0c, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + // Entry 180 - 1BF + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + // Entry 1C0 - 1FF + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x0d, 0x0d, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x0c, 0x0c, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + // Entry 200 - 23F + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x0c, 0x02, + 0x02, 0x0c, 0x0c, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + // Entry 240 - 27F + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x0d, 0x0d, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + // Entry 280 - 2BF + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + // Entry 2C0 - 2FF + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + // Entry 300 - 33F + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x09, +} // Size: 799 bytes + +var tagToPercent = []uint8{ // 775 elements + // Entry 0 - 3F + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x06, 0x06, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x03, 0x03, 0x03, 0x03, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + // Entry 40 - 7F + 0x06, 0x06, 0x06, 0x04, 0x04, 0x04, 0x03, 0x03, + 0x06, 0x06, 0x03, 0x04, 0x04, 0x03, 0x03, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x06, 0x06, 0x06, 0x03, + 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x03, 0x03, + 0x03, 0x04, 0x04, 0x03, 0x03, 0x03, 0x04, 0x03, + 0x03, 0x04, 0x03, 0x04, 0x04, 0x03, 0x03, 0x03, + 0x03, 0x04, 0x04, 0x04, 0x07, 0x07, 0x04, 0x04, + // Entry 80 - BF + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x03, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x03, 0x04, 0x03, 0x04, + 0x04, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x06, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + // Entry C0 - FF + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x03, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + // Entry 100 - 13F + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, + 0x0b, 0x0b, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x03, 0x03, 0x04, 0x04, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x04, 0x03, 0x03, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + // Entry 140 - 17F + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + 0x06, 0x06, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x06, + 0x06, 0x04, 0x04, 0x04, 0x03, 0x03, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + // Entry 180 - 1BF + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x06, 0x06, 0x06, 0x06, + 0x04, 0x04, 0x04, 0x04, 0x03, 0x03, 0x04, 0x04, + // Entry 1C0 - 1FF + 0x04, 0x04, 0x04, 0x04, 0x04, 0x03, 0x03, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x03, 0x03, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + // Entry 200 - 23F + 0x04, 0x04, 0x04, 0x04, 0x03, 0x03, 0x03, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x06, 0x06, 0x04, 0x04, 0x04, 0x06, 0x04, + 0x04, 0x06, 0x06, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + // Entry 240 - 27F + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x03, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + 0x03, 0x03, 0x04, 0x04, 0x03, 0x03, 0x03, 0x03, + 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, + // Entry 280 - 2BF + 0x04, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x03, 0x03, 0x03, + 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x06, + 0x06, 0x06, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x0e, + // Entry 2C0 - 2FF + 0x0e, 0x0e, 0x04, 0x03, 0x03, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x03, + 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + // Entry 300 - 33F + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0a, +} // Size: 799 bytes + +var formats = []Pattern{Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 0, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x0, + MinIntegerDigits: 0x0, + MaxIntegerDigits: 0x0, + MinFractionDigits: 0x0, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x0}, + Affix: "", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0x0, + GroupingSize: [2]uint8{0x0, + 0x0}, + Flags: 0x0}, + Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 3, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x0, + MinIntegerDigits: 0x1, + MaxIntegerDigits: 0x0, + MinFractionDigits: 0x0, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x0}, + Affix: "", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0x9, + GroupingSize: [2]uint8{0x3, + 0x0}, + Flags: 0x0}, + Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 0, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x0, + MinIntegerDigits: 0x0, + MaxIntegerDigits: 0x1, + MinFractionDigits: 0x0, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x1}, + Affix: "", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0x3, + GroupingSize: [2]uint8{0x0, + 0x0}, + Flags: 0x0}, + Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 0, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x2, + MinIntegerDigits: 0x1, + MaxIntegerDigits: 0x0, + MinFractionDigits: 0x0, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x0}, + Affix: "\x00\x03\u00a0%", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0x7, + GroupingSize: [2]uint8{0x3, + 0x0}, + Flags: 0x0}, + Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 0, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x2, + MinIntegerDigits: 0x1, + MaxIntegerDigits: 0x0, + MinFractionDigits: 0x0, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x0}, + Affix: "\x00\x01%", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0x6, + GroupingSize: [2]uint8{0x3, + 0x0}, + Flags: 0x0}, + Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 3, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x0, + MinIntegerDigits: 0x1, + MaxIntegerDigits: 0x0, + MinFractionDigits: 0x0, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x0}, + Affix: "", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0xc, + GroupingSize: [2]uint8{0x3, + 0x2}, + Flags: 0x0}, + Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 0, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x2, + MinIntegerDigits: 0x1, + MaxIntegerDigits: 0x0, + MinFractionDigits: 0x0, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x0}, + Affix: "\x00\x01%", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0x9, + GroupingSize: [2]uint8{0x3, + 0x2}, + Flags: 0x0}, + Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 0, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x2, + MinIntegerDigits: 0x1, + MaxIntegerDigits: 0x0, + MinFractionDigits: 0x0, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x0}, + Affix: "\x00\x03\u00a0%", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0xa, + GroupingSize: [2]uint8{0x3, + 0x2}, + Flags: 0x0}, + Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 6, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x0, + MinIntegerDigits: 0x1, + MaxIntegerDigits: 0x0, + MinFractionDigits: 0x0, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x0}, + Affix: "", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0x8, + GroupingSize: [2]uint8{0x0, + 0x0}, + Flags: 0x0}, + Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 6, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x0, + MinIntegerDigits: 0x1, + MaxIntegerDigits: 0x0, + MinFractionDigits: 0x6, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x3}, + Affix: "", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0xd, + GroupingSize: [2]uint8{0x0, + 0x0}, + Flags: 0x4}, + Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 0, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x2, + MinIntegerDigits: 0x1, + MaxIntegerDigits: 0x0, + MinFractionDigits: 0x0, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x0}, + Affix: "\x00\x01%", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0x2, + GroupingSize: [2]uint8{0x0, + 0x0}, + Flags: 0x0}, + Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 0, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x2, + MinIntegerDigits: 0x1, + MaxIntegerDigits: 0x0, + MinFractionDigits: 0x0, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x0}, + Affix: "\x03%\u00a0\x00", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0x7, + GroupingSize: [2]uint8{0x3, + 0x0}, + Flags: 0x0}, + Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 0, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x0, + MinIntegerDigits: 0x0, + MaxIntegerDigits: 0x1, + MinFractionDigits: 0x0, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x1}, + Affix: "\x01[\x01]", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0x5, + GroupingSize: [2]uint8{0x0, + 0x0}, + Flags: 0x0}, + Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 0, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x0, + MinIntegerDigits: 0x0, + MaxIntegerDigits: 0x0, + MinFractionDigits: 0x0, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x0}, + Affix: "", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0x1, + GroupingSize: [2]uint8{0x0, + 0x0}, + Flags: 0x0}, + Pattern{RoundingContext: RoundingContext{MaxSignificantDigits: 0, + MaxFractionDigits: 0, + Increment: 0x0, + IncrementScale: 0x0, + Mode: 0x0, + DigitShift: 0x2, + MinIntegerDigits: 0x1, + MaxIntegerDigits: 0x0, + MinFractionDigits: 0x0, + MinSignificantDigits: 0x0, + MinExponentDigits: 0x0}, + Affix: "\x01%\x00", + Offset: 0x0, + NegOffset: 0x0, + PadRune: 0, + FormatWidth: 0x6, + GroupingSize: [2]uint8{0x3, + 0x0}, + Flags: 0x0}} + +// Total table size 8634 bytes (8KiB); checksum: 8F23386D diff --git a/vendor/golang.org/x/text/internal/stringset/set.go b/vendor/golang.org/x/text/internal/stringset/set.go new file mode 100644 index 00000000..bb2fffbc --- /dev/null +++ b/vendor/golang.org/x/text/internal/stringset/set.go @@ -0,0 +1,86 @@ +// Copyright 2016 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 stringset provides a way to represent a collection of strings +// compactly. +package stringset + +import "sort" + +// A Set holds a collection of strings that can be looked up by an index number. +type Set struct { + // These fields are exported to allow for code generation. + + Data string + Index []uint16 +} + +// Elem returns the string with index i. It panics if i is out of range. +func (s *Set) Elem(i int) string { + return s.Data[s.Index[i]:s.Index[i+1]] +} + +// Len returns the number of strings in the set. +func (s *Set) Len() int { + return len(s.Index) - 1 +} + +// Search returns the index of the given string or -1 if it is not in the set. +// The Set must have been created with strings in sorted order. +func Search(s *Set, str string) int { + // TODO: optimize this if it gets used a lot. + n := len(s.Index) - 1 + p := sort.Search(n, func(i int) bool { + return s.Elem(i) >= str + }) + if p == n || str != s.Elem(p) { + return -1 + } + return p +} + +// A Builder constructs Sets. +type Builder struct { + set Set + index map[string]int +} + +// NewBuilder returns a new and initialized Builder. +func NewBuilder() *Builder { + return &Builder{ + set: Set{ + Index: []uint16{0}, + }, + index: map[string]int{}, + } +} + +// Set creates the set created so far. +func (b *Builder) Set() Set { + return b.set +} + +// Index returns the index for the given string, which must have been added +// before. +func (b *Builder) Index(s string) int { + return b.index[s] +} + +// Add adds a string to the index. Strings that are added by a single Add will +// be stored together, unless they match an existing string. +func (b *Builder) Add(ss ...string) { + // First check if the string already exists. + for _, s := range ss { + if _, ok := b.index[s]; ok { + continue + } + b.index[s] = len(b.set.Index) - 1 + b.set.Data += s + x := len(b.set.Data) + if x > 0xFFFF { + panic("Index too > 0xFFFF") + } + b.set.Index = append(b.set.Index, uint16(x)) + } +} diff --git a/vendor/golang.org/x/text/message/catalog.go b/vendor/golang.org/x/text/message/catalog.go new file mode 100644 index 00000000..068271de --- /dev/null +++ b/vendor/golang.org/x/text/message/catalog.go @@ -0,0 +1,36 @@ +// Copyright 2015 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 message + +// TODO: some types in this file will need to be made public at some time. +// Documentation and method names will reflect this by using the exported name. + +import ( + "golang.org/x/text/language" + "golang.org/x/text/message/catalog" +) + +// MatchLanguage reports the matched tag obtained from language.MatchStrings for +// the Matcher of the DefaultCatalog. +func MatchLanguage(preferred ...string) language.Tag { + c := DefaultCatalog + tag, _ := language.MatchStrings(c.Matcher(), preferred...) + return tag +} + +// DefaultCatalog is used by SetString. +var DefaultCatalog catalog.Catalog = defaultCatalog + +var defaultCatalog = catalog.NewBuilder() + +// SetString calls SetString on the initial default Catalog. +func SetString(tag language.Tag, key string, msg string) error { + return defaultCatalog.SetString(tag, key, msg) +} + +// Set calls Set on the initial default Catalog. +func Set(tag language.Tag, key string, msg ...catalog.Message) error { + return defaultCatalog.Set(tag, key, msg...) +} diff --git a/vendor/golang.org/x/text/message/catalog/catalog.go b/vendor/golang.org/x/text/message/catalog/catalog.go new file mode 100644 index 00000000..96955d07 --- /dev/null +++ b/vendor/golang.org/x/text/message/catalog/catalog.go @@ -0,0 +1,365 @@ +// Copyright 2017 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 catalog defines collections of translated format strings. +// +// This package mostly defines types for populating catalogs with messages. The +// catmsg package contains further definitions for creating custom message and +// dictionary types as well as packages that use Catalogs. +// +// Package catalog defines various interfaces: Dictionary, Loader, and Message. +// A Dictionary maintains a set of translations of format strings for a single +// language. The Loader interface defines a source of dictionaries. A +// translation of a format string is represented by a Message. +// +// # Catalogs +// +// A Catalog defines a programmatic interface for setting message translations. +// It maintains a set of per-language dictionaries with translations for a set +// of keys. For message translation to function properly, a translation should +// be defined for each key for each supported language. A dictionary may be +// underspecified, though, if there is a parent language that already defines +// the key. For example, a Dictionary for "en-GB" could leave out entries that +// are identical to those in a dictionary for "en". +// +// # Messages +// +// A Message is a format string which varies on the value of substitution +// variables. For instance, to indicate the number of results one could want "no +// results" if there are none, "1 result" if there is 1, and "%d results" for +// any other number. Catalog is agnostic to the kind of format strings that are +// used: for instance, messages can follow either the printf-style substitution +// from package fmt or use templates. +// +// A Message does not substitute arguments in the format string. This job is +// reserved for packages that render strings, such as message, that use Catalogs +// to selected string. This separation of concerns allows Catalog to be used to +// store any kind of formatting strings. +// +// # Selecting messages based on linguistic features of substitution arguments +// +// Messages may vary based on any linguistic features of the argument values. +// The most common one is plural form, but others exist. +// +// Selection messages are provided in packages that provide support for a +// specific linguistic feature. The following snippet uses plural.Selectf: +// +// catalog.Set(language.English, "You are %d minute(s) late.", +// plural.Selectf(1, "", +// plural.One, "You are 1 minute late.", +// plural.Other, "You are %d minutes late.")) +// +// In this example, a message is stored in the Catalog where one of two messages +// is selected based on the first argument, a number. The first message is +// selected if the argument is singular (identified by the selector "one") and +// the second message is selected in all other cases. The selectors are defined +// by the plural rules defined in CLDR. The selector "other" is special and will +// always match. Each language always defines one of the linguistic categories +// to be "other." For English, singular is "one" and plural is "other". +// +// Selects can be nested. This allows selecting sentences based on features of +// multiple arguments or multiple linguistic properties of a single argument. +// +// # String interpolation +// +// There is often a lot of commonality between the possible variants of a +// message. For instance, in the example above the word "minute" varies based on +// the plural catogory of the argument, but the rest of the sentence is +// identical. Using interpolation the above message can be rewritten as: +// +// catalog.Set(language.English, "You are %d minute(s) late.", +// catalog.Var("minutes", +// plural.Selectf(1, "", plural.One, "minute", plural.Other, "minutes")), +// catalog.String("You are %[1]d ${minutes} late.")) +// +// Var is defined to return the variable name if the message does not yield a +// match. This allows us to further simplify this snippet to +// +// catalog.Set(language.English, "You are %d minute(s) late.", +// catalog.Var("minutes", plural.Selectf(1, "", plural.One, "minute")), +// catalog.String("You are %d ${minutes} late.")) +// +// Overall this is still only a minor improvement, but things can get a lot more +// unwieldy if more than one linguistic feature is used to determine a message +// variant. Consider the following example: +// +// // argument 1: list of hosts, argument 2: list of guests +// catalog.Set(language.English, "%[1]v invite(s) %[2]v to their party.", +// catalog.Var("their", +// plural.Selectf(1, "" +// plural.One, gender.Select(1, "female", "her", "other", "his"))), +// catalog.Var("invites", plural.Selectf(1, "", plural.One, "invite")) +// catalog.String("%[1]v ${invites} %[2]v to ${their} party.")), +// +// Without variable substitution, this would have to be written as +// +// // argument 1: list of hosts, argument 2: list of guests +// catalog.Set(language.English, "%[1]v invite(s) %[2]v to their party.", +// plural.Selectf(1, "", +// plural.One, gender.Select(1, +// "female", "%[1]v invites %[2]v to her party." +// "other", "%[1]v invites %[2]v to his party."), +// plural.Other, "%[1]v invites %[2]v to their party.")) +// +// Not necessarily shorter, but using variables there is less duplication and +// the messages are more maintenance friendly. Moreover, languages may have up +// to six plural forms. This makes the use of variables more welcome. +// +// Different messages using the same inflections can reuse variables by moving +// them to macros. Using macros we can rewrite the message as: +// +// // argument 1: list of hosts, argument 2: list of guests +// catalog.SetString(language.English, "%[1]v invite(s) %[2]v to their party.", +// "%[1]v ${invites(1)} %[2]v to ${their(1)} party.") +// +// Where the following macros were defined separately. +// +// catalog.SetMacro(language.English, "invites", plural.Selectf(1, "", +// plural.One, "invite")) +// catalog.SetMacro(language.English, "their", plural.Selectf(1, "", +// plural.One, gender.Select(1, "female", "her", "other", "his"))), +// +// Placeholders use parentheses and the arguments to invoke a macro. +// +// # Looking up messages +// +// Message lookup using Catalogs is typically only done by specialized packages +// and is not something the user should be concerned with. For instance, to +// express the tardiness of a user using the related message we defined earlier, +// the user may use the package message like so: +// +// p := message.NewPrinter(language.English) +// p.Printf("You are %d minute(s) late.", 5) +// +// Which would print: +// +// You are 5 minutes late. +// +// This package is UNDER CONSTRUCTION and its API may change. +package catalog // import "golang.org/x/text/message/catalog" + +// TODO: +// Some way to freeze a catalog. +// - Locking on each lockup turns out to be about 50% of the total running time +// for some of the benchmarks in the message package. +// Consider these: +// - Sequence type to support sequences in user-defined messages. +// - Garbage collection: Remove dictionaries that can no longer be reached +// as other dictionaries have been added that cover all possible keys. + +import ( + "errors" + "fmt" + + "golang.org/x/text/internal" + + "golang.org/x/text/internal/catmsg" + "golang.org/x/text/language" +) + +// A Catalog allows lookup of translated messages. +type Catalog interface { + // Languages returns all languages for which the Catalog contains variants. + Languages() []language.Tag + + // Matcher returns a Matcher for languages from this Catalog. + Matcher() language.Matcher + + // A Context is used for evaluating Messages. + Context(tag language.Tag, r catmsg.Renderer) *Context + + // This method also makes Catalog a private interface. + lookup(tag language.Tag, key string) (data string, ok bool) +} + +// NewFromMap creates a Catalog from the given map. If a Dictionary is +// underspecified the entry is retrieved from a parent language. +func NewFromMap(dictionaries map[string]Dictionary, opts ...Option) (Catalog, error) { + options := options{} + for _, o := range opts { + o(&options) + } + c := &catalog{ + dicts: map[language.Tag]Dictionary{}, + } + _, hasFallback := dictionaries[options.fallback.String()] + if hasFallback { + // TODO: Should it be okay to not have a fallback language? + // Catalog generators could enforce there is always a fallback. + c.langs = append(c.langs, options.fallback) + } + for lang, dict := range dictionaries { + tag, err := language.Parse(lang) + if err != nil { + return nil, fmt.Errorf("catalog: invalid language tag %q", lang) + } + if _, ok := c.dicts[tag]; ok { + return nil, fmt.Errorf("catalog: duplicate entry for tag %q after normalization", tag) + } + c.dicts[tag] = dict + if !hasFallback || tag != options.fallback { + c.langs = append(c.langs, tag) + } + } + if hasFallback { + internal.SortTags(c.langs[1:]) + } else { + internal.SortTags(c.langs) + } + c.matcher = language.NewMatcher(c.langs) + return c, nil +} + +// A Dictionary is a source of translations for a single language. +type Dictionary interface { + // Lookup returns a message compiled with catmsg.Compile for the given key. + // It returns false for ok if such a message could not be found. + Lookup(key string) (data string, ok bool) +} + +type catalog struct { + langs []language.Tag + dicts map[language.Tag]Dictionary + macros store + matcher language.Matcher +} + +func (c *catalog) Languages() []language.Tag { return c.langs } +func (c *catalog) Matcher() language.Matcher { return c.matcher } + +func (c *catalog) lookup(tag language.Tag, key string) (data string, ok bool) { + for ; ; tag = tag.Parent() { + if dict, ok := c.dicts[tag]; ok { + if data, ok := dict.Lookup(key); ok { + return data, true + } + } + if tag == language.Und { + break + } + } + return "", false +} + +// Context returns a Context for formatting messages. +// Only one Message may be formatted per context at any given time. +func (c *catalog) Context(tag language.Tag, r catmsg.Renderer) *Context { + return &Context{ + cat: c, + tag: tag, + dec: catmsg.NewDecoder(tag, r, &dict{&c.macros, tag}), + } +} + +// A Builder allows building a Catalog programmatically. +type Builder struct { + options + matcher language.Matcher + + index store + macros store +} + +type options struct { + fallback language.Tag +} + +// An Option configures Catalog behavior. +type Option func(*options) + +// Fallback specifies the default fallback language. The default is Und. +func Fallback(tag language.Tag) Option { + return func(o *options) { o.fallback = tag } +} + +// TODO: +// // Catalogs specifies one or more sources for a Catalog. +// // Lookups are in order. +// // This can be changed inserting a Catalog used for setting, which implements +// // Loader, used for setting in the chain. +// func Catalogs(d ...Loader) Option { +// return nil +// } +// +// func Delims(start, end string) Option {} +// +// func Dict(tag language.Tag, d ...Dictionary) Option + +// NewBuilder returns an empty mutable Catalog. +func NewBuilder(opts ...Option) *Builder { + c := &Builder{} + for _, o := range opts { + o(&c.options) + } + return c +} + +// SetString is shorthand for Set(tag, key, String(msg)). +func (c *Builder) SetString(tag language.Tag, key string, msg string) error { + return c.set(tag, key, &c.index, String(msg)) +} + +// Set sets the translation for the given language and key. +// +// When evaluation this message, the first Message in the sequence to msgs to +// evaluate to a string will be the message returned. +func (c *Builder) Set(tag language.Tag, key string, msg ...Message) error { + return c.set(tag, key, &c.index, msg...) +} + +// SetMacro defines a Message that may be substituted in another message. +// The arguments to a macro Message are passed as arguments in the +// placeholder the form "${foo(arg1, arg2)}". +func (c *Builder) SetMacro(tag language.Tag, name string, msg ...Message) error { + return c.set(tag, name, &c.macros, msg...) +} + +// ErrNotFound indicates there was no message for the given key. +var ErrNotFound = errors.New("catalog: message not found") + +// String specifies a plain message string. It can be used as fallback if no +// other strings match or as a simple standalone message. +// +// It is an error to pass more than one String in a message sequence. +func String(name string) Message { + return catmsg.String(name) +} + +// Var sets a variable that may be substituted in formatting patterns using +// named substitution of the form "${name}". The name argument is used as a +// fallback if the statements do not produce a match. The statement sequence may +// not contain any Var calls. +// +// The name passed to a Var must be unique within message sequence. +func Var(name string, msg ...Message) Message { + return &catmsg.Var{Name: name, Message: firstInSequence(msg)} +} + +// Context returns a Context for formatting messages. +// Only one Message may be formatted per context at any given time. +func (b *Builder) Context(tag language.Tag, r catmsg.Renderer) *Context { + return &Context{ + cat: b, + tag: tag, + dec: catmsg.NewDecoder(tag, r, &dict{&b.macros, tag}), + } +} + +// A Context is used for evaluating Messages. +// Only one Message may be formatted per context at any given time. +type Context struct { + cat Catalog + tag language.Tag // TODO: use compact index. + dec *catmsg.Decoder +} + +// Execute looks up and executes the message with the given key. +// It returns ErrNotFound if no message could be found in the index. +func (c *Context) Execute(key string) error { + data, ok := c.cat.lookup(c.tag, key) + if !ok { + return ErrNotFound + } + return c.dec.Execute(data) +} diff --git a/vendor/golang.org/x/text/message/catalog/dict.go b/vendor/golang.org/x/text/message/catalog/dict.go new file mode 100644 index 00000000..a0eb8181 --- /dev/null +++ b/vendor/golang.org/x/text/message/catalog/dict.go @@ -0,0 +1,129 @@ +// Copyright 2017 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 catalog + +import ( + "sync" + + "golang.org/x/text/internal" + "golang.org/x/text/internal/catmsg" + "golang.org/x/text/language" +) + +// TODO: +// Dictionary returns a Dictionary that returns the first Message, using the +// given language tag, that matches: +// 1. the last one registered by one of the Set methods +// 2. returned by one of the Loaders +// 3. repeat from 1. using the parent language +// This approach allows messages to be underspecified. +// func (c *Catalog) Dictionary(tag language.Tag) (Dictionary, error) { +// // TODO: verify dictionary exists. +// return &dict{&c.index, tag}, nil +// } + +type dict struct { + s *store + tag language.Tag // TODO: make compact tag. +} + +func (d *dict) Lookup(key string) (data string, ok bool) { + return d.s.lookup(d.tag, key) +} + +func (b *Builder) lookup(tag language.Tag, key string) (data string, ok bool) { + return b.index.lookup(tag, key) +} + +func (c *Builder) set(tag language.Tag, key string, s *store, msg ...Message) error { + data, err := catmsg.Compile(tag, &dict{&c.macros, tag}, firstInSequence(msg)) + + s.mutex.Lock() + defer s.mutex.Unlock() + + m := s.index[tag] + if m == nil { + m = msgMap{} + if s.index == nil { + s.index = map[language.Tag]msgMap{} + } + c.matcher = nil + s.index[tag] = m + } + + m[key] = data + return err +} + +func (c *Builder) Matcher() language.Matcher { + c.index.mutex.RLock() + m := c.matcher + c.index.mutex.RUnlock() + if m != nil { + return m + } + + c.index.mutex.Lock() + if c.matcher == nil { + c.matcher = language.NewMatcher(c.unlockedLanguages()) + } + m = c.matcher + c.index.mutex.Unlock() + return m +} + +type store struct { + mutex sync.RWMutex + index map[language.Tag]msgMap +} + +type msgMap map[string]string + +func (s *store) lookup(tag language.Tag, key string) (data string, ok bool) { + s.mutex.RLock() + defer s.mutex.RUnlock() + + for ; ; tag = tag.Parent() { + if msgs, ok := s.index[tag]; ok { + if msg, ok := msgs[key]; ok { + return msg, true + } + } + if tag == language.Und { + break + } + } + return "", false +} + +// Languages returns all languages for which the Catalog contains variants. +func (b *Builder) Languages() []language.Tag { + s := &b.index + s.mutex.RLock() + defer s.mutex.RUnlock() + + return b.unlockedLanguages() +} + +func (b *Builder) unlockedLanguages() []language.Tag { + s := &b.index + if len(s.index) == 0 { + return nil + } + tags := make([]language.Tag, 0, len(s.index)) + _, hasFallback := s.index[b.options.fallback] + offset := 0 + if hasFallback { + tags = append(tags, b.options.fallback) + offset = 1 + } + for t := range s.index { + if t != b.options.fallback { + tags = append(tags, t) + } + } + internal.SortTags(tags[offset:]) + return tags +} diff --git a/vendor/golang.org/x/text/message/catalog/go19.go b/vendor/golang.org/x/text/message/catalog/go19.go new file mode 100644 index 00000000..291a4df9 --- /dev/null +++ b/vendor/golang.org/x/text/message/catalog/go19.go @@ -0,0 +1,15 @@ +// Copyright 2017 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. + +//go:build go1.9 + +package catalog + +import "golang.org/x/text/internal/catmsg" + +// A Message holds a collection of translations for the same phrase that may +// vary based on the values of substitution arguments. +type Message = catmsg.Message + +type firstInSequence = catmsg.FirstOf diff --git a/vendor/golang.org/x/text/message/catalog/gopre19.go b/vendor/golang.org/x/text/message/catalog/gopre19.go new file mode 100644 index 00000000..da44ebb8 --- /dev/null +++ b/vendor/golang.org/x/text/message/catalog/gopre19.go @@ -0,0 +1,23 @@ +// Copyright 2017 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. + +//go:build !go1.9 + +package catalog + +import "golang.org/x/text/internal/catmsg" + +// A Message holds a collection of translations for the same phrase that may +// vary based on the values of substitution arguments. +type Message interface { + catmsg.Message +} + +func firstInSequence(m []Message) catmsg.Message { + a := []catmsg.Message{} + for _, m := range m { + a = append(a, m) + } + return catmsg.FirstOf(a) +} diff --git a/vendor/golang.org/x/text/message/doc.go b/vendor/golang.org/x/text/message/doc.go new file mode 100644 index 00000000..4bf7bdca --- /dev/null +++ b/vendor/golang.org/x/text/message/doc.go @@ -0,0 +1,99 @@ +// Copyright 2017 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 message implements formatted I/O for localized strings with functions +// analogous to the fmt's print functions. It is a drop-in replacement for fmt. +// +// # Localized Formatting +// +// A format string can be localized by replacing any of the print functions of +// fmt with an equivalent call to a Printer. +// +// p := message.NewPrinter(message.MatchLanguage("en")) +// p.Println(123456.78) // Prints 123,456.78 +// +// p.Printf("%d ducks in a row", 4331) // Prints 4,331 ducks in a row +// +// p := message.NewPrinter(message.MatchLanguage("nl")) +// p.Printf("Hoogte: %.1f meter", 1244.9) // Prints Hoogte: 1,244.9 meter +// +// p := message.NewPrinter(message.MatchLanguage("bn")) +// p.Println(123456.78) // Prints ১,২৩,৪৫৬.৭৮ +// +// Printer currently supports numbers and specialized types for which packages +// exist in x/text. Other builtin types such as time.Time and slices are +// planned. +// +// Format strings largely have the same meaning as with fmt with the following +// notable exceptions: +// - flag # always resorts to fmt for printing +// - verb 'f', 'e', 'g', 'd' use localized formatting unless the '#' flag is +// specified. +// - verb 'm' inserts a translation of a string argument. +// +// See package fmt for more options. +// +// # Translation +// +// The format strings that are passed to Printf, Sprintf, Fprintf, or Errorf +// are used as keys to look up translations for the specified languages. +// More on how these need to be specified below. +// +// One can use arbitrary keys to distinguish between otherwise ambiguous +// strings: +// +// p := message.NewPrinter(language.English) +// p.Printf("archive(noun)") // Prints "archive" +// p.Printf("archive(verb)") // Prints "archive" +// +// p := message.NewPrinter(language.German) +// p.Printf("archive(noun)") // Prints "Archiv" +// p.Printf("archive(verb)") // Prints "archivieren" +// +// To retain the fallback functionality, use Key: +// +// p.Printf(message.Key("archive(noun)", "archive")) +// p.Printf(message.Key("archive(verb)", "archive")) +// +// # Translation Pipeline +// +// Format strings that contain text need to be translated to support different +// locales. The first step is to extract strings that need to be translated. +// +// 1. Install gotext +// +// go get -u golang.org/x/text/cmd/gotext +// gotext -help +// +// 2. Mark strings in your source to be translated by using message.Printer, +// instead of the functions of the fmt package. +// +// 3. Extract the strings from your source +// +// gotext extract +// +// The output will be written to the textdata directory. +// +// 4. Send the files for translation +// +// It is planned to support multiple formats, but for now one will have to +// rewrite the JSON output to the desired format. +// +// 5. Inject translations into program +// +// 6. Repeat from 2 +// +// Right now this has to be done programmatically with calls to Set or +// SetString. These functions as well as the methods defined in +// see also package golang.org/x/text/message/catalog can be used to implement +// either dynamic or static loading of messages. +// +// # Plural and Gender Forms +// +// Translated messages can vary based on the plural and gender forms of +// substitution values. In general, it is up to the translators to provide +// alternative translations for such forms. See the packages in +// golang.org/x/text/feature and golang.org/x/text/message/catalog for more +// information. +package message diff --git a/vendor/golang.org/x/text/message/format.go b/vendor/golang.org/x/text/message/format.go new file mode 100644 index 00000000..a47d17dd --- /dev/null +++ b/vendor/golang.org/x/text/message/format.go @@ -0,0 +1,510 @@ +// Copyright 2017 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 message + +import ( + "bytes" + "strconv" + "unicode/utf8" + + "golang.org/x/text/internal/format" +) + +const ( + ldigits = "0123456789abcdefx" + udigits = "0123456789ABCDEFX" +) + +const ( + signed = true + unsigned = false +) + +// A formatInfo is the raw formatter used by Printf etc. +// It prints into a buffer that must be set up separately. +type formatInfo struct { + buf *bytes.Buffer + + format.Parser + + // intbuf is large enough to store %b of an int64 with a sign and + // avoids padding at the end of the struct on 32 bit architectures. + intbuf [68]byte +} + +func (f *formatInfo) init(buf *bytes.Buffer) { + f.ClearFlags() + f.buf = buf +} + +// writePadding generates n bytes of padding. +func (f *formatInfo) writePadding(n int) { + if n <= 0 { // No padding bytes needed. + return + } + f.buf.Grow(n) + // Decide which byte the padding should be filled with. + padByte := byte(' ') + if f.Zero { + padByte = byte('0') + } + // Fill padding with padByte. + for i := 0; i < n; i++ { + f.buf.WriteByte(padByte) // TODO: make more efficient. + } +} + +// pad appends b to f.buf, padded on left (!f.minus) or right (f.minus). +func (f *formatInfo) pad(b []byte) { + if !f.WidthPresent || f.Width == 0 { + f.buf.Write(b) + return + } + width := f.Width - utf8.RuneCount(b) + if !f.Minus { + // left padding + f.writePadding(width) + f.buf.Write(b) + } else { + // right padding + f.buf.Write(b) + f.writePadding(width) + } +} + +// padString appends s to f.buf, padded on left (!f.minus) or right (f.minus). +func (f *formatInfo) padString(s string) { + if !f.WidthPresent || f.Width == 0 { + f.buf.WriteString(s) + return + } + width := f.Width - utf8.RuneCountInString(s) + if !f.Minus { + // left padding + f.writePadding(width) + f.buf.WriteString(s) + } else { + // right padding + f.buf.WriteString(s) + f.writePadding(width) + } +} + +// fmt_boolean formats a boolean. +func (f *formatInfo) fmt_boolean(v bool) { + if v { + f.padString("true") + } else { + f.padString("false") + } +} + +// fmt_unicode formats a uint64 as "U+0078" or with f.sharp set as "U+0078 'x'". +func (f *formatInfo) fmt_unicode(u uint64) { + buf := f.intbuf[0:] + + // With default precision set the maximum needed buf length is 18 + // for formatting -1 with %#U ("U+FFFFFFFFFFFFFFFF") which fits + // into the already allocated intbuf with a capacity of 68 bytes. + prec := 4 + if f.PrecPresent && f.Prec > 4 { + prec = f.Prec + // Compute space needed for "U+" , number, " '", character, "'". + width := 2 + prec + 2 + utf8.UTFMax + 1 + if width > len(buf) { + buf = make([]byte, width) + } + } + + // Format into buf, ending at buf[i]. Formatting numbers is easier right-to-left. + i := len(buf) + + // For %#U we want to add a space and a quoted character at the end of the buffer. + if f.Sharp && u <= utf8.MaxRune && strconv.IsPrint(rune(u)) { + i-- + buf[i] = '\'' + i -= utf8.RuneLen(rune(u)) + utf8.EncodeRune(buf[i:], rune(u)) + i-- + buf[i] = '\'' + i-- + buf[i] = ' ' + } + // Format the Unicode code point u as a hexadecimal number. + for u >= 16 { + i-- + buf[i] = udigits[u&0xF] + prec-- + u >>= 4 + } + i-- + buf[i] = udigits[u] + prec-- + // Add zeros in front of the number until requested precision is reached. + for prec > 0 { + i-- + buf[i] = '0' + prec-- + } + // Add a leading "U+". + i-- + buf[i] = '+' + i-- + buf[i] = 'U' + + oldZero := f.Zero + f.Zero = false + f.pad(buf[i:]) + f.Zero = oldZero +} + +// fmt_integer formats signed and unsigned integers. +func (f *formatInfo) fmt_integer(u uint64, base int, isSigned bool, digits string) { + negative := isSigned && int64(u) < 0 + if negative { + u = -u + } + + buf := f.intbuf[0:] + // The already allocated f.intbuf with a capacity of 68 bytes + // is large enough for integer formatting when no precision or width is set. + if f.WidthPresent || f.PrecPresent { + // Account 3 extra bytes for possible addition of a sign and "0x". + width := 3 + f.Width + f.Prec // wid and prec are always positive. + if width > len(buf) { + // We're going to need a bigger boat. + buf = make([]byte, width) + } + } + + // Two ways to ask for extra leading zero digits: %.3d or %03d. + // If both are specified the f.zero flag is ignored and + // padding with spaces is used instead. + prec := 0 + if f.PrecPresent { + prec = f.Prec + // Precision of 0 and value of 0 means "print nothing" but padding. + if prec == 0 && u == 0 { + oldZero := f.Zero + f.Zero = false + f.writePadding(f.Width) + f.Zero = oldZero + return + } + } else if f.Zero && f.WidthPresent { + prec = f.Width + if negative || f.Plus || f.Space { + prec-- // leave room for sign + } + } + + // Because printing is easier right-to-left: format u into buf, ending at buf[i]. + // We could make things marginally faster by splitting the 32-bit case out + // into a separate block but it's not worth the duplication, so u has 64 bits. + i := len(buf) + // Use constants for the division and modulo for more efficient code. + // Switch cases ordered by popularity. + switch base { + case 10: + for u >= 10 { + i-- + next := u / 10 + buf[i] = byte('0' + u - next*10) + u = next + } + case 16: + for u >= 16 { + i-- + buf[i] = digits[u&0xF] + u >>= 4 + } + case 8: + for u >= 8 { + i-- + buf[i] = byte('0' + u&7) + u >>= 3 + } + case 2: + for u >= 2 { + i-- + buf[i] = byte('0' + u&1) + u >>= 1 + } + default: + panic("fmt: unknown base; can't happen") + } + i-- + buf[i] = digits[u] + for i > 0 && prec > len(buf)-i { + i-- + buf[i] = '0' + } + + // Various prefixes: 0x, -, etc. + if f.Sharp { + switch base { + case 8: + if buf[i] != '0' { + i-- + buf[i] = '0' + } + case 16: + // Add a leading 0x or 0X. + i-- + buf[i] = digits[16] + i-- + buf[i] = '0' + } + } + + if negative { + i-- + buf[i] = '-' + } else if f.Plus { + i-- + buf[i] = '+' + } else if f.Space { + i-- + buf[i] = ' ' + } + + // Left padding with zeros has already been handled like precision earlier + // or the f.zero flag is ignored due to an explicitly set precision. + oldZero := f.Zero + f.Zero = false + f.pad(buf[i:]) + f.Zero = oldZero +} + +// truncate truncates the string to the specified precision, if present. +func (f *formatInfo) truncate(s string) string { + if f.PrecPresent { + n := f.Prec + for i := range s { + n-- + if n < 0 { + return s[:i] + } + } + } + return s +} + +// fmt_s formats a string. +func (f *formatInfo) fmt_s(s string) { + s = f.truncate(s) + f.padString(s) +} + +// fmt_sbx formats a string or byte slice as a hexadecimal encoding of its bytes. +func (f *formatInfo) fmt_sbx(s string, b []byte, digits string) { + length := len(b) + if b == nil { + // No byte slice present. Assume string s should be encoded. + length = len(s) + } + // Set length to not process more bytes than the precision demands. + if f.PrecPresent && f.Prec < length { + length = f.Prec + } + // Compute width of the encoding taking into account the f.sharp and f.space flag. + width := 2 * length + if width > 0 { + if f.Space { + // Each element encoded by two hexadecimals will get a leading 0x or 0X. + if f.Sharp { + width *= 2 + } + // Elements will be separated by a space. + width += length - 1 + } else if f.Sharp { + // Only a leading 0x or 0X will be added for the whole string. + width += 2 + } + } else { // The byte slice or string that should be encoded is empty. + if f.WidthPresent { + f.writePadding(f.Width) + } + return + } + // Handle padding to the left. + if f.WidthPresent && f.Width > width && !f.Minus { + f.writePadding(f.Width - width) + } + // Write the encoding directly into the output buffer. + buf := f.buf + if f.Sharp { + // Add leading 0x or 0X. + buf.WriteByte('0') + buf.WriteByte(digits[16]) + } + var c byte + for i := 0; i < length; i++ { + if f.Space && i > 0 { + // Separate elements with a space. + buf.WriteByte(' ') + if f.Sharp { + // Add leading 0x or 0X for each element. + buf.WriteByte('0') + buf.WriteByte(digits[16]) + } + } + if b != nil { + c = b[i] // Take a byte from the input byte slice. + } else { + c = s[i] // Take a byte from the input string. + } + // Encode each byte as two hexadecimal digits. + buf.WriteByte(digits[c>>4]) + buf.WriteByte(digits[c&0xF]) + } + // Handle padding to the right. + if f.WidthPresent && f.Width > width && f.Minus { + f.writePadding(f.Width - width) + } +} + +// fmt_sx formats a string as a hexadecimal encoding of its bytes. +func (f *formatInfo) fmt_sx(s, digits string) { + f.fmt_sbx(s, nil, digits) +} + +// fmt_bx formats a byte slice as a hexadecimal encoding of its bytes. +func (f *formatInfo) fmt_bx(b []byte, digits string) { + f.fmt_sbx("", b, digits) +} + +// fmt_q formats a string as a double-quoted, escaped Go string constant. +// If f.sharp is set a raw (backquoted) string may be returned instead +// if the string does not contain any control characters other than tab. +func (f *formatInfo) fmt_q(s string) { + s = f.truncate(s) + if f.Sharp && strconv.CanBackquote(s) { + f.padString("`" + s + "`") + return + } + buf := f.intbuf[:0] + if f.Plus { + f.pad(strconv.AppendQuoteToASCII(buf, s)) + } else { + f.pad(strconv.AppendQuote(buf, s)) + } +} + +// fmt_c formats an integer as a Unicode character. +// If the character is not valid Unicode, it will print '\ufffd'. +func (f *formatInfo) fmt_c(c uint64) { + r := rune(c) + if c > utf8.MaxRune { + r = utf8.RuneError + } + buf := f.intbuf[:0] + w := utf8.EncodeRune(buf[:utf8.UTFMax], r) + f.pad(buf[:w]) +} + +// fmt_qc formats an integer as a single-quoted, escaped Go character constant. +// If the character is not valid Unicode, it will print '\ufffd'. +func (f *formatInfo) fmt_qc(c uint64) { + r := rune(c) + if c > utf8.MaxRune { + r = utf8.RuneError + } + buf := f.intbuf[:0] + if f.Plus { + f.pad(strconv.AppendQuoteRuneToASCII(buf, r)) + } else { + f.pad(strconv.AppendQuoteRune(buf, r)) + } +} + +// fmt_float formats a float64. It assumes that verb is a valid format specifier +// for strconv.AppendFloat and therefore fits into a byte. +func (f *formatInfo) fmt_float(v float64, size int, verb rune, prec int) { + // Explicit precision in format specifier overrules default precision. + if f.PrecPresent { + prec = f.Prec + } + // Format number, reserving space for leading + sign if needed. + num := strconv.AppendFloat(f.intbuf[:1], v, byte(verb), prec, size) + if num[1] == '-' || num[1] == '+' { + num = num[1:] + } else { + num[0] = '+' + } + // f.space means to add a leading space instead of a "+" sign unless + // the sign is explicitly asked for by f.plus. + if f.Space && num[0] == '+' && !f.Plus { + num[0] = ' ' + } + // Special handling for infinities and NaN, + // which don't look like a number so shouldn't be padded with zeros. + if num[1] == 'I' || num[1] == 'N' { + oldZero := f.Zero + f.Zero = false + // Remove sign before NaN if not asked for. + if num[1] == 'N' && !f.Space && !f.Plus { + num = num[1:] + } + f.pad(num) + f.Zero = oldZero + return + } + // The sharp flag forces printing a decimal point for non-binary formats + // and retains trailing zeros, which we may need to restore. + if f.Sharp && verb != 'b' { + digits := 0 + switch verb { + case 'v', 'g', 'G': + digits = prec + // If no precision is set explicitly use a precision of 6. + if digits == -1 { + digits = 6 + } + } + + // Buffer pre-allocated with enough room for + // exponent notations of the form "e+123". + var tailBuf [5]byte + tail := tailBuf[:0] + + hasDecimalPoint := false + // Starting from i = 1 to skip sign at num[0]. + for i := 1; i < len(num); i++ { + switch num[i] { + case '.': + hasDecimalPoint = true + case 'e', 'E': + tail = append(tail, num[i:]...) + num = num[:i] + default: + digits-- + } + } + if !hasDecimalPoint { + num = append(num, '.') + } + for digits > 0 { + num = append(num, '0') + digits-- + } + num = append(num, tail...) + } + // We want a sign if asked for and if the sign is not positive. + if f.Plus || num[0] != '+' { + // If we're zero padding to the left we want the sign before the leading zeros. + // Achieve this by writing the sign out and then padding the unsigned number. + if f.Zero && f.WidthPresent && f.Width > len(num) { + f.buf.WriteByte(num[0]) + f.writePadding(f.Width - len(num)) + f.buf.Write(num[1:]) + return + } + f.pad(num) + return + } + // No sign to show and the number is positive; just print the unsigned number. + f.pad(num[1:]) +} diff --git a/vendor/golang.org/x/text/message/message.go b/vendor/golang.org/x/text/message/message.go new file mode 100644 index 00000000..48d76630 --- /dev/null +++ b/vendor/golang.org/x/text/message/message.go @@ -0,0 +1,193 @@ +// Copyright 2015 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 message // import "golang.org/x/text/message" + +import ( + "io" + "os" + + // Include features to facilitate generated catalogs. + _ "golang.org/x/text/feature/plural" + + "golang.org/x/text/internal/number" + "golang.org/x/text/language" + "golang.org/x/text/message/catalog" +) + +// A Printer implements language-specific formatted I/O analogous to the fmt +// package. +type Printer struct { + // the language + tag language.Tag + + toDecimal number.Formatter + toScientific number.Formatter + + cat catalog.Catalog +} + +type options struct { + cat catalog.Catalog + // TODO: + // - allow %s to print integers in written form (tables are likely too large + // to enable this by default). + // - list behavior + // +} + +// An Option defines an option of a Printer. +type Option func(o *options) + +// Catalog defines the catalog to be used. +func Catalog(c catalog.Catalog) Option { + return func(o *options) { o.cat = c } +} + +// NewPrinter returns a Printer that formats messages tailored to language t. +func NewPrinter(t language.Tag, opts ...Option) *Printer { + options := &options{ + cat: DefaultCatalog, + } + for _, o := range opts { + o(options) + } + p := &Printer{ + tag: t, + cat: options.cat, + } + p.toDecimal.InitDecimal(t) + p.toScientific.InitScientific(t) + return p +} + +// Sprint is like fmt.Sprint, but using language-specific formatting. +func (p *Printer) Sprint(a ...interface{}) string { + pp := newPrinter(p) + pp.doPrint(a) + s := pp.String() + pp.free() + return s +} + +// Fprint is like fmt.Fprint, but using language-specific formatting. +func (p *Printer) Fprint(w io.Writer, a ...interface{}) (n int, err error) { + pp := newPrinter(p) + pp.doPrint(a) + n64, err := io.Copy(w, &pp.Buffer) + pp.free() + return int(n64), err +} + +// Print is like fmt.Print, but using language-specific formatting. +func (p *Printer) Print(a ...interface{}) (n int, err error) { + return p.Fprint(os.Stdout, a...) +} + +// Sprintln is like fmt.Sprintln, but using language-specific formatting. +func (p *Printer) Sprintln(a ...interface{}) string { + pp := newPrinter(p) + pp.doPrintln(a) + s := pp.String() + pp.free() + return s +} + +// Fprintln is like fmt.Fprintln, but using language-specific formatting. +func (p *Printer) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { + pp := newPrinter(p) + pp.doPrintln(a) + n64, err := io.Copy(w, &pp.Buffer) + pp.free() + return int(n64), err +} + +// Println is like fmt.Println, but using language-specific formatting. +func (p *Printer) Println(a ...interface{}) (n int, err error) { + return p.Fprintln(os.Stdout, a...) +} + +// Sprintf is like fmt.Sprintf, but using language-specific formatting. +func (p *Printer) Sprintf(key Reference, a ...interface{}) string { + pp := newPrinter(p) + lookupAndFormat(pp, key, a) + s := pp.String() + pp.free() + return s +} + +// Fprintf is like fmt.Fprintf, but using language-specific formatting. +func (p *Printer) Fprintf(w io.Writer, key Reference, a ...interface{}) (n int, err error) { + pp := newPrinter(p) + lookupAndFormat(pp, key, a) + n, err = w.Write(pp.Bytes()) + pp.free() + return n, err + +} + +// Printf is like fmt.Printf, but using language-specific formatting. +func (p *Printer) Printf(key Reference, a ...interface{}) (n int, err error) { + pp := newPrinter(p) + lookupAndFormat(pp, key, a) + n, err = os.Stdout.Write(pp.Bytes()) + pp.free() + return n, err +} + +func lookupAndFormat(p *printer, r Reference, a []interface{}) { + p.fmt.Reset(a) + var id, msg string + switch v := r.(type) { + case string: + id, msg = v, v + case key: + id, msg = v.id, v.fallback + default: + panic("key argument is not a Reference") + } + + if p.catContext.Execute(id) == catalog.ErrNotFound { + if p.catContext.Execute(msg) == catalog.ErrNotFound { + p.Render(msg) + return + } + } +} + +type rawPrinter struct { + p *printer +} + +func (p rawPrinter) Render(msg string) { p.p.WriteString(msg) } +func (p rawPrinter) Arg(i int) interface{} { return nil } + +// Arg implements catmsg.Renderer. +func (p *printer) Arg(i int) interface{} { // TODO, also return "ok" bool + i-- + if uint(i) < uint(len(p.fmt.Args)) { + return p.fmt.Args[i] + } + return nil +} + +// Render implements catmsg.Renderer. +func (p *printer) Render(msg string) { + p.doPrintf(msg) +} + +// A Reference is a string or a message reference. +type Reference interface { + // TODO: also allow []string +} + +// Key creates a message Reference for a message where the given id is used for +// message lookup and the fallback is returned when no matches are found. +func Key(id string, fallback string) Reference { + return key{id, fallback} +} + +type key struct { + id, fallback string +} diff --git a/vendor/golang.org/x/text/message/print.go b/vendor/golang.org/x/text/message/print.go new file mode 100644 index 00000000..da304cc0 --- /dev/null +++ b/vendor/golang.org/x/text/message/print.go @@ -0,0 +1,984 @@ +// Copyright 2017 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 message + +import ( + "bytes" + "fmt" // TODO: consider copying interfaces from package fmt to avoid dependency. + "math" + "reflect" + "sync" + "unicode/utf8" + + "golang.org/x/text/internal/format" + "golang.org/x/text/internal/number" + "golang.org/x/text/language" + "golang.org/x/text/message/catalog" +) + +// Strings for use with buffer.WriteString. +// This is less overhead than using buffer.Write with byte arrays. +const ( + commaSpaceString = ", " + nilAngleString = "" + nilParenString = "(nil)" + nilString = "nil" + mapString = "map[" + percentBangString = "%!" + missingString = "(MISSING)" + badIndexString = "(BADINDEX)" + panicString = "(PANIC=" + extraString = "%!(EXTRA " + badWidthString = "%!(BADWIDTH)" + badPrecString = "%!(BADPREC)" + noVerbString = "%!(NOVERB)" + + invReflectString = "" +) + +var printerPool = sync.Pool{ + New: func() interface{} { return new(printer) }, +} + +// newPrinter allocates a new printer struct or grabs a cached one. +func newPrinter(pp *Printer) *printer { + p := printerPool.Get().(*printer) + p.Printer = *pp + // TODO: cache most of the following call. + p.catContext = pp.cat.Context(pp.tag, p) + + p.panicking = false + p.erroring = false + p.fmt.init(&p.Buffer) + return p +} + +// free saves used printer structs in printerFree; avoids an allocation per invocation. +func (p *printer) free() { + p.Buffer.Reset() + p.arg = nil + p.value = reflect.Value{} + printerPool.Put(p) +} + +// printer is used to store a printer's state. +// It implements "golang.org/x/text/internal/format".State. +type printer struct { + Printer + + // the context for looking up message translations + catContext *catalog.Context + + // buffer for accumulating output. + bytes.Buffer + + // arg holds the current item, as an interface{}. + arg interface{} + // value is used instead of arg for reflect values. + value reflect.Value + + // fmt is used to format basic items such as integers or strings. + fmt formatInfo + + // panicking is set by catchPanic to avoid infinite panic, recover, panic, ... recursion. + panicking bool + // erroring is set when printing an error string to guard against calling handleMethods. + erroring bool +} + +// Language implements "golang.org/x/text/internal/format".State. +func (p *printer) Language() language.Tag { return p.tag } + +func (p *printer) Width() (wid int, ok bool) { return p.fmt.Width, p.fmt.WidthPresent } + +func (p *printer) Precision() (prec int, ok bool) { return p.fmt.Prec, p.fmt.PrecPresent } + +func (p *printer) Flag(b int) bool { + switch b { + case '-': + return p.fmt.Minus + case '+': + return p.fmt.Plus || p.fmt.PlusV + case '#': + return p.fmt.Sharp || p.fmt.SharpV + case ' ': + return p.fmt.Space + case '0': + return p.fmt.Zero + } + return false +} + +// getField gets the i'th field of the struct value. +// If the field is itself is an interface, return a value for +// the thing inside the interface, not the interface itself. +func getField(v reflect.Value, i int) reflect.Value { + val := v.Field(i) + if val.Kind() == reflect.Interface && !val.IsNil() { + val = val.Elem() + } + return val +} + +func (p *printer) unknownType(v reflect.Value) { + if !v.IsValid() { + p.WriteString(nilAngleString) + return + } + p.WriteByte('?') + p.WriteString(v.Type().String()) + p.WriteByte('?') +} + +func (p *printer) badVerb(verb rune) { + p.erroring = true + p.WriteString(percentBangString) + p.WriteRune(verb) + p.WriteByte('(') + switch { + case p.arg != nil: + p.WriteString(reflect.TypeOf(p.arg).String()) + p.WriteByte('=') + p.printArg(p.arg, 'v') + case p.value.IsValid(): + p.WriteString(p.value.Type().String()) + p.WriteByte('=') + p.printValue(p.value, 'v', 0) + default: + p.WriteString(nilAngleString) + } + p.WriteByte(')') + p.erroring = false +} + +func (p *printer) fmtBool(v bool, verb rune) { + switch verb { + case 't', 'v': + p.fmt.fmt_boolean(v) + default: + p.badVerb(verb) + } +} + +// fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or +// not, as requested, by temporarily setting the sharp flag. +func (p *printer) fmt0x64(v uint64, leading0x bool) { + sharp := p.fmt.Sharp + p.fmt.Sharp = leading0x + p.fmt.fmt_integer(v, 16, unsigned, ldigits) + p.fmt.Sharp = sharp +} + +// fmtInteger formats a signed or unsigned integer. +func (p *printer) fmtInteger(v uint64, isSigned bool, verb rune) { + switch verb { + case 'v': + if p.fmt.SharpV && !isSigned { + p.fmt0x64(v, true) + return + } + fallthrough + case 'd': + if p.fmt.Sharp || p.fmt.SharpV { + p.fmt.fmt_integer(v, 10, isSigned, ldigits) + } else { + p.fmtDecimalInt(v, isSigned) + } + case 'b': + p.fmt.fmt_integer(v, 2, isSigned, ldigits) + case 'o': + p.fmt.fmt_integer(v, 8, isSigned, ldigits) + case 'x': + p.fmt.fmt_integer(v, 16, isSigned, ldigits) + case 'X': + p.fmt.fmt_integer(v, 16, isSigned, udigits) + case 'c': + p.fmt.fmt_c(v) + case 'q': + if v <= utf8.MaxRune { + p.fmt.fmt_qc(v) + } else { + p.badVerb(verb) + } + case 'U': + p.fmt.fmt_unicode(v) + default: + p.badVerb(verb) + } +} + +// fmtFloat formats a float. The default precision for each verb +// is specified as last argument in the call to fmt_float. +func (p *printer) fmtFloat(v float64, size int, verb rune) { + switch verb { + case 'b': + p.fmt.fmt_float(v, size, verb, -1) + case 'v': + verb = 'g' + fallthrough + case 'g', 'G': + if p.fmt.Sharp || p.fmt.SharpV { + p.fmt.fmt_float(v, size, verb, -1) + } else { + p.fmtVariableFloat(v, size) + } + case 'e', 'E': + if p.fmt.Sharp || p.fmt.SharpV { + p.fmt.fmt_float(v, size, verb, 6) + } else { + p.fmtScientific(v, size, 6) + } + case 'f', 'F': + if p.fmt.Sharp || p.fmt.SharpV { + p.fmt.fmt_float(v, size, verb, 6) + } else { + p.fmtDecimalFloat(v, size, 6) + } + default: + p.badVerb(verb) + } +} + +func (p *printer) setFlags(f *number.Formatter) { + f.Flags &^= number.ElideSign + if p.fmt.Plus || p.fmt.Space { + f.Flags |= number.AlwaysSign + if !p.fmt.Plus { + f.Flags |= number.ElideSign + } + } else { + f.Flags &^= number.AlwaysSign + } +} + +func (p *printer) updatePadding(f *number.Formatter) { + f.Flags &^= number.PadMask + if p.fmt.Minus { + f.Flags |= number.PadAfterSuffix + } else { + f.Flags |= number.PadBeforePrefix + } + f.PadRune = ' ' + f.FormatWidth = uint16(p.fmt.Width) +} + +func (p *printer) initDecimal(minFrac, maxFrac int) { + f := &p.toDecimal + f.MinIntegerDigits = 1 + f.MaxIntegerDigits = 0 + f.MinFractionDigits = uint8(minFrac) + f.MaxFractionDigits = int16(maxFrac) + p.setFlags(f) + f.PadRune = 0 + if p.fmt.WidthPresent { + if p.fmt.Zero { + wid := p.fmt.Width + // Use significant integers for this. + // TODO: this is not the same as width, but so be it. + if f.MinFractionDigits > 0 { + wid -= 1 + int(f.MinFractionDigits) + } + if p.fmt.Plus || p.fmt.Space { + wid-- + } + if wid > 0 && wid > int(f.MinIntegerDigits) { + f.MinIntegerDigits = uint8(wid) + } + } + p.updatePadding(f) + } +} + +func (p *printer) initScientific(minFrac, maxFrac int) { + f := &p.toScientific + if maxFrac < 0 { + f.SetPrecision(maxFrac) + } else { + f.SetPrecision(maxFrac + 1) + f.MinFractionDigits = uint8(minFrac) + f.MaxFractionDigits = int16(maxFrac) + } + f.MinExponentDigits = 2 + p.setFlags(f) + f.PadRune = 0 + if p.fmt.WidthPresent { + f.Flags &^= number.PadMask + if p.fmt.Zero { + f.PadRune = f.Digit(0) + f.Flags |= number.PadAfterPrefix + } else { + f.PadRune = ' ' + f.Flags |= number.PadBeforePrefix + } + p.updatePadding(f) + } +} + +func (p *printer) fmtDecimalInt(v uint64, isSigned bool) { + var d number.Decimal + + f := &p.toDecimal + if p.fmt.PrecPresent { + p.setFlags(f) + f.MinIntegerDigits = uint8(p.fmt.Prec) + f.MaxIntegerDigits = 0 + f.MinFractionDigits = 0 + f.MaxFractionDigits = 0 + if p.fmt.WidthPresent { + p.updatePadding(f) + } + } else { + p.initDecimal(0, 0) + } + d.ConvertInt(p.toDecimal.RoundingContext, isSigned, v) + + out := p.toDecimal.Format([]byte(nil), &d) + p.Buffer.Write(out) +} + +func (p *printer) fmtDecimalFloat(v float64, size, prec int) { + var d number.Decimal + if p.fmt.PrecPresent { + prec = p.fmt.Prec + } + p.initDecimal(prec, prec) + d.ConvertFloat(p.toDecimal.RoundingContext, v, size) + + out := p.toDecimal.Format([]byte(nil), &d) + p.Buffer.Write(out) +} + +func (p *printer) fmtVariableFloat(v float64, size int) { + prec := -1 + if p.fmt.PrecPresent { + prec = p.fmt.Prec + } + var d number.Decimal + p.initScientific(0, prec) + d.ConvertFloat(p.toScientific.RoundingContext, v, size) + + // Copy logic of 'g' formatting from strconv. It is simplified a bit as + // we don't have to mind having prec > len(d.Digits). + shortest := prec < 0 + ePrec := prec + if shortest { + prec = len(d.Digits) + ePrec = 6 + } else if prec == 0 { + prec = 1 + ePrec = 1 + } + exp := int(d.Exp) - 1 + if exp < -4 || exp >= ePrec { + p.initScientific(0, prec) + + out := p.toScientific.Format([]byte(nil), &d) + p.Buffer.Write(out) + } else { + if prec > int(d.Exp) { + prec = len(d.Digits) + } + if prec -= int(d.Exp); prec < 0 { + prec = 0 + } + p.initDecimal(0, prec) + + out := p.toDecimal.Format([]byte(nil), &d) + p.Buffer.Write(out) + } +} + +func (p *printer) fmtScientific(v float64, size, prec int) { + var d number.Decimal + if p.fmt.PrecPresent { + prec = p.fmt.Prec + } + p.initScientific(prec, prec) + rc := p.toScientific.RoundingContext + d.ConvertFloat(rc, v, size) + + out := p.toScientific.Format([]byte(nil), &d) + p.Buffer.Write(out) + +} + +// fmtComplex formats a complex number v with +// r = real(v) and j = imag(v) as (r+ji) using +// fmtFloat for r and j formatting. +func (p *printer) fmtComplex(v complex128, size int, verb rune) { + // Make sure any unsupported verbs are found before the + // calls to fmtFloat to not generate an incorrect error string. + switch verb { + case 'v', 'b', 'g', 'G', 'f', 'F', 'e', 'E': + p.WriteByte('(') + p.fmtFloat(real(v), size/2, verb) + // Imaginary part always has a sign. + if math.IsNaN(imag(v)) { + // By CLDR's rules, NaNs do not use patterns or signs. As this code + // relies on AlwaysSign working for imaginary parts, we need to + // manually handle NaNs. + f := &p.toScientific + p.setFlags(f) + p.updatePadding(f) + p.setFlags(f) + nan := f.Symbol(number.SymNan) + extra := 0 + if w, ok := p.Width(); ok { + extra = w - utf8.RuneCountInString(nan) - 1 + } + if f.Flags&number.PadAfterNumber == 0 { + for ; extra > 0; extra-- { + p.WriteRune(f.PadRune) + } + } + p.WriteString(f.Symbol(number.SymPlusSign)) + p.WriteString(nan) + for ; extra > 0; extra-- { + p.WriteRune(f.PadRune) + } + p.WriteString("i)") + return + } + oldPlus := p.fmt.Plus + p.fmt.Plus = true + p.fmtFloat(imag(v), size/2, verb) + p.WriteString("i)") // TODO: use symbol? + p.fmt.Plus = oldPlus + default: + p.badVerb(verb) + } +} + +func (p *printer) fmtString(v string, verb rune) { + switch verb { + case 'v': + if p.fmt.SharpV { + p.fmt.fmt_q(v) + } else { + p.fmt.fmt_s(v) + } + case 's': + p.fmt.fmt_s(v) + case 'x': + p.fmt.fmt_sx(v, ldigits) + case 'X': + p.fmt.fmt_sx(v, udigits) + case 'q': + p.fmt.fmt_q(v) + case 'm': + ctx := p.cat.Context(p.tag, rawPrinter{p}) + if ctx.Execute(v) == catalog.ErrNotFound { + p.WriteString(v) + } + default: + p.badVerb(verb) + } +} + +func (p *printer) fmtBytes(v []byte, verb rune, typeString string) { + switch verb { + case 'v', 'd': + if p.fmt.SharpV { + p.WriteString(typeString) + if v == nil { + p.WriteString(nilParenString) + return + } + p.WriteByte('{') + for i, c := range v { + if i > 0 { + p.WriteString(commaSpaceString) + } + p.fmt0x64(uint64(c), true) + } + p.WriteByte('}') + } else { + p.WriteByte('[') + for i, c := range v { + if i > 0 { + p.WriteByte(' ') + } + p.fmt.fmt_integer(uint64(c), 10, unsigned, ldigits) + } + p.WriteByte(']') + } + case 's': + p.fmt.fmt_s(string(v)) + case 'x': + p.fmt.fmt_bx(v, ldigits) + case 'X': + p.fmt.fmt_bx(v, udigits) + case 'q': + p.fmt.fmt_q(string(v)) + default: + p.printValue(reflect.ValueOf(v), verb, 0) + } +} + +func (p *printer) fmtPointer(value reflect.Value, verb rune) { + var u uintptr + switch value.Kind() { + case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: + u = value.Pointer() + default: + p.badVerb(verb) + return + } + + switch verb { + case 'v': + if p.fmt.SharpV { + p.WriteByte('(') + p.WriteString(value.Type().String()) + p.WriteString(")(") + if u == 0 { + p.WriteString(nilString) + } else { + p.fmt0x64(uint64(u), true) + } + p.WriteByte(')') + } else { + if u == 0 { + p.fmt.padString(nilAngleString) + } else { + p.fmt0x64(uint64(u), !p.fmt.Sharp) + } + } + case 'p': + p.fmt0x64(uint64(u), !p.fmt.Sharp) + case 'b', 'o', 'd', 'x', 'X': + if verb == 'd' { + p.fmt.Sharp = true // Print as standard go. TODO: does this make sense? + } + p.fmtInteger(uint64(u), unsigned, verb) + default: + p.badVerb(verb) + } +} + +func (p *printer) catchPanic(arg interface{}, verb rune) { + if err := recover(); err != nil { + // If it's a nil pointer, just say "". The likeliest causes are a + // Stringer that fails to guard against nil or a nil pointer for a + // value receiver, and in either case, "" is a nice result. + if v := reflect.ValueOf(arg); v.Kind() == reflect.Ptr && v.IsNil() { + p.WriteString(nilAngleString) + return + } + // Otherwise print a concise panic message. Most of the time the panic + // value will print itself nicely. + if p.panicking { + // Nested panics; the recursion in printArg cannot succeed. + panic(err) + } + + oldFlags := p.fmt.Parser + // For this output we want default behavior. + p.fmt.ClearFlags() + + p.WriteString(percentBangString) + p.WriteRune(verb) + p.WriteString(panicString) + p.panicking = true + p.printArg(err, 'v') + p.panicking = false + p.WriteByte(')') + + p.fmt.Parser = oldFlags + } +} + +func (p *printer) handleMethods(verb rune) (handled bool) { + if p.erroring { + return + } + // Is it a Formatter? + if formatter, ok := p.arg.(format.Formatter); ok { + handled = true + defer p.catchPanic(p.arg, verb) + formatter.Format(p, verb) + return + } + if formatter, ok := p.arg.(fmt.Formatter); ok { + handled = true + defer p.catchPanic(p.arg, verb) + formatter.Format(p, verb) + return + } + + // If we're doing Go syntax and the argument knows how to supply it, take care of it now. + if p.fmt.SharpV { + if stringer, ok := p.arg.(fmt.GoStringer); ok { + handled = true + defer p.catchPanic(p.arg, verb) + // Print the result of GoString unadorned. + p.fmt.fmt_s(stringer.GoString()) + return + } + } else { + // If a string is acceptable according to the format, see if + // the value satisfies one of the string-valued interfaces. + // Println etc. set verb to %v, which is "stringable". + switch verb { + case 'v', 's', 'x', 'X', 'q': + // Is it an error or Stringer? + // The duplication in the bodies is necessary: + // setting handled and deferring catchPanic + // must happen before calling the method. + switch v := p.arg.(type) { + case error: + handled = true + defer p.catchPanic(p.arg, verb) + p.fmtString(v.Error(), verb) + return + + case fmt.Stringer: + handled = true + defer p.catchPanic(p.arg, verb) + p.fmtString(v.String(), verb) + return + } + } + } + return false +} + +func (p *printer) printArg(arg interface{}, verb rune) { + p.arg = arg + p.value = reflect.Value{} + + if arg == nil { + switch verb { + case 'T', 'v': + p.fmt.padString(nilAngleString) + default: + p.badVerb(verb) + } + return + } + + // Special processing considerations. + // %T (the value's type) and %p (its address) are special; we always do them first. + switch verb { + case 'T': + p.fmt.fmt_s(reflect.TypeOf(arg).String()) + return + case 'p': + p.fmtPointer(reflect.ValueOf(arg), 'p') + return + } + + // Some types can be done without reflection. + switch f := arg.(type) { + case bool: + p.fmtBool(f, verb) + case float32: + p.fmtFloat(float64(f), 32, verb) + case float64: + p.fmtFloat(f, 64, verb) + case complex64: + p.fmtComplex(complex128(f), 64, verb) + case complex128: + p.fmtComplex(f, 128, verb) + case int: + p.fmtInteger(uint64(f), signed, verb) + case int8: + p.fmtInteger(uint64(f), signed, verb) + case int16: + p.fmtInteger(uint64(f), signed, verb) + case int32: + p.fmtInteger(uint64(f), signed, verb) + case int64: + p.fmtInteger(uint64(f), signed, verb) + case uint: + p.fmtInteger(uint64(f), unsigned, verb) + case uint8: + p.fmtInteger(uint64(f), unsigned, verb) + case uint16: + p.fmtInteger(uint64(f), unsigned, verb) + case uint32: + p.fmtInteger(uint64(f), unsigned, verb) + case uint64: + p.fmtInteger(f, unsigned, verb) + case uintptr: + p.fmtInteger(uint64(f), unsigned, verb) + case string: + p.fmtString(f, verb) + case []byte: + p.fmtBytes(f, verb, "[]byte") + case reflect.Value: + // Handle extractable values with special methods + // since printValue does not handle them at depth 0. + if f.IsValid() && f.CanInterface() { + p.arg = f.Interface() + if p.handleMethods(verb) { + return + } + } + p.printValue(f, verb, 0) + default: + // If the type is not simple, it might have methods. + if !p.handleMethods(verb) { + // Need to use reflection, since the type had no + // interface methods that could be used for formatting. + p.printValue(reflect.ValueOf(f), verb, 0) + } + } +} + +// printValue is similar to printArg but starts with a reflect value, not an interface{} value. +// It does not handle 'p' and 'T' verbs because these should have been already handled by printArg. +func (p *printer) printValue(value reflect.Value, verb rune, depth int) { + // Handle values with special methods if not already handled by printArg (depth == 0). + if depth > 0 && value.IsValid() && value.CanInterface() { + p.arg = value.Interface() + if p.handleMethods(verb) { + return + } + } + p.arg = nil + p.value = value + + switch f := value; value.Kind() { + case reflect.Invalid: + if depth == 0 { + p.WriteString(invReflectString) + } else { + switch verb { + case 'v': + p.WriteString(nilAngleString) + default: + p.badVerb(verb) + } + } + case reflect.Bool: + p.fmtBool(f.Bool(), verb) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + p.fmtInteger(uint64(f.Int()), signed, verb) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + p.fmtInteger(f.Uint(), unsigned, verb) + case reflect.Float32: + p.fmtFloat(f.Float(), 32, verb) + case reflect.Float64: + p.fmtFloat(f.Float(), 64, verb) + case reflect.Complex64: + p.fmtComplex(f.Complex(), 64, verb) + case reflect.Complex128: + p.fmtComplex(f.Complex(), 128, verb) + case reflect.String: + p.fmtString(f.String(), verb) + case reflect.Map: + if p.fmt.SharpV { + p.WriteString(f.Type().String()) + if f.IsNil() { + p.WriteString(nilParenString) + return + } + p.WriteByte('{') + } else { + p.WriteString(mapString) + } + keys := f.MapKeys() + for i, key := range keys { + if i > 0 { + if p.fmt.SharpV { + p.WriteString(commaSpaceString) + } else { + p.WriteByte(' ') + } + } + p.printValue(key, verb, depth+1) + p.WriteByte(':') + p.printValue(f.MapIndex(key), verb, depth+1) + } + if p.fmt.SharpV { + p.WriteByte('}') + } else { + p.WriteByte(']') + } + case reflect.Struct: + if p.fmt.SharpV { + p.WriteString(f.Type().String()) + } + p.WriteByte('{') + for i := 0; i < f.NumField(); i++ { + if i > 0 { + if p.fmt.SharpV { + p.WriteString(commaSpaceString) + } else { + p.WriteByte(' ') + } + } + if p.fmt.PlusV || p.fmt.SharpV { + if name := f.Type().Field(i).Name; name != "" { + p.WriteString(name) + p.WriteByte(':') + } + } + p.printValue(getField(f, i), verb, depth+1) + } + p.WriteByte('}') + case reflect.Interface: + value := f.Elem() + if !value.IsValid() { + if p.fmt.SharpV { + p.WriteString(f.Type().String()) + p.WriteString(nilParenString) + } else { + p.WriteString(nilAngleString) + } + } else { + p.printValue(value, verb, depth+1) + } + case reflect.Array, reflect.Slice: + switch verb { + case 's', 'q', 'x', 'X': + // Handle byte and uint8 slices and arrays special for the above verbs. + t := f.Type() + if t.Elem().Kind() == reflect.Uint8 { + var bytes []byte + if f.Kind() == reflect.Slice { + bytes = f.Bytes() + } else if f.CanAddr() { + bytes = f.Slice(0, f.Len()).Bytes() + } else { + // We have an array, but we cannot Slice() a non-addressable array, + // so we build a slice by hand. This is a rare case but it would be nice + // if reflection could help a little more. + bytes = make([]byte, f.Len()) + for i := range bytes { + bytes[i] = byte(f.Index(i).Uint()) + } + } + p.fmtBytes(bytes, verb, t.String()) + return + } + } + if p.fmt.SharpV { + p.WriteString(f.Type().String()) + if f.Kind() == reflect.Slice && f.IsNil() { + p.WriteString(nilParenString) + return + } + p.WriteByte('{') + for i := 0; i < f.Len(); i++ { + if i > 0 { + p.WriteString(commaSpaceString) + } + p.printValue(f.Index(i), verb, depth+1) + } + p.WriteByte('}') + } else { + p.WriteByte('[') + for i := 0; i < f.Len(); i++ { + if i > 0 { + p.WriteByte(' ') + } + p.printValue(f.Index(i), verb, depth+1) + } + p.WriteByte(']') + } + case reflect.Ptr: + // pointer to array or slice or struct? ok at top level + // but not embedded (avoid loops) + if depth == 0 && f.Pointer() != 0 { + switch a := f.Elem(); a.Kind() { + case reflect.Array, reflect.Slice, reflect.Struct, reflect.Map: + p.WriteByte('&') + p.printValue(a, verb, depth+1) + return + } + } + fallthrough + case reflect.Chan, reflect.Func, reflect.UnsafePointer: + p.fmtPointer(f, verb) + default: + p.unknownType(f) + } +} + +func (p *printer) badArgNum(verb rune) { + p.WriteString(percentBangString) + p.WriteRune(verb) + p.WriteString(badIndexString) +} + +func (p *printer) missingArg(verb rune) { + p.WriteString(percentBangString) + p.WriteRune(verb) + p.WriteString(missingString) +} + +func (p *printer) doPrintf(fmt string) { + for p.fmt.Parser.SetFormat(fmt); p.fmt.Scan(); { + switch p.fmt.Status { + case format.StatusText: + p.WriteString(p.fmt.Text()) + case format.StatusSubstitution: + p.printArg(p.Arg(p.fmt.ArgNum), p.fmt.Verb) + case format.StatusBadWidthSubstitution: + p.WriteString(badWidthString) + p.printArg(p.Arg(p.fmt.ArgNum), p.fmt.Verb) + case format.StatusBadPrecSubstitution: + p.WriteString(badPrecString) + p.printArg(p.Arg(p.fmt.ArgNum), p.fmt.Verb) + case format.StatusNoVerb: + p.WriteString(noVerbString) + case format.StatusBadArgNum: + p.badArgNum(p.fmt.Verb) + case format.StatusMissingArg: + p.missingArg(p.fmt.Verb) + default: + panic("unreachable") + } + } + + // Check for extra arguments, but only if there was at least one ordered + // argument. Note that this behavior is necessarily different from fmt: + // different variants of messages may opt to drop some or all of the + // arguments. + if !p.fmt.Reordered && p.fmt.ArgNum < len(p.fmt.Args) && p.fmt.ArgNum != 0 { + p.fmt.ClearFlags() + p.WriteString(extraString) + for i, arg := range p.fmt.Args[p.fmt.ArgNum:] { + if i > 0 { + p.WriteString(commaSpaceString) + } + if arg == nil { + p.WriteString(nilAngleString) + } else { + p.WriteString(reflect.TypeOf(arg).String()) + p.WriteString("=") + p.printArg(arg, 'v') + } + } + p.WriteByte(')') + } +} + +func (p *printer) doPrint(a []interface{}) { + prevString := false + for argNum, arg := range a { + isString := arg != nil && reflect.TypeOf(arg).Kind() == reflect.String + // Add a space between two non-string arguments. + if argNum > 0 && !isString && !prevString { + p.WriteByte(' ') + } + p.printArg(arg, 'v') + prevString = isString + } +} + +// doPrintln is like doPrint but always adds a space between arguments +// and a newline after the last argument. +func (p *printer) doPrintln(a []interface{}) { + for argNum, arg := range a { + if argNum > 0 { + p.WriteByte(' ') + } + p.printArg(arg, 'v') + } + p.WriteByte('\n') +} diff --git a/vendor/golang.org/x/time/LICENSE b/vendor/golang.org/x/time/LICENSE new file mode 100644 index 00000000..2a7cf70d --- /dev/null +++ b/vendor/golang.org/x/time/LICENSE @@ -0,0 +1,27 @@ +Copyright 2009 The Go Authors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google LLC nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/golang.org/x/time/PATENTS b/vendor/golang.org/x/time/PATENTS new file mode 100644 index 00000000..73309904 --- /dev/null +++ b/vendor/golang.org/x/time/PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the Go project. + +Google hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) +patent license to make, have made, use, offer to sell, sell, import, +transfer and otherwise run, modify and propagate the contents of this +implementation of Go, where such license applies only to those patent +claims, both currently owned or controlled by Google and acquired in +the future, licensable by Google that are necessarily infringed by this +implementation of Go. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute or +order or agree to the institution of patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging +that this implementation of Go or any code incorporated within this +implementation of Go constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of Go +shall terminate as of the date such litigation is filed. diff --git a/vendor/golang.org/x/time/rate/rate.go b/vendor/golang.org/x/time/rate/rate.go new file mode 100644 index 00000000..794b2e32 --- /dev/null +++ b/vendor/golang.org/x/time/rate/rate.go @@ -0,0 +1,427 @@ +// Copyright 2015 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 rate provides a rate limiter. +package rate + +import ( + "context" + "fmt" + "math" + "sync" + "time" +) + +// Limit defines the maximum frequency of some events. +// Limit is represented as number of events per second. +// A zero Limit allows no events. +type Limit float64 + +// Inf is the infinite rate limit; it allows all events (even if burst is zero). +const Inf = Limit(math.MaxFloat64) + +// Every converts a minimum time interval between events to a Limit. +func Every(interval time.Duration) Limit { + if interval <= 0 { + return Inf + } + return 1 / Limit(interval.Seconds()) +} + +// A Limiter controls how frequently events are allowed to happen. +// It implements a "token bucket" of size b, initially full and refilled +// at rate r tokens per second. +// Informally, in any large enough time interval, the Limiter limits the +// rate to r tokens per second, with a maximum burst size of b events. +// As a special case, if r == Inf (the infinite rate), b is ignored. +// See https://en.wikipedia.org/wiki/Token_bucket for more about token buckets. +// +// The zero value is a valid Limiter, but it will reject all events. +// Use NewLimiter to create non-zero Limiters. +// +// Limiter has three main methods, Allow, Reserve, and Wait. +// Most callers should use Wait. +// +// Each of the three methods consumes a single token. +// They differ in their behavior when no token is available. +// If no token is available, Allow returns false. +// If no token is available, Reserve returns a reservation for a future token +// and the amount of time the caller must wait before using it. +// If no token is available, Wait blocks until one can be obtained +// or its associated context.Context is canceled. +// +// The methods AllowN, ReserveN, and WaitN consume n tokens. +// +// Limiter is safe for simultaneous use by multiple goroutines. +type Limiter struct { + mu sync.Mutex + limit Limit + burst int + tokens float64 + // last is the last time the limiter's tokens field was updated + last time.Time + // lastEvent is the latest time of a rate-limited event (past or future) + lastEvent time.Time +} + +// Limit returns the maximum overall event rate. +func (lim *Limiter) Limit() Limit { + lim.mu.Lock() + defer lim.mu.Unlock() + return lim.limit +} + +// Burst returns the maximum burst size. Burst is the maximum number of tokens +// that can be consumed in a single call to Allow, Reserve, or Wait, so higher +// Burst values allow more events to happen at once. +// A zero Burst allows no events, unless limit == Inf. +func (lim *Limiter) Burst() int { + lim.mu.Lock() + defer lim.mu.Unlock() + return lim.burst +} + +// TokensAt returns the number of tokens available at time t. +func (lim *Limiter) TokensAt(t time.Time) float64 { + lim.mu.Lock() + tokens := lim.advance(t) // does not mutate lim + lim.mu.Unlock() + return tokens +} + +// Tokens returns the number of tokens available now. +func (lim *Limiter) Tokens() float64 { + return lim.TokensAt(time.Now()) +} + +// NewLimiter returns a new Limiter that allows events up to rate r and permits +// bursts of at most b tokens. +func NewLimiter(r Limit, b int) *Limiter { + return &Limiter{ + limit: r, + burst: b, + tokens: float64(b), + } +} + +// Allow reports whether an event may happen now. +func (lim *Limiter) Allow() bool { + return lim.AllowN(time.Now(), 1) +} + +// AllowN reports whether n events may happen at time t. +// Use this method if you intend to drop / skip events that exceed the rate limit. +// Otherwise use Reserve or Wait. +func (lim *Limiter) AllowN(t time.Time, n int) bool { + return lim.reserveN(t, n, 0).ok +} + +// A Reservation holds information about events that are permitted by a Limiter to happen after a delay. +// A Reservation may be canceled, which may enable the Limiter to permit additional events. +type Reservation struct { + ok bool + lim *Limiter + tokens int + timeToAct time.Time + // This is the Limit at reservation time, it can change later. + limit Limit +} + +// OK returns whether the limiter can provide the requested number of tokens +// within the maximum wait time. If OK is false, Delay returns InfDuration, and +// Cancel does nothing. +func (r *Reservation) OK() bool { + return r.ok +} + +// Delay is shorthand for DelayFrom(time.Now()). +func (r *Reservation) Delay() time.Duration { + return r.DelayFrom(time.Now()) +} + +// InfDuration is the duration returned by Delay when a Reservation is not OK. +const InfDuration = time.Duration(math.MaxInt64) + +// DelayFrom returns the duration for which the reservation holder must wait +// before taking the reserved action. Zero duration means act immediately. +// InfDuration means the limiter cannot grant the tokens requested in this +// Reservation within the maximum wait time. +func (r *Reservation) DelayFrom(t time.Time) time.Duration { + if !r.ok { + return InfDuration + } + delay := r.timeToAct.Sub(t) + if delay < 0 { + return 0 + } + return delay +} + +// Cancel is shorthand for CancelAt(time.Now()). +func (r *Reservation) Cancel() { + r.CancelAt(time.Now()) +} + +// CancelAt indicates that the reservation holder will not perform the reserved action +// and reverses the effects of this Reservation on the rate limit as much as possible, +// considering that other reservations may have already been made. +func (r *Reservation) CancelAt(t time.Time) { + if !r.ok { + return + } + + r.lim.mu.Lock() + defer r.lim.mu.Unlock() + + if r.lim.limit == Inf || r.tokens == 0 || r.timeToAct.Before(t) { + return + } + + // calculate tokens to restore + // The duration between lim.lastEvent and r.timeToAct tells us how many tokens were reserved + // after r was obtained. These tokens should not be restored. + restoreTokens := float64(r.tokens) - r.limit.tokensFromDuration(r.lim.lastEvent.Sub(r.timeToAct)) + if restoreTokens <= 0 { + return + } + // advance time to now + tokens := r.lim.advance(t) + // calculate new number of tokens + tokens += restoreTokens + if burst := float64(r.lim.burst); tokens > burst { + tokens = burst + } + // update state + r.lim.last = t + r.lim.tokens = tokens + if r.timeToAct == r.lim.lastEvent { + prevEvent := r.timeToAct.Add(r.limit.durationFromTokens(float64(-r.tokens))) + if !prevEvent.Before(t) { + r.lim.lastEvent = prevEvent + } + } +} + +// Reserve is shorthand for ReserveN(time.Now(), 1). +func (lim *Limiter) Reserve() *Reservation { + return lim.ReserveN(time.Now(), 1) +} + +// ReserveN returns a Reservation that indicates how long the caller must wait before n events happen. +// The Limiter takes this Reservation into account when allowing future events. +// The returned Reservation’s OK() method returns false if n exceeds the Limiter's burst size. +// Usage example: +// +// r := lim.ReserveN(time.Now(), 1) +// if !r.OK() { +// // Not allowed to act! Did you remember to set lim.burst to be > 0 ? +// return +// } +// time.Sleep(r.Delay()) +// Act() +// +// Use this method if you wish to wait and slow down in accordance with the rate limit without dropping events. +// If you need to respect a deadline or cancel the delay, use Wait instead. +// To drop or skip events exceeding rate limit, use Allow instead. +func (lim *Limiter) ReserveN(t time.Time, n int) *Reservation { + r := lim.reserveN(t, n, InfDuration) + return &r +} + +// Wait is shorthand for WaitN(ctx, 1). +func (lim *Limiter) Wait(ctx context.Context) (err error) { + return lim.WaitN(ctx, 1) +} + +// WaitN blocks until lim permits n events to happen. +// It returns an error if n exceeds the Limiter's burst size, the Context is +// canceled, or the expected wait time exceeds the Context's Deadline. +// The burst limit is ignored if the rate limit is Inf. +func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) { + // The test code calls lim.wait with a fake timer generator. + // This is the real timer generator. + newTimer := func(d time.Duration) (<-chan time.Time, func() bool, func()) { + timer := time.NewTimer(d) + return timer.C, timer.Stop, func() {} + } + + return lim.wait(ctx, n, time.Now(), newTimer) +} + +// wait is the internal implementation of WaitN. +func (lim *Limiter) wait(ctx context.Context, n int, t time.Time, newTimer func(d time.Duration) (<-chan time.Time, func() bool, func())) error { + lim.mu.Lock() + burst := lim.burst + limit := lim.limit + lim.mu.Unlock() + + if n > burst && limit != Inf { + return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, burst) + } + // Check if ctx is already cancelled + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + // Determine wait limit + waitLimit := InfDuration + if deadline, ok := ctx.Deadline(); ok { + waitLimit = deadline.Sub(t) + } + // Reserve + r := lim.reserveN(t, n, waitLimit) + if !r.ok { + return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n) + } + // Wait if necessary + delay := r.DelayFrom(t) + if delay == 0 { + return nil + } + ch, stop, advance := newTimer(delay) + defer stop() + advance() // only has an effect when testing + select { + case <-ch: + // We can proceed. + return nil + case <-ctx.Done(): + // Context was canceled before we could proceed. Cancel the + // reservation, which may permit other events to proceed sooner. + r.Cancel() + return ctx.Err() + } +} + +// SetLimit is shorthand for SetLimitAt(time.Now(), newLimit). +func (lim *Limiter) SetLimit(newLimit Limit) { + lim.SetLimitAt(time.Now(), newLimit) +} + +// SetLimitAt sets a new Limit for the limiter. The new Limit, and Burst, may be violated +// or underutilized by those which reserved (using Reserve or Wait) but did not yet act +// before SetLimitAt was called. +func (lim *Limiter) SetLimitAt(t time.Time, newLimit Limit) { + lim.mu.Lock() + defer lim.mu.Unlock() + + tokens := lim.advance(t) + + lim.last = t + lim.tokens = tokens + lim.limit = newLimit +} + +// SetBurst is shorthand for SetBurstAt(time.Now(), newBurst). +func (lim *Limiter) SetBurst(newBurst int) { + lim.SetBurstAt(time.Now(), newBurst) +} + +// SetBurstAt sets a new burst size for the limiter. +func (lim *Limiter) SetBurstAt(t time.Time, newBurst int) { + lim.mu.Lock() + defer lim.mu.Unlock() + + tokens := lim.advance(t) + + lim.last = t + lim.tokens = tokens + lim.burst = newBurst +} + +// reserveN is a helper method for AllowN, ReserveN, and WaitN. +// maxFutureReserve specifies the maximum reservation wait duration allowed. +// reserveN returns Reservation, not *Reservation, to avoid allocation in AllowN and WaitN. +func (lim *Limiter) reserveN(t time.Time, n int, maxFutureReserve time.Duration) Reservation { + lim.mu.Lock() + defer lim.mu.Unlock() + + if lim.limit == Inf { + return Reservation{ + ok: true, + lim: lim, + tokens: n, + timeToAct: t, + } + } + + tokens := lim.advance(t) + + // Calculate the remaining number of tokens resulting from the request. + tokens -= float64(n) + + // Calculate the wait duration + var waitDuration time.Duration + if tokens < 0 { + waitDuration = lim.limit.durationFromTokens(-tokens) + } + + // Decide result + ok := n <= lim.burst && waitDuration <= maxFutureReserve + + // Prepare reservation + r := Reservation{ + ok: ok, + lim: lim, + limit: lim.limit, + } + if ok { + r.tokens = n + r.timeToAct = t.Add(waitDuration) + + // Update state + lim.last = t + lim.tokens = tokens + lim.lastEvent = r.timeToAct + } + + return r +} + +// advance calculates and returns an updated number of tokens for lim +// resulting from the passage of time. +// lim is not changed. +// advance requires that lim.mu is held. +func (lim *Limiter) advance(t time.Time) (newTokens float64) { + last := lim.last + if t.Before(last) { + last = t + } + + // Calculate the new number of tokens, due to time that passed. + elapsed := t.Sub(last) + delta := lim.limit.tokensFromDuration(elapsed) + tokens := lim.tokens + delta + if burst := float64(lim.burst); tokens > burst { + tokens = burst + } + return tokens +} + +// durationFromTokens is a unit conversion function from the number of tokens to the duration +// of time it takes to accumulate them at a rate of limit tokens per second. +func (limit Limit) durationFromTokens(tokens float64) time.Duration { + if limit <= 0 { + return InfDuration + } + + duration := (tokens / float64(limit)) * float64(time.Second) + + // Cap the duration to the maximum representable int64 value, to avoid overflow. + if duration > float64(math.MaxInt64) { + return InfDuration + } + + return time.Duration(duration) +} + +// tokensFromDuration is a unit conversion function from a time duration to the number of tokens +// which could be accumulated during that duration at a rate of limit tokens per second. +func (limit Limit) tokensFromDuration(d time.Duration) float64 { + if limit <= 0 { + return 0 + } + return d.Seconds() * float64(limit) +} diff --git a/vendor/golang.org/x/time/rate/sometimes.go b/vendor/golang.org/x/time/rate/sometimes.go new file mode 100644 index 00000000..9b839326 --- /dev/null +++ b/vendor/golang.org/x/time/rate/sometimes.go @@ -0,0 +1,69 @@ +// Copyright 2022 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 rate + +import ( + "sync" + "time" +) + +// Sometimes will perform an action occasionally. The First, Every, and +// Interval fields govern the behavior of Do, which performs the action. +// A zero Sometimes value will perform an action exactly once. +// +// # Example: logging with rate limiting +// +// var sometimes = rate.Sometimes{First: 3, Interval: 10*time.Second} +// func Spammy() { +// sometimes.Do(func() { log.Info("here I am!") }) +// } +type Sometimes struct { + First int // if non-zero, the first N calls to Do will run f. + Every int // if non-zero, every Nth call to Do will run f. + Interval time.Duration // if non-zero and Interval has elapsed since f's last run, Do will run f. + + mu sync.Mutex + count int // number of Do calls + last time.Time // last time f was run +} + +// Do runs the function f as allowed by First, Every, and Interval. +// +// The model is a union (not intersection) of filters. The first call to Do +// always runs f. Subsequent calls to Do run f if allowed by First or Every or +// Interval. +// +// A non-zero First:N causes the first N Do(f) calls to run f. +// +// A non-zero Every:M causes every Mth Do(f) call, starting with the first, to +// run f. +// +// A non-zero Interval causes Do(f) to run f if Interval has elapsed since +// Do last ran f. +// +// Specifying multiple filters produces the union of these execution streams. +// For example, specifying both First:N and Every:M causes the first N Do(f) +// calls and every Mth Do(f) call, starting with the first, to run f. See +// Examples for more. +// +// If Do is called multiple times simultaneously, the calls will block and run +// serially. Therefore, Do is intended for lightweight operations. +// +// Because a call to Do may block until f returns, if f causes Do to be called, +// it will deadlock. +func (s *Sometimes) Do(f func()) { + s.mu.Lock() + defer s.mu.Unlock() + if s.count == 0 || + (s.First > 0 && s.count < s.First) || + (s.Every > 0 && s.count%s.Every == 0) || + (s.Interval > 0 && time.Since(s.last) >= s.Interval) { + f() + if s.Interval > 0 { + s.last = time.Now() + } + } + s.count++ +} diff --git a/vendor/gopkg.in/yaml.v2/.travis.yml b/vendor/gopkg.in/yaml.v2/.travis.yml new file mode 100644 index 00000000..7348c50c --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/.travis.yml @@ -0,0 +1,17 @@ +language: go + +go: + - "1.4.x" + - "1.5.x" + - "1.6.x" + - "1.7.x" + - "1.8.x" + - "1.9.x" + - "1.10.x" + - "1.11.x" + - "1.12.x" + - "1.13.x" + - "1.14.x" + - "tip" + +go_import_path: gopkg.in/yaml.v2 diff --git a/vendor/gopkg.in/yaml.v2/LICENSE b/vendor/gopkg.in/yaml.v2/LICENSE new file mode 100644 index 00000000..8dada3ed --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/gopkg.in/yaml.v2/LICENSE.libyaml b/vendor/gopkg.in/yaml.v2/LICENSE.libyaml new file mode 100644 index 00000000..8da58fbf --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/LICENSE.libyaml @@ -0,0 +1,31 @@ +The following files were ported to Go from C files of libyaml, and thus +are still covered by their original copyright and license: + + apic.go + emitterc.go + parserc.go + readerc.go + scannerc.go + writerc.go + yamlh.go + yamlprivateh.go + +Copyright (c) 2006 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/gopkg.in/yaml.v2/NOTICE b/vendor/gopkg.in/yaml.v2/NOTICE new file mode 100644 index 00000000..866d74a7 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/NOTICE @@ -0,0 +1,13 @@ +Copyright 2011-2016 Canonical Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/gopkg.in/yaml.v2/README.md b/vendor/gopkg.in/yaml.v2/README.md new file mode 100644 index 00000000..b50c6e87 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/README.md @@ -0,0 +1,133 @@ +# YAML support for the Go language + +Introduction +------------ + +The yaml package enables Go programs to comfortably encode and decode YAML +values. It was developed within [Canonical](https://www.canonical.com) as +part of the [juju](https://juju.ubuntu.com) project, and is based on a +pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) +C library to parse and generate YAML data quickly and reliably. + +Compatibility +------------- + +The yaml package supports most of YAML 1.1 and 1.2, including support for +anchors, tags, map merging, etc. Multi-document unmarshalling is not yet +implemented, and base-60 floats from YAML 1.1 are purposefully not +supported since they're a poor design and are gone in YAML 1.2. + +Installation and usage +---------------------- + +The import path for the package is *gopkg.in/yaml.v2*. + +To install it, run: + + go get gopkg.in/yaml.v2 + +API documentation +----------------- + +If opened in a browser, the import path itself leads to the API documentation: + + * [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2) + +API stability +------------- + +The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in). + + +License +------- + +The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details. + + +Example +------- + +```Go +package main + +import ( + "fmt" + "log" + + "gopkg.in/yaml.v2" +) + +var data = ` +a: Easy! +b: + c: 2 + d: [3, 4] +` + +// Note: struct fields must be public in order for unmarshal to +// correctly populate the data. +type T struct { + A string + B struct { + RenamedC int `yaml:"c"` + D []int `yaml:",flow"` + } +} + +func main() { + t := T{} + + err := yaml.Unmarshal([]byte(data), &t) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- t:\n%v\n\n", t) + + d, err := yaml.Marshal(&t) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- t dump:\n%s\n\n", string(d)) + + m := make(map[interface{}]interface{}) + + err = yaml.Unmarshal([]byte(data), &m) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- m:\n%v\n\n", m) + + d, err = yaml.Marshal(&m) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- m dump:\n%s\n\n", string(d)) +} +``` + +This example will generate the following output: + +``` +--- t: +{Easy! {2 [3 4]}} + +--- t dump: +a: Easy! +b: + c: 2 + d: [3, 4] + + +--- m: +map[a:Easy! b:map[c:2 d:[3 4]]] + +--- m dump: +a: Easy! +b: + c: 2 + d: + - 3 + - 4 +``` + diff --git a/vendor/gopkg.in/yaml.v2/apic.go b/vendor/gopkg.in/yaml.v2/apic.go new file mode 100644 index 00000000..acf71402 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/apic.go @@ -0,0 +1,744 @@ +package yaml + +import ( + "io" +) + +func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { + //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) + + // Check if we can move the queue at the beginning of the buffer. + if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { + if parser.tokens_head != len(parser.tokens) { + copy(parser.tokens, parser.tokens[parser.tokens_head:]) + } + parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head] + parser.tokens_head = 0 + } + parser.tokens = append(parser.tokens, *token) + if pos < 0 { + return + } + copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:]) + parser.tokens[parser.tokens_head+pos] = *token +} + +// Create a new parser object. +func yaml_parser_initialize(parser *yaml_parser_t) bool { + *parser = yaml_parser_t{ + raw_buffer: make([]byte, 0, input_raw_buffer_size), + buffer: make([]byte, 0, input_buffer_size), + } + return true +} + +// Destroy a parser object. +func yaml_parser_delete(parser *yaml_parser_t) { + *parser = yaml_parser_t{} +} + +// String read handler. +func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { + if parser.input_pos == len(parser.input) { + return 0, io.EOF + } + n = copy(buffer, parser.input[parser.input_pos:]) + parser.input_pos += n + return n, nil +} + +// Reader read handler. +func yaml_reader_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { + return parser.input_reader.Read(buffer) +} + +// Set a string input. +func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { + if parser.read_handler != nil { + panic("must set the input source only once") + } + parser.read_handler = yaml_string_read_handler + parser.input = input + parser.input_pos = 0 +} + +// Set a file input. +func yaml_parser_set_input_reader(parser *yaml_parser_t, r io.Reader) { + if parser.read_handler != nil { + panic("must set the input source only once") + } + parser.read_handler = yaml_reader_read_handler + parser.input_reader = r +} + +// Set the source encoding. +func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { + if parser.encoding != yaml_ANY_ENCODING { + panic("must set the encoding only once") + } + parser.encoding = encoding +} + +var disableLineWrapping = false + +// Create a new emitter object. +func yaml_emitter_initialize(emitter *yaml_emitter_t) { + *emitter = yaml_emitter_t{ + buffer: make([]byte, output_buffer_size), + raw_buffer: make([]byte, 0, output_raw_buffer_size), + states: make([]yaml_emitter_state_t, 0, initial_stack_size), + events: make([]yaml_event_t, 0, initial_queue_size), + } + if disableLineWrapping { + emitter.best_width = -1 + } +} + +// Destroy an emitter object. +func yaml_emitter_delete(emitter *yaml_emitter_t) { + *emitter = yaml_emitter_t{} +} + +// String write handler. +func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error { + *emitter.output_buffer = append(*emitter.output_buffer, buffer...) + return nil +} + +// yaml_writer_write_handler uses emitter.output_writer to write the +// emitted text. +func yaml_writer_write_handler(emitter *yaml_emitter_t, buffer []byte) error { + _, err := emitter.output_writer.Write(buffer) + return err +} + +// Set a string output. +func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) { + if emitter.write_handler != nil { + panic("must set the output target only once") + } + emitter.write_handler = yaml_string_write_handler + emitter.output_buffer = output_buffer +} + +// Set a file output. +func yaml_emitter_set_output_writer(emitter *yaml_emitter_t, w io.Writer) { + if emitter.write_handler != nil { + panic("must set the output target only once") + } + emitter.write_handler = yaml_writer_write_handler + emitter.output_writer = w +} + +// Set the output encoding. +func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) { + if emitter.encoding != yaml_ANY_ENCODING { + panic("must set the output encoding only once") + } + emitter.encoding = encoding +} + +// Set the canonical output style. +func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { + emitter.canonical = canonical +} + +//// Set the indentation increment. +func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { + if indent < 2 || indent > 9 { + indent = 2 + } + emitter.best_indent = indent +} + +// Set the preferred line width. +func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) { + if width < 0 { + width = -1 + } + emitter.best_width = width +} + +// Set if unescaped non-ASCII characters are allowed. +func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) { + emitter.unicode = unicode +} + +// Set the preferred line break character. +func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) { + emitter.line_break = line_break +} + +///* +// * Destroy a token object. +// */ +// +//YAML_DECLARE(void) +//yaml_token_delete(yaml_token_t *token) +//{ +// assert(token); // Non-NULL token object expected. +// +// switch (token.type) +// { +// case YAML_TAG_DIRECTIVE_TOKEN: +// yaml_free(token.data.tag_directive.handle); +// yaml_free(token.data.tag_directive.prefix); +// break; +// +// case YAML_ALIAS_TOKEN: +// yaml_free(token.data.alias.value); +// break; +// +// case YAML_ANCHOR_TOKEN: +// yaml_free(token.data.anchor.value); +// break; +// +// case YAML_TAG_TOKEN: +// yaml_free(token.data.tag.handle); +// yaml_free(token.data.tag.suffix); +// break; +// +// case YAML_SCALAR_TOKEN: +// yaml_free(token.data.scalar.value); +// break; +// +// default: +// break; +// } +// +// memset(token, 0, sizeof(yaml_token_t)); +//} +// +///* +// * Check if a string is a valid UTF-8 sequence. +// * +// * Check 'reader.c' for more details on UTF-8 encoding. +// */ +// +//static int +//yaml_check_utf8(yaml_char_t *start, size_t length) +//{ +// yaml_char_t *end = start+length; +// yaml_char_t *pointer = start; +// +// while (pointer < end) { +// unsigned char octet; +// unsigned int width; +// unsigned int value; +// size_t k; +// +// octet = pointer[0]; +// width = (octet & 0x80) == 0x00 ? 1 : +// (octet & 0xE0) == 0xC0 ? 2 : +// (octet & 0xF0) == 0xE0 ? 3 : +// (octet & 0xF8) == 0xF0 ? 4 : 0; +// value = (octet & 0x80) == 0x00 ? octet & 0x7F : +// (octet & 0xE0) == 0xC0 ? octet & 0x1F : +// (octet & 0xF0) == 0xE0 ? octet & 0x0F : +// (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; +// if (!width) return 0; +// if (pointer+width > end) return 0; +// for (k = 1; k < width; k ++) { +// octet = pointer[k]; +// if ((octet & 0xC0) != 0x80) return 0; +// value = (value << 6) + (octet & 0x3F); +// } +// if (!((width == 1) || +// (width == 2 && value >= 0x80) || +// (width == 3 && value >= 0x800) || +// (width == 4 && value >= 0x10000))) return 0; +// +// pointer += width; +// } +// +// return 1; +//} +// + +// Create STREAM-START. +func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) { + *event = yaml_event_t{ + typ: yaml_STREAM_START_EVENT, + encoding: encoding, + } +} + +// Create STREAM-END. +func yaml_stream_end_event_initialize(event *yaml_event_t) { + *event = yaml_event_t{ + typ: yaml_STREAM_END_EVENT, + } +} + +// Create DOCUMENT-START. +func yaml_document_start_event_initialize( + event *yaml_event_t, + version_directive *yaml_version_directive_t, + tag_directives []yaml_tag_directive_t, + implicit bool, +) { + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + version_directive: version_directive, + tag_directives: tag_directives, + implicit: implicit, + } +} + +// Create DOCUMENT-END. +func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) { + *event = yaml_event_t{ + typ: yaml_DOCUMENT_END_EVENT, + implicit: implicit, + } +} + +///* +// * Create ALIAS. +// */ +// +//YAML_DECLARE(int) +//yaml_alias_event_initialize(event *yaml_event_t, anchor *yaml_char_t) +//{ +// mark yaml_mark_t = { 0, 0, 0 } +// anchor_copy *yaml_char_t = NULL +// +// assert(event) // Non-NULL event object is expected. +// assert(anchor) // Non-NULL anchor is expected. +// +// if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0 +// +// anchor_copy = yaml_strdup(anchor) +// if (!anchor_copy) +// return 0 +// +// ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark) +// +// return 1 +//} + +// Create SCALAR. +func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool { + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + anchor: anchor, + tag: tag, + value: value, + implicit: plain_implicit, + quoted_implicit: quoted_implicit, + style: yaml_style_t(style), + } + return true +} + +// Create SEQUENCE-START. +func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool { + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(style), + } + return true +} + +// Create SEQUENCE-END. +func yaml_sequence_end_event_initialize(event *yaml_event_t) bool { + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + } + return true +} + +// Create MAPPING-START. +func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) { + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(style), + } +} + +// Create MAPPING-END. +func yaml_mapping_end_event_initialize(event *yaml_event_t) { + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + } +} + +// Destroy an event object. +func yaml_event_delete(event *yaml_event_t) { + *event = yaml_event_t{} +} + +///* +// * Create a document object. +// */ +// +//YAML_DECLARE(int) +//yaml_document_initialize(document *yaml_document_t, +// version_directive *yaml_version_directive_t, +// tag_directives_start *yaml_tag_directive_t, +// tag_directives_end *yaml_tag_directive_t, +// start_implicit int, end_implicit int) +//{ +// struct { +// error yaml_error_type_t +// } context +// struct { +// start *yaml_node_t +// end *yaml_node_t +// top *yaml_node_t +// } nodes = { NULL, NULL, NULL } +// version_directive_copy *yaml_version_directive_t = NULL +// struct { +// start *yaml_tag_directive_t +// end *yaml_tag_directive_t +// top *yaml_tag_directive_t +// } tag_directives_copy = { NULL, NULL, NULL } +// value yaml_tag_directive_t = { NULL, NULL } +// mark yaml_mark_t = { 0, 0, 0 } +// +// assert(document) // Non-NULL document object is expected. +// assert((tag_directives_start && tag_directives_end) || +// (tag_directives_start == tag_directives_end)) +// // Valid tag directives are expected. +// +// if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error +// +// if (version_directive) { +// version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t)) +// if (!version_directive_copy) goto error +// version_directive_copy.major = version_directive.major +// version_directive_copy.minor = version_directive.minor +// } +// +// if (tag_directives_start != tag_directives_end) { +// tag_directive *yaml_tag_directive_t +// if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE)) +// goto error +// for (tag_directive = tag_directives_start +// tag_directive != tag_directives_end; tag_directive ++) { +// assert(tag_directive.handle) +// assert(tag_directive.prefix) +// if (!yaml_check_utf8(tag_directive.handle, +// strlen((char *)tag_directive.handle))) +// goto error +// if (!yaml_check_utf8(tag_directive.prefix, +// strlen((char *)tag_directive.prefix))) +// goto error +// value.handle = yaml_strdup(tag_directive.handle) +// value.prefix = yaml_strdup(tag_directive.prefix) +// if (!value.handle || !value.prefix) goto error +// if (!PUSH(&context, tag_directives_copy, value)) +// goto error +// value.handle = NULL +// value.prefix = NULL +// } +// } +// +// DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy, +// tag_directives_copy.start, tag_directives_copy.top, +// start_implicit, end_implicit, mark, mark) +// +// return 1 +// +//error: +// STACK_DEL(&context, nodes) +// yaml_free(version_directive_copy) +// while (!STACK_EMPTY(&context, tag_directives_copy)) { +// value yaml_tag_directive_t = POP(&context, tag_directives_copy) +// yaml_free(value.handle) +// yaml_free(value.prefix) +// } +// STACK_DEL(&context, tag_directives_copy) +// yaml_free(value.handle) +// yaml_free(value.prefix) +// +// return 0 +//} +// +///* +// * Destroy a document object. +// */ +// +//YAML_DECLARE(void) +//yaml_document_delete(document *yaml_document_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// tag_directive *yaml_tag_directive_t +// +// context.error = YAML_NO_ERROR // Eliminate a compiler warning. +// +// assert(document) // Non-NULL document object is expected. +// +// while (!STACK_EMPTY(&context, document.nodes)) { +// node yaml_node_t = POP(&context, document.nodes) +// yaml_free(node.tag) +// switch (node.type) { +// case YAML_SCALAR_NODE: +// yaml_free(node.data.scalar.value) +// break +// case YAML_SEQUENCE_NODE: +// STACK_DEL(&context, node.data.sequence.items) +// break +// case YAML_MAPPING_NODE: +// STACK_DEL(&context, node.data.mapping.pairs) +// break +// default: +// assert(0) // Should not happen. +// } +// } +// STACK_DEL(&context, document.nodes) +// +// yaml_free(document.version_directive) +// for (tag_directive = document.tag_directives.start +// tag_directive != document.tag_directives.end +// tag_directive++) { +// yaml_free(tag_directive.handle) +// yaml_free(tag_directive.prefix) +// } +// yaml_free(document.tag_directives.start) +// +// memset(document, 0, sizeof(yaml_document_t)) +//} +// +///** +// * Get a document node. +// */ +// +//YAML_DECLARE(yaml_node_t *) +//yaml_document_get_node(document *yaml_document_t, index int) +//{ +// assert(document) // Non-NULL document object is expected. +// +// if (index > 0 && document.nodes.start + index <= document.nodes.top) { +// return document.nodes.start + index - 1 +// } +// return NULL +//} +// +///** +// * Get the root object. +// */ +// +//YAML_DECLARE(yaml_node_t *) +//yaml_document_get_root_node(document *yaml_document_t) +//{ +// assert(document) // Non-NULL document object is expected. +// +// if (document.nodes.top != document.nodes.start) { +// return document.nodes.start +// } +// return NULL +//} +// +///* +// * Add a scalar node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_scalar(document *yaml_document_t, +// tag *yaml_char_t, value *yaml_char_t, length int, +// style yaml_scalar_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// value_copy *yaml_char_t = NULL +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// assert(value) // Non-NULL value is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (length < 0) { +// length = strlen((char *)value) +// } +// +// if (!yaml_check_utf8(value, length)) goto error +// value_copy = yaml_malloc(length+1) +// if (!value_copy) goto error +// memcpy(value_copy, value, length) +// value_copy[length] = '\0' +// +// SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// yaml_free(tag_copy) +// yaml_free(value_copy) +// +// return 0 +//} +// +///* +// * Add a sequence node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_sequence(document *yaml_document_t, +// tag *yaml_char_t, style yaml_sequence_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// struct { +// start *yaml_node_item_t +// end *yaml_node_item_t +// top *yaml_node_item_t +// } items = { NULL, NULL, NULL } +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error +// +// SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end, +// style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// STACK_DEL(&context, items) +// yaml_free(tag_copy) +// +// return 0 +//} +// +///* +// * Add a mapping node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_mapping(document *yaml_document_t, +// tag *yaml_char_t, style yaml_mapping_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// struct { +// start *yaml_node_pair_t +// end *yaml_node_pair_t +// top *yaml_node_pair_t +// } pairs = { NULL, NULL, NULL } +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error +// +// MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end, +// style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// STACK_DEL(&context, pairs) +// yaml_free(tag_copy) +// +// return 0 +//} +// +///* +// * Append an item to a sequence node. +// */ +// +//YAML_DECLARE(int) +//yaml_document_append_sequence_item(document *yaml_document_t, +// sequence int, item int) +//{ +// struct { +// error yaml_error_type_t +// } context +// +// assert(document) // Non-NULL document is required. +// assert(sequence > 0 +// && document.nodes.start + sequence <= document.nodes.top) +// // Valid sequence id is required. +// assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE) +// // A sequence node is required. +// assert(item > 0 && document.nodes.start + item <= document.nodes.top) +// // Valid item id is required. +// +// if (!PUSH(&context, +// document.nodes.start[sequence-1].data.sequence.items, item)) +// return 0 +// +// return 1 +//} +// +///* +// * Append a pair of a key and a value to a mapping node. +// */ +// +//YAML_DECLARE(int) +//yaml_document_append_mapping_pair(document *yaml_document_t, +// mapping int, key int, value int) +//{ +// struct { +// error yaml_error_type_t +// } context +// +// pair yaml_node_pair_t +// +// assert(document) // Non-NULL document is required. +// assert(mapping > 0 +// && document.nodes.start + mapping <= document.nodes.top) +// // Valid mapping id is required. +// assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE) +// // A mapping node is required. +// assert(key > 0 && document.nodes.start + key <= document.nodes.top) +// // Valid key id is required. +// assert(value > 0 && document.nodes.start + value <= document.nodes.top) +// // Valid value id is required. +// +// pair.key = key +// pair.value = value +// +// if (!PUSH(&context, +// document.nodes.start[mapping-1].data.mapping.pairs, pair)) +// return 0 +// +// return 1 +//} +// +// diff --git a/vendor/gopkg.in/yaml.v2/decode.go b/vendor/gopkg.in/yaml.v2/decode.go new file mode 100644 index 00000000..129bc2a9 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/decode.go @@ -0,0 +1,815 @@ +package yaml + +import ( + "encoding" + "encoding/base64" + "fmt" + "io" + "math" + "reflect" + "strconv" + "time" +) + +const ( + documentNode = 1 << iota + mappingNode + sequenceNode + scalarNode + aliasNode +) + +type node struct { + kind int + line, column int + tag string + // For an alias node, alias holds the resolved alias. + alias *node + value string + implicit bool + children []*node + anchors map[string]*node +} + +// ---------------------------------------------------------------------------- +// Parser, produces a node tree out of a libyaml event stream. + +type parser struct { + parser yaml_parser_t + event yaml_event_t + doc *node + doneInit bool +} + +func newParser(b []byte) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + if len(b) == 0 { + b = []byte{'\n'} + } + yaml_parser_set_input_string(&p.parser, b) + return &p +} + +func newParserFromReader(r io.Reader) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + yaml_parser_set_input_reader(&p.parser, r) + return &p +} + +func (p *parser) init() { + if p.doneInit { + return + } + p.expect(yaml_STREAM_START_EVENT) + p.doneInit = true +} + +func (p *parser) destroy() { + if p.event.typ != yaml_NO_EVENT { + yaml_event_delete(&p.event) + } + yaml_parser_delete(&p.parser) +} + +// expect consumes an event from the event stream and +// checks that it's of the expected type. +func (p *parser) expect(e yaml_event_type_t) { + if p.event.typ == yaml_NO_EVENT { + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + } + if p.event.typ == yaml_STREAM_END_EVENT { + failf("attempted to go past the end of stream; corrupted value?") + } + if p.event.typ != e { + p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ) + p.fail() + } + yaml_event_delete(&p.event) + p.event.typ = yaml_NO_EVENT +} + +// peek peeks at the next event in the event stream, +// puts the results into p.event and returns the event type. +func (p *parser) peek() yaml_event_type_t { + if p.event.typ != yaml_NO_EVENT { + return p.event.typ + } + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + return p.event.typ +} + +func (p *parser) fail() { + var where string + var line int + if p.parser.problem_mark.line != 0 { + line = p.parser.problem_mark.line + // Scanner errors don't iterate line before returning error + if p.parser.error == yaml_SCANNER_ERROR { + line++ + } + } else if p.parser.context_mark.line != 0 { + line = p.parser.context_mark.line + } + if line != 0 { + where = "line " + strconv.Itoa(line) + ": " + } + var msg string + if len(p.parser.problem) > 0 { + msg = p.parser.problem + } else { + msg = "unknown problem parsing YAML content" + } + failf("%s%s", where, msg) +} + +func (p *parser) anchor(n *node, anchor []byte) { + if anchor != nil { + p.doc.anchors[string(anchor)] = n + } +} + +func (p *parser) parse() *node { + p.init() + switch p.peek() { + case yaml_SCALAR_EVENT: + return p.scalar() + case yaml_ALIAS_EVENT: + return p.alias() + case yaml_MAPPING_START_EVENT: + return p.mapping() + case yaml_SEQUENCE_START_EVENT: + return p.sequence() + case yaml_DOCUMENT_START_EVENT: + return p.document() + case yaml_STREAM_END_EVENT: + // Happens when attempting to decode an empty buffer. + return nil + default: + panic("attempted to parse unknown event: " + p.event.typ.String()) + } +} + +func (p *parser) node(kind int) *node { + return &node{ + kind: kind, + line: p.event.start_mark.line, + column: p.event.start_mark.column, + } +} + +func (p *parser) document() *node { + n := p.node(documentNode) + n.anchors = make(map[string]*node) + p.doc = n + p.expect(yaml_DOCUMENT_START_EVENT) + n.children = append(n.children, p.parse()) + p.expect(yaml_DOCUMENT_END_EVENT) + return n +} + +func (p *parser) alias() *node { + n := p.node(aliasNode) + n.value = string(p.event.anchor) + n.alias = p.doc.anchors[n.value] + if n.alias == nil { + failf("unknown anchor '%s' referenced", n.value) + } + p.expect(yaml_ALIAS_EVENT) + return n +} + +func (p *parser) scalar() *node { + n := p.node(scalarNode) + n.value = string(p.event.value) + n.tag = string(p.event.tag) + n.implicit = p.event.implicit + p.anchor(n, p.event.anchor) + p.expect(yaml_SCALAR_EVENT) + return n +} + +func (p *parser) sequence() *node { + n := p.node(sequenceNode) + p.anchor(n, p.event.anchor) + p.expect(yaml_SEQUENCE_START_EVENT) + for p.peek() != yaml_SEQUENCE_END_EVENT { + n.children = append(n.children, p.parse()) + } + p.expect(yaml_SEQUENCE_END_EVENT) + return n +} + +func (p *parser) mapping() *node { + n := p.node(mappingNode) + p.anchor(n, p.event.anchor) + p.expect(yaml_MAPPING_START_EVENT) + for p.peek() != yaml_MAPPING_END_EVENT { + n.children = append(n.children, p.parse(), p.parse()) + } + p.expect(yaml_MAPPING_END_EVENT) + return n +} + +// ---------------------------------------------------------------------------- +// Decoder, unmarshals a node into a provided value. + +type decoder struct { + doc *node + aliases map[*node]bool + mapType reflect.Type + terrors []string + strict bool + + decodeCount int + aliasCount int + aliasDepth int +} + +var ( + mapItemType = reflect.TypeOf(MapItem{}) + durationType = reflect.TypeOf(time.Duration(0)) + defaultMapType = reflect.TypeOf(map[interface{}]interface{}{}) + ifaceType = defaultMapType.Elem() + timeType = reflect.TypeOf(time.Time{}) + ptrTimeType = reflect.TypeOf(&time.Time{}) +) + +func newDecoder(strict bool) *decoder { + d := &decoder{mapType: defaultMapType, strict: strict} + d.aliases = make(map[*node]bool) + return d +} + +func (d *decoder) terror(n *node, tag string, out reflect.Value) { + if n.tag != "" { + tag = n.tag + } + value := n.value + if tag != yaml_SEQ_TAG && tag != yaml_MAP_TAG { + if len(value) > 10 { + value = " `" + value[:7] + "...`" + } else { + value = " `" + value + "`" + } + } + d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.line+1, shortTag(tag), value, out.Type())) +} + +func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) { + terrlen := len(d.terrors) + err := u.UnmarshalYAML(func(v interface{}) (err error) { + defer handleErr(&err) + d.unmarshal(n, reflect.ValueOf(v)) + if len(d.terrors) > terrlen { + issues := d.terrors[terrlen:] + d.terrors = d.terrors[:terrlen] + return &TypeError{issues} + } + return nil + }) + if e, ok := err.(*TypeError); ok { + d.terrors = append(d.terrors, e.Errors...) + return false + } + if err != nil { + fail(err) + } + return true +} + +// d.prepare initializes and dereferences pointers and calls UnmarshalYAML +// if a value is found to implement it. +// It returns the initialized and dereferenced out value, whether +// unmarshalling was already done by UnmarshalYAML, and if so whether +// its types unmarshalled appropriately. +// +// If n holds a null value, prepare returns before doing anything. +func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { + if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "~" || n.value == "" && n.implicit) { + return out, false, false + } + again := true + for again { + again = false + if out.Kind() == reflect.Ptr { + if out.IsNil() { + out.Set(reflect.New(out.Type().Elem())) + } + out = out.Elem() + again = true + } + if out.CanAddr() { + if u, ok := out.Addr().Interface().(Unmarshaler); ok { + good = d.callUnmarshaler(n, u) + return out, true, good + } + } + } + return out, false, false +} + +const ( + // 400,000 decode operations is ~500kb of dense object declarations, or + // ~5kb of dense object declarations with 10000% alias expansion + alias_ratio_range_low = 400000 + + // 4,000,000 decode operations is ~5MB of dense object declarations, or + // ~4.5MB of dense object declarations with 10% alias expansion + alias_ratio_range_high = 4000000 + + // alias_ratio_range is the range over which we scale allowed alias ratios + alias_ratio_range = float64(alias_ratio_range_high - alias_ratio_range_low) +) + +func allowedAliasRatio(decodeCount int) float64 { + switch { + case decodeCount <= alias_ratio_range_low: + // allow 99% to come from alias expansion for small-to-medium documents + return 0.99 + case decodeCount >= alias_ratio_range_high: + // allow 10% to come from alias expansion for very large documents + return 0.10 + default: + // scale smoothly from 99% down to 10% over the range. + // this maps to 396,000 - 400,000 allowed alias-driven decodes over the range. + // 400,000 decode operations is ~100MB of allocations in worst-case scenarios (single-item maps). + return 0.99 - 0.89*(float64(decodeCount-alias_ratio_range_low)/alias_ratio_range) + } +} + +func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) { + d.decodeCount++ + if d.aliasDepth > 0 { + d.aliasCount++ + } + if d.aliasCount > 100 && d.decodeCount > 1000 && float64(d.aliasCount)/float64(d.decodeCount) > allowedAliasRatio(d.decodeCount) { + failf("document contains excessive aliasing") + } + switch n.kind { + case documentNode: + return d.document(n, out) + case aliasNode: + return d.alias(n, out) + } + out, unmarshaled, good := d.prepare(n, out) + if unmarshaled { + return good + } + switch n.kind { + case scalarNode: + good = d.scalar(n, out) + case mappingNode: + good = d.mapping(n, out) + case sequenceNode: + good = d.sequence(n, out) + default: + panic("internal error: unknown node kind: " + strconv.Itoa(n.kind)) + } + return good +} + +func (d *decoder) document(n *node, out reflect.Value) (good bool) { + if len(n.children) == 1 { + d.doc = n + d.unmarshal(n.children[0], out) + return true + } + return false +} + +func (d *decoder) alias(n *node, out reflect.Value) (good bool) { + if d.aliases[n] { + // TODO this could actually be allowed in some circumstances. + failf("anchor '%s' value contains itself", n.value) + } + d.aliases[n] = true + d.aliasDepth++ + good = d.unmarshal(n.alias, out) + d.aliasDepth-- + delete(d.aliases, n) + return good +} + +var zeroValue reflect.Value + +func resetMap(out reflect.Value) { + for _, k := range out.MapKeys() { + out.SetMapIndex(k, zeroValue) + } +} + +func (d *decoder) scalar(n *node, out reflect.Value) bool { + var tag string + var resolved interface{} + if n.tag == "" && !n.implicit { + tag = yaml_STR_TAG + resolved = n.value + } else { + tag, resolved = resolve(n.tag, n.value) + if tag == yaml_BINARY_TAG { + data, err := base64.StdEncoding.DecodeString(resolved.(string)) + if err != nil { + failf("!!binary value contains invalid base64 data") + } + resolved = string(data) + } + } + if resolved == nil { + if out.Kind() == reflect.Map && !out.CanAddr() { + resetMap(out) + } else { + out.Set(reflect.Zero(out.Type())) + } + return true + } + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + // We've resolved to exactly the type we want, so use that. + out.Set(resolvedv) + return true + } + // Perhaps we can use the value as a TextUnmarshaler to + // set its value. + if out.CanAddr() { + u, ok := out.Addr().Interface().(encoding.TextUnmarshaler) + if ok { + var text []byte + if tag == yaml_BINARY_TAG { + text = []byte(resolved.(string)) + } else { + // We let any value be unmarshaled into TextUnmarshaler. + // That might be more lax than we'd like, but the + // TextUnmarshaler itself should bowl out any dubious values. + text = []byte(n.value) + } + err := u.UnmarshalText(text) + if err != nil { + fail(err) + } + return true + } + } + switch out.Kind() { + case reflect.String: + if tag == yaml_BINARY_TAG { + out.SetString(resolved.(string)) + return true + } + if resolved != nil { + out.SetString(n.value) + return true + } + case reflect.Interface: + if resolved == nil { + out.Set(reflect.Zero(out.Type())) + } else if tag == yaml_TIMESTAMP_TAG { + // It looks like a timestamp but for backward compatibility + // reasons we set it as a string, so that code that unmarshals + // timestamp-like values into interface{} will continue to + // see a string and not a time.Time. + // TODO(v3) Drop this. + out.Set(reflect.ValueOf(n.value)) + } else { + out.Set(reflect.ValueOf(resolved)) + } + return true + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + switch resolved := resolved.(type) { + case int: + if !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case int64: + if !out.OverflowInt(resolved) { + out.SetInt(resolved) + return true + } + case uint64: + if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case float64: + if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case string: + if out.Type() == durationType { + d, err := time.ParseDuration(resolved) + if err == nil { + out.SetInt(int64(d)) + return true + } + } + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + switch resolved := resolved.(type) { + case int: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case int64: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case uint64: + if !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case float64: + if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + } + case reflect.Bool: + switch resolved := resolved.(type) { + case bool: + out.SetBool(resolved) + return true + } + case reflect.Float32, reflect.Float64: + switch resolved := resolved.(type) { + case int: + out.SetFloat(float64(resolved)) + return true + case int64: + out.SetFloat(float64(resolved)) + return true + case uint64: + out.SetFloat(float64(resolved)) + return true + case float64: + out.SetFloat(resolved) + return true + } + case reflect.Struct: + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + out.Set(resolvedv) + return true + } + case reflect.Ptr: + if out.Type().Elem() == reflect.TypeOf(resolved) { + // TODO DOes this make sense? When is out a Ptr except when decoding a nil value? + elem := reflect.New(out.Type().Elem()) + elem.Elem().Set(reflect.ValueOf(resolved)) + out.Set(elem) + return true + } + } + d.terror(n, tag, out) + return false +} + +func settableValueOf(i interface{}) reflect.Value { + v := reflect.ValueOf(i) + sv := reflect.New(v.Type()).Elem() + sv.Set(v) + return sv +} + +func (d *decoder) sequence(n *node, out reflect.Value) (good bool) { + l := len(n.children) + + var iface reflect.Value + switch out.Kind() { + case reflect.Slice: + out.Set(reflect.MakeSlice(out.Type(), l, l)) + case reflect.Array: + if l != out.Len() { + failf("invalid array: want %d elements but got %d", out.Len(), l) + } + case reflect.Interface: + // No type hints. Will have to use a generic sequence. + iface = out + out = settableValueOf(make([]interface{}, l)) + default: + d.terror(n, yaml_SEQ_TAG, out) + return false + } + et := out.Type().Elem() + + j := 0 + for i := 0; i < l; i++ { + e := reflect.New(et).Elem() + if ok := d.unmarshal(n.children[i], e); ok { + out.Index(j).Set(e) + j++ + } + } + if out.Kind() != reflect.Array { + out.Set(out.Slice(0, j)) + } + if iface.IsValid() { + iface.Set(out) + } + return true +} + +func (d *decoder) mapping(n *node, out reflect.Value) (good bool) { + switch out.Kind() { + case reflect.Struct: + return d.mappingStruct(n, out) + case reflect.Slice: + return d.mappingSlice(n, out) + case reflect.Map: + // okay + case reflect.Interface: + if d.mapType.Kind() == reflect.Map { + iface := out + out = reflect.MakeMap(d.mapType) + iface.Set(out) + } else { + slicev := reflect.New(d.mapType).Elem() + if !d.mappingSlice(n, slicev) { + return false + } + out.Set(slicev) + return true + } + default: + d.terror(n, yaml_MAP_TAG, out) + return false + } + outt := out.Type() + kt := outt.Key() + et := outt.Elem() + + mapType := d.mapType + if outt.Key() == ifaceType && outt.Elem() == ifaceType { + d.mapType = outt + } + + if out.IsNil() { + out.Set(reflect.MakeMap(outt)) + } + l := len(n.children) + for i := 0; i < l; i += 2 { + if isMerge(n.children[i]) { + d.merge(n.children[i+1], out) + continue + } + k := reflect.New(kt).Elem() + if d.unmarshal(n.children[i], k) { + kkind := k.Kind() + if kkind == reflect.Interface { + kkind = k.Elem().Kind() + } + if kkind == reflect.Map || kkind == reflect.Slice { + failf("invalid map key: %#v", k.Interface()) + } + e := reflect.New(et).Elem() + if d.unmarshal(n.children[i+1], e) { + d.setMapIndex(n.children[i+1], out, k, e) + } + } + } + d.mapType = mapType + return true +} + +func (d *decoder) setMapIndex(n *node, out, k, v reflect.Value) { + if d.strict && out.MapIndex(k) != zeroValue { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: key %#v already set in map", n.line+1, k.Interface())) + return + } + out.SetMapIndex(k, v) +} + +func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) { + outt := out.Type() + if outt.Elem() != mapItemType { + d.terror(n, yaml_MAP_TAG, out) + return false + } + + mapType := d.mapType + d.mapType = outt + + var slice []MapItem + var l = len(n.children) + for i := 0; i < l; i += 2 { + if isMerge(n.children[i]) { + d.merge(n.children[i+1], out) + continue + } + item := MapItem{} + k := reflect.ValueOf(&item.Key).Elem() + if d.unmarshal(n.children[i], k) { + v := reflect.ValueOf(&item.Value).Elem() + if d.unmarshal(n.children[i+1], v) { + slice = append(slice, item) + } + } + } + out.Set(reflect.ValueOf(slice)) + d.mapType = mapType + return true +} + +func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) { + sinfo, err := getStructInfo(out.Type()) + if err != nil { + panic(err) + } + name := settableValueOf("") + l := len(n.children) + + var inlineMap reflect.Value + var elemType reflect.Type + if sinfo.InlineMap != -1 { + inlineMap = out.Field(sinfo.InlineMap) + inlineMap.Set(reflect.New(inlineMap.Type()).Elem()) + elemType = inlineMap.Type().Elem() + } + + var doneFields []bool + if d.strict { + doneFields = make([]bool, len(sinfo.FieldsList)) + } + for i := 0; i < l; i += 2 { + ni := n.children[i] + if isMerge(ni) { + d.merge(n.children[i+1], out) + continue + } + if !d.unmarshal(ni, name) { + continue + } + if info, ok := sinfo.FieldsMap[name.String()]; ok { + if d.strict { + if doneFields[info.Id] { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.line+1, name.String(), out.Type())) + continue + } + doneFields[info.Id] = true + } + var field reflect.Value + if info.Inline == nil { + field = out.Field(info.Num) + } else { + field = out.FieldByIndex(info.Inline) + } + d.unmarshal(n.children[i+1], field) + } else if sinfo.InlineMap != -1 { + if inlineMap.IsNil() { + inlineMap.Set(reflect.MakeMap(inlineMap.Type())) + } + value := reflect.New(elemType).Elem() + d.unmarshal(n.children[i+1], value) + d.setMapIndex(n.children[i+1], inlineMap, name, value) + } else if d.strict { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.line+1, name.String(), out.Type())) + } + } + return true +} + +func failWantMap() { + failf("map merge requires map or sequence of maps as the value") +} + +func (d *decoder) merge(n *node, out reflect.Value) { + switch n.kind { + case mappingNode: + d.unmarshal(n, out) + case aliasNode: + if n.alias != nil && n.alias.kind != mappingNode { + failWantMap() + } + d.unmarshal(n, out) + case sequenceNode: + // Step backwards as earlier nodes take precedence. + for i := len(n.children) - 1; i >= 0; i-- { + ni := n.children[i] + if ni.kind == aliasNode { + if ni.alias != nil && ni.alias.kind != mappingNode { + failWantMap() + } + } else if ni.kind != mappingNode { + failWantMap() + } + d.unmarshal(ni, out) + } + default: + failWantMap() + } +} + +func isMerge(n *node) bool { + return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == yaml_MERGE_TAG) +} diff --git a/vendor/gopkg.in/yaml.v2/emitterc.go b/vendor/gopkg.in/yaml.v2/emitterc.go new file mode 100644 index 00000000..a1c2cc52 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/emitterc.go @@ -0,0 +1,1685 @@ +package yaml + +import ( + "bytes" + "fmt" +) + +// Flush the buffer if needed. +func flush(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) { + return yaml_emitter_flush(emitter) + } + return true +} + +// Put a character to the output buffer. +func put(emitter *yaml_emitter_t, value byte) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + emitter.buffer[emitter.buffer_pos] = value + emitter.buffer_pos++ + emitter.column++ + return true +} + +// Put a line break to the output buffer. +func put_break(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + switch emitter.line_break { + case yaml_CR_BREAK: + emitter.buffer[emitter.buffer_pos] = '\r' + emitter.buffer_pos += 1 + case yaml_LN_BREAK: + emitter.buffer[emitter.buffer_pos] = '\n' + emitter.buffer_pos += 1 + case yaml_CRLN_BREAK: + emitter.buffer[emitter.buffer_pos+0] = '\r' + emitter.buffer[emitter.buffer_pos+1] = '\n' + emitter.buffer_pos += 2 + default: + panic("unknown line break setting") + } + emitter.column = 0 + emitter.line++ + return true +} + +// Copy a character from a string into buffer. +func write(emitter *yaml_emitter_t, s []byte, i *int) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + p := emitter.buffer_pos + w := width(s[*i]) + switch w { + case 4: + emitter.buffer[p+3] = s[*i+3] + fallthrough + case 3: + emitter.buffer[p+2] = s[*i+2] + fallthrough + case 2: + emitter.buffer[p+1] = s[*i+1] + fallthrough + case 1: + emitter.buffer[p+0] = s[*i+0] + default: + panic("unknown character width") + } + emitter.column++ + emitter.buffer_pos += w + *i += w + return true +} + +// Write a whole string into buffer. +func write_all(emitter *yaml_emitter_t, s []byte) bool { + for i := 0; i < len(s); { + if !write(emitter, s, &i) { + return false + } + } + return true +} + +// Copy a line break character from a string into buffer. +func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool { + if s[*i] == '\n' { + if !put_break(emitter) { + return false + } + *i++ + } else { + if !write(emitter, s, i) { + return false + } + emitter.column = 0 + emitter.line++ + } + return true +} + +// Set an emitter error and return false. +func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_EMITTER_ERROR + emitter.problem = problem + return false +} + +// Emit an event. +func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.events = append(emitter.events, *event) + for !yaml_emitter_need_more_events(emitter) { + event := &emitter.events[emitter.events_head] + if !yaml_emitter_analyze_event(emitter, event) { + return false + } + if !yaml_emitter_state_machine(emitter, event) { + return false + } + yaml_event_delete(event) + emitter.events_head++ + } + return true +} + +// Check if we need to accumulate more events before emitting. +// +// We accumulate extra +// - 1 event for DOCUMENT-START +// - 2 events for SEQUENCE-START +// - 3 events for MAPPING-START +// +func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { + if emitter.events_head == len(emitter.events) { + return true + } + var accumulate int + switch emitter.events[emitter.events_head].typ { + case yaml_DOCUMENT_START_EVENT: + accumulate = 1 + break + case yaml_SEQUENCE_START_EVENT: + accumulate = 2 + break + case yaml_MAPPING_START_EVENT: + accumulate = 3 + break + default: + return false + } + if len(emitter.events)-emitter.events_head > accumulate { + return false + } + var level int + for i := emitter.events_head; i < len(emitter.events); i++ { + switch emitter.events[i].typ { + case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT: + level++ + case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT: + level-- + } + if level == 0 { + return false + } + } + return true +} + +// Append a directive to the directives stack. +func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool { + for i := 0; i < len(emitter.tag_directives); i++ { + if bytes.Equal(value.handle, emitter.tag_directives[i].handle) { + if allow_duplicates { + return true + } + return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive") + } + } + + // [Go] Do we actually need to copy this given garbage collection + // and the lack of deallocating destructors? + tag_copy := yaml_tag_directive_t{ + handle: make([]byte, len(value.handle)), + prefix: make([]byte, len(value.prefix)), + } + copy(tag_copy.handle, value.handle) + copy(tag_copy.prefix, value.prefix) + emitter.tag_directives = append(emitter.tag_directives, tag_copy) + return true +} + +// Increase the indentation level. +func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool { + emitter.indents = append(emitter.indents, emitter.indent) + if emitter.indent < 0 { + if flow { + emitter.indent = emitter.best_indent + } else { + emitter.indent = 0 + } + } else if !indentless { + emitter.indent += emitter.best_indent + } + return true +} + +// State dispatcher. +func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool { + switch emitter.state { + default: + case yaml_EMIT_STREAM_START_STATE: + return yaml_emitter_emit_stream_start(emitter, event) + + case yaml_EMIT_FIRST_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, true) + + case yaml_EMIT_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, false) + + case yaml_EMIT_DOCUMENT_CONTENT_STATE: + return yaml_emitter_emit_document_content(emitter, event) + + case yaml_EMIT_DOCUMENT_END_STATE: + return yaml_emitter_emit_document_end(emitter, event) + + case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, true) + + case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, false) + + case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, true) + + case yaml_EMIT_FLOW_MAPPING_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, false) + + case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, true) + + case yaml_EMIT_FLOW_MAPPING_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, false) + + case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, true) + + case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, false) + + case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, true) + + case yaml_EMIT_BLOCK_MAPPING_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, false) + + case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, true) + + case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, false) + + case yaml_EMIT_END_STATE: + return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END") + } + panic("invalid emitter state") +} + +// Expect STREAM-START. +func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_STREAM_START_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START") + } + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = event.encoding + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = yaml_UTF8_ENCODING + } + } + if emitter.best_indent < 2 || emitter.best_indent > 9 { + emitter.best_indent = 2 + } + if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 { + emitter.best_width = 80 + } + if emitter.best_width < 0 { + emitter.best_width = 1<<31 - 1 + } + if emitter.line_break == yaml_ANY_BREAK { + emitter.line_break = yaml_LN_BREAK + } + + emitter.indent = -1 + emitter.line = 0 + emitter.column = 0 + emitter.whitespace = true + emitter.indention = true + + if emitter.encoding != yaml_UTF8_ENCODING { + if !yaml_emitter_write_bom(emitter) { + return false + } + } + emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE + return true +} + +// Expect DOCUMENT-START or STREAM-END. +func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + + if event.typ == yaml_DOCUMENT_START_EVENT { + + if event.version_directive != nil { + if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) { + return false + } + } + + for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) { + return false + } + if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) { + return false + } + } + + for i := 0; i < len(default_tag_directives); i++ { + tag_directive := &default_tag_directives[i] + if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) { + return false + } + } + + implicit := event.implicit + if !first || emitter.canonical { + implicit = false + } + + if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if event.version_directive != nil { + implicit = false + if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if len(event.tag_directives) > 0 { + implicit = false + for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) { + return false + } + if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } + + if yaml_emitter_check_empty_document(emitter) { + implicit = false + } + if !implicit { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) { + return false + } + if emitter.canonical { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } + + emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE + return true + } + + if event.typ == yaml_STREAM_END_EVENT { + if emitter.open_ended { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_END_STATE + return true + } + + return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END") +} + +// Expect the root node. +func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE) + return yaml_emitter_emit_node(emitter, event, true, false, false, false) +} + +// Expect DOCUMENT-END. +func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_DOCUMENT_END_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END") + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !event.implicit { + // [Go] Allocate the slice elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_DOCUMENT_START_STATE + emitter.tag_directives = emitter.tag_directives[:0] + return true +} + +// Expect a flow item node. +func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } + + if event.typ == yaml_SEQUENCE_END_EVENT { + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.canonical && !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + + return true + } + + if !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) + return yaml_emitter_emit_node(emitter, event, false, true, false, false) +} + +// Expect a flow key node. +func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } + + if event.typ == yaml_MAPPING_END_EVENT { + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.canonical && !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + + if !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if !emitter.canonical && yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a flow value node. +func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a block item node. +func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, emitter.mapping_context && !emitter.indention) { + return false + } + } + if event.typ == yaml_SEQUENCE_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE) + return yaml_emitter_emit_node(emitter, event, false, true, false, false) +} + +// Expect a block key node. +func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, false) { + return false + } + } + if event.typ == yaml_MAPPING_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a block value node. +func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a node. +func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t, + root bool, sequence bool, mapping bool, simple_key bool) bool { + + emitter.root_context = root + emitter.sequence_context = sequence + emitter.mapping_context = mapping + emitter.simple_key_context = simple_key + + switch event.typ { + case yaml_ALIAS_EVENT: + return yaml_emitter_emit_alias(emitter, event) + case yaml_SCALAR_EVENT: + return yaml_emitter_emit_scalar(emitter, event) + case yaml_SEQUENCE_START_EVENT: + return yaml_emitter_emit_sequence_start(emitter, event) + case yaml_MAPPING_START_EVENT: + return yaml_emitter_emit_mapping_start(emitter, event) + default: + return yaml_emitter_set_emitter_error(emitter, + fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.typ)) + } +} + +// Expect ALIAS. +func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true +} + +// Expect SCALAR. +func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_select_scalar_style(emitter, event) { + return false + } + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + if !yaml_emitter_process_scalar(emitter) { + return false + } + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true +} + +// Expect SEQUENCE-START. +func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE || + yaml_emitter_check_empty_sequence(emitter) { + emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE + } + return true +} + +// Expect MAPPING-START. +func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE || + yaml_emitter_check_empty_mapping(emitter) { + emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE + } + return true +} + +// Check if the document content is an empty scalar. +func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool { + return false // [Go] Huh? +} + +// Check if the next events represent an empty sequence. +func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT +} + +// Check if the next events represent an empty mapping. +func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT +} + +// Check if the next node can be expressed as a simple key. +func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { + length := 0 + switch emitter.events[emitter.events_head].typ { + case yaml_ALIAS_EVENT: + length += len(emitter.anchor_data.anchor) + case yaml_SCALAR_EVENT: + if emitter.scalar_data.multiline { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + + len(emitter.scalar_data.value) + case yaml_SEQUENCE_START_EVENT: + if !yaml_emitter_check_empty_sequence(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + case yaml_MAPPING_START_EVENT: + if !yaml_emitter_check_empty_mapping(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + default: + return false + } + return length <= 128 +} + +// Determine an acceptable scalar style. +func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { + + no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 + if no_tag && !event.implicit && !event.quoted_implicit { + return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") + } + + style := event.scalar_style() + if style == yaml_ANY_SCALAR_STYLE { + style = yaml_PLAIN_SCALAR_STYLE + } + if emitter.canonical { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + if emitter.simple_key_context && emitter.scalar_data.multiline { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + + if style == yaml_PLAIN_SCALAR_STYLE { + if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed || + emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if no_tag && !event.implicit { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_SINGLE_QUOTED_SCALAR_STYLE { + if !emitter.scalar_data.single_quoted_allowed { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE { + if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } + + if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE { + emitter.tag_data.handle = []byte{'!'} + } + emitter.scalar_data.style = style + return true +} + +// Write an anchor. +func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { + if emitter.anchor_data.anchor == nil { + return true + } + c := []byte{'&'} + if emitter.anchor_data.alias { + c[0] = '*' + } + if !yaml_emitter_write_indicator(emitter, c, true, false, false) { + return false + } + return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor) +} + +// Write a tag. +func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool { + if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 { + return true + } + if len(emitter.tag_data.handle) > 0 { + if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) { + return false + } + if len(emitter.tag_data.suffix) > 0 { + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + } + } else { + // [Go] Allocate these slices elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) { + return false + } + } + return true +} + +// Write a scalar. +func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool { + switch emitter.scalar_data.style { + case yaml_PLAIN_SCALAR_STYLE: + return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_SINGLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_DOUBLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_LITERAL_SCALAR_STYLE: + return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value) + + case yaml_FOLDED_SCALAR_STYLE: + return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value) + } + panic("unknown scalar style") +} + +// Check if a %YAML directive is valid. +func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool { + if version_directive.major != 1 || version_directive.minor != 1 { + return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive") + } + return true +} + +// Check if a %TAG directive is valid. +func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool { + handle := tag_directive.handle + prefix := tag_directive.prefix + if len(handle) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty") + } + if handle[0] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'") + } + if handle[len(handle)-1] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'") + } + for i := 1; i < len(handle)-1; i += width(handle[i]) { + if !is_alpha(handle, i) { + return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only") + } + } + if len(prefix) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty") + } + return true +} + +// Check if an anchor is valid. +func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool { + if len(anchor) == 0 { + problem := "anchor value must not be empty" + if alias { + problem = "alias value must not be empty" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + for i := 0; i < len(anchor); i += width(anchor[i]) { + if !is_alpha(anchor, i) { + problem := "anchor value must contain alphanumerical characters only" + if alias { + problem = "alias value must contain alphanumerical characters only" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + } + emitter.anchor_data.anchor = anchor + emitter.anchor_data.alias = alias + return true +} + +// Check if a tag is valid. +func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool { + if len(tag) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty") + } + for i := 0; i < len(emitter.tag_directives); i++ { + tag_directive := &emitter.tag_directives[i] + if bytes.HasPrefix(tag, tag_directive.prefix) { + emitter.tag_data.handle = tag_directive.handle + emitter.tag_data.suffix = tag[len(tag_directive.prefix):] + return true + } + } + emitter.tag_data.suffix = tag + return true +} + +// Check if a scalar is valid. +func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { + var ( + block_indicators = false + flow_indicators = false + line_breaks = false + special_characters = false + + leading_space = false + leading_break = false + trailing_space = false + trailing_break = false + break_space = false + space_break = false + + preceded_by_whitespace = false + followed_by_whitespace = false + previous_space = false + previous_break = false + ) + + emitter.scalar_data.value = value + + if len(value) == 0 { + emitter.scalar_data.multiline = false + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = false + return true + } + + if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) { + block_indicators = true + flow_indicators = true + } + + preceded_by_whitespace = true + for i, w := 0, 0; i < len(value); i += w { + w = width(value[i]) + followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w) + + if i == 0 { + switch value[i] { + case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`': + flow_indicators = true + block_indicators = true + case '?', ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '-': + if followed_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } else { + switch value[i] { + case ',', '?', '[', ']', '{', '}': + flow_indicators = true + case ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '#': + if preceded_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } + + if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { + special_characters = true + } + if is_space(value, i) { + if i == 0 { + leading_space = true + } + if i+width(value[i]) == len(value) { + trailing_space = true + } + if previous_break { + break_space = true + } + previous_space = true + previous_break = false + } else if is_break(value, i) { + line_breaks = true + if i == 0 { + leading_break = true + } + if i+width(value[i]) == len(value) { + trailing_break = true + } + if previous_space { + space_break = true + } + previous_space = false + previous_break = true + } else { + previous_space = false + previous_break = false + } + + // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition. + preceded_by_whitespace = is_blankz(value, i) + } + + emitter.scalar_data.multiline = line_breaks + emitter.scalar_data.flow_plain_allowed = true + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = true + + if leading_space || leading_break || trailing_space || trailing_break { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if trailing_space { + emitter.scalar_data.block_allowed = false + } + if break_space { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + } + if space_break || special_characters { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + emitter.scalar_data.block_allowed = false + } + if line_breaks { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if flow_indicators { + emitter.scalar_data.flow_plain_allowed = false + } + if block_indicators { + emitter.scalar_data.block_plain_allowed = false + } + return true +} + +// Check if the event data is valid. +func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { + + emitter.anchor_data.anchor = nil + emitter.tag_data.handle = nil + emitter.tag_data.suffix = nil + emitter.scalar_data.value = nil + + switch event.typ { + case yaml_ALIAS_EVENT: + if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) { + return false + } + + case yaml_SCALAR_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + if !yaml_emitter_analyze_scalar(emitter, event.value) { + return false + } + + case yaml_SEQUENCE_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + + case yaml_MAPPING_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + } + return true +} + +// Write the BOM character. +func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool { + if !flush(emitter) { + return false + } + pos := emitter.buffer_pos + emitter.buffer[pos+0] = '\xEF' + emitter.buffer[pos+1] = '\xBB' + emitter.buffer[pos+2] = '\xBF' + emitter.buffer_pos += 3 + return true +} + +func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { + indent := emitter.indent + if indent < 0 { + indent = 0 + } + if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) { + if !put_break(emitter) { + return false + } + } + for emitter.column < indent { + if !put(emitter, ' ') { + return false + } + } + emitter.whitespace = true + emitter.indention = true + return true +} + +func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, indicator) { + return false + } + emitter.whitespace = is_whitespace + emitter.indention = (emitter.indention && is_indention) + emitter.open_ended = false + return true +} + +func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool { + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool { + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + for i := 0; i < len(value); { + var must_write bool + switch value[i] { + case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']': + must_write = true + default: + must_write = is_alpha(value, i) + } + if must_write { + if !write(emitter, value, &i) { + return false + } + } else { + w := width(value[i]) + for k := 0; k < w; k++ { + octet := value[i] + i++ + if !put(emitter, '%') { + return false + } + + c := octet >> 4 + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } + + c = octet & 0x0f + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } + } + } + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + + spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } + + emitter.whitespace = false + emitter.indention = false + if emitter.root_context { + emitter.open_ended = true + } + + return true +} + +func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + + if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { + return false + } + + spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if value[i] == '\'' { + if !put(emitter, '\'') { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + spaces := false + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) { + return false + } + + for i := 0; i < len(value); { + if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) || + is_bom(value, i) || is_break(value, i) || + value[i] == '"' || value[i] == '\\' { + + octet := value[i] + + var w int + var v rune + switch { + case octet&0x80 == 0x00: + w, v = 1, rune(octet&0x7F) + case octet&0xE0 == 0xC0: + w, v = 2, rune(octet&0x1F) + case octet&0xF0 == 0xE0: + w, v = 3, rune(octet&0x0F) + case octet&0xF8 == 0xF0: + w, v = 4, rune(octet&0x07) + } + for k := 1; k < w; k++ { + octet = value[i+k] + v = (v << 6) + (rune(octet) & 0x3F) + } + i += w + + if !put(emitter, '\\') { + return false + } + + var ok bool + switch v { + case 0x00: + ok = put(emitter, '0') + case 0x07: + ok = put(emitter, 'a') + case 0x08: + ok = put(emitter, 'b') + case 0x09: + ok = put(emitter, 't') + case 0x0A: + ok = put(emitter, 'n') + case 0x0b: + ok = put(emitter, 'v') + case 0x0c: + ok = put(emitter, 'f') + case 0x0d: + ok = put(emitter, 'r') + case 0x1b: + ok = put(emitter, 'e') + case 0x22: + ok = put(emitter, '"') + case 0x5c: + ok = put(emitter, '\\') + case 0x85: + ok = put(emitter, 'N') + case 0xA0: + ok = put(emitter, '_') + case 0x2028: + ok = put(emitter, 'L') + case 0x2029: + ok = put(emitter, 'P') + default: + if v <= 0xFF { + ok = put(emitter, 'x') + w = 2 + } else if v <= 0xFFFF { + ok = put(emitter, 'u') + w = 4 + } else { + ok = put(emitter, 'U') + w = 8 + } + for k := (w - 1) * 4; ok && k >= 0; k -= 4 { + digit := byte((v >> uint(k)) & 0x0F) + if digit < 10 { + ok = put(emitter, digit+'0') + } else { + ok = put(emitter, digit+'A'-10) + } + } + } + if !ok { + return false + } + spaces = false + } else if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 { + if !yaml_emitter_write_indent(emitter) { + return false + } + if is_space(value, i+1) { + if !put(emitter, '\\') { + return false + } + } + i += width(value[i]) + } else if !write(emitter, value, &i) { + return false + } + spaces = true + } else { + if !write(emitter, value, &i) { + return false + } + spaces = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool { + if is_space(value, 0) || is_break(value, 0) { + indent_hint := []byte{'0' + byte(emitter.best_indent)} + if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) { + return false + } + } + + emitter.open_ended = false + + var chomp_hint [1]byte + if len(value) == 0 { + chomp_hint[0] = '-' + } else { + i := len(value) - 1 + for value[i]&0xC0 == 0x80 { + i-- + } + if !is_break(value, i) { + chomp_hint[0] = '-' + } else if i == 0 { + chomp_hint[0] = '+' + emitter.open_ended = true + } else { + i-- + for value[i]&0xC0 == 0x80 { + i-- + } + if is_break(value, i) { + chomp_hint[0] = '+' + emitter.open_ended = true + } + } + } + if chomp_hint[0] != 0 { + if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) { + return false + } + } + return true +} + +func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + if !put_break(emitter) { + return false + } + emitter.indention = true + emitter.whitespace = true + breaks := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + breaks = false + } + } + + return true +} + +func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + + if !put_break(emitter) { + return false + } + emitter.indention = true + emitter.whitespace = true + + breaks := true + leading_spaces := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !breaks && !leading_spaces && value[i] == '\n' { + k := 0 + for is_break(value, k) { + k += width(value[k]) + } + if !is_blankz(value, k) { + if !put_break(emitter) { + return false + } + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + leading_spaces = is_blank(value, i) + } + if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + emitter.indention = false + breaks = false + } + } + return true +} diff --git a/vendor/gopkg.in/yaml.v2/encode.go b/vendor/gopkg.in/yaml.v2/encode.go new file mode 100644 index 00000000..0ee738e1 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/encode.go @@ -0,0 +1,390 @@ +package yaml + +import ( + "encoding" + "fmt" + "io" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +// jsonNumber is the interface of the encoding/json.Number datatype. +// Repeating the interface here avoids a dependency on encoding/json, and also +// supports other libraries like jsoniter, which use a similar datatype with +// the same interface. Detecting this interface is useful when dealing with +// structures containing json.Number, which is a string under the hood. The +// encoder should prefer the use of Int64(), Float64() and string(), in that +// order, when encoding this type. +type jsonNumber interface { + Float64() (float64, error) + Int64() (int64, error) + String() string +} + +type encoder struct { + emitter yaml_emitter_t + event yaml_event_t + out []byte + flow bool + // doneInit holds whether the initial stream_start_event has been + // emitted. + doneInit bool +} + +func newEncoder() *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_string(&e.emitter, &e.out) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func newEncoderWithWriter(w io.Writer) *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_writer(&e.emitter, w) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func (e *encoder) init() { + if e.doneInit { + return + } + yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING) + e.emit() + e.doneInit = true +} + +func (e *encoder) finish() { + e.emitter.open_ended = false + yaml_stream_end_event_initialize(&e.event) + e.emit() +} + +func (e *encoder) destroy() { + yaml_emitter_delete(&e.emitter) +} + +func (e *encoder) emit() { + // This will internally delete the e.event value. + e.must(yaml_emitter_emit(&e.emitter, &e.event)) +} + +func (e *encoder) must(ok bool) { + if !ok { + msg := e.emitter.problem + if msg == "" { + msg = "unknown problem generating YAML content" + } + failf("%s", msg) + } +} + +func (e *encoder) marshalDoc(tag string, in reflect.Value) { + e.init() + yaml_document_start_event_initialize(&e.event, nil, nil, true) + e.emit() + e.marshal(tag, in) + yaml_document_end_event_initialize(&e.event, true) + e.emit() +} + +func (e *encoder) marshal(tag string, in reflect.Value) { + if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() { + e.nilv() + return + } + iface := in.Interface() + switch m := iface.(type) { + case jsonNumber: + integer, err := m.Int64() + if err == nil { + // In this case the json.Number is a valid int64 + in = reflect.ValueOf(integer) + break + } + float, err := m.Float64() + if err == nil { + // In this case the json.Number is a valid float64 + in = reflect.ValueOf(float) + break + } + // fallback case - no number could be obtained + in = reflect.ValueOf(m.String()) + case time.Time, *time.Time: + // Although time.Time implements TextMarshaler, + // we don't want to treat it as a string for YAML + // purposes because YAML has special support for + // timestamps. + case Marshaler: + v, err := m.MarshalYAML() + if err != nil { + fail(err) + } + if v == nil { + e.nilv() + return + } + in = reflect.ValueOf(v) + case encoding.TextMarshaler: + text, err := m.MarshalText() + if err != nil { + fail(err) + } + in = reflect.ValueOf(string(text)) + case nil: + e.nilv() + return + } + switch in.Kind() { + case reflect.Interface: + e.marshal(tag, in.Elem()) + case reflect.Map: + e.mapv(tag, in) + case reflect.Ptr: + if in.Type() == ptrTimeType { + e.timev(tag, in.Elem()) + } else { + e.marshal(tag, in.Elem()) + } + case reflect.Struct: + if in.Type() == timeType { + e.timev(tag, in) + } else { + e.structv(tag, in) + } + case reflect.Slice, reflect.Array: + if in.Type().Elem() == mapItemType { + e.itemsv(tag, in) + } else { + e.slicev(tag, in) + } + case reflect.String: + e.stringv(tag, in) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if in.Type() == durationType { + e.stringv(tag, reflect.ValueOf(iface.(time.Duration).String())) + } else { + e.intv(tag, in) + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + e.uintv(tag, in) + case reflect.Float32, reflect.Float64: + e.floatv(tag, in) + case reflect.Bool: + e.boolv(tag, in) + default: + panic("cannot marshal type: " + in.Type().String()) + } +} + +func (e *encoder) mapv(tag string, in reflect.Value) { + e.mappingv(tag, func() { + keys := keyList(in.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + e.marshal("", k) + e.marshal("", in.MapIndex(k)) + } + }) +} + +func (e *encoder) itemsv(tag string, in reflect.Value) { + e.mappingv(tag, func() { + slice := in.Convert(reflect.TypeOf([]MapItem{})).Interface().([]MapItem) + for _, item := range slice { + e.marshal("", reflect.ValueOf(item.Key)) + e.marshal("", reflect.ValueOf(item.Value)) + } + }) +} + +func (e *encoder) structv(tag string, in reflect.Value) { + sinfo, err := getStructInfo(in.Type()) + if err != nil { + panic(err) + } + e.mappingv(tag, func() { + for _, info := range sinfo.FieldsList { + var value reflect.Value + if info.Inline == nil { + value = in.Field(info.Num) + } else { + value = in.FieldByIndex(info.Inline) + } + if info.OmitEmpty && isZero(value) { + continue + } + e.marshal("", reflect.ValueOf(info.Key)) + e.flow = info.Flow + e.marshal("", value) + } + if sinfo.InlineMap >= 0 { + m := in.Field(sinfo.InlineMap) + if m.Len() > 0 { + e.flow = false + keys := keyList(m.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + if _, found := sinfo.FieldsMap[k.String()]; found { + panic(fmt.Sprintf("Can't have key %q in inlined map; conflicts with struct field", k.String())) + } + e.marshal("", k) + e.flow = false + e.marshal("", m.MapIndex(k)) + } + } + } + }) +} + +func (e *encoder) mappingv(tag string, f func()) { + implicit := tag == "" + style := yaml_BLOCK_MAPPING_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_MAPPING_STYLE + } + yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) + e.emit() + f() + yaml_mapping_end_event_initialize(&e.event) + e.emit() +} + +func (e *encoder) slicev(tag string, in reflect.Value) { + implicit := tag == "" + style := yaml_BLOCK_SEQUENCE_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_SEQUENCE_STYLE + } + e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) + e.emit() + n := in.Len() + for i := 0; i < n; i++ { + e.marshal("", in.Index(i)) + } + e.must(yaml_sequence_end_event_initialize(&e.event)) + e.emit() +} + +// isBase60 returns whether s is in base 60 notation as defined in YAML 1.1. +// +// The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported +// in YAML 1.2 and by this package, but these should be marshalled quoted for +// the time being for compatibility with other parsers. +func isBase60Float(s string) (result bool) { + // Fast path. + if s == "" { + return false + } + c := s[0] + if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 { + return false + } + // Do the full match. + return base60float.MatchString(s) +} + +// From http://yaml.org/type/float.html, except the regular expression there +// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix. +var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`) + +func (e *encoder) stringv(tag string, in reflect.Value) { + var style yaml_scalar_style_t + s := in.String() + canUsePlain := true + switch { + case !utf8.ValidString(s): + if tag == yaml_BINARY_TAG { + failf("explicitly tagged !!binary data must be base64-encoded") + } + if tag != "" { + failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) + } + // It can't be encoded directly as YAML so use a binary tag + // and encode it as base64. + tag = yaml_BINARY_TAG + s = encodeBase64(s) + case tag == "": + // Check to see if it would resolve to a specific + // tag when encoded unquoted. If it doesn't, + // there's no need to quote it. + rtag, _ := resolve("", s) + canUsePlain = rtag == yaml_STR_TAG && !isBase60Float(s) + } + // Note: it's possible for user code to emit invalid YAML + // if they explicitly specify a tag and a string containing + // text that's incompatible with that tag. + switch { + case strings.Contains(s, "\n"): + style = yaml_LITERAL_SCALAR_STYLE + case canUsePlain: + style = yaml_PLAIN_SCALAR_STYLE + default: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + e.emitScalar(s, "", tag, style) +} + +func (e *encoder) boolv(tag string, in reflect.Value) { + var s string + if in.Bool() { + s = "true" + } else { + s = "false" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) intv(tag string, in reflect.Value) { + s := strconv.FormatInt(in.Int(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) uintv(tag string, in reflect.Value) { + s := strconv.FormatUint(in.Uint(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) timev(tag string, in reflect.Value) { + t := in.Interface().(time.Time) + s := t.Format(time.RFC3339Nano) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) floatv(tag string, in reflect.Value) { + // Issue #352: When formatting, use the precision of the underlying value + precision := 64 + if in.Kind() == reflect.Float32 { + precision = 32 + } + + s := strconv.FormatFloat(in.Float(), 'g', -1, precision) + switch s { + case "+Inf": + s = ".inf" + case "-Inf": + s = "-.inf" + case "NaN": + s = ".nan" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) nilv() { + e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t) { + implicit := tag == "" + e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)) + e.emit() +} diff --git a/vendor/gopkg.in/yaml.v2/parserc.go b/vendor/gopkg.in/yaml.v2/parserc.go new file mode 100644 index 00000000..81d05dfe --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/parserc.go @@ -0,0 +1,1095 @@ +package yaml + +import ( + "bytes" +) + +// The parser implements the following grammar: +// +// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +// implicit_document ::= block_node DOCUMENT-END* +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// block_node_or_indentless_sequence ::= +// ALIAS +// | properties (block_content | indentless_block_sequence)? +// | block_content +// | indentless_block_sequence +// block_node ::= ALIAS +// | properties block_content? +// | block_content +// flow_node ::= ALIAS +// | properties flow_content? +// | flow_content +// properties ::= TAG ANCHOR? | ANCHOR TAG? +// block_content ::= block_collection | flow_collection | SCALAR +// flow_content ::= flow_collection | SCALAR +// block_collection ::= block_sequence | block_mapping +// flow_collection ::= flow_sequence | flow_mapping +// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +// block_mapping ::= BLOCK-MAPPING_START +// ((KEY block_node_or_indentless_sequence?)? +// (VALUE block_node_or_indentless_sequence?)?)* +// BLOCK-END +// flow_sequence ::= FLOW-SEQUENCE-START +// (flow_sequence_entry FLOW-ENTRY)* +// flow_sequence_entry? +// FLOW-SEQUENCE-END +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// flow_mapping ::= FLOW-MAPPING-START +// (flow_mapping_entry FLOW-ENTRY)* +// flow_mapping_entry? +// FLOW-MAPPING-END +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + +// Peek the next token in the token queue. +func peek_token(parser *yaml_parser_t) *yaml_token_t { + if parser.token_available || yaml_parser_fetch_more_tokens(parser) { + return &parser.tokens[parser.tokens_head] + } + return nil +} + +// Remove the next token from the queue (must be called after peek_token). +func skip_token(parser *yaml_parser_t) { + parser.token_available = false + parser.tokens_parsed++ + parser.stream_end_produced = parser.tokens[parser.tokens_head].typ == yaml_STREAM_END_TOKEN + parser.tokens_head++ +} + +// Get the next event. +func yaml_parser_parse(parser *yaml_parser_t, event *yaml_event_t) bool { + // Erase the event object. + *event = yaml_event_t{} + + // No events after the end of the stream or error. + if parser.stream_end_produced || parser.error != yaml_NO_ERROR || parser.state == yaml_PARSE_END_STATE { + return true + } + + // Generate the next event. + return yaml_parser_state_machine(parser, event) +} + +// Set parser error. +func yaml_parser_set_parser_error(parser *yaml_parser_t, problem string, problem_mark yaml_mark_t) bool { + parser.error = yaml_PARSER_ERROR + parser.problem = problem + parser.problem_mark = problem_mark + return false +} + +func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string, problem_mark yaml_mark_t) bool { + parser.error = yaml_PARSER_ERROR + parser.context = context + parser.context_mark = context_mark + parser.problem = problem + parser.problem_mark = problem_mark + return false +} + +// State dispatcher. +func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool { + //trace("yaml_parser_state_machine", "state:", parser.state.String()) + + switch parser.state { + case yaml_PARSE_STREAM_START_STATE: + return yaml_parser_parse_stream_start(parser, event) + + case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return yaml_parser_parse_document_start(parser, event, true) + + case yaml_PARSE_DOCUMENT_START_STATE: + return yaml_parser_parse_document_start(parser, event, false) + + case yaml_PARSE_DOCUMENT_CONTENT_STATE: + return yaml_parser_parse_document_content(parser, event) + + case yaml_PARSE_DOCUMENT_END_STATE: + return yaml_parser_parse_document_end(parser, event) + + case yaml_PARSE_BLOCK_NODE_STATE: + return yaml_parser_parse_node(parser, event, true, false) + + case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return yaml_parser_parse_node(parser, event, true, true) + + case yaml_PARSE_FLOW_NODE_STATE: + return yaml_parser_parse_node(parser, event, false, false) + + case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return yaml_parser_parse_block_sequence_entry(parser, event, true) + + case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_block_sequence_entry(parser, event, false) + + case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_indentless_sequence_entry(parser, event) + + case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_parser_parse_block_mapping_key(parser, event, true) + + case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: + return yaml_parser_parse_block_mapping_key(parser, event, false) + + case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: + return yaml_parser_parse_block_mapping_value(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return yaml_parser_parse_flow_sequence_entry(parser, event, true) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_flow_sequence_entry(parser, event, false) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event) + + case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_parser_parse_flow_mapping_key(parser, event, true) + + case yaml_PARSE_FLOW_MAPPING_KEY_STATE: + return yaml_parser_parse_flow_mapping_key(parser, event, false) + + case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: + return yaml_parser_parse_flow_mapping_value(parser, event, false) + + case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return yaml_parser_parse_flow_mapping_value(parser, event, true) + + default: + panic("invalid parser state") + } +} + +// Parse the production: +// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +// ************ +func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_STREAM_START_TOKEN { + return yaml_parser_set_parser_error(parser, "did not find expected ", token.start_mark) + } + parser.state = yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE + *event = yaml_event_t{ + typ: yaml_STREAM_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + encoding: token.encoding, + } + skip_token(parser) + return true +} + +// Parse the productions: +// implicit_document ::= block_node DOCUMENT-END* +// * +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// ************************* +func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { + + token := peek_token(parser) + if token == nil { + return false + } + + // Parse extra document end indicators. + if !implicit { + for token.typ == yaml_DOCUMENT_END_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } + + if implicit && token.typ != yaml_VERSION_DIRECTIVE_TOKEN && + token.typ != yaml_TAG_DIRECTIVE_TOKEN && + token.typ != yaml_DOCUMENT_START_TOKEN && + token.typ != yaml_STREAM_END_TOKEN { + // Parse an implicit document. + if !yaml_parser_process_directives(parser, nil, nil) { + return false + } + parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) + parser.state = yaml_PARSE_BLOCK_NODE_STATE + + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + + } else if token.typ != yaml_STREAM_END_TOKEN { + // Parse an explicit document. + var version_directive *yaml_version_directive_t + var tag_directives []yaml_tag_directive_t + start_mark := token.start_mark + if !yaml_parser_process_directives(parser, &version_directive, &tag_directives) { + return false + } + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_DOCUMENT_START_TOKEN { + yaml_parser_set_parser_error(parser, + "did not find expected ", token.start_mark) + return false + } + parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) + parser.state = yaml_PARSE_DOCUMENT_CONTENT_STATE + end_mark := token.end_mark + + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + version_directive: version_directive, + tag_directives: tag_directives, + implicit: false, + } + skip_token(parser) + + } else { + // Parse the stream end. + parser.state = yaml_PARSE_END_STATE + *event = yaml_event_t{ + typ: yaml_STREAM_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + skip_token(parser) + } + + return true +} + +// Parse the productions: +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// *********** +// +func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VERSION_DIRECTIVE_TOKEN || + token.typ == yaml_TAG_DIRECTIVE_TOKEN || + token.typ == yaml_DOCUMENT_START_TOKEN || + token.typ == yaml_DOCUMENT_END_TOKEN || + token.typ == yaml_STREAM_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + return yaml_parser_process_empty_scalar(parser, event, + token.start_mark) + } + return yaml_parser_parse_node(parser, event, true, false) +} + +// Parse the productions: +// implicit_document ::= block_node DOCUMENT-END* +// ************* +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// +func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + + start_mark := token.start_mark + end_mark := token.start_mark + + implicit := true + if token.typ == yaml_DOCUMENT_END_TOKEN { + end_mark = token.end_mark + skip_token(parser) + implicit = false + } + + parser.tag_directives = parser.tag_directives[:0] + + parser.state = yaml_PARSE_DOCUMENT_START_STATE + *event = yaml_event_t{ + typ: yaml_DOCUMENT_END_EVENT, + start_mark: start_mark, + end_mark: end_mark, + implicit: implicit, + } + return true +} + +// Parse the productions: +// block_node_or_indentless_sequence ::= +// ALIAS +// ***** +// | properties (block_content | indentless_block_sequence)? +// ********** * +// | block_content | indentless_block_sequence +// * +// block_node ::= ALIAS +// ***** +// | properties block_content? +// ********** * +// | block_content +// * +// flow_node ::= ALIAS +// ***** +// | properties flow_content? +// ********** * +// | flow_content +// * +// properties ::= TAG ANCHOR? | ANCHOR TAG? +// ************************* +// block_content ::= block_collection | flow_collection | SCALAR +// ****** +// flow_content ::= flow_collection | SCALAR +// ****** +func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { + //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_ALIAS_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + *event = yaml_event_t{ + typ: yaml_ALIAS_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + anchor: token.value, + } + skip_token(parser) + return true + } + + start_mark := token.start_mark + end_mark := token.start_mark + + var tag_token bool + var tag_handle, tag_suffix, anchor []byte + var tag_mark yaml_mark_t + if token.typ == yaml_ANCHOR_TOKEN { + anchor = token.value + start_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_TAG_TOKEN { + tag_token = true + tag_handle = token.value + tag_suffix = token.suffix + tag_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } else if token.typ == yaml_TAG_TOKEN { + tag_token = true + tag_handle = token.value + tag_suffix = token.suffix + start_mark = token.start_mark + tag_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_ANCHOR_TOKEN { + anchor = token.value + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } + + var tag []byte + if tag_token { + if len(tag_handle) == 0 { + tag = tag_suffix + tag_suffix = nil + } else { + for i := range parser.tag_directives { + if bytes.Equal(parser.tag_directives[i].handle, tag_handle) { + tag = append([]byte(nil), parser.tag_directives[i].prefix...) + tag = append(tag, tag_suffix...) + break + } + } + if len(tag) == 0 { + yaml_parser_set_parser_error_context(parser, + "while parsing a node", start_mark, + "found undefined tag handle", tag_mark) + return false + } + } + } + + implicit := len(tag) == 0 + if indentless_sequence && token.typ == yaml_BLOCK_ENTRY_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), + } + return true + } + if token.typ == yaml_SCALAR_TOKEN { + var plain_implicit, quoted_implicit bool + end_mark = token.end_mark + if (len(tag) == 0 && token.style == yaml_PLAIN_SCALAR_STYLE) || (len(tag) == 1 && tag[0] == '!') { + plain_implicit = true + } else if len(tag) == 0 { + quoted_implicit = true + } + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + value: token.value, + implicit: plain_implicit, + quoted_implicit: quoted_implicit, + style: yaml_style_t(token.style), + } + skip_token(parser) + return true + } + if token.typ == yaml_FLOW_SEQUENCE_START_TOKEN { + // [Go] Some of the events below can be merged as they differ only on style. + end_mark = token.end_mark + parser.state = yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_FLOW_SEQUENCE_STYLE), + } + return true + } + if token.typ == yaml_FLOW_MAPPING_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), + } + return true + } + if block && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), + } + return true + } + if block && token.typ == yaml_BLOCK_MAPPING_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_MAPPING_STYLE), + } + return true + } + if len(anchor) > 0 || len(tag) > 0 { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + quoted_implicit: false, + style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), + } + return true + } + + context := "while parsing a flow node" + if block { + context = "while parsing a block node" + } + yaml_parser_set_parser_error_context(parser, context, start_mark, + "did not find expected node content", token.start_mark) + return false +} + +// Parse the productions: +// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// ******************** *********** * ********* +// +func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_BLOCK_ENTRY_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, true, false) + } else { + parser.state = yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + } + if token.typ == yaml_BLOCK_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + + skip_token(parser) + return true + } + + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a block collection", context_mark, + "did not find expected '-' indicator", token.start_mark) +} + +// Parse the productions: +// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +// *********** * +func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_BLOCK_ENTRY_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_BLOCK_ENTRY_TOKEN && + token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, true, false) + } + parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.start_mark, // [Go] Shouldn't this be token.end_mark? + } + return true +} + +// Parse the productions: +// block_mapping ::= BLOCK-MAPPING_START +// ******************* +// ((KEY block_node_or_indentless_sequence?)? +// *** * +// (VALUE block_node_or_indentless_sequence?)?)* +// +// BLOCK-END +// ********* +// +func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_KEY_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, true, true) + } else { + parser.state = yaml_PARSE_BLOCK_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + } else if token.typ == yaml_BLOCK_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + skip_token(parser) + return true + } + + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a block mapping", context_mark, + "did not find expected key", token.start_mark) +} + +// Parse the productions: +// block_mapping ::= BLOCK-MAPPING_START +// +// ((KEY block_node_or_indentless_sequence?)? +// +// (VALUE block_node_or_indentless_sequence?)?)* +// ***** * +// BLOCK-END +// +// +func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VALUE_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_KEY_STATE) + return yaml_parser_parse_node(parser, event, true, true) + } + parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Parse the productions: +// flow_sequence ::= FLOW-SEQUENCE-START +// ******************* +// (flow_sequence_entry FLOW-ENTRY)* +// * ********** +// flow_sequence_entry? +// * +// FLOW-SEQUENCE-END +// ***************** +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * +// +func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + if !first { + if token.typ == yaml_FLOW_ENTRY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } else { + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a flow sequence", context_mark, + "did not find expected ',' or ']'", token.start_mark) + } + } + + if token.typ == yaml_KEY_TOKEN { + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + implicit: true, + style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), + } + skip_token(parser) + return true + } else if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + + skip_token(parser) + return true +} + +// +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// *** * +// +func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_FLOW_ENTRY_TOKEN && + token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + mark := token.end_mark + skip_token(parser) + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) +} + +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// ***** * +// +func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VALUE_TOKEN { + skip_token(parser) + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * +// +func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.start_mark, // [Go] Shouldn't this be end_mark? + } + return true +} + +// Parse the productions: +// flow_mapping ::= FLOW-MAPPING-START +// ****************** +// (flow_mapping_entry FLOW-ENTRY)* +// * ********** +// flow_mapping_entry? +// ****************** +// FLOW-MAPPING-END +// **************** +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * *** * +// +func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ != yaml_FLOW_MAPPING_END_TOKEN { + if !first { + if token.typ == yaml_FLOW_ENTRY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } else { + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a flow mapping", context_mark, + "did not find expected ',' or '}'", token.start_mark) + } + } + + if token.typ == yaml_KEY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_FLOW_ENTRY_TOKEN && + token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } else { + parser.state = yaml_PARSE_FLOW_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) + } + } else if token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + skip_token(parser) + return true +} + +// Parse the productions: +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * ***** * +// +func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { + token := peek_token(parser) + if token == nil { + return false + } + if empty { + parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) + } + if token.typ == yaml_VALUE_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_KEY_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Generate an empty scalar event. +func yaml_parser_process_empty_scalar(parser *yaml_parser_t, event *yaml_event_t, mark yaml_mark_t) bool { + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: mark, + end_mark: mark, + value: nil, // Empty + implicit: true, + style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), + } + return true +} + +var default_tag_directives = []yaml_tag_directive_t{ + {[]byte("!"), []byte("!")}, + {[]byte("!!"), []byte("tag:yaml.org,2002:")}, +} + +// Parse directives. +func yaml_parser_process_directives(parser *yaml_parser_t, + version_directive_ref **yaml_version_directive_t, + tag_directives_ref *[]yaml_tag_directive_t) bool { + + var version_directive *yaml_version_directive_t + var tag_directives []yaml_tag_directive_t + + token := peek_token(parser) + if token == nil { + return false + } + + for token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN { + if token.typ == yaml_VERSION_DIRECTIVE_TOKEN { + if version_directive != nil { + yaml_parser_set_parser_error(parser, + "found duplicate %YAML directive", token.start_mark) + return false + } + if token.major != 1 || token.minor != 1 { + yaml_parser_set_parser_error(parser, + "found incompatible YAML document", token.start_mark) + return false + } + version_directive = &yaml_version_directive_t{ + major: token.major, + minor: token.minor, + } + } else if token.typ == yaml_TAG_DIRECTIVE_TOKEN { + value := yaml_tag_directive_t{ + handle: token.value, + prefix: token.prefix, + } + if !yaml_parser_append_tag_directive(parser, value, false, token.start_mark) { + return false + } + tag_directives = append(tag_directives, value) + } + + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + + for i := range default_tag_directives { + if !yaml_parser_append_tag_directive(parser, default_tag_directives[i], true, token.start_mark) { + return false + } + } + + if version_directive_ref != nil { + *version_directive_ref = version_directive + } + if tag_directives_ref != nil { + *tag_directives_ref = tag_directives + } + return true +} + +// Append a tag directive to the directives stack. +func yaml_parser_append_tag_directive(parser *yaml_parser_t, value yaml_tag_directive_t, allow_duplicates bool, mark yaml_mark_t) bool { + for i := range parser.tag_directives { + if bytes.Equal(value.handle, parser.tag_directives[i].handle) { + if allow_duplicates { + return true + } + return yaml_parser_set_parser_error(parser, "found duplicate %TAG directive", mark) + } + } + + // [Go] I suspect the copy is unnecessary. This was likely done + // because there was no way to track ownership of the data. + value_copy := yaml_tag_directive_t{ + handle: make([]byte, len(value.handle)), + prefix: make([]byte, len(value.prefix)), + } + copy(value_copy.handle, value.handle) + copy(value_copy.prefix, value.prefix) + parser.tag_directives = append(parser.tag_directives, value_copy) + return true +} diff --git a/vendor/gopkg.in/yaml.v2/readerc.go b/vendor/gopkg.in/yaml.v2/readerc.go new file mode 100644 index 00000000..7c1f5fac --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/readerc.go @@ -0,0 +1,412 @@ +package yaml + +import ( + "io" +) + +// Set the reader error and return 0. +func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool { + parser.error = yaml_READER_ERROR + parser.problem = problem + parser.problem_offset = offset + parser.problem_value = value + return false +} + +// Byte order marks. +const ( + bom_UTF8 = "\xef\xbb\xbf" + bom_UTF16LE = "\xff\xfe" + bom_UTF16BE = "\xfe\xff" +) + +// Determine the input stream encoding by checking the BOM symbol. If no BOM is +// found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. +func yaml_parser_determine_encoding(parser *yaml_parser_t) bool { + // Ensure that we had enough bytes in the raw buffer. + for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 { + if !yaml_parser_update_raw_buffer(parser) { + return false + } + } + + // Determine the encoding. + buf := parser.raw_buffer + pos := parser.raw_buffer_pos + avail := len(buf) - pos + if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] { + parser.encoding = yaml_UTF16LE_ENCODING + parser.raw_buffer_pos += 2 + parser.offset += 2 + } else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] { + parser.encoding = yaml_UTF16BE_ENCODING + parser.raw_buffer_pos += 2 + parser.offset += 2 + } else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] { + parser.encoding = yaml_UTF8_ENCODING + parser.raw_buffer_pos += 3 + parser.offset += 3 + } else { + parser.encoding = yaml_UTF8_ENCODING + } + return true +} + +// Update the raw buffer. +func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool { + size_read := 0 + + // Return if the raw buffer is full. + if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) { + return true + } + + // Return on EOF. + if parser.eof { + return true + } + + // Move the remaining bytes in the raw buffer to the beginning. + if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) { + copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:]) + } + parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos] + parser.raw_buffer_pos = 0 + + // Call the read handler to fill the buffer. + size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)]) + parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read] + if err == io.EOF { + parser.eof = true + } else if err != nil { + return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1) + } + return true +} + +// Ensure that the buffer contains at least `length` characters. +// Return true on success, false on failure. +// +// The length is supposed to be significantly less that the buffer size. +func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { + if parser.read_handler == nil { + panic("read handler must be set") + } + + // [Go] This function was changed to guarantee the requested length size at EOF. + // The fact we need to do this is pretty awful, but the description above implies + // for that to be the case, and there are tests + + // If the EOF flag is set and the raw buffer is empty, do nothing. + if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { + // [Go] ACTUALLY! Read the documentation of this function above. + // This is just broken. To return true, we need to have the + // given length in the buffer. Not doing that means every single + // check that calls this function to make sure the buffer has a + // given length is Go) panicking; or C) accessing invalid memory. + //return true + } + + // Return if the buffer contains enough characters. + if parser.unread >= length { + return true + } + + // Determine the input encoding if it is not known yet. + if parser.encoding == yaml_ANY_ENCODING { + if !yaml_parser_determine_encoding(parser) { + return false + } + } + + // Move the unread characters to the beginning of the buffer. + buffer_len := len(parser.buffer) + if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len { + copy(parser.buffer, parser.buffer[parser.buffer_pos:]) + buffer_len -= parser.buffer_pos + parser.buffer_pos = 0 + } else if parser.buffer_pos == buffer_len { + buffer_len = 0 + parser.buffer_pos = 0 + } + + // Open the whole buffer for writing, and cut it before returning. + parser.buffer = parser.buffer[:cap(parser.buffer)] + + // Fill the buffer until it has enough characters. + first := true + for parser.unread < length { + + // Fill the raw buffer if necessary. + if !first || parser.raw_buffer_pos == len(parser.raw_buffer) { + if !yaml_parser_update_raw_buffer(parser) { + parser.buffer = parser.buffer[:buffer_len] + return false + } + } + first = false + + // Decode the raw buffer. + inner: + for parser.raw_buffer_pos != len(parser.raw_buffer) { + var value rune + var width int + + raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos + + // Decode the next character. + switch parser.encoding { + case yaml_UTF8_ENCODING: + // Decode a UTF-8 character. Check RFC 3629 + // (http://www.ietf.org/rfc/rfc3629.txt) for more details. + // + // The following table (taken from the RFC) is used for + // decoding. + // + // Char. number range | UTF-8 octet sequence + // (hexadecimal) | (binary) + // --------------------+------------------------------------ + // 0000 0000-0000 007F | 0xxxxxxx + // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx + // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx + // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + // + // Additionally, the characters in the range 0xD800-0xDFFF + // are prohibited as they are reserved for use with UTF-16 + // surrogate pairs. + + // Determine the length of the UTF-8 sequence. + octet := parser.raw_buffer[parser.raw_buffer_pos] + switch { + case octet&0x80 == 0x00: + width = 1 + case octet&0xE0 == 0xC0: + width = 2 + case octet&0xF0 == 0xE0: + width = 3 + case octet&0xF8 == 0xF0: + width = 4 + default: + // The leading octet is invalid. + return yaml_parser_set_reader_error(parser, + "invalid leading UTF-8 octet", + parser.offset, int(octet)) + } + + // Check if the raw buffer contains an incomplete character. + if width > raw_unread { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-8 octet sequence", + parser.offset, -1) + } + break inner + } + + // Decode the leading octet. + switch { + case octet&0x80 == 0x00: + value = rune(octet & 0x7F) + case octet&0xE0 == 0xC0: + value = rune(octet & 0x1F) + case octet&0xF0 == 0xE0: + value = rune(octet & 0x0F) + case octet&0xF8 == 0xF0: + value = rune(octet & 0x07) + default: + value = 0 + } + + // Check and decode the trailing octets. + for k := 1; k < width; k++ { + octet = parser.raw_buffer[parser.raw_buffer_pos+k] + + // Check if the octet is valid. + if (octet & 0xC0) != 0x80 { + return yaml_parser_set_reader_error(parser, + "invalid trailing UTF-8 octet", + parser.offset+k, int(octet)) + } + + // Decode the octet. + value = (value << 6) + rune(octet&0x3F) + } + + // Check the length of the sequence against the value. + switch { + case width == 1: + case width == 2 && value >= 0x80: + case width == 3 && value >= 0x800: + case width == 4 && value >= 0x10000: + default: + return yaml_parser_set_reader_error(parser, + "invalid length of a UTF-8 sequence", + parser.offset, -1) + } + + // Check the range of the value. + if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF { + return yaml_parser_set_reader_error(parser, + "invalid Unicode character", + parser.offset, int(value)) + } + + case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING: + var low, high int + if parser.encoding == yaml_UTF16LE_ENCODING { + low, high = 0, 1 + } else { + low, high = 1, 0 + } + + // The UTF-16 encoding is not as simple as one might + // naively think. Check RFC 2781 + // (http://www.ietf.org/rfc/rfc2781.txt). + // + // Normally, two subsequent bytes describe a Unicode + // character. However a special technique (called a + // surrogate pair) is used for specifying character + // values larger than 0xFFFF. + // + // A surrogate pair consists of two pseudo-characters: + // high surrogate area (0xD800-0xDBFF) + // low surrogate area (0xDC00-0xDFFF) + // + // The following formulas are used for decoding + // and encoding characters using surrogate pairs: + // + // U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) + // U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) + // W1 = 110110yyyyyyyyyy + // W2 = 110111xxxxxxxxxx + // + // where U is the character value, W1 is the high surrogate + // area, W2 is the low surrogate area. + + // Check for incomplete UTF-16 character. + if raw_unread < 2 { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-16 character", + parser.offset, -1) + } + break inner + } + + // Get the character. + value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) + + (rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8) + + // Check for unexpected low surrogate area. + if value&0xFC00 == 0xDC00 { + return yaml_parser_set_reader_error(parser, + "unexpected low surrogate area", + parser.offset, int(value)) + } + + // Check for a high surrogate area. + if value&0xFC00 == 0xD800 { + width = 4 + + // Check for incomplete surrogate pair. + if raw_unread < 4 { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-16 surrogate pair", + parser.offset, -1) + } + break inner + } + + // Get the next character. + value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) + + (rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8) + + // Check for a low surrogate area. + if value2&0xFC00 != 0xDC00 { + return yaml_parser_set_reader_error(parser, + "expected low surrogate area", + parser.offset+2, int(value2)) + } + + // Generate the value of the surrogate pair. + value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF) + } else { + width = 2 + } + + default: + panic("impossible") + } + + // Check if the character is in the allowed range: + // #x9 | #xA | #xD | [#x20-#x7E] (8 bit) + // | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) + // | [#x10000-#x10FFFF] (32 bit) + switch { + case value == 0x09: + case value == 0x0A: + case value == 0x0D: + case value >= 0x20 && value <= 0x7E: + case value == 0x85: + case value >= 0xA0 && value <= 0xD7FF: + case value >= 0xE000 && value <= 0xFFFD: + case value >= 0x10000 && value <= 0x10FFFF: + default: + return yaml_parser_set_reader_error(parser, + "control characters are not allowed", + parser.offset, int(value)) + } + + // Move the raw pointers. + parser.raw_buffer_pos += width + parser.offset += width + + // Finally put the character into the buffer. + if value <= 0x7F { + // 0000 0000-0000 007F . 0xxxxxxx + parser.buffer[buffer_len+0] = byte(value) + buffer_len += 1 + } else if value <= 0x7FF { + // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6)) + parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F)) + buffer_len += 2 + } else if value <= 0xFFFF { + // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12)) + parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F)) + parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F)) + buffer_len += 3 + } else { + // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18)) + parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F)) + parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F)) + parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F)) + buffer_len += 4 + } + + parser.unread++ + } + + // On EOF, put NUL into the buffer and return. + if parser.eof { + parser.buffer[buffer_len] = 0 + buffer_len++ + parser.unread++ + break + } + } + // [Go] Read the documentation of this function above. To return true, + // we need to have the given length in the buffer. Not doing that means + // every single check that calls this function to make sure the buffer + // has a given length is Go) panicking; or C) accessing invalid memory. + // This happens here due to the EOF above breaking early. + for buffer_len < length { + parser.buffer[buffer_len] = 0 + buffer_len++ + } + parser.buffer = parser.buffer[:buffer_len] + return true +} diff --git a/vendor/gopkg.in/yaml.v2/resolve.go b/vendor/gopkg.in/yaml.v2/resolve.go new file mode 100644 index 00000000..4120e0c9 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/resolve.go @@ -0,0 +1,258 @@ +package yaml + +import ( + "encoding/base64" + "math" + "regexp" + "strconv" + "strings" + "time" +) + +type resolveMapItem struct { + value interface{} + tag string +} + +var resolveTable = make([]byte, 256) +var resolveMap = make(map[string]resolveMapItem) + +func init() { + t := resolveTable + t[int('+')] = 'S' // Sign + t[int('-')] = 'S' + for _, c := range "0123456789" { + t[int(c)] = 'D' // Digit + } + for _, c := range "yYnNtTfFoO~" { + t[int(c)] = 'M' // In map + } + t[int('.')] = '.' // Float (potentially in map) + + var resolveMapList = []struct { + v interface{} + tag string + l []string + }{ + {true, yaml_BOOL_TAG, []string{"y", "Y", "yes", "Yes", "YES"}}, + {true, yaml_BOOL_TAG, []string{"true", "True", "TRUE"}}, + {true, yaml_BOOL_TAG, []string{"on", "On", "ON"}}, + {false, yaml_BOOL_TAG, []string{"n", "N", "no", "No", "NO"}}, + {false, yaml_BOOL_TAG, []string{"false", "False", "FALSE"}}, + {false, yaml_BOOL_TAG, []string{"off", "Off", "OFF"}}, + {nil, yaml_NULL_TAG, []string{"", "~", "null", "Null", "NULL"}}, + {math.NaN(), yaml_FLOAT_TAG, []string{".nan", ".NaN", ".NAN"}}, + {math.Inf(+1), yaml_FLOAT_TAG, []string{".inf", ".Inf", ".INF"}}, + {math.Inf(+1), yaml_FLOAT_TAG, []string{"+.inf", "+.Inf", "+.INF"}}, + {math.Inf(-1), yaml_FLOAT_TAG, []string{"-.inf", "-.Inf", "-.INF"}}, + {"<<", yaml_MERGE_TAG, []string{"<<"}}, + } + + m := resolveMap + for _, item := range resolveMapList { + for _, s := range item.l { + m[s] = resolveMapItem{item.v, item.tag} + } + } +} + +const longTagPrefix = "tag:yaml.org,2002:" + +func shortTag(tag string) string { + // TODO This can easily be made faster and produce less garbage. + if strings.HasPrefix(tag, longTagPrefix) { + return "!!" + tag[len(longTagPrefix):] + } + return tag +} + +func longTag(tag string) string { + if strings.HasPrefix(tag, "!!") { + return longTagPrefix + tag[2:] + } + return tag +} + +func resolvableTag(tag string) bool { + switch tag { + case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG, yaml_TIMESTAMP_TAG: + return true + } + return false +} + +var yamlStyleFloat = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`) + +func resolve(tag string, in string) (rtag string, out interface{}) { + if !resolvableTag(tag) { + return tag, in + } + + defer func() { + switch tag { + case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG: + return + case yaml_FLOAT_TAG: + if rtag == yaml_INT_TAG { + switch v := out.(type) { + case int64: + rtag = yaml_FLOAT_TAG + out = float64(v) + return + case int: + rtag = yaml_FLOAT_TAG + out = float64(v) + return + } + } + } + failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) + }() + + // Any data is accepted as a !!str or !!binary. + // Otherwise, the prefix is enough of a hint about what it might be. + hint := byte('N') + if in != "" { + hint = resolveTable[in[0]] + } + if hint != 0 && tag != yaml_STR_TAG && tag != yaml_BINARY_TAG { + // Handle things we can lookup in a map. + if item, ok := resolveMap[in]; ok { + return item.tag, item.value + } + + // Base 60 floats are a bad idea, were dropped in YAML 1.2, and + // are purposefully unsupported here. They're still quoted on + // the way out for compatibility with other parser, though. + + switch hint { + case 'M': + // We've already checked the map above. + + case '.': + // Not in the map, so maybe a normal float. + floatv, err := strconv.ParseFloat(in, 64) + if err == nil { + return yaml_FLOAT_TAG, floatv + } + + case 'D', 'S': + // Int, float, or timestamp. + // Only try values as a timestamp if the value is unquoted or there's an explicit + // !!timestamp tag. + if tag == "" || tag == yaml_TIMESTAMP_TAG { + t, ok := parseTimestamp(in) + if ok { + return yaml_TIMESTAMP_TAG, t + } + } + + plain := strings.Replace(in, "_", "", -1) + intv, err := strconv.ParseInt(plain, 0, 64) + if err == nil { + if intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + uintv, err := strconv.ParseUint(plain, 0, 64) + if err == nil { + return yaml_INT_TAG, uintv + } + if yamlStyleFloat.MatchString(plain) { + floatv, err := strconv.ParseFloat(plain, 64) + if err == nil { + return yaml_FLOAT_TAG, floatv + } + } + if strings.HasPrefix(plain, "0b") { + intv, err := strconv.ParseInt(plain[2:], 2, 64) + if err == nil { + if intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + uintv, err := strconv.ParseUint(plain[2:], 2, 64) + if err == nil { + return yaml_INT_TAG, uintv + } + } else if strings.HasPrefix(plain, "-0b") { + intv, err := strconv.ParseInt("-" + plain[3:], 2, 64) + if err == nil { + if true || intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + } + default: + panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")") + } + } + return yaml_STR_TAG, in +} + +// encodeBase64 encodes s as base64 that is broken up into multiple lines +// as appropriate for the resulting length. +func encodeBase64(s string) string { + const lineLen = 70 + encLen := base64.StdEncoding.EncodedLen(len(s)) + lines := encLen/lineLen + 1 + buf := make([]byte, encLen*2+lines) + in := buf[0:encLen] + out := buf[encLen:] + base64.StdEncoding.Encode(in, []byte(s)) + k := 0 + for i := 0; i < len(in); i += lineLen { + j := i + lineLen + if j > len(in) { + j = len(in) + } + k += copy(out[k:], in[i:j]) + if lines > 1 { + out[k] = '\n' + k++ + } + } + return string(out[:k]) +} + +// This is a subset of the formats allowed by the regular expression +// defined at http://yaml.org/type/timestamp.html. +var allowedTimestampFormats = []string{ + "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. + "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". + "2006-1-2 15:4:5.999999999", // space separated with no time zone + "2006-1-2", // date only + // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" + // from the set of examples. +} + +// parseTimestamp parses s as a timestamp string and +// returns the timestamp and reports whether it succeeded. +// Timestamp formats are defined at http://yaml.org/type/timestamp.html +func parseTimestamp(s string) (time.Time, bool) { + // TODO write code to check all the formats supported by + // http://yaml.org/type/timestamp.html instead of using time.Parse. + + // Quick check: all date formats start with YYYY-. + i := 0 + for ; i < len(s); i++ { + if c := s[i]; c < '0' || c > '9' { + break + } + } + if i != 4 || i == len(s) || s[i] != '-' { + return time.Time{}, false + } + for _, format := range allowedTimestampFormats { + if t, err := time.Parse(format, s); err == nil { + return t, true + } + } + return time.Time{}, false +} diff --git a/vendor/gopkg.in/yaml.v2/scannerc.go b/vendor/gopkg.in/yaml.v2/scannerc.go new file mode 100644 index 00000000..0b9bb603 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/scannerc.go @@ -0,0 +1,2711 @@ +package yaml + +import ( + "bytes" + "fmt" +) + +// Introduction +// ************ +// +// The following notes assume that you are familiar with the YAML specification +// (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in +// some cases we are less restrictive that it requires. +// +// The process of transforming a YAML stream into a sequence of events is +// divided on two steps: Scanning and Parsing. +// +// The Scanner transforms the input stream into a sequence of tokens, while the +// parser transform the sequence of tokens produced by the Scanner into a +// sequence of parsing events. +// +// The Scanner is rather clever and complicated. The Parser, on the contrary, +// is a straightforward implementation of a recursive-descendant parser (or, +// LL(1) parser, as it is usually called). +// +// Actually there are two issues of Scanning that might be called "clever", the +// rest is quite straightforward. The issues are "block collection start" and +// "simple keys". Both issues are explained below in details. +// +// Here the Scanning step is explained and implemented. We start with the list +// of all the tokens produced by the Scanner together with short descriptions. +// +// Now, tokens: +// +// STREAM-START(encoding) # The stream start. +// STREAM-END # The stream end. +// VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. +// TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. +// DOCUMENT-START # '---' +// DOCUMENT-END # '...' +// BLOCK-SEQUENCE-START # Indentation increase denoting a block +// BLOCK-MAPPING-START # sequence or a block mapping. +// BLOCK-END # Indentation decrease. +// FLOW-SEQUENCE-START # '[' +// FLOW-SEQUENCE-END # ']' +// BLOCK-SEQUENCE-START # '{' +// BLOCK-SEQUENCE-END # '}' +// BLOCK-ENTRY # '-' +// FLOW-ENTRY # ',' +// KEY # '?' or nothing (simple keys). +// VALUE # ':' +// ALIAS(anchor) # '*anchor' +// ANCHOR(anchor) # '&anchor' +// TAG(handle,suffix) # '!handle!suffix' +// SCALAR(value,style) # A scalar. +// +// The following two tokens are "virtual" tokens denoting the beginning and the +// end of the stream: +// +// STREAM-START(encoding) +// STREAM-END +// +// We pass the information about the input stream encoding with the +// STREAM-START token. +// +// The next two tokens are responsible for tags: +// +// VERSION-DIRECTIVE(major,minor) +// TAG-DIRECTIVE(handle,prefix) +// +// Example: +// +// %YAML 1.1 +// %TAG ! !foo +// %TAG !yaml! tag:yaml.org,2002: +// --- +// +// The correspoding sequence of tokens: +// +// STREAM-START(utf-8) +// VERSION-DIRECTIVE(1,1) +// TAG-DIRECTIVE("!","!foo") +// TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") +// DOCUMENT-START +// STREAM-END +// +// Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole +// line. +// +// The document start and end indicators are represented by: +// +// DOCUMENT-START +// DOCUMENT-END +// +// Note that if a YAML stream contains an implicit document (without '---' +// and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be +// produced. +// +// In the following examples, we present whole documents together with the +// produced tokens. +// +// 1. An implicit document: +// +// 'a scalar' +// +// Tokens: +// +// STREAM-START(utf-8) +// SCALAR("a scalar",single-quoted) +// STREAM-END +// +// 2. An explicit document: +// +// --- +// 'a scalar' +// ... +// +// Tokens: +// +// STREAM-START(utf-8) +// DOCUMENT-START +// SCALAR("a scalar",single-quoted) +// DOCUMENT-END +// STREAM-END +// +// 3. Several documents in a stream: +// +// 'a scalar' +// --- +// 'another scalar' +// --- +// 'yet another scalar' +// +// Tokens: +// +// STREAM-START(utf-8) +// SCALAR("a scalar",single-quoted) +// DOCUMENT-START +// SCALAR("another scalar",single-quoted) +// DOCUMENT-START +// SCALAR("yet another scalar",single-quoted) +// STREAM-END +// +// We have already introduced the SCALAR token above. The following tokens are +// used to describe aliases, anchors, tag, and scalars: +// +// ALIAS(anchor) +// ANCHOR(anchor) +// TAG(handle,suffix) +// SCALAR(value,style) +// +// The following series of examples illustrate the usage of these tokens: +// +// 1. A recursive sequence: +// +// &A [ *A ] +// +// Tokens: +// +// STREAM-START(utf-8) +// ANCHOR("A") +// FLOW-SEQUENCE-START +// ALIAS("A") +// FLOW-SEQUENCE-END +// STREAM-END +// +// 2. A tagged scalar: +// +// !!float "3.14" # A good approximation. +// +// Tokens: +// +// STREAM-START(utf-8) +// TAG("!!","float") +// SCALAR("3.14",double-quoted) +// STREAM-END +// +// 3. Various scalar styles: +// +// --- # Implicit empty plain scalars do not produce tokens. +// --- a plain scalar +// --- 'a single-quoted scalar' +// --- "a double-quoted scalar" +// --- |- +// a literal scalar +// --- >- +// a folded +// scalar +// +// Tokens: +// +// STREAM-START(utf-8) +// DOCUMENT-START +// DOCUMENT-START +// SCALAR("a plain scalar",plain) +// DOCUMENT-START +// SCALAR("a single-quoted scalar",single-quoted) +// DOCUMENT-START +// SCALAR("a double-quoted scalar",double-quoted) +// DOCUMENT-START +// SCALAR("a literal scalar",literal) +// DOCUMENT-START +// SCALAR("a folded scalar",folded) +// STREAM-END +// +// Now it's time to review collection-related tokens. We will start with +// flow collections: +// +// FLOW-SEQUENCE-START +// FLOW-SEQUENCE-END +// FLOW-MAPPING-START +// FLOW-MAPPING-END +// FLOW-ENTRY +// KEY +// VALUE +// +// The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and +// FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' +// correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the +// indicators '?' and ':', which are used for denoting mapping keys and values, +// are represented by the KEY and VALUE tokens. +// +// The following examples show flow collections: +// +// 1. A flow sequence: +// +// [item 1, item 2, item 3] +// +// Tokens: +// +// STREAM-START(utf-8) +// FLOW-SEQUENCE-START +// SCALAR("item 1",plain) +// FLOW-ENTRY +// SCALAR("item 2",plain) +// FLOW-ENTRY +// SCALAR("item 3",plain) +// FLOW-SEQUENCE-END +// STREAM-END +// +// 2. A flow mapping: +// +// { +// a simple key: a value, # Note that the KEY token is produced. +// ? a complex key: another value, +// } +// +// Tokens: +// +// STREAM-START(utf-8) +// FLOW-MAPPING-START +// KEY +// SCALAR("a simple key",plain) +// VALUE +// SCALAR("a value",plain) +// FLOW-ENTRY +// KEY +// SCALAR("a complex key",plain) +// VALUE +// SCALAR("another value",plain) +// FLOW-ENTRY +// FLOW-MAPPING-END +// STREAM-END +// +// A simple key is a key which is not denoted by the '?' indicator. Note that +// the Scanner still produce the KEY token whenever it encounters a simple key. +// +// For scanning block collections, the following tokens are used (note that we +// repeat KEY and VALUE here): +// +// BLOCK-SEQUENCE-START +// BLOCK-MAPPING-START +// BLOCK-END +// BLOCK-ENTRY +// KEY +// VALUE +// +// The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation +// increase that precedes a block collection (cf. the INDENT token in Python). +// The token BLOCK-END denote indentation decrease that ends a block collection +// (cf. the DEDENT token in Python). However YAML has some syntax pecularities +// that makes detections of these tokens more complex. +// +// The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators +// '-', '?', and ':' correspondingly. +// +// The following examples show how the tokens BLOCK-SEQUENCE-START, +// BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: +// +// 1. Block sequences: +// +// - item 1 +// - item 2 +// - +// - item 3.1 +// - item 3.2 +// - +// key 1: value 1 +// key 2: value 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-ENTRY +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 3.1",plain) +// BLOCK-ENTRY +// SCALAR("item 3.2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// 2. Block mappings: +// +// a simple key: a value # The KEY token is produced here. +// ? a complex key +// : another value +// a mapping: +// key 1: value 1 +// key 2: value 2 +// a sequence: +// - item 1 +// - item 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("a simple key",plain) +// VALUE +// SCALAR("a value",plain) +// KEY +// SCALAR("a complex key",plain) +// VALUE +// SCALAR("another value",plain) +// KEY +// SCALAR("a mapping",plain) +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// KEY +// SCALAR("a sequence",plain) +// VALUE +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// YAML does not always require to start a new block collection from a new +// line. If the current line contains only '-', '?', and ':' indicators, a new +// block collection may start at the current line. The following examples +// illustrate this case: +// +// 1. Collections in a sequence: +// +// - - item 1 +// - item 2 +// - key 1: value 1 +// key 2: value 2 +// - ? complex key +// : complex value +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("complex key") +// VALUE +// SCALAR("complex value") +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// 2. Collections in a mapping: +// +// ? a sequence +// : - item 1 +// - item 2 +// ? a mapping +// : key 1: value 1 +// key 2: value 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("a sequence",plain) +// VALUE +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// KEY +// SCALAR("a mapping",plain) +// VALUE +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// YAML also permits non-indented sequences if they are included into a block +// mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: +// +// key: +// - item 1 # BLOCK-SEQUENCE-START is NOT produced here. +// - item 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("key",plain) +// VALUE +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// + +// Ensure that the buffer contains the required number of characters. +// Return true on success, false on failure (reader error or memory error). +func cache(parser *yaml_parser_t, length int) bool { + // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B) + return parser.unread >= length || yaml_parser_update_buffer(parser, length) +} + +// Advance the buffer pointer. +func skip(parser *yaml_parser_t) { + parser.mark.index++ + parser.mark.column++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) +} + +func skip_line(parser *yaml_parser_t) { + if is_crlf(parser.buffer, parser.buffer_pos) { + parser.mark.index += 2 + parser.mark.column = 0 + parser.mark.line++ + parser.unread -= 2 + parser.buffer_pos += 2 + } else if is_break(parser.buffer, parser.buffer_pos) { + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) + } +} + +// Copy a character to a string buffer and advance pointers. +func read(parser *yaml_parser_t, s []byte) []byte { + w := width(parser.buffer[parser.buffer_pos]) + if w == 0 { + panic("invalid character sequence") + } + if len(s) == 0 { + s = make([]byte, 0, 32) + } + if w == 1 && len(s)+w <= cap(s) { + s = s[:len(s)+1] + s[len(s)-1] = parser.buffer[parser.buffer_pos] + parser.buffer_pos++ + } else { + s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...) + parser.buffer_pos += w + } + parser.mark.index++ + parser.mark.column++ + parser.unread-- + return s +} + +// Copy a line break character to a string buffer and advance pointers. +func read_line(parser *yaml_parser_t, s []byte) []byte { + buf := parser.buffer + pos := parser.buffer_pos + switch { + case buf[pos] == '\r' && buf[pos+1] == '\n': + // CR LF . LF + s = append(s, '\n') + parser.buffer_pos += 2 + parser.mark.index++ + parser.unread-- + case buf[pos] == '\r' || buf[pos] == '\n': + // CR|LF . LF + s = append(s, '\n') + parser.buffer_pos += 1 + case buf[pos] == '\xC2' && buf[pos+1] == '\x85': + // NEL . LF + s = append(s, '\n') + parser.buffer_pos += 2 + case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'): + // LS|PS . LS|PS + s = append(s, buf[parser.buffer_pos:pos+3]...) + parser.buffer_pos += 3 + default: + return s + } + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + return s +} + +// Get the next token. +func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool { + // Erase the token object. + *token = yaml_token_t{} // [Go] Is this necessary? + + // No tokens after STREAM-END or error. + if parser.stream_end_produced || parser.error != yaml_NO_ERROR { + return true + } + + // Ensure that the tokens queue contains enough tokens. + if !parser.token_available { + if !yaml_parser_fetch_more_tokens(parser) { + return false + } + } + + // Fetch the next token from the queue. + *token = parser.tokens[parser.tokens_head] + parser.tokens_head++ + parser.tokens_parsed++ + parser.token_available = false + + if token.typ == yaml_STREAM_END_TOKEN { + parser.stream_end_produced = true + } + return true +} + +// Set the scanner error and return false. +func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool { + parser.error = yaml_SCANNER_ERROR + parser.context = context + parser.context_mark = context_mark + parser.problem = problem + parser.problem_mark = parser.mark + return false +} + +func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool { + context := "while parsing a tag" + if directive { + context = "while parsing a %TAG directive" + } + return yaml_parser_set_scanner_error(parser, context, context_mark, problem) +} + +func trace(args ...interface{}) func() { + pargs := append([]interface{}{"+++"}, args...) + fmt.Println(pargs...) + pargs = append([]interface{}{"---"}, args...) + return func() { fmt.Println(pargs...) } +} + +// Ensure that the tokens queue contains at least one token which can be +// returned to the Parser. +func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { + // While we need more tokens to fetch, do it. + for { + if parser.tokens_head != len(parser.tokens) { + // If queue is non-empty, check if any potential simple key may + // occupy the head position. + head_tok_idx, ok := parser.simple_keys_by_tok[parser.tokens_parsed] + if !ok { + break + } else if valid, ok := yaml_simple_key_is_valid(parser, &parser.simple_keys[head_tok_idx]); !ok { + return false + } else if !valid { + break + } + } + // Fetch the next token. + if !yaml_parser_fetch_next_token(parser) { + return false + } + } + + parser.token_available = true + return true +} + +// The dispatcher for token fetchers. +func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { + // Ensure that the buffer is initialized. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check if we just started scanning. Fetch STREAM-START then. + if !parser.stream_start_produced { + return yaml_parser_fetch_stream_start(parser) + } + + // Eat whitespaces and comments until we reach the next token. + if !yaml_parser_scan_to_next_token(parser) { + return false + } + + // Check the indentation level against the current column. + if !yaml_parser_unroll_indent(parser, parser.mark.column) { + return false + } + + // Ensure that the buffer contains at least 4 characters. 4 is the length + // of the longest indicators ('--- ' and '... '). + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + + // Is it the end of the stream? + if is_z(parser.buffer, parser.buffer_pos) { + return yaml_parser_fetch_stream_end(parser) + } + + // Is it a directive? + if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' { + return yaml_parser_fetch_directive(parser) + } + + buf := parser.buffer + pos := parser.buffer_pos + + // Is it the document start indicator? + if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN) + } + + // Is it the document end indicator? + if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) + } + + // Is it the flow sequence start indicator? + if buf[pos] == '[' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) + } + + // Is it the flow mapping start indicator? + if parser.buffer[parser.buffer_pos] == '{' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) + } + + // Is it the flow sequence end indicator? + if parser.buffer[parser.buffer_pos] == ']' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_SEQUENCE_END_TOKEN) + } + + // Is it the flow mapping end indicator? + if parser.buffer[parser.buffer_pos] == '}' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_MAPPING_END_TOKEN) + } + + // Is it the flow entry indicator? + if parser.buffer[parser.buffer_pos] == ',' { + return yaml_parser_fetch_flow_entry(parser) + } + + // Is it the block entry indicator? + if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) { + return yaml_parser_fetch_block_entry(parser) + } + + // Is it the key indicator? + if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_key(parser) + } + + // Is it the value indicator? + if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_value(parser) + } + + // Is it an alias? + if parser.buffer[parser.buffer_pos] == '*' { + return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) + } + + // Is it an anchor? + if parser.buffer[parser.buffer_pos] == '&' { + return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) + } + + // Is it a tag? + if parser.buffer[parser.buffer_pos] == '!' { + return yaml_parser_fetch_tag(parser) + } + + // Is it a literal scalar? + if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, true) + } + + // Is it a folded scalar? + if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, false) + } + + // Is it a single-quoted scalar? + if parser.buffer[parser.buffer_pos] == '\'' { + return yaml_parser_fetch_flow_scalar(parser, true) + } + + // Is it a double-quoted scalar? + if parser.buffer[parser.buffer_pos] == '"' { + return yaml_parser_fetch_flow_scalar(parser, false) + } + + // Is it a plain scalar? + // + // A plain scalar may start with any non-blank characters except + // + // '-', '?', ':', ',', '[', ']', '{', '}', + // '#', '&', '*', '!', '|', '>', '\'', '\"', + // '%', '@', '`'. + // + // In the block context (and, for the '-' indicator, in the flow context + // too), it may also start with the characters + // + // '-', '?', ':' + // + // if it is followed by a non-space character. + // + // The last rule is more restrictive than the specification requires. + // [Go] Make this logic more reasonable. + //switch parser.buffer[parser.buffer_pos] { + //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': + //} + if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' || + parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' || + parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') || + (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level == 0 && + (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') && + !is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_plain_scalar(parser) + } + + // If we don't determine the token type so far, it is an error. + return yaml_parser_set_scanner_error(parser, + "while scanning for the next token", parser.mark, + "found character that cannot start any token") +} + +func yaml_simple_key_is_valid(parser *yaml_parser_t, simple_key *yaml_simple_key_t) (valid, ok bool) { + if !simple_key.possible { + return false, true + } + + // The 1.2 specification says: + // + // "If the ? indicator is omitted, parsing needs to see past the + // implicit key to recognize it as such. To limit the amount of + // lookahead required, the “:” indicator must appear at most 1024 + // Unicode characters beyond the start of the key. In addition, the key + // is restricted to a single line." + // + if simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index { + // Check if the potential simple key to be removed is required. + if simple_key.required { + return false, yaml_parser_set_scanner_error(parser, + "while scanning a simple key", simple_key.mark, + "could not find expected ':'") + } + simple_key.possible = false + return false, true + } + return true, true +} + +// Check if a simple key may start at the current position and add it if +// needed. +func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { + // A simple key is required at the current position if the scanner is in + // the block context and the current column coincides with the indentation + // level. + + required := parser.flow_level == 0 && parser.indent == parser.mark.column + + // + // If the current position may start a simple key, save it. + // + if parser.simple_key_allowed { + simple_key := yaml_simple_key_t{ + possible: true, + required: required, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + mark: parser.mark, + } + + if !yaml_parser_remove_simple_key(parser) { + return false + } + parser.simple_keys[len(parser.simple_keys)-1] = simple_key + parser.simple_keys_by_tok[simple_key.token_number] = len(parser.simple_keys) - 1 + } + return true +} + +// Remove a potential simple key at the current flow level. +func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { + i := len(parser.simple_keys) - 1 + if parser.simple_keys[i].possible { + // If the key is required, it is an error. + if parser.simple_keys[i].required { + return yaml_parser_set_scanner_error(parser, + "while scanning a simple key", parser.simple_keys[i].mark, + "could not find expected ':'") + } + // Remove the key from the stack. + parser.simple_keys[i].possible = false + delete(parser.simple_keys_by_tok, parser.simple_keys[i].token_number) + } + return true +} + +// max_flow_level limits the flow_level +const max_flow_level = 10000 + +// Increase the flow level and resize the simple key list if needed. +func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { + // Reset the simple key on the next level. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{ + possible: false, + required: false, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + mark: parser.mark, + }) + + // Increase the flow level. + parser.flow_level++ + if parser.flow_level > max_flow_level { + return yaml_parser_set_scanner_error(parser, + "while increasing flow level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_flow_level)) + } + return true +} + +// Decrease the flow level. +func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { + if parser.flow_level > 0 { + parser.flow_level-- + last := len(parser.simple_keys) - 1 + delete(parser.simple_keys_by_tok, parser.simple_keys[last].token_number) + parser.simple_keys = parser.simple_keys[:last] + } + return true +} + +// max_indents limits the indents stack size +const max_indents = 10000 + +// Push the current indentation level to the stack and set the new level +// the current column is greater than the indentation level. In this case, +// append or insert the specified token into the token queue. +func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } + + if parser.indent < column { + // Push the current indentation level to the stack and set the new + // indentation level. + parser.indents = append(parser.indents, parser.indent) + parser.indent = column + if len(parser.indents) > max_indents { + return yaml_parser_set_scanner_error(parser, + "while increasing indent level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_indents)) + } + + // Create a token and insert it into the queue. + token := yaml_token_t{ + typ: typ, + start_mark: mark, + end_mark: mark, + } + if number > -1 { + number -= parser.tokens_parsed + } + yaml_insert_token(parser, number, &token) + } + return true +} + +// Pop indentation levels from the indents stack until the current level +// becomes less or equal to the column. For each indentation level, append +// the BLOCK-END token. +func yaml_parser_unroll_indent(parser *yaml_parser_t, column int) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } + + // Loop through the indentation levels in the stack. + for parser.indent > column { + // Create a token and append it to the queue. + token := yaml_token_t{ + typ: yaml_BLOCK_END_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + } + yaml_insert_token(parser, -1, &token) + + // Pop the indentation level. + parser.indent = parser.indents[len(parser.indents)-1] + parser.indents = parser.indents[:len(parser.indents)-1] + } + return true +} + +// Initialize the scanner and produce the STREAM-START token. +func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { + + // Set the initial indentation. + parser.indent = -1 + + // Initialize the simple key stack. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) + + parser.simple_keys_by_tok = make(map[int]int) + + // A simple key is allowed at the beginning of the stream. + parser.simple_key_allowed = true + + // We have started. + parser.stream_start_produced = true + + // Create the STREAM-START token and append it to the queue. + token := yaml_token_t{ + typ: yaml_STREAM_START_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + encoding: parser.encoding, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the STREAM-END token and shut down the scanner. +func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { + + // Force new line. + if parser.mark.column != 0 { + parser.mark.column = 0 + parser.mark.line++ + } + + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Create the STREAM-END token and append it to the queue. + token := yaml_token_t{ + typ: yaml_STREAM_END_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. +func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. + token := yaml_token_t{} + if !yaml_parser_scan_directive(parser, &token) { + return false + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the DOCUMENT-START or DOCUMENT-END token. +func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Consume the token. + start_mark := parser.mark + + skip(parser) + skip(parser) + skip(parser) + + end_mark := parser.mark + + // Create the DOCUMENT-START or DOCUMENT-END token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. +func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // The indicators '[' and '{' may start a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // Increase the flow level. + if !yaml_parser_increase_flow_level(parser) { + return false + } + + // A simple key may follow the indicators '[' and '{'. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. +func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset any potential simple key on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Decrease the flow level. + if !yaml_parser_decrease_flow_level(parser) { + return false + } + + // No simple keys after the indicators ']' and '}'. + parser.simple_key_allowed = false + + // Consume the token. + + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-ENTRY token. +func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool { + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after ','. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-ENTRY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_FLOW_ENTRY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the BLOCK-ENTRY token. +func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { + // Check if the scanner is in the block context. + if parser.flow_level == 0 { + // Check if we are allowed to start a new entry. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "block sequence entries are not allowed in this context") + } + // Add the BLOCK-SEQUENCE-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) { + return false + } + } else { + // It is an error for the '-' indicator to occur in the flow context, + // but we let the Parser detect and report about it because the Parser + // is able to point to the context. + } + + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after '-'. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the BLOCK-ENTRY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_BLOCK_ENTRY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the KEY token. +func yaml_parser_fetch_key(parser *yaml_parser_t) bool { + + // In the block context, additional checks are required. + if parser.flow_level == 0 { + // Check if we are allowed to start a new key (not nessesary simple). + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping keys are not allowed in this context") + } + // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } + + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after '?' in the block context. + parser.simple_key_allowed = parser.flow_level == 0 + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the KEY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_KEY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the VALUE token. +func yaml_parser_fetch_value(parser *yaml_parser_t) bool { + + simple_key := &parser.simple_keys[len(parser.simple_keys)-1] + + // Have we found a simple key? + if valid, ok := yaml_simple_key_is_valid(parser, simple_key); !ok { + return false + + } else if valid { + + // Create the KEY token and insert it into the queue. + token := yaml_token_t{ + typ: yaml_KEY_TOKEN, + start_mark: simple_key.mark, + end_mark: simple_key.mark, + } + yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token) + + // In the block context, we may need to add the BLOCK-MAPPING-START token. + if !yaml_parser_roll_indent(parser, simple_key.mark.column, + simple_key.token_number, + yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) { + return false + } + + // Remove the simple key. + simple_key.possible = false + delete(parser.simple_keys_by_tok, simple_key.token_number) + + // A simple key cannot follow another simple key. + parser.simple_key_allowed = false + + } else { + // The ':' indicator follows a complex key. + + // In the block context, extra checks are required. + if parser.flow_level == 0 { + + // Check if we are allowed to start a complex value. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping values are not allowed in this context") + } + + // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } + + // Simple keys after ':' are allowed in the block context. + parser.simple_key_allowed = parser.flow_level == 0 + } + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the VALUE token and append it to the queue. + token := yaml_token_t{ + typ: yaml_VALUE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the ALIAS or ANCHOR token. +func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // An anchor or an alias could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow an anchor or an alias. + parser.simple_key_allowed = false + + // Create the ALIAS or ANCHOR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_anchor(parser, &token, typ) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the TAG token. +func yaml_parser_fetch_tag(parser *yaml_parser_t) bool { + // A tag could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a tag. + parser.simple_key_allowed = false + + // Create the TAG token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_tag(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. +func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool { + // Remove any potential simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // A simple key may follow a block scalar. + parser.simple_key_allowed = true + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_block_scalar(parser, &token, literal) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. +func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_flow_scalar(parser, &token, single) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,plain) token. +func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_plain_scalar(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Eat whitespaces and comments until the next token is found. +func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { + + // Until the next token is not found. + for { + // Allow the BOM mark to start a line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) { + skip(parser) + } + + // Eat whitespaces. + // Tabs are allowed: + // - in the flow context + // - in the block context, but not at the beginning of the line or + // after '-', '?', or ':' (complex value). + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Eat a comment until a line break. + if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // If it is a line break, eat it. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + + // In the block context, a new line may start a simple key. + if parser.flow_level == 0 { + parser.simple_key_allowed = true + } + } else { + break // We have found a token. + } + } + + return true +} + +// Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// +func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { + // Eat '%'. + start_mark := parser.mark + skip(parser) + + // Scan the directive name. + var name []byte + if !yaml_parser_scan_directive_name(parser, start_mark, &name) { + return false + } + + // Is it a YAML directive? + if bytes.Equal(name, []byte("YAML")) { + // Scan the VERSION directive value. + var major, minor int8 + if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) { + return false + } + end_mark := parser.mark + + // Create a VERSION-DIRECTIVE token. + *token = yaml_token_t{ + typ: yaml_VERSION_DIRECTIVE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + major: major, + minor: minor, + } + + // Is it a TAG directive? + } else if bytes.Equal(name, []byte("TAG")) { + // Scan the TAG directive value. + var handle, prefix []byte + if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) { + return false + } + end_mark := parser.mark + + // Create a TAG-DIRECTIVE token. + *token = yaml_token_t{ + typ: yaml_TAG_DIRECTIVE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: handle, + prefix: prefix, + } + + // Unknown directive. + } else { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unknown directive name") + return false + } + + // Eat the rest of the line including any comments. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "did not find expected comment or line break") + return false + } + + // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } + + return true +} + +// Scan the directive name. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^ +// +func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { + // Consume the directive name. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + var s []byte + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the name is empty. + if len(s) == 0 { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "could not find expected directive name") + return false + } + + // Check for an blank character after the name. + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unexpected non-alphabetical character") + return false + } + *name = s + return true +} + +// Scan the value of VERSION-DIRECTIVE. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^^^ +func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { + // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Consume the major version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, major) { + return false + } + + // Eat '.'. + if parser.buffer[parser.buffer_pos] != '.' { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected digit or '.' character") + } + + skip(parser) + + // Consume the minor version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) { + return false + } + return true +} + +const max_number_length = 2 + +// Scan the version number of VERSION-DIRECTIVE. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^ +// %YAML 1.1 # a comment \n +// ^ +func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { + + // Repeat while the next character is digit. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var value, length int8 + for is_digit(parser.buffer, parser.buffer_pos) { + // Check if the number is too long. + length++ + if length > max_number_length { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "found extremely long version number") + } + value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos)) + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the number was present. + if length == 0 { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected version number") + } + *number = value + return true +} + +// Scan the value of a TAG-DIRECTIVE token. +// +// Scope: +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// +func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { + var handle_value, prefix_value []byte + + // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Scan a handle. + if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { + return false + } + + // Expect a whitespace. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blank(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace") + return false + } + + // Eat whitespaces. + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Scan a prefix. + if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { + return false + } + + // Expect a whitespace or line break. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace or line break") + return false + } + + *handle = handle_value + *prefix = prefix_value + return true +} + +func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool { + var s []byte + + // Eat the indicator character. + start_mark := parser.mark + skip(parser) + + // Consume the value. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + end_mark := parser.mark + + /* + * Check if length of the anchor is greater than 0 and it is followed by + * a whitespace character or one of the indicators: + * + * '?', ':', ',', ']', '}', '%', '@', '`'. + */ + + if len(s) == 0 || + !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' || + parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '`') { + context := "while scanning an alias" + if typ == yaml_ANCHOR_TOKEN { + context = "while scanning an anchor" + } + yaml_parser_set_scanner_error(parser, context, start_mark, + "did not find expected alphabetic or numeric character") + return false + } + + // Create a token. + *token = yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + value: s, + } + + return true +} + +/* + * Scan a TAG token. + */ + +func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool { + var handle, suffix []byte + + start_mark := parser.mark + + // Check if the tag is in the canonical form. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + if parser.buffer[parser.buffer_pos+1] == '<' { + // Keep the handle as '' + + // Eat '!<' + skip(parser) + skip(parser) + + // Consume the tag value. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } + + // Check for '>' and eat it. + if parser.buffer[parser.buffer_pos] != '>' { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find the expected '>'") + return false + } + + skip(parser) + } else { + // The tag has either the '!suffix' or the '!handle!suffix' form. + + // First, try to scan a handle. + if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) { + return false + } + + // Check if it is, indeed, handle. + if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' { + // Scan the suffix now. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } + } else { + // It wasn't a handle after all. Scan the rest of the tag. + if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) { + return false + } + + // Set the handle to '!'. + handle = []byte{'!'} + + // A special case: the '!' tag. Set the handle to '' and the + // suffix to '!'. + if len(suffix) == 0 { + handle, suffix = suffix, handle + } + } + } + + // Check the character which ends the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find expected whitespace or line break") + return false + } + + end_mark := parser.mark + + // Create a token. + *token = yaml_token_t{ + typ: yaml_TAG_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: handle, + suffix: suffix, + } + return true +} + +// Scan a tag handle. +func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool { + // Check the initial '!' character. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] != '!' { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } + + var s []byte + + // Copy the '!' character. + s = read(parser, s) + + // Copy all subsequent alphabetical and numerical characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the trailing character is '!' and copy it. + if parser.buffer[parser.buffer_pos] == '!' { + s = read(parser, s) + } else { + // It's either the '!' tag or not really a tag handle. If it's a %TAG + // directive, it's an error. If it's a tag token, it must be a part of URI. + if directive && string(s) != "!" { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } + } + + *handle = s + return true +} + +// Scan a tag. +func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { + //size_t length = head ? strlen((char *)head) : 0 + var s []byte + hasTag := len(head) > 0 + + // Copy the head if needed. + // + // Note that we don't copy the leading '!' character. + if len(head) > 1 { + s = append(s, head[1:]...) + } + + // Scan the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // The set of characters that may appear in URI is as follows: + // + // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', + // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', + // '%'. + // [Go] Convert this into more reasonable logic. + for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || + parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' || + parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' || + parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' || + parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || + parser.buffer[parser.buffer_pos] == '%' { + // Check if it is a URI-escape sequence. + if parser.buffer[parser.buffer_pos] == '%' { + if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { + return false + } + } else { + s = read(parser, s) + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + hasTag = true + } + + if !hasTag { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected tag URI") + return false + } + *uri = s + return true +} + +// Decode an URI-escape sequence corresponding to a single UTF-8 character. +func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { + + // Decode the required number of characters. + w := 1024 + for w > 0 { + // Check for a URI-escaped octet. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } + + if !(parser.buffer[parser.buffer_pos] == '%' && + is_hex(parser.buffer, parser.buffer_pos+1) && + is_hex(parser.buffer, parser.buffer_pos+2)) { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find URI escaped octet") + } + + // Get the octet. + octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2)) + + // If it is the leading octet, determine the length of the UTF-8 sequence. + if w == 1024 { + w = width(octet) + if w == 0 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect leading UTF-8 octet") + } + } else { + // Check if the trailing octet is correct. + if octet&0xC0 != 0x80 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect trailing UTF-8 octet") + } + } + + // Copy the octet and move the pointers. + *s = append(*s, octet) + skip(parser) + skip(parser) + skip(parser) + w-- + } + return true +} + +// Scan a block scalar. +func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool { + // Eat the indicator '|' or '>'. + start_mark := parser.mark + skip(parser) + + // Scan the additional block scalar indicators. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check for a chomping indicator. + var chomping, increment int + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + // Set the chomping method and eat the indicator. + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) + + // Check for an indentation indicator. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_digit(parser.buffer, parser.buffer_pos) { + // Check that the indentation is greater than 0. + if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } + + // Get the indentation level and eat the indicator. + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) + } + + } else if is_digit(parser.buffer, parser.buffer_pos) { + // Do the same as above, but in the opposite order. + + if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) + + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) + } + } + + // Eat whitespaces and comments to the end of the line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "did not find expected comment or line break") + return false + } + + // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } + + end_mark := parser.mark + + // Set the indentation level if it was specified. + var indent int + if increment > 0 { + if parser.indent >= 0 { + indent = parser.indent + increment + } else { + indent = increment + } + } + + // Scan the leading line breaks and determine the indentation level if needed. + var s, leading_break, trailing_breaks []byte + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } + + // Scan the block scalar content. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var leading_blank, trailing_blank bool + for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) { + // We are at the beginning of a non-empty line. + + // Is it a trailing whitespace? + trailing_blank = is_blank(parser.buffer, parser.buffer_pos) + + // Check if we need to fold the leading line break. + if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' { + // Do we need to join the lines by space? + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } + } else { + s = append(s, leading_break...) + } + leading_break = leading_break[:0] + + // Append the remaining line breaks. + s = append(s, trailing_breaks...) + trailing_breaks = trailing_breaks[:0] + + // Is it a leading whitespace? + leading_blank = is_blank(parser.buffer, parser.buffer_pos) + + // Consume the current line. + for !is_breakz(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + leading_break = read_line(parser, leading_break) + + // Eat the following indentation spaces and line breaks. + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } + } + + // Chomp the tail. + if chomping != -1 { + s = append(s, leading_break...) + } + if chomping == 1 { + s = append(s, trailing_breaks...) + } + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_LITERAL_SCALAR_STYLE, + } + if !literal { + token.style = yaml_FOLDED_SCALAR_STYLE + } + return true +} + +// Scan indentation spaces and line breaks for a block scalar. Determine the +// indentation level if needed. +func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool { + *end_mark = parser.mark + + // Eat the indentation spaces and line breaks. + max_indent := 0 + for { + // Eat the indentation spaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.mark.column > max_indent { + max_indent = parser.mark.column + } + + // Check for a tab character messing the indentation. + if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) { + return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found a tab character where an indentation space is expected") + } + + // Have we found a non-empty line? + if !is_break(parser.buffer, parser.buffer_pos) { + break + } + + // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + // [Go] Should really be returning breaks instead. + *breaks = read_line(parser, *breaks) + *end_mark = parser.mark + } + + // Determine the indentation level if needed. + if *indent == 0 { + *indent = max_indent + if *indent < parser.indent+1 { + *indent = parser.indent + 1 + } + if *indent < 1 { + *indent = 1 + } + } + return true +} + +// Scan a quoted scalar. +func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool { + // Eat the left quote. + start_mark := parser.mark + skip(parser) + + // Consume the content of the quoted scalar. + var s, leading_break, trailing_breaks, whitespaces []byte + for { + // Check that there are no document indicators at the beginning of the line. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + + if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected document indicator") + return false + } + + // Check for EOF. + if is_z(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected end of stream") + return false + } + + // Consume non-blank characters. + leading_blanks := false + for !is_blankz(parser.buffer, parser.buffer_pos) { + if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' { + // Is is an escaped single quote. + s = append(s, '\'') + skip(parser) + skip(parser) + + } else if single && parser.buffer[parser.buffer_pos] == '\'' { + // It is a right single quote. + break + } else if !single && parser.buffer[parser.buffer_pos] == '"' { + // It is a right double quote. + break + + } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { + // It is an escaped line break. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } + skip(parser) + skip_line(parser) + leading_blanks = true + break + + } else if !single && parser.buffer[parser.buffer_pos] == '\\' { + // It is an escape sequence. + code_length := 0 + + // Check the escape character. + switch parser.buffer[parser.buffer_pos+1] { + case '0': + s = append(s, 0) + case 'a': + s = append(s, '\x07') + case 'b': + s = append(s, '\x08') + case 't', '\t': + s = append(s, '\x09') + case 'n': + s = append(s, '\x0A') + case 'v': + s = append(s, '\x0B') + case 'f': + s = append(s, '\x0C') + case 'r': + s = append(s, '\x0D') + case 'e': + s = append(s, '\x1B') + case ' ': + s = append(s, '\x20') + case '"': + s = append(s, '"') + case '\'': + s = append(s, '\'') + case '\\': + s = append(s, '\\') + case 'N': // NEL (#x85) + s = append(s, '\xC2') + s = append(s, '\x85') + case '_': // #xA0 + s = append(s, '\xC2') + s = append(s, '\xA0') + case 'L': // LS (#x2028) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA8') + case 'P': // PS (#x2029) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA9') + case 'x': + code_length = 2 + case 'u': + code_length = 4 + case 'U': + code_length = 8 + default: + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found unknown escape character") + return false + } + + skip(parser) + skip(parser) + + // Consume an arbitrary escape code. + if code_length > 0 { + var value int + + // Scan the character value. + if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) { + return false + } + for k := 0; k < code_length; k++ { + if !is_hex(parser.buffer, parser.buffer_pos+k) { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "did not find expected hexdecimal number") + return false + } + value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k) + } + + // Check the value and write the character. + if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found invalid Unicode character escape code") + return false + } + if value <= 0x7F { + s = append(s, byte(value)) + } else if value <= 0x7FF { + s = append(s, byte(0xC0+(value>>6))) + s = append(s, byte(0x80+(value&0x3F))) + } else if value <= 0xFFFF { + s = append(s, byte(0xE0+(value>>12))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } else { + s = append(s, byte(0xF0+(value>>18))) + s = append(s, byte(0x80+((value>>12)&0x3F))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } + + // Advance the pointer. + for k := 0; k < code_length; k++ { + skip(parser) + } + } + } else { + // It is a non-escaped non-blank character. + s = read(parser, s) + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } + + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check if we are at the end of the scalar. + if single { + if parser.buffer[parser.buffer_pos] == '\'' { + break + } + } else { + if parser.buffer[parser.buffer_pos] == '"' { + break + } + } + + // Consume blank characters. + for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { + // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Join the whitespaces or fold line breaks. + if leading_blanks { + // Do we need to fold line breaks? + if len(leading_break) > 0 && leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } + + // Eat the right quote. + skip(parser) + end_mark := parser.mark + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_SINGLE_QUOTED_SCALAR_STYLE, + } + if !single { + token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + return true +} + +// Scan a plain scalar. +func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { + + var s, leading_break, trailing_breaks, whitespaces []byte + var leading_blanks bool + var indent = parser.indent + 1 + + start_mark := parser.mark + end_mark := parser.mark + + // Consume the content of the plain scalar. + for { + // Check for a document indicator. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + break + } + + // Check for a comment. + if parser.buffer[parser.buffer_pos] == '#' { + break + } + + // Consume non-blank characters. + for !is_blankz(parser.buffer, parser.buffer_pos) { + + // Check for indicators that may end a plain scalar. + if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level > 0 && + (parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}')) { + break + } + + // Check if we need to join whitespaces and breaks. + if leading_blanks || len(whitespaces) > 0 { + if leading_blanks { + // Do we need to fold line breaks? + if leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + leading_blanks = false + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } + + // Copy the character. + s = read(parser, s) + + end_mark = parser.mark + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } + + // Is it the end? + if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) { + break + } + + // Consume blank characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { + + // Check for tab characters that abuse indentation. + if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", + start_mark, "found a tab character that violates indentation") + return false + } + + // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check indentation level. + if parser.flow_level == 0 && parser.mark.column < indent { + break + } + } + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_PLAIN_SCALAR_STYLE, + } + + // Note that we change the 'simple_key_allowed' flag. + if leading_blanks { + parser.simple_key_allowed = true + } + return true +} diff --git a/vendor/gopkg.in/yaml.v2/sorter.go b/vendor/gopkg.in/yaml.v2/sorter.go new file mode 100644 index 00000000..4c45e660 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/sorter.go @@ -0,0 +1,113 @@ +package yaml + +import ( + "reflect" + "unicode" +) + +type keyList []reflect.Value + +func (l keyList) Len() int { return len(l) } +func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } +func (l keyList) Less(i, j int) bool { + a := l[i] + b := l[j] + ak := a.Kind() + bk := b.Kind() + for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { + a = a.Elem() + ak = a.Kind() + } + for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { + b = b.Elem() + bk = b.Kind() + } + af, aok := keyFloat(a) + bf, bok := keyFloat(b) + if aok && bok { + if af != bf { + return af < bf + } + if ak != bk { + return ak < bk + } + return numLess(a, b) + } + if ak != reflect.String || bk != reflect.String { + return ak < bk + } + ar, br := []rune(a.String()), []rune(b.String()) + for i := 0; i < len(ar) && i < len(br); i++ { + if ar[i] == br[i] { + continue + } + al := unicode.IsLetter(ar[i]) + bl := unicode.IsLetter(br[i]) + if al && bl { + return ar[i] < br[i] + } + if al || bl { + return bl + } + var ai, bi int + var an, bn int64 + if ar[i] == '0' || br[i] == '0' { + for j := i-1; j >= 0 && unicode.IsDigit(ar[j]); j-- { + if ar[j] != '0' { + an = 1 + bn = 1 + break + } + } + } + for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { + an = an*10 + int64(ar[ai]-'0') + } + for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { + bn = bn*10 + int64(br[bi]-'0') + } + if an != bn { + return an < bn + } + if ai != bi { + return ai < bi + } + return ar[i] < br[i] + } + return len(ar) < len(br) +} + +// keyFloat returns a float value for v if it is a number/bool +// and whether it is a number/bool or not. +func keyFloat(v reflect.Value) (f float64, ok bool) { + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return float64(v.Int()), true + case reflect.Float32, reflect.Float64: + return v.Float(), true + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return float64(v.Uint()), true + case reflect.Bool: + if v.Bool() { + return 1, true + } + return 0, true + } + return 0, false +} + +// numLess returns whether a < b. +// a and b must necessarily have the same kind. +func numLess(a, b reflect.Value) bool { + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() < b.Int() + case reflect.Float32, reflect.Float64: + return a.Float() < b.Float() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Bool: + return !a.Bool() && b.Bool() + } + panic("not a number") +} diff --git a/vendor/gopkg.in/yaml.v2/writerc.go b/vendor/gopkg.in/yaml.v2/writerc.go new file mode 100644 index 00000000..a2dde608 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/writerc.go @@ -0,0 +1,26 @@ +package yaml + +// Set the writer error and return false. +func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_WRITER_ERROR + emitter.problem = problem + return false +} + +// Flush the output buffer. +func yaml_emitter_flush(emitter *yaml_emitter_t) bool { + if emitter.write_handler == nil { + panic("write handler not set") + } + + // Check if the buffer is empty. + if emitter.buffer_pos == 0 { + return true + } + + if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { + return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) + } + emitter.buffer_pos = 0 + return true +} diff --git a/vendor/gopkg.in/yaml.v2/yaml.go b/vendor/gopkg.in/yaml.v2/yaml.go new file mode 100644 index 00000000..30813884 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/yaml.go @@ -0,0 +1,478 @@ +// Package yaml implements YAML support for the Go language. +// +// Source code and other details for the project are available at GitHub: +// +// https://github.com/go-yaml/yaml +// +package yaml + +import ( + "errors" + "fmt" + "io" + "reflect" + "strings" + "sync" +) + +// MapSlice encodes and decodes as a YAML map. +// The order of keys is preserved when encoding and decoding. +type MapSlice []MapItem + +// MapItem is an item in a MapSlice. +type MapItem struct { + Key, Value interface{} +} + +// The Unmarshaler interface may be implemented by types to customize their +// behavior when being unmarshaled from a YAML document. The UnmarshalYAML +// method receives a function that may be called to unmarshal the original +// YAML value into a field or variable. It is safe to call the unmarshal +// function parameter more than once if necessary. +type Unmarshaler interface { + UnmarshalYAML(unmarshal func(interface{}) error) error +} + +// The Marshaler interface may be implemented by types to customize their +// behavior when being marshaled into a YAML document. The returned value +// is marshaled in place of the original value implementing Marshaler. +// +// If an error is returned by MarshalYAML, the marshaling procedure stops +// and returns with the provided error. +type Marshaler interface { + MarshalYAML() (interface{}, error) +} + +// Unmarshal decodes the first document found within the in byte slice +// and assigns decoded values into the out value. +// +// Maps and pointers (to a struct, string, int, etc) are accepted as out +// values. If an internal pointer within a struct is not initialized, +// the yaml package will initialize it if necessary for unmarshalling +// the provided data. The out parameter must not be nil. +// +// The type of the decoded values should be compatible with the respective +// values in out. If one or more values cannot be decoded due to a type +// mismatches, decoding continues partially until the end of the YAML +// content, and a *yaml.TypeError is returned with details for all +// missed values. +// +// Struct fields are only unmarshalled if they are exported (have an +// upper case first letter), and are unmarshalled using the field name +// lowercased as the default key. Custom keys may be defined via the +// "yaml" name in the field tag: the content preceding the first comma +// is used as the key, and the following comma-separated options are +// used to tweak the marshalling process (see Marshal). +// Conflicting names result in a runtime error. +// +// For example: +// +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// var t T +// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) +// +// See the documentation of Marshal for the format of tags and a list of +// supported tag options. +// +func Unmarshal(in []byte, out interface{}) (err error) { + return unmarshal(in, out, false) +} + +// UnmarshalStrict is like Unmarshal except that any fields that are found +// in the data that do not have corresponding struct members, or mapping +// keys that are duplicates, will result in +// an error. +func UnmarshalStrict(in []byte, out interface{}) (err error) { + return unmarshal(in, out, true) +} + +// A Decoder reads and decodes YAML values from an input stream. +type Decoder struct { + strict bool + parser *parser +} + +// NewDecoder returns a new decoder that reads from r. +// +// The decoder introduces its own buffering and may read +// data from r beyond the YAML values requested. +func NewDecoder(r io.Reader) *Decoder { + return &Decoder{ + parser: newParserFromReader(r), + } +} + +// SetStrict sets whether strict decoding behaviour is enabled when +// decoding items in the data (see UnmarshalStrict). By default, decoding is not strict. +func (dec *Decoder) SetStrict(strict bool) { + dec.strict = strict +} + +// Decode reads the next YAML-encoded value from its input +// and stores it in the value pointed to by v. +// +// See the documentation for Unmarshal for details about the +// conversion of YAML into a Go value. +func (dec *Decoder) Decode(v interface{}) (err error) { + d := newDecoder(dec.strict) + defer handleErr(&err) + node := dec.parser.parse() + if node == nil { + return io.EOF + } + out := reflect.ValueOf(v) + if out.Kind() == reflect.Ptr && !out.IsNil() { + out = out.Elem() + } + d.unmarshal(node, out) + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +func unmarshal(in []byte, out interface{}, strict bool) (err error) { + defer handleErr(&err) + d := newDecoder(strict) + p := newParser(in) + defer p.destroy() + node := p.parse() + if node != nil { + v := reflect.ValueOf(out) + if v.Kind() == reflect.Ptr && !v.IsNil() { + v = v.Elem() + } + d.unmarshal(node, v) + } + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +// Marshal serializes the value provided into a YAML document. The structure +// of the generated document will reflect the structure of the value itself. +// Maps and pointers (to struct, string, int, etc) are accepted as the in value. +// +// Struct fields are only marshalled if they are exported (have an upper case +// first letter), and are marshalled using the field name lowercased as the +// default key. Custom keys may be defined via the "yaml" name in the field +// tag: the content preceding the first comma is used as the key, and the +// following comma-separated options are used to tweak the marshalling process. +// Conflicting names result in a runtime error. +// +// The field tag format accepted is: +// +// `(...) yaml:"[][,[,]]" (...)` +// +// The following flags are currently supported: +// +// omitempty Only include the field if it's not set to the zero +// value for the type or to empty slices or maps. +// Zero valued structs will be omitted if all their public +// fields are zero, unless they implement an IsZero +// method (see the IsZeroer interface type), in which +// case the field will be excluded if IsZero returns true. +// +// flow Marshal using a flow style (useful for structs, +// sequences and maps). +// +// inline Inline the field, which must be a struct or a map, +// causing all of its fields or keys to be processed as if +// they were part of the outer struct. For maps, keys must +// not conflict with the yaml keys of other struct fields. +// +// In addition, if the key is "-", the field is ignored. +// +// For example: +// +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" +// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" +// +func Marshal(in interface{}) (out []byte, err error) { + defer handleErr(&err) + e := newEncoder() + defer e.destroy() + e.marshalDoc("", reflect.ValueOf(in)) + e.finish() + out = e.out + return +} + +// An Encoder writes YAML values to an output stream. +type Encoder struct { + encoder *encoder +} + +// NewEncoder returns a new encoder that writes to w. +// The Encoder should be closed after use to flush all data +// to w. +func NewEncoder(w io.Writer) *Encoder { + return &Encoder{ + encoder: newEncoderWithWriter(w), + } +} + +// Encode writes the YAML encoding of v to the stream. +// If multiple items are encoded to the stream, the +// second and subsequent document will be preceded +// with a "---" document separator, but the first will not. +// +// See the documentation for Marshal for details about the conversion of Go +// values to YAML. +func (e *Encoder) Encode(v interface{}) (err error) { + defer handleErr(&err) + e.encoder.marshalDoc("", reflect.ValueOf(v)) + return nil +} + +// Close closes the encoder by writing any remaining data. +// It does not write a stream terminating string "...". +func (e *Encoder) Close() (err error) { + defer handleErr(&err) + e.encoder.finish() + return nil +} + +func handleErr(err *error) { + if v := recover(); v != nil { + if e, ok := v.(yamlError); ok { + *err = e.err + } else { + panic(v) + } + } +} + +type yamlError struct { + err error +} + +func fail(err error) { + panic(yamlError{err}) +} + +func failf(format string, args ...interface{}) { + panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) +} + +// A TypeError is returned by Unmarshal when one or more fields in +// the YAML document cannot be properly decoded into the requested +// types. When this error is returned, the value is still +// unmarshaled partially. +type TypeError struct { + Errors []string +} + +func (e *TypeError) Error() string { + return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) +} + +// -------------------------------------------------------------------------- +// Maintain a mapping of keys to structure field indexes + +// The code in this section was copied from mgo/bson. + +// structInfo holds details for the serialization of fields of +// a given struct. +type structInfo struct { + FieldsMap map[string]fieldInfo + FieldsList []fieldInfo + + // InlineMap is the number of the field in the struct that + // contains an ,inline map, or -1 if there's none. + InlineMap int +} + +type fieldInfo struct { + Key string + Num int + OmitEmpty bool + Flow bool + // Id holds the unique field identifier, so we can cheaply + // check for field duplicates without maintaining an extra map. + Id int + + // Inline holds the field index if the field is part of an inlined struct. + Inline []int +} + +var structMap = make(map[reflect.Type]*structInfo) +var fieldMapMutex sync.RWMutex + +func getStructInfo(st reflect.Type) (*structInfo, error) { + fieldMapMutex.RLock() + sinfo, found := structMap[st] + fieldMapMutex.RUnlock() + if found { + return sinfo, nil + } + + n := st.NumField() + fieldsMap := make(map[string]fieldInfo) + fieldsList := make([]fieldInfo, 0, n) + inlineMap := -1 + for i := 0; i != n; i++ { + field := st.Field(i) + if field.PkgPath != "" && !field.Anonymous { + continue // Private field + } + + info := fieldInfo{Num: i} + + tag := field.Tag.Get("yaml") + if tag == "" && strings.Index(string(field.Tag), ":") < 0 { + tag = string(field.Tag) + } + if tag == "-" { + continue + } + + inline := false + fields := strings.Split(tag, ",") + if len(fields) > 1 { + for _, flag := range fields[1:] { + switch flag { + case "omitempty": + info.OmitEmpty = true + case "flow": + info.Flow = true + case "inline": + inline = true + default: + return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st)) + } + } + tag = fields[0] + } + + if inline { + switch field.Type.Kind() { + case reflect.Map: + if inlineMap >= 0 { + return nil, errors.New("Multiple ,inline maps in struct " + st.String()) + } + if field.Type.Key() != reflect.TypeOf("") { + return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String()) + } + inlineMap = info.Num + case reflect.Struct: + sinfo, err := getStructInfo(field.Type) + if err != nil { + return nil, err + } + for _, finfo := range sinfo.FieldsList { + if _, found := fieldsMap[finfo.Key]; found { + msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + if finfo.Inline == nil { + finfo.Inline = []int{i, finfo.Num} + } else { + finfo.Inline = append([]int{i}, finfo.Inline...) + } + finfo.Id = len(fieldsList) + fieldsMap[finfo.Key] = finfo + fieldsList = append(fieldsList, finfo) + } + default: + //return nil, errors.New("Option ,inline needs a struct value or map field") + return nil, errors.New("Option ,inline needs a struct value field") + } + continue + } + + if tag != "" { + info.Key = tag + } else { + info.Key = strings.ToLower(field.Name) + } + + if _, found = fieldsMap[info.Key]; found { + msg := "Duplicated key '" + info.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + + info.Id = len(fieldsList) + fieldsList = append(fieldsList, info) + fieldsMap[info.Key] = info + } + + sinfo = &structInfo{ + FieldsMap: fieldsMap, + FieldsList: fieldsList, + InlineMap: inlineMap, + } + + fieldMapMutex.Lock() + structMap[st] = sinfo + fieldMapMutex.Unlock() + return sinfo, nil +} + +// IsZeroer is used to check whether an object is zero to +// determine whether it should be omitted when marshaling +// with the omitempty flag. One notable implementation +// is time.Time. +type IsZeroer interface { + IsZero() bool +} + +func isZero(v reflect.Value) bool { + kind := v.Kind() + if z, ok := v.Interface().(IsZeroer); ok { + if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() { + return true + } + return z.IsZero() + } + switch kind { + case reflect.String: + return len(v.String()) == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + case reflect.Slice: + return v.Len() == 0 + case reflect.Map: + return v.Len() == 0 + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Struct: + vt := v.Type() + for i := v.NumField() - 1; i >= 0; i-- { + if vt.Field(i).PkgPath != "" { + continue // Private field + } + if !isZero(v.Field(i)) { + return false + } + } + return true + } + return false +} + +// FutureLineWrap globally disables line wrapping when encoding long strings. +// This is a temporary and thus deprecated method introduced to faciliate +// migration towards v3, which offers more control of line lengths on +// individual encodings, and has a default matching the behavior introduced +// by this function. +// +// The default formatting of v2 was erroneously changed in v2.3.0 and reverted +// in v2.4.0, at which point this function was introduced to help migration. +func FutureLineWrap() { + disableLineWrapping = true +} diff --git a/vendor/gopkg.in/yaml.v2/yamlh.go b/vendor/gopkg.in/yaml.v2/yamlh.go new file mode 100644 index 00000000..f6a9c8e3 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/yamlh.go @@ -0,0 +1,739 @@ +package yaml + +import ( + "fmt" + "io" +) + +// The version directive data. +type yaml_version_directive_t struct { + major int8 // The major version number. + minor int8 // The minor version number. +} + +// The tag directive data. +type yaml_tag_directive_t struct { + handle []byte // The tag handle. + prefix []byte // The tag prefix. +} + +type yaml_encoding_t int + +// The stream encoding. +const ( + // Let the parser choose the encoding. + yaml_ANY_ENCODING yaml_encoding_t = iota + + yaml_UTF8_ENCODING // The default UTF-8 encoding. + yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM. + yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM. +) + +type yaml_break_t int + +// Line break types. +const ( + // Let the parser choose the break type. + yaml_ANY_BREAK yaml_break_t = iota + + yaml_CR_BREAK // Use CR for line breaks (Mac style). + yaml_LN_BREAK // Use LN for line breaks (Unix style). + yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style). +) + +type yaml_error_type_t int + +// Many bad things could happen with the parser and emitter. +const ( + // No error is produced. + yaml_NO_ERROR yaml_error_type_t = iota + + yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. + yaml_READER_ERROR // Cannot read or decode the input stream. + yaml_SCANNER_ERROR // Cannot scan the input stream. + yaml_PARSER_ERROR // Cannot parse the input stream. + yaml_COMPOSER_ERROR // Cannot compose a YAML document. + yaml_WRITER_ERROR // Cannot write to the output stream. + yaml_EMITTER_ERROR // Cannot emit a YAML stream. +) + +// The pointer position. +type yaml_mark_t struct { + index int // The position index. + line int // The position line. + column int // The position column. +} + +// Node Styles + +type yaml_style_t int8 + +type yaml_scalar_style_t yaml_style_t + +// Scalar styles. +const ( + // Let the emitter choose the style. + yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = iota + + yaml_PLAIN_SCALAR_STYLE // The plain scalar style. + yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. + yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. + yaml_LITERAL_SCALAR_STYLE // The literal scalar style. + yaml_FOLDED_SCALAR_STYLE // The folded scalar style. +) + +type yaml_sequence_style_t yaml_style_t + +// Sequence styles. +const ( + // Let the emitter choose the style. + yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota + + yaml_BLOCK_SEQUENCE_STYLE // The block sequence style. + yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. +) + +type yaml_mapping_style_t yaml_style_t + +// Mapping styles. +const ( + // Let the emitter choose the style. + yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota + + yaml_BLOCK_MAPPING_STYLE // The block mapping style. + yaml_FLOW_MAPPING_STYLE // The flow mapping style. +) + +// Tokens + +type yaml_token_type_t int + +// Token types. +const ( + // An empty token. + yaml_NO_TOKEN yaml_token_type_t = iota + + yaml_STREAM_START_TOKEN // A STREAM-START token. + yaml_STREAM_END_TOKEN // A STREAM-END token. + + yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. + yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. + yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. + yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. + + yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. + yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. + yaml_BLOCK_END_TOKEN // A BLOCK-END token. + + yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. + yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. + yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. + yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. + + yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. + yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. + yaml_KEY_TOKEN // A KEY token. + yaml_VALUE_TOKEN // A VALUE token. + + yaml_ALIAS_TOKEN // An ALIAS token. + yaml_ANCHOR_TOKEN // An ANCHOR token. + yaml_TAG_TOKEN // A TAG token. + yaml_SCALAR_TOKEN // A SCALAR token. +) + +func (tt yaml_token_type_t) String() string { + switch tt { + case yaml_NO_TOKEN: + return "yaml_NO_TOKEN" + case yaml_STREAM_START_TOKEN: + return "yaml_STREAM_START_TOKEN" + case yaml_STREAM_END_TOKEN: + return "yaml_STREAM_END_TOKEN" + case yaml_VERSION_DIRECTIVE_TOKEN: + return "yaml_VERSION_DIRECTIVE_TOKEN" + case yaml_TAG_DIRECTIVE_TOKEN: + return "yaml_TAG_DIRECTIVE_TOKEN" + case yaml_DOCUMENT_START_TOKEN: + return "yaml_DOCUMENT_START_TOKEN" + case yaml_DOCUMENT_END_TOKEN: + return "yaml_DOCUMENT_END_TOKEN" + case yaml_BLOCK_SEQUENCE_START_TOKEN: + return "yaml_BLOCK_SEQUENCE_START_TOKEN" + case yaml_BLOCK_MAPPING_START_TOKEN: + return "yaml_BLOCK_MAPPING_START_TOKEN" + case yaml_BLOCK_END_TOKEN: + return "yaml_BLOCK_END_TOKEN" + case yaml_FLOW_SEQUENCE_START_TOKEN: + return "yaml_FLOW_SEQUENCE_START_TOKEN" + case yaml_FLOW_SEQUENCE_END_TOKEN: + return "yaml_FLOW_SEQUENCE_END_TOKEN" + case yaml_FLOW_MAPPING_START_TOKEN: + return "yaml_FLOW_MAPPING_START_TOKEN" + case yaml_FLOW_MAPPING_END_TOKEN: + return "yaml_FLOW_MAPPING_END_TOKEN" + case yaml_BLOCK_ENTRY_TOKEN: + return "yaml_BLOCK_ENTRY_TOKEN" + case yaml_FLOW_ENTRY_TOKEN: + return "yaml_FLOW_ENTRY_TOKEN" + case yaml_KEY_TOKEN: + return "yaml_KEY_TOKEN" + case yaml_VALUE_TOKEN: + return "yaml_VALUE_TOKEN" + case yaml_ALIAS_TOKEN: + return "yaml_ALIAS_TOKEN" + case yaml_ANCHOR_TOKEN: + return "yaml_ANCHOR_TOKEN" + case yaml_TAG_TOKEN: + return "yaml_TAG_TOKEN" + case yaml_SCALAR_TOKEN: + return "yaml_SCALAR_TOKEN" + } + return "" +} + +// The token structure. +type yaml_token_t struct { + // The token type. + typ yaml_token_type_t + + // The start/end of the token. + start_mark, end_mark yaml_mark_t + + // The stream encoding (for yaml_STREAM_START_TOKEN). + encoding yaml_encoding_t + + // The alias/anchor/scalar value or tag/tag directive handle + // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN). + value []byte + + // The tag suffix (for yaml_TAG_TOKEN). + suffix []byte + + // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN). + prefix []byte + + // The scalar style (for yaml_SCALAR_TOKEN). + style yaml_scalar_style_t + + // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN). + major, minor int8 +} + +// Events + +type yaml_event_type_t int8 + +// Event types. +const ( + // An empty event. + yaml_NO_EVENT yaml_event_type_t = iota + + yaml_STREAM_START_EVENT // A STREAM-START event. + yaml_STREAM_END_EVENT // A STREAM-END event. + yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event. + yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. + yaml_ALIAS_EVENT // An ALIAS event. + yaml_SCALAR_EVENT // A SCALAR event. + yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event. + yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. + yaml_MAPPING_START_EVENT // A MAPPING-START event. + yaml_MAPPING_END_EVENT // A MAPPING-END event. +) + +var eventStrings = []string{ + yaml_NO_EVENT: "none", + yaml_STREAM_START_EVENT: "stream start", + yaml_STREAM_END_EVENT: "stream end", + yaml_DOCUMENT_START_EVENT: "document start", + yaml_DOCUMENT_END_EVENT: "document end", + yaml_ALIAS_EVENT: "alias", + yaml_SCALAR_EVENT: "scalar", + yaml_SEQUENCE_START_EVENT: "sequence start", + yaml_SEQUENCE_END_EVENT: "sequence end", + yaml_MAPPING_START_EVENT: "mapping start", + yaml_MAPPING_END_EVENT: "mapping end", +} + +func (e yaml_event_type_t) String() string { + if e < 0 || int(e) >= len(eventStrings) { + return fmt.Sprintf("unknown event %d", e) + } + return eventStrings[e] +} + +// The event structure. +type yaml_event_t struct { + + // The event type. + typ yaml_event_type_t + + // The start and end of the event. + start_mark, end_mark yaml_mark_t + + // The document encoding (for yaml_STREAM_START_EVENT). + encoding yaml_encoding_t + + // The version directive (for yaml_DOCUMENT_START_EVENT). + version_directive *yaml_version_directive_t + + // The list of tag directives (for yaml_DOCUMENT_START_EVENT). + tag_directives []yaml_tag_directive_t + + // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). + anchor []byte + + // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + tag []byte + + // The scalar value (for yaml_SCALAR_EVENT). + value []byte + + // Is the document start/end indicator implicit, or the tag optional? + // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT). + implicit bool + + // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT). + quoted_implicit bool + + // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + style yaml_style_t +} + +func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } +func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) } +func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } + +// Nodes + +const ( + yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. + yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. + yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. + yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. + yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. + yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. + + yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. + yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. + + // Not in original libyaml. + yaml_BINARY_TAG = "tag:yaml.org,2002:binary" + yaml_MERGE_TAG = "tag:yaml.org,2002:merge" + + yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. + yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq. + yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. +) + +type yaml_node_type_t int + +// Node types. +const ( + // An empty node. + yaml_NO_NODE yaml_node_type_t = iota + + yaml_SCALAR_NODE // A scalar node. + yaml_SEQUENCE_NODE // A sequence node. + yaml_MAPPING_NODE // A mapping node. +) + +// An element of a sequence node. +type yaml_node_item_t int + +// An element of a mapping node. +type yaml_node_pair_t struct { + key int // The key of the element. + value int // The value of the element. +} + +// The node structure. +type yaml_node_t struct { + typ yaml_node_type_t // The node type. + tag []byte // The node tag. + + // The node data. + + // The scalar parameters (for yaml_SCALAR_NODE). + scalar struct { + value []byte // The scalar value. + length int // The length of the scalar value. + style yaml_scalar_style_t // The scalar style. + } + + // The sequence parameters (for YAML_SEQUENCE_NODE). + sequence struct { + items_data []yaml_node_item_t // The stack of sequence items. + style yaml_sequence_style_t // The sequence style. + } + + // The mapping parameters (for yaml_MAPPING_NODE). + mapping struct { + pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). + pairs_start *yaml_node_pair_t // The beginning of the stack. + pairs_end *yaml_node_pair_t // The end of the stack. + pairs_top *yaml_node_pair_t // The top of the stack. + style yaml_mapping_style_t // The mapping style. + } + + start_mark yaml_mark_t // The beginning of the node. + end_mark yaml_mark_t // The end of the node. + +} + +// The document structure. +type yaml_document_t struct { + + // The document nodes. + nodes []yaml_node_t + + // The version directive. + version_directive *yaml_version_directive_t + + // The list of tag directives. + tag_directives_data []yaml_tag_directive_t + tag_directives_start int // The beginning of the tag directives list. + tag_directives_end int // The end of the tag directives list. + + start_implicit int // Is the document start indicator implicit? + end_implicit int // Is the document end indicator implicit? + + // The start/end of the document. + start_mark, end_mark yaml_mark_t +} + +// The prototype of a read handler. +// +// The read handler is called when the parser needs to read more bytes from the +// source. The handler should write not more than size bytes to the buffer. +// The number of written bytes should be set to the size_read variable. +// +// [in,out] data A pointer to an application data specified by +// yaml_parser_set_input(). +// [out] buffer The buffer to write the data from the source. +// [in] size The size of the buffer. +// [out] size_read The actual number of bytes read from the source. +// +// On success, the handler should return 1. If the handler failed, +// the returned value should be 0. On EOF, the handler should set the +// size_read to 0 and return 1. +type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) + +// This structure holds information about a potential simple key. +type yaml_simple_key_t struct { + possible bool // Is a simple key possible? + required bool // Is a simple key required? + token_number int // The number of the token. + mark yaml_mark_t // The position mark. +} + +// The states of the parser. +type yaml_parser_state_t int + +const ( + yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota + + yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. + yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. + yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. + yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. + yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. + yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence. + yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. + yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. + yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. + yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. + yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. + yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. + yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. + yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. + yaml_PARSE_END_STATE // Expect nothing. +) + +func (ps yaml_parser_state_t) String() string { + switch ps { + case yaml_PARSE_STREAM_START_STATE: + return "yaml_PARSE_STREAM_START_STATE" + case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_START_STATE: + return "yaml_PARSE_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_CONTENT_STATE: + return "yaml_PARSE_DOCUMENT_CONTENT_STATE" + case yaml_PARSE_DOCUMENT_END_STATE: + return "yaml_PARSE_DOCUMENT_END_STATE" + case yaml_PARSE_BLOCK_NODE_STATE: + return "yaml_PARSE_BLOCK_NODE_STATE" + case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE" + case yaml_PARSE_FLOW_NODE_STATE: + return "yaml_PARSE_FLOW_NODE_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: + return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE" + case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE" + case yaml_PARSE_END_STATE: + return "yaml_PARSE_END_STATE" + } + return "" +} + +// This structure holds aliases data. +type yaml_alias_data_t struct { + anchor []byte // The anchor. + index int // The node id. + mark yaml_mark_t // The anchor mark. +} + +// The parser structure. +// +// All members are internal. Manage the structure using the +// yaml_parser_ family of functions. +type yaml_parser_t struct { + + // Error handling + + error yaml_error_type_t // Error type. + + problem string // Error description. + + // The byte about which the problem occurred. + problem_offset int + problem_value int + problem_mark yaml_mark_t + + // The error context. + context string + context_mark yaml_mark_t + + // Reader stuff + + read_handler yaml_read_handler_t // Read handler. + + input_reader io.Reader // File input data. + input []byte // String input data. + input_pos int + + eof bool // EOF flag + + buffer []byte // The working buffer. + buffer_pos int // The current position of the buffer. + + unread int // The number of unread characters in the buffer. + + raw_buffer []byte // The raw buffer. + raw_buffer_pos int // The current position of the buffer. + + encoding yaml_encoding_t // The input encoding. + + offset int // The offset of the current position (in bytes). + mark yaml_mark_t // The mark of the current position. + + // Scanner stuff + + stream_start_produced bool // Have we started to scan the input stream? + stream_end_produced bool // Have we reached the end of the input stream? + + flow_level int // The number of unclosed '[' and '{' indicators. + + tokens []yaml_token_t // The tokens queue. + tokens_head int // The head of the tokens queue. + tokens_parsed int // The number of tokens fetched from the queue. + token_available bool // Does the tokens queue contain a token ready for dequeueing. + + indent int // The current indentation level. + indents []int // The indentation levels stack. + + simple_key_allowed bool // May a simple key occur at the current position? + simple_keys []yaml_simple_key_t // The stack of simple keys. + simple_keys_by_tok map[int]int // possible simple_key indexes indexed by token_number + + // Parser stuff + + state yaml_parser_state_t // The current parser state. + states []yaml_parser_state_t // The parser states stack. + marks []yaml_mark_t // The stack of marks. + tag_directives []yaml_tag_directive_t // The list of TAG directives. + + // Dumper stuff + + aliases []yaml_alias_data_t // The alias data. + + document *yaml_document_t // The currently parsed document. +} + +// Emitter Definitions + +// The prototype of a write handler. +// +// The write handler is called when the emitter needs to flush the accumulated +// characters to the output. The handler should write @a size bytes of the +// @a buffer to the output. +// +// @param[in,out] data A pointer to an application data specified by +// yaml_emitter_set_output(). +// @param[in] buffer The buffer with bytes to be written. +// @param[in] size The size of the buffer. +// +// @returns On success, the handler should return @c 1. If the handler failed, +// the returned value should be @c 0. +// +type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error + +type yaml_emitter_state_t int + +// The emitter states. +const ( + // Expect STREAM-START. + yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota + + yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. + yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. + yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. + yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. + yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. + yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. + yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. + yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. + yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. + yaml_EMIT_END_STATE // Expect nothing. +) + +// The emitter structure. +// +// All members are internal. Manage the structure using the @c yaml_emitter_ +// family of functions. +type yaml_emitter_t struct { + + // Error handling + + error yaml_error_type_t // Error type. + problem string // Error description. + + // Writer stuff + + write_handler yaml_write_handler_t // Write handler. + + output_buffer *[]byte // String output data. + output_writer io.Writer // File output data. + + buffer []byte // The working buffer. + buffer_pos int // The current position of the buffer. + + raw_buffer []byte // The raw buffer. + raw_buffer_pos int // The current position of the buffer. + + encoding yaml_encoding_t // The stream encoding. + + // Emitter stuff + + canonical bool // If the output is in the canonical style? + best_indent int // The number of indentation spaces. + best_width int // The preferred width of the output lines. + unicode bool // Allow unescaped non-ASCII characters? + line_break yaml_break_t // The preferred line break. + + state yaml_emitter_state_t // The current emitter state. + states []yaml_emitter_state_t // The stack of states. + + events []yaml_event_t // The event queue. + events_head int // The head of the event queue. + + indents []int // The stack of indentation levels. + + tag_directives []yaml_tag_directive_t // The list of tag directives. + + indent int // The current indentation level. + + flow_level int // The current flow level. + + root_context bool // Is it the document root context? + sequence_context bool // Is it a sequence context? + mapping_context bool // Is it a mapping context? + simple_key_context bool // Is it a simple mapping key context? + + line int // The current line. + column int // The current column. + whitespace bool // If the last character was a whitespace? + indention bool // If the last character was an indentation character (' ', '-', '?', ':')? + open_ended bool // If an explicit document end is required? + + // Anchor analysis. + anchor_data struct { + anchor []byte // The anchor value. + alias bool // Is it an alias? + } + + // Tag analysis. + tag_data struct { + handle []byte // The tag handle. + suffix []byte // The tag suffix. + } + + // Scalar analysis. + scalar_data struct { + value []byte // The scalar value. + multiline bool // Does the scalar contain line breaks? + flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? + block_plain_allowed bool // Can the scalar be expressed in the block plain style? + single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? + block_allowed bool // Can the scalar be expressed in the literal or folded styles? + style yaml_scalar_style_t // The output style. + } + + // Dumper stuff + + opened bool // If the stream was already opened? + closed bool // If the stream was already closed? + + // The information associated with the document nodes. + anchors *struct { + references int // The number of references. + anchor int // The anchor id. + serialized bool // If the node has been emitted? + } + + last_anchor_id int // The last assigned anchor id. + + document *yaml_document_t // The currently emitted document. +} diff --git a/vendor/gopkg.in/yaml.v2/yamlprivateh.go b/vendor/gopkg.in/yaml.v2/yamlprivateh.go new file mode 100644 index 00000000..8110ce3c --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/yamlprivateh.go @@ -0,0 +1,173 @@ +package yaml + +const ( + // The size of the input raw buffer. + input_raw_buffer_size = 512 + + // The size of the input buffer. + // It should be possible to decode the whole raw buffer. + input_buffer_size = input_raw_buffer_size * 3 + + // The size of the output buffer. + output_buffer_size = 128 + + // The size of the output raw buffer. + // It should be possible to encode the whole output buffer. + output_raw_buffer_size = (output_buffer_size*2 + 2) + + // The size of other stacks and queues. + initial_stack_size = 16 + initial_queue_size = 16 + initial_string_size = 16 +) + +// Check if the character at the specified position is an alphabetical +// character, a digit, '_', or '-'. +func is_alpha(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-' +} + +// Check if the character at the specified position is a digit. +func is_digit(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' +} + +// Get the value of a digit. +func as_digit(b []byte, i int) int { + return int(b[i]) - '0' +} + +// Check if the character at the specified position is a hex-digit. +func is_hex(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f' +} + +// Get the value of a hex-digit. +func as_hex(b []byte, i int) int { + bi := b[i] + if bi >= 'A' && bi <= 'F' { + return int(bi) - 'A' + 10 + } + if bi >= 'a' && bi <= 'f' { + return int(bi) - 'a' + 10 + } + return int(bi) - '0' +} + +// Check if the character is ASCII. +func is_ascii(b []byte, i int) bool { + return b[i] <= 0x7F +} + +// Check if the character at the start of the buffer can be printed unescaped. +func is_printable(b []byte, i int) bool { + return ((b[i] == 0x0A) || // . == #x0A + (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E + (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF + (b[i] > 0xC2 && b[i] < 0xED) || + (b[i] == 0xED && b[i+1] < 0xA0) || + (b[i] == 0xEE) || + (b[i] == 0xEF && // #xE000 <= . <= #xFFFD + !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF + !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF)))) +} + +// Check if the character at the specified position is NUL. +func is_z(b []byte, i int) bool { + return b[i] == 0x00 +} + +// Check if the beginning of the buffer is a BOM. +func is_bom(b []byte, i int) bool { + return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF +} + +// Check if the character at the specified position is space. +func is_space(b []byte, i int) bool { + return b[i] == ' ' +} + +// Check if the character at the specified position is tab. +func is_tab(b []byte, i int) bool { + return b[i] == '\t' +} + +// Check if the character at the specified position is blank (space or tab). +func is_blank(b []byte, i int) bool { + //return is_space(b, i) || is_tab(b, i) + return b[i] == ' ' || b[i] == '\t' +} + +// Check if the character at the specified position is a line break. +func is_break(b []byte, i int) bool { + return (b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029) +} + +func is_crlf(b []byte, i int) bool { + return b[i] == '\r' && b[i+1] == '\n' +} + +// Check if the character is a line break or NUL. +func is_breakz(b []byte, i int) bool { + //return is_break(b, i) || is_z(b, i) + return ( // is_break: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + // is_z: + b[i] == 0) +} + +// Check if the character is a line break, space, or NUL. +func is_spacez(b []byte, i int) bool { + //return is_space(b, i) || is_breakz(b, i) + return ( // is_space: + b[i] == ' ' || + // is_breakz: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + b[i] == 0) +} + +// Check if the character is a line break, space, tab, or NUL. +func is_blankz(b []byte, i int) bool { + //return is_blank(b, i) || is_breakz(b, i) + return ( // is_blank: + b[i] == ' ' || b[i] == '\t' || + // is_breakz: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + b[i] == 0) +} + +// Determine the width of the character. +func width(b byte) int { + // Don't replace these by a switch without first + // confirming that it is being inlined. + if b&0x80 == 0x00 { + return 1 + } + if b&0xE0 == 0xC0 { + return 2 + } + if b&0xF0 == 0xE0 { + return 3 + } + if b&0xF8 == 0xF0 { + return 4 + } + return 0 + +} diff --git a/vendor/gopkg.in/yaml.v3/LICENSE b/vendor/gopkg.in/yaml.v3/LICENSE new file mode 100644 index 00000000..2683e4bb --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/LICENSE @@ -0,0 +1,50 @@ + +This project is covered by two different licenses: MIT and Apache. + +#### MIT License #### + +The following files were ported to Go from C files of libyaml, and thus +are still covered by their original MIT license, with the additional +copyright staring in 2011 when the project was ported over: + + apic.go emitterc.go parserc.go readerc.go scannerc.go + writerc.go yamlh.go yamlprivateh.go + +Copyright (c) 2006-2010 Kirill Simonov +Copyright (c) 2006-2011 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +### Apache License ### + +All the remaining project files are covered by the Apache license: + +Copyright (c) 2011-2019 Canonical Ltd + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/gopkg.in/yaml.v3/NOTICE b/vendor/gopkg.in/yaml.v3/NOTICE new file mode 100644 index 00000000..866d74a7 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/NOTICE @@ -0,0 +1,13 @@ +Copyright 2011-2016 Canonical Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/gopkg.in/yaml.v3/README.md b/vendor/gopkg.in/yaml.v3/README.md new file mode 100644 index 00000000..08eb1bab --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/README.md @@ -0,0 +1,150 @@ +# YAML support for the Go language + +Introduction +------------ + +The yaml package enables Go programs to comfortably encode and decode YAML +values. It was developed within [Canonical](https://www.canonical.com) as +part of the [juju](https://juju.ubuntu.com) project, and is based on a +pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) +C library to parse and generate YAML data quickly and reliably. + +Compatibility +------------- + +The yaml package supports most of YAML 1.2, but preserves some behavior +from 1.1 for backwards compatibility. + +Specifically, as of v3 of the yaml package: + + - YAML 1.1 bools (_yes/no, on/off_) are supported as long as they are being + decoded into a typed bool value. Otherwise they behave as a string. Booleans + in YAML 1.2 are _true/false_ only. + - Octals encode and decode as _0777_ per YAML 1.1, rather than _0o777_ + as specified in YAML 1.2, because most parsers still use the old format. + Octals in the _0o777_ format are supported though, so new files work. + - Does not support base-60 floats. These are gone from YAML 1.2, and were + actually never supported by this package as it's clearly a poor choice. + +and offers backwards +compatibility with YAML 1.1 in some cases. +1.2, including support for +anchors, tags, map merging, etc. Multi-document unmarshalling is not yet +implemented, and base-60 floats from YAML 1.1 are purposefully not +supported since they're a poor design and are gone in YAML 1.2. + +Installation and usage +---------------------- + +The import path for the package is *gopkg.in/yaml.v3*. + +To install it, run: + + go get gopkg.in/yaml.v3 + +API documentation +----------------- + +If opened in a browser, the import path itself leads to the API documentation: + + - [https://gopkg.in/yaml.v3](https://gopkg.in/yaml.v3) + +API stability +------------- + +The package API for yaml v3 will remain stable as described in [gopkg.in](https://gopkg.in). + + +License +------- + +The yaml package is licensed under the MIT and Apache License 2.0 licenses. +Please see the LICENSE file for details. + + +Example +------- + +```Go +package main + +import ( + "fmt" + "log" + + "gopkg.in/yaml.v3" +) + +var data = ` +a: Easy! +b: + c: 2 + d: [3, 4] +` + +// Note: struct fields must be public in order for unmarshal to +// correctly populate the data. +type T struct { + A string + B struct { + RenamedC int `yaml:"c"` + D []int `yaml:",flow"` + } +} + +func main() { + t := T{} + + err := yaml.Unmarshal([]byte(data), &t) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- t:\n%v\n\n", t) + + d, err := yaml.Marshal(&t) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- t dump:\n%s\n\n", string(d)) + + m := make(map[interface{}]interface{}) + + err = yaml.Unmarshal([]byte(data), &m) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- m:\n%v\n\n", m) + + d, err = yaml.Marshal(&m) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- m dump:\n%s\n\n", string(d)) +} +``` + +This example will generate the following output: + +``` +--- t: +{Easy! {2 [3 4]}} + +--- t dump: +a: Easy! +b: + c: 2 + d: [3, 4] + + +--- m: +map[a:Easy! b:map[c:2 d:[3 4]]] + +--- m dump: +a: Easy! +b: + c: 2 + d: + - 3 + - 4 +``` + diff --git a/vendor/gopkg.in/yaml.v3/apic.go b/vendor/gopkg.in/yaml.v3/apic.go new file mode 100644 index 00000000..ae7d049f --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/apic.go @@ -0,0 +1,747 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +import ( + "io" +) + +func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { + //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) + + // Check if we can move the queue at the beginning of the buffer. + if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { + if parser.tokens_head != len(parser.tokens) { + copy(parser.tokens, parser.tokens[parser.tokens_head:]) + } + parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head] + parser.tokens_head = 0 + } + parser.tokens = append(parser.tokens, *token) + if pos < 0 { + return + } + copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:]) + parser.tokens[parser.tokens_head+pos] = *token +} + +// Create a new parser object. +func yaml_parser_initialize(parser *yaml_parser_t) bool { + *parser = yaml_parser_t{ + raw_buffer: make([]byte, 0, input_raw_buffer_size), + buffer: make([]byte, 0, input_buffer_size), + } + return true +} + +// Destroy a parser object. +func yaml_parser_delete(parser *yaml_parser_t) { + *parser = yaml_parser_t{} +} + +// String read handler. +func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { + if parser.input_pos == len(parser.input) { + return 0, io.EOF + } + n = copy(buffer, parser.input[parser.input_pos:]) + parser.input_pos += n + return n, nil +} + +// Reader read handler. +func yaml_reader_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { + return parser.input_reader.Read(buffer) +} + +// Set a string input. +func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { + if parser.read_handler != nil { + panic("must set the input source only once") + } + parser.read_handler = yaml_string_read_handler + parser.input = input + parser.input_pos = 0 +} + +// Set a file input. +func yaml_parser_set_input_reader(parser *yaml_parser_t, r io.Reader) { + if parser.read_handler != nil { + panic("must set the input source only once") + } + parser.read_handler = yaml_reader_read_handler + parser.input_reader = r +} + +// Set the source encoding. +func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { + if parser.encoding != yaml_ANY_ENCODING { + panic("must set the encoding only once") + } + parser.encoding = encoding +} + +// Create a new emitter object. +func yaml_emitter_initialize(emitter *yaml_emitter_t) { + *emitter = yaml_emitter_t{ + buffer: make([]byte, output_buffer_size), + raw_buffer: make([]byte, 0, output_raw_buffer_size), + states: make([]yaml_emitter_state_t, 0, initial_stack_size), + events: make([]yaml_event_t, 0, initial_queue_size), + best_width: -1, + } +} + +// Destroy an emitter object. +func yaml_emitter_delete(emitter *yaml_emitter_t) { + *emitter = yaml_emitter_t{} +} + +// String write handler. +func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error { + *emitter.output_buffer = append(*emitter.output_buffer, buffer...) + return nil +} + +// yaml_writer_write_handler uses emitter.output_writer to write the +// emitted text. +func yaml_writer_write_handler(emitter *yaml_emitter_t, buffer []byte) error { + _, err := emitter.output_writer.Write(buffer) + return err +} + +// Set a string output. +func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) { + if emitter.write_handler != nil { + panic("must set the output target only once") + } + emitter.write_handler = yaml_string_write_handler + emitter.output_buffer = output_buffer +} + +// Set a file output. +func yaml_emitter_set_output_writer(emitter *yaml_emitter_t, w io.Writer) { + if emitter.write_handler != nil { + panic("must set the output target only once") + } + emitter.write_handler = yaml_writer_write_handler + emitter.output_writer = w +} + +// Set the output encoding. +func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) { + if emitter.encoding != yaml_ANY_ENCODING { + panic("must set the output encoding only once") + } + emitter.encoding = encoding +} + +// Set the canonical output style. +func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { + emitter.canonical = canonical +} + +// Set the indentation increment. +func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { + if indent < 2 || indent > 9 { + indent = 2 + } + emitter.best_indent = indent +} + +// Set the preferred line width. +func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) { + if width < 0 { + width = -1 + } + emitter.best_width = width +} + +// Set if unescaped non-ASCII characters are allowed. +func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) { + emitter.unicode = unicode +} + +// Set the preferred line break character. +func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) { + emitter.line_break = line_break +} + +///* +// * Destroy a token object. +// */ +// +//YAML_DECLARE(void) +//yaml_token_delete(yaml_token_t *token) +//{ +// assert(token); // Non-NULL token object expected. +// +// switch (token.type) +// { +// case YAML_TAG_DIRECTIVE_TOKEN: +// yaml_free(token.data.tag_directive.handle); +// yaml_free(token.data.tag_directive.prefix); +// break; +// +// case YAML_ALIAS_TOKEN: +// yaml_free(token.data.alias.value); +// break; +// +// case YAML_ANCHOR_TOKEN: +// yaml_free(token.data.anchor.value); +// break; +// +// case YAML_TAG_TOKEN: +// yaml_free(token.data.tag.handle); +// yaml_free(token.data.tag.suffix); +// break; +// +// case YAML_SCALAR_TOKEN: +// yaml_free(token.data.scalar.value); +// break; +// +// default: +// break; +// } +// +// memset(token, 0, sizeof(yaml_token_t)); +//} +// +///* +// * Check if a string is a valid UTF-8 sequence. +// * +// * Check 'reader.c' for more details on UTF-8 encoding. +// */ +// +//static int +//yaml_check_utf8(yaml_char_t *start, size_t length) +//{ +// yaml_char_t *end = start+length; +// yaml_char_t *pointer = start; +// +// while (pointer < end) { +// unsigned char octet; +// unsigned int width; +// unsigned int value; +// size_t k; +// +// octet = pointer[0]; +// width = (octet & 0x80) == 0x00 ? 1 : +// (octet & 0xE0) == 0xC0 ? 2 : +// (octet & 0xF0) == 0xE0 ? 3 : +// (octet & 0xF8) == 0xF0 ? 4 : 0; +// value = (octet & 0x80) == 0x00 ? octet & 0x7F : +// (octet & 0xE0) == 0xC0 ? octet & 0x1F : +// (octet & 0xF0) == 0xE0 ? octet & 0x0F : +// (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; +// if (!width) return 0; +// if (pointer+width > end) return 0; +// for (k = 1; k < width; k ++) { +// octet = pointer[k]; +// if ((octet & 0xC0) != 0x80) return 0; +// value = (value << 6) + (octet & 0x3F); +// } +// if (!((width == 1) || +// (width == 2 && value >= 0x80) || +// (width == 3 && value >= 0x800) || +// (width == 4 && value >= 0x10000))) return 0; +// +// pointer += width; +// } +// +// return 1; +//} +// + +// Create STREAM-START. +func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) { + *event = yaml_event_t{ + typ: yaml_STREAM_START_EVENT, + encoding: encoding, + } +} + +// Create STREAM-END. +func yaml_stream_end_event_initialize(event *yaml_event_t) { + *event = yaml_event_t{ + typ: yaml_STREAM_END_EVENT, + } +} + +// Create DOCUMENT-START. +func yaml_document_start_event_initialize( + event *yaml_event_t, + version_directive *yaml_version_directive_t, + tag_directives []yaml_tag_directive_t, + implicit bool, +) { + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + version_directive: version_directive, + tag_directives: tag_directives, + implicit: implicit, + } +} + +// Create DOCUMENT-END. +func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) { + *event = yaml_event_t{ + typ: yaml_DOCUMENT_END_EVENT, + implicit: implicit, + } +} + +// Create ALIAS. +func yaml_alias_event_initialize(event *yaml_event_t, anchor []byte) bool { + *event = yaml_event_t{ + typ: yaml_ALIAS_EVENT, + anchor: anchor, + } + return true +} + +// Create SCALAR. +func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool { + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + anchor: anchor, + tag: tag, + value: value, + implicit: plain_implicit, + quoted_implicit: quoted_implicit, + style: yaml_style_t(style), + } + return true +} + +// Create SEQUENCE-START. +func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool { + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(style), + } + return true +} + +// Create SEQUENCE-END. +func yaml_sequence_end_event_initialize(event *yaml_event_t) bool { + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + } + return true +} + +// Create MAPPING-START. +func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) { + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(style), + } +} + +// Create MAPPING-END. +func yaml_mapping_end_event_initialize(event *yaml_event_t) { + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + } +} + +// Destroy an event object. +func yaml_event_delete(event *yaml_event_t) { + *event = yaml_event_t{} +} + +///* +// * Create a document object. +// */ +// +//YAML_DECLARE(int) +//yaml_document_initialize(document *yaml_document_t, +// version_directive *yaml_version_directive_t, +// tag_directives_start *yaml_tag_directive_t, +// tag_directives_end *yaml_tag_directive_t, +// start_implicit int, end_implicit int) +//{ +// struct { +// error yaml_error_type_t +// } context +// struct { +// start *yaml_node_t +// end *yaml_node_t +// top *yaml_node_t +// } nodes = { NULL, NULL, NULL } +// version_directive_copy *yaml_version_directive_t = NULL +// struct { +// start *yaml_tag_directive_t +// end *yaml_tag_directive_t +// top *yaml_tag_directive_t +// } tag_directives_copy = { NULL, NULL, NULL } +// value yaml_tag_directive_t = { NULL, NULL } +// mark yaml_mark_t = { 0, 0, 0 } +// +// assert(document) // Non-NULL document object is expected. +// assert((tag_directives_start && tag_directives_end) || +// (tag_directives_start == tag_directives_end)) +// // Valid tag directives are expected. +// +// if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error +// +// if (version_directive) { +// version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t)) +// if (!version_directive_copy) goto error +// version_directive_copy.major = version_directive.major +// version_directive_copy.minor = version_directive.minor +// } +// +// if (tag_directives_start != tag_directives_end) { +// tag_directive *yaml_tag_directive_t +// if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE)) +// goto error +// for (tag_directive = tag_directives_start +// tag_directive != tag_directives_end; tag_directive ++) { +// assert(tag_directive.handle) +// assert(tag_directive.prefix) +// if (!yaml_check_utf8(tag_directive.handle, +// strlen((char *)tag_directive.handle))) +// goto error +// if (!yaml_check_utf8(tag_directive.prefix, +// strlen((char *)tag_directive.prefix))) +// goto error +// value.handle = yaml_strdup(tag_directive.handle) +// value.prefix = yaml_strdup(tag_directive.prefix) +// if (!value.handle || !value.prefix) goto error +// if (!PUSH(&context, tag_directives_copy, value)) +// goto error +// value.handle = NULL +// value.prefix = NULL +// } +// } +// +// DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy, +// tag_directives_copy.start, tag_directives_copy.top, +// start_implicit, end_implicit, mark, mark) +// +// return 1 +// +//error: +// STACK_DEL(&context, nodes) +// yaml_free(version_directive_copy) +// while (!STACK_EMPTY(&context, tag_directives_copy)) { +// value yaml_tag_directive_t = POP(&context, tag_directives_copy) +// yaml_free(value.handle) +// yaml_free(value.prefix) +// } +// STACK_DEL(&context, tag_directives_copy) +// yaml_free(value.handle) +// yaml_free(value.prefix) +// +// return 0 +//} +// +///* +// * Destroy a document object. +// */ +// +//YAML_DECLARE(void) +//yaml_document_delete(document *yaml_document_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// tag_directive *yaml_tag_directive_t +// +// context.error = YAML_NO_ERROR // Eliminate a compiler warning. +// +// assert(document) // Non-NULL document object is expected. +// +// while (!STACK_EMPTY(&context, document.nodes)) { +// node yaml_node_t = POP(&context, document.nodes) +// yaml_free(node.tag) +// switch (node.type) { +// case YAML_SCALAR_NODE: +// yaml_free(node.data.scalar.value) +// break +// case YAML_SEQUENCE_NODE: +// STACK_DEL(&context, node.data.sequence.items) +// break +// case YAML_MAPPING_NODE: +// STACK_DEL(&context, node.data.mapping.pairs) +// break +// default: +// assert(0) // Should not happen. +// } +// } +// STACK_DEL(&context, document.nodes) +// +// yaml_free(document.version_directive) +// for (tag_directive = document.tag_directives.start +// tag_directive != document.tag_directives.end +// tag_directive++) { +// yaml_free(tag_directive.handle) +// yaml_free(tag_directive.prefix) +// } +// yaml_free(document.tag_directives.start) +// +// memset(document, 0, sizeof(yaml_document_t)) +//} +// +///** +// * Get a document node. +// */ +// +//YAML_DECLARE(yaml_node_t *) +//yaml_document_get_node(document *yaml_document_t, index int) +//{ +// assert(document) // Non-NULL document object is expected. +// +// if (index > 0 && document.nodes.start + index <= document.nodes.top) { +// return document.nodes.start + index - 1 +// } +// return NULL +//} +// +///** +// * Get the root object. +// */ +// +//YAML_DECLARE(yaml_node_t *) +//yaml_document_get_root_node(document *yaml_document_t) +//{ +// assert(document) // Non-NULL document object is expected. +// +// if (document.nodes.top != document.nodes.start) { +// return document.nodes.start +// } +// return NULL +//} +// +///* +// * Add a scalar node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_scalar(document *yaml_document_t, +// tag *yaml_char_t, value *yaml_char_t, length int, +// style yaml_scalar_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// value_copy *yaml_char_t = NULL +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// assert(value) // Non-NULL value is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (length < 0) { +// length = strlen((char *)value) +// } +// +// if (!yaml_check_utf8(value, length)) goto error +// value_copy = yaml_malloc(length+1) +// if (!value_copy) goto error +// memcpy(value_copy, value, length) +// value_copy[length] = '\0' +// +// SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// yaml_free(tag_copy) +// yaml_free(value_copy) +// +// return 0 +//} +// +///* +// * Add a sequence node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_sequence(document *yaml_document_t, +// tag *yaml_char_t, style yaml_sequence_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// struct { +// start *yaml_node_item_t +// end *yaml_node_item_t +// top *yaml_node_item_t +// } items = { NULL, NULL, NULL } +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error +// +// SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end, +// style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// STACK_DEL(&context, items) +// yaml_free(tag_copy) +// +// return 0 +//} +// +///* +// * Add a mapping node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_mapping(document *yaml_document_t, +// tag *yaml_char_t, style yaml_mapping_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// struct { +// start *yaml_node_pair_t +// end *yaml_node_pair_t +// top *yaml_node_pair_t +// } pairs = { NULL, NULL, NULL } +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error +// +// MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end, +// style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// STACK_DEL(&context, pairs) +// yaml_free(tag_copy) +// +// return 0 +//} +// +///* +// * Append an item to a sequence node. +// */ +// +//YAML_DECLARE(int) +//yaml_document_append_sequence_item(document *yaml_document_t, +// sequence int, item int) +//{ +// struct { +// error yaml_error_type_t +// } context +// +// assert(document) // Non-NULL document is required. +// assert(sequence > 0 +// && document.nodes.start + sequence <= document.nodes.top) +// // Valid sequence id is required. +// assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE) +// // A sequence node is required. +// assert(item > 0 && document.nodes.start + item <= document.nodes.top) +// // Valid item id is required. +// +// if (!PUSH(&context, +// document.nodes.start[sequence-1].data.sequence.items, item)) +// return 0 +// +// return 1 +//} +// +///* +// * Append a pair of a key and a value to a mapping node. +// */ +// +//YAML_DECLARE(int) +//yaml_document_append_mapping_pair(document *yaml_document_t, +// mapping int, key int, value int) +//{ +// struct { +// error yaml_error_type_t +// } context +// +// pair yaml_node_pair_t +// +// assert(document) // Non-NULL document is required. +// assert(mapping > 0 +// && document.nodes.start + mapping <= document.nodes.top) +// // Valid mapping id is required. +// assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE) +// // A mapping node is required. +// assert(key > 0 && document.nodes.start + key <= document.nodes.top) +// // Valid key id is required. +// assert(value > 0 && document.nodes.start + value <= document.nodes.top) +// // Valid value id is required. +// +// pair.key = key +// pair.value = value +// +// if (!PUSH(&context, +// document.nodes.start[mapping-1].data.mapping.pairs, pair)) +// return 0 +// +// return 1 +//} +// +// diff --git a/vendor/gopkg.in/yaml.v3/decode.go b/vendor/gopkg.in/yaml.v3/decode.go new file mode 100644 index 00000000..0173b698 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/decode.go @@ -0,0 +1,1000 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yaml + +import ( + "encoding" + "encoding/base64" + "fmt" + "io" + "math" + "reflect" + "strconv" + "time" +) + +// ---------------------------------------------------------------------------- +// Parser, produces a node tree out of a libyaml event stream. + +type parser struct { + parser yaml_parser_t + event yaml_event_t + doc *Node + anchors map[string]*Node + doneInit bool + textless bool +} + +func newParser(b []byte) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + if len(b) == 0 { + b = []byte{'\n'} + } + yaml_parser_set_input_string(&p.parser, b) + return &p +} + +func newParserFromReader(r io.Reader) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + yaml_parser_set_input_reader(&p.parser, r) + return &p +} + +func (p *parser) init() { + if p.doneInit { + return + } + p.anchors = make(map[string]*Node) + p.expect(yaml_STREAM_START_EVENT) + p.doneInit = true +} + +func (p *parser) destroy() { + if p.event.typ != yaml_NO_EVENT { + yaml_event_delete(&p.event) + } + yaml_parser_delete(&p.parser) +} + +// expect consumes an event from the event stream and +// checks that it's of the expected type. +func (p *parser) expect(e yaml_event_type_t) { + if p.event.typ == yaml_NO_EVENT { + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + } + if p.event.typ == yaml_STREAM_END_EVENT { + failf("attempted to go past the end of stream; corrupted value?") + } + if p.event.typ != e { + p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ) + p.fail() + } + yaml_event_delete(&p.event) + p.event.typ = yaml_NO_EVENT +} + +// peek peeks at the next event in the event stream, +// puts the results into p.event and returns the event type. +func (p *parser) peek() yaml_event_type_t { + if p.event.typ != yaml_NO_EVENT { + return p.event.typ + } + // It's curious choice from the underlying API to generally return a + // positive result on success, but on this case return true in an error + // scenario. This was the source of bugs in the past (issue #666). + if !yaml_parser_parse(&p.parser, &p.event) || p.parser.error != yaml_NO_ERROR { + p.fail() + } + return p.event.typ +} + +func (p *parser) fail() { + var where string + var line int + if p.parser.context_mark.line != 0 { + line = p.parser.context_mark.line + // Scanner errors don't iterate line before returning error + if p.parser.error == yaml_SCANNER_ERROR { + line++ + } + } else if p.parser.problem_mark.line != 0 { + line = p.parser.problem_mark.line + // Scanner errors don't iterate line before returning error + if p.parser.error == yaml_SCANNER_ERROR { + line++ + } + } + if line != 0 { + where = "line " + strconv.Itoa(line) + ": " + } + var msg string + if len(p.parser.problem) > 0 { + msg = p.parser.problem + } else { + msg = "unknown problem parsing YAML content" + } + failf("%s%s", where, msg) +} + +func (p *parser) anchor(n *Node, anchor []byte) { + if anchor != nil { + n.Anchor = string(anchor) + p.anchors[n.Anchor] = n + } +} + +func (p *parser) parse() *Node { + p.init() + switch p.peek() { + case yaml_SCALAR_EVENT: + return p.scalar() + case yaml_ALIAS_EVENT: + return p.alias() + case yaml_MAPPING_START_EVENT: + return p.mapping() + case yaml_SEQUENCE_START_EVENT: + return p.sequence() + case yaml_DOCUMENT_START_EVENT: + return p.document() + case yaml_STREAM_END_EVENT: + // Happens when attempting to decode an empty buffer. + return nil + case yaml_TAIL_COMMENT_EVENT: + panic("internal error: unexpected tail comment event (please report)") + default: + panic("internal error: attempted to parse unknown event (please report): " + p.event.typ.String()) + } +} + +func (p *parser) node(kind Kind, defaultTag, tag, value string) *Node { + var style Style + if tag != "" && tag != "!" { + tag = shortTag(tag) + style = TaggedStyle + } else if defaultTag != "" { + tag = defaultTag + } else if kind == ScalarNode { + tag, _ = resolve("", value) + } + n := &Node{ + Kind: kind, + Tag: tag, + Value: value, + Style: style, + } + if !p.textless { + n.Line = p.event.start_mark.line + 1 + n.Column = p.event.start_mark.column + 1 + n.HeadComment = string(p.event.head_comment) + n.LineComment = string(p.event.line_comment) + n.FootComment = string(p.event.foot_comment) + } + return n +} + +func (p *parser) parseChild(parent *Node) *Node { + child := p.parse() + parent.Content = append(parent.Content, child) + return child +} + +func (p *parser) document() *Node { + n := p.node(DocumentNode, "", "", "") + p.doc = n + p.expect(yaml_DOCUMENT_START_EVENT) + p.parseChild(n) + if p.peek() == yaml_DOCUMENT_END_EVENT { + n.FootComment = string(p.event.foot_comment) + } + p.expect(yaml_DOCUMENT_END_EVENT) + return n +} + +func (p *parser) alias() *Node { + n := p.node(AliasNode, "", "", string(p.event.anchor)) + n.Alias = p.anchors[n.Value] + if n.Alias == nil { + failf("unknown anchor '%s' referenced", n.Value) + } + p.expect(yaml_ALIAS_EVENT) + return n +} + +func (p *parser) scalar() *Node { + var parsedStyle = p.event.scalar_style() + var nodeStyle Style + switch { + case parsedStyle&yaml_DOUBLE_QUOTED_SCALAR_STYLE != 0: + nodeStyle = DoubleQuotedStyle + case parsedStyle&yaml_SINGLE_QUOTED_SCALAR_STYLE != 0: + nodeStyle = SingleQuotedStyle + case parsedStyle&yaml_LITERAL_SCALAR_STYLE != 0: + nodeStyle = LiteralStyle + case parsedStyle&yaml_FOLDED_SCALAR_STYLE != 0: + nodeStyle = FoldedStyle + } + var nodeValue = string(p.event.value) + var nodeTag = string(p.event.tag) + var defaultTag string + if nodeStyle == 0 { + if nodeValue == "<<" { + defaultTag = mergeTag + } + } else { + defaultTag = strTag + } + n := p.node(ScalarNode, defaultTag, nodeTag, nodeValue) + n.Style |= nodeStyle + p.anchor(n, p.event.anchor) + p.expect(yaml_SCALAR_EVENT) + return n +} + +func (p *parser) sequence() *Node { + n := p.node(SequenceNode, seqTag, string(p.event.tag), "") + if p.event.sequence_style()&yaml_FLOW_SEQUENCE_STYLE != 0 { + n.Style |= FlowStyle + } + p.anchor(n, p.event.anchor) + p.expect(yaml_SEQUENCE_START_EVENT) + for p.peek() != yaml_SEQUENCE_END_EVENT { + p.parseChild(n) + } + n.LineComment = string(p.event.line_comment) + n.FootComment = string(p.event.foot_comment) + p.expect(yaml_SEQUENCE_END_EVENT) + return n +} + +func (p *parser) mapping() *Node { + n := p.node(MappingNode, mapTag, string(p.event.tag), "") + block := true + if p.event.mapping_style()&yaml_FLOW_MAPPING_STYLE != 0 { + block = false + n.Style |= FlowStyle + } + p.anchor(n, p.event.anchor) + p.expect(yaml_MAPPING_START_EVENT) + for p.peek() != yaml_MAPPING_END_EVENT { + k := p.parseChild(n) + if block && k.FootComment != "" { + // Must be a foot comment for the prior value when being dedented. + if len(n.Content) > 2 { + n.Content[len(n.Content)-3].FootComment = k.FootComment + k.FootComment = "" + } + } + v := p.parseChild(n) + if k.FootComment == "" && v.FootComment != "" { + k.FootComment = v.FootComment + v.FootComment = "" + } + if p.peek() == yaml_TAIL_COMMENT_EVENT { + if k.FootComment == "" { + k.FootComment = string(p.event.foot_comment) + } + p.expect(yaml_TAIL_COMMENT_EVENT) + } + } + n.LineComment = string(p.event.line_comment) + n.FootComment = string(p.event.foot_comment) + if n.Style&FlowStyle == 0 && n.FootComment != "" && len(n.Content) > 1 { + n.Content[len(n.Content)-2].FootComment = n.FootComment + n.FootComment = "" + } + p.expect(yaml_MAPPING_END_EVENT) + return n +} + +// ---------------------------------------------------------------------------- +// Decoder, unmarshals a node into a provided value. + +type decoder struct { + doc *Node + aliases map[*Node]bool + terrors []string + + stringMapType reflect.Type + generalMapType reflect.Type + + knownFields bool + uniqueKeys bool + decodeCount int + aliasCount int + aliasDepth int + + mergedFields map[interface{}]bool +} + +var ( + nodeType = reflect.TypeOf(Node{}) + durationType = reflect.TypeOf(time.Duration(0)) + stringMapType = reflect.TypeOf(map[string]interface{}{}) + generalMapType = reflect.TypeOf(map[interface{}]interface{}{}) + ifaceType = generalMapType.Elem() + timeType = reflect.TypeOf(time.Time{}) + ptrTimeType = reflect.TypeOf(&time.Time{}) +) + +func newDecoder() *decoder { + d := &decoder{ + stringMapType: stringMapType, + generalMapType: generalMapType, + uniqueKeys: true, + } + d.aliases = make(map[*Node]bool) + return d +} + +func (d *decoder) terror(n *Node, tag string, out reflect.Value) { + if n.Tag != "" { + tag = n.Tag + } + value := n.Value + if tag != seqTag && tag != mapTag { + if len(value) > 10 { + value = " `" + value[:7] + "...`" + } else { + value = " `" + value + "`" + } + } + d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.Line, shortTag(tag), value, out.Type())) +} + +func (d *decoder) callUnmarshaler(n *Node, u Unmarshaler) (good bool) { + err := u.UnmarshalYAML(n) + if e, ok := err.(*TypeError); ok { + d.terrors = append(d.terrors, e.Errors...) + return false + } + if err != nil { + fail(err) + } + return true +} + +func (d *decoder) callObsoleteUnmarshaler(n *Node, u obsoleteUnmarshaler) (good bool) { + terrlen := len(d.terrors) + err := u.UnmarshalYAML(func(v interface{}) (err error) { + defer handleErr(&err) + d.unmarshal(n, reflect.ValueOf(v)) + if len(d.terrors) > terrlen { + issues := d.terrors[terrlen:] + d.terrors = d.terrors[:terrlen] + return &TypeError{issues} + } + return nil + }) + if e, ok := err.(*TypeError); ok { + d.terrors = append(d.terrors, e.Errors...) + return false + } + if err != nil { + fail(err) + } + return true +} + +// d.prepare initializes and dereferences pointers and calls UnmarshalYAML +// if a value is found to implement it. +// It returns the initialized and dereferenced out value, whether +// unmarshalling was already done by UnmarshalYAML, and if so whether +// its types unmarshalled appropriately. +// +// If n holds a null value, prepare returns before doing anything. +func (d *decoder) prepare(n *Node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { + if n.ShortTag() == nullTag { + return out, false, false + } + again := true + for again { + again = false + if out.Kind() == reflect.Ptr { + if out.IsNil() { + out.Set(reflect.New(out.Type().Elem())) + } + out = out.Elem() + again = true + } + if out.CanAddr() { + outi := out.Addr().Interface() + if u, ok := outi.(Unmarshaler); ok { + good = d.callUnmarshaler(n, u) + return out, true, good + } + if u, ok := outi.(obsoleteUnmarshaler); ok { + good = d.callObsoleteUnmarshaler(n, u) + return out, true, good + } + } + } + return out, false, false +} + +func (d *decoder) fieldByIndex(n *Node, v reflect.Value, index []int) (field reflect.Value) { + if n.ShortTag() == nullTag { + return reflect.Value{} + } + for _, num := range index { + for { + if v.Kind() == reflect.Ptr { + if v.IsNil() { + v.Set(reflect.New(v.Type().Elem())) + } + v = v.Elem() + continue + } + break + } + v = v.Field(num) + } + return v +} + +const ( + // 400,000 decode operations is ~500kb of dense object declarations, or + // ~5kb of dense object declarations with 10000% alias expansion + alias_ratio_range_low = 400000 + + // 4,000,000 decode operations is ~5MB of dense object declarations, or + // ~4.5MB of dense object declarations with 10% alias expansion + alias_ratio_range_high = 4000000 + + // alias_ratio_range is the range over which we scale allowed alias ratios + alias_ratio_range = float64(alias_ratio_range_high - alias_ratio_range_low) +) + +func allowedAliasRatio(decodeCount int) float64 { + switch { + case decodeCount <= alias_ratio_range_low: + // allow 99% to come from alias expansion for small-to-medium documents + return 0.99 + case decodeCount >= alias_ratio_range_high: + // allow 10% to come from alias expansion for very large documents + return 0.10 + default: + // scale smoothly from 99% down to 10% over the range. + // this maps to 396,000 - 400,000 allowed alias-driven decodes over the range. + // 400,000 decode operations is ~100MB of allocations in worst-case scenarios (single-item maps). + return 0.99 - 0.89*(float64(decodeCount-alias_ratio_range_low)/alias_ratio_range) + } +} + +func (d *decoder) unmarshal(n *Node, out reflect.Value) (good bool) { + d.decodeCount++ + if d.aliasDepth > 0 { + d.aliasCount++ + } + if d.aliasCount > 100 && d.decodeCount > 1000 && float64(d.aliasCount)/float64(d.decodeCount) > allowedAliasRatio(d.decodeCount) { + failf("document contains excessive aliasing") + } + if out.Type() == nodeType { + out.Set(reflect.ValueOf(n).Elem()) + return true + } + switch n.Kind { + case DocumentNode: + return d.document(n, out) + case AliasNode: + return d.alias(n, out) + } + out, unmarshaled, good := d.prepare(n, out) + if unmarshaled { + return good + } + switch n.Kind { + case ScalarNode: + good = d.scalar(n, out) + case MappingNode: + good = d.mapping(n, out) + case SequenceNode: + good = d.sequence(n, out) + case 0: + if n.IsZero() { + return d.null(out) + } + fallthrough + default: + failf("cannot decode node with unknown kind %d", n.Kind) + } + return good +} + +func (d *decoder) document(n *Node, out reflect.Value) (good bool) { + if len(n.Content) == 1 { + d.doc = n + d.unmarshal(n.Content[0], out) + return true + } + return false +} + +func (d *decoder) alias(n *Node, out reflect.Value) (good bool) { + if d.aliases[n] { + // TODO this could actually be allowed in some circumstances. + failf("anchor '%s' value contains itself", n.Value) + } + d.aliases[n] = true + d.aliasDepth++ + good = d.unmarshal(n.Alias, out) + d.aliasDepth-- + delete(d.aliases, n) + return good +} + +var zeroValue reflect.Value + +func resetMap(out reflect.Value) { + for _, k := range out.MapKeys() { + out.SetMapIndex(k, zeroValue) + } +} + +func (d *decoder) null(out reflect.Value) bool { + if out.CanAddr() { + switch out.Kind() { + case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: + out.Set(reflect.Zero(out.Type())) + return true + } + } + return false +} + +func (d *decoder) scalar(n *Node, out reflect.Value) bool { + var tag string + var resolved interface{} + if n.indicatedString() { + tag = strTag + resolved = n.Value + } else { + tag, resolved = resolve(n.Tag, n.Value) + if tag == binaryTag { + data, err := base64.StdEncoding.DecodeString(resolved.(string)) + if err != nil { + failf("!!binary value contains invalid base64 data") + } + resolved = string(data) + } + } + if resolved == nil { + return d.null(out) + } + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + // We've resolved to exactly the type we want, so use that. + out.Set(resolvedv) + return true + } + // Perhaps we can use the value as a TextUnmarshaler to + // set its value. + if out.CanAddr() { + u, ok := out.Addr().Interface().(encoding.TextUnmarshaler) + if ok { + var text []byte + if tag == binaryTag { + text = []byte(resolved.(string)) + } else { + // We let any value be unmarshaled into TextUnmarshaler. + // That might be more lax than we'd like, but the + // TextUnmarshaler itself should bowl out any dubious values. + text = []byte(n.Value) + } + err := u.UnmarshalText(text) + if err != nil { + fail(err) + } + return true + } + } + switch out.Kind() { + case reflect.String: + if tag == binaryTag { + out.SetString(resolved.(string)) + return true + } + out.SetString(n.Value) + return true + case reflect.Interface: + out.Set(reflect.ValueOf(resolved)) + return true + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + // This used to work in v2, but it's very unfriendly. + isDuration := out.Type() == durationType + + switch resolved := resolved.(type) { + case int: + if !isDuration && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case int64: + if !isDuration && !out.OverflowInt(resolved) { + out.SetInt(resolved) + return true + } + case uint64: + if !isDuration && resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case float64: + if !isDuration && resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case string: + if out.Type() == durationType { + d, err := time.ParseDuration(resolved) + if err == nil { + out.SetInt(int64(d)) + return true + } + } + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + switch resolved := resolved.(type) { + case int: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case int64: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case uint64: + if !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case float64: + if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + } + case reflect.Bool: + switch resolved := resolved.(type) { + case bool: + out.SetBool(resolved) + return true + case string: + // This offers some compatibility with the 1.1 spec (https://yaml.org/type/bool.html). + // It only works if explicitly attempting to unmarshal into a typed bool value. + switch resolved { + case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON": + out.SetBool(true) + return true + case "n", "N", "no", "No", "NO", "off", "Off", "OFF": + out.SetBool(false) + return true + } + } + case reflect.Float32, reflect.Float64: + switch resolved := resolved.(type) { + case int: + out.SetFloat(float64(resolved)) + return true + case int64: + out.SetFloat(float64(resolved)) + return true + case uint64: + out.SetFloat(float64(resolved)) + return true + case float64: + out.SetFloat(resolved) + return true + } + case reflect.Struct: + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + out.Set(resolvedv) + return true + } + case reflect.Ptr: + panic("yaml internal error: please report the issue") + } + d.terror(n, tag, out) + return false +} + +func settableValueOf(i interface{}) reflect.Value { + v := reflect.ValueOf(i) + sv := reflect.New(v.Type()).Elem() + sv.Set(v) + return sv +} + +func (d *decoder) sequence(n *Node, out reflect.Value) (good bool) { + l := len(n.Content) + + var iface reflect.Value + switch out.Kind() { + case reflect.Slice: + out.Set(reflect.MakeSlice(out.Type(), l, l)) + case reflect.Array: + if l != out.Len() { + failf("invalid array: want %d elements but got %d", out.Len(), l) + } + case reflect.Interface: + // No type hints. Will have to use a generic sequence. + iface = out + out = settableValueOf(make([]interface{}, l)) + default: + d.terror(n, seqTag, out) + return false + } + et := out.Type().Elem() + + j := 0 + for i := 0; i < l; i++ { + e := reflect.New(et).Elem() + if ok := d.unmarshal(n.Content[i], e); ok { + out.Index(j).Set(e) + j++ + } + } + if out.Kind() != reflect.Array { + out.Set(out.Slice(0, j)) + } + if iface.IsValid() { + iface.Set(out) + } + return true +} + +func (d *decoder) mapping(n *Node, out reflect.Value) (good bool) { + l := len(n.Content) + if d.uniqueKeys { + nerrs := len(d.terrors) + for i := 0; i < l; i += 2 { + ni := n.Content[i] + for j := i + 2; j < l; j += 2 { + nj := n.Content[j] + if ni.Kind == nj.Kind && ni.Value == nj.Value { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: mapping key %#v already defined at line %d", nj.Line, nj.Value, ni.Line)) + } + } + } + if len(d.terrors) > nerrs { + return false + } + } + switch out.Kind() { + case reflect.Struct: + return d.mappingStruct(n, out) + case reflect.Map: + // okay + case reflect.Interface: + iface := out + if isStringMap(n) { + out = reflect.MakeMap(d.stringMapType) + } else { + out = reflect.MakeMap(d.generalMapType) + } + iface.Set(out) + default: + d.terror(n, mapTag, out) + return false + } + + outt := out.Type() + kt := outt.Key() + et := outt.Elem() + + stringMapType := d.stringMapType + generalMapType := d.generalMapType + if outt.Elem() == ifaceType { + if outt.Key().Kind() == reflect.String { + d.stringMapType = outt + } else if outt.Key() == ifaceType { + d.generalMapType = outt + } + } + + mergedFields := d.mergedFields + d.mergedFields = nil + + var mergeNode *Node + + mapIsNew := false + if out.IsNil() { + out.Set(reflect.MakeMap(outt)) + mapIsNew = true + } + for i := 0; i < l; i += 2 { + if isMerge(n.Content[i]) { + mergeNode = n.Content[i+1] + continue + } + k := reflect.New(kt).Elem() + if d.unmarshal(n.Content[i], k) { + if mergedFields != nil { + ki := k.Interface() + if mergedFields[ki] { + continue + } + mergedFields[ki] = true + } + kkind := k.Kind() + if kkind == reflect.Interface { + kkind = k.Elem().Kind() + } + if kkind == reflect.Map || kkind == reflect.Slice { + failf("invalid map key: %#v", k.Interface()) + } + e := reflect.New(et).Elem() + if d.unmarshal(n.Content[i+1], e) || n.Content[i+1].ShortTag() == nullTag && (mapIsNew || !out.MapIndex(k).IsValid()) { + out.SetMapIndex(k, e) + } + } + } + + d.mergedFields = mergedFields + if mergeNode != nil { + d.merge(n, mergeNode, out) + } + + d.stringMapType = stringMapType + d.generalMapType = generalMapType + return true +} + +func isStringMap(n *Node) bool { + if n.Kind != MappingNode { + return false + } + l := len(n.Content) + for i := 0; i < l; i += 2 { + shortTag := n.Content[i].ShortTag() + if shortTag != strTag && shortTag != mergeTag { + return false + } + } + return true +} + +func (d *decoder) mappingStruct(n *Node, out reflect.Value) (good bool) { + sinfo, err := getStructInfo(out.Type()) + if err != nil { + panic(err) + } + + var inlineMap reflect.Value + var elemType reflect.Type + if sinfo.InlineMap != -1 { + inlineMap = out.Field(sinfo.InlineMap) + elemType = inlineMap.Type().Elem() + } + + for _, index := range sinfo.InlineUnmarshalers { + field := d.fieldByIndex(n, out, index) + d.prepare(n, field) + } + + mergedFields := d.mergedFields + d.mergedFields = nil + var mergeNode *Node + var doneFields []bool + if d.uniqueKeys { + doneFields = make([]bool, len(sinfo.FieldsList)) + } + name := settableValueOf("") + l := len(n.Content) + for i := 0; i < l; i += 2 { + ni := n.Content[i] + if isMerge(ni) { + mergeNode = n.Content[i+1] + continue + } + if !d.unmarshal(ni, name) { + continue + } + sname := name.String() + if mergedFields != nil { + if mergedFields[sname] { + continue + } + mergedFields[sname] = true + } + if info, ok := sinfo.FieldsMap[sname]; ok { + if d.uniqueKeys { + if doneFields[info.Id] { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.Line, name.String(), out.Type())) + continue + } + doneFields[info.Id] = true + } + var field reflect.Value + if info.Inline == nil { + field = out.Field(info.Num) + } else { + field = d.fieldByIndex(n, out, info.Inline) + } + d.unmarshal(n.Content[i+1], field) + } else if sinfo.InlineMap != -1 { + if inlineMap.IsNil() { + inlineMap.Set(reflect.MakeMap(inlineMap.Type())) + } + value := reflect.New(elemType).Elem() + d.unmarshal(n.Content[i+1], value) + inlineMap.SetMapIndex(name, value) + } else if d.knownFields { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.Line, name.String(), out.Type())) + } + } + + d.mergedFields = mergedFields + if mergeNode != nil { + d.merge(n, mergeNode, out) + } + return true +} + +func failWantMap() { + failf("map merge requires map or sequence of maps as the value") +} + +func (d *decoder) merge(parent *Node, merge *Node, out reflect.Value) { + mergedFields := d.mergedFields + if mergedFields == nil { + d.mergedFields = make(map[interface{}]bool) + for i := 0; i < len(parent.Content); i += 2 { + k := reflect.New(ifaceType).Elem() + if d.unmarshal(parent.Content[i], k) { + d.mergedFields[k.Interface()] = true + } + } + } + + switch merge.Kind { + case MappingNode: + d.unmarshal(merge, out) + case AliasNode: + if merge.Alias != nil && merge.Alias.Kind != MappingNode { + failWantMap() + } + d.unmarshal(merge, out) + case SequenceNode: + for i := 0; i < len(merge.Content); i++ { + ni := merge.Content[i] + if ni.Kind == AliasNode { + if ni.Alias != nil && ni.Alias.Kind != MappingNode { + failWantMap() + } + } else if ni.Kind != MappingNode { + failWantMap() + } + d.unmarshal(ni, out) + } + default: + failWantMap() + } + + d.mergedFields = mergedFields +} + +func isMerge(n *Node) bool { + return n.Kind == ScalarNode && n.Value == "<<" && (n.Tag == "" || n.Tag == "!" || shortTag(n.Tag) == mergeTag) +} diff --git a/vendor/gopkg.in/yaml.v3/emitterc.go b/vendor/gopkg.in/yaml.v3/emitterc.go new file mode 100644 index 00000000..0f47c9ca --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/emitterc.go @@ -0,0 +1,2020 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +import ( + "bytes" + "fmt" +) + +// Flush the buffer if needed. +func flush(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) { + return yaml_emitter_flush(emitter) + } + return true +} + +// Put a character to the output buffer. +func put(emitter *yaml_emitter_t, value byte) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + emitter.buffer[emitter.buffer_pos] = value + emitter.buffer_pos++ + emitter.column++ + return true +} + +// Put a line break to the output buffer. +func put_break(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + switch emitter.line_break { + case yaml_CR_BREAK: + emitter.buffer[emitter.buffer_pos] = '\r' + emitter.buffer_pos += 1 + case yaml_LN_BREAK: + emitter.buffer[emitter.buffer_pos] = '\n' + emitter.buffer_pos += 1 + case yaml_CRLN_BREAK: + emitter.buffer[emitter.buffer_pos+0] = '\r' + emitter.buffer[emitter.buffer_pos+1] = '\n' + emitter.buffer_pos += 2 + default: + panic("unknown line break setting") + } + if emitter.column == 0 { + emitter.space_above = true + } + emitter.column = 0 + emitter.line++ + // [Go] Do this here and below and drop from everywhere else (see commented lines). + emitter.indention = true + return true +} + +// Copy a character from a string into buffer. +func write(emitter *yaml_emitter_t, s []byte, i *int) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + p := emitter.buffer_pos + w := width(s[*i]) + switch w { + case 4: + emitter.buffer[p+3] = s[*i+3] + fallthrough + case 3: + emitter.buffer[p+2] = s[*i+2] + fallthrough + case 2: + emitter.buffer[p+1] = s[*i+1] + fallthrough + case 1: + emitter.buffer[p+0] = s[*i+0] + default: + panic("unknown character width") + } + emitter.column++ + emitter.buffer_pos += w + *i += w + return true +} + +// Write a whole string into buffer. +func write_all(emitter *yaml_emitter_t, s []byte) bool { + for i := 0; i < len(s); { + if !write(emitter, s, &i) { + return false + } + } + return true +} + +// Copy a line break character from a string into buffer. +func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool { + if s[*i] == '\n' { + if !put_break(emitter) { + return false + } + *i++ + } else { + if !write(emitter, s, i) { + return false + } + if emitter.column == 0 { + emitter.space_above = true + } + emitter.column = 0 + emitter.line++ + // [Go] Do this here and above and drop from everywhere else (see commented lines). + emitter.indention = true + } + return true +} + +// Set an emitter error and return false. +func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_EMITTER_ERROR + emitter.problem = problem + return false +} + +// Emit an event. +func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.events = append(emitter.events, *event) + for !yaml_emitter_need_more_events(emitter) { + event := &emitter.events[emitter.events_head] + if !yaml_emitter_analyze_event(emitter, event) { + return false + } + if !yaml_emitter_state_machine(emitter, event) { + return false + } + yaml_event_delete(event) + emitter.events_head++ + } + return true +} + +// Check if we need to accumulate more events before emitting. +// +// We accumulate extra +// - 1 event for DOCUMENT-START +// - 2 events for SEQUENCE-START +// - 3 events for MAPPING-START +// +func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { + if emitter.events_head == len(emitter.events) { + return true + } + var accumulate int + switch emitter.events[emitter.events_head].typ { + case yaml_DOCUMENT_START_EVENT: + accumulate = 1 + break + case yaml_SEQUENCE_START_EVENT: + accumulate = 2 + break + case yaml_MAPPING_START_EVENT: + accumulate = 3 + break + default: + return false + } + if len(emitter.events)-emitter.events_head > accumulate { + return false + } + var level int + for i := emitter.events_head; i < len(emitter.events); i++ { + switch emitter.events[i].typ { + case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT: + level++ + case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT: + level-- + } + if level == 0 { + return false + } + } + return true +} + +// Append a directive to the directives stack. +func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool { + for i := 0; i < len(emitter.tag_directives); i++ { + if bytes.Equal(value.handle, emitter.tag_directives[i].handle) { + if allow_duplicates { + return true + } + return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive") + } + } + + // [Go] Do we actually need to copy this given garbage collection + // and the lack of deallocating destructors? + tag_copy := yaml_tag_directive_t{ + handle: make([]byte, len(value.handle)), + prefix: make([]byte, len(value.prefix)), + } + copy(tag_copy.handle, value.handle) + copy(tag_copy.prefix, value.prefix) + emitter.tag_directives = append(emitter.tag_directives, tag_copy) + return true +} + +// Increase the indentation level. +func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool { + emitter.indents = append(emitter.indents, emitter.indent) + if emitter.indent < 0 { + if flow { + emitter.indent = emitter.best_indent + } else { + emitter.indent = 0 + } + } else if !indentless { + // [Go] This was changed so that indentations are more regular. + if emitter.states[len(emitter.states)-1] == yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE { + // The first indent inside a sequence will just skip the "- " indicator. + emitter.indent += 2 + } else { + // Everything else aligns to the chosen indentation. + emitter.indent = emitter.best_indent*((emitter.indent+emitter.best_indent)/emitter.best_indent) + } + } + return true +} + +// State dispatcher. +func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool { + switch emitter.state { + default: + case yaml_EMIT_STREAM_START_STATE: + return yaml_emitter_emit_stream_start(emitter, event) + + case yaml_EMIT_FIRST_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, true) + + case yaml_EMIT_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, false) + + case yaml_EMIT_DOCUMENT_CONTENT_STATE: + return yaml_emitter_emit_document_content(emitter, event) + + case yaml_EMIT_DOCUMENT_END_STATE: + return yaml_emitter_emit_document_end(emitter, event) + + case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, true, false) + + case yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, false, true) + + case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, false, false) + + case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, true, false) + + case yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, false, true) + + case yaml_EMIT_FLOW_MAPPING_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, false, false) + + case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, true) + + case yaml_EMIT_FLOW_MAPPING_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, false) + + case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, true) + + case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, false) + + case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, true) + + case yaml_EMIT_BLOCK_MAPPING_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, false) + + case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, true) + + case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, false) + + case yaml_EMIT_END_STATE: + return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END") + } + panic("invalid emitter state") +} + +// Expect STREAM-START. +func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_STREAM_START_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START") + } + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = event.encoding + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = yaml_UTF8_ENCODING + } + } + if emitter.best_indent < 2 || emitter.best_indent > 9 { + emitter.best_indent = 2 + } + if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 { + emitter.best_width = 80 + } + if emitter.best_width < 0 { + emitter.best_width = 1<<31 - 1 + } + if emitter.line_break == yaml_ANY_BREAK { + emitter.line_break = yaml_LN_BREAK + } + + emitter.indent = -1 + emitter.line = 0 + emitter.column = 0 + emitter.whitespace = true + emitter.indention = true + emitter.space_above = true + emitter.foot_indent = -1 + + if emitter.encoding != yaml_UTF8_ENCODING { + if !yaml_emitter_write_bom(emitter) { + return false + } + } + emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE + return true +} + +// Expect DOCUMENT-START or STREAM-END. +func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + + if event.typ == yaml_DOCUMENT_START_EVENT { + + if event.version_directive != nil { + if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) { + return false + } + } + + for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) { + return false + } + if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) { + return false + } + } + + for i := 0; i < len(default_tag_directives); i++ { + tag_directive := &default_tag_directives[i] + if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) { + return false + } + } + + implicit := event.implicit + if !first || emitter.canonical { + implicit = false + } + + if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if event.version_directive != nil { + implicit = false + if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if len(event.tag_directives) > 0 { + implicit = false + for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) { + return false + } + if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } + + if yaml_emitter_check_empty_document(emitter) { + implicit = false + } + if !implicit { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) { + return false + } + if emitter.canonical || true { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } + + if len(emitter.head_comment) > 0 { + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if !put_break(emitter) { + return false + } + } + + emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE + return true + } + + if event.typ == yaml_STREAM_END_EVENT { + if emitter.open_ended { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_END_STATE + return true + } + + return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END") +} + +// Expect the root node. +func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE) + + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if !yaml_emitter_emit_node(emitter, event, true, false, false, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true +} + +// Expect DOCUMENT-END. +func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_DOCUMENT_END_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END") + } + // [Go] Force document foot separation. + emitter.foot_indent = 0 + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + emitter.foot_indent = -1 + if !yaml_emitter_write_indent(emitter) { + return false + } + if !event.implicit { + // [Go] Allocate the slice elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_DOCUMENT_START_STATE + emitter.tag_directives = emitter.tag_directives[:0] + return true +} + +// Expect a flow item node. +func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first, trail bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } + + if event.typ == yaml_SEQUENCE_END_EVENT { + if emitter.canonical && !first && !trail { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.column == 0 || emitter.canonical && !first { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + + return true + } + + if !first && !trail { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if emitter.column == 0 { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE) + } else { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) + } + if !yaml_emitter_emit_node(emitter, event, false, true, false, false) { + return false + } + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true +} + +// Expect a flow key node. +func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first, trail bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } + + if event.typ == yaml_MAPPING_END_EVENT { + if (emitter.canonical || len(emitter.head_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0) && !first && !trail { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if !yaml_emitter_process_head_comment(emitter) { + return false + } + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.canonical && !first { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + + if !first && !trail { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + + if !yaml_emitter_process_head_comment(emitter) { + return false + } + + if emitter.column == 0 { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if !emitter.canonical && yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a flow value node. +func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) { + return false + } + } + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE) + } else { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) + } + if !yaml_emitter_emit_node(emitter, event, false, false, true, false) { + return false + } + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true +} + +// Expect a block item node. +func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, false) { + return false + } + } + if event.typ == yaml_SEQUENCE_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE) + if !yaml_emitter_emit_node(emitter, event, false, true, false, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true +} + +// Expect a block key node. +func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, false) { + return false + } + } + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if event.typ == yaml_MAPPING_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if len(emitter.line_comment) > 0 { + // [Go] A line comment was provided for the key. That's unusual as the + // scanner associates line comments with the value. Either way, + // save the line comment and render it appropriately later. + emitter.key_line_comment = emitter.line_comment + emitter.line_comment = nil + } + if yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a block value node. +func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) { + return false + } + } + if len(emitter.key_line_comment) > 0 { + // [Go] Line comments are generally associated with the value, but when there's + // no value on the same line as a mapping key they end up attached to the + // key itself. + if event.typ == yaml_SCALAR_EVENT { + if len(emitter.line_comment) == 0 { + // A scalar is coming and it has no line comments by itself yet, + // so just let it handle the line comment as usual. If it has a + // line comment, we can't have both so the one from the key is lost. + emitter.line_comment = emitter.key_line_comment + emitter.key_line_comment = nil + } + } else if event.sequence_style() != yaml_FLOW_SEQUENCE_STYLE && (event.typ == yaml_MAPPING_START_EVENT || event.typ == yaml_SEQUENCE_START_EVENT) { + // An indented block follows, so write the comment right now. + emitter.line_comment, emitter.key_line_comment = emitter.key_line_comment, emitter.line_comment + if !yaml_emitter_process_line_comment(emitter) { + return false + } + emitter.line_comment, emitter.key_line_comment = emitter.key_line_comment, emitter.line_comment + } + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE) + if !yaml_emitter_emit_node(emitter, event, false, false, true, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true +} + +func yaml_emitter_silent_nil_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { + return event.typ == yaml_SCALAR_EVENT && event.implicit && !emitter.canonical && len(emitter.scalar_data.value) == 0 +} + +// Expect a node. +func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t, + root bool, sequence bool, mapping bool, simple_key bool) bool { + + emitter.root_context = root + emitter.sequence_context = sequence + emitter.mapping_context = mapping + emitter.simple_key_context = simple_key + + switch event.typ { + case yaml_ALIAS_EVENT: + return yaml_emitter_emit_alias(emitter, event) + case yaml_SCALAR_EVENT: + return yaml_emitter_emit_scalar(emitter, event) + case yaml_SEQUENCE_START_EVENT: + return yaml_emitter_emit_sequence_start(emitter, event) + case yaml_MAPPING_START_EVENT: + return yaml_emitter_emit_mapping_start(emitter, event) + default: + return yaml_emitter_set_emitter_error(emitter, + fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.typ)) + } +} + +// Expect ALIAS. +func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true +} + +// Expect SCALAR. +func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_select_scalar_style(emitter, event) { + return false + } + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + if !yaml_emitter_process_scalar(emitter) { + return false + } + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true +} + +// Expect SEQUENCE-START. +func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE || + yaml_emitter_check_empty_sequence(emitter) { + emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE + } + return true +} + +// Expect MAPPING-START. +func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE || + yaml_emitter_check_empty_mapping(emitter) { + emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE + } + return true +} + +// Check if the document content is an empty scalar. +func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool { + return false // [Go] Huh? +} + +// Check if the next events represent an empty sequence. +func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT +} + +// Check if the next events represent an empty mapping. +func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT +} + +// Check if the next node can be expressed as a simple key. +func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { + length := 0 + switch emitter.events[emitter.events_head].typ { + case yaml_ALIAS_EVENT: + length += len(emitter.anchor_data.anchor) + case yaml_SCALAR_EVENT: + if emitter.scalar_data.multiline { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + + len(emitter.scalar_data.value) + case yaml_SEQUENCE_START_EVENT: + if !yaml_emitter_check_empty_sequence(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + case yaml_MAPPING_START_EVENT: + if !yaml_emitter_check_empty_mapping(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + default: + return false + } + return length <= 128 +} + +// Determine an acceptable scalar style. +func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { + + no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 + if no_tag && !event.implicit && !event.quoted_implicit { + return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") + } + + style := event.scalar_style() + if style == yaml_ANY_SCALAR_STYLE { + style = yaml_PLAIN_SCALAR_STYLE + } + if emitter.canonical { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + if emitter.simple_key_context && emitter.scalar_data.multiline { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + + if style == yaml_PLAIN_SCALAR_STYLE { + if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed || + emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if no_tag && !event.implicit { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_SINGLE_QUOTED_SCALAR_STYLE { + if !emitter.scalar_data.single_quoted_allowed { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE { + if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } + + if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE { + emitter.tag_data.handle = []byte{'!'} + } + emitter.scalar_data.style = style + return true +} + +// Write an anchor. +func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { + if emitter.anchor_data.anchor == nil { + return true + } + c := []byte{'&'} + if emitter.anchor_data.alias { + c[0] = '*' + } + if !yaml_emitter_write_indicator(emitter, c, true, false, false) { + return false + } + return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor) +} + +// Write a tag. +func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool { + if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 { + return true + } + if len(emitter.tag_data.handle) > 0 { + if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) { + return false + } + if len(emitter.tag_data.suffix) > 0 { + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + } + } else { + // [Go] Allocate these slices elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) { + return false + } + } + return true +} + +// Write a scalar. +func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool { + switch emitter.scalar_data.style { + case yaml_PLAIN_SCALAR_STYLE: + return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_SINGLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_DOUBLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_LITERAL_SCALAR_STYLE: + return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value) + + case yaml_FOLDED_SCALAR_STYLE: + return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value) + } + panic("unknown scalar style") +} + +// Write a head comment. +func yaml_emitter_process_head_comment(emitter *yaml_emitter_t) bool { + if len(emitter.tail_comment) > 0 { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_comment(emitter, emitter.tail_comment) { + return false + } + emitter.tail_comment = emitter.tail_comment[:0] + emitter.foot_indent = emitter.indent + if emitter.foot_indent < 0 { + emitter.foot_indent = 0 + } + } + + if len(emitter.head_comment) == 0 { + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_comment(emitter, emitter.head_comment) { + return false + } + emitter.head_comment = emitter.head_comment[:0] + return true +} + +// Write an line comment. +func yaml_emitter_process_line_comment(emitter *yaml_emitter_t) bool { + if len(emitter.line_comment) == 0 { + return true + } + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !yaml_emitter_write_comment(emitter, emitter.line_comment) { + return false + } + emitter.line_comment = emitter.line_comment[:0] + return true +} + +// Write a foot comment. +func yaml_emitter_process_foot_comment(emitter *yaml_emitter_t) bool { + if len(emitter.foot_comment) == 0 { + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_comment(emitter, emitter.foot_comment) { + return false + } + emitter.foot_comment = emitter.foot_comment[:0] + emitter.foot_indent = emitter.indent + if emitter.foot_indent < 0 { + emitter.foot_indent = 0 + } + return true +} + +// Check if a %YAML directive is valid. +func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool { + if version_directive.major != 1 || version_directive.minor != 1 { + return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive") + } + return true +} + +// Check if a %TAG directive is valid. +func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool { + handle := tag_directive.handle + prefix := tag_directive.prefix + if len(handle) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty") + } + if handle[0] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'") + } + if handle[len(handle)-1] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'") + } + for i := 1; i < len(handle)-1; i += width(handle[i]) { + if !is_alpha(handle, i) { + return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only") + } + } + if len(prefix) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty") + } + return true +} + +// Check if an anchor is valid. +func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool { + if len(anchor) == 0 { + problem := "anchor value must not be empty" + if alias { + problem = "alias value must not be empty" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + for i := 0; i < len(anchor); i += width(anchor[i]) { + if !is_alpha(anchor, i) { + problem := "anchor value must contain alphanumerical characters only" + if alias { + problem = "alias value must contain alphanumerical characters only" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + } + emitter.anchor_data.anchor = anchor + emitter.anchor_data.alias = alias + return true +} + +// Check if a tag is valid. +func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool { + if len(tag) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty") + } + for i := 0; i < len(emitter.tag_directives); i++ { + tag_directive := &emitter.tag_directives[i] + if bytes.HasPrefix(tag, tag_directive.prefix) { + emitter.tag_data.handle = tag_directive.handle + emitter.tag_data.suffix = tag[len(tag_directive.prefix):] + return true + } + } + emitter.tag_data.suffix = tag + return true +} + +// Check if a scalar is valid. +func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { + var ( + block_indicators = false + flow_indicators = false + line_breaks = false + special_characters = false + tab_characters = false + + leading_space = false + leading_break = false + trailing_space = false + trailing_break = false + break_space = false + space_break = false + + preceded_by_whitespace = false + followed_by_whitespace = false + previous_space = false + previous_break = false + ) + + emitter.scalar_data.value = value + + if len(value) == 0 { + emitter.scalar_data.multiline = false + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = false + return true + } + + if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) { + block_indicators = true + flow_indicators = true + } + + preceded_by_whitespace = true + for i, w := 0, 0; i < len(value); i += w { + w = width(value[i]) + followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w) + + if i == 0 { + switch value[i] { + case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`': + flow_indicators = true + block_indicators = true + case '?', ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '-': + if followed_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } else { + switch value[i] { + case ',', '?', '[', ']', '{', '}': + flow_indicators = true + case ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '#': + if preceded_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } + + if value[i] == '\t' { + tab_characters = true + } else if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { + special_characters = true + } + if is_space(value, i) { + if i == 0 { + leading_space = true + } + if i+width(value[i]) == len(value) { + trailing_space = true + } + if previous_break { + break_space = true + } + previous_space = true + previous_break = false + } else if is_break(value, i) { + line_breaks = true + if i == 0 { + leading_break = true + } + if i+width(value[i]) == len(value) { + trailing_break = true + } + if previous_space { + space_break = true + } + previous_space = false + previous_break = true + } else { + previous_space = false + previous_break = false + } + + // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition. + preceded_by_whitespace = is_blankz(value, i) + } + + emitter.scalar_data.multiline = line_breaks + emitter.scalar_data.flow_plain_allowed = true + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = true + + if leading_space || leading_break || trailing_space || trailing_break { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if trailing_space { + emitter.scalar_data.block_allowed = false + } + if break_space { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + } + if space_break || tab_characters || special_characters { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + } + if space_break || special_characters { + emitter.scalar_data.block_allowed = false + } + if line_breaks { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if flow_indicators { + emitter.scalar_data.flow_plain_allowed = false + } + if block_indicators { + emitter.scalar_data.block_plain_allowed = false + } + return true +} + +// Check if the event data is valid. +func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { + + emitter.anchor_data.anchor = nil + emitter.tag_data.handle = nil + emitter.tag_data.suffix = nil + emitter.scalar_data.value = nil + + if len(event.head_comment) > 0 { + emitter.head_comment = event.head_comment + } + if len(event.line_comment) > 0 { + emitter.line_comment = event.line_comment + } + if len(event.foot_comment) > 0 { + emitter.foot_comment = event.foot_comment + } + if len(event.tail_comment) > 0 { + emitter.tail_comment = event.tail_comment + } + + switch event.typ { + case yaml_ALIAS_EVENT: + if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) { + return false + } + + case yaml_SCALAR_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + if !yaml_emitter_analyze_scalar(emitter, event.value) { + return false + } + + case yaml_SEQUENCE_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + + case yaml_MAPPING_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + } + return true +} + +// Write the BOM character. +func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool { + if !flush(emitter) { + return false + } + pos := emitter.buffer_pos + emitter.buffer[pos+0] = '\xEF' + emitter.buffer[pos+1] = '\xBB' + emitter.buffer[pos+2] = '\xBF' + emitter.buffer_pos += 3 + return true +} + +func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { + indent := emitter.indent + if indent < 0 { + indent = 0 + } + if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) { + if !put_break(emitter) { + return false + } + } + if emitter.foot_indent == indent { + if !put_break(emitter) { + return false + } + } + for emitter.column < indent { + if !put(emitter, ' ') { + return false + } + } + emitter.whitespace = true + //emitter.indention = true + emitter.space_above = false + emitter.foot_indent = -1 + return true +} + +func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, indicator) { + return false + } + emitter.whitespace = is_whitespace + emitter.indention = (emitter.indention && is_indention) + emitter.open_ended = false + return true +} + +func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool { + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool { + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + for i := 0; i < len(value); { + var must_write bool + switch value[i] { + case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']': + must_write = true + default: + must_write = is_alpha(value, i) + } + if must_write { + if !write(emitter, value, &i) { + return false + } + } else { + w := width(value[i]) + for k := 0; k < w; k++ { + octet := value[i] + i++ + if !put(emitter, '%') { + return false + } + + c := octet >> 4 + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } + + c = octet & 0x0f + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } + } + } + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + if len(value) > 0 && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + + spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + //emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } + + if len(value) > 0 { + emitter.whitespace = false + } + emitter.indention = false + if emitter.root_context { + emitter.open_ended = true + } + + return true +} + +func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + + if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { + return false + } + + spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + //emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if value[i] == '\'' { + if !put(emitter, '\'') { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + spaces := false + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) { + return false + } + + for i := 0; i < len(value); { + if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) || + is_bom(value, i) || is_break(value, i) || + value[i] == '"' || value[i] == '\\' { + + octet := value[i] + + var w int + var v rune + switch { + case octet&0x80 == 0x00: + w, v = 1, rune(octet&0x7F) + case octet&0xE0 == 0xC0: + w, v = 2, rune(octet&0x1F) + case octet&0xF0 == 0xE0: + w, v = 3, rune(octet&0x0F) + case octet&0xF8 == 0xF0: + w, v = 4, rune(octet&0x07) + } + for k := 1; k < w; k++ { + octet = value[i+k] + v = (v << 6) + (rune(octet) & 0x3F) + } + i += w + + if !put(emitter, '\\') { + return false + } + + var ok bool + switch v { + case 0x00: + ok = put(emitter, '0') + case 0x07: + ok = put(emitter, 'a') + case 0x08: + ok = put(emitter, 'b') + case 0x09: + ok = put(emitter, 't') + case 0x0A: + ok = put(emitter, 'n') + case 0x0b: + ok = put(emitter, 'v') + case 0x0c: + ok = put(emitter, 'f') + case 0x0d: + ok = put(emitter, 'r') + case 0x1b: + ok = put(emitter, 'e') + case 0x22: + ok = put(emitter, '"') + case 0x5c: + ok = put(emitter, '\\') + case 0x85: + ok = put(emitter, 'N') + case 0xA0: + ok = put(emitter, '_') + case 0x2028: + ok = put(emitter, 'L') + case 0x2029: + ok = put(emitter, 'P') + default: + if v <= 0xFF { + ok = put(emitter, 'x') + w = 2 + } else if v <= 0xFFFF { + ok = put(emitter, 'u') + w = 4 + } else { + ok = put(emitter, 'U') + w = 8 + } + for k := (w - 1) * 4; ok && k >= 0; k -= 4 { + digit := byte((v >> uint(k)) & 0x0F) + if digit < 10 { + ok = put(emitter, digit+'0') + } else { + ok = put(emitter, digit+'A'-10) + } + } + } + if !ok { + return false + } + spaces = false + } else if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 { + if !yaml_emitter_write_indent(emitter) { + return false + } + if is_space(value, i+1) { + if !put(emitter, '\\') { + return false + } + } + i += width(value[i]) + } else if !write(emitter, value, &i) { + return false + } + spaces = true + } else { + if !write(emitter, value, &i) { + return false + } + spaces = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool { + if is_space(value, 0) || is_break(value, 0) { + indent_hint := []byte{'0' + byte(emitter.best_indent)} + if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) { + return false + } + } + + emitter.open_ended = false + + var chomp_hint [1]byte + if len(value) == 0 { + chomp_hint[0] = '-' + } else { + i := len(value) - 1 + for value[i]&0xC0 == 0x80 { + i-- + } + if !is_break(value, i) { + chomp_hint[0] = '-' + } else if i == 0 { + chomp_hint[0] = '+' + emitter.open_ended = true + } else { + i-- + for value[i]&0xC0 == 0x80 { + i-- + } + if is_break(value, i) { + chomp_hint[0] = '+' + emitter.open_ended = true + } + } + } + if chomp_hint[0] != 0 { + if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) { + return false + } + } + return true +} + +func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + //emitter.indention = true + emitter.whitespace = true + breaks := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !write_break(emitter, value, &i) { + return false + } + //emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + breaks = false + } + } + + return true +} + +func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + + //emitter.indention = true + emitter.whitespace = true + + breaks := true + leading_spaces := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !breaks && !leading_spaces && value[i] == '\n' { + k := 0 + for is_break(value, k) { + k += width(value[k]) + } + if !is_blankz(value, k) { + if !put_break(emitter) { + return false + } + } + } + if !write_break(emitter, value, &i) { + return false + } + //emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + leading_spaces = is_blank(value, i) + } + if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + emitter.indention = false + breaks = false + } + } + return true +} + +func yaml_emitter_write_comment(emitter *yaml_emitter_t, comment []byte) bool { + breaks := false + pound := false + for i := 0; i < len(comment); { + if is_break(comment, i) { + if !write_break(emitter, comment, &i) { + return false + } + //emitter.indention = true + breaks = true + pound = false + } else { + if breaks && !yaml_emitter_write_indent(emitter) { + return false + } + if !pound { + if comment[i] != '#' && (!put(emitter, '#') || !put(emitter, ' ')) { + return false + } + pound = true + } + if !write(emitter, comment, &i) { + return false + } + emitter.indention = false + breaks = false + } + } + if !breaks && !put_break(emitter) { + return false + } + + emitter.whitespace = true + //emitter.indention = true + return true +} diff --git a/vendor/gopkg.in/yaml.v3/encode.go b/vendor/gopkg.in/yaml.v3/encode.go new file mode 100644 index 00000000..de9e72a3 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/encode.go @@ -0,0 +1,577 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yaml + +import ( + "encoding" + "fmt" + "io" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +type encoder struct { + emitter yaml_emitter_t + event yaml_event_t + out []byte + flow bool + indent int + doneInit bool +} + +func newEncoder() *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_string(&e.emitter, &e.out) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func newEncoderWithWriter(w io.Writer) *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_writer(&e.emitter, w) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func (e *encoder) init() { + if e.doneInit { + return + } + if e.indent == 0 { + e.indent = 4 + } + e.emitter.best_indent = e.indent + yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING) + e.emit() + e.doneInit = true +} + +func (e *encoder) finish() { + e.emitter.open_ended = false + yaml_stream_end_event_initialize(&e.event) + e.emit() +} + +func (e *encoder) destroy() { + yaml_emitter_delete(&e.emitter) +} + +func (e *encoder) emit() { + // This will internally delete the e.event value. + e.must(yaml_emitter_emit(&e.emitter, &e.event)) +} + +func (e *encoder) must(ok bool) { + if !ok { + msg := e.emitter.problem + if msg == "" { + msg = "unknown problem generating YAML content" + } + failf("%s", msg) + } +} + +func (e *encoder) marshalDoc(tag string, in reflect.Value) { + e.init() + var node *Node + if in.IsValid() { + node, _ = in.Interface().(*Node) + } + if node != nil && node.Kind == DocumentNode { + e.nodev(in) + } else { + yaml_document_start_event_initialize(&e.event, nil, nil, true) + e.emit() + e.marshal(tag, in) + yaml_document_end_event_initialize(&e.event, true) + e.emit() + } +} + +func (e *encoder) marshal(tag string, in reflect.Value) { + tag = shortTag(tag) + if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() { + e.nilv() + return + } + iface := in.Interface() + switch value := iface.(type) { + case *Node: + e.nodev(in) + return + case Node: + if !in.CanAddr() { + var n = reflect.New(in.Type()).Elem() + n.Set(in) + in = n + } + e.nodev(in.Addr()) + return + case time.Time: + e.timev(tag, in) + return + case *time.Time: + e.timev(tag, in.Elem()) + return + case time.Duration: + e.stringv(tag, reflect.ValueOf(value.String())) + return + case Marshaler: + v, err := value.MarshalYAML() + if err != nil { + fail(err) + } + if v == nil { + e.nilv() + return + } + e.marshal(tag, reflect.ValueOf(v)) + return + case encoding.TextMarshaler: + text, err := value.MarshalText() + if err != nil { + fail(err) + } + in = reflect.ValueOf(string(text)) + case nil: + e.nilv() + return + } + switch in.Kind() { + case reflect.Interface: + e.marshal(tag, in.Elem()) + case reflect.Map: + e.mapv(tag, in) + case reflect.Ptr: + e.marshal(tag, in.Elem()) + case reflect.Struct: + e.structv(tag, in) + case reflect.Slice, reflect.Array: + e.slicev(tag, in) + case reflect.String: + e.stringv(tag, in) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + e.intv(tag, in) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + e.uintv(tag, in) + case reflect.Float32, reflect.Float64: + e.floatv(tag, in) + case reflect.Bool: + e.boolv(tag, in) + default: + panic("cannot marshal type: " + in.Type().String()) + } +} + +func (e *encoder) mapv(tag string, in reflect.Value) { + e.mappingv(tag, func() { + keys := keyList(in.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + e.marshal("", k) + e.marshal("", in.MapIndex(k)) + } + }) +} + +func (e *encoder) fieldByIndex(v reflect.Value, index []int) (field reflect.Value) { + for _, num := range index { + for { + if v.Kind() == reflect.Ptr { + if v.IsNil() { + return reflect.Value{} + } + v = v.Elem() + continue + } + break + } + v = v.Field(num) + } + return v +} + +func (e *encoder) structv(tag string, in reflect.Value) { + sinfo, err := getStructInfo(in.Type()) + if err != nil { + panic(err) + } + e.mappingv(tag, func() { + for _, info := range sinfo.FieldsList { + var value reflect.Value + if info.Inline == nil { + value = in.Field(info.Num) + } else { + value = e.fieldByIndex(in, info.Inline) + if !value.IsValid() { + continue + } + } + if info.OmitEmpty && isZero(value) { + continue + } + e.marshal("", reflect.ValueOf(info.Key)) + e.flow = info.Flow + e.marshal("", value) + } + if sinfo.InlineMap >= 0 { + m := in.Field(sinfo.InlineMap) + if m.Len() > 0 { + e.flow = false + keys := keyList(m.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + if _, found := sinfo.FieldsMap[k.String()]; found { + panic(fmt.Sprintf("cannot have key %q in inlined map: conflicts with struct field", k.String())) + } + e.marshal("", k) + e.flow = false + e.marshal("", m.MapIndex(k)) + } + } + } + }) +} + +func (e *encoder) mappingv(tag string, f func()) { + implicit := tag == "" + style := yaml_BLOCK_MAPPING_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_MAPPING_STYLE + } + yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) + e.emit() + f() + yaml_mapping_end_event_initialize(&e.event) + e.emit() +} + +func (e *encoder) slicev(tag string, in reflect.Value) { + implicit := tag == "" + style := yaml_BLOCK_SEQUENCE_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_SEQUENCE_STYLE + } + e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) + e.emit() + n := in.Len() + for i := 0; i < n; i++ { + e.marshal("", in.Index(i)) + } + e.must(yaml_sequence_end_event_initialize(&e.event)) + e.emit() +} + +// isBase60 returns whether s is in base 60 notation as defined in YAML 1.1. +// +// The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported +// in YAML 1.2 and by this package, but these should be marshalled quoted for +// the time being for compatibility with other parsers. +func isBase60Float(s string) (result bool) { + // Fast path. + if s == "" { + return false + } + c := s[0] + if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 { + return false + } + // Do the full match. + return base60float.MatchString(s) +} + +// From http://yaml.org/type/float.html, except the regular expression there +// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix. +var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`) + +// isOldBool returns whether s is bool notation as defined in YAML 1.1. +// +// We continue to force strings that YAML 1.1 would interpret as booleans to be +// rendered as quotes strings so that the marshalled output valid for YAML 1.1 +// parsing. +func isOldBool(s string) (result bool) { + switch s { + case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON", + "n", "N", "no", "No", "NO", "off", "Off", "OFF": + return true + default: + return false + } +} + +func (e *encoder) stringv(tag string, in reflect.Value) { + var style yaml_scalar_style_t + s := in.String() + canUsePlain := true + switch { + case !utf8.ValidString(s): + if tag == binaryTag { + failf("explicitly tagged !!binary data must be base64-encoded") + } + if tag != "" { + failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) + } + // It can't be encoded directly as YAML so use a binary tag + // and encode it as base64. + tag = binaryTag + s = encodeBase64(s) + case tag == "": + // Check to see if it would resolve to a specific + // tag when encoded unquoted. If it doesn't, + // there's no need to quote it. + rtag, _ := resolve("", s) + canUsePlain = rtag == strTag && !(isBase60Float(s) || isOldBool(s)) + } + // Note: it's possible for user code to emit invalid YAML + // if they explicitly specify a tag and a string containing + // text that's incompatible with that tag. + switch { + case strings.Contains(s, "\n"): + if e.flow { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } else { + style = yaml_LITERAL_SCALAR_STYLE + } + case canUsePlain: + style = yaml_PLAIN_SCALAR_STYLE + default: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + e.emitScalar(s, "", tag, style, nil, nil, nil, nil) +} + +func (e *encoder) boolv(tag string, in reflect.Value) { + var s string + if in.Bool() { + s = "true" + } else { + s = "false" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) intv(tag string, in reflect.Value) { + s := strconv.FormatInt(in.Int(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) uintv(tag string, in reflect.Value) { + s := strconv.FormatUint(in.Uint(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) timev(tag string, in reflect.Value) { + t := in.Interface().(time.Time) + s := t.Format(time.RFC3339Nano) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) floatv(tag string, in reflect.Value) { + // Issue #352: When formatting, use the precision of the underlying value + precision := 64 + if in.Kind() == reflect.Float32 { + precision = 32 + } + + s := strconv.FormatFloat(in.Float(), 'g', -1, precision) + switch s { + case "+Inf": + s = ".inf" + case "-Inf": + s = "-.inf" + case "NaN": + s = ".nan" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) nilv() { + e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t, head, line, foot, tail []byte) { + // TODO Kill this function. Replace all initialize calls by their underlining Go literals. + implicit := tag == "" + if !implicit { + tag = longTag(tag) + } + e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)) + e.event.head_comment = head + e.event.line_comment = line + e.event.foot_comment = foot + e.event.tail_comment = tail + e.emit() +} + +func (e *encoder) nodev(in reflect.Value) { + e.node(in.Interface().(*Node), "") +} + +func (e *encoder) node(node *Node, tail string) { + // Zero nodes behave as nil. + if node.Kind == 0 && node.IsZero() { + e.nilv() + return + } + + // If the tag was not explicitly requested, and dropping it won't change the + // implicit tag of the value, don't include it in the presentation. + var tag = node.Tag + var stag = shortTag(tag) + var forceQuoting bool + if tag != "" && node.Style&TaggedStyle == 0 { + if node.Kind == ScalarNode { + if stag == strTag && node.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0 { + tag = "" + } else { + rtag, _ := resolve("", node.Value) + if rtag == stag { + tag = "" + } else if stag == strTag { + tag = "" + forceQuoting = true + } + } + } else { + var rtag string + switch node.Kind { + case MappingNode: + rtag = mapTag + case SequenceNode: + rtag = seqTag + } + if rtag == stag { + tag = "" + } + } + } + + switch node.Kind { + case DocumentNode: + yaml_document_start_event_initialize(&e.event, nil, nil, true) + e.event.head_comment = []byte(node.HeadComment) + e.emit() + for _, node := range node.Content { + e.node(node, "") + } + yaml_document_end_event_initialize(&e.event, true) + e.event.foot_comment = []byte(node.FootComment) + e.emit() + + case SequenceNode: + style := yaml_BLOCK_SEQUENCE_STYLE + if node.Style&FlowStyle != 0 { + style = yaml_FLOW_SEQUENCE_STYLE + } + e.must(yaml_sequence_start_event_initialize(&e.event, []byte(node.Anchor), []byte(longTag(tag)), tag == "", style)) + e.event.head_comment = []byte(node.HeadComment) + e.emit() + for _, node := range node.Content { + e.node(node, "") + } + e.must(yaml_sequence_end_event_initialize(&e.event)) + e.event.line_comment = []byte(node.LineComment) + e.event.foot_comment = []byte(node.FootComment) + e.emit() + + case MappingNode: + style := yaml_BLOCK_MAPPING_STYLE + if node.Style&FlowStyle != 0 { + style = yaml_FLOW_MAPPING_STYLE + } + yaml_mapping_start_event_initialize(&e.event, []byte(node.Anchor), []byte(longTag(tag)), tag == "", style) + e.event.tail_comment = []byte(tail) + e.event.head_comment = []byte(node.HeadComment) + e.emit() + + // The tail logic below moves the foot comment of prior keys to the following key, + // since the value for each key may be a nested structure and the foot needs to be + // processed only the entirety of the value is streamed. The last tail is processed + // with the mapping end event. + var tail string + for i := 0; i+1 < len(node.Content); i += 2 { + k := node.Content[i] + foot := k.FootComment + if foot != "" { + kopy := *k + kopy.FootComment = "" + k = &kopy + } + e.node(k, tail) + tail = foot + + v := node.Content[i+1] + e.node(v, "") + } + + yaml_mapping_end_event_initialize(&e.event) + e.event.tail_comment = []byte(tail) + e.event.line_comment = []byte(node.LineComment) + e.event.foot_comment = []byte(node.FootComment) + e.emit() + + case AliasNode: + yaml_alias_event_initialize(&e.event, []byte(node.Value)) + e.event.head_comment = []byte(node.HeadComment) + e.event.line_comment = []byte(node.LineComment) + e.event.foot_comment = []byte(node.FootComment) + e.emit() + + case ScalarNode: + value := node.Value + if !utf8.ValidString(value) { + if stag == binaryTag { + failf("explicitly tagged !!binary data must be base64-encoded") + } + if stag != "" { + failf("cannot marshal invalid UTF-8 data as %s", stag) + } + // It can't be encoded directly as YAML so use a binary tag + // and encode it as base64. + tag = binaryTag + value = encodeBase64(value) + } + + style := yaml_PLAIN_SCALAR_STYLE + switch { + case node.Style&DoubleQuotedStyle != 0: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + case node.Style&SingleQuotedStyle != 0: + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + case node.Style&LiteralStyle != 0: + style = yaml_LITERAL_SCALAR_STYLE + case node.Style&FoldedStyle != 0: + style = yaml_FOLDED_SCALAR_STYLE + case strings.Contains(value, "\n"): + style = yaml_LITERAL_SCALAR_STYLE + case forceQuoting: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + + e.emitScalar(value, node.Anchor, tag, style, []byte(node.HeadComment), []byte(node.LineComment), []byte(node.FootComment), []byte(tail)) + default: + failf("cannot encode node with unknown kind %d", node.Kind) + } +} diff --git a/vendor/gopkg.in/yaml.v3/parserc.go b/vendor/gopkg.in/yaml.v3/parserc.go new file mode 100644 index 00000000..268558a0 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/parserc.go @@ -0,0 +1,1258 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +import ( + "bytes" +) + +// The parser implements the following grammar: +// +// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +// implicit_document ::= block_node DOCUMENT-END* +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// block_node_or_indentless_sequence ::= +// ALIAS +// | properties (block_content | indentless_block_sequence)? +// | block_content +// | indentless_block_sequence +// block_node ::= ALIAS +// | properties block_content? +// | block_content +// flow_node ::= ALIAS +// | properties flow_content? +// | flow_content +// properties ::= TAG ANCHOR? | ANCHOR TAG? +// block_content ::= block_collection | flow_collection | SCALAR +// flow_content ::= flow_collection | SCALAR +// block_collection ::= block_sequence | block_mapping +// flow_collection ::= flow_sequence | flow_mapping +// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +// block_mapping ::= BLOCK-MAPPING_START +// ((KEY block_node_or_indentless_sequence?)? +// (VALUE block_node_or_indentless_sequence?)?)* +// BLOCK-END +// flow_sequence ::= FLOW-SEQUENCE-START +// (flow_sequence_entry FLOW-ENTRY)* +// flow_sequence_entry? +// FLOW-SEQUENCE-END +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// flow_mapping ::= FLOW-MAPPING-START +// (flow_mapping_entry FLOW-ENTRY)* +// flow_mapping_entry? +// FLOW-MAPPING-END +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + +// Peek the next token in the token queue. +func peek_token(parser *yaml_parser_t) *yaml_token_t { + if parser.token_available || yaml_parser_fetch_more_tokens(parser) { + token := &parser.tokens[parser.tokens_head] + yaml_parser_unfold_comments(parser, token) + return token + } + return nil +} + +// yaml_parser_unfold_comments walks through the comments queue and joins all +// comments behind the position of the provided token into the respective +// top-level comment slices in the parser. +func yaml_parser_unfold_comments(parser *yaml_parser_t, token *yaml_token_t) { + for parser.comments_head < len(parser.comments) && token.start_mark.index >= parser.comments[parser.comments_head].token_mark.index { + comment := &parser.comments[parser.comments_head] + if len(comment.head) > 0 { + if token.typ == yaml_BLOCK_END_TOKEN { + // No heads on ends, so keep comment.head for a follow up token. + break + } + if len(parser.head_comment) > 0 { + parser.head_comment = append(parser.head_comment, '\n') + } + parser.head_comment = append(parser.head_comment, comment.head...) + } + if len(comment.foot) > 0 { + if len(parser.foot_comment) > 0 { + parser.foot_comment = append(parser.foot_comment, '\n') + } + parser.foot_comment = append(parser.foot_comment, comment.foot...) + } + if len(comment.line) > 0 { + if len(parser.line_comment) > 0 { + parser.line_comment = append(parser.line_comment, '\n') + } + parser.line_comment = append(parser.line_comment, comment.line...) + } + *comment = yaml_comment_t{} + parser.comments_head++ + } +} + +// Remove the next token from the queue (must be called after peek_token). +func skip_token(parser *yaml_parser_t) { + parser.token_available = false + parser.tokens_parsed++ + parser.stream_end_produced = parser.tokens[parser.tokens_head].typ == yaml_STREAM_END_TOKEN + parser.tokens_head++ +} + +// Get the next event. +func yaml_parser_parse(parser *yaml_parser_t, event *yaml_event_t) bool { + // Erase the event object. + *event = yaml_event_t{} + + // No events after the end of the stream or error. + if parser.stream_end_produced || parser.error != yaml_NO_ERROR || parser.state == yaml_PARSE_END_STATE { + return true + } + + // Generate the next event. + return yaml_parser_state_machine(parser, event) +} + +// Set parser error. +func yaml_parser_set_parser_error(parser *yaml_parser_t, problem string, problem_mark yaml_mark_t) bool { + parser.error = yaml_PARSER_ERROR + parser.problem = problem + parser.problem_mark = problem_mark + return false +} + +func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string, problem_mark yaml_mark_t) bool { + parser.error = yaml_PARSER_ERROR + parser.context = context + parser.context_mark = context_mark + parser.problem = problem + parser.problem_mark = problem_mark + return false +} + +// State dispatcher. +func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool { + //trace("yaml_parser_state_machine", "state:", parser.state.String()) + + switch parser.state { + case yaml_PARSE_STREAM_START_STATE: + return yaml_parser_parse_stream_start(parser, event) + + case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return yaml_parser_parse_document_start(parser, event, true) + + case yaml_PARSE_DOCUMENT_START_STATE: + return yaml_parser_parse_document_start(parser, event, false) + + case yaml_PARSE_DOCUMENT_CONTENT_STATE: + return yaml_parser_parse_document_content(parser, event) + + case yaml_PARSE_DOCUMENT_END_STATE: + return yaml_parser_parse_document_end(parser, event) + + case yaml_PARSE_BLOCK_NODE_STATE: + return yaml_parser_parse_node(parser, event, true, false) + + case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return yaml_parser_parse_node(parser, event, true, true) + + case yaml_PARSE_FLOW_NODE_STATE: + return yaml_parser_parse_node(parser, event, false, false) + + case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return yaml_parser_parse_block_sequence_entry(parser, event, true) + + case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_block_sequence_entry(parser, event, false) + + case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_indentless_sequence_entry(parser, event) + + case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_parser_parse_block_mapping_key(parser, event, true) + + case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: + return yaml_parser_parse_block_mapping_key(parser, event, false) + + case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: + return yaml_parser_parse_block_mapping_value(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return yaml_parser_parse_flow_sequence_entry(parser, event, true) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_flow_sequence_entry(parser, event, false) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event) + + case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_parser_parse_flow_mapping_key(parser, event, true) + + case yaml_PARSE_FLOW_MAPPING_KEY_STATE: + return yaml_parser_parse_flow_mapping_key(parser, event, false) + + case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: + return yaml_parser_parse_flow_mapping_value(parser, event, false) + + case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return yaml_parser_parse_flow_mapping_value(parser, event, true) + + default: + panic("invalid parser state") + } +} + +// Parse the production: +// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +// ************ +func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_STREAM_START_TOKEN { + return yaml_parser_set_parser_error(parser, "did not find expected ", token.start_mark) + } + parser.state = yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE + *event = yaml_event_t{ + typ: yaml_STREAM_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + encoding: token.encoding, + } + skip_token(parser) + return true +} + +// Parse the productions: +// implicit_document ::= block_node DOCUMENT-END* +// * +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// ************************* +func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { + + token := peek_token(parser) + if token == nil { + return false + } + + // Parse extra document end indicators. + if !implicit { + for token.typ == yaml_DOCUMENT_END_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } + + if implicit && token.typ != yaml_VERSION_DIRECTIVE_TOKEN && + token.typ != yaml_TAG_DIRECTIVE_TOKEN && + token.typ != yaml_DOCUMENT_START_TOKEN && + token.typ != yaml_STREAM_END_TOKEN { + // Parse an implicit document. + if !yaml_parser_process_directives(parser, nil, nil) { + return false + } + parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) + parser.state = yaml_PARSE_BLOCK_NODE_STATE + + var head_comment []byte + if len(parser.head_comment) > 0 { + // [Go] Scan the header comment backwards, and if an empty line is found, break + // the header so the part before the last empty line goes into the + // document header, while the bottom of it goes into a follow up event. + for i := len(parser.head_comment) - 1; i > 0; i-- { + if parser.head_comment[i] == '\n' { + if i == len(parser.head_comment)-1 { + head_comment = parser.head_comment[:i] + parser.head_comment = parser.head_comment[i+1:] + break + } else if parser.head_comment[i-1] == '\n' { + head_comment = parser.head_comment[:i-1] + parser.head_comment = parser.head_comment[i+1:] + break + } + } + } + } + + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + + head_comment: head_comment, + } + + } else if token.typ != yaml_STREAM_END_TOKEN { + // Parse an explicit document. + var version_directive *yaml_version_directive_t + var tag_directives []yaml_tag_directive_t + start_mark := token.start_mark + if !yaml_parser_process_directives(parser, &version_directive, &tag_directives) { + return false + } + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_DOCUMENT_START_TOKEN { + yaml_parser_set_parser_error(parser, + "did not find expected ", token.start_mark) + return false + } + parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) + parser.state = yaml_PARSE_DOCUMENT_CONTENT_STATE + end_mark := token.end_mark + + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + version_directive: version_directive, + tag_directives: tag_directives, + implicit: false, + } + skip_token(parser) + + } else { + // Parse the stream end. + parser.state = yaml_PARSE_END_STATE + *event = yaml_event_t{ + typ: yaml_STREAM_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + skip_token(parser) + } + + return true +} + +// Parse the productions: +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// *********** +// +func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_VERSION_DIRECTIVE_TOKEN || + token.typ == yaml_TAG_DIRECTIVE_TOKEN || + token.typ == yaml_DOCUMENT_START_TOKEN || + token.typ == yaml_DOCUMENT_END_TOKEN || + token.typ == yaml_STREAM_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + return yaml_parser_process_empty_scalar(parser, event, + token.start_mark) + } + return yaml_parser_parse_node(parser, event, true, false) +} + +// Parse the productions: +// implicit_document ::= block_node DOCUMENT-END* +// ************* +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// +func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + + start_mark := token.start_mark + end_mark := token.start_mark + + implicit := true + if token.typ == yaml_DOCUMENT_END_TOKEN { + end_mark = token.end_mark + skip_token(parser) + implicit = false + } + + parser.tag_directives = parser.tag_directives[:0] + + parser.state = yaml_PARSE_DOCUMENT_START_STATE + *event = yaml_event_t{ + typ: yaml_DOCUMENT_END_EVENT, + start_mark: start_mark, + end_mark: end_mark, + implicit: implicit, + } + yaml_parser_set_event_comments(parser, event) + if len(event.head_comment) > 0 && len(event.foot_comment) == 0 { + event.foot_comment = event.head_comment + event.head_comment = nil + } + return true +} + +func yaml_parser_set_event_comments(parser *yaml_parser_t, event *yaml_event_t) { + event.head_comment = parser.head_comment + event.line_comment = parser.line_comment + event.foot_comment = parser.foot_comment + parser.head_comment = nil + parser.line_comment = nil + parser.foot_comment = nil + parser.tail_comment = nil + parser.stem_comment = nil +} + +// Parse the productions: +// block_node_or_indentless_sequence ::= +// ALIAS +// ***** +// | properties (block_content | indentless_block_sequence)? +// ********** * +// | block_content | indentless_block_sequence +// * +// block_node ::= ALIAS +// ***** +// | properties block_content? +// ********** * +// | block_content +// * +// flow_node ::= ALIAS +// ***** +// | properties flow_content? +// ********** * +// | flow_content +// * +// properties ::= TAG ANCHOR? | ANCHOR TAG? +// ************************* +// block_content ::= block_collection | flow_collection | SCALAR +// ****** +// flow_content ::= flow_collection | SCALAR +// ****** +func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { + //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_ALIAS_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + *event = yaml_event_t{ + typ: yaml_ALIAS_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + anchor: token.value, + } + yaml_parser_set_event_comments(parser, event) + skip_token(parser) + return true + } + + start_mark := token.start_mark + end_mark := token.start_mark + + var tag_token bool + var tag_handle, tag_suffix, anchor []byte + var tag_mark yaml_mark_t + if token.typ == yaml_ANCHOR_TOKEN { + anchor = token.value + start_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_TAG_TOKEN { + tag_token = true + tag_handle = token.value + tag_suffix = token.suffix + tag_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } else if token.typ == yaml_TAG_TOKEN { + tag_token = true + tag_handle = token.value + tag_suffix = token.suffix + start_mark = token.start_mark + tag_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_ANCHOR_TOKEN { + anchor = token.value + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } + + var tag []byte + if tag_token { + if len(tag_handle) == 0 { + tag = tag_suffix + tag_suffix = nil + } else { + for i := range parser.tag_directives { + if bytes.Equal(parser.tag_directives[i].handle, tag_handle) { + tag = append([]byte(nil), parser.tag_directives[i].prefix...) + tag = append(tag, tag_suffix...) + break + } + } + if len(tag) == 0 { + yaml_parser_set_parser_error_context(parser, + "while parsing a node", start_mark, + "found undefined tag handle", tag_mark) + return false + } + } + } + + implicit := len(tag) == 0 + if indentless_sequence && token.typ == yaml_BLOCK_ENTRY_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), + } + return true + } + if token.typ == yaml_SCALAR_TOKEN { + var plain_implicit, quoted_implicit bool + end_mark = token.end_mark + if (len(tag) == 0 && token.style == yaml_PLAIN_SCALAR_STYLE) || (len(tag) == 1 && tag[0] == '!') { + plain_implicit = true + } else if len(tag) == 0 { + quoted_implicit = true + } + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + value: token.value, + implicit: plain_implicit, + quoted_implicit: quoted_implicit, + style: yaml_style_t(token.style), + } + yaml_parser_set_event_comments(parser, event) + skip_token(parser) + return true + } + if token.typ == yaml_FLOW_SEQUENCE_START_TOKEN { + // [Go] Some of the events below can be merged as they differ only on style. + end_mark = token.end_mark + parser.state = yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_FLOW_SEQUENCE_STYLE), + } + yaml_parser_set_event_comments(parser, event) + return true + } + if token.typ == yaml_FLOW_MAPPING_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), + } + yaml_parser_set_event_comments(parser, event) + return true + } + if block && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), + } + if parser.stem_comment != nil { + event.head_comment = parser.stem_comment + parser.stem_comment = nil + } + return true + } + if block && token.typ == yaml_BLOCK_MAPPING_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_MAPPING_STYLE), + } + if parser.stem_comment != nil { + event.head_comment = parser.stem_comment + parser.stem_comment = nil + } + return true + } + if len(anchor) > 0 || len(tag) > 0 { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + quoted_implicit: false, + style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), + } + return true + } + + context := "while parsing a flow node" + if block { + context = "while parsing a block node" + } + yaml_parser_set_parser_error_context(parser, context, start_mark, + "did not find expected node content", token.start_mark) + return false +} + +// Parse the productions: +// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// ******************** *********** * ********* +// +func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + if token == nil { + return false + } + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_BLOCK_ENTRY_TOKEN { + mark := token.end_mark + prior_head_len := len(parser.head_comment) + skip_token(parser) + yaml_parser_split_stem_comment(parser, prior_head_len) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, true, false) + } else { + parser.state = yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + } + if token.typ == yaml_BLOCK_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + + skip_token(parser) + return true + } + + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a block collection", context_mark, + "did not find expected '-' indicator", token.start_mark) +} + +// Parse the productions: +// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +// *********** * +func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_BLOCK_ENTRY_TOKEN { + mark := token.end_mark + prior_head_len := len(parser.head_comment) + skip_token(parser) + yaml_parser_split_stem_comment(parser, prior_head_len) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_BLOCK_ENTRY_TOKEN && + token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, true, false) + } + parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.start_mark, // [Go] Shouldn't this be token.end_mark? + } + return true +} + +// Split stem comment from head comment. +// +// When a sequence or map is found under a sequence entry, the former head comment +// is assigned to the underlying sequence or map as a whole, not the individual +// sequence or map entry as would be expected otherwise. To handle this case the +// previous head comment is moved aside as the stem comment. +func yaml_parser_split_stem_comment(parser *yaml_parser_t, stem_len int) { + if stem_len == 0 { + return + } + + token := peek_token(parser) + if token == nil || token.typ != yaml_BLOCK_SEQUENCE_START_TOKEN && token.typ != yaml_BLOCK_MAPPING_START_TOKEN { + return + } + + parser.stem_comment = parser.head_comment[:stem_len] + if len(parser.head_comment) == stem_len { + parser.head_comment = nil + } else { + // Copy suffix to prevent very strange bugs if someone ever appends + // further bytes to the prefix in the stem_comment slice above. + parser.head_comment = append([]byte(nil), parser.head_comment[stem_len+1:]...) + } +} + +// Parse the productions: +// block_mapping ::= BLOCK-MAPPING_START +// ******************* +// ((KEY block_node_or_indentless_sequence?)? +// *** * +// (VALUE block_node_or_indentless_sequence?)?)* +// +// BLOCK-END +// ********* +// +func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + if token == nil { + return false + } + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + // [Go] A tail comment was left from the prior mapping value processed. Emit an event + // as it needs to be processed with that value and not the following key. + if len(parser.tail_comment) > 0 { + *event = yaml_event_t{ + typ: yaml_TAIL_COMMENT_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + foot_comment: parser.tail_comment, + } + parser.tail_comment = nil + return true + } + + if token.typ == yaml_KEY_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, true, true) + } else { + parser.state = yaml_PARSE_BLOCK_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + } else if token.typ == yaml_BLOCK_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + yaml_parser_set_event_comments(parser, event) + skip_token(parser) + return true + } + + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a block mapping", context_mark, + "did not find expected key", token.start_mark) +} + +// Parse the productions: +// block_mapping ::= BLOCK-MAPPING_START +// +// ((KEY block_node_or_indentless_sequence?)? +// +// (VALUE block_node_or_indentless_sequence?)?)* +// ***** * +// BLOCK-END +// +// +func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VALUE_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_KEY_STATE) + return yaml_parser_parse_node(parser, event, true, true) + } + parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Parse the productions: +// flow_sequence ::= FLOW-SEQUENCE-START +// ******************* +// (flow_sequence_entry FLOW-ENTRY)* +// * ********** +// flow_sequence_entry? +// * +// FLOW-SEQUENCE-END +// ***************** +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * +// +func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + if token == nil { + return false + } + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + if !first { + if token.typ == yaml_FLOW_ENTRY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } else { + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a flow sequence", context_mark, + "did not find expected ',' or ']'", token.start_mark) + } + } + + if token.typ == yaml_KEY_TOKEN { + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + implicit: true, + style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), + } + skip_token(parser) + return true + } else if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + yaml_parser_set_event_comments(parser, event) + + skip_token(parser) + return true +} + +// +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// *** * +// +func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_FLOW_ENTRY_TOKEN && + token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + mark := token.end_mark + skip_token(parser) + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) +} + +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// ***** * +// +func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VALUE_TOKEN { + skip_token(parser) + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * +// +func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.start_mark, // [Go] Shouldn't this be end_mark? + } + return true +} + +// Parse the productions: +// flow_mapping ::= FLOW-MAPPING-START +// ****************** +// (flow_mapping_entry FLOW-ENTRY)* +// * ********** +// flow_mapping_entry? +// ****************** +// FLOW-MAPPING-END +// **************** +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * *** * +// +func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ != yaml_FLOW_MAPPING_END_TOKEN { + if !first { + if token.typ == yaml_FLOW_ENTRY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } else { + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a flow mapping", context_mark, + "did not find expected ',' or '}'", token.start_mark) + } + } + + if token.typ == yaml_KEY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_FLOW_ENTRY_TOKEN && + token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } else { + parser.state = yaml_PARSE_FLOW_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) + } + } else if token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + yaml_parser_set_event_comments(parser, event) + skip_token(parser) + return true +} + +// Parse the productions: +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * ***** * +// +func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { + token := peek_token(parser) + if token == nil { + return false + } + if empty { + parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) + } + if token.typ == yaml_VALUE_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_KEY_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Generate an empty scalar event. +func yaml_parser_process_empty_scalar(parser *yaml_parser_t, event *yaml_event_t, mark yaml_mark_t) bool { + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: mark, + end_mark: mark, + value: nil, // Empty + implicit: true, + style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), + } + return true +} + +var default_tag_directives = []yaml_tag_directive_t{ + {[]byte("!"), []byte("!")}, + {[]byte("!!"), []byte("tag:yaml.org,2002:")}, +} + +// Parse directives. +func yaml_parser_process_directives(parser *yaml_parser_t, + version_directive_ref **yaml_version_directive_t, + tag_directives_ref *[]yaml_tag_directive_t) bool { + + var version_directive *yaml_version_directive_t + var tag_directives []yaml_tag_directive_t + + token := peek_token(parser) + if token == nil { + return false + } + + for token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN { + if token.typ == yaml_VERSION_DIRECTIVE_TOKEN { + if version_directive != nil { + yaml_parser_set_parser_error(parser, + "found duplicate %YAML directive", token.start_mark) + return false + } + if token.major != 1 || token.minor != 1 { + yaml_parser_set_parser_error(parser, + "found incompatible YAML document", token.start_mark) + return false + } + version_directive = &yaml_version_directive_t{ + major: token.major, + minor: token.minor, + } + } else if token.typ == yaml_TAG_DIRECTIVE_TOKEN { + value := yaml_tag_directive_t{ + handle: token.value, + prefix: token.prefix, + } + if !yaml_parser_append_tag_directive(parser, value, false, token.start_mark) { + return false + } + tag_directives = append(tag_directives, value) + } + + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + + for i := range default_tag_directives { + if !yaml_parser_append_tag_directive(parser, default_tag_directives[i], true, token.start_mark) { + return false + } + } + + if version_directive_ref != nil { + *version_directive_ref = version_directive + } + if tag_directives_ref != nil { + *tag_directives_ref = tag_directives + } + return true +} + +// Append a tag directive to the directives stack. +func yaml_parser_append_tag_directive(parser *yaml_parser_t, value yaml_tag_directive_t, allow_duplicates bool, mark yaml_mark_t) bool { + for i := range parser.tag_directives { + if bytes.Equal(value.handle, parser.tag_directives[i].handle) { + if allow_duplicates { + return true + } + return yaml_parser_set_parser_error(parser, "found duplicate %TAG directive", mark) + } + } + + // [Go] I suspect the copy is unnecessary. This was likely done + // because there was no way to track ownership of the data. + value_copy := yaml_tag_directive_t{ + handle: make([]byte, len(value.handle)), + prefix: make([]byte, len(value.prefix)), + } + copy(value_copy.handle, value.handle) + copy(value_copy.prefix, value.prefix) + parser.tag_directives = append(parser.tag_directives, value_copy) + return true +} diff --git a/vendor/gopkg.in/yaml.v3/readerc.go b/vendor/gopkg.in/yaml.v3/readerc.go new file mode 100644 index 00000000..b7de0a89 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/readerc.go @@ -0,0 +1,434 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +import ( + "io" +) + +// Set the reader error and return 0. +func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool { + parser.error = yaml_READER_ERROR + parser.problem = problem + parser.problem_offset = offset + parser.problem_value = value + return false +} + +// Byte order marks. +const ( + bom_UTF8 = "\xef\xbb\xbf" + bom_UTF16LE = "\xff\xfe" + bom_UTF16BE = "\xfe\xff" +) + +// Determine the input stream encoding by checking the BOM symbol. If no BOM is +// found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. +func yaml_parser_determine_encoding(parser *yaml_parser_t) bool { + // Ensure that we had enough bytes in the raw buffer. + for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 { + if !yaml_parser_update_raw_buffer(parser) { + return false + } + } + + // Determine the encoding. + buf := parser.raw_buffer + pos := parser.raw_buffer_pos + avail := len(buf) - pos + if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] { + parser.encoding = yaml_UTF16LE_ENCODING + parser.raw_buffer_pos += 2 + parser.offset += 2 + } else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] { + parser.encoding = yaml_UTF16BE_ENCODING + parser.raw_buffer_pos += 2 + parser.offset += 2 + } else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] { + parser.encoding = yaml_UTF8_ENCODING + parser.raw_buffer_pos += 3 + parser.offset += 3 + } else { + parser.encoding = yaml_UTF8_ENCODING + } + return true +} + +// Update the raw buffer. +func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool { + size_read := 0 + + // Return if the raw buffer is full. + if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) { + return true + } + + // Return on EOF. + if parser.eof { + return true + } + + // Move the remaining bytes in the raw buffer to the beginning. + if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) { + copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:]) + } + parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos] + parser.raw_buffer_pos = 0 + + // Call the read handler to fill the buffer. + size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)]) + parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read] + if err == io.EOF { + parser.eof = true + } else if err != nil { + return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1) + } + return true +} + +// Ensure that the buffer contains at least `length` characters. +// Return true on success, false on failure. +// +// The length is supposed to be significantly less that the buffer size. +func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { + if parser.read_handler == nil { + panic("read handler must be set") + } + + // [Go] This function was changed to guarantee the requested length size at EOF. + // The fact we need to do this is pretty awful, but the description above implies + // for that to be the case, and there are tests + + // If the EOF flag is set and the raw buffer is empty, do nothing. + if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { + // [Go] ACTUALLY! Read the documentation of this function above. + // This is just broken. To return true, we need to have the + // given length in the buffer. Not doing that means every single + // check that calls this function to make sure the buffer has a + // given length is Go) panicking; or C) accessing invalid memory. + //return true + } + + // Return if the buffer contains enough characters. + if parser.unread >= length { + return true + } + + // Determine the input encoding if it is not known yet. + if parser.encoding == yaml_ANY_ENCODING { + if !yaml_parser_determine_encoding(parser) { + return false + } + } + + // Move the unread characters to the beginning of the buffer. + buffer_len := len(parser.buffer) + if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len { + copy(parser.buffer, parser.buffer[parser.buffer_pos:]) + buffer_len -= parser.buffer_pos + parser.buffer_pos = 0 + } else if parser.buffer_pos == buffer_len { + buffer_len = 0 + parser.buffer_pos = 0 + } + + // Open the whole buffer for writing, and cut it before returning. + parser.buffer = parser.buffer[:cap(parser.buffer)] + + // Fill the buffer until it has enough characters. + first := true + for parser.unread < length { + + // Fill the raw buffer if necessary. + if !first || parser.raw_buffer_pos == len(parser.raw_buffer) { + if !yaml_parser_update_raw_buffer(parser) { + parser.buffer = parser.buffer[:buffer_len] + return false + } + } + first = false + + // Decode the raw buffer. + inner: + for parser.raw_buffer_pos != len(parser.raw_buffer) { + var value rune + var width int + + raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos + + // Decode the next character. + switch parser.encoding { + case yaml_UTF8_ENCODING: + // Decode a UTF-8 character. Check RFC 3629 + // (http://www.ietf.org/rfc/rfc3629.txt) for more details. + // + // The following table (taken from the RFC) is used for + // decoding. + // + // Char. number range | UTF-8 octet sequence + // (hexadecimal) | (binary) + // --------------------+------------------------------------ + // 0000 0000-0000 007F | 0xxxxxxx + // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx + // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx + // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + // + // Additionally, the characters in the range 0xD800-0xDFFF + // are prohibited as they are reserved for use with UTF-16 + // surrogate pairs. + + // Determine the length of the UTF-8 sequence. + octet := parser.raw_buffer[parser.raw_buffer_pos] + switch { + case octet&0x80 == 0x00: + width = 1 + case octet&0xE0 == 0xC0: + width = 2 + case octet&0xF0 == 0xE0: + width = 3 + case octet&0xF8 == 0xF0: + width = 4 + default: + // The leading octet is invalid. + return yaml_parser_set_reader_error(parser, + "invalid leading UTF-8 octet", + parser.offset, int(octet)) + } + + // Check if the raw buffer contains an incomplete character. + if width > raw_unread { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-8 octet sequence", + parser.offset, -1) + } + break inner + } + + // Decode the leading octet. + switch { + case octet&0x80 == 0x00: + value = rune(octet & 0x7F) + case octet&0xE0 == 0xC0: + value = rune(octet & 0x1F) + case octet&0xF0 == 0xE0: + value = rune(octet & 0x0F) + case octet&0xF8 == 0xF0: + value = rune(octet & 0x07) + default: + value = 0 + } + + // Check and decode the trailing octets. + for k := 1; k < width; k++ { + octet = parser.raw_buffer[parser.raw_buffer_pos+k] + + // Check if the octet is valid. + if (octet & 0xC0) != 0x80 { + return yaml_parser_set_reader_error(parser, + "invalid trailing UTF-8 octet", + parser.offset+k, int(octet)) + } + + // Decode the octet. + value = (value << 6) + rune(octet&0x3F) + } + + // Check the length of the sequence against the value. + switch { + case width == 1: + case width == 2 && value >= 0x80: + case width == 3 && value >= 0x800: + case width == 4 && value >= 0x10000: + default: + return yaml_parser_set_reader_error(parser, + "invalid length of a UTF-8 sequence", + parser.offset, -1) + } + + // Check the range of the value. + if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF { + return yaml_parser_set_reader_error(parser, + "invalid Unicode character", + parser.offset, int(value)) + } + + case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING: + var low, high int + if parser.encoding == yaml_UTF16LE_ENCODING { + low, high = 0, 1 + } else { + low, high = 1, 0 + } + + // The UTF-16 encoding is not as simple as one might + // naively think. Check RFC 2781 + // (http://www.ietf.org/rfc/rfc2781.txt). + // + // Normally, two subsequent bytes describe a Unicode + // character. However a special technique (called a + // surrogate pair) is used for specifying character + // values larger than 0xFFFF. + // + // A surrogate pair consists of two pseudo-characters: + // high surrogate area (0xD800-0xDBFF) + // low surrogate area (0xDC00-0xDFFF) + // + // The following formulas are used for decoding + // and encoding characters using surrogate pairs: + // + // U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) + // U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) + // W1 = 110110yyyyyyyyyy + // W2 = 110111xxxxxxxxxx + // + // where U is the character value, W1 is the high surrogate + // area, W2 is the low surrogate area. + + // Check for incomplete UTF-16 character. + if raw_unread < 2 { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-16 character", + parser.offset, -1) + } + break inner + } + + // Get the character. + value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) + + (rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8) + + // Check for unexpected low surrogate area. + if value&0xFC00 == 0xDC00 { + return yaml_parser_set_reader_error(parser, + "unexpected low surrogate area", + parser.offset, int(value)) + } + + // Check for a high surrogate area. + if value&0xFC00 == 0xD800 { + width = 4 + + // Check for incomplete surrogate pair. + if raw_unread < 4 { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-16 surrogate pair", + parser.offset, -1) + } + break inner + } + + // Get the next character. + value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) + + (rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8) + + // Check for a low surrogate area. + if value2&0xFC00 != 0xDC00 { + return yaml_parser_set_reader_error(parser, + "expected low surrogate area", + parser.offset+2, int(value2)) + } + + // Generate the value of the surrogate pair. + value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF) + } else { + width = 2 + } + + default: + panic("impossible") + } + + // Check if the character is in the allowed range: + // #x9 | #xA | #xD | [#x20-#x7E] (8 bit) + // | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) + // | [#x10000-#x10FFFF] (32 bit) + switch { + case value == 0x09: + case value == 0x0A: + case value == 0x0D: + case value >= 0x20 && value <= 0x7E: + case value == 0x85: + case value >= 0xA0 && value <= 0xD7FF: + case value >= 0xE000 && value <= 0xFFFD: + case value >= 0x10000 && value <= 0x10FFFF: + default: + return yaml_parser_set_reader_error(parser, + "control characters are not allowed", + parser.offset, int(value)) + } + + // Move the raw pointers. + parser.raw_buffer_pos += width + parser.offset += width + + // Finally put the character into the buffer. + if value <= 0x7F { + // 0000 0000-0000 007F . 0xxxxxxx + parser.buffer[buffer_len+0] = byte(value) + buffer_len += 1 + } else if value <= 0x7FF { + // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6)) + parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F)) + buffer_len += 2 + } else if value <= 0xFFFF { + // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12)) + parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F)) + parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F)) + buffer_len += 3 + } else { + // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18)) + parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F)) + parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F)) + parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F)) + buffer_len += 4 + } + + parser.unread++ + } + + // On EOF, put NUL into the buffer and return. + if parser.eof { + parser.buffer[buffer_len] = 0 + buffer_len++ + parser.unread++ + break + } + } + // [Go] Read the documentation of this function above. To return true, + // we need to have the given length in the buffer. Not doing that means + // every single check that calls this function to make sure the buffer + // has a given length is Go) panicking; or C) accessing invalid memory. + // This happens here due to the EOF above breaking early. + for buffer_len < length { + parser.buffer[buffer_len] = 0 + buffer_len++ + } + parser.buffer = parser.buffer[:buffer_len] + return true +} diff --git a/vendor/gopkg.in/yaml.v3/resolve.go b/vendor/gopkg.in/yaml.v3/resolve.go new file mode 100644 index 00000000..64ae8880 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/resolve.go @@ -0,0 +1,326 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yaml + +import ( + "encoding/base64" + "math" + "regexp" + "strconv" + "strings" + "time" +) + +type resolveMapItem struct { + value interface{} + tag string +} + +var resolveTable = make([]byte, 256) +var resolveMap = make(map[string]resolveMapItem) + +func init() { + t := resolveTable + t[int('+')] = 'S' // Sign + t[int('-')] = 'S' + for _, c := range "0123456789" { + t[int(c)] = 'D' // Digit + } + for _, c := range "yYnNtTfFoO~" { + t[int(c)] = 'M' // In map + } + t[int('.')] = '.' // Float (potentially in map) + + var resolveMapList = []struct { + v interface{} + tag string + l []string + }{ + {true, boolTag, []string{"true", "True", "TRUE"}}, + {false, boolTag, []string{"false", "False", "FALSE"}}, + {nil, nullTag, []string{"", "~", "null", "Null", "NULL"}}, + {math.NaN(), floatTag, []string{".nan", ".NaN", ".NAN"}}, + {math.Inf(+1), floatTag, []string{".inf", ".Inf", ".INF"}}, + {math.Inf(+1), floatTag, []string{"+.inf", "+.Inf", "+.INF"}}, + {math.Inf(-1), floatTag, []string{"-.inf", "-.Inf", "-.INF"}}, + {"<<", mergeTag, []string{"<<"}}, + } + + m := resolveMap + for _, item := range resolveMapList { + for _, s := range item.l { + m[s] = resolveMapItem{item.v, item.tag} + } + } +} + +const ( + nullTag = "!!null" + boolTag = "!!bool" + strTag = "!!str" + intTag = "!!int" + floatTag = "!!float" + timestampTag = "!!timestamp" + seqTag = "!!seq" + mapTag = "!!map" + binaryTag = "!!binary" + mergeTag = "!!merge" +) + +var longTags = make(map[string]string) +var shortTags = make(map[string]string) + +func init() { + for _, stag := range []string{nullTag, boolTag, strTag, intTag, floatTag, timestampTag, seqTag, mapTag, binaryTag, mergeTag} { + ltag := longTag(stag) + longTags[stag] = ltag + shortTags[ltag] = stag + } +} + +const longTagPrefix = "tag:yaml.org,2002:" + +func shortTag(tag string) string { + if strings.HasPrefix(tag, longTagPrefix) { + if stag, ok := shortTags[tag]; ok { + return stag + } + return "!!" + tag[len(longTagPrefix):] + } + return tag +} + +func longTag(tag string) string { + if strings.HasPrefix(tag, "!!") { + if ltag, ok := longTags[tag]; ok { + return ltag + } + return longTagPrefix + tag[2:] + } + return tag +} + +func resolvableTag(tag string) bool { + switch tag { + case "", strTag, boolTag, intTag, floatTag, nullTag, timestampTag: + return true + } + return false +} + +var yamlStyleFloat = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`) + +func resolve(tag string, in string) (rtag string, out interface{}) { + tag = shortTag(tag) + if !resolvableTag(tag) { + return tag, in + } + + defer func() { + switch tag { + case "", rtag, strTag, binaryTag: + return + case floatTag: + if rtag == intTag { + switch v := out.(type) { + case int64: + rtag = floatTag + out = float64(v) + return + case int: + rtag = floatTag + out = float64(v) + return + } + } + } + failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) + }() + + // Any data is accepted as a !!str or !!binary. + // Otherwise, the prefix is enough of a hint about what it might be. + hint := byte('N') + if in != "" { + hint = resolveTable[in[0]] + } + if hint != 0 && tag != strTag && tag != binaryTag { + // Handle things we can lookup in a map. + if item, ok := resolveMap[in]; ok { + return item.tag, item.value + } + + // Base 60 floats are a bad idea, were dropped in YAML 1.2, and + // are purposefully unsupported here. They're still quoted on + // the way out for compatibility with other parser, though. + + switch hint { + case 'M': + // We've already checked the map above. + + case '.': + // Not in the map, so maybe a normal float. + floatv, err := strconv.ParseFloat(in, 64) + if err == nil { + return floatTag, floatv + } + + case 'D', 'S': + // Int, float, or timestamp. + // Only try values as a timestamp if the value is unquoted or there's an explicit + // !!timestamp tag. + if tag == "" || tag == timestampTag { + t, ok := parseTimestamp(in) + if ok { + return timestampTag, t + } + } + + plain := strings.Replace(in, "_", "", -1) + intv, err := strconv.ParseInt(plain, 0, 64) + if err == nil { + if intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + uintv, err := strconv.ParseUint(plain, 0, 64) + if err == nil { + return intTag, uintv + } + if yamlStyleFloat.MatchString(plain) { + floatv, err := strconv.ParseFloat(plain, 64) + if err == nil { + return floatTag, floatv + } + } + if strings.HasPrefix(plain, "0b") { + intv, err := strconv.ParseInt(plain[2:], 2, 64) + if err == nil { + if intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + uintv, err := strconv.ParseUint(plain[2:], 2, 64) + if err == nil { + return intTag, uintv + } + } else if strings.HasPrefix(plain, "-0b") { + intv, err := strconv.ParseInt("-"+plain[3:], 2, 64) + if err == nil { + if true || intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + } + // Octals as introduced in version 1.2 of the spec. + // Octals from the 1.1 spec, spelled as 0777, are still + // decoded by default in v3 as well for compatibility. + // May be dropped in v4 depending on how usage evolves. + if strings.HasPrefix(plain, "0o") { + intv, err := strconv.ParseInt(plain[2:], 8, 64) + if err == nil { + if intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + uintv, err := strconv.ParseUint(plain[2:], 8, 64) + if err == nil { + return intTag, uintv + } + } else if strings.HasPrefix(plain, "-0o") { + intv, err := strconv.ParseInt("-"+plain[3:], 8, 64) + if err == nil { + if true || intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + } + default: + panic("internal error: missing handler for resolver table: " + string(rune(hint)) + " (with " + in + ")") + } + } + return strTag, in +} + +// encodeBase64 encodes s as base64 that is broken up into multiple lines +// as appropriate for the resulting length. +func encodeBase64(s string) string { + const lineLen = 70 + encLen := base64.StdEncoding.EncodedLen(len(s)) + lines := encLen/lineLen + 1 + buf := make([]byte, encLen*2+lines) + in := buf[0:encLen] + out := buf[encLen:] + base64.StdEncoding.Encode(in, []byte(s)) + k := 0 + for i := 0; i < len(in); i += lineLen { + j := i + lineLen + if j > len(in) { + j = len(in) + } + k += copy(out[k:], in[i:j]) + if lines > 1 { + out[k] = '\n' + k++ + } + } + return string(out[:k]) +} + +// This is a subset of the formats allowed by the regular expression +// defined at http://yaml.org/type/timestamp.html. +var allowedTimestampFormats = []string{ + "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. + "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". + "2006-1-2 15:4:5.999999999", // space separated with no time zone + "2006-1-2", // date only + // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" + // from the set of examples. +} + +// parseTimestamp parses s as a timestamp string and +// returns the timestamp and reports whether it succeeded. +// Timestamp formats are defined at http://yaml.org/type/timestamp.html +func parseTimestamp(s string) (time.Time, bool) { + // TODO write code to check all the formats supported by + // http://yaml.org/type/timestamp.html instead of using time.Parse. + + // Quick check: all date formats start with YYYY-. + i := 0 + for ; i < len(s); i++ { + if c := s[i]; c < '0' || c > '9' { + break + } + } + if i != 4 || i == len(s) || s[i] != '-' { + return time.Time{}, false + } + for _, format := range allowedTimestampFormats { + if t, err := time.Parse(format, s); err == nil { + return t, true + } + } + return time.Time{}, false +} diff --git a/vendor/gopkg.in/yaml.v3/scannerc.go b/vendor/gopkg.in/yaml.v3/scannerc.go new file mode 100644 index 00000000..ca007010 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/scannerc.go @@ -0,0 +1,3038 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +import ( + "bytes" + "fmt" +) + +// Introduction +// ************ +// +// The following notes assume that you are familiar with the YAML specification +// (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in +// some cases we are less restrictive that it requires. +// +// The process of transforming a YAML stream into a sequence of events is +// divided on two steps: Scanning and Parsing. +// +// The Scanner transforms the input stream into a sequence of tokens, while the +// parser transform the sequence of tokens produced by the Scanner into a +// sequence of parsing events. +// +// The Scanner is rather clever and complicated. The Parser, on the contrary, +// is a straightforward implementation of a recursive-descendant parser (or, +// LL(1) parser, as it is usually called). +// +// Actually there are two issues of Scanning that might be called "clever", the +// rest is quite straightforward. The issues are "block collection start" and +// "simple keys". Both issues are explained below in details. +// +// Here the Scanning step is explained and implemented. We start with the list +// of all the tokens produced by the Scanner together with short descriptions. +// +// Now, tokens: +// +// STREAM-START(encoding) # The stream start. +// STREAM-END # The stream end. +// VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. +// TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. +// DOCUMENT-START # '---' +// DOCUMENT-END # '...' +// BLOCK-SEQUENCE-START # Indentation increase denoting a block +// BLOCK-MAPPING-START # sequence or a block mapping. +// BLOCK-END # Indentation decrease. +// FLOW-SEQUENCE-START # '[' +// FLOW-SEQUENCE-END # ']' +// BLOCK-SEQUENCE-START # '{' +// BLOCK-SEQUENCE-END # '}' +// BLOCK-ENTRY # '-' +// FLOW-ENTRY # ',' +// KEY # '?' or nothing (simple keys). +// VALUE # ':' +// ALIAS(anchor) # '*anchor' +// ANCHOR(anchor) # '&anchor' +// TAG(handle,suffix) # '!handle!suffix' +// SCALAR(value,style) # A scalar. +// +// The following two tokens are "virtual" tokens denoting the beginning and the +// end of the stream: +// +// STREAM-START(encoding) +// STREAM-END +// +// We pass the information about the input stream encoding with the +// STREAM-START token. +// +// The next two tokens are responsible for tags: +// +// VERSION-DIRECTIVE(major,minor) +// TAG-DIRECTIVE(handle,prefix) +// +// Example: +// +// %YAML 1.1 +// %TAG ! !foo +// %TAG !yaml! tag:yaml.org,2002: +// --- +// +// The correspoding sequence of tokens: +// +// STREAM-START(utf-8) +// VERSION-DIRECTIVE(1,1) +// TAG-DIRECTIVE("!","!foo") +// TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") +// DOCUMENT-START +// STREAM-END +// +// Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole +// line. +// +// The document start and end indicators are represented by: +// +// DOCUMENT-START +// DOCUMENT-END +// +// Note that if a YAML stream contains an implicit document (without '---' +// and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be +// produced. +// +// In the following examples, we present whole documents together with the +// produced tokens. +// +// 1. An implicit document: +// +// 'a scalar' +// +// Tokens: +// +// STREAM-START(utf-8) +// SCALAR("a scalar",single-quoted) +// STREAM-END +// +// 2. An explicit document: +// +// --- +// 'a scalar' +// ... +// +// Tokens: +// +// STREAM-START(utf-8) +// DOCUMENT-START +// SCALAR("a scalar",single-quoted) +// DOCUMENT-END +// STREAM-END +// +// 3. Several documents in a stream: +// +// 'a scalar' +// --- +// 'another scalar' +// --- +// 'yet another scalar' +// +// Tokens: +// +// STREAM-START(utf-8) +// SCALAR("a scalar",single-quoted) +// DOCUMENT-START +// SCALAR("another scalar",single-quoted) +// DOCUMENT-START +// SCALAR("yet another scalar",single-quoted) +// STREAM-END +// +// We have already introduced the SCALAR token above. The following tokens are +// used to describe aliases, anchors, tag, and scalars: +// +// ALIAS(anchor) +// ANCHOR(anchor) +// TAG(handle,suffix) +// SCALAR(value,style) +// +// The following series of examples illustrate the usage of these tokens: +// +// 1. A recursive sequence: +// +// &A [ *A ] +// +// Tokens: +// +// STREAM-START(utf-8) +// ANCHOR("A") +// FLOW-SEQUENCE-START +// ALIAS("A") +// FLOW-SEQUENCE-END +// STREAM-END +// +// 2. A tagged scalar: +// +// !!float "3.14" # A good approximation. +// +// Tokens: +// +// STREAM-START(utf-8) +// TAG("!!","float") +// SCALAR("3.14",double-quoted) +// STREAM-END +// +// 3. Various scalar styles: +// +// --- # Implicit empty plain scalars do not produce tokens. +// --- a plain scalar +// --- 'a single-quoted scalar' +// --- "a double-quoted scalar" +// --- |- +// a literal scalar +// --- >- +// a folded +// scalar +// +// Tokens: +// +// STREAM-START(utf-8) +// DOCUMENT-START +// DOCUMENT-START +// SCALAR("a plain scalar",plain) +// DOCUMENT-START +// SCALAR("a single-quoted scalar",single-quoted) +// DOCUMENT-START +// SCALAR("a double-quoted scalar",double-quoted) +// DOCUMENT-START +// SCALAR("a literal scalar",literal) +// DOCUMENT-START +// SCALAR("a folded scalar",folded) +// STREAM-END +// +// Now it's time to review collection-related tokens. We will start with +// flow collections: +// +// FLOW-SEQUENCE-START +// FLOW-SEQUENCE-END +// FLOW-MAPPING-START +// FLOW-MAPPING-END +// FLOW-ENTRY +// KEY +// VALUE +// +// The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and +// FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' +// correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the +// indicators '?' and ':', which are used for denoting mapping keys and values, +// are represented by the KEY and VALUE tokens. +// +// The following examples show flow collections: +// +// 1. A flow sequence: +// +// [item 1, item 2, item 3] +// +// Tokens: +// +// STREAM-START(utf-8) +// FLOW-SEQUENCE-START +// SCALAR("item 1",plain) +// FLOW-ENTRY +// SCALAR("item 2",plain) +// FLOW-ENTRY +// SCALAR("item 3",plain) +// FLOW-SEQUENCE-END +// STREAM-END +// +// 2. A flow mapping: +// +// { +// a simple key: a value, # Note that the KEY token is produced. +// ? a complex key: another value, +// } +// +// Tokens: +// +// STREAM-START(utf-8) +// FLOW-MAPPING-START +// KEY +// SCALAR("a simple key",plain) +// VALUE +// SCALAR("a value",plain) +// FLOW-ENTRY +// KEY +// SCALAR("a complex key",plain) +// VALUE +// SCALAR("another value",plain) +// FLOW-ENTRY +// FLOW-MAPPING-END +// STREAM-END +// +// A simple key is a key which is not denoted by the '?' indicator. Note that +// the Scanner still produce the KEY token whenever it encounters a simple key. +// +// For scanning block collections, the following tokens are used (note that we +// repeat KEY and VALUE here): +// +// BLOCK-SEQUENCE-START +// BLOCK-MAPPING-START +// BLOCK-END +// BLOCK-ENTRY +// KEY +// VALUE +// +// The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation +// increase that precedes a block collection (cf. the INDENT token in Python). +// The token BLOCK-END denote indentation decrease that ends a block collection +// (cf. the DEDENT token in Python). However YAML has some syntax pecularities +// that makes detections of these tokens more complex. +// +// The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators +// '-', '?', and ':' correspondingly. +// +// The following examples show how the tokens BLOCK-SEQUENCE-START, +// BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: +// +// 1. Block sequences: +// +// - item 1 +// - item 2 +// - +// - item 3.1 +// - item 3.2 +// - +// key 1: value 1 +// key 2: value 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-ENTRY +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 3.1",plain) +// BLOCK-ENTRY +// SCALAR("item 3.2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// 2. Block mappings: +// +// a simple key: a value # The KEY token is produced here. +// ? a complex key +// : another value +// a mapping: +// key 1: value 1 +// key 2: value 2 +// a sequence: +// - item 1 +// - item 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("a simple key",plain) +// VALUE +// SCALAR("a value",plain) +// KEY +// SCALAR("a complex key",plain) +// VALUE +// SCALAR("another value",plain) +// KEY +// SCALAR("a mapping",plain) +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// KEY +// SCALAR("a sequence",plain) +// VALUE +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// YAML does not always require to start a new block collection from a new +// line. If the current line contains only '-', '?', and ':' indicators, a new +// block collection may start at the current line. The following examples +// illustrate this case: +// +// 1. Collections in a sequence: +// +// - - item 1 +// - item 2 +// - key 1: value 1 +// key 2: value 2 +// - ? complex key +// : complex value +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("complex key") +// VALUE +// SCALAR("complex value") +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// 2. Collections in a mapping: +// +// ? a sequence +// : - item 1 +// - item 2 +// ? a mapping +// : key 1: value 1 +// key 2: value 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("a sequence",plain) +// VALUE +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// KEY +// SCALAR("a mapping",plain) +// VALUE +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// YAML also permits non-indented sequences if they are included into a block +// mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: +// +// key: +// - item 1 # BLOCK-SEQUENCE-START is NOT produced here. +// - item 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("key",plain) +// VALUE +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// + +// Ensure that the buffer contains the required number of characters. +// Return true on success, false on failure (reader error or memory error). +func cache(parser *yaml_parser_t, length int) bool { + // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B) + return parser.unread >= length || yaml_parser_update_buffer(parser, length) +} + +// Advance the buffer pointer. +func skip(parser *yaml_parser_t) { + if !is_blank(parser.buffer, parser.buffer_pos) { + parser.newlines = 0 + } + parser.mark.index++ + parser.mark.column++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) +} + +func skip_line(parser *yaml_parser_t) { + if is_crlf(parser.buffer, parser.buffer_pos) { + parser.mark.index += 2 + parser.mark.column = 0 + parser.mark.line++ + parser.unread -= 2 + parser.buffer_pos += 2 + parser.newlines++ + } else if is_break(parser.buffer, parser.buffer_pos) { + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) + parser.newlines++ + } +} + +// Copy a character to a string buffer and advance pointers. +func read(parser *yaml_parser_t, s []byte) []byte { + if !is_blank(parser.buffer, parser.buffer_pos) { + parser.newlines = 0 + } + w := width(parser.buffer[parser.buffer_pos]) + if w == 0 { + panic("invalid character sequence") + } + if len(s) == 0 { + s = make([]byte, 0, 32) + } + if w == 1 && len(s)+w <= cap(s) { + s = s[:len(s)+1] + s[len(s)-1] = parser.buffer[parser.buffer_pos] + parser.buffer_pos++ + } else { + s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...) + parser.buffer_pos += w + } + parser.mark.index++ + parser.mark.column++ + parser.unread-- + return s +} + +// Copy a line break character to a string buffer and advance pointers. +func read_line(parser *yaml_parser_t, s []byte) []byte { + buf := parser.buffer + pos := parser.buffer_pos + switch { + case buf[pos] == '\r' && buf[pos+1] == '\n': + // CR LF . LF + s = append(s, '\n') + parser.buffer_pos += 2 + parser.mark.index++ + parser.unread-- + case buf[pos] == '\r' || buf[pos] == '\n': + // CR|LF . LF + s = append(s, '\n') + parser.buffer_pos += 1 + case buf[pos] == '\xC2' && buf[pos+1] == '\x85': + // NEL . LF + s = append(s, '\n') + parser.buffer_pos += 2 + case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'): + // LS|PS . LS|PS + s = append(s, buf[parser.buffer_pos:pos+3]...) + parser.buffer_pos += 3 + default: + return s + } + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + parser.newlines++ + return s +} + +// Get the next token. +func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool { + // Erase the token object. + *token = yaml_token_t{} // [Go] Is this necessary? + + // No tokens after STREAM-END or error. + if parser.stream_end_produced || parser.error != yaml_NO_ERROR { + return true + } + + // Ensure that the tokens queue contains enough tokens. + if !parser.token_available { + if !yaml_parser_fetch_more_tokens(parser) { + return false + } + } + + // Fetch the next token from the queue. + *token = parser.tokens[parser.tokens_head] + parser.tokens_head++ + parser.tokens_parsed++ + parser.token_available = false + + if token.typ == yaml_STREAM_END_TOKEN { + parser.stream_end_produced = true + } + return true +} + +// Set the scanner error and return false. +func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool { + parser.error = yaml_SCANNER_ERROR + parser.context = context + parser.context_mark = context_mark + parser.problem = problem + parser.problem_mark = parser.mark + return false +} + +func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool { + context := "while parsing a tag" + if directive { + context = "while parsing a %TAG directive" + } + return yaml_parser_set_scanner_error(parser, context, context_mark, problem) +} + +func trace(args ...interface{}) func() { + pargs := append([]interface{}{"+++"}, args...) + fmt.Println(pargs...) + pargs = append([]interface{}{"---"}, args...) + return func() { fmt.Println(pargs...) } +} + +// Ensure that the tokens queue contains at least one token which can be +// returned to the Parser. +func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { + // While we need more tokens to fetch, do it. + for { + // [Go] The comment parsing logic requires a lookahead of two tokens + // so that foot comments may be parsed in time of associating them + // with the tokens that are parsed before them, and also for line + // comments to be transformed into head comments in some edge cases. + if parser.tokens_head < len(parser.tokens)-2 { + // If a potential simple key is at the head position, we need to fetch + // the next token to disambiguate it. + head_tok_idx, ok := parser.simple_keys_by_tok[parser.tokens_parsed] + if !ok { + break + } else if valid, ok := yaml_simple_key_is_valid(parser, &parser.simple_keys[head_tok_idx]); !ok { + return false + } else if !valid { + break + } + } + // Fetch the next token. + if !yaml_parser_fetch_next_token(parser) { + return false + } + } + + parser.token_available = true + return true +} + +// The dispatcher for token fetchers. +func yaml_parser_fetch_next_token(parser *yaml_parser_t) (ok bool) { + // Ensure that the buffer is initialized. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check if we just started scanning. Fetch STREAM-START then. + if !parser.stream_start_produced { + return yaml_parser_fetch_stream_start(parser) + } + + scan_mark := parser.mark + + // Eat whitespaces and comments until we reach the next token. + if !yaml_parser_scan_to_next_token(parser) { + return false + } + + // [Go] While unrolling indents, transform the head comments of prior + // indentation levels observed after scan_start into foot comments at + // the respective indexes. + + // Check the indentation level against the current column. + if !yaml_parser_unroll_indent(parser, parser.mark.column, scan_mark) { + return false + } + + // Ensure that the buffer contains at least 4 characters. 4 is the length + // of the longest indicators ('--- ' and '... '). + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + + // Is it the end of the stream? + if is_z(parser.buffer, parser.buffer_pos) { + return yaml_parser_fetch_stream_end(parser) + } + + // Is it a directive? + if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' { + return yaml_parser_fetch_directive(parser) + } + + buf := parser.buffer + pos := parser.buffer_pos + + // Is it the document start indicator? + if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN) + } + + // Is it the document end indicator? + if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) + } + + comment_mark := parser.mark + if len(parser.tokens) > 0 && (parser.flow_level == 0 && buf[pos] == ':' || parser.flow_level > 0 && buf[pos] == ',') { + // Associate any following comments with the prior token. + comment_mark = parser.tokens[len(parser.tokens)-1].start_mark + } + defer func() { + if !ok { + return + } + if len(parser.tokens) > 0 && parser.tokens[len(parser.tokens)-1].typ == yaml_BLOCK_ENTRY_TOKEN { + // Sequence indicators alone have no line comments. It becomes + // a head comment for whatever follows. + return + } + if !yaml_parser_scan_line_comment(parser, comment_mark) { + ok = false + return + } + }() + + // Is it the flow sequence start indicator? + if buf[pos] == '[' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) + } + + // Is it the flow mapping start indicator? + if parser.buffer[parser.buffer_pos] == '{' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) + } + + // Is it the flow sequence end indicator? + if parser.buffer[parser.buffer_pos] == ']' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_SEQUENCE_END_TOKEN) + } + + // Is it the flow mapping end indicator? + if parser.buffer[parser.buffer_pos] == '}' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_MAPPING_END_TOKEN) + } + + // Is it the flow entry indicator? + if parser.buffer[parser.buffer_pos] == ',' { + return yaml_parser_fetch_flow_entry(parser) + } + + // Is it the block entry indicator? + if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) { + return yaml_parser_fetch_block_entry(parser) + } + + // Is it the key indicator? + if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_key(parser) + } + + // Is it the value indicator? + if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_value(parser) + } + + // Is it an alias? + if parser.buffer[parser.buffer_pos] == '*' { + return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) + } + + // Is it an anchor? + if parser.buffer[parser.buffer_pos] == '&' { + return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) + } + + // Is it a tag? + if parser.buffer[parser.buffer_pos] == '!' { + return yaml_parser_fetch_tag(parser) + } + + // Is it a literal scalar? + if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, true) + } + + // Is it a folded scalar? + if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, false) + } + + // Is it a single-quoted scalar? + if parser.buffer[parser.buffer_pos] == '\'' { + return yaml_parser_fetch_flow_scalar(parser, true) + } + + // Is it a double-quoted scalar? + if parser.buffer[parser.buffer_pos] == '"' { + return yaml_parser_fetch_flow_scalar(parser, false) + } + + // Is it a plain scalar? + // + // A plain scalar may start with any non-blank characters except + // + // '-', '?', ':', ',', '[', ']', '{', '}', + // '#', '&', '*', '!', '|', '>', '\'', '\"', + // '%', '@', '`'. + // + // In the block context (and, for the '-' indicator, in the flow context + // too), it may also start with the characters + // + // '-', '?', ':' + // + // if it is followed by a non-space character. + // + // The last rule is more restrictive than the specification requires. + // [Go] TODO Make this logic more reasonable. + //switch parser.buffer[parser.buffer_pos] { + //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': + //} + if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' || + parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' || + parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') || + (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level == 0 && + (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') && + !is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_plain_scalar(parser) + } + + // If we don't determine the token type so far, it is an error. + return yaml_parser_set_scanner_error(parser, + "while scanning for the next token", parser.mark, + "found character that cannot start any token") +} + +func yaml_simple_key_is_valid(parser *yaml_parser_t, simple_key *yaml_simple_key_t) (valid, ok bool) { + if !simple_key.possible { + return false, true + } + + // The 1.2 specification says: + // + // "If the ? indicator is omitted, parsing needs to see past the + // implicit key to recognize it as such. To limit the amount of + // lookahead required, the “:” indicator must appear at most 1024 + // Unicode characters beyond the start of the key. In addition, the key + // is restricted to a single line." + // + if simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index { + // Check if the potential simple key to be removed is required. + if simple_key.required { + return false, yaml_parser_set_scanner_error(parser, + "while scanning a simple key", simple_key.mark, + "could not find expected ':'") + } + simple_key.possible = false + return false, true + } + return true, true +} + +// Check if a simple key may start at the current position and add it if +// needed. +func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { + // A simple key is required at the current position if the scanner is in + // the block context and the current column coincides with the indentation + // level. + + required := parser.flow_level == 0 && parser.indent == parser.mark.column + + // + // If the current position may start a simple key, save it. + // + if parser.simple_key_allowed { + simple_key := yaml_simple_key_t{ + possible: true, + required: required, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + mark: parser.mark, + } + + if !yaml_parser_remove_simple_key(parser) { + return false + } + parser.simple_keys[len(parser.simple_keys)-1] = simple_key + parser.simple_keys_by_tok[simple_key.token_number] = len(parser.simple_keys) - 1 + } + return true +} + +// Remove a potential simple key at the current flow level. +func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { + i := len(parser.simple_keys) - 1 + if parser.simple_keys[i].possible { + // If the key is required, it is an error. + if parser.simple_keys[i].required { + return yaml_parser_set_scanner_error(parser, + "while scanning a simple key", parser.simple_keys[i].mark, + "could not find expected ':'") + } + // Remove the key from the stack. + parser.simple_keys[i].possible = false + delete(parser.simple_keys_by_tok, parser.simple_keys[i].token_number) + } + return true +} + +// max_flow_level limits the flow_level +const max_flow_level = 10000 + +// Increase the flow level and resize the simple key list if needed. +func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { + // Reset the simple key on the next level. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{ + possible: false, + required: false, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + mark: parser.mark, + }) + + // Increase the flow level. + parser.flow_level++ + if parser.flow_level > max_flow_level { + return yaml_parser_set_scanner_error(parser, + "while increasing flow level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_flow_level)) + } + return true +} + +// Decrease the flow level. +func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { + if parser.flow_level > 0 { + parser.flow_level-- + last := len(parser.simple_keys) - 1 + delete(parser.simple_keys_by_tok, parser.simple_keys[last].token_number) + parser.simple_keys = parser.simple_keys[:last] + } + return true +} + +// max_indents limits the indents stack size +const max_indents = 10000 + +// Push the current indentation level to the stack and set the new level +// the current column is greater than the indentation level. In this case, +// append or insert the specified token into the token queue. +func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } + + if parser.indent < column { + // Push the current indentation level to the stack and set the new + // indentation level. + parser.indents = append(parser.indents, parser.indent) + parser.indent = column + if len(parser.indents) > max_indents { + return yaml_parser_set_scanner_error(parser, + "while increasing indent level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_indents)) + } + + // Create a token and insert it into the queue. + token := yaml_token_t{ + typ: typ, + start_mark: mark, + end_mark: mark, + } + if number > -1 { + number -= parser.tokens_parsed + } + yaml_insert_token(parser, number, &token) + } + return true +} + +// Pop indentation levels from the indents stack until the current level +// becomes less or equal to the column. For each indentation level, append +// the BLOCK-END token. +func yaml_parser_unroll_indent(parser *yaml_parser_t, column int, scan_mark yaml_mark_t) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } + + block_mark := scan_mark + block_mark.index-- + + // Loop through the indentation levels in the stack. + for parser.indent > column { + + // [Go] Reposition the end token before potential following + // foot comments of parent blocks. For that, search + // backwards for recent comments that were at the same + // indent as the block that is ending now. + stop_index := block_mark.index + for i := len(parser.comments) - 1; i >= 0; i-- { + comment := &parser.comments[i] + + if comment.end_mark.index < stop_index { + // Don't go back beyond the start of the comment/whitespace scan, unless column < 0. + // If requested indent column is < 0, then the document is over and everything else + // is a foot anyway. + break + } + if comment.start_mark.column == parser.indent+1 { + // This is a good match. But maybe there's a former comment + // at that same indent level, so keep searching. + block_mark = comment.start_mark + } + + // While the end of the former comment matches with + // the start of the following one, we know there's + // nothing in between and scanning is still safe. + stop_index = comment.scan_mark.index + } + + // Create a token and append it to the queue. + token := yaml_token_t{ + typ: yaml_BLOCK_END_TOKEN, + start_mark: block_mark, + end_mark: block_mark, + } + yaml_insert_token(parser, -1, &token) + + // Pop the indentation level. + parser.indent = parser.indents[len(parser.indents)-1] + parser.indents = parser.indents[:len(parser.indents)-1] + } + return true +} + +// Initialize the scanner and produce the STREAM-START token. +func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { + + // Set the initial indentation. + parser.indent = -1 + + // Initialize the simple key stack. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) + + parser.simple_keys_by_tok = make(map[int]int) + + // A simple key is allowed at the beginning of the stream. + parser.simple_key_allowed = true + + // We have started. + parser.stream_start_produced = true + + // Create the STREAM-START token and append it to the queue. + token := yaml_token_t{ + typ: yaml_STREAM_START_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + encoding: parser.encoding, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the STREAM-END token and shut down the scanner. +func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { + + // Force new line. + if parser.mark.column != 0 { + parser.mark.column = 0 + parser.mark.line++ + } + + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1, parser.mark) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Create the STREAM-END token and append it to the queue. + token := yaml_token_t{ + typ: yaml_STREAM_END_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. +func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1, parser.mark) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. + token := yaml_token_t{} + if !yaml_parser_scan_directive(parser, &token) { + return false + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the DOCUMENT-START or DOCUMENT-END token. +func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1, parser.mark) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Consume the token. + start_mark := parser.mark + + skip(parser) + skip(parser) + skip(parser) + + end_mark := parser.mark + + // Create the DOCUMENT-START or DOCUMENT-END token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. +func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { + + // The indicators '[' and '{' may start a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // Increase the flow level. + if !yaml_parser_increase_flow_level(parser) { + return false + } + + // A simple key may follow the indicators '[' and '{'. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. +func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset any potential simple key on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Decrease the flow level. + if !yaml_parser_decrease_flow_level(parser) { + return false + } + + // No simple keys after the indicators ']' and '}'. + parser.simple_key_allowed = false + + // Consume the token. + + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-ENTRY token. +func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool { + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after ','. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-ENTRY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_FLOW_ENTRY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the BLOCK-ENTRY token. +func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { + // Check if the scanner is in the block context. + if parser.flow_level == 0 { + // Check if we are allowed to start a new entry. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "block sequence entries are not allowed in this context") + } + // Add the BLOCK-SEQUENCE-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) { + return false + } + } else { + // It is an error for the '-' indicator to occur in the flow context, + // but we let the Parser detect and report about it because the Parser + // is able to point to the context. + } + + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after '-'. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the BLOCK-ENTRY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_BLOCK_ENTRY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the KEY token. +func yaml_parser_fetch_key(parser *yaml_parser_t) bool { + + // In the block context, additional checks are required. + if parser.flow_level == 0 { + // Check if we are allowed to start a new key (not nessesary simple). + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping keys are not allowed in this context") + } + // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } + + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after '?' in the block context. + parser.simple_key_allowed = parser.flow_level == 0 + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the KEY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_KEY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the VALUE token. +func yaml_parser_fetch_value(parser *yaml_parser_t) bool { + + simple_key := &parser.simple_keys[len(parser.simple_keys)-1] + + // Have we found a simple key? + if valid, ok := yaml_simple_key_is_valid(parser, simple_key); !ok { + return false + + } else if valid { + + // Create the KEY token and insert it into the queue. + token := yaml_token_t{ + typ: yaml_KEY_TOKEN, + start_mark: simple_key.mark, + end_mark: simple_key.mark, + } + yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token) + + // In the block context, we may need to add the BLOCK-MAPPING-START token. + if !yaml_parser_roll_indent(parser, simple_key.mark.column, + simple_key.token_number, + yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) { + return false + } + + // Remove the simple key. + simple_key.possible = false + delete(parser.simple_keys_by_tok, simple_key.token_number) + + // A simple key cannot follow another simple key. + parser.simple_key_allowed = false + + } else { + // The ':' indicator follows a complex key. + + // In the block context, extra checks are required. + if parser.flow_level == 0 { + + // Check if we are allowed to start a complex value. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping values are not allowed in this context") + } + + // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } + + // Simple keys after ':' are allowed in the block context. + parser.simple_key_allowed = parser.flow_level == 0 + } + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the VALUE token and append it to the queue. + token := yaml_token_t{ + typ: yaml_VALUE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the ALIAS or ANCHOR token. +func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // An anchor or an alias could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow an anchor or an alias. + parser.simple_key_allowed = false + + // Create the ALIAS or ANCHOR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_anchor(parser, &token, typ) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the TAG token. +func yaml_parser_fetch_tag(parser *yaml_parser_t) bool { + // A tag could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a tag. + parser.simple_key_allowed = false + + // Create the TAG token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_tag(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. +func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool { + // Remove any potential simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // A simple key may follow a block scalar. + parser.simple_key_allowed = true + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_block_scalar(parser, &token, literal) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. +func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_flow_scalar(parser, &token, single) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,plain) token. +func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_plain_scalar(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Eat whitespaces and comments until the next token is found. +func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { + + scan_mark := parser.mark + + // Until the next token is not found. + for { + // Allow the BOM mark to start a line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) { + skip(parser) + } + + // Eat whitespaces. + // Tabs are allowed: + // - in the flow context + // - in the block context, but not at the beginning of the line or + // after '-', '?', or ':' (complex value). + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if we just had a line comment under a sequence entry that + // looks more like a header to the following content. Similar to this: + // + // - # The comment + // - Some data + // + // If so, transform the line comment to a head comment and reposition. + if len(parser.comments) > 0 && len(parser.tokens) > 1 { + tokenA := parser.tokens[len(parser.tokens)-2] + tokenB := parser.tokens[len(parser.tokens)-1] + comment := &parser.comments[len(parser.comments)-1] + if tokenA.typ == yaml_BLOCK_SEQUENCE_START_TOKEN && tokenB.typ == yaml_BLOCK_ENTRY_TOKEN && len(comment.line) > 0 && !is_break(parser.buffer, parser.buffer_pos) { + // If it was in the prior line, reposition so it becomes a + // header of the follow up token. Otherwise, keep it in place + // so it becomes a header of the former. + comment.head = comment.line + comment.line = nil + if comment.start_mark.line == parser.mark.line-1 { + comment.token_mark = parser.mark + } + } + } + + // Eat a comment until a line break. + if parser.buffer[parser.buffer_pos] == '#' { + if !yaml_parser_scan_comments(parser, scan_mark) { + return false + } + } + + // If it is a line break, eat it. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + + // In the block context, a new line may start a simple key. + if parser.flow_level == 0 { + parser.simple_key_allowed = true + } + } else { + break // We have found a token. + } + } + + return true +} + +// Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// +func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { + // Eat '%'. + start_mark := parser.mark + skip(parser) + + // Scan the directive name. + var name []byte + if !yaml_parser_scan_directive_name(parser, start_mark, &name) { + return false + } + + // Is it a YAML directive? + if bytes.Equal(name, []byte("YAML")) { + // Scan the VERSION directive value. + var major, minor int8 + if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) { + return false + } + end_mark := parser.mark + + // Create a VERSION-DIRECTIVE token. + *token = yaml_token_t{ + typ: yaml_VERSION_DIRECTIVE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + major: major, + minor: minor, + } + + // Is it a TAG directive? + } else if bytes.Equal(name, []byte("TAG")) { + // Scan the TAG directive value. + var handle, prefix []byte + if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) { + return false + } + end_mark := parser.mark + + // Create a TAG-DIRECTIVE token. + *token = yaml_token_t{ + typ: yaml_TAG_DIRECTIVE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: handle, + prefix: prefix, + } + + // Unknown directive. + } else { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unknown directive name") + return false + } + + // Eat the rest of the line including any comments. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + if parser.buffer[parser.buffer_pos] == '#' { + // [Go] Discard this inline comment for the time being. + //if !yaml_parser_scan_line_comment(parser, start_mark) { + // return false + //} + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "did not find expected comment or line break") + return false + } + + // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } + + return true +} + +// Scan the directive name. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^ +// +func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { + // Consume the directive name. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + var s []byte + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the name is empty. + if len(s) == 0 { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "could not find expected directive name") + return false + } + + // Check for an blank character after the name. + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unexpected non-alphabetical character") + return false + } + *name = s + return true +} + +// Scan the value of VERSION-DIRECTIVE. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^^^ +func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { + // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Consume the major version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, major) { + return false + } + + // Eat '.'. + if parser.buffer[parser.buffer_pos] != '.' { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected digit or '.' character") + } + + skip(parser) + + // Consume the minor version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) { + return false + } + return true +} + +const max_number_length = 2 + +// Scan the version number of VERSION-DIRECTIVE. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^ +// %YAML 1.1 # a comment \n +// ^ +func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { + + // Repeat while the next character is digit. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var value, length int8 + for is_digit(parser.buffer, parser.buffer_pos) { + // Check if the number is too long. + length++ + if length > max_number_length { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "found extremely long version number") + } + value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos)) + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the number was present. + if length == 0 { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected version number") + } + *number = value + return true +} + +// Scan the value of a TAG-DIRECTIVE token. +// +// Scope: +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// +func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { + var handle_value, prefix_value []byte + + // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Scan a handle. + if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { + return false + } + + // Expect a whitespace. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blank(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace") + return false + } + + // Eat whitespaces. + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Scan a prefix. + if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { + return false + } + + // Expect a whitespace or line break. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace or line break") + return false + } + + *handle = handle_value + *prefix = prefix_value + return true +} + +func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool { + var s []byte + + // Eat the indicator character. + start_mark := parser.mark + skip(parser) + + // Consume the value. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + end_mark := parser.mark + + /* + * Check if length of the anchor is greater than 0 and it is followed by + * a whitespace character or one of the indicators: + * + * '?', ':', ',', ']', '}', '%', '@', '`'. + */ + + if len(s) == 0 || + !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' || + parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '`') { + context := "while scanning an alias" + if typ == yaml_ANCHOR_TOKEN { + context = "while scanning an anchor" + } + yaml_parser_set_scanner_error(parser, context, start_mark, + "did not find expected alphabetic or numeric character") + return false + } + + // Create a token. + *token = yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + value: s, + } + + return true +} + +/* + * Scan a TAG token. + */ + +func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool { + var handle, suffix []byte + + start_mark := parser.mark + + // Check if the tag is in the canonical form. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + if parser.buffer[parser.buffer_pos+1] == '<' { + // Keep the handle as '' + + // Eat '!<' + skip(parser) + skip(parser) + + // Consume the tag value. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } + + // Check for '>' and eat it. + if parser.buffer[parser.buffer_pos] != '>' { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find the expected '>'") + return false + } + + skip(parser) + } else { + // The tag has either the '!suffix' or the '!handle!suffix' form. + + // First, try to scan a handle. + if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) { + return false + } + + // Check if it is, indeed, handle. + if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' { + // Scan the suffix now. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } + } else { + // It wasn't a handle after all. Scan the rest of the tag. + if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) { + return false + } + + // Set the handle to '!'. + handle = []byte{'!'} + + // A special case: the '!' tag. Set the handle to '' and the + // suffix to '!'. + if len(suffix) == 0 { + handle, suffix = suffix, handle + } + } + } + + // Check the character which ends the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find expected whitespace or line break") + return false + } + + end_mark := parser.mark + + // Create a token. + *token = yaml_token_t{ + typ: yaml_TAG_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: handle, + suffix: suffix, + } + return true +} + +// Scan a tag handle. +func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool { + // Check the initial '!' character. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] != '!' { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } + + var s []byte + + // Copy the '!' character. + s = read(parser, s) + + // Copy all subsequent alphabetical and numerical characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the trailing character is '!' and copy it. + if parser.buffer[parser.buffer_pos] == '!' { + s = read(parser, s) + } else { + // It's either the '!' tag or not really a tag handle. If it's a %TAG + // directive, it's an error. If it's a tag token, it must be a part of URI. + if directive && string(s) != "!" { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } + } + + *handle = s + return true +} + +// Scan a tag. +func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { + //size_t length = head ? strlen((char *)head) : 0 + var s []byte + hasTag := len(head) > 0 + + // Copy the head if needed. + // + // Note that we don't copy the leading '!' character. + if len(head) > 1 { + s = append(s, head[1:]...) + } + + // Scan the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // The set of characters that may appear in URI is as follows: + // + // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', + // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', + // '%'. + // [Go] TODO Convert this into more reasonable logic. + for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || + parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' || + parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' || + parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' || + parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || + parser.buffer[parser.buffer_pos] == '%' { + // Check if it is a URI-escape sequence. + if parser.buffer[parser.buffer_pos] == '%' { + if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { + return false + } + } else { + s = read(parser, s) + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + hasTag = true + } + + if !hasTag { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected tag URI") + return false + } + *uri = s + return true +} + +// Decode an URI-escape sequence corresponding to a single UTF-8 character. +func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { + + // Decode the required number of characters. + w := 1024 + for w > 0 { + // Check for a URI-escaped octet. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } + + if !(parser.buffer[parser.buffer_pos] == '%' && + is_hex(parser.buffer, parser.buffer_pos+1) && + is_hex(parser.buffer, parser.buffer_pos+2)) { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find URI escaped octet") + } + + // Get the octet. + octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2)) + + // If it is the leading octet, determine the length of the UTF-8 sequence. + if w == 1024 { + w = width(octet) + if w == 0 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect leading UTF-8 octet") + } + } else { + // Check if the trailing octet is correct. + if octet&0xC0 != 0x80 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect trailing UTF-8 octet") + } + } + + // Copy the octet and move the pointers. + *s = append(*s, octet) + skip(parser) + skip(parser) + skip(parser) + w-- + } + return true +} + +// Scan a block scalar. +func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool { + // Eat the indicator '|' or '>'. + start_mark := parser.mark + skip(parser) + + // Scan the additional block scalar indicators. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check for a chomping indicator. + var chomping, increment int + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + // Set the chomping method and eat the indicator. + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) + + // Check for an indentation indicator. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_digit(parser.buffer, parser.buffer_pos) { + // Check that the indentation is greater than 0. + if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } + + // Get the indentation level and eat the indicator. + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) + } + + } else if is_digit(parser.buffer, parser.buffer_pos) { + // Do the same as above, but in the opposite order. + + if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) + + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) + } + } + + // Eat whitespaces and comments to the end of the line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.buffer[parser.buffer_pos] == '#' { + if !yaml_parser_scan_line_comment(parser, start_mark) { + return false + } + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "did not find expected comment or line break") + return false + } + + // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } + + end_mark := parser.mark + + // Set the indentation level if it was specified. + var indent int + if increment > 0 { + if parser.indent >= 0 { + indent = parser.indent + increment + } else { + indent = increment + } + } + + // Scan the leading line breaks and determine the indentation level if needed. + var s, leading_break, trailing_breaks []byte + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } + + // Scan the block scalar content. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var leading_blank, trailing_blank bool + for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) { + // We are at the beginning of a non-empty line. + + // Is it a trailing whitespace? + trailing_blank = is_blank(parser.buffer, parser.buffer_pos) + + // Check if we need to fold the leading line break. + if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' { + // Do we need to join the lines by space? + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } + } else { + s = append(s, leading_break...) + } + leading_break = leading_break[:0] + + // Append the remaining line breaks. + s = append(s, trailing_breaks...) + trailing_breaks = trailing_breaks[:0] + + // Is it a leading whitespace? + leading_blank = is_blank(parser.buffer, parser.buffer_pos) + + // Consume the current line. + for !is_breakz(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + leading_break = read_line(parser, leading_break) + + // Eat the following indentation spaces and line breaks. + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } + } + + // Chomp the tail. + if chomping != -1 { + s = append(s, leading_break...) + } + if chomping == 1 { + s = append(s, trailing_breaks...) + } + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_LITERAL_SCALAR_STYLE, + } + if !literal { + token.style = yaml_FOLDED_SCALAR_STYLE + } + return true +} + +// Scan indentation spaces and line breaks for a block scalar. Determine the +// indentation level if needed. +func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool { + *end_mark = parser.mark + + // Eat the indentation spaces and line breaks. + max_indent := 0 + for { + // Eat the indentation spaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.mark.column > max_indent { + max_indent = parser.mark.column + } + + // Check for a tab character messing the indentation. + if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) { + return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found a tab character where an indentation space is expected") + } + + // Have we found a non-empty line? + if !is_break(parser.buffer, parser.buffer_pos) { + break + } + + // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + // [Go] Should really be returning breaks instead. + *breaks = read_line(parser, *breaks) + *end_mark = parser.mark + } + + // Determine the indentation level if needed. + if *indent == 0 { + *indent = max_indent + if *indent < parser.indent+1 { + *indent = parser.indent + 1 + } + if *indent < 1 { + *indent = 1 + } + } + return true +} + +// Scan a quoted scalar. +func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool { + // Eat the left quote. + start_mark := parser.mark + skip(parser) + + // Consume the content of the quoted scalar. + var s, leading_break, trailing_breaks, whitespaces []byte + for { + // Check that there are no document indicators at the beginning of the line. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + + if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected document indicator") + return false + } + + // Check for EOF. + if is_z(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected end of stream") + return false + } + + // Consume non-blank characters. + leading_blanks := false + for !is_blankz(parser.buffer, parser.buffer_pos) { + if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' { + // Is is an escaped single quote. + s = append(s, '\'') + skip(parser) + skip(parser) + + } else if single && parser.buffer[parser.buffer_pos] == '\'' { + // It is a right single quote. + break + } else if !single && parser.buffer[parser.buffer_pos] == '"' { + // It is a right double quote. + break + + } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { + // It is an escaped line break. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } + skip(parser) + skip_line(parser) + leading_blanks = true + break + + } else if !single && parser.buffer[parser.buffer_pos] == '\\' { + // It is an escape sequence. + code_length := 0 + + // Check the escape character. + switch parser.buffer[parser.buffer_pos+1] { + case '0': + s = append(s, 0) + case 'a': + s = append(s, '\x07') + case 'b': + s = append(s, '\x08') + case 't', '\t': + s = append(s, '\x09') + case 'n': + s = append(s, '\x0A') + case 'v': + s = append(s, '\x0B') + case 'f': + s = append(s, '\x0C') + case 'r': + s = append(s, '\x0D') + case 'e': + s = append(s, '\x1B') + case ' ': + s = append(s, '\x20') + case '"': + s = append(s, '"') + case '\'': + s = append(s, '\'') + case '\\': + s = append(s, '\\') + case 'N': // NEL (#x85) + s = append(s, '\xC2') + s = append(s, '\x85') + case '_': // #xA0 + s = append(s, '\xC2') + s = append(s, '\xA0') + case 'L': // LS (#x2028) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA8') + case 'P': // PS (#x2029) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA9') + case 'x': + code_length = 2 + case 'u': + code_length = 4 + case 'U': + code_length = 8 + default: + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found unknown escape character") + return false + } + + skip(parser) + skip(parser) + + // Consume an arbitrary escape code. + if code_length > 0 { + var value int + + // Scan the character value. + if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) { + return false + } + for k := 0; k < code_length; k++ { + if !is_hex(parser.buffer, parser.buffer_pos+k) { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "did not find expected hexdecimal number") + return false + } + value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k) + } + + // Check the value and write the character. + if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found invalid Unicode character escape code") + return false + } + if value <= 0x7F { + s = append(s, byte(value)) + } else if value <= 0x7FF { + s = append(s, byte(0xC0+(value>>6))) + s = append(s, byte(0x80+(value&0x3F))) + } else if value <= 0xFFFF { + s = append(s, byte(0xE0+(value>>12))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } else { + s = append(s, byte(0xF0+(value>>18))) + s = append(s, byte(0x80+((value>>12)&0x3F))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } + + // Advance the pointer. + for k := 0; k < code_length; k++ { + skip(parser) + } + } + } else { + // It is a non-escaped non-blank character. + s = read(parser, s) + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } + + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check if we are at the end of the scalar. + if single { + if parser.buffer[parser.buffer_pos] == '\'' { + break + } + } else { + if parser.buffer[parser.buffer_pos] == '"' { + break + } + } + + // Consume blank characters. + for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { + // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Join the whitespaces or fold line breaks. + if leading_blanks { + // Do we need to fold line breaks? + if len(leading_break) > 0 && leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } + + // Eat the right quote. + skip(parser) + end_mark := parser.mark + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_SINGLE_QUOTED_SCALAR_STYLE, + } + if !single { + token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + return true +} + +// Scan a plain scalar. +func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { + + var s, leading_break, trailing_breaks, whitespaces []byte + var leading_blanks bool + var indent = parser.indent + 1 + + start_mark := parser.mark + end_mark := parser.mark + + // Consume the content of the plain scalar. + for { + // Check for a document indicator. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + break + } + + // Check for a comment. + if parser.buffer[parser.buffer_pos] == '#' { + break + } + + // Consume non-blank characters. + for !is_blankz(parser.buffer, parser.buffer_pos) { + + // Check for indicators that may end a plain scalar. + if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level > 0 && + (parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}')) { + break + } + + // Check if we need to join whitespaces and breaks. + if leading_blanks || len(whitespaces) > 0 { + if leading_blanks { + // Do we need to fold line breaks? + if leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + leading_blanks = false + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } + + // Copy the character. + s = read(parser, s) + + end_mark = parser.mark + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } + + // Is it the end? + if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) { + break + } + + // Consume blank characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { + + // Check for tab characters that abuse indentation. + if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", + start_mark, "found a tab character that violates indentation") + return false + } + + // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check indentation level. + if parser.flow_level == 0 && parser.mark.column < indent { + break + } + } + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_PLAIN_SCALAR_STYLE, + } + + // Note that we change the 'simple_key_allowed' flag. + if leading_blanks { + parser.simple_key_allowed = true + } + return true +} + +func yaml_parser_scan_line_comment(parser *yaml_parser_t, token_mark yaml_mark_t) bool { + if parser.newlines > 0 { + return true + } + + var start_mark yaml_mark_t + var text []byte + + for peek := 0; peek < 512; peek++ { + if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) { + break + } + if is_blank(parser.buffer, parser.buffer_pos+peek) { + continue + } + if parser.buffer[parser.buffer_pos+peek] == '#' { + seen := parser.mark.index+peek + for { + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_breakz(parser.buffer, parser.buffer_pos) { + if parser.mark.index >= seen { + break + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } else if parser.mark.index >= seen { + if len(text) == 0 { + start_mark = parser.mark + } + text = read(parser, text) + } else { + skip(parser) + } + } + } + break + } + if len(text) > 0 { + parser.comments = append(parser.comments, yaml_comment_t{ + token_mark: token_mark, + start_mark: start_mark, + line: text, + }) + } + return true +} + +func yaml_parser_scan_comments(parser *yaml_parser_t, scan_mark yaml_mark_t) bool { + token := parser.tokens[len(parser.tokens)-1] + + if token.typ == yaml_FLOW_ENTRY_TOKEN && len(parser.tokens) > 1 { + token = parser.tokens[len(parser.tokens)-2] + } + + var token_mark = token.start_mark + var start_mark yaml_mark_t + var next_indent = parser.indent + if next_indent < 0 { + next_indent = 0 + } + + var recent_empty = false + var first_empty = parser.newlines <= 1 + + var line = parser.mark.line + var column = parser.mark.column + + var text []byte + + // The foot line is the place where a comment must start to + // still be considered as a foot of the prior content. + // If there's some content in the currently parsed line, then + // the foot is the line below it. + var foot_line = -1 + if scan_mark.line > 0 { + foot_line = parser.mark.line-parser.newlines+1 + if parser.newlines == 0 && parser.mark.column > 1 { + foot_line++ + } + } + + var peek = 0 + for ; peek < 512; peek++ { + if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) { + break + } + column++ + if is_blank(parser.buffer, parser.buffer_pos+peek) { + continue + } + c := parser.buffer[parser.buffer_pos+peek] + var close_flow = parser.flow_level > 0 && (c == ']' || c == '}') + if close_flow || is_breakz(parser.buffer, parser.buffer_pos+peek) { + // Got line break or terminator. + if close_flow || !recent_empty { + if close_flow || first_empty && (start_mark.line == foot_line && token.typ != yaml_VALUE_TOKEN || start_mark.column-1 < next_indent) { + // This is the first empty line and there were no empty lines before, + // so this initial part of the comment is a foot of the prior token + // instead of being a head for the following one. Split it up. + // Alternatively, this might also be the last comment inside a flow + // scope, so it must be a footer. + if len(text) > 0 { + if start_mark.column-1 < next_indent { + // If dedented it's unrelated to the prior token. + token_mark = start_mark + } + parser.comments = append(parser.comments, yaml_comment_t{ + scan_mark: scan_mark, + token_mark: token_mark, + start_mark: start_mark, + end_mark: yaml_mark_t{parser.mark.index + peek, line, column}, + foot: text, + }) + scan_mark = yaml_mark_t{parser.mark.index + peek, line, column} + token_mark = scan_mark + text = nil + } + } else { + if len(text) > 0 && parser.buffer[parser.buffer_pos+peek] != 0 { + text = append(text, '\n') + } + } + } + if !is_break(parser.buffer, parser.buffer_pos+peek) { + break + } + first_empty = false + recent_empty = true + column = 0 + line++ + continue + } + + if len(text) > 0 && (close_flow || column-1 < next_indent && column != start_mark.column) { + // The comment at the different indentation is a foot of the + // preceding data rather than a head of the upcoming one. + parser.comments = append(parser.comments, yaml_comment_t{ + scan_mark: scan_mark, + token_mark: token_mark, + start_mark: start_mark, + end_mark: yaml_mark_t{parser.mark.index + peek, line, column}, + foot: text, + }) + scan_mark = yaml_mark_t{parser.mark.index + peek, line, column} + token_mark = scan_mark + text = nil + } + + if parser.buffer[parser.buffer_pos+peek] != '#' { + break + } + + if len(text) == 0 { + start_mark = yaml_mark_t{parser.mark.index + peek, line, column} + } else { + text = append(text, '\n') + } + + recent_empty = false + + // Consume until after the consumed comment line. + seen := parser.mark.index+peek + for { + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_breakz(parser.buffer, parser.buffer_pos) { + if parser.mark.index >= seen { + break + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } else if parser.mark.index >= seen { + text = read(parser, text) + } else { + skip(parser) + } + } + + peek = 0 + column = 0 + line = parser.mark.line + next_indent = parser.indent + if next_indent < 0 { + next_indent = 0 + } + } + + if len(text) > 0 { + parser.comments = append(parser.comments, yaml_comment_t{ + scan_mark: scan_mark, + token_mark: start_mark, + start_mark: start_mark, + end_mark: yaml_mark_t{parser.mark.index + peek - 1, line, column}, + head: text, + }) + } + return true +} diff --git a/vendor/gopkg.in/yaml.v3/sorter.go b/vendor/gopkg.in/yaml.v3/sorter.go new file mode 100644 index 00000000..9210ece7 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/sorter.go @@ -0,0 +1,134 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yaml + +import ( + "reflect" + "unicode" +) + +type keyList []reflect.Value + +func (l keyList) Len() int { return len(l) } +func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } +func (l keyList) Less(i, j int) bool { + a := l[i] + b := l[j] + ak := a.Kind() + bk := b.Kind() + for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { + a = a.Elem() + ak = a.Kind() + } + for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { + b = b.Elem() + bk = b.Kind() + } + af, aok := keyFloat(a) + bf, bok := keyFloat(b) + if aok && bok { + if af != bf { + return af < bf + } + if ak != bk { + return ak < bk + } + return numLess(a, b) + } + if ak != reflect.String || bk != reflect.String { + return ak < bk + } + ar, br := []rune(a.String()), []rune(b.String()) + digits := false + for i := 0; i < len(ar) && i < len(br); i++ { + if ar[i] == br[i] { + digits = unicode.IsDigit(ar[i]) + continue + } + al := unicode.IsLetter(ar[i]) + bl := unicode.IsLetter(br[i]) + if al && bl { + return ar[i] < br[i] + } + if al || bl { + if digits { + return al + } else { + return bl + } + } + var ai, bi int + var an, bn int64 + if ar[i] == '0' || br[i] == '0' { + for j := i - 1; j >= 0 && unicode.IsDigit(ar[j]); j-- { + if ar[j] != '0' { + an = 1 + bn = 1 + break + } + } + } + for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { + an = an*10 + int64(ar[ai]-'0') + } + for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { + bn = bn*10 + int64(br[bi]-'0') + } + if an != bn { + return an < bn + } + if ai != bi { + return ai < bi + } + return ar[i] < br[i] + } + return len(ar) < len(br) +} + +// keyFloat returns a float value for v if it is a number/bool +// and whether it is a number/bool or not. +func keyFloat(v reflect.Value) (f float64, ok bool) { + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return float64(v.Int()), true + case reflect.Float32, reflect.Float64: + return v.Float(), true + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return float64(v.Uint()), true + case reflect.Bool: + if v.Bool() { + return 1, true + } + return 0, true + } + return 0, false +} + +// numLess returns whether a < b. +// a and b must necessarily have the same kind. +func numLess(a, b reflect.Value) bool { + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() < b.Int() + case reflect.Float32, reflect.Float64: + return a.Float() < b.Float() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Bool: + return !a.Bool() && b.Bool() + } + panic("not a number") +} diff --git a/vendor/gopkg.in/yaml.v3/writerc.go b/vendor/gopkg.in/yaml.v3/writerc.go new file mode 100644 index 00000000..b8a116bf --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/writerc.go @@ -0,0 +1,48 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +// Set the writer error and return false. +func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_WRITER_ERROR + emitter.problem = problem + return false +} + +// Flush the output buffer. +func yaml_emitter_flush(emitter *yaml_emitter_t) bool { + if emitter.write_handler == nil { + panic("write handler not set") + } + + // Check if the buffer is empty. + if emitter.buffer_pos == 0 { + return true + } + + if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { + return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) + } + emitter.buffer_pos = 0 + return true +} diff --git a/vendor/gopkg.in/yaml.v3/yaml.go b/vendor/gopkg.in/yaml.v3/yaml.go new file mode 100644 index 00000000..8cec6da4 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/yaml.go @@ -0,0 +1,698 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package yaml implements YAML support for the Go language. +// +// Source code and other details for the project are available at GitHub: +// +// https://github.com/go-yaml/yaml +// +package yaml + +import ( + "errors" + "fmt" + "io" + "reflect" + "strings" + "sync" + "unicode/utf8" +) + +// The Unmarshaler interface may be implemented by types to customize their +// behavior when being unmarshaled from a YAML document. +type Unmarshaler interface { + UnmarshalYAML(value *Node) error +} + +type obsoleteUnmarshaler interface { + UnmarshalYAML(unmarshal func(interface{}) error) error +} + +// The Marshaler interface may be implemented by types to customize their +// behavior when being marshaled into a YAML document. The returned value +// is marshaled in place of the original value implementing Marshaler. +// +// If an error is returned by MarshalYAML, the marshaling procedure stops +// and returns with the provided error. +type Marshaler interface { + MarshalYAML() (interface{}, error) +} + +// Unmarshal decodes the first document found within the in byte slice +// and assigns decoded values into the out value. +// +// Maps and pointers (to a struct, string, int, etc) are accepted as out +// values. If an internal pointer within a struct is not initialized, +// the yaml package will initialize it if necessary for unmarshalling +// the provided data. The out parameter must not be nil. +// +// The type of the decoded values should be compatible with the respective +// values in out. If one or more values cannot be decoded due to a type +// mismatches, decoding continues partially until the end of the YAML +// content, and a *yaml.TypeError is returned with details for all +// missed values. +// +// Struct fields are only unmarshalled if they are exported (have an +// upper case first letter), and are unmarshalled using the field name +// lowercased as the default key. Custom keys may be defined via the +// "yaml" name in the field tag: the content preceding the first comma +// is used as the key, and the following comma-separated options are +// used to tweak the marshalling process (see Marshal). +// Conflicting names result in a runtime error. +// +// For example: +// +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// var t T +// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) +// +// See the documentation of Marshal for the format of tags and a list of +// supported tag options. +// +func Unmarshal(in []byte, out interface{}) (err error) { + return unmarshal(in, out, false) +} + +// A Decoder reads and decodes YAML values from an input stream. +type Decoder struct { + parser *parser + knownFields bool +} + +// NewDecoder returns a new decoder that reads from r. +// +// The decoder introduces its own buffering and may read +// data from r beyond the YAML values requested. +func NewDecoder(r io.Reader) *Decoder { + return &Decoder{ + parser: newParserFromReader(r), + } +} + +// KnownFields ensures that the keys in decoded mappings to +// exist as fields in the struct being decoded into. +func (dec *Decoder) KnownFields(enable bool) { + dec.knownFields = enable +} + +// Decode reads the next YAML-encoded value from its input +// and stores it in the value pointed to by v. +// +// See the documentation for Unmarshal for details about the +// conversion of YAML into a Go value. +func (dec *Decoder) Decode(v interface{}) (err error) { + d := newDecoder() + d.knownFields = dec.knownFields + defer handleErr(&err) + node := dec.parser.parse() + if node == nil { + return io.EOF + } + out := reflect.ValueOf(v) + if out.Kind() == reflect.Ptr && !out.IsNil() { + out = out.Elem() + } + d.unmarshal(node, out) + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +// Decode decodes the node and stores its data into the value pointed to by v. +// +// See the documentation for Unmarshal for details about the +// conversion of YAML into a Go value. +func (n *Node) Decode(v interface{}) (err error) { + d := newDecoder() + defer handleErr(&err) + out := reflect.ValueOf(v) + if out.Kind() == reflect.Ptr && !out.IsNil() { + out = out.Elem() + } + d.unmarshal(n, out) + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +func unmarshal(in []byte, out interface{}, strict bool) (err error) { + defer handleErr(&err) + d := newDecoder() + p := newParser(in) + defer p.destroy() + node := p.parse() + if node != nil { + v := reflect.ValueOf(out) + if v.Kind() == reflect.Ptr && !v.IsNil() { + v = v.Elem() + } + d.unmarshal(node, v) + } + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +// Marshal serializes the value provided into a YAML document. The structure +// of the generated document will reflect the structure of the value itself. +// Maps and pointers (to struct, string, int, etc) are accepted as the in value. +// +// Struct fields are only marshalled if they are exported (have an upper case +// first letter), and are marshalled using the field name lowercased as the +// default key. Custom keys may be defined via the "yaml" name in the field +// tag: the content preceding the first comma is used as the key, and the +// following comma-separated options are used to tweak the marshalling process. +// Conflicting names result in a runtime error. +// +// The field tag format accepted is: +// +// `(...) yaml:"[][,[,]]" (...)` +// +// The following flags are currently supported: +// +// omitempty Only include the field if it's not set to the zero +// value for the type or to empty slices or maps. +// Zero valued structs will be omitted if all their public +// fields are zero, unless they implement an IsZero +// method (see the IsZeroer interface type), in which +// case the field will be excluded if IsZero returns true. +// +// flow Marshal using a flow style (useful for structs, +// sequences and maps). +// +// inline Inline the field, which must be a struct or a map, +// causing all of its fields or keys to be processed as if +// they were part of the outer struct. For maps, keys must +// not conflict with the yaml keys of other struct fields. +// +// In addition, if the key is "-", the field is ignored. +// +// For example: +// +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" +// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" +// +func Marshal(in interface{}) (out []byte, err error) { + defer handleErr(&err) + e := newEncoder() + defer e.destroy() + e.marshalDoc("", reflect.ValueOf(in)) + e.finish() + out = e.out + return +} + +// An Encoder writes YAML values to an output stream. +type Encoder struct { + encoder *encoder +} + +// NewEncoder returns a new encoder that writes to w. +// The Encoder should be closed after use to flush all data +// to w. +func NewEncoder(w io.Writer) *Encoder { + return &Encoder{ + encoder: newEncoderWithWriter(w), + } +} + +// Encode writes the YAML encoding of v to the stream. +// If multiple items are encoded to the stream, the +// second and subsequent document will be preceded +// with a "---" document separator, but the first will not. +// +// See the documentation for Marshal for details about the conversion of Go +// values to YAML. +func (e *Encoder) Encode(v interface{}) (err error) { + defer handleErr(&err) + e.encoder.marshalDoc("", reflect.ValueOf(v)) + return nil +} + +// Encode encodes value v and stores its representation in n. +// +// See the documentation for Marshal for details about the +// conversion of Go values into YAML. +func (n *Node) Encode(v interface{}) (err error) { + defer handleErr(&err) + e := newEncoder() + defer e.destroy() + e.marshalDoc("", reflect.ValueOf(v)) + e.finish() + p := newParser(e.out) + p.textless = true + defer p.destroy() + doc := p.parse() + *n = *doc.Content[0] + return nil +} + +// SetIndent changes the used indentation used when encoding. +func (e *Encoder) SetIndent(spaces int) { + if spaces < 0 { + panic("yaml: cannot indent to a negative number of spaces") + } + e.encoder.indent = spaces +} + +// Close closes the encoder by writing any remaining data. +// It does not write a stream terminating string "...". +func (e *Encoder) Close() (err error) { + defer handleErr(&err) + e.encoder.finish() + return nil +} + +func handleErr(err *error) { + if v := recover(); v != nil { + if e, ok := v.(yamlError); ok { + *err = e.err + } else { + panic(v) + } + } +} + +type yamlError struct { + err error +} + +func fail(err error) { + panic(yamlError{err}) +} + +func failf(format string, args ...interface{}) { + panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) +} + +// A TypeError is returned by Unmarshal when one or more fields in +// the YAML document cannot be properly decoded into the requested +// types. When this error is returned, the value is still +// unmarshaled partially. +type TypeError struct { + Errors []string +} + +func (e *TypeError) Error() string { + return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) +} + +type Kind uint32 + +const ( + DocumentNode Kind = 1 << iota + SequenceNode + MappingNode + ScalarNode + AliasNode +) + +type Style uint32 + +const ( + TaggedStyle Style = 1 << iota + DoubleQuotedStyle + SingleQuotedStyle + LiteralStyle + FoldedStyle + FlowStyle +) + +// Node represents an element in the YAML document hierarchy. While documents +// are typically encoded and decoded into higher level types, such as structs +// and maps, Node is an intermediate representation that allows detailed +// control over the content being decoded or encoded. +// +// It's worth noting that although Node offers access into details such as +// line numbers, colums, and comments, the content when re-encoded will not +// have its original textual representation preserved. An effort is made to +// render the data plesantly, and to preserve comments near the data they +// describe, though. +// +// Values that make use of the Node type interact with the yaml package in the +// same way any other type would do, by encoding and decoding yaml data +// directly or indirectly into them. +// +// For example: +// +// var person struct { +// Name string +// Address yaml.Node +// } +// err := yaml.Unmarshal(data, &person) +// +// Or by itself: +// +// var person Node +// err := yaml.Unmarshal(data, &person) +// +type Node struct { + // Kind defines whether the node is a document, a mapping, a sequence, + // a scalar value, or an alias to another node. The specific data type of + // scalar nodes may be obtained via the ShortTag and LongTag methods. + Kind Kind + + // Style allows customizing the apperance of the node in the tree. + Style Style + + // Tag holds the YAML tag defining the data type for the value. + // When decoding, this field will always be set to the resolved tag, + // even when it wasn't explicitly provided in the YAML content. + // When encoding, if this field is unset the value type will be + // implied from the node properties, and if it is set, it will only + // be serialized into the representation if TaggedStyle is used or + // the implicit tag diverges from the provided one. + Tag string + + // Value holds the unescaped and unquoted represenation of the value. + Value string + + // Anchor holds the anchor name for this node, which allows aliases to point to it. + Anchor string + + // Alias holds the node that this alias points to. Only valid when Kind is AliasNode. + Alias *Node + + // Content holds contained nodes for documents, mappings, and sequences. + Content []*Node + + // HeadComment holds any comments in the lines preceding the node and + // not separated by an empty line. + HeadComment string + + // LineComment holds any comments at the end of the line where the node is in. + LineComment string + + // FootComment holds any comments following the node and before empty lines. + FootComment string + + // Line and Column hold the node position in the decoded YAML text. + // These fields are not respected when encoding the node. + Line int + Column int +} + +// IsZero returns whether the node has all of its fields unset. +func (n *Node) IsZero() bool { + return n.Kind == 0 && n.Style == 0 && n.Tag == "" && n.Value == "" && n.Anchor == "" && n.Alias == nil && n.Content == nil && + n.HeadComment == "" && n.LineComment == "" && n.FootComment == "" && n.Line == 0 && n.Column == 0 +} + + +// LongTag returns the long form of the tag that indicates the data type for +// the node. If the Tag field isn't explicitly defined, one will be computed +// based on the node properties. +func (n *Node) LongTag() string { + return longTag(n.ShortTag()) +} + +// ShortTag returns the short form of the YAML tag that indicates data type for +// the node. If the Tag field isn't explicitly defined, one will be computed +// based on the node properties. +func (n *Node) ShortTag() string { + if n.indicatedString() { + return strTag + } + if n.Tag == "" || n.Tag == "!" { + switch n.Kind { + case MappingNode: + return mapTag + case SequenceNode: + return seqTag + case AliasNode: + if n.Alias != nil { + return n.Alias.ShortTag() + } + case ScalarNode: + tag, _ := resolve("", n.Value) + return tag + case 0: + // Special case to make the zero value convenient. + if n.IsZero() { + return nullTag + } + } + return "" + } + return shortTag(n.Tag) +} + +func (n *Node) indicatedString() bool { + return n.Kind == ScalarNode && + (shortTag(n.Tag) == strTag || + (n.Tag == "" || n.Tag == "!") && n.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0) +} + +// SetString is a convenience function that sets the node to a string value +// and defines its style in a pleasant way depending on its content. +func (n *Node) SetString(s string) { + n.Kind = ScalarNode + if utf8.ValidString(s) { + n.Value = s + n.Tag = strTag + } else { + n.Value = encodeBase64(s) + n.Tag = binaryTag + } + if strings.Contains(n.Value, "\n") { + n.Style = LiteralStyle + } +} + +// -------------------------------------------------------------------------- +// Maintain a mapping of keys to structure field indexes + +// The code in this section was copied from mgo/bson. + +// structInfo holds details for the serialization of fields of +// a given struct. +type structInfo struct { + FieldsMap map[string]fieldInfo + FieldsList []fieldInfo + + // InlineMap is the number of the field in the struct that + // contains an ,inline map, or -1 if there's none. + InlineMap int + + // InlineUnmarshalers holds indexes to inlined fields that + // contain unmarshaler values. + InlineUnmarshalers [][]int +} + +type fieldInfo struct { + Key string + Num int + OmitEmpty bool + Flow bool + // Id holds the unique field identifier, so we can cheaply + // check for field duplicates without maintaining an extra map. + Id int + + // Inline holds the field index if the field is part of an inlined struct. + Inline []int +} + +var structMap = make(map[reflect.Type]*structInfo) +var fieldMapMutex sync.RWMutex +var unmarshalerType reflect.Type + +func init() { + var v Unmarshaler + unmarshalerType = reflect.ValueOf(&v).Elem().Type() +} + +func getStructInfo(st reflect.Type) (*structInfo, error) { + fieldMapMutex.RLock() + sinfo, found := structMap[st] + fieldMapMutex.RUnlock() + if found { + return sinfo, nil + } + + n := st.NumField() + fieldsMap := make(map[string]fieldInfo) + fieldsList := make([]fieldInfo, 0, n) + inlineMap := -1 + inlineUnmarshalers := [][]int(nil) + for i := 0; i != n; i++ { + field := st.Field(i) + if field.PkgPath != "" && !field.Anonymous { + continue // Private field + } + + info := fieldInfo{Num: i} + + tag := field.Tag.Get("yaml") + if tag == "" && strings.Index(string(field.Tag), ":") < 0 { + tag = string(field.Tag) + } + if tag == "-" { + continue + } + + inline := false + fields := strings.Split(tag, ",") + if len(fields) > 1 { + for _, flag := range fields[1:] { + switch flag { + case "omitempty": + info.OmitEmpty = true + case "flow": + info.Flow = true + case "inline": + inline = true + default: + return nil, errors.New(fmt.Sprintf("unsupported flag %q in tag %q of type %s", flag, tag, st)) + } + } + tag = fields[0] + } + + if inline { + switch field.Type.Kind() { + case reflect.Map: + if inlineMap >= 0 { + return nil, errors.New("multiple ,inline maps in struct " + st.String()) + } + if field.Type.Key() != reflect.TypeOf("") { + return nil, errors.New("option ,inline needs a map with string keys in struct " + st.String()) + } + inlineMap = info.Num + case reflect.Struct, reflect.Ptr: + ftype := field.Type + for ftype.Kind() == reflect.Ptr { + ftype = ftype.Elem() + } + if ftype.Kind() != reflect.Struct { + return nil, errors.New("option ,inline may only be used on a struct or map field") + } + if reflect.PtrTo(ftype).Implements(unmarshalerType) { + inlineUnmarshalers = append(inlineUnmarshalers, []int{i}) + } else { + sinfo, err := getStructInfo(ftype) + if err != nil { + return nil, err + } + for _, index := range sinfo.InlineUnmarshalers { + inlineUnmarshalers = append(inlineUnmarshalers, append([]int{i}, index...)) + } + for _, finfo := range sinfo.FieldsList { + if _, found := fieldsMap[finfo.Key]; found { + msg := "duplicated key '" + finfo.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + if finfo.Inline == nil { + finfo.Inline = []int{i, finfo.Num} + } else { + finfo.Inline = append([]int{i}, finfo.Inline...) + } + finfo.Id = len(fieldsList) + fieldsMap[finfo.Key] = finfo + fieldsList = append(fieldsList, finfo) + } + } + default: + return nil, errors.New("option ,inline may only be used on a struct or map field") + } + continue + } + + if tag != "" { + info.Key = tag + } else { + info.Key = strings.ToLower(field.Name) + } + + if _, found = fieldsMap[info.Key]; found { + msg := "duplicated key '" + info.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + + info.Id = len(fieldsList) + fieldsList = append(fieldsList, info) + fieldsMap[info.Key] = info + } + + sinfo = &structInfo{ + FieldsMap: fieldsMap, + FieldsList: fieldsList, + InlineMap: inlineMap, + InlineUnmarshalers: inlineUnmarshalers, + } + + fieldMapMutex.Lock() + structMap[st] = sinfo + fieldMapMutex.Unlock() + return sinfo, nil +} + +// IsZeroer is used to check whether an object is zero to +// determine whether it should be omitted when marshaling +// with the omitempty flag. One notable implementation +// is time.Time. +type IsZeroer interface { + IsZero() bool +} + +func isZero(v reflect.Value) bool { + kind := v.Kind() + if z, ok := v.Interface().(IsZeroer); ok { + if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() { + return true + } + return z.IsZero() + } + switch kind { + case reflect.String: + return len(v.String()) == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + case reflect.Slice: + return v.Len() == 0 + case reflect.Map: + return v.Len() == 0 + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Struct: + vt := v.Type() + for i := v.NumField() - 1; i >= 0; i-- { + if vt.Field(i).PkgPath != "" { + continue // Private field + } + if !isZero(v.Field(i)) { + return false + } + } + return true + } + return false +} diff --git a/vendor/gopkg.in/yaml.v3/yamlh.go b/vendor/gopkg.in/yaml.v3/yamlh.go new file mode 100644 index 00000000..7c6d0077 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/yamlh.go @@ -0,0 +1,807 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +import ( + "fmt" + "io" +) + +// The version directive data. +type yaml_version_directive_t struct { + major int8 // The major version number. + minor int8 // The minor version number. +} + +// The tag directive data. +type yaml_tag_directive_t struct { + handle []byte // The tag handle. + prefix []byte // The tag prefix. +} + +type yaml_encoding_t int + +// The stream encoding. +const ( + // Let the parser choose the encoding. + yaml_ANY_ENCODING yaml_encoding_t = iota + + yaml_UTF8_ENCODING // The default UTF-8 encoding. + yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM. + yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM. +) + +type yaml_break_t int + +// Line break types. +const ( + // Let the parser choose the break type. + yaml_ANY_BREAK yaml_break_t = iota + + yaml_CR_BREAK // Use CR for line breaks (Mac style). + yaml_LN_BREAK // Use LN for line breaks (Unix style). + yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style). +) + +type yaml_error_type_t int + +// Many bad things could happen with the parser and emitter. +const ( + // No error is produced. + yaml_NO_ERROR yaml_error_type_t = iota + + yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. + yaml_READER_ERROR // Cannot read or decode the input stream. + yaml_SCANNER_ERROR // Cannot scan the input stream. + yaml_PARSER_ERROR // Cannot parse the input stream. + yaml_COMPOSER_ERROR // Cannot compose a YAML document. + yaml_WRITER_ERROR // Cannot write to the output stream. + yaml_EMITTER_ERROR // Cannot emit a YAML stream. +) + +// The pointer position. +type yaml_mark_t struct { + index int // The position index. + line int // The position line. + column int // The position column. +} + +// Node Styles + +type yaml_style_t int8 + +type yaml_scalar_style_t yaml_style_t + +// Scalar styles. +const ( + // Let the emitter choose the style. + yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = 0 + + yaml_PLAIN_SCALAR_STYLE yaml_scalar_style_t = 1 << iota // The plain scalar style. + yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. + yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. + yaml_LITERAL_SCALAR_STYLE // The literal scalar style. + yaml_FOLDED_SCALAR_STYLE // The folded scalar style. +) + +type yaml_sequence_style_t yaml_style_t + +// Sequence styles. +const ( + // Let the emitter choose the style. + yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota + + yaml_BLOCK_SEQUENCE_STYLE // The block sequence style. + yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. +) + +type yaml_mapping_style_t yaml_style_t + +// Mapping styles. +const ( + // Let the emitter choose the style. + yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota + + yaml_BLOCK_MAPPING_STYLE // The block mapping style. + yaml_FLOW_MAPPING_STYLE // The flow mapping style. +) + +// Tokens + +type yaml_token_type_t int + +// Token types. +const ( + // An empty token. + yaml_NO_TOKEN yaml_token_type_t = iota + + yaml_STREAM_START_TOKEN // A STREAM-START token. + yaml_STREAM_END_TOKEN // A STREAM-END token. + + yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. + yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. + yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. + yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. + + yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. + yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. + yaml_BLOCK_END_TOKEN // A BLOCK-END token. + + yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. + yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. + yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. + yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. + + yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. + yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. + yaml_KEY_TOKEN // A KEY token. + yaml_VALUE_TOKEN // A VALUE token. + + yaml_ALIAS_TOKEN // An ALIAS token. + yaml_ANCHOR_TOKEN // An ANCHOR token. + yaml_TAG_TOKEN // A TAG token. + yaml_SCALAR_TOKEN // A SCALAR token. +) + +func (tt yaml_token_type_t) String() string { + switch tt { + case yaml_NO_TOKEN: + return "yaml_NO_TOKEN" + case yaml_STREAM_START_TOKEN: + return "yaml_STREAM_START_TOKEN" + case yaml_STREAM_END_TOKEN: + return "yaml_STREAM_END_TOKEN" + case yaml_VERSION_DIRECTIVE_TOKEN: + return "yaml_VERSION_DIRECTIVE_TOKEN" + case yaml_TAG_DIRECTIVE_TOKEN: + return "yaml_TAG_DIRECTIVE_TOKEN" + case yaml_DOCUMENT_START_TOKEN: + return "yaml_DOCUMENT_START_TOKEN" + case yaml_DOCUMENT_END_TOKEN: + return "yaml_DOCUMENT_END_TOKEN" + case yaml_BLOCK_SEQUENCE_START_TOKEN: + return "yaml_BLOCK_SEQUENCE_START_TOKEN" + case yaml_BLOCK_MAPPING_START_TOKEN: + return "yaml_BLOCK_MAPPING_START_TOKEN" + case yaml_BLOCK_END_TOKEN: + return "yaml_BLOCK_END_TOKEN" + case yaml_FLOW_SEQUENCE_START_TOKEN: + return "yaml_FLOW_SEQUENCE_START_TOKEN" + case yaml_FLOW_SEQUENCE_END_TOKEN: + return "yaml_FLOW_SEQUENCE_END_TOKEN" + case yaml_FLOW_MAPPING_START_TOKEN: + return "yaml_FLOW_MAPPING_START_TOKEN" + case yaml_FLOW_MAPPING_END_TOKEN: + return "yaml_FLOW_MAPPING_END_TOKEN" + case yaml_BLOCK_ENTRY_TOKEN: + return "yaml_BLOCK_ENTRY_TOKEN" + case yaml_FLOW_ENTRY_TOKEN: + return "yaml_FLOW_ENTRY_TOKEN" + case yaml_KEY_TOKEN: + return "yaml_KEY_TOKEN" + case yaml_VALUE_TOKEN: + return "yaml_VALUE_TOKEN" + case yaml_ALIAS_TOKEN: + return "yaml_ALIAS_TOKEN" + case yaml_ANCHOR_TOKEN: + return "yaml_ANCHOR_TOKEN" + case yaml_TAG_TOKEN: + return "yaml_TAG_TOKEN" + case yaml_SCALAR_TOKEN: + return "yaml_SCALAR_TOKEN" + } + return "" +} + +// The token structure. +type yaml_token_t struct { + // The token type. + typ yaml_token_type_t + + // The start/end of the token. + start_mark, end_mark yaml_mark_t + + // The stream encoding (for yaml_STREAM_START_TOKEN). + encoding yaml_encoding_t + + // The alias/anchor/scalar value or tag/tag directive handle + // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN). + value []byte + + // The tag suffix (for yaml_TAG_TOKEN). + suffix []byte + + // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN). + prefix []byte + + // The scalar style (for yaml_SCALAR_TOKEN). + style yaml_scalar_style_t + + // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN). + major, minor int8 +} + +// Events + +type yaml_event_type_t int8 + +// Event types. +const ( + // An empty event. + yaml_NO_EVENT yaml_event_type_t = iota + + yaml_STREAM_START_EVENT // A STREAM-START event. + yaml_STREAM_END_EVENT // A STREAM-END event. + yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event. + yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. + yaml_ALIAS_EVENT // An ALIAS event. + yaml_SCALAR_EVENT // A SCALAR event. + yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event. + yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. + yaml_MAPPING_START_EVENT // A MAPPING-START event. + yaml_MAPPING_END_EVENT // A MAPPING-END event. + yaml_TAIL_COMMENT_EVENT +) + +var eventStrings = []string{ + yaml_NO_EVENT: "none", + yaml_STREAM_START_EVENT: "stream start", + yaml_STREAM_END_EVENT: "stream end", + yaml_DOCUMENT_START_EVENT: "document start", + yaml_DOCUMENT_END_EVENT: "document end", + yaml_ALIAS_EVENT: "alias", + yaml_SCALAR_EVENT: "scalar", + yaml_SEQUENCE_START_EVENT: "sequence start", + yaml_SEQUENCE_END_EVENT: "sequence end", + yaml_MAPPING_START_EVENT: "mapping start", + yaml_MAPPING_END_EVENT: "mapping end", + yaml_TAIL_COMMENT_EVENT: "tail comment", +} + +func (e yaml_event_type_t) String() string { + if e < 0 || int(e) >= len(eventStrings) { + return fmt.Sprintf("unknown event %d", e) + } + return eventStrings[e] +} + +// The event structure. +type yaml_event_t struct { + + // The event type. + typ yaml_event_type_t + + // The start and end of the event. + start_mark, end_mark yaml_mark_t + + // The document encoding (for yaml_STREAM_START_EVENT). + encoding yaml_encoding_t + + // The version directive (for yaml_DOCUMENT_START_EVENT). + version_directive *yaml_version_directive_t + + // The list of tag directives (for yaml_DOCUMENT_START_EVENT). + tag_directives []yaml_tag_directive_t + + // The comments + head_comment []byte + line_comment []byte + foot_comment []byte + tail_comment []byte + + // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). + anchor []byte + + // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + tag []byte + + // The scalar value (for yaml_SCALAR_EVENT). + value []byte + + // Is the document start/end indicator implicit, or the tag optional? + // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT). + implicit bool + + // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT). + quoted_implicit bool + + // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + style yaml_style_t +} + +func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } +func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) } +func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } + +// Nodes + +const ( + yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. + yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. + yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. + yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. + yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. + yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. + + yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. + yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. + + // Not in original libyaml. + yaml_BINARY_TAG = "tag:yaml.org,2002:binary" + yaml_MERGE_TAG = "tag:yaml.org,2002:merge" + + yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. + yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq. + yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. +) + +type yaml_node_type_t int + +// Node types. +const ( + // An empty node. + yaml_NO_NODE yaml_node_type_t = iota + + yaml_SCALAR_NODE // A scalar node. + yaml_SEQUENCE_NODE // A sequence node. + yaml_MAPPING_NODE // A mapping node. +) + +// An element of a sequence node. +type yaml_node_item_t int + +// An element of a mapping node. +type yaml_node_pair_t struct { + key int // The key of the element. + value int // The value of the element. +} + +// The node structure. +type yaml_node_t struct { + typ yaml_node_type_t // The node type. + tag []byte // The node tag. + + // The node data. + + // The scalar parameters (for yaml_SCALAR_NODE). + scalar struct { + value []byte // The scalar value. + length int // The length of the scalar value. + style yaml_scalar_style_t // The scalar style. + } + + // The sequence parameters (for YAML_SEQUENCE_NODE). + sequence struct { + items_data []yaml_node_item_t // The stack of sequence items. + style yaml_sequence_style_t // The sequence style. + } + + // The mapping parameters (for yaml_MAPPING_NODE). + mapping struct { + pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). + pairs_start *yaml_node_pair_t // The beginning of the stack. + pairs_end *yaml_node_pair_t // The end of the stack. + pairs_top *yaml_node_pair_t // The top of the stack. + style yaml_mapping_style_t // The mapping style. + } + + start_mark yaml_mark_t // The beginning of the node. + end_mark yaml_mark_t // The end of the node. + +} + +// The document structure. +type yaml_document_t struct { + + // The document nodes. + nodes []yaml_node_t + + // The version directive. + version_directive *yaml_version_directive_t + + // The list of tag directives. + tag_directives_data []yaml_tag_directive_t + tag_directives_start int // The beginning of the tag directives list. + tag_directives_end int // The end of the tag directives list. + + start_implicit int // Is the document start indicator implicit? + end_implicit int // Is the document end indicator implicit? + + // The start/end of the document. + start_mark, end_mark yaml_mark_t +} + +// The prototype of a read handler. +// +// The read handler is called when the parser needs to read more bytes from the +// source. The handler should write not more than size bytes to the buffer. +// The number of written bytes should be set to the size_read variable. +// +// [in,out] data A pointer to an application data specified by +// yaml_parser_set_input(). +// [out] buffer The buffer to write the data from the source. +// [in] size The size of the buffer. +// [out] size_read The actual number of bytes read from the source. +// +// On success, the handler should return 1. If the handler failed, +// the returned value should be 0. On EOF, the handler should set the +// size_read to 0 and return 1. +type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) + +// This structure holds information about a potential simple key. +type yaml_simple_key_t struct { + possible bool // Is a simple key possible? + required bool // Is a simple key required? + token_number int // The number of the token. + mark yaml_mark_t // The position mark. +} + +// The states of the parser. +type yaml_parser_state_t int + +const ( + yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota + + yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. + yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. + yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. + yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. + yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. + yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence. + yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. + yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. + yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. + yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. + yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. + yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. + yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. + yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. + yaml_PARSE_END_STATE // Expect nothing. +) + +func (ps yaml_parser_state_t) String() string { + switch ps { + case yaml_PARSE_STREAM_START_STATE: + return "yaml_PARSE_STREAM_START_STATE" + case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_START_STATE: + return "yaml_PARSE_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_CONTENT_STATE: + return "yaml_PARSE_DOCUMENT_CONTENT_STATE" + case yaml_PARSE_DOCUMENT_END_STATE: + return "yaml_PARSE_DOCUMENT_END_STATE" + case yaml_PARSE_BLOCK_NODE_STATE: + return "yaml_PARSE_BLOCK_NODE_STATE" + case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE" + case yaml_PARSE_FLOW_NODE_STATE: + return "yaml_PARSE_FLOW_NODE_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: + return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE" + case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE" + case yaml_PARSE_END_STATE: + return "yaml_PARSE_END_STATE" + } + return "" +} + +// This structure holds aliases data. +type yaml_alias_data_t struct { + anchor []byte // The anchor. + index int // The node id. + mark yaml_mark_t // The anchor mark. +} + +// The parser structure. +// +// All members are internal. Manage the structure using the +// yaml_parser_ family of functions. +type yaml_parser_t struct { + + // Error handling + + error yaml_error_type_t // Error type. + + problem string // Error description. + + // The byte about which the problem occurred. + problem_offset int + problem_value int + problem_mark yaml_mark_t + + // The error context. + context string + context_mark yaml_mark_t + + // Reader stuff + + read_handler yaml_read_handler_t // Read handler. + + input_reader io.Reader // File input data. + input []byte // String input data. + input_pos int + + eof bool // EOF flag + + buffer []byte // The working buffer. + buffer_pos int // The current position of the buffer. + + unread int // The number of unread characters in the buffer. + + newlines int // The number of line breaks since last non-break/non-blank character + + raw_buffer []byte // The raw buffer. + raw_buffer_pos int // The current position of the buffer. + + encoding yaml_encoding_t // The input encoding. + + offset int // The offset of the current position (in bytes). + mark yaml_mark_t // The mark of the current position. + + // Comments + + head_comment []byte // The current head comments + line_comment []byte // The current line comments + foot_comment []byte // The current foot comments + tail_comment []byte // Foot comment that happens at the end of a block. + stem_comment []byte // Comment in item preceding a nested structure (list inside list item, etc) + + comments []yaml_comment_t // The folded comments for all parsed tokens + comments_head int + + // Scanner stuff + + stream_start_produced bool // Have we started to scan the input stream? + stream_end_produced bool // Have we reached the end of the input stream? + + flow_level int // The number of unclosed '[' and '{' indicators. + + tokens []yaml_token_t // The tokens queue. + tokens_head int // The head of the tokens queue. + tokens_parsed int // The number of tokens fetched from the queue. + token_available bool // Does the tokens queue contain a token ready for dequeueing. + + indent int // The current indentation level. + indents []int // The indentation levels stack. + + simple_key_allowed bool // May a simple key occur at the current position? + simple_keys []yaml_simple_key_t // The stack of simple keys. + simple_keys_by_tok map[int]int // possible simple_key indexes indexed by token_number + + // Parser stuff + + state yaml_parser_state_t // The current parser state. + states []yaml_parser_state_t // The parser states stack. + marks []yaml_mark_t // The stack of marks. + tag_directives []yaml_tag_directive_t // The list of TAG directives. + + // Dumper stuff + + aliases []yaml_alias_data_t // The alias data. + + document *yaml_document_t // The currently parsed document. +} + +type yaml_comment_t struct { + + scan_mark yaml_mark_t // Position where scanning for comments started + token_mark yaml_mark_t // Position after which tokens will be associated with this comment + start_mark yaml_mark_t // Position of '#' comment mark + end_mark yaml_mark_t // Position where comment terminated + + head []byte + line []byte + foot []byte +} + +// Emitter Definitions + +// The prototype of a write handler. +// +// The write handler is called when the emitter needs to flush the accumulated +// characters to the output. The handler should write @a size bytes of the +// @a buffer to the output. +// +// @param[in,out] data A pointer to an application data specified by +// yaml_emitter_set_output(). +// @param[in] buffer The buffer with bytes to be written. +// @param[in] size The size of the buffer. +// +// @returns On success, the handler should return @c 1. If the handler failed, +// the returned value should be @c 0. +// +type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error + +type yaml_emitter_state_t int + +// The emitter states. +const ( + // Expect STREAM-START. + yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota + + yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. + yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. + yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. + yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. + yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. + yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE // Expect the next item of a flow sequence, with the comma already written out + yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. + yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE // Expect the next key of a flow mapping, with the comma already written out + yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. + yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. + yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. + yaml_EMIT_END_STATE // Expect nothing. +) + +// The emitter structure. +// +// All members are internal. Manage the structure using the @c yaml_emitter_ +// family of functions. +type yaml_emitter_t struct { + + // Error handling + + error yaml_error_type_t // Error type. + problem string // Error description. + + // Writer stuff + + write_handler yaml_write_handler_t // Write handler. + + output_buffer *[]byte // String output data. + output_writer io.Writer // File output data. + + buffer []byte // The working buffer. + buffer_pos int // The current position of the buffer. + + raw_buffer []byte // The raw buffer. + raw_buffer_pos int // The current position of the buffer. + + encoding yaml_encoding_t // The stream encoding. + + // Emitter stuff + + canonical bool // If the output is in the canonical style? + best_indent int // The number of indentation spaces. + best_width int // The preferred width of the output lines. + unicode bool // Allow unescaped non-ASCII characters? + line_break yaml_break_t // The preferred line break. + + state yaml_emitter_state_t // The current emitter state. + states []yaml_emitter_state_t // The stack of states. + + events []yaml_event_t // The event queue. + events_head int // The head of the event queue. + + indents []int // The stack of indentation levels. + + tag_directives []yaml_tag_directive_t // The list of tag directives. + + indent int // The current indentation level. + + flow_level int // The current flow level. + + root_context bool // Is it the document root context? + sequence_context bool // Is it a sequence context? + mapping_context bool // Is it a mapping context? + simple_key_context bool // Is it a simple mapping key context? + + line int // The current line. + column int // The current column. + whitespace bool // If the last character was a whitespace? + indention bool // If the last character was an indentation character (' ', '-', '?', ':')? + open_ended bool // If an explicit document end is required? + + space_above bool // Is there's an empty line above? + foot_indent int // The indent used to write the foot comment above, or -1 if none. + + // Anchor analysis. + anchor_data struct { + anchor []byte // The anchor value. + alias bool // Is it an alias? + } + + // Tag analysis. + tag_data struct { + handle []byte // The tag handle. + suffix []byte // The tag suffix. + } + + // Scalar analysis. + scalar_data struct { + value []byte // The scalar value. + multiline bool // Does the scalar contain line breaks? + flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? + block_plain_allowed bool // Can the scalar be expressed in the block plain style? + single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? + block_allowed bool // Can the scalar be expressed in the literal or folded styles? + style yaml_scalar_style_t // The output style. + } + + // Comments + head_comment []byte + line_comment []byte + foot_comment []byte + tail_comment []byte + + key_line_comment []byte + + // Dumper stuff + + opened bool // If the stream was already opened? + closed bool // If the stream was already closed? + + // The information associated with the document nodes. + anchors *struct { + references int // The number of references. + anchor int // The anchor id. + serialized bool // If the node has been emitted? + } + + last_anchor_id int // The last assigned anchor id. + + document *yaml_document_t // The currently emitted document. +} diff --git a/vendor/gopkg.in/yaml.v3/yamlprivateh.go b/vendor/gopkg.in/yaml.v3/yamlprivateh.go new file mode 100644 index 00000000..e88f9c54 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/yamlprivateh.go @@ -0,0 +1,198 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +const ( + // The size of the input raw buffer. + input_raw_buffer_size = 512 + + // The size of the input buffer. + // It should be possible to decode the whole raw buffer. + input_buffer_size = input_raw_buffer_size * 3 + + // The size of the output buffer. + output_buffer_size = 128 + + // The size of the output raw buffer. + // It should be possible to encode the whole output buffer. + output_raw_buffer_size = (output_buffer_size*2 + 2) + + // The size of other stacks and queues. + initial_stack_size = 16 + initial_queue_size = 16 + initial_string_size = 16 +) + +// Check if the character at the specified position is an alphabetical +// character, a digit, '_', or '-'. +func is_alpha(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-' +} + +// Check if the character at the specified position is a digit. +func is_digit(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' +} + +// Get the value of a digit. +func as_digit(b []byte, i int) int { + return int(b[i]) - '0' +} + +// Check if the character at the specified position is a hex-digit. +func is_hex(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f' +} + +// Get the value of a hex-digit. +func as_hex(b []byte, i int) int { + bi := b[i] + if bi >= 'A' && bi <= 'F' { + return int(bi) - 'A' + 10 + } + if bi >= 'a' && bi <= 'f' { + return int(bi) - 'a' + 10 + } + return int(bi) - '0' +} + +// Check if the character is ASCII. +func is_ascii(b []byte, i int) bool { + return b[i] <= 0x7F +} + +// Check if the character at the start of the buffer can be printed unescaped. +func is_printable(b []byte, i int) bool { + return ((b[i] == 0x0A) || // . == #x0A + (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E + (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF + (b[i] > 0xC2 && b[i] < 0xED) || + (b[i] == 0xED && b[i+1] < 0xA0) || + (b[i] == 0xEE) || + (b[i] == 0xEF && // #xE000 <= . <= #xFFFD + !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF + !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF)))) +} + +// Check if the character at the specified position is NUL. +func is_z(b []byte, i int) bool { + return b[i] == 0x00 +} + +// Check if the beginning of the buffer is a BOM. +func is_bom(b []byte, i int) bool { + return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF +} + +// Check if the character at the specified position is space. +func is_space(b []byte, i int) bool { + return b[i] == ' ' +} + +// Check if the character at the specified position is tab. +func is_tab(b []byte, i int) bool { + return b[i] == '\t' +} + +// Check if the character at the specified position is blank (space or tab). +func is_blank(b []byte, i int) bool { + //return is_space(b, i) || is_tab(b, i) + return b[i] == ' ' || b[i] == '\t' +} + +// Check if the character at the specified position is a line break. +func is_break(b []byte, i int) bool { + return (b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029) +} + +func is_crlf(b []byte, i int) bool { + return b[i] == '\r' && b[i+1] == '\n' +} + +// Check if the character is a line break or NUL. +func is_breakz(b []byte, i int) bool { + //return is_break(b, i) || is_z(b, i) + return ( + // is_break: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + // is_z: + b[i] == 0) +} + +// Check if the character is a line break, space, or NUL. +func is_spacez(b []byte, i int) bool { + //return is_space(b, i) || is_breakz(b, i) + return ( + // is_space: + b[i] == ' ' || + // is_breakz: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + b[i] == 0) +} + +// Check if the character is a line break, space, tab, or NUL. +func is_blankz(b []byte, i int) bool { + //return is_blank(b, i) || is_breakz(b, i) + return ( + // is_blank: + b[i] == ' ' || b[i] == '\t' || + // is_breakz: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + b[i] == 0) +} + +// Determine the width of the character. +func width(b byte) int { + // Don't replace these by a switch without first + // confirming that it is being inlined. + if b&0x80 == 0x00 { + return 1 + } + if b&0xE0 == 0xC0 { + return 2 + } + if b&0xF0 == 0xE0 { + return 3 + } + if b&0xF8 == 0xF0 { + return 4 + } + return 0 + +} diff --git a/vendor/modules.txt b/vendor/modules.txt index d709a278..4c2893e2 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,3 +1,10 @@ +# dario.cat/mergo v1.0.0 +## explicit; go 1.13 +dario.cat/mergo +# filippo.io/edwards25519 v1.1.0 +## explicit; go 1.20 +filippo.io/edwards25519 +filippo.io/edwards25519/field # github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 ## explicit github.com/99designs/go-keychain @@ -47,9 +54,23 @@ github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/internal/shared github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/pageblob github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service +# github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 +## explicit; go 1.16 +github.com/Azure/go-ansiterm +github.com/Azure/go-ansiterm/winterm # github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c ## explicit github.com/JohnCGriffin/overflow +# github.com/Microsoft/go-winio v0.6.2 +## explicit; go 1.21 +github.com/Microsoft/go-winio +github.com/Microsoft/go-winio/internal/fs +github.com/Microsoft/go-winio/internal/socket +github.com/Microsoft/go-winio/internal/stringbuffer +github.com/Microsoft/go-winio/pkg/guid +# github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 +## explicit +github.com/Nvveen/Gotty # github.com/andybalholm/brotli v1.0.6 ## explicit; go 1.12 github.com/andybalholm/brotli @@ -171,9 +192,42 @@ github.com/aws/smithy-go/time github.com/aws/smithy-go/transport/http github.com/aws/smithy-go/transport/http/internal/io github.com/aws/smithy-go/waiter +# github.com/cenkalti/backoff/v4 v4.3.0 +## explicit; go 1.18 +github.com/cenkalti/backoff/v4 +# github.com/containerd/continuity v0.4.5 +## explicit; go 1.21 +github.com/containerd/continuity/pathdriver # github.com/danieljoos/wincred v1.2.0 ## explicit; go 1.18 github.com/danieljoos/wincred +# github.com/docker/cli v27.4.1+incompatible +## explicit +github.com/docker/cli/cli/compose/interpolation +github.com/docker/cli/cli/compose/loader +github.com/docker/cli/cli/compose/schema +github.com/docker/cli/cli/compose/template +github.com/docker/cli/cli/compose/types +github.com/docker/cli/opts +github.com/docker/cli/pkg/kvfile +# github.com/docker/docker v27.1.1+incompatible +## explicit +github.com/docker/docker/api/types/blkiodev +github.com/docker/docker/api/types/container +github.com/docker/docker/api/types/filters +github.com/docker/docker/api/types/mount +github.com/docker/docker/api/types/network +github.com/docker/docker/api/types/strslice +github.com/docker/docker/api/types/swarm +github.com/docker/docker/api/types/swarm/runtime +github.com/docker/docker/api/types/versions +github.com/docker/docker/internal/multierror +# github.com/docker/go-connections v0.5.0 +## explicit; go 1.18 +github.com/docker/go-connections/nat +# github.com/docker/go-units v0.5.0 +## explicit +github.com/docker/go-units # github.com/dvsekhvalnov/jose2go v1.5.0 ## explicit; go 1.15 github.com/dvsekhvalnov/jose2go @@ -193,9 +247,13 @@ github.com/gabriel-vasile/mimetype github.com/gabriel-vasile/mimetype/internal/charset github.com/gabriel-vasile/mimetype/internal/json github.com/gabriel-vasile/mimetype/internal/magic -# github.com/go-sql-driver/mysql v1.7.1 -## explicit; go 1.13 +# github.com/go-sql-driver/mysql v1.8.1 +## explicit; go 1.18 github.com/go-sql-driver/mysql +# github.com/go-viper/mapstructure/v2 v2.1.0 +## explicit; go 1.18 +github.com/go-viper/mapstructure/v2 +github.com/go-viper/mapstructure/v2/internal/errors # github.com/goccy/go-json v0.10.2 ## explicit; go 1.12 github.com/goccy/go-json @@ -210,6 +268,9 @@ github.com/goccy/go-json/internal/runtime # github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 ## explicit; go 1.12 github.com/godbus/dbus +# github.com/gogo/protobuf v1.3.2 +## explicit; go 1.15 +github.com/gogo/protobuf/proto # github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 ## explicit github.com/golang-sql/civil @@ -222,19 +283,28 @@ github.com/golang/snappy # github.com/google/flatbuffers v23.5.26+incompatible ## explicit github.com/google/flatbuffers/go +# github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 +## explicit; go 1.13 +github.com/google/shlex # github.com/google/uuid v1.4.0 ## explicit github.com/google/uuid # github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c ## explicit github.com/gsterjov/go-libsecret +# github.com/jackc/pgio v1.0.0 +## explicit; go 1.12 +github.com/jackc/pgio +# github.com/jackc/pglogrepl v0.0.0-20250509230407-a9884f6bd75a +## explicit; go 1.21 +github.com/jackc/pglogrepl # github.com/jackc/pgpassfile v1.0.0 ## explicit; go 1.12 github.com/jackc/pgpassfile # github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a ## explicit; go 1.14 github.com/jackc/pgservicefile -# github.com/jackc/pgx/v5 v5.5.0 +# github.com/jackc/pgx/v5 v5.5.4 ## explicit; go 1.19 github.com/jackc/pgx/v5 github.com/jackc/pgx/v5/internal/anynil @@ -299,9 +369,54 @@ github.com/minio/asm2plan9s # github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3 ## explicit github.com/minio/c2goasm +# github.com/moby/docker-image-spec v1.3.1 +## explicit; go 1.18 +github.com/moby/docker-image-spec/specs-go/v1 +# github.com/moby/sys/user v0.3.0 +## explicit; go 1.17 +github.com/moby/sys/user +# github.com/moby/term v0.5.0 +## explicit; go 1.18 +github.com/moby/term +github.com/moby/term/windows # github.com/mtibben/percent v0.2.1 ## explicit; go 1.14 github.com/mtibben/percent +# github.com/opencontainers/go-digest v1.0.0 +## explicit; go 1.13 +github.com/opencontainers/go-digest +# github.com/opencontainers/image-spec v1.1.0 +## explicit; go 1.18 +github.com/opencontainers/image-spec/specs-go +github.com/opencontainers/image-spec/specs-go/v1 +# github.com/opencontainers/runc v1.2.3 +## explicit; go 1.22 +github.com/opencontainers/runc/libcontainer/user +# github.com/ory/dockertest/v3 v3.12.0 +## explicit; go 1.22 +github.com/ory/dockertest/v3 +github.com/ory/dockertest/v3/docker +github.com/ory/dockertest/v3/docker/opts +github.com/ory/dockertest/v3/docker/pkg/archive +github.com/ory/dockertest/v3/docker/pkg/fileutils +github.com/ory/dockertest/v3/docker/pkg/homedir +github.com/ory/dockertest/v3/docker/pkg/idtools +github.com/ory/dockertest/v3/docker/pkg/ioutils +github.com/ory/dockertest/v3/docker/pkg/jsonmessage +github.com/ory/dockertest/v3/docker/pkg/longpath +github.com/ory/dockertest/v3/docker/pkg/mount +github.com/ory/dockertest/v3/docker/pkg/pools +github.com/ory/dockertest/v3/docker/pkg/stdcopy +github.com/ory/dockertest/v3/docker/pkg/system +github.com/ory/dockertest/v3/docker/types +github.com/ory/dockertest/v3/docker/types/blkiodev +github.com/ory/dockertest/v3/docker/types/container +github.com/ory/dockertest/v3/docker/types/filters +github.com/ory/dockertest/v3/docker/types/mount +github.com/ory/dockertest/v3/docker/types/network +github.com/ory/dockertest/v3/docker/types/registry +github.com/ory/dockertest/v3/docker/types/strslice +github.com/ory/dockertest/v3/docker/types/versions # github.com/pierrec/lz4/v4 v4.1.18 ## explicit; go 1.14 github.com/pierrec/lz4/v4 @@ -312,6 +427,13 @@ github.com/pierrec/lz4/v4/internal/xxh32 # github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 ## explicit; go 1.14 github.com/pkg/browser +# github.com/pkg/errors v0.9.1 +## explicit +github.com/pkg/errors +# github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 +## explicit; go 1.21 +github.com/santhosh-tekuri/jsonschema/v6 +github.com/santhosh-tekuri/jsonschema/v6/kind # github.com/sijms/go-ora/v2 v2.7.19 ## explicit; go 1.17 github.com/sijms/go-ora/v2 @@ -328,10 +450,25 @@ github.com/sirupsen/logrus # github.com/snowflakedb/gosnowflake v1.6.25 ## explicit; go 1.19 github.com/snowflakedb/gosnowflake +# github.com/stretchr/objx v0.5.2 +## explicit; go 1.20 +# github.com/stripe/stripe-go/v82 v82.3.0 +## explicit; go 1.18 +github.com/stripe/stripe-go/v82 +github.com/stripe/stripe-go/v82/form +# github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb +## explicit +github.com/xeipuuv/gojsonpointer +# github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 +## explicit +github.com/xeipuuv/gojsonreference +# github.com/xeipuuv/gojsonschema v1.2.0 +## explicit +github.com/xeipuuv/gojsonschema # github.com/zeebo/xxh3 v1.0.2 ## explicit; go 1.17 github.com/zeebo/xxh3 -# golang.org/x/crypto v0.15.0 +# golang.org/x/crypto v0.22.0 ## explicit; go 1.18 golang.org/x/crypto/md4 golang.org/x/crypto/ocsp @@ -346,7 +483,7 @@ golang.org/x/exp/slices golang.org/x/mod/internal/lazyregexp golang.org/x/mod/module golang.org/x/mod/semver -# golang.org/x/net v0.18.0 +# golang.org/x/net v0.24.0 ## explicit; go 1.18 golang.org/x/net/html golang.org/x/net/html/atom @@ -354,18 +491,18 @@ golang.org/x/net/http/httpguts golang.org/x/net/http2 golang.org/x/net/http2/hpack golang.org/x/net/idna -# golang.org/x/sync v0.5.0 +# golang.org/x/sync v0.8.0 ## explicit; go 1.18 golang.org/x/sync/errgroup golang.org/x/sync/semaphore -# golang.org/x/sys v0.14.0 +# golang.org/x/sys v0.28.0 ## explicit; go 1.18 golang.org/x/sys/cpu golang.org/x/sys/execabs golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows -# golang.org/x/term v0.14.0 +# golang.org/x/term v0.19.0 ## explicit; go 1.18 golang.org/x/term # golang.org/x/text v0.14.0 @@ -375,12 +512,19 @@ golang.org/x/text/encoding golang.org/x/text/encoding/internal golang.org/x/text/encoding/internal/identifier golang.org/x/text/encoding/unicode +golang.org/x/text/feature/plural golang.org/x/text/internal +golang.org/x/text/internal/catmsg +golang.org/x/text/internal/format golang.org/x/text/internal/language golang.org/x/text/internal/language/compact +golang.org/x/text/internal/number +golang.org/x/text/internal/stringset golang.org/x/text/internal/tag golang.org/x/text/internal/utf8internal golang.org/x/text/language +golang.org/x/text/message +golang.org/x/text/message/catalog golang.org/x/text/runes golang.org/x/text/secure/bidirule golang.org/x/text/secure/precis @@ -388,6 +532,9 @@ golang.org/x/text/transform golang.org/x/text/unicode/bidi golang.org/x/text/unicode/norm golang.org/x/text/width +# golang.org/x/time v0.12.0 +## explicit; go 1.23.0 +golang.org/x/time/rate # golang.org/x/tools v0.15.0 ## explicit; go 1.18 golang.org/x/tools/cmd/goimports @@ -415,3 +562,9 @@ golang.org/x/tools/internal/typesinternal ## explicit; go 1.18 golang.org/x/xerrors golang.org/x/xerrors/internal +# gopkg.in/yaml.v2 v2.4.0 +## explicit; go 1.15 +gopkg.in/yaml.v2 +# gopkg.in/yaml.v3 v3.0.1 +## explicit +gopkg.in/yaml.v3